text
stringlengths
27
775k
<?php namespace CF\Error; class GenericErrorCollection extends \CF\Error\ErrorCollection { /** * @return String */ public function outputFormatted($outputFormat = NULL) { return implode(PHP_EOL, $this->errors); } }
module Distribution.Client.Init.Simple ( -- * Project creation createProject -- * Gen targets , genSimplePkgDesc , genSimpleLibTarget , genSimpleExeTarget , genSimpleTestTarget ) where import Distribution.Client.Init.Types import Distribution.Verbosity import Distribution.Simple.PackageIndex import Distribution.Client.Types.SourcePackageDb (SourcePackageDb(..)) import qualified Data.List.NonEmpty as NEL import Distribution.Client.Init.Utils (currentDirPkgName, mkPackageNameDep, fixupDocFiles) import Distribution.Client.Init.Defaults import Distribution.Simple.Flag (fromFlagOrDefault, flagElim, Flag(..)) import Distribution.Client.Init.FlagExtractors import qualified Data.Set as Set import Distribution.Types.Dependency import Distribution.Types.PackageName (unPackageName) createProject :: Interactive m => Verbosity -> InstalledPackageIndex -> SourcePackageDb -> InitFlags -> m ProjectSettings createProject v pkgIx _srcDb initFlags = do pkgType <- packageTypePrompt initFlags isMinimal <- getMinimal initFlags doOverwrite <- getOverwrite initFlags pkgDir <- getPackageDir initFlags pkgDesc <- fixupDocFiles v =<< genSimplePkgDesc initFlags let pkgName = _pkgName pkgDesc cabalSpec = _pkgCabalVersion pkgDesc mkOpts cs = WriteOpts doOverwrite isMinimal cs v pkgDir pkgType pkgName basedFlags <- addBaseDepToFlags pkgIx initFlags case pkgType of Library -> do libTarget <- genSimpleLibTarget basedFlags testTarget <- addLibDepToTest pkgName <$> genSimpleTestTarget basedFlags return $ ProjectSettings (mkOpts False cabalSpec) pkgDesc (Just libTarget) Nothing testTarget Executable -> do exeTarget <- genSimpleExeTarget basedFlags return $ ProjectSettings (mkOpts False cabalSpec) pkgDesc Nothing (Just exeTarget) Nothing LibraryAndExecutable -> do libTarget <- genSimpleLibTarget basedFlags testTarget <- addLibDepToTest pkgName <$> genSimpleTestTarget basedFlags exeTarget <- addLibDepToExe pkgName <$> genSimpleExeTarget basedFlags return $ ProjectSettings (mkOpts False cabalSpec) pkgDesc (Just libTarget) (Just exeTarget) testTarget TestSuite -> do testTarget <- genSimpleTestTarget basedFlags return $ ProjectSettings (mkOpts False cabalSpec) pkgDesc Nothing Nothing testTarget where -- Add package name as dependency of test suite -- addLibDepToTest _ Nothing = Nothing addLibDepToTest n (Just t) = Just $ t { _testDependencies = _testDependencies t ++ [mkPackageNameDep n] } -- Add package name as dependency of executable -- addLibDepToExe n exe = exe { _exeDependencies = _exeDependencies exe ++ [mkPackageNameDep n] } genSimplePkgDesc :: Interactive m => InitFlags -> m PkgDescription genSimplePkgDesc flags = mkPkgDesc <$> currentDirPkgName where defaultExtraDoc = Just $ Set.singleton defaultChangelog extractExtraDoc [] = defaultExtraDoc extractExtraDoc fs = Just $ Set.fromList fs mkPkgDesc pkgName = PkgDescription (fromFlagOrDefault defaultCabalVersion (cabalVersion flags)) pkgName (fromFlagOrDefault defaultVersion (version flags)) (fromFlagOrDefault defaultLicense (license flags)) (fromFlagOrDefault "" (author flags)) (fromFlagOrDefault "" (email flags)) (fromFlagOrDefault "" (homepage flags)) (fromFlagOrDefault "" (synopsis flags)) (fromFlagOrDefault "" (category flags)) (flagElim mempty Set.fromList (extraSrc flags)) (flagElim defaultExtraDoc extractExtraDoc (extraDoc flags)) genSimpleLibTarget :: Interactive m => InitFlags -> m LibTarget genSimpleLibTarget flags = do buildToolDeps <- getBuildTools flags return $ LibTarget { _libSourceDirs = fromFlagOrDefault [defaultSourceDir] $ sourceDirs flags , _libLanguage = fromFlagOrDefault defaultLanguage $ language flags , _libExposedModules = flagElim (myLibModule NEL.:| []) extractMods $ exposedModules flags , _libOtherModules = fromFlagOrDefault [] $ otherModules flags , _libOtherExts = fromFlagOrDefault [] $ otherExts flags , _libDependencies = fromFlagOrDefault [] $ dependencies flags , _libBuildTools = buildToolDeps } where extractMods [] = myLibModule NEL.:| [] extractMods as = NEL.fromList as genSimpleExeTarget :: Interactive m => InitFlags -> m ExeTarget genSimpleExeTarget flags = do buildToolDeps <- getBuildTools flags return $ ExeTarget { _exeMainIs = flagElim defaultMainIs toHsFilePath $ mainIs flags , _exeApplicationDirs = fromFlagOrDefault [defaultApplicationDir] $ applicationDirs flags , _exeLanguage = fromFlagOrDefault defaultLanguage $ language flags , _exeOtherModules = fromFlagOrDefault [] $ otherModules flags , _exeOtherExts = fromFlagOrDefault [] $ otherExts flags , _exeDependencies = fromFlagOrDefault [] $ dependencies flags , _exeBuildTools = buildToolDeps } genSimpleTestTarget :: Interactive m => InitFlags -> m (Maybe TestTarget) genSimpleTestTarget flags = go =<< initializeTestSuitePrompt flags where go initialized | not initialized = return Nothing | otherwise = do buildToolDeps <- getBuildTools flags return $ Just $ TestTarget { _testMainIs = flagElim defaultMainIs toHsFilePath $ mainIs flags , _testDirs = fromFlagOrDefault [defaultTestDir] $ testDirs flags , _testLanguage = fromFlagOrDefault defaultLanguage $ language flags , _testOtherModules = fromFlagOrDefault [] $ otherModules flags , _testOtherExts = fromFlagOrDefault [] $ otherExts flags , _testDependencies = fromFlagOrDefault [] $ dependencies flags , _testBuildTools = buildToolDeps } -- -------------------------------------------------------------------- -- -- Utils -- | If deps are defined, and base is present, we skip the search for base. -- otherwise, we look up @base@ and add it to the list. addBaseDepToFlags :: Interactive m => InstalledPackageIndex -> InitFlags -> m InitFlags addBaseDepToFlags pkgIx initFlags = case dependencies initFlags of Flag as | any ((==) "base" . unPackageName . depPkgName) as -> return initFlags | otherwise -> do based <- dependenciesPrompt pkgIx initFlags return $ initFlags { dependencies = Flag $ based ++ as } _ -> do based <- dependenciesPrompt pkgIx initFlags return initFlags { dependencies = Flag based }
# TrelloReportAutomation Program to automate reports for Trello work so you can get your micromanaging boss off your case.
require 'dotify' module Dotify module CLI class Listing include CLI::Utilities attr_reader :collection, :options def initialize(collection, options = {}) @collection = collection @options = options end def count collection.count end def write color = Thor::Shell::Color.new if self.count > 0 inform "Dotify is managing #{self.count} files:" collection.each { |dot| color.say(" * #{dot.filename}", :yellow) } else inform "Dotify is not managing any files yet." end end end end end
# dasmの文法(x86) ```lua ------------------------------------------------------------------------------ -- x86 Template String Description -- =============================== -- -- Each template string is a list of [match:]pattern pairs, -- separated by "|". The first match wins. No match means a -- bad or unsupported combination of operand modes or sizes. -- -- The match part and the ":" is omitted if the operation has -- no operands. Otherwise the first N characters are matched -- against the mode strings of each of the N operands. -- -- The mode string for each operand type is (see parseoperand()): -- Integer register: "rm", +"R" for eax, ax, al, +"C" for cl -- FP register: "f", +"F" for st0 -- Index operand: "xm", +"O" for [disp] (pure offset) -- Immediate: "i", +"S" for signed 8 bit, +"1" for 1, +"I" for arg, +"P" for pointer -- Any: +"J" for valid jump targets -- -- So a match character "m" (mixed) matches both an integer register -- and an index operand (to be encoded with the ModRM/SIB scheme). -- But "r" matches only a register and "x" only an index operand -- (e.g. for FP memory access operations). -- -- The operand size match string starts right after the mode match -- characters and ends before the ":". "dwb" or "qdwb" is assumed, if empty. -- The effective data size of the operation is matched against this list. -- -- If only the regular "b", "w", "d", "q", "t" operand sizes are -- present, then all operands must be the same size. Unspecified sizes -- are ignored, but at least one operand must have a size or the pattern -- won't match (use the "byte", "word", "dword", "qword", "tword" -- operand size overrides. E.g.: mov dword [eax], 1). -- -- If the list has a "1" or "2" prefix, the operand size is taken -- from the respective operand and any other operand sizes are ignored. -- If the list contains only ".", all operand sizes are ignored. -- If the list has a "/" prefix, the concatenated (mixed) operand sizes -- are compared to the match. -- -- E.g. "rrdw" matches for either two dword registers or two word -- registers. "Fx2dq" matches an st0 operand plus an index operand -- pointing to a dword (float) or qword (double). -- -- Every character after the ":" is part of the pattern string: -- Hex chars are accumulated to form the opcode (left to right). -- "n" disables the standard opcode mods -- (otherwise: -1 for "b", o16 prefix for "w", rex.w for "q") -- "X" Force REX.W. -- "r"/"R" adds the reg. number from the 1st/2nd operand to the opcode. -- "m"/"M" generates ModRM/SIB from the 1st/2nd operand. -- The spare 3 bits are either filled with the last hex digit or -- the result from a previous "r"/"R". The opcode is restored. -- -- All of the following characters force a flush of the opcode: -- "o"/"O" stores a pure 32 bit disp (offset) from the 1st/2nd operand. -- "S" stores a signed 8 bit immediate from the last operand. -- "U" stores an unsigned 8 bit immediate from the last operand. -- "W" stores an unsigned 16 bit immediate from the last operand. -- "i" stores an operand sized immediate from the last operand. -- "I" dito, but generates an action code to optionally modify the opcode (+2) for a signed 8 bit immediate. -- "J" generates one of the REL action codes from the last operand. -- ------------------------------------------------------------------------------ -- Template strings for x86 instructions. Ordered by first opcode byte. -- Unimplemented opcodes (deliberate omissions) are marked with *. local map_op = { -- 00-05: add... -- 06: *push es -- 07: *pop es -- 08-0D: or... -- 0E: *push cs -- 0F: two byte opcode prefix -- 10-15: adc... -- 16: *push ss -- 17: *pop ss -- 18-1D: sbb... -- 1E: *push ds -- 1F: *pop ds -- 20-25: and... es_0 = "26", -- 27: *daa -- 28-2D: sub... cs_0 = "2E", -- 2F: *das -- 30-35: xor... ss_0 = "36", -- 37: *aaa -- 38-3D: cmp... ds_0 = "3E", -- 3F: *aas inc_1 = x64 and "m:FF0m" or "rdw:40r|m:FF0m", dec_1 = x64 and "m:FF1m" or "rdw:48r|m:FF1m", push_1 = (x64 and "rq:n50r|rw:50r|mq:nFF6m|mw:FF6m" or "rdw:50r|mdw:FF6m").."|S.:6AS|ib:n6Ai|i.:68i", pop_1 = x64 and "rq:n58r|rw:58r|mq:n8F0m|mw:8F0m" or "rdw:58r|mdw:8F0m", -- 60: *pusha, *pushad, *pushaw -- 61: *popa, *popad, *popaw -- 62: *bound rdw,x -- 63: x86: *arpl mw,rw movsxd_2 = x64 and "rm/qd:63rM", fs_0 = "64", gs_0 = "65", o16_0 = "66", a16_0 = not x64 and "67" or nil, a32_0 = x64 and "67", -- 68: push idw -- 69: imul rdw,mdw,idw -- 6A: push ib -- 6B: imul rdw,mdw,S -- 6C: *insb -- 6D: *insd, *insw -- 6E: *outsb -- 6F: *outsd, *outsw -- 70-7F: jcc lb -- 80: add... mb,i -- 81: add... mdw,i -- 82: *undefined -- 83: add... mdw,S test_2 = "mr:85Rm|rm:85rM|Ri:A9ri|mi:F70mi", -- 86: xchg rb,mb -- 87: xchg rdw,mdw -- 88: mov mb,r -- 89: mov mdw,r -- 8A: mov r,mb -- 8B: mov r,mdw -- 8C: *mov mdw,seg lea_2 = "rx1dq:8DrM", -- 8E: *mov seg,mdw -- 8F: pop mdw nop_0 = "90", xchg_2 = "Rrqdw:90R|rRqdw:90r|rm:87rM|mr:87Rm", cbw_0 = "6698", cwde_0 = "98", cdqe_0 = "4898", cwd_0 = "6699", cdq_0 = "99", cqo_0 = "4899", -- 9A: *call iw:idw wait_0 = "9B", fwait_0 = "9B", pushf_0 = "9C", pushfd_0 = not x64 and "9C", pushfq_0 = x64 and "9C", popf_0 = "9D", popfd_0 = not x64 and "9D", popfq_0 = x64 and "9D", sahf_0 = "9E", lahf_0 = "9F", mov_2 = "OR:A3o|RO:A1O|mr:89Rm|rm:8BrM|rib:nB0ri|ridw:B8ri|mi:C70mi", movsb_0 = "A4", movsw_0 = "66A5", movsd_0 = "A5", cmpsb_0 = "A6", cmpsw_0 = "66A7", cmpsd_0 = "A7", -- A8: test Rb,i -- A9: test Rdw,i stosb_0 = "AA", stosw_0 = "66AB", stosd_0 = "AB", lodsb_0 = "AC", lodsw_0 = "66AD", lodsd_0 = "AD", scasb_0 = "AE", scasw_0 = "66AF", scasd_0 = "AF", -- B0-B7: mov rb,i -- B8-BF: mov rdw,i -- C0: rol... mb,i -- C1: rol... mdw,i ret_1 = "i.:nC2W", ret_0 = "C3", -- C4: *les rdw,mq -- C5: *lds rdw,mq -- C6: mov mb,i -- C7: mov mdw,i -- C8: *enter iw,ib leave_0 = "C9", -- CA: *retf iw -- CB: *retf int3_0 = "CC", int_1 = "i.:nCDU", into_0 = "CE", -- CF: *iret -- D0: rol... mb,1 -- D1: rol... mdw,1 -- D2: rol... mb,cl -- D3: rol... mb,cl -- D4: *aam ib -- D5: *aad ib -- D6: *salc -- D7: *xlat -- D8-DF: floating point ops -- E0: *loopne -- E1: *loope -- E2: *loop -- E3: *jcxz, *jecxz -- E4: *in Rb,ib -- E5: *in Rdw,ib -- E6: *out ib,Rb -- E7: *out ib,Rdw call_1 = x64 and "mq:nFF2m|J.:E8nJ" or "md:FF2m|J.:E8J", jmp_1 = x64 and "mq:nFF4m|J.:E9nJ" or "md:FF4m|J.:E9J", -- short: EB -- EA: *jmp iw:idw -- EB: jmp ib -- EC: *in Rb,dx -- ED: *in Rdw,dx -- EE: *out dx,Rb -- EF: *out dx,Rdw lock_0 = "F0", int1_0 = "F1", repne_0 = "F2", repnz_0 = "F2", rep_0 = "F3", repe_0 = "F3", repz_0 = "F3", -- F4: *hlt cmc_0 = "F5", -- F6: test... mb,i; div... mb -- F7: test... mdw,i; div... mdw clc_0 = "F8", stc_0 = "F9", -- FA: *cli cld_0 = "FC", std_0 = "FD", -- FE: inc... mb -- FF: inc... mdw -- misc ops not_1 = "m:F72m", neg_1 = "m:F73m", mul_1 = "m:F74m", imul_1 = "m:F75m", div_1 = "m:F76m", idiv_1 = "m:F77m", imul_2 = "rmqdw:0FAFrM|rIqdw:69rmI|rSqdw:6BrmS|riqdw:69rmi", imul_3 = "rmIqdw:69rMI|rmSqdw:6BrMS|rmiqdw:69rMi", movzx_2 = "rm/db:0FB6rM|rm/qb:|rm/wb:0FB6rM|rm/dw:0FB7rM|rm/qw:", movsx_2 = "rm/db:0FBErM|rm/qb:|rm/wb:0FBErM|rm/dw:0FBFrM|rm/qw:", bswap_1 = "rqd:0FC8r", bsf_2 = "rmqdw:0FBCrM", bsr_2 = "rmqdw:0FBDrM", bt_2 = "mrqdw:0FA3Rm|miqdw:0FBA4mU", btc_2 = "mrqdw:0FBBRm|miqdw:0FBA7mU", btr_2 = "mrqdw:0FB3Rm|miqdw:0FBA6mU", bts_2 = "mrqdw:0FABRm|miqdw:0FBA5mU", shld_3 = "mriqdw:0FA4RmU|mrC/qq:0FA5Rm|mrC/dd:|mrC/ww:", shrd_3 = "mriqdw:0FACRmU|mrC/qq:0FADRm|mrC/dd:|mrC/ww:", rdtsc_0 = "0F31", -- P1+ rdpmc_0 = "0F33", -- P6+ cpuid_0 = "0FA2", -- P1+ -- floating point ops fst_1 = "ff:DDD0r|xd:D92m|xq:nDD2m", fstp_1 = "ff:DDD8r|xd:D93m|xq:nDD3m|xt:DB7m", fld_1 = "ff:D9C0r|xd:D90m|xq:nDD0m|xt:DB5m", fpop_0 = "DDD8", -- Alias for fstp st0. fist_1 = "xw:nDF2m|xd:DB2m", fistp_1 = "xw:nDF3m|xd:DB3m|xq:nDF7m", fild_1 = "xw:nDF0m|xd:DB0m|xq:nDF5m", fxch_0 = "D9C9", fxch_1 = "ff:D9C8r", fxch_2 = "fFf:D9C8r|Fff:D9C8R", fucom_1 = "ff:DDE0r", fucom_2 = "Fff:DDE0R", fucomp_1 = "ff:DDE8r", fucomp_2 = "Fff:DDE8R", fucomi_1 = "ff:DBE8r", -- P6+ fucomi_2 = "Fff:DBE8R", -- P6+ fucomip_1 = "ff:DFE8r", -- P6+ fucomip_2 = "Fff:DFE8R", -- P6+ fcomi_1 = "ff:DBF0r", -- P6+ fcomi_2 = "Fff:DBF0R", -- P6+ fcomip_1 = "ff:DFF0r", -- P6+ fcomip_2 = "Fff:DFF0R", -- P6+ fucompp_0 = "DAE9", fcompp_0 = "DED9", fldenv_1 = "x.:D94m", fnstenv_1 = "x.:D96m", fstenv_1 = "x.:9BD96m", fldcw_1 = "xw:nD95m", fstcw_1 = "xw:n9BD97m", fnstcw_1 = "xw:nD97m", fstsw_1 = "Rw:n9BDFE0|xw:n9BDD7m", fnstsw_1 = "Rw:nDFE0|xw:nDD7m", fclex_0 = "9BDBE2", fnclex_0 = "DBE2", fnop_0 = "D9D0", -- D9D1-D9DF: unassigned fchs_0 = "D9E0", fabs_0 = "D9E1", -- D9E2: unassigned -- D9E3: unassigned ftst_0 = "D9E4", fxam_0 = "D9E5", -- D9E6: unassigned -- D9E7: unassigned fld1_0 = "D9E8", fldl2t_0 = "D9E9", fldl2e_0 = "D9EA", fldpi_0 = "D9EB", fldlg2_0 = "D9EC", fldln2_0 = "D9ED", fldz_0 = "D9EE", -- D9EF: unassigned f2xm1_0 = "D9F0", fyl2x_0 = "D9F1", fptan_0 = "D9F2", fpatan_0 = "D9F3", fxtract_0 = "D9F4", fprem1_0 = "D9F5", fdecstp_0 = "D9F6", fincstp_0 = "D9F7", fprem_0 = "D9F8", fyl2xp1_0 = "D9F9", fsqrt_0 = "D9FA", fsincos_0 = "D9FB", frndint_0 = "D9FC", fscale_0 = "D9FD", fsin_0 = "D9FE", fcos_0 = "D9FF", -- SSE, SSE2 andnpd_2 = "rmo:660F55rM", andnps_2 = "rmo:0F55rM", andpd_2 = "rmo:660F54rM", andps_2 = "rmo:0F54rM", clflush_1 = "x.:0FAE7m", cmppd_3 = "rmio:660FC2rMU", cmpps_3 = "rmio:0FC2rMU", cmpsd_3 = "rrio:F20FC2rMU|rxi/oq:", cmpss_3 = "rrio:F30FC2rMU|rxi/od:", comisd_2 = "rro:660F2FrM|rx/oq:", comiss_2 = "rro:0F2FrM|rx/od:", cvtdq2pd_2 = "rro:F30FE6rM|rx/oq:", cvtdq2ps_2 = "rmo:0F5BrM", cvtpd2dq_2 = "rmo:F20FE6rM", cvtpd2ps_2 = "rmo:660F5ArM", cvtpi2pd_2 = "rx/oq:660F2ArM", cvtpi2ps_2 = "rx/oq:0F2ArM", cvtps2dq_2 = "rmo:660F5BrM", cvtps2pd_2 = "rro:0F5ArM|rx/oq:", cvtsd2si_2 = "rr/do:F20F2DrM|rr/qo:|rx/dq:|rxq:", cvtsd2ss_2 = "rro:F20F5ArM|rx/oq:", cvtsi2sd_2 = "rm/od:F20F2ArM|rm/oq:F20F2ArXM", cvtsi2ss_2 = "rm/od:F30F2ArM|rm/oq:F30F2ArXM", cvtss2sd_2 = "rro:F30F5ArM|rx/od:", cvtss2si_2 = "rr/do:F30F2DrM|rr/qo:|rxd:|rx/qd:", cvttpd2dq_2 = "rmo:660FE6rM", cvttps2dq_2 = "rmo:F30F5BrM", cvttsd2si_2 = "rr/do:F20F2CrM|rr/qo:|rx/dq:|rxq:", cvttss2si_2 = "rr/do:F30F2CrM|rr/qo:|rxd:|rx/qd:", fxsave_1 = "x.:0FAE0m", fxrstor_1 = "x.:0FAE1m", ldmxcsr_1 = "xd:0FAE2m", lfence_0 = "0FAEE8", maskmovdqu_2 = "rro:660FF7rM", mfence_0 = "0FAEF0", movapd_2 = "rmo:660F28rM|mro:660F29Rm", movaps_2 = "rmo:0F28rM|mro:0F29Rm", movd_2 = "rm/od:660F6ErM|rm/oq:660F6ErXM|mr/do:660F7ERm|mr/qo:", movdqa_2 = "rmo:660F6FrM|mro:660F7FRm", movdqu_2 = "rmo:F30F6FrM|mro:F30F7FRm", movhlps_2 = "rro:0F12rM", movhpd_2 = "rx/oq:660F16rM|xr/qo:n660F17Rm", movhps_2 = "rx/oq:0F16rM|xr/qo:n0F17Rm", movlhps_2 = "rro:0F16rM", movlpd_2 = "rx/oq:660F12rM|xr/qo:n660F13Rm", movlps_2 = "rx/oq:0F12rM|xr/qo:n0F13Rm", movmskpd_2 = "rr/do:660F50rM", movmskps_2 = "rr/do:0F50rM", movntdq_2 = "xro:660FE7Rm", movnti_2 = "xrqd:0FC3Rm", movntpd_2 = "xro:660F2BRm", movntps_2 = "xro:0F2BRm", movq_2 = "rro:F30F7ErM|rx/oq:|xr/qo:n660FD6Rm", movsd_2 = "rro:F20F10rM|rx/oq:|xr/qo:nF20F11Rm", movss_2 = "rro:F30F10rM|rx/od:|xr/do:F30F11Rm", movupd_2 = "rmo:660F10rM|mro:660F11Rm", movups_2 = "rmo:0F10rM|mro:0F11Rm", orpd_2 = "rmo:660F56rM", orps_2 = "rmo:0F56rM", packssdw_2 = "rmo:660F6BrM", packsswb_2 = "rmo:660F63rM", packuswb_2 = "rmo:660F67rM", paddb_2 = "rmo:660FFCrM", paddd_2 = "rmo:660FFErM", paddq_2 = "rmo:660FD4rM", paddsb_2 = "rmo:660FECrM", paddsw_2 = "rmo:660FEDrM", paddusb_2 = "rmo:660FDCrM", paddusw_2 = "rmo:660FDDrM", paddw_2 = "rmo:660FFDrM", pand_2 = "rmo:660FDBrM", pandn_2 = "rmo:660FDFrM", pause_0 = "F390", pavgb_2 = "rmo:660FE0rM", pavgw_2 = "rmo:660FE3rM", pcmpeqb_2 = "rmo:660F74rM", pcmpeqd_2 = "rmo:660F76rM", pcmpeqw_2 = "rmo:660F75rM", pcmpgtb_2 = "rmo:660F64rM", pcmpgtd_2 = "rmo:660F66rM", pcmpgtw_2 = "rmo:660F65rM", pextrw_3 = "rri/do:660FC5rMU|xri/wo:660F3A15nRmU", -- Mem op: SSE4.1 only. pinsrw_3 = "rri/od:660FC4rMU|rxi/ow:", pmaddwd_2 = "rmo:660FF5rM", pmaxsw_2 = "rmo:660FEErM", pmaxub_2 = "rmo:660FDErM", pminsw_2 = "rmo:660FEArM", pminub_2 = "rmo:660FDArM", pmovmskb_2 = "rr/do:660FD7rM", pmulhuw_2 = "rmo:660FE4rM", pmulhw_2 = "rmo:660FE5rM", pmullw_2 = "rmo:660FD5rM", pmuludq_2 = "rmo:660FF4rM", por_2 = "rmo:660FEBrM", prefetchnta_1 = "xb:n0F180m", prefetcht0_1 = "xb:n0F181m", prefetcht1_1 = "xb:n0F182m", prefetcht2_1 = "xb:n0F183m", psadbw_2 = "rmo:660FF6rM", pshufd_3 = "rmio:660F70rMU", pshufhw_3 = "rmio:F30F70rMU", pshuflw_3 = "rmio:F20F70rMU", pslld_2 = "rmo:660FF2rM|rio:660F726mU", pslldq_2 = "rio:660F737mU", psllq_2 = "rmo:660FF3rM|rio:660F736mU", psllw_2 = "rmo:660FF1rM|rio:660F716mU", psrad_2 = "rmo:660FE2rM|rio:660F724mU", psraw_2 = "rmo:660FE1rM|rio:660F714mU", psrld_2 = "rmo:660FD2rM|rio:660F722mU", psrldq_2 = "rio:660F733mU", psrlq_2 = "rmo:660FD3rM|rio:660F732mU", psrlw_2 = "rmo:660FD1rM|rio:660F712mU", psubb_2 = "rmo:660FF8rM", psubd_2 = "rmo:660FFArM", psubq_2 = "rmo:660FFBrM", psubsb_2 = "rmo:660FE8rM", psubsw_2 = "rmo:660FE9rM", psubusb_2 = "rmo:660FD8rM", psubusw_2 = "rmo:660FD9rM", psubw_2 = "rmo:660FF9rM", punpckhbw_2 = "rmo:660F68rM", punpckhdq_2 = "rmo:660F6ArM", punpckhqdq_2 = "rmo:660F6DrM", punpckhwd_2 = "rmo:660F69rM", punpcklbw_2 = "rmo:660F60rM", punpckldq_2 = "rmo:660F62rM", punpcklqdq_2 = "rmo:660F6CrM", punpcklwd_2 = "rmo:660F61rM", pxor_2 = "rmo:660FEFrM", rcpps_2 = "rmo:0F53rM", rcpss_2 = "rro:F30F53rM|rx/od:", rsqrtps_2 = "rmo:0F52rM", rsqrtss_2 = "rmo:F30F52rM", sfence_0 = "0FAEF8", shufpd_3 = "rmio:660FC6rMU", shufps_3 = "rmio:0FC6rMU", stmxcsr_1 = "xd:0FAE3m", ucomisd_2 = "rro:660F2ErM|rx/oq:", ucomiss_2 = "rro:0F2ErM|rx/od:", unpckhpd_2 = "rmo:660F15rM", unpckhps_2 = "rmo:0F15rM", unpcklpd_2 = "rmo:660F14rM", unpcklps_2 = "rmo:0F14rM", xorpd_2 = "rmo:660F57rM", xorps_2 = "rmo:0F57rM", -- SSE3 ops fisttp_1 = "xw:nDF1m|xd:DB1m|xq:nDD1m", addsubpd_2 = "rmo:660FD0rM", addsubps_2 = "rmo:F20FD0rM", haddpd_2 = "rmo:660F7CrM", haddps_2 = "rmo:F20F7CrM", hsubpd_2 = "rmo:660F7DrM", hsubps_2 = "rmo:F20F7DrM", lddqu_2 = "rxo:F20FF0rM", movddup_2 = "rmo:F20F12rM", movshdup_2 = "rmo:F30F16rM", movsldup_2 = "rmo:F30F12rM", -- SSSE3 ops pabsb_2 = "rmo:660F381CrM", pabsd_2 = "rmo:660F381ErM", pabsw_2 = "rmo:660F381DrM", palignr_3 = "rmio:660F3A0FrMU", phaddd_2 = "rmo:660F3802rM", phaddsw_2 = "rmo:660F3803rM", phaddw_2 = "rmo:660F3801rM", phsubd_2 = "rmo:660F3806rM", phsubsw_2 = "rmo:660F3807rM", phsubw_2 = "rmo:660F3805rM", pmaddubsw_2 = "rmo:660F3804rM", pmulhrsw_2 = "rmo:660F380BrM", pshufb_2 = "rmo:660F3800rM", psignb_2 = "rmo:660F3808rM", psignd_2 = "rmo:660F380ArM", psignw_2 = "rmo:660F3809rM", -- SSE4.1 ops blendpd_3 = "rmio:660F3A0DrMU", blendps_3 = "rmio:660F3A0CrMU", blendvpd_3 = "rmRo:660F3815rM", blendvps_3 = "rmRo:660F3814rM", dppd_3 = "rmio:660F3A41rMU", dpps_3 = "rmio:660F3A40rMU", extractps_3 = "mri/do:660F3A17RmU|rri/qo:660F3A17RXmU", insertps_3 = "rrio:660F3A41rMU|rxi/od:", movntdqa_2 = "rxo:660F382ArM", mpsadbw_3 = "rmio:660F3A42rMU", packusdw_2 = "rmo:660F382BrM", pblendvb_3 = "rmRo:660F3810rM", pblendw_3 = "rmio:660F3A0ErMU", pcmpeqq_2 = "rmo:660F3829rM", pextrb_3 = "rri/do:660F3A14nRmU|rri/qo:|xri/bo:", pextrd_3 = "mri/do:660F3A16RmU", pextrq_3 = "mri/qo:660F3A16RmU", -- pextrw is SSE2, mem operand is SSE4.1 only phminposuw_2 = "rmo:660F3841rM", pinsrb_3 = "rri/od:660F3A20nrMU|rxi/ob:", pinsrd_3 = "rmi/od:660F3A22rMU", pinsrq_3 = "rmi/oq:660F3A22rXMU", pmaxsb_2 = "rmo:660F383CrM", pmaxsd_2 = "rmo:660F383DrM", pmaxud_2 = "rmo:660F383FrM", pmaxuw_2 = "rmo:660F383ErM", pminsb_2 = "rmo:660F3838rM", pminsd_2 = "rmo:660F3839rM", pminud_2 = "rmo:660F383BrM", pminuw_2 = "rmo:660F383ArM", pmovsxbd_2 = "rro:660F3821rM|rx/od:", pmovsxbq_2 = "rro:660F3822rM|rx/ow:", pmovsxbw_2 = "rro:660F3820rM|rx/oq:", pmovsxdq_2 = "rro:660F3825rM|rx/oq:", pmovsxwd_2 = "rro:660F3823rM|rx/oq:", pmovsxwq_2 = "rro:660F3824rM|rx/od:", pmovzxbd_2 = "rro:660F3831rM|rx/od:", pmovzxbq_2 = "rro:660F3832rM|rx/ow:", pmovzxbw_2 = "rro:660F3830rM|rx/oq:", pmovzxdq_2 = "rro:660F3835rM|rx/oq:", pmovzxwd_2 = "rro:660F3833rM|rx/oq:", pmovzxwq_2 = "rro:660F3834rM|rx/od:", pmuldq_2 = "rmo:660F3828rM", pmulld_2 = "rmo:660F3840rM", ptest_2 = "rmo:660F3817rM", roundpd_3 = "rmio:660F3A09rMU", roundps_3 = "rmio:660F3A08rMU", roundsd_3 = "rrio:660F3A0BrMU|rxi/oq:", roundss_3 = "rrio:660F3A0ArMU|rxi/od:", -- SSE4.2 ops crc32_2 = "rmqd:F20F38F1rM|rm/dw:66F20F38F1rM|rm/db:F20F38F0rM|rm/qb:", pcmpestri_3 = "rmio:660F3A61rMU", pcmpestrm_3 = "rmio:660F3A60rMU", pcmpgtq_2 = "rmo:660F3837rM", pcmpistri_3 = "rmio:660F3A63rMU", pcmpistrm_3 = "rmio:660F3A62rMU", popcnt_2 = "rmqdw:F30FB8rM", -- SSE4a extrq_2 = "rro:660F79rM", extrq_3 = "riio:660F780mUU", insertq_2 = "rro:F20F79rM", insertq_4 = "rriio:F20F78rMUU", lzcnt_2 = "rmqdw:F30FBDrM", movntsd_2 = "xr/qo:nF20F2BRm", movntss_2 = "xr/do:F30F2BRm", -- popcnt is also in SSE4.2 } ```
using System.Management.Automation; using Microsoft.SharePoint.Client; using OfficeDevPnP.PowerShell.Commands.Base.PipeBinds; using Resources = OfficeDevPnP.PowerShell.Commands.Properties.Resources; namespace OfficeDevPnP.PowerShell.Commands { [Cmdlet(VerbsCommon.Remove, "SPOCustomAction", ConfirmImpact = ConfirmImpact.High)] public class RemoveCustomAction : SPOWebCmdlet { [Parameter(Mandatory = true, Position=0, ValueFromPipeline=true)] public GuidPipeBind Identity; [Parameter(Mandatory = false)] public SwitchParameter Force; protected override void ExecuteCmdlet() { if (Identity != null) { if (Force || ShouldContinue(Resources.RemoveCustomAction, Resources.Confirm)) { SelectedWeb.DeleteCustomAction(Identity.Id); } } } } }
import { levels } from "./jsonmodule"; import { Level, LevelData } from "./levelstructure"; // Meets version 4 level standards // https://gist.github.com/Zolo101/36ae33e5dd15510a2cb41e942dbf7044 // const allBlocks = blocks.map((array: { name: string; }) => array.name); // const usedBlocks: string[] = []; export function checkLevel(): void { // const blockArray = [...levels[levelnum].data]; const curlevel: LevelData = levels; let levelsExist = true; // console.log(levels); switch (true) { case curlevel.name === undefined: console.warn("No title!"); // falls through case curlevel.author === undefined: console.warn("No author!"); // falls through case curlevel.description === undefined: console.warn("No description!"); // falls through case curlevel.struct_version === undefined: console.error("No version specficied (This is required!)"); // falls through case curlevel.level_version === undefined: console.warn("No title!"); // falls through case curlevel.levels === undefined: console.error("No levels...?"); levelsExist = false; // falls through default: break; } // No levels if (levelsExist) return; curlevel.levels.forEach((level: Level, i: number) => { switch (true) { case level.name === undefined: console.error(`No level name @ level number ${i}.`); // falls through case level.width === undefined: console.error(`No level width @ level number ${i}.`); // falls through case level.height === undefined: console.error(`No level height @ level number ${i}.`); // falls through case level.background === undefined: console.error(`No level background @ level number ${i}.`); // falls through case level.data === undefined: console.error(`No level data @ level number ${i}.`); // falls through //case level[0].entity === undefined: // console.warn(`No level entities @ level number ${i}.`); // falls through default: break; } }); /* // No width/height if ((curlevel.width || curlevel.height) === undefined) { console.error("No width/height variable!"); } // Too small if (curlevel.width < 32 || curlevel.height < 18) { console.error("Level is too small!"); } // No background if (curlevel.background === undefined) { console.warn("No background!"); } // Invalid background if (curlevel.background > 11) { console.error("Invalid background!"); } */ // No level // Level size does not equal width/height (not good) /* if (curlevel.data === undefined) { console.error("No level!"); } else if (curlevel.height !== curlevel.data.length || curlevel.width !== curlevel.data[0].length) { console.error("The Level size is different from the width/height variable!"); } */ // Level size does not equal width/height (not good) // Unknown / Unsupported block // blockArray.forEach((bc) => { // if (!usedBlocks.includes(bc)) { // usedBlocks.push(bc); // } // }); // if (usedBlocks.every((ub) => allBlocks.includes(ub))) { // // For now // console.warn("Unknown/Unsupported block detected!"); // } // No entity // if (curlevel.entity === undefined) { // console.error("No entities!"); // } } export default checkLevel;
#define PY_SSIZE_T_CLEAN #include <Python.h> #include <math.h> #include <structmember.h> #define PY3_9_OR_MORE PY_VERSION_HEX >= 0x03090000 #define PY3_11_OR_MORE PY_VERSION_HEX >= 0x030b0000 static int is_negative_Object(PyObject *self) { PyObject *tmp = PyLong_FromLong(0); int result = PyObject_RichCompareBool(self, tmp, Py_LT); Py_DECREF(tmp); return result; } static int is_unit_Object(PyObject *self) { PyObject *tmp = PyLong_FromLong(1); int result = PyObject_RichCompareBool(self, tmp, Py_EQ); Py_DECREF(tmp); return result; } static PyObject *round_Object(PyObject *self) { PyObject *round_method_name = PyUnicode_FromString("__round__"); if (!round_method_name) return NULL; PyObject *result = #if PY3_9_OR_MORE PyObject_CallMethodNoArgs(self, round_method_name) #else PyObject_CallMethodObjArgs(self, round_method_name, NULL) #endif ; Py_DECREF(round_method_name); return result; } static int PyUnicode_is_ascii(PyObject *self) { return ((PyASCIIObject *)self)->state.ascii; } static PyObject *Rational = NULL; typedef struct { PyObject_HEAD PyObject *numerator; PyObject *denominator; } FractionObject; static int is_negative_Fraction(FractionObject *self) { return is_negative_Object(self->numerator); } static int is_integral_Fraction(FractionObject *self) { return is_unit_Object(self->denominator); } static void Fraction_dealloc(FractionObject *self) { Py_DECREF(self->numerator); Py_DECREF(self->denominator); Py_TYPE(self)->tp_free((PyObject *)self); } static PyTypeObject FractionType; static int normalize_Fraction_components_moduli(PyObject **result_numerator, PyObject **result_denominator) { PyObject *gcd = _PyLong_GCD(*result_numerator, *result_denominator); if (!gcd) return -1; int is_gcd_unit = is_unit_Object(gcd); if (is_gcd_unit < 0) { Py_DECREF(gcd); return -1; } else if (!is_gcd_unit) { PyObject *numerator = PyNumber_FloorDivide(*result_numerator, gcd); if (!numerator) { Py_DECREF(gcd); return -1; } PyObject *denominator = PyNumber_FloorDivide(*result_denominator, gcd); if (!denominator) { Py_DECREF(numerator); Py_DECREF(gcd); return -1; } PyObject *tmp = *result_numerator; *result_numerator = numerator; Py_DECREF(tmp); tmp = *result_denominator; *result_denominator = denominator; Py_DECREF(tmp); } Py_DECREF(gcd); return 0; } static int normalize_Fraction_components_signs(PyObject **result_numerator, PyObject **result_denominator) { int is_denominator_negative = is_negative_Object(*result_denominator); if (is_denominator_negative < 0) return -1; else if (is_denominator_negative) { PyObject *numerator = PyNumber_Negative(*result_numerator); if (!numerator) return -1; PyObject *denominator = PyNumber_Negative(*result_denominator); if (!denominator) { Py_DECREF(numerator); return -1; } PyObject *tmp = *result_numerator; *result_numerator = numerator; Py_DECREF(tmp); tmp = *result_denominator; *result_denominator = denominator; Py_DECREF(tmp); } return 0; } static int parse_Fraction_components_from_rational( PyObject *rational, PyObject **result_numerator, PyObject **result_denominator) { PyObject *numerator = PyObject_GetAttrString(rational, "numerator"); if (!numerator) return -1; PyObject *denominator = PyObject_GetAttrString(rational, "denominator"); if (!denominator) { Py_DECREF(numerator); return -1; } if (normalize_Fraction_components_signs(&numerator, &denominator) < 0 || normalize_Fraction_components_moduli(&numerator, &denominator) < 0) { Py_DECREF(denominator); Py_DECREF(numerator); return -1; } *result_numerator = numerator; *result_denominator = denominator; return 0; } static int parse_Fraction_components_from_double( double value, PyObject **result_numerator, PyObject **result_denominator) { if (isinf(value)) { PyErr_SetString(PyExc_OverflowError, "Cannot construct Fraction from infinity."); return -1; } if (isnan(value)) { PyErr_SetString(PyExc_ValueError, "Cannot construct Fraction from NaN."); return -1; } int exponent; value = frexp(value, &exponent); for (size_t index = 0; index < 300 && value != floor(value); ++index) { value *= 2.0; exponent--; } PyObject *numerator = PyLong_FromDouble(value); if (!numerator) return -1; PyObject *denominator = PyLong_FromLong(1); if (!denominator) { Py_DECREF(numerator); return -1; } PyObject *exponent_object = PyLong_FromLong(abs(exponent)); if (!exponent_object) { Py_DECREF(numerator); Py_DECREF(denominator); return -1; } if (exponent > 0) { PyObject *tmp = numerator; numerator = PyNumber_Lshift(numerator, exponent_object); Py_DECREF(tmp); if (!numerator) { Py_DECREF(denominator); Py_DECREF(exponent_object); return -1; } } else { PyObject *tmp = denominator; denominator = PyNumber_Lshift(denominator, exponent_object); Py_DECREF(tmp); if (!denominator) { Py_DECREF(numerator); Py_DECREF(exponent_object); return -1; } } Py_DECREF(exponent_object); *result_denominator = denominator; *result_numerator = numerator; return 0; } const Py_UCS1 ascii_whitespaces[] = { 0, 0, 0, 0, 0, 0, 0, 0, /* case 0x0009: * CHARACTER TABULATION */ /* case 0x000A: * LINE FEED */ /* case 0x000B: * LINE TABULATION */ /* case 0x000C: * FORM FEED */ /* case 0x000D: * CARRIAGE RETURN */ 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* case 0x001C: * FILE SEPARATOR */ /* case 0x001D: * GROUP SEPARATOR */ /* case 0x001E: * RECORD SEPARATOR */ /* case 0x001F: * UNIT SEPARATOR */ 0, 0, 0, 0, 1, 1, 1, 1, /* case 0x0020: * SPACE */ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; static PyObject *PyUnicode_strip(PyObject *self) { Py_ssize_t size = PyUnicode_GET_LENGTH(self); Py_ssize_t start, stop; if (PyUnicode_is_ascii(self)) { const Py_UCS1 *data = PyUnicode_1BYTE_DATA(self); start = 0; while (start < size && ascii_whitespaces[data[start]]) start++; stop = size - 1; while (stop >= start && ascii_whitespaces[data[stop]]) stop--; stop++; } else { int kind = PyUnicode_KIND(self); const void *data = PyUnicode_DATA(self); start = 0; while (start < size && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, start))) start++; stop = size - 1; while (stop >= start && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, stop))) stop--; stop++; } return PyUnicode_Substring(self, start, stop); } static int is_sign_character(Py_UCS4 character) { return character == '+' || character == '-'; } #if PY3_11_OR_MORE static int is_delimiter(Py_UCS4 character) { return character == '_'; } static Py_ssize_t search_unsigned_PyLong(int kind, const void *data, Py_ssize_t size, Py_ssize_t start) { Py_ssize_t index = start; for (int follows_delimiter = 1; index < size; ++index) { Py_UCS4 character = PyUnicode_READ(kind, data, index); if (Py_UNICODE_ISDIGIT(character)) { follows_delimiter = 0; continue; } else if (!follows_delimiter && is_delimiter(character)) { follows_delimiter = !follows_delimiter; continue; } break; } return index; } #else static Py_ssize_t search_unsigned_PyLong(int kind, const void *data, Py_ssize_t size, Py_ssize_t start) { Py_ssize_t index = start; for (; index < size && Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, index)); ++index) ; return index; } #endif static Py_ssize_t search_signed_PyLong(int kind, const void *data, Py_ssize_t size, Py_ssize_t start) { return search_unsigned_PyLong( kind, data, size, start + is_sign_character(PyUnicode_READ(kind, data, start))); } static PyObject *parse_PyLong(PyObject *self, Py_ssize_t start, Py_ssize_t stop) { PyObject *result_unicode = PyUnicode_Substring(self, start, stop); if (!result_unicode) return NULL; PyObject *result = PyLong_FromUnicodeObject(result_unicode, 10); Py_DECREF(result_unicode); return result; } static PyObject *append_zeros(PyObject *self, PyObject *exponent) { PyObject *base = PyLong_FromLong(10); if (!base) return NULL; PyObject *scale = PyNumber_Power(base, exponent, Py_None); Py_DECREF(base); if (!scale) return NULL; PyObject *result = PyNumber_Multiply(self, scale); Py_DECREF(scale); return result; } static int parse_Fraction_components_from_PyUnicode( PyObject *value, PyObject **result_numerator, PyObject **result_denominator) { Py_ssize_t size = PyUnicode_GET_LENGTH(value); int kind = PyUnicode_KIND(value); const void *data = PyUnicode_DATA(value); Py_UCS4 first_character = PyUnicode_READ(kind, data, 0); Py_ssize_t start = is_sign_character(first_character); Py_ssize_t numerator_stop = search_unsigned_PyLong(kind, data, size, start); if (numerator_stop == size) { *result_numerator = PyLong_FromUnicodeObject(value, 10); if (!*result_numerator) return -1; *result_denominator = PyLong_FromLong(1); if (!*result_denominator) { Py_DECREF(*result_numerator); return -1; } return 0; } int is_negative = first_character == '-'; int has_numerator = numerator_stop != start; *result_numerator = has_numerator ? parse_PyLong(value, start, numerator_stop) : PyLong_FromLong(0); if (!*result_numerator) return -1; *result_denominator = PyLong_FromLong(1); if (!*result_denominator) { Py_DECREF(*result_numerator); return -1; } Py_UCS4 character = PyUnicode_READ(kind, data, numerator_stop); if (character == '/' && start < numerator_stop && numerator_stop < size - 1) { Py_ssize_t denominator_stop = search_unsigned_PyLong(kind, data, size, numerator_stop + 1); if (denominator_stop == size) { *result_numerator = parse_PyLong(value, start, numerator_stop); if (!*result_numerator) { Py_DECREF(*result_denominator); return -1; } *result_denominator = parse_PyLong(value, numerator_stop + 1, denominator_stop); if (!*result_denominator) { Py_DECREF(*result_numerator); return -1; } if (PyObject_Not(*result_denominator)) { PyErr_Format(PyExc_ZeroDivisionError, "Fraction(%S, 0)", *result_numerator); Py_DECREF(*result_denominator); Py_DECREF(*result_numerator); return -1; } if (is_negative) { PyObject *tmp = *result_numerator; *result_numerator = PyNumber_Negative(*result_numerator); Py_DECREF(tmp); if (!*result_numerator) { Py_DECREF(*result_denominator); return -1; } } return normalize_Fraction_components_moduli(result_numerator, result_denominator); } } else if (character == '.') { Py_ssize_t decimal_part_stop = search_unsigned_PyLong(kind, data, size, numerator_stop + 1); int has_decimal_part = decimal_part_stop != numerator_stop + 1; if (has_decimal_part) { PyObject *decimal_part = parse_PyLong(value, numerator_stop + 1, decimal_part_stop); if (!decimal_part) { Py_DECREF(*result_denominator); Py_DECREF(*result_numerator); return -1; } #if PY3_11_OR_MORE Py_ssize_t delimiters_count = 0; for (Py_ssize_t index = numerator_stop + 2; index < decimal_part_stop; ++index) if (is_delimiter(PyUnicode_READ(kind, data, index))) ++delimiters_count; PyObject *exponent = PyLong_FromSsize_t( decimal_part_stop - numerator_stop - 1 - delimiters_count); #else PyObject *exponent = PyLong_FromSsize_t(decimal_part_stop - numerator_stop - 1); #endif if (!exponent) { Py_DECREF(decimal_part); Py_DECREF(*result_denominator); Py_DECREF(*result_numerator); return -1; } PyObject *tmp = *result_numerator; *result_numerator = append_zeros(*result_numerator, exponent); Py_DECREF(tmp); if (!*result_numerator) { Py_DECREF(exponent); Py_DECREF(decimal_part); Py_DECREF(*result_denominator); return -1; } tmp = *result_numerator; *result_numerator = PyNumber_Add(*result_numerator, decimal_part); Py_DECREF(tmp); Py_DECREF(decimal_part); if (!*result_numerator) { Py_DECREF(exponent); Py_DECREF(*result_denominator); return -1; } tmp = *result_denominator; *result_denominator = append_zeros(*result_denominator, exponent); Py_DECREF(tmp); Py_DECREF(exponent); if (!*result_denominator) { Py_DECREF(*result_numerator); return -1; } } if (decimal_part_stop == size) { if (is_negative) { PyObject *tmp = *result_numerator; *result_numerator = PyNumber_Negative(*result_numerator); Py_DECREF(tmp); if (!*result_numerator) { Py_DECREF(*result_denominator); return -1; } } return normalize_Fraction_components_moduli(result_numerator, result_denominator); } else { character = PyUnicode_READ(kind, data, decimal_part_stop); if ((has_numerator || has_decimal_part) && (character == 'e' || character == 'E')) { if (is_negative) { PyObject *tmp = *result_numerator; *result_numerator = PyNumber_Negative(*result_numerator); Py_DECREF(tmp); if (!*result_numerator) { Py_DECREF(*result_denominator); return -1; } } Py_ssize_t exponent_stop = search_signed_PyLong(kind, data, size, decimal_part_stop + 1); if (exponent_stop == size) { PyObject *exponent = parse_PyLong(value, decimal_part_stop + 1, exponent_stop); if (!exponent) { Py_DECREF(*result_denominator); Py_DECREF(*result_numerator); return -1; } int is_exponent_negative = is_negative_Object(exponent); if (is_exponent_negative < 0) { Py_DECREF(exponent); Py_DECREF(*result_denominator); Py_DECREF(*result_numerator); return -1; } else if (is_exponent_negative) { PyObject *tmp = exponent; exponent = PyNumber_Negative(exponent); Py_DECREF(tmp); if (!exponent) { Py_DECREF(*result_denominator); Py_DECREF(*result_numerator); return -1; } tmp = *result_denominator; *result_denominator = append_zeros(*result_denominator, exponent); Py_DECREF(tmp); Py_DECREF(exponent); if (!*result_denominator) { Py_DECREF(*result_numerator); return -1; } return normalize_Fraction_components_moduli(result_numerator, result_denominator); } else { PyObject *tmp = *result_numerator; *result_numerator = append_zeros(*result_numerator, exponent); Py_DECREF(tmp); Py_DECREF(exponent); if (!*result_numerator) { Py_DECREF(*result_denominator); return -1; } return normalize_Fraction_components_moduli(result_numerator, result_denominator); } } } } } else if (has_numerator && (character == 'e' || character == 'E')) { if (is_negative) { PyObject *tmp = *result_numerator; *result_numerator = PyNumber_Negative(*result_numerator); Py_DECREF(tmp); if (!*result_numerator) { Py_DECREF(*result_denominator); return -1; } } Py_ssize_t exponent_stop = search_signed_PyLong(kind, data, size, numerator_stop + 1); if (exponent_stop == size) { PyObject *exponent = parse_PyLong(value, numerator_stop + 1, exponent_stop); if (!exponent) { Py_DECREF(*result_denominator); Py_DECREF(*result_numerator); return -1; } int is_exponent_negative = is_negative_Object(exponent); if (is_exponent_negative < 0) { Py_DECREF(exponent); Py_DECREF(*result_denominator); Py_DECREF(*result_numerator); return -1; } else if (is_exponent_negative) { PyObject *tmp = exponent; exponent = PyNumber_Negative(exponent); Py_DECREF(tmp); if (!exponent) { Py_DECREF(*result_denominator); Py_DECREF(*result_numerator); return -1; } tmp = *result_denominator; *result_denominator = append_zeros(*result_denominator, exponent); Py_DECREF(tmp); Py_DECREF(exponent); if (!*result_denominator) { Py_DECREF(*result_numerator); return -1; } return normalize_Fraction_components_moduli(result_numerator, result_denominator); } else { PyObject *tmp = *result_numerator; *result_numerator = append_zeros(*result_numerator, exponent); Py_DECREF(tmp); Py_DECREF(exponent); if (!*result_numerator) { Py_DECREF(*result_denominator); return -1; } return normalize_Fraction_components_moduli(result_numerator, result_denominator); } } } PyErr_Format(PyExc_ValueError, "Invalid literal for Fraction: %R", value); return -1; } static FractionObject *construct_Fraction(PyTypeObject *cls, PyObject *numerator, PyObject *denominator) { FractionObject *result = (FractionObject *)(cls->tp_alloc(cls, 0)); if (result) { result->numerator = numerator; result->denominator = denominator; } else { Py_DECREF(denominator); Py_DECREF(numerator); } return result; } static PyObject *Fraction_new(PyTypeObject *cls, PyObject *args, PyObject *kwargs) { if (!_PyArg_NoKeywords("Fraction", kwargs)) return NULL; PyObject *numerator = NULL, *denominator = NULL; if (!PyArg_ParseTuple(args, "|OO", &numerator, &denominator)) return NULL; if (denominator) { if (!PyLong_Check(numerator)) { PyErr_SetString(PyExc_TypeError, "Numerator should be an integer."); return NULL; } if (!PyLong_Check(denominator)) { PyErr_SetString(PyExc_TypeError, "Denominator should be an integer."); return NULL; } if (PyObject_Not(denominator)) { PyErr_SetString(PyExc_ZeroDivisionError, "Denominator should be non-zero."); return NULL; } int is_denominator_negative = is_negative_Object(denominator); if (is_denominator_negative < 0) return NULL; else if (is_denominator_negative) { numerator = PyNumber_Negative(numerator); if (!numerator) return NULL; denominator = PyNumber_Negative(denominator); if (!denominator) { Py_DECREF(numerator); return NULL; } } else { Py_INCREF(numerator); Py_INCREF(denominator); } if (normalize_Fraction_components_moduli(&numerator, &denominator) < 0) { Py_DECREF(numerator); Py_DECREF(denominator); return NULL; } } else if (numerator) { if (PyLong_Check(numerator)) { denominator = PyLong_FromLong(1); if (!denominator) return NULL; Py_INCREF(numerator); } else if (PyFloat_Check(numerator)) { if (parse_Fraction_components_from_double(PyFloat_AS_DOUBLE(numerator), &numerator, &denominator) < 0) return NULL; } else if (PyObject_TypeCheck(numerator, &FractionType)) { FractionObject *fraction_numerator = (FractionObject *)numerator; Py_INCREF(fraction_numerator->denominator); denominator = fraction_numerator->denominator; Py_INCREF(fraction_numerator->numerator); numerator = fraction_numerator->numerator; } else if (PyObject_IsInstance(numerator, Rational)) { if (parse_Fraction_components_from_rational(numerator, &numerator, &denominator) < 0) return NULL; } else if (PyUnicode_Check(numerator)) { PyObject *stripped_unicode = PyUnicode_strip(numerator); int flag = parse_Fraction_components_from_PyUnicode( stripped_unicode, &numerator, &denominator); Py_DECREF(stripped_unicode); if (flag < 0) return NULL; } else { PyErr_SetString(PyExc_TypeError, "Single argument should be either an integer, " "a floating point, a rational number or a string " "representation of a fraction."); return NULL; } } else { denominator = PyLong_FromLong(1); numerator = PyLong_FromLong(0); } return (PyObject *)construct_Fraction(cls, numerator, denominator); } static PyObject *Fractions_components_richcompare(PyObject *numerator, PyObject *denominator, PyObject *other_numerator, PyObject *other_denominator, int op) { switch (op) { case Py_EQ: { int comparison_signal = PyObject_RichCompareBool(numerator, other_numerator, op); if (comparison_signal < 0) return NULL; else if (!comparison_signal) Py_RETURN_FALSE; return PyObject_RichCompare(denominator, other_denominator, op); } case Py_NE: { int comparison_signal = PyObject_RichCompareBool(numerator, other_numerator, op); if (comparison_signal < 0) return NULL; else if (comparison_signal) Py_RETURN_TRUE; return PyObject_RichCompare(denominator, other_denominator, op); } default: { PyObject *result, *left, *right; left = PyNumber_Multiply(numerator, other_denominator); if (!left) return NULL; right = PyNumber_Multiply(other_numerator, denominator); if (!right) { Py_DECREF(left); return NULL; } result = PyObject_RichCompare(left, right, op); Py_DECREF(left); Py_DECREF(right); return result; } } } static PyObject *Fractions_richcompare(FractionObject *self, FractionObject *other, int op) { return Fractions_components_richcompare(self->numerator, self->denominator, other->numerator, other->denominator, op); } static PyObject *Fraction_richcompare(FractionObject *self, PyObject *other, int op) { if (PyObject_TypeCheck(other, &FractionType)) return Fractions_richcompare(self, (FractionObject *)other, op); else if (PyLong_Check(other)) { if (op == Py_EQ) { int is_integral = is_integral_Fraction(self); if (is_integral < 0) return NULL; else if (!is_integral) Py_RETURN_FALSE; return PyObject_RichCompare(self->numerator, other, op); } else if (op == Py_NE) { int is_integral = is_integral_Fraction(self); if (is_integral < 0) return NULL; else if (!is_integral) Py_RETURN_TRUE; return PyObject_RichCompare(self->numerator, other, op); } else { PyObject *result, *tmp; tmp = PyNumber_Multiply(other, self->denominator); if (!tmp) return NULL; result = PyObject_RichCompare(self->numerator, tmp, op); Py_DECREF(tmp); return result; } } else if (PyFloat_Check(other)) { double other_value = PyFloat_AS_DOUBLE(other); if (!isfinite(other_value)) switch (op) { case Py_EQ: Py_RETURN_FALSE; case Py_GT: case Py_GE: return PyBool_FromLong(isinf(other_value) && other_value < 0.); case Py_LT: case Py_LE: return PyBool_FromLong(isinf(other_value) && other_value > 0.); case Py_NE: Py_RETURN_TRUE; default: return NULL; } PyObject *other_denominator, *other_numerator; if (parse_Fraction_components_from_double(other_value, &other_numerator, &other_denominator) < 0) return NULL; return Fractions_components_richcompare(self->numerator, self->denominator, other_numerator, other_denominator, op); } else if (PyObject_IsInstance(other, Rational)) { PyObject *other_denominator, *other_numerator; if (parse_Fraction_components_from_rational(other, &other_numerator, &other_denominator) < 0) return NULL; return Fractions_components_richcompare(self->numerator, self->denominator, other_numerator, other_denominator, op); } Py_RETURN_NOTIMPLEMENTED; } static FractionObject *Fraction_negative(FractionObject *self) { PyObject *numerator = PyNumber_Negative(self->numerator); if (!numerator) return NULL; Py_INCREF(self->denominator); PyObject *denominator = self->denominator; return construct_Fraction(&FractionType, numerator, denominator); } static FractionObject *Fraction_absolute(FractionObject *self) { PyObject *numerator = PyNumber_Absolute(self->numerator); if (!numerator) return NULL; Py_INCREF(self->denominator); PyObject *denominator = self->denominator; return construct_Fraction(&FractionType, numerator, denominator); } static PyObject *Fraction_float(FractionObject *self) { return PyNumber_TrueDivide(self->numerator, self->denominator); } static FractionObject *Fractions_components_add(PyObject *numerator, PyObject *denominator, PyObject *other_numerator, PyObject *other_denominator) { PyObject *first_result_numerator_component = PyNumber_Multiply(numerator, other_denominator); if (!first_result_numerator_component) return NULL; PyObject *second_result_numerator_component = PyNumber_Multiply(other_numerator, denominator); if (!second_result_numerator_component) { Py_DECREF(first_result_numerator_component); return NULL; } PyObject *result_numerator = PyNumber_Add(first_result_numerator_component, second_result_numerator_component); Py_DECREF(second_result_numerator_component); Py_DECREF(first_result_numerator_component); if (!result_numerator) return NULL; PyObject *result_denominator = PyNumber_Multiply(denominator, other_denominator); if (!result_denominator) { Py_DECREF(result_numerator); return NULL; } if (normalize_Fraction_components_moduli(&result_numerator, &result_denominator)) { Py_DECREF(result_denominator); Py_DECREF(result_numerator); return NULL; } return construct_Fraction(&FractionType, result_numerator, result_denominator); } static FractionObject *Fractions_add(FractionObject *self, FractionObject *other) { return Fractions_components_add(self->numerator, self->denominator, other->numerator, other->denominator); } static PyObject *Fraction_Float_add(FractionObject *self, PyObject *other) { PyObject *tmp = Fraction_float(self); if (!tmp) return NULL; PyObject *result = PyNumber_Add(tmp, other); Py_DECREF(tmp); return result; } static FractionObject *Fraction_Long_add(FractionObject *self, PyObject *other) { PyObject *tmp = PyNumber_Multiply(other, self->denominator); if (!tmp) return NULL; PyObject *result_numerator = PyNumber_Add(self->numerator, tmp); Py_DECREF(tmp); if (!result_numerator) return NULL; Py_INCREF(self->denominator); PyObject *result_denominator = self->denominator; if (normalize_Fraction_components_moduli(&result_numerator, &result_denominator) < 0) { Py_DECREF(result_denominator); Py_DECREF(result_numerator); return NULL; } return construct_Fraction(&FractionType, result_numerator, result_denominator); } static FractionObject *Fraction_Rational_add(FractionObject *self, PyObject *other) { PyObject *other_denominator, *other_numerator; if (parse_Fraction_components_from_rational(other, &other_numerator, &other_denominator) < 0) return NULL; FractionObject *result = Fractions_components_add( self->numerator, self->denominator, other_numerator, other_denominator); Py_DECREF(other_denominator); Py_DECREF(other_numerator); return result; } static PyObject *Fraction_add(PyObject *self, PyObject *other) { if (PyObject_TypeCheck(self, &FractionType)) { if (PyObject_TypeCheck(other, &FractionType)) return (PyObject *)Fractions_add((FractionObject *)self, (FractionObject *)other); else if (PyLong_Check(other)) return (PyObject *)Fraction_Long_add((FractionObject *)self, other); else if (PyFloat_Check(other)) return (PyObject *)Fraction_Float_add((FractionObject *)self, other); else if (PyObject_IsInstance(other, Rational)) return (PyObject *)Fraction_Rational_add((FractionObject *)self, other); } else if (PyLong_Check(self)) return (PyObject *)Fraction_Long_add((FractionObject *)other, self); else if (PyFloat_Check(self)) return (PyObject *)Fraction_Float_add((FractionObject *)other, self); else if (PyObject_IsInstance(self, Rational)) return (PyObject *)Fraction_Rational_add((FractionObject *)other, self); Py_RETURN_NOTIMPLEMENTED; } static PyObject *Fraction_as_integer_ratio(FractionObject *self, PyObject *Py_UNUSED(args)) { return PyTuple_Pack(2, self->numerator, self->denominator); } static int Fraction_bool(FractionObject *self) { return PyObject_IsTrue(self->numerator); } static PyObject *Fraction_ceil_impl(FractionObject *self) { PyObject *tmp = PyNumber_Negative(self->numerator); if (!tmp) return NULL; PyObject *result = PyNumber_FloorDivide(tmp, self->denominator); Py_DECREF(tmp); if (!result) return NULL; tmp = result; result = PyNumber_Negative(result); Py_DECREF(tmp); return result; } static PyObject *Fraction_ceil(FractionObject *self, PyObject *Py_UNUSED(args)) { return Fraction_ceil_impl(self); } static PyObject *Fraction_copy(FractionObject *self, PyObject *Py_UNUSED(args)) { if (Py_TYPE(self) == &FractionType) { Py_INCREF(self); return (PyObject *)self; } else return PyObject_CallFunctionObjArgs( (PyObject *)Py_TYPE(self), self->numerator, self->denominator, NULL); } static PyObject *Fraction_reduce(FractionObject *self, PyObject *Py_UNUSED(args)) { return Py_BuildValue("O(OO)", Py_TYPE(self), self->numerator, self->denominator); } static PyObject *Fraction_floor_impl(FractionObject *self) { return PyNumber_FloorDivide(self->numerator, self->denominator); } static PyObject *Fraction_floor(FractionObject *self, PyObject *Py_UNUSED(args)) { return Fraction_floor_impl(self); } static PyObject *Fractions_components_floor_divide( PyObject *numerator, PyObject *denominator, PyObject *other_numerator, PyObject *other_denominator) { PyObject *dividend = PyNumber_Multiply(numerator, other_denominator); if (!dividend) return NULL; PyObject *divisor = PyNumber_Multiply(denominator, other_numerator); if (!divisor) { Py_DECREF(dividend); return NULL; } PyObject *result = PyNumber_FloorDivide(dividend, divisor); Py_DECREF(dividend); Py_DECREF(divisor); return result; } static PyObject *Fractions_floor_divide(FractionObject *self, FractionObject *other) { return Fractions_components_floor_divide( self->numerator, self->denominator, other->numerator, other->denominator); } static PyObject *Fraction_Long_floor_divide(FractionObject *self, PyObject *other) { PyObject *gcd = _PyLong_GCD(self->numerator, other); if (!gcd) return NULL; PyObject *dividend = PyNumber_FloorDivide(self->numerator, gcd); if (!dividend) { Py_DECREF(gcd); return NULL; } PyObject *other_normalized = PyNumber_FloorDivide(other, gcd); Py_DECREF(gcd); if (!other_normalized) { Py_DECREF(dividend); return NULL; } PyObject *divisor = PyNumber_Multiply(self->denominator, other_normalized); Py_DECREF(other_normalized); if (!divisor) { Py_DECREF(dividend); return NULL; } PyObject *result = PyNumber_FloorDivide(dividend, divisor); Py_DECREF(dividend); Py_DECREF(divisor); return result; } static PyObject *Long_Fraction_floor_divide(PyObject *self, FractionObject *other) { PyObject *gcd = _PyLong_GCD(self, other->numerator); if (!gcd) return NULL; PyObject *divisor = PyNumber_FloorDivide(other->numerator, gcd); if (!divisor) { Py_DECREF(gcd); return NULL; } PyObject *self_normalized = PyNumber_FloorDivide(self, gcd); Py_DECREF(gcd); if (!self_normalized) { Py_DECREF(divisor); return NULL; } PyObject *dividend = PyNumber_Multiply(self_normalized, other->denominator); Py_DECREF(self_normalized); if (!dividend) { Py_DECREF(divisor); return NULL; } PyObject *result = PyNumber_FloorDivide(dividend, divisor); Py_DECREF(dividend); Py_DECREF(divisor); return result; } static PyObject *Fraction_Rational_floor_divide(FractionObject *self, PyObject *other) { PyObject *other_denominator, *other_numerator; if (parse_Fraction_components_from_rational(other, &other_numerator, &other_denominator) < 0) return NULL; PyObject *result = Fractions_components_floor_divide( self->numerator, self->denominator, other_numerator, other_denominator); Py_DECREF(other_denominator); Py_DECREF(other_numerator); return result; } static PyObject *Rational_Fraction_floor_divide(PyObject *self, FractionObject *other) { PyObject *denominator, *numerator; if (parse_Fraction_components_from_rational(self, &numerator, &denominator) < 0) return NULL; PyObject *result = Fractions_components_floor_divide( numerator, denominator, other->numerator, other->denominator); Py_DECREF(denominator); Py_DECREF(numerator); return result; } static PyObject *Fraction_floor_divide(PyObject *self, PyObject *other) { if (PyObject_TypeCheck(self, &FractionType)) { if (PyObject_TypeCheck(other, &FractionType)) return Fractions_floor_divide((FractionObject *)self, (FractionObject *)other); else if (PyLong_Check(other)) return Fraction_Long_floor_divide((FractionObject *)self, other); else if (PyFloat_Check(other)) { PyObject *result, *tmp; tmp = Fraction_float((FractionObject *)self); if (!tmp) return NULL; result = PyNumber_FloorDivide(tmp, other); Py_DECREF(tmp); return result; } else if (PyObject_IsInstance(other, Rational)) return Fraction_Rational_floor_divide((FractionObject *)self, other); } else if (PyLong_Check(self)) return Long_Fraction_floor_divide(self, (FractionObject *)other); else if (PyFloat_Check(self)) { PyObject *result, *tmp; tmp = Fraction_float((FractionObject *)other); if (!tmp) return NULL; result = PyNumber_FloorDivide(self, tmp); Py_DECREF(tmp); return result; } else if (PyObject_IsInstance(self, Rational)) return Rational_Fraction_floor_divide(self, (FractionObject *)other); Py_RETURN_NOTIMPLEMENTED; } static int Longs_divmod(PyObject *dividend, PyObject *divisor, PyObject **result_quotient, PyObject **result_remainder) { PyObject *pair = PyNumber_Divmod(dividend, divisor); if (!pair) return -1; else if (!PyTuple_Check(pair) || PyTuple_GET_SIZE(pair) != 2) { PyErr_SetString(PyExc_TypeError, "divmod should return pair of integers."); Py_DECREF(pair); return -1; } PyObject *quotient = PyTuple_GET_ITEM(pair, 0); Py_INCREF(quotient); PyObject *remainder = PyTuple_GET_ITEM(pair, 1); Py_INCREF(remainder); Py_DECREF(pair); *result_quotient = quotient; *result_remainder = remainder; return 0; } static PyObject *Fractions_components_divmod(PyObject *numerator, PyObject *denominator, PyObject *other_numerator, PyObject *other_denominator) { PyObject *dividend = PyNumber_Multiply(numerator, other_denominator); if (!dividend) return NULL; PyObject *divisor = PyNumber_Multiply(other_numerator, denominator); if (!divisor) { Py_DECREF(dividend); return NULL; } PyObject *quotient, *remainder_numerator; int divmod_signal = Longs_divmod(dividend, divisor, &quotient, &remainder_numerator); Py_DECREF(divisor); Py_DECREF(dividend); if (divmod_signal < 0) return NULL; PyObject *remainder_denominator = PyNumber_Multiply(denominator, other_denominator); if (!remainder_denominator) { Py_DECREF(remainder_numerator); Py_DECREF(quotient); return NULL; } if (normalize_Fraction_components_moduli(&remainder_numerator, &remainder_denominator) < 0) { Py_DECREF(remainder_denominator); Py_DECREF(remainder_numerator); Py_DECREF(quotient); return NULL; } FractionObject *remainder = construct_Fraction( &FractionType, remainder_numerator, remainder_denominator); if (!remainder) { Py_DECREF(quotient); return NULL; } return PyTuple_Pack(2, quotient, remainder); } static PyObject *Fractions_divmod(FractionObject *self, FractionObject *other) { return Fractions_components_divmod(self->numerator, self->denominator, other->numerator, other->denominator); } static PyObject *Fraction_Long_divmod(FractionObject *self, PyObject *other) { PyObject *tmp = PyNumber_Multiply(other, self->denominator); if (!tmp) return NULL; PyObject *quotient, *remainder_numerator; int divmod_signal = Longs_divmod(self->numerator, tmp, &quotient, &remainder_numerator); if (divmod_signal < 0) return NULL; PyObject *remainder_denominator = self->denominator; Py_INCREF(remainder_denominator); if (normalize_Fraction_components_moduli(&remainder_numerator, &remainder_denominator) < 0) { Py_DECREF(remainder_denominator); Py_DECREF(remainder_numerator); Py_DECREF(quotient); return NULL; } FractionObject *remainder = construct_Fraction( &FractionType, remainder_numerator, remainder_denominator); if (!remainder) { Py_DECREF(quotient); return NULL; } return PyTuple_Pack(2, quotient, remainder); } static PyObject *Long_Fraction_divmod(PyObject *self, FractionObject *other) { PyObject *tmp = PyNumber_Multiply(self, other->denominator); if (!tmp) return NULL; PyObject *quotient, *remainder_numerator; int divmod_signal = Longs_divmod(tmp, other->numerator, &quotient, &remainder_numerator); if (divmod_signal < 0) return NULL; PyObject *remainder_denominator = other->denominator; Py_INCREF(remainder_denominator); if (normalize_Fraction_components_moduli(&remainder_numerator, &remainder_denominator) < 0) { Py_DECREF(remainder_denominator); Py_DECREF(remainder_numerator); Py_DECREF(quotient); return NULL; } FractionObject *remainder = construct_Fraction( &FractionType, remainder_numerator, remainder_denominator); if (!remainder) { Py_DECREF(quotient); return NULL; } return PyTuple_Pack(2, quotient, remainder); } static PyObject *Fraction_Rational_divmod(FractionObject *self, PyObject *other) { PyObject *other_denominator, *other_numerator; if (parse_Fraction_components_from_rational(other, &other_numerator, &other_denominator) < 0) return NULL; PyObject *result = Fractions_components_divmod( self->numerator, self->denominator, other_numerator, other_denominator); Py_DECREF(other_denominator); Py_DECREF(other_numerator); return result; } static PyObject *Rational_Fraction_divmod(PyObject *self, FractionObject *other) { PyObject *denominator, *numerator; if (parse_Fraction_components_from_rational(self, &numerator, &denominator) < 0) return NULL; PyObject *result = Fractions_components_divmod( numerator, denominator, other->numerator, other->denominator); Py_DECREF(denominator); Py_DECREF(numerator); return result; } static PyObject *Fraction_divmod(PyObject *self, PyObject *other) { if (PyObject_TypeCheck(self, &FractionType)) { if (PyObject_TypeCheck(other, &FractionType)) return Fractions_divmod((FractionObject *)self, (FractionObject *)other); else if (PyLong_Check(other)) return Fraction_Long_divmod((FractionObject *)self, other); else if (PyFloat_Check(other)) { PyObject *float_self, *result; float_self = Fraction_float((FractionObject *)self); if (!float_self) return NULL; result = PyNumber_Divmod(float_self, other); Py_DECREF(float_self); return result; } else if (PyObject_IsInstance(other, Rational)) return Fraction_Rational_divmod((FractionObject *)self, other); } else if (PyLong_Check(self)) return Long_Fraction_divmod(self, (FractionObject *)other); else if (PyFloat_Check(self)) { PyObject *float_other, *result; float_other = Fraction_float((FractionObject *)other); if (!float_other) return NULL; result = PyNumber_Divmod(self, float_other); Py_DECREF(float_other); return result; } else if (PyObject_IsInstance(self, Rational)) return Rational_Fraction_divmod(self, (FractionObject *)other); Py_RETURN_NOTIMPLEMENTED; } static Py_hash_t Fraction_hash(FractionObject *self) { PyObject *hash_modulus = PyLong_FromSize_t(_PyHASH_MODULUS); if (!hash_modulus) return -1; PyObject *tmp = PyLong_FromSize_t(_PyHASH_MODULUS - 2); if (!tmp) { Py_DECREF(hash_modulus); return -1; } PyObject *inverted_denominator_hash = PyNumber_Power(self->denominator, tmp, hash_modulus); Py_DECREF(tmp); if (!inverted_denominator_hash) { Py_DECREF(hash_modulus); return -1; } PyObject *hash_; if (PyObject_Not(inverted_denominator_hash)) { Py_DECREF(inverted_denominator_hash); Py_DECREF(hash_modulus); return _PyHASH_INF; } else { PyObject *numerator_modulus = PyNumber_Absolute(self->numerator); if (!numerator_modulus) { Py_DECREF(inverted_denominator_hash); Py_DECREF(hash_modulus); return -1; } tmp = PyNumber_Multiply(numerator_modulus, inverted_denominator_hash); hash_ = PyNumber_Remainder(tmp, hash_modulus); Py_DECREF(tmp); Py_DECREF(numerator_modulus); Py_DECREF(inverted_denominator_hash); Py_DECREF(hash_modulus); if (!hash_) return -1; } int is_negative = is_negative_Fraction(self); if (is_negative < 0) return -1; else if (is_negative) { tmp = hash_; hash_ = PyNumber_Negative(hash_); Py_DECREF(tmp); } Py_hash_t result = PyLong_AsSsize_t(hash_); Py_DECREF(hash_); if (PyErr_Occurred()) return -1; return result == -1 ? -2 : result; } static FractionObject *Fractions_components_multiply( PyObject *numerator, PyObject *denominator, PyObject *other_numerator, PyObject *other_denominator) { PyObject *gcd = _PyLong_GCD(numerator, other_denominator); if (!gcd) return NULL; numerator = PyNumber_FloorDivide(numerator, gcd); if (!numerator) { Py_DECREF(gcd); return NULL; } other_denominator = PyNumber_FloorDivide(other_denominator, gcd); Py_DECREF(gcd); if (!other_denominator) { Py_DECREF(numerator); return NULL; } gcd = _PyLong_GCD(other_numerator, denominator); if (!gcd) return NULL; other_numerator = PyNumber_FloorDivide(other_numerator, gcd); if (!other_numerator) { Py_DECREF(gcd); Py_DECREF(other_denominator); Py_DECREF(numerator); return NULL; } denominator = PyNumber_FloorDivide(denominator, gcd); Py_DECREF(gcd); if (!denominator) { Py_DECREF(other_numerator); Py_DECREF(other_denominator); Py_DECREF(numerator); return NULL; } PyObject *result_numerator = PyNumber_Multiply(numerator, other_numerator); Py_DECREF(other_numerator); Py_DECREF(numerator); if (!result_numerator) { Py_DECREF(other_denominator); Py_DECREF(denominator); return NULL; } PyObject *result_denominator = PyNumber_Multiply(denominator, other_denominator); Py_DECREF(other_denominator); Py_DECREF(denominator); if (!result_denominator) { Py_DECREF(result_numerator); return NULL; } return construct_Fraction(&FractionType, result_numerator, result_denominator); } static FractionObject *Fractions_multiply(FractionObject *self, FractionObject *other) { return Fractions_components_multiply(self->numerator, self->denominator, other->numerator, other->denominator); } static PyObject *Fraction_Float_multiply(FractionObject *self, PyObject *other) { PyObject *result, *tmp; tmp = Fraction_float(self); if (!tmp) return NULL; result = PyNumber_Multiply(tmp, other); Py_DECREF(tmp); return result; } static FractionObject *Fraction_Long_multiply(FractionObject *self, PyObject *other) { PyObject *gcd = _PyLong_GCD(other, self->denominator); if (!gcd) return NULL; PyObject *other_normalized = PyNumber_FloorDivide(other, gcd); if (!other_normalized) { Py_DECREF(gcd); return NULL; } PyObject *result_denominator = PyNumber_FloorDivide(self->denominator, gcd); Py_DECREF(gcd); if (!result_denominator) { Py_DECREF(other_normalized); return NULL; } PyObject *result_numerator = PyNumber_Multiply(self->numerator, other_normalized); Py_DECREF(other_normalized); if (!result_numerator) { Py_DECREF(result_denominator); return NULL; } return construct_Fraction(&FractionType, result_numerator, result_denominator); } static FractionObject *Fraction_Rational_multiply(FractionObject *self, PyObject *other) { PyObject *other_denominator, *other_numerator; if (parse_Fraction_components_from_rational(other, &other_numerator, &other_denominator) < 0) return NULL; FractionObject *result = Fractions_components_multiply( self->numerator, self->denominator, other_numerator, other_denominator); Py_DECREF(other_denominator); Py_DECREF(other_numerator); return result; } static PyObject *Fraction_multiply(PyObject *self, PyObject *other) { if (PyObject_TypeCheck(self, &FractionType)) { if (PyObject_TypeCheck(other, &FractionType)) return (PyObject *)Fractions_multiply((FractionObject *)self, (FractionObject *)other); else if (PyLong_Check(other)) return (PyObject *)Fraction_Long_multiply((FractionObject *)self, other); else if (PyFloat_Check(other)) return (PyObject *)Fraction_Float_multiply((FractionObject *)self, other); else if (PyObject_IsInstance(other, Rational)) return (PyObject *)Fraction_Rational_multiply((FractionObject *)self, other); } else if (PyLong_Check(self)) return (PyObject *)Fraction_Long_multiply((FractionObject *)other, self); else if (PyFloat_Check(self)) return (PyObject *)Fraction_Float_multiply((FractionObject *)other, self); else if (PyObject_IsInstance(self, Rational)) return (PyObject *)Fraction_Rational_multiply((FractionObject *)other, self); Py_RETURN_NOTIMPLEMENTED; } static FractionObject *Fractions_components_remainder( PyObject *numerator, PyObject *denominator, PyObject *other_numerator, PyObject *other_denominator) { PyObject *dividend = PyNumber_Multiply(numerator, other_denominator); if (!dividend) return NULL; PyObject *divisor = PyNumber_Multiply(other_numerator, denominator); if (!divisor) { Py_DECREF(dividend); return NULL; } PyObject *result_numerator = PyNumber_Remainder(dividend, divisor); Py_DECREF(dividend); Py_DECREF(divisor); if (!result_numerator) return NULL; PyObject *result_denominator = PyNumber_Multiply(denominator, other_denominator); if (!result_denominator) { Py_DECREF(result_numerator); return NULL; } if (normalize_Fraction_components_moduli(&result_numerator, &result_denominator) < 0) { Py_DECREF(result_denominator); Py_DECREF(result_numerator); return NULL; } return construct_Fraction(&FractionType, result_numerator, result_denominator); } static FractionObject *Fractions_remainder(FractionObject *self, FractionObject *other) { return Fractions_components_remainder(self->numerator, self->denominator, other->numerator, other->denominator); } static FractionObject *Fraction_Long_remainder(FractionObject *self, PyObject *other) { PyObject *tmp = PyNumber_Multiply(other, self->denominator); if (!tmp) return NULL; PyObject *result_numerator = PyNumber_Remainder(self->numerator, tmp); Py_DECREF(tmp); if (!result_numerator) return NULL; Py_INCREF(self->denominator); PyObject *result_denominator = self->denominator; if (normalize_Fraction_components_moduli(&result_numerator, &result_denominator) < 0) { Py_DECREF(result_denominator); Py_DECREF(result_numerator); return NULL; } return construct_Fraction(&FractionType, result_numerator, result_denominator); } static FractionObject *Long_Fraction_remainder(PyObject *self, FractionObject *other) { PyObject *tmp = PyNumber_Multiply(self, other->denominator); if (!tmp) return NULL; PyObject *result_numerator = PyNumber_Remainder(tmp, other->numerator); Py_DECREF(tmp); if (!result_numerator) return NULL; Py_INCREF(other->denominator); PyObject *result_denominator = other->denominator; if (normalize_Fraction_components_moduli(&result_numerator, &result_denominator) < 0) { Py_DECREF(result_denominator); Py_DECREF(result_numerator); } return construct_Fraction(&FractionType, result_numerator, result_denominator); } static FractionObject *Fraction_Rational_remainder(FractionObject *self, PyObject *other) { PyObject *other_denominator, *other_numerator; if (parse_Fraction_components_from_rational(other, &other_numerator, &other_denominator) < 0) return NULL; FractionObject *result = Fractions_components_remainder( self->numerator, self->denominator, other_numerator, other_denominator); Py_DECREF(other_denominator); Py_DECREF(other_numerator); return result; } static FractionObject *Rational_Fraction_remainder(PyObject *self, FractionObject *other) { PyObject *denominator, *numerator; if (parse_Fraction_components_from_rational(self, &numerator, &denominator) < 0) return NULL; FractionObject *result = Fractions_components_remainder( numerator, denominator, other->numerator, other->denominator); Py_DECREF(denominator); Py_DECREF(numerator); return result; } static PyObject *FractionObject_remainder(FractionObject *self, PyObject *other) { if (PyObject_TypeCheck(other, &FractionType)) return (PyObject *)Fractions_remainder(self, (FractionObject *)other); else if (PyLong_Check(other)) return (PyObject *)Fraction_Long_remainder(self, other); else if (PyFloat_Check(other)) { PyObject *tmp = Fraction_float(self); if (!tmp) return NULL; PyObject *result = PyNumber_Remainder(tmp, other); Py_DECREF(tmp); return result; } else if (PyObject_IsInstance(other, Rational)) return (PyObject *)Fraction_Rational_remainder(self, other); Py_RETURN_NOTIMPLEMENTED; } static PyObject *Fraction_remainder(PyObject *self, PyObject *other) { if (PyObject_TypeCheck(self, &FractionType)) return FractionObject_remainder((FractionObject *)self, other); else if (PyLong_Check(self)) return (PyObject *)Long_Fraction_remainder(self, (FractionObject *)other); else if (PyFloat_Check(self)) { PyObject *tmp = Fraction_float((FractionObject *)other); if (!tmp) return NULL; PyObject *result = PyNumber_Remainder(self, tmp); Py_DECREF(tmp); return result; } else if (PyObject_IsInstance(self, Rational)) return (PyObject *)Rational_Fraction_remainder(self, (FractionObject *)other); Py_RETURN_NOTIMPLEMENTED; } static PyObject *Long_Fraction_power(PyObject *self, FractionObject *exponent, PyObject *modulo) { int comparison_signal = is_integral_Fraction(exponent); if (comparison_signal < 0) return NULL; else if (comparison_signal) { comparison_signal = is_negative_Fraction(exponent); if (comparison_signal < 0) return NULL; else if (comparison_signal) { if (PyObject_Not(self)) { PyErr_SetString(PyExc_ZeroDivisionError, "Either exponent should be non-negative " "or base should not be zero."); return NULL; } PyObject *positive_exponent = PyNumber_Negative(exponent->numerator); if (!positive_exponent) return NULL; PyObject *result_denominator = PyNumber_Power(self, positive_exponent, Py_None); Py_DECREF(positive_exponent); if (!result_denominator) return NULL; PyObject *result_numerator = PyLong_FromLong(1); if (!result_numerator) { Py_DECREF(result_denominator); return NULL; } FractionObject *result = construct_Fraction( &FractionType, result_numerator, result_denominator); if (!!result && modulo != Py_None) { PyObject *remainder = FractionObject_remainder(result, modulo); Py_DECREF(result); return remainder; } return (PyObject *)result; } else { PyObject *result_numerator = PyNumber_Power(self, exponent->numerator, modulo); if (!result_numerator) return NULL; PyObject *result_denominator = PyLong_FromLong(1); if (!result_denominator) { Py_DECREF(result_numerator); return NULL; } return (PyObject *)construct_Fraction(&FractionType, result_numerator, result_denominator); } } else { PyObject *float_exponent = PyNumber_TrueDivide(exponent->numerator, exponent->denominator); if (!float_exponent) return NULL; PyObject *result = PyNumber_Power(self, float_exponent, modulo); Py_DECREF(float_exponent); return result; } } static PyObject *Fractions_components_positive_Long_power(PyObject *numerator, PyObject *denominator, PyObject *exponent, PyObject *modulo) { int comparison_signal = is_unit_Object(denominator); if (comparison_signal < 0) return NULL; else if (comparison_signal && (modulo == Py_None || PyLong_Check(modulo))) { PyObject *result_numerator = PyNumber_Power(numerator, exponent, modulo); if (!result_numerator) return NULL; PyObject *result_denominator = PyLong_FromLong(1); if (!result_denominator) { Py_DECREF(result_numerator); return NULL; } return (PyObject *)construct_Fraction(&FractionType, result_numerator, result_denominator); } else { PyObject *result_numerator = PyNumber_Power(numerator, exponent, Py_None); if (!result_numerator) return NULL; PyObject *result_denominator = PyNumber_Power(denominator, exponent, Py_None); if (!result_denominator) { Py_DECREF(result_numerator); return NULL; } FractionObject *result = construct_Fraction(&FractionType, result_numerator, result_denominator); if (!!result && modulo != Py_None) { PyObject *remainder = FractionObject_remainder(result, modulo); Py_DECREF(result); return remainder; } return (PyObject *)result; } } static PyObject *Fraction_components_Long_power(PyObject *numerator, PyObject *denominator, PyObject *exponent, PyObject *modulo) { int comparison_signal = is_negative_Object(exponent); if (comparison_signal < 0) return NULL; else if (comparison_signal) { if (PyObject_Not(numerator)) { PyErr_SetString(PyExc_ZeroDivisionError, "Either exponent should be non-negative " "or base should not be zero."); return NULL; } PyObject *positive_exponent = PyNumber_Negative(exponent); if (!positive_exponent) return NULL; Py_INCREF(denominator); PyObject *inverted_numerator = denominator; Py_INCREF(numerator); PyObject *inverted_denominator = numerator; if (normalize_Fraction_components_signs(&inverted_numerator, &inverted_denominator) < 0) { Py_DECREF(positive_exponent); return NULL; } PyObject *result = Fractions_components_positive_Long_power( inverted_numerator, inverted_denominator, positive_exponent, modulo); Py_DECREF(inverted_denominator); Py_DECREF(inverted_numerator); Py_DECREF(positive_exponent); return result; } return Fractions_components_positive_Long_power(numerator, denominator, exponent, modulo); } static PyObject *Float_Fraction_components_power(PyObject *self, PyObject *exponent_numerator, PyObject *exponent_denominator, PyObject *modulo) { PyObject *float_exponent = PyNumber_TrueDivide(exponent_numerator, exponent_denominator); if (!float_exponent) return NULL; PyObject *result = PyNumber_Power(self, float_exponent, modulo); Py_DECREF(float_exponent); return result; } static PyObject *Float_Fraction_power(PyObject *self, FractionObject *exponent, PyObject *modulo) { return Float_Fraction_components_power(self, exponent->numerator, exponent->denominator, modulo); } static PyObject *Fractions_components_power(PyObject *numerator, PyObject *denominator, PyObject *exponent_numerator, PyObject *exponent_denominator, PyObject *modulo) { int is_integral_exponent = is_unit_Object(exponent_denominator); if (is_integral_exponent < 0) return NULL; else if (is_integral_exponent) return Fraction_components_Long_power(numerator, denominator, exponent_numerator, modulo); else { PyObject *float_self = PyNumber_TrueDivide(numerator, denominator); if (!float_self) return NULL; PyObject *result = Float_Fraction_components_power( float_self, exponent_numerator, exponent_denominator, modulo); Py_DECREF(float_self); return result; } } static PyObject *Fractions_power(FractionObject *self, FractionObject *exponent, PyObject *modulo) { return Fractions_components_power(self->numerator, self->denominator, exponent->numerator, exponent->denominator, modulo); } static PyObject *Fraction_Long_power(FractionObject *self, PyObject *exponent, PyObject *modulo) { return Fraction_components_Long_power(self->numerator, self->denominator, exponent, modulo); } static PyObject *Fraction_Rational_power(FractionObject *self, PyObject *exponent, PyObject *modulo) { PyObject *exponent_denominator, *exponent_numerator; if (parse_Fraction_components_from_rational(exponent, &exponent_numerator, &exponent_denominator) < 0) return NULL; PyObject *result = Fractions_components_power( self->numerator, self->denominator, exponent_numerator, exponent_denominator, modulo); Py_DECREF(exponent_denominator); Py_DECREF(exponent_numerator); return result; } static PyObject *Rational_Fraction_power(PyObject *self, FractionObject *exponent, PyObject *modulo) { PyObject *denominator, *numerator; if (parse_Fraction_components_from_rational(self, &numerator, &denominator) < 0) return NULL; PyObject *result = Fractions_components_power(numerator, denominator, exponent->numerator, exponent->denominator, modulo); Py_DECREF(denominator); Py_DECREF(numerator); return result; } static PyObject *Fraction_power(PyObject *self, PyObject *exponent, PyObject *modulo) { if (PyObject_TypeCheck(self, &FractionType)) { if (PyObject_TypeCheck(exponent, &FractionType)) return Fractions_power((FractionObject *)self, (FractionObject *)exponent, modulo); else if (PyLong_Check(exponent)) return Fraction_Long_power((FractionObject *)self, exponent, modulo); else if (PyFloat_Check(exponent)) { PyObject *float_self, *result; float_self = Fraction_float((FractionObject *)self); result = PyNumber_Power(float_self, exponent, modulo); Py_DECREF(float_self); return result; } else if (PyObject_IsInstance(exponent, Rational)) return Fraction_Rational_power((FractionObject *)self, exponent, modulo); } else if (PyObject_TypeCheck(exponent, &FractionType)) { if (PyLong_Check(self)) return Long_Fraction_power(self, (FractionObject *)exponent, modulo); else if (PyFloat_Check(self)) return Float_Fraction_power(self, (FractionObject *)exponent, modulo); else if (PyObject_IsInstance(self, Rational)) return Rational_Fraction_power(self, (FractionObject *)exponent, modulo); } else { PyObject *tmp = PyNumber_Power(self, exponent, Py_None); if (!tmp) return NULL; PyObject *result = Fraction_remainder(tmp, modulo); Py_DECREF(tmp); return result; } Py_RETURN_NOTIMPLEMENTED; } static FractionObject *Fractions_components_subtract( PyObject *numerator, PyObject *denominator, PyObject *other_numerator, PyObject *other_denominator) { PyObject *numerator_minuend = PyNumber_Multiply(numerator, other_denominator); if (!numerator_minuend) return NULL; PyObject *numerator_subtrahend = PyNumber_Multiply(other_numerator, denominator); if (!numerator_subtrahend) { Py_DECREF(numerator_minuend); return NULL; } PyObject *result_numerator = PyNumber_Subtract(numerator_minuend, numerator_subtrahend); Py_DECREF(numerator_subtrahend); Py_DECREF(numerator_minuend); if (!result_numerator) return NULL; PyObject *result_denominator = PyNumber_Multiply(denominator, other_denominator); if (!result_denominator) { Py_DECREF(result_numerator); return NULL; } if (normalize_Fraction_components_moduli(&result_numerator, &result_denominator)) { Py_DECREF(result_denominator); Py_DECREF(result_numerator); return NULL; } return construct_Fraction(&FractionType, result_numerator, result_denominator); } static FractionObject *Fractions_subtract(FractionObject *self, FractionObject *other) { return Fractions_components_subtract(self->numerator, self->denominator, other->numerator, other->denominator); } static PyObject *Fraction_Float_subtract(FractionObject *self, PyObject *other) { PyObject *tmp = Fraction_float(self); if (!tmp) return NULL; PyObject *result = PyNumber_Subtract(tmp, other); Py_DECREF(tmp); return result; } static FractionObject *Fraction_Long_subtract(FractionObject *self, PyObject *other) { PyObject *tmp = PyNumber_Multiply(other, self->denominator); if (!tmp) return NULL; PyObject *result_numerator = PyNumber_Subtract(self->numerator, tmp); Py_DECREF(tmp); Py_INCREF(self->denominator); PyObject *result_denominator = self->denominator; if (normalize_Fraction_components_moduli(&result_numerator, &result_denominator) < 0) { Py_DECREF(result_denominator); Py_DECREF(result_numerator); } return construct_Fraction(&FractionType, result_numerator, result_denominator); } static FractionObject *Fraction_Rational_subtract(FractionObject *self, PyObject *other) { PyObject *other_denominator, *other_numerator; if (parse_Fraction_components_from_rational(other, &other_numerator, &other_denominator) < 0) return NULL; FractionObject *result = Fractions_components_subtract( self->numerator, self->denominator, other_numerator, other_denominator); Py_DECREF(other_denominator); Py_DECREF(other_numerator); return result; } static PyObject *Fraction_subtract(PyObject *self, PyObject *other) { if (PyObject_TypeCheck(self, &FractionType)) { if (PyObject_TypeCheck(other, &FractionType)) return (PyObject *)Fractions_subtract((FractionObject *)self, (FractionObject *)other); else if (PyLong_Check(other)) return (PyObject *)Fraction_Long_subtract((FractionObject *)self, other); else if (PyFloat_Check(other)) return (PyObject *)Fraction_Float_subtract((FractionObject *)self, other); else if (PyObject_IsInstance(other, Rational)) return (PyObject *)Fraction_Rational_subtract((FractionObject *)self, other); } else if (PyLong_Check(self)) { FractionObject *result = Fraction_Long_subtract((FractionObject *)other, self); if (!result) return NULL; PyObject *tmp = result->numerator; result->numerator = PyNumber_Negative(result->numerator); Py_DECREF(tmp); return (PyObject *)result; } else if (PyFloat_Check(self)) { PyObject *tmp = (PyObject *)Fraction_Float_subtract((FractionObject *)other, self); if (!tmp) return NULL; PyObject *result = PyNumber_Negative(tmp); Py_DECREF(tmp); return result; } else if (PyObject_IsInstance(self, Rational)) { FractionObject *result = Fraction_Rational_subtract((FractionObject *)other, self); if (!result) return NULL; PyObject *tmp = result->numerator; result->numerator = PyNumber_Negative(result->numerator); Py_DECREF(tmp); return (PyObject *)result; } Py_RETURN_NOTIMPLEMENTED; } static FractionObject *Fraction_limit_denominator_impl( FractionObject *self, PyObject *max_denominator) { PyObject *tmp = PyLong_FromLong(1); if (!tmp) return NULL; int comparison_signal = PyObject_RichCompareBool(max_denominator, tmp, Py_LT); Py_DECREF(tmp); if (comparison_signal < 0) return NULL; else if (comparison_signal) { PyErr_SetString(PyExc_ValueError, "`max_denominator` should not be less than 1."); return NULL; } comparison_signal = PyObject_RichCompareBool(self->denominator, max_denominator, Py_LE); if (comparison_signal < 0) return NULL; else if (comparison_signal) { Py_INCREF(self); return self; } PyObject *denominator = self->denominator, *numerator = self->numerator; Py_INCREF(denominator); Py_INCREF(numerator); PyObject *first_bound_numerator = PyLong_FromLong(0), *first_bound_denominator = PyLong_FromLong(1), *second_bound_numerator = PyLong_FromLong(1), *second_bound_denominator = PyLong_FromLong(0); while (1) { PyObject *quotient = PyNumber_FloorDivide(numerator, denominator); if (!quotient) goto error; PyObject *tmp = PyNumber_Multiply(quotient, second_bound_denominator); if (!tmp) { Py_DECREF(quotient); goto loop_error; } PyObject *candidate_denominator = PyNumber_Add(first_bound_denominator, tmp); Py_DECREF(tmp); if (!candidate_denominator) { Py_DECREF(quotient); goto loop_error; } comparison_signal = PyObject_RichCompareBool(candidate_denominator, max_denominator, Py_GT); if (comparison_signal < 0) { Py_DECREF(candidate_denominator); Py_DECREF(quotient); goto loop_error; } else if (comparison_signal) { Py_DECREF(candidate_denominator); Py_DECREF(quotient); break; } tmp = PyNumber_Multiply(quotient, denominator); if (!tmp) { Py_DECREF(candidate_denominator); Py_DECREF(quotient); goto loop_error; } PyObject *other_tmp = PyNumber_Subtract(numerator, tmp); Py_DECREF(tmp); if (!other_tmp) { Py_DECREF(candidate_denominator); Py_DECREF(quotient); goto loop_error; } numerator = denominator; denominator = other_tmp; Py_DECREF(first_bound_denominator); first_bound_denominator = second_bound_denominator; second_bound_denominator = candidate_denominator; tmp = PyNumber_Multiply(quotient, second_bound_numerator); Py_DECREF(quotient); if (!tmp) goto loop_error; other_tmp = PyNumber_Add(first_bound_numerator, tmp); Py_DECREF(tmp); if (!other_tmp) goto loop_error; first_bound_numerator = second_bound_numerator; second_bound_numerator = other_tmp; } Py_DECREF(numerator); Py_DECREF(denominator); tmp = PyNumber_Subtract(max_denominator, first_bound_denominator); if (!tmp) goto error; PyObject *scale = PyNumber_FloorDivide(tmp, second_bound_denominator); Py_DECREF(tmp); if (!scale) goto error; tmp = PyNumber_Multiply(scale, second_bound_numerator); if (!tmp) { Py_DECREF(scale); goto error; } PyObject *other_tmp = PyNumber_Add(first_bound_numerator, tmp); Py_DECREF(tmp); if (!other_tmp) { Py_DECREF(scale); goto error; } Py_DECREF(first_bound_numerator); first_bound_numerator = other_tmp; tmp = PyNumber_Multiply(scale, second_bound_denominator); if (!tmp) { Py_DECREF(scale); goto error; } other_tmp = PyNumber_Add(first_bound_denominator, tmp); Py_DECREF(tmp); if (!other_tmp) { Py_DECREF(scale); goto error; } Py_DECREF(first_bound_denominator); first_bound_denominator = other_tmp; FractionObject *first_bound = construct_Fraction( &FractionType, first_bound_numerator, first_bound_denominator); if (!first_bound) { Py_DECREF(second_bound_denominator); Py_DECREF(second_bound_numerator); return NULL; }; FractionObject *second_bound = construct_Fraction( &FractionType, second_bound_numerator, second_bound_denominator); if (!second_bound) { Py_DECREF(first_bound); return NULL; } FractionObject *difference = Fractions_subtract(first_bound, self); if (!difference) { Py_DECREF(first_bound); Py_DECREF(second_bound); return NULL; } FractionObject *first_bound_distance_to_self = Fraction_absolute(difference); Py_DECREF(difference); if (!first_bound_distance_to_self) { Py_DECREF(first_bound); Py_DECREF(second_bound); return NULL; } difference = Fractions_subtract(second_bound, self); if (!difference) { Py_DECREF(first_bound_distance_to_self); Py_DECREF(first_bound); Py_DECREF(second_bound); return NULL; } FractionObject *second_bound_distance_to_self = Fraction_absolute(difference); Py_DECREF(difference); if (!second_bound_distance_to_self) { Py_DECREF(first_bound_distance_to_self); Py_DECREF(first_bound); Py_DECREF(second_bound); return NULL; } PyObject *comparison_result = Fractions_richcompare( second_bound_distance_to_self, first_bound_distance_to_self, Py_LE); Py_DECREF(first_bound_distance_to_self); Py_DECREF(second_bound_distance_to_self); if (!comparison_result) { Py_DECREF(first_bound); Py_DECREF(second_bound); return NULL; } else if (comparison_result == Py_True) { Py_DECREF(comparison_result); Py_DECREF(first_bound); return second_bound; } else { Py_DECREF(comparison_result); Py_DECREF(second_bound); return first_bound; } loop_error: Py_DECREF(numerator); Py_DECREF(denominator); error: Py_DECREF(first_bound_denominator); Py_DECREF(first_bound_numerator); Py_DECREF(second_bound_denominator); Py_DECREF(second_bound_numerator); return NULL; } static PyObject *Fraction_limit_denominator(FractionObject *self, PyObject *args) { PyObject *max_denominator = NULL; if (!PyArg_ParseTuple(args, "|O", &max_denominator)) return NULL; if (!max_denominator) { max_denominator = PyLong_FromLong(1000000); PyObject *result = (PyObject *)Fraction_limit_denominator_impl(self, max_denominator); Py_DECREF(max_denominator); return result; } else return (PyObject *)Fraction_limit_denominator_impl(self, max_denominator); } static FractionObject *Fractions_components_true_divide( PyObject *numerator, PyObject *denominator, PyObject *other_numerator, PyObject *other_denominator) { if (PyObject_Not(other_numerator)) { PyErr_Format(PyExc_ZeroDivisionError, "Fraction(%S, 0)", numerator); return NULL; } PyObject *gcd = _PyLong_GCD(numerator, other_numerator); if (!gcd) return NULL; numerator = PyNumber_FloorDivide(numerator, gcd); if (!numerator) { Py_DECREF(gcd); return NULL; } other_numerator = PyNumber_FloorDivide(other_numerator, gcd); Py_DECREF(gcd); if (!other_numerator) { Py_DECREF(numerator); return NULL; } gcd = _PyLong_GCD(denominator, other_denominator); if (!gcd) return NULL; denominator = PyNumber_FloorDivide(denominator, gcd); if (!denominator) { Py_DECREF(gcd); Py_DECREF(other_numerator); Py_DECREF(numerator); return NULL; } other_denominator = PyNumber_FloorDivide(other_denominator, gcd); Py_DECREF(gcd); if (!other_denominator) { Py_DECREF(denominator); Py_DECREF(other_numerator); Py_DECREF(numerator); return NULL; } PyObject *result_numerator = PyNumber_Multiply(numerator, other_denominator); Py_DECREF(other_denominator); Py_DECREF(numerator); if (!result_numerator) { Py_DECREF(other_numerator); Py_DECREF(denominator); return NULL; } PyObject *result_denominator = PyNumber_Multiply(denominator, other_numerator); Py_DECREF(other_numerator); Py_DECREF(denominator); if (!result_denominator) { Py_DECREF(result_numerator); return NULL; } if (normalize_Fraction_components_signs(&result_numerator, &result_denominator) < 0) { Py_INCREF(result_denominator); Py_INCREF(result_numerator); return NULL; } return construct_Fraction(&FractionType, result_numerator, result_denominator); } static FractionObject *Fractions_true_divide(FractionObject *self, FractionObject *other) { return Fractions_components_true_divide(self->numerator, self->denominator, other->numerator, other->denominator); } static FractionObject *Fraction_Long_true_divide(FractionObject *self, PyObject *other) { if (PyObject_Not(other)) { PyErr_Format(PyExc_ZeroDivisionError, "Fraction(%S, 0)", self->numerator); return NULL; } PyObject *gcd = _PyLong_GCD(self->numerator, other); if (!gcd) return NULL; PyObject *result_numerator = PyNumber_FloorDivide(self->numerator, gcd); if (!result_numerator) { Py_DECREF(gcd); return NULL; } PyObject *other_normalized = PyNumber_FloorDivide(other, gcd); Py_DECREF(gcd); if (!other_normalized) { Py_DECREF(result_numerator); return NULL; } PyObject *result_denominator = PyNumber_Multiply(self->denominator, other_normalized); Py_DECREF(other_normalized); if (!result_denominator) { Py_DECREF(result_numerator); return NULL; } if (normalize_Fraction_components_signs(&result_numerator, &result_denominator) < 0) { Py_INCREF(result_denominator); Py_INCREF(result_numerator); return NULL; } return construct_Fraction(&FractionType, result_numerator, result_denominator); } static FractionObject *Long_Fraction_true_divide(PyObject *self, FractionObject *other) { if (!Fraction_bool(other)) { PyErr_Format(PyExc_ZeroDivisionError, "Fraction(%S, 0)", self); return NULL; } PyObject *gcd = _PyLong_GCD(self, other->numerator); if (!gcd) return NULL; PyObject *result_denominator = PyNumber_FloorDivide(other->numerator, gcd); if (!result_denominator) { Py_DECREF(gcd); return NULL; } PyObject *self_normalized = PyNumber_FloorDivide(self, gcd); Py_DECREF(gcd); if (!self_normalized) { Py_DECREF(result_denominator); return NULL; } PyObject *result_numerator = PyNumber_Multiply(self_normalized, other->denominator); Py_DECREF(self_normalized); if (!result_numerator) { Py_DECREF(result_denominator); return NULL; } if (normalize_Fraction_components_signs(&result_numerator, &result_denominator) < 0) { Py_INCREF(result_denominator); Py_INCREF(result_numerator); return NULL; } return construct_Fraction(&FractionType, result_numerator, result_denominator); } static FractionObject *Fraction_Rational_true_divide(FractionObject *self, PyObject *other) { PyObject *other_denominator, *other_numerator; if (parse_Fraction_components_from_rational(other, &other_numerator, &other_denominator) < 0) return NULL; FractionObject *result = Fractions_components_true_divide( self->numerator, self->denominator, other_numerator, other_denominator); Py_DECREF(other_denominator); Py_DECREF(other_numerator); return result; } static FractionObject *Rational_Fraction_true_divide(PyObject *self, FractionObject *other) { PyObject *denominator, *numerator; if (parse_Fraction_components_from_rational(self, &numerator, &denominator) < 0) return NULL; FractionObject *result = Fractions_components_true_divide( numerator, denominator, other->numerator, other->denominator); Py_DECREF(denominator); Py_DECREF(numerator); return result; } static PyObject *Fraction_true_divide(PyObject *self, PyObject *other) { if (PyObject_TypeCheck(self, &FractionType)) { if (PyObject_TypeCheck(other, &FractionType)) return (PyObject *)Fractions_true_divide((FractionObject *)self, (FractionObject *)other); else if (PyLong_Check(other)) return (PyObject *)Fraction_Long_true_divide((FractionObject *)self, other); else if (PyFloat_Check(other)) { PyObject *tmp = Fraction_float((FractionObject *)self); if (!tmp) return NULL; PyObject *result = PyNumber_TrueDivide(tmp, other); Py_DECREF(tmp); return result; } else if (PyObject_IsInstance(other, Rational)) return (PyObject *)Fraction_Rational_true_divide((FractionObject *)self, other); } else if (PyLong_Check(self)) return (PyObject *)Long_Fraction_true_divide(self, (FractionObject *)other); else if (PyFloat_Check(self)) { PyObject *tmp = Fraction_float((FractionObject *)other); if (!tmp) return NULL; PyObject *result = PyNumber_TrueDivide(self, tmp); Py_DECREF(tmp); return result; } else if (PyObject_IsInstance(self, Rational)) return (PyObject *)Rational_Fraction_true_divide(self, (FractionObject *)other); Py_RETURN_NOTIMPLEMENTED; } static FractionObject *Fraction_positive(FractionObject *self) { Py_INCREF(self); return self; } static PyObject *Fraction_round_plain(FractionObject *self) { PyObject *quotient, *remainder; int divmod_signal = Longs_divmod(self->numerator, self->denominator, &quotient, &remainder); if (divmod_signal < 0) return NULL; PyObject *scalar = PyLong_FromLong(2); if (!scalar) { Py_DECREF(remainder); Py_DECREF(quotient); return NULL; } PyObject *tmp = PyNumber_Multiply(remainder, scalar); Py_DECREF(remainder); if (!tmp) { Py_DECREF(scalar); Py_DECREF(quotient); return NULL; } int comparison_signal = PyObject_RichCompareBool(tmp, self->denominator, Py_LT); if (comparison_signal < 0) { Py_DECREF(tmp); Py_DECREF(scalar); Py_DECREF(quotient); return NULL; } else if (comparison_signal) { Py_DECREF(tmp); Py_DECREF(scalar); return quotient; } comparison_signal = PyObject_RichCompareBool(tmp, self->denominator, Py_EQ); Py_DECREF(tmp); if (comparison_signal < 0) { Py_DECREF(scalar); Py_DECREF(quotient); return NULL; } else if (comparison_signal) { tmp = PyNumber_Remainder(quotient, scalar); Py_DECREF(scalar); if (PyObject_Not(tmp)) { Py_DECREF(tmp); return quotient; } Py_DECREF(tmp); } Py_DECREF(scalar); scalar = PyLong_FromLong(1); if (!scalar) { Py_DECREF(quotient); return NULL; } tmp = quotient; quotient = PyNumber_Add(quotient, scalar); Py_DECREF(tmp); Py_DECREF(scalar); return quotient; } static PyObject *Fraction_round(FractionObject *self, PyObject *args) { PyObject *precision = NULL; if (!PyArg_ParseTuple(args, "|O", &precision)) return NULL; if (!precision) return Fraction_round_plain(self); int comparison_signal = is_negative_Object(precision); if (comparison_signal < 0) return NULL; PyObject *result_denominator, *result_numerator; if (comparison_signal) { PyObject *tmp = PyLong_FromLong(10); if (!tmp) return NULL; PyObject *positive_precision = PyNumber_Negative(precision); if (!positive_precision) { Py_DECREF(tmp); return NULL; } PyObject *shift = PyNumber_Power(tmp, positive_precision, Py_None); Py_DECREF(tmp); if (!shift) return NULL; tmp = PyNumber_TrueDivide((PyObject *)self, shift); if (!tmp) { Py_DECREF(shift); return NULL; } result_numerator = round_Object(tmp); Py_DECREF(tmp); if (!result_numerator) { Py_DECREF(shift); return NULL; } tmp = result_numerator; result_numerator = PyNumber_Multiply(result_numerator, shift); Py_DECREF(tmp); Py_DECREF(shift); if (!result_numerator) return NULL; result_denominator = PyLong_FromLong(1); if (!result_denominator) { Py_DECREF(result_numerator); return NULL; } } else { PyObject *tmp = PyLong_FromLong(10); if (!tmp) return NULL; result_denominator = PyNumber_Power(tmp, precision, Py_None); Py_DECREF(tmp); if (!result_denominator) return NULL; tmp = PyNumber_Multiply((PyObject *)self, result_denominator); if (!tmp) { Py_DECREF(result_denominator); return NULL; } result_numerator = round_Object(tmp); Py_DECREF(tmp); if (!result_numerator) { Py_DECREF(result_denominator); return NULL; } if (normalize_Fraction_components_moduli(&result_numerator, &result_denominator) < 0) { Py_DECREF(result_numerator); Py_DECREF(result_denominator); return NULL; } } return (PyObject *)construct_Fraction(&FractionType, result_numerator, result_denominator); } static PyObject *Fraction_repr(FractionObject *self) { return PyUnicode_FromFormat("Fraction(%R, %R)", self->numerator, self->denominator); } static PyObject *Fraction_str(FractionObject *self) { PyObject *tmp = PyLong_FromLong(1); int comparison_signal = PyObject_RichCompareBool(self->denominator, tmp, Py_EQ); Py_DECREF(tmp); if (comparison_signal < 0) return NULL; else return comparison_signal ? PyUnicode_FromFormat("%S", self->numerator) : PyUnicode_FromFormat("%S/%S", self->numerator, self->denominator); } static PyObject *Fraction_trunc(FractionObject *self, PyObject *Py_UNUSED(args)) { int is_negative = is_negative_Fraction(self); if (is_negative < 0) return NULL; else return is_negative ? Fraction_ceil_impl(self) : Fraction_floor_impl(self); } static PyMemberDef Fraction_members[] = { {"numerator", T_OBJECT_EX, offsetof(FractionObject, numerator), READONLY, "Numerator of the fraction."}, {"denominator", T_OBJECT_EX, offsetof(FractionObject, denominator), READONLY, "Denominator of the fraction."}, {NULL} /* sentinel */ }; static PyMethodDef Fraction_methods[] = { {"as_integer_ratio", (PyCFunction)Fraction_as_integer_ratio, METH_NOARGS, NULL}, {"limit_denominator", (PyCFunction)Fraction_limit_denominator, METH_VARARGS, NULL}, {"__ceil__", (PyCFunction)Fraction_ceil, METH_NOARGS, NULL}, {"__copy__", (PyCFunction)Fraction_copy, METH_NOARGS, NULL}, {"__deepcopy__", (PyCFunction)Fraction_copy, METH_VARARGS, NULL}, {"__floor__", (PyCFunction)Fraction_floor, METH_NOARGS, NULL}, {"__reduce__", (PyCFunction)Fraction_reduce, METH_NOARGS, NULL}, {"__round__", (PyCFunction)Fraction_round, METH_VARARGS, NULL}, {"__trunc__", (PyCFunction)Fraction_trunc, METH_NOARGS, NULL}, {NULL, NULL} /* sentinel */ }; static PyNumberMethods Fraction_as_number = { .nb_absolute = (unaryfunc)Fraction_absolute, .nb_add = Fraction_add, .nb_bool = (inquiry)Fraction_bool, .nb_divmod = Fraction_divmod, .nb_float = (unaryfunc)Fraction_float, .nb_floor_divide = Fraction_floor_divide, .nb_multiply = Fraction_multiply, .nb_negative = (unaryfunc)Fraction_negative, .nb_positive = (unaryfunc)Fraction_positive, .nb_power = Fraction_power, .nb_remainder = Fraction_remainder, .nb_subtract = Fraction_subtract, .nb_true_divide = Fraction_true_divide, }; static PyTypeObject FractionType = { PyVarObject_HEAD_INIT(NULL, 0).tp_as_number = &Fraction_as_number, .tp_basicsize = sizeof(FractionObject), .tp_dealloc = (destructor)Fraction_dealloc, .tp_doc = PyDoc_STR("Represents rational numbers in the exact form."), .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, .tp_hash = (hashfunc)Fraction_hash, .tp_itemsize = 0, .tp_members = Fraction_members, .tp_methods = Fraction_methods, .tp_name = "cfractions.Fraction", .tp_new = Fraction_new, .tp_repr = (reprfunc)Fraction_repr, .tp_richcompare = (richcmpfunc)Fraction_richcompare, .tp_str = (reprfunc)Fraction_str, }; static PyModuleDef _cfractions_module = { PyModuleDef_HEAD_INIT, .m_doc = PyDoc_STR("Python C API alternative to `fractions` module."), .m_name = "cfractions", .m_size = -1, }; static int load_rational() { PyObject *numbers_module = PyImport_ImportModule("numbers"); if (!numbers_module) return -1; Rational = PyObject_GetAttrString(numbers_module, "Rational"); Py_DECREF(numbers_module); return !Rational ? -1 : 0; } static int mark_as_rational(PyObject *python_type) { PyObject *register_method_name = PyUnicode_FromString("register"); if (!register_method_name) return -1; PyObject *tmp = #if PY3_9_OR_MORE PyObject_CallMethodOneArg(Rational, register_method_name, python_type); #else PyObject_CallMethodObjArgs(Rational, register_method_name, python_type, NULL) #endif ; Py_DECREF(register_method_name); if (!tmp) return -1; Py_DECREF(tmp); return 0; } PyMODINIT_FUNC PyInit__cfractions(void) { PyObject *result; if (PyType_Ready(&FractionType) < 0) return NULL; result = PyModule_Create(&_cfractions_module); if (result == NULL) return NULL; Py_INCREF(&FractionType); if (PyModule_AddObject(result, "Fraction", (PyObject *)&FractionType) < 0) { Py_DECREF(&FractionType); Py_DECREF(result); return NULL; } if (load_rational() < 0) { Py_DECREF(result); return NULL; } if (mark_as_rational((PyObject *)&FractionType) < 0) { Py_DECREF(Rational); Py_DECREF(result); return NULL; } return result; }
<?php namespace frontend\service; use frontend\dao\BidDao; class BidService { /** * * @var type frontend\dao\HomeDao */ public $bid_dao; function __construct() { $this->bid_dao = new BidDao(); } public function getBidReplyInfo($bid_reply_id) { return $this->bid_dao->getBidReplyInfo($bid_reply_id); } public function getMoreReplies($bid_id, $last_time, $offset) { return $this->bid_dao->getMoreReplies($bid_id, $last_time,$offset); } }
class CreatePokemonsets < ActiveRecord::Migration[4.2] def change create_table :pokemonsets do |t| t.string :title t.integer :specie t.integer :hp t.integer :atk t.integer :defe t.integer :spatk t.integer :spdef t.integer :spd t.integer :item t.integer :nature t.integer :ability t.integer :move1 t.integer :move2 t.integer :move3 t.integer :move4 t.string :comment t.boolean :active t.timestamps end end end
import { EventsHandler, IEventHandler } from '@nestjs/cqrs'; import { AccessTokenCreatedEvent } from './access-token-created.event'; @EventsHandler(AccessTokenCreatedEvent) export class AccessTokenCreatedEventHandler implements IEventHandler<AccessTokenCreatedEvent> { handle(event: AccessTokenCreatedEvent) { console.log({ event }); } }
# encoding: utf-8 # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module Azure::Web::Mgmt::V2016_06_01 module Models # # Defines values for ConnectionParameterType # module ConnectionParameterType String = "string" Securestring = "securestring" Secureobject = "secureobject" Int = "int" Bool = "bool" Object = "object" Array = "array" OauthSetting = "oauthSetting" Connection = "connection" end end end
#!/bin/bash /Applications/mongodb/bin/mongod --dbpath /Applications/mongodb/db/ & /Applications/redis/src/redis-server & node-dev "/Users/xukai/Documents/Aptana workspace/melodycoder/app.js" &
#!/usr/bin/env scala object yes { def main (args: Array[String]) { val output = if (args.isEmpty) { "y" } else { args.mkString(" ") } while (true) { println(output) } } }
<?php declare(strict_types=1); namespace BEAR\QueryRepository; use BEAR\RepositoryModule\Annotation\AbstractCacheControl; use BEAR\RepositoryModule\Annotation\Cacheable; use BEAR\RepositoryModule\Annotation\Commands; use BEAR\RepositoryModule\Annotation\Purge; use BEAR\RepositoryModule\Annotation\Refresh; use BEAR\Sunday\Extension\Transfer\HttpCacheInterface; use Ray\Di\AbstractModule; final class CacheableModule extends AbstractModule { /** * {@inheritdoc} */ protected function configure(): void { $this->bind(HttpCacheInterface::class)->to(HttpCache::class); $this->bind()->annotatedWith(Commands::class)->toProvider(CommandsProvider::class); $this->bind(RefreshInterceptor::class); $this->install(new StorageExpiryModule(60, 60 * 60, 60 * 60 * 24)); $this->installAopModule(); } protected function installAopModule(): void { $this->bindPriorityInterceptor( $this->matcher->annotatedWith(Cacheable::class), $this->matcher->startsWith('onGet'), [CacheInterceptor::class] ); $this->bindInterceptor( $this->matcher->annotatedWith(Cacheable::class), $this->matcher->logicalOr( $this->matcher->startsWith('onPut'), $this->matcher->logicalOr( $this->matcher->startsWith('onPatch'), $this->matcher->startsWith('onDelete') ) ), [CommandInterceptor::class] ); $this->bindInterceptor( $this->matcher->logicalNot( $this->matcher->annotatedWith(Cacheable::class) ), $this->matcher->logicalOr( $this->matcher->annotatedWith(Purge::class), $this->matcher->annotatedWith(Refresh::class) ), [RefreshInterceptor::class] ); $this->bindInterceptor( $this->matcher->annotatedWith(AbstractCacheControl::class), $this->matcher->startsWith('onGet'), [HttpCacheInterceptor::class] ); } }
package cz.linkedlist; import cz.linkedlist.info.ProductInfo; import cz.linkedlist.info.TileInfo; import org.springframework.util.concurrent.ListenableFuture; import java.util.Collection; import java.util.List; /** * @author Martin Macko <https://github.com/LinkedList> */ public interface TileInfoService { TileInfo getTileInfo(TileSet tileSet); ProductInfo getProductInfo(TileSet tileSet); /** * Will download TileInfo for specified tileSet * @param tileSet * @return new instance of TileSet with downloaded TileInfo */ ListenableFuture<TileSet> downTileInfo(final TileSet tileSet); ListenableFuture<List<TileSet>> downTileInfo(final Collection<TileSet> tileSets); }
<?php namespace Tests\Unit\Repository\Home; use Exception; use Tests\TestCase; use Illuminate\Http\Request; use App\Model\Article as Model; use App\Repository\Home\Article; use App\Model\Article as ModelArticle; use Illuminate\Foundation\Testing\WithFaker; use Illuminate\Foundation\Testing\RefreshDatabase; class ArticleTest extends TestCase { use RefreshDatabase; /** * A basic unit test for article repository. * @group unit * * @return void */ public function test_find_by_id_witch_is_not_number() { $repository = app()->make(Article::class); try{ $result = $repository->find('sdf'); } catch(Exception $e) { $this->assertTrue($e instanceof \Symfony\Component\HttpKernel\Exception\NotFoundHttpException); } } /** * A basic unit test for article repository. * @group unit * * @return void */ public function test_get_all_by_visit_num() { $this->makeUser('master'); factory(ModelArticle::class, 10)->create(); $repository = app()->make(Article::class); $request = new Request(['order_by' => 'visit']); $result = $repository->all($request); $this->assertEquals($result['articleNum'], 10); for($i = 0, $len = 9; $i < $len; $i++) { $this->assertTrue($result['articles'][$i]['visited'] >= $result['articles'][$i + 1]['visited']); } } /** * A basic unit test for article repository. * @group unit * * @return void */ public function test_get_all_by_comment_num() { $this->makeUser('master'); factory(ModelArticle::class, 10)->create(); $repository = app()->make(Article::class); $request = new Request(['order_by' => 'commented']); $result = $repository->all($request); $this->assertEquals($result['articleNum'], 10); for($i = 0, $len = 9; $i < $len; $i++) { $this->assertTrue($result['articles'][$i]['commented'] >= $result['articles'][$i + 1]['commented']); } } /** * A basic unit test for article repository. * @group unit * * @return void */ public function test_get_zero_article_count() { $repository = app()->make(Article::class); $result = $repository->getArticleCount(); $this->assertEquals($result, 0); } /** * A basic unit test for article repository. * @group unit * * @return void */ public function test_get_twenty_article_count() { $this->makeUser('master'); factory(Model::class, 50)->create(); $repository = app()->make(Article::class); $result = $repository->getArticleCount(); $this->assertEquals($result, 50); } }
require 'open3' require 'timeout' require_relative './GameBoard' class PlayerProcess attr_reader :name class TimeLimitExceededError < RuntimeError; end def initialize(name, cmd) @name = name @stdin, @stdout, @stderr, @thread = Open3.popen3(cmd) @thread.freeze end def send_initial_info(init_info) writeline(init_info) end def communicate(game_info, time_limit) res, exec_time = nil, nil timeout_val = time_limit * 1.1 / 1000.0 begin writeline(game_info) start_at = Time.now Timeout.timeout(timeout_val) { res = readline } exec_time = ((Time.now - start_at) * 1000).to_i rescue Timeout::Error self.exit raise TimeLimitExceededError end [res, exec_time] end def exit begin STDERR.puts "Kill the Player #{name}'s process" Process.kill("KILL", @thread.pid) close_pipes rescue Errno::ESRCH STDERR.puts "The process is already killed" end end private def readline @stdout.gets end def writeline(str) @stdin.puts str @stdin.flush end def close_pipes [@stdin, @stdout, @stderr].each do |pipe| pipe.close end end end class GameManager BOARD_WIDTH = 6 BOARD_HEIGHT = 6 private attr_reader :game_board, :players, :time_limit_max, :time_limits, :logger public def initialize(players, args) @players = players @time_limit_max = args.fetch(:time_limit, 60 * 1000) # (ms) @time_limits = Array.new(2, time_limit_max) @game_board = GameBoard.new @in_progress = false if args[:log] @logger = File.open(args[:log], "w") else @logger = STDOUT end end def start logger.puts <<~EOT # Battle Information Player1: #{players[0].name} Player2: #{players[1].name} Time: #{time_limit_max} EOT @players.each_with_index do |player, i| init_info = [BOARD_WIDTH, BOARD_HEIGHT, i].join("\n") STDERR.puts "Send the initial informations to Player #{player.name}:" STDERR.puts init_info STDERR.puts "" player.send_initial_info(init_info) end @in_progress = true end def play logger.puts "# Battle Log" @move_history = [] while in_progress? play_turn end end def in_progress? @in_progress && game_board.in_progress? end def exit @players.each do |player| player.exit end end private def play_turn turn = game_board.turn turn_player_idx = game_board.turn_player_idx turn_player = players[turn_player_idx] time_limit = time_limits[turn_player_idx] game_info = <<~EOT #{turn} #{time_limit} #{game_board} EOT STDERR.puts "Send the game informations to Player #{turn_player.name}" STDERR.puts game_info STDERR.puts "" begin move, time = turn_player.communicate(game_info, time_limit) time_limits[turn_player_idx] -= time raise PlayerProcess::TimeLimitExceededError if time_limits[turn_player_idx] <= 0 rescue PlayerProcess::TimeLimitExceededError STDERR.puts "Player #{turn_player.name}: Time Limit Exceeded" game_end(turn_player_idx^1, "(Player #{turn_player.name}: Time Limit Exceeded)") return end move = move.chomp @move_history << move begin result = game_board.move(*move.split.map(&:to_i)) rescue GameBoard::InvalidMoveError STDERR.puts "Player #{turn_player.name}: Invalid Move" game_end(turn_player_idx^1, "(Player #{turn_player.name}: Invalid Move \"#{move}\")") return end logger.puts <<~EOT Turn #{turn}: #{players[turn_player_idx].name} [#{game_board.turn_player_symmbol}] Move: #{move} #{game_board} EOT if result if result == GameBoard::Result::DRAW game_end(-1, "Draw") else winner = result-1 game_end(winner, "(Player #{players[winner].name}: Got five stones in a row)") end end end def game_end(winner, reason) logger.puts <<~EOT # Moves #{@move_history.join("\n")} EOT if winner != -1 logger.puts <<~EOT # Result Winner: #{players[winner].name} #{reason} EOT else logger.puts <<~EOT #Result Draw EOT end @in_progress = false end end if __FILE__ == $0 gm = GameManager.new( [PlayerProcess.new("Alice", "./ai_sample.out"), PlayerProcess.new("Bob", "./ai_sample.out")] ) gm.start begin gm.play rescue Interrupt gm.exit exit(1) end gm.exit end
package main import ( "encoding/json" "flag" "fmt" "io" "io/fs" "log" "os" "path/filepath" "strconv" "strings" "github.com/ItsLychee/alto/dsl" "github.com/dhowden/tag" "github.com/pkg/errors" ) var SupportedFormats = []tag.FileType{ tag.MP3, tag.M4A, tag.M4B, tag.M4P, tag.ALAC, tag.FLAC, tag.OGG, tag.DSF, } type Config struct { Path string `json:"path"` Destination string `json:"destination"` Source string `json:"source"` } func filepathFunc(dst *string) func(s string) error { return func(s string) error { if v, err := filepath.Abs(s); err != nil { return err } else { *dst = v } return nil } } func main() { var config Config base, _ := os.UserConfigDir() buf, _ := os.ReadFile(filepath.Join(base, "alto", "config.json")) json.Unmarshal(buf, &config) if v, err := filepath.Abs(config.Destination); err == nil { config.Destination = v } if v, err := filepath.Abs(config.Source); err == nil { config.Source = v } flag.Func("config", "custom path to configuration file", func(s string) error { buf, err := os.ReadFile(s) if err != nil { return err } config = Config{} return json.Unmarshal(buf, &config) }) flag.Func("path", "formatting syntax alto should use for files", func(s string) error { config.Path = s return nil }) flag.Func("source", "where alto should read and index from", filepathFunc(&config.Source)) flag.Func("destination", "where alto should write to", filepathFunc(&config.Destination)) flag.Parse() if config.Destination == "" || config.Path == "" { log.Panicln("path and/or destination must not be nil") } var sourceIndex []string err := filepath.WalkDir(config.Source, func(path string, d fs.DirEntry, err error) error { if err != nil { return err } if d.IsDir() { return err } for _, ext := range SupportedFormats { if strings.HasSuffix(strings.ToLower(path), strings.ToLower(string(ext))) { log.Printf("[%d] indexed: %s", len(sourceIndex)+1, path) sourceIndex = append(sourceIndex, path) return nil } } return nil }) if err != nil { log.Panicln(err) } if len(sourceIndex) == 0 { log.Println("error: no files ending with the appropriate extension were indexed") return } scope, nodes, err := ParseFormatString(config.Path) if err != nil { log.Panicln(errors.Wrap(err, "could not compile nodes for provided path")) } if len(nodes) == 0 { log.Panicln("no nodes were sent") } if err := os.MkdirAll(config.Destination, 0); err != nil { log.Panic(err) } if err := os.Chdir(config.Destination); err != nil { log.Panic(err) } index_iter: for index, path := range sourceIndex { prelimInfo := fmt.Sprintf("[%d/%d]", index+1, len(sourceIndex)) log.Println(prelimInfo, "opening:", path) f, err := os.Open(path) if err != nil { log.Panicln(errors.Wrap(err, fmt.Sprintf("error while opening %s", path))) } defer f.Close() scope.Functions = map[string]dsl.ASTFunction{} scope.Variables = map[string]string{} metadata, err := tag.ReadFrom(f) if err != nil { log.Println(prelimInfo, errors.Wrap(err, "metadata may not be present, error")) } else { discCurrent, discTotal := metadata.Disc() trackCurrent, trackTotal := metadata.Track() scope.Variables = map[string]string{ "trackcurrent": strconv.Itoa(trackCurrent), "tracktotal": strconv.Itoa(trackTotal), "disccurrent": strconv.Itoa(discCurrent), "disctotal": strconv.Itoa(discTotal), "year": strconv.Itoa(metadata.Year()), "comment": metadata.Comment(), "format": string(metadata.Format()), "composer": metadata.Composer(), "genre": metadata.Genre(), "albumartist": metadata.AlbumArtist(), "album": metadata.Album(), "artist": metadata.Artist(), "title": metadata.Title(), "filetype": strings.ToLower(string(metadata.FileType())), } } f.Seek(0, 0) rawFilename := strings.Split(filepath.Base(path), ".") scope.Variables["filename"] = strings.Join(rawFilename[:len(rawFilename)-1], ".") scope.Variables["alto_index"] = strconv.Itoa(index) scope.Variables["alto_source"] = config.Source scope.Variables["alto_dest"] = config.Destination scope.Functions = dsl.DefaultFunctions for k, v := range AltoFunctions { scope.Functions[k] = v } var output strings.Builder for _, v := range nodes { s, err := v.Execute(scope) if err != nil { if err == ErrSkip { log.Println(prelimInfo, "<skip> called") continue index_iter } panic(err) } output.WriteString(s) } if output.String() == "" { panic("no output string") } if err := os.MkdirAll(filepath.Dir(output.String()), 0777); err != nil { panic(err) } destFile, err := os.OpenFile(output.String(), os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0666) if err != nil { panic(err) } written, err := io.Copy(destFile, f) if err != nil { panic(err) } log.Println(prelimInfo, "finished copying to", destFile.Name()) log.Println(prelimInfo, fmt.Sprintf("results: wrote %d MBs (%d bytes)", written/1000000, written)) f.Close() } }
$ErrorActionPreference = "Stop" [reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") Import-Module SitecoreInstallFramework Import-Module Carbon function Get-SitecoreDatabase( [parameter(Mandatory=$true)]$SqlServer, [parameter(Mandatory=$true)]$SqlAdminUser, [parameter(Mandatory=$true)]$SqlAdminPassword ) { $databaseServer = New-Object Microsoft.SqlServer.Management.Smo.Server($SqlServer) $databaseServer.ConnectionContext.LoginSecure = $false $databaseServer.ConnectionContext.Login = $SqlAdminUser $databaseServer.ConnectionContext.Password = $SqlAdminPassword $databases = $databaseServer.Databases return $databaseServer } function Remove-SitecoreDatabase( [parameter(Mandatory=$true)] $Name, [parameter(Mandatory=$true)] $Server ) { if ($Server.Databases[$Name]) { $Server.KillDatabase($Name) Write-Host "Database ($Name) is dropped" -ForegroundColor Green } else { Write-Host "Could not find database ($Name)" -ForegroundColor Yellow } } function Remove-SitecoreSolrCore( [parameter(Mandatory=$true)]$coreName, [parameter(Mandatory=$true)]$root) { $coreRootPath = Join-Path $root "server\solr" $corePath = Join-Path $coreRootPath $coreName if (Test-Path $corePath) { Remove-Item $corePath -Force -Recurse Write-Host "Solr Core $coreName, ($corePath) is removed" -ForegroundColor Green } else { Write-Host "Could not find Solr Core $coreName, ($corePath)" -ForegroundColor Yellow } } function Remove-SitecoreCertificate($certificateName) { $cert = Get-ChildItem -Path "cert:\LocalMachine\My" | Where-Object { $_.subject -like "CN=$certificateName" } if ($cert -and $cert.Thumbprint) { $certPath = "cert:\LocalMachine\My\" + $cert.Thumbprint Remove-Item $certPath Write-Host "Removing certificate $certificateName ($certPath)" -ForegroundColor Green } else { Write-Host "Could not find certificate $certificateName under cert:\LocalMachine\My" -ForegroundColor Yellow } } function Remove-SitecoreWindowsService($name) { if (Get-Service $name -ErrorAction SilentlyContinue) { Uninstall-Service $name Write-Host "Windows service $name is uninstalled" -ForegroundColor Green } else { Write-Host "Could not find windows service $name" -ForegroundColor Yellow } } function Remove-SitecoreIisSite($name) { # Delete site if (Get-IisWebsite $name) { Uninstall-IisWebsite $name Write-Host "IIS site $name is uninstalled" -ForegroundColor Green } else { Write-Host "Could not find IIS site $name" -ForegroundColor Yellow } # Delete app pool if (Get-IisAppPool $name) { Uninstall-IisAppPool $name Write-Host "IIS App Pool $name is uninstalled" -ForegroundColor Green } else { Write-Host "Could not find IIS App Pool $name" -ForegroundColor Yellow } } function Remove-SitecoreFiles($path) { # Delete site if (Test-Path($path)) { Remove-Item $path -Recurse -Force Write-Host "Removing files $path" -ForegroundColor Green } else { Write-Host "Could not find files $path" -ForegroundColor Yellow } }
import * as React from "react"; import { storiesOf } from "@storybook/react"; import { boolean, select } from '@storybook/addon-knobs'; import Panel from "./Panel"; import { PanelHeader } from "../PanelHeader"; import { PanelBody } from "../PanelBody"; import { PanelFooter } from "../PanelFooter"; import { PanelRow } from "../PanelRow"; import { PanelCell } from "../PanelCell"; const stories = storiesOf("Panel", module); export default { title: 'Panel', component: Panel, }; stories.add("Defaults", () => ( <Panel> <PanelHeader title="Panel with Header, Body, Rows, Cells, and Footer" /> <PanelBody> <PanelRow> <PanelCell>Panel Cell Content</PanelCell> <PanelCell>Panel Cell Content</PanelCell> </PanelRow> <PanelRow>Second Panel Row Content</PanelRow> </PanelBody> <PanelFooter>Panel Footer Content</PanelFooter> </Panel> )); stories.add("Full Panel", () => ( <Panel> <PanelHeader title="Full Panel, with Nested Child Elements" /> <PanelBody> <PanelRow isWithCells> <PanelCell mods="u-size4of24 u-flexGrow0" isTitle isHeader> Bill Murray Bio </PanelCell> <PanelCell mods="u-size12of24"> Bill Murray is an American actor, comedian, and writer. The fifth of nine children, he was born William James Murray in Wilmette, Illinois, to Lucille (Collins), a mailroom clerk, and Edward Joseph Murray II, who sold lumber. He is of Irish descent. Among his siblings are actors Brian Doyle-Murray, Joel Murray, and John Murray. He and most of his siblings worked as caddies, which paid his tuition to Loyola Academy, a Jesuit school. He played sports and did some acting while in that school, but in his words, mostly "screwed off." He enrolled at Regis College in Denver to study pre-med but dropped out after being arrested for marijuana possession. He then joined the National Lampoon Radio Hour with fellow members Dan Aykroyd, Gilda Radner, and John Belushi. </PanelCell> <PanelCell mods="u-size8of24"> <img src="https://www.fillmurray.com/640/360" /> </PanelCell> </PanelRow> <PanelRow isWithCells> <PanelCell mods="u-size4of24 u-flexGrow0" isTitle isHeader> Bill Murray Movies </PanelCell> <PanelCell mods="u-size4of24"> Meatballs (1979), Caddyshack (1980), Stripes (1981), Tootsie (1982), Ghostbusters (1984), Ghostbusters II (1989), Scrooged (1988), What About Bob? (1991), and Groundhog Day (1993). </PanelCell> </PanelRow> </PanelBody> <PanelFooter> <span className="Button Button--negative">Cancel Button Placeholder</span> <span className="Button Button--primary u-spaceLeftSm"> Confirm Button Placeholder </span> </PanelFooter> </Panel> )); stories.add("Image Header Panel", () => ( <Panel mods="u-lg-size4of12 u-md-size8of12"> <PanelHeader headerImage={{ Source: "https://www.fillmurray.com/640/360", Placeholder: "https://www.fillmurray.com/640/360" }} title="Panel with Image Header" /> <PanelBody> <PanelRow> <p> Select different panel images to place in the space above. You may also adjust the size of the image too, to ensure it scales properly to the space. </p> </PanelRow> </PanelBody> <PanelFooter> <span className="Button Button--primary u-size1of1 u-textCenter"> Action Button Placeholder </span> </PanelFooter> </Panel> ));
// // RYVRPlayer.h // RYVRPlayer // // Created by Single on 2017/3/9. // Copyright © 2017年 single. All rights reserved. // #import <Foundation/Foundation.h> FOUNDATION_EXPORT double RYVRPlayerVersionNumber; FOUNDATION_EXPORT const unsigned char RYVRPlayerVersionString[]; // Platform #import "RYVRPlatform.h" // RYVRPlayer #import "RYVRPlayerImp.h" #import "RYVRPlayerTrack.h" #import "RYVRPlayerAction.h" #import "RYVRPlayerDecoder.h"
package App::DuckPAN::Config; BEGIN { $App::DuckPAN::Config::AUTHORITY = 'cpan:DDG'; } # ABSTRACT: Configuration class of the duckpan client $App::DuckPAN::Config::VERSION = '0.165'; use Moo; use File::HomeDir; use Path::Tiny; use Config::INI::Reader; use Config::INI::Writer; has config_path => ( is => 'ro', lazy => 1, default => sub { _path_for('config') }, ); has config_file => ( is => 'ro', lazy => 1, default => sub { shift->config_path->child('config.ini') }, ); has cache_path => ( is => 'ro', lazy => 1, default => sub { _path_for('cache') }, ); sub _path_for { my $which = shift; my $from_env = $ENV{'DUCKPAN_' . uc $which . '_PATH'}; my $path = ($from_env) ? path($from_env) : path(File::HomeDir->my_home, '.duckpan', lc $which); $path->mkpath unless $path->exists; return $path; } sub set_config { my ( $self, $config ) = @_; Config::INI::Writer->write_file($config,$self->config_file); } sub get_config { my ( $self ) = @_; return unless $self->config_file->is_file; Config::INI::Reader->read_file($self->config_file); } 1; __END__ =pod =head1 NAME App::DuckPAN::Config - Configuration class of the duckpan client =head1 VERSION version 0.165 =head1 AUTHOR Torsten Raudssus <[email protected]> L<https://raudss.us/> =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2013 by DuckDuckGo, Inc. L<https://duckduckgo.com/>. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. =cut
pub struct Window { pub raw: winit::window::Window, }
import 'dart:async'; import 'package:flutter/material.dart'; import 'package:json_class/json_class.dart'; import 'package:sitecore_flutter/sitecore_dynamic_widget.dart'; import 'package:sitecore_flutter/src/builders/sitecore_promo_container_builder.dart'; class SitecoreWidgetRegistry { /// Constructs a one-off registry. This accepts an optional group of custom /// widget [builders], custom widget [functions], and widget [values]. SitecoreWidgetRegistry({ Map<String, JsonClassBuilder<Object>>? builders, this.debugLabel, this.disableValidation = false, Map<String, dynamic>? values, }) { _customBuilders .addAll(builders as Map<String, SitecoreWidgetBuilderContainer>? ?? {}); _values.addAll(values ?? {}); } static final SitecoreWidgetRegistry instance = SitecoreWidgetRegistry( debugLabel: 'default', ); final _customBuilders = <String, SitecoreWidgetBuilderContainer>{}; final String? debugLabel; final bool disableValidation; final _values = <String?, dynamic>{}; final _internalBuilders = <String, SitecoreWidgetBuilderContainer>{ SitecoreHeroBannerBuilder.type: SitecoreWidgetBuilderContainer( builder: SitecoreHeroBannerBuilder.fromDynamic), SitecorePromoContainerBuilder.type: SitecoreWidgetBuilderContainer( builder: SitecorePromoContainerBuilder.fromDynamic), SitecorePromoCardBuilder.type: SitecoreWidgetBuilderContainer( builder: SitecorePromoCardBuilder.fromDynamic), SitecoreSectionHeaderBuilder.type: SitecoreWidgetBuilderContainer( builder: SitecoreSectionHeaderBuilder.fromDynamic), SitecoreFooterBuilder.type: SitecoreWidgetBuilderContainer( builder: SitecoreFooterBuilder.fromDynamic), }; final _internalValues = <String, dynamic>{}..addAll( CurvesValues.values, ); /// Returns an unmodifiable reference to the internal set of values. Map<String, dynamic> get values => Map.unmodifiable(_values); StreamController<String>? _valueStreamController = StreamController<String>.broadcast(); /// Returns the [Stream] that an element can listen to in order to be notified /// when Stream<String?> get valueStream => _valueStreamController!.stream; /// Removes all variable values from the registry void clearValues() { var keys = Set<String>.from(_values.keys); _values.clear(); keys.forEach((element) => _valueStreamController?.add(element)); } /// Disposes the registry. void dispose() { _valueStreamController?.close(); _valueStreamController = null; } /// Returns the variable value for the given [key].This will first check for /// a custom dynamic value using the [key], and if none is found, this will /// then check the internal values. If a variable with named [key] cannot be /// found, this will return [null]. dynamic getValue(String? key) => _values[key] ?? _internalValues[key!]; /// Returns the builder for the requested [type]. This will first search the /// registered custom builders, then if no builder is found, this will then /// search the library provided builders. /// /// If no builder is registered for the given [type] then this will throw an /// [Exception]. SitecoreWidgetBuilderBuilder getWidgetBuilder(String type) { var container = _customBuilders[type] ?? _internalBuilders[type]; if (container == null) { return PlaceholderBuilder.fromDynamic; } var builder = container.builder; return builder; } /// Processes any dynamic argument values from [args]. This will return a /// metadata object with the results as well as a collection of dynamic /// variable names that were encounted. DynamicParamsResult processDynamicArgs( dynamic args, { Set<String>? dynamicKeys, }) { dynamicKeys ??= <String>{}; dynamic result; if (args is String) { var parsed = SitecoreWidgetRegexHelper.parse(args); if (parsed?.isNotEmpty == true) { List<dynamic>? functionArgs; for (var item in parsed!) { if (item.isVariable == true) { if (item.isStatic != true) { dynamicKeys.add(item.key!); } var value = getValue(item.key); functionArgs?.add(value); result = value; } else { functionArgs?.add(item.key); result = item.key; } } } else { result = args; } } else if (args is Iterable) { result = []; for (var value in args) { result.add(processDynamicArgs( value, dynamicKeys: dynamicKeys, ).values); } } else if (args is Map) { result = {}; if (args['componentName'] != null && (args['placeholders'] != null || args['fields'] != null)) { // The entry has a "componentName" and one of: "placeholders", "fields". This // means the item is most like a SitecoreWidgetData class, so we should not // process the args yet. We should wait until the actual SitecoreWidgetData // gets built. result = args; } else { args.forEach((key, value) { result[key] = processDynamicArgs( value, dynamicKeys: dynamicKeys, ).values; }); } } else { result = args; } return DynamicParamsResult( dynamicKeys: dynamicKeys, values: result, ); } /// Registers the widget type with the registry to that [type] can be used in /// custom forms. Types registered by the application take precidence over /// built in registered builders. This allows an application the ability to /// provide custom widgets even for built in form types. /// /// If the [container] has an associated schema id then in DEBUG builds, that /// schema will be used to validate the attributes sent to the builder. void registerCustomBuilder( String type, SitecoreWidgetBuilderContainer container, ) => _customBuilders[type] = container; /// Registers the custom builders. This is a convenience method that calls /// [registerCustomBuilder] for each entry in [containers]. void registerCustomBuilders( Map<String, SitecoreWidgetBuilderContainer> containers, ) => containers.forEach((key, value) => registerCustomBuilder(key, value)); /// Removes the [key] from the registry. /// /// If, and only if, the [key] was registered on the registry will this fire /// an event on the [valueStream] with the [key] so listeners can be notified /// that the value has changed. dynamic removeValue(String key) { assert(key.isNotEmpty == true); var hasKey = _values.containsKey(key); var result = _values.remove(key); if (hasKey == true) { _valueStreamController?.add(key); } return result; } /// Sets the [value] for the [key] on the registry. If the [value] is [null], /// this redirects to [removeValue]. /// /// If the [value] is different than the current value for the [key] then this /// will fire an event on the [valueStream] with the [key] so listeners can be /// notified that it has changed. void setValue( String key, dynamic value, ) { assert(key.isNotEmpty == true); if (value == null) { removeValue(key); } else { var current = _values[key]; if (current != value) { _values[key] = value; _valueStreamController?.add(key); } } } @override String toString() => 'SitecoreWidgetRegistry{$debugLabel}'; /// Removes a registered [type] from the custom registry and returns the /// associated builder, if one exists. If the [type] is not registered then /// this will [null]. SitecoreWidgetBuilderContainer? unregisterCustomBuilder(String type) => _customBuilders.remove(type); }
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You 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. */ package producer import ( "context" "testing" "time" "github.com/golang/mock/gomock" "github.com/stretchr/testify/assert" "github.com/nj-leegern/rocketmq-client-go/internal" "github.com/nj-leegern/rocketmq-client-go/internal/remote" "github.com/nj-leegern/rocketmq-client-go/primitive" ) const ( topic = "TopicTest" ) func TestShutdown(t *testing.T) { p, _ := NewDefaultProducer( WithNameServer([]string{"127.0.0.1:9876"}), WithRetry(2), WithQueueSelector(NewManualQueueSelector()), ) ctrl := gomock.NewController(t) defer ctrl.Finish() client := internal.NewMockRMQClient(ctrl) p.client = client client.EXPECT().RegisterProducer(gomock.Any(), gomock.Any()).Return() client.EXPECT().Start().Return() err := p.Start() assert.Nil(t, err) client.EXPECT().Shutdown().Return() err = p.Shutdown() assert.Nil(t, err) ctx := context.Background() msg := new(primitive.Message) r, err := p.SendSync(ctx, msg) assert.Equal(t, ErrNotRunning, err) assert.Nil(t, r) err = p.SendOneWay(ctx, msg) assert.Equal(t, ErrNotRunning, err) f := func(context.Context, *primitive.SendResult, error) { assert.False(t, true, "should not come in") } err = p.SendAsync(ctx, f, msg) assert.Equal(t, ErrNotRunning, err) } func mockB4Send(p *defaultProducer) { p.publishInfo.Store(topic, &internal.TopicPublishInfo{ HaveTopicRouterInfo: true, MqList: []*primitive.MessageQueue{ { Topic: topic, BrokerName: "aa", QueueId: 0, }, }, }) p.options.Namesrv.AddBroker(&internal.TopicRouteData{ BrokerDataList: []*internal.BrokerData{ { Cluster: "cluster", BrokerName: "aa", BrokerAddresses: map[int64]string{ 0: "1", }, }, }, }) } func TestSync(t *testing.T) { p, _ := NewDefaultProducer( WithNameServer([]string{"127.0.0.1:9876"}), WithRetry(2), WithQueueSelector(NewManualQueueSelector()), ) ctrl := gomock.NewController(t) defer ctrl.Finish() client := internal.NewMockRMQClient(ctrl) p.client = client client.EXPECT().RegisterProducer(gomock.Any(), gomock.Any()).Return() client.EXPECT().Start().Return() err := p.Start() assert.Nil(t, err) ctx := context.Background() msg := &primitive.Message{ Topic: topic, Body: []byte("this is a message body"), Queue: &primitive.MessageQueue{ Topic: topic, BrokerName: "aa", QueueId: 0, }, } msg.WithProperty("key", "value") expectedResp := &primitive.SendResult{ Status: primitive.SendOK, MsgID: "111", QueueOffset: 0, OffsetMsgID: "0", } mockB4Send(p) client.EXPECT().InvokeSync(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, nil) client.EXPECT().ProcessSendResponse(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Do( func(brokerName string, cmd *remote.RemotingCommand, resp *primitive.SendResult, msgs ...*primitive.Message) { resp.Status = expectedResp.Status resp.MsgID = expectedResp.MsgID resp.QueueOffset = expectedResp.QueueOffset resp.OffsetMsgID = expectedResp.OffsetMsgID }) resp, err := p.SendSync(ctx, msg) assert.Nil(t, err) assert.Equal(t, expectedResp, resp) } func TestASync(t *testing.T) { p, _ := NewDefaultProducer( WithNameServer([]string{"127.0.0.1:9876"}), WithRetry(2), WithQueueSelector(NewManualQueueSelector()), ) ctrl := gomock.NewController(t) defer ctrl.Finish() client := internal.NewMockRMQClient(ctrl) p.client = client client.EXPECT().RegisterProducer(gomock.Any(), gomock.Any()).Return() client.EXPECT().Start().Return() err := p.Start() assert.Nil(t, err) ctx := context.Background() msg := &primitive.Message{ Topic: topic, Body: []byte("this is a message body"), Queue: &primitive.MessageQueue{ Topic: topic, BrokerName: "aa", QueueId: 0, }, } msg.WithProperty("key", "value") expectedResp := &primitive.SendResult{ Status: primitive.SendOK, MsgID: "111", QueueOffset: 0, OffsetMsgID: "0", } f := func(ctx context.Context, resp *primitive.SendResult, err error) { assert.Nil(t, err) assert.Equal(t, expectedResp, resp) } mockB4Send(p) client.EXPECT().InvokeAsync(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn( func(ctx context.Context, addr string, request *remote.RemotingCommand, timeoutMillis time.Duration, f func(*remote.RemotingCommand, error)) error { // mock invoke callback f(nil, nil) return nil }) client.EXPECT().ProcessSendResponse(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Do( func(brokerName string, cmd *remote.RemotingCommand, resp *primitive.SendResult, msgs ...*primitive.Message) { resp.Status = expectedResp.Status resp.MsgID = expectedResp.MsgID resp.QueueOffset = expectedResp.QueueOffset resp.OffsetMsgID = expectedResp.OffsetMsgID }) err = p.SendAsync(ctx, f, msg) assert.Nil(t, err) } func TestOneway(t *testing.T) { p, _ := NewDefaultProducer( WithNameServer([]string{"127.0.0.1:9876"}), WithRetry(2), WithQueueSelector(NewManualQueueSelector()), ) ctrl := gomock.NewController(t) defer ctrl.Finish() client := internal.NewMockRMQClient(ctrl) p.client = client client.EXPECT().RegisterProducer(gomock.Any(), gomock.Any()).Return() client.EXPECT().Start().Return() err := p.Start() assert.Nil(t, err) ctx := context.Background() msg := &primitive.Message{ Topic: topic, Body: []byte("this is a message body"), Queue: &primitive.MessageQueue{ Topic: topic, BrokerName: "aa", QueueId: 0, }, } msg.WithProperty("key", "value") mockB4Send(p) client.EXPECT().InvokeOneWay(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil).AnyTimes() err = p.SendOneWay(ctx, msg) assert.Nil(t, err) }
#!/bin/bash # Name: set_syncclient_teriminal # Usage: set_env, change_path, close_terminal, execute_sync_client # ./esyncclient -p ../etc/policies.json -t ../data/dm_tree/ function run_testcase(){ python /home/tiankang/Downloads/OtaSmoke/Execute/execute.py } run_testcase
module Physics.FunPart.Score ( -- * Types Score(..) , ScoreValue -- * Functions , updateAllByBatch ) where import Control.Lens import Data.List (foldl') import Physics.FunPart.Core import Physics.FunPart.Track import Physics.FunPart.Stat -- | A type synonim for more expressive function signatures. type ScoreValue = SVar FPFloat updateByTrackPoint :: Score -> TrackPoint -> Score updateByTrackPoint score@(CollFlux val) trackPoint = case trackPoint^.pointType of CollisionPoint xs _ -> CollFlux $ tally val (1.0/xs) _ -> score updateByTrackPoint _ _ = undefined updateByTrack :: Score -> Track -> Score updateByTrack (TrackLength val) track = TrackLength $ tally val len where len = fromIntegral . length $ track^.trackPoints -- | /Default implementation/: a fold over all the track points. updateByTrack score track = foldl' updateByTrackPoint score (_trackPoints track) -- | /Default implementation/: a fold over all the tracks. updateByBatch :: Score -> [Track] -> Score updateByBatch = foldl' updateByTrack -- | Helper function to map updateByBatch on a list of scores. updateAllByBatch :: [Score] -> [Track] -> [Score] updateAllByBatch scores tracks = map (`updateByBatch` tracks) scores -- | A union type for different scores. data Score = CollFlux ScoreValue -- ^ A collision-based flux score. | TrackLength ScoreValue -- ^ A track-length score. deriving (Show, Eq)
/* * Copyright (c) 2004-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include "RouteUpdater.h" #include <numeric> #include <boost/container/flat_map.hpp> #include <boost/container/flat_set.hpp> #include <boost/integer/common_factor.hpp> #include <folly/logging/xlog.h> #include "fboss/agent/FbossError.h" #include "fboss/agent/if/gen-cpp2/ctrl_types.h" #include "fboss/agent/state/NodeBase-defs.h" #include "fboss/agent/state/Route.h" #include <algorithm> #include "fboss/agent/Utils.h" using boost::container::flat_map; using boost::container::flat_set; using folly::CIDRNetwork; using folly::IPAddress; using folly::IPAddressV4; using folly::IPAddressV6; namespace facebook::fboss { static const RoutePrefixV6 kIPv6LinkLocalPrefix{ folly::IPAddressV6("fe80::"), 64}; static const auto kInterfaceRouteClientId = ClientID::INTERFACE_ROUTE; RibRouteUpdater::RibRouteUpdater( IPv4NetworkToRouteMap* v4Routes, IPv6NetworkToRouteMap* v6Routes) : v4Routes_(v4Routes), v6Routes_(v6Routes) {} void RibRouteUpdater::update( const std::map<ClientID, std::vector<RouteEntry>>& toAdd, const std::map<ClientID, std::vector<folly::CIDRNetwork>>& toDel, const std::set<ClientID>& resetClientsRoutesFor) { std::set<ClientID> clients; std::for_each(toAdd.begin(), toAdd.end(), [&clients](const auto& entry) { clients.insert(entry.first); }); std::for_each(toDel.begin(), toDel.end(), [&clients](const auto& entry) { clients.insert(entry.first); }); clients.insert(resetClientsRoutesFor.begin(), resetClientsRoutesFor.end()); for (auto client : clients) { auto addItr = toAdd.find(client); auto delItr = toDel.find(client); updateImpl( client, (addItr == toAdd.end() ? std::vector<RouteEntry>() : addItr->second), (delItr == toDel.end() ? std::vector<folly::CIDRNetwork>() : delItr->second), resetClientsRoutesFor.find(client) != resetClientsRoutesFor.end()); } updateDone(); } void RibRouteUpdater::updateImpl( ClientID client, const std::vector<RouteEntry>& toAdd, const std::vector<folly::CIDRNetwork>& toDel, bool resetClientsRoutes) { if (resetClientsRoutes) { removeAllRoutesForClient(client); } std::for_each( toAdd.begin(), toAdd.end(), [this, client](const auto& routeEntry) { addOrReplaceRoute( routeEntry.prefix.first, routeEntry.prefix.second, client, routeEntry.nhopEntry); }); std::for_each(toDel.begin(), toDel.end(), [this, client](const auto& prefix) { delRoute(prefix.first, prefix.second, client); }); } template <typename AddressT> void RibRouteUpdater::addOrReplaceRouteImpl( const Prefix<AddressT>& prefix, NetworkToRouteMap<AddressT>* routes, ClientID clientID, RouteNextHopEntry entry) { auto it = routes->exactMatch(prefix.network, prefix.mask); if (it != routes->end()) { auto route = it->value(); auto existingRouteForClient = route->getEntryForClient(clientID); if (!existingRouteForClient || !(*existingRouteForClient == entry)) { route = writableRoute<AddressT>(it); route->update(clientID, entry); } return; } routes->insert( prefix.network, prefix.mask, std::make_shared<Route<AddressT>>(prefix, clientID, entry)); } void RibRouteUpdater::addOrReplaceRoute( const folly::IPAddress& network, uint8_t mask, ClientID clientID, RouteNextHopEntry entry) { if (network.isV4()) { RoutePrefixV4 prefix{network.asV4().mask(mask), mask}; addOrReplaceRouteImpl(prefix, v4Routes_, clientID, std::move(entry)); } else { RoutePrefixV6 prefix{network.asV6().mask(mask), mask}; addOrReplaceRouteImpl(prefix, v6Routes_, clientID, std::move(entry)); } } template <typename AddressT> void RibRouteUpdater::delRouteImpl( const Prefix<AddressT>& prefix, NetworkToRouteMap<AddressT>* routes, ClientID clientID) { auto it = routes->exactMatch(prefix.network, prefix.mask); if (it == routes->end()) { XLOG(DBG3) << "Failed to delete route: " << prefix.str() << " does not exist"; return; } auto& route = it->value(); auto clientNhopEntry = route->getEntryForClient(clientID); if (!clientNhopEntry) { return; } if (route->numClientEntries() == 1) { // If this client's the only entry, simply erase XLOG(DBG3) << "Deleting route: " << route->str(); routes->erase(it); } else { route = writableRoute<AddressT>(it); route->delEntryForClient(clientID); XLOG(DBG3) << "Deleted next-hops for prefix " << prefix.str() << "from client " << folly::to<std::string>(clientID); } } void RibRouteUpdater::delRoute( const folly::IPAddress& network, uint8_t mask, ClientID clientID) { if (network.isV4()) { RoutePrefixV4 prefix{network.asV4().mask(mask), mask}; delRouteImpl(prefix, v4Routes_, clientID); } else { CHECK(network.isV6()); RoutePrefixV6 prefix{network.asV6().mask(mask), mask}; delRouteImpl(prefix, v6Routes_, clientID); } } template <typename AddressT> void RibRouteUpdater::removeAllRoutesFromClientImpl( NetworkToRouteMap<AddressT>* routes, ClientID clientID) { std::vector<typename NetworkToRouteMap<AddressT>::Iterator> toDelete; for (auto it = routes->begin(); it != routes->end(); ++it) { auto route = it->value(); auto nhopEntry = route->getEntryForClient(clientID); if (!nhopEntry) { continue; } if (route->numClientEntries() == 1) { // This client's is the only entry avoid unnecessary cloning // we are going to prune the route anyways toDelete.push_back(it); } else { route = writableRoute<AddressT>(it); route->delEntryForClient(clientID); if (route->hasNoEntry()) { // The nexthops we removed was the only one. Delete the route-> toDelete.push_back(it); } } } // Now, delete whatever routes went from 1 nexthoplist to 0. for (auto it : toDelete) { routes->erase(it); } } void RibRouteUpdater::removeAllRoutesForClient(ClientID clientID) { removeAllRoutesFromClientImpl<IPAddressV4>(v4Routes_, clientID); removeAllRoutesFromClientImpl<IPAddressV6>(v6Routes_, clientID); } // Some helper functions for recursive weight resolution // These aren't really usefully reusable, but structuring them // this way helps with clarifying their meaning. namespace { using NextHopForwardInfos = std::map<NextHop, RouteNextHopSet>; struct NextHopCombinedWeightsKey { explicit NextHopCombinedWeightsKey(NextHop nhop) : ip(nhop.addr()), intfId(nhop.intf()), // must be resolved next hop action(nhop.labelForwardingAction()) { /* "weightless" next hop, consider all attrs of L3 next hop except its * weight, this is used in computing number of required paths to next hop, * for correct programming of unequal cost multipath */ } bool operator<(const NextHopCombinedWeightsKey& other) const { return std::tie(ip, intfId, action) < std::tie(other.ip, other.intfId, other.action); } folly::IPAddress ip; InterfaceID intfId; std::optional<LabelForwardingAction> action; }; using NextHopCombinedWeights = boost::container::flat_map<NextHopCombinedWeightsKey, NextHopWeight>; NextHopWeight totalWeightsLcm(const NextHopForwardInfos& nhToFwds) { auto lcmAccumFn = [](NextHopWeight l, std::pair<NextHop, RouteNextHopSet> nhToFwd) -> NextHopWeight { auto t = totalWeight(nhToFwd.second); return boost::integer::lcm(l, t); }; return std::accumulate(nhToFwds.begin(), nhToFwds.end(), 1, lcmAccumFn); } bool hasEcmpNextHop(const NextHopForwardInfos& nhToFwds) { for (const auto& nhToFwd : nhToFwds) { if (nhToFwd.first.weight() == 0) { return true; } } return false; } /* * In the case that any next hop has weight 0, go through the next hop set * of each resolved next hop and bring its next hop set in with weight 0. */ template <typename AddressT> RouteNextHopSet mergeForwardInfosEcmp( const NextHopForwardInfos& nhToFwds, const std::shared_ptr<Route<AddressT>>& route) { RouteNextHopSet fwd; for (const auto& nhToFwd : nhToFwds) { const NextHop& nh = nhToFwd.first; const RouteNextHopSet& fw = nhToFwd.second; if (nh.weight()) { XLOG(WARNING) << "While resolving " << route->str() << " defaulting resolution of weighted next hop " << nh << " to ECMP because another next hop has weight 0"; } for (const auto& fnh : fw) { if (fnh.weight()) { XLOG(DBG4) << "While resolving " << route->str() << " defaulting weighted recursively resolved next hop " << fnh << " to ECMP because the next hop being resolved has weight 0: " << nh; } fwd.emplace(ResolvedNextHop( fnh.addr(), fnh.intf(), ECMP_WEIGHT, fnh.labelForwardingAction())); } } return fwd; } /* * for each recursively resolved next hop set, combine the next hops into * a map from (IP,InterfaceID)->weight, normalizing weights to the scale of * the LCM of the total weights of each resolved next hop set. The odd map * representation is needed to combine weights for different instances of * the same next hop coming from different recursively resolved next hop sets. */ template <typename AddressT> NextHopCombinedWeights combineWeights( const NextHopForwardInfos& nhToFwds, const std::shared_ptr<Route<AddressT>>& route) { NextHopCombinedWeights cws; NextHopWeight l = totalWeightsLcm(nhToFwds); for (const auto& nhToFwd : nhToFwds) { const NextHop& unh = nhToFwd.first; const RouteNextHopSet& fw = nhToFwd.second; if (fw.empty()) { continue; } NextHopWeight normalization; NextHopWeight t = totalWeight(fw); // If total weight of any resolved next hop set is 0, the LCM will // also be 0. This represents the case where one of the recursively // resolved routes has ECMP next hops. In this case, we want the // ECMP behavior to "propagate up" to this route, so lcm and thus // the normalizationg factor being 0 is desirable. // We need to check t for 0 for precisely the ecmp // recursively resolved next hop sets to not do 0/0. normalization = t ? l / t : 0; bool loggedEcmpDefault = false; for (const auto& fnh : fw) { NextHopWeight w = fnh.weight() * normalization * unh.weight(); // We only want to log this once per recursively resolved next hop // to prevent a large ecmp group from spamming pointless logs if (!loggedEcmpDefault && !w && unh.weight()) { XLOG(WARNING) << "While resolving " << route->str() << " defaulting resolution of weighted next hop " << unh << " to ECMP because another next hop in the resolution" << " tree uses ECMP."; loggedEcmpDefault = true; } cws[NextHopCombinedWeightsKey(fnh)] += w; } } return cws; } /* * Given a map from (IP,InterfaceID)->weight, take the gcd of the weights * and return a next hop set with IP, intf, weight/GCD to minimize the weights */ RouteNextHopSet optimizeWeights(const NextHopCombinedWeights& cws) { RouteNextHopSet fwd; auto gcdAccumFn = [](NextHopWeight g, const std::pair<NextHopCombinedWeightsKey, NextHopWeight>& cw) { NextHopWeight w = cw.second; return (g ? boost::integer::gcd(g, w) : w); }; auto fwdWeightGcd = std::accumulate(cws.begin(), cws.end(), 0, gcdAccumFn); for (const auto& cw : cws) { const folly::IPAddress& addr = cw.first.ip; const InterfaceID& intf = cw.first.intfId; const auto& action = cw.first.action; NextHopWeight w = fwdWeightGcd ? cw.second / fwdWeightGcd : 0; fwd.emplace(ResolvedNextHop(addr, intf, w, action)); } return fwd; } /* * Take the resolved forwarding info (NextHopSet containing ResolvedNextHops) * from each recursively resolved next hop and merge them together. * * There are two cases: * 1) Any of the weights of the current routes next hops are 0. * This represents a mix of ECMP and UCMP next hops. In this case, * we default to just ECMP-ing everything from all the next hops. * 2) This route's next hops all have weight. In this case, we run through * algorithm to normalize all the weights for the next hops resolved for * each next hop (combineWeights) then minimize the weights * (optimizeWeights). Both of these algorithms will preserve the critical * ratio w_i/w_j for any two weights w_i, w_j of next hops i, j in both * the current route's weights and in the recursively resolved route's * weights. * * NOTE: case 1) will propagate recursively, so in effect, any ECMP next hop * anywhere in the resolution tree for a route will result in the entire * tree ultimately being treated as an ECMP route. * * An example to illustrate the requirement: * We will represent the recursive route resolution tree for three routes * R1, R2, and R3. Numbers on the edges represent weights for next hops, * and I1, I2, I3, and I4 are connected interfaces. * * R1 * 3/ 2\ * R2 R3 * 5/ 4\ 3/ 2\ * I1 I2 I3 I4 * * In resolving R1, resolveOne and getFwdInfoFromNhop will mutually recursively * get to a point where we have resolved R2 and R3 to having next hops I1 with * weight 5, I2 with weight 4, and I3 with weight 3 and I4 with weight 2 * respectively: {R2x3:{I1x5, I2x4}, R3x2:{I3x2, I4x2}} * We need to preserve the following ratios in the final result: * I1/I2=5/4; I3/I4=3/2; (I1+I2)/(I3+I4)=3/2 * To do this, we normalize the weights by finding the LCM of the total * weights of the recursively resolved next hop sets: * LCM(9, 5) = 45, then bring in each next hop into the final next hop * set with its weight multiplied by LCM/TotalWeight(its next hop) * and by the weight of its top level next hop: * I1: 5*(45/9)*3=75, I2: 4*(45/9)*3=60, I3: 3*(45/5)*2=54, I4: 2*(45/5)*2=36 * I1/I2=75/60=5/4, I3/I4=54/36=3/2, (I1+I2)/(I3+I4)=135/90=3/2 * as required. Finally, we can find the gcds of top level weights to minimize * these weights: * GCD(75, 60, 54, 36) = 3 so we reach a final next hop set of: * {I1x25, I2x20, I3x18, I4x12} */ template <typename AddressT> RouteNextHopSet mergeForwardInfos( const NextHopForwardInfos& nhToFwds, const std::shared_ptr<Route<AddressT>>& route) { RouteNextHopSet fwd; if (hasEcmpNextHop(nhToFwds)) { fwd = mergeForwardInfosEcmp(nhToFwds, route); } else { NextHopCombinedWeights cws = combineWeights(nhToFwds, route); fwd = optimizeWeights(cws); } return fwd; } } // anonymous namespace template <typename AddressT> void RibRouteUpdater::getFwdInfoFromNhop( NetworkToRouteMap<AddressT>* routes, const AddressT& nh, const std::optional<LabelForwardingAction>& labelAction, bool* hasToCpu, bool* hasDrop, RouteNextHopSet& fwd) { auto it = routes->longestMatch(nh, nh.bitCount()); if (it == routes->end()) { XLOG(DBG3) << "Could not find subnet for next-hop: " << nh; // Unresolvable next hop return; } auto route = it->value(); CHECK(route); if (needResolve(route)) { route = resolveOne<AddressT>(it); CHECK(route); } if (route->isResolved()) { const auto& fwdInfo = route->getForwardInfo(); if (fwdInfo.isDrop()) { *hasDrop = true; } else if (fwdInfo.isToCPU()) { *hasToCpu = true; } else { const auto& nhops = fwdInfo.getNextHopSet(); // if the route used to resolve the nexthop is directly connected if (route->isConnected()) { const auto& rtNh = *nhops.begin(); // NOTE: we need to use a UCMP compatible weight so that this can // be a leaf in the recursive resolution defined in the comment // describing mergeForwardInfos above. fwd.emplace(ResolvedNextHop( nh, rtNh.intf(), UCMP_DEFAULT_WEIGHT, LabelForwardingAction::combinePushLabelStack( labelAction, rtNh.labelForwardingAction()))); } else { std::for_each( nhops.begin(), nhops.end(), [&fwd, labelAction](const auto& nhop) { fwd.insert(ResolvedNextHop( nhop.addr(), nhop.intf(), nhop.weight(), LabelForwardingAction::combinePushLabelStack( labelAction, nhop.labelForwardingAction()))); }); } } } } template <typename AddressT> std::shared_ptr<Route<AddressT>> RibRouteUpdater::resolveOne( typename NetworkToRouteMap<AddressT>::Iterator ritr) { auto& route = ritr->value(); // Starting resolution for this route, remove from resolution queue needsResolution_.erase(route.get()); bool hasToCpu{false}; bool hasDrop{false}; RouteNextHopSet* fwd{nullptr}; auto bestPair = route->getBestEntry(); const auto clientId = bestPair.first; const auto bestEntry = bestPair.second; const auto action = bestEntry->getAction(); if (action == RouteForwardAction::DROP) { hasDrop = true; } else if (action == RouteForwardAction::TO_CPU) { hasToCpu = true; } else { auto fwItr = unresolvedToResolvedNhops_.find(bestEntry->getNextHopSet()); if (fwItr == unresolvedToResolvedNhops_.end()) { NextHopForwardInfos nhToFwds; // loop through all nexthops to find out the forward info for (const auto& nh : bestEntry->getNextHopSet()) { const auto& addr = nh.addr(); // There are two reasons why InterfaceID is specified in the next hop. // 1) The nexthop was generated for interface route. // In this case, the clientId is INTERFACE_ROUTE // 2) The nexthop was for v6 link-local address. // In both cases, this nexthop is resolved. if (nh.intfID().has_value()) { // It is either an interface route or v6 link-local CHECK( clientId == kInterfaceRouteClientId or (addr.isV6() and addr.isLinkLocal())); nhToFwds[nh].emplace(nh); continue; } if (addr.isV4()) { getFwdInfoFromNhop( v4Routes_, nh.addr().asV4(), nh.labelForwardingAction(), &hasToCpu, &hasDrop, nhToFwds[nh]); } else { CHECK(addr.isV6()); getFwdInfoFromNhop( v6Routes_, nh.addr().asV6(), nh.labelForwardingAction(), &hasToCpu, &hasDrop, nhToFwds[nh]); } } fwItr = unresolvedToResolvedNhops_ .insert( {bestEntry->getNextHopSet(), mergeForwardInfos(nhToFwds, route)}) .first; } fwd = &(fwItr->second); } std::shared_ptr<Route<AddressT>> updatedRoute; auto updateRoute = [this, clientId, &updatedRoute]( typename NetworkToRouteMap<AddressT>::Iterator ritr, std::optional<RouteNextHopEntry> nhop) { updatedRoute = writableRoute<AddressT>(ritr); if (nhop) { updatedRoute->setResolved(*nhop); if (clientId == kInterfaceRouteClientId && !nhop->getNextHopSet().empty()) { updatedRoute->setConnected(); } } else { updatedRoute->setUnresolvable(); } updatedRoute->publish(); XLOG(DBG3) << (updatedRoute->isResolved() ? "Resolved" : "Cannot resolve") << " route " << updatedRoute->str(); }; if (fwd && !fwd->empty()) { if (route->getForwardInfo().getNextHopSet() != *fwd) { updateRoute( ritr, RouteNextHopEntry(*fwd, AdminDistance::MAX_ADMIN_DISTANCE)); } } else if (hasToCpu) { if (!route->isToCPU()) { updateRoute( ritr, RouteNextHopEntry( RouteForwardAction::TO_CPU, AdminDistance::MAX_ADMIN_DISTANCE)); } } else if (hasDrop) { if (!route->isDrop()) { updateRoute( ritr, RouteNextHopEntry( RouteForwardAction::DROP, AdminDistance::MAX_ADMIN_DISTANCE)); } } else { updateRoute(ritr, std::nullopt); } if (!updatedRoute) { route->publish(); XLOG(DBG3) << " Retained resolution :" << (route->isResolved() ? "Resolved" : "Cannot resolve") << " route " << route->str(); } return updatedRoute ? updatedRoute : route; } template <typename AddressT> std::shared_ptr<Route<AddressT>> RibRouteUpdater::writableRoute( typename NetworkToRouteMap<AddressT>::Iterator ritr) { if (ritr->value()->isPublished()) { ritr->value() = ritr->value()->clone(); } return ritr->value(); } template <typename AddressT> void RibRouteUpdater::resolve(NetworkToRouteMap<AddressT>* routes) { for (auto ritr = routes->begin(); ritr != routes->end(); ++ritr) { if (needResolve(ritr->value())) { resolveOne<AddressT>(ritr); } } } template <typename AddressT> bool RibRouteUpdater::needResolve( const std::shared_ptr<Route<AddressT>>& route) const { return needsResolution_.find(route.get()) != needsResolution_.end(); } void RibRouteUpdater::updateDone() { // Record all routes as needing resolution auto markForResolution = [this](const auto& routes) { std::for_each(routes->begin(), routes->end(), [this](const auto& route) { needsResolution_.insert(route.value().get()); }); }; markForResolution(v4Routes_); markForResolution(v6Routes_); SCOPE_EXIT { needsResolution_.clear(); unresolvedToResolvedNhops_.clear(); }; resolve(v4Routes_); resolve(v6Routes_); } } // namespace facebook::fboss
<?php namespace App\Http\Controllers\Frontend; use App\Http\Controllers\Controller; use App\Models\Frontend\CartModel; use App\Models\Backend\OrderDetailModel; use App\Models\Backend\OrderModel; use App\Models\Backend\ProductsModel; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; use PHPUnit\Util\Json; class CartController extends Controller { // thử xem có lên không public function shareKey() { $cart = new CartModel(); $totalQttCart = $cart->getTotalQuantity(); $totalPriceCart = $cart->getTotalPrice(); view()->share('totalQttCart', $totalQttCart); view()->share('totalPriceCart', $totalPriceCart); } public function index(){ $this->shareKey(); $data = []; $cart = new CartModel(); $data["cart"] = $cart->getItems(); $cartIds = []; foreach($data["cart"] as $id => $valCart) { $cartIds[] = $id; } $products = DB::table("products")->whereIn("id", $cartIds)->get(); $data["products"] = $products; return view("frontend.cart", $data); } public function payment(){ $this->shareKey(); $cart = new CartModel(); $data['cart'] = $cart->getItems(); $cartIds = []; foreach ($data['cart'] as $id=>$valCart){ $cartIds[] = $id; } $products = DB::table("products")->whereIn("id",$cartIds)->get(); $data["products"] = $products; return view("frontend.payment", $data); } public function checkout(Request $request){ $this->shareKey(); $validatedData = $request->validate([ 'customer_name' => 'required', 'customer_email' => 'required', 'customer_phone' => 'required', 'customer_address' => 'required', 'order_note' => 'required', ]); // lấy thông tin khách hàng $customer_name = $request->get("customer_name", ""); $customer_address = $request->get("customer_address", ""); $customer_phone = $request->get("customer_phone", ""); $customer_email = $request->get("customer_email", ""); $order_note = $request->get("order_note", ""); // lây ra thông tin từ giỏ hàng $cart = new CartModel(); $data["cart"] = $cart->getItems(); // insert đơn hàng $order = new OrderModel(); $order->customer_name = $customer_name; $order->customer_email = $customer_email; $order->customer_phone = $customer_phone; $order->customer_address = $customer_address; $order->order_status = 1; $order->order_note = $order_note; foreach ($data["cart"] as $id =>$valCart ){ $cartIds[] = $id; $quantity = $valCart[0]['quantity']; $product = ProductsModel::find($id); $totalPriceProduct = $quantity* $product->product_price; $order->total_product += $quantity; $order->total_price +=$totalPriceProduct; } $order->save(); // thêm chi tiết đơn hàng foreach($data["cart"] as $id => $valCart) { $quantity = $valCart[0]['quantity']; $product = ProductsModel::find($id); $orderDetail = new OrderDetailModel(); $orderDetail->product_id = $id; $orderDetail->product_price = $product->product_price; $orderDetail->quantity = $quantity; $orderDetail->order_id = $order->id; $orderDetail->order_status = 1; $orderDetail->save(); } $cart->clearCart(); return redirect("/aftercheckout")->with('status',"Thêm vào đơn hàng thành công "); } public function add(Request $request) { $this->shareKey(); $cart = new CartModel(); $id = $request->get("id", 0); $quantity = $request->get("quantity", 1); $attributes = $request->get("attributes", []); $cart->addCart($id, $quantity, $attributes); // response json $msg = ["text" => "thêm sản phẩm thành công"]; return response()->json($msg, 200); } public function update(Request $request){ $this->shareKey(); $cart = new CartModel(); $id = $request->get("id",0); $quantity = $request->get('quantity', 1); $attributes = $request->get("attributes", []); $cart ->updateCart($id,$quantity,$attributes); $msg= ['text' => "Cập nhật giỏ hàng thành công"]; return response()->json($msg,200); } public function remove(Request $request){ $this->shareKey(); $cart = new CartModel(); $id = $request->get("id", 0 ); $attributes= $request->get("attributes", []); $cart->removeCart($id, $attributes); //response json $msg= ["text" => "Xóa sản phẩm thành công"]; return response()->json($msg,200); } public function clear(){ $this->shareKey(); $cart = new CartModel(); $cart ->clearCart(); $msg = ['text' => "xÓA GIỎ HÀNG THÀNH CÔNG"]; return response()->json($msg,200); } public function aftercheckout(){ $this->shareKey(); return view("frontend.aftercheckout"); } } ?>
//! Handler perform that Async task mod challenge; mod ideas; mod tags; mod users;
class ApplicationError extends Error { constructor(errors, httpCode, message) { super((message || 'Error')); this.httpCode = httpCode || 422; this.errors = errors; } } module.exports = ApplicationError;
require 'cancan' require 'state_machine' module Pageflow class ApplicationController < ActionController::Base layout 'pageflow/application' before_filter do I18n.locale = current_user.try(:locale) || locale_from_accept_language_header || I18n.default_locale end # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception include EditLocking rescue_from ActionController::UnknownFormat do |exception| debug_log_with_backtrace(exception) render(status: 404, text: 'Not found') end rescue_from ActiveRecord::RecordNotFound do |exception| debug_log_with_backtrace(exception) respond_to do |format| format.html do begin render file: Rails.public_path.join('pageflow', 'error_pages', '404.html'), status: :not_found rescue ActionView::MissingTemplate => exception debug_log_with_backtrace(exception) head :not_found end end format.any { head :not_found } end end rescue_from CanCan::AccessDenied do |exception| debug_log_with_backtrace(exception) respond_to do |format| format.html { redirect_to main_app.admin_root_path, :alert => t('pageflow.unauthorized') } format.any(:json, :css) { head :forbidden } end end rescue_from StateMachine::InvalidTransition do |exception| debug_log_with_backtrace(exception) respond_to do |format| format.html { redirect_to main_app.admin_root_path, :alert => t('pageflow.invalid_transition') } format.json { head :bad_request } end end protected def current_ability @current_ability ||= Ability.new(current_user) end def after_sign_in_path_for(resource_or_scope) root_url(:protocol => 'http') end def after_sign_out_path_for(resource_or_scope) root_url(:protocol => 'http') end def locale_from_accept_language_header http_accept_language.compatible_language_from(I18n.available_locales) end def debug_log_with_backtrace(exception) Rails.logger.debug exception backtrace = '' exception.backtrace.each do |line| backtrace << line end Rails.logger.debug backtrace end end end
import mxnet as mx from mxnet import autograd from mxnet import profiler #################### Set Profiler Config ###################### profiler.set_config(profile_all=True, aggregate_stats=True, filename='cpu_mnist_cnn_profile_output.json') ############################################################### # Build Network from mxnet import gluon net = gluon.nn.HybridSequential() with net.name_scope(): net.add(gluon.nn.Conv2D(channels=20, kernel_size=5, activation='relu')) net.add(gluon.nn.MaxPool2D(pool_size=2, strides=2)) net.add(gluon.nn.Conv2D(channels=50, kernel_size=5, activation='relu')) net.add(gluon.nn.MaxPool2D(pool_size=2, strides=2)) net.add(gluon.nn.Flatten()) net.add(gluon.nn.Dense(512, activation="relu")) net.add(gluon.nn.Dense(10)) from mxnet.gluon.data.vision import transforms train_data = gluon.data.DataLoader(gluon.data.vision.MNIST(train=True).transform_first(transforms.ToTensor()), batch_size=64, shuffle=True) # Set Context ctx = mx.cpu() # Initialize the parameters with random weights net.collect_params().initialize(mx.init.Xavier(), ctx=ctx) # Use SGD optimizer trainer = gluon.Trainer(net.collect_params(), 'sgd', {'learning_rate': .1}) # Softmax Cross Entropy is a frequently used loss function for multi-classs classification softmax_cross_entropy = gluon.loss.SoftmaxCrossEntropyLoss() # A helper function to run one training iteration def run_training_iteration(data, label): # Load data and label is the right context data = data.as_in_context(ctx) label = label.as_in_context(ctx) # Run the forward pass with autograd.record(): output = net(data) loss = softmax_cross_entropy(output, label) # Run the backward pass loss.backward() # Apply changes to parameters trainer.step(data.shape[0]) # Ignore first run because MXNet does some house keeping itr = iter(train_data) run_training_iteration(*next(itr)) ##################### Profiler 1 batch run ######################## data, label = next(itr) # Ask the profiler to start recording profiler.set_state('run') run_training_iteration(*next(itr)) # Ask the profiler to stop recording after operations have completed mx.nd.waitall() profiler.set_state('stop') ################################################################### #################### Dump output on Console ####################### print(profiler.dumps()) ################################################################### #################### Dump output to JSON ########################## profiler.dump() ###################################################################
import React from "react"; const Nav = () => ( <nav> <h1>TAILWIND TRADERS APP</h1> </nav> ); export default Nav;
[ActiveSupport PAR] ; Global primary clocks GLOBAL_PRIMARY_USED = 1; ; Global primary clock #0 GLOBAL_PRIMARY_0_SIGNALNAME = out_vga_ck_c; GLOBAL_PRIMARY_0_DRIVERTYPE = PLL; GLOBAL_PRIMARY_0_LOADNUM = 152; ; # of global secondary clocks GLOBAL_SECONDARY_USED = 4; ; Global secondary clock #0 GLOBAL_SECONDARY_0_SIGNALNAME = u_vga_core/out_vga_ck_c_enable_53; GLOBAL_SECONDARY_0_DRIVERTYPE = SLICE; GLOBAL_SECONDARY_0_LOADNUM = 28; GLOBAL_SECONDARY_0_SIGTYPE = CE+RST; ; Global secondary clock #1 GLOBAL_SECONDARY_1_SIGNALNAME = mode_bit; GLOBAL_SECONDARY_1_DRIVERTYPE = SLICE; GLOBAL_SECONDARY_1_LOADNUM = 87; GLOBAL_SECONDARY_1_SIGTYPE = CE+RST; ; Global secondary clock #2 GLOBAL_SECONDARY_2_SIGNALNAME = u_vga_core/u0_vid_new_frame; GLOBAL_SECONDARY_2_DRIVERTYPE = SLICE; GLOBAL_SECONDARY_2_LOADNUM = 21; GLOBAL_SECONDARY_2_SIGTYPE = CE+RST; ; Global secondary clock #3 GLOBAL_SECONDARY_3_SIGNALNAME = u_vga_core/u0_vga_timing/h_rollover; GLOBAL_SECONDARY_3_DRIVERTYPE = SLICE; GLOBAL_SECONDARY_3_LOADNUM = 12; GLOBAL_SECONDARY_3_SIGTYPE = CE; ; I/O Bank 0 Usage BANK_0_USED = 8; BANK_0_AVAIL = 51; BANK_0_VCCIO = 3.3V; BANK_0_VREF1 = NA; ; I/O Bank 1 Usage BANK_1_USED = 8; BANK_1_AVAIL = 52; BANK_1_VCCIO = 3.3V; BANK_1_VREF1 = NA; ; I/O Bank 2 Usage BANK_2_USED = 0; BANK_2_AVAIL = 52; BANK_2_VCCIO = NA; BANK_2_VREF1 = NA; ; I/O Bank 3 Usage BANK_3_USED = 0; BANK_3_AVAIL = 16; BANK_3_VCCIO = NA; BANK_3_VREF1 = NA; ; I/O Bank 4 Usage BANK_4_USED = 0; BANK_4_AVAIL = 16; BANK_4_VCCIO = NA; BANK_4_VREF1 = NA; ; I/O Bank 5 Usage BANK_5_USED = 0; BANK_5_AVAIL = 20; BANK_5_VCCIO = NA; BANK_5_VREF1 = NA;
import store from '../store'; import { checkLocalStorageAvailability } from '../utils'; import { BASE_URL, ENDPOINTS } from '../constants/api'; import setAuth from '../actions/setAuth'; import unsetAuth from '../actions/unsetAuth'; const isLocalStorageAvailable = checkLocalStorageAvailability(); export const authenticate = async (username, password) => { const options = { method: 'post', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username, password }), json: true }; const response = await window.fetch(`${BASE_URL}${ENDPOINTS.JWT}`, options); const auth = await response.json(); if (!response.ok) { forgetAuth(); return { token: null, message: auth.message }; } rememberAuth(auth); return auth; }; export const recallAuth = () => (isLocalStorageAvailable ? JSON.parse(window.localStorage.getItem('auth')) : null); export const validateToken = async token => { if (!token) return false; const options = { method: 'post', headers: { Authorization: `Bearer ${token}` }, json: true }; const response = await window.fetch(`${BASE_URL}${ENDPOINTS.JWT_VALIDATION}`, options); if (!response.ok) { forgetAuth(); return false; } const auth = await response.json(); return auth.code === 'jwt_auth_valid_token'; }; export const rememberAuth = auth => { if (isLocalStorageAvailable) { try { window.localStorage.setItem('auth', JSON.stringify(auth)); } catch {} } const action = setAuth(auth); store.dispatch(action); }; export const forgetAuth = () => { if (isLocalStorageAvailable) { window.localStorage.removeItem('auth'); } const action = unsetAuth(); store.dispatch(action); };
package com.letv.android.client.view; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface.OnClickListener; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup.LayoutParams; import android.widget.Button; import android.widget.TextView; import com.letv.android.client.R; import com.letv.hackdex.VerifyLoad; import com.letv.hotfixlib.HotFix; public class FeedbackDialog extends Dialog { public static class Builder { private View mContentView; private Context mContext; private String mMessage; private String mNegativeButton; private OnClickListener mNegativeListener; public Builder(Context context) { if (HotFix.PREVENT_VERIFY) { System.out.println(VerifyLoad.class); } this.mContext = context; } public Builder setmMessage(String mMessage) { this.mMessage = mMessage; return this; } public Builder setButton(String button) { this.mNegativeButton = button; return this; } public Builder setContentView(View v) { this.mContentView = v; return this; } public Builder setmNegativeButton(String button_content, OnClickListener listener) { this.mNegativeButton = button_content; this.mNegativeListener = listener; return this; } public FeedbackDialog create() { LayoutInflater inflater = (LayoutInflater) this.mContext.getSystemService("layout_inflater"); FeedbackDialog feedbackDialog = new FeedbackDialog(this.mContext, R.style.feedback_dialog); View layout = inflater.inflate(R.layout.custom_feedback_dialog, null); feedbackDialog.addContentView(layout, new LayoutParams(-2, -2)); ((TextView) layout.findViewById(2131362362)).setText(this.mMessage); ((Button) layout.findViewById(2131362363)).setText(this.mNegativeButton); layout.findViewById(2131362363).setOnClickListener(new 1(this, feedbackDialog)); return feedbackDialog; } } public FeedbackDialog(Context context) { if (HotFix.PREVENT_VERIFY) { System.out.println(VerifyLoad.class); } super(context); } public FeedbackDialog(Context context, int theme) { super(context, theme); } }
package dev.floffah.gamermode.server.packet; public enum PacketType { /** * Packet type representing any packet that may be sent to the server. */ SERVERBOUND, /** * Packet type representing any packet that may be sent to the player. */ CLIENTBOUND, /** * Edge case packet type representing any packet that is ambiguous. */ UNKNOWN, }
sap.ui.require([ "sap/ui/test/Opa5", "sap/ui/demo/todo/test/integration/pages/Common", "sap/ui/test/matchers/AggregationLengthEquals", "sap/ui/test/matchers/PropertyStrictEquals", "sap/ui/test/matchers/Properties", "sap/ui/test/matchers/LabelFor", "sap/ui/test/actions/EnterText", "sap/ui/test/actions/Press" ], function (Opa5, Common, AggregationLengthEquals, PropertyStrictEquals, Properties, LabelFor, EnterText, Press) { "use strict"; var sViewName = "sap.ui.demo.todo.view.App"; var sProductFormAddButton = "productFormAddButton"; var sSearchTodoItemsInputId = "searchProductsInput"; var sItemListId = "productList"; var sClearUnavailableId = "clearUnavailable"; var sItemsLeftLabelId = "totalValueLabel"; Opa5.createPageObjects({ onTheAppPage: { baseClass: Common, actions: { iEnterTextForNewProductAndPressEnter: function(name, quantity, price, unavailable) { return this.waitFor({ viewName: sViewName, controlType: "sap.m.Input", matchers: new LabelFor({ text: "Name" }), actions: new EnterText({text: name}), errorMessage: "Failed to fulfill Name input" }).waitFor({ viewName: sViewName, controlType: "sap.m.Input", matchers: new LabelFor({ text: "Quantity" }), actions: new EnterText({text: quantity}), errorMessage: "Failed to fulfill Quantity input" }).waitFor({ viewName: sViewName, controlType: "sap.m.Input", matchers: new LabelFor({ text: "Price" }), actions: new EnterText({text: price}), errorMessage: "Failed to fulfill Price input" }).waitFor({ viewName: sViewName, controlType: "sap.m.CheckBox", matchers: new LabelFor({ text: "Unavialable" }), actions: unavailable ? new Press() : [], errorMessage: "Failed to fulfill Unavialable checkbox" }).waitFor({ id: sProductFormAddButton, viewName: sViewName, controlType: "sap.m.Button", actions: new Press(), errorMessage: "Form add button can not be pressed" }); }, iEnterTextForSearchAndPressEnter: function(text) { return this.waitFor({ id: sSearchTodoItemsInputId, viewName: sViewName, actions: [new EnterText({ text: text })], errorMessage: "The text cannot be entered" }); }, iSelectTheLastItem: function(bSelected) { return this.waitFor({ id: sItemListId, viewName: sViewName, // selectionChange actions: [function(oList) { var iLength = oList.getItems().length; var oListItem = oList.getItems()[iLength - 1]; this._triggerCheckboxSelection(oListItem, bSelected); }.bind(this)], errorMessage: "Last checkbox cannot be pressed" }); }, iSelectAllItems: function(bSelected) { return this.waitFor({ id: sItemListId, viewName: sViewName, actions: [function(oList) { oList.getItems().forEach(function(oListItem) { this._triggerCheckboxSelection(oListItem, bSelected) }.bind(this)); }.bind(this)], errorMessage: "checkbox cannot be pressed" }); }, _triggerCheckboxSelection: function(oListItem, bSelected) { //determine existing selection state and ensure that it becomes <code>bSelected</code> if (oListItem.getSelected() && !bSelected || !oListItem.getSelected() && bSelected) { var oPress = new Press(); //search within the ColumnListItem for the checkbox id ending with 'selectMulti-CB' oPress.controlAdapters["sap.m.ColumnListItem"] = "selectMulti-CB"; oPress.executeOn(oListItem); } }, iClearTheUnavailableItems: function() { return this.waitFor({ id: sClearUnavailableId, viewName: sViewName, actions: [new Press()], errorMessage: "checkbox cannot be pressed" }); }, iFilterForItems: function(filterKey) { return this.waitFor({ viewName: sViewName, controlType: "sap.m.SegmentedButtonItem", matchers: [ new Properties({ key: filterKey }) ], actions: [new Press()], errorMessage: "SegmentedButton can not be pressed" }); } }, assertions: { iShouldSeeTheItemBeingAdded: function(iItemCount, sLastAddedText) { return this.waitFor({ id: sItemListId, viewName: sViewName, matchers: [new AggregationLengthEquals({ name: "items", length: iItemCount }), function(oControl) { var iLength = oControl.getItems().length; var oInput = oControl.getItems()[iLength - 1].getCells()[0]; return new PropertyStrictEquals({ name: "value", value: sLastAddedText }).isMatching(oInput); }], success: function() { Opa5.assert.ok(true, "The table has " + iItemCount + " item(s), with '" + sLastAddedText + "' as last item"); }, errorMessage: "List does not have expected entry '" + sLastAddedText + "'." }); }, iShouldSeeTheLastItemBeingUnavailable: function(bSelected) { return this.waitFor({ id: sItemListId, viewName: sViewName, matchers: [function(oControl) { var iLength = oControl.getItems().length; var oInput = oControl.getItems()[iLength - 1].getCells()[0]; return bSelected && !oInput.getEnabled() || !bSelected && oInput.getEnabled(); }], success: function() { Opa5.assert.ok(true, "The last item is marked as completed"); }, errorMessage: "The last item is not disabled." }); }, iShouldSeeAllButOneItemBeingRemoved: function(sLastItemText) { return this.waitFor({ id: sItemListId, viewName: sViewName, matchers: [new AggregationLengthEquals({ name: "items", length: 1 }), function(oControl) { var oInput = oControl.getItems()[0].getCells()[0]; return new PropertyStrictEquals({ name: "value", value: sLastItemText }).isMatching(oInput); }], success: function() { Opa5.assert.ok(true, "The table has 1 item, with '" + sLastItemText + "' as Last item"); }, errorMessage: "List does not have expected entry '" + sLastItemText + "'." }); }, iShouldSeeTotalValuePrice: function(iTotalValuePrice) { return this.waitFor({ id: sItemsLeftLabelId, viewName: sViewName, matchers: [new PropertyStrictEquals({ name: "text", value: "Total available price value: " + iTotalValuePrice + " EUR" }) ], success: function() { Opa5.assert.ok(true, "" + iTotalValuePrice + " total value"); }, errorMessage: "Items are not selected." }); }, iShouldSeeItemCount: function(iItemCount) { return this.waitFor({ id: sItemListId, viewName: sViewName, matchers: [new AggregationLengthEquals({ name: "items", length: iItemCount })], success: function() { Opa5.assert.ok(true, "The table has " + iItemCount + " item(s)"); }, errorMessage: "List does not have expected number of items '" + iItemCount + "'." }); } } } }); });
# json_script Safely outputs a Python object as JSON, wrapped in a `<script>` tag, ready for use with JavaScript. Argument: HTML "id" of the `<script>` tag. --- ```htmldjango {{ value|json_script:"hello-data" }} ```
/* * Copyright (c) 2018-2020, Arm Limited. All rights reserved. * * SPDX-License-Identifier: BSD-3-Clause * */ #include <stddef.h> #include <stdint.h> #include "tfm_mbedcrypto_include.h" #include "tfm_crypto_api.h" #include "tfm_crypto_defs.h" #include "tfm_crypto_private.h" /*! * \defgroup public_psa Public functions, PSA * */ /*!@{*/ psa_status_t tfm_crypto_hash_setup(psa_invec in_vec[], size_t in_len, psa_outvec out_vec[], size_t out_len) { #ifdef TFM_CRYPTO_HASH_MODULE_DISABLED SUPPRESS_UNUSED_IOVEC_PARAM_WARNING(); return PSA_ERROR_NOT_SUPPORTED; #else psa_status_t status = PSA_SUCCESS; psa_hash_operation_t *operation = NULL; CRYPTO_IN_OUT_LEN_VALIDATE(in_len, 1, 1, out_len, 1, 1); if ((out_vec[0].len != sizeof(uint32_t)) || (in_vec[0].len != sizeof(struct tfm_crypto_pack_iovec))) { return PSA_ERROR_PROGRAMMER_ERROR; } const struct tfm_crypto_pack_iovec *iov = in_vec[0].base; uint32_t handle = iov->op_handle; uint32_t *handle_out = out_vec[0].base; psa_algorithm_t alg = iov->alg; /* Init the handle in the operation with the one passed from the iov */ *handle_out = iov->op_handle; /* Allocate the operation context in the secure world */ status = tfm_crypto_operation_alloc(TFM_CRYPTO_HASH_OPERATION, &handle, (void **)&operation); if (status != PSA_SUCCESS) { #if defined(TFM_CONFIG_SL_SECURE_LIBRARY) if (status == PSA_ERROR_BAD_STATE) { *handle_out = handle; /* Release the operation context, ignore if the operation fails. */ (void)tfm_crypto_operation_release(handle_out); } #endif return status; } *handle_out = handle; status = psa_hash_setup(operation, alg); if (status != PSA_SUCCESS) { /* Release the operation context, ignore if the operation fails. */ (void)tfm_crypto_operation_release(handle_out); } return status; #endif /* TFM_CRYPTO_HASH_MODULE_DISABLED */ } psa_status_t tfm_crypto_hash_update(psa_invec in_vec[], size_t in_len, psa_outvec out_vec[], size_t out_len) { #ifdef TFM_CRYPTO_HASH_MODULE_DISABLED SUPPRESS_UNUSED_IOVEC_PARAM_WARNING(); return PSA_ERROR_NOT_SUPPORTED; #else psa_status_t status = PSA_SUCCESS; psa_hash_operation_t *operation = NULL; CRYPTO_IN_OUT_LEN_VALIDATE(in_len, 1, 2, out_len, 1, 1); if ((in_vec[0].len != sizeof(struct tfm_crypto_pack_iovec)) || (out_vec[0].len != sizeof(uint32_t))) { return PSA_ERROR_PROGRAMMER_ERROR; } const struct tfm_crypto_pack_iovec *iov = in_vec[0].base; uint32_t handle = iov->op_handle; uint32_t *handle_out = out_vec[0].base; const uint8_t *input = in_vec[1].base; size_t input_length = in_vec[1].len; /* Init the handle in the operation with the one passed from the iov */ *handle_out = iov->op_handle; /* Look up the corresponding operation context */ status = tfm_crypto_operation_lookup(TFM_CRYPTO_HASH_OPERATION, handle, (void **)&operation); if (status != PSA_SUCCESS) { #if defined(TFM_CONFIG_SL_SECURE_LIBRARY) if (status == PSA_ERROR_BAD_STATE) { *handle_out = handle; /* Release the operation context, ignore if the operation fails. */ (void)tfm_crypto_operation_release(handle_out); } #endif return status; } return psa_hash_update(operation, input, input_length); #endif /* TFM_CRYPTO_HASH_MODULE_DISABLED */ } psa_status_t tfm_crypto_hash_finish(psa_invec in_vec[], size_t in_len, psa_outvec out_vec[], size_t out_len) { #ifdef TFM_CRYPTO_HASH_MODULE_DISABLED SUPPRESS_UNUSED_IOVEC_PARAM_WARNING(); return PSA_ERROR_NOT_SUPPORTED; #else psa_status_t status = PSA_SUCCESS; psa_hash_operation_t *operation = NULL; CRYPTO_IN_OUT_LEN_VALIDATE(in_len, 1, 1, out_len, 1, 2); if ((in_vec[0].len != sizeof(struct tfm_crypto_pack_iovec)) || (out_vec[0].len != sizeof(uint32_t))) { return PSA_ERROR_PROGRAMMER_ERROR; } const struct tfm_crypto_pack_iovec *iov = in_vec[0].base; uint32_t handle = iov->op_handle; uint32_t *handle_out = out_vec[0].base; uint8_t *hash = out_vec[1].base; size_t hash_size = out_vec[1].len; /* Init the handle in the operation with the one passed from the iov */ *handle_out = iov->op_handle; /* Initialise hash_length to zero */ out_vec[1].len = 0; /* Look up the corresponding operation context */ status = tfm_crypto_operation_lookup(TFM_CRYPTO_HASH_OPERATION, handle, (void **)&operation); if (status != PSA_SUCCESS) { #if defined(TFM_CONFIG_SL_SECURE_LIBRARY) if (status == PSA_ERROR_BAD_STATE) { *handle_out = handle; /* Release the operation context, ignore if the operation fails. */ (void)tfm_crypto_operation_release(handle_out); } #endif return status; } status = psa_hash_finish(operation, hash, hash_size, &out_vec[1].len); if (status == PSA_SUCCESS) { /* Release the operation context, ignore if the operation fails. */ (void)tfm_crypto_operation_release(handle_out); } return status; #endif /* TFM_CRYPTO_HASH_MODULE_DISABLED */ } psa_status_t tfm_crypto_hash_verify(psa_invec in_vec[], size_t in_len, psa_outvec out_vec[], size_t out_len) { #ifdef TFM_CRYPTO_HASH_MODULE_DISABLED SUPPRESS_UNUSED_IOVEC_PARAM_WARNING(); return PSA_ERROR_NOT_SUPPORTED; #else psa_status_t status = PSA_SUCCESS; psa_hash_operation_t *operation = NULL; CRYPTO_IN_OUT_LEN_VALIDATE(in_len, 1, 2, out_len, 1, 1); if ((in_vec[0].len != sizeof(struct tfm_crypto_pack_iovec)) || (out_vec[0].len != sizeof(uint32_t))) { return PSA_ERROR_PROGRAMMER_ERROR; } const struct tfm_crypto_pack_iovec *iov = in_vec[0].base; uint32_t handle = iov->op_handle; uint32_t *handle_out = out_vec[0].base; const uint8_t *hash = in_vec[1].base; size_t hash_length = in_vec[1].len; /* Init the handle in the operation with the one passed from the iov */ *handle_out = iov->op_handle; /* Look up the corresponding operation context */ status = tfm_crypto_operation_lookup(TFM_CRYPTO_HASH_OPERATION, handle, (void **)&operation); if (status != PSA_SUCCESS) { return status; } status = psa_hash_verify(operation, hash, hash_length); #if !defined(TFM_CONFIG_SL_SECURE_LIBRARY) if (status == PSA_SUCCESS) #endif { /* Release the operation context, ignore if the operation fails. */ (void)tfm_crypto_operation_release(handle_out); } return status; #endif /* TFM_CRYPTO_HASH_MODULE_DISABLED */ } psa_status_t tfm_crypto_hash_abort(psa_invec in_vec[], size_t in_len, psa_outvec out_vec[], size_t out_len) { #ifdef TFM_CRYPTO_HASH_MODULE_DISABLED SUPPRESS_UNUSED_IOVEC_PARAM_WARNING(); return PSA_ERROR_NOT_SUPPORTED; #else psa_status_t status = PSA_SUCCESS; psa_hash_operation_t *operation = NULL; CRYPTO_IN_OUT_LEN_VALIDATE(in_len, 1, 1, out_len, 1, 1); if ((in_vec[0].len != sizeof(struct tfm_crypto_pack_iovec)) || (out_vec[0].len != sizeof(uint32_t))) { return PSA_ERROR_PROGRAMMER_ERROR; } const struct tfm_crypto_pack_iovec *iov = in_vec[0].base; uint32_t handle = iov->op_handle; uint32_t *handle_out = out_vec[0].base; /* Init the handle in the operation with the one passed from the iov */ *handle_out = iov->op_handle; /* Look up the corresponding operation context */ status = tfm_crypto_operation_lookup(TFM_CRYPTO_HASH_OPERATION, handle, (void **)&operation); if (status != PSA_SUCCESS) { /* Operation does not exist, so abort has no effect */ return PSA_SUCCESS; } status = psa_hash_abort(operation); if (status != PSA_SUCCESS) { /* Release the operation context, ignore if the operation fails. */ (void)tfm_crypto_operation_release(handle_out); return status; } return tfm_crypto_operation_release(handle_out); #endif /* TFM_CRYPTO_HASH_MODULE_DISABLED */ } psa_status_t tfm_crypto_hash_clone(psa_invec in_vec[], size_t in_len, psa_outvec out_vec[], size_t out_len) { #ifdef TFM_CRYPTO_HASH_MODULE_DISABLED SUPPRESS_UNUSED_IOVEC_PARAM_WARNING(); return PSA_ERROR_NOT_SUPPORTED; #else psa_status_t status = PSA_SUCCESS; psa_hash_operation_t *source_operation = NULL; psa_hash_operation_t *target_operation = NULL; CRYPTO_IN_OUT_LEN_VALIDATE(in_len, 1, 1, out_len, 1, 1); if ((in_vec[0].len != sizeof(struct tfm_crypto_pack_iovec)) || (out_vec[0].len != sizeof(uint32_t))) { return PSA_ERROR_PROGRAMMER_ERROR; } const struct tfm_crypto_pack_iovec *iov = in_vec[0].base; uint32_t source_handle = iov->op_handle; uint32_t *target_handle = out_vec[0].base; /* Look up the corresponding source operation context */ status = tfm_crypto_operation_lookup(TFM_CRYPTO_HASH_OPERATION, source_handle, (void **)&source_operation); if (status != PSA_SUCCESS) { return status; } /* Allocate the target operation context in the secure world */ status = tfm_crypto_operation_alloc(TFM_CRYPTO_HASH_OPERATION, target_handle, (void **)&target_operation); if (status != PSA_SUCCESS) { return status; } return psa_hash_clone(source_operation, target_operation); #endif /* TFM_CRYPTO_HASH_MODULE_DISABLED */ } psa_status_t tfm_crypto_hash_compute(psa_invec in_vec[], size_t in_len, psa_outvec out_vec[], size_t out_len) { #ifdef TFM_CRYPTO_HASH_MODULE_DISABLED SUPPRESS_UNUSED_IOVEC_PARAM_WARNING(); return PSA_ERROR_NOT_SUPPORTED; #else CRYPTO_IN_OUT_LEN_VALIDATE(in_len, 1, 2, out_len, 0, 1); if ((in_vec[0].len != sizeof(struct tfm_crypto_pack_iovec))) { return PSA_ERROR_PROGRAMMER_ERROR; } const struct tfm_crypto_pack_iovec *iov = in_vec[0].base; psa_algorithm_t alg = iov->alg; const uint8_t *input = in_vec[1].base; size_t input_length = in_vec[1].len; uint8_t *hash = out_vec[0].base; size_t hash_size = out_vec[0].len; /* Initialize hash_length to zero */ out_vec[0].len = 0; return psa_hash_compute(alg, input, input_length, hash, hash_size, &out_vec[0].len); #endif /* TFM_CRYPTO_HASH_MODULE_DISABLED */ } psa_status_t tfm_crypto_hash_compare(psa_invec in_vec[], size_t in_len, psa_outvec out_vec[], size_t out_len) { #ifdef TFM_CRYPTO_HASH_MODULE_DISABLED SUPPRESS_UNUSED_IOVEC_PARAM_WARNING(); return PSA_ERROR_NOT_SUPPORTED; #else // No output. (void)out_vec; CRYPTO_IN_OUT_LEN_VALIDATE(in_len, 1, 3, out_len, 0, 0); if ((in_vec[0].len != sizeof(struct tfm_crypto_pack_iovec))) { return PSA_ERROR_PROGRAMMER_ERROR; } const struct tfm_crypto_pack_iovec *iov = in_vec[0].base; psa_algorithm_t alg = iov->alg; const uint8_t *input = in_vec[1].base; size_t input_length = in_vec[1].len; const uint8_t *hash = in_vec[2].base; size_t hash_length = in_vec[2].len; return psa_hash_compare(alg, input, input_length, hash, hash_length); #endif /* TFM_CRYPTO_HASH_MODULE_DISABLED */ } /*!@}*/
require 'spec_helper' module BoletoBancario module Core describe Banrisul do it_should_behave_like 'boleto bancario' describe "on validations" do it "agencia should have 3 digits" do should have_valid(:agencia).when("1", "123", 1, 123) should_not have_valid(:agencia).when(nil, "", "1234") end it "codigo cedente should have 07 digits" do should have_valid(:codigo_cedente).when("1234567", "12", "12345") should_not have_valid(:codigo_cedente).when(nil, "", "12345678", "123456789") end it "numero documento should have 8 digits" do should have_valid(:numero_documento).when("12345678", "1234") should_not have_valid(:numero_documento).when(nil, "", "123456789") end it "carteira is supported" do should have_valid(:carteira).when('00', '08', 0, 8) should_not have_valid(:carteira).when(nil, '', '5', '20', '100') end end describe "#agencia" do context "when have a value" do subject { Banrisul.new(agencia: '34') } its(:agencia) { should eq '034' } end context "when is nil" do subject { Banrisul.new(agencia: nil) } its(:agencia) { should be nil } end end describe "#numero_documento" do context "when have a value" do subject { Banrisul.new(numero_documento: '1234') } its(:numero_documento) { should eq '00001234' } end context "when is nil" do subject { Banrisul.new(numero_documento: nil) } its(:numero_documento) { should be nil } end end describe "#codigo_cedente" do context "when have a value" do subject { Banrisul.new(codigo_cedente: '1234') } its(:codigo_cedente) { should eq '0001234' } end context "when is nil" do subject { Banrisul.new(codigo_cedente: nil) } its(:codigo_cedente) { should be nil } end end describe "#codigo_banco" do its(:codigo_banco) { should eq '041' } end describe "#digito_codigo_banco" do its(:digito_codigo_banco) { should eq '8' } end describe "#agencia_codigo_cedente" do subject { Banrisul.new(agencia: '100', codigo_cedente: '0000001') } its(:agencia_codigo_cedente) { should eq '100.81 0000001.83' } end describe "#nosso_numero" do context "using one example from documentation" do subject { Banrisul.new(numero_documento: '00009194') } its(:nosso_numero) { should eq '00009194.38' } end context "using other example from documentation" do subject { Banrisul.new(numero_documento: '00009274') } its(:nosso_numero) { should eq '00009274.22' } end context "another example" do subject { Banrisul.new(numero_documento: '22832563') } its(:nosso_numero) { should eq '22832563.51' } end end describe "#codigo_de_barras" do context "one example" do subject do Banrisul.new do |boleto| boleto.numero_documento = 22832563 boleto.agencia = 100 boleto.data_vencimento = Date.parse('2004-07-04') boleto.codigo_cedente = "0000001" boleto.valor_documento = 5.0 end end its(:codigo_de_barras) { should eq '04197246200000005002110000000012283256304168' } its(:linha_digitavel) { should eq '04192.11008 00000.012286 32563.041683 7 24620000000500' } end end end end end
module Helpers module Errors def error_403!(options = {}) content = { status: 'Error', code: 403, message: 'Access denied' } content.merge!(options) error!(content, 403) end def error_401!(options = {}) content = { status: 'Error', code: 401, message: 'Unauthorized' } content.merge!(options) error!(content, 401) end def error_500!(options = {}) content = { status: 'Error', code: 500, message: 'Internal Server Error' } content.merge!(options) error!(content, 500) end def error_400!(options = {}) content = { status: 'Error', code: 400, message: 'Bad request' } content.merge!(options) error!(content, 400) end def error_422!(options = {}) error!(options, 422) end def success!(options = {}) options.reverse_merge!(status: 'Ok', code: 200) Rack::Response.new(options, 200).finish end def added!(options = {}) options.reverse_merge!(status: 'Ok', code: 201) Rack::Response.new(options, 201, 'Content-type' => 'application/json').finish end end end
Rails.application.routes.draw do use_doorkeeper root to: 'static_pages#home' get 'static_pages/home' get 'static_pages/about_us' get 'static_pages/contact_us' devise_for :users scope 'tickets' do resources :ticket_categories, path: 'categories', only: [:index, :show] resources :ticket_items, path: '/' end namespace :admin do get 'dashboard', to: 'dashboard#index', as: :dashboard resources :users scope 'tickets' do resources :ticket_categories, path: 'categories' resources :ticket_items, path: '/', except: [:new, :create] end end api_version(:module => "V1", :path => {:value => "api/v1"}, :defaults => {:format => "json"}, :default => true) do mount_devise_token_auth_for 'User', at: 'auth', controllers: { confirmations: 'devise_token_auth/confirmations', passwords: 'devise_token_auth/passwords', omniauth_callbacks: 'devise_token_auth/omniauth_callbacks', registrations: 'devise_token_auth/registrations', sessions: 'devise_token_auth/sessions', token_validations: 'devise_token_auth/token_validations' } scope 'tickets' do resources :ticket_categories, path: 'categories' end end end
%% See LICENSE for licensing information. %% -*- coding: utf-8 -*- -module(thaw_examples_tests). %% Examples written in Erlang rather than ICE. %% %% They are written as tests for convenience. -include_lib("eunit/include/eunit.hrl"). %% API. -export([fib_seq/1]). -export([fib_par/1]). -export([spawn_n/2, join/1]). %% Functions exported for internals of fib_par/1 fib_seq(0) -> 0; fib_seq(1) -> 1; fib_seq(N) -> fib_seq(N - 2) + fib_seq(N - 1). fib_par(0) -> 0; fib_par(1) -> 1; fib_par(N) -> MFA2 = [?MODULE, fib_par, [N - 2]], MFA1 = [?MODULE, fib_par, [N - 1]], Pids = ?MODULE:spawn_n(self(), [MFA2, MFA1]), [N2, N1] = ?MODULE:join(Pids), N2 + N1. %% API internals. spawn_n(PPid, MFAs) -> lists:map( fun([M,F,A]) -> spawn(fun() -> PPid ! {self(), apply(M,F,A)} end) end, MFAs). join(Pids) -> lists:map(fun(Pid) -> receive {Pid, RV} -> RV end end, Pids). %% API tests. fib_seq_test() -> ?assertEqual( [0,1,1,2,3,5,13,55], lists:map(fun ?MODULE:fib_seq/1, [0,1,2,3,4,5,7,10])). fib_par_test() -> ?assertEqual( [0,1,1,2,3,5,13,55], lists:map(fun ?MODULE:fib_par/1, [0,1,2,3,4,5,7,10])). %% Tests' internals. %% End of Module.
using System; using System.Collections.Generic; using System.Reflection; using FlaxEngine; namespace Mirror { public static class InspectorHelper { /// <summary> /// Gets all public and private fields for a type /// </summary> /// <param name="type"></param> /// <param name="deepestBaseType">Stops at this base type (exclusive)</param> /// <returns></returns> public static IEnumerable<FieldInfo> GetAllFields(Type type, Type deepestBaseType) { const BindingFlags publicFields = BindingFlags.Public | BindingFlags.Instance; const BindingFlags privateFields = BindingFlags.NonPublic | BindingFlags.Instance; // get public fields (includes fields from base type) FieldInfo[] allPublicFields = type.GetFields(publicFields); foreach (FieldInfo field in allPublicFields) { yield return field; } // get private fields in current type, then move to base type while (type != null) { FieldInfo[] allPrivateFields = type.GetFields(privateFields); foreach (FieldInfo field in allPrivateFields) { yield return field; } type = type.BaseType; // stop early if (type == deepestBaseType) { break; } } } public static bool IsSyncVar(this FieldInfo field) { object[] fieldMarkers = field.GetCustomAttributes(typeof(SyncVarAttribute), true); return fieldMarkers.Length > 0; } public static bool IsSerialize(this FieldInfo field) { object[] fieldMarkers = field.GetCustomAttributes(typeof(Serialize), true); return fieldMarkers.Length > 0; } public static bool IsVisibleField(this FieldInfo field) { return field.IsPublic || IsSerialize(field); } public static bool IsSyncObject(this FieldInfo field) { return typeof(SyncObject).IsAssignableFrom(field.FieldType); } public static bool HasShowInInspector(this FieldInfo field) { object[] fieldMarkers = field.GetCustomAttributes(typeof(ShowInInspectorAttribute), true); return fieldMarkers.Length > 0; } public static bool IsVisibleSyncObject(this FieldInfo field) { return field.IsPublic || HasShowInInspector(field); } } }
using System; using System.ComponentModel.DataAnnotations; namespace rbkApiModules.Analytics.Core { public class SessionEntry { public SessionEntry(string username, DateTime start, DateTime end) { Username = username; Start = start; End = end; Duration = (float)(end - start).TotalMinutes; } public Guid Id { get; set; } public DateTime Start { get; set; } public DateTime End { get; set; } [MaxLength(128)] public string Username { get; set; } public float Duration { get; set; } } }
import Control.Monad (guard) inBounds :: [String] -> Int -> Int -> Bool inBounds xs i j = i >= 0 && i < length xs && j >= 0 && j < length (head xs) neighbors :: Bool -> [String] -> Int -> Int -> [Char] neighbors lookFar xs i j = do (iDir, jDir) <- [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)] let goDir (i', j') = (i' + iDir, j' + jDir) (i', j') = if lookFar then until (\(i', j') -> not (inBounds xs i' j') || xs !! i' !! j' /= '.') goDir (goDir (i, j)) else goDir (i, j) guard $ inBounds xs i' j' return $ xs !! i' !! j' newState :: ([String] -> Int -> Int -> [Char]) -> Int -> [String] -> Int -> Int -> Char newState neighbors threshold xs i j | xs !! i !! j == 'L' && occupied == 0 = '#' | xs !! i !! j == '#' && occupied >= threshold = 'L' | otherwise = xs !! i !! j where occupied = length . filter (=='#') $ neighbors xs i j nextCycle :: ([String] -> Int -> Int -> Char) -> [String] -> [String] nextCycle newState xs = [[newState xs i j | j <- [0..pred . length . head $ xs]] | i <- [0..pred . length $ xs]] main :: IO () main = do input <- lines <$> readFile "input.txt" let countFinalOccupied = length . filter (=='#') . concat print $ countFinalOccupied $ (until =<< ((==) =<<)) (nextCycle $ newState (neighbors False) 4) input print $ countFinalOccupied $ (until =<< ((==) =<<)) (nextCycle $ newState (neighbors True) 5) input
# Docker port 命令 **docker port :**列出指定的容器的端口映射,或者查找将PRIVATE_PORT NAT到面向公众的端口。 ### 语法 ``` docker port [OPTIONS] CONTAINER [PRIVATE_PORT[/PROTO]] ``` ### 实例 查看容器mynginx的端口映射情况。 ``` runoob@runoob:~$ docker port mymysql 3306/tcp -> 0.0.0.0:3306 ```
package com.jet.parking.common.domain interface ErrorCode { fun getCode(): Int fun getDesc(): String? }
#! /bin/bash # Completion for bash: # # (1) install this file, # # (2) load the script, and # . ~/.profile.d/rb_optparse.bash # # (3) define completions in your .bashrc, # rb_optparse command_using_optparse_1 # rb_optparse command_using_optparse_2 _rb_optparse() { COMPREPLY=($("${COMP_WORDS[0]}" "--*-completion-bash=${COMP_WORDS[COMP_CWORD]}")) return 0 } rb_optparse () { [ $# = 0 ] || complete -o default -F _rb_optparse "$@" }
# League_Of_Follows This is a portfolio project that will test the Riot API to practice JSON requests.
# frozen_string_literal: true require 'active_support/concern' module SnFoil module Policy extend ActiveSupport::Concern attr_reader :record, :entity attr_accessor :options def initialize(entity, record, options = {}) @record = record @entity = entity @options = options end def index? false end def show? false end def create? false end def update? false end def destroy? false end def associate? false end class Scope attr_reader :scope, :entity def initialize(scope, entity = nil) @entity = entity @scope = scope end def resolve scope.all end end end end
#include "felippa_prism.hpp" namespace neon { felippa_prism::felippa_prism(int const minimum_degree) { switch (minimum_degree) { case 1: { m_degree = 1; m_weights = {1.0}; m_coordinates = {{0, 1.0 / 3.0, 1.0 / 3.0, 0.0}}; break; } case 2: case 3: { m_degree = 3; m_weights.resize(6, 1.0 / 6.0); m_coordinates = {{0, 0.16666666666666666, 0.6666666666666667, 0.5773502691896257}, {1, 0.6666666666666667, 0.16666666666666666, 0.5773502691896257}, {2, 0.16666666666666666, 0.16666666666666666, 0.5773502691896257}, {3, 0.16666666666666666, 0.6666666666666667, -0.5773502691896257}, {4, 0.6666666666666667, 0.16666666666666666, -0.5773502691896257}, {5, 0.16666666666666666, 0.16666666666666666, -0.5773502691896257}}; break; } case 4: { m_degree = 4; m_weights = {0.06205044157722541, 0.06205044157722541, 0.06205044157722541, 0.06205044157722541, 0.06205044157722541, 0.06205044157722541, 0.03054215101536719, 0.03054215101536719, 0.03054215101536719, 0.03054215101536719, 0.03054215101536719, 0.03054215101536719, 0.09928070652356065, 0.09928070652356065, 0.09928070652356065, 0.0488674416245875, 0.0488674416245875, 0.0488674416245875}; m_coordinates = {{0, 0.4459484909159649, 0.10810301816807022, 0.7745966692414834}, {1, 0.10810301816807022, 0.4459484909159649, 0.7745966692414834}, {2, 0.4459484909159649, 0.4459484909159649, 0.7745966692414834}, {3, 0.4459484909159649, 0.10810301816807022, -0.7745966692414834}, {4, 0.10810301816807022, 0.4459484909159649, -0.7745966692414834}, {5, 0.4459484909159649, 0.4459484909159649, -0.7745966692414834}, {6, 0.09157621350977073, 0.8168475729804585, 0.7745966692414834}, {7, 0.8168475729804585, 0.09157621350977073, 0.7745966692414834}, {8, 0.09157621350977073, 0.09157621350977073, 0.7745966692414834}, {9, 0.09157621350977073, 0.8168475729804585, -0.7745966692414834}, {10, 0.8168475729804585, 0.09157621350977073, -0.7745966692414834}, {11, 0.09157621350977073, 0.09157621350977073, -0.7745966692414834}, {12, 0.4459484909159649, 0.10810301816807022, 0.0}, {13, 0.10810301816807022, 0.4459484909159649, 0.0}, {14, 0.4459484909159649, 0.4459484909159649, 0.0}, {15, 0.09157621350977073, 0.8168475729804585, 0.0}, {16, 0.8168475729804585, 0.09157621350977073, 0.0}, {17, 0.09157621350977073, 0.09157621350977073, 0.0}}; break; } case 5: { m_degree = 5; m_weights = {0.03498310570689643, 0.03498310570689643, 0.03498310570689643, 0.03498310570689643, 0.03498310570689643, 0.03498310570689643, 0.03677615355236283, 0.03677615355236283, 0.03677615355236283, 0.03677615355236283, 0.03677615355236283, 0.03677615355236283, 0.0625, 0.0625, 0.05597296913103428, 0.05597296913103428, 0.05597296913103428, 0.05884184568378053, 0.05884184568378053, 0.05884184568378053, 0.1}; m_coordinates = {{0, 0.10128650732345633, 0.7974269853530873, 0.7745966692414834}, {1, 0.7974269853530873, 0.10128650732345633, 0.7745966692414834}, {2, 0.10128650732345633, 0.10128650732345633, 0.7745966692414834}, {3, 0.10128650732345633, 0.7974269853530873, -0.7745966692414834}, {4, 0.7974269853530873, 0.10128650732345633, -0.7745966692414834}, {5, 0.10128650732345633, 0.10128650732345633, -0.7745966692414834}, {6, 0.47014206410511505, 0.05971587178976989, 0.7745966692414834}, {7, 0.05971587178976989, 0.47014206410511505, 0.7745966692414834}, {8, 0.47014206410511505, 0.47014206410511505, 0.7745966692414834}, {9, 0.47014206410511505, 0.05971587178976989, -0.7745966692414834}, {10, 0.05971587178976989, 0.47014206410511505, -0.7745966692414834}, {11, 0.47014206410511505, 0.47014206410511505, -0.7745966692414834}, {12, 0.3333333333333333, 0.3333333333333333, 0.7745966692414834}, {13, 0.3333333333333333, 0.3333333333333333, -0.7745966692414834}, {14, 0.10128650732345633, 0.7974269853530873, 0.0}, {15, 0.7974269853530873, 0.10128650732345633, 0.0}, {16, 0.10128650732345633, 0.10128650732345633, 0.0}, {17, 0.47014206410511505, 0.05971587178976989, 0.0}, {18, 0.05971587178976989, 0.47014206410511505, 0.0}, {19, 0.47014206410511505, 0.47014206410511505, 0.0}, {20, 0.3333333333333333, 0.3333333333333333, 0.0}}; break; } case 6: { m_degree = 6; m_weights = {0.008843323515718317, 0.008843323515718317, 0.008843323515718317, 0.008843323515718317, 0.008843323515718317, 0.008843323515718317, 0.02031233592848984, 0.02031233592848984, 0.02031233592848984, 0.02031233592848984, 0.02031233592848984, 0.02031233592848984, 0.01441007403935041, 0.01441007403935041, 0.01441007403935041, 0.01441007403935041, 0.01441007403935041, 0.01441007403935041, 0.01441007403935041, 0.01441007403935041, 0.01441007403935041, 0.01441007403935041, 0.01441007403935041, 0.01441007403935041, 0.01657912966938509, 0.01657912966938509, 0.01657912966938509, 0.01657912966938509, 0.01657912966938509, 0.01657912966938509, 0.03808080193469984, 0.03808080193469984, 0.03808080193469984, 0.03808080193469984, 0.03808080193469984, 0.03808080193469984, 0.02701546376983638, 0.02701546376983638, 0.02701546376983638, 0.02701546376983638, 0.02701546376983638, 0.02701546376983638, 0.02701546376983638, 0.02701546376983638, 0.02701546376983638, 0.02701546376983638, 0.02701546376983638, 0.02701546376983638}; m_coordinates = {{0, 0.06308901449150223, 0.8738219710169955, -0.8611363115940526}, {1, 0.8738219710169955, 0.06308901449150223, -0.8611363115940526}, {2, 0.06308901449150223, 0.06308901449150223, -0.8611363115940526}, {3, 0.06308901449150223, 0.8738219710169955, 0.8611363115940526}, {4, 0.8738219710169955, 0.06308901449150223, 0.8611363115940526}, {5, 0.06308901449150223, 0.06308901449150223, 0.8611363115940526}, {6, 0.2492867451709104, 0.5014265096581791, -0.8611363115940526}, {7, 0.5014265096581791, 0.2492867451709104, -0.8611363115940526}, {8, 0.2492867451709104, 0.2492867451709104, -0.8611363115940526}, {9, 0.2492867451709104, 0.5014265096581791, 0.8611363115940526}, {10, 0.5014265096581791, 0.2492867451709104, 0.8611363115940526}, {11, 0.2492867451709104, 0.2492867451709104, 0.8611363115940526}, {12, 0.3103524510337844, 0.6365024991213987, 0.8611363115940526}, {13, 0.05314504984481695, 0.3103524510337844, 0.8611363115940526}, {14, 0.6365024991213987, 0.05314504984481695, 0.8611363115940526}, {15, 0.6365024991213987, 0.3103524510337844, 0.8611363115940526}, {16, 0.05314504984481695, 0.6365024991213987, 0.8611363115940526}, {17, 0.3103524510337844, 0.05314504984481695, 0.8611363115940526}, {18, 0.3103524510337844, 0.6365024991213987, -0.8611363115940526}, {19, 0.05314504984481695, 0.3103524510337844, -0.8611363115940526}, {20, 0.6365024991213987, 0.05314504984481695, -0.8611363115940526}, {21, 0.6365024991213987, 0.3103524510337844, -0.8611363115940526}, {22, 0.05314504984481695, 0.6365024991213987, -0.8611363115940526}, {23, 0.3103524510337844, 0.05314504984481695, -0.8611363115940526}, {24, 0.06308901449150223, 0.8738219710169955, 0.3399810435848563}, {25, 0.8738219710169955, 0.06308901449150223, 0.3399810435848563}, {26, 0.06308901449150223, 0.06308901449150223, 0.3399810435848563}, {27, 0.06308901449150223, 0.8738219710169955, -0.3399810435848563}, {28, 0.8738219710169955, 0.06308901449150223, -0.3399810435848563}, {29, 0.06308901449150223, 0.06308901449150223, -0.3399810435848563}, {30, 0.2492867451709104, 0.5014265096581791, 0.3399810435848563}, {31, 0.5014265096581791, 0.2492867451709104, 0.3399810435848563}, {32, 0.2492867451709104, 0.2492867451709104, 0.3399810435848563}, {33, 0.2492867451709104, 0.5014265096581791, -0.3399810435848563}, {34, 0.5014265096581791, 0.2492867451709104, -0.3399810435848563}, {35, 0.2492867451709104, 0.2492867451709104, -0.3399810435848563}, {36, 0.3103524510337844, 0.6365024991213987, 0.3399810435848563}, {37, 0.05314504984481695, 0.3103524510337844, 0.3399810435848563}, {38, 0.6365024991213987, 0.05314504984481695, 0.3399810435848563}, {39, 0.6365024991213987, 0.3103524510337844, 0.3399810435848563}, {40, 0.05314504984481695, 0.6365024991213987, 0.3399810435848563}, {41, 0.3103524510337844, 0.05314504984481695, 0.3399810435848563}, {42, 0.3103524510337844, 0.6365024991213987, -0.3399810435848563}, {43, 0.05314504984481695, 0.3103524510337844, -0.3399810435848563}, {44, 0.6365024991213987, 0.05314504984481695, -0.3399810435848563}, {45, 0.6365024991213987, 0.3103524510337844, -0.3399810435848563}, {46, 0.05314504984481695, 0.6365024991213987, -0.3399810435848563}, {47, 0.3103524510337844, 0.05314504984481695, -0.3399810435848563}}; break; } default: { throw std::domain_error("This is not the quadrature scheme you are looking for"); } } } }
#region HappyDo // This is HappyDo // which downloads files from one place to another // thus, making me happy. // https://github.com/picrap/HappyDo // MIT License #endregion namespace HappyDo.Core.Rules { public class Rule { public string Match { get; set; } public string SubDirectory { get; set; } } }
### Create sequental IPs list Run as <i>tclsh</i> <b>cipl.tcl</b> \<<i>start address</i>\> [\<<i>end address</i> | amount adresses\>] - cipl.tcl - initial algorithm - cipl2.tcl - optimize - cipl3.tcl - more optimize [There is article about this on Habrahabr](https://habrahabr.ru/post/135920/)
<?php use Illuminate\Auth\UserTrait; use Illuminate\Auth\UserInterface; use Illuminate\Auth\Reminders\RemindableTrait; use Illuminate\Auth\Reminders\RemindableInterface; class Step extends Eloquent { var $fillable = ['id','recipe_id','order']; public $timestamps = false; public function recipe(){ return $this->belongsTo('Recipe'); } }
package me.rnelson.learn.kotlin.rng.controllers import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RestController import java.util.Random @RestController @RequestMapping("/generate") class RandomController { private val r = Random() @GetMapping("/int") fun getInt(): Int { return r.nextInt() } @GetMapping("/float") fun getFloat(): Float { return r.nextFloat() } @GetMapping("/double") fun getDouble(): Double { return r.nextDouble() } @GetMapping("/int/{max}") fun getIntMax(@PathVariable max: Int): Int { return r.nextInt(max) } @GetMapping("/seeded/int/{seed}") fun getSeededInt(@PathVariable seed: Long): Int { val seededRandom = Random(seed) return seededRandom.nextInt() } @GetMapping("/seeded/float/{seed}") fun getSeededFloat(@PathVariable seed: Long): Float { val seededRandom = Random(seed) return seededRandom.nextFloat() } @GetMapping("/seeded/double/{seed}") fun getSeededDouble(@PathVariable seed: Long): Double { val seededRandom = Random(seed) return seededRandom.nextDouble() } }
import os import sys import subprocess # Application Viewer for CariboSystem6 Preview print() def app_uninstall(): if sys.platform == "win32": application = input("Enter APP Name: ") print("Are you sure you want to uninstall " + application + " ?") confirm = input("Yes/No > ") if confirm == "yes": core_application = application + ".py" core_dat = application + ".dat" del_application = "del " + core_application del_dat = "del " + core_dat os.system(del_application) os.system(del_dat) print("App Uninstalled Successfully..!") log = open("app.log", 'a') log.write("\n Uninstalled " + application) log.close() print() else: print() else: opener = "open" if sys.platform == "darwin" else "xdg-open" application = input("Enter APP Name: ") print("Are you sure you want to uninstall " + application + " ?") confirm = input("Yes/No > ") if confirm == "yes": core_application = application + ".py" core_dat = application + ".dat" del_application = "rm " + "app/" + core_application del_dat = "rm " + "app/" + core_dat os.system(del_application) os.system(del_dat) print("App Uninstalled Successfully..!") log = open("app.log", 'a') log.write("\n Uninstalled " + application) log.close() print() else: print() print("CariboSystem App Manager") print("---------------------------") print() core = "" while core != "quit" or core != "exit": print("Enter `unin` to uninstall an app, Enter `exit` to quit to CariboSystem") print() core = input("> ").lower() if core == "unin": app_uninstall() elif core == "exit" or core == "quit": break else: print("Invalid Selection...!")
package com.tkstr.kobold import com.tkstr.kobold.utils.logger import org.jetbrains.spek.api.Spek /** * @author Ben Teichman */ class ConstructorSpec : Spek() { open class Innermost { val LOG by logger() constructor() { LOG.info("constructed") } } class MiddlemostByConvention : Innermost { constructor() : super() { LOG.info("constructed") } } class MiddlemostByLegacy : Innermost { constructor() { LOG.info("constructed") } } init { given("a class") { on("instantiation") { it("should log") { val inner = MiddlemostByLegacy() } } } } }
const snarkjs = require("snarkjs"); const eddsa = require("circomlib/src/eddsa.js"); const mimcsponge = require("circomlib/src/mimcsponge.js") const bigInt = snarkjs.bigInt; const msg = "00010203040506070809"; // 10 bytes const prvSeed = "0001020304050607080900010203040506070809000102030405060708090001"; function eddsa_jubjub_sign() { const msgBig = bigInt("0x" + msg); // console.log("msg in bigint: ", msgBig); const hm = mimcsponge.multiHash([msgBig]); const hmBuff = bigInt.leInt2Buff(hm, 32); console.log("msg hash in bigint:\n ", hm, " --> msg"); // private key of eddsa is generated by 32bytes seed. Some implementations // use the seed as private key // https://blog.mozilla.org/warner/2011/11/29/ed25519-keys/ const prvKey = Buffer.from(prvSeed, "hex"); const pubKey = eddsa.prv2pub(prvKey); const signature = eddsa.sign(prvKey, hmBuff); console.log("public key:\n ", pubKey[0], " --> Ax") console.log(" ", pubKey[1], " --> Ay") console.log("signature:\n ", signature.R8[0], " --> R8x") console.log(" ", signature.R8[1], " --> R8y") console.log(" ", signature.S, " --> S") if(!eddsa.verify(hmBuff, signature, pubKey)){ console.log("\nsignature not matched\n"); } } eddsa_jubjub_sign()
#[macro_use] extern crate log; #[macro_use] extern crate lazy_static; #[macro_use] extern crate serde_derive; pub mod dashboard; pub mod exit_manager; pub mod heartbeat; pub mod light_client_manager; pub mod logging; pub mod operator_fee_manager; pub mod operator_update; pub mod rita_loop; pub mod traffic_watcher; mod error; pub use error::RitaClientError; use rita_common::READABLE_VERSION; pub use crate::dashboard::auth::*; pub use crate::dashboard::backup_created::*; pub use crate::dashboard::bandwidth_limit::*; pub use crate::dashboard::contact_info::*; pub use crate::dashboard::contact_info::*; pub use crate::dashboard::eth_private_key::*; pub use crate::dashboard::exits::*; pub use crate::dashboard::installation_details::*; pub use crate::dashboard::interfaces::*; pub use crate::dashboard::localization::*; pub use crate::dashboard::logging::*; pub use crate::dashboard::mesh_ip::*; pub use crate::dashboard::neighbors::*; pub use crate::dashboard::notifications::*; pub use crate::dashboard::operator::*; pub use crate::dashboard::prices::*; pub use crate::dashboard::remote_access::*; pub use crate::dashboard::router::*; pub use crate::dashboard::system_chain::*; pub use crate::dashboard::usage; pub use crate::dashboard::wifi::*; use settings::client::{default_config_path, APP_NAME}; #[derive(Debug, Deserialize)] pub struct Args { #[serde(default = "default_config_path")] pub flag_config: String, pub flag_platform: String, pub flag_future: bool, } impl Default for Args { fn default() -> Self { Args { flag_config: default_config_path(), flag_platform: "linux".to_string(), flag_future: false, } } } /// TODO platform is in the process of being removed as a support argument /// as it's not even used. Config can still be used but has a sane default /// and does not need to be specified. pub fn get_client_usage(version: &str, git_hash: &str) -> String { format!( "Usage: {} [--config=<settings>] [--platform=<platform>] [--future] Options: -c, --config=<settings> Name of config file -p, --platform=<platform> Platform (linux or OpenWrt) --future Enable B side of A/B releases About: Version {} - {} git hash {}", APP_NAME, READABLE_VERSION, version, git_hash ) }
--- title: 5402 - TokenValidationStarted ms.date: 03/30/2017 ms.assetid: d3e9a727-92dd-4d5b-bca9-2ec98c1fde5c ms.openlocfilehash: 212c6cd3a341f46e6ba0ad4b8542d47f699fb7c9 ms.sourcegitcommit: 9b552addadfb57fab0b9e7852ed4f1f1b8a42f8e ms.translationtype: MT ms.contentlocale: fr-FR ms.lasthandoff: 04/23/2019 ms.locfileid: "61762499" --- # <a name="5402---tokenvalidationstarted"></a>5402 - TokenValidationStarted ## <a name="properties"></a>Properties ||| |-|-| |Id|5402| |Mots clés|Sécurité| |Niveau|Verbose| |Canal|Microsoft-Windows-Application Server-Applications/Débogage| ## <a name="description"></a>Description Cet événement est émis lorsque la validation de SecurityToken a commencé. ## <a name="message"></a>Message Début de la validation de SecurityToken (type « %1 » et ID « %2 »). ## <a name="details"></a>Détails
# ShellEx Small program where we can see executions in bash from C# program.
<?php return [ 'api_base_url' => 'https://pos.snapscan.io', 'api_key' => '', 'merchant_code' => '' ];
/* * Copyright (c) 2008-2015, Hazelcast, Inc. All Rights Reserved. * * 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. */ package com.hazelcast.cache.impl.client; import com.hazelcast.cache.impl.CacheContext; import com.hazelcast.cache.impl.CachePortableHook; import com.hazelcast.cache.impl.CacheService; import com.hazelcast.client.ClientEndpoint; import com.hazelcast.client.impl.client.CallableClientRequest; import com.hazelcast.client.impl.client.RetryableRequest; import com.hazelcast.nio.serialization.PortableReader; import com.hazelcast.nio.serialization.PortableWriter; import java.io.IOException; import java.security.Permission; public class CacheAddInvalidationListenerRequest extends CallableClientRequest implements RetryableRequest { private String name; public CacheAddInvalidationListenerRequest() { } public CacheAddInvalidationListenerRequest(String name) { this.name = name; } @Override public Object call() { ClientEndpoint endpoint = getEndpoint(); CacheService cacheService = getService(); CacheContext cacheContext = cacheService.getOrCreateCacheContext(name); CacheInvalidationListener listener = new CacheInvalidationListener(endpoint, getCallId(), cacheContext); String registrationId = cacheService.addInvalidationListener(name, listener); endpoint.setListenerRegistration(CacheService.SERVICE_NAME, name, registrationId); return registrationId; } public String getServiceName() { return CacheService.SERVICE_NAME; } @Override public int getFactoryId() { return CachePortableHook.F_ID; } @Override public int getClassId() { return CachePortableHook.ADD_INVALIDATION_LISTENER; } @Override public void write(PortableWriter writer) throws IOException { super.write(writer); writer.writeUTF("n", name); } @Override public void read(PortableReader reader) throws IOException { super.read(reader); name = reader.readUTF("n"); } @Override public Permission getRequiredPermission() { return null; } }
library docs_bloc; export 'commercio_docs_bloc.dart'; export 'commercio_docs_event.dart'; export 'commercio_docs_state.dart';
<?php namespace Tests\Feature; use App\Deck; use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Foundation\Testing\WithFaker; use Tests\TestCase; class ReviewTest extends TestCase { use RefreshDatabase; /** @test */ function empty_deck_not_have_review_mode() { $deck = factory(Deck::class)->create(); $this->get($deck->path('review')) ->assertRedirect($deck->path()); } /** @test */ public function review_cards_of_deck() { $this->withoutExceptionHandling(); $deck = factory('App\Deck')->create(); $cards = factory('App\Card', 10)->create([ 'deck_id' => $deck->id ]); $this->get($deck->path('review')) ->assertOk() ->assertSee($cards->first()->front) ->assertSee($cards->first()->back); } }
#!/bin/bash TARGETS=($(ls -1 "${CIQ_HOME}../../devices")) PROJECT=`basename $PWD` BETAMC="$CIQ_HOME/bin/monkeyc" BETAVERSION=`"$BETAMC" --version |sed -e 's/.*version //'` echo "Compiling $PROJECT beta releases with $BETAVERSION for various devices" BETAFILE="releases/${PROJECT}-${BETAVERSION}.iq" echo $BETAFILE "$BETAMC" -f beta.jungle -e -y $CIQ_KEYFILE -o ${BETAFILE} for TARGET in "${TARGETS[@]}" do OUTFILE="releases/${PROJECT}-${BETAVERSION}-${TARGET}.prg" echo $OUTFILE "$BETAMC" -f beta.jungle -d ${TARGET} -y $CIQ_KEYFILE -o ${OUTFILE} done echo "Finished!"
<?php namespace App\Http\Controllers; use App\AboutAvard; use App\AboutExperience; use App\AboutHeader; use App\AboutService; use App\Brand; use App\ContactUs; use App\Currency; use App\Faquestion; use App\Group; use App\OneCategory; use App\Post; use App\Service; use App\Product; use App\Folower; use App\QuestionsImage; use App\Subcategory; use Illuminate\Http\Request; use App\OrderingProduct; use Session; class ServiceController extends Controller { /** * Show the application dashboard. * * @return \Illuminate\Contracts\Support\Renderable */ public function index() { $about_faquestions = Faquestion::all(); $about_partners = AboutAvard::all(); $about_service1 = AboutService::where('id', 1)->firstOrFail(); $about_service2 = AboutService::where('id', 2)->firstOrFail(); $about_service3 = AboutService::where('id', 3)->firstOrFail(); $about_service4 = AboutService::where('id', 4)->firstOrFail(); $about_header = AboutHeader::where('id', 1)->firstOrFail(); $about_kids = QuestionsImage::where('id', 1)->firstOrFail(); $contact_us = ContactUs::where('id', 1)->firstOrFail(); $services = Service::all(); $one_categories = OneCategory::all(); $brands = Brand::all(); $blog_post = Post::orderBy('created_at', 'desc')->take(3)->get(); return view('youcan.service')->with([ 'about_service1' => $about_service1, 'about_service2' => $about_service2, 'about_service3' => $about_service3, 'about_service4' => $about_service4, 'about_faquestions' => $about_faquestions, 'about_partners' => $about_partners, 'about_header' => $about_header, 'contact_us' => $contact_us, 'about_kids' => $about_kids, 'blog_post' => $blog_post, 'one_categories' => $one_categories, 'brands' => $brands, 'services' => $services, ]); } public function show($slug) { $popular_posts = Post::inRandomOrder()->take(3)->get(); $blog_images = QuestionsImage::all(); $about_kids = QuestionsImage::where('id', 1)->firstOrFail(); $services = Service::where('slug', $slug)->firstOrFail(); $contact_us = ContactUs::where('id', 1)->firstOrFail(); $one_categories = OneCategory::all(); $brands = Brand::all(); $blog_services = Service::orderBy('created_at', 'desc')->take(3)->get(); $photos = Product::orderBy('created_at', 'desc')->take(9)->get(); return view('youcan.single_service')->with([ 'services' => $services, 'about_kids' => $about_kids, 'popular_posts' => $popular_posts, 'blog_images' => $blog_images, 'contact_us' => $contact_us, 'one_categories' => $one_categories, 'brands' => $brands, 'blog_services' => $blog_services, 'photos' => $photos, ]); } }
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNextGen.Insights.Latest.Inputs { /// <summary> /// Specifies the log search query. /// </summary> public sealed class SourceArgs : Pulumi.ResourceArgs { [Input("authorizedResources")] private InputList<string>? _authorizedResources; /// <summary> /// List of Resource referred into query /// </summary> public InputList<string> AuthorizedResources { get => _authorizedResources ?? (_authorizedResources = new InputList<string>()); set => _authorizedResources = value; } /// <summary> /// The resource uri over which log search query is to be run. /// </summary> [Input("dataSourceId", required: true)] public Input<string> DataSourceId { get; set; } = null!; /// <summary> /// Log search query. Required for action type - AlertingAction /// </summary> [Input("query")] public Input<string>? Query { get; set; } /// <summary> /// Set value to 'ResultCount' . /// </summary> [Input("queryType")] public Input<string>? QueryType { get; set; } public SourceArgs() { } } }
# Running TINC 1.1pre15 inside a Docker container <!-- 2018-08-16 19:30 CEST --> ## References * Docker image sources: <https://github.com/JensErat/docker-tinc> * tinc v1.1 manual: <https://www.tinc-vpn.org/documentation-1.1/> * tinc VPN homepage: <https://www.tinc-vpn.org/> ## Prerequisites * A host running Docker CE 18.03 (called _mynode_ from now on) * Login credentials to the same host (called _user@mynode_ from now on) allowing `sudo` and `docker` commands * A uniquely assigned IP address - For ninux-torino this is something like _10.23.X.Y_ The following instruction have been tested on host `iongmacario` - Host OS: Ubuntu 18.04.1 LTS 64-bit - Assigned IP Address/range: 10.23.3.27/32 ## Install tinc in a Docker container ### Verify prerequisites Login as _user@mynode_ and try running a Docker container ```text gmacario@iongmacario:~$ docker run hello-world Unable to find image 'hello-world:latest' locally latest: Pulling from library/hello-world 9db2ca6ccae0: Pull complete Digest: sha256:4b8ff392a12ed9ea17784bd3c9a8b1fa3299cac44aca35a85c90c5e3c7afacdc Status: Downloaded newer image for hello-world:latest Hello from Docker! This message shows that your installation appears to be working correctly. To generate this message, Docker took the following steps: 1. The Docker client contacted the Docker daemon. 2. The Docker daemon pulled the "hello-world" image from the Docker Hub. (amd64) 3. The Docker daemon created a new container from that image which runs the executable that produces the output you are currently reading. 4. The Docker daemon streamed that output to the Docker client, which sent it to your terminal. To try something more ambitious, you can run an Ubuntu container with: $ docker run -it ubuntu bash Share images, automate workflows, and more with a free Docker ID: https://hub.docker.com/ For more examples and ideas, visit: https://docs.docker.com/engine/userguide/ gmacario@iongmacario:~$ ``` ### Print tinc command line help Login as _user@mynode_ ```shell docker run --rm jenserat/tinc --help ``` ### Prepare the configuration Login as _user@mynode_ Create the TINC configuration file (NOTE: Replace _mynode_ with the actual name of your node): ```shell mkdir -p $HOME/tinc-config docker run --rm --volume $HOME/tinc-config:/etc/tinc jenserat/tinc \ -n ninuxto init mynode ``` Example: ```shell mkdir -p $HOME/tinc-config docker run --rm --volume $HOME/tinc-config:/etc/tinc jenserat/tinc \ -n ninuxto init iongmacario ``` Add known hosts ```shell cd $HOME/tinc-config/ninuxto/hosts sudo chown $USER . curl -O -L https://github.com/gmacario/tinc-ninuxto/raw/master/hosts/rpi3gm23 curl -O -L https://github.com/gmacario/tinc-ninuxto/raw/master/hosts/udooneogm01 sudo chmod 644 * ``` Modify the initial configuration (replace `10.23.X.Y/32` with your assigned IP address / range) ```shell docker run --rm --volume $HOME/tinc-config:/etc/tinc jenserat/tinc \ -n ninuxto add subnet 10.23.X.Y/32 docker run --rm --volume $HOME/tinc-config:/etc/tinc jenserat/tinc \ -n ninuxto add connectto rpi3gm23 docker run --rm --volume $HOME/tinc-config:/etc/tinc jenserat/tinc \ -n ninuxto add connectto udooneogm01 ``` Configure script `$HOME/tinc-config/ninuxto/tinc-up` - (again, replace `10.23.X.Y` with your assigned IP address) ```diff gmacario@iongmacario:~/tinc-config/ninuxto$ diff -uw tinc-up.ORIG tinc-up --- tinc-up.ORIG 2018-08-17 08:06:06.966615850 +0200 +++ tinc-up 2018-08-17 08:06:48.965671907 +0200 @@ -1,5 +1,5 @@ #!/bin/sh -echo 'Unconfigured tinc-up script, please edit '$0'!' +ifconfig $INTERFACE 10.23.X.Y netmask 255.255.0.0 -#ifconfig $INTERFACE <your vpn IP address> netmask <netmask of whole VPN> +# EOF gmacario@iongmacario:~/tinc-config/ninuxto$ ``` TODO: Submit a new <https://github.com/gmacario/tinc-ninuxto/pulls> with the configuration of the new node TODO: Update configuration on peer hosts (rpi3gm23, udooneogm01) to recognize the new node TODO: Start tinc daemon in debug mode ### Start tinc daemon Logged as _user@mynode_ ```shell docker run -d --rm \ --name tinc \ --net=host \ --device=/dev/net/tun \ --cap-add NET_ADMIN \ --volume $HOME/tinc-config:/etc/tinc \ jenserat/tinc \ start -D -n ninuxto -U nobody -d0 ``` TODO: How to ensure the container is restarted when the host is rebooted? ## Runtime commands When the tinc daemon is running in a container you can issue runtime commands as arguments to `docker exec tinc ...` ### Dump reachable nodes <!-- 2018-08-17 07:48 CEST --> Logged as _user@mynode_ ```shell docker exec tinc \ tinc -n ninuxto dump reachable nodes ``` ### Dump network as a digraph <!-- 2018-08-17 08:12 CEST --> Logged as _user@mynode_ ```shell docker exec tinc \ tinc -n ninuxto dump digraph ``` Result: ```json digraph { ardyungm33 [label = "ardyungm33", color = "red"]; chipgm32 [label = "chipgm32", color = "red"]; iongmacario [label = "iongmacario", color = "green", style = "filled"]; itmgmacariow7 [label = "itmgmacariow7", color = "red"]; rpi2gm89 [label = "rpi2gm89", color = "black"]; rpi3gm23 [label = "rpi3gm23", color = "green"]; tincgw21 [label = "tincgw21", color = "black"]; udooneogm01 [label = "udooneogm01", color = "black"]; udooneogm02 [label = "udooneogm02", color = "black"]; iongmacario -> rpi3gm23 [w = 297.542999, weight = 297.542999]; rpi2gm89 -> rpi3gm23 [w = 79.864021, weight = 79.864021]; rpi2gm89 -> tincgw21 [w = 157.410507, weight = 157.410507]; rpi3gm23 -> iongmacario [w = 297.542999, weight = 297.542999]; rpi3gm23 -> rpi2gm89 [w = 79.864021, weight = 79.864021]; rpi3gm23 -> tincgw21 [w = 207.738174, weight = 207.738174]; rpi3gm23 -> udooneogm01 [w = 211.726685, weight = 211.726685]; rpi3gm23 -> udooneogm02 [w = 105.025398, weight = 105.025398]; tincgw21 -> rpi2gm89 [w = 157.410507, weight = 157.410507]; tincgw21 -> rpi3gm23 [w = 207.738174, weight = 207.738174]; tincgw21 -> udooneogm01 [w = 188.782242, weight = 188.782242]; tincgw21 -> udooneogm02 [w = 67.264915, weight = 67.264915]; udooneogm01 -> rpi3gm23 [w = 211.726685, weight = 211.726685]; udooneogm01 -> tincgw21 [w = 188.782242, weight = 188.782242]; udooneogm02 -> rpi3gm23 [w = 105.025398, weight = 105.025398]; udooneogm02 -> tincgw21 [w = 67.264915, weight = 67.264915]; } ``` You can then convert the digraph to a PDF using [Graphviz](http://www.graphviz.org/) ```shell docker exec tinc \ tinc -n ninuxto dump digraph \ | circo -Tpdf >tinc-network.pdf ``` Alternatively view it online with <http://sandbox.kidstrythisathome.com/erdos/> ### Display information about a node Logged as _user@mynode_ ```shell docker exec tinc tinc -n ninuxto info anothernode ``` Example: ```bash gmacario@iongmacario:~/tinc-config/ninuxto$ docker exec tinc tinc -n ninuxto info tincgw21 Node: tincgw21 Node ID: d33bffc03796 Address: 52.58.214.157 port 655 Online since: 2018-08-17 06:07:42 Status: visited reachable Options: pmtu_discovery clamp_mss Protocol: 17.0 Reachability: unknown Edges: rpi2gm89 rpi3gm23 udooneogm01 udooneogm02 Subnets: 10.23.3.21 gmacario@iongmacario:~/tinc-config/ninuxto$ ``` ### Display runtime network statistics Logged as _user@mynode_ ```shell docker exec -ti tinc \ tinc -n ninuxto top ``` <!-- EOF -->
import fs from 'fs'; import path from 'path'; import parser from '../list2JsonParser'; import TxtNode from '../../TxtNode'; function loadMd(path: string): string { const buf = fs.readFileSync(path); return buf.toString(); } test('parse simple md', (): void => { const dir = path.resolve(__dirname, 'md-files', 'simple.md'); // console.log(dir); const md = loadMd(dir); // console.log('===' + md + '==='); const nodeTree: TxtNode[] | null = parser(md); // console.log(nodeTree); expect(nodeTree).not.toBeNull(); if (nodeTree) { expect(nodeTree.length).toBe(4); expect(nodeTree[0].title).toBe('aa'); expect(nodeTree[0].children.length).toBe(0); expect(nodeTree[1].children.length).toBe(2); expect(nodeTree[1].children[0].title).toBe('cc'); expect(nodeTree[1].children[1].title).toBe('dd'); expect(nodeTree[2].title).toBe('ee'); expect(nodeTree[2].children.length).toBe(1); expect(nodeTree[2].children[0].title).toBe('ff'); expect(nodeTree[3].title).toBe('gg'); expect(nodeTree[3].children.length).toBe(1); expect(nodeTree[3].children[0].title).toBe('hh'); expect(nodeTree[3].children[0].children.length).toBe(2); expect(nodeTree[3].children[0].children[0].title).toBe('ii'); expect(nodeTree[3].children[0].children[0].children.length).toBe(1); expect(nodeTree[3].children[0].children[0].children[0].title).toBe('jj'); expect(nodeTree[3].children[0].children[1].title).toBe('kk'); } }); test('parse tab and space mix md', (): void => { const dir = path.resolve(__dirname, 'md-files', 'tab-space-mix.md'); // console.log(dir); const md = loadMd(dir); // console.log('===' + md + '==='); const nodeTree: TxtNode[] | null = parser(md); // console.log(nodeTree); expect(nodeTree).not.toBeNull(); if (nodeTree) { expect(nodeTree.length).toBe(4); expect(nodeTree[0].title).toBe('aa'); expect(nodeTree[0].children.length).toBe(0); // console.log(nodeTree[1].children); expect(nodeTree[1].children[0].children[0].title).toBe('tab01'); // tab02 行是前置 3 个空格 + 1 个 tab expect(nodeTree[1].children[1].children[0].title).toBe('tab02'); expect(nodeTree[1].children[1].children[0].children[0].title).toBe('tab03'); } }); test('parse complex list to json', (): void => { const dir = path.resolve(__dirname, 'md-files', 'complex.md'); // console.log(dir); const md = loadMd(dir); // console.log('===' + md + '==='); const nodeTree: TxtNode[] | null = parser(md); // console.log(nodeTree); expect(nodeTree).not.toBeNull(); if (nodeTree) { expect(nodeTree.length).toBe(3); expect(nodeTree[0].children.length).toBe(2); expect(nodeTree[0].children[0].children.length).toBe(2); expect(nodeTree[0].children[0].children[1].children.length).toBe(2); expect(nodeTree[0].title).toBe('00'); expect(nodeTree[0].children[0].title).toBe('10'); expect(nodeTree[0].children[1].title).toBe('11'); expect(nodeTree[0].children[0].children[1].children[0].title).toBe('30'); expect(nodeTree[0].children[0].children[1].children[1].title).toBe('40'); expect(nodeTree[1].title).toBe('01'); expect(nodeTree[2].title).toBe('02'); } }); test('level md file', (): void => { const dir = path.resolve(__dirname, 'md-files', 'level.md'); // console.log(dir); const md = loadMd(dir); // console.log('===' + md + '==='); const nodeTree: TxtNode[] | null = parser(md); // console.log(nodeTree); expect(nodeTree).not.toBeNull(); if (nodeTree) { // console.log(nodeTree[0].children); expect(nodeTree[0].title).toBe('level1'); expect(nodeTree[0].rawTitle).toBe('level1'); expect(nodeTree[0].children[0].title).toBe('l11'); expect(nodeTree[0].children[0].rawTitle).toBe('l11.txt'); expect(nodeTree[0].children[1].title).toBe('l12'); expect(nodeTree[0].children[1].rawTitle).toBe('level1/l12.md'); } });
<?php namespace App\Services; use App\CarouselSlide; use App\Http\Requests\CreateCarouselSlideRequest; use App\Http\Requests\EditCarouselSlideRequest; use App\Http\Requests\OrderCarouselSlidesRequest; use Illuminate\Support\Facades\DB; class CarouselSlideService { function findById($id) { $slide = CarouselSlide::find($id); if (!$slide) { abort(404); } return $slide; } function getAll() { return CarouselSlide::ordered()->get(); } function setNewOrder(OrderCarouselSlidesRequest $request) { CarouselSlide::setNewOrder($request->input('carousel_slides_order')); } function create(CreateCarouselSlideRequest $request) { return DB::transaction(function () use ($request) { $slide = CarouselSlide::create([ 'label' => $request->input('label'), ]); $slide->addMediaFromRequest('photo')->toMediaCollection('photos'); return $slide; }); } function update(CarouselSlide $slide, EditCarouselSlideRequest $request) { $slide->label = $request->input('label'); if ($request->hasFile('photo')) { $slide->clearMediaCollection('photos'); $slide->addMediaFromRequest('photo')->toMediaCollection('photos'); } $slide->save(); } }
module Parser where import Control.Applicative ((<|>)) import Expression (getExpr) import Grammar import Lexer (char, double, integer) import ParserLib (Parser, many) import Token (Token (..)) expression :: Parser Expression expression = getExpr <$> tokens token :: Parser Token token = (double >>= \d -> return (ConstD_T d)) <|> (integer >>= \i -> return (ConstI_T i)) <|> (char '+' >> return (Binop_T ADD)) <|> (char '-' >> return (Binop_T SUB)) <|> (char '*' >> return (Binop_T MUL)) <|> (char '/' >> return (Binop_T DIV)) <|> (char '^' >> return (Binop_T EXP)) <|> (char '%' >> return (Binop_T MOD)) <|> (char '(' >> return LParen_T) <|> (char ')' >> return RParen_T) tokens :: Parser [Token] tokens = many token
use vcell::VolatileCell; #[doc = r" Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - GPIO port mode register"] pub moder: Moder, #[doc = "0x04 - GPIO port output type register"] pub otyper: Otyper, #[doc = "0x08 - GPIO port output speed register"] pub ospeedr: Ospeedr, #[doc = "0x0c - GPIO port pull-up/pull-down register"] pub pupdr: Pupdr, #[doc = "0x10 - GPIO port input data register"] pub idr: Idr, #[doc = "0x14 - GPIO port output data register"] pub odr: Odr, #[doc = "0x18 - GPIO port bit set/reset register"] pub bsrr: Bsrr, #[doc = "0x1c - GPIO port configuration lock register"] pub lckr: Lckr, #[doc = "0x20 - GPIO alternate function low register"] pub afrl: Afrl, #[doc = "0x24 - GPIO alternate function high register"] pub afrh: Afrh, } #[doc = "GPIO port mode register"] pub struct Moder { register: VolatileCell<u32>, } #[doc = "GPIO port mode register"] pub mod moder; #[doc = "GPIO port output type register"] pub struct Otyper { register: VolatileCell<u32>, } #[doc = "GPIO port output type register"] pub mod otyper; #[doc = "GPIO port output speed register"] pub struct Ospeedr { register: VolatileCell<u32>, } #[doc = "GPIO port output speed register"] pub mod ospeedr; #[doc = "GPIO port pull-up/pull-down register"] pub struct Pupdr { register: VolatileCell<u32>, } #[doc = "GPIO port pull-up/pull-down register"] pub mod pupdr; #[doc = "GPIO port input data register"] pub struct Idr { register: VolatileCell<u32>, } #[doc = "GPIO port input data register"] pub mod idr; #[doc = "GPIO port output data register"] pub struct Odr { register: VolatileCell<u32>, } #[doc = "GPIO port output data register"] pub mod odr; #[doc = "GPIO port bit set/reset register"] pub struct Bsrr { register: VolatileCell<u32>, } #[doc = "GPIO port bit set/reset register"] pub mod bsrr; #[doc = "GPIO port configuration lock register"] pub struct Lckr { register: VolatileCell<u32>, } #[doc = "GPIO port configuration lock register"] pub mod lckr; #[doc = "GPIO alternate function low register"] pub struct Afrl { register: VolatileCell<u32>, } #[doc = "GPIO alternate function low register"] pub mod afrl; #[doc = "GPIO alternate function high register"] pub struct Afrh { register: VolatileCell<u32>, } #[doc = "GPIO alternate function high register"] pub mod afrh;
<?php session_start(); if (!isset($_SESSION['UserFullName'])) { header("location: index.php"); } $questions = $_SESSION['questions']; $answers = $_SESSION['answers']; $numberOfQuestions = count($questions); $numberOfCorrectAnswers = 0; $connection = mysqli_connect("localhost", "root", "", "toefl") or die("Connection Error ".mysqli_error($connection)); for ($i = 0; $i < $numberOfQuestions; $i++) { $q = $questions[$i]; $sql = "SELECT correct_option_id FROM answers WHERE question_id = $q"; $result = $connection->query($sql) or die(mysqli_error($connection)); $row = mysqli_fetch_array($result); $a = $row['correct_option_id']; if ($a == $answers[$i]) { $numberOfCorrectAnswers++; } } $score = (100 * $numberOfCorrectAnswers) / $numberOfQuestions; session_destroy(); ?> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta http-equiv="Content-Language" content="en" /> <link rel="stylesheet" type="text/css" href="style.css" /> <title>Free Online Practice Test</title> </head> <body> <?php include_once('header.php'); ?> <div id="content" class="content-width-wrapper"> <h2>Time out!</h2> <br /><br /><br /> <h3><?php echo $_SESSION['UserFullName']; ?></h3> <h3>Your Score is: <?php echo $score; ?>%</h3> </div> </body> </html>
prompt - type drs_customer_t (row) create or replace type drs_customer_t as object ( customer_id integer, first_name varchar2(45 char), last_name varchar2(45 char), email varchar2(50 char), address drs_address_t, active char(1 byte), create_date date, last_update date ); / prompt - type drs_customers_t (tab) create or replace type drs_customers_t as table of drs_customer_t; /
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoMonomorphismRestriction #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE ViewPatterns #-} module Language.Rsc.Transformations ( Transformable (..), NameTransformable (..), AnnotTransformable (..) , transFmap, ntransFmap, ntransPure , emapReft, mapReftM , replaceDotRef , replaceAbsolute , fixFunBinders ) where import Control.Arrow ((***)) import Control.Monad.State.Strict import Data.Default import Data.Functor.Identity import Data.Generics import qualified Data.HashSet as HS import qualified Data.IntMap.Strict as I import Data.List (find) import Data.Text (pack, splitOn) import qualified Data.Traversable as T import qualified Language.Fixpoint.Types as F import Language.Fixpoint.Types.Errors import Language.Fixpoint.Types.Names (suffixSymbol, symbolString) import qualified Language.Fixpoint.Types.Visitor as FV import Language.Rsc.Annotations import Language.Rsc.AST import Language.Rsc.Core.Env import Language.Rsc.Errors import Language.Rsc.Locations import Language.Rsc.Misc import Language.Rsc.Module import Language.Rsc.Names import Language.Rsc.Pretty import Language.Rsc.Program import Language.Rsc.Symbols import Language.Rsc.Traversals import Language.Rsc.Typecheck.Types import Language.Rsc.Types import Language.Rsc.Visitor -------------------------------------------------------------------------------- -- | Transformable -------------------------------------------------------------------------------- class Transformable t where trans :: F.Reftable r => ([TVar] -> [BindQ q r] -> RTypeQ q r -> RTypeQ q r) -> [TVar] -> [BindQ q r] -> t q r -> t q r instance Transformable RTypeQ where trans = transRType instance Transformable BindQ where trans f αs xs b = b { b_type = trans f αs xs $ b_type b } instance Transformable FactQ where trans = transFact instance Transformable TypeDeclQ where trans f αs xs (TD s@(TS _ b _) p es) = TD (trans f αs xs s) p (trans f αs' xs es) where αs' = map btvToTV (b_args b) ++ αs instance Transformable TypeSigQ where trans f αs xs (TS k b h) = TS k (trans f αs xs b) (transIFDBase f αs' xs h) where αs' = map btvToTV (b_args b) ++ αs instance Transformable TypeMembersQ where trans f αs xs (TM m sm c k s n) = TM (fmap g m) (fmap g sm) (fmap g c) (fmap g k) (fmap (g *** g) s) (fmap (g *** g) n) where g = trans f αs xs instance Transformable BTGenQ where trans f αs xs (BGen n ts) = BGen n $ trans f αs xs <$> ts instance Transformable TGenQ where trans f αs xs (Gen n ts) = Gen n $ trans f αs xs <$> ts instance Transformable BTVarQ where trans f αs xs (BTV x l c) = BTV x l $ trans f αs xs <$> c instance Transformable TypeMemberQ where trans f αs xs (FI n o a t') = FI n o (trans f αs xs a) (trans f αs xs t') trans f αs xs (MI n o mts) = MI n o (mapSnd (trans f αs xs) <$> mts) instance Transformable ModuleDefQ where trans f αs xs (ModuleDef v t e p) = ModuleDef (envMap (trans f αs xs) v) (envMap (trans f αs xs) t) e p instance Transformable SymInfoQ where trans f αs xs (SI x l a t) = SI x l a $ trans f αs xs t instance Transformable FAnnQ where trans f αs xs (FA i s ys) = FA i s $ trans f αs xs <$> ys transFmap :: (F.Reftable r, Functor thing) => ([TVar] -> [BindQ q r] -> RTypeQ q r -> RTypeQ q r) -> [TVar] -> thing (FAnnQ q r) -> thing (FAnnQ q r) transFmap f αs = fmap (trans f αs []) transIFDBase f αs xs (es,is) = (trans f αs xs <$> es, trans f αs xs <$> is) transFact :: F.Reftable r => ([TVar] -> [BindQ q r] -> RTypeQ q r -> RTypeQ q r) -> [TVar] -> [BindQ q r] -> FactQ q r -> FactQ q r transFact f = go where go αs xs (TypInst x y ts) = TypInst x y $ trans f αs xs <$> ts go αs xs (EltOverload x m t) = EltOverload x (trans f αs xs m) (trans f αs xs t) go αs xs (VarAnn x l a t) = VarAnn x l a $ trans f αs xs <$> t go αs xs (MemberAnn t) = MemberAnn $ trans f αs xs t go αs xs (CtorAnn t) = CtorAnn $ trans f αs xs t go αs xs (UserCast t) = UserCast $ trans f αs xs t go αs xs (SigAnn x l t) = SigAnn x l $ trans f αs xs t go αs xs (ClassAnn l ts) = ClassAnn l $ trans f αs xs ts go αs xs (ClassInvAnn r) = ClassInvAnn $ rTypeR -- PV: a little indirect $ trans f αs xs $ tVoid `strengthen` r go αs xs (InterfaceAnn td) = InterfaceAnn $ trans f αs xs td go _ _ t = t -- | transRType : -- -- Binds (αs and bs) accumulate on the left. -- transRType :: F.Reftable r => ([TVar] -> [BindQ q r] -> RTypeQ q r -> RTypeQ q r) -> [TVar] -> [BindQ q r] -> RTypeQ q r -> RTypeQ q r transRType f = go where go αs xs (TPrim c r) = f αs xs $ TPrim c r go αs xs (TVar v r) = f αs xs $ TVar v r go αs xs (TOr ts r) = f αs xs $ TOr ts' r where ts' = go αs xs <$> ts go αs xs (TAnd ts) = f αs xs $ TAnd ts' where ts' = mapSnd (go αs xs) <$> ts go αs xs (TRef n r) = f αs xs $ TRef n' r where n' = trans f αs xs n go αs xs (TObj m ms r) = f αs xs $ TObj m' ms' r where m' = trans f αs xs m ms' = trans f αs xs ms go αs xs (TClass n) = f αs xs $ TClass n' where n' = trans f αs xs n go αs xs (TMod m) = f αs xs $ TMod m go αs xs (TAll a t) = f αs xs $ TAll a' t' where a' = trans f αs xs a t' = go αs' xs t αs' = αs ++ [btvToTV a] go αs xs (TFun bs t r) = f αs xs $ TFun bs' t' r where bs' = trans f αs xs' <$> bs t' = go αs xs' t xs' = bs ++ xs go _ _ (TExp e) = TExp e -------------------------------------------------------------------------------- -- | Transform names -------------------------------------------------------------------------------- ntransPure :: (NameTransformable t, F.Reftable r) => (QN p -> QN q) -> (QP p -> QP q) -> t p r -> t q r ntransPure f g a = runIdentity (ntrans f' g' a) where g' = return . g f' = return . f class NameTransformable t where ntrans :: (Monad m, Applicative m, F.Reftable r) => (QN p -> m (QN q)) -> (QP p -> m (QP q)) -> t p r -> m (t q r) instance NameTransformable RTypeQ where ntrans = ntransRType instance NameTransformable BindQ where ntrans f g (B s o t) = B s o <$> ntrans f g t instance NameTransformable FactQ where ntrans = ntransFact instance NameTransformable TypeDeclQ where ntrans f g (TD s p m) = TD <$> ntrans f g s <*> pure p <*> ntrans f g m instance NameTransformable TypeSigQ where ntrans f g (TS k b (e,i)) = TS k <$> ntrans f g b <*> liftM2 (,) (mapM (ntrans f g) e) (mapM (ntrans f g) i) instance NameTransformable TypeMembersQ where ntrans f g (TM m sm c k s n) = TM <$> T.mapM h m <*> T.mapM h sm <*> T.mapM h c <*> T.mapM h k <*> T.mapM (\(m_, t_) -> (,) <$> h m_ <*> h t_) s <*> T.mapM (\(m_, t_) -> (,) <$> h m_ <*> h t_) n where h = ntrans f g instance NameTransformable BTGenQ where ntrans f g (BGen n ts) = BGen <$> f n <*> mapM (ntrans f g) ts instance NameTransformable TGenQ where ntrans f g (Gen n ts) = Gen <$> f n <*> mapM (ntrans f g) ts instance NameTransformable BTVarQ where ntrans f g (BTV x l c) = BTV x l <$> T.mapM (ntrans f g) c instance NameTransformable TypeMemberQ where ntrans f g (FI x o m t) = FI x o <$> ntrans f g m <*> ntrans f g t ntrans f g (MI x o mts) = MI x o <$> mapM (mapPairM (ntrans f g) (ntrans f g)) mts ntransFmap :: (F.Reftable r, Applicative m, Monad m, T.Traversable t) => (QN p -> m (QN q)) -> (QP p -> m (QP q)) -> t (FAnnQ p r) -> m (t (FAnnQ q r)) ntransFmap f g x = T.mapM (ntrans f g) x ntransFact f g = go where go (PhiVar v) = pure $ PhiVar v go (PhiLoopTC v) = pure $ PhiLoopTC v go (PhiLoop xs) = pure $ PhiLoop xs go (Overload x m i) = pure $ Overload x m i go (EnumAnn e) = pure $ EnumAnn e go (BypassUnique) = pure $ BypassUnique go (DeadCast x es) = pure $ DeadCast x es go (TypeCast x t) = pure $ TypeCast x t -- TODO: transform this? go (ClassInvAnn r) = pure $ ClassInvAnn r go (ModuleAnn l m) = ModuleAnn l <$> g m go (TypInst x y ts) = TypInst x y <$> mapM (ntrans f g) ts go (EltOverload x m t) = EltOverload x <$> ntrans f g m <*> ntrans f g t go (VarAnn x l a t) = VarAnn x l a <$> T.mapM (ntrans f g) t go (MemberAnn t) = MemberAnn <$> ntrans f g t go (CtorAnn t) = CtorAnn <$> ntrans f g t go (UserCast t) = UserCast <$> ntrans f g t go (SigAnn x l t) = SigAnn x l <$> ntrans f g t go (ClassAnn l t) = ClassAnn l <$> ntrans f g t go (InterfaceAnn t) = InterfaceAnn <$> ntrans f g t ntransRType :: (Monad m, Applicative m, F.Reftable r) => (QN p -> m (QN q)) -> (QP p -> m (QP q)) -> RTypeQ p r -> m (RTypeQ q r) ntransRType f g t = go t where go (TPrim p r) = pure $ TPrim p r go (TVar v r) = pure $ TVar v r go (TExp e) = pure $ TExp e go (TOr ts r) = TOr <$> ts' <*> pure r where ts' = mapM go ts go (TAnd ts) = TAnd <$> ts' where ts' = mapM (mapSndM go) ts go (TRef n r) = TRef <$> n' <*> pure r where n' = ntrans f g n go (TObj m ms r) = TObj <$> m' <*> ms' <*> pure r where m' = ntrans f g m ms' = ntrans f g ms go (TClass n) = TClass <$> n' where n' = ntrans f g n go (TMod p) = TMod <$> p' where p' = g p go (TAll a t) = TAll <$> a' <*> t' where a' = ntrans f g a t' = go t go (TFun bs t r) = TFun <$> bs' <*> t' <*> pure r where bs' = mapM (ntrans f g) bs t' = go t instance NameTransformable FAnnQ where ntrans f g (FA i s ys) = FA i s <$> mapM (ntrans f g) ys -------------------------------------------------------------------------------- -- | Transformers over @RType@ -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- emapReft :: PPR r => ([F.Symbol] -> r -> r') -> [F.Symbol] -> RTypeQ q r -> RTypeQ q r' -------------------------------------------------------------------------------- emapReft f γ (TVar α r) = TVar α (f γ r) emapReft f γ (TPrim c r) = TPrim c (f γ r) emapReft f γ (TRef n r) = TRef (emapReftGen f γ n) (f γ r) emapReft f γ (TAll α t) = TAll (emapReftBTV f γ α) (emapReft f γ t) emapReft f γ (TFun xts t r) = TFun (emapReftBind f γ' <$> xts) (emapReft f γ' t) (f γ r) where γ' = (b_sym <$> xts) ++ γ emapReft f γ (TObj m xts r) = TObj (emapReft f γ m) (emapReftTM f γ xts) (f γ r) emapReft f γ (TClass n) = TClass (emapReftBGen f γ n) emapReft _ _ (TMod m) = TMod m emapReft f γ (TOr ts r) = TOr (emapReft f γ <$> ts) (f γ r) emapReft f γ (TAnd ts) = TAnd (mapSnd (emapReft f γ) <$> ts) emapReft _ _ _ = error "Not supported in emapReft" emapReftBTV f γ (BTV s l c) = BTV s l $ emapReft f γ <$> c emapReftGen f γ (Gen n ts) = Gen n $ emapReft f γ <$> ts emapReftBGen f γ (BGen n ts) = BGen n $ emapReftBTV f γ <$> ts emapReftBind f γ (B x o t) = B x o $ emapReft f γ t emapReftTM f γ (TM m sm c k s n) = TM (fmap (emapReftElt f γ) m) (fmap (emapReftElt f γ) sm) (emapReft f γ <$> c) (emapReft f γ <$> k) ((emapReft f γ *** emapReft f γ) <$> s) ((emapReft f γ *** emapReft f γ) <$> n) emapReftElt f γ (FI x m a t) = FI x m (emapReft f γ a) (emapReft f γ t) emapReftElt f γ (MI x m mts) = MI x m (mapPair (emapReft f γ) <$> mts) -------------------------------------------------------------------------------- mapReftM :: (F.Reftable r, PP r, Applicative m, Monad m) => (r -> m r') -> RTypeQ q r -> m (RTypeQ q r') -------------------------------------------------------------------------------- mapReftM f (TVar α r) = TVar α <$> f r mapReftM f (TPrim c r) = TPrim c <$> f r mapReftM f (TRef n r) = TRef <$> mapReftGenM f n <*> f r mapReftM f (TFun xts t r) = TFun <$> mapM (mapReftBindM f) xts <*> mapReftM f t <*> f r mapReftM f (TAll α t) = TAll <$> mapReftBTV f α <*> mapReftM f t mapReftM f (TAnd ts) = TAnd <$> mapM (mapSndM (mapReftM f)) ts mapReftM f (TOr ts r) = TOr <$> mapM (mapReftM f) ts <*> f r mapReftM f (TObj m xts r) = TObj <$> mapReftM f m <*> mapTypeMembers f xts <*> f r mapReftM f (TClass n) = TClass <$> mapReftBGenM f n mapReftM _ (TMod a) = TMod <$> pure a mapReftM _ t = error $ "Not supported in mapReftM: " ++ ppshow t mapReftBTV f (BTV s l c) = BTV s l <$> T.mapM (mapReftM f) c mapReftGenM f (Gen n ts) = Gen n <$> mapM (mapReftM f) ts mapReftBGenM f (BGen n ts) = BGen n <$> mapM (mapReftBTV f) ts mapReftBindM f (B x o t) = B x o <$> mapReftM f t mapTypeMembers f (TM m sm c k s n) = TM <$> T.mapM (mapReftElt f) m <*> T.mapM (mapReftElt f) sm <*> T.mapM (mapReftM f) c <*> T.mapM (mapReftM f) k <*> T.mapM (\(m_,t_) -> (,) <$> mapReftM f m_ <*> mapReftM f t_) s <*> T.mapM (\(m_,t_) -> (,) <$> mapReftM f m_ <*> mapReftM f t_) n mapReftElt f (FI x m a t) = FI x m <$> mapReftM f a <*> mapReftM f t mapReftElt f (MI x m mts) = MI x m <$> mapM (mapPairM (mapReftM f) (mapReftM f)) mts -------------------------------------------------------------------------------- -- | Replace all relatively qualified names/paths with absolute ones. -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- replaceAbsolute :: (PPR r, Data r, Typeable r) => BareRelRsc r -> Either [Error] (BareRsc r) -------------------------------------------------------------------------------- replaceAbsolute pgm@(Rsc { code = Src ss }) = case sOut of [] -> Right (pgm { code = Src ss' }) _ -> Left sOut where (ss', sOut) = runState (mapM (T.mapM (\l -> ntrans (safeAbsName l) (safeAbsPath l) l)) ss) [] (ns, ps) = accumNamesAndPaths ss safeAbsName l a@(absAct (absoluteName ns) l -> n) | Just a' <- n = return a' | Nothing <- n , isAlias a = return $ toAbsoluteName a | otherwise = modify (errorUnboundName (srcPos l) a:) >> pure (mkAbsName [] a) safeAbsPath l a@(absAct (absolutePath ps) l -> n) | Just a' <- n = return a' | otherwise = modify (errorUnboundPath (srcPos l) a:) >> pure (mkAbsPath []) isAlias (QN (QP RK_ _ []) s) = envMem s $ tAlias pgm isAlias (QN _ _) = False absAct f l a = I.lookup (fId l) mm >>= (`f` a) mm = snd $ visitStmts vs (QP AK_ def []) ss vs = defaultVisitor { ctxStmt = cStmt } { accStmt = acc } { accExpr = acc } { accCElt = acc } { accVDec = acc } cStmt (QP AK_ l p) (ModuleStmt _ x _) = QP AK_ l $ p ++ [F.symbol x] cStmt q _ = q acc c s = I.singleton (fId a) c where a = getAnnotation s -------------------------------------------------------------------------------- -- | Replace `a.b.c...z` with `offset(offset(...(offset(a),"b"),"c"),...,"z")` -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- replaceDotRef :: RefScript -> RefScript -------------------------------------------------------------------------------- replaceDotRef p@(Rsc { code = Src fs, tAlias = ta, pAlias = pa, invts = is }) = p { code = Src $ tf <##> fs , tAlias = trans tt [] [] <###> ta , pAlias = tt [] [] <##> pa , invts = trans tt [] [] <##> is } where tf (FA l a facts) = FA l a (map (trans tt [] []) facts) tt _ _ = fmap $ FV.trans vs () () vs = FV.defaultVisitor { FV.txExpr = tx } tx _ (F.EVar s) | (x:y:zs) <- pack "." `splitOn` pack (symbolString s) = foldl offset (F.eVar x) (y:zs) tx _ e = e offset k v = F.mkEApp offsetLocSym [F.expr k, F.expr v] -- -- XXX: Treat this at lookup -- -- -------------------------------------------------------------------------------- -- -- | Replace `TRef x _ _` where `x` is a name for an enumeration with `number` -- -------------------------------------------------------------------------------- -- -- -------------------------------------------------------------------------------- -- fixEnums :: PPR r => QEnv (ModuleDef r) -> BareRsc r -> (QEnv (ModuleDef r), BareRsc r) -- -------------------------------------------------------------------------------- -- fixEnums m p@(Rsc { code = Src ss }) = (m',p') -- where -- p' = p { code = Src $ (trans f [] [] <$>) <$> ss } -- m' = fixEnumsInModule m `qenvMap` m -- f _ _ = fixEnumInType m -- -- fixEnumInType :: F.Reftable r => QEnv (ModuleDef r) -> RType r -> RType r -- fixEnumInType ms (TRef (Gen (QN p x) []) r) -- | Just m <- qenvFindTy p ms -- , Just e <- envFindTy x $ m_enums m -- = if isBvEnum e then tBV32 `strengthen` r -- else tNum `strengthen` r -- fixEnumInType _ t = t -- -- fixEnumsInModule :: F.Reftable r => QEnv (ModuleDef r) -> ModuleDef r -> ModuleDef r -- fixEnumsInModule m = trans (const $ const $ fixEnumInType m) [] [] -- -------------------------------------------------------------------------------- -- | Add a '#' at the end of every function binder (to avoid capture) -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- fixFunBinders :: RefScript -> RefScript -------------------------------------------------------------------------------- fixFunBinders p@(Rsc { code = Src ss }) = p' where p' = p { code = Src $ (trans fixFunBindersInType [] [] <$>) <$> ss } fixFunBindersInType _ bs = go where ks = [ y | B y _ _ <- bs ] ss = (`suffixSymbol` F.symbol "") ks' = map (F.eVar . ss) ks sub :: F.Subable a => a -> a sub = F.subst (F.mkSubst (zip ks ks')) go (TFun bs t r) = TFun [B (ss s) o ts | B s o ts <- bs] t (sub r) go t = toplevel sub t -- When costructing the substitution haskmap, if the list contains duplicate -- mappings, the later mappings take precedence. -------------------------------------------------------------------------------- -- | Spec Transformer -------------------------------------------------------------------------------- class AnnotTransformable t where strans :: (ctx -> a -> b) -> (ctx -> b -> ctx) -> ctx -> t a -> t b instance AnnotTransformable Statement where strans = stransStatement instance AnnotTransformable Expression where strans = stransExpression instance AnnotTransformable Id where strans = stransId instance AnnotTransformable ForInInit where strans = stransForInInit instance AnnotTransformable ForInit where strans = stransForInit instance AnnotTransformable CatchClause where strans = stransCatchClause instance AnnotTransformable VarDecl where strans = stransVarDecl instance AnnotTransformable ClassElt where strans = stransClassElt instance AnnotTransformable EnumElt where strans = stransEnumElt instance AnnotTransformable Prop where strans = stransProp instance AnnotTransformable LValue where strans = stransLvalue stransStatement f g ctx st = go st where a = getAnnotation st b = f ctx a ctx' = g ctx b ss = strans f g ctx' go (BlockStmt _ sts) = BlockStmt b (ss <$> sts) go (EmptyStmt _) = EmptyStmt b go (ExprStmt _ e) = ExprStmt b (ss e) go (IfStmt _ e s1 s2) = IfStmt b (ss e) (ss s1) (ss s2) go (IfSingleStmt _ e s) = IfSingleStmt b (ss e) (ss s) go (WhileStmt _ e s) = WhileStmt b (ss e) (ss s) go (DoWhileStmt _ s e) = DoWhileStmt b (ss s) (ss e) go (BreakStmt _ i) = BreakStmt b (ss <$> i) go (ContinueStmt _ i) = ContinueStmt b (ss <$> i) go (LabelledStmt _ i s) = LabelledStmt b (ss i) (ss s) go (ForInStmt _ fi e s) = ForInStmt b (ss fi) (ss e) (ss s) go (ForStmt _ fi me1 me2 s) = ForStmt b (ss fi) (ss <$> me1) (ss <$> me2) (ss s) go (TryStmt _ s mcc ms) = TryStmt b (ss s) (ss <$> mcc) (ss <$> ms) go (ThrowStmt _ e) = ThrowStmt b (ss e) go (ReturnStmt _ me) = ReturnStmt b (ss <$> me) go (WithStmt _ e s) = WithStmt b (ss e) (ss s) go (VarDeclStmt _ vs) = VarDeclStmt b (ss <$> vs) go (FunctionStmt _ i is mss) = FunctionStmt b (ss i) (ss <$> is) ((ss <$>) <$> mss) go (ClassStmt _ i cs) = ClassStmt b (ss i) (ss <$> cs) go (ModuleStmt _ i sts) = ModuleStmt b (ss i) (ss <$> sts) go (InterfaceStmt _ i) = InterfaceStmt b (ss i) go (EnumStmt _ i es) = EnumStmt b (ss i) (ss <$> es) go s = error $ "[unimplemented] stransStatement for " ++ ppshow s stransExpression f g ctx exp = go exp where a = getAnnotation exp b = f ctx a ctx' = g ctx b ss = strans f g ctx' go (StringLit _ s) = StringLit b s go (RegexpLit _ s b1 b2) = RegexpLit b s b1 b2 go (NumLit _ d) = NumLit b d go (IntLit _ i) = IntLit b i go (BoolLit _ bl) = BoolLit b bl go (NullLit _) = NullLit b go (ArrayLit _ es) = ArrayLit b (ss <$> es) go (ObjectLit _ pes) = ObjectLit b ((\(p,e) -> (ss p, ss e)) <$> pes) go (HexLit _ s) = HexLit b s go (ThisRef _) = ThisRef b go (VarRef _ i) = VarRef b (ss i) go (DotRef _ e i) = DotRef b (ss e) (ss i) go (BracketRef _ e1 e2) = BracketRef b (ss e1) (ss e2) go (NewExpr _ e es) = NewExpr b (ss e) (ss <$> es) go (PrefixExpr _ op e) = PrefixExpr b op (ss e) go (UnaryAssignExpr _ op l) = UnaryAssignExpr b op (ss l) go (InfixExpr _ op e1 e2) = InfixExpr b op (ss e1) (ss e2) go (CondExpr _ e1 e2 e3) = CondExpr b (ss e1) (ss e2) (ss e3) go (AssignExpr _ op l e) = AssignExpr b op (ss l) (ss e) go (ListExpr _ es) = ListExpr b (ss <$> es) go (CallExpr _ e es) = CallExpr b (ss e) (ss <$> es) go (SuperRef _) = SuperRef b go (FuncExpr _ mi is sts) = FuncExpr b (ss <$> mi) (ss <$> is) (ss <$> sts) go (Cast _ e) = Cast b (ss e) go (Cast_ _ e) = Cast_ b (ss e) stransId f _ ctx (Id a s) = Id (f ctx a) s stransForInInit f g ctx (ForInVar i) = ForInVar (strans f g ctx i) stransForInInit f g ctx (ForInLVal i) = ForInLVal (strans f g ctx i) stransForInit _ _ _ NoInit = NoInit stransForInit f g ctx (VarInit vs) = VarInit (strans f g ctx <$> vs) stransForInit f g ctx (ExprInit e) = ExprInit (strans f g ctx e) stransCatchClause f g ctx (CatchClause a i s) = CatchClause b (ss i) (ss s) where b = f ctx a ctx' = g ctx b ss = strans f g ctx' stransVarDecl f g ctx (VarDecl a i me) = VarDecl b (ss i) (ss <$> me) where b = f ctx a ctx' = g ctx b ss = strans f g ctx' stransClassElt f g ctx ce = go ce where a = getAnnotation ce b = f ctx a ctx' = g ctx b ss = strans f g ctx' go (Constructor _ is sts) = Constructor b (ss <$> is) (ss <$> sts) go (MemberVarDecl _ st i me) = MemberVarDecl b st (ss i) (ss <$> me) go (MemberMethDecl _ st i is sts) = MemberMethDecl b st (ss i) (ss <$> is) (ss <$> sts) stransEnumElt f g ctx (EnumElt a i e) = EnumElt b (ss i) (ss e) where b = f ctx a ctx' = g ctx b ss = strans f g ctx' stransProp f g ctx p = go p where a = getAnnotation p b = f ctx a ctx' = g ctx b ss = strans f g ctx' go (PropId _ i) = PropId b (ss i) go (PropString _ s) = PropString b s go (PropNum _ i) = PropNum b i stransLvalue f g ctx lv = go lv where a = getAnnotation lv b = f ctx a ctx' = g ctx b ss = strans f g ctx' go (LVar _ s) = LVar b s go (LDot _ e s) = LDot b (ss e) s go (LBracket _ e1 e2) = LBracket b (ss e1) (ss e2) -------------------------------------------------------------------------- -- | Name transformation -------------------------------------------------------------------------- -- | `absoluteName env p r` returns `Just a` where `a` is the absolute path of -- the relative name `r` when referenced in the context of the absolute path -- `p`; `Nothing` otherwise. -- -- If p = A.B.C and r = C.D.E then the paths that will be checked in this -- order are: -- -- A.B.C.C.D.E -- A.B.C.D.E -- A.C.D.E -- C.D.E -- --------------------------------------------------------------------------------- absoluteName :: HS.HashSet AbsName -> AbsPath -> RelName -> Maybe AbsName --------------------------------------------------------------------------------- absoluteName ns (QP AK_ _ p) (QN (QP RK_ _ ss) s) = find (`HS.member` ns) $ (`mkAbsName` s) . (++ ss) <$> prefixes p where prefixes = map reverse . suffixes . reverse suffixes [] = [[]] suffixes (x:xs) = (x:xs) : suffixes xs --------------------------------------------------------------------------------- absolutePath :: HS.HashSet AbsPath -> AbsPath -> RelPath -> Maybe AbsPath --------------------------------------------------------------------------------- absolutePath ps (QP AK_ _ p) (QP RK_ _ ss) = find (`HS.member` ps) $ mkAbsPath . (++ ss) <$> prefixes p where prefixes = map reverse . suffixes . reverse suffixes [] = [[]] suffixes (x:xs) = (x:xs) : suffixes xs toAbsoluteName (QN (QP RK_ l ss) s) = QN (QP AK_ l ss) s
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using CP77.CR2W.Types; namespace CP77.CR2W { public static class CR2WReaderExtensions { /// <summary> /// Read null terminated string /// </summary> /// <param name="file">Reader</param> /// <param name="len">Fixed length string</param> /// <returns>string</returns> public static string ReadCR2WString(this BinaryReader file, int len = 0) { string str = null; if (len > 0) { str = Encoding.GetEncoding("ISO-8859-1").GetString(file.ReadBytes(len)); } else { var sb = new StringBuilder(); while (true) { var c = (char)file.ReadByte(); if (c == 0) break; sb.Append(c); } str = sb.ToString(); } return str; } public static void WriteCR2WString(this BinaryWriter file, string str) { if (str != null) { file.Write(Encoding.GetEncoding("ISO-8859-1").GetBytes(str)); } file.Write((byte)0); } public static void AddUnique(this Dictionary<string, uint> dic, string str, uint val) { if (str == null) str = ""; if (!dic.ContainsKey(str)) { dic.Add(str, val); } } public static uint Get(this Dictionary<string, uint> dic, string str) { if (str == null) str = ""; return dic[str]; } public static byte[] ReadRemainingData(this BinaryReader br) { return br.ReadBytes((int)(br.BaseStream.Length - br.BaseStream.Position)); } } }
<?php namespace App; use Eloquent; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Collection; use Illuminate\Database\Eloquent\Relations\BelongsToMany; use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Database\Eloquent\Relations\MorphToMany; use Illuminate\Support\Carbon; use Savitar\Auth\Controllers\BillingDataController; use Savitar\Auth\SavitarAccount; use Savitar\Auth\SavitarBillingData; use Savitar\Auth\SavitarUser; use Savitar\Auth\SavitarZone; use Savitar\Files\SavitarFile; use Savitar\Models\SavitarBuilder; /** * App\Account * * @property string $id * @property string|null $countryId * @property string|null $provinceId * @property string $name * @property string $slug * @property string|null $nif * @property bool $isActive * @property string|null $city * @property string|null $address * @property string|null $zipCode * @property string|null $phone * @property string|null $fax * @property string|null $website * @property string|null $email * @property string|null $facebookUrl * @property string|null $twitterUrl * @property string|null $youtubeUrl * @property string|null $instagramUrl * @property string $selectedTheme * @property bool $initialConfiguration * @property bool $isSuperAdminAccount * @property string|null $observations * @property string|null $contactName * @property string|null $contactPhone * @property string|null $createdBy * @property string|null $updatedBy * @property string|null $deletedBy * @property Carbon|null $createdAt * @property Carbon|null $updatedAt * @property Carbon|null $deletedAt * @property string|null $anfixCustomerId * @property string|null $anfixCompanyAccountingAccountNumber * @property float|null $maximumAdvance * @property bool $canCreateInvitations * @property bool $unlimitedInvitations * @property int|null $oldId * @property-read Collection|SavitarBillingData[] $billingData * @property-read int|null $billingDataCount * @property-read SavitarZone|null $country * @property-read User|null $createdByUser * @property-read User|null $deletedByUser * @property-read Collection|SavitarFile[] $files * @property-read int|null $filesCount * @property-read string|null $lastLicenseStatus * @property-read mixed|string $logoUrl * @property-read string|null $planName * @property-read Collection|PointOfSale[] $pointsOfSale * @property-read int|null $pointsOfSaleCount * @property-read SavitarZone|null $province * @property-read Collection|ShowTemplate[] $showTemplates * @property-read int|null $showTemplatesCount * @property-read Collection|Show[] $shows * @property-read int|null $showsCount * @property-read User|null $updatedByUser * @property-read Collection|SavitarUser[] $users * @property-read int|null $usersCount * @property-read Collection|Enterprise[] $enterprises * @property-read int|null $enterprisesCount * @method static SavitarBuilder|Account newModelQuery() * @method static SavitarBuilder|Account newQuery() * @method static SavitarBuilder|Account query() * @method static Builder|Account whereAddress($value) * @method static Builder|Account whereCity($value) * @method static Builder|Account whereContactName($value) * @method static Builder|Account whereContactPhone($value) * @method static Builder|Account whereCountryId($value) * @method static Builder|Account whereCreatedAt($value) * @method static Builder|Account whereCreatedBy($value) * @method static Builder|Account whereDeletedAt($value) * @method static Builder|Account whereDeletedBy($value) * @method static Builder|Account whereEmail($value) * @method static Builder|Account whereFacebookUrl($value) * @method static Builder|Account whereFax($value) * @method static Builder|Account whereId($value) * @method static Builder|Account whereInitialConfiguration($value) * @method static Builder|Account whereInstagramUrl($value) * @method static Builder|Account whereIsActive($value) * @method static Builder|Account whereIsSuperAdminAccount($value) * @method static Builder|Account whereName($value) * @method static Builder|Account whereNif($value) * @method static Builder|Account whereObservations($value) * @method static Builder|Account wherePhone($value) * @method static Builder|Account whereProvinceId($value) * @method static Builder|Account whereSelectedTheme($value) * @method static Builder|Account whereSlug($value) * @method static Builder|Account whereTwitterUrl($value) * @method static Builder|Account whereUpdatedAt($value) * @method static Builder|Account whereUpdatedBy($value) * @method static Builder|Account whereWebsite($value) * @method static Builder|Account whereYoutubeUrl($value) * @method static Builder|Account whereZipCode($value) * @method static Builder|Account whereCanCreateInvitations($value) * @method static Builder|Account whereMaximumAdvance($value) * @method static Builder|Account whereUnlimitedInvitations($value) * @method static Builder|Account whereAnfixCompanyAccountingAccountNumber($value) * @method static Builder|Account whereAnfixCustomerId($value) * @method static Builder|Account whereOldId($value) * @mixin Eloquent */ class Account extends SavitarAccount { protected $modelDefinition = [ 'visibleAttributes' => [ 'name' => [ 'name' => 'Nombre', 'type' => 'string', 'sql' => 'Account.name', 'default' => true, ], 'isActive' => [ 'name' => 'Estado', 'type' => 'boolean', 'sql' => 'Account.isActive', 'possibleValues' => [false, true], 'configuration' => [ 'false' => ['html' => 'Bloqueado', 'translation' => 'Bloqueado', 'statusColor' => 'red-status'], 'true' => ['html' => 'Activo', 'translation' => 'Activo', 'statusColor' => 'green-status'], // 'true' => ['html' => 'Activo', 'translation' => 'Activo', 'customColor' => '#359964'], ], 'default' => true, ], 'nif' => [ 'name' => 'CIF/NIF', 'type' => 'string', 'sql' => 'Account.nif', ], 'initialConfiguration' => [ 'name' => 'Config. inicial realizada', 'type' => 'boolean', 'sql' => 'Account.initialConfiguration', 'possibleValues' => [false, true], 'configuration' => [ 'false' => ['html' => 'No', 'translation' => 'No'], 'true' => ['html' => 'Sí', 'translation' => 'Sí'], ], ], 'provinceName' => [ 'name' => 'Provincia', 'type' => 'string', 'sql' => 'Zone.name', 'foreignKey' => 'Account.provinceId', 'update' => false, 'save' => false, ], 'city' => [ 'name' => 'Localidad', 'type' => 'string', 'sql' => 'Account.city', ], 'address' => [ 'name' => 'Dirección', 'type' => 'string', 'sql' => 'Account.address', ], 'zipCode' => [ 'name' => 'Código Postal', 'type' => 'string', 'sql' => 'Account.zipCode', ], 'phone' => [ 'name' => 'Teléfono', 'type' => 'string', 'sql' => 'Account.phone', 'default' => true, ], 'email' => [ 'name' => 'Email', 'type' => 'string', 'sql' => 'Account.email', ], 'website' => [ 'name' => 'Web', 'type' => 'string', 'sql' => 'Account.website', ], 'maximumAdvance' => [ 'name' => 'Máximo anticipado', 'type' => 'money', 'sql' => 'Account.maximumAdvance', ], 'canCreateInvitations' => [ 'name' => 'Puede crear invitaciones', 'type' => 'boolean', 'sql' => 'Account.canCreateInvitations', 'possibleValues' => [false, true], 'configuration' => [ 'false' => ['html' => 'No', 'translation' => 'No'], 'true' => ['html' => 'Sí', 'translation' => 'Sí'], ], ], 'unlimitedInvitations' => [ 'name' => 'Invitaciones ilimitadas', 'type' => 'boolean', 'sql' => 'Account.unlimitedInvitations', 'possibleValues' => [false, true], 'configuration' => [ 'false' => ['html' => 'No', 'translation' => 'No'], 'true' => ['html' => 'Sí', 'translation' => 'Sí'], ], ], 'observations' => [ 'name' => 'Observaciones', 'type' => 'string', 'sql' => 'Account.observations', ], 'contactName' => [ 'name' => 'Nombre de la persona de contacto', 'type' => 'string', 'sql' => 'Account.contactName', ], 'contactPhone' => [ 'name' => 'Teléfono de la persona de contacto', 'type' => 'string', 'sql' => 'Account.contactPhone', ], 'createdAt' => [ 'name' => 'Fecha de creación', 'type' => 'fullDate', 'sql' => 'Account.createdAt', 'default' => true, 'accountConfiguration' => false, ], 'createdBy' => [ 'name' => 'Creador', 'type' => 'string', 'sql' => 'Account.createdBy', 'accountConfiguration' => false, ], 'updatedAt' => [ 'name' => 'Fecha de actualización', 'type' => 'fullDate', 'sql' => 'Account.updatedAt', 'accountConfiguration' => false, ], 'updatedBy' => [ 'name' => 'Actualizado por', 'type' => 'string', 'sql' => 'Account.updatedBy', 'accountConfiguration' => false, ], ], 'shadowAttributes' => [ 'id' => [ 'name' => 'UUID', 'validation' => 'uuid|required', 'type' => 'string', 'update' => false, 'save' => false, 'accountConfiguration' => false, ], 'deletedAt' => [ 'name' => 'Fecha de eliminación', 'validation' => 'date|required', 'type' => 'date', 'update' => false, 'save' => false, 'accountConfiguration' => false, ], 'deletedBy' => [ 'name' => 'Eliminado por', 'type' => 'string', 'sql' => 'Account.deletedBy', 'accountConfiguration' => false, ], 'fax' => [ 'name' => 'Fax', 'type' => 'string', 'sql' => 'Account.fax', ], 'users' => [ 'name' => 'Usuario', 'type' => 'relation', 'relationType' => 'hasMany', 'relatedModelClass' => SavitarUser::class, ], 'billingData' => [ 'name' => 'Datos de facturación', 'type' => 'relation', 'relationType' => 'hasMany', 'relatedModelClass' => SavitarBillingData::class, 'relatedModelControllerClass' => BillingDataController::class, ], 'country' => [ 'name' => 'País', 'type' => 'relation', 'relationType' => 'belongsTo', 'relatedModelClass' => SavitarZone::class, ], 'province' => [ 'name' => 'Provincia', 'type' => 'relation', 'relationType' => 'belongsTo', 'relatedModelClass' => SavitarZone::class, ], 'files' => [ 'name' => 'Archivos', 'type' => 'relation', 'relationType' => 'morphMany', 'relatedModelClass' => SavitarFile::class, ], 'pointsOfSale' => [ 'name' => 'Puntos de venta', 'type' => 'relation', 'relationType' => 'belongsToMany', 'relatedModelClass' => PointOfSale::class, ], ], ]; /** * A sponsor has many shows * * @return HasMany */ public function shows(): HasMany { return $this->hasMany(Show::class); } /** * A sponsor has many showTemplates * * @return HasMany */ public function showTemplates(): HasMany { return $this->hasMany(ShowTemplate::class); } /** * An account belongs to many points of sale * * @return BelongsToMany */ public function pointsOfSale(): BelongsToMany { return $this->belongsToMany(PointOfSale::class)->using(AccountPointOfSale::class)->withTimestamps(); } /** * An account has many files * * @return HasMany */ public function files(): HasMany { return $this->hasMany(SavitarFile::class, 'fileableId'); } /** * Get all of the enterprises for the account. */ public function enterprises(): MorphToMany { return $this->morphToMany(Enterprise::class, 'enterprisable', 'Enterprisable'); } }
export SECRET_KEY='jadiel' export MAIL_USERNAME='[email protected]' export MAIL_PASSWORD='church95' python3.6 manage.py server
//! Main API entry point for reading and manipulating Metamath databases. //! //! A variable of type `Database` represents a loaded database. You can //! construct a `Database` object, then cause it to represent a database from a //! disk file using the `parse` method, then query various analysis results //! which will be computed on demand. You can call `parse` again to reload //! data; the implementation expects there to be minor changes, and optimizes //! with incremental recomputation. //! //! It is also possible to modify a loaded database by opening it (details TBD); //! while the database is open most analyses cannot be used, but it is permitted //! to call `Clone::clone` on a `Database` and the type is designed to make that //! relatively efficient (currently requires the duplication of three large hash //! tables, this can be optimized). //! //! ## On segmentation //! //! Existing Metamath verifiers which attempt to maintain a DOM represent it as //! a flat list of statements. In order to permit incremental and parallel //! operation across _all_ phases, we split the list into one or more segments. //! A **segment** is a run of statements which are parsed together and will //! always remain contiguous in the logical system. Segments are generated by //! the parsing process, and are the main unit of recalculation and parallelism //! for subsequent passes. We do not allow grouping constructs to span segment //! boundaries; since we also disallow top-level `$e` statements, this means //! that the scope of an `$e` statement is always limited to a single segment. //! //! A source file without include statements will be treated as a single segment //! (except for splitting, see below). A source file with N include statements //! will generate N + 1 segments; a new segment is started immediately after //! each include to allow any segment(s) from the included file to be slotted //! into the correct order. Thus segments cannot quite be the parallelism //! granularity for parsing, because during the parse we don't know the final //! number of segments; instead each source file is parsed independently, gating //! rereading and reparsing on the file modification time. //! //! As an exception to support parallel processing of large single files (like //! set.mm at the time of writing), source files larger than 1MiB are //! automatically split into multiple pieces before parsing. Each piece tracks //! the need to recalculate independently, and each piece may generate or or //! more segments as above. Pieces are identified using chapter header //! comments, and are located using a simple word-at-a-time Boyer-Moore search //! that is much faster than the actual parser (empirically, it is limited by //! main memory sequential read speed). _Note that this means that for large //! files, chapter header comments are effectively illegal inside of grouping //! statements. set.mm is fine with that restriction, but it does not match the //! spec._ //! //! Each loaded segment is assigned an ID (of type `SegmentId`, an opacified //! 32-bit integer). These IDs are **reused** when a segment is replaced with //! another segment with the same logical sequence position; this allows //! subsequent passes to interpret the new segment as the inheritor of the //! previous segment, and reuse caches as applicable. It then becomes necessary //! to decide which of two segments is earlier in the logical order; it is not //! possible to simply use numeric order, as a new segment might need to be //! added between any two existing segments. This is the well-studied //! [order-maintenance problem][OMP]; we currently have a naive algorithm in the //! `parser::SegmentOrder` structure, but a more sophisticated one could be //! added later. We never reuse a `SegmentId` in a way which would cause the //! relative position of two `SegmentId` values to change; this means that after //! many edits and incremental reloads the `SegmentOrder` will grow, and it may //! become necessary to add code later to trigger a global renumbering (which //! would necesssarily entail recomputation of all passes for all segments, but //! the amortized complexity need not be bad). //! //! [OMP]: https://en.wikipedia.org/wiki/Order-maintenance_problem //! //! ## Incremental processing: Readers and Usages //! //! A pass will be calculated when its result is needed. Operation is currently //! lazy at a pass level, so it is not possible to verify only one segment, //! although that _might_ change. The results of a pass are stored in a data //! structure indexed by some means, each element of which has an associated //! version number. When another pass needs to use the result of the first //! pass, it tracks which elements of the first pass's result are used for each //! segment, and their associated version numbers; this means that if a small //! database change is made and the second pass is rerun, it can quickly abort //! on most segments by checking if the dependencies _of that segment_ have //! changed, using only the version numbers. //! //! This is not yet a rigidly systematized thing; for an example, nameck //! generates its result as a `nameck::Nameset`, and implements //! `nameck::NameUsage` objects which scopeck can use to record which names were //! used scoping a given segment; it also provides `nameck::NameReader` objects //! which can be used to access the nameset while simultaneously building a //! usage object that can be used for future checking. //! //! ## Parallelism and promises //! //! The current parallel processing implementation is fairly simplistic. If you //! want to run a number of code fragments in parallel, get a reference to the //! `Executor` object for the current database, then use it to queue a closure //! for each task you want to run; the queueing step returns a `Promise` object //! which can be used to wait for the task to complete. Generally you want to //! queue everything, then wait for everything. //! //! To improve packing efficiency, jobs are dispatched in descending order of //! estimated runtime. This requires an additional argument when queueing. use crate::diag; use crate::diag::DiagnosticClass; use crate::diag::Notation; use crate::export; use crate::formula::Label; use crate::grammar; use crate::grammar::Grammar; use crate::grammar::StmtParse; use crate::nameck::Nameset; use crate::outline::OutlineNode; use crate::parser::StatementRef; use crate::scopeck; use crate::scopeck::ScopeResult; use crate::segment_set::SegmentSet; use crate::verify; use crate::verify::VerifyResult; use std::cmp::Ordering; use std::collections::BinaryHeap; use std::fmt; use std::fmt::Debug; use std::fs::File; use std::panic; use std::sync::Arc; use std::sync::Condvar; use std::sync::Mutex; use std::thread; use std::time::Instant; /// Structure for options that affect database processing, and must be constant /// for the lifetime of the database container. /// /// Some of these could theoretically support modification. #[derive(Copy, Clone, Debug)] pub struct DbOptions { /// If true, the automatic splitting of large files described above is /// enabled, with the caveat about chapter comments inside grouping /// statements. pub autosplit: bool, /// If true, time in milliseconds is printed after the completion of each /// pass. pub timing: bool, /// True to print names (determined by a very simple heuristic, see /// `parser::guess_buffer_name`) of segments which are recalculated in each /// pass. pub trace_recalc: bool, /// True to record detailed usage data needed for incremental operation. /// /// This will slow down the initial analysis, so don't set it if you won't /// use it. If this is false, any reparse will result in a full /// recalculation, so it is always safe but different settings will be /// faster for different tasks. pub incremental: bool, /// Number of jobs to run in parallel at any given time. pub jobs: usize, } impl Default for DbOptions { fn default() -> Self { Self { autosplit: false, timing: false, trace_recalc: false, incremental: false, jobs: 1, } } } /// Wraps a heap-allocated closure with a difficulty score which can be used for /// sorting; this might belong in the standard library as `CompareFirst` or such. struct Job(usize, Box<dyn FnMut() + Send>); impl PartialEq for Job { fn eq(&self, other: &Job) -> bool { self.0 == other.0 } } impl Eq for Job {} impl PartialOrd for Job { fn partial_cmp(&self, other: &Job) -> Option<Ordering> { Some(self.0.cmp(&other.0)) } } impl Ord for Job { fn cmp(&self, other: &Job) -> Ordering { self.0.cmp(&other.0) } } /// Object which holds the state of the work queue and allows queueing tasks to /// run on the thread pool. #[derive(Clone)] pub struct Executor { concurrency: usize, // Jobs are kept in a heap so that we can dispatch the biggest one first. mutex: Arc<Mutex<BinaryHeap<Job>>>, // Condvar used to notify work threads of new work. work_cv: Arc<Condvar>, } /// Debug printing for `Executor` displays the current count of queued but not /// dispatched tasks. impl fmt::Debug for Executor { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let g = self.mutex.lock().unwrap(); write!(f, "Executor(active={})", g.len()) } } fn queue_work(exec: &Executor, estimate: usize, mut f: Box<dyn FnMut() + Send>) { if exec.concurrency <= 1 { f(); return; } let mut wq = exec.mutex.lock().unwrap(); wq.push(Job(estimate, f)); exec.work_cv.notify_one(); } impl Executor { /// Instantiates a new work queue and creates the threads to service it. /// /// The threads will exit when the `Executor` goes out of scope (not yet /// implemented). In the future, we *may* have process-level coordination /// to allow different `Executor`s to share a thread pool, and use per-job /// concurrency limits. #[must_use] pub fn new(concurrency: usize) -> Executor { let mutex = Arc::new(Mutex::new(BinaryHeap::new())); let cv = Arc::new(Condvar::new()); if concurrency > 1 { for _ in 0..concurrency { let mutex = mutex.clone(); let cv = cv.clone(); thread::spawn(move || loop { let mut task: Job = { let mut mutexg = mutex.lock().unwrap(); while mutexg.is_empty() { mutexg = cv.wait(mutexg).unwrap(); } mutexg.pop().unwrap() }; (task.1)(); }); } } Executor { concurrency, mutex, work_cv: cv, } } /// Queue a job on this work queue. /// /// The estimate is meaningless in isolation but jobs with a higher estimate /// will be dispatched first, so it should be comparable among jobs that /// could simultaneously be in the work queue. /// /// Returns a `Promise` that can be used to wait for completion of the /// queued work. If the provided task panics, the error will be stored and /// rethrown when the promise is awaited. pub fn exec<TASK, RV>(&self, estimate: usize, task: TASK) -> Promise<RV> where TASK: FnOnce() -> RV + Send + 'static, RV: Send + 'static, { let parts = Arc::new((Mutex::new(None), Condvar::new())); let partsc = parts.clone(); let mut task_o = Some(task); queue_work( self, estimate, Box::new(move || { let mut g = partsc.0.lock().unwrap(); let task_f = panic::AssertUnwindSafe(task_o.take().expect("should only be called once")); *g = Some(panic::catch_unwind(task_f)); partsc.1.notify_one(); }), ); Promise::new_once(move || { let mut g = parts.0.lock().unwrap(); while g.is_none() { g = parts.1.wait(g).unwrap(); } g.take().unwrap().unwrap() }) } } /// A handle for a value which will be available later. /// /// Promises are normally constructed using `Executor::exec`, which moves /// computation to a thread pool. There are several other methods to attach /// code to promises; these do **not** parallelize, and are intended to do very /// cheap tasks for interface consistency purposes only. pub struct Promise<T>(Box<dyn FnMut() -> T + Send>); impl<T> Debug for Promise<T> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "Promise(..)") } } impl<T> Promise<T> { /// Wait for a value to be available and return it, rethrowing any panic. #[must_use] pub fn wait(mut self) -> T { (self.0)() } /// Construct a promise which uses a provided closure to wait for the value /// when necessary. /// /// This does **not** do any parallelism; the provided closure will be /// invoked when `wait` is called, on the thread where `wait` is called. If /// you want to run code in parallel, use `Executor::exec`. pub fn new_once<FN>(fun: FN) -> Promise<T> where FN: FnOnce() -> T + Send + 'static, { let mut funcell = Some(fun); // the take hack works around the lack of stable FnBox Promise(Box::new(move || (funcell.take().unwrap())())) } /// Wrap a value which is available now in a promise. pub fn new(value: T) -> Self where T: Send + 'static, { Promise::new_once(move || value) } /// Modify a promise with a function, which will be called at `wait` time on /// the `wait` thread. pub fn map<FN, RV>(self, fun: FN) -> Promise<RV> where T: 'static, FN: Send + FnOnce(T) -> RV + 'static, { Promise::new_once(move || fun(self.wait())) } /// Convert a collection of promises into a single promise, which waits for /// all of its parts. #[must_use] pub fn join(promises: Vec<Promise<T>>) -> Promise<Vec<T>> where T: 'static, { Promise::new_once(move || promises.into_iter().map(Promise::wait).collect()) } } /// Master type of database containers. /// /// A variable of type `Database` holds a database, i.e. an ordered collection /// of segments and analysis results for that collection. Analysis results are /// generated lazily for each database, and are invalidated on any edit to the /// database's segments. If you need to refer to old analysis results while /// making a sequence of edits, call `Clone::clone` on the database first; this /// is intended to be a relatively cheap operation. /// /// More specifically, cloning a `Database` object does essentially no work /// until it is necessary to run an analysis pass on one clone or the other; /// then if the analysis pass has a result index which is normally updated in /// place, such as the hash table of statement labels constructed by nameck, /// that table must be duplicated so that it can be updated for one database /// without affecting the other. #[derive(Debug)] pub struct Database { options: Arc<DbOptions>, segments: Arc<SegmentSet>, /// We track the "current" and "previous" for all known passes, so that each /// pass can use its most recent results for optimized incremental /// processing. Any change to the segment vector zeroizes the current /// fields but not the previous fields. prev_nameset: Option<Arc<Nameset>>, nameset: Option<Arc<Nameset>>, prev_scopes: Option<Arc<ScopeResult>>, scopes: Option<Arc<ScopeResult>>, prev_verify: Option<Arc<VerifyResult>>, verify: Option<Arc<VerifyResult>>, outline: Option<Arc<OutlineNode>>, grammar: Option<Arc<Grammar>>, stmt_parse: Option<Arc<StmtParse>>, } impl Default for Database { fn default() -> Self { Self::new(DbOptions::default()) } } fn time<R, F: FnOnce() -> R>(opts: &DbOptions, name: &str, f: F) -> R { let now = Instant::now(); let ret = f(); if opts.timing { // no as_msecs :( println!("{} {}ms", name, (now.elapsed() * 1000).as_secs()); } ret } impl Drop for Database { fn drop(&mut self) { time(&self.options.clone(), "free", move || { self.prev_verify = None; self.verify = None; self.prev_scopes = None; self.scopes = None; self.prev_nameset = None; self.nameset = None; Arc::make_mut(&mut self.segments).clear(); self.outline = None; }); } } impl Database { /// Constructs a new database object representing an empty set of segments. /// /// Use `parse` to load it with data. Currently this eagerly starts the /// threadpool, but that may change. #[must_use] pub fn new(options: DbOptions) -> Database { let options = Arc::new(options); let exec = Executor::new(options.jobs); Database { segments: Arc::new(SegmentSet::new(options.clone(), &exec)), options, nameset: None, scopes: None, verify: None, outline: None, grammar: None, stmt_parse: None, prev_nameset: None, prev_scopes: None, prev_verify: None, } } /// Replaces the content of a database in memory with the parsed content of /// one or more input files. /// /// To load data from disk files, pass the pathname as `start` and leave /// `text` empty. `start` and any references arising from file inclusions /// will be processed relative to the current directory; we _may_ add a base /// directory option later. /// /// The database object will remember the name and OS modification time of /// all files read to construct its current state, and will skip rereading /// them if the modification change has not changed on the next call to /// `parse`. If your filesystem has poor modification time granulatity, /// beware of possible lost updates if you modify a file and the timestamp /// does not change. /// /// To parse data already resident in program memory, pass an arbitrary name /// as `start` and then pass a pair in `text` mapping that name to the /// buffer to parse. Any file inclusions found in the buffer can be /// resolved from additional pairs in `text`; file inclusions which are /// _not_ found in `text` will be resolved on disk relative to the current /// directory as above (this feature has [an uncertain future][FALLBACK]). /// /// [FALLBACK]: https://github.com/sorear/smetamath-rs/issues/18 /// /// All analysis passes will be invalidated; they will not immediately be /// rerun, but will be when next requested. If the database is not /// currently empty, the files loaded are assumed to be similar to the /// current database content and incremental processing will be used as /// appropriate. pub fn parse(&mut self, start: String, text: Vec<(String, Vec<u8>)>) { time(&self.options.clone(), "parse", || { Arc::make_mut(&mut self.segments).read(start, text); self.nameset = None; self.scopes = None; self.verify = None; self.outline = None; self.grammar = None; }); } /// Obtains a reference to the current parsed data. pub(crate) const fn parse_result(&self) -> &Arc<SegmentSet> { &self.segments } /// Calculates and returns the name to definition lookup table. pub fn name_pass(&mut self) -> &Arc<Nameset> { if self.nameset.is_none() { time(&self.options.clone(), "nameck", || { let mut ns = self.prev_nameset.take().unwrap_or_default(); let pr = self.parse_result(); Arc::make_mut(&mut ns).update(pr); self.prev_nameset = Some(ns.clone()); self.nameset = Some(ns); }); } self.name_result() } /// Returns the name to definition lookup table. /// Panics if [`Database::name_pass`] was not previously called. #[inline] #[must_use] pub fn name_result(&self) -> &Arc<Nameset> { self.nameset.as_ref().unwrap() } /// Calculates and returns the frames for this database, i.e. the actual /// logical system. /// /// All logical properties of the database (as opposed to surface syntactic /// properties) can be obtained from this object. pub fn scope_pass(&mut self) -> &Arc<ScopeResult> { if self.scopes.is_none() { self.name_pass(); time(&self.options.clone(), "scopeck", || { let mut sc = self.prev_scopes.take().unwrap_or_default(); let parse = self.parse_result(); let name = self.name_result(); scopeck::scope_check(Arc::make_mut(&mut sc), parse, name); self.prev_scopes = Some(sc.clone()); self.scopes = Some(sc); }); } self.scope_result() } /// Returns the frames for this database, i.e. the actual logical system. /// Panics if [`Database::scope_pass`] was not previously called. /// /// All logical properties of the database (as opposed to surface syntactic /// properties) can be obtained from this object. #[inline] #[must_use] pub fn scope_result(&self) -> &Arc<ScopeResult> { self.scopes.as_ref().unwrap() } /// Calculates and returns verification information for the database. /// /// This is an optimized verifier which returns no useful information other /// than error diagnostics. It does not save any parsed proof data. pub fn verify_pass(&mut self) -> &Arc<VerifyResult> { if self.verify.is_none() { self.name_pass(); self.scope_pass(); time(&self.options.clone(), "verify", || { let mut ver = self.prev_verify.take().unwrap_or_default(); let parse = self.parse_result(); let scope = self.scope_result(); let name = self.name_result(); verify::verify(Arc::make_mut(&mut ver), parse, name, scope); self.prev_verify = Some(ver.clone()); self.verify = Some(ver); }); } self.verify_result() } /// Returns verification information for the database. /// Panics if [`Database::verify_pass`] was not previously called. /// /// This is an optimized verifier which returns no useful information other /// than error diagnostics. It does not save any parsed proof data. #[inline] #[must_use] pub fn verify_result(&self) -> &Arc<VerifyResult> { self.verify.as_ref().unwrap() } /// Computes and returns the root node of the outline. pub fn outline_pass(&mut self) -> &Arc<OutlineNode> { if self.outline.is_none() { time(&self.options.clone(), "outline", || { let parse = self.parse_result().clone(); let mut outline = OutlineNode::default(); parse.build_outline(&mut outline); self.outline = Some(Arc::new(outline)); }) } self.outline_result() } /// Returns the root node of the outline. /// Panics if [`Database::outline_pass`] was not previously called. #[inline] #[must_use] pub fn outline_result(&self) -> &Arc<OutlineNode> { self.outline.as_ref().unwrap() } /// Builds and returns the grammar. pub fn grammar_pass(&mut self) -> &Arc<Grammar> { if self.grammar.is_none() { self.name_pass(); self.scope_pass(); time(&self.options.clone(), "grammar", || { self.grammar = Some(Arc::new(Grammar::new(self))); }) } self.grammar_result() } /// Returns the grammar. /// Panics if [`Database::grammar_pass`] was not previously called. #[inline] #[must_use] pub fn grammar_result(&self) -> &Arc<Grammar> { self.grammar.as_ref().unwrap() } /// Parses the statements using the grammar. pub fn stmt_parse_pass(&mut self) -> &Arc<StmtParse> { if self.stmt_parse.is_none() { self.name_pass(); self.scope_pass(); self.grammar_pass(); time(&self.options.clone(), "stmt_parse", || { let parse = self.parse_result(); let name = self.name_result(); let grammar = self.grammar_result(); let mut stmt_parse = StmtParse::default(); grammar::parse_statements(&mut stmt_parse, parse, name, grammar); self.stmt_parse = Some(Arc::new(stmt_parse)); }) } self.stmt_parse_result() } /// Returns the statements parsed using the grammar. /// Panics if [`Database::stmt_parse_pass`] was not previously called. #[inline] #[must_use] pub fn stmt_parse_result(&self) -> &Arc<StmtParse> { self.stmt_parse.as_ref().unwrap() } /// A getter method which does not build the outline. #[inline] #[must_use] pub const fn get_outline(&self) -> Option<&Arc<OutlineNode>> { self.outline.as_ref() } /// Get a statement by label. Requires: [`Database::name_pass`] #[must_use] pub fn statement(&self, name: &str) -> Option<StatementRef<'_>> { let lookup = self.name_result().lookup_label(name.as_bytes())?; Some(self.parse_result().statement(lookup.address)) } /// Get a statement by label atom. #[must_use] pub fn statement_by_label(&self, label: Label) -> Option<StatementRef<'_>> { let token = self.name_result().atom_name(label); let lookup = self.name_result().lookup_label(token)?; Some(self.parse_result().statement(lookup.address)) } /// Iterates over all the statements pub fn statements(&self) -> impl Iterator<Item = StatementRef<'_>> + '_ { self.segments.segments().into_iter().flatten() } /// Export an mmp file for a given statement. /// Requires: [`Database::name_pass`], [`Database::scope_pass`] pub fn export(&self, stmt: &str) { time(&self.options, "export", || { let sref = self.statement(stmt).unwrap_or_else(|| { panic!("Label {} did not correspond to an existing statement", stmt) }); File::create(format!("{}.mmp", stmt)) .map_err(export::ExportError::Io) .and_then(|mut file| self.export_mmp(sref, &mut file)) .unwrap() }) } /// Export the grammar of this database in DOT format. /// Requires: [`Database::name_pass`], [`Database::grammar_pass`] #[cfg(feature = "dot")] pub fn export_grammar_dot(&self) { time(&self.options, "export_grammar_dot", || { let name = self.name_result(); let grammar = self.grammar_result(); File::create("grammar.dot") .map_err(export::ExportError::Io) .and_then(|mut file| grammar.export_dot(name, &mut file)) .unwrap() }) } /// Dump the grammar of this database. /// Requires: [`Database::name_pass`], [`Database::grammar_pass`] pub fn print_grammar(&self) { time(&self.options, "print_grammar", || { self.grammar_result().dump(self); }) } /// Dump the formulas of this database. /// Requires: [`Database::name_pass`], [`Database::stmt_parse_pass`] pub fn print_formula(&self) { time(&self.options, "print_formulas", || { self.stmt_parse_result().dump(self); }) } /// Verify that printing the formulas of this database gives back the original formulas. /// Requires: [`Database::name_pass`], [`Database::stmt_parse_pass`] pub fn verify_parse_stmt(&self) { time(&self.options, "verify_parse_stmt", || { if let Err(diag) = self.stmt_parse_result().verify(self) { drop(diag::to_annotations(self.parse_result(), vec![diag])); } }) } /// Dump the outline of this database. /// Requires: [`Database::outline_pass`] pub fn print_outline(&self) { time(&self.options, "print_outline", || { let root_node = self.outline_result(); self.print_outline_node(root_node, 0); }) } /// Dump the outline of this database. fn print_outline_node(&self, node: &OutlineNode, indent: usize) { // let indent = (node.level as usize) * 3 println!( "{:indent$} {:?} {:?}", "", node.level, node.get_name(), indent = indent ); for child in &node.children { self.print_outline_node(child, indent + 1); } } /// Collects and returns all errors generated by the passes run. /// /// Passes are identified by the `types` argument and are not inclusive; if /// you ask for Verify, you will not get Parse unless you specifically ask /// for that as well. /// /// Currently there is no way to incrementally fetch diagnostics, so this /// will be a bit slow if there are thousands of errors. pub fn diag_notations(&mut self, types: &[DiagnosticClass]) -> Vec<Notation> { let mut diags = Vec::new(); if types.contains(&DiagnosticClass::Parse) { diags.extend(self.parse_result().parse_diagnostics()); } if types.contains(&DiagnosticClass::Scope) { diags.extend(self.scope_pass().diagnostics()); } if types.contains(&DiagnosticClass::Verify) { diags.extend(self.verify_pass().diagnostics()); } if types.contains(&DiagnosticClass::Grammar) { diags.extend(self.grammar_pass().diagnostics()); } if types.contains(&DiagnosticClass::StmtParse) { diags.extend(self.stmt_parse_pass().diagnostics()); } time(&self.options.clone(), "diag", || { diag::to_annotations(self.parse_result(), diags) }) } }
"""archetypal UmiBase module.""" import itertools import math import re from collections.abc import Hashable, MutableSet import numpy as np from validator_collection import validators from archetypal.utils import lcm def _resolve_combined_names(predecessors): """Creates a unique name from the list of :class:`UmiBase` objects (predecessors) Args: predecessors (MetaData): """ # all_names = [obj.Name for obj in predecessors] class_ = list(set([obj.__class__.__name__ for obj in predecessors]))[0] return "Combined_%s_%s" % ( class_, str(hash((pre.Name for pre in predecessors))).strip("-"), ) def _shorten_name(long_name): """Check if name is longer than 300 characters, and return truncated version Args: long_name (str): A long name (300 char+) to shorten. """ if len(long_name) > 300: # shorten name if longer than 300 characters (limit set by # EnergyPlus) return long_name[:148] + (long_name[148:] and " .. ") else: return long_name class UmiBase(object): """Base class for template objects.""" __slots__ = ( "_id", "_datasource", "_predecessors", "_name", "_category", "_comments", "_allow_duplicates", "_unit_number", ) CREATED_OBJECTS = [] _ids = itertools.count(0) # unique id for each class instance def __init__( self, Name, Category="Uncategorized", Comments="", DataSource=None, allow_duplicates=False, **kwargs, ): """The UmiBase class handles common properties to all Template objects. Args: Name (str): Unique, the name of the object. Category (str): Group objects by assigning the same category identifier. Thies can be any string. Comments (str): A comment displayed in the UmiTemplateLibrary. DataSource (str): A description of the datasource of the object. This helps identify from which data is the current object created. allow_duplicates (bool): If True, this object can be equal to another one if it has a different name. **kwargs: """ self.Name = Name self.Category = Category self.Comments = Comments self.DataSource = DataSource self.id = kwargs.get("id", None) self.allow_duplicates = allow_duplicates self.unit_number = next(self._ids) self.predecessors = None UmiBase.CREATED_OBJECTS.append(self) @property def Name(self): """Get or set the name of the object.""" return self._name @Name.setter def Name(self, value): self._name = validators.string(value, coerce_value=True) @property def id(self): """Get or set the id.""" return self._id @id.setter def id(self, value): if value is None: value = id(self) self._id = validators.string(value, coerce_value=True) @property def DataSource(self): """Get or set the datasource of the object.""" return self._datasource @DataSource.setter def DataSource(self, value): self._datasource = validators.string(value, coerce_value=True, allow_empty=True) @property def Category(self): """Get or set the Category attribute.""" return self._category @Category.setter def Category(self, value): value = validators.string(value, coerce_value=True, allow_empty=True) if value is None: value = "" self._category = value @property def Comments(self): """Get or set the object comments.""" return self._comments @Comments.setter def Comments(self, value): value = validators.string(value, coerce_value=True, allow_empty=True) if value is None: value = "" self._comments = value @property def allow_duplicates(self): """Get or set the use of duplicates [bool].""" return self._allow_duplicates @allow_duplicates.setter def allow_duplicates(self, value): assert isinstance(value, bool), value self._allow_duplicates = value @property def unit_number(self): return self._unit_number @unit_number.setter def unit_number(self, value): self._unit_number = validators.integer(value) @property def predecessors(self): """Get or set the predecessors of self. Of which objects is self made of. If from nothing else then self, return self. """ if self._predecessors is None: self._predecessors = MetaData([self]) return self._predecessors @predecessors.setter def predecessors(self, value): self._predecessors = value def duplicate(self): """Get copy of self.""" return self.__copy__() def _get_predecessors_meta(self, other): """get predecessor objects to self and other Args: other (UmiBase): The other object. """ predecessors = self.predecessors + other.predecessors meta = self.combine_meta(predecessors) return meta def combine_meta(self, predecessors): return { "Name": _resolve_combined_names(predecessors), "Comments": ( "Object composed of a combination of these " "objects:\n{}".format( "\n- ".join(set(obj.Name for obj in predecessors)) ) ), "Category": ", ".join( set( itertools.chain(*[obj.Category.split(", ") for obj in predecessors]) ) ), "DataSource": ", ".join( set( itertools.chain( *[ obj.DataSource.split(", ") for obj in predecessors if obj.DataSource is not None ] ) ) ), } def combine(self, other, allow_duplicates=False): pass def rename(self, name): """renames self as well as the cached object Args: name (str): the name. """ self.Name = name def to_dict(self): """Return UmiBase dictionary representation.""" return {"$id": "{}".format(self.id), "Name": "{}".format(self.Name)} @classmethod def get_classref(cls, ref): return next( iter( [value for value in UmiBase.CREATED_OBJECTS if value.id == ref["$ref"]] ), None, ) def get_ref(self, ref): pass def __hash__(self): """Return the hash value of self.""" return hash((self.__class__.mro()[0].__name__, self.Name)) def __repr__(self): """Return a representation of self.""" return ":".join([str(self.id), str(self.Name)]) def __str__(self): """string representation of the object as id:Name""" return self.__repr__() def __iter__(self): """Iterate over attributes. Yields tuple of (keys, value).""" for attr, value in self.mapping().items(): yield attr, value def __copy__(self): """Create a copy of self.""" return self.__class__(**self.mapping(validate=False)) def to_ref(self): """Return a ref pointer to self.""" return {"$ref": str(self.id)} def float_mean(self, other, attr, weights=None): """Calculates the average attribute value of two floats. Can provide weights. Args: other (UmiBase): The other UmiBase object to calculate average value with. attr (str): The attribute of the UmiBase object. weights (iterable, optional): Weights of [self, other] to calculate weighted average. """ if getattr(self, attr) is None: return getattr(other, attr) if getattr(other, attr) is None: return getattr(self, attr) # If weights is a list of zeros if not np.array(weights).any(): weights = [1, 1] if not isinstance(getattr(self, attr), list) and not isinstance( getattr(other, attr), list ): if math.isnan(getattr(self, attr)): return getattr(other, attr) elif math.isnan(getattr(other, attr)): return getattr(self, attr) elif math.isnan(getattr(self, attr)) and math.isnan(getattr(other, attr)): raise ValueError("Both values for self and other are Not A Number.") else: return float( np.average( [getattr(self, attr), getattr(other, attr)], weights=weights ) ) elif getattr(self, attr) is None and getattr(other, attr) is None: return None else: # handle arrays by finding the least common multiple of the two arrays and # tiling to the full length; then, apply average self_attr_ = np.array(getattr(self, attr)) other_attr_ = np.array(getattr(other, attr)) l_ = lcm(len(self_attr_), len(other_attr_)) self_attr_ = np.tile(self_attr_, int(l_ / len(self_attr_))) other_attr_ = np.tile(other_attr_, int(l_ / len(other_attr_))) return np.average([self_attr_, other_attr_], weights=weights, axis=0) def _str_mean(self, other, attr, append=False): """Returns the combined string attributes Args: other (UmiBase): The other UmiBase object to calculate combined string. attr (str): The attribute of the UmiBase object. append (bool): Whether or not the attributes should be combined together. If False, the attribute of self will is used (other is ignored). """ if self is None: return other if other is None: return self # if self has info, but other is none, use self if getattr(self, attr) is not None and getattr(other, attr) is None: return getattr(self, attr) # if self is none, but other is not none, use other elif getattr(self, attr) is None and getattr(other, attr) is not None: return getattr(other, attr) # if both are not note, impose self elif getattr(self, attr) and getattr(other, attr): if append: return getattr(self, attr) + getattr(other, attr) else: return getattr(self, attr) # if both are None, return None else: return None def __iadd__(self, other): """Overload += to implement self.extend. Args: other: """ return UmiBase.extend(self, other, allow_duplicates=True) def extend(self, other, allow_duplicates): """Append other to self. Modify and return self. Args: other (UmiBase): Returns: UmiBase: self """ if self is None: return other if other is None: return self self.CREATED_OBJECTS.remove(self) id = self.id new_obj = self.combine(other, allow_duplicates=allow_duplicates) new_obj.id = id for key in self.mapping(validate=False): setattr(self, key, getattr(new_obj, key)) return self def validate(self): """Validate UmiObjects and fills in missing values.""" return self def mapping(self, validate=True): """Get a dict based on the object properties, useful for dict repr. Args: validate (bool): If True, try to validate object before returning the mapping. """ if validate: self.validate() return dict( id=self.id, Name=self.Name, Category=self.Category, Comments=self.Comments, DataSource=self.DataSource, ) def get_unique(self): """Return first object matching equality in the list of instantiated objects.""" if self.allow_duplicates: # We want to return the first similar object (equality) that has this name. obj = next( iter( sorted( ( x for x in UmiBase.CREATED_OBJECTS if x == self and x.Name == self.Name and type(x) == type(self) ), key=lambda x: x.unit_number, ) ), self, ) else: # We want to return the first similar object (equality) regardless of the # name. obj = next( iter( sorted( ( x for x in UmiBase.CREATED_OBJECTS if x == self and type(x) == type(self) ), key=lambda x: x.unit_number, ) ), self, ) return obj class UserSet(Hashable, MutableSet): """UserSet class.""" __hash__ = MutableSet._hash def __init__(self, iterable=()): """Initialize object.""" self.data = set(iterable) def __contains__(self, value): """Assert value is in self.data.""" return value in self.data def __iter__(self): """Iterate over self.data.""" return iter(self.data) def __len__(self): """return len of self.""" return len(self.data) def __repr__(self): """Return a representation of self.""" return repr(self.data) def __add__(self, other): """Add other to self.""" self.data.update(other.data) return self def update(self, other): """Update self with other.""" self.data.update(other.data) return self def add(self, item): """Add an item.""" self.data.add(item) def discard(self, item): """Remove a class if it is currently present.""" self.data.discard(item) class MetaData(UserSet): """Handles data of combined objects such as Name, Comments and other.""" @property def Name(self): """Get object name.""" return "+".join([obj.Name for obj in self]) @property def comments(self): """Get object comments.""" return "Object composed of a combination of these objects:\n{}".format( set(obj.Name for obj in self) ) class UniqueName(str): """Attribute unique user-defined names for :class:`UmiBase`.""" existing = set() def __new__(cls, content): """Pick a name. Will increment the name if already used.""" return str.__new__(cls, cls.create_unique(content)) @classmethod def create_unique(cls, name): """Check if name has already been used. If so, try to increment until not used. Args: name: """ if not name: return None if name not in cls.existing: cls.existing.add(name) return name else: match = re.match(r"^(.*?)(\D*)(\d+)$", name) if match: groups = list(match.groups()) pad = len(groups[-1]) groups[-1] = int(groups[-1]) groups[-1] += 1 groups[-1] = str(groups[-1]).zfill(pad) name = "".join(map(str, groups)) return cls.create_unique(name) else: return cls.create_unique(name + "_1")
frame 0, 04 frame 4, 08 setrepeat 3 frame 1, 08 frame 2, 08 dorepeat 3 frame 3, 08 endanim
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ import { ILogger } from '../logging/ILogger'; export interface MediaRequestArgs { onMediaLoaded?: (source: string) => void; onMediaLoadFailed?: (source: string, errorCode: number, error: string) => void; onRequestGraphic?: (source: string) => void; logger?: ILogger; } export declare const requestMedia: (mediaEvent: number, source: string[], args: MediaRequestArgs) => Promise<any>; export declare function ensureDefaultArgs(args: MediaRequestArgs): { onMediaLoaded: () => void; onMediaLoadFailed: () => void; onRequestGraphic: () => void; logger: ILogger; } & MediaRequestArgs;
# Sample Programs in R Welcome to Sample Programs in R! ## Sample Programs - [Hello World in R](https://therenegadecoder.com/code/hello-world-in-r) ## Fun Facts - Debut: 1993 - Developer: R Core Team - Typing: Dynamic - License: GPL v2 ## References - [R Official Website](https://www.r-project.org/) - [R Wiki](https://en.wikipedia.org/wiki/R_(programming_language)) - [R Online Editor](https://www.jdoodle.com/execute-r-online)
#!/bin/sh VERSION=0.12 if [ -d .svn ]; then svnversion -cn .|sed s/.*://g|sed s/exported//g elif [ -d CVS ]; then DATE=`date +%Y%m%d` printf "%s" "$VERSION-CVS-$DATE" else echo $VERSION fi
using System; using System.Reactive.Linq; using Reactive.Bindings; using Reactive.Bindings.Extensions; using TrainTripThinker.Core.Data; using TrainTripThinker.Core.Enums; namespace TrainTripThinker.ViewModel { public class TrainViewModel : TransportBaseViewModel { public TrainViewModel(Train model) : base(model) { Class = model.ObserveProperty(m => m.Class).ToReactiveProperty(); LineColor = model.ObserveProperty(m => m.LineColor).ToReactiveProperty(); Seat = model.ObserveProperty(m => m.Seat).Select(s => new TransportSeatViewModel(s)).ToReactiveProperty(); HasRestRoom = model.ObserveProperty(m => m.HasRestRoom).ToReactiveProperty(); MealType = model.ObserveProperty(m => m.MealType).ToReactiveProperty(); // ViewModel -> Model Class.Subscribe(x => model.Class = x).AddTo(Disposables); LineColor.Subscribe(x => model.LineColor = x).AddTo(Disposables); HasRestRoom.Subscribe(x => model.HasRestRoom = x).AddTo(Disposables); } public ReactiveProperty<TransportClass> Class { get; } public ReactiveProperty<Color32> LineColor { get; } public ReactiveProperty<TransportSeatViewModel> Seat { get; } public ReactiveProperty<bool> HasRestRoom { get; } public ReactiveProperty<MealType> MealType { get; } } }
<?php /* Общий код, который используется сразу в нескольких файлах, удобно организовать в отдельные файлы и включить их в PHP-сценарии с помощью одной из двух инструкций: include() и require(). Обе команды работают почти одинаково, за исключением одного существенного различия: * команда require() используется, когда файл должен быть включен обязательно; * команда include() — если файл, в зависимости от обстоятельств, может быть включен или нет. При отсутствии указанного файла: * команда require() выводит сообщение об ошибке и прерывает исполнение файла; * команда include() выводит предупреждение, но продолжает исполнение файла. Команды include_once() и require_once() работают так же, как include() и require(), соответственно, с тем отличием, что они защищают от повторного прикрепления кода из указанных в них файлов. */ // Файл header.php, содержащий шапку, обязательно будет добавлен только один раз: require_once('header.php'); require_once('header.php'); /* Боковая колонка будет добавлена только один раз, если будет найден файл asideleft.php: */ include_once('asideleft.php'); include_once('asideleft.php'); // Список статей будет добавлен, если будет найден файл articlemain.php include('articlemain.php'); /* Посредством инструкции include() список статей можно добавить еще один или несколько раз: */ // include('articlemain.php'); // include('articlemain.php'); /* Боковая колонка будет добавлена только один раз, если будет найден файл asideright.php: */ include_once('asideright.php'); // Файл footer.php, содержащий подвал, обязательно будет добавлен только один раз: require_once('footer.php'); ?>
#!/usr/bin/env bash # #!/bin/bash if [ $# -eq 0 ] then echo "" echo "" echo "Usage: $0 CiteKey" echo "by Le CHEN, ([email protected])" echo "Sat 25 Dec 2021 01:30:48 PM EST" echo "" echo "" exit 1 fi file=$(rg "CiteKey: $1" ~/Dropbox/Research-References/ | sed 's/info.*$/output.pdf/g') echo $file zathura $file &
package java.io abstract class Writer private[this] (_lock: Option[Object]) extends Appendable with Closeable with Flushable { protected val lock = _lock.getOrElse(this) protected def this(lock: Object) = this(Some(lock)) protected def this() = this(None) def write(c: Int): Unit = write(Array(c.toChar)) def write(cbuf: Array[Char]): Unit = write(cbuf, 0, cbuf.length) def write(cbuf: Array[Char], off: Int, len: Int): Unit def write(str: String): Unit = write(str.toCharArray) def write(str: String, off: Int, len: Int): Unit = write(str.toCharArray, off, len) def append(csq: CharSequence): Writer = { write(if (csq == null) "null" else csq.toString) this } def append(csq: CharSequence, start: Int, end: Int): Writer = { val csq1 = if (csq == null) "null" else csq write(csq1.subSequence(start, end).toString) this } def append(c: Char): Writer = { write(c.toInt) this } def flush(): Unit def close(): Unit }
class RoadSign { final String signImage, signName; RoadSign({required this.signImage, required this.signName}); } List signName = [ 'Roundabout Ahead', 'No Entry', 'Speed Limit 50km/h', 'Men At Work', 'Left Hand Curve', 'Narrow Road From Right', 'Narrow Road from Both Sides', 'Pedestrian Crossing', 'Do Not Enter', 'No Cars Allowed', 'No Right Turn', 'Stop', 'No U-turn', 'Traffic Signal', ]; List signImage = [ 'assets/images/roundabout.jpg', 'assets/images/noentry.jpg', 'assets/images/speedlimit.jpg', 'assets/images/menatwork.jpg', 'assets/images/lefthandcurve.jpg', 'assets/images/narrowroad.jpg', 'assets/images/narrowroad2.jpg', 'assets/images/pedestriancrossing.jpg', 'assets/images/donotenter.jpg', 'assets/images/nocarsallowed.jpg', 'assets/images/norightturn.jpg', 'assets/images/stop.jpg', 'assets/images/nouturn.png', 'assets/images/trafficsignal.png', ]; List<RoadSign> signs = [ RoadSign(signImage: signImage[0], signName: signName[0]), RoadSign(signImage: signImage[1], signName: signName[1]), RoadSign(signImage: signImage[2], signName: signName[2]), RoadSign(signImage: signImage[3], signName: signName[3]), RoadSign(signImage: signImage[4], signName: signName[4]), RoadSign(signImage: signImage[5], signName: signName[5]), RoadSign(signImage: signImage[6], signName: signName[6]), RoadSign(signImage: signImage[7], signName: signName[7]), RoadSign(signImage: signImage[8], signName: signName[8]), RoadSign(signImage: signImage[9], signName: signName[9]), RoadSign(signImage: signImage[10], signName: signName[10]), RoadSign(signImage: signImage[11], signName: signName[11]), RoadSign(signImage: signImage[12], signName: signName[12]), RoadSign(signImage: signImage[13], signName: signName[13]), ];
import 'package:bkci_app/widgets/PFText.dart'; import 'package:flutter/material.dart'; import 'package:bkci_app/utils/util.dart'; class TabItem { final String id; final String label; TabItem({ @required this.id, @required this.label, }); } class ToggleTab extends StatelessWidget { final bool value; final List<TabItem> tabs; final Function(TabItem tab, int index) handleTap; ToggleTab({this.value, this.handleTap, this.tabs}); @override Widget build(BuildContext context) { return Container( width: 686.px, height: 80.px, decoration: BoxDecoration( color: '#F0F1F5'.color, borderRadius: BorderRadius.circular(44.px), ), child: Stack( children: [ AnimatedPositioned( duration: const Duration(milliseconds: 200), curve: Curves.bounceInOut, top: 8.px, left: value ? 8.px : 347.px, child: Container( alignment: Alignment.center, width: 331.px, height: 64.px, decoration: BoxDecoration( borderRadius: BorderRadius.circular(36.px), color: Colors.white, ), ), ), Row( mainAxisAlignment: MainAxisAlignment.spaceAround, crossAxisAlignment: CrossAxisAlignment.center, children: tabs.map((tab) { int pos = tabs.indexOf(tab); return Expanded( flex: 1, child: InkWell( onTap: () { handleTap(tab, pos); }, child: Container( alignment: Alignment.center, child: PFMediumText( tab.label, ), ), ), ); }).toList(), ), ], ), ); } }
import about from '../../data/about.json'; import styles from './about.module.scss'; const About = () => ( <section id='About' className={styles.color}> <div className={styles.container}> <h1 className={styles.title}>{about.title}</h1> {about.content.map((c, i) => ( <p className={styles.paragraph} key={i}> {c} </p> ))} </div> </section> ); export default About;
CREATE TABLE `__database_name__`.`__table_name__`( `id` int(11) NOT NULL AUTO_INCREMENT, `facebook_id` varchar(100) DEFAULT NULL, `type` enum('user','customer','admin') NOT NULL DEFAULT 'user', `first_name` varchar(45) DEFAULT NULL, `last_name` varchar(45) DEFAULT NULL, `seo_name` varchar(100) DEFAULT NULL, `email` varchar(45) NOT NULL, `salt` varchar(10) DEFAULT NULL, `password` varchar(100) DEFAULT NULL, `status` enum('active','inactive') DEFAULT 'active', `profile_main_image` varchar(100) DEFAULT NULL, `token` varchar(50) DEFAULT NULL, `last_login_date` datetime DEFAULT NULL, `ip_address` varchar(16) DEFAULT NULL, `num_visits` int(11) DEFAULT '0', `created_date` timestamp NULL DEFAULT CURRENT_TIMESTAMP, `last_modified_date` datetime DEFAULT NULL, `last_modified_by` int(11) NULL, `is_active` tinyint(1) DEFAULT '1', `is_deleted` tinyint(1) DEFAULT '0', `deleted_date` datetime DEFAULT NULL, `ckey` varchar(50) DEFAULT NULL, `ctime` varchar(50) DEFAULT NULL, `comments` longtext, PRIMARY KEY (`id`), UNIQUE KEY `email_UNIQUE` (`email`) ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
package learnfp.monoid import org.scalatest.{WordSpecLike, Matchers} class ListMonoidTest extends WordSpecLike with Matchers { import MonoidOps._ import ListMonoid._ "list monoid" should { "append lists" in { List(1, 2, 3) |+| List(4, 5, 6) shouldBe List(1, 2, 3, 4, 5, 6) } "obey identity" in { List(1, 2, 3, 4, 5) |+| Monoid.mzero[List[Int]] shouldBe List(1, 2, 3, 4, 5) } "obey associtiativity" in { val a = List(1, 2, 3) val b = List(4, 5, 6) val c = List(7, 8, 9) a |+| b |+| c shouldBe a |+| (b |+| c) } } }
var libcpp_8h = [ [ "operator delete", "d5/dab/libcpp_8h.html#a3d97a7e2a0208075b4b37328c96ed390", null ], [ "operator delete[]", "d5/dab/libcpp_8h.html#a1d8b2d6f17242ae0d182b0f7a98ba54f", null ], [ "operator new", "d5/dab/libcpp_8h.html#a9bccb23e08907b6033c45f524578239a", null ], [ "operator new[]", "d5/dab/libcpp_8h.html#ae55853bd31de5afc92b2093f2567c007", null ] ];
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ package com.aws.greengrass.util.platforms.unix; import com.aws.greengrass.testcommons.testutilities.GGExtension; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.arrayContaining; import static org.hamcrest.Matchers.is; @ExtendWith({GGExtension.class}) class UnixPlatformTest { private static String[] command = {"echo", "hello", "world"}; @Test void GIVEN_no_user_and_no_group_WHEN_decorate_THEN_do_not_generate_sudo_with_user_and_group() { assertThat(new UnixPlatform.SudoDecorator().decorate(command), is(arrayContaining(command))); } @Test void GIVEN_user_and_group_WHEN_decorate_THEN_generate_sudo_with_user_and_group() { assertThat(new UnixPlatform.SudoDecorator() .withUser("foo") .withGroup("bar") .decorate(command), is(arrayContaining("sudo", "-n", "-E", "-H", "-u", "foo", "-g", "bar", "--", "echo", "hello", "world"))); } @Test void GIVEN_numeric_user_and_group_WHEN_decorate_THEN_generate_sudo_with_prefix() { assertThat(new UnixPlatform.SudoDecorator() .withUser("100") .withGroup("200") .decorate(command), is(arrayContaining("sudo", "-n", "-E", "-H", "-u", "#100", "-g", "#200", "--", "echo", "hello", "world"))); } @Test void GIVEN_user_WHEN_decorate_THEN_generate_sudo_without_group() { assertThat(new UnixPlatform.SudoDecorator() .withUser("foo") .decorate(command), is(arrayContaining("sudo", "-n", "-E", "-H", "-u", "foo", "--", "echo", "hello", "world"))); } }