text
stringlengths
2
99k
meta
dict
package jetbrains.mps.lang.smodel.constraints; /*Generated by MPS */ import jetbrains.mps.smodel.runtime.base.BaseConstraintsDescriptor; import jetbrains.mps.smodel.runtime.ConstraintFunction; import jetbrains.mps.smodel.runtime.ConstraintContext_CanBeChild; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import jetbrains.mps.smodel.runtime.CheckingNodeContext; import org.jetbrains.mps.openapi.model.SNode; import org.jetbrains.mps.openapi.language.SAbstractConcept; import org.jetbrains.mps.openapi.language.SContainmentLink; import jetbrains.mps.lang.smodel.generator.smodelAdapter.SNodeOperations; import jetbrains.mps.smodel.SNodePointer; import org.jetbrains.mps.openapi.language.SInterfaceConcept; import jetbrains.mps.smodel.adapter.structure.MetaAdapterFactory; import org.jetbrains.mps.openapi.language.SConcept; public class SEnumOperation_Old_Constraints extends BaseConstraintsDescriptor { public SEnumOperation_Old_Constraints() { super(CONCEPTS.SEnumOperation_Old$hZ); } @Override protected ConstraintFunction<ConstraintContext_CanBeChild, Boolean> calculateCanBeChildConstraint() { return new ConstraintFunction<ConstraintContext_CanBeChild, Boolean>() { @NotNull public Boolean invoke(@NotNull ConstraintContext_CanBeChild context, @Nullable CheckingNodeContext checkingNodeContext) { boolean result = staticCanBeAChild(context.getNode(), context.getParentNode(), context.getConcept(), context.getLink()); if (!(result) && checkingNodeContext != null) { checkingNodeContext.setBreakingNode(canBeChildBreakingPoint); } return result; } }; } private static boolean staticCanBeAChild(SNode node, SNode parentNode, SAbstractConcept childConcept, SContainmentLink link) { return SNodeOperations.isInstanceOf(parentNode, CONCEPTS.SEnumOperationInvocation$_F); } private static final SNodePointer canBeChildBreakingPoint = new SNodePointer("r:00000000-0000-4000-0000-011c895902fb(jetbrains.mps.lang.smodel.constraints)", "1227128029536563490"); private static final class CONCEPTS { /*package*/ static final SInterfaceConcept SEnumOperation_Old$hZ = MetaAdapterFactory.getInterfaceConcept(0x7866978ea0f04cc7L, 0x81bc4d213d9375e1L, 0x120ed37273dL, "jetbrains.mps.lang.smodel.structure.SEnumOperation_Old"); /*package*/ static final SConcept SEnumOperationInvocation$_F = MetaAdapterFactory.getConcept(0x7866978ea0f04cc7L, 0x81bc4d213d9375e1L, 0x120ed32e98bL, "jetbrains.mps.lang.smodel.structure.SEnumOperationInvocation"); } }
{ "pile_set_name": "Github" }
ship = Atlas V 522 version = 1.1.3 description = LEO - unknown. Use 500 series fairings. type = None size = 5.2943573,45.6513939,7.36009026 PART { part = EJ.CentaurAtlas_4292992818 partName = Part pos = -11.4471016,40.5496597,-4.916152 attPos = 0,0,0 attPos0 = -11.4471016,40.5496597,-4.916152 rot = 0,0,0,1 attRot = 0,0,0,1 attRot0 = 0,0,0,1 mir = 1,1,1 symMethod = Radial autostrutMode = Off rigidAttachment = False istg = 20 resPri = 0 dstg = 0 sidx = 1 sqor = 20 sepI = -1 attm = 0 modCost = 9.25304699 modMass = 0 modSize = 0,0,0 link = EJ.RL10C1_4292992684 link = EJ.RL10C1_4292992526 link = EJ.5xxplfBoattail_4292987714 attN = bottom,EJ.5xxplfBoattail_4292987714 EVENTS { } ACTIONS { } PARTDATA { } MODULE { name = ModuleRCSFX isEnabled = True rcsEnabled = False thrustPercentage = 100 currentShowToggles = False enableYaw = True enablePitch = True enableRoll = True enableX = True enableY = True enableZ = True useThrottle = False fullThrust = False stagingEnabled = True EVENTS { } ACTIONS { ToggleAction { actionGroup = None } } UPGRADESAPPLIED { } } MODULE { name = ModuleProbeControlPoint isEnabled = True stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } MODULE { name = ModuleCommand isEnabled = True hibernation = False hibernateOnWarp = False stagingEnabled = True EVENTS { } ACTIONS { MakeReferenceToggle { actionGroup = None } HibernateToggle { actionGroup = None active = False } } UPGRADESAPPLIED { } } MODULE { name = ModuleKerbNetAccess isEnabled = True stagingEnabled = True EVENTS { } ACTIONS { OpenKerbNetAction { actionGroup = None } } UPGRADESAPPLIED { } } MODULE { name = ModuleDataTransmitter isEnabled = True xmitIncomplete = False stagingEnabled = True EVENTS { } ACTIONS { StartTransmissionAction { actionGroup = None active = False } } UPGRADESAPPLIED { } } MODULE { name = GeometryPartModule isEnabled = True stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } MODULE { name = FARAeroPartModule isEnabled = True stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } MODULE { name = FARPartModule isEnabled = True stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } MODULE { name = ModuleFuelTanks isEnabled = True type = ServiceModule utilization = 86 mass = 1.801 _numberOfAddedMLILayers = 0 partPrevTemperature = -1 stagingEnabled = True volume = 60831.9928 EVENTS { } ACTIONS { } TANK { name = LqdOxygen note = (has insulation, pressurized) utilization = 1 mass = 7.89999976E-05 cost = 0 loss_rate = 0 temperature = 90.1500015 fillable = True techRequired = amount = 15447.597900000001 maxAmount = 15447.597900000001 } TANK { name = Kerosene note = (pressurized) utilization = 1 mass = 7.6999997E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = LqdHydrogen note = (has insulation, pressurized) utilization = 1 mass = 6.70000009E-05 cost = 0 loss_rate = 0 temperature = 20.1499996 fillable = True techRequired = amount = 45226.394899999999 maxAmount = 45226.394899999999 } TANK { name = NTO note = (pressurized) utilization = 1 mass = 8.09999983E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = UDMH note = (pressurized) utilization = 1 mass = 8.09999983E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = Hydrazine note = (pressurized) utilization = 1 mass = 8.09999983E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 108 maxAmount = 108 } TANK { name = Aerozine50 note = (pressurized) utilization = 1 mass = 8.09999983E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = MMH note = (pressurized) utilization = 1 mass = 8.09999983E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = HTP note = (pressurized) utilization = 1 mass = 8.09999983E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = AvGas note = (pressurized) utilization = 1 mass = 7.30000029E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = Nitrogen note = (pressurized) utilization = 200 mass = 9.50000031E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = IRFNA-III note = (pressurized) utilization = 1 mass = 8.49999997E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = NitrousOxide note = (pressurized) utilization = 100 mass = 9.50000031E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = Aniline note = (pressurized) utilization = 1 mass = 8.49999997E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = Ethanol75 note = (pressurized) utilization = 1 mass = 7.79999973E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = Ethanol90 note = (pressurized) utilization = 1 mass = 7.79999973E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = Ethanol note = (pressurized) utilization = 1 mass = 7.79999973E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = LqdAmmonia note = (has insulation, pressurized) utilization = 1 mass = 7.6999997E-05 cost = 0 loss_rate = 0 temperature = 237.649994 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = LqdMethane note = (has insulation, pressurized) utilization = 1 mass = 7.6999997E-05 cost = 0 loss_rate = 0 temperature = 111.449997 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = Helium note = (pressurized) utilization = 200 mass = 0.000115000003 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = ClF3 note = (pressurized) utilization = 1 mass = 0.000104999999 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = ClF5 note = (pressurized) utilization = 1 mass = 0.000104999999 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = Diborane note = (has insulation, pressurized) utilization = 1 mass = 8.2999999E-05 cost = 0 loss_rate = 0 temperature = 180.649994 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = Pentaborane note = (pressurized) utilization = 1 mass = 8.2999999E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = Ethane note = (has insulation, pressurized) utilization = 1 mass = 8.09999983E-05 cost = 0 loss_rate = 0 temperature = 184.649994 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = Ethylene note = (has insulation, pressurized) utilization = 1 mass = 8.09999983E-05 cost = 0 loss_rate = 0 temperature = 169.449997 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = OF2 note = (has insulation, pressurized) utilization = 1 mass = 8.2999999E-05 cost = 0 loss_rate = 1.6E-11 temperature = 128.399994 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = LqdFluorine note = (has insulation, pressurized) utilization = 1 mass = 0.000104999999 cost = 0 loss_rate = 8.8000000000000006E-11 temperature = 85.0400009 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = N2F4 note = (has insulation, pressurized) utilization = 1 mass = 7.50000036E-05 cost = 0 loss_rate = 0 temperature = 200.149994 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = Methanol note = (pressurized) utilization = 1 mass = 7.6999997E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = Furfuryl note = (pressurized) utilization = 1 mass = 7.89999976E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = UH25 note = (pressurized) utilization = 1 mass = 8.09999983E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = Tonka250 note = (pressurized) utilization = 1 mass = 8.09999983E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = Tonka500 note = (pressurized) utilization = 1 mass = 8.09999983E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = FLOX30 note = (has insulation, pressurized) utilization = 1 mass = 8.15000021E-05 cost = 0 loss_rate = 0 temperature = 216.149994 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = FLOX70 note = (has insulation, pressurized) utilization = 1 mass = 0.000103500002 cost = 0 loss_rate = 0 temperature = 216.149994 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = FLOX88 note = (has insulation, pressurized) utilization = 1 mass = 0.000113399998 cost = 0 loss_rate = 0 temperature = 216.149994 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = IWFNA note = (pressurized) utilization = 1 mass = 8.49999997E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = IRFNA-IV note = (pressurized) utilization = 1 mass = 8.49999997E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = AK20 note = (pressurized) utilization = 1 mass = 8.49999997E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = AK27 note = (pressurized) utilization = 1 mass = 8.49999997E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = CaveaB note = (pressurized) utilization = 1 mass = 8.49999997E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = MON1 note = (pressurized) utilization = 1 mass = 8.09999983E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = MON3 note = (pressurized) utilization = 1 mass = 8.09999983E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = MON10 note = (pressurized) utilization = 1 mass = 8.09999983E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = MON15 note = (pressurized) utilization = 1 mass = 8.09999983E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = MON20 note = (pressurized) utilization = 1 mass = 8.09999983E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = MON25 note = (pressurized) utilization = 1 mass = 8.09999983E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = ArgonGas note = (pressurized) utilization = 100 mass = 2.99999992E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = KryptonGas note = (pressurized) utilization = 100 mass = 2.99999992E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = Hydrogen note = (pressurized) utilization = 100 mass = 2.99999992E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = Oxygen note = (pressurized) utilization = 200 mass = 2.99999992E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = Food note = (pressurized) utilization = 1 mass = 9.99999975E-06 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = Water note = (pressurized) utilization = 1 mass = 9.99999975E-06 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = CarbonDioxide note = (pressurized) utilization = 200 mass = 2.99999992E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = False techRequired = amount = 0 maxAmount = 0 } TANK { name = Waste note = (pressurized) utilization = 1 mass = 9.99999975E-06 cost = 0 loss_rate = 0 temperature = 300 fillable = False techRequired = amount = 0 maxAmount = 0 } TANK { name = WasteWater note = (pressurized) utilization = 1 mass = 9.99999975E-06 cost = 0 loss_rate = 0 temperature = 300 fillable = False techRequired = amount = 0 maxAmount = 0 } TANK { name = LithiumPeroxide note = (pressurized) utilization = 1 mass = 9.99999975E-06 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = LithiumHydroxide note = (pressurized) utilization = 1 mass = 9.99999975E-06 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = PotassiumSuperoxide note = (pressurized) utilization = 1 mass = 9.99999975E-06 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = Hydyne note = (pressurized) utilization = 1 mass = 7.79999973E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = Syntin note = (pressurized) utilization = 1 mass = 7.6999997E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = LiquidFuel note = (pressurized) utilization = 1 mass = 8.09999983E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = Oxidizer note = (pressurized) utilization = 1 mass = 8.09999983E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = MonoPropellant note = (pressurized) utilization = 1 mass = 7.6999997E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = XenonGas note = (pressurized) utilization = 100 mass = 2.99999992E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = ElectricCharge note = (pressurized) utilization = 1000 mass = 0.00288999989 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 50000 maxAmount = 50000 } TANK { name = LeadBallast note = (pressurized) utilization = 1 mass = 6.50000002E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = Turpentine note = (pressurized) utilization = 1 mass = 7.79999973E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = Beryllium note = utilization = 1 mass = 8.09999983E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } UPGRADESAPPLIED { } } MODULE { name = MechJebCore isEnabled = True running = True stagingEnabled = True EVENTS { } ACTIONS { OnOrbitProgradeAction { actionGroup = None } OnOrbitRetrogradeAction { actionGroup = None } OnOrbitNormalAction { actionGroup = None } OnOrbitAntinormalAction { actionGroup = None } OnOrbitRadialInAction { actionGroup = None } OnOrbitRadialOutAction { actionGroup = None } OnKillRotationAction { actionGroup = None } OnDeactivateSmartASSAction { actionGroup = None } OnPanicAction { actionGroup = None } OnTranslatronOffAction { actionGroup = None } OnTranslatronKeepVertAction { actionGroup = None } OnTranslatronZeroSpeedAction { actionGroup = None } OnTranslatronPlusOneSpeedAction { actionGroup = None } OnTranslatronMinusOneSpeedAction { actionGroup = None } OnTranslatronToggleHSAction { actionGroup = None } OnAscentAPToggleAction { actionGroup = None } } UPGRADESAPPLIED { } } MODULE { name = ModuleTripLogger isEnabled = True stagingEnabled = True EVENTS { } ACTIONS { } Log { flight = 0 } UPGRADESAPPLIED { } } RESOURCE { name = Hydrazine amount = 108 maxAmount = 108 flowState = True isTweakable = True hideFlow = False isVisible = True flowMode = Both } RESOURCE { name = ElectricCharge amount = 50000 maxAmount = 50000 flowState = True isTweakable = True hideFlow = False isVisible = True flowMode = Both } RESOURCE { name = LqdHydrogen amount = 45226.394899999999 maxAmount = 45226.394899999999 flowState = True isTweakable = True hideFlow = False isVisible = True flowMode = Both } RESOURCE { name = LqdOxygen amount = 15447.597900000001 maxAmount = 15447.597900000001 flowState = True isTweakable = True hideFlow = False isVisible = True flowMode = Both } } PART { part = EJ.RL10C1_4292992684 partName = Part pos = -11.4471016,36.425705,-5.6519227 attPos = 0.0568267182,0.250217438,-0.735770583 attPos0 = -0.0568267778,-4.37417221,3.39059625E-09 rot = -5.9604659E-08,0.707107186,-5.96046661E-08,0.707106471 attRot = -1.78188627E-15,-0.707106233,-7.08131784E-15,0.707107306 attRot0 = -5.13146929E-08,0.793354392,-6.68748257E-08,0.608760059 mir = 1,1,1 symMethod = Radial autostrutMode = Off rigidAttachment = False istg = 19 resPri = 0 dstg = 0 sidx = 0 sqor = 19 sepI = -1 attm = 1 modCost = 0 modMass = 0 modSize = 0,0,0 sym = EJ.RL10C1_4292992526 srfN = srfAttach,EJ.CentaurAtlas_4292992818 EVENTS { } ACTIONS { } PARTDATA { } MODULE { name = ModuleEnginesRF isEnabled = True ignitions = 10 staged = False flameout = False EngineIgnited = False engineShutdown = False currentThrottle = 0 thrustPercentage = 100 manuallyOverridden = False stagingEnabled = True EVENTS { } ACTIONS { OnAction { actionGroup = None } ShutdownAction { actionGroup = None } ActivateAction { actionGroup = None } } Ullage { } UPGRADESAPPLIED { } } MODULE { name = ModuleGimbal isEnabled = True gimbalLock = False gimbalLimiter = 100 currentShowToggles = False enableYaw = True enablePitch = True enableRoll = True gimbalActive = False stagingEnabled = True EVENTS { } ACTIONS { ToggleAction { actionGroup = None } LockAction { actionGroup = None } FreeAction { actionGroup = None } TogglePitchAction { actionGroup = None } ToggleYawAction { actionGroup = None } ToggleRollAction { actionGroup = None } } UPGRADESAPPLIED { } } MODULE { name = ModuleSurfaceFX isEnabled = True stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } MODULE { name = ModuleTestSubject isEnabled = True stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } MODULE { name = EngineGroupModule isEnabled = True EngineGroupId = stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } MODULE { name = GeometryPartModule isEnabled = True stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } MODULE { name = FARAeroPartModule isEnabled = True stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } MODULE { name = FARPartModule isEnabled = True stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } MODULE { name = ModuleEngineConfigs isEnabled = True configuration = RL10A-4-1-2 techLevel = -1 thrustRating = maxThrust modded = False stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } } PART { part = EJ.RL10C1_4292992526 partName = Part pos = -11.4471016,36.425705,-4.1803813 attPos = -0.0568266511,0.250217438,0.735770583 attPos0 = 0.0568267778,-4.37417221,-8.3600753E-09 rot = 5.9604659E-08,-0.707106471,-5.96046519E-08,0.707107067 attRot = -1.78188627E-15,-0.707106233,-7.08131784E-15,0.707107306 attRot0 = 5.9604659E-08,-0.707106471,-5.96046519E-08,0.707107067 mir = 1,1,1 symMethod = Radial autostrutMode = Off rigidAttachment = False istg = 19 resPri = 0 dstg = 0 sidx = 0 sqor = 19 sepI = -1 attm = 1 modCost = 0 modMass = 0 modSize = 0,0,0 sym = EJ.RL10C1_4292992684 srfN = srfAttach,EJ.CentaurAtlas_4292992818 EVENTS { } ACTIONS { } PARTDATA { } MODULE { name = ModuleEnginesRF isEnabled = True ignitions = 10 staged = False flameout = False EngineIgnited = False engineShutdown = False currentThrottle = 0 thrustPercentage = 100 manuallyOverridden = False stagingEnabled = True EVENTS { } ACTIONS { OnAction { actionGroup = None } ShutdownAction { actionGroup = None } ActivateAction { actionGroup = None } } Ullage { } UPGRADESAPPLIED { } } MODULE { name = ModuleGimbal isEnabled = True gimbalLock = False gimbalLimiter = 100 currentShowToggles = False enableYaw = True enablePitch = True enableRoll = True gimbalActive = False stagingEnabled = True EVENTS { } ACTIONS { ToggleAction { actionGroup = None } LockAction { actionGroup = None } FreeAction { actionGroup = None } TogglePitchAction { actionGroup = None } ToggleYawAction { actionGroup = None } ToggleRollAction { actionGroup = None } } UPGRADESAPPLIED { } } MODULE { name = ModuleSurfaceFX isEnabled = True stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } MODULE { name = ModuleTestSubject isEnabled = True stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } MODULE { name = EngineGroupModule isEnabled = True EngineGroupId = stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } MODULE { name = GeometryPartModule isEnabled = True stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } MODULE { name = FARAeroPartModule isEnabled = True stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } MODULE { name = FARPartModule isEnabled = True stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } MODULE { name = ModuleEngineConfigs isEnabled = True configuration = RL10A-4-1-2 techLevel = -1 thrustRating = maxThrust modded = False stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } } PART { part = EJ.5xxplfBoattail_4292987714 partName = Part pos = -11.4471016,36.9446602,-4.916152 attPos = 0,0,0 attPos0 = 0,-3.60499954,0 rot = 0,0,0,1 attRot = 0,0,0,1 attRot0 = 0,0,0,1 mir = 1,1,1 symMethod = Radial autostrutMode = Off rigidAttachment = False istg = 20 resPri = 0 dstg = 1 sidx = 2 sqor = 20 sepI = 20 attm = 0 modCost = 0 modMass = 0 modSize = 0,0,0 link = EJ.Interstage_4292987568 attN = bottom,EJ.Interstage_4292987568 attN = top,EJ.CentaurAtlas_4292992818 EVENTS { } ACTIONS { } PARTDATA { } MODULE { name = ModuleDecouple isEnabled = True ejectionForcePercent = 100 isDecoupled = False stagingEnabled = True EVENTS { } ACTIONS { DecoupleAction { actionGroup = None } } UPGRADESAPPLIED { } } MODULE { name = GeometryPartModule isEnabled = True stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } MODULE { name = FARAeroPartModule isEnabled = True stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } MODULE { name = FARPartModule isEnabled = True stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } MODULE { name = ModuleToggleCrossfeed isEnabled = True crossfeedStatus = False stagingEnabled = True EVENTS { } ACTIONS { ToggleAction { actionGroup = None } EnableAction { actionGroup = None } DisableAction { actionGroup = None } } UPGRADESAPPLIED { } } } PART { part = EJ.Interstage_4292987568 partName = Part pos = -11.4471016,34.7846603,-4.916152 attPos = 0,0,0 attPos0 = 0,-2.15999985,0 rot = 0,0,0,1 attRot = 0,0,0,1 attRot0 = 0,0,0,1 mir = 1,1,1 symMethod = Radial autostrutMode = Off rigidAttachment = False istg = 20 resPri = 0 dstg = 2 sidx = -1 sqor = -1 sepI = 20 attm = 0 modCost = 0 modMass = 0 modSize = 0,0,0 link = EJ.CCB_4292987468 attN = bottom,EJ.CCB_4292987468 attN = top,EJ.5xxplfBoattail_4292987714 EVENTS { } ACTIONS { } PARTDATA { } MODULE { name = GeometryPartModule isEnabled = True stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } MODULE { name = FARAeroPartModule isEnabled = True stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } MODULE { name = FARPartModule isEnabled = True stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } } PART { part = EJ.CCB_4292987468 partName = Part pos = -11.4471016,18.35466,-4.916152 attPos = 0,0,0 attPos0 = 0,-16.4300003,0 rot = 0,0,0,1 attRot = 0,0,0,1 attRot0 = 0,0,0,1 mir = 1,1,1 symMethod = Radial autostrutMode = Off rigidAttachment = False istg = 20 resPri = 0 dstg = 2 sidx = -1 sqor = -1 sepI = 20 attm = 0 modCost = 12.1276636 modMass = 0 modSize = 0,0,0 link = EJ.AtlasPants_4292987422 link = EJ.RD180_4292987378 link = KK.AV.CCB.Seperator_4292987022 link = KK.AV.CCB.Seperator_4292986960 link = KK.AV.CCB.Seperator_4292986898 link = KK.AV.CCB.Seperator_4292986836 link = KK.AV.CCB.Seperator_4292986774 link = KK.AV.CCB.Seperator_4292986712 link = KK.AV.CCB.Seperator_4292986650 link = KK.AV.CCB.Seperator_4292986588 link = EJ.AJ60aDecoupler_4292986526 link = EJ.AJ60aDecoupler_4292986376 link = launchClamp1_4292986226 link = launchClamp1_4292986110 link = launchClamp1_4292985994 link = launchClamp1_4292985878 attN = top,EJ.Interstage_4292987568 attN = bottom,EJ.AtlasPants_4292987422 attN = bottom01,EJ.RD180_4292987378 EVENTS { } ACTIONS { } PARTDATA { } MODULE { name = GeometryPartModule isEnabled = True stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } MODULE { name = FARAeroPartModule isEnabled = True stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } MODULE { name = FARPartModule isEnabled = True stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } MODULE { name = ModuleFuelTanks isEnabled = True type = Default utilization = 86 mass = 14.0600004 _numberOfAddedMLILayers = 0 partPrevTemperature = -1 stagingEnabled = True volume = 275180.41930000001 EVENTS { } ACTIONS { } TANK { name = LqdOxygen note = (lacks insulation) utilization = 1 mass = 1.40000002E-05 cost = 0 loss_rate = 0 temperature = 90.1500015 fillable = True techRequired = amount = 182169.43770000001 maxAmount = 182169.43770000001 } TANK { name = Kerosene note = utilization = 1 mass = 1.20000004E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 93010.981599999999 maxAmount = 93010.981599999999 } TANK { name = LqdHydrogen note = (basic insulation) utilization = 1 mass = 1.99999999E-06 cost = 0 loss_rate = 0 temperature = 20.1499996 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = NTO note = utilization = 1 mass = 1.6E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = UDMH note = utilization = 1 mass = 1.6E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = Aerozine50 note = utilization = 1 mass = 1.6E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = MMH note = utilization = 1 mass = 1.6E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = HTP note = utilization = 1 mass = 1.6E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = AvGas note = utilization = 1 mass = 7.99999998E-06 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = IRFNA-III note = utilization = 1 mass = 1.99999995E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = NitrousOxide note = (pressurized) utilization = 100 mass = 2.99999992E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = Aniline note = utilization = 1 mass = 1.99999995E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = Ethanol75 note = utilization = 1 mass = 1.29999999E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = Ethanol90 note = utilization = 1 mass = 1.29999999E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = Ethanol note = utilization = 1 mass = 1.29999999E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = LqdAmmonia note = (lacks insulation) utilization = 1 mass = 1.20000004E-05 cost = 0 loss_rate = 0 temperature = 237.649994 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = LqdMethane note = (lacks insulation) utilization = 1 mass = 1.20000004E-05 cost = 0 loss_rate = 0 temperature = 111.449997 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = ClF3 note = utilization = 1 mass = 3.9999999E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = ClF5 note = utilization = 1 mass = 3.9999999E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = Diborane note = (lacks insulation) utilization = 1 mass = 1.80000006E-05 cost = 0 loss_rate = 2.3000000000000001E-10 temperature = 180.649994 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = Pentaborane note = utilization = 1 mass = 1.80000006E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = Ethane note = (lacks insulation) utilization = 1 mass = 1.6E-05 cost = 0 loss_rate = 2.5000000000000002E-10 temperature = 184.649994 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = Ethylene note = (lacks insulation) utilization = 1 mass = 1.6E-05 cost = 0 loss_rate = 3.4999999999999998E-10 temperature = 169.449997 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = OF2 note = (lacks insulation) utilization = 1 mass = 1.80000006E-05 cost = 0 loss_rate = 1.0000000000000001E-09 temperature = 128.399994 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = LqdFluorine note = (lacks insulation) utilization = 1 mass = 3.9999999E-05 cost = 0 loss_rate = 5.4999999999999996E-09 temperature = 85.0400009 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = N2F4 note = (lacks insulation) utilization = 1 mass = 9.99999975E-06 cost = 0 loss_rate = 1.7000000000000001E-10 temperature = 200.149994 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = Methanol note = utilization = 1 mass = 1.20000004E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = Furfuryl note = utilization = 1 mass = 1.40000002E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = UH25 note = utilization = 1 mass = 1.6E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = Tonka250 note = utilization = 1 mass = 1.6E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = Tonka500 note = utilization = 1 mass = 1.6E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = FLOX30 note = (lacks insulation) utilization = 1 mass = 1.65000001E-05 cost = 0 loss_rate = 1E-10 temperature = 216.149994 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = FLOX70 note = (lacks insulation) utilization = 1 mass = 3.84999985E-05 cost = 0 loss_rate = 1E-10 temperature = 216.149994 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = FLOX88 note = (lacks insulation) utilization = 1 mass = 4.84000011E-05 cost = 0 loss_rate = 1E-10 temperature = 216.149994 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = IWFNA note = utilization = 1 mass = 1.99999995E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = IRFNA-IV note = utilization = 1 mass = 1.99999995E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = AK20 note = utilization = 1 mass = 1.99999995E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = AK27 note = utilization = 1 mass = 1.99999995E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = MON1 note = utilization = 1 mass = 1.6E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = MON3 note = utilization = 1 mass = 1.6E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = MON10 note = utilization = 1 mass = 1.6E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = MON15 note = utilization = 1 mass = 1.6E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = MON20 note = utilization = 1 mass = 1.6E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = MON25 note = utilization = 1 mass = 1.6E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = Hydyne note = utilization = 1 mass = 1.29999999E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = Syntin note = utilization = 1 mass = 1.20000004E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = LiquidFuel note = utilization = 1 mass = 1.6E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = Oxidizer note = utilization = 1 mass = 1.6E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = LeadBallast note = utilization = 1 mass = 0 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } TANK { name = Beryllium note = utilization = 1 mass = 1.6E-05 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 0 maxAmount = 0 } UPGRADESAPPLIED { } } RESOURCE { name = LqdOxygen amount = 182169.43770000001 maxAmount = 182169.43770000001 flowState = True isTweakable = True hideFlow = False isVisible = True flowMode = Both } RESOURCE { name = Kerosene amount = 93010.981599999999 maxAmount = 93010.981599999999 flowState = True isTweakable = True hideFlow = False isVisible = True flowMode = Both } } PART { part = EJ.AtlasPants_4292987422 partName = Part pos = -11.4471016,3.36665726,-4.916152 attPos = 0,0,0 attPos0 = 0,-14.9880028,0 rot = 0,0,0,1 attRot = 0,0,0,1 attRot0 = 0,0,0,1 mir = 1,1,1 symMethod = Radial autostrutMode = Off rigidAttachment = False istg = 20 resPri = 0 dstg = 2 sidx = -1 sqor = -1 sepI = 20 attm = 0 modCost = 0 modMass = 0 modSize = 0,0,0 attN = top,EJ.CCB_4292987468 EVENTS { } ACTIONS { } PARTDATA { } MODULE { name = GeometryPartModule isEnabled = True stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } MODULE { name = FARAeroPartModule isEnabled = True stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } MODULE { name = FARPartModule isEnabled = True stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } } PART { part = EJ.RD180_4292987378 partName = Part pos = -11.4471016,4.66865921,-4.916152 attPos = 0,0,0 attPos0 = 0,-13.6860008,0 rot = 0,0,0,1 attRot = 0,0,0,1 attRot0 = 0,0,0,1 mir = 1,1,1 symMethod = Radial autostrutMode = Off rigidAttachment = False istg = 23 resPri = 0 dstg = 2 sidx = 0 sqor = 23 sepI = 20 attm = 0 modCost = 0 modMass = 0 modSize = 0,0,0 attN = top,EJ.CCB_4292987468 EVENTS { } ACTIONS { } PARTDATA { } MODULE { name = ModuleEnginesRF isEnabled = True ignitions = 1 staged = False flameout = False EngineIgnited = False engineShutdown = False currentThrottle = 0 thrustPercentage = 100 manuallyOverridden = False stagingEnabled = True EVENTS { } ACTIONS { OnAction { actionGroup = None } ShutdownAction { actionGroup = None } ActivateAction { actionGroup = None } } Ullage { } UPGRADESAPPLIED { } } MODULE { name = ModuleGimbal isEnabled = True gimbalLock = False gimbalLimiter = 100 currentShowToggles = False enableYaw = True enablePitch = True enableRoll = True gimbalActive = False stagingEnabled = True EVENTS { } ACTIONS { ToggleAction { actionGroup = None } LockAction { actionGroup = None } FreeAction { actionGroup = None } TogglePitchAction { actionGroup = None } ToggleYawAction { actionGroup = None } ToggleRollAction { actionGroup = None } } UPGRADESAPPLIED { } } MODULE { name = ModuleGimbal isEnabled = True gimbalLock = False gimbalLimiter = 100 currentShowToggles = False enableYaw = True enablePitch = True enableRoll = True gimbalActive = False stagingEnabled = True EVENTS { } ACTIONS { ToggleAction { actionGroup = None } LockAction { actionGroup = None } FreeAction { actionGroup = None } TogglePitchAction { actionGroup = None } ToggleYawAction { actionGroup = None } ToggleRollAction { actionGroup = None } } UPGRADESAPPLIED { } } MODULE { name = ModuleSurfaceFX isEnabled = True stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } MODULE { name = FXModuleLookAtConstraint isEnabled = True stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } MODULE { name = EngineGroupModule isEnabled = True EngineGroupId = stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } MODULE { name = GeometryPartModule isEnabled = True stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } MODULE { name = FARAeroPartModule isEnabled = True stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } MODULE { name = FARPartModule isEnabled = True stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } MODULE { name = ModuleEngineConfigs isEnabled = True configuration = RD-180 techLevel = -1 thrustRating = maxThrust modded = False stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } RESOURCE { name = TEATEB amount = 1 maxAmount = 1 flowState = True isTweakable = True hideFlow = False isVisible = True flowMode = Both } } PART { part = KK.AV.CCB.Seperator_4292987022 partName = Part pos = -12.3981733,32.3989639,-6.56345654 attPos = 0,0,0 attPos0 = -0.951071799,14.0443039,-1.6473043 rot = 0,0.965925813,0,-0.258819073 attRot = 0,0,0,1 attRot0 = 0,0.965925813,0,-0.258819073 mir = 1,1,1 symMethod = Radial autostrutMode = Off rigidAttachment = False istg = 20 resPri = 0 dstg = 2 sidx = 0 sqor = 20 sepI = 20 attm = 1 modCost = 0 modMass = 0 modSize = 0,0,0 sym = KK.AV.CCB.Seperator_4292986960 sym = KK.AV.CCB.Seperator_4292986898 sym = KK.AV.CCB.Seperator_4292986836 sym = KK.AV.CCB.Seperator_4292986774 sym = KK.AV.CCB.Seperator_4292986712 sym = KK.AV.CCB.Seperator_4292986650 sym = KK.AV.CCB.Seperator_4292986588 srfN = srfAttach,EJ.CCB_4292987468 EVENTS { } ACTIONS { } PARTDATA { } MODULE { name = ModuleEnginesRF isEnabled = True ignitions = -1 staged = False flameout = False EngineIgnited = False engineShutdown = False currentThrottle = 0 thrustPercentage = 100 manuallyOverridden = False stagingEnabled = True EVENTS { } ACTIONS { OnAction { actionGroup = None } ShutdownAction { actionGroup = None } ActivateAction { actionGroup = None } } Ullage { } UPGRADESAPPLIED { } } MODULE { name = GeometryPartModule isEnabled = True stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } MODULE { name = FARAeroPartModule isEnabled = True stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } MODULE { name = FARPartModule isEnabled = True stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } MODULE { name = ModuleEngineConfigs isEnabled = True configuration = CCB techLevel = -1 thrustRating = maxThrust modded = False stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } RESOURCE { name = PSPC amount = 19.399999999999999 maxAmount = 19.399999999999999 flowState = True isTweakable = True hideFlow = False isVisible = True flowMode = Both } } PART { part = KK.AV.CCB.Seperator_4292986960 partName = Part pos = -13.2844315,32.3989639,-5.40846252 attPos = 0,0,0 attPos0 = -1.83732939,14.0443039,-0.492310613 rot = 0,0.793353319,0,-0.608761549 attRot = 0,0,0,1 attRot0 = 0,0.793353319,0,-0.608761549 mir = 1,1,1 symMethod = Radial autostrutMode = Off rigidAttachment = False istg = 20 resPri = 0 dstg = 2 sidx = 0 sqor = 20 sepI = 20 attm = 1 modCost = 0 modMass = 0 modSize = 0,0,0 sym = KK.AV.CCB.Seperator_4292987022 sym = KK.AV.CCB.Seperator_4292986898 sym = KK.AV.CCB.Seperator_4292986836 sym = KK.AV.CCB.Seperator_4292986774 sym = KK.AV.CCB.Seperator_4292986712 sym = KK.AV.CCB.Seperator_4292986650 sym = KK.AV.CCB.Seperator_4292986588 srfN = srfAttach,EJ.CCB_4292987468 EVENTS { } ACTIONS { } PARTDATA { } MODULE { name = ModuleEnginesRF isEnabled = True ignitions = -1 staged = False flameout = False EngineIgnited = False engineShutdown = False currentThrottle = 0 thrustPercentage = 100 manuallyOverridden = False stagingEnabled = True EVENTS { } ACTIONS { OnAction { actionGroup = None } ShutdownAction { actionGroup = None } ActivateAction { actionGroup = None } } Ullage { } UPGRADESAPPLIED { } } MODULE { name = GeometryPartModule isEnabled = True stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } MODULE { name = FARAeroPartModule isEnabled = True stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } MODULE { name = FARPartModule isEnabled = True stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } MODULE { name = ModuleEngineConfigs isEnabled = True configuration = CCB techLevel = -1 thrustRating = maxThrust modded = False stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } RESOURCE { name = PSPC amount = 19.399999999999999 maxAmount = 19.399999999999999 flowState = True isTweakable = True hideFlow = False isVisible = True flowMode = Both } } PART { part = KK.AV.CCB.Seperator_4292986898 partName = Part pos = -13.0944061,32.3989639,-3.96508026 attPos = 0,0,0 attPos0 = -1.6473043,14.0443039,0.95107162 rot = 0,0.49999997,0,-0.866025388 attRot = 0,0,0,1 attRot0 = 0,0.49999997,0,-0.866025388 mir = 1,1,1 symMethod = Radial autostrutMode = Off rigidAttachment = False istg = 20 resPri = 0 dstg = 2 sidx = 0 sqor = 20 sepI = 20 attm = 1 modCost = 0 modMass = 0 modSize = 0,0,0 sym = KK.AV.CCB.Seperator_4292987022 sym = KK.AV.CCB.Seperator_4292986960 sym = KK.AV.CCB.Seperator_4292986836 sym = KK.AV.CCB.Seperator_4292986774 sym = KK.AV.CCB.Seperator_4292986712 sym = KK.AV.CCB.Seperator_4292986650 sym = KK.AV.CCB.Seperator_4292986588 srfN = srfAttach,EJ.CCB_4292987468 EVENTS { } ACTIONS { } PARTDATA { } MODULE { name = ModuleEnginesRF isEnabled = True ignitions = -1 staged = False flameout = False EngineIgnited = False engineShutdown = False currentThrottle = 0 thrustPercentage = 100 manuallyOverridden = False stagingEnabled = True EVENTS { } ACTIONS { OnAction { actionGroup = None } ShutdownAction { actionGroup = None } ActivateAction { actionGroup = None } } Ullage { } UPGRADESAPPLIED { } } MODULE { name = GeometryPartModule isEnabled = True stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } MODULE { name = FARAeroPartModule isEnabled = True stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } MODULE { name = FARPartModule isEnabled = True stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } MODULE { name = ModuleEngineConfigs isEnabled = True configuration = CCB techLevel = -1 thrustRating = maxThrust modded = False stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } RESOURCE { name = PSPC amount = 19.399999999999999 maxAmount = 19.399999999999999 flowState = True isTweakable = True hideFlow = False isVisible = True flowMode = Both } } PART { part = KK.AV.CCB.Seperator_4292986836 partName = Part pos = -11.9394121,32.3989639,-3.07882309 attPos = 0,0,0 attPos0 = -0.492310762,14.0443039,1.83732927 rot = 0,0.13052617,0,-0.991444886 attRot = 0,0,0,1 attRot0 = 0,0.13052617,0,-0.991444886 mir = 1,1,1 symMethod = Radial autostrutMode = Off rigidAttachment = False istg = 20 resPri = 0 dstg = 2 sidx = 0 sqor = 20 sepI = 20 attm = 1 modCost = 0 modMass = 0 modSize = 0,0,0 sym = KK.AV.CCB.Seperator_4292987022 sym = KK.AV.CCB.Seperator_4292986960 sym = KK.AV.CCB.Seperator_4292986898 sym = KK.AV.CCB.Seperator_4292986774 sym = KK.AV.CCB.Seperator_4292986712 sym = KK.AV.CCB.Seperator_4292986650 sym = KK.AV.CCB.Seperator_4292986588 srfN = srfAttach,EJ.CCB_4292987468 EVENTS { } ACTIONS { } PARTDATA { } MODULE { name = ModuleEnginesRF isEnabled = True ignitions = -1 staged = False flameout = False EngineIgnited = False engineShutdown = False currentThrottle = 0 thrustPercentage = 100 manuallyOverridden = False stagingEnabled = True EVENTS { } ACTIONS { OnAction { actionGroup = None } ShutdownAction { actionGroup = None } ActivateAction { actionGroup = None } } Ullage { } UPGRADESAPPLIED { } } MODULE { name = GeometryPartModule isEnabled = True stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } MODULE { name = FARAeroPartModule isEnabled = True stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } MODULE { name = FARPartModule isEnabled = True stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } MODULE { name = ModuleEngineConfigs isEnabled = True configuration = CCB techLevel = -1 thrustRating = maxThrust modded = False stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } RESOURCE { name = PSPC amount = 19.399999999999999 maxAmount = 19.399999999999999 flowState = True isTweakable = True hideFlow = False isVisible = True flowMode = Both } } PART { part = KK.AV.CCB.Seperator_4292986774 partName = Part pos = -10.4960299,32.3989639,-3.26884747 attPos = 0,0,0 attPos0 = 0.951071918,14.0443039,1.64730418 rot = 0,-0.258819103,0,-0.965925813 attRot = 0,0,0,1 attRot0 = 0,-0.258819103,0,-0.965925813 mir = 1,1,1 symMethod = Radial autostrutMode = Off rigidAttachment = False istg = 20 resPri = 0 dstg = 2 sidx = 0 sqor = 20 sepI = 20 attm = 1 modCost = 0 modMass = 0 modSize = 0,0,0 sym = KK.AV.CCB.Seperator_4292987022 sym = KK.AV.CCB.Seperator_4292986960 sym = KK.AV.CCB.Seperator_4292986898 sym = KK.AV.CCB.Seperator_4292986836 sym = KK.AV.CCB.Seperator_4292986712 sym = KK.AV.CCB.Seperator_4292986650 sym = KK.AV.CCB.Seperator_4292986588 srfN = srfAttach,EJ.CCB_4292987468 EVENTS { } ACTIONS { } PARTDATA { } MODULE { name = ModuleEnginesRF isEnabled = True ignitions = -1 staged = False flameout = False EngineIgnited = False engineShutdown = False currentThrottle = 0 thrustPercentage = 100 manuallyOverridden = False stagingEnabled = True EVENTS { } ACTIONS { OnAction { actionGroup = None } ShutdownAction { actionGroup = None } ActivateAction { actionGroup = None } } Ullage { } UPGRADESAPPLIED { } } MODULE { name = GeometryPartModule isEnabled = True stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } MODULE { name = FARAeroPartModule isEnabled = True stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } MODULE { name = FARPartModule isEnabled = True stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } MODULE { name = ModuleEngineConfigs isEnabled = True configuration = CCB techLevel = -1 thrustRating = maxThrust modded = False stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } RESOURCE { name = PSPC amount = 19.399999999999999 maxAmount = 19.399999999999999 flowState = True isTweakable = True hideFlow = False isVisible = True flowMode = Both } } PART { part = KK.AV.CCB.Seperator_4292986712 partName = Part pos = -9.60977268,32.3989639,-4.42384148 attPos = 0,0,0 attPos0 = 1.83732951,14.0443039,0.492310494 rot = 0,-0.608761549,0,-0.79335326 attRot = 0,0,0,1 attRot0 = 0,-0.608761549,0,-0.79335326 mir = 1,1,1 symMethod = Radial autostrutMode = Off rigidAttachment = False istg = 20 resPri = 0 dstg = 2 sidx = 0 sqor = 20 sepI = 20 attm = 1 modCost = 0 modMass = 0 modSize = 0,0,0 sym = KK.AV.CCB.Seperator_4292987022 sym = KK.AV.CCB.Seperator_4292986960 sym = KK.AV.CCB.Seperator_4292986898 sym = KK.AV.CCB.Seperator_4292986836 sym = KK.AV.CCB.Seperator_4292986774 sym = KK.AV.CCB.Seperator_4292986650 sym = KK.AV.CCB.Seperator_4292986588 srfN = srfAttach,EJ.CCB_4292987468 EVENTS { } ACTIONS { } PARTDATA { } MODULE { name = ModuleEnginesRF isEnabled = True ignitions = -1 staged = False flameout = False EngineIgnited = False engineShutdown = False currentThrottle = 0 thrustPercentage = 100 manuallyOverridden = False stagingEnabled = True EVENTS { } ACTIONS { OnAction { actionGroup = None } ShutdownAction { actionGroup = None } ActivateAction { actionGroup = None } } Ullage { } UPGRADESAPPLIED { } } MODULE { name = GeometryPartModule isEnabled = True stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } MODULE { name = FARAeroPartModule isEnabled = True stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } MODULE { name = FARPartModule isEnabled = True stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } MODULE { name = ModuleEngineConfigs isEnabled = True configuration = CCB techLevel = -1 thrustRating = maxThrust modded = False stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } RESOURCE { name = PSPC amount = 19.399999999999999 maxAmount = 19.399999999999999 flowState = True isTweakable = True hideFlow = False isVisible = True flowMode = Both } } PART { part = KK.AV.CCB.Seperator_4292986650 partName = Part pos = -9.79979801,32.3989639,-5.86722374 attPos = 0,0,0 attPos0 = 1.64730418,14.0443039,-0.951071858 rot = 0,-0.866025388,0,-0.49999997 attRot = 0,0,0,1 attRot0 = 0,-0.866025388,0,-0.49999997 mir = 1,1,1 symMethod = Radial autostrutMode = Off rigidAttachment = False istg = 20 resPri = 0 dstg = 2 sidx = 0 sqor = 20 sepI = 20 attm = 1 modCost = 0 modMass = 0 modSize = 0,0,0 sym = KK.AV.CCB.Seperator_4292987022 sym = KK.AV.CCB.Seperator_4292986960 sym = KK.AV.CCB.Seperator_4292986898 sym = KK.AV.CCB.Seperator_4292986836 sym = KK.AV.CCB.Seperator_4292986774 sym = KK.AV.CCB.Seperator_4292986712 sym = KK.AV.CCB.Seperator_4292986588 srfN = srfAttach,EJ.CCB_4292987468 EVENTS { } ACTIONS { } PARTDATA { } MODULE { name = ModuleEnginesRF isEnabled = True ignitions = -1 staged = False flameout = False EngineIgnited = False engineShutdown = False currentThrottle = 0 thrustPercentage = 100 manuallyOverridden = False stagingEnabled = True EVENTS { } ACTIONS { OnAction { actionGroup = None } ShutdownAction { actionGroup = None } ActivateAction { actionGroup = None } } Ullage { } UPGRADESAPPLIED { } } MODULE { name = GeometryPartModule isEnabled = True stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } MODULE { name = FARAeroPartModule isEnabled = True stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } MODULE { name = FARPartModule isEnabled = True stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } MODULE { name = ModuleEngineConfigs isEnabled = True configuration = CCB techLevel = -1 thrustRating = maxThrust modded = False stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } RESOURCE { name = PSPC amount = 19.399999999999999 maxAmount = 19.399999999999999 flowState = True isTweakable = True hideFlow = False isVisible = True flowMode = Both } } PART { part = KK.AV.CCB.Seperator_4292986588 partName = Part pos = -10.9547911,32.3989639,-6.75348091 attPos = 0,0,0 attPos0 = 0.492310196,14.0443039,-1.83732951 rot = 0,-0.991444886,0,-0.130525991 attRot = 0,0,0,1 attRot0 = 0,-0.991444886,0,-0.130525991 mir = 1,1,1 symMethod = Radial autostrutMode = Off rigidAttachment = False istg = 20 resPri = 0 dstg = 2 sidx = 0 sqor = 20 sepI = 20 attm = 1 modCost = 0 modMass = 0 modSize = 0,0,0 sym = KK.AV.CCB.Seperator_4292987022 sym = KK.AV.CCB.Seperator_4292986960 sym = KK.AV.CCB.Seperator_4292986898 sym = KK.AV.CCB.Seperator_4292986836 sym = KK.AV.CCB.Seperator_4292986774 sym = KK.AV.CCB.Seperator_4292986712 sym = KK.AV.CCB.Seperator_4292986650 srfN = srfAttach,EJ.CCB_4292987468 EVENTS { } ACTIONS { } PARTDATA { } MODULE { name = ModuleEnginesRF isEnabled = True ignitions = -1 staged = False flameout = False EngineIgnited = False engineShutdown = False currentThrottle = 0 thrustPercentage = 100 manuallyOverridden = False stagingEnabled = True EVENTS { } ACTIONS { OnAction { actionGroup = None } ShutdownAction { actionGroup = None } ActivateAction { actionGroup = None } } Ullage { } UPGRADESAPPLIED { } } MODULE { name = GeometryPartModule isEnabled = True stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } MODULE { name = FARAeroPartModule isEnabled = True stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } MODULE { name = FARPartModule isEnabled = True stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } MODULE { name = ModuleEngineConfigs isEnabled = True configuration = CCB techLevel = -1 thrustRating = maxThrust modded = False stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } RESOURCE { name = PSPC amount = 19.399999999999999 maxAmount = 19.399999999999999 flowState = True isTweakable = True hideFlow = False isVisible = True flowMode = Both } } PART { part = EJ.AJ60aDecoupler_4292986526 partName = Part pos = -11.4471016,10.4129181,-2.99566174 attPos = 0,0,0 attPos0 = 0,-7.94174194,1.92049026 rot = 0,0.707106829,0,0.707106829 attRot = 0,0,0,1 attRot0 = 0,0.707106829,0,0.707106829 mir = 1,1,1 symMethod = Radial autostrutMode = Off rigidAttachment = False istg = 21 resPri = 0 dstg = 3 sidx = 0 sqor = 21 sepI = 21 attm = 1 modCost = 0 modMass = 0 modSize = 0,0,0 link = EJ.AJ60A_4292986456 srfN = srfAttach,EJ.CCB_4292987468 EVENTS { } ACTIONS { } PARTDATA { } MODULE { name = ModuleAnchoredDecoupler isEnabled = True ejectionForcePercent = 100 isDecoupled = False stagingEnabled = True EVENTS { } ACTIONS { DecoupleAction { actionGroup = None } } UPGRADESAPPLIED { } } MODULE { name = ModuleToggleCrossfeed isEnabled = True crossfeedStatus = False stagingEnabled = True EVENTS { } ACTIONS { ToggleAction { actionGroup = None } EnableAction { actionGroup = None } DisableAction { actionGroup = None } } UPGRADESAPPLIED { } } MODULE { name = GeometryPartModule isEnabled = True stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } MODULE { name = FARAeroPartModule isEnabled = True stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } MODULE { name = FARPartModule isEnabled = True stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } } PART { part = EJ.AJ60A_4292986456 partName = Part pos = -11.4471016,10.6275864,-2.12620902 attPos = 0.139125943,0,0 attPos0 = -1.00857699,0.214668274,-1.1920924E-07 rot = 0.00416805781,-8.94069672E-08,4.65661287E-10,0.999991417 attRot = 0,0,0,1 attRot0 = 0.00294726132,-0.707100749,0.00294726179,0.70710063 mir = 1,1,1 symMethod = Radial autostrutMode = Off rigidAttachment = False istg = 22 resPri = 0 dstg = 4 sidx = 2 sqor = 22 sepI = 21 attm = 1 modCost = 694.186401 modMass = 0 modSize = 0,0,0 srfN = srfAttach,EJ.AJ60aDecoupler_4292986526 EVENTS { } ACTIONS { } PARTDATA { } MODULE { name = ModuleEnginesRF isEnabled = True ignitions = 1 staged = False flameout = False EngineIgnited = False engineShutdown = False currentThrottle = 0 thrustPercentage = 100 manuallyOverridden = False stagingEnabled = True EVENTS { } ACTIONS { OnAction { actionGroup = None } ShutdownAction { actionGroup = None } ActivateAction { actionGroup = None } } Ullage { } UPGRADESAPPLIED { } } MODULE { name = ModuleSurfaceFX isEnabled = True stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } MODULE { name = GeometryPartModule isEnabled = True stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } MODULE { name = FARAeroPartModule isEnabled = True stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } MODULE { name = FARPartModule isEnabled = True stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } MODULE { name = ModuleFuelTanks isEnabled = True type = HTPB utilization = 86 mass = 5.23999977 _numberOfAddedMLILayers = 0 partPrevTemperature = -1 stagingEnabled = True volume = 24040 EVENTS { } ACTIONS { } TANK { name = HTPB note = utilization = 1 mass = 0 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 24040 maxAmount = 24040 } UPGRADESAPPLIED { } } MODULE { name = ModuleEngineConfigs isEnabled = True configuration = AJ-60A techLevel = -1 thrustRating = maxThrust modded = False stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } RESOURCE { name = HTPB amount = 24040 maxAmount = 24040 flowState = True isTweakable = True hideFlow = False isVisible = True flowMode = Both } } PART { part = EJ.AJ60aDecoupler_4292986376 partName = Part pos = -12.0054817,10.4134521,-6.73086357 attPos = 0,0,0 attPos0 = -0.558380425,-7.94120789,-1.81471169 rot = 0,-0.600070894,0,0.799946904 attRot = 0,-0.0436193869,0,-0.999048114 attRot0 = 0,-0.600070894,0,0.799946904 mir = 1,1,1 symMethod = Radial autostrutMode = Off rigidAttachment = False istg = 21 resPri = 0 dstg = 3 sidx = 1 sqor = 21 sepI = 21 attm = 1 modCost = 0 modMass = 0 modSize = 0,0,0 link = EJ.AJ60A_4292986306 srfN = srfAttach,EJ.CCB_4292987468 EVENTS { } ACTIONS { } PARTDATA { } MODULE { name = ModuleAnchoredDecoupler isEnabled = True ejectionForcePercent = 100 isDecoupled = False stagingEnabled = True EVENTS { } ACTIONS { DecoupleAction { actionGroup = None } } UPGRADESAPPLIED { } } MODULE { name = ModuleToggleCrossfeed isEnabled = True crossfeedStatus = False stagingEnabled = True EVENTS { } ACTIONS { ToggleAction { actionGroup = None } EnableAction { actionGroup = None } DisableAction { actionGroup = None } } UPGRADESAPPLIED { } } MODULE { name = GeometryPartModule isEnabled = True stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } MODULE { name = FARAeroPartModule isEnabled = True stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } MODULE { name = FARPartModule isEnabled = True stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } } PART { part = EJ.AJ60A_4292986306 partName = Part pos = -12.2487812,10.6281204,-7.56558228 attPos = 0.139125943,0,0 attPos0 = -1.00857699,0.214668274,-1.1920924E-07 rot = 0.000589086674,-0.989953518,0.00412621815,0.141332328 attRot = 0,0,0,1 attRot0 = 0.00294726132,-0.707100749,0.00294726179,0.70710063 mir = 1,1,1 symMethod = Radial autostrutMode = Off rigidAttachment = False istg = 22 resPri = 0 dstg = 4 sidx = 3 sqor = 22 sepI = 21 attm = 1 modCost = 694.186401 modMass = 0 modSize = 0,0,0 srfN = srfAttach,EJ.AJ60aDecoupler_4292986376 EVENTS { } ACTIONS { } PARTDATA { } MODULE { name = ModuleEnginesRF isEnabled = True ignitions = 1 staged = False flameout = False EngineIgnited = False engineShutdown = False currentThrottle = 0 thrustPercentage = 100 manuallyOverridden = False stagingEnabled = True EVENTS { } ACTIONS { OnAction { actionGroup = None } ShutdownAction { actionGroup = None } ActivateAction { actionGroup = None } } Ullage { } UPGRADESAPPLIED { } } MODULE { name = ModuleSurfaceFX isEnabled = True stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } MODULE { name = GeometryPartModule isEnabled = True stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } MODULE { name = FARAeroPartModule isEnabled = True stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } MODULE { name = FARPartModule isEnabled = True stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } MODULE { name = ModuleFuelTanks isEnabled = True type = HTPB utilization = 86 mass = 5.23999977 _numberOfAddedMLILayers = 0 partPrevTemperature = -1 stagingEnabled = True volume = 24040 EVENTS { } ACTIONS { } TANK { name = HTPB note = utilization = 1 mass = 0 cost = 0 loss_rate = 0 temperature = 300 fillable = True techRequired = amount = 24040 maxAmount = 24040 } UPGRADESAPPLIED { } } MODULE { name = ModuleEngineConfigs isEnabled = True configuration = AJ-60A techLevel = -1 thrustRating = maxThrust modded = False stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } RESOURCE { name = HTPB amount = 24040 maxAmount = 24040 flowState = True isTweakable = True hideFlow = False isVisible = True flowMode = Both } } PART { part = launchClamp1_4292986226 partName = Part pos = -9.08523369,5.26416779,-6.27977753 attPos = 0,0,0 attPos0 = 2.36186814,-13.0904922,-1.36362553 rot = 0,0.49999997,0,-0.866025388 attRot = 0,0,0,1 attRot0 = 0,0.49999997,0,-0.866025388 mir = 1,1,1 symMethod = Radial autostrutMode = Off rigidAttachment = False istg = 22 resPri = 0 dstg = 2 sidx = 0 sqor = 22 sepI = 22 attm = 1 modCost = 0 modMass = 0 modSize = 0,0,0 sym = launchClamp1_4292986110 srfN = srfAttach,EJ.CCB_4292987468 EVENTS { } ACTIONS { } PARTDATA { } MODULE { name = LaunchClamp isEnabled = True scaleFactor = 2.34794354 height = 5.92431641 stagingEnabled = True towerRot = 0,-0.49999997,0,-0.866025388 EVENTS { } ACTIONS { ReleaseClamp { actionGroup = None } } UPGRADESAPPLIED { } } MODULE { name = ModuleGenerator isEnabled = True generatorIsActive = False throttle = 0 stagingEnabled = True EVENTS { } ACTIONS { ToggleAction { actionGroup = None active = False } ActivateAction { actionGroup = None active = False } ShutdownAction { actionGroup = None active = False } } UPGRADESAPPLIED { } } MODULE { name = ModuleTestSubject isEnabled = True stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } MODULE { name = RefuelingPump isEnabled = True enablePump = True pump_rate = 100 stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } MODULE { name = FARPartModule isEnabled = True stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } } PART { part = launchClamp1_4292986110 partName = Part pos = -13.8089695,5.26416779,-3.55252647 attPos = 0,0,0 attPos0 = -2.3618679,-13.0904922,1.36362576 rot = 0,-0.866025448,0,-0.49999997 attRot = 0,0,0,1 attRot0 = 0,-0.866025448,0,-0.49999997 mir = 1,1,1 symMethod = Radial autostrutMode = Off rigidAttachment = False istg = 22 resPri = 0 dstg = 2 sidx = 0 sqor = 22 sepI = 22 attm = 1 modCost = 0 modMass = 0 modSize = 0,0,0 sym = launchClamp1_4292986226 srfN = srfAttach,EJ.CCB_4292987468 EVENTS { } ACTIONS { } PARTDATA { } MODULE { name = LaunchClamp isEnabled = True scaleFactor = 2.34794354 height = 5.92431641 stagingEnabled = True towerRot = 0,0.866025448,0,-0.49999997 EVENTS { } ACTIONS { ReleaseClamp { actionGroup = None } } UPGRADESAPPLIED { } } MODULE { name = ModuleGenerator isEnabled = True generatorIsActive = False throttle = 0 stagingEnabled = True EVENTS { } ACTIONS { ToggleAction { actionGroup = None active = False } ActivateAction { actionGroup = None active = False } ShutdownAction { actionGroup = None active = False } } UPGRADESAPPLIED { } } MODULE { name = ModuleTestSubject isEnabled = True stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } MODULE { name = RefuelingPump isEnabled = True enablePump = True pump_rate = 100 stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } MODULE { name = FARPartModule isEnabled = True stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } } PART { part = launchClamp1_4292985994 partName = Part pos = -8.71931076,5.23638535,-4.916152 attPos = 0,0,0 attPos0 = 2.72779107,-13.1182747,2.10689905E-07 rot = 0,0.707106829,0,-0.707106829 attRot = 0,0,0,1 attRot0 = 0,0.707106829,0,-0.707106829 mir = 1,1,1 symMethod = Radial autostrutMode = Off rigidAttachment = False istg = 22 resPri = 0 dstg = 2 sidx = 1 sqor = 22 sepI = 22 attm = 1 modCost = 0 modMass = 0 modSize = 0,0,0 sym = launchClamp1_4292985878 srfN = srfAttach,EJ.CCB_4292987468 EVENTS { } ACTIONS { } PARTDATA { } MODULE { name = LaunchClamp isEnabled = True scaleFactor = 2.33693075 height = 5.89653778 stagingEnabled = True towerRot = 0,-0.707106829,0,-0.707106829 EVENTS { } ACTIONS { ReleaseClamp { actionGroup = None } } UPGRADESAPPLIED { } } MODULE { name = ModuleGenerator isEnabled = True generatorIsActive = False throttle = 0 stagingEnabled = True EVENTS { } ACTIONS { ToggleAction { actionGroup = None active = False } ActivateAction { actionGroup = None active = False } ShutdownAction { actionGroup = None active = False } } UPGRADESAPPLIED { } } MODULE { name = ModuleTestSubject isEnabled = True stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } MODULE { name = RefuelingPump isEnabled = True enablePump = True pump_rate = 100 stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } MODULE { name = FARPartModule isEnabled = True stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } } PART { part = launchClamp1_4292985878 partName = Part pos = -14.1748924,5.23638535,-4.916152 attPos = 0,0,0 attPos0 = -2.72779107,-13.1182747,2.77796062E-08 rot = 0,-0.707106888,0,-0.707106769 attRot = 0,0,0,1 attRot0 = 0,-0.707106888,0,-0.707106769 mir = 1,1,1 symMethod = Radial autostrutMode = Off rigidAttachment = False istg = 22 resPri = 0 dstg = 2 sidx = 1 sqor = 22 sepI = 22 attm = 1 modCost = 0 modMass = 0 modSize = 0,0,0 sym = launchClamp1_4292985994 srfN = srfAttach,EJ.CCB_4292987468 EVENTS { } ACTIONS { } PARTDATA { } MODULE { name = LaunchClamp isEnabled = True scaleFactor = 2.33693075 height = 5.89653778 stagingEnabled = True towerRot = 0,0.707106888,0,-0.707106769 EVENTS { } ACTIONS { ReleaseClamp { actionGroup = None } } UPGRADESAPPLIED { } } MODULE { name = ModuleGenerator isEnabled = True generatorIsActive = False throttle = 0 stagingEnabled = True EVENTS { } ACTIONS { ToggleAction { actionGroup = None active = False } ActivateAction { actionGroup = None active = False } ShutdownAction { actionGroup = None active = False } } UPGRADESAPPLIED { } } MODULE { name = ModuleTestSubject isEnabled = True stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } MODULE { name = RefuelingPump isEnabled = True enablePump = True pump_rate = 100 stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } MODULE { name = FARPartModule isEnabled = True stagingEnabled = True EVENTS { } ACTIONS { } UPGRADESAPPLIED { } } }
{ "pile_set_name": "Github" }
<UserControl x:Class="ZdfFlatUI.Test.UITest.UCTCascaderBoxTest" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:System="clr-namespace:System;assembly=mscorlib" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:local="clr-namespace:ZdfFlatUI.Test.UITest" xmlns:WPF.UI="clr-namespace:ZdfFlatUI;assembly=WPF.UI" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" d:DesignHeight="300" d:DesignWidth="600" mc:Ignorable="d"> <UserControl.Resources> <PathGeometry x:Key="Icon_Right" Figures="M8.59,16.58L13.17,12 8.59,7.41 10,6 16,12 10,18 8.59,16.58z" /> <Style TargetType="{x:Type RadioButton}"> <Setter Property="Focusable" Value="False" /> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type RadioButton}"> <Border x:Name="Bd" Grid.Column="1" Background="Transparent" Padding="5"> <Path x:Name="ExpandPath" Data="{StaticResource Icon_Right}" Fill="Black" HorizontalAlignment="Right" VerticalAlignment="Center" Stretch="Uniform" Width="5" /> </Border> <ControlTemplate.Triggers> <Trigger Property="IsChecked" Value="True"> <Setter TargetName="Bd" Property="Background" Value="#F3F3F3" /> <Setter TargetName="ExpandPath" Property="Fill" Value="#FF595959" /> <Setter TargetName="ExpandPath" Property="Stroke" Value="#FF262626" /> </Trigger> <Trigger Property="IsMouseOver" Value="True"> <Setter TargetName="ExpandPath" Property="Stroke" Value="#FF27C7F7" /> <Setter TargetName="ExpandPath" Property="Fill" Value="#FFCCEEFB" /> </Trigger> <MultiTrigger> <MultiTrigger.Conditions> <Condition Property="IsMouseOver" Value="True" /> <Condition Property="IsChecked" Value="True" /> </MultiTrigger.Conditions> <Setter TargetName="ExpandPath" Property="Stroke" Value="#FF1CC4F7" /> <Setter TargetName="ExpandPath" Property="Fill" Value="#FF82DFFB" /> </MultiTrigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> </UserControl.Resources> <UniformGrid Columns="1"> <WPF.UI:Cascader x:Name="treeView" VerticalAlignment="Center" Height="28" Width="400" /> <WPF.UI:Cascader x:Name="treeView1" VerticalAlignment="Center" Height="28" Width="400" Separator=" - "/> </UniformGrid> </UserControl>
{ "pile_set_name": "Github" }
<Project Sdk="MSBuild.Sdk.Extras"> <PropertyGroup> <Description>Interactive Extensions Providers Library used to build query providers and express queries over enumerable sequences.</Description> <AssemblyTitle>Interactive Extensions - Providers Library</AssemblyTitle> <TargetFrameworks>net45;netstandard1.0;netstandard2.0</TargetFrameworks> <PackageTags>Ix;Interactive;Extensions;Enumerable</PackageTags> </PropertyGroup> <PropertyGroup Condition="'$(TargetFramework)' == 'netstandard1.0'"> <DefineConstants>$(DefineConstants);CRIPPLED_REFLECTION</DefineConstants> </PropertyGroup> <ItemGroup> <EmbeddedResource Include="Properties\System.Interactive.Providers.rd.xml" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\System.Interactive\System.Interactive.csproj" /> <ReferenceAssemblyProjectReference Include="..\refs\System.Interactive.Providers.Ref\System.Interactive.Providers.Ref.csproj" /> </ItemGroup> <ItemGroup Condition="'$(TargetFramework)' == 'netstandard1.0'"> <PackageReference Include="System.Linq.Queryable" Version="4.3.0" /> </ItemGroup> </Project>
{ "pile_set_name": "Github" }
source 'https://rubygems.org' gem 'rake', '< 11.0' gem 'railties', '~> 4.1.0' gem 'rspec-rails', '~> 3.2.1' gemspec path: '../'
{ "pile_set_name": "Github" }
{ "title":"Subresource Integrity", "description":"Subresource Integrity enables browsers to verify that file is delivered without unexpected manipulation.", "spec":"http://www.w3.org/TR/SRI/", "status":"rec", "links":[ { "url":"https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity", "title":"Subresource Integrity (MDN)" }, { "url":"https://www.srihash.org/", "title":"SRI generation and browser support test" }, { "url":"https://sritest.io", "title":"SRI hash webpage scanner" }, { "url":"https://bugs.webkit.org/show_bug.cgi?id=148363", "title":"WebKit feature request bug" } ], "bugs":[ ], "categories":[ "HTML5", "Security" ], "stats":{ "ie":{ "5.5":"n", "6":"n", "7":"n", "8":"n", "9":"n", "10":"n", "11":"n" }, "edge":{ "12":"n", "13":"n", "14":"n", "15":"n", "16":"n", "17":"n" }, "firefox":{ "2":"n", "3":"n", "3.5":"n", "3.6":"n", "4":"n", "5":"n", "6":"n", "7":"n", "8":"n", "9":"n", "10":"n", "11":"n", "12":"n", "13":"n", "14":"n", "15":"n", "16":"n", "17":"n", "18":"n", "19":"n", "20":"n", "21":"n", "22":"n", "23":"n", "24":"n", "25":"n", "26":"n", "27":"n", "28":"n", "29":"n", "30":"n", "31":"n", "32":"n", "33":"n", "34":"n", "35":"n", "36":"n", "37":"n", "38":"n", "39":"n", "40":"n", "41":"n", "42":"n", "43":"y", "44":"y", "45":"y", "46":"y", "47":"y", "48":"y", "49":"y", "50":"y", "51":"y", "52":"y", "53":"y", "54":"y", "55":"y", "56":"y", "57":"y", "58":"y", "59":"y", "60":"y" }, "chrome":{ "4":"n", "5":"n", "6":"n", "7":"n", "8":"n", "9":"n", "10":"n", "11":"n", "12":"n", "13":"n", "14":"n", "15":"n", "16":"n", "17":"n", "18":"n", "19":"n", "20":"n", "21":"n", "22":"n", "23":"n", "24":"n", "25":"n", "26":"n", "27":"n", "28":"n", "29":"n", "30":"n", "31":"n", "32":"n", "33":"n", "34":"n", "35":"n", "36":"n", "37":"n", "38":"n", "39":"n", "40":"n", "41":"n", "42":"n", "43":"n", "44":"n", "45":"y", "46":"y", "47":"y", "48":"y", "49":"y", "50":"y", "51":"y", "52":"y", "53":"y", "54":"y", "55":"y", "56":"y", "57":"y", "58":"y", "59":"y", "60":"y", "61":"y", "62":"y", "63":"y", "64":"y", "65":"y" }, "safari":{ "3.1":"n", "3.2":"n", "4":"n", "5":"n", "5.1":"n", "6":"n", "6.1":"n", "7":"n", "7.1":"n", "8":"n", "9":"n", "9.1":"n", "10":"n", "10.1":"n", "11":"y", "TP":"y" }, "opera":{ "9":"n", "9.5-9.6":"n", "10.0-10.1":"n", "10.5":"n", "10.6":"n", "11":"n", "11.1":"n", "11.5":"n", "11.6":"n", "12":"n", "12.1":"n", "15":"n", "16":"n", "17":"n", "18":"n", "19":"n", "20":"n", "21":"n", "22":"n", "23":"n", "24":"n", "25":"n", "26":"n", "27":"n", "28":"n", "29":"n", "30":"n", "31":"n", "32":"y", "33":"y", "34":"y", "35":"y", "36":"y", "37":"y", "38":"y", "39":"y", "40":"y", "41":"y", "42":"y", "43":"y", "44":"y", "45":"y", "46":"y", "47":"y", "48":"y", "49":"y", "50":"y" }, "ios_saf":{ "3.2":"n", "4.0-4.1":"n", "4.2-4.3":"n", "5.0-5.1":"n", "6.0-6.1":"n", "7.0-7.1":"n", "8":"n", "8.1-8.4":"n", "9.0-9.2":"n", "9.3":"n", "10.0-10.2":"n", "10.3":"n", "11":"n d #1" }, "op_mini":{ "all":"n" }, "android":{ "2.1":"n", "2.2":"n", "2.3":"n", "3":"n", "4":"n", "4.1":"n", "4.2-4.3":"n", "4.4":"n", "4.4.3-4.4.4":"n", "56":"y" }, "bb":{ "7":"n", "10":"n" }, "op_mob":{ "10":"n", "11":"n", "11.1":"n", "11.5":"n", "12":"n", "12.1":"n", "37":"y" }, "and_chr":{ "61":"y" }, "and_ff":{ "56":"y" }, "ie_mob":{ "10":"n", "11":"n" }, "and_uc":{ "11.4":"n" }, "samsung":{ "4":"n", "5":"y" }, "and_qq":{ "1.2":"y" }, "baidu":{ "7.12":"y" } }, "notes":"", "notes_by_num":{ "1":"Can be enabled via the \"Experimental Features\" developer menu" }, "usage_perc_y":65.17, "usage_perc_a":0, "ucprefix":false, "parent":"", "keywords":"SRI, security, hash", "ie_id":"subresourceintegrity", "chrome_id":"6183089948590080", "firefox_id":"subresource-integrity", "webkit_id":"feature-subresource-integrity", "shown":true }
{ "pile_set_name": "Github" }
// Copyright 2015 Google Inc. All rights reserved. // Use of this source code is governed by the Apache 2.0 // license that can be found in the LICENSE file. // +build appengine package internal import ( "appengine" netcontext "golang.org/x/net/context" ) func init() { appengineStandard = true } func DefaultVersionHostname(ctx netcontext.Context) string { c := fromContext(ctx) if c == nil { panic(errNotAppEngineContext) } return appengine.DefaultVersionHostname(c) } func Datacenter(_ netcontext.Context) string { return appengine.Datacenter() } func ServerSoftware() string { return appengine.ServerSoftware() } func InstanceID() string { return appengine.InstanceID() } func IsDevAppServer() bool { return appengine.IsDevAppServer() } func RequestID(ctx netcontext.Context) string { c := fromContext(ctx) if c == nil { panic(errNotAppEngineContext) } return appengine.RequestID(c) } func ModuleName(ctx netcontext.Context) string { c := fromContext(ctx) if c == nil { panic(errNotAppEngineContext) } return appengine.ModuleName(c) } func VersionID(ctx netcontext.Context) string { c := fromContext(ctx) if c == nil { panic(errNotAppEngineContext) } return appengine.VersionID(c) } func fullyQualifiedAppID(ctx netcontext.Context) string { c := fromContext(ctx) if c == nil { panic(errNotAppEngineContext) } return c.FullyQualifiedAppID() }
{ "pile_set_name": "Github" }
{ "ramlVersion": "RAML10", "type": "Api", "specification": { "types": [ { "SimpleType1": { "name": "SimpleType1", "displayName": "SimpleType1", "typePropertyKind": "TYPE_EXPRESSION", "type": [ "object" ], "properties": { "property1": { "name": "property1", "displayName": "property1", "typePropertyKind": "TYPE_EXPRESSION", "type": [ "string" ], "required": true, "__METADATA__": { "primitiveValuesMeta": { "displayName": { "calculated": true }, "required": { "insertedAsDefault": true } } }, "sourceMap": { "path": "apiInvalid.raml" } }, "property2": { "name": "property2", "displayName": "property2", "typePropertyKind": "TYPE_EXPRESSION", "type": [ "string" ], "required": true, "__METADATA__": { "primitiveValuesMeta": { "displayName": { "calculated": true }, "required": { "insertedAsDefault": true } } }, "sourceMap": { "path": "apiInvalid.raml" } } }, "__METADATA__": { "primitiveValuesMeta": { "displayName": { "calculated": true }, "type": { "insertedAsDefault": true } } }, "sourceMap": { "path": "apiInvalid.raml" } } }, { "SimpleType2": { "name": "SimpleType2", "displayName": "SimpleType2", "typePropertyKind": "TYPE_EXPRESSION", "type": [ "object" ], "properties": { "property3": { "name": "property3", "displayName": "property3", "typePropertyKind": "TYPE_EXPRESSION", "type": [ "string" ], "required": true, "__METADATA__": { "primitiveValuesMeta": { "displayName": { "calculated": true }, "required": { "insertedAsDefault": true } } }, "sourceMap": { "path": "apiInvalid.raml" } }, "property4": { "name": "property4", "displayName": "property4", "typePropertyKind": "TYPE_EXPRESSION", "type": [ "string" ], "required": true, "__METADATA__": { "primitiveValuesMeta": { "displayName": { "calculated": true }, "required": { "insertedAsDefault": true } } }, "sourceMap": { "path": "apiInvalid.raml" } } }, "__METADATA__": { "primitiveValuesMeta": { "displayName": { "calculated": true }, "type": { "insertedAsDefault": true } } }, "sourceMap": { "path": "apiInvalid.raml" } } }, { "SimpleUnion": { "name": "SimpleUnion", "displayName": "SimpleUnion", "typePropertyKind": "TYPE_EXPRESSION", "type": [ "SimpleType1 | SimpleType2" ], "__METADATA__": { "primitiveValuesMeta": { "displayName": { "calculated": true } } }, "sourceMap": { "path": "apiInvalid.raml" } } }, { "TypeWithUnionProps": { "name": "TypeWithUnionProps", "displayName": "TypeWithUnionProps", "typePropertyKind": "TYPE_EXPRESSION", "type": [ "object" ], "example": { "unionArray": [ { "property1": "val1", "property4": "val2" }, { "property3": "val3", "property4": "val4" } ] }, "properties": { "unionArray": { "name": "unionArray", "displayName": "unionArray", "typePropertyKind": "TYPE_EXPRESSION", "type": [ "array" ], "required": true, "__METADATA__": { "primitiveValuesMeta": { "displayName": { "calculated": true }, "required": { "insertedAsDefault": true } } }, "sourceMap": { "path": "apiInvalid.raml" }, "items": "SimpleUnion" } }, "__METADATA__": { "primitiveValuesMeta": { "displayName": { "calculated": true } } }, "sourceMap": { "path": "apiInvalid.raml" }, "structuredExample": { "value": "{\n \"unionArray\": [\n {\n \"property1\": \"val1\",\n \"property4\": \"val2\"\n },\n {\n \"property3\": \"val3\",\n \"property4\": \"val4\"\n }\n ]\n}", "strict": true, "name": null, "structuredValue": { "unionArray": [ { "property1": "val1", "property4": "val2" }, { "property3": "val3", "property4": "val4" } ] }, "sourceMap": { "path": "apiInvalid.raml" } } } } ], "title": "API", "sourceMap": { "path": "apiInvalid.raml" } }, "errors": [ { "code": "UNION_TYPE_FAILURE_DETAILS", "message": "Union type option does not pass validation (SimpleType1: Required property 'property2' is missing)", "path": "apiInvalid.raml", "range": { "start": { "line": 24, "column": 10, "position": 380 }, "end": { "line": 25, "column": 25, "position": 421 } } }, { "code": "UNION_TYPE_FAILURE_DETAILS", "message": "Union type option does not pass validation (SimpleType2: Required property 'property3' is missing)", "path": "apiInvalid.raml", "range": { "start": { "line": 24, "column": 10, "position": 380 }, "end": { "line": 25, "column": 25, "position": 421 } } }, { "code": "UNION_TYPE_FAILURE", "message": "Union type options do not pass validation", "path": "apiInvalid.raml", "range": { "start": { "line": 24, "column": 10, "position": 380 }, "end": { "line": 25, "column": 25, "position": 421 } } } ] }
{ "pile_set_name": "Github" }
/* Copyright The Kubernetes Authors. 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. */ // Code generated by client-gen. DO NOT EDIT. // This package has the automatically generated typed clients. package v1beta1
{ "pile_set_name": "Github" }
{ "texture" : "mobs/cold_spirit.png", "width" : 16, "height" : 16, "idle" : { "fps" : 6, "looped" : true, "frames" : [0,1,2] }, "run" : { "fps" : 8, "looped" : true, "frames" : [0,1,2] }, "attack" : { "fps" : 6, "looped" : false, "frames" : [3,2,1] }, "die" : { "fps" : 10, "looped" : false, "frames" : [4,5,6,7,8,9] }, "bloodColor" : "0xFFDDDDFF" }
{ "pile_set_name": "Github" }
#! @PYTHON3@ # # Copyright (c) 2010 Nicira, Inc. # # 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. from __future__ import print_function import binascii import getopt import struct import sys class PcapException(Exception): pass class PcapReader(object): def __init__(self, file_name): self.file = open(file_name, "rb") header = self.file.read(24) if len(header) != 24: raise PcapException("end of file reading pcap header") magic, version, thiszone, sigfigs, snaplen, network = \ struct.unpack(">6I", header) if magic == 0xa1b2c3d4 or magic == 0xa1b23c4d: self.header_format = ">4I" elif magic == 0xd4c3b2a1 or magic == 0x4d3cb2a1: self.header_format = "<4I" else: raise PcapException("bad magic %u reading pcap file " "(expected 0xa1b2c3d4, 0xa1b23c4d, 0x4d3cb2a1 or " "0xd4c3b2a1)" % magic) def read(self): header = self.file.read(16) if len(header) == 0: return None elif len(header) != 16: raise PcapException("end of file within pcap record header") ts_sec, ts_usec, incl_len, orig_len = struct.unpack(self.header_format, header) packet = self.file.read(incl_len) if len(packet) != incl_len: raise PcapException("end of file reading pcap packet data") return packet argv0 = sys.argv[0] def usage(): print("""\ %(argv0)s: print pcap file packet data as hex usage: %(argv0)s FILE where FILE is a PCAP file. The following options are also available: -h, --help display this help message -V, --version display version information\ """ % {'argv0': argv0}) sys.exit(0) if __name__ == "__main__": try: try: options, args = getopt.gnu_getopt(sys.argv[1:], 'hV', ['help', 'version']) except getopt.GetoptException as geo: sys.stderr.write("%s: %s\n" % (argv0, geo.msg)) sys.exit(1) for key, value in options: if key in ['-h', '--help']: usage() elif key in ['-V', '--version']: print("ovs-pcap (Open vSwitch) @VERSION@") else: sys.exit(0) if len(args) != 1: sys.stderr.write("%s: exactly 1 non-option argument required " "(use --help for help)\n" % argv0) sys.exit(1) reader = PcapReader(args[0]) while True: packet = reader.read() if packet is None: break print(binascii.hexlify(packet).decode().strip()) except PcapException as e: sys.stderr.write("%s: %s\n" % (argv0, e)) sys.exit(1) # Local variables: # mode: python # End:
{ "pile_set_name": "Github" }
TT_ADOBE_IDS ============ A list of valid values for the 'encoding_id' for TT_PLATFORM_ADOBE charmaps. This is a FreeType-specific extension! .. data:: TT_ADOBE_ID_STANDARD Adobe standard encoding. .. data:: TT_ADOBE_ID_EXPERT Adobe expert encoding. .. data:: TT_ADOBE_ID_CUSTOM Adobe custom encoding. .. data:: TT_ADOBE_ID_LATIN_1 Adobe Latin 1 encoding.
{ "pile_set_name": "Github" }
"use strict"; // This example adds three custom symbols to a polyline. function initMap() { const map = new google.maps.Map(document.getElementById("map"), { zoom: 6, center: { lat: 20.291, lng: 153.027, }, mapTypeId: "terrain", }); // Define the custom symbols. All symbols are defined via SVG path notation. // They have varying stroke color, fill color, stroke weight, // opacity and rotation properties. const symbolOne = { path: "M -2,0 0,-2 2,0 0,2 z", strokeColor: "#F00", fillColor: "#F00", fillOpacity: 1, }; const symbolTwo = { path: "M -1,0 A 1,1 0 0 0 -3,0 1,1 0 0 0 -1,0M 1,0 A 1,1 0 0 0 3,0 1,1 0 0 0 1,0M -3,3 Q 0,5 3,3", strokeColor: "#00F", rotation: 45, }; const symbolThree = { path: "M -2,-2 2,2 M 2,-2 -2,2", strokeColor: "#292", strokeWeight: 4, }; // Create the polyline and add the symbols via the 'icons' property. const line = new google.maps.Polyline({ path: [ { lat: 22.291, lng: 153.027, }, { lat: 18.291, lng: 153.027, }, ], icons: [ { icon: symbolOne, offset: "0%", }, { icon: symbolTwo, offset: "50%", }, { icon: symbolThree, offset: "100%", }, ], map: map, }); }
{ "pile_set_name": "Github" }
fileFormatVersion: 2 guid: e14c4c87d3a36824f818d1be40708fd2 timeCreated: 1470840504 licenseType: Pro ModelImporter: serializedVersion: 22 fileIDToRecycleName: 100000: Bip001 100002: Bip001 Head 100004: Bip001 L Calf 100006: Bip001 L Clavicle 100008: Bip001 L Foot 100010: Bip001 L Forearm 100012: Bip001 L Hand 100014: Bip001 L Thigh 100016: Bip001 L Toe0 100018: Bip001 L UpperArm 100020: Bip001 Neck 100022: Bip001 Pelvis 100024: Bip001 R Calf 100026: Bip001 R Clavicle 100028: Bip001 R Foot 100030: Bip001 R Forearm 100032: Bip001 R Hand 100034: Bip001 R Thigh 100036: Bip001 R Toe0 100038: Bip001 R UpperArm 100040: Bip001 Spine 100042: Bip001 Spine1 100044: origin 100046: //RootNode 100048: Bip001 skirt_correct 100050: Bip001 Head 1 400000: Bip001 400002: Bip001 Head 400004: Bip001 L Calf 400006: Bip001 L Clavicle 400008: Bip001 L Foot 400010: Bip001 L Forearm 400012: Bip001 L Hand 400014: Bip001 L Thigh 400016: Bip001 L Toe0 400018: Bip001 L UpperArm 400020: Bip001 Neck 400022: Bip001 Pelvis 400024: Bip001 R Calf 400026: Bip001 R Clavicle 400028: Bip001 R Foot 400030: Bip001 R Forearm 400032: Bip001 R Hand 400034: Bip001 R Thigh 400036: Bip001 R Toe0 400038: Bip001 R UpperArm 400040: Bip001 Spine 400042: Bip001 Spine1 400044: origin 400046: //RootNode 400048: Bip001 skirt_correct 400050: Bip001 Head 1 2300000: Bip001 Head 3300000: Bip001 Head 4300000: Bip001 Head 7400000: Death 9500000: //RootNode 11100000: //RootNode externalObjects: {} materials: importMaterials: 0 autoMapExternalMaterials: 1 materialName: 0 materialSearch: 1 materialLocation: 0 animations: legacyGenerateAnimations: 4 bakeSimulation: 0 resampleCurves: 1 optimizeGameObjects: 0 motionNodeName: rigImportErrors: rigImportWarnings: animationImportErrors: animationImportWarnings: animationRetargetingWarnings: animationDoRetargetingWarnings: 0 importAnimatedCustomProperties: 0 animationCompression: 1 animationRotationError: 0.5 animationPositionError: 0.5 animationScaleError: 0.5 animationWrapMode: 0 extraExposedTransformPaths: [] extraUserProperties: [] clipAnimations: - serializedVersion: 16 name: Death takeName: Take 001 firstFrame: 0 lastFrame: 30 wrapMode: 0 orientationOffsetY: 0 level: 0 cycleOffset: 0 loop: 0 hasAdditiveReferencePose: 0 loopTime: 0 loopBlend: 0 loopBlendOrientation: 0 loopBlendPositionY: 0 loopBlendPositionXZ: 0 keepOriginalOrientation: 0 keepOriginalPositionY: 1 keepOriginalPositionXZ: 0 heightFromFeet: 0 mirror: 0 bodyMask: 01000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000 curves: [] events: [] transformMask: - path: weight: 1 - path: Bip001 weight: 1 - path: Bip001/Bip001 Pelvis weight: 1 - path: Bip001/Bip001 Pelvis/Bip001 L Thigh weight: 1 - path: Bip001/Bip001 Pelvis/Bip001 L Thigh/Bip001 L Calf weight: 1 - path: Bip001/Bip001 Pelvis/Bip001 L Thigh/Bip001 L Calf/Bip001 L Foot weight: 1 - path: Bip001/Bip001 Pelvis/Bip001 R Thigh weight: 1 - path: Bip001/Bip001 Pelvis/Bip001 R Thigh/Bip001 R Calf weight: 1 - path: Bip001/Bip001 Pelvis/Bip001 R Thigh/Bip001 R Calf/Bip001 R Foot weight: 1 - path: Bip001/Bip001 Pelvis/Bip001 Spine weight: 1 - path: Bip001/Bip001 Pelvis/Bip001 Spine/Bip001 Head weight: 1 - path: Bip001/Bip001 Pelvis/Bip001 Spine/Bip001 L UpperArm weight: 1 - path: Bip001/Bip001 Pelvis/Bip001 Spine/Bip001 L UpperArm/Bip001 L Forearm weight: 1 - path: Bip001/Bip001 Pelvis/Bip001 Spine/Bip001 L UpperArm/Bip001 L Forearm/Bip001 L Hand weight: 1 - path: Bip001/Bip001 Pelvis/Bip001 Spine/Bip001 R UpperArm weight: 1 - path: Bip001/Bip001 Pelvis/Bip001 Spine/Bip001 R UpperArm/Bip001 R Forearm weight: 1 - path: Bip001/Bip001 Pelvis/Bip001 Spine/Bip001 R UpperArm/Bip001 R Forearm/Bip001 R Hand weight: 1 - path: Bip001/Bip001 Pelvis/Bip001 Spine/Bip001 Spine1 weight: 1 - path: origin weight: 1 maskType: 0 maskSource: {instanceID: 0} additiveReferencePoseFrame: 0 isReadable: 1 meshes: lODScreenPercentages: [] globalScale: 1 meshCompression: 0 addColliders: 0 importVisibility: 0 importBlendShapes: 1 importCameras: 0 importLights: 0 swapUVChannels: 0 generateSecondaryUV: 0 useFileUnits: 1 optimizeMeshForGPU: 1 keepQuads: 0 weldVertices: 1 preserveHierarchy: 0 secondaryUVAngleDistortion: 8 secondaryUVAreaDistortion: 15.000001 secondaryUVHardAngle: 88 secondaryUVPackMargin: 4 useFileScale: 1 tangentSpace: normalSmoothAngle: 60 normalImportMode: 0 tangentImportMode: 3 normalCalculationMode: 0 importAnimation: 1 copyAvatar: 0 humanDescription: serializedVersion: 2 human: [] skeleton: [] armTwist: 0.5 foreArmTwist: 0.5 upperLegTwist: 0.5 legTwist: 0.5 armStretch: 0.05 legStretch: 0.05 feetSpacing: 0 rootMotionBoneName: rootMotionBoneRotation: {x: 0, y: 0, z: 0, w: 1} hasTranslationDoF: 0 hasExtraRoot: 0 skeletonHasParents: 0 lastHumanDescriptionAvatarSource: {instanceID: 0} animationType: 1 humanoidOversampling: 1 additionalBone: 0 userData: assetBundleName: assetBundleVariant:
{ "pile_set_name": "Github" }
fileFormatVersion: 2 guid: ae11de2f76b064a6ea762a517997c88c NativeFormatImporter: userData:
{ "pile_set_name": "Github" }
[**中文说明**](README_ZH.md) | [**English**](README.md) 这个例子展示MSRA NER(中文命名实体识别)任务上,在**分布式数据并行训练**(Distributed Data-Parallel, DDP)模式(single node, muliti-GPU)下的[Chinese-ELECTRA-base](https://github.com/ymcui/Chinese-ELECTRA)模型蒸馏。 * ner_ElectraTrain_dist.sh : 训练教师模型(ELECTRA-base)。 * ner_ElectraDistill_dist.sh : 将教师模型蒸馏到学生模型(ELECTRA-small)。 运行脚本前,请根据自己的环境设置相应变量: * ELECTRA_DIR_BASE : 存放Chinese-ELECTRA-base模型的目录,包含vocab.txt,pytorch_model.bin和config.json。 * OUTPUT_DIR : 存放训练好的模型权重文件和日志。 * DATA_DIR : MSRA NER数据集目录,包含 * msra_train_bio.txt * msra_test_bio.txt 对于蒸馏,需要设置: * ELECTRA_DIR_SMALL : Chinese-ELECTRA-small预训练权重所在目录。应包含pytorch_model.bin。 也可不提供预训练权重,则学生模型将随机初始化。 * student_config_file : 学生模型配置文件,一般文件名为config.json,也位于 $\{ELECTRA_DIR_SMALL\}。 * trained_teacher_model_file : 在MSRA NER任务上训练好的ELECTRA-base教师模型。 该脚本在 **PyTorch==1.2, Transformers==2.8** 下测试通过。
{ "pile_set_name": "Github" }
//===- Preprocessor.h - C Language Family Preprocessor ----------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // /// \file /// Defines the clang::Preprocessor interface. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_LEX_PREPROCESSOR_H #define LLVM_CLANG_LEX_PREPROCESSOR_H #include "clang/Basic/Builtins.h" #include "clang/Basic/Diagnostic.h" #include "clang/Basic/IdentifierTable.h" #include "clang/Basic/LLVM.h" #include "clang/Basic/LangOptions.h" #include "clang/Basic/Module.h" #include "clang/Basic/SourceLocation.h" #include "clang/Basic/SourceManager.h" #include "clang/Basic/TokenKinds.h" #include "clang/Lex/Lexer.h" #include "clang/Lex/MacroInfo.h" #include "clang/Lex/ModuleLoader.h" #include "clang/Lex/ModuleMap.h" #include "clang/Lex/PPCallbacks.h" #include "clang/Lex/PreprocessorExcludedConditionalDirectiveSkipMapping.h" #include "clang/Lex/Token.h" #include "clang/Lex/TokenLexer.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/FoldingSet.h" #include "llvm/ADT/FunctionExtras.h" #include "llvm/ADT/None.h" #include "llvm/ADT/Optional.h" #include "llvm/ADT/PointerUnion.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringRef.h" #include "llvm/ADT/TinyPtrVector.h" #include "llvm/ADT/iterator_range.h" #include "llvm/Support/Allocator.h" #include "llvm/Support/Casting.h" #include "llvm/Support/Registry.h" #include <cassert> #include <cstddef> #include <cstdint> #include <map> #include <memory> #include <string> #include <utility> #include <vector> namespace llvm { template<unsigned InternalLen> class SmallString; } // namespace llvm namespace clang { class CodeCompletionHandler; class CommentHandler; class DirectoryEntry; class DirectoryLookup; class ExternalPreprocessorSource; class FileEntry; class FileManager; class HeaderSearch; class MacroArgs; class PragmaHandler; class PragmaNamespace; class PreprocessingRecord; class PreprocessorLexer; class PreprocessorOptions; class ScratchBuffer; class TargetInfo; /// Stores token information for comparing actual tokens with /// predefined values. Only handles simple tokens and identifiers. class TokenValue { tok::TokenKind Kind; IdentifierInfo *II; public: TokenValue(tok::TokenKind Kind) : Kind(Kind), II(nullptr) { assert(Kind != tok::raw_identifier && "Raw identifiers are not supported."); assert(Kind != tok::identifier && "Identifiers should be created by TokenValue(IdentifierInfo *)"); assert(!tok::isLiteral(Kind) && "Literals are not supported."); assert(!tok::isAnnotation(Kind) && "Annotations are not supported."); } TokenValue(IdentifierInfo *II) : Kind(tok::identifier), II(II) {} bool operator==(const Token &Tok) const { return Tok.getKind() == Kind && (!II || II == Tok.getIdentifierInfo()); } }; /// Context in which macro name is used. enum MacroUse { // other than #define or #undef MU_Other = 0, // macro name specified in #define MU_Define = 1, // macro name specified in #undef MU_Undef = 2 }; /// Engages in a tight little dance with the lexer to efficiently /// preprocess tokens. /// /// Lexers know only about tokens within a single source file, and don't /// know anything about preprocessor-level issues like the \#include stack, /// token expansion, etc. class Preprocessor { friend class VAOptDefinitionContext; friend class VariadicMacroScopeGuard; llvm::unique_function<void(const clang::Token &)> OnToken; std::shared_ptr<PreprocessorOptions> PPOpts; DiagnosticsEngine *Diags; LangOptions &LangOpts; const TargetInfo *Target = nullptr; const TargetInfo *AuxTarget = nullptr; FileManager &FileMgr; SourceManager &SourceMgr; std::unique_ptr<ScratchBuffer> ScratchBuf; HeaderSearch &HeaderInfo; ModuleLoader &TheModuleLoader; /// External source of macros. ExternalPreprocessorSource *ExternalSource; /// A BumpPtrAllocator object used to quickly allocate and release /// objects internal to the Preprocessor. llvm::BumpPtrAllocator BP; /// Identifiers for builtin macros and other builtins. IdentifierInfo *Ident__LINE__, *Ident__FILE__; // __LINE__, __FILE__ IdentifierInfo *Ident__DATE__, *Ident__TIME__; // __DATE__, __TIME__ IdentifierInfo *Ident__INCLUDE_LEVEL__; // __INCLUDE_LEVEL__ IdentifierInfo *Ident__BASE_FILE__; // __BASE_FILE__ IdentifierInfo *Ident__FILE_NAME__; // __FILE_NAME__ IdentifierInfo *Ident__TIMESTAMP__; // __TIMESTAMP__ IdentifierInfo *Ident__COUNTER__; // __COUNTER__ IdentifierInfo *Ident_Pragma, *Ident__pragma; // _Pragma, __pragma IdentifierInfo *Ident__identifier; // __identifier IdentifierInfo *Ident__VA_ARGS__; // __VA_ARGS__ IdentifierInfo *Ident__VA_OPT__; // __VA_OPT__ IdentifierInfo *Ident__has_feature; // __has_feature IdentifierInfo *Ident__has_extension; // __has_extension IdentifierInfo *Ident__has_builtin; // __has_builtin IdentifierInfo *Ident__has_attribute; // __has_attribute IdentifierInfo *Ident__has_include; // __has_include IdentifierInfo *Ident__has_include_next; // __has_include_next IdentifierInfo *Ident__has_warning; // __has_warning IdentifierInfo *Ident__is_identifier; // __is_identifier IdentifierInfo *Ident__building_module; // __building_module IdentifierInfo *Ident__MODULE__; // __MODULE__ IdentifierInfo *Ident__has_cpp_attribute; // __has_cpp_attribute IdentifierInfo *Ident__has_c_attribute; // __has_c_attribute IdentifierInfo *Ident__has_declspec; // __has_declspec_attribute IdentifierInfo *Ident__is_target_arch; // __is_target_arch IdentifierInfo *Ident__is_target_vendor; // __is_target_vendor IdentifierInfo *Ident__is_target_os; // __is_target_os IdentifierInfo *Ident__is_target_environment; // __is_target_environment // Weak, only valid (and set) while InMacroArgs is true. Token* ArgMacro; SourceLocation DATELoc, TIMELoc; // Next __COUNTER__ value, starts at 0. unsigned CounterValue = 0; enum { /// Maximum depth of \#includes. MaxAllowedIncludeStackDepth = 200 }; // State that is set before the preprocessor begins. bool KeepComments : 1; bool KeepMacroComments : 1; bool SuppressIncludeNotFoundError : 1; // State that changes while the preprocessor runs: bool InMacroArgs : 1; // True if parsing fn macro invocation args. /// Whether the preprocessor owns the header search object. bool OwnsHeaderSearch : 1; /// True if macro expansion is disabled. bool DisableMacroExpansion : 1; /// Temporarily disables DisableMacroExpansion (i.e. enables expansion) /// when parsing preprocessor directives. bool MacroExpansionInDirectivesOverride : 1; class ResetMacroExpansionHelper; /// Whether we have already loaded macros from the external source. mutable bool ReadMacrosFromExternalSource : 1; /// True if pragmas are enabled. bool PragmasEnabled : 1; /// True if the current build action is a preprocessing action. bool PreprocessedOutput : 1; /// True if we are currently preprocessing a #if or #elif directive bool ParsingIfOrElifDirective; /// True if we are pre-expanding macro arguments. bool InMacroArgPreExpansion; /// Mapping/lookup information for all identifiers in /// the program, including program keywords. mutable IdentifierTable Identifiers; /// This table contains all the selectors in the program. /// /// Unlike IdentifierTable above, this table *isn't* populated by the /// preprocessor. It is declared/expanded here because its role/lifetime is /// conceptually similar to the IdentifierTable. In addition, the current /// control flow (in clang::ParseAST()), make it convenient to put here. /// /// FIXME: Make sure the lifetime of Identifiers/Selectors *isn't* tied to /// the lifetime of the preprocessor. SelectorTable Selectors; /// Information about builtins. Builtin::Context BuiltinInfo; /// Tracks all of the pragmas that the client registered /// with this preprocessor. std::unique_ptr<PragmaNamespace> PragmaHandlers; /// Pragma handlers of the original source is stored here during the /// parsing of a model file. std::unique_ptr<PragmaNamespace> PragmaHandlersBackup; /// Tracks all of the comment handlers that the client registered /// with this preprocessor. std::vector<CommentHandler *> CommentHandlers; /// True if we want to ignore EOF token and continue later on (thus /// avoid tearing the Lexer and etc. down). bool IncrementalProcessing = false; /// The kind of translation unit we are processing. TranslationUnitKind TUKind; /// The code-completion handler. CodeCompletionHandler *CodeComplete = nullptr; /// The file that we're performing code-completion for, if any. const FileEntry *CodeCompletionFile = nullptr; /// The offset in file for the code-completion point. unsigned CodeCompletionOffset = 0; /// The location for the code-completion point. This gets instantiated /// when the CodeCompletionFile gets \#include'ed for preprocessing. SourceLocation CodeCompletionLoc; /// The start location for the file of the code-completion point. /// /// This gets instantiated when the CodeCompletionFile gets \#include'ed /// for preprocessing. SourceLocation CodeCompletionFileLoc; /// The source location of the \c import contextual keyword we just /// lexed, if any. SourceLocation ModuleImportLoc; /// The module import path that we're currently processing. SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> ModuleImportPath; /// Whether the last token we lexed was an '@'. bool LastTokenWasAt = false; /// A position within a C++20 import-seq. class ImportSeq { public: enum State : int { // Positive values represent a number of unclosed brackets. AtTopLevel = 0, AfterTopLevelTokenSeq = -1, AfterExport = -2, AfterImportSeq = -3, }; ImportSeq(State S) : S(S) {} /// Saw any kind of open bracket. void handleOpenBracket() { S = static_cast<State>(std::max<int>(S, 0) + 1); } /// Saw any kind of close bracket other than '}'. void handleCloseBracket() { S = static_cast<State>(std::max<int>(S, 1) - 1); } /// Saw a close brace. void handleCloseBrace() { handleCloseBracket(); if (S == AtTopLevel && !AfterHeaderName) S = AfterTopLevelTokenSeq; } /// Saw a semicolon. void handleSemi() { if (atTopLevel()) { S = AfterTopLevelTokenSeq; AfterHeaderName = false; } } /// Saw an 'export' identifier. void handleExport() { if (S == AfterTopLevelTokenSeq) S = AfterExport; else if (S <= 0) S = AtTopLevel; } /// Saw an 'import' identifier. void handleImport() { if (S == AfterTopLevelTokenSeq || S == AfterExport) S = AfterImportSeq; else if (S <= 0) S = AtTopLevel; } /// Saw a 'header-name' token; do not recognize any more 'import' tokens /// until we reach a top-level semicolon. void handleHeaderName() { if (S == AfterImportSeq) AfterHeaderName = true; handleMisc(); } /// Saw any other token. void handleMisc() { if (S <= 0) S = AtTopLevel; } bool atTopLevel() { return S <= 0; } bool afterImportSeq() { return S == AfterImportSeq; } private: State S; /// Whether we're in the pp-import-suffix following the header-name in a /// pp-import. If so, a close-brace is not sufficient to end the /// top-level-token-seq of an import-seq. bool AfterHeaderName = false; }; /// Our current position within a C++20 import-seq. ImportSeq ImportSeqState = ImportSeq::AfterTopLevelTokenSeq; /// Whether the module import expects an identifier next. Otherwise, /// it expects a '.' or ';'. bool ModuleImportExpectsIdentifier = false; /// The identifier and source location of the currently-active /// \#pragma clang arc_cf_code_audited begin. std::pair<IdentifierInfo *, SourceLocation> PragmaARCCFCodeAuditedInfo; /// The source location of the currently-active /// \#pragma clang assume_nonnull begin. SourceLocation PragmaAssumeNonNullLoc; /// True if we hit the code-completion point. bool CodeCompletionReached = false; /// The code completion token containing the information /// on the stem that is to be code completed. IdentifierInfo *CodeCompletionII = nullptr; /// Range for the code completion token. SourceRange CodeCompletionTokenRange; /// The directory that the main file should be considered to occupy, /// if it does not correspond to a real file (as happens when building a /// module). const DirectoryEntry *MainFileDir = nullptr; /// The number of bytes that we will initially skip when entering the /// main file, along with a flag that indicates whether skipping this number /// of bytes will place the lexer at the start of a line. /// /// This is used when loading a precompiled preamble. std::pair<int, bool> SkipMainFilePreamble; /// Whether we hit an error due to reaching max allowed include depth. Allows /// to avoid hitting the same error over and over again. bool HasReachedMaxIncludeDepth = false; /// The number of currently-active calls to Lex. /// /// Lex is reentrant, and asking for an (end-of-phase-4) token can often /// require asking for multiple additional tokens. This counter makes it /// possible for Lex to detect whether it's producing a token for the end /// of phase 4 of translation or for some other situation. unsigned LexLevel = 0; public: struct PreambleSkipInfo { SourceLocation HashTokenLoc; SourceLocation IfTokenLoc; bool FoundNonSkipPortion; bool FoundElse; SourceLocation ElseLoc; PreambleSkipInfo(SourceLocation HashTokenLoc, SourceLocation IfTokenLoc, bool FoundNonSkipPortion, bool FoundElse, SourceLocation ElseLoc) : HashTokenLoc(HashTokenLoc), IfTokenLoc(IfTokenLoc), FoundNonSkipPortion(FoundNonSkipPortion), FoundElse(FoundElse), ElseLoc(ElseLoc) {} }; private: friend class ASTReader; friend class MacroArgs; class PreambleConditionalStackStore { enum State { Off = 0, Recording = 1, Replaying = 2, }; public: PreambleConditionalStackStore() = default; void startRecording() { ConditionalStackState = Recording; } void startReplaying() { ConditionalStackState = Replaying; } bool isRecording() const { return ConditionalStackState == Recording; } bool isReplaying() const { return ConditionalStackState == Replaying; } ArrayRef<PPConditionalInfo> getStack() const { return ConditionalStack; } void doneReplaying() { ConditionalStack.clear(); ConditionalStackState = Off; } void setStack(ArrayRef<PPConditionalInfo> s) { if (!isRecording() && !isReplaying()) return; ConditionalStack.clear(); ConditionalStack.append(s.begin(), s.end()); } bool hasRecordedPreamble() const { return !ConditionalStack.empty(); } bool reachedEOFWhileSkipping() const { return SkipInfo.hasValue(); } void clearSkipInfo() { SkipInfo.reset(); } llvm::Optional<PreambleSkipInfo> SkipInfo; private: SmallVector<PPConditionalInfo, 4> ConditionalStack; State ConditionalStackState = Off; } PreambleConditionalStack; /// The current top of the stack that we're lexing from if /// not expanding a macro and we are lexing directly from source code. /// /// Only one of CurLexer, or CurTokenLexer will be non-null. std::unique_ptr<Lexer> CurLexer; /// The current top of the stack what we're lexing from /// if not expanding a macro. /// /// This is an alias for CurLexer. PreprocessorLexer *CurPPLexer = nullptr; /// Used to find the current FileEntry, if CurLexer is non-null /// and if applicable. /// /// This allows us to implement \#include_next and find directory-specific /// properties. const DirectoryLookup *CurDirLookup = nullptr; /// The current macro we are expanding, if we are expanding a macro. /// /// One of CurLexer and CurTokenLexer must be null. std::unique_ptr<TokenLexer> CurTokenLexer; /// The kind of lexer we're currently working with. enum CurLexerKind { CLK_Lexer, CLK_TokenLexer, CLK_CachingLexer, CLK_LexAfterModuleImport } CurLexerKind = CLK_Lexer; /// If the current lexer is for a submodule that is being built, this /// is that submodule. Module *CurLexerSubmodule = nullptr; /// Keeps track of the stack of files currently /// \#included, and macros currently being expanded from, not counting /// CurLexer/CurTokenLexer. struct IncludeStackInfo { enum CurLexerKind CurLexerKind; Module *TheSubmodule; std::unique_ptr<Lexer> TheLexer; PreprocessorLexer *ThePPLexer; std::unique_ptr<TokenLexer> TheTokenLexer; const DirectoryLookup *TheDirLookup; // The following constructors are completely useless copies of the default // versions, only needed to pacify MSVC. IncludeStackInfo(enum CurLexerKind CurLexerKind, Module *TheSubmodule, std::unique_ptr<Lexer> &&TheLexer, PreprocessorLexer *ThePPLexer, std::unique_ptr<TokenLexer> &&TheTokenLexer, const DirectoryLookup *TheDirLookup) : CurLexerKind(std::move(CurLexerKind)), TheSubmodule(std::move(TheSubmodule)), TheLexer(std::move(TheLexer)), ThePPLexer(std::move(ThePPLexer)), TheTokenLexer(std::move(TheTokenLexer)), TheDirLookup(std::move(TheDirLookup)) {} }; std::vector<IncludeStackInfo> IncludeMacroStack; /// Actions invoked when some preprocessor activity is /// encountered (e.g. a file is \#included, etc). std::unique_ptr<PPCallbacks> Callbacks; struct MacroExpandsInfo { Token Tok; MacroDefinition MD; SourceRange Range; MacroExpandsInfo(Token Tok, MacroDefinition MD, SourceRange Range) : Tok(Tok), MD(MD), Range(Range) {} }; SmallVector<MacroExpandsInfo, 2> DelayedMacroExpandsCallbacks; /// Information about a name that has been used to define a module macro. struct ModuleMacroInfo { /// The most recent macro directive for this identifier. MacroDirective *MD; /// The active module macros for this identifier. llvm::TinyPtrVector<ModuleMacro *> ActiveModuleMacros; /// The generation number at which we last updated ActiveModuleMacros. /// \see Preprocessor::VisibleModules. unsigned ActiveModuleMacrosGeneration = 0; /// Whether this macro name is ambiguous. bool IsAmbiguous = false; /// The module macros that are overridden by this macro. llvm::TinyPtrVector<ModuleMacro *> OverriddenMacros; ModuleMacroInfo(MacroDirective *MD) : MD(MD) {} }; /// The state of a macro for an identifier. class MacroState { mutable llvm::PointerUnion<MacroDirective *, ModuleMacroInfo *> State; ModuleMacroInfo *getModuleInfo(Preprocessor &PP, const IdentifierInfo *II) const { if (II->isOutOfDate()) PP.updateOutOfDateIdentifier(const_cast<IdentifierInfo&>(*II)); // FIXME: Find a spare bit on IdentifierInfo and store a // HasModuleMacros flag. if (!II->hasMacroDefinition() || (!PP.getLangOpts().Modules && !PP.getLangOpts().ModulesLocalVisibility) || !PP.CurSubmoduleState->VisibleModules.getGeneration()) return nullptr; auto *Info = State.dyn_cast<ModuleMacroInfo*>(); if (!Info) { Info = new (PP.getPreprocessorAllocator()) ModuleMacroInfo(State.get<MacroDirective *>()); State = Info; } if (PP.CurSubmoduleState->VisibleModules.getGeneration() != Info->ActiveModuleMacrosGeneration) PP.updateModuleMacroInfo(II, *Info); return Info; } public: MacroState() : MacroState(nullptr) {} MacroState(MacroDirective *MD) : State(MD) {} MacroState(MacroState &&O) noexcept : State(O.State) { O.State = (MacroDirective *)nullptr; } MacroState &operator=(MacroState &&O) noexcept { auto S = O.State; O.State = (MacroDirective *)nullptr; State = S; return *this; } ~MacroState() { if (auto *Info = State.dyn_cast<ModuleMacroInfo*>()) Info->~ModuleMacroInfo(); } MacroDirective *getLatest() const { if (auto *Info = State.dyn_cast<ModuleMacroInfo*>()) return Info->MD; return State.get<MacroDirective*>(); } void setLatest(MacroDirective *MD) { if (auto *Info = State.dyn_cast<ModuleMacroInfo*>()) Info->MD = MD; else State = MD; } bool isAmbiguous(Preprocessor &PP, const IdentifierInfo *II) const { auto *Info = getModuleInfo(PP, II); return Info ? Info->IsAmbiguous : false; } ArrayRef<ModuleMacro *> getActiveModuleMacros(Preprocessor &PP, const IdentifierInfo *II) const { if (auto *Info = getModuleInfo(PP, II)) return Info->ActiveModuleMacros; return None; } MacroDirective::DefInfo findDirectiveAtLoc(SourceLocation Loc, SourceManager &SourceMgr) const { // FIXME: Incorporate module macros into the result of this. if (auto *Latest = getLatest()) return Latest->findDirectiveAtLoc(Loc, SourceMgr); return {}; } void overrideActiveModuleMacros(Preprocessor &PP, IdentifierInfo *II) { if (auto *Info = getModuleInfo(PP, II)) { Info->OverriddenMacros.insert(Info->OverriddenMacros.end(), Info->ActiveModuleMacros.begin(), Info->ActiveModuleMacros.end()); Info->ActiveModuleMacros.clear(); Info->IsAmbiguous = false; } } ArrayRef<ModuleMacro*> getOverriddenMacros() const { if (auto *Info = State.dyn_cast<ModuleMacroInfo*>()) return Info->OverriddenMacros; return None; } void setOverriddenMacros(Preprocessor &PP, ArrayRef<ModuleMacro *> Overrides) { auto *Info = State.dyn_cast<ModuleMacroInfo*>(); if (!Info) { if (Overrides.empty()) return; Info = new (PP.getPreprocessorAllocator()) ModuleMacroInfo(State.get<MacroDirective *>()); State = Info; } Info->OverriddenMacros.clear(); Info->OverriddenMacros.insert(Info->OverriddenMacros.end(), Overrides.begin(), Overrides.end()); Info->ActiveModuleMacrosGeneration = 0; } }; /// For each IdentifierInfo that was associated with a macro, we /// keep a mapping to the history of all macro definitions and #undefs in /// the reverse order (the latest one is in the head of the list). /// /// This mapping lives within the \p CurSubmoduleState. using MacroMap = llvm::DenseMap<const IdentifierInfo *, MacroState>; struct SubmoduleState; /// Information about a submodule that we're currently building. struct BuildingSubmoduleInfo { /// The module that we are building. Module *M; /// The location at which the module was included. SourceLocation ImportLoc; /// Whether we entered this submodule via a pragma. bool IsPragma; /// The previous SubmoduleState. SubmoduleState *OuterSubmoduleState; /// The number of pending module macro names when we started building this. unsigned OuterPendingModuleMacroNames; BuildingSubmoduleInfo(Module *M, SourceLocation ImportLoc, bool IsPragma, SubmoduleState *OuterSubmoduleState, unsigned OuterPendingModuleMacroNames) : M(M), ImportLoc(ImportLoc), IsPragma(IsPragma), OuterSubmoduleState(OuterSubmoduleState), OuterPendingModuleMacroNames(OuterPendingModuleMacroNames) {} }; SmallVector<BuildingSubmoduleInfo, 8> BuildingSubmoduleStack; /// Information about a submodule's preprocessor state. struct SubmoduleState { /// The macros for the submodule. MacroMap Macros; /// The set of modules that are visible within the submodule. VisibleModuleSet VisibleModules; // FIXME: CounterValue? // FIXME: PragmaPushMacroInfo? }; std::map<Module *, SubmoduleState> Submodules; /// The preprocessor state for preprocessing outside of any submodule. SubmoduleState NullSubmoduleState; /// The current submodule state. Will be \p NullSubmoduleState if we're not /// in a submodule. SubmoduleState *CurSubmoduleState; /// The set of known macros exported from modules. llvm::FoldingSet<ModuleMacro> ModuleMacros; /// The names of potential module macros that we've not yet processed. llvm::SmallVector<const IdentifierInfo *, 32> PendingModuleMacroNames; /// The list of module macros, for each identifier, that are not overridden by /// any other module macro. llvm::DenseMap<const IdentifierInfo *, llvm::TinyPtrVector<ModuleMacro *>> LeafModuleMacros; /// Macros that we want to warn because they are not used at the end /// of the translation unit. /// /// We store just their SourceLocations instead of /// something like MacroInfo*. The benefit of this is that when we are /// deserializing from PCH, we don't need to deserialize identifier & macros /// just so that we can report that they are unused, we just warn using /// the SourceLocations of this set (that will be filled by the ASTReader). /// We are using SmallPtrSet instead of a vector for faster removal. using WarnUnusedMacroLocsTy = llvm::SmallPtrSet<SourceLocation, 32>; WarnUnusedMacroLocsTy WarnUnusedMacroLocs; /// A "freelist" of MacroArg objects that can be /// reused for quick allocation. MacroArgs *MacroArgCache = nullptr; /// For each IdentifierInfo used in a \#pragma push_macro directive, /// we keep a MacroInfo stack used to restore the previous macro value. llvm::DenseMap<IdentifierInfo *, std::vector<MacroInfo *>> PragmaPushMacroInfo; // Various statistics we track for performance analysis. unsigned NumDirectives = 0; unsigned NumDefined = 0; unsigned NumUndefined = 0; unsigned NumPragma = 0; unsigned NumIf = 0; unsigned NumElse = 0; unsigned NumEndif = 0; unsigned NumEnteredSourceFiles = 0; unsigned MaxIncludeStackDepth = 0; unsigned NumMacroExpanded = 0; unsigned NumFnMacroExpanded = 0; unsigned NumBuiltinMacroExpanded = 0; unsigned NumFastMacroExpanded = 0; unsigned NumTokenPaste = 0; unsigned NumFastTokenPaste = 0; unsigned NumSkipped = 0; /// The predefined macros that preprocessor should use from the /// command line etc. std::string Predefines; /// The file ID for the preprocessor predefines. FileID PredefinesFileID; /// The file ID for the PCH through header. FileID PCHThroughHeaderFileID; /// Whether tokens are being skipped until a #pragma hdrstop is seen. bool SkippingUntilPragmaHdrStop = false; /// Whether tokens are being skipped until the through header is seen. bool SkippingUntilPCHThroughHeader = false; /// \{ /// Cache of macro expanders to reduce malloc traffic. enum { TokenLexerCacheSize = 8 }; unsigned NumCachedTokenLexers; std::unique_ptr<TokenLexer> TokenLexerCache[TokenLexerCacheSize]; /// \} /// Keeps macro expanded tokens for TokenLexers. // /// Works like a stack; a TokenLexer adds the macro expanded tokens that is /// going to lex in the cache and when it finishes the tokens are removed /// from the end of the cache. SmallVector<Token, 16> MacroExpandedTokens; std::vector<std::pair<TokenLexer *, size_t>> MacroExpandingLexersStack; /// A record of the macro definitions and expansions that /// occurred during preprocessing. /// /// This is an optional side structure that can be enabled with /// \c createPreprocessingRecord() prior to preprocessing. PreprocessingRecord *Record = nullptr; /// Cached tokens state. using CachedTokensTy = SmallVector<Token, 1>; /// Cached tokens are stored here when we do backtracking or /// lookahead. They are "lexed" by the CachingLex() method. CachedTokensTy CachedTokens; /// The position of the cached token that CachingLex() should /// "lex" next. /// /// If it points beyond the CachedTokens vector, it means that a normal /// Lex() should be invoked. CachedTokensTy::size_type CachedLexPos = 0; /// Stack of backtrack positions, allowing nested backtracks. /// /// The EnableBacktrackAtThisPos() method pushes a position to /// indicate where CachedLexPos should be set when the BackTrack() method is /// invoked (at which point the last position is popped). std::vector<CachedTokensTy::size_type> BacktrackPositions; struct MacroInfoChain { MacroInfo MI; MacroInfoChain *Next; }; /// MacroInfos are managed as a chain for easy disposal. This is the head /// of that list. MacroInfoChain *MIChainHead = nullptr; void updateOutOfDateIdentifier(IdentifierInfo &II) const; public: Preprocessor(std::shared_ptr<PreprocessorOptions> PPOpts, DiagnosticsEngine &diags, LangOptions &opts, SourceManager &SM, HeaderSearch &Headers, ModuleLoader &TheModuleLoader, IdentifierInfoLookup *IILookup = nullptr, bool OwnsHeaderSearch = false, TranslationUnitKind TUKind = TU_Complete); ~Preprocessor(); /// Initialize the preprocessor using information about the target. /// /// \param Target is owned by the caller and must remain valid for the /// lifetime of the preprocessor. /// \param AuxTarget is owned by the caller and must remain valid for /// the lifetime of the preprocessor. void Initialize(const TargetInfo &Target, const TargetInfo *AuxTarget = nullptr); /// Initialize the preprocessor to parse a model file /// /// To parse model files the preprocessor of the original source is reused to /// preserver the identifier table. However to avoid some duplicate /// information in the preprocessor some cleanup is needed before it is used /// to parse model files. This method does that cleanup. void InitializeForModelFile(); /// Cleanup after model file parsing void FinalizeForModelFile(); /// Retrieve the preprocessor options used to initialize this /// preprocessor. PreprocessorOptions &getPreprocessorOpts() const { return *PPOpts; } DiagnosticsEngine &getDiagnostics() const { return *Diags; } void setDiagnostics(DiagnosticsEngine &D) { Diags = &D; } const LangOptions &getLangOpts() const { return LangOpts; } const TargetInfo &getTargetInfo() const { return *Target; } const TargetInfo *getAuxTargetInfo() const { return AuxTarget; } FileManager &getFileManager() const { return FileMgr; } SourceManager &getSourceManager() const { return SourceMgr; } HeaderSearch &getHeaderSearchInfo() const { return HeaderInfo; } IdentifierTable &getIdentifierTable() { return Identifiers; } const IdentifierTable &getIdentifierTable() const { return Identifiers; } SelectorTable &getSelectorTable() { return Selectors; } Builtin::Context &getBuiltinInfo() { return BuiltinInfo; } llvm::BumpPtrAllocator &getPreprocessorAllocator() { return BP; } void setExternalSource(ExternalPreprocessorSource *Source) { ExternalSource = Source; } ExternalPreprocessorSource *getExternalSource() const { return ExternalSource; } /// Retrieve the module loader associated with this preprocessor. ModuleLoader &getModuleLoader() const { return TheModuleLoader; } bool hadModuleLoaderFatalFailure() const { return TheModuleLoader.HadFatalFailure; } /// True if we are currently preprocessing a #if or #elif directive bool isParsingIfOrElifDirective() const { return ParsingIfOrElifDirective; } /// Control whether the preprocessor retains comments in output. void SetCommentRetentionState(bool KeepComments, bool KeepMacroComments) { this->KeepComments = KeepComments | KeepMacroComments; this->KeepMacroComments = KeepMacroComments; } bool getCommentRetentionState() const { return KeepComments; } void setPragmasEnabled(bool Enabled) { PragmasEnabled = Enabled; } bool getPragmasEnabled() const { return PragmasEnabled; } void SetSuppressIncludeNotFoundError(bool Suppress) { SuppressIncludeNotFoundError = Suppress; } bool GetSuppressIncludeNotFoundError() { return SuppressIncludeNotFoundError; } /// Sets whether the preprocessor is responsible for producing output or if /// it is producing tokens to be consumed by Parse and Sema. void setPreprocessedOutput(bool IsPreprocessedOutput) { PreprocessedOutput = IsPreprocessedOutput; } /// Returns true if the preprocessor is responsible for generating output, /// false if it is producing tokens to be consumed by Parse and Sema. bool isPreprocessedOutput() const { return PreprocessedOutput; } /// Return true if we are lexing directly from the specified lexer. bool isCurrentLexer(const PreprocessorLexer *L) const { return CurPPLexer == L; } /// Return the current lexer being lexed from. /// /// Note that this ignores any potentially active macro expansions and _Pragma /// expansions going on at the time. PreprocessorLexer *getCurrentLexer() const { return CurPPLexer; } /// Return the current file lexer being lexed from. /// /// Note that this ignores any potentially active macro expansions and _Pragma /// expansions going on at the time. PreprocessorLexer *getCurrentFileLexer() const; /// Return the submodule owning the file being lexed. This may not be /// the current module if we have changed modules since entering the file. Module *getCurrentLexerSubmodule() const { return CurLexerSubmodule; } /// Returns the FileID for the preprocessor predefines. FileID getPredefinesFileID() const { return PredefinesFileID; } /// \{ /// Accessors for preprocessor callbacks. /// /// Note that this class takes ownership of any PPCallbacks object given to /// it. PPCallbacks *getPPCallbacks() const { return Callbacks.get(); } void addPPCallbacks(std::unique_ptr<PPCallbacks> C) { if (Callbacks) C = std::make_unique<PPChainedCallbacks>(std::move(C), std::move(Callbacks)); Callbacks = std::move(C); } /// \} /// Register a function that would be called on each token in the final /// expanded token stream. /// This also reports annotation tokens produced by the parser. void setTokenWatcher(llvm::unique_function<void(const clang::Token &)> F) { OnToken = std::move(F); } bool isMacroDefined(StringRef Id) { return isMacroDefined(&Identifiers.get(Id)); } bool isMacroDefined(const IdentifierInfo *II) { return II->hasMacroDefinition() && (!getLangOpts().Modules || (bool)getMacroDefinition(II)); } /// Determine whether II is defined as a macro within the module M, /// if that is a module that we've already preprocessed. Does not check for /// macros imported into M. bool isMacroDefinedInLocalModule(const IdentifierInfo *II, Module *M) { if (!II->hasMacroDefinition()) return false; auto I = Submodules.find(M); if (I == Submodules.end()) return false; auto J = I->second.Macros.find(II); if (J == I->second.Macros.end()) return false; auto *MD = J->second.getLatest(); return MD && MD->isDefined(); } MacroDefinition getMacroDefinition(const IdentifierInfo *II) { if (!II->hasMacroDefinition()) return {}; MacroState &S = CurSubmoduleState->Macros[II]; auto *MD = S.getLatest(); while (MD && isa<VisibilityMacroDirective>(MD)) MD = MD->getPrevious(); return MacroDefinition(dyn_cast_or_null<DefMacroDirective>(MD), S.getActiveModuleMacros(*this, II), S.isAmbiguous(*this, II)); } MacroDefinition getMacroDefinitionAtLoc(const IdentifierInfo *II, SourceLocation Loc) { if (!II->hadMacroDefinition()) return {}; MacroState &S = CurSubmoduleState->Macros[II]; MacroDirective::DefInfo DI; if (auto *MD = S.getLatest()) DI = MD->findDirectiveAtLoc(Loc, getSourceManager()); // FIXME: Compute the set of active module macros at the specified location. return MacroDefinition(DI.getDirective(), S.getActiveModuleMacros(*this, II), S.isAmbiguous(*this, II)); } /// Given an identifier, return its latest non-imported MacroDirective /// if it is \#define'd and not \#undef'd, or null if it isn't \#define'd. MacroDirective *getLocalMacroDirective(const IdentifierInfo *II) const { if (!II->hasMacroDefinition()) return nullptr; auto *MD = getLocalMacroDirectiveHistory(II); if (!MD || MD->getDefinition().isUndefined()) return nullptr; return MD; } const MacroInfo *getMacroInfo(const IdentifierInfo *II) const { return const_cast<Preprocessor*>(this)->getMacroInfo(II); } MacroInfo *getMacroInfo(const IdentifierInfo *II) { if (!II->hasMacroDefinition()) return nullptr; if (auto MD = getMacroDefinition(II)) return MD.getMacroInfo(); return nullptr; } /// Given an identifier, return the latest non-imported macro /// directive for that identifier. /// /// One can iterate over all previous macro directives from the most recent /// one. MacroDirective *getLocalMacroDirectiveHistory(const IdentifierInfo *II) const; /// Add a directive to the macro directive history for this identifier. void appendMacroDirective(IdentifierInfo *II, MacroDirective *MD); DefMacroDirective *appendDefMacroDirective(IdentifierInfo *II, MacroInfo *MI, SourceLocation Loc) { DefMacroDirective *MD = AllocateDefMacroDirective(MI, Loc); appendMacroDirective(II, MD); return MD; } DefMacroDirective *appendDefMacroDirective(IdentifierInfo *II, MacroInfo *MI) { return appendDefMacroDirective(II, MI, MI->getDefinitionLoc()); } /// Set a MacroDirective that was loaded from a PCH file. void setLoadedMacroDirective(IdentifierInfo *II, MacroDirective *ED, MacroDirective *MD); /// Register an exported macro for a module and identifier. ModuleMacro *addModuleMacro(Module *Mod, IdentifierInfo *II, MacroInfo *Macro, ArrayRef<ModuleMacro *> Overrides, bool &IsNew); ModuleMacro *getModuleMacro(Module *Mod, IdentifierInfo *II); /// Get the list of leaf (non-overridden) module macros for a name. ArrayRef<ModuleMacro*> getLeafModuleMacros(const IdentifierInfo *II) const { if (II->isOutOfDate()) updateOutOfDateIdentifier(const_cast<IdentifierInfo&>(*II)); auto I = LeafModuleMacros.find(II); if (I != LeafModuleMacros.end()) return I->second; return None; } /// \{ /// Iterators for the macro history table. Currently defined macros have /// IdentifierInfo::hasMacroDefinition() set and an empty /// MacroInfo::getUndefLoc() at the head of the list. using macro_iterator = MacroMap::const_iterator; macro_iterator macro_begin(bool IncludeExternalMacros = true) const; macro_iterator macro_end(bool IncludeExternalMacros = true) const; llvm::iterator_range<macro_iterator> macros(bool IncludeExternalMacros = true) const { macro_iterator begin = macro_begin(IncludeExternalMacros); macro_iterator end = macro_end(IncludeExternalMacros); return llvm::make_range(begin, end); } /// \} /// Return the name of the macro defined before \p Loc that has /// spelling \p Tokens. If there are multiple macros with same spelling, /// return the last one defined. StringRef getLastMacroWithSpelling(SourceLocation Loc, ArrayRef<TokenValue> Tokens) const; const std::string &getPredefines() const { return Predefines; } /// Set the predefines for this Preprocessor. /// /// These predefines are automatically injected when parsing the main file. void setPredefines(const char *P) { Predefines = P; } void setPredefines(StringRef P) { Predefines = P; } /// Return information about the specified preprocessor /// identifier token. IdentifierInfo *getIdentifierInfo(StringRef Name) const { return &Identifiers.get(Name); } /// Add the specified pragma handler to this preprocessor. /// /// If \p Namespace is non-null, then it is a token required to exist on the /// pragma line before the pragma string starts, e.g. "STDC" or "GCC". void AddPragmaHandler(StringRef Namespace, PragmaHandler *Handler); void AddPragmaHandler(PragmaHandler *Handler) { AddPragmaHandler(StringRef(), Handler); } /// Remove the specific pragma handler from this preprocessor. /// /// If \p Namespace is non-null, then it should be the namespace that /// \p Handler was added to. It is an error to remove a handler that /// has not been registered. void RemovePragmaHandler(StringRef Namespace, PragmaHandler *Handler); void RemovePragmaHandler(PragmaHandler *Handler) { RemovePragmaHandler(StringRef(), Handler); } /// Install empty handlers for all pragmas (making them ignored). void IgnorePragmas(); /// Add the specified comment handler to the preprocessor. void addCommentHandler(CommentHandler *Handler); /// Remove the specified comment handler. /// /// It is an error to remove a handler that has not been registered. void removeCommentHandler(CommentHandler *Handler); /// Set the code completion handler to the given object. void setCodeCompletionHandler(CodeCompletionHandler &Handler) { CodeComplete = &Handler; } /// Retrieve the current code-completion handler. CodeCompletionHandler *getCodeCompletionHandler() const { return CodeComplete; } /// Clear out the code completion handler. void clearCodeCompletionHandler() { CodeComplete = nullptr; } /// Hook used by the lexer to invoke the "included file" code /// completion point. void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled); /// Hook used by the lexer to invoke the "natural language" code /// completion point. void CodeCompleteNaturalLanguage(); /// Set the code completion token for filtering purposes. void setCodeCompletionIdentifierInfo(IdentifierInfo *Filter) { CodeCompletionII = Filter; } /// Set the code completion token range for detecting replacement range later /// on. void setCodeCompletionTokenRange(const SourceLocation Start, const SourceLocation End) { CodeCompletionTokenRange = {Start, End}; } SourceRange getCodeCompletionTokenRange() const { return CodeCompletionTokenRange; } /// Get the code completion token for filtering purposes. StringRef getCodeCompletionFilter() { if (CodeCompletionII) return CodeCompletionII->getName(); return {}; } /// Retrieve the preprocessing record, or NULL if there is no /// preprocessing record. PreprocessingRecord *getPreprocessingRecord() const { return Record; } /// Create a new preprocessing record, which will keep track of /// all macro expansions, macro definitions, etc. void createPreprocessingRecord(); /// Returns true if the FileEntry is the PCH through header. bool isPCHThroughHeader(const FileEntry *FE); /// True if creating a PCH with a through header. bool creatingPCHWithThroughHeader(); /// True if using a PCH with a through header. bool usingPCHWithThroughHeader(); /// True if creating a PCH with a #pragma hdrstop. bool creatingPCHWithPragmaHdrStop(); /// True if using a PCH with a #pragma hdrstop. bool usingPCHWithPragmaHdrStop(); /// Skip tokens until after the #include of the through header or /// until after a #pragma hdrstop. void SkipTokensWhileUsingPCH(); /// Process directives while skipping until the through header or /// #pragma hdrstop is found. void HandleSkippedDirectiveWhileUsingPCH(Token &Result, SourceLocation HashLoc); /// Enter the specified FileID as the main source file, /// which implicitly adds the builtin defines etc. void EnterMainSourceFile(); /// Inform the preprocessor callbacks that processing is complete. void EndSourceFile(); /// Add a source file to the top of the include stack and /// start lexing tokens from it instead of the current buffer. /// /// Emits a diagnostic, doesn't enter the file, and returns true on error. bool EnterSourceFile(FileID FID, const DirectoryLookup *Dir, SourceLocation Loc); /// Add a Macro to the top of the include stack and start lexing /// tokens from it instead of the current buffer. /// /// \param Args specifies the tokens input to a function-like macro. /// \param ILEnd specifies the location of the ')' for a function-like macro /// or the identifier for an object-like macro. void EnterMacro(Token &Tok, SourceLocation ILEnd, MacroInfo *Macro, MacroArgs *Args); private: /// Add a "macro" context to the top of the include stack, /// which will cause the lexer to start returning the specified tokens. /// /// If \p DisableMacroExpansion is true, tokens lexed from the token stream /// will not be subject to further macro expansion. Otherwise, these tokens /// will be re-macro-expanded when/if expansion is enabled. /// /// If \p OwnsTokens is false, this method assumes that the specified stream /// of tokens has a permanent owner somewhere, so they do not need to be /// copied. If it is true, it assumes the array of tokens is allocated with /// \c new[] and the Preprocessor will delete[] it. /// /// If \p IsReinject the resulting tokens will have Token::IsReinjected flag /// set, see the flag documentation for details. void EnterTokenStream(const Token *Toks, unsigned NumToks, bool DisableMacroExpansion, bool OwnsTokens, bool IsReinject); public: void EnterTokenStream(std::unique_ptr<Token[]> Toks, unsigned NumToks, bool DisableMacroExpansion, bool IsReinject) { EnterTokenStream(Toks.release(), NumToks, DisableMacroExpansion, true, IsReinject); } void EnterTokenStream(ArrayRef<Token> Toks, bool DisableMacroExpansion, bool IsReinject) { EnterTokenStream(Toks.data(), Toks.size(), DisableMacroExpansion, false, IsReinject); } /// Pop the current lexer/macro exp off the top of the lexer stack. /// /// This should only be used in situations where the current state of the /// top-of-stack lexer is known. void RemoveTopOfLexerStack(); /// From the point that this method is called, and until /// CommitBacktrackedTokens() or Backtrack() is called, the Preprocessor /// keeps track of the lexed tokens so that a subsequent Backtrack() call will /// make the Preprocessor re-lex the same tokens. /// /// Nested backtracks are allowed, meaning that EnableBacktrackAtThisPos can /// be called multiple times and CommitBacktrackedTokens/Backtrack calls will /// be combined with the EnableBacktrackAtThisPos calls in reverse order. /// /// NOTE: *DO NOT* forget to call either CommitBacktrackedTokens or Backtrack /// at some point after EnableBacktrackAtThisPos. If you don't, caching of /// tokens will continue indefinitely. /// void EnableBacktrackAtThisPos(); /// Disable the last EnableBacktrackAtThisPos call. void CommitBacktrackedTokens(); /// Make Preprocessor re-lex the tokens that were lexed since /// EnableBacktrackAtThisPos() was previously called. void Backtrack(); /// True if EnableBacktrackAtThisPos() was called and /// caching of tokens is on. bool isBacktrackEnabled() const { return !BacktrackPositions.empty(); } /// Lex the next token for this preprocessor. void Lex(Token &Result); /// Lex a token, forming a header-name token if possible. bool LexHeaderName(Token &Result, bool AllowMacroExpansion = true); bool LexAfterModuleImport(Token &Result); void CollectPpImportSuffix(SmallVectorImpl<Token> &Toks); void makeModuleVisible(Module *M, SourceLocation Loc); SourceLocation getModuleImportLoc(Module *M) const { return CurSubmoduleState->VisibleModules.getImportLoc(M); } /// Lex a string literal, which may be the concatenation of multiple /// string literals and may even come from macro expansion. /// \returns true on success, false if a error diagnostic has been generated. bool LexStringLiteral(Token &Result, std::string &String, const char *DiagnosticTag, bool AllowMacroExpansion) { if (AllowMacroExpansion) Lex(Result); else LexUnexpandedToken(Result); return FinishLexStringLiteral(Result, String, DiagnosticTag, AllowMacroExpansion); } /// Complete the lexing of a string literal where the first token has /// already been lexed (see LexStringLiteral). bool FinishLexStringLiteral(Token &Result, std::string &String, const char *DiagnosticTag, bool AllowMacroExpansion); /// Lex a token. If it's a comment, keep lexing until we get /// something not a comment. /// /// This is useful in -E -C mode where comments would foul up preprocessor /// directive handling. void LexNonComment(Token &Result) { do Lex(Result); while (Result.getKind() == tok::comment); } /// Just like Lex, but disables macro expansion of identifier tokens. void LexUnexpandedToken(Token &Result) { // Disable macro expansion. bool OldVal = DisableMacroExpansion; DisableMacroExpansion = true; // Lex the token. Lex(Result); // Reenable it. DisableMacroExpansion = OldVal; } /// Like LexNonComment, but this disables macro expansion of /// identifier tokens. void LexUnexpandedNonComment(Token &Result) { do LexUnexpandedToken(Result); while (Result.getKind() == tok::comment); } /// Parses a simple integer literal to get its numeric value. Floating /// point literals and user defined literals are rejected. Used primarily to /// handle pragmas that accept integer arguments. bool parseSimpleIntegerLiteral(Token &Tok, uint64_t &Value); /// Disables macro expansion everywhere except for preprocessor directives. void SetMacroExpansionOnlyInDirectives() { DisableMacroExpansion = true; MacroExpansionInDirectivesOverride = true; } /// Peeks ahead N tokens and returns that token without consuming any /// tokens. /// /// LookAhead(0) returns the next token that would be returned by Lex(), /// LookAhead(1) returns the token after it, etc. This returns normal /// tokens after phase 5. As such, it is equivalent to using /// 'Lex', not 'LexUnexpandedToken'. const Token &LookAhead(unsigned N) { assert(LexLevel == 0 && "cannot use lookahead while lexing"); if (CachedLexPos + N < CachedTokens.size()) return CachedTokens[CachedLexPos+N]; else return PeekAhead(N+1); } /// When backtracking is enabled and tokens are cached, /// this allows to revert a specific number of tokens. /// /// Note that the number of tokens being reverted should be up to the last /// backtrack position, not more. void RevertCachedTokens(unsigned N) { assert(isBacktrackEnabled() && "Should only be called when tokens are cached for backtracking"); assert(signed(CachedLexPos) - signed(N) >= signed(BacktrackPositions.back()) && "Should revert tokens up to the last backtrack position, not more"); assert(signed(CachedLexPos) - signed(N) >= 0 && "Corrupted backtrack positions ?"); CachedLexPos -= N; } /// Enters a token in the token stream to be lexed next. /// /// If BackTrack() is called afterwards, the token will remain at the /// insertion point. /// If \p IsReinject is true, resulting token will have Token::IsReinjected /// flag set. See the flag documentation for details. void EnterToken(const Token &Tok, bool IsReinject) { if (LexLevel) { // It's not correct in general to enter caching lex mode while in the // middle of a nested lexing action. auto TokCopy = std::make_unique<Token[]>(1); TokCopy[0] = Tok; EnterTokenStream(std::move(TokCopy), 1, true, IsReinject); } else { EnterCachingLexMode(); assert(IsReinject && "new tokens in the middle of cached stream"); CachedTokens.insert(CachedTokens.begin()+CachedLexPos, Tok); } } /// We notify the Preprocessor that if it is caching tokens (because /// backtrack is enabled) it should replace the most recent cached tokens /// with the given annotation token. This function has no effect if /// backtracking is not enabled. /// /// Note that the use of this function is just for optimization, so that the /// cached tokens doesn't get re-parsed and re-resolved after a backtrack is /// invoked. void AnnotateCachedTokens(const Token &Tok) { assert(Tok.isAnnotation() && "Expected annotation token"); if (CachedLexPos != 0 && isBacktrackEnabled()) AnnotatePreviousCachedTokens(Tok); } /// Get the location of the last cached token, suitable for setting the end /// location of an annotation token. SourceLocation getLastCachedTokenLocation() const { assert(CachedLexPos != 0); return CachedTokens[CachedLexPos-1].getLastLoc(); } /// Whether \p Tok is the most recent token (`CachedLexPos - 1`) in /// CachedTokens. bool IsPreviousCachedToken(const Token &Tok) const; /// Replace token in `CachedLexPos - 1` in CachedTokens by the tokens /// in \p NewToks. /// /// Useful when a token needs to be split in smaller ones and CachedTokens /// most recent token must to be updated to reflect that. void ReplacePreviousCachedToken(ArrayRef<Token> NewToks); /// Replace the last token with an annotation token. /// /// Like AnnotateCachedTokens(), this routine replaces an /// already-parsed (and resolved) token with an annotation /// token. However, this routine only replaces the last token with /// the annotation token; it does not affect any other cached /// tokens. This function has no effect if backtracking is not /// enabled. void ReplaceLastTokenWithAnnotation(const Token &Tok) { assert(Tok.isAnnotation() && "Expected annotation token"); if (CachedLexPos != 0 && isBacktrackEnabled()) CachedTokens[CachedLexPos-1] = Tok; } /// Enter an annotation token into the token stream. void EnterAnnotationToken(SourceRange Range, tok::TokenKind Kind, void *AnnotationVal); /// Update the current token to represent the provided /// identifier, in order to cache an action performed by typo correction. void TypoCorrectToken(const Token &Tok) { assert(Tok.getIdentifierInfo() && "Expected identifier token"); if (CachedLexPos != 0 && isBacktrackEnabled()) CachedTokens[CachedLexPos-1] = Tok; } /// Recompute the current lexer kind based on the CurLexer/ /// CurTokenLexer pointers. void recomputeCurLexerKind(); /// Returns true if incremental processing is enabled bool isIncrementalProcessingEnabled() const { return IncrementalProcessing; } /// Enables the incremental processing void enableIncrementalProcessing(bool value = true) { IncrementalProcessing = value; } /// Specify the point at which code-completion will be performed. /// /// \param File the file in which code completion should occur. If /// this file is included multiple times, code-completion will /// perform completion the first time it is included. If NULL, this /// function clears out the code-completion point. /// /// \param Line the line at which code completion should occur /// (1-based). /// /// \param Column the column at which code completion should occur /// (1-based). /// /// \returns true if an error occurred, false otherwise. bool SetCodeCompletionPoint(const FileEntry *File, unsigned Line, unsigned Column); /// Determine if we are performing code completion. bool isCodeCompletionEnabled() const { return CodeCompletionFile != nullptr; } /// Returns the location of the code-completion point. /// /// Returns an invalid location if code-completion is not enabled or the file /// containing the code-completion point has not been lexed yet. SourceLocation getCodeCompletionLoc() const { return CodeCompletionLoc; } /// Returns the start location of the file of code-completion point. /// /// Returns an invalid location if code-completion is not enabled or the file /// containing the code-completion point has not been lexed yet. SourceLocation getCodeCompletionFileLoc() const { return CodeCompletionFileLoc; } /// Returns true if code-completion is enabled and we have hit the /// code-completion point. bool isCodeCompletionReached() const { return CodeCompletionReached; } /// Note that we hit the code-completion point. void setCodeCompletionReached() { assert(isCodeCompletionEnabled() && "Code-completion not enabled!"); CodeCompletionReached = true; // Silence any diagnostics that occur after we hit the code-completion. getDiagnostics().setSuppressAllDiagnostics(true); } /// The location of the currently-active \#pragma clang /// arc_cf_code_audited begin. /// /// Returns an invalid location if there is no such pragma active. std::pair<IdentifierInfo *, SourceLocation> getPragmaARCCFCodeAuditedInfo() const { return PragmaARCCFCodeAuditedInfo; } /// Set the location of the currently-active \#pragma clang /// arc_cf_code_audited begin. An invalid location ends the pragma. void setPragmaARCCFCodeAuditedInfo(IdentifierInfo *Ident, SourceLocation Loc) { PragmaARCCFCodeAuditedInfo = {Ident, Loc}; } /// The location of the currently-active \#pragma clang /// assume_nonnull begin. /// /// Returns an invalid location if there is no such pragma active. SourceLocation getPragmaAssumeNonNullLoc() const { return PragmaAssumeNonNullLoc; } /// Set the location of the currently-active \#pragma clang /// assume_nonnull begin. An invalid location ends the pragma. void setPragmaAssumeNonNullLoc(SourceLocation Loc) { PragmaAssumeNonNullLoc = Loc; } /// Set the directory in which the main file should be considered /// to have been found, if it is not a real file. void setMainFileDir(const DirectoryEntry *Dir) { MainFileDir = Dir; } /// Instruct the preprocessor to skip part of the main source file. /// /// \param Bytes The number of bytes in the preamble to skip. /// /// \param StartOfLine Whether skipping these bytes puts the lexer at the /// start of a line. void setSkipMainFilePreamble(unsigned Bytes, bool StartOfLine) { SkipMainFilePreamble.first = Bytes; SkipMainFilePreamble.second = StartOfLine; } /// Forwarding function for diagnostics. This emits a diagnostic at /// the specified Token's location, translating the token's start /// position in the current buffer into a SourcePosition object for rendering. DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) const { return Diags->Report(Loc, DiagID); } DiagnosticBuilder Diag(const Token &Tok, unsigned DiagID) const { return Diags->Report(Tok.getLocation(), DiagID); } /// Return the 'spelling' of the token at the given /// location; does not go up to the spelling location or down to the /// expansion location. /// /// \param buffer A buffer which will be used only if the token requires /// "cleaning", e.g. if it contains trigraphs or escaped newlines /// \param invalid If non-null, will be set \c true if an error occurs. StringRef getSpelling(SourceLocation loc, SmallVectorImpl<char> &buffer, bool *invalid = nullptr) const { return Lexer::getSpelling(loc, buffer, SourceMgr, LangOpts, invalid); } /// Return the 'spelling' of the Tok token. /// /// The spelling of a token is the characters used to represent the token in /// the source file after trigraph expansion and escaped-newline folding. In /// particular, this wants to get the true, uncanonicalized, spelling of /// things like digraphs, UCNs, etc. /// /// \param Invalid If non-null, will be set \c true if an error occurs. std::string getSpelling(const Token &Tok, bool *Invalid = nullptr) const { return Lexer::getSpelling(Tok, SourceMgr, LangOpts, Invalid); } /// Get the spelling of a token into a preallocated buffer, instead /// of as an std::string. /// /// The caller is required to allocate enough space for the token, which is /// guaranteed to be at least Tok.getLength() bytes long. The length of the /// actual result is returned. /// /// Note that this method may do two possible things: it may either fill in /// the buffer specified with characters, or it may *change the input pointer* /// to point to a constant buffer with the data already in it (avoiding a /// copy). The caller is not allowed to modify the returned buffer pointer /// if an internal buffer is returned. unsigned getSpelling(const Token &Tok, const char *&Buffer, bool *Invalid = nullptr) const { return Lexer::getSpelling(Tok, Buffer, SourceMgr, LangOpts, Invalid); } /// Get the spelling of a token into a SmallVector. /// /// Note that the returned StringRef may not point to the /// supplied buffer if a copy can be avoided. StringRef getSpelling(const Token &Tok, SmallVectorImpl<char> &Buffer, bool *Invalid = nullptr) const; /// Relex the token at the specified location. /// \returns true if there was a failure, false on success. bool getRawToken(SourceLocation Loc, Token &Result, bool IgnoreWhiteSpace = false) { return Lexer::getRawToken(Loc, Result, SourceMgr, LangOpts, IgnoreWhiteSpace); } /// Given a Token \p Tok that is a numeric constant with length 1, /// return the character. char getSpellingOfSingleCharacterNumericConstant(const Token &Tok, bool *Invalid = nullptr) const { assert(Tok.is(tok::numeric_constant) && Tok.getLength() == 1 && "Called on unsupported token"); assert(!Tok.needsCleaning() && "Token can't need cleaning with length 1"); // If the token is carrying a literal data pointer, just use it. if (const char *D = Tok.getLiteralData()) return *D; // Otherwise, fall back on getCharacterData, which is slower, but always // works. return *SourceMgr.getCharacterData(Tok.getLocation(), Invalid); } /// Retrieve the name of the immediate macro expansion. /// /// This routine starts from a source location, and finds the name of the /// macro responsible for its immediate expansion. It looks through any /// intervening macro argument expansions to compute this. It returns a /// StringRef that refers to the SourceManager-owned buffer of the source /// where that macro name is spelled. Thus, the result shouldn't out-live /// the SourceManager. StringRef getImmediateMacroName(SourceLocation Loc) { return Lexer::getImmediateMacroName(Loc, SourceMgr, getLangOpts()); } /// Plop the specified string into a scratch buffer and set the /// specified token's location and length to it. /// /// If specified, the source location provides a location of the expansion /// point of the token. void CreateString(StringRef Str, Token &Tok, SourceLocation ExpansionLocStart = SourceLocation(), SourceLocation ExpansionLocEnd = SourceLocation()); /// Split the first Length characters out of the token starting at TokLoc /// and return a location pointing to the split token. Re-lexing from the /// split token will return the split token rather than the original. SourceLocation SplitToken(SourceLocation TokLoc, unsigned Length); /// Computes the source location just past the end of the /// token at this source location. /// /// This routine can be used to produce a source location that /// points just past the end of the token referenced by \p Loc, and /// is generally used when a diagnostic needs to point just after a /// token where it expected something different that it received. If /// the returned source location would not be meaningful (e.g., if /// it points into a macro), this routine returns an invalid /// source location. /// /// \param Offset an offset from the end of the token, where the source /// location should refer to. The default offset (0) produces a source /// location pointing just past the end of the token; an offset of 1 produces /// a source location pointing to the last character in the token, etc. SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0) { return Lexer::getLocForEndOfToken(Loc, Offset, SourceMgr, LangOpts); } /// Returns true if the given MacroID location points at the first /// token of the macro expansion. /// /// \param MacroBegin If non-null and function returns true, it is set to /// begin location of the macro. bool isAtStartOfMacroExpansion(SourceLocation loc, SourceLocation *MacroBegin = nullptr) const { return Lexer::isAtStartOfMacroExpansion(loc, SourceMgr, LangOpts, MacroBegin); } /// Returns true if the given MacroID location points at the last /// token of the macro expansion. /// /// \param MacroEnd If non-null and function returns true, it is set to /// end location of the macro. bool isAtEndOfMacroExpansion(SourceLocation loc, SourceLocation *MacroEnd = nullptr) const { return Lexer::isAtEndOfMacroExpansion(loc, SourceMgr, LangOpts, MacroEnd); } /// Print the token to stderr, used for debugging. void DumpToken(const Token &Tok, bool DumpFlags = false) const; void DumpLocation(SourceLocation Loc) const; void DumpMacro(const MacroInfo &MI) const; void dumpMacroInfo(const IdentifierInfo *II); /// Given a location that specifies the start of a /// token, return a new location that specifies a character within the token. SourceLocation AdvanceToTokenCharacter(SourceLocation TokStart, unsigned Char) const { return Lexer::AdvanceToTokenCharacter(TokStart, Char, SourceMgr, LangOpts); } /// Increment the counters for the number of token paste operations /// performed. /// /// If fast was specified, this is a 'fast paste' case we handled. void IncrementPasteCounter(bool isFast) { if (isFast) ++NumFastTokenPaste; else ++NumTokenPaste; } void PrintStats(); size_t getTotalMemory() const; /// When the macro expander pastes together a comment (/##/) in Microsoft /// mode, this method handles updating the current state, returning the /// token on the next source line. void HandleMicrosoftCommentPaste(Token &Tok); //===--------------------------------------------------------------------===// // Preprocessor callback methods. These are invoked by a lexer as various // directives and events are found. /// Given a tok::raw_identifier token, look up the /// identifier information for the token and install it into the token, /// updating the token kind accordingly. IdentifierInfo *LookUpIdentifierInfo(Token &Identifier) const; private: llvm::DenseMap<IdentifierInfo*,unsigned> PoisonReasons; public: /// Specifies the reason for poisoning an identifier. /// /// If that identifier is accessed while poisoned, then this reason will be /// used instead of the default "poisoned" diagnostic. void SetPoisonReason(IdentifierInfo *II, unsigned DiagID); /// Display reason for poisoned identifier. void HandlePoisonedIdentifier(Token & Identifier); void MaybeHandlePoisonedIdentifier(Token & Identifier) { if(IdentifierInfo * II = Identifier.getIdentifierInfo()) { if(II->isPoisoned()) { HandlePoisonedIdentifier(Identifier); } } } private: /// Identifiers used for SEH handling in Borland. These are only /// allowed in particular circumstances // __except block IdentifierInfo *Ident__exception_code, *Ident___exception_code, *Ident_GetExceptionCode; // __except filter expression IdentifierInfo *Ident__exception_info, *Ident___exception_info, *Ident_GetExceptionInfo; // __finally IdentifierInfo *Ident__abnormal_termination, *Ident___abnormal_termination, *Ident_AbnormalTermination; const char *getCurLexerEndPos(); void diagnoseMissingHeaderInUmbrellaDir(const Module &Mod); public: void PoisonSEHIdentifiers(bool Poison = true); // Borland /// Callback invoked when the lexer reads an identifier and has /// filled in the tokens IdentifierInfo member. /// /// This callback potentially macro expands it or turns it into a named /// token (like 'for'). /// /// \returns true if we actually computed a token, false if we need to /// lex again. bool HandleIdentifier(Token &Identifier); /// Callback invoked when the lexer hits the end of the current file. /// /// This either returns the EOF token and returns true, or /// pops a level off the include stack and returns false, at which point the /// client should call lex again. bool HandleEndOfFile(Token &Result, bool isEndOfMacro = false); /// Callback invoked when the current TokenLexer hits the end of its /// token stream. bool HandleEndOfTokenLexer(Token &Result); /// Callback invoked when the lexer sees a # token at the start of a /// line. /// /// This consumes the directive, modifies the lexer/preprocessor state, and /// advances the lexer(s) so that the next token read is the correct one. void HandleDirective(Token &Result); /// Ensure that the next token is a tok::eod token. /// /// If not, emit a diagnostic and consume up until the eod. /// If \p EnableMacros is true, then we consider macros that expand to zero /// tokens as being ok. /// /// \return The location of the end of the directive (the terminating /// newline). SourceLocation CheckEndOfDirective(const char *DirType, bool EnableMacros = false); /// Read and discard all tokens remaining on the current line until /// the tok::eod token is found. Returns the range of the skipped tokens. SourceRange DiscardUntilEndOfDirective(); /// Returns true if the preprocessor has seen a use of /// __DATE__ or __TIME__ in the file so far. bool SawDateOrTime() const { return DATELoc != SourceLocation() || TIMELoc != SourceLocation(); } unsigned getCounterValue() const { return CounterValue; } void setCounterValue(unsigned V) { CounterValue = V; } /// Retrieves the module that we're currently building, if any. Module *getCurrentModule(); /// Allocate a new MacroInfo object with the provided SourceLocation. MacroInfo *AllocateMacroInfo(SourceLocation L); /// Turn the specified lexer token into a fully checked and spelled /// filename, e.g. as an operand of \#include. /// /// The caller is expected to provide a buffer that is large enough to hold /// the spelling of the filename, but is also expected to handle the case /// when this method decides to use a different buffer. /// /// \returns true if the input filename was in <>'s or false if it was /// in ""'s. bool GetIncludeFilenameSpelling(SourceLocation Loc,StringRef &Buffer); /// Given a "foo" or \<foo> reference, look up the indicated file. /// /// Returns None on failure. \p isAngled indicates whether the file /// reference is for system \#include's or not (i.e. using <> instead of ""). Optional<FileEntryRef> LookupFile(SourceLocation FilenameLoc, StringRef Filename, bool isAngled, const DirectoryLookup *FromDir, const FileEntry *FromFile, const DirectoryLookup *&CurDir, SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath, ModuleMap::KnownHeader *SuggestedModule, bool *IsMapped, bool *IsFrameworkFound, bool SkipCache = false); /// Get the DirectoryLookup structure used to find the current /// FileEntry, if CurLexer is non-null and if applicable. /// /// This allows us to implement \#include_next and find directory-specific /// properties. const DirectoryLookup *GetCurDirLookup() { return CurDirLookup; } /// Return true if we're in the top-level file, not in a \#include. bool isInPrimaryFile() const; /// Lex an on-off-switch (C99 6.10.6p2) and verify that it is /// followed by EOD. Return true if the token is not a valid on-off-switch. bool LexOnOffSwitch(tok::OnOffSwitch &Result); bool CheckMacroName(Token &MacroNameTok, MacroUse isDefineUndef, bool *ShadowFlag = nullptr); void EnterSubmodule(Module *M, SourceLocation ImportLoc, bool ForPragma); Module *LeaveSubmodule(bool ForPragma); private: friend void TokenLexer::ExpandFunctionArguments(); void PushIncludeMacroStack() { assert(CurLexerKind != CLK_CachingLexer && "cannot push a caching lexer"); IncludeMacroStack.emplace_back(CurLexerKind, CurLexerSubmodule, std::move(CurLexer), CurPPLexer, std::move(CurTokenLexer), CurDirLookup); CurPPLexer = nullptr; } void PopIncludeMacroStack() { CurLexer = std::move(IncludeMacroStack.back().TheLexer); CurPPLexer = IncludeMacroStack.back().ThePPLexer; CurTokenLexer = std::move(IncludeMacroStack.back().TheTokenLexer); CurDirLookup = IncludeMacroStack.back().TheDirLookup; CurLexerSubmodule = IncludeMacroStack.back().TheSubmodule; CurLexerKind = IncludeMacroStack.back().CurLexerKind; IncludeMacroStack.pop_back(); } void PropagateLineStartLeadingSpaceInfo(Token &Result); /// Determine whether we need to create module macros for #defines in the /// current context. bool needModuleMacros() const; /// Update the set of active module macros and ambiguity flag for a module /// macro name. void updateModuleMacroInfo(const IdentifierInfo *II, ModuleMacroInfo &Info); DefMacroDirective *AllocateDefMacroDirective(MacroInfo *MI, SourceLocation Loc); UndefMacroDirective *AllocateUndefMacroDirective(SourceLocation UndefLoc); VisibilityMacroDirective *AllocateVisibilityMacroDirective(SourceLocation Loc, bool isPublic); /// Lex and validate a macro name, which occurs after a /// \#define or \#undef. /// /// \param MacroNameTok Token that represents the name defined or undefined. /// \param IsDefineUndef Kind if preprocessor directive. /// \param ShadowFlag Points to flag that is set if macro name shadows /// a keyword. /// /// This emits a diagnostic, sets the token kind to eod, /// and discards the rest of the macro line if the macro name is invalid. void ReadMacroName(Token &MacroNameTok, MacroUse IsDefineUndef = MU_Other, bool *ShadowFlag = nullptr); /// ReadOptionalMacroParameterListAndBody - This consumes all (i.e. the /// entire line) of the macro's tokens and adds them to MacroInfo, and while /// doing so performs certain validity checks including (but not limited to): /// - # (stringization) is followed by a macro parameter /// \param MacroNameTok - Token that represents the macro name /// \param ImmediatelyAfterHeaderGuard - Macro follows an #ifdef header guard /// /// Either returns a pointer to a MacroInfo object OR emits a diagnostic and /// returns a nullptr if an invalid sequence of tokens is encountered. MacroInfo *ReadOptionalMacroParameterListAndBody( const Token &MacroNameTok, bool ImmediatelyAfterHeaderGuard); /// The ( starting an argument list of a macro definition has just been read. /// Lex the rest of the parameters and the closing ), updating \p MI with /// what we learn and saving in \p LastTok the last token read. /// Return true if an error occurs parsing the arg list. bool ReadMacroParameterList(MacroInfo *MI, Token& LastTok); /// We just read a \#if or related directive and decided that the /// subsequent tokens are in the \#if'd out portion of the /// file. Lex the rest of the file, until we see an \#endif. If \p /// FoundNonSkipPortion is true, then we have already emitted code for part of /// this \#if directive, so \#else/\#elif blocks should never be entered. If /// \p FoundElse is false, then \#else directives are ok, if not, then we have /// already seen one so a \#else directive is a duplicate. When this returns, /// the caller can lex the first valid token. void SkipExcludedConditionalBlock(SourceLocation HashTokenLoc, SourceLocation IfTokenLoc, bool FoundNonSkipPortion, bool FoundElse, SourceLocation ElseLoc = SourceLocation()); /// Information about the result for evaluating an expression for a /// preprocessor directive. struct DirectiveEvalResult { /// Whether the expression was evaluated as true or not. bool Conditional; /// True if the expression contained identifiers that were undefined. bool IncludedUndefinedIds; /// The source range for the expression. SourceRange ExprRange; }; /// Evaluate an integer constant expression that may occur after a /// \#if or \#elif directive and return a \p DirectiveEvalResult object. /// /// If the expression is equivalent to "!defined(X)" return X in IfNDefMacro. DirectiveEvalResult EvaluateDirectiveExpression(IdentifierInfo *&IfNDefMacro); /// Install the standard preprocessor pragmas: /// \#pragma GCC poison/system_header/dependency and \#pragma once. void RegisterBuiltinPragmas(); /// Register builtin macros such as __LINE__ with the identifier table. void RegisterBuiltinMacros(); /// If an identifier token is read that is to be expanded as a macro, handle /// it and return the next token as 'Tok'. If we lexed a token, return true; /// otherwise the caller should lex again. bool HandleMacroExpandedIdentifier(Token &Identifier, const MacroDefinition &MD); /// Cache macro expanded tokens for TokenLexers. // /// Works like a stack; a TokenLexer adds the macro expanded tokens that is /// going to lex in the cache and when it finishes the tokens are removed /// from the end of the cache. Token *cacheMacroExpandedTokens(TokenLexer *tokLexer, ArrayRef<Token> tokens); void removeCachedMacroExpandedTokensOfLastLexer(); /// Determine whether the next preprocessor token to be /// lexed is a '('. If so, consume the token and return true, if not, this /// method should have no observable side-effect on the lexed tokens. bool isNextPPTokenLParen(); /// After reading "MACRO(", this method is invoked to read all of the formal /// arguments specified for the macro invocation. Returns null on error. MacroArgs *ReadMacroCallArgumentList(Token &MacroName, MacroInfo *MI, SourceLocation &MacroEnd); /// If an identifier token is read that is to be expanded /// as a builtin macro, handle it and return the next token as 'Tok'. void ExpandBuiltinMacro(Token &Tok); /// Read a \c _Pragma directive, slice it up, process it, then /// return the first token after the directive. /// This assumes that the \c _Pragma token has just been read into \p Tok. void Handle_Pragma(Token &Tok); /// Like Handle_Pragma except the pragma text is not enclosed within /// a string literal. void HandleMicrosoft__pragma(Token &Tok); /// Add a lexer to the top of the include stack and /// start lexing tokens from it instead of the current buffer. void EnterSourceFileWithLexer(Lexer *TheLexer, const DirectoryLookup *Dir); /// Set the FileID for the preprocessor predefines. void setPredefinesFileID(FileID FID) { assert(PredefinesFileID.isInvalid() && "PredefinesFileID already set!"); PredefinesFileID = FID; } /// Set the FileID for the PCH through header. void setPCHThroughHeaderFileID(FileID FID); /// Returns true if we are lexing from a file and not a /// pragma or a macro. static bool IsFileLexer(const Lexer* L, const PreprocessorLexer* P) { return L ? !L->isPragmaLexer() : P != nullptr; } static bool IsFileLexer(const IncludeStackInfo& I) { return IsFileLexer(I.TheLexer.get(), I.ThePPLexer); } bool IsFileLexer() const { return IsFileLexer(CurLexer.get(), CurPPLexer); } //===--------------------------------------------------------------------===// // Caching stuff. void CachingLex(Token &Result); bool InCachingLexMode() const { // If the Lexer pointers are 0 and IncludeMacroStack is empty, it means // that we are past EOF, not that we are in CachingLex mode. return !CurPPLexer && !CurTokenLexer && !IncludeMacroStack.empty(); } void EnterCachingLexMode(); void EnterCachingLexModeUnchecked(); void ExitCachingLexMode() { if (InCachingLexMode()) RemoveTopOfLexerStack(); } const Token &PeekAhead(unsigned N); void AnnotatePreviousCachedTokens(const Token &Tok); //===--------------------------------------------------------------------===// /// Handle*Directive - implement the various preprocessor directives. These /// should side-effect the current preprocessor object so that the next call /// to Lex() will return the appropriate token next. void HandleLineDirective(); void HandleDigitDirective(Token &Tok); void HandleUserDiagnosticDirective(Token &Tok, bool isWarning); void HandleIdentSCCSDirective(Token &Tok); void HandleMacroPublicDirective(Token &Tok); void HandleMacroPrivateDirective(); /// An additional notification that can be produced by a header inclusion or /// import to tell the parser what happened. struct ImportAction { enum ActionKind { None, ModuleBegin, ModuleImport, SkippedModuleImport, } Kind; Module *ModuleForHeader = nullptr; ImportAction(ActionKind AK, Module *Mod = nullptr) : Kind(AK), ModuleForHeader(Mod) { assert((AK == None || Mod) && "no module for module action"); } }; Optional<FileEntryRef> LookupHeaderIncludeOrImport( const DirectoryLookup *&CurDir, StringRef Filename, SourceLocation FilenameLoc, CharSourceRange FilenameRange, const Token &FilenameTok, bool &IsFrameworkFound, bool IsImportDecl, bool &IsMapped, const DirectoryLookup *LookupFrom, const FileEntry *LookupFromFile, StringRef LookupFilename, SmallVectorImpl<char> &RelativePath, SmallVectorImpl<char> &SearchPath, ModuleMap::KnownHeader &SuggestedModule, bool isAngled); // File inclusion. void HandleIncludeDirective(SourceLocation HashLoc, Token &Tok, const DirectoryLookup *LookupFrom = nullptr, const FileEntry *LookupFromFile = nullptr); ImportAction HandleHeaderIncludeOrImport(SourceLocation HashLoc, Token &IncludeTok, Token &FilenameTok, SourceLocation EndLoc, const DirectoryLookup *LookupFrom = nullptr, const FileEntry *LookupFromFile = nullptr); void HandleIncludeNextDirective(SourceLocation HashLoc, Token &Tok); void HandleIncludeMacrosDirective(SourceLocation HashLoc, Token &Tok); void HandleImportDirective(SourceLocation HashLoc, Token &Tok); void HandleMicrosoftImportDirective(Token &Tok); public: /// Check that the given module is available, producing a diagnostic if not. /// \return \c true if the check failed (because the module is not available). /// \c false if the module appears to be usable. static bool checkModuleIsAvailable(const LangOptions &LangOpts, const TargetInfo &TargetInfo, DiagnosticsEngine &Diags, Module *M); // Module inclusion testing. /// Find the module that owns the source or header file that /// \p Loc points to. If the location is in a file that was included /// into a module, or is outside any module, returns nullptr. Module *getModuleForLocation(SourceLocation Loc); /// We want to produce a diagnostic at location IncLoc concerning a /// missing module import. /// /// \param IncLoc The location at which the missing import was detected. /// \param M The desired module. /// \param MLoc A location within the desired module at which some desired /// effect occurred (eg, where a desired entity was declared). /// /// \return A file that can be #included to import a module containing MLoc. /// Null if no such file could be determined or if a #include is not /// appropriate. const FileEntry *getModuleHeaderToIncludeForDiagnostics(SourceLocation IncLoc, Module *M, SourceLocation MLoc); bool isRecordingPreamble() const { return PreambleConditionalStack.isRecording(); } bool hasRecordedPreamble() const { return PreambleConditionalStack.hasRecordedPreamble(); } ArrayRef<PPConditionalInfo> getPreambleConditionalStack() const { return PreambleConditionalStack.getStack(); } void setRecordedPreambleConditionalStack(ArrayRef<PPConditionalInfo> s) { PreambleConditionalStack.setStack(s); } void setReplayablePreambleConditionalStack(ArrayRef<PPConditionalInfo> s, llvm::Optional<PreambleSkipInfo> SkipInfo) { PreambleConditionalStack.startReplaying(); PreambleConditionalStack.setStack(s); PreambleConditionalStack.SkipInfo = SkipInfo; } llvm::Optional<PreambleSkipInfo> getPreambleSkipInfo() const { return PreambleConditionalStack.SkipInfo; } private: /// After processing predefined file, initialize the conditional stack from /// the preamble. void replayPreambleConditionalStack(); // Macro handling. void HandleDefineDirective(Token &Tok, bool ImmediatelyAfterHeaderGuard); void HandleUndefDirective(); // Conditional Inclusion. void HandleIfdefDirective(Token &Result, const Token &HashToken, bool isIfndef, bool ReadAnyTokensBeforeDirective); void HandleIfDirective(Token &IfToken, const Token &HashToken, bool ReadAnyTokensBeforeDirective); void HandleEndifDirective(Token &EndifToken); void HandleElseDirective(Token &Result, const Token &HashToken); void HandleElifDirective(Token &ElifToken, const Token &HashToken); // Pragmas. void HandlePragmaDirective(PragmaIntroducer Introducer); public: void HandlePragmaOnce(Token &OnceTok); void HandlePragmaMark(); void HandlePragmaPoison(); void HandlePragmaSystemHeader(Token &SysHeaderTok); void HandlePragmaDependency(Token &DependencyTok); void HandlePragmaPushMacro(Token &Tok); void HandlePragmaPopMacro(Token &Tok); void HandlePragmaIncludeAlias(Token &Tok); void HandlePragmaModuleBuild(Token &Tok); void HandlePragmaHdrstop(Token &Tok); IdentifierInfo *ParsePragmaPushOrPopMacro(Token &Tok); // Return true and store the first token only if any CommentHandler // has inserted some tokens and getCommentRetentionState() is false. bool HandleComment(Token &result, SourceRange Comment); /// A macro is used, update information about macros that need unused /// warnings. void markMacroAsUsed(MacroInfo *MI); private: Optional<unsigned> getSkippedRangeForExcludedConditionalBlock(SourceLocation HashLoc); /// Contains the currently active skipped range mappings for skipping excluded /// conditional directives. ExcludedPreprocessorDirectiveSkipMapping *ExcludedConditionalDirectiveSkipMappings; }; /// Abstract base class that describes a handler that will receive /// source ranges for each of the comments encountered in the source file. class CommentHandler { public: virtual ~CommentHandler(); // The handler shall return true if it has pushed any tokens // to be read using e.g. EnterToken or EnterTokenStream. virtual bool HandleComment(Preprocessor &PP, SourceRange Comment) = 0; }; /// Registry of pragma handlers added by plugins using PragmaHandlerRegistry = llvm::Registry<PragmaHandler>; } // namespace clang #endif // LLVM_CLANG_LEX_PREPROCESSOR_H
{ "pile_set_name": "Github" }
#ifndef __BASE64_H__ #define __BASE64_H__ #include <string> std::string base64_encode(unsigned char const* , unsigned int len); std::string base64_decode(std::string const& s); #endif /* __BASE64_H__ */
{ "pile_set_name": "Github" }
<!DOCTYPE html> <html lang="zh-cn"> <head> <meta charset="UTF-8" /> <title>系统异常</title> <!-- 最新版本的 Bootstrap 核心 CSS 文件 --> <link rel="stylesheet" href="/bootstrap-3.3.7/css/bootstrap.min.css"> <!-- 可选的 Bootstrap 主题文件(一般不用引入) --> <link rel="stylesheet" href="/bootstrap-3.3.7/css/bootstrap-theme.min.css"> <!-- 最新的 Bootstrap 核心 JavaScript 文件 --> <script src="/bootstrap-3.3.7/js/jquery-1.11.2.min.js"></script> <script src="/bootstrap-3.3.7/js/bootstrap.min.js"></script> </head> <body> <br /> <br /> <div class="container"> <div class="jumbotron"> <h1>系统异常!</h1> <p>对不起,系统好像发生异常,请联系管理员或重试!</p> <p><a class="btn btn-primary btn-lg" href="/">返回首页</a></p> </div> </div> </body> </html>
{ "pile_set_name": "Github" }
/* Macros for taking apart, interpreting and processing file names. These are here because some non-Posix (a.k.a. DOSish) systems have drive letter brain-damage at the beginning of an absolute file name, use forward- and back-slash in path names interchangeably, and some of them have case-insensitive file names. Copyright (C) 2000-2019 Free Software Foundation, Inc. This file is part of BFD, the Binary File Descriptor library. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef FILENAMES_H #define FILENAMES_H #include "hashtab.h" /* for hashval_t */ #ifdef __cplusplus extern "C" { #endif #if defined(__MSDOS__) || defined(_WIN32) || defined(__OS2__) || defined (__CYGWIN__) # ifndef HAVE_DOS_BASED_FILE_SYSTEM # define HAVE_DOS_BASED_FILE_SYSTEM 1 # endif # ifndef HAVE_CASE_INSENSITIVE_FILE_SYSTEM # define HAVE_CASE_INSENSITIVE_FILE_SYSTEM 1 # endif # define HAS_DRIVE_SPEC(f) HAS_DOS_DRIVE_SPEC (f) # define IS_DIR_SEPARATOR(c) IS_DOS_DIR_SEPARATOR (c) # define IS_ABSOLUTE_PATH(f) IS_DOS_ABSOLUTE_PATH (f) #else /* not DOSish */ # if defined(__APPLE__) # ifndef HAVE_CASE_INSENSITIVE_FILE_SYSTEM # define HAVE_CASE_INSENSITIVE_FILE_SYSTEM 1 # endif # endif /* __APPLE__ */ # define HAS_DRIVE_SPEC(f) (0) # define IS_DIR_SEPARATOR(c) IS_UNIX_DIR_SEPARATOR (c) # define IS_ABSOLUTE_PATH(f) IS_UNIX_ABSOLUTE_PATH (f) #endif #define IS_DIR_SEPARATOR_1(dos_based, c) \ (((c) == '/') \ || (((c) == '\\') && (dos_based))) #define HAS_DRIVE_SPEC_1(dos_based, f) \ ((f)[0] && ((f)[1] == ':') && (dos_based)) /* Remove the drive spec from F, assuming HAS_DRIVE_SPEC (f). The result is a pointer to the remainder of F. */ #define STRIP_DRIVE_SPEC(f) ((f) + 2) #define IS_DOS_DIR_SEPARATOR(c) IS_DIR_SEPARATOR_1 (1, c) #define IS_DOS_ABSOLUTE_PATH(f) IS_ABSOLUTE_PATH_1 (1, f) #define HAS_DOS_DRIVE_SPEC(f) HAS_DRIVE_SPEC_1 (1, f) #define IS_UNIX_DIR_SEPARATOR(c) IS_DIR_SEPARATOR_1 (0, c) #define IS_UNIX_ABSOLUTE_PATH(f) IS_ABSOLUTE_PATH_1 (0, f) /* Note that when DOS_BASED is true, IS_ABSOLUTE_PATH accepts d:foo as well, although it is only semi-absolute. This is because the users of IS_ABSOLUTE_PATH want to know whether to prepend the current working directory to a file name, which should not be done with a name like d:foo. */ #define IS_ABSOLUTE_PATH_1(dos_based, f) \ (IS_DIR_SEPARATOR_1 (dos_based, (f)[0]) \ || HAS_DRIVE_SPEC_1 (dos_based, f)) extern int filename_cmp (const char *s1, const char *s2); #define FILENAME_CMP(s1, s2) filename_cmp(s1, s2) extern int filename_ncmp (const char *s1, const char *s2, size_t n); extern hashval_t filename_hash (const void *s); extern int filename_eq (const void *s1, const void *s2); extern int canonical_filename_eq (const char *a, const char *b); #ifdef __cplusplus } #endif #endif /* FILENAMES_H */
{ "pile_set_name": "Github" }
# Copyright (c) 2014-2020 Maltrail developers (https://github.com/stamparm/maltrail/) # See the file 'LICENSE' for copying permission # Reference: https://www.symantec.com/security_response/writeup.jsp?docid=2011-072806-2905-99&tabid=2 cooshare.com/careu/positionrecorder.asmx
{ "pile_set_name": "Github" }
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chromeos/disks/disk_mount_manager.h" #include <stddef.h> #include <stdint.h> #include <map> #include <set> #include <string> #include <utility> #include <vector> #include "base/barrier_closure.h" #include "base/bind.h" #include "base/bind_helpers.h" #include "base/logging.h" #include "base/macros.h" #include "base/memory/ptr_util.h" #include "base/memory/weak_ptr.h" #include "base/metrics/histogram_functions.h" #include "base/observer_list.h" #include "base/strings/string_util.h" #include "chromeos/constants/chromeos_features.h" #include "chromeos/dbus/cros_disks_client.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/disks/disk.h" #include "chromeos/disks/suspend_unmount_manager.h" namespace chromeos { namespace disks { namespace { constexpr char kDeviceNotFound[] = "Device could not be found"; DiskMountManager* g_disk_mount_manager = NULL; struct UnmountDeviceRecursivelyCallbackData { UnmountDeviceRecursivelyCallbackData( DiskMountManager::UnmountDeviceRecursivelyCallbackType in_callback) : callback(std::move(in_callback)) {} DiskMountManager::UnmountDeviceRecursivelyCallbackType callback; MountError error_code = MOUNT_ERROR_NONE; }; void OnAllUnmountDeviceRecursively( std::unique_ptr<UnmountDeviceRecursivelyCallbackData> cb_data) { std::move(cb_data->callback).Run(cb_data->error_code); } std::string FormatFileSystemTypeToString(FormatFileSystemType filesystem) { switch (filesystem) { case FormatFileSystemType::kUnknown: return ""; case FormatFileSystemType::kVfat: return "vfat"; case FormatFileSystemType::kExfat: return "exfat"; case FormatFileSystemType::kNtfs: return "ntfs"; } NOTREACHED() << "Unknown filesystem type " << static_cast<int>(filesystem); return ""; } // The DiskMountManager implementation. class DiskMountManagerImpl : public DiskMountManager, public CrosDisksClient::Observer { public: DiskMountManagerImpl() : already_refreshed_(false) { DBusThreadManager* dbus_thread_manager = DBusThreadManager::Get(); cros_disks_client_ = dbus_thread_manager->GetCrosDisksClient(); suspend_unmount_manager_.reset(new SuspendUnmountManager(this)); cros_disks_client_->AddObserver(this); } ~DiskMountManagerImpl() override { cros_disks_client_->RemoveObserver(this); } // DiskMountManager override. void AddObserver(DiskMountManager::Observer* observer) override { observers_.AddObserver(observer); } // DiskMountManager override. void RemoveObserver(DiskMountManager::Observer* observer) override { observers_.RemoveObserver(observer); } // DiskMountManager override. void MountPath(const std::string& source_path, const std::string& source_format, const std::string& mount_label, const std::vector<std::string>& mount_options, MountType type, MountAccessMode access_mode) override { // Hidden and non-existent devices should not be mounted. if (type == MOUNT_TYPE_DEVICE) { DiskMap::const_iterator it = disks_.find(source_path); if (it == disks_.end() || it->second->is_hidden()) { OnMountCompleted(MountEntry(MOUNT_ERROR_INTERNAL, source_path, type, "")); return; } } std::vector<std::string> options = mount_options; if (base::FeatureList::IsEnabled(chromeos::features::kFsNosymfollow)) options.push_back("nosymfollow"); cros_disks_client_->Mount( source_path, source_format, mount_label, options, access_mode, REMOUNT_OPTION_MOUNT_NEW_DEVICE, base::BindOnce(&DiskMountManagerImpl::OnMount, weak_ptr_factory_.GetWeakPtr(), source_path, type)); // Record the access mode option passed to CrosDisks. // This is needed because CrosDisks service methods doesn't return the info // via DBus. access_modes_.insert(std::make_pair(source_path, access_mode)); } // DiskMountManager override. void UnmountPath(const std::string& mount_path, UnmountPathCallback callback) override { UnmountChildMounts(mount_path); cros_disks_client_->Unmount( mount_path, base::BindOnce(&DiskMountManagerImpl::OnUnmountPath, weak_ptr_factory_.GetWeakPtr(), std::move(callback), mount_path)); } void RemountAllRemovableDrives(MountAccessMode mode) override { // TODO(yamaguchi): Retry for tentative remount failures. crbug.com/661455 for (const auto& device_path_and_disk : disks_) { const Disk& disk = *device_path_and_disk.second; if (disk.is_read_only_hardware()) { // Read-only devices can be mounted in RO mode only. No need to remount. continue; } if (!disk.is_mounted()) { continue; } RemountRemovableDrive(disk, mode); } } // DiskMountManager override. void FormatMountedDevice(const std::string& mount_path, FormatFileSystemType filesystem, const std::string& label) override { MountPointMap::const_iterator mount_point = mount_points_.find(mount_path); if (mount_point == mount_points_.end()) { LOG(ERROR) << "Mount point with path \"" << mount_path << "\" not found."; // We can't call OnFormatCompleted until |pending_format_changes_| has // been populated. NotifyFormatStatusUpdate(FORMAT_COMPLETED, FORMAT_ERROR_UNKNOWN, mount_path, label); return; } std::string device_path = mount_point->second.source_path; const std::string filesystem_str = FormatFileSystemTypeToString(filesystem); pending_format_changes_[device_path] = {filesystem_str, label}; DiskMap::const_iterator disk = disks_.find(device_path); if (disk == disks_.end()) { LOG(ERROR) << "Device with path \"" << device_path << "\" not found."; OnFormatCompleted(FORMAT_ERROR_UNKNOWN, device_path); return; } if (disk->second->is_read_only()) { LOG(ERROR) << "Device with path \"" << device_path << "\" is read-only."; OnFormatCompleted(FORMAT_ERROR_DEVICE_NOT_ALLOWED, device_path); return; } if (filesystem == FormatFileSystemType::kUnknown) { LOG(ERROR) << "Unknown filesystem passed to FormatMountedDevice"; OnFormatCompleted(FORMAT_ERROR_UNSUPPORTED_FILESYSTEM, device_path); return; } UnmountPath(disk->second->mount_path(), base::BindOnce(&DiskMountManagerImpl::OnUnmountPathForFormat, weak_ptr_factory_.GetWeakPtr(), device_path, filesystem, label)); } void RenameMountedDevice(const std::string& mount_path, const std::string& volume_name) override { MountPointMap::const_iterator mount_point = mount_points_.find(mount_path); if (mount_point == mount_points_.end()) { LOG(ERROR) << "Mount point with path '" << mount_path << "' not found."; // We can't call OnRenameCompleted until |pending_rename_changes_| has // been populated. NotifyRenameStatusUpdate(RENAME_COMPLETED, RENAME_ERROR_UNKNOWN, mount_path, volume_name); return; } std::string device_path = mount_point->second.source_path; pending_rename_changes_[device_path] = volume_name; DiskMap::const_iterator iter = disks_.find(device_path); if (iter == disks_.end()) { LOG(ERROR) << "Device with path '" << device_path << "' not found."; OnRenameCompleted(RENAME_ERROR_UNKNOWN, device_path); return; } if (iter->second->is_read_only()) { LOG(ERROR) << "Device with path '" << device_path << "' is read-only."; OnRenameCompleted(RENAME_ERROR_DEVICE_NOT_ALLOWED, device_path); return; } UnmountPath(iter->second->mount_path(), base::BindOnce(&DiskMountManagerImpl::OnUnmountPathForRename, weak_ptr_factory_.GetWeakPtr(), device_path, volume_name)); } // DiskMountManager override. void UnmountDeviceRecursively( const std::string& device_path, UnmountDeviceRecursivelyCallbackType callback) override { std::vector<std::string> devices_to_unmount; // Get list of all devices to unmount. int device_path_len = device_path.length(); for (DiskMap::iterator it = disks_.begin(); it != disks_.end(); ++it) { if (!it->second->mount_path().empty() && strncmp(device_path.c_str(), it->second->device_path().c_str(), device_path_len) == 0) { devices_to_unmount.push_back(it->second->mount_path()); } } // We should detect at least original device. if (devices_to_unmount.empty()) { if (disks_.find(device_path) == disks_.end()) { LOG(WARNING) << "Unmount recursive request failed for device " << device_path << ", with error: " << kDeviceNotFound; std::move(callback).Run(MOUNT_ERROR_INVALID_DEVICE_PATH); return; } // Nothing to unmount. std::move(callback).Run(MOUNT_ERROR_NONE); return; } std::unique_ptr<UnmountDeviceRecursivelyCallbackData> cb_data = std::make_unique<UnmountDeviceRecursivelyCallbackData>( std::move(callback)); UnmountDeviceRecursivelyCallbackData* raw_cb_data = cb_data.get(); base::RepeatingClosure done_callback = base::BarrierClosure( devices_to_unmount.size(), base::BindOnce(&OnAllUnmountDeviceRecursively, std::move(cb_data))); for (size_t i = 0; i < devices_to_unmount.size(); ++i) { cros_disks_client_->Unmount( devices_to_unmount[i], base::BindOnce(&DiskMountManagerImpl::OnUnmountDeviceRecursively, weak_ptr_factory_.GetWeakPtr(), raw_cb_data, devices_to_unmount[i], done_callback)); } } // DiskMountManager override. void EnsureMountInfoRefreshed(EnsureMountInfoRefreshedCallback callback, bool force) override { if (!force && already_refreshed_) { std::move(callback).Run(true); return; } refresh_callbacks_.push_back(std::move(callback)); if (refresh_callbacks_.size() == 1) { // If there's no in-flight refreshing task, start it. cros_disks_client_->EnumerateDevices( base::BindOnce(&DiskMountManagerImpl::RefreshAfterEnumerateDevices, weak_ptr_factory_.GetWeakPtr()), base::BindOnce(&DiskMountManagerImpl::RefreshCompleted, weak_ptr_factory_.GetWeakPtr(), false)); } } // DiskMountManager override. const DiskMap& disks() const override { return disks_; } // DiskMountManager override. const Disk* FindDiskBySourcePath( const std::string& source_path) const override { DiskMap::const_iterator disk_it = disks_.find(source_path); return disk_it == disks_.end() ? NULL : disk_it->second.get(); } // DiskMountManager override. const MountPointMap& mount_points() const override { return mount_points_; } // DiskMountManager override. bool AddDiskForTest(std::unique_ptr<Disk> disk) override { if (disks_.find(disk->device_path()) != disks_.end()) { LOG(ERROR) << "Attempt to add a duplicate disk"; return false; } disks_.insert(std::make_pair(disk->device_path(), std::move(disk))); return true; } // DiskMountManager override. // Corresponding disk should be added to the manager before this is called. bool AddMountPointForTest(const MountPointInfo& mount_point) override { if (mount_points_.find(mount_point.mount_path) != mount_points_.end()) { LOG(ERROR) << "Attempt to add a duplicate mount point"; return false; } if (mount_point.mount_type == chromeos::MOUNT_TYPE_DEVICE && disks_.find(mount_point.source_path) == disks_.end()) { LOG(ERROR) << "Device mount points must have a disk entry."; return false; } mount_points_.insert(std::make_pair(mount_point.mount_path, mount_point)); return true; } private: // A struct to represent information about a format changes. struct FormatChange { // new file system type std::string file_system_type; // New volume name std::string volume_name; }; // Stores new volume name and file system type for a device on which // formatting is invoked on, so that OnFormatCompleted can set it back to // |disks_|. The key is a device_path and the value is a FormatChange. std::map<std::string, FormatChange> pending_format_changes_; // Stores new volume name for a device on which renaming is invoked on, so // that OnRenameCompleted can set it back to |disks_|. The key is a // device_path and the value is new volume_name. std::map<std::string, std::string> pending_rename_changes_; // Called on D-Bus CrosDisksClient::Mount() is done. void OnMount(const std::string& source_path, MountType type, bool result) { // When succeeds, OnMountCompleted will be called by "MountCompleted", // signal instead. Do nothing now. if (result) return; OnMountCompleted( MountEntry(MOUNT_ERROR_INTERNAL, source_path, type, std::string())); } void RemountRemovableDrive(const Disk& disk, MountAccessMode access_mode) { const std::string& mount_path = disk.mount_path(); MountPointMap::const_iterator mount_point = mount_points_.find(mount_path); if (mount_point == mount_points_.end()) { // Not in mount_points_. This happens when the mount_points and disks_ are // inconsistent. LOG(ERROR) << "Mount point with path \"" << mount_path << "\" not found."; OnMountCompleted( MountEntry(MOUNT_ERROR_PATH_NOT_MOUNTED, disk.device_path(), MOUNT_TYPE_DEVICE, mount_path)); return; } const std::string& source_path = mount_point->second.source_path; // Update the access mode option passed to CrosDisks. // This is needed because CrosDisks service methods doesn't return the info // via DBus, and must be updated before issuing Mount command as it'll be // read by the handler of MountCompleted signal. access_modes_[source_path] = access_mode; cros_disks_client_->Mount( mount_point->second.source_path, std::string(), std::string(), {}, access_mode, REMOUNT_OPTION_REMOUNT_EXISTING_DEVICE, base::BindOnce(&DiskMountManagerImpl::OnMount, weak_ptr_factory_.GetWeakPtr(), source_path, mount_point->second.mount_type)); } // Unmounts all mount points whose source path is transitively parented by // |mount_path|. void UnmountChildMounts(const std::string& mount_path_in) { std::string mount_path = mount_path_in; // Let's make sure mount path has trailing slash. if (mount_path.back() != '/') mount_path += '/'; for (MountPointMap::iterator it = mount_points_.begin(); it != mount_points_.end(); ++it) { if (base::StartsWith(it->second.source_path, mount_path, base::CompareCase::SENSITIVE)) { // TODO(tbarzic): Handle the case where this fails. UnmountPath(it->second.mount_path, UnmountPathCallback()); } } } // Callback for UnmountDeviceRecursively. void OnUnmountDeviceRecursively(UnmountDeviceRecursivelyCallbackData* cb_data, const std::string& mount_path, base::OnceClosure done_callback, MountError error_code) { if (error_code == MOUNT_ERROR_PATH_NOT_MOUNTED || error_code == MOUNT_ERROR_INVALID_PATH) { // The path was already unmounted by something else. error_code = MOUNT_ERROR_NONE; } if (error_code == MOUNT_ERROR_NONE) { // Do standard processing for Unmount event. OnUnmountPath(UnmountPathCallback(), mount_path, MOUNT_ERROR_NONE); VLOG(1) << mount_path << " unmounted."; } else { // This causes the last non-success error to be reported. // TODO(amistry): We could ignore certain errors such as // MOUNT_ERROR_PATH_NOT_MOUNTED, or prioritise more important ones. cb_data->error_code = error_code; } std::move(done_callback).Run(); } // CrosDisksClient::Observer override. void OnMountCompleted(const MountEntry& entry) override { MountCondition mount_condition = MOUNT_CONDITION_NONE; if (entry.mount_type() == MOUNT_TYPE_DEVICE) { if (entry.error_code() == MOUNT_ERROR_UNKNOWN_FILESYSTEM) { mount_condition = MOUNT_CONDITION_UNKNOWN_FILESYSTEM; } if (entry.error_code() == MOUNT_ERROR_UNSUPPORTED_FILESYSTEM) { mount_condition = MOUNT_CONDITION_UNSUPPORTED_FILESYSTEM; } } const MountPointInfo mount_info(entry.source_path(), entry.mount_path(), entry.mount_type(), mount_condition); // If the device is corrupted but it's still possible to format it, it will // be fake mounted. if ((entry.error_code() == MOUNT_ERROR_NONE || mount_info.mount_condition) && mount_points_.find(mount_info.mount_path) == mount_points_.end()) { mount_points_.insert(MountPointMap::value_type(mount_info.mount_path, mount_info)); } Disk* disk = nullptr; if ((entry.error_code() == MOUNT_ERROR_NONE || mount_info.mount_condition) && mount_info.mount_type == MOUNT_TYPE_DEVICE && !mount_info.source_path.empty() && !mount_info.mount_path.empty()) { DiskMap::iterator iter = disks_.find(mount_info.source_path); if (iter != disks_.end()) { // disk might have been removed by now? disk = iter->second.get(); DCHECK(disk); // Currently the MountCompleted signal doesn't tell whether the device // is mounted in read-only mode or not. Instead use the mount option // recorded by DiskMountManagerImpl::MountPath(). // |source_path| should be same as |disk->device_path| because // |VolumeManager::OnDiskEvent()| passes the latter to cros-disks as a // source path when mounting a device. AccessModeMap::iterator it = access_modes_.find(entry.source_path()); // Store whether the disk was mounted in read-only mode due to a policy. disk->set_write_disabled_by_policy( it != access_modes_.end() && !disk->is_read_only_hardware() && it->second == MOUNT_ACCESS_MODE_READ_ONLY); disk->SetMountPath(mount_info.mount_path); // Only set the mount path if the disk is actually mounted. Right now, a // number of code paths (format, rename, unmount) rely on the mount path // being set even if the disk isn't mounted. cros-disks also does some // tracking of non-mounted mount paths. Making this change is // non-trivial. // TODO(amistry): Change these code paths to use device path instead of // mount path. disk->set_mounted(entry.error_code() == MOUNT_ERROR_NONE); } } // Observers may read the values of disks_. So notify them after tweaking // values of disks_. NotifyMountStatusUpdate(MOUNTING, entry.error_code(), mount_info); if (disk) { disk->set_is_first_mount(false); } } // Callback for UnmountPath. void OnUnmountPath(UnmountPathCallback callback, const std::string& mount_path, MountError error_code) { MountPointMap::iterator mount_points_it = mount_points_.find(mount_path); if (mount_points_it == mount_points_.end()) { // The path was unmounted, but not as a result of this unmount request, // so return error. if (!callback.is_null()) std::move(callback).Run(MOUNT_ERROR_INTERNAL); return; } if (error_code == MOUNT_ERROR_PATH_NOT_MOUNTED || error_code == MOUNT_ERROR_INVALID_PATH) { // The path was already unmounted by something else. error_code = MOUNT_ERROR_NONE; } NotifyMountStatusUpdate( UNMOUNTING, error_code, MountPointInfo(mount_points_it->second.source_path, mount_points_it->second.mount_path, mount_points_it->second.mount_type, mount_points_it->second.mount_condition)); std::string path(mount_points_it->second.source_path); if (error_code == MOUNT_ERROR_NONE) mount_points_.erase(mount_points_it); DiskMap::iterator disk_iter = disks_.find(path); if (disk_iter != disks_.end()) { DCHECK(disk_iter->second); if (error_code == MOUNT_ERROR_NONE) { disk_iter->second->clear_mount_path(); disk_iter->second->set_mounted(false); } } if (!callback.is_null()) std::move(callback).Run(error_code); } void OnUnmountPathForFormat(const std::string& device_path, FormatFileSystemType filesystem, const std::string& label, MountError error_code) { if (error_code == MOUNT_ERROR_NONE && disks_.find(device_path) != disks_.end()) { FormatUnmountedDevice(device_path, filesystem, label); } else { OnFormatCompleted(FORMAT_ERROR_UNKNOWN, device_path); } } // Starts device formatting. void FormatUnmountedDevice(const std::string& device_path, FormatFileSystemType filesystem, const std::string& label) { DiskMap::const_iterator disk = disks_.find(device_path); DCHECK(disk != disks_.end() && disk->second->mount_path().empty()); base::UmaHistogramEnumeration("FileBrowser.FormatFileSystemType", filesystem); cros_disks_client_->Format( device_path, FormatFileSystemTypeToString(filesystem), label, base::BindOnce(&DiskMountManagerImpl::OnFormatStarted, weak_ptr_factory_.GetWeakPtr(), device_path, label)); } // Callback for Format. void OnFormatStarted(const std::string& device_path, const std::string& device_label, bool success) { if (!success) { OnFormatCompleted(FORMAT_ERROR_UNKNOWN, device_path); return; } NotifyFormatStatusUpdate(FORMAT_STARTED, FORMAT_ERROR_NONE, device_path, device_label); } // CrosDisksClient::Observer override. void OnFormatCompleted(FormatError error_code, const std::string& device_path) override { std::string device_label; auto pending_change = pending_format_changes_.find(device_path); if (pending_change != pending_format_changes_.end()) { device_label = pending_change->second.volume_name; } auto iter = disks_.find(device_path); // disk might have been removed by now? if (iter != disks_.end()) { Disk* disk = iter->second.get(); DCHECK(disk); if (pending_change != pending_format_changes_.end() && error_code == FORMAT_ERROR_NONE) { disk->set_device_label(pending_change->second.volume_name); disk->set_file_system_type(pending_change->second.file_system_type); } } pending_format_changes_.erase(device_path); NotifyFormatStatusUpdate(FORMAT_COMPLETED, error_code, device_path, device_label); } void OnUnmountPathForRename(const std::string& device_path, const std::string& volume_name, MountError error_code) { if (error_code != MOUNT_ERROR_NONE || disks_.find(device_path) == disks_.end()) { OnRenameCompleted(RENAME_ERROR_UNKNOWN, device_path); return; } RenameUnmountedDevice(device_path, volume_name); } // Start device renaming void RenameUnmountedDevice(const std::string& device_path, const std::string& volume_name) { DiskMap::const_iterator disk = disks_.find(device_path); DCHECK(disk != disks_.end() && disk->second->mount_path().empty()); cros_disks_client_->Rename( device_path, volume_name, base::BindOnce(&DiskMountManagerImpl::OnRenameStarted, weak_ptr_factory_.GetWeakPtr(), device_path, volume_name)); } // Callback for Rename. void OnRenameStarted(const std::string& device_path, const std::string& volume_name, bool success) { if (!success) { OnRenameCompleted(RENAME_ERROR_UNKNOWN, device_path); return; } NotifyRenameStatusUpdate(RENAME_STARTED, RENAME_ERROR_NONE, device_path, volume_name); } // CrosDisksClient::Observer override. void OnRenameCompleted(RenameError error_code, const std::string& device_path) override { std::string device_label; auto pending_change = pending_rename_changes_.find(device_path); if (pending_change != pending_rename_changes_.end()) { device_label = pending_change->second; } auto iter = disks_.find(device_path); // disk might have been removed by now? if (iter != disks_.end()) { Disk* disk = iter->second.get(); DCHECK(disk); if (pending_change != pending_rename_changes_.end() && error_code == RENAME_ERROR_NONE) disk->set_device_label(pending_change->second); } pending_rename_changes_.erase(device_path); NotifyRenameStatusUpdate(RENAME_COMPLETED, error_code, device_path, device_label); } // Callback for GetDeviceProperties. void OnGetDeviceProperties(const DiskInfo& disk_info) { if (disk_info.is_virtual()) return; DVLOG(1) << "Found disk " << disk_info.device_path(); // Delete previous disk info for this path: bool is_new = true; bool is_first_mount = false; std::string base_mount_path = std::string(); DiskMap::iterator iter = disks_.find(disk_info.device_path()); if (iter != disks_.end()) { is_first_mount = iter->second->is_first_mount(); base_mount_path = iter->second->base_mount_path(); disks_.erase(iter); is_new = false; } // If the device was mounted by the instance, apply recorded parameter. // Otherwise, default to false. // Lookup by |device_path| which we pass to cros-disks when mounting a // device in |VolumeManager::OnDiskEvent()|. auto access_mode = access_modes_.find(disk_info.device_path()); bool write_disabled_by_policy = access_mode != access_modes_.end() && access_mode->second == chromeos::MOUNT_ACCESS_MODE_READ_ONLY; Disk* disk = new Disk(disk_info, write_disabled_by_policy, base_mount_path); if (!is_new) { disk->set_is_first_mount(is_first_mount); } disks_.insert( std::make_pair(disk_info.device_path(), base::WrapUnique(disk))); NotifyDiskStatusUpdate(is_new ? DISK_ADDED : DISK_CHANGED, *disk); } // Part of EnsureMountInfoRefreshed(). Called after the list of devices are // enumerated. void RefreshAfterEnumerateDevices(const std::vector<std::string>& devices) { std::set<std::string> current_device_set(devices.begin(), devices.end()); for (DiskMap::iterator iter = disks_.begin(); iter != disks_.end(); ) { if (current_device_set.find(iter->first) == current_device_set.end()) { disks_.erase(iter++); } else { ++iter; } } RefreshDeviceAtIndex(devices, 0); } // Part of EnsureMountInfoRefreshed(). Called for each device to refresh info. void RefreshDeviceAtIndex(const std::vector<std::string>& devices, size_t index) { if (index == devices.size()) { // All devices info retrieved. Proceed to enumerate mount point info. cros_disks_client_->EnumerateMountEntries( base::BindOnce( &DiskMountManagerImpl::RefreshAfterEnumerateMountEntries, weak_ptr_factory_.GetWeakPtr()), base::BindOnce(&DiskMountManagerImpl::RefreshCompleted, weak_ptr_factory_.GetWeakPtr(), false)); return; } cros_disks_client_->GetDeviceProperties( devices[index], base::BindOnce(&DiskMountManagerImpl::RefreshAfterGetDeviceProperties, weak_ptr_factory_.GetWeakPtr(), devices, index + 1), base::BindOnce(&DiskMountManagerImpl::RefreshDeviceAtIndex, weak_ptr_factory_.GetWeakPtr(), devices, index + 1)); } // Part of EnsureMountInfoRefreshed(). void RefreshAfterGetDeviceProperties(const std::vector<std::string>& devices, size_t next_index, const DiskInfo& disk_info) { OnGetDeviceProperties(disk_info); RefreshDeviceAtIndex(devices, next_index); } // Part of EnsureMountInfoRefreshed(). Called after mount entries are listed. void RefreshAfterEnumerateMountEntries( const std::vector<MountEntry>& entries) { for (size_t i = 0; i < entries.size(); ++i) OnMountCompleted(entries[i]); RefreshCompleted(true); } // Part of EnsureMountInfoRefreshed(). Called when the refreshing is done. void RefreshCompleted(bool success) { already_refreshed_ = true; for (size_t i = 0; i < refresh_callbacks_.size(); ++i) std::move(refresh_callbacks_[i]).Run(success); refresh_callbacks_.clear(); } // CrosDisksClient::Observer override. void OnMountEvent(MountEventType event, const std::string& device_path_arg) override { // Take a copy of the argument so we can modify it below. std::string device_path = device_path_arg; switch (event) { case CROS_DISKS_DISK_ADDED: { cros_disks_client_->GetDeviceProperties( device_path, base::BindOnce(&DiskMountManagerImpl::OnGetDeviceProperties, weak_ptr_factory_.GetWeakPtr()), base::DoNothing()); break; } case CROS_DISKS_DISK_REMOVED: { // Search and remove disks that are no longer present. DiskMountManager::DiskMap::iterator iter = disks_.find(device_path); if (iter != disks_.end()) { Disk* disk = iter->second.get(); NotifyDiskStatusUpdate(DISK_REMOVED, *disk); disks_.erase(iter); } break; } case CROS_DISKS_DEVICE_ADDED: { NotifyDeviceStatusUpdate(DEVICE_ADDED, device_path); break; } case CROS_DISKS_DEVICE_REMOVED: { NotifyDeviceStatusUpdate(DEVICE_REMOVED, device_path); break; } case CROS_DISKS_DEVICE_SCANNED: { NotifyDeviceStatusUpdate(DEVICE_SCANNED, device_path); break; } default: { LOG(ERROR) << "Unknown event: " << event; } } } // Notifies all observers about disk status update. void NotifyDiskStatusUpdate(DiskEvent event, const Disk& disk) { for (auto& observer : observers_) { disk.is_auto_mountable() ? observer.OnAutoMountableDiskEvent(event, disk) : observer.OnBootDeviceDiskEvent(event, disk); } } // Notifies all observers about device status update. void NotifyDeviceStatusUpdate(DeviceEvent event, const std::string& device_path) { for (auto& observer : observers_) observer.OnDeviceEvent(event, device_path); } // Notifies all observers about mount completion. void NotifyMountStatusUpdate(MountEvent event, MountError error_code, const MountPointInfo& mount_info) { for (auto& observer : observers_) observer.OnMountEvent(event, error_code, mount_info); } void NotifyFormatStatusUpdate(FormatEvent event, FormatError error_code, const std::string& device_path, const std::string& device_label) { for (auto& observer : observers_) observer.OnFormatEvent(event, error_code, device_path, device_label); } void NotifyRenameStatusUpdate(RenameEvent event, RenameError error_code, const std::string& device_path, const std::string& device_label) { for (auto& observer : observers_) observer.OnRenameEvent(event, error_code, device_path, device_label); } // Mount event change observers. base::ObserverList<DiskMountManager::Observer> observers_; CrosDisksClient* cros_disks_client_; // The list of disks found. DiskMountManager::DiskMap disks_; DiskMountManager::MountPointMap mount_points_; bool already_refreshed_; std::vector<EnsureMountInfoRefreshedCallback> refresh_callbacks_; std::unique_ptr<SuspendUnmountManager> suspend_unmount_manager_; // Whether the instance attempted to mount a device in read-only mode for // each source path. typedef std::map<std::string, chromeos::MountAccessMode> AccessModeMap; AccessModeMap access_modes_; base::WeakPtrFactory<DiskMountManagerImpl> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(DiskMountManagerImpl); }; } // namespace DiskMountManager::Observer::~Observer() { DCHECK(!IsInObserverList()); } bool DiskMountManager::AddDiskForTest(std::unique_ptr<Disk> disk) { return false; } bool DiskMountManager::AddMountPointForTest(const MountPointInfo& mount_point) { return false; } // static std::string DiskMountManager::MountConditionToString(MountCondition condition) { switch (condition) { case MOUNT_CONDITION_NONE: return ""; case MOUNT_CONDITION_UNKNOWN_FILESYSTEM: return "unknown_filesystem"; case MOUNT_CONDITION_UNSUPPORTED_FILESYSTEM: return "unsupported_filesystem"; default: NOTREACHED(); } return ""; } // static std::string DiskMountManager::DeviceTypeToString(DeviceType type) { switch (type) { case DEVICE_TYPE_USB: return "usb"; case DEVICE_TYPE_SD: return "sd"; case DEVICE_TYPE_OPTICAL_DISC: return "optical"; case DEVICE_TYPE_MOBILE: return "mobile"; default: return "unknown"; } } // static void DiskMountManager::Initialize() { if (g_disk_mount_manager) { LOG(WARNING) << "DiskMountManager was already initialized"; return; } g_disk_mount_manager = new DiskMountManagerImpl(); VLOG(1) << "DiskMountManager initialized"; } // static void DiskMountManager::InitializeForTesting( DiskMountManager* disk_mount_manager) { if (g_disk_mount_manager) { LOG(WARNING) << "DiskMountManager was already initialized"; return; } g_disk_mount_manager = disk_mount_manager; VLOG(1) << "DiskMountManager initialized"; } // static void DiskMountManager::Shutdown() { if (!g_disk_mount_manager) { LOG(WARNING) << "DiskMountManager::Shutdown() called with NULL manager"; return; } delete g_disk_mount_manager; g_disk_mount_manager = NULL; VLOG(1) << "DiskMountManager Shutdown completed"; } // static DiskMountManager* DiskMountManager::GetInstance() { return g_disk_mount_manager; } } // namespace disks } // namespace chromeos
{ "pile_set_name": "Github" }
<?php class Swift_Transport_EsmtpTransportTest extends Swift_Transport_AbstractSmtpEventSupportTest{ protected function _getTransport($buf, $dispatcher = null) { if (!$dispatcher) { $dispatcher = $this->_createEventDispatcher(); } return new Swift_Transport_EsmtpTransport($buf, array(), $dispatcher); } public function testHostCanBeSetAndFetched() { $buf = $this->_getBuffer(); $smtp = $this->_getTransport($buf); $smtp->setHost('foo'); $this->assertEquals('foo', $smtp->getHost(), '%s: Host should be returned'); } public function testPortCanBeSetAndFetched() { $buf = $this->_getBuffer(); $smtp = $this->_getTransport($buf); $smtp->setPort(25); $this->assertEquals(25, $smtp->getPort(), '%s: Port should be returned'); } public function testTimeoutCanBeSetAndFetched() { $buf = $this->_getBuffer(); $buf->shouldReceive('setParam') ->once() ->with('timeout', 10); $smtp = $this->_getTransport($buf); $smtp->setTimeout(10); $this->assertEquals(10, $smtp->getTimeout(), '%s: Timeout should be returned'); } public function testEncryptionCanBeSetAndFetched() { $buf = $this->_getBuffer(); $smtp = $this->_getTransport($buf); $smtp->setEncryption('tls'); $this->assertEquals('tls', $smtp->getEncryption(), '%s: Crypto should be returned'); } public function testStartSendsHeloToInitiate() { //Overridden for EHLO instead } public function testStartSendsEhloToInitiate() { /* -- RFC 2821, 3.2. 3.2 Client Initiation Once the server has sent the welcoming message and the client has received it, the client normally sends the EHLO command to the server, indicating the client's identity. In addition to opening the session, use of EHLO indicates that the client is able to process service extensions and requests that the server provide a list of the extensions it supports. Older SMTP systems which are unable to support service extensions and contemporary clients which do not require service extensions in the mail session being initiated, MAY use HELO instead of EHLO. Servers MUST NOT return the extended EHLO-style response to a HELO command. For a particular connection attempt, if the server returns a "command not recognized" response to EHLO, the client SHOULD be able to fall back and send HELO. In the EHLO command the host sending the command identifies itself; the command may be interpreted as saying "Hello, I am <domain>" (and, in the case of EHLO, "and I support service extension requests"). -- RFC 2281, 4.1.1.1. ehlo = "EHLO" SP Domain CRLF helo = "HELO" SP Domain CRLF -- RFC 2821, 4.3.2. EHLO or HELO S: 250 E: 504, 550 */ $buf = $this->_getBuffer(); $smtp = $this->_getTransport($buf); $buf->shouldReceive('initialize') ->once(); $buf->shouldReceive('readLine') ->once() ->with(0) ->andReturn("220 some.server.tld bleh\r\n"); $buf->shouldReceive('write') ->once() ->with('~^EHLO .+?\r\n$~D') ->andReturn(1); $buf->shouldReceive('readLine') ->once() ->with(1) ->andReturn('250 ServerName'."\r\n"); $this->_finishBuffer($buf); try { $smtp->start(); } catch (Exception $e) { $this->fail('Starting Esmtp should send EHLO and accept 250 response'); } } public function testHeloIsUsedAsFallback() { /* -- RFC 2821, 4.1.4. If the EHLO command is not acceptable to the SMTP server, 501, 500, or 502 failure replies MUST be returned as appropriate. The SMTP server MUST stay in the same state after transmitting these replies that it was in before the EHLO was received. */ $buf = $this->_getBuffer(); $smtp = $this->_getTransport($buf); $buf->shouldReceive('initialize') ->once(); $buf->shouldReceive('readLine') ->once() ->with(0) ->andReturn("220 some.server.tld bleh\r\n"); $buf->shouldReceive('write') ->once() ->with('~^EHLO .+?\r\n$~D') ->andReturn(1); $buf->shouldReceive('readLine') ->once() ->with(1) ->andReturn('501 WTF'."\r\n"); $buf->shouldReceive('write') ->once() ->with('~^HELO .+?\r\n$~D') ->andReturn(2); $buf->shouldReceive('readLine') ->once() ->with(2) ->andReturn('250 HELO'."\r\n"); $this->_finishBuffer($buf); try { $smtp->start(); } catch (Exception $e) { $this->fail( 'Starting Esmtp should fallback to HELO if needed and accept 250 response' ); } } public function testInvalidHeloResponseCausesException() { //Overridden to first try EHLO $buf = $this->_getBuffer(); $smtp = $this->_getTransport($buf); $buf->shouldReceive('initialize') ->once(); $buf->shouldReceive('readLine') ->once() ->with(0) ->andReturn("220 some.server.tld bleh\r\n"); $buf->shouldReceive('write') ->once() ->with('~^EHLO .+?\r\n$~D') ->andReturn(1); $buf->shouldReceive('readLine') ->once() ->with(1) ->andReturn('501 WTF'."\r\n"); $buf->shouldReceive('write') ->once() ->with('~^HELO .+?\r\n$~D') ->andReturn(2); $buf->shouldReceive('readLine') ->once() ->with(2) ->andReturn('504 WTF'."\r\n"); $this->_finishBuffer($buf); try { $this->assertFalse($smtp->isStarted(), '%s: SMTP should begin non-started'); $smtp->start(); $this->fail('Non 250 HELO response should raise Exception'); } catch (Exception $e) { $this->assertFalse($smtp->isStarted(), '%s: SMTP start() should have failed'); } } public function testDomainNameIsPlacedInEhlo() { /* -- RFC 2821, 4.1.4. The SMTP client MUST, if possible, ensure that the domain parameter to the EHLO command is a valid principal host name (not a CNAME or MX name) for its host. If this is not possible (e.g., when the client's address is dynamically assigned and the client does not have an obvious name), an address literal SHOULD be substituted for the domain name and supplemental information provided that will assist in identifying the client. */ $buf = $this->_getBuffer(); $smtp = $this->_getTransport($buf); $buf->shouldReceive('initialize') ->once(); $buf->shouldReceive('readLine') ->once() ->with(0) ->andReturn("220 some.server.tld bleh\r\n"); $buf->shouldReceive('write') ->once() ->with("EHLO mydomain.com\r\n") ->andReturn(1); $buf->shouldReceive('readLine') ->once() ->with(1) ->andReturn('250 ServerName'."\r\n"); $this->_finishBuffer($buf); $smtp->setLocalDomain('mydomain.com'); $smtp->start(); } public function testDomainNameIsPlacedInHelo() { //Overridden to include ESMTP /* -- RFC 2821, 4.1.4. The SMTP client MUST, if possible, ensure that the domain parameter to the EHLO command is a valid principal host name (not a CNAME or MX name) for its host. If this is not possible (e.g., when the client's address is dynamically assigned and the client does not have an obvious name), an address literal SHOULD be substituted for the domain name and supplemental information provided that will assist in identifying the client. */ $buf = $this->_getBuffer(); $smtp = $this->_getTransport($buf); $buf->shouldReceive('initialize') ->once(); $buf->shouldReceive('readLine') ->once() ->with(0) ->andReturn("220 some.server.tld bleh\r\n"); $buf->shouldReceive('write') ->once() ->with('~^EHLO .+?\r\n$~D') ->andReturn(1); $buf->shouldReceive('readLine') ->once() ->with(1) ->andReturn('501 WTF'."\r\n"); $buf->shouldReceive('write') ->once() ->with("HELO mydomain.com\r\n") ->andReturn(2); $buf->shouldReceive('readLine') ->once() ->with(2) ->andReturn('250 ServerName'."\r\n"); $this->_finishBuffer($buf); $smtp->setLocalDomain('mydomain.com'); $smtp->start(); } public function testFluidInterface() { $buf = $this->_getBuffer(); $smtp = $this->_getTransport($buf); $buf->shouldReceive('setParam') ->once() ->with('timeout', 30); $ref = $smtp ->setHost('foo') ->setPort(25) ->setEncryption('tls') ->setTimeout(30) ; $this->assertEquals($ref, $smtp); } }
{ "pile_set_name": "Github" }
/** * editor_plugin_src.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function(tinymce) { var each = tinymce.each; // Checks if the selection/caret is at the start of the specified block element function isAtStart(rng, par) { var doc = par.ownerDocument, rng2 = doc.createRange(), elm; rng2.setStartBefore(par); rng2.setEnd(rng.endContainer, rng.endOffset); elm = doc.createElement('body'); elm.appendChild(rng2.cloneContents()); // Check for text characters of other elements that should be treated as content return elm.innerHTML.replace(/<(br|img|object|embed|input|textarea)[^>]*>/gi, '-').replace(/<[^>]+>/g, '').length == 0; }; function getSpanVal(td, name) { return parseInt(td.getAttribute(name) || 1); } /** * Table Grid class. */ function TableGrid(table, dom, selection) { var grid, startPos, endPos, selectedCell; buildGrid(); selectedCell = dom.getParent(selection.getStart(), 'th,td'); if (selectedCell) { startPos = getPos(selectedCell); endPos = findEndPos(); selectedCell = getCell(startPos.x, startPos.y); } function cloneNode(node, children) { node = node.cloneNode(children); node.removeAttribute('id'); return node; } function buildGrid() { var startY = 0; grid = []; each(['thead', 'tbody', 'tfoot'], function(part) { var rows = dom.select('> ' + part + ' tr', table); each(rows, function(tr, y) { y += startY; each(dom.select('> td, > th', tr), function(td, x) { var x2, y2, rowspan, colspan; // Skip over existing cells produced by rowspan if (grid[y]) { while (grid[y][x]) x++; } // Get col/rowspan from cell rowspan = getSpanVal(td, 'rowspan'); colspan = getSpanVal(td, 'colspan'); // Fill out rowspan/colspan right and down for (y2 = y; y2 < y + rowspan; y2++) { if (!grid[y2]) grid[y2] = []; for (x2 = x; x2 < x + colspan; x2++) { grid[y2][x2] = { part : part, real : y2 == y && x2 == x, elm : td, rowspan : rowspan, colspan : colspan }; } } }); }); startY += rows.length; }); }; function getCell(x, y) { var row; row = grid[y]; if (row) return row[x]; }; function setSpanVal(td, name, val) { if (td) { val = parseInt(val); if (val === 1) td.removeAttribute(name, 1); else td.setAttribute(name, val, 1); } } function isCellSelected(cell) { return cell && (dom.hasClass(cell.elm, 'mceSelected') || cell == selectedCell); }; function getSelectedRows() { var rows = []; each(table.rows, function(row) { each(row.cells, function(cell) { if (dom.hasClass(cell, 'mceSelected') || cell == selectedCell.elm) { rows.push(row); return false; } }); }); return rows; }; function deleteTable() { var rng = dom.createRng(); rng.setStartAfter(table); rng.setEndAfter(table); selection.setRng(rng); dom.remove(table); }; function cloneCell(cell) { var formatNode; // Clone formats tinymce.walk(cell, function(node) { var curNode; if (node.nodeType == 3) { each(dom.getParents(node.parentNode, null, cell).reverse(), function(node) { node = cloneNode(node, false); if (!formatNode) formatNode = curNode = node; else if (curNode) curNode.appendChild(node); curNode = node; }); // Add something to the inner node if (curNode) curNode.innerHTML = tinymce.isIE && !tinymce.isIE11 ? '&nbsp;' : '<br data-mce-bogus="1" />'; return false; } }, 'childNodes'); cell = cloneNode(cell, false); setSpanVal(cell, 'rowSpan', 1); setSpanVal(cell, 'colSpan', 1); if (formatNode) { cell.appendChild(formatNode); } else { if (!tinymce.isIE || tinymce.isIE11) cell.innerHTML = '<br data-mce-bogus="1" />'; } return cell; }; function cleanup() { var rng = dom.createRng(); // Empty rows each(dom.select('tr', table), function(tr) { if (tr.cells.length == 0) dom.remove(tr); }); // Empty table if (dom.select('tr', table).length == 0) { rng.setStartAfter(table); rng.setEndAfter(table); selection.setRng(rng); dom.remove(table); return; } // Empty header/body/footer each(dom.select('thead,tbody,tfoot', table), function(part) { if (part.rows.length == 0) dom.remove(part); }); // Restore selection to start position if it still exists buildGrid(); // Restore the selection to the closest table position row = grid[Math.min(grid.length - 1, startPos.y)]; if (row) { selection.select(row[Math.min(row.length - 1, startPos.x)].elm, true); selection.collapse(true); } }; function fillLeftDown(x, y, rows, cols) { var tr, x2, r, c, cell; tr = grid[y][x].elm.parentNode; for (r = 1; r <= rows; r++) { tr = dom.getNext(tr, 'tr'); if (tr) { // Loop left to find real cell for (x2 = x; x2 >= 0; x2--) { cell = grid[y + r][x2].elm; if (cell.parentNode == tr) { // Append clones after for (c = 1; c <= cols; c++) dom.insertAfter(cloneCell(cell), cell); break; } } if (x2 == -1) { // Insert nodes before first cell for (c = 1; c <= cols; c++) tr.insertBefore(cloneCell(tr.cells[0]), tr.cells[0]); } } } }; function split() { each(grid, function(row, y) { each(row, function(cell, x) { var colSpan, rowSpan, newCell, i; if (isCellSelected(cell)) { cell = cell.elm; colSpan = getSpanVal(cell, 'colspan'); rowSpan = getSpanVal(cell, 'rowspan'); if (colSpan > 1 || rowSpan > 1) { setSpanVal(cell, 'rowSpan', 1); setSpanVal(cell, 'colSpan', 1); // Insert cells right for (i = 0; i < colSpan - 1; i++) dom.insertAfter(cloneCell(cell), cell); fillLeftDown(x, y, rowSpan - 1, colSpan); } } }); }); }; function merge(cell, cols, rows) { var startX, startY, endX, endY, x, y, startCell, endCell, cell, children, count; // Use specified cell and cols/rows if (cell) { pos = getPos(cell); startX = pos.x; startY = pos.y; endX = startX + (cols - 1); endY = startY + (rows - 1); } else { startPos = endPos = null; // Calculate start/end pos by checking for selected cells in grid works better with context menu each(grid, function(row, y) { each(row, function(cell, x) { if (isCellSelected(cell)) { if (!startPos) { startPos = {x: x, y: y}; } endPos = {x: x, y: y}; } }); }); // Use selection startX = startPos.x; startY = startPos.y; endX = endPos.x; endY = endPos.y; } // Find start/end cells startCell = getCell(startX, startY); endCell = getCell(endX, endY); // Check if the cells exists and if they are of the same part for example tbody = tbody if (startCell && endCell && startCell.part == endCell.part) { // Split and rebuild grid split(); buildGrid(); // Set row/col span to start cell startCell = getCell(startX, startY).elm; setSpanVal(startCell, 'colSpan', (endX - startX) + 1); setSpanVal(startCell, 'rowSpan', (endY - startY) + 1); // Remove other cells and add it's contents to the start cell for (y = startY; y <= endY; y++) { for (x = startX; x <= endX; x++) { if (!grid[y] || !grid[y][x]) continue; cell = grid[y][x].elm; if (cell != startCell) { // Move children to startCell children = tinymce.grep(cell.childNodes); each(children, function(node) { startCell.appendChild(node); }); // Remove bogus nodes if there is children in the target cell if (children.length) { children = tinymce.grep(startCell.childNodes); count = 0; each(children, function(node) { if (node.nodeName == 'BR' && dom.getAttrib(node, 'data-mce-bogus') && count++ < children.length - 1) startCell.removeChild(node); }); } // Remove cell dom.remove(cell); } } } // Remove empty rows etc and restore caret location cleanup(); } }; function insertRow(before) { var posY, cell, lastCell, x, rowElm, newRow, newCell, otherCell, rowSpan; // Find first/last row each(grid, function(row, y) { each(row, function(cell, x) { if (isCellSelected(cell)) { cell = cell.elm; rowElm = cell.parentNode; newRow = cloneNode(rowElm, false); posY = y; if (before) return false; } }); if (before) return !posY; }); for (x = 0; x < grid[0].length; x++) { // Cell not found could be because of an invalid table structure if (!grid[posY][x]) continue; cell = grid[posY][x].elm; if (cell != lastCell) { if (!before) { rowSpan = getSpanVal(cell, 'rowspan'); if (rowSpan > 1) { setSpanVal(cell, 'rowSpan', rowSpan + 1); continue; } } else { // Check if cell above can be expanded if (posY > 0 && grid[posY - 1][x]) { otherCell = grid[posY - 1][x].elm; rowSpan = getSpanVal(otherCell, 'rowSpan'); if (rowSpan > 1) { setSpanVal(otherCell, 'rowSpan', rowSpan + 1); continue; } } } // Insert new cell into new row newCell = cloneCell(cell); setSpanVal(newCell, 'colSpan', cell.colSpan); newRow.appendChild(newCell); lastCell = cell; } } if (newRow.hasChildNodes()) { if (!before) dom.insertAfter(newRow, rowElm); else rowElm.parentNode.insertBefore(newRow, rowElm); } }; function insertCol(before) { var posX, lastCell; // Find first/last column each(grid, function(row, y) { each(row, function(cell, x) { if (isCellSelected(cell)) { posX = x; if (before) return false; } }); if (before) return !posX; }); each(grid, function(row, y) { var cell, rowSpan, colSpan; if (!row[posX]) return; cell = row[posX].elm; if (cell != lastCell) { colSpan = getSpanVal(cell, 'colspan'); rowSpan = getSpanVal(cell, 'rowspan'); if (colSpan == 1) { if (!before) { dom.insertAfter(cloneCell(cell), cell); fillLeftDown(posX, y, rowSpan - 1, colSpan); } else { cell.parentNode.insertBefore(cloneCell(cell), cell); fillLeftDown(posX, y, rowSpan - 1, colSpan); } } else setSpanVal(cell, 'colSpan', cell.colSpan + 1); lastCell = cell; } }); }; function deleteCols() { var cols = []; // Get selected column indexes each(grid, function(row, y) { each(row, function(cell, x) { if (isCellSelected(cell) && tinymce.inArray(cols, x) === -1) { each(grid, function(row) { var cell = row[x].elm, colSpan; colSpan = getSpanVal(cell, 'colSpan'); if (colSpan > 1) setSpanVal(cell, 'colSpan', colSpan - 1); else dom.remove(cell); }); cols.push(x); } }); }); cleanup(); }; function deleteRows() { var rows; function deleteRow(tr) { var nextTr, pos, lastCell; nextTr = dom.getNext(tr, 'tr'); // Move down row spanned cells each(tr.cells, function(cell) { var rowSpan = getSpanVal(cell, 'rowSpan'); if (rowSpan > 1) { setSpanVal(cell, 'rowSpan', rowSpan - 1); pos = getPos(cell); fillLeftDown(pos.x, pos.y, 1, 1); } }); // Delete cells pos = getPos(tr.cells[0]); each(grid[pos.y], function(cell) { var rowSpan; cell = cell.elm; if (cell != lastCell) { rowSpan = getSpanVal(cell, 'rowSpan'); if (rowSpan <= 1) dom.remove(cell); else setSpanVal(cell, 'rowSpan', rowSpan - 1); lastCell = cell; } }); }; // Get selected rows and move selection out of scope rows = getSelectedRows(); // Delete all selected rows each(rows.reverse(), function(tr) { deleteRow(tr); }); cleanup(); }; function cutRows() { var rows = getSelectedRows(); dom.remove(rows); cleanup(); return rows; }; function copyRows() { var rows = getSelectedRows(); each(rows, function(row, i) { rows[i] = cloneNode(row, true); }); return rows; }; function pasteRows(rows, before) { // If we don't have any rows in the clipboard, return immediately if(!rows) return; var selectedRows = getSelectedRows(), targetRow = selectedRows[before ? 0 : selectedRows.length - 1], targetCellCount = targetRow.cells.length; // Calc target cell count each(grid, function(row) { var match; targetCellCount = 0; each(row, function(cell, x) { if (cell.real) targetCellCount += cell.colspan; if (cell.elm.parentNode == targetRow) match = 1; }); if (match) return false; }); if (!before) rows.reverse(); each(rows, function(row) { var cellCount = row.cells.length, cell; // Remove col/rowspans for (i = 0; i < cellCount; i++) { cell = row.cells[i]; setSpanVal(cell, 'colSpan', 1); setSpanVal(cell, 'rowSpan', 1); } // Needs more cells for (i = cellCount; i < targetCellCount; i++) row.appendChild(cloneCell(row.cells[cellCount - 1])); // Needs less cells for (i = targetCellCount; i < cellCount; i++) dom.remove(row.cells[i]); // Add before/after if (before) targetRow.parentNode.insertBefore(row, targetRow); else dom.insertAfter(row, targetRow); }); // Remove current selection dom.removeClass(dom.select('td.mceSelected,th.mceSelected'), 'mceSelected'); }; function getPos(target) { var pos; each(grid, function(row, y) { each(row, function(cell, x) { if (cell.elm == target) { pos = {x : x, y : y}; return false; } }); return !pos; }); return pos; }; function setStartCell(cell) { startPos = getPos(cell); }; function findEndPos() { var pos, maxX, maxY; maxX = maxY = 0; each(grid, function(row, y) { each(row, function(cell, x) { var colSpan, rowSpan; if (isCellSelected(cell)) { cell = grid[y][x]; if (x > maxX) maxX = x; if (y > maxY) maxY = y; if (cell.real) { colSpan = cell.colspan - 1; rowSpan = cell.rowspan - 1; if (colSpan) { if (x + colSpan > maxX) maxX = x + colSpan; } if (rowSpan) { if (y + rowSpan > maxY) maxY = y + rowSpan; } } } }); }); return {x : maxX, y : maxY}; }; function setEndCell(cell) { var startX, startY, endX, endY, maxX, maxY, colSpan, rowSpan; endPos = getPos(cell); if (startPos && endPos) { // Get start/end positions startX = Math.min(startPos.x, endPos.x); startY = Math.min(startPos.y, endPos.y); endX = Math.max(startPos.x, endPos.x); endY = Math.max(startPos.y, endPos.y); // Expand end positon to include spans maxX = endX; maxY = endY; // Expand startX for (y = startY; y <= maxY; y++) { cell = grid[y][startX]; if (!cell.real) { if (startX - (cell.colspan - 1) < startX) startX -= cell.colspan - 1; } } // Expand startY for (x = startX; x <= maxX; x++) { cell = grid[startY][x]; if (!cell.real) { if (startY - (cell.rowspan - 1) < startY) startY -= cell.rowspan - 1; } } // Find max X, Y for (y = startY; y <= endY; y++) { for (x = startX; x <= endX; x++) { cell = grid[y][x]; if (cell.real) { colSpan = cell.colspan - 1; rowSpan = cell.rowspan - 1; if (colSpan) { if (x + colSpan > maxX) maxX = x + colSpan; } if (rowSpan) { if (y + rowSpan > maxY) maxY = y + rowSpan; } } } } // Remove current selection dom.removeClass(dom.select('td.mceSelected,th.mceSelected'), 'mceSelected'); // Add new selection for (y = startY; y <= maxY; y++) { for (x = startX; x <= maxX; x++) { if (grid[y][x]) dom.addClass(grid[y][x].elm, 'mceSelected'); } } } }; // Expose to public tinymce.extend(this, { deleteTable : deleteTable, split : split, merge : merge, insertRow : insertRow, insertCol : insertCol, deleteCols : deleteCols, deleteRows : deleteRows, cutRows : cutRows, copyRows : copyRows, pasteRows : pasteRows, getPos : getPos, setStartCell : setStartCell, setEndCell : setEndCell }); }; tinymce.create('tinymce.plugins.TablePlugin', { init : function(ed, url) { var winMan, clipboardRows, hasCellSelection = true; // Might be selected cells on reload function createTableGrid(node) { var selection = ed.selection, tblElm = ed.dom.getParent(node || selection.getNode(), 'table'); if (tblElm) return new TableGrid(tblElm, ed.dom, selection); }; function cleanup() { // Restore selection possibilities ed.getBody().style.webkitUserSelect = ''; if (hasCellSelection) { ed.dom.removeClass(ed.dom.select('td.mceSelected,th.mceSelected'), 'mceSelected'); hasCellSelection = false; } }; // Register buttons each([ ['table', 'table.desc', 'mceInsertTable', true], ['delete_table', 'table.del', 'mceTableDelete'], ['delete_col', 'table.delete_col_desc', 'mceTableDeleteCol'], ['delete_row', 'table.delete_row_desc', 'mceTableDeleteRow'], ['col_after', 'table.col_after_desc', 'mceTableInsertColAfter'], ['col_before', 'table.col_before_desc', 'mceTableInsertColBefore'], ['row_after', 'table.row_after_desc', 'mceTableInsertRowAfter'], ['row_before', 'table.row_before_desc', 'mceTableInsertRowBefore'], ['row_props', 'table.row_desc', 'mceTableRowProps', true], ['cell_props', 'table.cell_desc', 'mceTableCellProps', true], ['split_cells', 'table.split_cells_desc', 'mceTableSplitCells', true], ['merge_cells', 'table.merge_cells_desc', 'mceTableMergeCells', true] ], function(c) { ed.addButton(c[0], {title : c[1], cmd : c[2], ui : c[3]}); }); // Select whole table is a table border is clicked if (!tinymce.isIE) { ed.onClick.add(function(ed, e) { e = e.target; if (e.nodeName === 'TABLE') { ed.selection.select(e); ed.nodeChanged(); } }); } ed.onPreProcess.add(function(ed, args) { var nodes, i, node, dom = ed.dom, value; nodes = dom.select('table', args.node); i = nodes.length; while (i--) { node = nodes[i]; dom.setAttrib(node, 'data-mce-style', ''); if ((value = dom.getAttrib(node, 'width'))) { dom.setStyle(node, 'width', value); dom.setAttrib(node, 'width', ''); } if ((value = dom.getAttrib(node, 'height'))) { dom.setStyle(node, 'height', value); dom.setAttrib(node, 'height', ''); } } }); // Handle node change updates ed.onNodeChange.add(function(ed, cm, n) { var p; n = ed.selection.getStart(); p = ed.dom.getParent(n, 'td,th,caption'); cm.setActive('table', n.nodeName === 'TABLE' || !!p); // Disable table tools if we are in caption if (p && p.nodeName === 'CAPTION') p = 0; cm.setDisabled('delete_table', !p); cm.setDisabled('delete_col', !p); cm.setDisabled('delete_table', !p); cm.setDisabled('delete_row', !p); cm.setDisabled('col_after', !p); cm.setDisabled('col_before', !p); cm.setDisabled('row_after', !p); cm.setDisabled('row_before', !p); cm.setDisabled('row_props', !p); cm.setDisabled('cell_props', !p); cm.setDisabled('split_cells', !p); cm.setDisabled('merge_cells', !p); }); ed.onInit.add(function(ed) { var startTable, startCell, dom = ed.dom, tableGrid; winMan = ed.windowManager; // Add cell selection logic ed.onMouseDown.add(function(ed, e) { if (e.button != 2) { cleanup(); startCell = dom.getParent(e.target, 'td,th'); startTable = dom.getParent(startCell, 'table'); } }); dom.bind(ed.getDoc(), 'mouseover', function(e) { var sel, table, target = e.target; if (startCell && (tableGrid || target != startCell) && (target.nodeName == 'TD' || target.nodeName == 'TH')) { table = dom.getParent(target, 'table'); if (table == startTable) { if (!tableGrid) { tableGrid = createTableGrid(table); tableGrid.setStartCell(startCell); ed.getBody().style.webkitUserSelect = 'none'; } tableGrid.setEndCell(target); hasCellSelection = true; } // Remove current selection sel = ed.selection.getSel(); try { if (sel.removeAllRanges) sel.removeAllRanges(); else sel.empty(); } catch (ex) { // IE9 might throw errors here } e.preventDefault(); } }); ed.onMouseUp.add(function(ed, e) { var rng, sel = ed.selection, selectedCells, nativeSel = sel.getSel(), walker, node, lastNode, endNode; // Move selection to startCell if (startCell) { if (tableGrid) ed.getBody().style.webkitUserSelect = ''; function setPoint(node, start) { var walker = new tinymce.dom.TreeWalker(node, node); do { // Text node if (node.nodeType == 3 && tinymce.trim(node.nodeValue).length != 0) { if (start) rng.setStart(node, 0); else rng.setEnd(node, node.nodeValue.length); return; } // BR element if (node.nodeName == 'BR') { if (start) rng.setStartBefore(node); else rng.setEndBefore(node); return; } } while (node = (start ? walker.next() : walker.prev())); } // Try to expand text selection as much as we can only Gecko supports cell selection selectedCells = dom.select('td.mceSelected,th.mceSelected'); if (selectedCells.length > 0) { rng = dom.createRng(); node = selectedCells[0]; endNode = selectedCells[selectedCells.length - 1]; rng.setStartBefore(node); rng.setEndAfter(node); setPoint(node, 1); walker = new tinymce.dom.TreeWalker(node, dom.getParent(selectedCells[0], 'table')); do { if (node.nodeName == 'TD' || node.nodeName == 'TH') { if (!dom.hasClass(node, 'mceSelected')) break; lastNode = node; } } while (node = walker.next()); setPoint(lastNode); sel.setRng(rng); } ed.nodeChanged(); startCell = tableGrid = startTable = null; } }); ed.onKeyUp.add(function(ed, e) { cleanup(); }); ed.onKeyDown.add(function (ed, e) { fixTableCellSelection(ed); }); ed.onMouseDown.add(function (ed, e) { if (e.button != 2) { fixTableCellSelection(ed); } }); function tableCellSelected(ed, rng, n, currentCell) { // The decision of when a table cell is selected is somewhat involved. The fact that this code is // required is actually a pointer to the root cause of this bug. A cell is selected when the start // and end offsets are 0, the start container is a text, and the selection node is either a TR (most cases) // or the parent of the table (in the case of the selection containing the last cell of a table). var TEXT_NODE = 3, table = ed.dom.getParent(rng.startContainer, 'TABLE'), tableParent, allOfCellSelected, tableCellSelection; if (table) tableParent = table.parentNode; allOfCellSelected =rng.startContainer.nodeType == TEXT_NODE && rng.startOffset == 0 && rng.endOffset == 0 && currentCell && (n.nodeName=="TR" || n==tableParent); tableCellSelection = (n.nodeName=="TD"||n.nodeName=="TH")&& !currentCell; return allOfCellSelected || tableCellSelection; // return false; } // this nasty hack is here to work around some WebKit selection bugs. function fixTableCellSelection(ed) { if (!tinymce.isWebKit) return; var rng = ed.selection.getRng(); var n = ed.selection.getNode(); var currentCell = ed.dom.getParent(rng.startContainer, 'TD,TH'); if (!tableCellSelected(ed, rng, n, currentCell)) return; if (!currentCell) { currentCell=n; } // Get the very last node inside the table cell var end = currentCell.lastChild; while (end.lastChild) end = end.lastChild; // Select the entire table cell. Nothing outside of the table cell should be selected. rng.setEnd(end, end.nodeValue.length); ed.selection.setRng(rng); } ed.plugins.table.fixTableCellSelection=fixTableCellSelection; // Add context menu if (ed && ed.plugins.contextmenu) { ed.plugins.contextmenu.onContextMenu.add(function(th, m, e) { var sm, se = ed.selection, el = se.getNode() || ed.getBody(); if (ed.dom.getParent(e, 'td') || ed.dom.getParent(e, 'th') || ed.dom.select('td.mceSelected,th.mceSelected').length) { m.removeAll(); if (el.nodeName == 'A' && !ed.dom.getAttrib(el, 'name')) { m.add({title : 'advanced.link_desc', icon : 'link', cmd : ed.plugins.advlink ? 'mceAdvLink' : 'mceLink', ui : true}); m.add({title : 'advanced.unlink_desc', icon : 'unlink', cmd : 'UnLink'}); m.addSeparator(); } if (el.nodeName == 'IMG' && el.className.indexOf('mceItem') == -1) { m.add({title : 'advanced.image_desc', icon : 'image', cmd : ed.plugins.advimage ? 'mceAdvImage' : 'mceImage', ui : true}); m.addSeparator(); } m.add({title : 'table.desc', icon : 'table', cmd : 'mceInsertTable', value : {action : 'insert'}}); m.add({title : 'table.props_desc', icon : 'table_props', cmd : 'mceInsertTable'}); m.add({title : 'table.del', icon : 'delete_table', cmd : 'mceTableDelete'}); m.addSeparator(); // Cell menu sm = m.addMenu({title : 'table.cell'}); sm.add({title : 'table.cell_desc', icon : 'cell_props', cmd : 'mceTableCellProps'}); sm.add({title : 'table.split_cells_desc', icon : 'split_cells', cmd : 'mceTableSplitCells'}); sm.add({title : 'table.merge_cells_desc', icon : 'merge_cells', cmd : 'mceTableMergeCells'}); // Row menu sm = m.addMenu({title : 'table.row'}); sm.add({title : 'table.row_desc', icon : 'row_props', cmd : 'mceTableRowProps'}); sm.add({title : 'table.row_before_desc', icon : 'row_before', cmd : 'mceTableInsertRowBefore'}); sm.add({title : 'table.row_after_desc', icon : 'row_after', cmd : 'mceTableInsertRowAfter'}); sm.add({title : 'table.delete_row_desc', icon : 'delete_row', cmd : 'mceTableDeleteRow'}); sm.addSeparator(); sm.add({title : 'table.cut_row_desc', icon : 'cut', cmd : 'mceTableCutRow'}); sm.add({title : 'table.copy_row_desc', icon : 'copy', cmd : 'mceTableCopyRow'}); sm.add({title : 'table.paste_row_before_desc', icon : 'paste', cmd : 'mceTablePasteRowBefore'}).setDisabled(!clipboardRows); sm.add({title : 'table.paste_row_after_desc', icon : 'paste', cmd : 'mceTablePasteRowAfter'}).setDisabled(!clipboardRows); // Column menu sm = m.addMenu({title : 'table.col'}); sm.add({title : 'table.col_before_desc', icon : 'col_before', cmd : 'mceTableInsertColBefore'}); sm.add({title : 'table.col_after_desc', icon : 'col_after', cmd : 'mceTableInsertColAfter'}); sm.add({title : 'table.delete_col_desc', icon : 'delete_col', cmd : 'mceTableDeleteCol'}); } else m.add({title : 'table.desc', icon : 'table', cmd : 'mceInsertTable'}); }); } // Fix to allow navigating up and down in a table in WebKit browsers. if (tinymce.isWebKit) { function moveSelection(ed, e) { var VK = tinymce.VK; var key = e.keyCode; function handle(upBool, sourceNode, event) { var siblingDirection = upBool ? 'previousSibling' : 'nextSibling'; var currentRow = ed.dom.getParent(sourceNode, 'tr'); var siblingRow = currentRow[siblingDirection]; if (siblingRow) { moveCursorToRow(ed, sourceNode, siblingRow, upBool); tinymce.dom.Event.cancel(event); return true; } else { var tableNode = ed.dom.getParent(currentRow, 'table'); var middleNode = currentRow.parentNode; var parentNodeName = middleNode.nodeName.toLowerCase(); if (parentNodeName === 'tbody' || parentNodeName === (upBool ? 'tfoot' : 'thead')) { var targetParent = getTargetParent(upBool, tableNode, middleNode, 'tbody'); if (targetParent !== null) { return moveToRowInTarget(upBool, targetParent, sourceNode, event); } } return escapeTable(upBool, currentRow, siblingDirection, tableNode, event); } } function getTargetParent(upBool, topNode, secondNode, nodeName) { var tbodies = ed.dom.select('>' + nodeName, topNode); var position = tbodies.indexOf(secondNode); if (upBool && position === 0 || !upBool && position === tbodies.length - 1) { return getFirstHeadOrFoot(upBool, topNode); } else if (position === -1) { var topOrBottom = secondNode.tagName.toLowerCase() === 'thead' ? 0 : tbodies.length - 1; return tbodies[topOrBottom]; } else { return tbodies[position + (upBool ? -1 : 1)]; } } function getFirstHeadOrFoot(upBool, parent) { var tagName = upBool ? 'thead' : 'tfoot'; var headOrFoot = ed.dom.select('>' + tagName, parent); return headOrFoot.length !== 0 ? headOrFoot[0] : null; } function moveToRowInTarget(upBool, targetParent, sourceNode, event) { var targetRow = getChildForDirection(targetParent, upBool); targetRow && moveCursorToRow(ed, sourceNode, targetRow, upBool); tinymce.dom.Event.cancel(event); return true; } function escapeTable(upBool, currentRow, siblingDirection, table, event) { var tableSibling = table[siblingDirection]; if (tableSibling) { moveCursorToStartOfElement(tableSibling); return true; } else { var parentCell = ed.dom.getParent(table, 'td,th'); if (parentCell) { return handle(upBool, parentCell, event); } else { var backUpSibling = getChildForDirection(currentRow, !upBool); moveCursorToStartOfElement(backUpSibling); return tinymce.dom.Event.cancel(event); } } } function getChildForDirection(parent, up) { var child = parent && parent[up ? 'lastChild' : 'firstChild']; // BR is not a valid table child to return in this case we return the table cell return child && child.nodeName === 'BR' ? ed.dom.getParent(child, 'td,th') : child; } function moveCursorToStartOfElement(n) { ed.selection.setCursorLocation(n, 0); } function isVerticalMovement() { return key == VK.UP || key == VK.DOWN; } function isInTable(ed) { var node = ed.selection.getNode(); var currentRow = ed.dom.getParent(node, 'tr'); return currentRow !== null; } function columnIndex(column) { var colIndex = 0; var c = column; while (c.previousSibling) { c = c.previousSibling; colIndex = colIndex + getSpanVal(c, "colspan"); } return colIndex; } function findColumn(rowElement, columnIndex) { var c = 0; var r = 0; each(rowElement.children, function(cell, i) { c = c + getSpanVal(cell, "colspan"); r = i; if (c > columnIndex) return false; }); return r; } function moveCursorToRow(ed, node, row, upBool) { var srcColumnIndex = columnIndex(ed.dom.getParent(node, 'td,th')); var tgtColumnIndex = findColumn(row, srcColumnIndex); var tgtNode = row.childNodes[tgtColumnIndex]; var rowCellTarget = getChildForDirection(tgtNode, upBool); moveCursorToStartOfElement(rowCellTarget || tgtNode); } function shouldFixCaret(preBrowserNode) { var newNode = ed.selection.getNode(); var newParent = ed.dom.getParent(newNode, 'td,th'); var oldParent = ed.dom.getParent(preBrowserNode, 'td,th'); return newParent && newParent !== oldParent && checkSameParentTable(newParent, oldParent) } function checkSameParentTable(nodeOne, NodeTwo) { return ed.dom.getParent(nodeOne, 'TABLE') === ed.dom.getParent(NodeTwo, 'TABLE'); } if (isVerticalMovement() && isInTable(ed)) { var preBrowserNode = ed.selection.getNode(); setTimeout(function() { if (shouldFixCaret(preBrowserNode)) { handle(!e.shiftKey && key === VK.UP, preBrowserNode, e); } }, 0); } } ed.onKeyDown.add(moveSelection); } // Fixes an issue on Gecko where it's impossible to place the caret behind a table // This fix will force a paragraph element after the table but only when the forced_root_block setting is enabled function fixTableCaretPos() { var last; // Skip empty text nodes form the end for (last = ed.getBody().lastChild; last && last.nodeType == 3 && !last.nodeValue.length; last = last.previousSibling) ; if (last && last.nodeName == 'TABLE') { if (ed.settings.forced_root_block) ed.dom.add(ed.getBody(), ed.settings.forced_root_block, null, tinymce.isIE && !tinymce.isIE11 ? '&nbsp;' : '<br data-mce-bogus="1" />'); else ed.dom.add(ed.getBody(), 'br', {'data-mce-bogus': '1'}); } }; // Fixes an bug where it's impossible to place the caret before a table in Gecko // this fix solves it by detecting when the caret is at the beginning of such a table // and then manually moves the caret infront of the table if (tinymce.isGecko) { ed.onKeyDown.add(function(ed, e) { var rng, table, dom = ed.dom; // On gecko it's not possible to place the caret before a table if (e.keyCode == 37 || e.keyCode == 38) { rng = ed.selection.getRng(); table = dom.getParent(rng.startContainer, 'table'); if (table && ed.getBody().firstChild == table) { if (isAtStart(rng, table)) { rng = dom.createRng(); rng.setStartBefore(table); rng.setEndBefore(table); ed.selection.setRng(rng); e.preventDefault(); } } } }); } ed.onKeyUp.add(fixTableCaretPos); ed.onSetContent.add(fixTableCaretPos); ed.onVisualAid.add(fixTableCaretPos); ed.onPreProcess.add(function(ed, o) { var last = o.node.lastChild; if (last && (last.nodeName == "BR" || (last.childNodes.length == 1 && (last.firstChild.nodeName == 'BR' || last.firstChild.nodeValue == '\u00a0'))) && last.previousSibling && last.previousSibling.nodeName == "TABLE") { ed.dom.remove(last); } }); /** * Fixes bug in Gecko where shift-enter in table cell does not place caret on new line * * Removed: Since the new enter logic seems to fix this one. */ /* if (tinymce.isGecko) { ed.onKeyDown.add(function(ed, e) { if (e.keyCode === tinymce.VK.ENTER && e.shiftKey) { var node = ed.selection.getRng().startContainer; var tableCell = dom.getParent(node, 'td,th'); if (tableCell) { var zeroSizedNbsp = ed.getDoc().createTextNode("\uFEFF"); dom.insertAfter(zeroSizedNbsp, node); } } }); } */ fixTableCaretPos(); ed.startContent = ed.getContent({format : 'raw'}); }); // Register action commands each({ mceTableSplitCells : function(grid) { grid.split(); }, mceTableMergeCells : function(grid) { var rowSpan, colSpan, cell; cell = ed.dom.getParent(ed.selection.getNode(), 'th,td'); if (cell) { rowSpan = cell.rowSpan; colSpan = cell.colSpan; } if (!ed.dom.select('td.mceSelected,th.mceSelected').length) { winMan.open({ url : url + '/merge_cells.htm', width : 240 + parseInt(ed.getLang('table.merge_cells_delta_width', 0)), height : 110 + parseInt(ed.getLang('table.merge_cells_delta_height', 0)), inline : 1 }, { rows : rowSpan, cols : colSpan, onaction : function(data) { grid.merge(cell, data.cols, data.rows); }, plugin_url : url }); } else grid.merge(); }, mceTableInsertRowBefore : function(grid) { grid.insertRow(true); }, mceTableInsertRowAfter : function(grid) { grid.insertRow(); }, mceTableInsertColBefore : function(grid) { grid.insertCol(true); }, mceTableInsertColAfter : function(grid) { grid.insertCol(); }, mceTableDeleteCol : function(grid) { grid.deleteCols(); }, mceTableDeleteRow : function(grid) { grid.deleteRows(); }, mceTableCutRow : function(grid) { clipboardRows = grid.cutRows(); }, mceTableCopyRow : function(grid) { clipboardRows = grid.copyRows(); }, mceTablePasteRowBefore : function(grid) { grid.pasteRows(clipboardRows, true); }, mceTablePasteRowAfter : function(grid) { grid.pasteRows(clipboardRows); }, mceTableDelete : function(grid) { grid.deleteTable(); } }, function(func, name) { ed.addCommand(name, function() { var grid = createTableGrid(); if (grid) { func(grid); ed.execCommand('mceRepaint'); cleanup(); } }); }); // Register dialog commands each({ mceInsertTable : function(val) { winMan.open({ url : url + '/table.htm', width : 400 + parseInt(ed.getLang('table.table_delta_width', 0)), height : 320 + parseInt(ed.getLang('table.table_delta_height', 0)), inline : 1 }, { plugin_url : url, action : val ? val.action : 0 }); }, mceTableRowProps : function() { winMan.open({ url : url + '/row.htm', width : 400 + parseInt(ed.getLang('table.rowprops_delta_width', 0)), height : 295 + parseInt(ed.getLang('table.rowprops_delta_height', 0)), inline : 1 }, { plugin_url : url }); }, mceTableCellProps : function() { winMan.open({ url : url + '/cell.htm', width : 400 + parseInt(ed.getLang('table.cellprops_delta_width', 0)), height : 295 + parseInt(ed.getLang('table.cellprops_delta_height', 0)), inline : 1 }, { plugin_url : url }); } }, function(func, name) { ed.addCommand(name, function(ui, val) { func(val); }); }); } }); // Register plugin tinymce.PluginManager.add('table', tinymce.plugins.TablePlugin); })(tinymce);
{ "pile_set_name": "Github" }
/******************************************************************************* * AMetal * ---------------------------- * innovating embedded platform * * Copyright (c) 2001-2018 Guangzhou ZHIYUAN Electronics Co., Ltd. * All rights reserved. * * Contact information: * web site: http://www.zlg.cn/ *******************************************************************************/ /** * \file * \brief TIM1 定时器 PWM 例程,通过标准接口实现 * * - 实验现象: * 1. PIOA_3(TIM3_CH1)输出 2KHz 的 PWM,占空比为 50%; * * \par 源代码 * \snippet demo_hc32l17x_std_tim3_pwm.c src_hc32l17x_std_tim3_pwm * * \internal * \par Modification history * - 1.00 19-09-23 zp, first implementation * \endinternal */ /** * \addtogroup demo_if_hc32l17x_std_tim3_pwm * \copydoc demo_hc32l17x_std_tim3_pwm.c */ /** [src_hc32l17x_std_tim3_pwm] */ #include "ametal.h" #include "am_vdebug.h" #include "am_hc32_tim_pwm.h" #include "am_hc32l17x_inst_init.h" #include "demo_std_entries.h" #include "demo_aml17x_core_entries.h" /** * \brief 例程入口 */ void demo_hc32l17x_core_std_tim3_pwm_entry (void) { AM_DBG_INFO("demo aml17x_core std tim3 pwm!\r\n"); demo_std_timer_pwm_entry(am_hc32_tim3_pwm_inst_init(), AM_HC32_TIM_PWM_CH1A); } /** [src_hc32l17x_std_tim3_pwm] */ /* end of file */
{ "pile_set_name": "Github" }
package org.hexworks.zircon.examples.fragments import org.hexworks.zircon.api.CP437TilesetResources import org.hexworks.zircon.api.ColorThemes import org.hexworks.zircon.api.Components import org.hexworks.zircon.api.SwingApplications import org.hexworks.zircon.api.application.AppConfig import org.hexworks.zircon.api.data.Size import org.hexworks.zircon.api.extensions.toScreen import org.hexworks.zircon.examples.base.Defaults import org.hexworks.zircon.examples.components.ButtonsExampleJava import org.hexworks.zircon.examples.components.CheckBoxesExampleJava import org.hexworks.zircon.examples.components.ToggleButtonsExampleJava import org.hexworks.zircon.internal.component.renderer.NoOpComponentRenderer import org.hexworks.zircon.internal.fragment.impl.DefaultVerticalTabBar object VerticalTabBarExample { private val tileset = CP437TilesetResources.taffer20x20() private val size = Defaults.GRID_SIZE + Size.create(12, 2) @JvmStatic fun main(args: Array<String>) { val screen = SwingApplications.startTileGrid(AppConfig.newBuilder() .withDefaultTileset(tileset) .withSize(size) .withDebugMode(true) .build()).toScreen() val contentSize = screen.size - Size.create(2, 2) val content = Components.panel() .withSize(contentSize) .withPosition(1, 1) .withComponentRenderer(NoOpComponentRenderer()) .build() content.addFragment(DefaultVerticalTabBar( contentSize = contentSize.withRelativeWidth(-10), barSize = contentSize.withWidth(10), defaultSelected = "Buttons", tabs = mapOf( "Buttons" to ButtonsExampleJava().createExampleContainer(screen, "Buttons"), "CheckBoxes" to CheckBoxesExampleJava().createExampleContainer(screen, "CheckBoxes"), "ToggleBtns" to ToggleButtonsExampleJava().createExampleContainer(screen, "ToggleBtns") ))) screen.addComponent(content) screen.display() screen.theme = ColorThemes.amigaOs() } }
{ "pile_set_name": "Github" }
<?php /* * Copyright 2014 Google Inc. * * 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. */ class Google_Service_Sasportal_SasPortalDeviceConfig extends Google_Collection { protected $collection_key = 'measurementCapabilities'; protected $airInterfaceType = 'Google_Service_Sasportal_SasPortalDeviceAirInterface'; protected $airInterfaceDataType = ''; public $callSign; public $category; protected $installationParamsType = 'Google_Service_Sasportal_SasPortalInstallationParams'; protected $installationParamsDataType = ''; public $isSigned; public $measurementCapabilities; protected $modelType = 'Google_Service_Sasportal_SasPortalDeviceModel'; protected $modelDataType = ''; public $state; public $updateTime; public $userId; /** * @param Google_Service_Sasportal_SasPortalDeviceAirInterface */ public function setAirInterface(Google_Service_Sasportal_SasPortalDeviceAirInterface $airInterface) { $this->airInterface = $airInterface; } /** * @return Google_Service_Sasportal_SasPortalDeviceAirInterface */ public function getAirInterface() { return $this->airInterface; } public function setCallSign($callSign) { $this->callSign = $callSign; } public function getCallSign() { return $this->callSign; } public function setCategory($category) { $this->category = $category; } public function getCategory() { return $this->category; } /** * @param Google_Service_Sasportal_SasPortalInstallationParams */ public function setInstallationParams(Google_Service_Sasportal_SasPortalInstallationParams $installationParams) { $this->installationParams = $installationParams; } /** * @return Google_Service_Sasportal_SasPortalInstallationParams */ public function getInstallationParams() { return $this->installationParams; } public function setIsSigned($isSigned) { $this->isSigned = $isSigned; } public function getIsSigned() { return $this->isSigned; } public function setMeasurementCapabilities($measurementCapabilities) { $this->measurementCapabilities = $measurementCapabilities; } public function getMeasurementCapabilities() { return $this->measurementCapabilities; } /** * @param Google_Service_Sasportal_SasPortalDeviceModel */ public function setModel(Google_Service_Sasportal_SasPortalDeviceModel $model) { $this->model = $model; } /** * @return Google_Service_Sasportal_SasPortalDeviceModel */ public function getModel() { return $this->model; } public function setState($state) { $this->state = $state; } public function getState() { return $this->state; } public function setUpdateTime($updateTime) { $this->updateTime = $updateTime; } public function getUpdateTime() { return $this->updateTime; } public function setUserId($userId) { $this->userId = $userId; } public function getUserId() { return $this->userId; } }
{ "pile_set_name": "Github" }
package com.tencent.mm.sdk.modelmsg; import android.graphics.Bitmap; import android.graphics.Bitmap.CompressFormat; import android.os.Bundle; import com.tencent.mm.sdk.platformtools.v; import java.io.ByteArrayOutputStream; import java.io.File; public class WXImageObject implements WXMediaMessage.b { private static final int CONTENT_LENGTH_LIMIT = 10485760; private static final int PATH_LENGTH_LIMIT = 10240; private static final String TAG = "MicroMsg.SDK.WXImageObject"; public byte[] imageData; public String imagePath; public WXImageObject() {} public WXImageObject(Bitmap paramBitmap) { try { ByteArrayOutputStream localByteArrayOutputStream = new ByteArrayOutputStream(); paramBitmap.compress(Bitmap.CompressFormat.JPEG, 85, localByteArrayOutputStream); imageData = localByteArrayOutputStream.toByteArray(); localByteArrayOutputStream.close(); return; } catch (Exception paramBitmap) {} } public WXImageObject(byte[] paramArrayOfByte) { imageData = paramArrayOfByte; } private int getFileSize(String paramString) { if ((paramString == null) || (paramString.length() == 0)) {} do { return 0; paramString = new File(paramString); } while (!paramString.exists()); return (int)paramString.length(); } public boolean checkArgs() { if (((imageData == null) || (imageData.length == 0)) && ((imagePath == null) || (imagePath.length() == 0))) { v.e("MicroMsg.SDK.WXImageObject", "checkArgs fail, all arguments are null"); return false; } if ((imageData != null) && (imageData.length > 10485760)) { v.e("MicroMsg.SDK.WXImageObject", "checkArgs fail, content is too large"); return false; } if ((imagePath != null) && (imagePath.length() > 10240)) { v.e("MicroMsg.SDK.WXImageObject", "checkArgs fail, path is invalid"); return false; } if ((imagePath != null) && (getFileSize(imagePath) > 10485760)) { v.e("MicroMsg.SDK.WXImageObject", "checkArgs fail, image content is too large"); return false; } return true; } public void serialize(Bundle paramBundle) { paramBundle.putByteArray("_wximageobject_imageData", imageData); paramBundle.putString("_wximageobject_imagePath", imagePath); } public void setImagePath(String paramString) { imagePath = paramString; } public int type() { return 2; } public void unserialize(Bundle paramBundle) { imageData = paramBundle.getByteArray("_wximageobject_imageData"); imagePath = paramBundle.getString("_wximageobject_imagePath"); } } /* Location: * Qualified Name: com.tencent.mm.sdk.modelmsg.WXImageObject * Java Class Version: 6 (50.0) * JD-Core Version: 0.7.1 */
{ "pile_set_name": "Github" }
// // detail/winrt_resolve_op.hpp // ~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef BOOST_ASIO_DETAIL_WINRT_RESOLVE_OP_HPP #define BOOST_ASIO_DETAIL_WINRT_RESOLVE_OP_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #if defined(BOOST_ASIO_WINDOWS_RUNTIME) #include <boost/asio/detail/bind_handler.hpp> #include <boost/asio/detail/fenced_block.hpp> #include <boost/asio/detail/handler_alloc_helpers.hpp> #include <boost/asio/detail/handler_invoke_helpers.hpp> #include <boost/asio/detail/memory.hpp> #include <boost/asio/detail/winrt_async_op.hpp> #include <boost/asio/ip/basic_resolver_results.hpp> #include <boost/asio/error.hpp> #include <boost/asio/detail/push_options.hpp> namespace boost { namespace asio { namespace detail { template <typename Protocol, typename Handler> class winrt_resolve_op : public winrt_async_op< Windows::Foundation::Collections::IVectorView< Windows::Networking::EndpointPair^>^> { public: BOOST_ASIO_DEFINE_HANDLER_PTR(winrt_resolve_op); typedef typename Protocol::endpoint endpoint_type; typedef boost::asio::ip::basic_resolver_query<Protocol> query_type; typedef boost::asio::ip::basic_resolver_results<Protocol> results_type; winrt_resolve_op(const query_type& query, Handler& handler) : winrt_async_op< Windows::Foundation::Collections::IVectorView< Windows::Networking::EndpointPair^>^>( &winrt_resolve_op::do_complete), query_(query), handler_(BOOST_ASIO_MOVE_CAST(Handler)(handler)) { handler_work<Handler>::start(handler_); } static void do_complete(void* owner, operation* base, const boost::system::error_code&, std::size_t) { // Take ownership of the operation object. winrt_resolve_op* o(static_cast<winrt_resolve_op*>(base)); ptr p = { boost::asio::detail::addressof(o->handler_), o, o }; handler_work<Handler> w(o->handler_); BOOST_ASIO_HANDLER_COMPLETION((*o)); results_type results = results_type(); if (!o->ec_) { try { results = results_type::create(o->result_, o->query_.hints(), o->query_.host_name(), o->query_.service_name()); } catch (Platform::Exception^ e) { o->ec_ = boost::system::error_code(e->HResult, boost::system::system_category()); } } // Make a copy of the handler so that the memory can be deallocated before // the upcall is made. Even if we're not about to make an upcall, a // sub-object of the handler may be the true owner of the memory associated // with the handler. Consequently, a local copy of the handler is required // to ensure that any owning sub-object remains valid until after we have // deallocated the memory here. detail::binder2<Handler, boost::system::error_code, results_type> handler(o->handler_, o->ec_, results); p.h = boost::asio::detail::addressof(handler.handler_); p.reset(); // Make the upcall if required. if (owner) { fenced_block b(fenced_block::half); BOOST_ASIO_HANDLER_INVOCATION_BEGIN((handler.arg1_, "...")); w.complete(handler, handler.handler_); BOOST_ASIO_HANDLER_INVOCATION_END; } } private: query_type query_; Handler handler_; }; } // namespace detail } // namespace asio } // namespace boost #include <boost/asio/detail/pop_options.hpp> #endif // defined(BOOST_ASIO_WINDOWS_RUNTIME) #endif // BOOST_ASIO_DETAIL_WINRT_RESOLVE_OP_HPP
{ "pile_set_name": "Github" }
// +build linux // Copyright Amazon.com Inc. or its affiliates. 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. A copy of the // License is located at // // http://aws.amazon.com/apache2.0/ // // or in the "license" file accompanying this file. This file 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 factory //go:generate mockgen -destination=mock/mock_cgroups_linux.go -copyright_file=../../../../../scripts/copyright_file github.com/containerd/cgroups Cgroup //go:generate mockgen -destination=mock_factory/mock_cgroup_factory_linux.go -copyright_file=../../../../../scripts/copyright_file github.com/aws/amazon-ecs-agent/agent/taskresource/cgroup/control/factory CgroupFactory
{ "pile_set_name": "Github" }
tails
{ "pile_set_name": "Github" }
Quick port test with `netcat` Logging dropped firewall packets Useful ssh client optimizations Bandwidth monitoring tools Use `tcpdump` to listen to network interface traffic
{ "pile_set_name": "Github" }
// RUN: %clang -S %s -o /dev/null struct rtxc_snapshot { int a, b, c, d; }; __attribute__ ((section("__DATA, __common"))) struct rtxc_snapshot rtxc_log_A[4];
{ "pile_set_name": "Github" }
package hxd.fs; @:keep @:keepSub class Convert { public var sourceExts(default,null) : Array<String>; public var destExt(default,null) : String; /** Major version of the Convert. When incremented, all files processed by this Convert would be rebuilt. **/ public var version(default, null) : Int; public var params : Dynamic; public var srcPath : String; public var dstPath : String; public var originalFilename : String; public var srcBytes : haxe.io.Bytes; public function new( sourceExts, destExt ) { this.sourceExts = sourceExts == null ? null : sourceExts.split(","); this.destExt = destExt; this.version = 0; } public function convert() { throw "Not implemented"; } function hasParam( name : String ) { var f : Dynamic = Reflect.field(params, name); return f != null && f != false; } function getParam( name : String ) { var f = Reflect.field(params, name); if( f == null ) throw "Missing required parameter '"+name+"' for converting "+srcPath+" to "+dstPath; return f; } function save( bytes : haxe.io.Bytes ) { hxd.File.saveBytes(dstPath, bytes); } function command( cmd : String, args : Array<String> ) { #if flash trace("TODO"); #elseif (sys || nodejs) var code = Sys.command(cmd, args); if( code != 0 ) throw "Command '" + cmd + (args.length == 0 ? "" : " " + args.join(" ")) + "' failed with exit code " + code; #else throw "Don't know how to run command on this platform"; #end } static var converts = new Map<String,Array<Convert>>(); public static function register( c : Convert ) : Int { var dest = converts.get(c.destExt); if( dest == null ) { dest = []; converts.set(c.destExt, dest); } dest.unshift(c); // latest registered get priority ! (allow override defaults) return 0; } } class ConvertFBX2HMD extends Convert { public function new() { super("fbx", "hmd"); } override function convert() { var fbx = try hxd.fmt.fbx.Parser.parse(srcBytes) catch( e : Dynamic ) throw Std.string(e) + " in " + srcPath; var hmdout = new hxd.fmt.fbx.HMDOut(srcPath); hmdout.load(fbx); var isAnim = StringTools.startsWith(originalFilename, "Anim_") || originalFilename.toLowerCase().indexOf("_anim_") > 0; var hmd = hmdout.toHMD(null, !isAnim); var out = new haxe.io.BytesOutput(); new hxd.fmt.hmd.Writer(out).write(hmd); save(out.getBytes()); } static var _ = Convert.register(new ConvertFBX2HMD()); } class Command extends Convert { var cmd : String; var args : Array<String>; public function new(fr,to,cmd:String,args:Array<String>) { super(fr,to); this.cmd = cmd; this.args = args; } override function convert() { command(cmd,[for( a in args ) if( a == "%SRC" ) srcPath else if( a == "%DST" ) dstPath else a]); } } class ConvertWAV2MP3 extends Convert { public function new() { super("wav", "mp3"); } override function convert() { command("lame", ["--resample", "44100", "--silent", "-h", srcPath, dstPath]); } static var _ = Convert.register(new ConvertWAV2MP3()); } class ConvertWAV2OGG extends Convert { public function new() { super("wav", "ogg"); } override function convert() { var cmd = "oggenc"; var args = ["--resample", "44100", "-Q", srcPath, "-o", dstPath]; #if (sys || nodejs) if( Sys.systemName() == "Windows" ) cmd = "oggenc2"; if( hasParam("mono") ) { var f = sys.io.File.read(srcPath); var wav = new format.wav.Reader(f).read(); f.close(); if( wav.header.channels >= 2 ) args.push("--downmix"); } #end command(cmd, args); } static var _ = Convert.register(new ConvertWAV2OGG()); } class ConvertTGA2PNG extends Convert { public function new() { super("tga", "png"); } override function convert() { #if (sys || nodejs) var input = new haxe.io.BytesInput(sys.io.File.getBytes(srcPath)); var r = new format.tga.Reader(input).read(); if( r.header.imageType != UncompressedTrueColor || r.header.bitsPerPixel != 32 ) throw "Not supported "+r.header.imageType+"/"+r.header.bitsPerPixel; var w = r.header.width; var h = r.header.height; var pix = hxd.Pixels.alloc(w, h, ARGB); var access : hxd.Pixels.PixelsARGB = pix; var p = 0; for( y in 0...h ) for( x in 0...w ) { var c = r.imageData[x + y * w]; access.setPixel(x, y, c); } switch( r.header.imageOrigin ) { case BottomLeft: pix.flags.set(FlipY); case TopLeft: default: throw "Not supported "+r.header.imageOrigin; } sys.io.File.saveBytes(dstPath, pix.toPNG()); #else throw "Not implemented"; #end } static var _ = Convert.register(new ConvertTGA2PNG()); } class ConvertFNT2BFNT extends Convert { var emptyTile : h2d.Tile; public function new() { // Fake tile create subs before discarding the font. emptyTile = @:privateAccess new h2d.Tile(null, 0, 0, 0, 0, 0, 0); super("fnt", "bfnt"); version = 1; } override public function convert() { var font = hxd.fmt.bfnt.FontParser.parse(srcBytes, srcPath, resolveTile); var out = new haxe.io.BytesOutput(); new hxd.fmt.bfnt.Writer(out).write(font); save(out.getBytes()); } function resolveTile( path : String ) : h2d.Tile { #if sys if (!sys.FileSystem.exists(path)) throw "Could not resolve BitmapFont texture reference at path: " + path; #end return emptyTile; } static var _ = Convert.register(new ConvertFNT2BFNT()); } class CompressIMG extends Convert { override function convert() { command("CompressonatorCLI", ["-silent","-fd",getParam("format"),srcPath,dstPath]); } static var _ = Convert.register(new CompressIMG("png,tga,jpg,jpeg","dds")); } class DummyConvert extends Convert { override function convert() { save(haxe.io.Bytes.alloc(0)); } static var _ = [ Convert.register(new DummyConvert(null,"dummy")), Convert.register(new DummyConvert(null,"remove")) ]; }
{ "pile_set_name": "Github" }
<refentry xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:xi="http://www.w3.org/2001/XInclude" xmlns:src="http://nwalsh.com/xmlns/litprog/fragment" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="5.0" xml:id="olink.lang.fallback.sequence"> <refmeta> <refentrytitle>olink.lang.fallback.sequence</refentrytitle> <refmiscinfo class="other" otherclass="datatype">string</refmiscinfo> </refmeta> <refnamediv> <refname>olink.lang.fallback.sequence</refname> <refpurpose>look up translated documents if olink not found?</refpurpose> </refnamediv> <refsynopsisdiv> <src:fragment xml:id="olink.lang.fallback.sequence.frag"> <xsl:param name="olink.lang.fallback.sequence"></xsl:param> </src:fragment> </refsynopsisdiv> <refsection><info><title>Description</title></info> <para>This parameter defines a list of lang values to search among to resolve olinks. </para> <para>Normally an olink tries to resolve to a document in the same language as the olink itself. The language of an olink is determined by its nearest ancestor element with a <tag class="attribute">lang</tag> attribute, otherwise the value of the <parameter>l10n.gentext.default.lang</parameter> parameter. </para> <para>An olink database can contain target data for the same document in multiple languages. Each set of data has the same value for the <tag>targetdoc</tag> attribute in the <tag>document</tag> element in the database, but with a different <tag>lang</tag> attribute value. </para> <para>When an olink is being resolved, the target is first sought in the document with the same language as the olink. If no match is found there, then this parameter is consulted for additional languages to try.</para> <para>The <parameter>olink.lang.fallback.sequence</parameter> must be a whitespace separated list of lang values to try. The first one with a match in the olink database is used. The default value is empty.</para> <para>For example, a document might be written in German and contain an olink with <literal>targetdoc="adminguide"</literal>. When the document is processed, the processor first looks for a target dataset in the olink database starting with:</para> <literallayout><literal>&lt;document targetdoc="adminguide" lang="de"&gt;</literal>. </literallayout> <para>If there is no such element, then the <parameter>olink.lang.fallback.sequence</parameter> parameter is consulted. If its value is, for example, <quote>fr en</quote>, then the processor next looks for <literal>targetdoc="adminguide" lang="fr"</literal>, and then for <literal>targetdoc="adminguide" lang="en"</literal>. If there is still no match, it looks for <literal>targetdoc="adminguide"</literal> with no lang attribute. </para> <para>This parameter is useful when a set of documents is only partially translated, or is in the process of being translated. If a target of an olink has not yet been translated, then this parameter permits the processor to look for the document in other languages. This assumes the reader would rather have a link to a document in a different language than to have a broken link. </para> </refsection> </refentry>
{ "pile_set_name": "Github" }
// Automatically upgrade packages from these (origin:archive) pairs <%- if @legacy_origin -%> Unattended-Upgrade::Allowed-Origins { <%- else -%> Unattended-Upgrade::Origins-Pattern { <%- end -%> <% @origins.each do |origin| -%> "<%= origin %>"; <% end -%> }; // List of packages to not update Unattended-Upgrade::Package-Blacklist { <% @blacklist.each do |package| -%> "<%= package %>"; <% end -%> }; // This option allows you to control if on a unclean dpkg exit // unattended-upgrades will automatically run // dpkg --force-confold --configure -a // The default is true, to ensure updates keep getting installed Unattended-Upgrade::AutoFixInterruptedDpkg "<%= @auto_fix %>"; // Split the upgrade into the smallest possible chunks so that // they can be interrupted with SIGUSR1. This makes the upgrade // a bit slower but it has the benefit that shutdown while a upgrade // is running is possible (with a small delay) Unattended-Upgrade::MinimalSteps "<%= @minimal_steps %>"; // Install all unattended-upgrades when the machine is shuting down // instead of doing it in the background while the machine is running // This will (obviously) make shutdown slower Unattended-Upgrade::InstallOnShutdown "<%= @install_on_shutdown %>"; // Send email to this address for problems or packages upgrades // If empty or unset then no email is sent, make sure that you // have a working mail setup on your system. A package that provides // 'mailx' must be installed. <% if @mail_to != "NONE" %>Unattended-Upgrade::Mail "<%= @mail_to %>";<% end %> // Set this value to "true" to get emails only on errors. Default // is to always send a mail if Unattended-Upgrade::Mail is set <% if @mail_to != "NONE" %>Unattended-Upgrade::MailOnlyOnError "<%= @mail_only_on_error %>";<% end %> // Do automatic removal of new unused dependencies after the upgrade // (equivalent to apt-get autoremove) Unattended-Upgrade::Remove-Unused-Dependencies "<%= @remove_unused %>"; // Automatically reboot *WITHOUT CONFIRMATION* if a // the file /var/run/reboot-required is found after the upgrade Unattended-Upgrade::Automatic-Reboot "<%= @auto_reboot %>"; // Use apt bandwidth limit feature, this example limits the download // speed to 70kb/sec <% if @dl_limit != "NONE" %>Acquire::http::Dl-Limit "<%= @dl_limit %>";<% end %>
{ "pile_set_name": "Github" }
<?php /** * PEAR, the PHP Extension and Application Repository * * Command line interface * * PHP versions 4 and 5 * * @category pear * @package PEAR * @author Stig Bakken <ssb@php.net> * @author Tomas V.V.Cox <cox@idecnet.com> * @copyright 1997-2009 The Authors * @license http://opensource.org/licenses/bsd-license.php New BSD License * @link http://pear.php.net/package/PEAR */ @ob_end_clean(); if (!defined('PEAR_RUNTYPE')) { // this is defined in peclcmd.php as 'pecl' define('PEAR_RUNTYPE', 'pear'); } define('PEAR_IGNORE_BACKTRACE', 1); /** * @nodep Gtk */ //the space is needed for windows include paths with trailing backslash // http://pear.php.net/bugs/bug.php?id=19482 if ('@include_path@ ' != '@'.'include_path'.'@ ') { ini_set('include_path', trim('@include_path@ '). PATH_SEPARATOR . get_include_path()); $raw = false; } else { // this is a raw, uninstalled pear, either a cvs checkout, or php distro $raw = true; } @ini_set('allow_url_fopen', true); @set_time_limit(0); ob_implicit_flush(true); @ini_set('track_errors', true); @ini_set('html_errors', false); $_PEAR_PHPDIR = '#$%^&*'; set_error_handler('error_handler'); $pear_package_version = "@pear_version@"; require_once 'PEAR.php'; require_once 'PEAR/Frontend.php'; require_once 'PEAR/Config.php'; require_once 'PEAR/Command.php'; require_once 'Console/Getopt.php'; PEAR_Command::setFrontendType('CLI'); $all_commands = PEAR_Command::getCommands(); // remove this next part when we stop supporting that crap-ass PHP 4.2 if (!isset($_SERVER['argv']) && !isset($argv) && !isset($HTTP_SERVER_VARS['argv'])) { echo 'ERROR: either use the CLI php executable, ' . 'or set register_argc_argv=On in php.ini'; exit(1); } $argv = Console_Getopt::readPHPArgv(); // fix CGI sapi oddity - the -- in pear.bat/pear is not removed if (php_sapi_name() != 'cli' && isset($argv[1]) && $argv[1] == '--') { unset($argv[1]); $argv = array_values($argv); } $progname = PEAR_RUNTYPE; array_shift($argv); $options = Console_Getopt::getopt2($argv, "c:C:d:D:Gh?sSqu:vV"); if (PEAR::isError($options)) { usage($options); } $opts = $options[0]; $fetype = 'CLI'; if ($progname == 'gpear' || $progname == 'pear-gtk') { $fetype = 'Gtk2'; } else { foreach ($opts as $opt) { if ($opt[0] == 'G') { $fetype = 'Gtk2'; } } } $pear_user_config = ''; $pear_system_config = ''; $store_user_config = false; $store_system_config = false; $verbose = 1; foreach ($opts as $opt) { switch ($opt[0]) { case 'c': $pear_user_config = $opt[1]; break; case 'C': $pear_system_config = $opt[1]; break; } } PEAR_Command::setFrontendType($fetype); $ui = &PEAR_Command::getFrontendObject(); $config = &PEAR_Config::singleton($pear_user_config, $pear_system_config); if (PEAR::isError($config)) { $_file = ''; if ($pear_user_config !== false) { $_file .= $pear_user_config; } if ($pear_system_config !== false) { $_file .= '/' . $pear_system_config; } if ($_file == '/') { $_file = 'The default config file'; } $config->getMessage(); $ui->outputData("ERROR: $_file is not a valid config file or is corrupted."); // We stop, we have no idea where we are :) exit(1); } // this is used in the error handler to retrieve a relative path $_PEAR_PHPDIR = $config->get('php_dir'); $ui->setConfig($config); PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array($ui, "displayFatalError")); $verbose = $config->get("verbose"); $cmdopts = array(); if ($raw) { if (!$config->isDefinedLayer('user') && !$config->isDefinedLayer('system')) { $found = false; foreach ($opts as $opt) { if ($opt[0] == 'd' || $opt[0] == 'D') { // the user knows what they are doing, and are setting config values $found = true; } } if (!$found) { // no prior runs, try to install PEAR $parent = dirname(__FILE__); if (strpos($parent, 'scripts')) { $grandparent = dirname($parent); $packagexml = $grandparent . DIRECTORY_SEPARATOR . 'package2.xml'; $pearbase = $grandparent; } else { $packagexml = $parent . DIRECTORY_SEPARATOR . 'package2.xml'; $pearbase = $parent; } if (file_exists($packagexml)) { $options[1] = array( 'install', $packagexml ); $config->set('php_dir', $pearbase . DIRECTORY_SEPARATOR . 'php'); $config->set('data_dir', $pearbase . DIRECTORY_SEPARATOR . 'data'); $config->set('doc_dir', $pearbase . DIRECTORY_SEPARATOR . 'docs'); $config->set('test_dir', $pearbase . DIRECTORY_SEPARATOR . 'tests'); $config->set( 'ext_dir', $pearbase . DIRECTORY_SEPARATOR . 'extensions' ); $config->set('bin_dir', $pearbase); $config->mergeConfigFile($pearbase . 'pear.ini', false); $config->store(); $config->set('auto_discover', 1); } } } } foreach ($opts as $opt) { $param = !empty($opt[1]) ? $opt[1] : true; switch ($opt[0]) { case 'd': if ($param === true) { die( 'Invalid usage of "-d" option, expected -d config_value=value, ' . 'received "-d"' . "\n" ); } $possible = explode('=', $param); if (count($possible) != 2) { die( 'Invalid usage of "-d" option, expected ' . '-d config_value=value, received "' . $param . '"' . "\n" ); } list($key, $value) = explode('=', $param); $config->set($key, $value, 'user'); break; case 'D': if ($param === true) { die( 'Invalid usage of "-d" option, expected ' . '-d config_value=value, received "-d"' . "\n" ); } $possible = explode('=', $param); if (count($possible) != 2) { die( 'Invalid usage of "-d" option, expected ' . '-d config_value=value, received "' . $param . '"' . "\n" ); } list($key, $value) = explode('=', $param); $config->set($key, $value, 'system'); break; case 's': $store_user_config = true; break; case 'S': $store_system_config = true; break; case 'u': $config->remove($param, 'user'); break; case 'v': $config->set('verbose', $config->get('verbose') + 1); break; case 'q': $config->set('verbose', $config->get('verbose') - 1); break; case 'V': usage(null, 'version'); case 'c': case 'C': break; default: // all non pear params goes to the command $cmdopts[$opt[0]] = $param; break; } } if ($store_system_config) { $config->store('system'); } if ($store_user_config) { $config->store('user'); } $command = (isset($options[1][0])) ? $options[1][0] : null; if (empty($command) && ($store_user_config || $store_system_config)) { exit; } if ($fetype == 'Gtk2') { if (!$config->validConfiguration()) { PEAR::raiseError( "CRITICAL ERROR: no existing valid configuration files found in " . "files '$pear_user_config' or '$pear_system_config', " . "please copy an existing configuration file to one of these " . "locations, or use the -c and -s options to create one" ); } Gtk::main(); } else { do { if ($command == 'help') { usage(null, isset($options[1][1]) ? $options[1][1] : null); } if (!$config->validConfiguration()) { PEAR::raiseError( "CRITICAL ERROR: no existing valid configuration files found " . "in files '$pear_user_config' or '$pear_system_config', " . "please copy an existing configuration file to one of " . "these locations, or use the -c and -s options to create one" ); } PEAR::pushErrorHandling(PEAR_ERROR_RETURN); $cmd = PEAR_Command::factory($command, $config); PEAR::popErrorHandling(); if (PEAR::isError($cmd)) { usage(null, isset($options[1][0]) ? $options[1][0] : null); } $short_args = $long_args = null; PEAR_Command::getGetoptArgs($command, $short_args, $long_args); array_shift($options[1]); $tmp = Console_Getopt::getopt2($options[1], $short_args, $long_args); if (PEAR::isError($tmp)) { break; } list($tmpopt, $params) = $tmp; $opts = array(); foreach ($tmpopt as $foo => $tmp2) { list($opt, $value) = $tmp2; if ($value === null) { $value = true; // options without args } if (strlen($opt) == 1) { $cmdoptions = $cmd->getOptions($command); foreach ($cmdoptions as $o => $d) { if (isset($d['shortopt']) && $d['shortopt'] == $opt) { $opts[$o] = $value; } } } else { if (substr($opt, 0, 2) == '--') { $opts[substr($opt, 2)] = $value; } } } $ok = $cmd->run($command, $opts, $params); if ($ok === false) { PEAR::raiseError("unknown command `$command'"); } if (PEAR::isError($ok)) { PEAR::setErrorHandling( PEAR_ERROR_CALLBACK, array($ui, "displayFatalError") ); PEAR::raiseError($ok); } } while (false); } // {{{ usage() /** * Display usage information * * @param mixed $error Optional error message * @param mixed $helpsubject Optional subject/command to display help for * * @return void */ function usage($error = null, $helpsubject = null) { global $progname, $all_commands; $stdout = fopen('php://stdout', 'w'); if (PEAR::isError($error)) { fputs($stdout, $error->getMessage() . "\n"); } elseif ($error !== null) { fputs($stdout, "$error\n"); } if ($helpsubject != null) { $put = cmdHelp($helpsubject); } else { $put = "Commands:\n"; $maxlen = max(array_map("strlen", $all_commands)); $formatstr = "%-{$maxlen}s %s\n"; ksort($all_commands); foreach ($all_commands as $cmd => $class) { $put .= sprintf($formatstr, $cmd, PEAR_Command::getDescription($cmd)); } $put .= "Usage: $progname [options] command [command-options] <parameters>\n". "Type \"$progname help options\" to list all options.\n". "Type \"$progname help shortcuts\" to list all command shortcuts.\n". "Type \"$progname help version\" or ". "\"$progname version\" to list version information.\n". "Type \"$progname help <command>\" to get the help ". "for the specified command."; } fputs($stdout, "$put\n"); fclose($stdout); if ($error === null) { exit(0); } exit(1); } /** * Return help string for specified command * * @param string $command Command to return help for * * @return void */ function cmdHelp($command) { global $progname, $all_commands, $config; if ($command == "options") { return "Options:\n". " -v increase verbosity level (default 1)\n". " -q be quiet, decrease verbosity level\n". " -c file find user configuration in `file'\n". " -C file find system configuration in `file'\n". " -d foo=bar set user config variable `foo' to `bar'\n". " -D foo=bar set system config variable `foo' to `bar'\n". " -G start in graphical (Gtk) mode\n". " -s store user configuration\n". " -S store system configuration\n". " -u foo unset `foo' in the user configuration\n". " -h, -? display help/usage (this message)\n". " -V version information\n"; } elseif ($command == "shortcuts") { $sc = PEAR_Command::getShortcuts(); $ret = "Shortcuts:\n"; foreach ($sc as $s => $c) { $ret .= sprintf(" %-8s %s\n", $s, $c); } return $ret; } elseif ($command == "version") { return "PEAR Version: ".$GLOBALS['pear_package_version']. "\nPHP Version: ".phpversion(). "\nZend Engine Version: ".zend_version(). "\nRunning on: ".php_uname(); } elseif ($help = PEAR_Command::getHelp($command)) { if (is_string($help)) { return "$progname $command [options] $help\n"; } if ($help[1] === null) { return "$progname $command $help[0]"; } return "$progname $command [options] $help[0]\n$help[1]"; } return "Command '$command' is not valid, try '$progname help'"; } // }}} /** * error_handler * * @param mixed $errno Error number * @param mixed $errmsg Message * @param mixed $file Filename * @param mixed $line Line number * @param mixed $vars Variables * * @access public * @return boolean */ function error_handler($errno, $errmsg, $file, $line, $vars) { if ($errno & E_STRICT || $errno & E_DEPRECATED || !error_reporting() ) { if ($errno & E_STRICT) { return; // E_STRICT } if ($errno & E_DEPRECATED) { return; // E_DEPRECATED } if (!error_reporting() && isset($GLOBALS['config']) && $GLOBALS['config']->get('verbose') < 4) { return false; // @silenced error, show all if debug is high enough } } $errortype = array ( E_DEPRECATED => 'Deprecated Warning', E_ERROR => "Error", E_WARNING => "Warning", E_PARSE => "Parsing Error", E_STRICT => 'Strict Warning', E_NOTICE => "Notice", E_CORE_ERROR => "Core Error", E_CORE_WARNING => "Core Warning", E_COMPILE_ERROR => "Compile Error", E_COMPILE_WARNING => "Compile Warning", E_USER_ERROR => "User Error", E_USER_WARNING => "User Warning", E_USER_NOTICE => "User Notice" ); $prefix = $errortype[$errno]; global $_PEAR_PHPDIR; if (stristr($file, $_PEAR_PHPDIR)) { $file = substr($file, strlen($_PEAR_PHPDIR) + 1); } else { $file = basename($file); } print "\n$prefix: $errmsg in $file on line $line\n"; return false; } /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * indent-tabs-mode: nil * mode: php * End: */ // vim600:syn=php
{ "pile_set_name": "Github" }
/* Webcamoid, webcam capture application. * Copyright (C) 2016 Gonzalo Exequiel Pedone * * Webcamoid is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Webcamoid is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Webcamoid. If not, see <http://www.gnu.org/licenses/>. * * Web-Site: http://webcamoid.github.io/ */ import QtQuick 2.12 import QtQuick.Controls 2.5 import QtQuick.Layouts 1.3 GridLayout { columns: 3 Connections { target: Swirl onDegreesChanged: { sldDegrees.value = degrees spbDegrees.value = degrees } } Label { text: qsTr("Degrees") } Slider { id: sldDegrees value: Swirl.degrees stepSize: 1 from: -360 to: 360 Layout.fillWidth: true onValueChanged: Swirl.degrees = value } SpinBox { id: spbDegrees value: Swirl.degrees from: sldDegrees.from to: sldDegrees.to stepSize: sldDegrees.stepSize editable: true onValueChanged: Swirl.degrees = value } }
{ "pile_set_name": "Github" }
<template> <div class="main" > <div class="tagselect" v-on:click.stop="alltagsshow=!alltagsshow">{{this.type}}</div> <div class="hottags"> <h5>热门标签:</h5> <template v-for="(tag,$index) in hottags" > <h5 style="cursor:pointer;" v-on:click="$router.push({name:'allplaylist',params:{type:tag.name}});"> {{tag.name}} </h5> <h5 class="col" v-if="$index<hottags.length-1"></h5> </template> </div> <div class="ranklist2"> <div class="continer"> <template v-for="(rank,$index) in list"> <div class="rank2 disk"> <div class="rankimg2" :style="{background:'url('+rank.coverImgUrl+'?param=150y150) no-repeat 0px 0px'}" v-on:click="goPlaylist(rank.id)"> <!-- <span>{{Math.ceil(rank.playCount/10000)}}万</span> --> <span><span>{{Math.ceil(rank.playCount/10000)}}万</span><div class="counticon"></div></span> </div> <span>{{rank.name}}</span> </div> </template> <div class="rank2" style="height:1px;"></div> <div class="rank2" style="height:1px;"></div> <div class="rank2" style="height:1px;"></div> <div class="rank2" style="height:1px;"></div> <div class="rank2" style="height:1px;"></div> <div class="rank2" style="height:1px;"></div> <div class="rank2" style="height:1px;"></div> <div class="rank2" style="height:1px;"></div> </div> </div> <transition name="alltags_transition"> <div class="alltags" v-on:click.stop="" v-show="alltagsshow"> <span style="cursor:pointer;" v-on:click="$router.push({name:'allplaylist',params:{type:'全部'}});alltagsshow=false;"> 全部 </span> <br/> <template v-for="(tag,$index) in alltags"> <span style="cursor:pointer;" v-on:click="$router.push({name:'allplaylist',params:{type:tag.name}});alltagsshow=false;"> {{tag.name}} </span> <h5 class="col" v-if="$index<alltags.length-1"></h5> </template> <div class="tran"></div> </div> </transition> </div> </template> <script> import config from "@/config" export default { name: 'allplaylist', mounted() { this.eventer.on("main-continer-scroll",this.onScroll); document.addEventListener("click",()=>{this.alltagsshow=false;}); axios.get('music163/api/playlist/hottags',{}).then(m=>{ if (m.status == 200 && m.data.code == 200 && m.data.tags) { this.hottags=m.data.tags; } console.log(m) }); axios.get('music163/api/playlist/catalogue',{}).then(m=>{ this.alltags=m.data.sub; console.log(m) }); this.type = this.$route.params.type || "全部"; this.search(); }, data() { return { list: [], hottags:[], alltags:[], type:"", searchString: "", msg: 'Welcome to Your Vue.js App', source:axios.CancelToken.source(), more:false, offset:0, alltagsshow:false, } }, methods: { onScroll(e){ if (this.more) { this.search(); } }, search() { this.source.cancel("aaaa"); this.source=axios.CancelToken.source(); axios.get('music163/api/playlist/list'+(this.type?('?cat='+this.type):'?cat=全部')+'&limit=30'+'&offset='+this.offset,{cancelToken: this.source.token}).then(m=>{ if (m.status == 200 && m.data.code == 200 && m.data.playlists) { m.data.playlists.forEach((o)=>{ this.list.push(o); }); this.more=m.data.more; this.offset+=30; } }); }, goPlaylist(id) { this.$router.push({ name: 'playlist', params: { id: id } }); }, goSong(id) { this.$router.push({ name: 'song', params: { id: id } }); }, }, components: { }, beforeDestroy(){ this.eventer.off("main-continer-scroll"); document.removeEventListener("click"); this.source.cancel("aaaa"); } , watch: { $route() { this.source.cancel("aaaa"); this.offset=0; this.more=0; this.type = this.$route.params.type || "全部"; this.list=[]; this.alltagsshow=false; this.search(); }, }, } </script> <!-- Add "scoped" attribute to limit CSS to this component only --> <style scoped> .ranklist1 { padding-top: 20px; /*border-top: solid 1px #e6e6e6;*/ } .ranklist2 { padding-top: 20px; /*border-top: solid 1px #e6e6e6;*/ } .ranklist2 > div { display: flex; justify-content: space-between; flex-wrap: wrap; } .ranklist1 .rank1 { height: 360px; width: calc(33.3% - 10px); cursor: pointer; overflow: hidden; /*margin-left: 15px;*/ display: inline-block; float: left; margin-bottom: 20px; border: solid 1px #e6e6e6; } .ranklist2 .rank2 { height: auto; width: 150px; cursor: pointer; overflow: hidden; /*margin-left: 15px;*/ display: inline-block; /*float: left;*/ margin-right: 30px; margin-left: 30px; } .ranklist2 .continer { margin-left:-30px; margin-right:-30px; } .ranklist1 .rank1 .rankimg1 { height: 80px; width: 100%; position: relative; } .ranklist2 .rank2 .rankimg2 { height: 150px; width: 150px; position: relative; background-size: contain !important; border: solid 1px #e6e6e6; } /*.ranklist2 .rank2 .rankimg2::before { content: ""; width: 100%; height: 100%; position: absolute; background: url(../assets/ntr.png) no-repeat rgba(0,0,0,0.5); }*/ .ranklist1 .rank1 .rankimg1 span { font-size: 12px; color: #ffffff; position: absolute; bottom: 5px; left: 50px; } .ranklist2 .rank2 .rankimg2 > span { height: 20px; font-size: 13px; color: #ffffff; position: absolute; top: 0px; right: 0px; font-weight: 900; /*width: 50%;*/ background: linear-gradient(-90deg,rgba(50,50,50,0.8),rgba(100,100,100,0.4),rgba(150,150,150,0)); text-align: right; padding-right: 5px; } .ranklist2 .rank2 .rankimg2 span > *{ float: right; } .ranklist2 .rank2 .rankimg2 span div{ width: 20px; height: 20px; background: url('../assets/headphones.png'); background-position: center; background-repeat: no-repeat; background-size: 80%; } .hotlist .hot p { width: 100%; margin: 0px; text-align: left; } .hotimg { width: 150px; height: 150px; border: solid 1px #e6e6e6; } .main { padding-left: 30px; padding-right: 30px; text-align: left; } .main h1 { margin: 0px; border-bottom: solid 3px #e6e6e6; display: inline-block; font-size: 24px; color: #666666; margin-right: 20px; } .main h3 { margin: 0px; display: inline-block; font-size: 16px; color: #666666; margin-right: 20px; } .hottags { /*position: relative;*/ } .hottags > * { display: inline-block; margin: 0px; } .hottags > .col { height: 15px; width:1px; background-color:#e6e6e6; margin-bottom: -3px; margin-left: 10px; margin-right: 10px; } .tagselect { border-radius: 5px; border: solid 1px #cccccc; display: inline-block; padding: 5px 10px; margin-bottom: 5px; text-align: center; box-shadow: rgba(0, 0, 0, 0.1) 0px 1px 1px 0px; cursor: pointer; } .tagselect:active { background-color: #efefef; } .alltags { max-width: 600px; /*height: 400px;*/ position: absolute; top: 45px; background: #fafafa; border: solid 1px #cccccc; box-shadow: 0px 0px 4px 1px rgba(0,0,0,0.25); border-radius: 5px; padding: 5px; /*overflow: hidden;*/ } .alltags .tran { height: 10px; width: 10px; position: absolute; right: 30px; border-width: 0px 5px 8px; border-style: solid; /*border-color: transparent transparent rgb(255, 255, 255);*/ border-color: transparent transparent rgba(0,0,0,0.15); /*box-shadow: 0px 0px 5px 1px rgba(0,0,0,0.25);*/ top: -10px; left: 10px; display: block; } .alltags .tran::before { content: ""; height: 2px; width: 0px; position: absolute; top: 2px; left: -5px; border-width: 0px 5px 8px; border-style: solid; border-color: transparent transparent rgb(255, 255, 255); display: block; } .alltags > span { display: inline-block; margin: 5px; } .alltags > .col { height: 15px; width:1px; background-color:#e6e6e6; margin-bottom: -3px; margin-top: 0px; margin-left: 5px; margin-right: 5px; display: inline-block; } .alltags_transition-enter-active, .alltags_transition-leave-active { transition: opacity .5s ; } .alltags_transition-enter, .alltags_transition-leave-active { opacity: 0; } @media screen and (max-width: 750px){ .ranklist2 .rank2 { width: 210px; margin-right: 10px; margin-left: 10px; } .ranklist2 .continer { margin-left:-10px; margin-right:-10px; } .ranklist2 .rank2 .rankimg2 { height: 210px; width: 210px; } .ranklist2 .rank2 .rankimg2>span { height: 40px; font-size: 26px; padding-right: 10px; } .ranklist2 .rank2 .rankimg2 span div { width: 40px; height: 40px; } h5 { font-size: 28px; } .alltags { max-width: 690px; top: 80px; } .alltags .tran { height: 20px; width: 20px; position: absolute; right: 30px; border-width: 0px 10px 18px; border-style: solid; /*border-color: transparent transparent rgb(255, 255, 255);*/ border-color: transparent transparent rgba(0,0,0,0.15); /*box-shadow: 0px 0px 5px 1px rgba(0,0,0,0.25);*/ top: -20px; left: 10px; display: block; } .alltags .tran::before { content: ""; height: 2px; width: 0px; position: absolute; top: 3px; left: -10px; border-width: 0px 10px 18px; border-style: solid; border-color: transparent transparent rgb(255, 255, 255); display: block; } } </style>
{ "pile_set_name": "Github" }
importance: 5 --- # Add an option to select There's a `<select>`: ```html <select id="genres"> <option value="rock">Rock</option> <option value="blues" selected>Blues</option> </select> ``` Use JavaScript to: 1. Show the value and the text of the selected option. 2. Add an option: `<option value="classic">Classic</option>`. 3. Make it selected. Note, if you've done everything right, your alert should show `blues`.
{ "pile_set_name": "Github" }
package co.netguru.videochatguru import android.content.Context import android.os.Handler import android.os.Looper import co.netguru.videochatguru.constraints.* import co.netguru.videochatguru.util.Logger import co.netguru.videochatguru.util.WebRtcUtils import co.netguru.videochatguru.util.addConstraints import org.webrtc.* import java.util.concurrent.Executors import java.util.concurrent.atomic.AtomicInteger /** * WebRTC client wraps webRTC implementation simplifying implementation of video chat. WebRTC client * uses set of default WebRTC constraints that should suffice most of the use cases if you need to overwrite * those you can pass your own [WebRtcConstraints] collection of constraints. * * @param context used only during camera initialization, not stored internally * @param localVideoWidth width of video recorded by this client * @param localVideoHeight height of video recorded by this client * @param localVideoFps frames per second recorded by this client * @param hardwareAcceleration set whether client should use hardware acceleration, enabled by default * @param booleanAudioConstraints enables overwriting default [BooleanAudioConstraints] used by client * @param integerAudioConstraints enables overwriting default [IntegerAudioConstraints] used by client * @param peerConnectionConstraints enables overwriting default [PeerConnectionConstraints] used by client * @param offerAnswerConstraints enables overwriting default [OfferAnswerConstraints] used by client */ open class WebRtcClient(context: Context, private val localVideoWidth: Int = 1280, private val localVideoHeight: Int = 720, private val localVideoFps: Int = 24, hardwareAcceleration: Boolean = true, booleanAudioConstraints: WebRtcConstraints<BooleanAudioConstraints, Boolean>? = null, integerAudioConstraints: WebRtcConstraints<IntegerAudioConstraints, Int>? = null, peerConnectionConstraints: WebRtcConstraints<PeerConnectionConstraints, Boolean>? = null, offerAnswerConstraints: WebRtcConstraints<OfferAnswerConstraints, Boolean>? = null) : RemoteVideoListener { companion object { private val TAG = WebRtcClient::class.java.simpleName //Enabling internal tracer was causing crashes private const val ENABLE_INTERNAL_TRACER = false } private val counter = AtomicInteger(0) private val singleThreadExecutor = Executors.newSingleThreadExecutor() private val mainThreadHandler = Handler(Looper.getMainLooper()) private var remoteVideoTrack: VideoTrack? = null private var videoSource: VideoSource? = null private var localVideoTrack: VideoTrack? = null private lateinit var peerConnectionFactory: PeerConnectionFactory private lateinit var audioSource: AudioSource private lateinit var localAudioTrack: AudioTrack private var remoteView: SurfaceViewRenderer? = null private var remoteVideoRenderer: VideoRenderer? = null private var localView: SurfaceViewRenderer? = null private var localVideoRenderer: VideoRenderer? = null private val eglBase = EglBase.create() private val audioBooleanConstraints by lazy { WebRtcConstraints<BooleanAudioConstraints, Boolean>().apply { addMandatoryConstraint(BooleanAudioConstraints.DISABLE_AUDIO_PROCESSING, true) } } private val audioIntegerConstraints by lazy { WebRtcConstraints<IntegerAudioConstraints, Int>() } private val offerAnswerConstraints by lazy { WebRtcConstraints<OfferAnswerConstraints, Boolean>().apply { addMandatoryConstraint(OfferAnswerConstraints.OFFER_TO_RECEIVE_AUDIO, true) addMandatoryConstraint(OfferAnswerConstraints.OFFER_TO_RECEIVE_VIDEO, true) } } private val peerConnectionConstraints by lazy { WebRtcConstraints<PeerConnectionConstraints, Boolean>().apply { addMandatoryConstraint(PeerConnectionConstraints.DTLS_SRTP_KEY_AGREEMENT_CONSTRAINT, true) addMandatoryConstraint(PeerConnectionConstraints.GOOG_CPU_OVERUSE_DETECTION, true) } } private val videoCameraCapturer = WebRtcUtils.createCameraCapturerWithFrontAsDefault(context) var cameraEnabled = true set(isEnabled) { field = isEnabled singleThreadExecutor.execute { videoCameraCapturer?.let { enableVideo(isEnabled, it) } } } var microphoneEnabled = true set(isEnabled) { field = isEnabled singleThreadExecutor.execute { localAudioTrack.setEnabled(isEnabled) } } private var isPeerConnectionInitialized = false private lateinit var peerConnection: PeerConnection private lateinit var peerConnectionListener: PeerConnectionListener private val videoPeerConnectionListener by lazy { VideoPeerConnectionObserver(peerConnectionListener, this) } private lateinit var offeringPartyHandler: WebRtcOfferingPartyHandler private lateinit var answeringPartyHandler: WebRtcAnsweringPartyHandler init { PeerConnectionFactory.initialize( PeerConnectionFactory.InitializationOptions.builder(context) .setEnableInternalTracer(ENABLE_INTERNAL_TRACER) .setEnableVideoHwAcceleration(hardwareAcceleration) .createInitializationOptions() ) booleanAudioConstraints?.let { audioBooleanConstraints += it } integerAudioConstraints?.let { audioIntegerConstraints += it } peerConnectionConstraints?.let { this.peerConnectionConstraints += it } offerAnswerConstraints?.let { this.offerAnswerConstraints += it } singleThreadExecutor.execute { initialize() } } private fun initialize() { peerConnectionFactory = PeerConnectionFactory(PeerConnectionFactory.Options()) if (videoCameraCapturer != null) { peerConnectionFactory.setVideoHwAccelerationOptions(eglBase.eglBaseContext, eglBase.eglBaseContext) videoSource = peerConnectionFactory.createVideoSource(videoCameraCapturer) localVideoTrack = peerConnectionFactory.createVideoTrack(counter.getAndIncrement().toString(), videoSource) enableVideo(cameraEnabled, videoCameraCapturer) } audioSource = peerConnectionFactory.createAudioSource(getAudioMediaConstraints()) localAudioTrack = peerConnectionFactory.createAudioTrack(getCounterStringValueAndIncrement(), audioSource) } /** * Initialize the peer connection * @param iceServers list of interactive connectivity establishment servers used for traversal or relaying media (Stun and Turn) * @param peerConnectionListener listener for interactive connectivity establishment actions * @param webRtcOfferingActionListener offering party actions listener * @param webRtcAnsweringPartyListener answering party actions listener */ fun initializePeerConnection(iceServers: List<PeerConnection.IceServer>, peerConnectionListener: PeerConnectionListener, webRtcOfferingActionListener: WebRtcOfferingActionListener, webRtcAnsweringPartyListener: WebRtcAnsweringPartyListener) { singleThreadExecutor.execute { this.peerConnectionListener = peerConnectionListener val rtcConfig = PeerConnection.RTCConfiguration(iceServers) peerConnection = peerConnectionFactory.createPeerConnection(rtcConfig, getPeerConnectionMediaConstraints(), videoPeerConnectionListener) isPeerConnectionInitialized = true val localMediaStream = peerConnectionFactory.createLocalMediaStream(getCounterStringValueAndIncrement()) localMediaStream.addTrack(localAudioTrack) localVideoTrack?.let { localMediaStream.addTrack(it) } peerConnection.addStream(localMediaStream) offeringPartyHandler = WebRtcOfferingPartyHandler(peerConnection, webRtcOfferingActionListener) answeringPartyHandler = WebRtcAnsweringPartyHandler(peerConnection, getOfferAnswerConstraints(), webRtcAnsweringPartyListener) } } override fun onAddRemoteVideoStream(remoteVideoTrack: VideoTrack) { singleThreadExecutor.execute { this.remoteVideoTrack = remoteVideoTrack remoteVideoRenderer?.let { remoteVideoTrack.addRenderer(it) } } } override fun removeVideoStream() { singleThreadExecutor.execute { remoteVideoTrack = null } } /** * Attach [SurfaceViewRenderer] to webrtc client used for rendering remote view. */ fun attachRemoteView(remoteView: SurfaceViewRenderer) { mainThreadHandler.post { remoteView.init(eglBase.eglBaseContext, null) this@WebRtcClient.remoteView = remoteView singleThreadExecutor.execute { remoteVideoRenderer = VideoRenderer(remoteView) remoteVideoTrack?.addRenderer(remoteVideoRenderer) } } } /** * Attach [SurfaceViewRenderer] to webrtc client used for rendering local view. */ fun attachLocalView(localView: SurfaceViewRenderer) { mainThreadHandler.post { localView.init(eglBase.eglBaseContext, null) this@WebRtcClient.localView = localView singleThreadExecutor.execute { localVideoRenderer = VideoRenderer(localView) localVideoTrack?.addRenderer(localVideoRenderer) } } } fun detachLocalView() { mainThreadHandler.post { localView?.release() localView = null } singleThreadExecutor.execute { localVideoRenderer?.let { localVideoTrack?.removeRenderer(it) it.dispose() localVideoRenderer = null } } } fun detachRemoteView() { mainThreadHandler.post { remoteView?.release() remoteView = null } singleThreadExecutor.execute { remoteVideoRenderer?.let { remoteVideoTrack?.removeRenderer(it) it.dispose() remoteVideoRenderer = null } } } /** * Detach all [SurfaceViewRenderer]'s from webrtc client. */ fun detachViews() { detachLocalView() detachRemoteView() } /** * Call this method after you finish using this WebRtcClient instance. */ fun dispose() { singleThreadExecutor.execute { if (isPeerConnectionInitialized) { peerConnection.close() peerConnection.dispose() } eglBase.release() audioSource.dispose() videoCameraCapturer?.dispose() videoSource?.dispose() peerConnectionFactory.dispose() } singleThreadExecutor.shutdown() } /** * Orders webrtc client to create offer for remote party. Offer will be returned in [WebRtcOfferingActionListener] callback */ fun createOffer() { singleThreadExecutor.execute { offeringPartyHandler.createOffer(getOfferAnswerConstraints()) } } /** * Handles received remote answer to our offer. */ fun handleRemoteAnswer(remoteSessionDescription: SessionDescription) { singleThreadExecutor.execute { offeringPartyHandler.handleRemoteAnswer(remoteSessionDescription) } } /** * Handles received remote offer. This will result in producing answer which will be returned in * [WebRtcAnsweringPartyListener] callback. */ fun handleRemoteOffer(remoteSessionDescription: SessionDescription) { singleThreadExecutor.execute { answeringPartyHandler.handleRemoteOffer(remoteSessionDescription) } } /** * Adds ice candidate from remote party to webrtc client */ fun addRemoteIceCandidate(iceCandidate: IceCandidate) { singleThreadExecutor.execute { peerConnection.addIceCandidate(iceCandidate) } } /** * Removes ice candidates */ fun removeRemoteIceCandidate(iceCandidates: Array<IceCandidate>) { singleThreadExecutor.execute { peerConnection.removeIceCandidates(iceCandidates) } } /** * Tries to start connection again, this should be called when connection state changes to * [PeerConnection.IceConnectionState.DISCONNECTED] or [PeerConnection.IceConnectionState.FAILED] * by one of the parties - preferably offering one. */ fun restart() { singleThreadExecutor.execute { offeringPartyHandler.createOffer(getOfferAnswerRestartConstraints()) } } /** * Switches the camera to other if there is any available. By default front camera is used. * @param cameraSwitchHandler allows listening for switch camera event */ @JvmOverloads fun switchCamera(cameraSwitchHandler: CameraVideoCapturer.CameraSwitchHandler? = null) { singleThreadExecutor.execute { videoCameraCapturer?.switchCamera(cameraSwitchHandler) } } /** * Safety net in case the owner of an object forgets to call its explicit termination method. * @see <a href="https://kotlinlang.org/docs/reference/java-interop.html#finalize"> * https://kotlinlang.org/docs/reference/java-interop.html#finalize</a> */ @Suppress("unused", "ProtectedInFinal") protected fun finalize() { if (!singleThreadExecutor.isShutdown) { Logger.e(TAG, "Dispose method wasn't called") dispose() } } private fun enableVideo(isEnabled: Boolean, videoCapturer: CameraVideoCapturer) { if (isEnabled) { videoCapturer.startCapture(localVideoWidth, localVideoHeight, localVideoFps) } else { videoCapturer.stopCapture() } } private fun getCounterStringValueAndIncrement() = counter.getAndIncrement().toString() private fun getAudioMediaConstraints() = MediaConstraints().apply { addConstraints(audioBooleanConstraints, audioIntegerConstraints) } private fun getPeerConnectionMediaConstraints() = MediaConstraints().apply { addConstraints(peerConnectionConstraints) } private fun getOfferAnswerConstraints() = MediaConstraints().apply { addConstraints(offerAnswerConstraints) } private fun getOfferAnswerRestartConstraints() = getOfferAnswerConstraints().apply { mandatory.add(OfferAnswerConstraints.ICE_RESTART.toKeyValuePair(true)) } }
{ "pile_set_name": "Github" }
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { UsersRoutingModule } from './users-routing.module'; @NgModule({ declarations: [], imports: [ CommonModule, UsersRoutingModule ] }) export class UsersModule { }
{ "pile_set_name": "Github" }
package com.riiablo.onet.reliable; import io.netty.bootstrap.Bootstrap; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufUtil; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.DatagramChannel; import io.netty.channel.socket.DatagramPacket; import io.netty.channel.socket.nio.NioDatagramChannel; import java.net.SocketAddress; import java.nio.ByteBuffer; import com.badlogic.gdx.Application; import com.badlogic.gdx.ApplicationAdapter; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.backends.headless.HeadlessApplication; import com.badlogic.gdx.backends.headless.HeadlessApplicationConfiguration; import com.riiablo.codec.Animation; import com.riiablo.net.packet.netty.Netty; import com.riiablo.net.packet.netty.NettyData; import com.riiablo.onet.Endpoint; import com.riiablo.onet.EndpointedChannelHandler; import com.riiablo.onet.PacketProcessor; public class TestServer extends ApplicationAdapter implements PacketProcessor { private static final String TAG = "Server"; static final int PORT = 6114; public static void main(String[] args) { HeadlessApplicationConfiguration config = new HeadlessApplicationConfiguration(); config.renderInterval = Animation.FRAME_DURATION; new HeadlessApplication(new TestServer(), config); } private Endpoint<?> endpoint; private EventLoopGroup group; @Override public void create() { Gdx.app.setLogLevel(Application.LOG_DEBUG); group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap() .group(group) .channel(NioDatagramChannel.class) .option(ChannelOption.SO_BROADCAST, true) .handler(new ChannelInitializer<DatagramChannel>() { @Override protected void initChannel(DatagramChannel ch) { ReliableEndpoint endpoint = new ReliableEndpoint(ch, TestServer.this); TestServer.this.endpoint = endpoint; ch.pipeline() .addLast(new EndpointedChannelHandler<>(DatagramPacket.class, endpoint)) ; } }) ; ChannelFuture f = b.bind(PORT).sync(); } catch (Throwable t) { Gdx.app.error(TAG, t.getMessage(), t); Gdx.app.exit(); } } @Override public void render() { endpoint.update(Gdx.graphics.getDeltaTime()); } @Override public void dispose() { if (!group.isShuttingDown()) group.shutdownGracefully(); } @Override public void processPacket(ChannelHandlerContext ctx, SocketAddress from, ByteBuf bb) { Gdx.app.debug(TAG, "Processing packet..."); Gdx.app.log(TAG, ByteBufUtil.hexDump(bb)); ByteBuffer nioBuffer = bb.nioBuffer(); Netty netty = Netty.getRootAsNetty(nioBuffer); byte dataType = netty.dataType(); if (0 <= dataType && dataType < NettyData.names.length) { Gdx.app.debug(TAG, "dataType=" + NettyData.name(dataType)); } } }
{ "pile_set_name": "Github" }
// Copyright (c) 2019 Uber Technologies, Inc. // // 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 procedure import ( "testing" "github.com/stretchr/testify/suite" ) type LabelManagerTestSuite struct { suite.Suite } // Test the basic usage of LabelManager.HasLabel func (suite *LabelManagerTestSuite) TestLabelManagerHasLabelBasic() { labelManager := NewLabelManager(&LabelManagerConfig{ Entries: []*LabelManagerConfigEntry{ {Procedures: []string{"testService:Procedure1"}, Labels: []string{"label1"}}, {Procedures: []string{"testService:Procedure2"}, Labels: []string{"label2"}}, {Procedures: []string{"testService:Procedure3"}, Labels: []string{"label3"}}, }, }) suite.True(labelManager.HasLabel("testService::Procedure1", "label1")) suite.True(labelManager.HasLabel("testService::Procedure2", "label2")) suite.True(labelManager.HasLabel("testService::Procedure3", "label3")) suite.False(labelManager.HasLabel("testService::Procedure1", "label3")) suite.False(labelManager.HasLabel("testService::Procedure2", "label1")) suite.False(labelManager.HasLabel("testService::Procedure3", "label1")) } // Test if LabelManager.HasLabel can deal with entries with multiple label func (suite *LabelManagerTestSuite) TestLabelManagerHasLabelMultipleLabels() { labelManager := NewLabelManager(&LabelManagerConfig{ Entries: []*LabelManagerConfigEntry{ {Procedures: []string{"testService:Procedure1"}, Labels: []string{"label1", "label2"}}, {Procedures: []string{"testService:Procedure1"}, Labels: []string{"label3"}}, }, }) suite.True(labelManager.HasLabel("testService::Procedure1", "label1")) suite.True(labelManager.HasLabel("testService::Procedure1", "label2")) suite.True(labelManager.HasLabel("testService::Procedure1", "label3")) suite.False(labelManager.HasLabel("testService::Procedure1", "label4")) } // Test LabelManager.HasLabel in the case of wildcard in service is used func (suite *LabelManagerTestSuite) TestLabelManagerHasLabelWildcardService() { labelManager := NewLabelManager(&LabelManagerConfig{ Entries: []*LabelManagerConfigEntry{ {Procedures: []string{"*:Procedure1"}, Labels: []string{"label1", "label2"}}, {Procedures: []string{"*:Procedure2"}, Labels: []string{"label3", "label4"}}, {Procedures: []string{"*:Procedure3*"}, Labels: []string{"label5", "label6"}}, }, }) suite.True(labelManager.HasLabel("testService1::Procedure1", "label1")) suite.True(labelManager.HasLabel("testService1::Procedure1", "label2")) suite.True(labelManager.HasLabel("testService2::Procedure1", "label1")) suite.True(labelManager.HasLabel("testService2::Procedure1", "label2")) suite.True(labelManager.HasLabel("testService1::Procedure2", "label3")) suite.True(labelManager.HasLabel("testService1::Procedure2", "label4")) suite.True(labelManager.HasLabel("testService2::Procedure2", "label3")) suite.True(labelManager.HasLabel("testService2::Procedure2", "label4")) suite.True(labelManager.HasLabel("testService1::Procedure3", "label5")) suite.True(labelManager.HasLabel("testService1::Procedure3", "label6")) suite.True(labelManager.HasLabel("testService2::Procedure3", "label5")) suite.True(labelManager.HasLabel("testService2::Procedure3", "label6")) suite.True(labelManager.HasLabel("testService1::Procedure34", "label5")) suite.True(labelManager.HasLabel("testService1::Procedure34", "label6")) suite.True(labelManager.HasLabel("testService2::Procedure34", "label5")) suite.True(labelManager.HasLabel("testService2::Procedure34", "label6")) suite.False(labelManager.HasLabel("testService1::Procedure1", "label3")) suite.False(labelManager.HasLabel("testService1::Procedure1", "label4")) suite.False(labelManager.HasLabel("testService2::Procedure1", "label3")) suite.False(labelManager.HasLabel("testService2::Procedure1", "label4")) suite.False(labelManager.HasLabel("testService1::Procedure2", "label1")) suite.False(labelManager.HasLabel("testService1::Procedure2", "label2")) suite.False(labelManager.HasLabel("testService2::Procedure2", "label1")) suite.False(labelManager.HasLabel("testService2::Procedure2", "label2")) } // Test if LabelManager.HasLabel can deal with entries with multiple label func (suite *LabelManagerTestSuite) TestLabelManagerHasLabelWildcardMethod() { labelManager := NewLabelManager(&LabelManagerConfig{ Entries: []*LabelManagerConfigEntry{ {Procedures: []string{"testService1:*"}, Labels: []string{"label1", "label2"}}, {Procedures: []string{"testService2:Get*"}, Labels: []string{"label1", "label2"}}, }, }) suite.True(labelManager.HasLabel("testService1::Procedure1", "label1")) suite.True(labelManager.HasLabel("testService1::Procedure1", "label2")) suite.True(labelManager.HasLabel("testService1::Procedure2", "label1")) suite.True(labelManager.HasLabel("testService1::Procedure2", "label2")) suite.True(labelManager.HasLabel("testService2::Get", "label1")) suite.True(labelManager.HasLabel("testService2::Get", "label2")) suite.True(labelManager.HasLabel("testService2::Get1", "label1")) suite.True(labelManager.HasLabel("testService2::Get2", "label2")) suite.False(labelManager.HasLabel("testService2::Procedure1", "label1")) suite.False(labelManager.HasLabel("testService2::Procedure1", "label2")) } // Test if LabelManager.HasLabel can handle default config with no setting func (suite *LabelManagerTestSuite) TestLabelManagerDefaultConfig() { labelManager := NewLabelManager(&LabelManagerConfig{}) suite.False(labelManager.HasLabel("testService1::Procedure2", "label1")) suite.False(labelManager.HasLabel("testService1::Procedure2", "label2")) suite.False(labelManager.HasLabel("testService2::Procedure2", "label1")) suite.False(labelManager.HasLabel("testService2::Procedure2", "label2")) } func TestLabelManagerTestSuite(t *testing.T) { suite.Run(t, new(LabelManagerTestSuite)) }
{ "pile_set_name": "Github" }
/****************************************************************************** * Spine Runtimes License Agreement * Last updated January 1, 2020. Replaces all prior versions. * * Copyright (c) 2013-2020, Esoteric Software LLC * * Integration of the Spine Runtimes into software or otherwise creating * derivative works of the Spine Runtimes is permitted under the terms and * conditions of Section 2 of the Spine Editor License Agreement: * http://esotericsoftware.com/spine-editor-license * * Otherwise, it is permitted to integrate the Spine Runtimes into software * or otherwise create derivative works of the Spine Runtimes (collectively, * "Products"), provided that each user of the Products must obtain their own * Spine Editor license and redistribution of the Products in any form must * include this license and copyright notice. * * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *****************************************************************************/ #ifdef SPINE_UE4 #include "SpinePluginPrivatePCH.h" #endif #include <spine/PointAttachment.h> #include <spine/Bone.h> #include <spine/MathUtil.h> using namespace spine; RTTI_IMPL(PointAttachment, Attachment) PointAttachment::PointAttachment(const String &name) : Attachment(name), _x(0), _y(0), _rotation(0) { } void PointAttachment::computeWorldPosition(Bone &bone, float &ox, float &oy) { bone.localToWorld(_x, _y, ox, oy); } float PointAttachment::computeWorldRotation(Bone &bone) { float cos = MathUtil::cosDeg(_rotation); float sin = MathUtil::sinDeg(_rotation); float ix = cos * bone._a + sin * bone._b; float iy = cos * bone._c + sin * bone._d; return MathUtil::atan2(iy, ix) * MathUtil::Rad_Deg; } float PointAttachment::getX() { return _x; } void PointAttachment::setX(float inValue) { _x = inValue; } float PointAttachment::getY() { return _y; } void PointAttachment::setY(float inValue) { _y = inValue; } float PointAttachment::getRotation() { return _rotation; } void PointAttachment::setRotation(float inValue) { _rotation = inValue; } Attachment* PointAttachment::copy() { PointAttachment* copy = new(__FILE__, __LINE__) PointAttachment(getName()); copy->_x = _x; copy->_y = _y; copy->_rotation = _rotation; return copy; }
{ "pile_set_name": "Github" }
// Copyright 2013 The Go Authors. All rights reserved. // // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file or at // https://developers.google.com/open-source/licenses/bsd. package cayleyhttp import ( "net/http" "strings" ) // Octet types from RFC 2616. var octetTypes [256]octetType type octetType byte const ( isToken octetType = 1 << iota isSpace ) func init() { // OCTET = <any 8-bit sequence of data> // CHAR = <any US-ASCII character (octets 0 - 127)> // CTL = <any US-ASCII control character (octets 0 - 31) and DEL (127)> // CR = <US-ASCII CR, carriage return (13)> // LF = <US-ASCII LF, linefeed (10)> // SP = <US-ASCII SP, space (32)> // HT = <US-ASCII HT, horizontal-tab (9)> // <"> = <US-ASCII double-quote mark (34)> // CRLF = CR LF // LWS = [CRLF] 1*( SP | HT ) // TEXT = <any OCTET except CTLs, but including LWS> // separators = "(" | ")" | "<" | ">" | "@" | "," | ";" | ":" | "\" | <"> // | "/" | "[" | "]" | "?" | "=" | "{" | "}" | SP | HT // token = 1*<any CHAR except CTLs or separators> // qdtext = <any TEXT except <">> for c := 0; c < 256; c++ { var t octetType isCtl := c <= 31 || c == 127 isChar := 0 <= c && c <= 127 isSeparator := strings.IndexRune(" \t\"(),/:;<=>?@[]\\{}", rune(c)) >= 0 if strings.IndexRune(" \t\r\n", rune(c)) >= 0 { t |= isSpace } if isChar && !isCtl && !isSeparator { t |= isToken } octetTypes[c] = t } } // AcceptSpec describes an Accept* header. type AcceptSpec struct { Value string Q float64 } // ParseAccept parses Accept* headers. func ParseAccept(header http.Header, key string) (specs []AcceptSpec) { loop: for _, s := range header[key] { for { var spec AcceptSpec spec.Value, s = expectTokenSlash(s) if spec.Value == "" { continue loop } spec.Q = 1.0 s = skipSpace(s) if strings.HasPrefix(s, ";") { s = skipSpace(s[1:]) if !strings.HasPrefix(s, "q=") { continue loop } spec.Q, s = expectQuality(s[2:]) if spec.Q < 0.0 { continue loop } } specs = append(specs, spec) s = skipSpace(s) if !strings.HasPrefix(s, ",") { continue loop } s = skipSpace(s[1:]) } } return } func skipSpace(s string) (rest string) { i := 0 for ; i < len(s); i++ { if octetTypes[s[i]]&isSpace == 0 { break } } return s[i:] } func expectTokenSlash(s string) (token, rest string) { i := 0 for ; i < len(s); i++ { b := s[i] if (octetTypes[b]&isToken == 0) && b != '/' { break } } return s[:i], s[i:] } func expectQuality(s string) (q float64, rest string) { switch { case len(s) == 0: return -1, "" case s[0] == '0': q = 0 case s[0] == '1': q = 1 default: return -1, "" } s = s[1:] if !strings.HasPrefix(s, ".") { return q, s } s = s[1:] i := 0 n := 0 d := 1 for ; i < len(s); i++ { b := s[i] if b < '0' || b > '9' { break } n = n*10 + int(b) - '0' d *= 10 } return q + float64(n)/float64(d), s[i:] }
{ "pile_set_name": "Github" }
/* * 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 flash.tools.debugger.threadsafe; import flash.tools.debugger.NoResponseException; import flash.tools.debugger.NotConnectedException; import flash.tools.debugger.NotSuspendedException; import flash.tools.debugger.Session; import flash.tools.debugger.Value; import flash.tools.debugger.Variable; /** * Thread-safe wrapper for flash.tools.debugger.Value */ public class ThreadSafeValue extends ThreadSafeDebuggerObject implements Value { private Value fVal; private ThreadSafeValue(Object syncObj, Value val) { super(syncObj); fVal = val; } /** * Wraps a Value inside a ThreadSafeValue. If the passed-in Value * is null, then this function returns null. */ public static ThreadSafeValue wrap(Object syncObj, Value val) { if (val != null) return new ThreadSafeValue(syncObj, val); else return null; } /** * Wraps an array of Values inside an array of ThreadSafeValues. */ public static ThreadSafeValue[] wrapArray(Object syncObj, Value[] values) { ThreadSafeValue[] threadSafeValues = new ThreadSafeValue[values.length]; for (int i=0; i<values.length; ++i) { threadSafeValues[i] = wrap(syncObj, values[i]); } return threadSafeValues; } /** * Returns the raw Value underlying a ThreadSafeValue. */ public static Value getRaw(Value v) { if (v instanceof ThreadSafeValue) return ((ThreadSafeValue)v).fVal; else return v; } public static Object getSyncObject(Value v) { return ((ThreadSafeValue)v).getSyncObject(); } @Override public boolean equals(Object other) { if (other instanceof Value) return fVal.equals(getRaw((Value)other)); else return false; } public int getAttributes() { synchronized (getSyncObject()) { return fVal.getAttributes(); } } public String getClassName() { synchronized (getSyncObject()) { return fVal.getClassName(); } } public long getId() { synchronized (getSyncObject()) { return fVal.getId(); } } public int getMemberCount(Session s) throws NotSuspendedException, NoResponseException, NotConnectedException { synchronized (getSyncObject()) { return fVal.getMemberCount(ThreadSafeSession.getRaw(s)); } } public Variable getMemberNamed(Session s, String name) throws NotSuspendedException, NoResponseException, NotConnectedException { synchronized (getSyncObject()) { return ThreadSafeVariable.wrap(getSyncObject(), fVal.getMemberNamed(ThreadSafeSession.getRaw(s), name)); } } public Variable[] getMembers(Session s) throws NotSuspendedException, NoResponseException, NotConnectedException { synchronized (getSyncObject()) { return ThreadSafeVariable.wrapArray(getSyncObject(), fVal.getMembers(ThreadSafeSession.getRaw(s))); } } public int getType() { synchronized (getSyncObject()) { return fVal.getType(); } } public String getTypeName() { synchronized (getSyncObject()) { return fVal.getTypeName(); } } public Object getValueAsObject() { synchronized (getSyncObject()) { return fVal.getValueAsObject(); } } public String getValueAsString() { synchronized (getSyncObject()) { return fVal.getValueAsString(); } } public boolean isAttributeSet(int variableAttribute) { synchronized (getSyncObject()) { return fVal.isAttributeSet(variableAttribute); } } public String[] getClassHierarchy(boolean allLevels) { synchronized (getSyncObject()) { return fVal.getClassHierarchy(allLevels); } } @Override public String toString() { synchronized (getSyncObject()) { return fVal.toString(); } } public Variable[] getPrivateInheritedMembers() { synchronized (getSyncObject()) { return ThreadSafeVariable.wrapArray(getSyncObject(), fVal.getPrivateInheritedMembers()); } } public Variable[] getPrivateInheritedMemberNamed(String name) { synchronized (getSyncObject()) { return ThreadSafeVariable.wrapArray(getSyncObject(), fVal.getPrivateInheritedMemberNamed(name)); } } @Override public int getIsolateId() { synchronized (getSyncObject()) { return fVal.getIsolateId(); } } }
{ "pile_set_name": "Github" }
using Microsoft.Extensions.DependencyInjection; namespace Abp.ZeroCore.SampleApp.Core { public static class ServicesCollectionDependencyRegistrar { public static void Register(ServiceCollection services) { services.AddLogging(); services.AddAbpIdentity<Tenant, User, Role>() .AddAbpTenantManager<TenantManager>() .AddAbpEditionManager<EditionManager>() .AddAbpRoleManager<RoleManager>() .AddAbpUserManager<UserManager>() .AddAbpSignInManager<SignInManager>() .AddAbpLogInManager<LogInManager>() .AddAbpUserClaimsPrincipalFactory<UserClaimsPrincipalFactory>() .AddAbpSecurityStampValidator<SecurityStampValidator>() .AddPermissionChecker<PermissionChecker>() .AddAbpUserStore<UserStore>() .AddAbpRoleStore<RoleStore>() .AddFeatureValueStore<FeatureValueStore>() .AddDefaultTokenProviders(); } } }
{ "pile_set_name": "Github" }
/** * \author Tilen Majerle * \email tilen@majerle.eu * \website https://majerle.eu/projects/gsm-at-commands-parser-for-embedded-systems * \license MIT * \version 0.5.0 * \brief GSM Library * \verbatim ---------------------------------------------------------------------- Copyright (c) 2016 Tilen Majerle Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ---------------------------------------------------------------------- \endverbatim */ #ifndef GSM_H #define GSM_H 050 /* C++ detection */ #ifdef __cplusplus extern "C" { #endif /** * \defgroup GSM * \brief Platform independent, written in ANSII C, GSM AT parser library for SIMcom modules * \{ */ #include "stdlib.h" #include "string.h" #include "stdint.h" #include "stdio.h" /* Proto threads */ #include "pt/pt.h" /* GSM configuration */ #include "gsm_config.h" /* Buffer implementation */ #include "buffer.h" /* GSM Low-Level drivers */ #include "gsm_ll.h" /* Backward compatibility */ #if !defined(GSM_HTTP) #define GSM_HTTP 1 #endif #if !defined(GSM_FTP) #define GSM_FTP 1 #endif #if !defined(GSM_PHONEBOOK) #define GSM_PHONEBOOK 1 #endif #if !defined(GSM_CALL) #define GSM_CALL 1 #endif #if !defined(GSM_SMS) #define GSM_SMS 1 #endif /** * @defgroup GSM_Macros * @brief Library defines * @{ */ #define gvol volatile #define gstatic static /* Configuration defines */ /** * \} */ /** * \defgroup GSM_Typedefs * \brief Library Typedefs * \{ */ /** * \brief GSM library result enumeration */ typedef enum _GSM_Result_t { gsmOK = 0x00, /*!< OK status */ gsmERROR, /*!< Error status */ gsmBUSY, /*!< GSM is busy right now */ gsmPARERROR, /*!< Parameter errors */ gsmTIMEOUT, /*!< Timeout occurred */ gsmSENDFAIL, /*!< Send data failed on connection */ gsmSYSERROR, /*!< Syscall error */ gsmLLERROR, /*!< Error in Low-Level processing */ gsmSIMNOTREADYERROR, /*!< SIM is not ready to operate */ gsmENTERTEXTMODEERROR, /*!< Error trying to enter text mode for SMS */ gsmSIMMEMORYERROR, /*!< Error trying to select SMS mode */ gsmNETWORKNOTREGISTEREDERROR, /*!< Device is not connected to network and is not searching for network anymore */ gsmNETWORKNOTREGISTEREDSEARCHINERROR, /*!< Device is not connected to network, but is searching for network. You might wait a little time when this status is returned */ gsmNETWORKREGISTRATIONDENIEDERROR, /*!< Device found network but registration to it has been denied */ gsmNETWORKERROR, } GSM_Result_t; /** * \brief Call direction enumeration */ typedef enum _GSM_CallDir_t { GSM_CallDir_MO = 0x00, /*!< Call direction is Mobile Originated, outgoing call */ GSM_CallDir_MT = 0x01 /*<! Call direction is Mobile Terminated, incoming call*/ } GSM_CallDir_t; /** * \brief Call type enumeration */ typedef enum _GSM_CallType_t { GSM_CallType_Voice = 0x00, /*!< Call type is voice */ GSM_CallType_Data = 0x01, /*!< Call type is data */ GSM_CallType_Fax = 0x02 /*!< Call type is fax */ } GSM_CallType_t; /** * \brief Call status enumeration */ typedef enum _GSM_CallState_t { GSM_CallState_Active = 0x00, /*!< Call is active, we have answered to someone or someone has answer to our call */ GSM_CallState_Held = 0x01, /*<! Call is held */ GSM_CallState_Dialing = 0x02, /*<! Call is dialing, we are calling someone */ GSM_CallState_Alerting = 0x03, /*<! Call is alerting */ GSM_CallState_Incoming = 0x04, /*<! Call is incoming, waiting our reaction */ GSM_CallState_Waiting = 0x05, /*<! Call is waiting */ GSM_CallState_Disconnect = 0x06 /*<! Call is disconnected, call is finished */ } GSM_CallState_t; /** * \brief SMS memory enumeration * \note This is currently not used and is for future purpose */ typedef enum _GSM_SMS_Memory_t { GSM_SMS_Memory_SM, GSM_SMS_Memory_BM, GSM_SMS_Memory_SE, GSM_SMS_Memory_ME } GSM_SMS_Memory_t; /** * \brief SMS mass delete enumeration */ typedef enum _GSM_SMS_MassDelete_t { GSM_SMS_MassDelete_Read = 0x00, /*!< Delete all read SMS messages */ GSM_SMS_MassDelete_Unread, /*!< Delete all unread SMS messages */ GSM_SMS_MassDelete_Sent, /*!< Delete all sent SMS messages */ GSM_SMS_MassDelete_Unsent, /*!< Delete all unset SMS messages */ GSM_SMS_MassDelete_Inbox, /*!< Delete all received SMS messages */ GSM_SMS_MassDelete_All /*!< Delete all SMS messages */ } GSM_SMS_MassDelete_t; /** * \brief SMS read type enumeration */ typedef enum _GSM_SMS_ReadType_t { GSM_SMS_ReadType_ALL, /*!< List all SMS entries */ GSM_SMS_ReadType_READ, /*!< List read entries only */ GSM_SMS_ReadType_UNREAD, /*!< List unread entries only */ GSM_SMS_ReadType_SENT, /*!< Read stored sent messages */ GSM_SMS_ReadType_UNSENT /*!< Read stored unsent messages */ } GSM_SMS_ReadType_t; /** * \brief SIM card informations */ typedef enum _GSM_CPIN_t { GSM_CPIN_Unknown = 0x00, /*!< Default value */ GSM_CPIN_Ready, /*!< SIM is ready to use */ GSM_CPIN_SIM_PIN, /*!< SIM is waiting for PIN number */ GSM_CPIN_SIM_PUK, /*!< SIM is blocked and is waiting for PUK number */ GSM_CPIN_PH_SIM_PIN, GSM_CPIN_PH_SIM_PUK, GSM_CPIN_SIM_PIN2, GSM_CPIN_SIM_PUK2 } GSM_CPIN_t; /** * \brief Time structure */ typedef struct _GSM_Date_t { uint8_t Day; /*!< Day in month, from 1 to 31 */ uint8_t Month; /*!< Month in a year, from 1 to 12 */ uint16_t Year; /*!< Year with included thousands */ } GSM_Date_t; /** * \brief Time structure */ typedef struct _GSM_Time_t { uint8_t Hours; /*!< Hours in format 00-24 */ uint8_t Minutes; /*!< Minutes */ uint8_t Seconds; /*!< Seconds */ } GSM_Time_t; /** * \brief Date and time structure */ typedef struct _GSM_DateTime_t { GSM_Date_t Date; /*!< Date data */ GSM_Time_t Time; /*!< Time data */ } GSM_DateTime_t; /** * \brief SMS structure for send message */ typedef struct _GSM_SMS_t { const char* Number; /*!< Pointer to constant string for number */ const char* Data; /*!< Pointer to constant data array */ uint16_t SentSMSMemNum; /*!< Memory number for sent SMS */ } GSM_SMS_t; /** * \brief Call information structure * \note Used when call status changes to notify user */ typedef struct _GSM_CallInfo_t { uint8_t ID; /*!< Call identification number, 0 - 7 */ GSM_CallDir_t Dir; /*!< Call direction */ GSM_CallState_t State; /*!< Call state */ GSM_CallType_t Type; /*!< Call type */ char Number[16]; /*!< Call phone number */ uint8_t IsMultiparty; /*!< Call multiparty status */ uint8_t AddressType; /*!< Call address type */ char Name[20]; /*!< Name in phonebook, if exists for selected number */ } GSM_CallInfo_t; /** * \brief SMS information structure * \note Used when new SMS is received to notify user */ typedef struct _GSM_SmsInfo_t { GSM_SMS_Memory_t Memory; /*!< Memory where received SMS was saved */ uint16_t Position; /*!< Position where SMS was stored in memory */ union { struct { uint8_t Received:1; /*!< Do we have new SMS info on this structure and was not yet checked */ uint8_t Used:1; /*!< Memory used indication */ uint8_t UsedByUser:1; /*!< Is this structure used by user? */ } F; uint8_t Value; } Flags; /*!< Structure flags management */ } GSM_SmsInfo_t; /** * \brief SMS item */ typedef struct _GSM_SMS_Entry_t { uint16_t Position; /*!< Position number in memory */ GSM_SMS_Memory_t Memory; /*!< Memory type used for SMS */ char Data[GSM_SMS_MAX_LENGTH]; /*!< Actual SMS data in text mode */ uint8_t DataLen; /*!< Length of SMS data */ char Name[20]; /*!< Name of sender if exists in phonebook */ char Number[20]; /*!< Sender phone number */ GSM_DateTime_t DateTime; /*!< SMS date and time sent/received */ } GSM_SMS_Entry_t; /** * \brief Phonebook entry item */ typedef struct _GSM_PB_Entry_t { uint16_t Index; /*!< Phonebook index number */ char Name[20]; /*!< Phonebook saved display name */ char Number[20]; /*!< Actual phone number */ } GSM_PB_Entry_t; /** * \brief Connection type enumeration */ typedef enum _GSM_CONN_Type_t { GSM_CONN_Type_TCP, /*!< Create TCP connection */ GSM_CONN_Type_UDP /*!< Create UDP connection */ } GSM_CONN_Type_t; /** * \brief Connection over SSL selection */ typedef enum _GSM_CONN_SSL_t { GSM_CONN_SSL_Disable = 0x00, /*!< Disable TCP over SSL */ GSM_CONN_SSL_Enable = 0x01 /*!< Enable TCP over SSL */ } GSM_CONN_SSL_t; /** * \brief Connection structure for GSM */ typedef struct _GSM_CONN_t { uint8_t ID; /*!< Connection identification */ uint8_t* ReceiveData; /*!< Pointer to data array for receive or send */ uint16_t BytesToRead; /*!< Bytes to read from receive at a time, selected by user on function call */ uint16_t BytesRead; /*!< Bytes actually read from device, number of bytes we actually read in packet */ uint32_t BytesReadTotal; /*!< Total number of bytes we already read from response */ uint16_t BytesReadRemaining; /*!< Number of bytes we have to read in current packet */ uint16_t BytesRemaining; /*!< Number of bytes remaining to read in module buffer */ uint16_t ReadTimeout; /*!< Timeout before checking for new data when reading */ union { struct { uint8_t Active:1; /*!< Connection active flag */ uint8_t RxGetReceived:1; /*!< RXGET was received waiting to read data */ uint8_t CallGetReceived:1; /*!< RXGET was received, notify user about new data */ uint8_t CallConnClosed:1; /*!< Connection was closed by remote server */ } F; uint8_t Value; /*!< Value containing all the flags in single memory */ } Flags; /*!< Union with all the listed flags */ } GSM_CONN_t; /** * \brief HTTP supported request methods */ typedef enum _GSM_HTTP_Method_t { GSM_HTTP_Method_GET = 0x00, /*!< HTTP method GET */ GSM_HTTP_Method_POST = 0x01, /*!< HTTP method POST */ GSM_HTTP_Method_HEAD = 0x02 /*!< HTTP method HEAD */ } GSM_HTTP_Method_t; /** * \brief HTTP structure for GSM */ typedef struct _GSM_HTTP_t { GSM_HTTP_Method_t Method; /*!< HTTP method */ const char* TMP; /*!< Pointer to URL to use/CONTENT to send */ uint16_t Code; /*!< HTTP response code */ uint8_t* Data; /*!< Pointer to read/write data array */ uint32_t DataLength; /*!< Length of data array in units of bytes */ uint32_t BytesReceived; /*!< Number of total bytes received by HTTP response from server to GSM */ uint32_t BytesReadTotal; /*!< Total number of bytes we already read from GSM module HTTP response */ uint16_t BytesToRead; /*!< Bytes to read from receive at a time, selected by user on function call */ uint32_t BytesRead; /*!< Actual number of bytes read in last read procedure */ uint32_t BytesReadRemaining; /*!< Number of bytes remaining to read in current read procedure */ } GSM_HTTP_t; /** * \brief HTTP over SSL selection */ typedef enum _GSM_HTTP_SSL_t { GSM_HTTP_SSL_Disable = 0x00, /*!< Disable SSL usage for HTTP */ GSM_HTTP_SSL_Enable = 0x01 /*!< Enable SSL usage for HTTP */ } GSM_HTTP_SSL_t; /** * \brief FTP structure for GSM */ typedef struct _GSM_FTP_t { uint8_t Mode; /*!< FTP usage mode (execute, read) */ uint8_t ErrorCode; /*!< Error code number */ uint8_t* Data; /*!< Pointer to read/write data array */ uint32_t BytesToProcess; /*!< Bytes to process (read/write) at a time, selected by user on function call */ uint32_t BytesRead; /*!< Bytes actually read from device, number of bytes we actually read in packet */ uint32_t BytesReadRemaining; /*!< Number of bytes remaining to read in current read procedure */ uint32_t BytesProcessedTotal; /*!< Total number of bytes read in FTP session */ uint32_t MaxBytesToPut; /*!< Maximal number of bytes we can put on FTPPUT command */ union { struct { uint8_t DataAvailable:1; /*!< Set to 1 when data available to read */ uint8_t DownloadActive:1; /*!< Set to 1 when download session is active */ } F; uint8_t Value; } Flags; /*!< FTP Flags */ } GSM_FTP_t; /** * \brief FTP connection mode */ typedef enum _GSM_FTP_Mode_t { GSM_FTP_Mode_Active = 0x00, /*!< Active FTP mode */ GSM_FTP_Mode_Passive = 0x01 /*!< Passive FTP mode */ } GSM_FTP_Mode_t; /** * \brief FTP over SSL selection */ typedef enum _GSM_FTP_SSL_t { GSM_FTP_SSL_Disable = 0x00, /*!< Do not use FTP over SSL */ GSM_FTP_SSL_Implicit = 0x01, /*!< Use FTP over SSL in implicit mode */ GSM_FTP_SSL_Explicit = 0x02 /*!< Use FTP over SSL in explicit mode */ } GSM_FTP_SSL_t; /** * \brief FTP upload mode */ typedef enum _GSM_FTP_UploadMode_t { GSM_FTP_UploadMode_Append = 0x00, /*!< Append file already existing on server */ GSM_FTP_UploadMode_StoreUnique = 0x01, GSM_FTP_UploadMode_Store = 0x02 } GSM_FTP_UploadMode_t; /** * \brief GSM network status */ typedef enum _GSM_NetworkStatus_t { GSM_NetworkStatus_NotRegistered = 0x00, /*!< Not registered and not searching */ GSM_NetworkStatus_RegisteredHome = 0x01, /*!< Registered in home network */ GSM_NetworkStatus_Searching = 0x02, /*!< Searching for network */ GSM_NetworkStatus_RegistrationDenied = 0x03, /*!< Registration has been denied */ GSM_NetworkStatus_Unknown = 0x04, /*!< Unknown status */ GSM_NetworkStatus_RegisteredRoaming = 0x05 /*!< Registered and roaming */ } GSM_NetworkStatus_t; /** * \brief GSM GPS location over GPRS */ typedef struct _GSM_GPS_t { uint16_t Error; /*!< Error number if exists */ float Latitude; /*!< GPS latitude location */ float Longitude; /*!< GPS longitude location */ GSM_Date_t Date; /*!< Date of GPS, UTC */ GSM_Time_t Time; /*!< Time of GPS, UTC */ } GSM_GPS_t; /** * \brief Battery informations */ typedef struct _GSM_Battery_t { uint8_t Charging; /*!< Status indicating battery is charging */ uint8_t Percentage; /*!< Battery percentage */ uint16_t Voltage; /*!< Battery voltage in units of millivolts */ } GSM_Battery_t; /** * \brief Network operator selection mode */ typedef enum _GSM_OperatorMode_t { GSM_OperatorMode_Auto = 0x00, /*!< Automatic network selection */ GSM_OperatorMode_Manual = 0x01, /*!< Manual network selection */ GSM_OperatorMode_ManualAuto = 0x04, /*!< Manual first, if it fails, use automatic */ } GSM_OperatorMode_t; /** * \brief Network operator reading mode */ typedef enum _GSM_OperatorFormat_t { GSM_OperatorFormat_LongName = 0x00, /*!< Operator name in long alphanumeric format */ GSM_OperatorFormat_ShortName = 0x01, /*!< Operator name in short alphanumeric format */ GSM_OperatorFormat_Number = 0x02 /*!< Operator name in number format */ } GSM_OperatorFormat_t; /** * \brief Network operator status */ typedef enum _GSM_OperatorStatus_t { GSM_OperatorStatus_Unknown = 0x00, /*!< Operator network status is unknown */ GSM_OperatorStatus_Available = 0x01, /*!< Operator network is available to use */ GSM_OperatorStatus_Current = 0x02, /*!< Operator network is currently in use */ GSM_OperatorStatus_Forbidden = 0x03 /*!< Operator network is forbidden to connect */ } GSM_OperatorStatus_t; /** * \brief Network operator structure */ typedef struct _GSM_OP_t { GSM_OperatorStatus_t Status; /*!< Network status */ char LongName[20]; /*!< Network long name */ char ShortName[20]; /*!< Network short name */ char Number[10]; /*!< Network number format name */ } GSM_OP_t; /** * \brief Phone functionality */ typedef enum _GSM_Func_t { GSM_Func_Min = 0x00, /*!< Minimal phone functionality */ GSM_Func_Full = 0x01, /*!< Full phone functionality */ GSM_Func_Disable = 0x04 /*!< RF circuit disabled, airplane mode */ } GSM_Func_t; /** * \brief Event enumeration for callback */ typedef enum _GSM_Event_t { gsmEventIdle = 0x00, /*!< Stack went idle */ gsmEventDataReceived, /*!< A new data received on connection */ gsmEventDataSent, /*!< Data were sent on connection */ gsmEventDataSentError, /*!< Data sent error */ #if GSM_CALL gsmEventCallCLCC, /*!< CLCC Call info was received with call data */ gsmEventCallRING, /*!< RING was received on call */ #endif /* GSM_CALL */ #if GSM_SMS gsmEventSMSCMTI, /*!< SMS info was received */ #endif /* GSM_SMS */ gsmEventGPRSAttached, /*!< GPRS has been attached */ gsmEventGPRSAttachError, /*!< Error while trying to attach GPRS */ gsmEventGPRSDetached, /*!< GPRS has been detached */ gsmEventUVWarning, /*!< Under voltage warning received */ gsmEventUVPowerDown, /*!< Under voltage power down */ } GSM_Event_t; /** * \brief Parameters for callback processing */ typedef struct _GSM_EventParams_t { const void* CP1; /*!< Constant void pointer number 1 */ const void* CP2; /*!< Constant void pointer number 2 */ uint32_t UI; /*!< Unsigned integer value */ } GSM_EventParams_t; /** * \brief Callback function prototype */ typedef int (*GSM_EventCallback_t)(GSM_Event_t, GSM_EventParams_t*); /** * \brief GSM structure */ typedef struct _GSM_t { gvol uint32_t Time; /*!< Current time in units of milliseconds */ gvol GSM_Result_t RetVal; /*!< Return value */ /*! Low-Level management */ GSM_LL_t LL; /*!< Structure for Low-Level communication */ /*!< Active command informations */ gvol uint16_t ActiveCmd; /*!< Current active command for execution */ gvol uint16_t ActiveCmdSaved; /*!< Value of saved active CMD when necessary to change active command while processing one. */ const char* gvol ActiveCmdResp; /*!< Pointer to active command response we are waiting for */ gvol uint32_t ActiveCmdStart; /*!< Time when new command started with execution */ gvol GSM_Result_t ActiveResult; /*!< Result to return from function */ gvol uint32_t ActiveCmdTimeout; /*!< Timeout in units of MS for active command to finish */ gvol GSM_NetworkStatus_t NetworkStatus; /*!< Network status enumeration */ /*!< SIM status */ GSM_CPIN_t CPIN; /*!< SIM status */ /*!< Phone functionality */ GSM_Func_t Func; /*!< Phone functionality */ /*!< Network options */ uint8_t IP[4]; /*!< Device IP address when connected to network */ /*!< Plain connections check */ GSM_CONN_t* Conns[6]; /*!< Array of pointers to connections */ #if GSM_SMS /*!< SMS management */ GSM_SMS_t SMS; /*!< SMS Send object */ GSM_SmsInfo_t SmsInfos[GSM_MAX_RECEIVED_SMS_INFO]; /*!< Received SMS info object */ #endif /* GSM_SMS */ #if GSM_CALL /*!< Call management */ GSM_CallInfo_t CallInfo; /*!< Call info object */ #endif /* GSM_CALL */ #if GSM_HTTP /*!< HTTP */ GSM_HTTP_t HTTP; /*!< HTTP related structure */ #endif #if GSM_FTP /*!< FTP */ GSM_FTP_t FTP; /*!< FTP related structure */ #endif #if GSM_RTOS /*!< RTOS support */ GSM_RTOS_SYNC_t Sync; /*!< RTOS Synchronization object */ #endif /*!< Flags management */ union { struct { uint8_t IsBlocking:1; /*!< Set to 1 when function is in blocking execution */ uint8_t Call_Idle:1; /*!< Set to 1 when we have to call IDLE callback */ uint8_t PIN_Ok:1; /*!< Set to 1 when PIN is entered correct */ uint8_t PIN_Error:1; /*!< Set to 1 when PIN is not connect */ uint8_t PUK_Ok:1; /*!< Set to 1 when PUK is entered correct */ uint8_t PUK_Error:1; /*!< Set to 1 when PUK is not correct */ #if GSM_SMS uint8_t SMS_SendOk:1; /*!< SMS was successfully sent */ uint8_t SMS_SendError:1; /*!< We got an error trying to send SMS */ uint8_t SMS_Read_Data:1; /*!< Set to 1 when we are reading actual SMS data */ uint8_t SMS_CMTI_Received:1; /*!< Set to 1 when CMTI SMS info is received and callback should be called */ #endif /* GSM_SMS */ #if GSM_CALL uint8_t CALL_CLCC_Received:1; /*!< Set to 1 when CLCC call info is received and callback should be called */ uint8_t CALL_RING_Received:1; /*!< Set to 1 when RING is received and callback should be called */ #endif /* GSM_CALL */ uint8_t ReadSingleLineDataRespond:1; /*!< Set to 1 when we have to read response from command like AT+CGMI. Data is returned as plain text without any special command before */ uint8_t CLIENT_Read_Data:1; /*!< Set to 1 when we are reading raw data from client response */ #if GSM_HTTP uint8_t HTTP_Read_Data:1; /*!< Set to 1 when reading data from HTTP response */ #endif /* GSM_HTTP */ #if GSM_FTP uint8_t FTP_Read_Data:1; /*!< Set to 1 when reading data from FTP response */ #endif /* GSM_FTP */ uint8_t Call_GPRS_Attached:1; /*!< Set to 1 when GPRS is attached sucessfully */ uint8_t Call_GPRS_Attach_Error:1; /*!< Set to 1 when GPRS was not attached */ uint8_t Call_GPRS_Detached:1; /*!< Set to 1 when GPRS was detached */ uint8_t Call_UV_Warn:1; /*!< Set to 1 when undervoltage warning received */ uint8_t Call_UV_PD:1; /*!< Set to 1 when undervoltage power down received */ uint8_t COPS_Read_Operators:1; /*!< Set to 1 when we should process incoming COPS data to read networks from scan */ uint8_t LastOperationStatus:1; } F; uint32_t Value; /*!< Value containing all the flags in single memory */ } Flags; /*!< Union holding all the required flags */ GSM_EventCallback_t Callback; /*!< Callback function */ GSM_EventParams_t CallbackParams; /*!< Callback parameters */ union { struct { uint8_t RespOk:1; /*!< OK message response */ uint8_t RespError:1; /*!< Error message response */ uint8_t RespTimeout:1; /*!< Timeout detected */ uint8_t RespBracket:1; /*!< Bracket received (SMS messages) */ uint8_t RespConnectOk:1; /*!< n, CONNECT OK was returned from device */ uint8_t RespConnectFail:1; /*!< n, CONNECT FAIL was returned from device */ uint8_t RespConnectAlready:1; /*!< n, ALREADY CONNECTED was returned from device */ uint8_t RespCloseOk:1; /*!< n, CLOSE OK was returned from device */ uint8_t RespSendOk:1; /*!< n, SEND OK was returned from device */ uint8_t RespSendFail:1; /*!< n, SEND FAIL was returned from device */ uint8_t RespCallReady:1; /*!< Set to 1 when call is ready */ uint8_t RespSMSReady:1; /*!< Set to 1 when SNS is ready */ #if GSM_HTTP uint8_t RespHttpAction:1; /*!< +HTTPACTION received and already parsed */ uint8_t RespDownload:1; /*!< DOWNLOAD received for download HTTP data */ #endif /* GSM_HTTP */ #if GSM_FTP uint8_t RespFtpGet:1; /*!< Response for FTPGET was received */ uint8_t RespFtpPut:1; /*!< Response for FTPPUT was received */ uint8_t RespFtpUploadReady:1; /*!< Response for FTPPUT was received for uploading data available */ #endif /* GSM_FTP */ } F; uint32_t Value; /*!< Value containing all the flags in single memory */ } Events; /*!< Union holding all the required events for library internal processing */ } GSM_t; /** * @} */ /** * \defgroup GSM_Functions * \brief Library Functions * \{ */ /** * \brief Initializes GSM stack and prepares low-level layer and system calls when necessary * \param[in,out] *GSM: Pointer to working \ref GSM_t structure * \param[in] *pin: Pointer to pin in string format to be used if SIM is inserted and not ready * \param[in] baudrate: Baudrate for UART communication * \param[in] callback: Pointer to callback function to be called on different events. * Use NULL if you don't need callback * \retval Member of \ref GSM_Result_t enumeration */ GSM_Result_t GSM_Init(gvol GSM_t* GSM, const char* pin, uint32_t baudrate, GSM_EventCallback_t callback); /** * \brief Checks received data and makes action according to selected action * \note When in <b>RTOS</b> mode, it is recommended to use this function in separate thread only for GSM processing * * \note When in <b>ASYNC</b> mode only (without <b>RTOS</b>), it is recommended to use this function in 1ms interrupt handler for processing incoming data * * \note When not in <b>RTOS</b> and <b>ASYNC</b> mode, you have to call this function in main while loop as faster as possible. * \param[in,out] *GSM: Pointer to working \ref GSM_t structure * \retval Member of \ref GSM_Result_t enumeration */ GSM_Result_t GSM_Update(gvol GSM_t* GSM); /** * \brief Checks for flags and calls callback functions for user. * \note When in <b>RTOS</b> or <b>ASYNC</b> mode, user has to call this function manually. * \note When not in <b>RTOS</b> AND <b>ASYNC</b> mode, this function is called from GSM library itself and can be left by user. * * \param[in,out] *GSM: Pointer to working \ref GSM_t structure * \retval Member of \ref GSM_Result_t enumeration */ GSM_Result_t GSM_ProcessCallbacks(gvol GSM_t* GSM); /** * \brief Update time for GSM stack * \note This function must be called periodically with fixed frequency * \param[in,out] *GSM: Pointer to working \ref GSM_t structure * \param[in] millis: Number of milliseconds time is increased from last function call * \retval Member of \ref GSM_Result_t enumeration */ GSM_Result_t GSM_UpdateTime(gvol GSM_t* GSM, uint32_t millis); /** * \brief Gets last return status from stack * \note Use this function in callback function to detect returned status of last operation * \param[in,out] *GSM: Pointer to working \ref GSM_t structure * \retval Member of \ref GSM_Result_t enumeration */ GSM_Result_t GSM_GetLastReturnStatus(gvol GSM_t* GSM); /** * \brief Waits for stack to be ready inside desired milliseconds * \param[in,out] *GSM: Pointer to working \ref GSM_t structure * \param[in] timeout: Timeout to wait before returning in units of milliseconds * \retval Member of \ref GSM_Result_t enumeration */ GSM_Result_t GSM_WaitReady(gvol GSM_t* GSM, uint32_t timeout); /** * \brief Delay for specific amount of time * \note When not in ASYNC or RTOS mode, this function will also update stack for amount of timeout time * \param[in,out] *GSM: Pointer to working \ref GSM_t structure * \param[in] timeout: Timeout to delay in units of milliseconds * \retval Member of \ref GSM_Result_t enumeration */ GSM_Result_t GSM_Delay(gvol GSM_t* GSM, uint32_t timeout); /** * \brief Checks if stack is ready * \note This checks only flag in library. When working with RTOS, this function may not return actual value * \param[in,out] *GSM: Pointer to working \ref GSM_t structure * \retval Member of \ref GSM_Result_t enumeration */ GSM_Result_t GSM_IsReady(gvol GSM_t* GSM); /** * \brief Data were received from UART and should be transfered to GSM stack * \note This function should be called from UART RX interrupt for further processing * \param[in] *ch: Pointer to character or array of characters * \param[in] count: Number of characters received from UART * \retval Number of characters added to GSM stack */ uint32_t GSM_DataReceived(uint8_t* ch, uint32_t count); /** * \defgroup FUNC_API * \brief Phone functionality related functions * \{ */ /** * \brief Sets phone functionality * \param[in,out] *GSM: Pointer to working \ref GSM_t structure * \param[in] func: Phone functionality selection. This parameter can be a value of \ref GSM_Func_t enumeration * \param[in] blocking: Status whether this function should be blocking to check for response * \retval Member of \ref GSM_Result_t enumeration */ GSM_Result_t GSM_FUNC_Set(gvol GSM_t* GSM, GSM_Func_t func, uint32_t blocking); /** * \brief Gets phone functionality * \param[in,out] *GSM: Pointer to working \ref GSM_t structure * \param[out] *func: Pointer to \ref GSM_Func_t enumeration to save data to * \param[in] blocking: Status whether this function should be blocking to check for response * \retval Member of \ref GSM_Result_t enumeration */ GSM_Result_t GSM_FUNC_Get(gvol GSM_t* GSM, GSM_Func_t* func, uint32_t blocking); /** * \} */ /** * \defgroup INFO_API * \brief Informations based functions * \{ */ /** * \brief Get manufacturer from SIM device * \param[in,out] *GSM: Pointer to working \ref GSM_t structure * \param[out] *str: Pointer to string array to save menufacturer name * \param[in] length: Length of string array * \param[in] blocking: Status whether this function should be blocking to check for response * \retval Member of \ref GSM_Result_t enumeration */ GSM_Result_t GSM_INFO_GetManufacturer(gvol GSM_t* GSM, char* str, uint32_t length, uint32_t blocking); /** * \brief Get model name from SIM device * \param[in,out] *GSM: Pointer to working \ref GSM_t structure * \param[out] *str: Pointer to string array to save model name * \param[in] length: Length of string array * \param[in] blocking: Status whether this function should be blocking to check for response * \retval Member of \ref GSM_Result_t enumeration */ GSM_Result_t GSM_INFO_GetModel(gvol GSM_t* GSM, char* str, uint32_t length, uint32_t blocking); /** * \brief Get revision from SIM device * \param[in,out] *GSM: Pointer to working \ref GSM_t structure * \param[out] *str: Pointer to string array to save revision name * \param[in] length: Length of string array * \param[in] blocking: Status whether this function should be blocking to check for response * \retval Member of \ref GSM_Result_t enumeration */ GSM_Result_t GSM_INFO_GetRevision(gvol GSM_t* GSM, char* str, uint32_t length, uint32_t blocking); /** * \brief Get serial number (IMEI) from SIM device * \param[in,out] *GSM: Pointer to working \ref GSM_t structure * \param[out] *str: Pointer to string array to save serial number * \param[in] length: Length of string array * \param[in] blocking: Status whether this function should be blocking to check for response * \retval Member of \ref GSM_Result_t enumeration */ GSM_Result_t GSM_INFO_GetSerialNumber(gvol GSM_t* GSM, char* str, uint32_t length, uint32_t blocking); /** * \brief Get AT software info on GSM device * \param[in,out] *GSM: Pointer to working \ref GSM_t structure * \param[out] *rev: Pointer to array of string to save revision version. * Length of array should be at least 30 bytes but mostly depends on actual ESP8266 AT software. * Use NULL if you don't need revision version * \param[in] blocking: Status whether this function should be blocking to check for response * \retval Member of \ref ESP_Result_t enumeration */ GSM_Result_t GSM_INFO_GetSoftwareInfo(gvol GSM_t* GSM, char* rev, uint32_t blocking); /** * \brief Get battery status informations * \param[in,out] *GSM: Pointer to working \ref GSM_t structure * \param[out] *bat: Pointer to empty \ref GSM_Battery_t structure to save response * \param[in] blocking: Status whether this function should be blocking to check for response * \retval Member of \ref ESP_Result_t enumeration */ GSM_Result_t GSM_INFO_GetBatteryInfo(gvol GSM_t* GSM, GSM_Battery_t* bat, uint32_t blocking); /** * \brief Get signal strength information from network * \param[in,out] *GSM: Pointer to working \ref GSM_t structure * \param[out] *rssi: Pointer to variable to store information about RSSI into. * Value of variable is between 0-31 when valid (0 = worst, 32 = best) info or 99 when RSSI is not available * \param[in] blocking: Status whether this function should be blocking to check for response * \retval Member of \ref ESP_Result_t enumeration */ GSM_Result_t GSM_INFO_GetSignalStrength(gvol GSM_t* GSM, uint8_t* rssi, uint32_t blocking); /** * \} */ /** * \defgroup OPERATOR_API * \brief Network operator based functions * \{ */ /** * \brief Scan for network operators * \param[in,out] *GSM: Pointer to working \ref GSM_t structure * \param[out] *ops: Pointer to empty array of \ref GSM_OP_t structures to save received data * \param[in] optr: Size of ops array in units of \ref GSM_OP_t structures * \param[out] *opr: Pointer to save number of detected network operators in array * \param[in] blocking: Status whether this function should be blocking to check for response * \retval Member of \ref ESP_Result_t enumeration */ GSM_Result_t GSM_OP_Scan(gvol GSM_t* GSM, GSM_OP_t* ops, uint16_t optr, uint16_t* opr, uint32_t blocking); /** * \brief Get current operator and type of connection * \param[in,out] *GSM: Pointer to working \ref GSM_t structure * \param[out] *mode: Pointer to empty \ref GSM_OperatorMode_t enumeration store operator connection mode. * Set to NULL if value is not relevant for usage * \param[out] *format: Pointer to empty \ref GSM_OperatorFormat_t enumeration store operator name format. * Set to NULL if value is not relevant for usage * \param[out] *name: Pointer to string to save current operator name. * Set to NULL if value is not relevant for usage * When name is empty, device is not connected to network. * \param[in] blocking: Status whether this function should be blocking to check for response * \retval Member of \ref ESP_Result_t enumeration */ GSM_Result_t GSM_OP_Get(gvol GSM_t* GSM, GSM_OperatorMode_t* mode, GSM_OperatorFormat_t* format, char* name, uint32_t blocking); /** * \brief Set current operator and type of connection * \param[in,out] *GSM: Pointer to working \ref GSM_t structure * \param[in] mode: Module connection mode to network. This parameter can be a value of \ref GSM_OperatorMode_t enumeration. * When automatic mode is used, only this parameter is required * \param[in] format: Format of network name. This parameter can be a value of \ref GSM_OperatorFormat_t enumeration * \param[in] *name: Pointer to network name. Name must be in the same format as used in format parameter * \param[in] blocking: Status whether this function should be blocking to check for response * \retval Member of \ref ESP_Result_t enumeration */ GSM_Result_t GSM_OP_Set(gvol GSM_t* GSM, GSM_OperatorMode_t mode, GSM_OperatorFormat_t format, char* name, uint32_t blocking); /** * \} */ /** * \defgroup PIN_API * \brief PIN/PUK based functions * \{ */ /** * \brief Enter PIN code for SIM card * \param[in,out] *GSM: Pointer to working \ref GSM_t structure * \param[in] *pin: Pointer to PIN in string format * \param[in] blocking: Status whether this function should be blocking to check for response * \retval Member of \ref GSM_Result_t enumeration */ GSM_Result_t GSM_PIN_Enter(gvol GSM_t* GSM, const char* pin, uint32_t blocking); /** * \brief Remove PIN code for SIM card * \param[in,out] *GSM: Pointer to working \ref GSM_t structure * \param[in] *current_pin: Pointer to current PIN in string format * \param[in] blocking: Status whether this function should be blocking to check for response * \retval Member of \ref GSM_Result_t enumeration */ GSM_Result_t GSM_PIN_Remove(gvol GSM_t* GSM, const char* current_pin, uint32_t blocking); /** * \brief Set new PIN for SIM * \param[in,out] *GSM: Pointer to working \ref GSM_t structure * \param[in] *new_pin: Pointer to new PIN in string format * \param[in] blocking: Status whether this function should be blocking to check for response * \retval Member of \ref GSM_Result_t enumeration */ GSM_Result_t GSM_PIN_Add(gvol GSM_t* GSM, const char* new_pin, uint32_t blocking); /** * \brief Unlock SIM by entering PUK code and new PIN * \param[in,out] *GSM: Pointer to working \ref GSM_t structure * \param[in] *puk: Pointer to SIM PUK code * \param[in] *new_pin: Pointer to new PIN in string format * \param[in] blocking: Status whether this function should be blocking to check for response * \retval Member of \ref GSM_Result_t enumeration */ GSM_Result_t GSM_PUK_Enter(gvol GSM_t* GSM, const char* puk, const char* new_pin, uint32_t blocking); /** * \} */ /** * \defgroup CALL_API * \brief CALL based functions * \{ */ /** * \brief Start voice call to specific number * \param[in,out] *GSM: Pointer to working \ref GSM_t structure * \param[in] *number: Pointer to number in string format * \param[in] blocking: Status whether this function should be blocking to check for response * \retval Member of \ref GSM_Result_t enumeration */ GSM_Result_t GSM_CALL_Voice(gvol GSM_t* GSM, const char* number, uint32_t blocking); /** * \brief Start data call to specific number * \note This options has not been actually tested yet * \param[in,out] *GSM: Pointer to working \ref GSM_t structure * \param[in] *number: Pointer to number in string format * \param[in] blocking: Status whether this function should be blocking to check for response * \retval Member of \ref GSM_Result_t enumeration */ GSM_Result_t GSM_CALL_Data(gvol GSM_t* GSM, const char* number, uint32_t blocking); /** * \brief Start voice call to specific number selected from sim phonebook * \param[in,out] *GSM: Pointer to working \ref GSM_t structure * \param[in] pos: Phonebook position on SIM card * \param[in] blocking: Status whether this function should be blocking to check for response * \retval Member of \ref GSM_Result_t enumeration */ GSM_Result_t GSM_CALL_VoiceFromSIMPosition(gvol GSM_t* GSM, uint16_t pos, uint32_t blocking); /** * \brief Start data call to specific number selected from sim phonebook * \note This options has not been actually tested yet * \param[in,out] *GSM: Pointer to working \ref GSM_t structure * \param[in] pos: Phonebook position on SIM card * \param[in] blocking: Status whether this function should be blocking to check for response * \retval Member of \ref GSM_Result_t enumeration */ GSM_Result_t GSM_CALL_DataFromSIMPosition(gvol GSM_t* GSM, uint16_t pos, uint32_t blocking); /** * \brief Answer to received call * \param[in,out] *GSM: Pointer to working \ref GSM_t structure * \param[in] blocking: Status whether this function should be blocking to check for response * \retval Member of \ref GSM_Result_t enumeration */ GSM_Result_t GSM_CALL_Answer(gvol GSM_t* GSM, uint32_t blocking); /** * \brief Hang up a receiving call or finish with call * \param[in,out] *GSM: Pointer to working \ref GSM_t structure * \param[in] blocking: Status whether this function should be blocking to check for response * \retval Member of \ref GSM_Result_t enumeration */ GSM_Result_t GSM_CALL_HangUp(gvol GSM_t* GSM, uint32_t blocking); /** * \brief Get informations about current call, receive, outgoing or active * \param[in,out] *GSM: Pointer to working \ref GSM_t structure * \param[in] blocking: Status whether this function should be blocking to check for response * \retval Pointer to call info. */ GSM_CallInfo_t* GSM_CALL_GetInfo(gvol GSM_t* GSM, uint32_t blocking); /** * \brief Clear informations about call once you are done and you don't need info anymore * \param[in,out] *GSM: Pointer to working \ref GSM_t structure * \param[in] *info: Pointer to \ref GSM_CallInfo_t structure previously returned with \ref GSM_CALL_GetInfo function * \param[in] blocking: Status whether this function should be blocking to check for response * \retval Member of \ref GSM_Result_t enumeration */ GSM_Result_t GSM_CALL_ClearInfo(gvol GSM_t* GSM, GSM_CallInfo_t* info, uint32_t blocking); /** * \} */ /** * \defgroup SMS_API * \brief SMS based functions * \{ */ /** * \brief Send new SMS to specific number * \param[in,out] *GSM: Pointer to working \ref GSM_t structure * \param[in] *number: Phone number to send SMS to * \param[in] *data: SMS data in ASCII format * \param[in] blocking: Status whether this function should be blocking to check for response * \retval Member of \ref GSM_Result_t enumeration */ GSM_Result_t GSM_SMS_Send(gvol GSM_t* GSM, const char* number, const char* data, uint32_t blocking); /** * \brief Read SMS from specific SIM memory position * \param[in,out] *GSM: Pointer to working \ref GSM_t structure * \param[in] position: SMS position in memory. * \param[out] *SMS: Pointer to empty \ref GSM_SMS_Entry_t structure to save data to * \param[in] blocking: Status whether this function should be blocking to check for response * \retval Member of \ref GSM_Result_t enumeration */ GSM_Result_t GSM_SMS_Read(gvol GSM_t* GSM, uint16_t position, GSM_SMS_Entry_t* SMS, uint32_t blocking); /** * \brief List all SMS entries * \param[in,out] *GSM: Pointer to working \ref GSM_t structure * \param[in] type: SMS type to read. This parameter can be a value of \ref GSM_SMS_ReadType_t enumeration * \param[out] *entries: Pointer to array of \ref GSM_SMS_Entry_t structures * \param[in] btr: Number of entries to read. This parameter can't be greater than number of elements in entries array * \param[out] *br: Pointer to save actual SMS entries read from module * \param[in] blocking: Status whether this function should be blocking to check for response * \retval Member of \ref GSM_Result_t enumeration */ GSM_Result_t GSM_SMS_List(gvol GSM_t* GSM, GSM_SMS_ReadType_t type, GSM_SMS_Entry_t* entries, uint16_t btr, uint16_t* br, uint32_t blocking); /** * \brief Delete specific SMS at desired position * \param[in,out] *GSM: Pointer to working \ref GSM_t structure * \param[in] position: Position in memory to delete * \param[in] blocking: Status whether this function should be blocking to check for response * \retval Member of \ref GSM_Result_t enumeration */ GSM_Result_t GSM_SMS_Delete(gvol GSM_t* GSM, uint16_t position, uint32_t blocking); /** * \brief Process mass delete SMS entries * \note This function may take a while so take care of using it as blocking. * \param[in,out] *GSM: Pointer to working \ref GSM_t structure * \param[in] type: Mass delete type. This parameter can be a value of \ref GSM_SMS_MassDelete_t enumeration * \param[in] blocking: Status whether this function should be blocking to check for response * \retval Member of \ref GSM_Result_t enumeration */ GSM_Result_t GSM_SMS_MassDelete(gvol GSM_t* GSM, GSM_SMS_MassDelete_t type, uint32_t blocking); /** * \brief Get informations about received new SMS if possible * \param[in,out] *GSM: Pointer to working \ref GSM_t structure * \param[in] blocking: Status whether this function should be blocking to check for response * \retval Pointer to \ref GSM_SmsInfo_t structure with informations about received SMS or NULL if nothing received */ GSM_SmsInfo_t* GSM_SMS_GetReceivedInfo(gvol GSM_t* GSM, uint32_t blocking); /** * \brief Clear info about received SMS * \note You must call this function after you process everything from \ref GSM_SMS_GetReceivedInfo function call * to allow new SMS received infos to be saved again into free memory. * \param[in,out] *GSM: Pointer to working \ref GSM_t structure * \param[in] *info: Pointer to previously returned pointer from \ref GSM_SMS_GetReceivedInfo function to clear and free memory * \param[in] blocking: Status whether this function should be blocking to check for response * \retval Member of \ref GSM_Result_t enumeration */ GSM_Result_t GSM_SMS_ClearReceivedInfo(gvol GSM_t* GSM, GSM_SmsInfo_t* info, uint32_t blocking); /** * \} */ /** * \defgroup PHONEBOOK_API * \brief PHONEBOOK based functions * \{ */ /** * \brief Add new entry to phonebook * \param[in,out] *GSM: Pointer to working \ref GSM_t structure * \param[in] *name: Pointer to new phonebook entry name * \param[in] *number: Pointer to entry call number in string format * \param[in] blocking: Status whether this function should be blocking to check for response * \retval Member of \ref GSM_Result_t enumeration */ GSM_Result_t GSM_PB_Add(gvol GSM_t* GSM, const char* name, const char* number, uint32_t blocking); /** * \brief Edit phonebook entry * \param[in,out] *GSM: Pointer to working \ref GSM_t structure * \param[in] index: Index position for entry in phonebook * \param[in] *name: Pointer to new phonebook entry name * \param[in] *number: Pointer to entry call number in string format * \param[in] blocking: Status whether this function should be blocking to check for response * \retval Member of \ref GSM_Result_t enumeration */ GSM_Result_t GSM_PB_Edit(gvol GSM_t* GSM, uint32_t index, const char* name, const char* number, uint32_t blocking); /** * \brief Delete phonebook entry * \param[in,out] *GSM: Pointer to working \ref GSM_t structure * \param[in] index: Index position for entry in phonebook to delete * \param[in] blocking: Status whether this function should be blocking to check for response * \retval Member of \ref GSM_Result_t enumeration */ GSM_Result_t GSM_PB_Delete(gvol GSM_t* GSM, uint32_t index, uint32_t blocking); /** * \brief Read phonebook entry * \param[in,out] *GSM: Pointer to working \ref GSM_t structure * \param[out] *entry: Pointer to empty \ref GSM_PB_Entry_t structure to save entry informations * \param[in] index: Index in phonebook to read entry * \param[in] blocking: Status whether this function should be blocking to check for response * \retval Member of \ref GSM_Result_t enumeration */ GSM_Result_t GSM_PB_Get(gvol GSM_t* GSM, uint32_t index, GSM_PB_Entry_t* entry, uint32_t blocking); /** * \brief List entries from phonebook * \param[in,out] *GSM: Pointer to working \ref GSM_t structure * \param[out] *entries: Pointer to array of empty \ref GSM_PB_Entry_t structures to save data to * \param[in] start_index: Start index number in phonebook to read from * \param[in] btr: Number of entries to read. This number should not be greater than number of elements in entries array * \param[out] *br: Pointer to number to save actual number of entries read from phonebook * \param[in] blocking: Status whether this function should be blocking to check for response * \retval Member of \ref GSM_Result_t enumeration */ GSM_Result_t GSM_PB_List(gvol GSM_t* GSM, GSM_PB_Entry_t* entries, uint16_t start_index, uint16_t btr, uint16_t* br, uint32_t blocking); /** * \brief Search for entries in phonebook * \param[in,out] *GSM: Pointer to working \ref GSM_t structure * \param[in] *search: Pointer to string to use in search operation * \param[out] *entries: Pointer to array of empty entry structures to save data to * \param[in] btr: Number of entries to read. This number should not be greater than number of elements in entries array * \param[out] *br: Pointer to number to save actual number of entries read from phonebook * \param[in] blocking: Status whether this function should be blocking to check for response * \retval Member of \ref GSM_Result_t enumeration */ GSM_Result_t GSM_PB_Search(gvol GSM_t* GSM, const char* search, GSM_PB_Entry_t* entries, uint16_t btr, uint16_t* br, uint32_t blocking); /** * \} */ /** * \defgroup DATETIME_API * \brief DATETIME based functions * \{ */ /** * \brief Get current date and time from network * \note Some network operators does not support this function. In this case, time when module was last reset will be returned. * \param[in,out] *GSM: Pointer to working \ref GSM_t structure * \param[out] *datetime: Pointer to empty \ref GSM_DateTime_t structure to save date and time * \param[in] blocking: Status whether this function should be blocking to check for response * \retval Member of \ref GSM_Result_t enumeration */ GSM_Result_t GSM_DATETIME_Get(gvol GSM_t* GSM, GSM_DateTime_t* datetime, uint32_t blocking); /** * \} */ /** * \defgroup GPRS_API * \brief GPRS based functions * \{ */ /** * \brief Connects module to GPRS network to access to internet * \note This operation may take up to 3 minutes so take care when in blocking use. When in <b>RTOS</b> mode, you may use it in blocking mode easily. * \param[in,out] *GSM: Pointer to working \ref GSM_t structure * \param[in] *apn: Pointer to APN string for internet * \param[in] *user: Pointer to user name. Use "" when no user is required * \param[in] *pwd: Pointer to password. Use "" when no password is required * \param[in] blocking: Status whether this function should be blocking to check for response * \retval Member of \ref GSM_Result_t enumeration */ GSM_Result_t GSM_GPRS_Attach(gvol GSM_t* GSM, const char* apn, const char* user, const char* pwd, uint32_t blocking); /** * \brief Disconnects module from GPRS network * \param[in,out] *GSM: Pointer to working \ref GSM_t structure * \param[in] blocking: Status whether this function should be blocking to check for response * \retval Member of \ref GSM_Result_t enumeration */ GSM_Result_t GSM_GPRS_Detach(gvol GSM_t* GSM, uint32_t blocking); /** * \brief Gets GPS location from GPRS and current UTC time * \note Connection with GRPS must be active in order to get information * \param[in,out] *GSM: Pointer to working \ref GSM_t structure * \param[out] *GPS: Pointer to empty ref \GSM_GPS_t to save GPS information and date/time information * \param[in] blocking: Status whether this function should be blocking to check for response * \retval Member of \ref GSM_Result_t enumeration */ GSM_Result_t GSM_GPRS_GetLocationAndTime(gvol GSM_t* GSM, GSM_GPS_t* GPS, uint32_t blocking); /** * \} */ /** * \defgroup CONN_API * \brief TCP/UDP connection based functions * \{ * * \note Concept of connections is done to support multiple connections at the same time. * However, currently only single connection at a time can be used. */ /** * \brief Start a new connection * \param[in,out] *GSM: Pointer to working \ref GSM_t structure * \param[in] *conn: Pointer to empty \ref GSM_CONN_t structure for connection identifier * \param[in] type: Connection type. This parameter can be a value of \ref GSM_CONN_Type_t enumeration * \param[in] ssl: Connection over SSL. This parameter can be a value of \ref GSM_CONN_SSL_t enumeration. Parameter is valid only with TCP connection * \param[in] *host: Pointer to host where to connect. Can be a domain name or IP address, both in sting format * \param[in] port: Port to connect to * \param[in] blocking: Status whether this function should be blocking to check for response * \retval Member of \ref GSM_Result_t enumeration */ GSM_Result_t GSM_CONN_Start(gvol GSM_t* GSM, gvol GSM_CONN_t* conn, GSM_CONN_Type_t type, GSM_CONN_SSL_t ssl, const char* host, uint16_t port, uint32_t blocking); /** * \brief Send data on active connection * \param[in,out] *GSM: Pointer to working \ref GSM_t structure * \param[in] *conn: Pointer to working \ref GSM_CONN_t structure for connection * \param[in] *data: Pointer to data to send * \param[in] btw: Number of bytes to send * \param[out] *bw: Pointer to save number of bytes actually sent in connection * \param[in] blocking: Status whether this function should be blocking to check for response * \retval Member of \ref GSM_Result_t enumeration */ GSM_Result_t GSM_CONN_Send(gvol GSM_t* GSM, gvol GSM_CONN_t* conn, const void* data, uint16_t btw, uint32_t* bw, uint32_t blocking); /** * \brief Read received data on connection * \param[in,out] *GSM: Pointer to working \ref GSM_t structure * \param[in] *conn: Pointer to working \ref GSM_CONN_t structure for connection * \param[out] *data: Pointer to data array to save receive data to * \param[in] btr: Length of data array in units of bytes * \param[out] *br: Pointer to number of actually read bytes from response * \param[in] timeBeforeRead: Wait time before actual trying to read. This enables you to wait for actual data to receive from response. * Set to 0 if you don't want to wait. * \param[in] blocking: Status whether this function should be blocking to check for response * \retval Member of \ref GSM_Result_t enumeration */ GSM_Result_t GSM_CONN_Receive(gvol GSM_t* GSM, gvol GSM_CONN_t* conn, void* data, uint16_t btr, uint32_t* br, uint16_t timeBeforeRead, uint32_t blocking); /** * \brief Close active connection * \param[in,out] *GSM: Pointer to working \ref GSM_t structure * \param[in] *conn: Pointer to working \ref GSM_CONN_t structure for connection * \param[in] blocking: Status whether this function should be blocking to check for response * \retval Member of \ref GSM_Result_t enumeration */ GSM_Result_t GSM_CONN_Close(gvol GSM_t* GSM, gvol GSM_CONN_t* conn, uint32_t blocking); /** * \brief Checks if any data to read from connection response * \note This functions only checks flags and does not inquiry GSM. * It means that when you are not in RTOS or ASYNC mode, * you have to manually call \ref GSM_Update function to parse any incoming data in a loop for specific timeout * \param[in,out] *GSM: Pointer to working \ref GSM_t structure * \param[in] *conn: Pointer to active \ref GSM_CONN_t connection structure * \param[in] blocking: Status whether this function should be blocking to check for response. * Currently this param has no effect and is reserved for future use * \retval Status indicating if data available: * - 0: Data not available * - > 0: Data available for read operation */ uint32_t GSM_CONN_DataAvailable(gvol GSM_t* GSM, const gvol GSM_CONN_t* conn, uint32_t blocking); /** * \} */ /** * \defgroup HTTP_API * \brief HTTP based functions * \{ */ /** * \brief Begin with HTTP support on SIM module * \param[in,out] *GSM: Pointer to working \ref GSM_t structure * \param[in] blocking: Status whether this function should be blocking to check for response * \retval Member of \ref GSM_Result_t enumeration */ GSM_Result_t GSM_HTTP_Begin(gvol GSM_t* GSM, uint32_t blocking); /** * \brief Stop GSM HTTP SIM module * \note To use it again, use \ref GSM_HTTP_Begin function * \param[in,out] *GSM: Pointer to working \ref GSM_t structure * \param[in] blocking: Status whether this function should be blocking to check for response * \retval Member of \ref GSM_Result_t enumeration */ GSM_Result_t GSM_HTTP_End(gvol GSM_t* GSM, uint32_t blocking); /** * \brief Set content for HTTP request * \note This function does not set actual data for HTTP, but only sets content type, e.g. "application/json". * \param[in,out] *GSM: Pointer to working \ref GSM_t structure * \param[in] *content: Pointer to content type string * \param[in] blocking: Status whether this function should be blocking to check for response * \retval Member of \ref GSM_Result_t enumeration */ GSM_Result_t GSM_HTTP_SetContent(gvol GSM_t* GSM, const char* content, uint32_t blocking); /** * \brief Set data to be sent on HTTP body for POST or PUT methods * \param[in,out] *GSM: Pointer to working \ref GSM_t structure * \param[in] *data: Data to be sent as body * \param[in] btw: Number of bytes to send * \param[in] blocking: Status whether this function should be blocking to check for response * \retval Member of \ref GSM_Result_t enumeration */ GSM_Result_t GSM_HTTP_SetData(gvol GSM_t* GSM, const void* data, uint32_t btw, uint32_t blocking); /** * \brief Execute HTTP request to server with given URL and method * \param[in,out] *GSM: Pointer to working \ref GSM_t structure * \param[in] *url: Remote URL to use starting with "http://" or "https://" * \param[in] method: HTTP method to use. This parameter can be a value of \ref GSM_HTTP_Method_t enumeration * \param[in] ssl: Enable SSL for HTTP. This parameter can be a value of \ref GSM_HTTP_SSL_t enumeration * \param[in] blocking: Status whether this function should be blocking to check for response * \retval Member of \ref GSM_Result_t enumeration */ GSM_Result_t GSM_HTTP_Execute(gvol GSM_t* GSM, const char* url, GSM_HTTP_Method_t method, GSM_HTTP_SSL_t ssl, uint32_t blocking); /** * \brief Read data from HTTP response * \param[in,out] *GSM: Pointer to working \ref GSM_t structure * \param[out] *data: Pointer to array to save data to * \param[in] btr: Number of bytes to read from response * \param[out] *br: Pointer to save number of actual data read from response * \param[in] blocking: Status whether this function should be blocking to check for response * \retval Member of \ref GSM_Result_t enumeration */ GSM_Result_t GSM_HTTP_Read(gvol GSM_t* GSM, void* data, uint32_t btr, uint32_t* br, uint32_t blocking); /** * \brief Checks if any data to read from HTTP response * \note This functions only checks flags and does not inquiry GSM. * It means that when you are not in <b>RTOS</b> or <b>ASYNC</b> mode, * you have to manually call \ref GSM_Update function to parse any incoming data in a loop for specific timeout * \param[in,out] *GSM: Pointer to working \ref GSM_t structure * \param[in] blocking: Status whether this function should be blocking to check for response. * Currently this param has no effect and is reserved for future use * \retval Status indicating if data available: * - 0: Data not available * - > 0: Data available for read operation */ uint32_t GSM_HTTP_DataAvailable(gvol GSM_t* GSM, uint32_t blocking); /** * \} */ /** * \defgroup FTP_API * \brief FTP based functions * \since 0.4 * \{ */ /** * \brief Enable FTP procedure * \param[in,out] *GSM: Pointer to working \ref GSM_t structure * \param[in] mode: FTP mode either active or passive. This parameter can be a value of \ref GSM_FTP_Mode_t enumeration * \param[in] ssl: FTP over SSL. This parameter can be a value of \ref GSM_FTP_SSL_t enumeration * \param[in] blocking: Status whether this function should be blocking to check for response * \retval Member of \ref GSM_Result_t enumeration */ GSM_Result_t GSM_FTP_Begin(gvol GSM_t* GSM, GSM_FTP_Mode_t mode, GSM_FTP_SSL_t ssl, uint32_t blocking); /** * \brief Disable FTP procedure * \param[in,out] *GSM: Pointer to working \ref GSM_t structure * \param[in] blocking: Status whether this function should be blocking to check for response * \retval Member of \ref GSM_Result_t enumeration */ GSM_Result_t GSM_FTP_End(gvol GSM_t* GSM, uint32_t blocking); /** * \brief Authenticate to server with server name, port, username and password * \param[in,out] *GSM: Pointer to working \ref GSM_t structure * \param[in] *server: Pointer to server address * \param[in] port: FTP port to connect. In most cases, port 21 is used * \param[in] *user: FTP username * \param[in] *pass: FTP password * \param[in] blocking: Status whether this function should be blocking to check for response * \retval Member of \ref GSM_Result_t enumeration */ GSM_Result_t GSM_FTP_Authenticate(gvol GSM_t* GSM, const char* server, uint16_t port, const char* user, const char* pass, uint32_t blocking); /** * \brief Begin with file download session * \param[in,out] *GSM: Pointer to working \ref GSM_t structure * \param[in] *folder: Folder to use for file download * \param[in] *file: File to download in specific folder. For some FTP servers, this parameter must start with "/" character * \param[in] blocking: Status whether this function should be blocking to check for response * \retval Member of \ref GSM_Result_t enumeration */ GSM_Result_t GSM_FTP_DownloadBegin(gvol GSM_t* GSM, const char* folder, const char* file, uint32_t blocking); /** * \brief Checks if FTP download session is active * \param[in,out] *GSM: Pointer to working \ref GSM_t structure * \param[in] blocking: Status whether this function should be blocking to check for response * \retval Member of \ref GSM_Result_t enumeration */ GSM_Result_t GSM_FTP_DownloadActive(gvol GSM_t* GSM, uint32_t blocking); /** * \brief Checks if there are bytes to read in current session * \note If may happen that session is active (\ref GSM_FTP_DownloadActive) but there are no data to read. * This means that you will have to wait for incoming data a little first. * \param[in,out] *GSM: Pointer to working \ref GSM_t structure * \param[in] blocking: Status whether this function should be blocking to check for response * \retval Member of \ref GSM_Result_t enumeration */ GSM_Result_t GSM_FTP_DownloadAvailable(gvol GSM_t* GSM, uint32_t blocking); /** * \brief Read downloaded data from GSM device * \param[in,out] *GSM: Pointer to working \ref GSM_t structure * \param[out] *data: Data to save data read from GSM * \param[in] btr: Bytes to read from device * \param[out] *br: Pointer to number of bytes actually read from device * \param[in] blocking: Status whether this function should be blocking to check for response * \retval Member of \ref GSM_Result_t enumeration */ GSM_Result_t GSM_FTP_Download(gvol GSM_t* GSM, void* data, uint32_t btr, uint32_t* br, uint32_t blocking); /** * \brief Finish with FTP download session * \param[in,out] *GSM: Pointer to working \ref GSM_t structure * \param[in] blocking: Status whether this function should be blocking to check for response * \retval Member of \ref GSM_Result_t enumeration */ GSM_Result_t GSM_FTP_DownloadEnd(gvol GSM_t* GSM, uint32_t blocking); /** * \brief Begin with file upload session * \param[in,out] *GSM: Pointer to working \ref GSM_t structure * \param[in] *folder: Folder to use for file download * \param[in] *file: File to download in specific folder. For some FTP servers, this parameter must start with "/" character * \param[in] mode: Upload mode. This parameter can be a value of \ref GSM_FTP_UploadMode_t enumeration * \param[in] blocking: Status whether this function should be blocking to check for response * \retval Member of \ref GSM_Result_t enumeration */ GSM_Result_t GSM_FTP_UploadBegin(gvol GSM_t* GSM, const char* folder, const char* file, GSM_FTP_UploadMode_t mode, uint32_t blocking); /** * \brief Upload data to FTP server * \note This function can be called multiple times when more data needs to be sent * \param[in,out] *GSM: Pointer to working \ref GSM_t structure * \param[in] *data: Pointer to data to upload to FTP server * \param[in] btw: Number of bytes to write over FTP * \param[out] *bw: Pointer to save number of bytes written over FTP * \param[in] blocking: Status whether this function should be blocking to check for response * \retval Member of \ref GSM_Result_t enumeration */ GSM_Result_t GSM_FTP_Upload(gvol GSM_t* GSM, const void* data, uint32_t btw, uint32_t* bw, uint32_t blocking); /** * \brief Finish with FTP upload session * \param[in,out] *GSM: Pointer to working \ref GSM_t structure * \param[in] blocking: Status whether this function should be blocking to check for response * \retval Member of \ref GSM_Result_t enumeration */ GSM_Result_t GSM_FTP_UploadEnd(gvol GSM_t* GSM, uint32_t blocking); /** * \} */ /** * \} */ /** * \} */ /* C++ detection */ #ifdef __cplusplus } #endif #endif
{ "pile_set_name": "Github" }
<!--- Slatwall - An Open Source eCommerce Platform Copyright (C) ten24, LLC This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Linking this program statically or dynamically with other modules is making a combined work based on this program. Thus, the terms and conditions of the GNU General Public License cover the whole combination. As a special exception, the copyright holders of this program give you permission to combine this program with independent modules and your custom code, regardless of the license terms of these independent modules, and to copy and distribute the resulting program under terms of your choice, provided that you follow these specific guidelines: - You also meet the terms and conditions of the license of each independent module - You must not alter the default display of the Slatwall name or logo from any part of the application - Your custom code must not alter or create any files inside Slatwall, except in the following directories: /integrationServices/ You may copy and distribute the modified version of this program that meets the above guidelines as a combined work under the terms of GPL for this program, provided that you include the source code of that other code when and as the GNU GPL requires distribution of source code. If you modify this program, you may extend this exception to your version of the program, but you are not obligated to do so. Notes: ---> <cfimport prefix="swa" taglib="../../../tags" /> <cfimport prefix="hb" taglib="../../../org/Hibachi/HibachiTags" /> <cfparam name="rc.paymentMethod" type="any" /> <cfparam name="rc.paymentMethodType" type="string" default="#rc.paymentMethod.getPaymentMethodType()#" /> <cfparam name="rc.edit" type="boolean" default="false" /> <cfif getHibachiScope().getService('subscriptionService').hasAnySubscriptionWithAutoPayWithoutOrderPaymentWithAccountPaymentMethod() > <cfset request.slatwallScope.showMessageKey('entity.order.process.placeOrder.hasSubscriptionWithAutoPayFlagWithoutOrderPaymentWithAccountPaymentMethod_info') /> </cfif> <cfoutput> <cfif rc.paymentMethod.isNew()> <cfset rc.paymentMethod.setPaymentMethodType(rc.paymentMethodType) /> </cfif> <hb:HibachiEntityDetailForm object="#rc.paymentMethod#" edit="#rc.edit#"> <hb:HibachiEntityActionBar type="detail" object="#rc.paymentMethod#" edit="#rc.edit#" /> <input type="hidden" name="paymentMethodType" value="#rc.paymentMethod.getPaymentMethodType()#" /> <hb:HibachiEntityDetailGroup object="#rc.paymentMethod#"> <hb:HibachiEntityDetailItem view="admin:entity/paymentmethodtabs/basic" open="true" text="#$.slatwall.rbKey('admin.define.basic')#" showOnCreateFlag=true /> <hb:HibachiEntityDetailItem view="admin:entity/paymentmethodtabs/settings" /> </hb:HibachiEntityDetailGroup> </hb:HibachiEntityDetailForm> </cfoutput>
{ "pile_set_name": "Github" }
<!-- Description: rss item author - cdata escaped markup --> <rss version="2.0"> <channel> <item> <author><![CDATA[&lt;p&gt;Item Author&lt;/p&gt;]]></author> </item> </channel> </rss>
{ "pile_set_name": "Github" }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.Linq; namespace Xamarin.Forms { internal sealed class ShellContentCollection : ShellElementCollection<ShellContent> { public ShellContentCollection() : base() { Inner = new ObservableCollection<ShellContent>(); } protected override bool IsShellElementVisible(BaseShellItem item) { IShellContentController controller = (IShellContentController)item; return controller.Page == null || controller.Page.IsVisible; } void OnIsPageVisibleChanged(object sender, EventArgs e) { CheckVisibility((ShellContent)sender); } protected override void OnElementControllerInserting(IElementController element) { base.OnElementControllerInserting(element); if (element is IShellContentController controller) controller.IsPageVisibleChanged += OnIsPageVisibleChanged; } protected override void OnElementControllerRemoving(IElementController element) { base.OnElementControllerRemoving(element); if (element is IShellContentController controller) controller.IsPageVisibleChanged -= OnIsPageVisibleChanged; } } }
{ "pile_set_name": "Github" }
package com.tencent.ttpic.filter; import android.opengl.GLES20; import com.tencent.filter.BaseFilter; import com.tencent.filter.GLSLRender; import com.tencent.matrix.trace.core.AppMethodBeat; public class SpaceFilter extends BaseFilter { private float mRatio = 0.0f; public SpaceFilter() { super(GLSLRender.bJB); } public void setSpaceRatio(float f) { AppMethodBeat.i(82950); if (Float.compare(this.mRatio, f) == 0) { AppMethodBeat.o(82950); return; } this.mRatio = f; float f2 = 1.0f - this.mRatio; setPositions(new float[]{-f2, -f2, -f2, f2, f2, f2, f2, -f2}); AppMethodBeat.o(82950); } public boolean renderTexture(int i, int i2, int i3) { AppMethodBeat.i(82951); GLES20.glClearColor(1.0f, 1.0f, 1.0f, 1.0f); GLES20.glClear(16384); GLES20.glFinish(); boolean renderTexture = super.renderTexture(i, i2, i3); AppMethodBeat.o(82951); return renderTexture; } }
{ "pile_set_name": "Github" }
3 1 0 2 2 0 1 3 0
{ "pile_set_name": "Github" }
<annotation> <folder>imagesRaw</folder> <filename>2017-12-19 14:57:58.463759.jpg</filename> <path>/Users/abell/Development/other.nyc/Camera/imagesRaw/2017-12-19 14:57:58.463759.jpg</path> <source> <database>Unknown</database> </source> <size> <width>352</width> <height>240</height> <depth>3</depth> </size> <segmented>0</segmented> <object> <name>police</name> <pose>Unspecified</pose> <truncated>0</truncated> <difficult>0</difficult> <bndbox> <xmin>111</xmin> <ymin>147</ymin> <xmax>136</xmax> <ymax>168</ymax> </bndbox> </object> <object> <name>car</name> <pose>Unspecified</pose> <truncated>0</truncated> <difficult>0</difficult> <bndbox> <xmin>139</xmin> <ymin>161</ymin> <xmax>170</xmax> <ymax>186</ymax> </bndbox> </object> <object> <name>car</name> <pose>Unspecified</pose> <truncated>0</truncated> <difficult>0</difficult> <bndbox> <xmin>55</xmin> <ymin>162</ymin> <xmax>85</xmax> <ymax>183</ymax> </bndbox> </object> <object> <name>car</name> <pose>Unspecified</pose> <truncated>0</truncated> <difficult>0</difficult> <bndbox> <xmin>136</xmin> <ymin>198</ymin> <xmax>181</xmax> <ymax>237</ymax> </bndbox> </object> <object> <name>car</name> <pose>Unspecified</pose> <truncated>0</truncated> <difficult>0</difficult> <bndbox> <xmin>152</xmin> <ymin>141</ymin> <xmax>169</xmax> <ymax>154</ymax> </bndbox> </object> <object> <name>car</name> <pose>Unspecified</pose> <truncated>0</truncated> <difficult>0</difficult> <bndbox> <xmin>200</xmin> <ymin>147</ymin> <xmax>221</xmax> <ymax>163</ymax> </bndbox> </object> </annotation>
{ "pile_set_name": "Github" }
package com4j; /** * TODO: General purpose wrapper for COM SAFEARRAY. * * <p> * This class is provided for rare circumstances where the Java code * needs to control SAFEARRAY more precisely. * * <p> * Users are encouraged to use plain Java arrays * as much as possible. For example, the following Java method: * <pre> * void foo( short[] args ); * </pre> * would be bridged to the following COM method: * <pre> * HRESULT foo( [in] SAFEARRAY(short)* args ); * </pre> * * <p> * This works for the most of the cases, and is much easier to use. * * @author Kohsuke Kawaguchi (kk@kohsuke.org) */ public final class SafeArray { /** * Pointer to the allocated SAFEARRAY. */ private int ptr; public SafeArray( Variant.Type type, Bound[] bounds ) { } /** * Bound of an array index. */ public static final class Bound { public int lbound; public int ubound; } public native Object get( int... indices ); public native void set( int... indices ); }
{ "pile_set_name": "Github" }
/* * C Extension module to test Python interpreter C APIs. * * The 'test_*' functions exported by this module are run as part of the * standard Python regression test, via Lib/test/test_capi.py. */ #define PY_SSIZE_T_CLEAN #include "Python.h" #include <float.h> #include "structmember.h" #include "datetime.h" #ifdef WITH_THREAD #include "pythread.h" #endif /* WITH_THREAD */ static PyObject *TestError; /* set to exception object in init */ /* Raise TestError with test_name + ": " + msg, and return NULL. */ static PyObject * raiseTestError(const char* test_name, const char* msg) { PyErr_Format(TestError, "%s: %s", test_name, msg); return NULL; } /* Test #defines from pyconfig.h (particularly the SIZEOF_* defines). The ones derived from autoconf on the UNIX-like OSes can be relied upon (in the absence of sloppy cross-compiling), but the Windows platforms have these hardcoded. Better safe than sorry. */ static PyObject* sizeof_error(const char* fatname, const char* typname, int expected, int got) { PyErr_Format(TestError, "%s #define == %d but sizeof(%s) == %d", fatname, expected, typname, got); return (PyObject*)NULL; } static PyObject* test_config(PyObject *self) { #define CHECK_SIZEOF(FATNAME, TYPE) \ if (FATNAME != sizeof(TYPE)) \ return sizeof_error(#FATNAME, #TYPE, FATNAME, sizeof(TYPE)) CHECK_SIZEOF(SIZEOF_SHORT, short); CHECK_SIZEOF(SIZEOF_INT, int); CHECK_SIZEOF(SIZEOF_LONG, long); CHECK_SIZEOF(SIZEOF_VOID_P, void*); CHECK_SIZEOF(SIZEOF_TIME_T, time_t); #ifdef HAVE_LONG_LONG CHECK_SIZEOF(SIZEOF_LONG_LONG, PY_LONG_LONG); #endif #undef CHECK_SIZEOF Py_INCREF(Py_None); return Py_None; } static PyObject* test_list_api(PyObject *self) { PyObject* list; int i; /* SF bug 132008: PyList_Reverse segfaults */ #define NLIST 30 list = PyList_New(NLIST); if (list == (PyObject*)NULL) return (PyObject*)NULL; /* list = range(NLIST) */ for (i = 0; i < NLIST; ++i) { PyObject* anint = PyLong_FromLong(i); if (anint == (PyObject*)NULL) { Py_DECREF(list); return (PyObject*)NULL; } PyList_SET_ITEM(list, i, anint); } /* list.reverse(), via PyList_Reverse() */ i = PyList_Reverse(list); /* should not blow up! */ if (i != 0) { Py_DECREF(list); return (PyObject*)NULL; } /* Check that list == range(29, -1, -1) now */ for (i = 0; i < NLIST; ++i) { PyObject* anint = PyList_GET_ITEM(list, i); if (PyLong_AS_LONG(anint) != NLIST-1-i) { PyErr_SetString(TestError, "test_list_api: reverse screwed up"); Py_DECREF(list); return (PyObject*)NULL; } } Py_DECREF(list); #undef NLIST Py_INCREF(Py_None); return Py_None; } static int test_dict_inner(int count) { Py_ssize_t pos = 0, iterations = 0; int i; PyObject *dict = PyDict_New(); PyObject *v, *k; if (dict == NULL) return -1; for (i = 0; i < count; i++) { v = PyLong_FromLong(i); if (v == NULL) { return -1; } if (PyDict_SetItem(dict, v, v) < 0) { Py_DECREF(v); return -1; } Py_DECREF(v); } while (PyDict_Next(dict, &pos, &k, &v)) { PyObject *o; iterations++; i = PyLong_AS_LONG(v) + 1; o = PyLong_FromLong(i); if (o == NULL) return -1; if (PyDict_SetItem(dict, k, o) < 0) { Py_DECREF(o); return -1; } Py_DECREF(o); } Py_DECREF(dict); if (iterations != count) { PyErr_SetString( TestError, "test_dict_iteration: dict iteration went wrong "); return -1; } else { return 0; } } static PyObject* test_dict_iteration(PyObject* self) { int i; for (i = 0; i < 200; i++) { if (test_dict_inner(i) < 0) { return NULL; } } Py_INCREF(Py_None); return Py_None; } /* Issue #4701: Check that PyObject_Hash implicitly calls * PyType_Ready if it hasn't already been called */ static PyTypeObject _HashInheritanceTester_Type = { PyVarObject_HEAD_INIT(NULL, 0) "hashinheritancetester", /* Name of this type */ sizeof(PyObject), /* Basic object size */ 0, /* Item size for varobject */ (destructor)PyObject_Del, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ 0, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ PyType_GenericNew, /* tp_new */ }; static PyObject* test_lazy_hash_inheritance(PyObject* self) { PyTypeObject *type; PyObject *obj; Py_hash_t hash; type = &_HashInheritanceTester_Type; if (type->tp_dict != NULL) /* The type has already been initialized. This probably means -R is being used. */ Py_RETURN_NONE; obj = PyObject_New(PyObject, type); if (obj == NULL) { PyErr_Clear(); PyErr_SetString( TestError, "test_lazy_hash_inheritance: failed to create object"); return NULL; } if (type->tp_dict != NULL) { PyErr_SetString( TestError, "test_lazy_hash_inheritance: type initialised too soon"); Py_DECREF(obj); return NULL; } hash = PyObject_Hash(obj); if ((hash == -1) && PyErr_Occurred()) { PyErr_Clear(); PyErr_SetString( TestError, "test_lazy_hash_inheritance: could not hash object"); Py_DECREF(obj); return NULL; } if (type->tp_dict == NULL) { PyErr_SetString( TestError, "test_lazy_hash_inheritance: type not initialised by hash()"); Py_DECREF(obj); return NULL; } if (type->tp_hash != PyType_Type.tp_hash) { PyErr_SetString( TestError, "test_lazy_hash_inheritance: unexpected hash function"); Py_DECREF(obj); return NULL; } Py_DECREF(obj); Py_RETURN_NONE; } /* Tests of PyLong_{As, From}{Unsigned,}Long(), and (#ifdef HAVE_LONG_LONG) PyLong_{As, From}{Unsigned,}LongLong(). Note that the meat of the test is contained in testcapi_long.h. This is revolting, but delicate code duplication is worse: "almost exactly the same" code is needed to test PY_LONG_LONG, but the ubiquitous dependence on type names makes it impossible to use a parameterized function. A giant macro would be even worse than this. A C++ template would be perfect. The "report an error" functions are deliberately not part of the #include file: if the test fails, you can set a breakpoint in the appropriate error function directly, and crawl back from there in the debugger. */ #define UNBIND(X) Py_DECREF(X); (X) = NULL static PyObject * raise_test_long_error(const char* msg) { return raiseTestError("test_long_api", msg); } #define TESTNAME test_long_api_inner #define TYPENAME long #define F_S_TO_PY PyLong_FromLong #define F_PY_TO_S PyLong_AsLong #define F_U_TO_PY PyLong_FromUnsignedLong #define F_PY_TO_U PyLong_AsUnsignedLong #include "testcapi_long.h" static PyObject * test_long_api(PyObject* self) { return TESTNAME(raise_test_long_error); } #undef TESTNAME #undef TYPENAME #undef F_S_TO_PY #undef F_PY_TO_S #undef F_U_TO_PY #undef F_PY_TO_U #ifdef HAVE_LONG_LONG static PyObject * raise_test_longlong_error(const char* msg) { return raiseTestError("test_longlong_api", msg); } #define TESTNAME test_longlong_api_inner #define TYPENAME PY_LONG_LONG #define F_S_TO_PY PyLong_FromLongLong #define F_PY_TO_S PyLong_AsLongLong #define F_U_TO_PY PyLong_FromUnsignedLongLong #define F_PY_TO_U PyLong_AsUnsignedLongLong #include "testcapi_long.h" static PyObject * test_longlong_api(PyObject* self, PyObject *args) { return TESTNAME(raise_test_longlong_error); } #undef TESTNAME #undef TYPENAME #undef F_S_TO_PY #undef F_PY_TO_S #undef F_U_TO_PY #undef F_PY_TO_U /* Test the PyLong_AsLongAndOverflow API. General conversion to PY_LONG is tested by test_long_api_inner. This test will concentrate on proper handling of overflow. */ static PyObject * test_long_and_overflow(PyObject *self) { PyObject *num, *one, *temp; long value; int overflow; /* Test that overflow is set properly for a large value. */ /* num is a number larger than LONG_MAX even on 64-bit platforms */ num = PyLong_FromString("FFFFFFFFFFFFFFFFFFFFFFFF", NULL, 16); if (num == NULL) return NULL; overflow = 1234; value = PyLong_AsLongAndOverflow(num, &overflow); Py_DECREF(num); if (value == -1 && PyErr_Occurred()) return NULL; if (value != -1) return raiseTestError("test_long_and_overflow", "return value was not set to -1"); if (overflow != 1) return raiseTestError("test_long_and_overflow", "overflow was not set to 1"); /* Same again, with num = LONG_MAX + 1 */ num = PyLong_FromLong(LONG_MAX); if (num == NULL) return NULL; one = PyLong_FromLong(1L); if (one == NULL) { Py_DECREF(num); return NULL; } temp = PyNumber_Add(num, one); Py_DECREF(one); Py_DECREF(num); num = temp; if (num == NULL) return NULL; overflow = 0; value = PyLong_AsLongAndOverflow(num, &overflow); Py_DECREF(num); if (value == -1 && PyErr_Occurred()) return NULL; if (value != -1) return raiseTestError("test_long_and_overflow", "return value was not set to -1"); if (overflow != 1) return raiseTestError("test_long_and_overflow", "overflow was not set to 1"); /* Test that overflow is set properly for a large negative value. */ /* num is a number smaller than LONG_MIN even on 64-bit platforms */ num = PyLong_FromString("-FFFFFFFFFFFFFFFFFFFFFFFF", NULL, 16); if (num == NULL) return NULL; overflow = 1234; value = PyLong_AsLongAndOverflow(num, &overflow); Py_DECREF(num); if (value == -1 && PyErr_Occurred()) return NULL; if (value != -1) return raiseTestError("test_long_and_overflow", "return value was not set to -1"); if (overflow != -1) return raiseTestError("test_long_and_overflow", "overflow was not set to -1"); /* Same again, with num = LONG_MIN - 1 */ num = PyLong_FromLong(LONG_MIN); if (num == NULL) return NULL; one = PyLong_FromLong(1L); if (one == NULL) { Py_DECREF(num); return NULL; } temp = PyNumber_Subtract(num, one); Py_DECREF(one); Py_DECREF(num); num = temp; if (num == NULL) return NULL; overflow = 0; value = PyLong_AsLongAndOverflow(num, &overflow); Py_DECREF(num); if (value == -1 && PyErr_Occurred()) return NULL; if (value != -1) return raiseTestError("test_long_and_overflow", "return value was not set to -1"); if (overflow != -1) return raiseTestError("test_long_and_overflow", "overflow was not set to -1"); /* Test that overflow is cleared properly for small values. */ num = PyLong_FromString("FF", NULL, 16); if (num == NULL) return NULL; overflow = 1234; value = PyLong_AsLongAndOverflow(num, &overflow); Py_DECREF(num); if (value == -1 && PyErr_Occurred()) return NULL; if (value != 0xFF) return raiseTestError("test_long_and_overflow", "expected return value 0xFF"); if (overflow != 0) return raiseTestError("test_long_and_overflow", "overflow was not cleared"); num = PyLong_FromString("-FF", NULL, 16); if (num == NULL) return NULL; overflow = 0; value = PyLong_AsLongAndOverflow(num, &overflow); Py_DECREF(num); if (value == -1 && PyErr_Occurred()) return NULL; if (value != -0xFF) return raiseTestError("test_long_and_overflow", "expected return value 0xFF"); if (overflow != 0) return raiseTestError("test_long_and_overflow", "overflow was set incorrectly"); num = PyLong_FromLong(LONG_MAX); if (num == NULL) return NULL; overflow = 1234; value = PyLong_AsLongAndOverflow(num, &overflow); Py_DECREF(num); if (value == -1 && PyErr_Occurred()) return NULL; if (value != LONG_MAX) return raiseTestError("test_long_and_overflow", "expected return value LONG_MAX"); if (overflow != 0) return raiseTestError("test_long_and_overflow", "overflow was not cleared"); num = PyLong_FromLong(LONG_MIN); if (num == NULL) return NULL; overflow = 0; value = PyLong_AsLongAndOverflow(num, &overflow); Py_DECREF(num); if (value == -1 && PyErr_Occurred()) return NULL; if (value != LONG_MIN) return raiseTestError("test_long_and_overflow", "expected return value LONG_MIN"); if (overflow != 0) return raiseTestError("test_long_and_overflow", "overflow was not cleared"); Py_INCREF(Py_None); return Py_None; } /* Test the PyLong_AsLongLongAndOverflow API. General conversion to PY_LONG_LONG is tested by test_long_api_inner. This test will concentrate on proper handling of overflow. */ static PyObject * test_long_long_and_overflow(PyObject *self) { PyObject *num, *one, *temp; PY_LONG_LONG value; int overflow; /* Test that overflow is set properly for a large value. */ /* num is a number larger than PY_LLONG_MAX on a typical machine. */ num = PyLong_FromString("FFFFFFFFFFFFFFFFFFFFFFFF", NULL, 16); if (num == NULL) return NULL; overflow = 1234; value = PyLong_AsLongLongAndOverflow(num, &overflow); Py_DECREF(num); if (value == -1 && PyErr_Occurred()) return NULL; if (value != -1) return raiseTestError("test_long_long_and_overflow", "return value was not set to -1"); if (overflow != 1) return raiseTestError("test_long_long_and_overflow", "overflow was not set to 1"); /* Same again, with num = PY_LLONG_MAX + 1 */ num = PyLong_FromLongLong(PY_LLONG_MAX); if (num == NULL) return NULL; one = PyLong_FromLong(1L); if (one == NULL) { Py_DECREF(num); return NULL; } temp = PyNumber_Add(num, one); Py_DECREF(one); Py_DECREF(num); num = temp; if (num == NULL) return NULL; overflow = 0; value = PyLong_AsLongLongAndOverflow(num, &overflow); Py_DECREF(num); if (value == -1 && PyErr_Occurred()) return NULL; if (value != -1) return raiseTestError("test_long_long_and_overflow", "return value was not set to -1"); if (overflow != 1) return raiseTestError("test_long_long_and_overflow", "overflow was not set to 1"); /* Test that overflow is set properly for a large negative value. */ /* num is a number smaller than PY_LLONG_MIN on a typical platform */ num = PyLong_FromString("-FFFFFFFFFFFFFFFFFFFFFFFF", NULL, 16); if (num == NULL) return NULL; overflow = 1234; value = PyLong_AsLongLongAndOverflow(num, &overflow); Py_DECREF(num); if (value == -1 && PyErr_Occurred()) return NULL; if (value != -1) return raiseTestError("test_long_long_and_overflow", "return value was not set to -1"); if (overflow != -1) return raiseTestError("test_long_long_and_overflow", "overflow was not set to -1"); /* Same again, with num = PY_LLONG_MIN - 1 */ num = PyLong_FromLongLong(PY_LLONG_MIN); if (num == NULL) return NULL; one = PyLong_FromLong(1L); if (one == NULL) { Py_DECREF(num); return NULL; } temp = PyNumber_Subtract(num, one); Py_DECREF(one); Py_DECREF(num); num = temp; if (num == NULL) return NULL; overflow = 0; value = PyLong_AsLongLongAndOverflow(num, &overflow); Py_DECREF(num); if (value == -1 && PyErr_Occurred()) return NULL; if (value != -1) return raiseTestError("test_long_long_and_overflow", "return value was not set to -1"); if (overflow != -1) return raiseTestError("test_long_long_and_overflow", "overflow was not set to -1"); /* Test that overflow is cleared properly for small values. */ num = PyLong_FromString("FF", NULL, 16); if (num == NULL) return NULL; overflow = 1234; value = PyLong_AsLongLongAndOverflow(num, &overflow); Py_DECREF(num); if (value == -1 && PyErr_Occurred()) return NULL; if (value != 0xFF) return raiseTestError("test_long_long_and_overflow", "expected return value 0xFF"); if (overflow != 0) return raiseTestError("test_long_long_and_overflow", "overflow was not cleared"); num = PyLong_FromString("-FF", NULL, 16); if (num == NULL) return NULL; overflow = 0; value = PyLong_AsLongLongAndOverflow(num, &overflow); Py_DECREF(num); if (value == -1 && PyErr_Occurred()) return NULL; if (value != -0xFF) return raiseTestError("test_long_long_and_overflow", "expected return value 0xFF"); if (overflow != 0) return raiseTestError("test_long_long_and_overflow", "overflow was set incorrectly"); num = PyLong_FromLongLong(PY_LLONG_MAX); if (num == NULL) return NULL; overflow = 1234; value = PyLong_AsLongLongAndOverflow(num, &overflow); Py_DECREF(num); if (value == -1 && PyErr_Occurred()) return NULL; if (value != PY_LLONG_MAX) return raiseTestError("test_long_long_and_overflow", "expected return value PY_LLONG_MAX"); if (overflow != 0) return raiseTestError("test_long_long_and_overflow", "overflow was not cleared"); num = PyLong_FromLongLong(PY_LLONG_MIN); if (num == NULL) return NULL; overflow = 0; value = PyLong_AsLongLongAndOverflow(num, &overflow); Py_DECREF(num); if (value == -1 && PyErr_Occurred()) return NULL; if (value != PY_LLONG_MIN) return raiseTestError("test_long_long_and_overflow", "expected return value PY_LLONG_MIN"); if (overflow != 0) return raiseTestError("test_long_long_and_overflow", "overflow was not cleared"); Py_INCREF(Py_None); return Py_None; } /* Test the PyLong_As{Size,Ssize}_t API. At present this just tests that non-integer arguments are handled correctly. It should be extended to test overflow handling. */ static PyObject * test_long_as_size_t(PyObject *self) { size_t out_u; Py_ssize_t out_s; Py_INCREF(Py_None); out_u = PyLong_AsSize_t(Py_None); if (out_u != (size_t)-1 || !PyErr_Occurred()) return raiseTestError("test_long_as_size_t", "PyLong_AsSize_t(None) didn't complain"); if (!PyErr_ExceptionMatches(PyExc_TypeError)) return raiseTestError("test_long_as_size_t", "PyLong_AsSize_t(None) raised " "something other than TypeError"); PyErr_Clear(); out_s = PyLong_AsSsize_t(Py_None); if (out_s != (Py_ssize_t)-1 || !PyErr_Occurred()) return raiseTestError("test_long_as_size_t", "PyLong_AsSsize_t(None) didn't complain"); if (!PyErr_ExceptionMatches(PyExc_TypeError)) return raiseTestError("test_long_as_size_t", "PyLong_AsSsize_t(None) raised " "something other than TypeError"); PyErr_Clear(); /* Py_INCREF(Py_None) omitted - we already have a reference to it. */ return Py_None; } /* Test the PyLong_AsDouble API. At present this just tests that non-integer arguments are handled correctly. */ static PyObject * test_long_as_double(PyObject *self) { double out; Py_INCREF(Py_None); out = PyLong_AsDouble(Py_None); if (out != -1.0 || !PyErr_Occurred()) return raiseTestError("test_long_as_double", "PyLong_AsDouble(None) didn't complain"); if (!PyErr_ExceptionMatches(PyExc_TypeError)) return raiseTestError("test_long_as_double", "PyLong_AsDouble(None) raised " "something other than TypeError"); PyErr_Clear(); /* Py_INCREF(Py_None) omitted - we already have a reference to it. */ return Py_None; } /* Test the L code for PyArg_ParseTuple. This should deliver a PY_LONG_LONG for both long and int arguments. The test may leak a little memory if it fails. */ static PyObject * test_L_code(PyObject *self) { PyObject *tuple, *num; PY_LONG_LONG value; tuple = PyTuple_New(1); if (tuple == NULL) return NULL; num = PyLong_FromLong(42); if (num == NULL) return NULL; PyTuple_SET_ITEM(tuple, 0, num); value = -1; if (PyArg_ParseTuple(tuple, "L:test_L_code", &value) < 0) return NULL; if (value != 42) return raiseTestError("test_L_code", "L code returned wrong value for long 42"); Py_DECREF(num); num = PyLong_FromLong(42); if (num == NULL) return NULL; PyTuple_SET_ITEM(tuple, 0, num); value = -1; if (PyArg_ParseTuple(tuple, "L:test_L_code", &value) < 0) return NULL; if (value != 42) return raiseTestError("test_L_code", "L code returned wrong value for int 42"); Py_DECREF(tuple); Py_INCREF(Py_None); return Py_None; } #endif /* ifdef HAVE_LONG_LONG */ /* Test tuple argument processing */ static PyObject * getargs_tuple(PyObject *self, PyObject *args) { int a, b, c; if (!PyArg_ParseTuple(args, "i(ii)", &a, &b, &c)) return NULL; return Py_BuildValue("iii", a, b, c); } /* test PyArg_ParseTupleAndKeywords */ static PyObject * getargs_keywords(PyObject *self, PyObject *args, PyObject *kwargs) { static char *keywords[] = {"arg1","arg2","arg3","arg4","arg5", NULL}; static char *fmt="(ii)i|(i(ii))(iii)i"; int int_args[10]={-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; if (!PyArg_ParseTupleAndKeywords(args, kwargs, fmt, keywords, &int_args[0], &int_args[1], &int_args[2], &int_args[3], &int_args[4], &int_args[5], &int_args[6], &int_args[7], &int_args[8], &int_args[9])) return NULL; return Py_BuildValue("iiiiiiiiii", int_args[0], int_args[1], int_args[2], int_args[3], int_args[4], int_args[5], int_args[6], int_args[7], int_args[8], int_args[9]); } /* test PyArg_ParseTupleAndKeywords keyword-only arguments */ static PyObject * getargs_keyword_only(PyObject *self, PyObject *args, PyObject *kwargs) { static char *keywords[] = {"required", "optional", "keyword_only", NULL}; int required = -1; int optional = -1; int keyword_only = -1; if (!PyArg_ParseTupleAndKeywords(args, kwargs, "i|i$i", keywords, &required, &optional, &keyword_only)) return NULL; return Py_BuildValue("iii", required, optional, keyword_only); } /* Functions to call PyArg_ParseTuple with integer format codes, and return the result. */ static PyObject * getargs_b(PyObject *self, PyObject *args) { unsigned char value; if (!PyArg_ParseTuple(args, "b", &value)) return NULL; return PyLong_FromUnsignedLong((unsigned long)value); } static PyObject * getargs_B(PyObject *self, PyObject *args) { unsigned char value; if (!PyArg_ParseTuple(args, "B", &value)) return NULL; return PyLong_FromUnsignedLong((unsigned long)value); } static PyObject * getargs_h(PyObject *self, PyObject *args) { short value; if (!PyArg_ParseTuple(args, "h", &value)) return NULL; return PyLong_FromLong((long)value); } static PyObject * getargs_H(PyObject *self, PyObject *args) { unsigned short value; if (!PyArg_ParseTuple(args, "H", &value)) return NULL; return PyLong_FromUnsignedLong((unsigned long)value); } static PyObject * getargs_I(PyObject *self, PyObject *args) { unsigned int value; if (!PyArg_ParseTuple(args, "I", &value)) return NULL; return PyLong_FromUnsignedLong((unsigned long)value); } static PyObject * getargs_k(PyObject *self, PyObject *args) { unsigned long value; if (!PyArg_ParseTuple(args, "k", &value)) return NULL; return PyLong_FromUnsignedLong(value); } static PyObject * getargs_i(PyObject *self, PyObject *args) { int value; if (!PyArg_ParseTuple(args, "i", &value)) return NULL; return PyLong_FromLong((long)value); } static PyObject * getargs_l(PyObject *self, PyObject *args) { long value; if (!PyArg_ParseTuple(args, "l", &value)) return NULL; return PyLong_FromLong(value); } static PyObject * getargs_n(PyObject *self, PyObject *args) { Py_ssize_t value; if (!PyArg_ParseTuple(args, "n", &value)) return NULL; return PyLong_FromSsize_t(value); } static PyObject * getargs_p(PyObject *self, PyObject *args) { int value; if (!PyArg_ParseTuple(args, "p", &value)) return NULL; return PyLong_FromLong(value); } #ifdef HAVE_LONG_LONG static PyObject * getargs_L(PyObject *self, PyObject *args) { PY_LONG_LONG value; if (!PyArg_ParseTuple(args, "L", &value)) return NULL; return PyLong_FromLongLong(value); } static PyObject * getargs_K(PyObject *self, PyObject *args) { unsigned PY_LONG_LONG value; if (!PyArg_ParseTuple(args, "K", &value)) return NULL; return PyLong_FromUnsignedLongLong(value); } #endif /* This function not only tests the 'k' getargs code, but also the PyLong_AsUnsignedLongMask() and PyLong_AsUnsignedLongMask() functions. */ static PyObject * test_k_code(PyObject *self) { PyObject *tuple, *num; unsigned long value; tuple = PyTuple_New(1); if (tuple == NULL) return NULL; /* a number larger than ULONG_MAX even on 64-bit platforms */ num = PyLong_FromString("FFFFFFFFFFFFFFFFFFFFFFFF", NULL, 16); if (num == NULL) return NULL; value = PyLong_AsUnsignedLongMask(num); if (value != ULONG_MAX) return raiseTestError("test_k_code", "PyLong_AsUnsignedLongMask() returned wrong value for long 0xFFF...FFF"); PyTuple_SET_ITEM(tuple, 0, num); value = 0; if (PyArg_ParseTuple(tuple, "k:test_k_code", &value) < 0) return NULL; if (value != ULONG_MAX) return raiseTestError("test_k_code", "k code returned wrong value for long 0xFFF...FFF"); Py_DECREF(num); num = PyLong_FromString("-FFFFFFFF000000000000000042", NULL, 16); if (num == NULL) return NULL; value = PyLong_AsUnsignedLongMask(num); if (value != (unsigned long)-0x42) return raiseTestError("test_k_code", "PyLong_AsUnsignedLongMask() returned wrong value for long 0xFFF...FFF"); PyTuple_SET_ITEM(tuple, 0, num); value = 0; if (PyArg_ParseTuple(tuple, "k:test_k_code", &value) < 0) return NULL; if (value != (unsigned long)-0x42) return raiseTestError("test_k_code", "k code returned wrong value for long -0xFFF..000042"); Py_DECREF(tuple); Py_INCREF(Py_None); return Py_None; } static PyObject * getargs_c(PyObject *self, PyObject *args) { char c; if (!PyArg_ParseTuple(args, "c", &c)) return NULL; return PyBytes_FromStringAndSize(&c, 1); } static PyObject * getargs_s(PyObject *self, PyObject *args) { char *str; if (!PyArg_ParseTuple(args, "s", &str)) return NULL; return PyBytes_FromString(str); } static PyObject * getargs_s_star(PyObject *self, PyObject *args) { Py_buffer buffer; PyObject *bytes; if (!PyArg_ParseTuple(args, "s*", &buffer)) return NULL; bytes = PyBytes_FromStringAndSize(buffer.buf, buffer.len); PyBuffer_Release(&buffer); return bytes; } static PyObject * getargs_s_hash(PyObject *self, PyObject *args) { char *str; Py_ssize_t size; if (!PyArg_ParseTuple(args, "s#", &str, &size)) return NULL; return PyBytes_FromStringAndSize(str, size); } static PyObject * getargs_z(PyObject *self, PyObject *args) { char *str; if (!PyArg_ParseTuple(args, "z", &str)) return NULL; if (str != NULL) return PyBytes_FromString(str); else Py_RETURN_NONE; } static PyObject * getargs_z_star(PyObject *self, PyObject *args) { Py_buffer buffer; PyObject *bytes; if (!PyArg_ParseTuple(args, "z*", &buffer)) return NULL; if (buffer.buf != NULL) bytes = PyBytes_FromStringAndSize(buffer.buf, buffer.len); else { Py_INCREF(Py_None); bytes = Py_None; } PyBuffer_Release(&buffer); return bytes; } static PyObject * getargs_z_hash(PyObject *self, PyObject *args) { char *str; Py_ssize_t size; if (!PyArg_ParseTuple(args, "z#", &str, &size)) return NULL; if (str != NULL) return PyBytes_FromStringAndSize(str, size); else Py_RETURN_NONE; } static PyObject * getargs_y(PyObject *self, PyObject *args) { char *str; if (!PyArg_ParseTuple(args, "y", &str)) return NULL; return PyBytes_FromString(str); } static PyObject * getargs_y_star(PyObject *self, PyObject *args) { Py_buffer buffer; PyObject *bytes; if (!PyArg_ParseTuple(args, "y*", &buffer)) return NULL; bytes = PyBytes_FromStringAndSize(buffer.buf, buffer.len); PyBuffer_Release(&buffer); return bytes; } static PyObject * getargs_y_hash(PyObject *self, PyObject *args) { char *str; Py_ssize_t size; if (!PyArg_ParseTuple(args, "y#", &str, &size)) return NULL; return PyBytes_FromStringAndSize(str, size); } static PyObject * getargs_u(PyObject *self, PyObject *args) { Py_UNICODE *str; Py_ssize_t size; if (!PyArg_ParseTuple(args, "u", &str)) return NULL; size = Py_UNICODE_strlen(str); return PyUnicode_FromUnicode(str, size); } static PyObject * getargs_u_hash(PyObject *self, PyObject *args) { Py_UNICODE *str; Py_ssize_t size; if (!PyArg_ParseTuple(args, "u#", &str, &size)) return NULL; return PyUnicode_FromUnicode(str, size); } static PyObject * getargs_Z(PyObject *self, PyObject *args) { Py_UNICODE *str; Py_ssize_t size; if (!PyArg_ParseTuple(args, "Z", &str)) return NULL; if (str != NULL) { size = Py_UNICODE_strlen(str); return PyUnicode_FromUnicode(str, size); } else Py_RETURN_NONE; } static PyObject * getargs_Z_hash(PyObject *self, PyObject *args) { Py_UNICODE *str; Py_ssize_t size; if (!PyArg_ParseTuple(args, "Z#", &str, &size)) return NULL; if (str != NULL) return PyUnicode_FromUnicode(str, size); else Py_RETURN_NONE; } /* Test the s and z codes for PyArg_ParseTuple. */ static PyObject * test_s_code(PyObject *self) { /* Unicode strings should be accepted */ PyObject *tuple, *obj; char *value; tuple = PyTuple_New(1); if (tuple == NULL) return NULL; obj = PyUnicode_Decode("t\xeate", strlen("t\xeate"), "latin-1", NULL); if (obj == NULL) return NULL; PyTuple_SET_ITEM(tuple, 0, obj); /* These two blocks used to raise a TypeError: * "argument must be string without null bytes, not str" */ if (PyArg_ParseTuple(tuple, "s:test_s_code1", &value) < 0) return NULL; if (PyArg_ParseTuple(tuple, "z:test_s_code2", &value) < 0) return NULL; Py_DECREF(tuple); Py_RETURN_NONE; } static PyObject * parse_tuple_and_keywords(PyObject *self, PyObject *args) { PyObject *sub_args; PyObject *sub_kwargs; char *sub_format; PyObject *sub_keywords; Py_ssize_t i, size; char *keywords[8 + 1]; /* space for NULL at end */ PyObject *o; PyObject *converted[8]; int result; PyObject *return_value = NULL; double buffers[8][4]; /* double ensures alignment where necessary */ if (!PyArg_ParseTuple(args, "OOyO:parse_tuple_and_keywords", &sub_args, &sub_kwargs, &sub_format, &sub_keywords)) return NULL; if (!(PyList_CheckExact(sub_keywords) || PyTuple_CheckExact(sub_keywords))) { PyErr_SetString(PyExc_ValueError, "parse_tuple_and_keywords: sub_keywords must be either list or tuple"); return NULL; } memset(buffers, 0, sizeof(buffers)); memset(converted, 0, sizeof(converted)); memset(keywords, 0, sizeof(keywords)); size = PySequence_Fast_GET_SIZE(sub_keywords); if (size > 8) { PyErr_SetString(PyExc_ValueError, "parse_tuple_and_keywords: too many keywords in sub_keywords"); goto exit; } for (i = 0; i < size; i++) { o = PySequence_Fast_GET_ITEM(sub_keywords, i); if (!PyUnicode_FSConverter(o, (void *)(converted + i))) { PyErr_Format(PyExc_ValueError, "parse_tuple_and_keywords: could not convert keywords[%zd] to narrow string", i); goto exit; } keywords[i] = PyBytes_AS_STRING(converted[i]); } result = PyArg_ParseTupleAndKeywords(sub_args, sub_kwargs, sub_format, keywords, buffers + 0, buffers + 1, buffers + 2, buffers + 3, buffers + 4, buffers + 5, buffers + 6, buffers + 7); if (result) { return_value = Py_None; Py_INCREF(Py_None); } exit: size = sizeof(converted) / sizeof(converted[0]); for (i = 0; i < size; i++) { Py_XDECREF(converted[i]); } return return_value; } static volatile int x; /* Test the u and u# codes for PyArg_ParseTuple. May leak memory in case of an error. */ static PyObject * test_u_code(PyObject *self) { PyObject *tuple, *obj; Py_UNICODE *value; Py_ssize_t len; /* issue4122: Undefined reference to _Py_ascii_whitespace on Windows */ /* Just use the macro and check that it compiles */ x = Py_UNICODE_ISSPACE(25); tuple = PyTuple_New(1); if (tuple == NULL) return NULL; obj = PyUnicode_Decode("test", strlen("test"), "ascii", NULL); if (obj == NULL) return NULL; PyTuple_SET_ITEM(tuple, 0, obj); value = 0; if (PyArg_ParseTuple(tuple, "u:test_u_code", &value) < 0) return NULL; if (value != PyUnicode_AS_UNICODE(obj)) return raiseTestError("test_u_code", "u code returned wrong value for u'test'"); value = 0; if (PyArg_ParseTuple(tuple, "u#:test_u_code", &value, &len) < 0) return NULL; if (value != PyUnicode_AS_UNICODE(obj) || len != PyUnicode_GET_SIZE(obj)) return raiseTestError("test_u_code", "u# code returned wrong values for u'test'"); Py_DECREF(tuple); Py_INCREF(Py_None); return Py_None; } /* Test Z and Z# codes for PyArg_ParseTuple */ static PyObject * test_Z_code(PyObject *self) { PyObject *tuple, *obj; const Py_UNICODE *value1, *value2; Py_ssize_t len1, len2; tuple = PyTuple_New(2); if (tuple == NULL) return NULL; obj = PyUnicode_FromString("test"); PyTuple_SET_ITEM(tuple, 0, obj); Py_INCREF(Py_None); PyTuple_SET_ITEM(tuple, 1, Py_None); /* swap values on purpose */ value1 = NULL; value2 = PyUnicode_AS_UNICODE(obj); /* Test Z for both values */ if (PyArg_ParseTuple(tuple, "ZZ:test_Z_code", &value1, &value2) < 0) return NULL; if (value1 != PyUnicode_AS_UNICODE(obj)) return raiseTestError("test_Z_code", "Z code returned wrong value for 'test'"); if (value2 != NULL) return raiseTestError("test_Z_code", "Z code returned wrong value for None"); value1 = NULL; value2 = PyUnicode_AS_UNICODE(obj); len1 = -1; len2 = -1; /* Test Z# for both values */ if (PyArg_ParseTuple(tuple, "Z#Z#:test_Z_code", &value1, &len1, &value2, &len2) < 0) return NULL; if (value1 != PyUnicode_AS_UNICODE(obj) || len1 != PyUnicode_GET_SIZE(obj)) return raiseTestError("test_Z_code", "Z# code returned wrong values for 'test'"); if (value2 != NULL || len2 != 0) return raiseTestError("test_Z_code", "Z# code returned wrong values for None'"); Py_DECREF(tuple); Py_RETURN_NONE; } static PyObject * test_widechar(PyObject *self) { #if defined(SIZEOF_WCHAR_T) && (SIZEOF_WCHAR_T == 4) const wchar_t wtext[2] = {(wchar_t)0x10ABCDu}; size_t wtextlen = 1; const wchar_t invalid[1] = {(wchar_t)0x110000u}; #else const wchar_t wtext[3] = {(wchar_t)0xDBEAu, (wchar_t)0xDFCDu}; size_t wtextlen = 2; #endif PyObject *wide, *utf8; wide = PyUnicode_FromWideChar(wtext, wtextlen); if (wide == NULL) return NULL; utf8 = PyUnicode_FromString("\xf4\x8a\xaf\x8d"); if (utf8 == NULL) { Py_DECREF(wide); return NULL; } if (PyUnicode_GET_LENGTH(wide) != PyUnicode_GET_LENGTH(utf8)) { Py_DECREF(wide); Py_DECREF(utf8); return raiseTestError("test_widechar", "wide string and utf8 string " "have different length"); } if (PyUnicode_Compare(wide, utf8)) { Py_DECREF(wide); Py_DECREF(utf8); if (PyErr_Occurred()) return NULL; return raiseTestError("test_widechar", "wide string and utf8 string " "are different"); } Py_DECREF(wide); Py_DECREF(utf8); #if defined(SIZEOF_WCHAR_T) && (SIZEOF_WCHAR_T == 4) wide = PyUnicode_FromWideChar(invalid, 1); if (wide == NULL) PyErr_Clear(); else return raiseTestError("test_widechar", "PyUnicode_FromWideChar(L\"\\U00110000\", 1) didn't fail"); wide = PyUnicode_FromUnicode(invalid, 1); if (wide == NULL) PyErr_Clear(); else return raiseTestError("test_widechar", "PyUnicode_FromUnicode(L\"\\U00110000\", 1) didn't fail"); wide = PyUnicode_FromUnicode(NULL, 1); if (wide == NULL) return NULL; PyUnicode_AS_UNICODE(wide)[0] = invalid[0]; if (_PyUnicode_Ready(wide) < 0) { Py_DECREF(wide); PyErr_Clear(); } else { Py_DECREF(wide); return raiseTestError("test_widechar", "PyUnicode_Ready() didn't fail"); } #endif Py_RETURN_NONE; } static PyObject * unicode_aswidechar(PyObject *self, PyObject *args) { PyObject *unicode, *result; Py_ssize_t buflen, size; wchar_t *buffer; if (!PyArg_ParseTuple(args, "Un", &unicode, &buflen)) return NULL; buffer = PyMem_Malloc(buflen * sizeof(wchar_t)); if (buffer == NULL) return PyErr_NoMemory(); size = PyUnicode_AsWideChar(unicode, buffer, buflen); if (size == -1) { PyMem_Free(buffer); return NULL; } if (size < buflen) buflen = size + 1; else buflen = size; result = PyUnicode_FromWideChar(buffer, buflen); PyMem_Free(buffer); if (result == NULL) return NULL; return Py_BuildValue("(Nn)", result, size); } static PyObject * unicode_aswidecharstring(PyObject *self, PyObject *args) { PyObject *unicode, *result; Py_ssize_t size; wchar_t *buffer; if (!PyArg_ParseTuple(args, "U", &unicode)) return NULL; buffer = PyUnicode_AsWideCharString(unicode, &size); if (buffer == NULL) return NULL; result = PyUnicode_FromWideChar(buffer, size + 1); PyMem_Free(buffer); if (result == NULL) return NULL; return Py_BuildValue("(Nn)", result, size); } static PyObject * unicode_encodedecimal(PyObject *self, PyObject *args) { Py_UNICODE *unicode; Py_ssize_t length; char *errors = NULL; PyObject *decimal; Py_ssize_t decimal_length, new_length; int res; if (!PyArg_ParseTuple(args, "u#|s", &unicode, &length, &errors)) return NULL; decimal_length = length * 7; /* len('&#8364;') */ decimal = PyBytes_FromStringAndSize(NULL, decimal_length); if (decimal == NULL) return NULL; res = PyUnicode_EncodeDecimal(unicode, length, PyBytes_AS_STRING(decimal), errors); if (res < 0) { Py_DECREF(decimal); return NULL; } new_length = strlen(PyBytes_AS_STRING(decimal)); assert(new_length <= decimal_length); res = _PyBytes_Resize(&decimal, new_length); if (res < 0) return NULL; return decimal; } static PyObject * unicode_transformdecimaltoascii(PyObject *self, PyObject *args) { Py_UNICODE *unicode; Py_ssize_t length; if (!PyArg_ParseTuple(args, "u#|s", &unicode, &length)) return NULL; return PyUnicode_TransformDecimalToASCII(unicode, length); } static PyObject * unicode_legacy_string(PyObject *self, PyObject *args) { Py_UNICODE *data; Py_ssize_t len; PyObject *u; if (!PyArg_ParseTuple(args, "u#", &data, &len)) return NULL; u = PyUnicode_FromUnicode(NULL, len); if (u == NULL) return NULL; memcpy(PyUnicode_AS_UNICODE(u), data, len * sizeof(Py_UNICODE)); if (len > 0) { /* The empty string is always ready. */ assert(!PyUnicode_IS_READY(u)); } return u; } static PyObject * getargs_w_star(PyObject *self, PyObject *args) { Py_buffer buffer; PyObject *result; char *str; if (!PyArg_ParseTuple(args, "w*:getargs_w_star", &buffer)) return NULL; if (2 <= buffer.len) { str = buffer.buf; str[0] = '['; str[buffer.len-1] = ']'; } result = PyBytes_FromStringAndSize(buffer.buf, buffer.len); PyBuffer_Release(&buffer); return result; } static PyObject * test_empty_argparse(PyObject *self) { /* Test that formats can begin with '|'. See issue #4720. */ PyObject *tuple, *dict = NULL; static char *kwlist[] = {NULL}; int result; tuple = PyTuple_New(0); if (!tuple) return NULL; if ((result = PyArg_ParseTuple(tuple, "|:test_empty_argparse")) < 0) goto done; dict = PyDict_New(); if (!dict) goto done; result = PyArg_ParseTupleAndKeywords(tuple, dict, "|:test_empty_argparse", kwlist); done: Py_DECREF(tuple); Py_XDECREF(dict); if (result < 0) return NULL; else { Py_RETURN_NONE; } } static PyObject * codec_incrementalencoder(PyObject *self, PyObject *args) { const char *encoding, *errors = NULL; if (!PyArg_ParseTuple(args, "s|s:test_incrementalencoder", &encoding, &errors)) return NULL; return PyCodec_IncrementalEncoder(encoding, errors); } static PyObject * codec_incrementaldecoder(PyObject *self, PyObject *args) { const char *encoding, *errors = NULL; if (!PyArg_ParseTuple(args, "s|s:test_incrementaldecoder", &encoding, &errors)) return NULL; return PyCodec_IncrementalDecoder(encoding, errors); } /* Simple test of _PyLong_NumBits and _PyLong_Sign. */ static PyObject * test_long_numbits(PyObject *self) { struct triple { long input; size_t nbits; int sign; } testcases[] = {{0, 0, 0}, {1L, 1, 1}, {-1L, 1, -1}, {2L, 2, 1}, {-2L, 2, -1}, {3L, 2, 1}, {-3L, 2, -1}, {4L, 3, 1}, {-4L, 3, -1}, {0x7fffL, 15, 1}, /* one Python int digit */ {-0x7fffL, 15, -1}, {0xffffL, 16, 1}, {-0xffffL, 16, -1}, {0xfffffffL, 28, 1}, {-0xfffffffL, 28, -1}}; int i; for (i = 0; i < Py_ARRAY_LENGTH(testcases); ++i) { size_t nbits; int sign; PyObject *plong; plong = PyLong_FromLong(testcases[i].input); if (plong == NULL) return NULL; nbits = _PyLong_NumBits(plong); sign = _PyLong_Sign(plong); Py_DECREF(plong); if (nbits != testcases[i].nbits) return raiseTestError("test_long_numbits", "wrong result for _PyLong_NumBits"); if (sign != testcases[i].sign) return raiseTestError("test_long_numbits", "wrong result for _PyLong_Sign"); } Py_INCREF(Py_None); return Py_None; } /* Example passing NULLs to PyObject_Str(NULL). */ static PyObject * test_null_strings(PyObject *self) { PyObject *o1 = PyObject_Str(NULL), *o2 = PyObject_Str(NULL); PyObject *tuple = PyTuple_Pack(2, o1, o2); Py_XDECREF(o1); Py_XDECREF(o2); return tuple; } static PyObject * raise_exception(PyObject *self, PyObject *args) { PyObject *exc; PyObject *exc_args, *v; int num_args, i; if (!PyArg_ParseTuple(args, "Oi:raise_exception", &exc, &num_args)) return NULL; exc_args = PyTuple_New(num_args); if (exc_args == NULL) return NULL; for (i = 0; i < num_args; ++i) { v = PyLong_FromLong(i); if (v == NULL) { Py_DECREF(exc_args); return NULL; } PyTuple_SET_ITEM(exc_args, i, v); } PyErr_SetObject(exc, exc_args); Py_DECREF(exc_args); return NULL; } static PyObject * test_set_exc_info(PyObject *self, PyObject *args) { PyObject *orig_exc; PyObject *new_type, *new_value, *new_tb; PyObject *type, *value, *tb; if (!PyArg_ParseTuple(args, "OOO:test_set_exc_info", &new_type, &new_value, &new_tb)) return NULL; PyErr_GetExcInfo(&type, &value, &tb); Py_INCREF(new_type); Py_INCREF(new_value); Py_INCREF(new_tb); PyErr_SetExcInfo(new_type, new_value, new_tb); orig_exc = PyTuple_Pack(3, type ? type : Py_None, value ? value : Py_None, tb ? tb : Py_None); Py_XDECREF(type); Py_XDECREF(value); Py_XDECREF(tb); return orig_exc; } static int test_run_counter = 0; static PyObject * test_datetime_capi(PyObject *self, PyObject *args) { if (PyDateTimeAPI) { if (test_run_counter) { /* Probably regrtest.py -R */ Py_RETURN_NONE; } else { PyErr_SetString(PyExc_AssertionError, "PyDateTime_CAPI somehow initialized"); return NULL; } } test_run_counter++; PyDateTime_IMPORT; if (PyDateTimeAPI) Py_RETURN_NONE; else return NULL; } #ifdef WITH_THREAD /* test_thread_state spawns a thread of its own, and that thread releases * `thread_done` when it's finished. The driver code has to know when the * thread finishes, because the thread uses a PyObject (the callable) that * may go away when the driver finishes. The former lack of this explicit * synchronization caused rare segfaults, so rare that they were seen only * on a Mac buildbot (although they were possible on any box). */ static PyThread_type_lock thread_done = NULL; static int _make_call(void *callable) { PyObject *rc; int success; PyGILState_STATE s = PyGILState_Ensure(); rc = PyObject_CallFunction((PyObject *)callable, ""); success = (rc != NULL); Py_XDECREF(rc); PyGILState_Release(s); return success; } /* Same thing, but releases `thread_done` when it returns. This variant * should be called only from threads spawned by test_thread_state(). */ static void _make_call_from_thread(void *callable) { _make_call(callable); PyThread_release_lock(thread_done); } static PyObject * test_thread_state(PyObject *self, PyObject *args) { PyObject *fn; int success = 1; if (!PyArg_ParseTuple(args, "O:test_thread_state", &fn)) return NULL; if (!PyCallable_Check(fn)) { PyErr_Format(PyExc_TypeError, "'%s' object is not callable", fn->ob_type->tp_name); return NULL; } /* Ensure Python is set up for threading */ PyEval_InitThreads(); thread_done = PyThread_allocate_lock(); if (thread_done == NULL) return PyErr_NoMemory(); PyThread_acquire_lock(thread_done, 1); /* Start a new thread with our callback. */ PyThread_start_new_thread(_make_call_from_thread, fn); /* Make the callback with the thread lock held by this thread */ success &= _make_call(fn); /* Do it all again, but this time with the thread-lock released */ Py_BEGIN_ALLOW_THREADS success &= _make_call(fn); PyThread_acquire_lock(thread_done, 1); /* wait for thread to finish */ Py_END_ALLOW_THREADS /* And once more with and without a thread XXX - should use a lock and work out exactly what we are trying to test <wink> */ Py_BEGIN_ALLOW_THREADS PyThread_start_new_thread(_make_call_from_thread, fn); success &= _make_call(fn); PyThread_acquire_lock(thread_done, 1); /* wait for thread to finish */ Py_END_ALLOW_THREADS /* Release lock we acquired above. This is required on HP-UX. */ PyThread_release_lock(thread_done); PyThread_free_lock(thread_done); if (!success) return NULL; Py_RETURN_NONE; } /* test Py_AddPendingCalls using threads */ static int _pending_callback(void *arg) { /* we assume the argument is callable object to which we own a reference */ PyObject *callable = (PyObject *)arg; PyObject *r = PyObject_CallObject(callable, NULL); Py_DECREF(callable); Py_XDECREF(r); return r != NULL ? 0 : -1; } /* The following requests n callbacks to _pending_callback. It can be * run from any python thread. */ PyObject *pending_threadfunc(PyObject *self, PyObject *arg) { PyObject *callable; int r; if (PyArg_ParseTuple(arg, "O", &callable) == 0) return NULL; /* create the reference for the callbackwhile we hold the lock */ Py_INCREF(callable); Py_BEGIN_ALLOW_THREADS r = Py_AddPendingCall(&_pending_callback, callable); Py_END_ALLOW_THREADS if (r<0) { Py_DECREF(callable); /* unsuccessful add, destroy the extra reference */ Py_INCREF(Py_False); return Py_False; } Py_INCREF(Py_True); return Py_True; } #endif /* Some tests of PyUnicode_FromFormat(). This needs more tests. */ static PyObject * test_string_from_format(PyObject *self, PyObject *args) { PyObject *result; char *msg; #define CHECK_1_FORMAT(FORMAT, TYPE) \ result = PyUnicode_FromFormat(FORMAT, (TYPE)1); \ if (result == NULL) \ return NULL; \ if (PyUnicode_CompareWithASCIIString(result, "1")) { \ msg = FORMAT " failed at 1"; \ goto Fail; \ } \ Py_DECREF(result) CHECK_1_FORMAT("%d", int); CHECK_1_FORMAT("%ld", long); /* The z width modifier was added in Python 2.5. */ CHECK_1_FORMAT("%zd", Py_ssize_t); /* The u type code was added in Python 2.5. */ CHECK_1_FORMAT("%u", unsigned int); CHECK_1_FORMAT("%lu", unsigned long); CHECK_1_FORMAT("%zu", size_t); /* "%lld" and "%llu" support added in Python 2.7. */ #ifdef HAVE_LONG_LONG CHECK_1_FORMAT("%llu", unsigned PY_LONG_LONG); CHECK_1_FORMAT("%lld", PY_LONG_LONG); #endif Py_RETURN_NONE; Fail: Py_XDECREF(result); return raiseTestError("test_string_from_format", msg); #undef CHECK_1_FORMAT } static PyObject * test_unicode_compare_with_ascii(PyObject *self) { PyObject *py_s = PyUnicode_FromStringAndSize("str\0", 4); int result; if (py_s == NULL) return NULL; result = PyUnicode_CompareWithASCIIString(py_s, "str"); Py_DECREF(py_s); if (!result) { PyErr_SetString(TestError, "Python string ending in NULL " "should not compare equal to c string."); return NULL; } Py_RETURN_NONE; } /* This is here to provide a docstring for test_descr. */ static PyObject * test_with_docstring(PyObject *self) { Py_RETURN_NONE; } /* Test PyOS_string_to_double. */ static PyObject * test_string_to_double(PyObject *self) { double result; char *msg; #define CHECK_STRING(STR, expected) \ result = PyOS_string_to_double(STR, NULL, NULL); \ if (result == -1.0 && PyErr_Occurred()) \ return NULL; \ if (result != expected) { \ msg = "conversion of " STR " to float failed"; \ goto fail; \ } #define CHECK_INVALID(STR) \ result = PyOS_string_to_double(STR, NULL, NULL); \ if (result == -1.0 && PyErr_Occurred()) { \ if (PyErr_ExceptionMatches(PyExc_ValueError)) \ PyErr_Clear(); \ else \ return NULL; \ } \ else { \ msg = "conversion of " STR " didn't raise ValueError"; \ goto fail; \ } CHECK_STRING("0.1", 0.1); CHECK_STRING("1.234", 1.234); CHECK_STRING("-1.35", -1.35); CHECK_STRING(".1e01", 1.0); CHECK_STRING("2.e-2", 0.02); CHECK_INVALID(" 0.1"); CHECK_INVALID("\t\n-3"); CHECK_INVALID(".123 "); CHECK_INVALID("3\n"); CHECK_INVALID("123abc"); Py_RETURN_NONE; fail: return raiseTestError("test_string_to_double", msg); #undef CHECK_STRING #undef CHECK_INVALID } /* Coverage testing of capsule objects. */ static const char *capsule_name = "capsule name"; static char *capsule_pointer = "capsule pointer"; static char *capsule_context = "capsule context"; static const char *capsule_error = NULL; static int capsule_destructor_call_count = 0; static void capsule_destructor(PyObject *o) { capsule_destructor_call_count++; if (PyCapsule_GetContext(o) != capsule_context) { capsule_error = "context did not match in destructor!"; } else if (PyCapsule_GetDestructor(o) != capsule_destructor) { capsule_error = "destructor did not match in destructor! (woah!)"; } else if (PyCapsule_GetName(o) != capsule_name) { capsule_error = "name did not match in destructor!"; } else if (PyCapsule_GetPointer(o, capsule_name) != capsule_pointer) { capsule_error = "pointer did not match in destructor!"; } } typedef struct { char *name; char *module; char *attribute; } known_capsule; static PyObject * test_capsule(PyObject *self, PyObject *args) { PyObject *object; const char *error = NULL; void *pointer; void *pointer2; known_capsule known_capsules[] = { #define KNOWN_CAPSULE(module, name) { module "." name, module, name } KNOWN_CAPSULE("_socket", "CAPI"), KNOWN_CAPSULE("_curses", "_C_API"), KNOWN_CAPSULE("datetime", "datetime_CAPI"), { NULL, NULL }, }; known_capsule *known = &known_capsules[0]; #define FAIL(x) { error = (x); goto exit; } #define CHECK_DESTRUCTOR \ if (capsule_error) { \ FAIL(capsule_error); \ } \ else if (!capsule_destructor_call_count) { \ FAIL("destructor not called!"); \ } \ capsule_destructor_call_count = 0; \ object = PyCapsule_New(capsule_pointer, capsule_name, capsule_destructor); PyCapsule_SetContext(object, capsule_context); capsule_destructor(object); CHECK_DESTRUCTOR; Py_DECREF(object); CHECK_DESTRUCTOR; object = PyCapsule_New(known, "ignored", NULL); PyCapsule_SetPointer(object, capsule_pointer); PyCapsule_SetName(object, capsule_name); PyCapsule_SetDestructor(object, capsule_destructor); PyCapsule_SetContext(object, capsule_context); capsule_destructor(object); CHECK_DESTRUCTOR; /* intentionally access using the wrong name */ pointer2 = PyCapsule_GetPointer(object, "the wrong name"); if (!PyErr_Occurred()) { FAIL("PyCapsule_GetPointer should have failed but did not!"); } PyErr_Clear(); if (pointer2) { if (pointer2 == capsule_pointer) { FAIL("PyCapsule_GetPointer should not have" " returned the internal pointer!"); } else { FAIL("PyCapsule_GetPointer should have " "returned NULL pointer but did not!"); } } PyCapsule_SetDestructor(object, NULL); Py_DECREF(object); if (capsule_destructor_call_count) { FAIL("destructor called when it should not have been!"); } for (known = &known_capsules[0]; known->module != NULL; known++) { /* yeah, ordinarily I wouldn't do this either, but it's fine for this test harness. */ static char buffer[256]; #undef FAIL #define FAIL(x) \ { \ sprintf(buffer, "%s module: \"%s\" attribute: \"%s\"", \ x, known->module, known->attribute); \ error = buffer; \ goto exit; \ } \ PyObject *module = PyImport_ImportModule(known->module); if (module) { pointer = PyCapsule_Import(known->name, 0); if (!pointer) { Py_DECREF(module); FAIL("PyCapsule_GetPointer returned NULL unexpectedly!"); } object = PyObject_GetAttrString(module, known->attribute); if (!object) { Py_DECREF(module); return NULL; } pointer2 = PyCapsule_GetPointer(object, "weebles wobble but they don't fall down"); if (!PyErr_Occurred()) { Py_DECREF(object); Py_DECREF(module); FAIL("PyCapsule_GetPointer should have failed but did not!"); } PyErr_Clear(); if (pointer2) { Py_DECREF(module); Py_DECREF(object); if (pointer2 == pointer) { FAIL("PyCapsule_GetPointer should not have" " returned its internal pointer!"); } else { FAIL("PyCapsule_GetPointer should have" " returned NULL pointer but did not!"); } } Py_DECREF(object); Py_DECREF(module); } else PyErr_Clear(); } exit: if (error) { return raiseTestError("test_capsule", error); } Py_RETURN_NONE; #undef FAIL } #ifdef HAVE_GETTIMEOFDAY /* Profiling of integer performance */ static void print_delta(int test, struct timeval *s, struct timeval *e) { e->tv_sec -= s->tv_sec; e->tv_usec -= s->tv_usec; if (e->tv_usec < 0) { e->tv_sec -=1; e->tv_usec += 1000000; } printf("Test %d: %d.%06ds\n", test, (int)e->tv_sec, (int)e->tv_usec); } static PyObject * profile_int(PyObject *self, PyObject* args) { int i, k; struct timeval start, stop; PyObject *single, **multiple, *op1, *result; /* Test 1: Allocate and immediately deallocate many small integers */ gettimeofday(&start, NULL); for(k=0; k < 20000; k++) for(i=0; i < 1000; i++) { single = PyLong_FromLong(i); Py_DECREF(single); } gettimeofday(&stop, NULL); print_delta(1, &start, &stop); /* Test 2: Allocate and immediately deallocate many large integers */ gettimeofday(&start, NULL); for(k=0; k < 20000; k++) for(i=0; i < 1000; i++) { single = PyLong_FromLong(i+1000000); Py_DECREF(single); } gettimeofday(&stop, NULL); print_delta(2, &start, &stop); /* Test 3: Allocate a few integers, then release them all simultaneously. */ multiple = malloc(sizeof(PyObject*) * 1000); if (multiple == NULL) return PyErr_NoMemory(); gettimeofday(&start, NULL); for(k=0; k < 20000; k++) { for(i=0; i < 1000; i++) { multiple[i] = PyLong_FromLong(i+1000000); } for(i=0; i < 1000; i++) { Py_DECREF(multiple[i]); } } gettimeofday(&stop, NULL); print_delta(3, &start, &stop); free(multiple); /* Test 4: Allocate many integers, then release them all simultaneously. */ multiple = malloc(sizeof(PyObject*) * 1000000); if (multiple == NULL) return PyErr_NoMemory(); gettimeofday(&start, NULL); for(k=0; k < 20; k++) { for(i=0; i < 1000000; i++) { multiple[i] = PyLong_FromLong(i+1000000); } for(i=0; i < 1000000; i++) { Py_DECREF(multiple[i]); } } gettimeofday(&stop, NULL); print_delta(4, &start, &stop); free(multiple); /* Test 5: Allocate many integers < 32000 */ multiple = malloc(sizeof(PyObject*) * 1000000); if (multiple == NULL) return PyErr_NoMemory(); gettimeofday(&start, NULL); for(k=0; k < 10; k++) { for(i=0; i < 1000000; i++) { multiple[i] = PyLong_FromLong(i+1000); } for(i=0; i < 1000000; i++) { Py_DECREF(multiple[i]); } } gettimeofday(&stop, NULL); print_delta(5, &start, &stop); free(multiple); /* Test 6: Perform small int addition */ op1 = PyLong_FromLong(1); gettimeofday(&start, NULL); for(i=0; i < 10000000; i++) { result = PyNumber_Add(op1, op1); Py_DECREF(result); } gettimeofday(&stop, NULL); Py_DECREF(op1); print_delta(6, &start, &stop); /* Test 7: Perform medium int addition */ op1 = PyLong_FromLong(1000); if (op1 == NULL) return NULL; gettimeofday(&start, NULL); for(i=0; i < 10000000; i++) { result = PyNumber_Add(op1, op1); Py_XDECREF(result); } gettimeofday(&stop, NULL); Py_DECREF(op1); print_delta(7, &start, &stop); Py_INCREF(Py_None); return Py_None; } #endif /* To test the format of tracebacks as printed out. */ static PyObject * traceback_print(PyObject *self, PyObject *args) { PyObject *file; PyObject *traceback; int result; if (!PyArg_ParseTuple(args, "OO:traceback_print", &traceback, &file)) return NULL; result = PyTraceBack_Print(traceback, file); if (result < 0) return NULL; Py_RETURN_NONE; } /* To test the format of exceptions as printed out. */ static PyObject * exception_print(PyObject *self, PyObject *args) { PyObject *value; PyObject *tb; if (!PyArg_ParseTuple(args, "O:exception_print", &value)) return NULL; if (!PyExceptionInstance_Check(value)) { PyErr_Format(PyExc_TypeError, "an exception instance is required"); return NULL; } tb = PyException_GetTraceback(value); PyErr_Display((PyObject *) Py_TYPE(value), value, tb); Py_XDECREF(tb); Py_RETURN_NONE; } /* reliably raise a MemoryError */ static PyObject * raise_memoryerror(PyObject *self) { PyErr_NoMemory(); return NULL; } /* Issue 6012 */ static PyObject *str1, *str2; static int failing_converter(PyObject *obj, void *arg) { /* Clone str1, then let the conversion fail. */ assert(str1); str2 = str1; Py_INCREF(str2); return 0; } static PyObject* argparsing(PyObject *o, PyObject *args) { PyObject *res; str1 = str2 = NULL; if (!PyArg_ParseTuple(args, "O&O&", PyUnicode_FSConverter, &str1, failing_converter, &str2)) { if (!str2) /* argument converter not called? */ return NULL; /* Should be 1 */ res = PyLong_FromSsize_t(Py_REFCNT(str2)); Py_DECREF(str2); PyErr_Clear(); return res; } Py_RETURN_NONE; } /* To test that the result of PyCode_NewEmpty has the right members. */ static PyObject * code_newempty(PyObject *self, PyObject *args) { const char *filename; const char *funcname; int firstlineno; if (!PyArg_ParseTuple(args, "ssi:code_newempty", &filename, &funcname, &firstlineno)) return NULL; return (PyObject *)PyCode_NewEmpty(filename, funcname, firstlineno); } /* Test PyErr_NewExceptionWithDoc (also exercise PyErr_NewException). Run via Lib/test/test_exceptions.py */ static PyObject * make_exception_with_doc(PyObject *self, PyObject *args, PyObject *kwargs) { const char *name; const char *doc = NULL; PyObject *base = NULL; PyObject *dict = NULL; static char *kwlist[] = {"name", "doc", "base", "dict", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|sOO:make_exception_with_doc", kwlist, &name, &doc, &base, &dict)) return NULL; return PyErr_NewExceptionWithDoc(name, doc, base, dict); } static PyObject * make_memoryview_from_NULL_pointer(PyObject *self) { Py_buffer info; if (PyBuffer_FillInfo(&info, NULL, NULL, 1, 1, PyBUF_FULL_RO) < 0) return NULL; return PyMemoryView_FromBuffer(&info); } /* Test that the fatal error from not having a current thread doesn't cause an infinite loop. Run via Lib/test/test_capi.py */ static PyObject * crash_no_current_thread(PyObject *self) { Py_BEGIN_ALLOW_THREADS /* Using PyThreadState_Get() directly allows the test to pass in !pydebug mode. However, the test only actually tests anything in pydebug mode, since that's where the infinite loop was in the first place. */ PyThreadState_Get(); Py_END_ALLOW_THREADS return NULL; } /* To run some code in a sub-interpreter. */ static PyObject * run_in_subinterp(PyObject *self, PyObject *args) { const char *code; int r; PyThreadState *substate, *mainstate; if (!PyArg_ParseTuple(args, "s:run_in_subinterp", &code)) return NULL; mainstate = PyThreadState_Get(); PyThreadState_Swap(NULL); substate = Py_NewInterpreter(); if (substate == NULL) { /* Since no new thread state was created, there is no exception to propagate; raise a fresh one after swapping in the old thread state. */ PyThreadState_Swap(mainstate); PyErr_SetString(PyExc_RuntimeError, "sub-interpreter creation failed"); return NULL; } r = PyRun_SimpleString(code); Py_EndInterpreter(substate); PyThreadState_Swap(mainstate); return PyLong_FromLong(r); } static PyObject * test_pytime_object_to_time_t(PyObject *self, PyObject *args) { PyObject *obj; time_t sec; if (!PyArg_ParseTuple(args, "O:pytime_object_to_time_t", &obj)) return NULL; if (_PyTime_ObjectToTime_t(obj, &sec) == -1) return NULL; return _PyLong_FromTime_t(sec); } static PyObject * test_pytime_object_to_timeval(PyObject *self, PyObject *args) { PyObject *obj; time_t sec; long usec; if (!PyArg_ParseTuple(args, "O:pytime_object_to_timeval", &obj)) return NULL; if (_PyTime_ObjectToTimeval(obj, &sec, &usec) == -1) return NULL; return Py_BuildValue("Nl", _PyLong_FromTime_t(sec), usec); } static PyObject * test_pytime_object_to_timespec(PyObject *self, PyObject *args) { PyObject *obj; time_t sec; long nsec; if (!PyArg_ParseTuple(args, "O:pytime_object_to_timespec", &obj)) return NULL; if (_PyTime_ObjectToTimespec(obj, &sec, &nsec) == -1) return NULL; return Py_BuildValue("Nl", _PyLong_FromTime_t(sec), nsec); } static void slot_tp_del(PyObject *self) { _Py_IDENTIFIER(__tp_del__); PyObject *del, *res; PyObject *error_type, *error_value, *error_traceback; /* Temporarily resurrect the object. */ assert(self->ob_refcnt == 0); self->ob_refcnt = 1; /* Save the current exception, if any. */ PyErr_Fetch(&error_type, &error_value, &error_traceback); /* Execute __del__ method, if any. */ del = _PyObject_LookupSpecial(self, &PyId___tp_del__); if (del != NULL) { res = PyEval_CallObject(del, NULL); if (res == NULL) PyErr_WriteUnraisable(del); else Py_DECREF(res); Py_DECREF(del); } /* Restore the saved exception. */ PyErr_Restore(error_type, error_value, error_traceback); /* Undo the temporary resurrection; can't use DECREF here, it would * cause a recursive call. */ assert(self->ob_refcnt > 0); if (--self->ob_refcnt == 0) return; /* this is the normal path out */ /* __del__ resurrected it! Make it look like the original Py_DECREF * never happened. */ { Py_ssize_t refcnt = self->ob_refcnt; _Py_NewReference(self); self->ob_refcnt = refcnt; } assert(!PyType_IS_GC(Py_TYPE(self)) || _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED); /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so * we need to undo that. */ _Py_DEC_REFTOTAL; /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object * chain, so no more to do there. * If COUNT_ALLOCS, the original decref bumped tp_frees, and * _Py_NewReference bumped tp_allocs: both of those need to be * undone. */ #ifdef COUNT_ALLOCS --Py_TYPE(self)->tp_frees; --Py_TYPE(self)->tp_allocs; #endif } static PyObject * with_tp_del(PyObject *self, PyObject *args) { PyObject *obj; PyTypeObject *tp; if (!PyArg_ParseTuple(args, "O:with_tp_del", &obj)) return NULL; tp = (PyTypeObject *) obj; if (!PyType_Check(obj) || !PyType_HasFeature(tp, Py_TPFLAGS_HEAPTYPE)) { PyErr_Format(PyExc_TypeError, "heap type expected, got %R", obj); return NULL; } tp->tp_del = slot_tp_del; Py_INCREF(obj); return obj; } static PyObject * _test_incref(PyObject *ob) { Py_INCREF(ob); return ob; } static PyObject * test_xincref_doesnt_leak(PyObject *ob) { PyObject *obj = PyLong_FromLong(0); Py_XINCREF(_test_incref(obj)); Py_DECREF(obj); Py_DECREF(obj); Py_DECREF(obj); Py_RETURN_NONE; } static PyObject * test_incref_doesnt_leak(PyObject *ob) { PyObject *obj = PyLong_FromLong(0); Py_INCREF(_test_incref(obj)); Py_DECREF(obj); Py_DECREF(obj); Py_DECREF(obj); Py_RETURN_NONE; } static PyObject * test_xdecref_doesnt_leak(PyObject *ob) { Py_XDECREF(PyLong_FromLong(0)); Py_RETURN_NONE; } static PyObject * test_decref_doesnt_leak(PyObject *ob) { Py_DECREF(PyLong_FromLong(0)); Py_RETURN_NONE; } static PyObject * test_incref_decref_API(PyObject *ob) { PyObject *obj = PyLong_FromLong(0); Py_IncRef(ob); Py_DecRef(obj); Py_DecRef(obj); Py_RETURN_NONE; } static PyObject * test_pymem_alloc0(PyObject *self) { void *ptr; ptr = PyMem_Malloc(0); if (ptr == NULL) { PyErr_SetString(PyExc_RuntimeError, "PyMem_Malloc(0) returns NULL"); return NULL; } PyMem_Free(ptr); ptr = PyObject_Malloc(0); if (ptr == NULL) { PyErr_SetString(PyExc_RuntimeError, "PyObject_Malloc(0) returns NULL"); return NULL; } PyObject_Free(ptr); Py_RETURN_NONE; } typedef struct { PyMemAllocator alloc; size_t malloc_size; void *realloc_ptr; size_t realloc_new_size; void *free_ptr; } alloc_hook_t; static void* hook_malloc (void* ctx, size_t size) { alloc_hook_t *hook = (alloc_hook_t *)ctx; hook->malloc_size = size; return hook->alloc.malloc(hook->alloc.ctx, size); } static void* hook_realloc (void* ctx, void* ptr, size_t new_size) { alloc_hook_t *hook = (alloc_hook_t *)ctx; hook->realloc_ptr = ptr; hook->realloc_new_size = new_size; return hook->alloc.realloc(hook->alloc.ctx, ptr, new_size); } static void hook_free (void *ctx, void *ptr) { alloc_hook_t *hook = (alloc_hook_t *)ctx; hook->free_ptr = ptr; hook->alloc.free(hook->alloc.ctx, ptr); } static PyObject * test_setallocators(PyMemAllocatorDomain domain) { PyObject *res = NULL; const char *error_msg; alloc_hook_t hook; PyMemAllocator alloc; size_t size, size2; void *ptr, *ptr2; hook.malloc_size = 0; hook.realloc_ptr = NULL; hook.realloc_new_size = 0; hook.free_ptr = NULL; alloc.ctx = &hook; alloc.malloc = &hook_malloc; alloc.realloc = &hook_realloc; alloc.free = &hook_free; PyMem_GetAllocator(domain, &hook.alloc); PyMem_SetAllocator(domain, &alloc); size = 42; switch(domain) { case PYMEM_DOMAIN_RAW: ptr = PyMem_RawMalloc(size); break; case PYMEM_DOMAIN_MEM: ptr = PyMem_Malloc(size); break; case PYMEM_DOMAIN_OBJ: ptr = PyObject_Malloc(size); break; default: ptr = NULL; break; } if (ptr == NULL) { error_msg = "malloc failed"; goto fail; } if (hook.malloc_size != size) { error_msg = "malloc invalid size"; goto fail; } size2 = 200; switch(domain) { case PYMEM_DOMAIN_RAW: ptr2 = PyMem_RawRealloc(ptr, size2); break; case PYMEM_DOMAIN_MEM: ptr2 = PyMem_Realloc(ptr, size2); break; case PYMEM_DOMAIN_OBJ: ptr2 = PyObject_Realloc(ptr, size2); break; default: ptr2 = NULL; break; } if (ptr2 == NULL) { error_msg = "realloc failed"; goto fail; } if (hook.realloc_ptr != ptr || hook.realloc_new_size != size2) { error_msg = "realloc invalid parameters"; goto fail; } switch(domain) { case PYMEM_DOMAIN_RAW: PyMem_RawFree(ptr2); break; case PYMEM_DOMAIN_MEM: PyMem_Free(ptr2); break; case PYMEM_DOMAIN_OBJ: PyObject_Free(ptr2); break; } if (hook.free_ptr != ptr2) { error_msg = "free invalid pointer"; goto fail; } Py_INCREF(Py_None); res = Py_None; goto finally; fail: PyErr_SetString(PyExc_RuntimeError, error_msg); finally: PyMem_SetAllocator(domain, &hook.alloc); return res; } static PyObject * test_pymem_setrawallocators(PyObject *self) { return test_setallocators(PYMEM_DOMAIN_RAW); } static PyObject * test_pymem_setallocators(PyObject *self) { return test_setallocators(PYMEM_DOMAIN_MEM); } static PyObject * test_pyobject_setallocators(PyObject *self) { return test_setallocators(PYMEM_DOMAIN_OBJ); } static PyMethodDef TestMethods[] = { {"raise_exception", raise_exception, METH_VARARGS}, {"raise_memoryerror", (PyCFunction)raise_memoryerror, METH_NOARGS}, {"test_config", (PyCFunction)test_config, METH_NOARGS}, {"test_datetime_capi", test_datetime_capi, METH_NOARGS}, {"test_list_api", (PyCFunction)test_list_api, METH_NOARGS}, {"test_dict_iteration", (PyCFunction)test_dict_iteration,METH_NOARGS}, {"test_lazy_hash_inheritance", (PyCFunction)test_lazy_hash_inheritance,METH_NOARGS}, {"test_long_api", (PyCFunction)test_long_api, METH_NOARGS}, {"test_xincref_doesnt_leak",(PyCFunction)test_xincref_doesnt_leak, METH_NOARGS}, {"test_incref_doesnt_leak", (PyCFunction)test_incref_doesnt_leak, METH_NOARGS}, {"test_xdecref_doesnt_leak",(PyCFunction)test_xdecref_doesnt_leak, METH_NOARGS}, {"test_decref_doesnt_leak", (PyCFunction)test_decref_doesnt_leak, METH_NOARGS}, {"test_incref_decref_API", (PyCFunction)test_incref_decref_API, METH_NOARGS}, {"test_long_and_overflow", (PyCFunction)test_long_and_overflow, METH_NOARGS}, {"test_long_as_double", (PyCFunction)test_long_as_double,METH_NOARGS}, {"test_long_as_size_t", (PyCFunction)test_long_as_size_t,METH_NOARGS}, {"test_long_numbits", (PyCFunction)test_long_numbits, METH_NOARGS}, {"test_k_code", (PyCFunction)test_k_code, METH_NOARGS}, {"test_empty_argparse", (PyCFunction)test_empty_argparse,METH_NOARGS}, {"parse_tuple_and_keywords", parse_tuple_and_keywords, METH_VARARGS}, {"test_null_strings", (PyCFunction)test_null_strings, METH_NOARGS}, {"test_string_from_format", (PyCFunction)test_string_from_format, METH_NOARGS}, {"test_with_docstring", (PyCFunction)test_with_docstring, METH_NOARGS, PyDoc_STR("This is a pretty normal docstring.")}, {"test_string_to_double", (PyCFunction)test_string_to_double, METH_NOARGS}, {"test_unicode_compare_with_ascii", (PyCFunction)test_unicode_compare_with_ascii, METH_NOARGS}, {"test_capsule", (PyCFunction)test_capsule, METH_NOARGS}, {"getargs_tuple", getargs_tuple, METH_VARARGS}, {"getargs_keywords", (PyCFunction)getargs_keywords, METH_VARARGS|METH_KEYWORDS}, {"getargs_keyword_only", (PyCFunction)getargs_keyword_only, METH_VARARGS|METH_KEYWORDS}, {"getargs_b", getargs_b, METH_VARARGS}, {"getargs_B", getargs_B, METH_VARARGS}, {"getargs_h", getargs_h, METH_VARARGS}, {"getargs_H", getargs_H, METH_VARARGS}, {"getargs_I", getargs_I, METH_VARARGS}, {"getargs_k", getargs_k, METH_VARARGS}, {"getargs_i", getargs_i, METH_VARARGS}, {"getargs_l", getargs_l, METH_VARARGS}, {"getargs_n", getargs_n, METH_VARARGS}, {"getargs_p", getargs_p, METH_VARARGS}, #ifdef HAVE_LONG_LONG {"getargs_L", getargs_L, METH_VARARGS}, {"getargs_K", getargs_K, METH_VARARGS}, {"test_longlong_api", test_longlong_api, METH_NOARGS}, {"test_long_long_and_overflow", (PyCFunction)test_long_long_and_overflow, METH_NOARGS}, {"test_L_code", (PyCFunction)test_L_code, METH_NOARGS}, #endif {"getargs_c", getargs_c, METH_VARARGS}, {"getargs_s", getargs_s, METH_VARARGS}, {"getargs_s_star", getargs_s_star, METH_VARARGS}, {"getargs_s_hash", getargs_s_hash, METH_VARARGS}, {"getargs_z", getargs_z, METH_VARARGS}, {"getargs_z_star", getargs_z_star, METH_VARARGS}, {"getargs_z_hash", getargs_z_hash, METH_VARARGS}, {"getargs_y", getargs_y, METH_VARARGS}, {"getargs_y_star", getargs_y_star, METH_VARARGS}, {"getargs_y_hash", getargs_y_hash, METH_VARARGS}, {"getargs_u", getargs_u, METH_VARARGS}, {"getargs_u_hash", getargs_u_hash, METH_VARARGS}, {"getargs_Z", getargs_Z, METH_VARARGS}, {"getargs_Z_hash", getargs_Z_hash, METH_VARARGS}, {"getargs_w_star", getargs_w_star, METH_VARARGS}, {"codec_incrementalencoder", (PyCFunction)codec_incrementalencoder, METH_VARARGS}, {"codec_incrementaldecoder", (PyCFunction)codec_incrementaldecoder, METH_VARARGS}, {"test_s_code", (PyCFunction)test_s_code, METH_NOARGS}, {"test_u_code", (PyCFunction)test_u_code, METH_NOARGS}, {"test_Z_code", (PyCFunction)test_Z_code, METH_NOARGS}, {"test_widechar", (PyCFunction)test_widechar, METH_NOARGS}, {"unicode_aswidechar", unicode_aswidechar, METH_VARARGS}, {"unicode_aswidecharstring",unicode_aswidecharstring, METH_VARARGS}, {"unicode_encodedecimal", unicode_encodedecimal, METH_VARARGS}, {"unicode_transformdecimaltoascii", unicode_transformdecimaltoascii, METH_VARARGS}, {"unicode_legacy_string", unicode_legacy_string, METH_VARARGS}, #ifdef WITH_THREAD {"_test_thread_state", test_thread_state, METH_VARARGS}, {"_pending_threadfunc", pending_threadfunc, METH_VARARGS}, #endif #ifdef HAVE_GETTIMEOFDAY {"profile_int", profile_int, METH_NOARGS}, #endif {"traceback_print", traceback_print, METH_VARARGS}, {"exception_print", exception_print, METH_VARARGS}, {"set_exc_info", test_set_exc_info, METH_VARARGS}, {"argparsing", argparsing, METH_VARARGS}, {"code_newempty", code_newempty, METH_VARARGS}, {"make_exception_with_doc", (PyCFunction)make_exception_with_doc, METH_VARARGS | METH_KEYWORDS}, {"make_memoryview_from_NULL_pointer", (PyCFunction)make_memoryview_from_NULL_pointer, METH_NOARGS}, {"crash_no_current_thread", (PyCFunction)crash_no_current_thread, METH_NOARGS}, {"run_in_subinterp", run_in_subinterp, METH_VARARGS}, {"pytime_object_to_time_t", test_pytime_object_to_time_t, METH_VARARGS}, {"pytime_object_to_timeval", test_pytime_object_to_timeval, METH_VARARGS}, {"pytime_object_to_timespec", test_pytime_object_to_timespec, METH_VARARGS}, {"with_tp_del", with_tp_del, METH_VARARGS}, {"test_pymem", (PyCFunction)test_pymem_alloc0, METH_NOARGS}, {"test_pymem_alloc0", (PyCFunction)test_pymem_setrawallocators, METH_NOARGS}, {"test_pymem_setallocators", (PyCFunction)test_pymem_setallocators, METH_NOARGS}, {"test_pyobject_setallocators", (PyCFunction)test_pyobject_setallocators, METH_NOARGS}, {NULL, NULL} /* sentinel */ }; #define AddSym(d, n, f, v) {PyObject *o = f(v); PyDict_SetItemString(d, n, o); Py_DECREF(o);} typedef struct { char bool_member; char byte_member; unsigned char ubyte_member; short short_member; unsigned short ushort_member; int int_member; unsigned int uint_member; long long_member; unsigned long ulong_member; Py_ssize_t pyssizet_member; float float_member; double double_member; char inplace_member[6]; #ifdef HAVE_LONG_LONG PY_LONG_LONG longlong_member; unsigned PY_LONG_LONG ulonglong_member; #endif } all_structmembers; typedef struct { PyObject_HEAD all_structmembers structmembers; } test_structmembers; static struct PyMemberDef test_members[] = { {"T_BOOL", T_BOOL, offsetof(test_structmembers, structmembers.bool_member), 0, NULL}, {"T_BYTE", T_BYTE, offsetof(test_structmembers, structmembers.byte_member), 0, NULL}, {"T_UBYTE", T_UBYTE, offsetof(test_structmembers, structmembers.ubyte_member), 0, NULL}, {"T_SHORT", T_SHORT, offsetof(test_structmembers, structmembers.short_member), 0, NULL}, {"T_USHORT", T_USHORT, offsetof(test_structmembers, structmembers.ushort_member), 0, NULL}, {"T_INT", T_INT, offsetof(test_structmembers, structmembers.int_member), 0, NULL}, {"T_UINT", T_UINT, offsetof(test_structmembers, structmembers.uint_member), 0, NULL}, {"T_LONG", T_LONG, offsetof(test_structmembers, structmembers.long_member), 0, NULL}, {"T_ULONG", T_ULONG, offsetof(test_structmembers, structmembers.ulong_member), 0, NULL}, {"T_PYSSIZET", T_PYSSIZET, offsetof(test_structmembers, structmembers.pyssizet_member), 0, NULL}, {"T_FLOAT", T_FLOAT, offsetof(test_structmembers, structmembers.float_member), 0, NULL}, {"T_DOUBLE", T_DOUBLE, offsetof(test_structmembers, structmembers.double_member), 0, NULL}, {"T_STRING_INPLACE", T_STRING_INPLACE, offsetof(test_structmembers, structmembers.inplace_member), 0, NULL}, #ifdef HAVE_LONG_LONG {"T_LONGLONG", T_LONGLONG, offsetof(test_structmembers, structmembers.longlong_member), 0, NULL}, {"T_ULONGLONG", T_ULONGLONG, offsetof(test_structmembers, structmembers.ulonglong_member), 0, NULL}, #endif {NULL} }; static PyObject * test_structmembers_new(PyTypeObject *type, PyObject *args, PyObject *kwargs) { static char *keywords[] = { "T_BOOL", "T_BYTE", "T_UBYTE", "T_SHORT", "T_USHORT", "T_INT", "T_UINT", "T_LONG", "T_ULONG", "T_PYSSIZET", "T_FLOAT", "T_DOUBLE", "T_STRING_INPLACE", #ifdef HAVE_LONG_LONG "T_LONGLONG", "T_ULONGLONG", #endif NULL}; static char *fmt = "|bbBhHiIlknfds#" #ifdef HAVE_LONG_LONG "LK" #endif ; test_structmembers *ob; const char *s = NULL; Py_ssize_t string_len = 0; ob = PyObject_New(test_structmembers, type); if (ob == NULL) return NULL; memset(&ob->structmembers, 0, sizeof(all_structmembers)); if (!PyArg_ParseTupleAndKeywords(args, kwargs, fmt, keywords, &ob->structmembers.bool_member, &ob->structmembers.byte_member, &ob->structmembers.ubyte_member, &ob->structmembers.short_member, &ob->structmembers.ushort_member, &ob->structmembers.int_member, &ob->structmembers.uint_member, &ob->structmembers.long_member, &ob->structmembers.ulong_member, &ob->structmembers.pyssizet_member, &ob->structmembers.float_member, &ob->structmembers.double_member, &s, &string_len #ifdef HAVE_LONG_LONG , &ob->structmembers.longlong_member, &ob->structmembers.ulonglong_member #endif )) { Py_DECREF(ob); return NULL; } if (s != NULL) { if (string_len > 5) { Py_DECREF(ob); PyErr_SetString(PyExc_ValueError, "string too long"); return NULL; } strcpy(ob->structmembers.inplace_member, s); } else { strcpy(ob->structmembers.inplace_member, ""); } return (PyObject *)ob; } static void test_structmembers_free(PyObject *ob) { PyObject_FREE(ob); } static PyTypeObject test_structmembersType = { PyVarObject_HEAD_INIT(NULL, 0) "test_structmembersType", sizeof(test_structmembers), /* tp_basicsize */ 0, /* tp_itemsize */ test_structmembers_free, /* destructor tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ PyObject_GenericSetAttr, /* tp_setattro */ 0, /* tp_as_buffer */ 0, /* tp_flags */ "Type containing all structmember types", 0, /* traverseproc tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ test_members, /* tp_members */ 0, 0, 0, 0, 0, 0, 0, 0, test_structmembers_new, /* tp_new */ }; static struct PyModuleDef _testcapimodule = { PyModuleDef_HEAD_INIT, "_testcapi", NULL, -1, TestMethods, NULL, NULL, NULL, NULL }; PyMODINIT_FUNC PyInit__testcapi(void) { PyObject *m; m = PyModule_Create(&_testcapimodule); if (m == NULL) return NULL; Py_TYPE(&_HashInheritanceTester_Type)=&PyType_Type; Py_TYPE(&test_structmembersType)=&PyType_Type; Py_INCREF(&test_structmembersType); /* don't use a name starting with "test", since we don't want test_capi to automatically call this */ PyModule_AddObject(m, "_test_structmembersType", (PyObject *)&test_structmembersType); PyModule_AddObject(m, "CHAR_MAX", PyLong_FromLong(CHAR_MAX)); PyModule_AddObject(m, "CHAR_MIN", PyLong_FromLong(CHAR_MIN)); PyModule_AddObject(m, "UCHAR_MAX", PyLong_FromLong(UCHAR_MAX)); PyModule_AddObject(m, "SHRT_MAX", PyLong_FromLong(SHRT_MAX)); PyModule_AddObject(m, "SHRT_MIN", PyLong_FromLong(SHRT_MIN)); PyModule_AddObject(m, "USHRT_MAX", PyLong_FromLong(USHRT_MAX)); PyModule_AddObject(m, "INT_MAX", PyLong_FromLong(INT_MAX)); PyModule_AddObject(m, "INT_MIN", PyLong_FromLong(INT_MIN)); PyModule_AddObject(m, "UINT_MAX", PyLong_FromUnsignedLong(UINT_MAX)); PyModule_AddObject(m, "LONG_MAX", PyLong_FromLong(LONG_MAX)); PyModule_AddObject(m, "LONG_MIN", PyLong_FromLong(LONG_MIN)); PyModule_AddObject(m, "ULONG_MAX", PyLong_FromUnsignedLong(ULONG_MAX)); PyModule_AddObject(m, "FLT_MAX", PyFloat_FromDouble(FLT_MAX)); PyModule_AddObject(m, "FLT_MIN", PyFloat_FromDouble(FLT_MIN)); PyModule_AddObject(m, "DBL_MAX", PyFloat_FromDouble(DBL_MAX)); PyModule_AddObject(m, "DBL_MIN", PyFloat_FromDouble(DBL_MIN)); PyModule_AddObject(m, "LLONG_MAX", PyLong_FromLongLong(PY_LLONG_MAX)); PyModule_AddObject(m, "LLONG_MIN", PyLong_FromLongLong(PY_LLONG_MIN)); PyModule_AddObject(m, "ULLONG_MAX", PyLong_FromUnsignedLongLong(PY_ULLONG_MAX)); PyModule_AddObject(m, "PY_SSIZE_T_MAX", PyLong_FromSsize_t(PY_SSIZE_T_MAX)); PyModule_AddObject(m, "PY_SSIZE_T_MIN", PyLong_FromSsize_t(PY_SSIZE_T_MIN)); PyModule_AddObject(m, "SIZEOF_PYGC_HEAD", PyLong_FromSsize_t(sizeof(PyGC_Head))); Py_INCREF(&PyInstanceMethod_Type); PyModule_AddObject(m, "instancemethod", (PyObject *)&PyInstanceMethod_Type); TestError = PyErr_NewException("_testcapi.error", NULL, NULL); Py_INCREF(TestError); PyModule_AddObject(m, "error", TestError); return m; }
{ "pile_set_name": "Github" }
// Copyright Emil Fresk 2017. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE.md or copy at // http://www.boost.org/LICENSE_1_0.txt) #pragma once #include "../../functional/identity.hpp" #include "../../types/integral_constant.hpp" namespace kvasir { namespace mpl { template <typename C = identity> struct modulo { template <typename A, typename B> using f = typename C::template f< integral_constant<decltype(A::value % B::value), (A::value % B::value)>>; }; namespace eager { template <typename A, typename B> using modulo = integral_constant<decltype(A::value % B::value), (A::value % B::value)>; } } // namespace mpl } // namespace kvasir
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>BuildMachineOSBuild</key> <string>14F2009</string> <key>CFBundleDevelopmentRegion</key> <string>en</string> <key>CFBundleExecutable</key> <string>ApplePS2Keyboard</string> <key>CFBundleIdentifier</key> <string>org.emlydinesh.driver.ApplePS2Keyboard</string> <key>CFBundleInfoDictionaryVersion</key> <string>6.0</string> <key>CFBundleName</key> <string>ApplePS2Keyboard</string> <key>CFBundlePackageType</key> <string>KEXT</string> <key>CFBundleShortVersionString</key> <string>4.6.8</string> <key>CFBundleSignature</key> <string>????</string> <key>CFBundleVersion</key> <string>4.6.8</string> <key>DTCompiler</key> <string>com.apple.compilers.llvm.clang.1_0</string> <key>DTPlatformBuild</key> <string>6A2008a</string> <key>DTPlatformVersion</key> <string>GM</string> <key>DTSDKBuild</key> <string>12D75</string> <key>DTSDKName</key> <string>macosx10.8</string> <key>DTXcode</key> <string>0611</string> <key>DTXcodeBuild</key> <string>6A2008a</string> <key>IOKitPersonalities</key> <dict> <key>ApplePS2Keyboard</key> <dict> <key>CFBundleIdentifier</key> <string>org.emlydinesh.driver.ApplePS2Keyboard</string> <key>Extended Functions</key> <dict> <key>F13</key> <string>ALT CMD ESC</string> <key>F14</key> <string></string> <key>F15</key> <string></string> <key>F16</key> <string>ALT CMD D</string> <key>F17</key> <string>CTRL DAW</string> <key>F18</key> <string>CTRL UAW</string> <key>F19</key> <string>CTRL LAW</string> <key>F20</key> <string>CTRL RAW</string> <key>F21</key> <string></string> <key>F22</key> <string></string> <key>F23</key> <string>CMD Q</string> <key>F24</key> <string>CMD H</string> </dict> <key>Fn Keys Mode 1</key> <dict> <key>BrightnessDown</key> <string>F1</string> <key>BrightnessUp</key> <string>F2</string> <key>KBBacklightDown</key> <string>F3</string> <key>KBBacklightUp</key> <string>F4</string> <key>Launchpad</key> <string>F4</string> <key>MediaNext</key> <string>F9</string> <key>MediaPlayPause</key> <string>F8</string> <key>MediaPrevious</key> <string>F7</string> <key>Misson Control</key> <string>F3</string> <key>SleepDisplay</key> <string>F5</string> <key>Touchpad</key> <string>Pause</string> <key>VideoMirror</key> <string>F6</string> <key>VolumeDown</key> <string>F11</string> <key>VolumeMute</key> <string>F10</string> <key>VolumeUp</key> <string>F12</string> </dict> <key>Fn Keys Mode 2</key> <dict> <key>BrightnessDown</key> <string>F5</string> <key>BrightnessUp</key> <string>F6</string> <key>KBBacklightDown</key> <string>F3</string> <key>KBBacklightUp</key> <string>F4</string> <key>Launchpad</key> <string>F4</string> <key>MediaNext</key> <string>ArrowRight</string> <key>MediaPlayPause</key> <string>ArrowDown</string> <key>MediaPrevious</key> <string>ArrowLeft</string> <key>Misson Control</key> <string>F3</string> <key>SleepDisplay</key> <string>F7</string> <key>SystemSleep</key> <string>F1</string> <key>Touchpad</key> <string>F9</string> <key>VideoMirror</key> <string>F8</string> <key>VolumeDown</key> <string>F11</string> <key>VolumeMute</key> <string>F10</string> <key>VolumeUp</key> <string>F12</string> </dict> <key>Fn keys Layout</key> <string>NONE</string> <key>Fn keys Mode</key> <integer>2</integer> <key>IOClass</key> <string>ApplePS2Keyboard</string> <key>IOProviderClass</key> <string>ApplePS2KeyboardDevice</string> <key>Keyboard type (ID)</key> <integer>0</integer> <key>Preferences</key> <dict> <key>Disable Num Lock LED</key> <false/> <key>Enable Extended Functions</key> <true/> <key>Enable Sierra Caps Lock Fix</key> <true/> <key>FinerFnBrightnessControl</key> <true/> <key>FinerFnVolumeControl</key> <true/> <key>Make Caps Lock into key</key> <integer>0</integer> <key>Make ISO keypad key . to ,</key> <false/> <key>Make Num Lock into Clear</key> <false/> <key>Make context menu key into key</key> <integer>84</integer> <key>Make delete key into cmd + backspace</key> <false/> <key>Make right alt into key</key> <integer>0</integer> <key>Make right control into key</key> <integer>0</integer> <key>Make shift + caps into Fn key</key> <true/> <key>Num Lock enabled at boot</key> <true/> <key>Swap alt and windows key</key> <false/> </dict> <key>ProductID</key> <integer>782</integer> <key>Use ISO Layout</key> <false/> <key>VendorID</key> <integer>1452</integer> </dict> </dict> <key>NSHumanReadableCopyright</key> <string>Copyright © EMlyDinEsH (mg-dinesh@live.com) 2012-2016. All rights reserved.</string> <key>OSBundleCompatibleVersion</key> <string>4.6.8</string> <key>OSBundleLibraries</key> <dict> <key>com.apple.iokit.IOHIDSystem</key> <string>1.0.0b1</string> <key>com.apple.kpi.iokit</key> <string>8.0.0</string> <key>com.apple.kpi.libkern</key> <string>8.0.0</string> <key>com.apple.kpi.mach</key> <string>8.0.0</string> <key>com.apple.kpi.unsupported</key> <string>8.0.0</string> <key>org.emlydinesh.driver.ApplePS2Controller</key> <string>4.6.8</string> </dict> <key>OSBundleRequired</key> <string>Console</string> </dict> </plist>
{ "pile_set_name": "Github" }
#if __has_include(<mysql.h>) #include <mysql.h> #else #include <mysql/mysql.h> #endif #include <mysqlxx/Connection.h> #include <mysqlxx/ResultBase.h> namespace mysqlxx { ResultBase::ResultBase(MYSQL_RES * res_, Connection * conn_, const Query * query_) : res(res_), conn(conn_), query(query_) { fields = mysql_fetch_fields(res); num_fields = mysql_num_fields(res); } ResultBase::~ResultBase() { mysql_free_result(res); } }
{ "pile_set_name": "Github" }
/******************************************************************************* * Copyright (c) 2012 VMware, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * https://www.eclipse.org/legal/epl-v10.html * * Contributors: * VMware, Inc. - initial API and implementation *******************************************************************************/ package org.springframework.ide.eclipse.wizard.template.infrastructure.ui; import java.util.Map; /** * @author Terry Denney * @author Leo Dos Santos * @author Christian Dupuis */ public interface WizardUI { public void collectInput(Map<String, Object> collectedInput, Map<String, String> inputKinds); }
{ "pile_set_name": "Github" }
// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2008-2012 Gael Guennebaud <gael.guennebaud@inria.fr> /* NOTE: thes functions vave been adapted from the LDL library: LDL Copyright (c) 2005 by Timothy A. Davis. All Rights Reserved. LDL License: Your use or distribution of LDL or any modified version of LDL implies that you agree to this License. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Permission is hereby granted to use or copy this program under the terms of the GNU LGPL, provided that the Copyright, this License, and the Availability of the original version is retained on all copies. User documentation of any code that uses this code or any modified version of this code must cite the Copyright, this License, the Availability note, and "Used by permission." Permission to modify the code and to distribute modified code is granted, provided the Copyright, this License, and the Availability note are retained, and a notice that the code was modified is included. */ #include "../Core/util/NonMPL2.h" #ifndef EIGEN_SIMPLICIAL_CHOLESKY_IMPL_H #define EIGEN_SIMPLICIAL_CHOLESKY_IMPL_H namespace Eigen { template<typename Derived> void SimplicialCholeskyBase<Derived>::analyzePattern_preordered(const CholMatrixType& ap, bool doLDLT) { const StorageIndex size = StorageIndex(ap.rows()); m_matrix.resize(size, size); m_parent.resize(size); m_nonZerosPerCol.resize(size); ei_declare_aligned_stack_constructed_variable(StorageIndex, tags, size, 0); for(StorageIndex k = 0; k < size; ++k) { /* L(k,:) pattern: all nodes reachable in etree from nz in A(0:k-1,k) */ m_parent[k] = -1; /* parent of k is not yet known */ tags[k] = k; /* mark node k as visited */ m_nonZerosPerCol[k] = 0; /* count of nonzeros in column k of L */ for(typename CholMatrixType::InnerIterator it(ap,k); it; ++it) { StorageIndex i = it.index(); if(i < k) { /* follow path from i to root of etree, stop at flagged node */ for(; tags[i] != k; i = m_parent[i]) { /* find parent of i if not yet determined */ if (m_parent[i] == -1) m_parent[i] = k; m_nonZerosPerCol[i]++; /* L (k,i) is nonzero */ tags[i] = k; /* mark i as visited */ } } } } /* construct Lp index array from m_nonZerosPerCol column counts */ StorageIndex* Lp = m_matrix.outerIndexPtr(); Lp[0] = 0; for(StorageIndex k = 0; k < size; ++k) Lp[k+1] = Lp[k] + m_nonZerosPerCol[k] + (doLDLT ? 0 : 1); m_matrix.resizeNonZeros(Lp[size]); m_isInitialized = true; m_info = Success; m_analysisIsOk = true; m_factorizationIsOk = false; } template<typename Derived> template<bool DoLDLT> void SimplicialCholeskyBase<Derived>::factorize_preordered(const CholMatrixType& ap) { using std::sqrt; eigen_assert(m_analysisIsOk && "You must first call analyzePattern()"); eigen_assert(ap.rows()==ap.cols()); eigen_assert(m_parent.size()==ap.rows()); eigen_assert(m_nonZerosPerCol.size()==ap.rows()); const StorageIndex size = StorageIndex(ap.rows()); const StorageIndex* Lp = m_matrix.outerIndexPtr(); StorageIndex* Li = m_matrix.innerIndexPtr(); Scalar* Lx = m_matrix.valuePtr(); ei_declare_aligned_stack_constructed_variable(Scalar, y, size, 0); ei_declare_aligned_stack_constructed_variable(StorageIndex, pattern, size, 0); ei_declare_aligned_stack_constructed_variable(StorageIndex, tags, size, 0); bool ok = true; m_diag.resize(DoLDLT ? size : 0); for(StorageIndex k = 0; k < size; ++k) { // compute nonzero pattern of kth row of L, in topological order y[k] = 0.0; // Y(0:k) is now all zero StorageIndex top = size; // stack for pattern is empty tags[k] = k; // mark node k as visited m_nonZerosPerCol[k] = 0; // count of nonzeros in column k of L for(typename CholMatrixType::InnerIterator it(ap,k); it; ++it) { StorageIndex i = it.index(); if(i <= k) { y[i] += numext::conj(it.value()); /* scatter A(i,k) into Y (sum duplicates) */ Index len; for(len = 0; tags[i] != k; i = m_parent[i]) { pattern[len++] = i; /* L(k,i) is nonzero */ tags[i] = k; /* mark i as visited */ } while(len > 0) pattern[--top] = pattern[--len]; } } /* compute numerical values kth row of L (a sparse triangular solve) */ RealScalar d = numext::real(y[k]) * m_shiftScale + m_shiftOffset; // get D(k,k), apply the shift function, and clear Y(k) y[k] = 0.0; for(; top < size; ++top) { Index i = pattern[top]; /* pattern[top:n-1] is pattern of L(:,k) */ Scalar yi = y[i]; /* get and clear Y(i) */ y[i] = 0.0; /* the nonzero entry L(k,i) */ Scalar l_ki; if(DoLDLT) l_ki = yi / m_diag[i]; else yi = l_ki = yi / Lx[Lp[i]]; Index p2 = Lp[i] + m_nonZerosPerCol[i]; Index p; for(p = Lp[i] + (DoLDLT ? 0 : 1); p < p2; ++p) y[Li[p]] -= numext::conj(Lx[p]) * yi; d -= numext::real(l_ki * numext::conj(yi)); Li[p] = k; /* store L(k,i) in column form of L */ Lx[p] = l_ki; ++m_nonZerosPerCol[i]; /* increment count of nonzeros in col i */ } if(DoLDLT) { m_diag[k] = d; if(d == RealScalar(0)) { ok = false; /* failure, D(k,k) is zero */ break; } } else { Index p = Lp[k] + m_nonZerosPerCol[k]++; Li[p] = k ; /* store L(k,k) = sqrt (d) in column k */ if(d <= RealScalar(0)) { ok = false; /* failure, matrix is not positive definite */ break; } Lx[p] = sqrt(d) ; } } m_info = ok ? Success : NumericalIssue; m_factorizationIsOk = true; } } // end namespace Eigen #endif // EIGEN_SIMPLICIAL_CHOLESKY_IMPL_H
{ "pile_set_name": "Github" }
<resources> <string name="app_name">Patio</string> <string name="patio_take_picture">Nova Foto</string> <string name="patio_attach_picture">Adicionar</string> <string name="patio_remove_picture">Remover</string> <string name="patio_action_cancel">Cancelar</string> <string name="patio_thumbnails_message">%1$d de %2$d carregadas</string> </resources>
{ "pile_set_name": "Github" }
/* Copyright 1995-2017 Esri 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. For additional information, contact: Environmental Systems Research Institute, Inc. Attn: Contracts Dept 380 New York Street Redlands, California, USA 92373 email: contracts@esri.com */ package com.esri.core.geometry; import junit.framework.TestCase; import org.junit.Test; import com.esri.core.geometry.Geometry.GeometryAccelerationDegree; public class TestRasterizedGeometry2D extends TestCase { boolean rgHelper(RasterizedGeometry2D rg, MultiPath mp) { SegmentIterator iter = mp.querySegmentIterator(); while (iter.nextPath()) { while (iter.hasNextSegment()) { Segment seg = iter.nextSegment(); int count = 20; for (int i = 0; i < count; i++) { double t = (1.0 * i / count); Point2D pt = seg.getCoord2D(t); RasterizedGeometry2D.HitType hit = rg.queryPointInGeometry( pt.x, pt.y); if (hit != RasterizedGeometry2D.HitType.Border) return false; } } } if (mp.getType() != Geometry.Type.Polygon) return true; Polygon poly = (Polygon) mp; Envelope2D env = new Envelope2D(); poly.queryEnvelope2D(env); int count = 100; for (int iy = 0; iy < count; iy++) { double ty = 1.0 * iy / count; double y = env.ymin * (1.0 - ty) + ty * env.ymax; for (int ix = 0; ix < count; ix++) { double tx = 1.0 * ix / count; double x = env.xmin * (1.0 - tx) + tx * env.xmax; RasterizedGeometry2D.HitType hit = rg .queryPointInGeometry(x, y); PolygonUtils.PiPResult res = PolygonUtils.isPointInPolygon2D( poly, new Point2D(x, y), 0); if (res == PolygonUtils.PiPResult.PiPInside) { boolean bgood = (hit == RasterizedGeometry2D.HitType.Border || hit == RasterizedGeometry2D.HitType.Inside); if (!bgood) return false; } else if (res == PolygonUtils.PiPResult.PiPOutside) { boolean bgood = (hit == RasterizedGeometry2D.HitType.Border || hit == RasterizedGeometry2D.HitType.Outside); if (!bgood) return false; } else { boolean bgood = (hit == RasterizedGeometry2D.HitType.Border); if (!bgood) return false; } } } return true; } @Test public void test() { { Polygon poly = new Polygon(); poly.startPath(10, 10); poly.lineTo(100, 10); poly.lineTo(100, 100); poly.lineTo(10, 100); // create using move semantics. Usually we do not use this // approach. RasterizedGeometry2D rg = RasterizedGeometry2D .create(poly, 0, 1024); //rg.dbgSaveToBitmap("c:/temp/_dbg.bmp"); RasterizedGeometry2D.HitType res; res = rg.queryPointInGeometry(7, 10); assertTrue(res == RasterizedGeometry2D.HitType.Outside); res = rg.queryPointInGeometry(10, 10); assertTrue(res == RasterizedGeometry2D.HitType.Border); res = rg.queryPointInGeometry(50, 50); assertTrue(res == RasterizedGeometry2D.HitType.Inside); assertTrue(rgHelper(rg, poly)); } { Polygon poly = new Polygon(); // create a star (non-simple) poly.startPath(1, 0); poly.lineTo(5, 10); poly.lineTo(9, 0); poly.lineTo(0, 6); poly.lineTo(10, 6); RasterizedGeometry2D rg = RasterizedGeometry2D .create(poly, 0, 1024); //rg.dbgSaveToBitmap("c:/temp/_dbg.bmp"); RasterizedGeometry2D.HitType res; res = rg.queryPointInGeometry(5, 5.5); assertTrue(res == RasterizedGeometry2D.HitType.Outside); res = rg.queryPointInGeometry(5, 8); assertTrue(res == RasterizedGeometry2D.HitType.Inside); res = rg.queryPointInGeometry(1.63, 0.77); assertTrue(res == RasterizedGeometry2D.HitType.Inside); res = rg.queryPointInGeometry(1, 3); assertTrue(res == RasterizedGeometry2D.HitType.Outside); res = rg.queryPointInGeometry(1.6, 0.1); assertTrue(res == RasterizedGeometry2D.HitType.Outside); assertTrue(rgHelper(rg, poly)); } { Polygon poly = new Polygon(); // create a star (non-simple) poly.startPath(1, 0); poly.lineTo(5, 10); poly.lineTo(9, 0); poly.lineTo(0, 6); poly.lineTo(10, 6); SpatialReference sr = SpatialReference.create(4326); poly = (Polygon)OperatorSimplify.local().execute(poly, sr, true, null); OperatorContains.local().accelerateGeometry(poly, sr, GeometryAccelerationDegree.enumMedium); assertFalse(OperatorContains.local().execute(poly, new Point(5, 5.5), sr, null)); assertTrue(OperatorContains.local().execute(poly, new Point(5, 8), sr, null)); assertTrue(OperatorContains.local().execute(poly, new Point(1.63, 0.77), sr, null)); assertFalse(OperatorContains.local().execute(poly, new Point(1, 3), sr, null)); assertFalse(OperatorContains.local().execute(poly, new Point(1.6, 0.1), sr, null)); } /* { Geometry g = OperatorFactoryLocal.loadGeometryFromEsriShapeDbg("c:/temp/_poly_final.bin"); RasterizedGeometry2D rg1 = RasterizedGeometry2D .create(g, 0, 1024);//warmup rg1 = null; long t0 = System.nanoTime(); RasterizedGeometry2D rg = RasterizedGeometry2D .create(g, 0, 1024 * 1024); long t1 = System.nanoTime(); double d = (t1 - t0) / 1000000.0; System.out.printf("Time to rasterize the geometry: %f", d); rg.dbgSaveToBitmap("c:/temp/_dbg.bmp"); for (;;){} }*/ } }
{ "pile_set_name": "Github" }
// +build f10x_ld f10x_ld_vl f10x_md f10x_md_vl f10x_hd f10x_hd_vl f10x_xl f10x_cl package gpio import ( "mmio" "stm32/hal/raw/rcc" ) type registers struct { cr [2]mmio.U32 idr mmio.U16 _ uint16 odr mmio.U16 _ uint16 bsrr mmio.U32 brr mmio.U32 lckr mmio.U32 } const ( // Mode out = 1 alt = 8 + 1 altIn = 0 ana = 2 // Pull pullUp = 8 + 4 + 1 pullDown = 8 + 4 + 0 // Driver openDrain = 4 // Speed veryLow = 1 low = 1 high = 2 veryHigh = 2 ) func enableClock(p *Port, _ bool) { rcc.RCC.APB2ENR.AtomicSetBits(rcc.IOPAEN << portnum(p)) rcc.RCC.APB2ENR.Load() // RCC delay (workaround for silicon bugs). } func disableClock(p *Port) { rcc.RCC.APB2ENR.AtomicClearBits(rcc.IOPAEN << portnum(p)) } func reset(p *Port) { pnum := portnum(p) rcc.RCC.APB2RSTR.AtomicSetBits(rcc.IOPARST << pnum) rcc.RCC.APB2RSTR.AtomicClearBits(rcc.IOPARST << pnum) } func setup(p *Port, n int, cfg *Config) { cr := &p.cr[n>>3] pos := uint(n & 7 * 4) sel := uint32(0xf) << pos switch { case cfg.Mode == 0: // In, AltIn. cm := uint32(cfg.Pull)&(8+4) ^ 4 cr.StoreBits(sel, cm<<pos) p.StorePins(Pin0<<uint(n), Pins(cfg.Pull)<<uint(n)) case cfg.Mode&1 != 0: // Out, Alt. cm := uint32(cfg.Mode) & 8 cm |= uint32(cfg.Driver) cm |= uint32(cfg.Speed) + 1 cr.StoreBits(sel, cm<<pos) default: // Ana. cr.ClearBits(sel) } }
{ "pile_set_name": "Github" }
key.store=appintentdemo3-release.keystore key.alias=appintentdemo3aliaskey key.store.password=appintentdemo3passw key.alias.password=appintentdemo3passw
{ "pile_set_name": "Github" }
<?php /** * This file is part of phpDocumentor. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * @copyright 2010-2015 Mike van Riel<mike@phpdoc.org> * @license http://www.opensource.org/licenses/mit-license.php MIT * @link http://phpdoc.org */ namespace phpDocumentor\Reflection\Types; use phpDocumentor\Reflection\Type; /** * Value Object representing a Compound Type. * * A Compound Type is not so much a special keyword or object reference but is a series of Types that are separated * using an OR operator (`|`). This combination of types signifies that whatever is associated with this compound type * may contain a value with any of the given types. */ final class Compound implements Type { /** @var Type[] */ private $types = []; /** * Initializes a compound type (i.e. `string|int`) and tests if the provided types all implement the Type interface. * * @param Type[] $types */ public function __construct(array $types) { foreach ($types as $type) { if (!$type instanceof Type) { throw new \InvalidArgumentException('A compound type can only have other types as elements'); } } $this->types = $types; } /** * Returns the type at the given index. * * @param integer $index * * @return Type|null */ public function get($index) { if (!$this->has($index)) { return null; } return $this->types[$index]; } /** * Tests if this compound type has a type with the given index. * * @param integer $index * * @return bool */ public function has($index) { return isset($this->types[$index]); } /** * Returns a rendered output of the Type as it would be used in a DocBlock. * * @return string */ public function __toString() { return implode('|', $this->types); } }
{ "pile_set_name": "Github" }
// (C) Copyright Dave Abrahams, Steve Cleary, Beman Dawes, // Aleksey Gurtovoy, Howard Hinnant & John Maddock 2000. // Use, modification and distribution are subject to the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt). // // See http://www.boost.org/libs/type_traits for most recent version including documentation. #if !defined(BOOST_PP_IS_ITERATING) ///// header body #ifndef BOOST_TT_DETAIL_IS_FUNCTION_PTR_TESTER_HPP_INCLUDED #define BOOST_TT_DETAIL_IS_FUNCTION_PTR_TESTER_HPP_INCLUDED #include <boost/type_traits/detail/yes_no_type.hpp> #if defined(BOOST_TT_PREPROCESSING_MODE) // // Hide include dependencies from analysers since they're // only require in maintenance mode: // #define PP1 <boost/preprocessor/iterate.hpp> #define PP2 <boost/preprocessor/enum_params.hpp> #define PP3 <boost/preprocessor/comma_if.hpp> #include PP1 #include PP2 #include PP3 #undef PP1 #undef PP2 #undef PP3 #endif namespace boost { namespace type_traits { // Note it is acceptable to use ellipsis here, since the argument will // always be a pointer type of some sort (JM 2005/06/04): no_type BOOST_TT_DECL is_function_ptr_tester(...); #if !defined(BOOST_TT_PREPROCESSING_MODE) // pre-processed code, don't edit, try GNU cpp with // cpp -I../../../ -DBOOST_TT_PREPROCESSING_MODE -x c++ -P filename template <class R > yes_type is_function_ptr_tester(R (*)()); template <class R > yes_type is_function_ptr_tester(R (*)( ...)); #ifdef BOOST_TT_TEST_MS_FUNC_SIGS template <class R > yes_type is_function_ptr_tester(R (__stdcall*)()); #ifndef _MANAGED template <class R > yes_type is_function_ptr_tester(R (__fastcall*)()); #endif template <class R > yes_type is_function_ptr_tester(R (__cdecl*)()); #endif template <class R , class T0 > yes_type is_function_ptr_tester(R (*)( T0)); template <class R , class T0 > yes_type is_function_ptr_tester(R (*)( T0 ...)); #ifdef BOOST_TT_TEST_MS_FUNC_SIGS template <class R , class T0 > yes_type is_function_ptr_tester(R (__stdcall*)( T0)); #ifndef _MANAGED template <class R , class T0 > yes_type is_function_ptr_tester(R (__fastcall*)( T0)); #endif template <class R , class T0 > yes_type is_function_ptr_tester(R (__cdecl*)( T0)); #endif template <class R , class T0 , class T1 > yes_type is_function_ptr_tester(R (*)( T0 , T1)); template <class R , class T0 , class T1 > yes_type is_function_ptr_tester(R (*)( T0 , T1 ...)); #ifdef BOOST_TT_TEST_MS_FUNC_SIGS template <class R , class T0 , class T1 > yes_type is_function_ptr_tester(R (__stdcall*)( T0 , T1)); #ifndef _MANAGED template <class R , class T0 , class T1 > yes_type is_function_ptr_tester(R (__fastcall*)( T0 , T1)); #endif template <class R , class T0 , class T1 > yes_type is_function_ptr_tester(R (__cdecl*)( T0 , T1)); #endif template <class R , class T0 , class T1 , class T2 > yes_type is_function_ptr_tester(R (*)( T0 , T1 , T2)); template <class R , class T0 , class T1 , class T2 > yes_type is_function_ptr_tester(R (*)( T0 , T1 , T2 ...)); #ifdef BOOST_TT_TEST_MS_FUNC_SIGS template <class R , class T0 , class T1 , class T2 > yes_type is_function_ptr_tester(R (__stdcall*)( T0 , T1 , T2)); #ifndef _MANAGED template <class R , class T0 , class T1 , class T2 > yes_type is_function_ptr_tester(R (__fastcall*)( T0 , T1 , T2)); #endif template <class R , class T0 , class T1 , class T2 > yes_type is_function_ptr_tester(R (__cdecl*)( T0 , T1 , T2)); #endif template <class R , class T0 , class T1 , class T2 , class T3 > yes_type is_function_ptr_tester(R (*)( T0 , T1 , T2 , T3)); template <class R , class T0 , class T1 , class T2 , class T3 > yes_type is_function_ptr_tester(R (*)( T0 , T1 , T2 , T3 ...)); #ifdef BOOST_TT_TEST_MS_FUNC_SIGS template <class R , class T0 , class T1 , class T2 , class T3 > yes_type is_function_ptr_tester(R (__stdcall*)( T0 , T1 , T2 , T3)); #ifndef _MANAGED template <class R , class T0 , class T1 , class T2 , class T3 > yes_type is_function_ptr_tester(R (__fastcall*)( T0 , T1 , T2 , T3)); #endif template <class R , class T0 , class T1 , class T2 , class T3 > yes_type is_function_ptr_tester(R (__cdecl*)( T0 , T1 , T2 , T3)); #endif template <class R , class T0 , class T1 , class T2 , class T3 , class T4 > yes_type is_function_ptr_tester(R (*)( T0 , T1 , T2 , T3 , T4)); template <class R , class T0 , class T1 , class T2 , class T3 , class T4 > yes_type is_function_ptr_tester(R (*)( T0 , T1 , T2 , T3 , T4 ...)); #ifdef BOOST_TT_TEST_MS_FUNC_SIGS template <class R , class T0 , class T1 , class T2 , class T3 , class T4 > yes_type is_function_ptr_tester(R (__stdcall*)( T0 , T1 , T2 , T3 , T4)); #ifndef _MANAGED template <class R , class T0 , class T1 , class T2 , class T3 , class T4 > yes_type is_function_ptr_tester(R (__fastcall*)( T0 , T1 , T2 , T3 , T4)); #endif template <class R , class T0 , class T1 , class T2 , class T3 , class T4 > yes_type is_function_ptr_tester(R (__cdecl*)( T0 , T1 , T2 , T3 , T4)); #endif template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 > yes_type is_function_ptr_tester(R (*)( T0 , T1 , T2 , T3 , T4 , T5)); template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 > yes_type is_function_ptr_tester(R (*)( T0 , T1 , T2 , T3 , T4 , T5 ...)); #ifdef BOOST_TT_TEST_MS_FUNC_SIGS template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 > yes_type is_function_ptr_tester(R (__stdcall*)( T0 , T1 , T2 , T3 , T4 , T5)); #ifndef _MANAGED template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 > yes_type is_function_ptr_tester(R (__fastcall*)( T0 , T1 , T2 , T3 , T4 , T5)); #endif template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 > yes_type is_function_ptr_tester(R (__cdecl*)( T0 , T1 , T2 , T3 , T4 , T5)); #endif template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 > yes_type is_function_ptr_tester(R (*)( T0 , T1 , T2 , T3 , T4 , T5 , T6)); template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 > yes_type is_function_ptr_tester(R (*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 ...)); #ifdef BOOST_TT_TEST_MS_FUNC_SIGS template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 > yes_type is_function_ptr_tester(R (__stdcall*)( T0 , T1 , T2 , T3 , T4 , T5 , T6)); #ifndef _MANAGED template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 > yes_type is_function_ptr_tester(R (__fastcall*)( T0 , T1 , T2 , T3 , T4 , T5 , T6)); #endif template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 > yes_type is_function_ptr_tester(R (__cdecl*)( T0 , T1 , T2 , T3 , T4 , T5 , T6)); #endif template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 > yes_type is_function_ptr_tester(R (*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7)); template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 > yes_type is_function_ptr_tester(R (*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 ...)); #ifdef BOOST_TT_TEST_MS_FUNC_SIGS template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 > yes_type is_function_ptr_tester(R (__stdcall*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7)); #ifndef _MANAGED template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 > yes_type is_function_ptr_tester(R (__fastcall*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7)); #endif template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 > yes_type is_function_ptr_tester(R (__cdecl*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7)); #endif template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 > yes_type is_function_ptr_tester(R (*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8)); template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 > yes_type is_function_ptr_tester(R (*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 ...)); #ifdef BOOST_TT_TEST_MS_FUNC_SIGS template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 > yes_type is_function_ptr_tester(R (__stdcall*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8)); #ifndef _MANAGED template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 > yes_type is_function_ptr_tester(R (__fastcall*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8)); #endif template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 > yes_type is_function_ptr_tester(R (__cdecl*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8)); #endif template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 > yes_type is_function_ptr_tester(R (*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9)); template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 > yes_type is_function_ptr_tester(R (*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 ...)); #ifdef BOOST_TT_TEST_MS_FUNC_SIGS template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 > yes_type is_function_ptr_tester(R (__stdcall*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9)); #ifndef _MANAGED template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 > yes_type is_function_ptr_tester(R (__fastcall*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9)); #endif template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 > yes_type is_function_ptr_tester(R (__cdecl*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9)); #endif template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 , class T10 > yes_type is_function_ptr_tester(R (*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10)); template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 , class T10 > yes_type is_function_ptr_tester(R (*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 ...)); #ifdef BOOST_TT_TEST_MS_FUNC_SIGS template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 , class T10 > yes_type is_function_ptr_tester(R (__stdcall*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10)); #ifndef _MANAGED template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 , class T10 > yes_type is_function_ptr_tester(R (__fastcall*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10)); #endif template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 , class T10 > yes_type is_function_ptr_tester(R (__cdecl*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10)); #endif template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 , class T10 , class T11 > yes_type is_function_ptr_tester(R (*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11)); template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 , class T10 , class T11 > yes_type is_function_ptr_tester(R (*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 ...)); #ifdef BOOST_TT_TEST_MS_FUNC_SIGS template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 , class T10 , class T11 > yes_type is_function_ptr_tester(R (__stdcall*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11)); #ifndef _MANAGED template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 , class T10 , class T11 > yes_type is_function_ptr_tester(R (__fastcall*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11)); #endif template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 , class T10 , class T11 > yes_type is_function_ptr_tester(R (__cdecl*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11)); #endif template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 , class T10 , class T11 , class T12 > yes_type is_function_ptr_tester(R (*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12)); template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 , class T10 , class T11 , class T12 > yes_type is_function_ptr_tester(R (*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 ...)); #ifdef BOOST_TT_TEST_MS_FUNC_SIGS template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 , class T10 , class T11 , class T12 > yes_type is_function_ptr_tester(R (__stdcall*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12)); #ifndef _MANAGED template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 , class T10 , class T11 , class T12 > yes_type is_function_ptr_tester(R (__fastcall*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12)); #endif template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 , class T10 , class T11 , class T12 > yes_type is_function_ptr_tester(R (__cdecl*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12)); #endif template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 , class T10 , class T11 , class T12 , class T13 > yes_type is_function_ptr_tester(R (*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13)); template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 , class T10 , class T11 , class T12 , class T13 > yes_type is_function_ptr_tester(R (*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 ...)); #ifdef BOOST_TT_TEST_MS_FUNC_SIGS template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 , class T10 , class T11 , class T12 , class T13 > yes_type is_function_ptr_tester(R (__stdcall*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13)); #ifndef _MANAGED template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 , class T10 , class T11 , class T12 , class T13 > yes_type is_function_ptr_tester(R (__fastcall*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13)); #endif template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 , class T10 , class T11 , class T12 , class T13 > yes_type is_function_ptr_tester(R (__cdecl*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13)); #endif template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 , class T10 , class T11 , class T12 , class T13 , class T14 > yes_type is_function_ptr_tester(R (*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14)); template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 , class T10 , class T11 , class T12 , class T13 , class T14 > yes_type is_function_ptr_tester(R (*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 ...)); #ifdef BOOST_TT_TEST_MS_FUNC_SIGS template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 , class T10 , class T11 , class T12 , class T13 , class T14 > yes_type is_function_ptr_tester(R (__stdcall*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14)); #ifndef _MANAGED template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 , class T10 , class T11 , class T12 , class T13 , class T14 > yes_type is_function_ptr_tester(R (__fastcall*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14)); #endif template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 , class T10 , class T11 , class T12 , class T13 , class T14 > yes_type is_function_ptr_tester(R (__cdecl*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14)); #endif template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 , class T10 , class T11 , class T12 , class T13 , class T14 , class T15 > yes_type is_function_ptr_tester(R (*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15)); template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 , class T10 , class T11 , class T12 , class T13 , class T14 , class T15 > yes_type is_function_ptr_tester(R (*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 ...)); #ifdef BOOST_TT_TEST_MS_FUNC_SIGS template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 , class T10 , class T11 , class T12 , class T13 , class T14 , class T15 > yes_type is_function_ptr_tester(R (__stdcall*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15)); #ifndef _MANAGED template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 , class T10 , class T11 , class T12 , class T13 , class T14 , class T15 > yes_type is_function_ptr_tester(R (__fastcall*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15)); #endif template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 , class T10 , class T11 , class T12 , class T13 , class T14 , class T15 > yes_type is_function_ptr_tester(R (__cdecl*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15)); #endif template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 , class T10 , class T11 , class T12 , class T13 , class T14 , class T15 , class T16 > yes_type is_function_ptr_tester(R (*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16)); template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 , class T10 , class T11 , class T12 , class T13 , class T14 , class T15 , class T16 > yes_type is_function_ptr_tester(R (*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 ...)); #ifdef BOOST_TT_TEST_MS_FUNC_SIGS template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 , class T10 , class T11 , class T12 , class T13 , class T14 , class T15 , class T16 > yes_type is_function_ptr_tester(R (__stdcall*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16)); #ifndef _MANAGED template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 , class T10 , class T11 , class T12 , class T13 , class T14 , class T15 , class T16 > yes_type is_function_ptr_tester(R (__fastcall*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16)); #endif template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 , class T10 , class T11 , class T12 , class T13 , class T14 , class T15 , class T16 > yes_type is_function_ptr_tester(R (__cdecl*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16)); #endif template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 , class T10 , class T11 , class T12 , class T13 , class T14 , class T15 , class T16 , class T17 > yes_type is_function_ptr_tester(R (*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17)); template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 , class T10 , class T11 , class T12 , class T13 , class T14 , class T15 , class T16 , class T17 > yes_type is_function_ptr_tester(R (*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 ...)); #ifdef BOOST_TT_TEST_MS_FUNC_SIGS template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 , class T10 , class T11 , class T12 , class T13 , class T14 , class T15 , class T16 , class T17 > yes_type is_function_ptr_tester(R (__stdcall*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17)); #ifndef _MANAGED template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 , class T10 , class T11 , class T12 , class T13 , class T14 , class T15 , class T16 , class T17 > yes_type is_function_ptr_tester(R (__fastcall*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17)); #endif template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 , class T10 , class T11 , class T12 , class T13 , class T14 , class T15 , class T16 , class T17 > yes_type is_function_ptr_tester(R (__cdecl*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17)); #endif template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 , class T10 , class T11 , class T12 , class T13 , class T14 , class T15 , class T16 , class T17 , class T18 > yes_type is_function_ptr_tester(R (*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18)); template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 , class T10 , class T11 , class T12 , class T13 , class T14 , class T15 , class T16 , class T17 , class T18 > yes_type is_function_ptr_tester(R (*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 ...)); #ifdef BOOST_TT_TEST_MS_FUNC_SIGS template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 , class T10 , class T11 , class T12 , class T13 , class T14 , class T15 , class T16 , class T17 , class T18 > yes_type is_function_ptr_tester(R (__stdcall*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18)); #ifndef _MANAGED template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 , class T10 , class T11 , class T12 , class T13 , class T14 , class T15 , class T16 , class T17 , class T18 > yes_type is_function_ptr_tester(R (__fastcall*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18)); #endif template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 , class T10 , class T11 , class T12 , class T13 , class T14 , class T15 , class T16 , class T17 , class T18 > yes_type is_function_ptr_tester(R (__cdecl*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18)); #endif template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 , class T10 , class T11 , class T12 , class T13 , class T14 , class T15 , class T16 , class T17 , class T18 , class T19 > yes_type is_function_ptr_tester(R (*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19)); template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 , class T10 , class T11 , class T12 , class T13 , class T14 , class T15 , class T16 , class T17 , class T18 , class T19 > yes_type is_function_ptr_tester(R (*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 ...)); #ifdef BOOST_TT_TEST_MS_FUNC_SIGS template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 , class T10 , class T11 , class T12 , class T13 , class T14 , class T15 , class T16 , class T17 , class T18 , class T19 > yes_type is_function_ptr_tester(R (__stdcall*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19)); #ifndef _MANAGED template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 , class T10 , class T11 , class T12 , class T13 , class T14 , class T15 , class T16 , class T17 , class T18 , class T19 > yes_type is_function_ptr_tester(R (__fastcall*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19)); #endif template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 , class T10 , class T11 , class T12 , class T13 , class T14 , class T15 , class T16 , class T17 , class T18 , class T19 > yes_type is_function_ptr_tester(R (__cdecl*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19)); #endif template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 , class T10 , class T11 , class T12 , class T13 , class T14 , class T15 , class T16 , class T17 , class T18 , class T19 , class T20 > yes_type is_function_ptr_tester(R (*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20)); template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 , class T10 , class T11 , class T12 , class T13 , class T14 , class T15 , class T16 , class T17 , class T18 , class T19 , class T20 > yes_type is_function_ptr_tester(R (*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 ...)); #ifdef BOOST_TT_TEST_MS_FUNC_SIGS template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 , class T10 , class T11 , class T12 , class T13 , class T14 , class T15 , class T16 , class T17 , class T18 , class T19 , class T20 > yes_type is_function_ptr_tester(R (__stdcall*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20)); #ifndef _MANAGED template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 , class T10 , class T11 , class T12 , class T13 , class T14 , class T15 , class T16 , class T17 , class T18 , class T19 , class T20 > yes_type is_function_ptr_tester(R (__fastcall*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20)); #endif template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 , class T10 , class T11 , class T12 , class T13 , class T14 , class T15 , class T16 , class T17 , class T18 , class T19 , class T20 > yes_type is_function_ptr_tester(R (__cdecl*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20)); #endif template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 , class T10 , class T11 , class T12 , class T13 , class T14 , class T15 , class T16 , class T17 , class T18 , class T19 , class T20 , class T21 > yes_type is_function_ptr_tester(R (*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21)); template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 , class T10 , class T11 , class T12 , class T13 , class T14 , class T15 , class T16 , class T17 , class T18 , class T19 , class T20 , class T21 > yes_type is_function_ptr_tester(R (*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 ...)); #ifdef BOOST_TT_TEST_MS_FUNC_SIGS template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 , class T10 , class T11 , class T12 , class T13 , class T14 , class T15 , class T16 , class T17 , class T18 , class T19 , class T20 , class T21 > yes_type is_function_ptr_tester(R (__stdcall*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21)); #ifndef _MANAGED template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 , class T10 , class T11 , class T12 , class T13 , class T14 , class T15 , class T16 , class T17 , class T18 , class T19 , class T20 , class T21 > yes_type is_function_ptr_tester(R (__fastcall*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21)); #endif template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 , class T10 , class T11 , class T12 , class T13 , class T14 , class T15 , class T16 , class T17 , class T18 , class T19 , class T20 , class T21 > yes_type is_function_ptr_tester(R (__cdecl*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21)); #endif template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 , class T10 , class T11 , class T12 , class T13 , class T14 , class T15 , class T16 , class T17 , class T18 , class T19 , class T20 , class T21 , class T22 > yes_type is_function_ptr_tester(R (*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22)); template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 , class T10 , class T11 , class T12 , class T13 , class T14 , class T15 , class T16 , class T17 , class T18 , class T19 , class T20 , class T21 , class T22 > yes_type is_function_ptr_tester(R (*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 ...)); #ifdef BOOST_TT_TEST_MS_FUNC_SIGS template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 , class T10 , class T11 , class T12 , class T13 , class T14 , class T15 , class T16 , class T17 , class T18 , class T19 , class T20 , class T21 , class T22 > yes_type is_function_ptr_tester(R (__stdcall*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22)); #ifndef _MANAGED template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 , class T10 , class T11 , class T12 , class T13 , class T14 , class T15 , class T16 , class T17 , class T18 , class T19 , class T20 , class T21 , class T22 > yes_type is_function_ptr_tester(R (__fastcall*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22)); #endif template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 , class T10 , class T11 , class T12 , class T13 , class T14 , class T15 , class T16 , class T17 , class T18 , class T19 , class T20 , class T21 , class T22 > yes_type is_function_ptr_tester(R (__cdecl*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22)); #endif template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 , class T10 , class T11 , class T12 , class T13 , class T14 , class T15 , class T16 , class T17 , class T18 , class T19 , class T20 , class T21 , class T22 , class T23 > yes_type is_function_ptr_tester(R (*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23)); template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 , class T10 , class T11 , class T12 , class T13 , class T14 , class T15 , class T16 , class T17 , class T18 , class T19 , class T20 , class T21 , class T22 , class T23 > yes_type is_function_ptr_tester(R (*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 ...)); #ifdef BOOST_TT_TEST_MS_FUNC_SIGS template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 , class T10 , class T11 , class T12 , class T13 , class T14 , class T15 , class T16 , class T17 , class T18 , class T19 , class T20 , class T21 , class T22 , class T23 > yes_type is_function_ptr_tester(R (__stdcall*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23)); #ifndef _MANAGED template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 , class T10 , class T11 , class T12 , class T13 , class T14 , class T15 , class T16 , class T17 , class T18 , class T19 , class T20 , class T21 , class T22 , class T23 > yes_type is_function_ptr_tester(R (__fastcall*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23)); #endif template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 , class T10 , class T11 , class T12 , class T13 , class T14 , class T15 , class T16 , class T17 , class T18 , class T19 , class T20 , class T21 , class T22 , class T23 > yes_type is_function_ptr_tester(R (__cdecl*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23)); #endif template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 , class T10 , class T11 , class T12 , class T13 , class T14 , class T15 , class T16 , class T17 , class T18 , class T19 , class T20 , class T21 , class T22 , class T23 , class T24 > yes_type is_function_ptr_tester(R (*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24)); template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 , class T10 , class T11 , class T12 , class T13 , class T14 , class T15 , class T16 , class T17 , class T18 , class T19 , class T20 , class T21 , class T22 , class T23 , class T24 > yes_type is_function_ptr_tester(R (*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 ...)); #ifdef BOOST_TT_TEST_MS_FUNC_SIGS template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 , class T10 , class T11 , class T12 , class T13 , class T14 , class T15 , class T16 , class T17 , class T18 , class T19 , class T20 , class T21 , class T22 , class T23 , class T24 > yes_type is_function_ptr_tester(R (__stdcall*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24)); #ifndef _MANAGED template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 , class T10 , class T11 , class T12 , class T13 , class T14 , class T15 , class T16 , class T17 , class T18 , class T19 , class T20 , class T21 , class T22 , class T23 , class T24 > yes_type is_function_ptr_tester(R (__fastcall*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24)); #endif template <class R , class T0 , class T1 , class T2 , class T3 , class T4 , class T5 , class T6 , class T7 , class T8 , class T9 , class T10 , class T11 , class T12 , class T13 , class T14 , class T15 , class T16 , class T17 , class T18 , class T19 , class T20 , class T21 , class T22 , class T23 , class T24 > yes_type is_function_ptr_tester(R (__cdecl*)( T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24)); #endif #else #define BOOST_PP_ITERATION_PARAMS_1 \ (3, (0, 25, "boost/type_traits/detail/is_function_ptr_tester.hpp")) #include BOOST_PP_ITERATE() #endif // BOOST_TT_PREPROCESSING_MODE } // namespace type_traits } // namespace boost #endif // BOOST_TT_DETAIL_IS_FUNCTION_PTR_TESTER_HPP_INCLUDED ///// iteration #else #define BOOST_PP_COUNTER BOOST_PP_FRAME_ITERATION(1) #undef __stdcall #undef __fastcall #undef __cdecl template <class R BOOST_PP_COMMA_IF(BOOST_PP_COUNTER) BOOST_PP_ENUM_PARAMS(BOOST_PP_COUNTER,class T) > yes_type is_function_ptr_tester(R (*)(BOOST_PP_ENUM_PARAMS(BOOST_PP_COUNTER,T))); @#ifndef BOOST_TT_NO_ELLIPSIS_IN_FUNC_TESTING template <class R BOOST_PP_COMMA_IF(BOOST_PP_COUNTER) BOOST_PP_ENUM_PARAMS(BOOST_PP_COUNTER,class T) > yes_type is_function_ptr_tester(R (*)(BOOST_PP_ENUM_PARAMS(BOOST_PP_COUNTER,T) ...)); @#endif @#ifdef BOOST_TT_TEST_MS_FUNC_SIGS template <class R BOOST_PP_COMMA_IF(BOOST_PP_COUNTER) BOOST_PP_ENUM_PARAMS(BOOST_PP_COUNTER,class T) > yes_type is_function_ptr_tester(R (__stdcall*)(BOOST_PP_ENUM_PARAMS(BOOST_PP_COUNTER,T))); @#ifndef _MANAGED template <class R BOOST_PP_COMMA_IF(BOOST_PP_COUNTER) BOOST_PP_ENUM_PARAMS(BOOST_PP_COUNTER,class T) > yes_type is_function_ptr_tester(R (__fastcall*)(BOOST_PP_ENUM_PARAMS(BOOST_PP_COUNTER,T))); @#endif template <class R BOOST_PP_COMMA_IF(BOOST_PP_COUNTER) BOOST_PP_ENUM_PARAMS(BOOST_PP_COUNTER,class T) > yes_type is_function_ptr_tester(R (__cdecl*)(BOOST_PP_ENUM_PARAMS(BOOST_PP_COUNTER,T))); @#endif #undef BOOST_PP_COUNTER #endif // BOOST_PP_IS_ITERATING
{ "pile_set_name": "Github" }
## aframe-log-component [![Version](http://img.shields.io/npm/v/aframe-log-component.svg?style=flat-square)](https://npmjs.org/package/aframe-log-component) [![License](http://img.shields.io/npm/l/aframe-log-component.svg?style=flat-square)](https://npmjs.org/package/aframe-log-component) In-VR console logs for [A-Frame](https://aframe.io). ![logging](https://user-images.githubusercontent.com/674727/27067447-d875c6ac-4fbf-11e7-94ed-b127d7468dd3.gif) ### API #### AFRAME.log (message, channel) Provided global function to `console.log` a message into VR. ```html <a-scene> <a-entity position="0 0 -3"> <a-entity log geometry="primitive: plane" material></a-entity> <a-entity log="channel: foo" geometry="primitive: plane" material></a-entity> </a-entity> </a-scene> ``` ```js AFRAME.log('hello to all log entities'); AFRAME.log('hello to foo', 'foo'); ``` #### Properties | Property | Description | Default Value | | -------- | ----------- | ------------- | | channel | String to specify to only render logs that are sent with a specific channel. | '' | | filter | Plain-text string filter. (e.g., `filter: bar` would match log messages with `bar` in them. | '' | | max | Max number of logs to show at a time. | 100 | | showErrors | Whether to show JS errors. | true | #### `<a-log>` Primitive with a default plane geometry, black material, and light green text. ```html <script> AFRAME.registerComponent('main', { AFRAME.log('talking to <a-log>'); }); </script> <a-scene> <a-log position="0 0 -4"></a-log> </a-scene> ``` #### Logging Via Events ```js document.querySelector('a-scene').emit('log', {message: 'hello', channel: 'bar'}); ``` #### Disabling copy of output to Javascript `console.log` By default a copy of the in-VR log is also sent to the normal Javascript console via `console.log`. To disable this add `log` system to your `a-scene` and set `console` parameter to `false` (default: `true`). ```js <a-scene log="console: false"> <a-log position="0 0 -4"></a-log> </a-scene> ``` ### Installation #### Browser Install and use by directly including the [browser files](dist): ```html <head> <title>My A-Frame Scene</title> <script src="https://aframe.io/releases/0.9.0/aframe.min.js"></script> <script src="https://unpkg.com/aframe-log-component/dist/aframe-log-component.min.js"></script> </head> <body> <a-scene> <!-- Or <a-log position="0 0 -4"></a-log>. --> <a-entity log geometry="primitive: plane" material="color: #111" text="color: lightgreen" position="0 0 -4"></a-entity> </a-scene> </body> ``` #### npm Install via npm: ```bash npm install aframe-log-component ``` Then require and use. ```js require('aframe'); require('aframe-log-component'); ``` ### Roadmap - Allow listening and outputting from vanilla `console.log`s.
{ "pile_set_name": "Github" }
#!/bin/bash # Copyright © 2020 Interplanetary Database Association e.V., # BigchainDB and IPDB software contributors. # SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) # Code is Apache-2.0 and docs are CC-BY-4.0 docker build -t bigchaindb/mongodb-monitoring-agent:2.0.0-alpha . docker push bigchaindb/mongodb-monitoring-agent:2.0.0-alpha
{ "pile_set_name": "Github" }
// // AppDelegate.swift // ReactiveSwiftFlickrSearch // // Created by Colin Eberhardt on 06/07/2014. // Copyright (c) 2014 Colin Eberhardt. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var navigationController: UINavigationController! func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool { navigationController = UINavigationController() navigationController.navigationBar.barTintColor = UIColor.darkGrayColor() navigationController.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName : UIColor.whiteColor()] let viewModelServices = ViewModelServicesImpl(navigationController: navigationController) let viewModel = FlickrSearchViewModel(services: viewModelServices) let viewController = FlickrSearchViewController(viewModel: viewModel) navigationController.pushViewController(viewController, animated: false) window = UIWindow(frame: UIScreen.mainScreen().bounds) window!.rootViewController = navigationController window!.makeKeyAndVisible() return true } }
{ "pile_set_name": "Github" }
quspin.tools.lanczos.lanczos\_full ================================== .. currentmodule:: quspin.tools.lanczos .. autofunction:: lanczos_full
{ "pile_set_name": "Github" }
/* Copyright 2017 The Kubernetes Authors. 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 eventratelimit import ( "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" ) var ( SchemeBuilder = runtime.NewSchemeBuilder(addKnownTypes) AddToScheme = SchemeBuilder.AddToScheme ) // GroupName is the group name use in this package const GroupName = "eventratelimit.admission.k8s.io" // SchemeGroupVersion is group version used to register these objects var SchemeGroupVersion = schema.GroupVersion{Group: GroupName, Version: runtime.APIVersionInternal} // Kind takes an unqualified kind and returns a Group qualified GroupKind func Kind(kind string) schema.GroupKind { return SchemeGroupVersion.WithKind(kind).GroupKind() } // Resource takes an unqualified resource and returns a Group qualified GroupResource func Resource(resource string) schema.GroupResource { return SchemeGroupVersion.WithResource(resource).GroupResource() } func addKnownTypes(scheme *runtime.Scheme) error { // TODO this will get cleaned up with the scheme types are fixed scheme.AddKnownTypes(SchemeGroupVersion, &Configuration{}, ) return nil }
{ "pile_set_name": "Github" }
# Why We Need Both See `@hdgarrood`'s [Thoughts on PureScript package management in 2019](https://harry.garrood.me/blog/purescript-package-management-in-2019/). Below are my thoughts on why we need both. I'm not sure whether this is entirely correct. Think about what happens when a PureScript release is made that includes breaking changes. Updating each library in the ecosystem to account for those breaking changes is similar to putting a plant inside a vase with colored water. The colored water will first enter its roots, then go up its branches, and finally appear in every leaf ([Kids' experiment explained with photos](http://www.teaching-tiny-tots.com/toddler-science-celery-experiment.html)) In our above analogy, the `purescript-prelude` library and other libraries with no dependencies are the "roots" of the ecosystem. As they get updated, the libraries that depend on them (i.e. the "branches") can now be updated. A "leaf" corresponds to a library which has no dependents. A package set is immutable. Thus, one cannot add to the package set a package that has been updated to the new release unless all of the packages in the package set can also be updated. During that transitional time, `spago` cannot help. Rather, we must depend on `Bower` to slowly update each library to its new version that depends on transitive libraries that have been updated to new versions. Again, `spago` is more suited for application developers and `bower` is more suited for library developers.
{ "pile_set_name": "Github" }
// // Thread_WIN32.h // // $Id: //poco/1.4/Foundation/include/Poco/Thread_WIN32.h#1 $ // // Library: Foundation // Package: Threading // Module: Thread // // Definition of the ThreadImpl class for WIN32. // // Copyright (c) 2004-2009, Applied Informatics Software Engineering GmbH. // and Contributors. // // SPDX-License-Identifier: BSL-1.0 // #ifndef Foundation_Thread_WIN32_INCLUDED #define Foundation_Thread_WIN32_INCLUDED #include "Poco/Foundation.h" #include "Poco/Runnable.h" #include "Poco/SharedPtr.h" #include "Poco/UnWindows.h" namespace Poco { class Foundation_API ThreadImpl { public: typedef DWORD TIDImpl; typedef void (*Callable)(void*); #if defined(_DLL) typedef DWORD (WINAPI *Entry)(LPVOID); #else typedef unsigned (__stdcall *Entry)(void*); #endif enum Priority { PRIO_LOWEST_IMPL = THREAD_PRIORITY_LOWEST, PRIO_LOW_IMPL = THREAD_PRIORITY_BELOW_NORMAL, PRIO_NORMAL_IMPL = THREAD_PRIORITY_NORMAL, PRIO_HIGH_IMPL = THREAD_PRIORITY_ABOVE_NORMAL, PRIO_HIGHEST_IMPL = THREAD_PRIORITY_HIGHEST }; enum Policy { POLICY_DEFAULT_IMPL = 0 }; ThreadImpl(); ~ThreadImpl(); TIDImpl tidImpl() const; void setPriorityImpl(int prio); int getPriorityImpl() const; void setOSPriorityImpl(int prio, int policy = 0); int getOSPriorityImpl() const; static int getMinOSPriorityImpl(int policy); static int getMaxOSPriorityImpl(int policy); void setStackSizeImpl(int size); int getStackSizeImpl() const; void startImpl(SharedPtr<Runnable> pTarget); void joinImpl(); bool joinImpl(long milliseconds); bool isRunningImpl() const; static void sleepImpl(long milliseconds); static void yieldImpl(); static ThreadImpl* currentImpl(); static TIDImpl currentTidImpl(); protected: #if defined(_DLL) static DWORD WINAPI runnableEntry(LPVOID pThread); #else static unsigned __stdcall runnableEntry(void* pThread); #endif void createImpl(Entry ent, void* pData); void threadCleanup(); private: class CurrentThreadHolder { public: CurrentThreadHolder(): _slot(TlsAlloc()) { if (_slot == TLS_OUT_OF_INDEXES) throw SystemException("cannot allocate thread context key"); } ~CurrentThreadHolder() { TlsFree(_slot); } ThreadImpl* get() const { return reinterpret_cast<ThreadImpl*>(TlsGetValue(_slot)); } void set(ThreadImpl* pThread) { TlsSetValue(_slot, pThread); } private: DWORD _slot; }; SharedPtr<Runnable> _pRunnableTarget; HANDLE _thread; DWORD _threadId; int _prio; int _stackSize; static CurrentThreadHolder _currentThreadHolder; }; // // inlines // inline int ThreadImpl::getPriorityImpl() const { return _prio; } inline int ThreadImpl::getOSPriorityImpl() const { return _prio; } inline int ThreadImpl::getMinOSPriorityImpl(int /* policy */) { return PRIO_LOWEST_IMPL; } inline int ThreadImpl::getMaxOSPriorityImpl(int /* policy */) { return PRIO_HIGHEST_IMPL; } inline void ThreadImpl::sleepImpl(long milliseconds) { Sleep(DWORD(milliseconds)); } inline void ThreadImpl::yieldImpl() { Sleep(0); } inline void ThreadImpl::setStackSizeImpl(int size) { _stackSize = size; } inline int ThreadImpl::getStackSizeImpl() const { return _stackSize; } inline ThreadImpl::TIDImpl ThreadImpl::tidImpl() const { return _threadId; } } // namespace Poco #endif // Foundation_Thread_WIN32_INCLUDED
{ "pile_set_name": "Github" }
/* * 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 org.apache.arrow.gandiva.expression; import org.apache.arrow.gandiva.exceptions.GandivaException; import org.apache.arrow.gandiva.ipc.GandivaTypes; /** * Defines an internal node in the expression tree. */ public interface TreeNode { /** * Converts a TreeNode into a protobuf. * * @return A treenode protobuf * @throws GandivaException in case the TreeNode cannot be processed */ GandivaTypes.TreeNode toProtobuf() throws GandivaException; }
{ "pile_set_name": "Github" }
// Copyright 2018 The Prometheus Authors // 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 util import ( "io/ioutil" "strconv" "strings" ) // ParseUint32s parses a slice of strings into a slice of uint32s. func ParseUint32s(ss []string) ([]uint32, error) { us := make([]uint32, 0, len(ss)) for _, s := range ss { u, err := strconv.ParseUint(s, 10, 32) if err != nil { return nil, err } us = append(us, uint32(u)) } return us, nil } // ParseUint64s parses a slice of strings into a slice of uint64s. func ParseUint64s(ss []string) ([]uint64, error) { us := make([]uint64, 0, len(ss)) for _, s := range ss { u, err := strconv.ParseUint(s, 10, 64) if err != nil { return nil, err } us = append(us, u) } return us, nil } // ReadUintFromFile reads a file and attempts to parse a uint64 from it. func ReadUintFromFile(path string) (uint64, error) { data, err := ioutil.ReadFile(path) if err != nil { return 0, err } return strconv.ParseUint(strings.TrimSpace(string(data)), 10, 64) }
{ "pile_set_name": "Github" }
PREP(accessAllowed); PREP(addDisplayPassthroughKeys); PREP(getUnitsBIChannel); PREP(handlePttKeyPress); PREP(handlePttKeyPressUp); PREP(modifyGroup); PREP(nameGroup); PREP(sendText);
{ "pile_set_name": "Github" }
package ratelimiter type Storage interface { GetBucketFor(string) (*LeakyBucket, error) SetBucketFor(string, LeakyBucket) error }
{ "pile_set_name": "Github" }
BOOST_LIBS = @Boost_LIBS_@ BOOST_INCLUDE = @Boost_INCLUDE_@ BOOST_LIBRARIES = @Boost_LIBRARIES_@ BOOST_SYSTEM_LIB = @Boost_SYSTEM_LIBRARY@ BOOST_FILESYSTEM_LIB = @Boost_FILESYSTEM_LIBRARY@ BOOST_PROGRAM_OPTIONS_LIB = @Boost_PROGRAM_OPTIONS_LIBRARY@ SUNDIALS_LIBS=@SUNDIALS_LIBS_@ SUNDIALS_INCLUDE= @SUNDIALS_INCLUDE_DIR_@ SUNDIALS_LIBRARIES = @SUNDIALS_LIBRARIES_@ LAPACK_LIBS = @LAPACK_LIBS_@ LAPACK_LIBRARIES = @LAPACK_LIBRARIES_@ UMFPACK_LIBS = @SUITESPARSE_UMFPACK_LIBS@ UMFPACK_INCLUDE = @UMFPACK_INCLUDE_@ UMFPACK_LIBRARIES = @UMFPACK_LIBRARIES_@ INTEL_TBB_LIBS=@TBB_LIBRARY_DIRS@ INTEL_TBB_INCLUDE = @TBB_INCLUDE_DIR_@ INTEL_TBB_LIBRARIES = @INTEL_TBB_LIBS@ PUGIXML_INCLUDE = @PUGIXML_INCLUDE_DIR_@ PUGIXML_LIBRARIES = @PUGIXML_LIBRARIES@ MODELICA_SYSTEM_LIB_EXT = @MODELICA_SYSTEM_LIB_EXT@ FMI_ARCH_DIR = @FMI_ARCH_DIR@ LINUX_LIB_DL = @LINUX_LIB_DL@ BASE_LIB = @BASE_LIB@ PCH_FILE = @PCH_FILE@ PCH_LIB = @PCH_LIB@ H_FILE = @H_FILE@ BUILD_TYPE = @BUILD_TYPE@ SYSTEM_CFLAGS = @SYSTEM_CFLAGS@ ADDITIONAL_DEFINES = @ADDITIONAL_DEFINES@ USE_LOGGER=@USE_LOGGER_@ USE_DGESV=@USE_DGESV_@
{ "pile_set_name": "Github" }
/* * Copyright 2020 Adobe. All rights reserved. * This file is licensed 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 REPRESENTATIONS * OF ANY KIND, either express or implied. See the License for the specific language * governing permissions and limitations under the License. */ import {ProgressBar} from '../'; import React from 'react'; import {render} from '@testing-library/react'; import V2ProgressBar from '@react/react-spectrum/Progress'; describe('ProgressBar', function () { it.each` Name | Component ${'ProgressBar'} | ${ProgressBar} ${'V2ProgressBar'} | ${V2ProgressBar} `('$Name handles defaults', function ({Component}) { let {getByRole} = render(<Component label="Progress Bar" />); let progressBar = getByRole('progressbar'); expect(progressBar).toHaveAttribute('aria-valuemin', '0'); expect(progressBar).toHaveAttribute('aria-valuemax', '100'); expect(progressBar).toHaveAttribute('aria-valuenow', '0'); expect(progressBar).toHaveAttribute('aria-valuetext', '0%'); let labelId = progressBar.getAttribute('aria-labelledby'); expect(labelId).toBeDefined(); let label = document.getElementById(labelId); expect(label).toHaveTextContent('Progress Bar'); }); it.each` Name | Component | props ${'ProgressBar'} | ${ProgressBar} | ${{value: 30}} ${'V2ProgressBar'} | ${V2ProgressBar} | ${{value: 30}} `('$Name update all fileds by value', function ({Component, props}) { let {getByRole} = render(<Component {...props} label="Progress Bar" />); let progressBar = getByRole('progressbar'); expect(progressBar).toHaveAttribute('aria-valuemin', '0'); expect(progressBar).toHaveAttribute('aria-valuemax', '100'); expect(progressBar).toHaveAttribute('aria-valuenow', '30'); expect(progressBar).toHaveAttribute('aria-valuetext', '30%'); }); it.each` Name | Component | props ${'ProgressBar'} | ${ProgressBar} | ${{value: -1}} ${'V2ProgressBar'} | ${V2ProgressBar} | ${{value: -1}} `('$Name clamps values to 0', function ({Component, props}) { let {getByRole} = render(<Component {...props} label="Progress Bar" />); let progressBar = getByRole('progressbar'); expect(progressBar).toHaveAttribute('aria-valuenow', '0'); expect(progressBar).toHaveAttribute('aria-valuetext', '0%'); }); it.each` Name | Component | props ${'ProgressBar'} | ${ProgressBar} | ${{value: 1000}} ${'V2ProgressBar'} | ${V2ProgressBar} | ${{value: 1000}} `('$Name clamps values to 100', function ({Component, props}) { let {getByRole} = render(<Component {...props} label="Progress Bar" />); let progressBar = getByRole('progressbar'); expect(progressBar).toHaveAttribute('aria-valuenow', '100'); expect(progressBar).toHaveAttribute('aria-valuetext', '100%'); }); it.each` Name | Component | props ${'ProgressBar'} | ${ProgressBar} | ${{size: 'S', UNSAFE_className: 'testClass'}} ${'V2ProgressBar'} | ${V2ProgressBar} | ${{size: 'S', className: 'testClass'}} `('$Name supports UNSAFE_className', function ({Component, props}) { let {getByRole} = render(<Component {...props} label="Progress Bar" />); let progressBar = getByRole('progressbar'); expect(progressBar).toHaveAttribute('class', expect.stringContaining('testClass')); }); it('Can handle negative values', () => { let {getByRole} = render(<ProgressBar value={0} minValue={-5} maxValue={5} label="Progress Bar" />); let progressBar = getByRole('progressbar'); expect(progressBar).toHaveAttribute('aria-valuenow', '0'); expect(progressBar).toHaveAttribute('aria-valuetext', '50%'); }); it('warns user if no aria-label is provided', () => { let spyWarn = jest.spyOn(console, 'warn').mockImplementation(() => {}); render(<ProgressBar value={25} />); expect(spyWarn).toHaveBeenCalledWith('If you do not provide a visible label via children, you must specify an aria-label or aria-labelledby attribute for accessibility'); }); it('supports custom DOM props', function () { let {getByTestId} = render(<ProgressBar label="Meter" data-testid="test" />); let progressBar = getByTestId('test'); expect(progressBar).toBeInTheDocument(); }); });
{ "pile_set_name": "Github" }
/* * Copyright 2012-2016 the original author or authors * @license MIT, see LICENSE.txt for details * * @author Jeremy Grelle * @author Scott Andrews */ 'use strict'; var parser, http, https, mixin, normalizeHeaderName, responsePromise, client, httpsExp; parser = require('url'); http = require('http'); https = require('https'); mixin = require('../util/mixin'); normalizeHeaderName = require('../util/normalizeHeaderName'); responsePromise = require('../util/responsePromise'); client = require('../client'); httpsExp = /^https/i; // TODO remove once Node 0.6 is no longer supported Buffer.concat = Buffer.concat || function (list, length) { /*jshint plusplus:false, shadow:true */ // from https://github.com/joyent/node/blob/v0.8.21/lib/buffer.js if (!Array.isArray(list)) { throw new Error('Usage: Buffer.concat(list, [length])'); } if (list.length === 0) { return new Buffer(0); } else if (list.length === 1) { return list[0]; } if (typeof length !== 'number') { length = 0; for (var i = 0; i < list.length; i++) { var buf = list[i]; length += buf.length; } } var buffer = new Buffer(length); var pos = 0; for (var i = 0; i < list.length; i++) { var buf = list[i]; buf.copy(buffer, pos); pos += buf.length; } return buffer; }; module.exports = client(function node(request) { /*jshint maxcomplexity:20 */ return responsePromise.promise(function (resolve, reject) { var options, clientRequest, client, url, headers, entity, response; request = typeof request === 'string' ? { path: request } : request || {}; response = { request: request }; if (request.canceled) { response.error = 'precanceled'; reject(response); return; } url = response.url = request.path || ''; client = url.match(httpsExp) ? https : http; options = mixin({}, request.mixin, parser.parse(url)); entity = request.entity; request.method = request.method || (entity ? 'POST' : 'GET'); options.method = request.method; headers = options.headers = {}; Object.keys(request.headers || {}).forEach(function (name) { headers[normalizeHeaderName(name)] = request.headers[name]; }); if (!headers['Content-Length']) { headers['Content-Length'] = entity ? Buffer.byteLength(entity, 'utf8') : 0; } request.canceled = false; request.cancel = function cancel() { request.canceled = true; clientRequest.abort(); }; clientRequest = client.request(options, function (clientResponse) { // Array of Buffers to collect response chunks var buffers = []; response.raw = { request: clientRequest, response: clientResponse }; response.status = { code: clientResponse.statusCode // node doesn't provide access to the status text }; response.headers = {}; Object.keys(clientResponse.headers).forEach(function (name) { response.headers[normalizeHeaderName(name)] = clientResponse.headers[name]; }); clientResponse.on('data', function (data) { // Collect the next Buffer chunk buffers.push(data); }); clientResponse.on('end', function () { // Create the final response entity response.entity = buffers.length > 0 ? Buffer.concat(buffers).toString() : ''; buffers = null; resolve(response); }); }); clientRequest.on('error', function (e) { response.error = e; reject(response); }); if (entity) { clientRequest.write(entity); } clientRequest.end(); }); });
{ "pile_set_name": "Github" }
package integration import model.{ Article, Comment, User } import skinny.micro.context.SkinnyContext object NullIntegration extends ExternalServiceIntegration { override def onCommentCreated(commenter: User, comment: Comment)(implicit ctx: SkinnyContext): Unit = {} override def onPostCreated(author: User, article: Article)(implicit ctx: SkinnyContext): Unit = {} }
{ "pile_set_name": "Github" }
import { storiesOf } from "@storybook/react"; import * as React from "react"; import { PostCard } from "."; import { defaultLinkProps } from "../Link"; import { MyButton } from "../MyButton"; storiesOf("Post Card", module).add("basic example", () => ( <div style={{ display: "inline-block" }}> <PostCard id="12" title="i am a title" commitId="" repo="codeponder" repoOwner="benawad" topics={["typescript"]} creator={{ id: "1", username: "benawad", pictureUrl: "https://dummyimage.com/600x400/000/fff", }} Link={MyButton} getLinkProps={() => defaultLinkProps} /> </div> ));
{ "pile_set_name": "Github" }
/************************************************************************ * Copyright(c) 2010, One Unified. All rights reserved. * * * * This file is provided as is WITHOUT ANY WARRANTY * * without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * * * This software may not be used nor distributed without proper license * * agreement. * * * * See the file LICENSE.txt for redistribution information. * ************************************************************************/ #pragma once // 2010/09/12 // unsigned long autoinc keys for uniquely identifying records // for best performance, database/table should be kept open. #include <string> #include "KeyValuePairs.h" // // CAutoIncKeys // class CAutoIncKeys: public CKeyValuePairs { public: typedef unsigned long keyValue_t; CAutoIncKeys( const std::string& sDbFileName ); ~CAutoIncKeys(void); void SetNextId( const std::string& key, keyValue_t ); keyValue_t GetNextId( const std::string& sKeyName ); keyValue_t GetCurrentId( const std::string& sKeyName ); protected: private: static const std::string m_sDbName; }; // // CAutoIncKey // class CAutoIncKey: public CAutoIncKeys { public: typedef unsigned long keyValue_t; CAutoIncKey( const std::string& sDbFileName, const std::string& sKeyName ); ~CAutoIncKey(void); void SetNextId( keyValue_t ); keyValue_t GetNextId( void ); keyValue_t GetCurrentId( void ); protected: std::string m_sKeyName; private: };
{ "pile_set_name": "Github" }
/*************************************************************************** qgsalgorithmlineintersection.h --------------------- begin : April 2017 copyright : (C) 2017 by Nyall Dawson email : nyall dot dawson at gmail dot com ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #ifndef QGSALGORITHMLINEINTERSECTION_H #define QGSALGORITHMLINEINTERSECTION_H #define SIP_NO_FILE #include "qgis_sip.h" #include "qgsprocessingalgorithm.h" #include "qgsapplication.h" ///@cond PRIVATE /** * Native line intersection algorithm. */ class QgsLineIntersectionAlgorithm : public QgsProcessingAlgorithm { public: QgsLineIntersectionAlgorithm() = default; void initAlgorithm( const QVariantMap &configuration = QVariantMap() ) override; QIcon icon() const override { return QgsApplication::getThemeIcon( QStringLiteral( "/algorithms/mAlgorithmLineIntersections.svg" ) ); } QString svgIconPath() const override { return QgsApplication::iconPath( QStringLiteral( "/algorithms/mAlgorithmLineIntersections.svg" ) ); } QString name() const override; QString displayName() const override; QStringList tags() const override; QString group() const override; QString groupId() const override; QString shortHelpString() const override; QgsLineIntersectionAlgorithm *createInstance() const override SIP_FACTORY; protected: QVariantMap processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback ) override; }; ///@endcond PRIVATE #endif // QGSALGORITHMLINEINTERSECTION_H
{ "pile_set_name": "Github" }
/** * This header is generated by class-dump-z 0.2b. * * Source: /System/Library/PrivateFrameworks/iWorkImport.framework/iWorkImport */ #import <iWorkImport/iWorkImport-Structs.h> #import <iWorkImport/GQDCallout2Path.h> #import <iWorkImport/GQDPath.h> __attribute__((visibility("hidden"))) @interface GQDCallout2Path : GQDPath { @private CGSize mSize; // 8 = 0x8 double mCornerRadius; // 16 = 0x10 CGPoint mTailPosition; // 24 = 0x18 double mTailSize; // 32 = 0x20 BOOL mTailAtCenter; // 40 = 0x28 } - (CGPoint)tailCenter; // 0x59421 - (CGPathRef)createBezierPath; // 0x596cd - (CGSize)size; // 0x5958d - (double)cornerRadius; // 0x595a5 - (CGPoint)tailPosition; // 0x595bd - (double)tailSize; // 0x595d5 - (BOOL)tailAtCenter; // 0x595ed @end @interface GQDCallout2Path (Private) - (int)readAttributesFromReader:(xmlTextReader *)reader processor:(id)processor; // 0x59b79 @end
{ "pile_set_name": "Github" }
@comment $NetBSD: PLIST,v 1.42 2010/11/24 20:24:10 drochner Exp $ bin/gnome-about include/gnome-desktop-2.0/libgnome/gnome-desktop-item.h include/gnome-desktop-2.0/libgnome/gnome-desktop-utils.h include/gnome-desktop-2.0/libgnomeui/gnome-bg-crossfade.h include/gnome-desktop-2.0/libgnomeui/gnome-bg.h include/gnome-desktop-2.0/libgnomeui/gnome-desktop-thumbnail.h include/gnome-desktop-2.0/libgnomeui/gnome-rr-config.h include/gnome-desktop-2.0/libgnomeui/gnome-rr-labeler.h include/gnome-desktop-2.0/libgnomeui/gnome-rr.h lib/libgnome-desktop-2.la lib/pkgconfig/gnome-desktop-2.0.pc man/man1/gnome-about.1 share/applications/gnome-about.desktop share/gnome-about/contributors.list share/gnome-about/foundation-members.list share/gnome-about/gnome-64.png share/gnome-about/gnome-version.xml share/gnome-about/headers/header-bg-ancient01a.png share/gnome-about/headers/header-bg-city01.png share/gnome-about/headers/header-bg-clouds01.png share/gnome-about/headers/header-bg-clouds02.png share/gnome-about/headers/header-bg-hills01.png share/gnome-about/headers/header-bg-landscape01.png share/gnome-about/headers/header-bg-mountains01.png share/gnome-about/headers/header-bg-snow01.png share/gnome-about/headers/header-bg-sunset01.png share/gnome/help/fdl/C/fdl.xml share/gnome/help/fdl/ar/fdl.xml share/gnome/help/fdl/ca/fdl.xml share/gnome/help/fdl/de/fdl.xml share/gnome/help/fdl/el/fdl.xml share/gnome/help/fdl/es/fdl.xml share/gnome/help/fdl/eu/fdl.xml share/gnome/help/fdl/fr/fdl.xml share/gnome/help/fdl/hu/fdl.xml share/gnome/help/fdl/ko/fdl.xml share/gnome/help/fdl/oc/fdl.xml share/gnome/help/fdl/pl/fdl.xml share/gnome/help/fdl/sv/fdl.xml share/gnome/help/fdl/uk/fdl.xml share/gnome/help/fdl/vi/fdl.xml share/gnome/help/gpl/C/gpl.xml share/gnome/help/gpl/ar/gpl.xml share/gnome/help/gpl/ca/gpl.xml share/gnome/help/gpl/cs/gpl.xml share/gnome/help/gpl/de/gpl.xml share/gnome/help/gpl/el/gpl.xml share/gnome/help/gpl/es/gpl.xml share/gnome/help/gpl/eu/gpl.xml share/gnome/help/gpl/fi/gpl.xml share/gnome/help/gpl/fr/gpl.xml share/gnome/help/gpl/hu/gpl.xml share/gnome/help/gpl/ko/gpl.xml share/gnome/help/gpl/nds/gpl.xml share/gnome/help/gpl/oc/gpl.xml share/gnome/help/gpl/pa/gpl.xml share/gnome/help/gpl/sv/gpl.xml share/gnome/help/gpl/uk/gpl.xml share/gnome/help/gpl/vi/gpl.xml share/gnome/help/gpl/zh_CN/gpl.xml share/gnome/help/lgpl/C/lgpl.xml share/gnome/help/lgpl/ar/lgpl.xml share/gnome/help/lgpl/de/lgpl.xml share/gnome/help/lgpl/el/lgpl.xml share/gnome/help/lgpl/es/lgpl.xml share/gnome/help/lgpl/eu/lgpl.xml share/gnome/help/lgpl/fi/lgpl.xml share/gnome/help/lgpl/fr/lgpl.xml share/gnome/help/lgpl/hu/lgpl.xml share/gnome/help/lgpl/ko/lgpl.xml share/gnome/help/lgpl/oc/lgpl.xml share/gnome/help/lgpl/pa/lgpl.xml share/gnome/help/lgpl/sv/lgpl.xml share/gnome/help/lgpl/uk/lgpl.xml share/gnome/help/lgpl/vi/lgpl.xml share/gnome/help/lgpl/zh_CN/lgpl.xml share/gtk-doc/html/gnome-desktop/GnomeBG.html share/gtk-doc/html/gnome-desktop/GnomeDesktopThumbnailFactory.html share/gtk-doc/html/gnome-desktop/GnomeRRLabeler.html share/gtk-doc/html/gnome-desktop/background.html share/gtk-doc/html/gnome-desktop/gnome-desktop-GnomeDesktopItem.html share/gtk-doc/html/gnome-desktop/gnome-desktop-Miscellaneous-Functions.html share/gtk-doc/html/gnome-desktop/gnome-desktop-Miscellaneous-Thumbnail-Functions.html share/gtk-doc/html/gnome-desktop/gnome-desktop-gnome-rr-config.html share/gtk-doc/html/gnome-desktop/gnome-desktop-gnome-rr-crtc.html share/gtk-doc/html/gnome-desktop/gnome-desktop-gnome-rr-mode.html share/gtk-doc/html/gnome-desktop/gnome-desktop-gnome-rr-output.html share/gtk-doc/html/gnome-desktop/gnome-desktop-gnome-rr-screen.html share/gtk-doc/html/gnome-desktop/gnome-desktop.devhelp share/gtk-doc/html/gnome-desktop/gnome-desktop.devhelp2 share/gtk-doc/html/gnome-desktop/home.png share/gtk-doc/html/gnome-desktop/index.html share/gtk-doc/html/gnome-desktop/index.sgml share/gtk-doc/html/gnome-desktop/intro.html share/gtk-doc/html/gnome-desktop/left.png share/gtk-doc/html/gnome-desktop/libgnome.html share/gtk-doc/html/gnome-desktop/randr.html share/gtk-doc/html/gnome-desktop/right.png share/gtk-doc/html/gnome-desktop/style.css share/gtk-doc/html/gnome-desktop/thumbnail.html share/gtk-doc/html/gnome-desktop/up.png share/libgnome-desktop/pnp.ids share/locale/af/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/am/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/an/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/ar/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/as/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/ast/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/az/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/be/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/be@latin/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/bg/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/bn/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/bn_IN/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/br/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/bs/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/ca/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/ca@valencia/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/crh/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/cs/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/cy/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/da/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/de/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/dz/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/el/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/en@shaw/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/en_CA/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/en_GB/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/eo/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/es/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/et/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/eu/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/fa/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/fi/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/fr/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/fur/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/ga/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/gl/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/gu/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/he/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/hi/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/hr/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/hu/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/hy/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/id/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/ig/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/is/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/it/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/ja/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/ka/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/kk/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/kn/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/ko/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/ku/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/ky/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/li/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/lo/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/lt/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/lv/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/mai/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/mg/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/mi/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/mk/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/ml/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/mn/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/mr/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/ms/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/nb/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/nds/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/ne/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/nl/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/nn/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/nso/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/oc/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/or/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/pa/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/pl/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/ps/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/pt/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/pt_BR/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/ro/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/ru/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/rw/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/si/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/sk/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/sl/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/sq/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/sr/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/sr@latin/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/sv/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/ta/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/te/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/th/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/tk/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/tr/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/ug/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/uk/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/ur/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/uz/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/uz@cyrillic/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/vi/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/wa/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/xh/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/yi/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/yo/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/zh_CN/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/zh_HK/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/zh_TW/LC_MESSAGES/gnome-desktop-2.0.mo share/locale/zu/LC_MESSAGES/gnome-desktop-2.0.mo share/omf/fdl/fdl-C.omf share/omf/fdl/fdl-ar.omf share/omf/fdl/fdl-ca.omf share/omf/fdl/fdl-de.omf share/omf/fdl/fdl-el.omf share/omf/fdl/fdl-es.omf share/omf/fdl/fdl-eu.omf share/omf/fdl/fdl-fr.omf share/omf/fdl/fdl-hu.omf share/omf/fdl/fdl-ko.omf share/omf/fdl/fdl-oc.omf share/omf/fdl/fdl-pl.omf share/omf/fdl/fdl-sv.omf share/omf/fdl/fdl-uk.omf share/omf/fdl/fdl-vi.omf share/omf/gpl/gpl-C.omf share/omf/gpl/gpl-ar.omf share/omf/gpl/gpl-ca.omf share/omf/gpl/gpl-cs.omf share/omf/gpl/gpl-de.omf share/omf/gpl/gpl-el.omf share/omf/gpl/gpl-es.omf share/omf/gpl/gpl-eu.omf share/omf/gpl/gpl-fi.omf share/omf/gpl/gpl-fr.omf share/omf/gpl/gpl-hu.omf share/omf/gpl/gpl-ko.omf share/omf/gpl/gpl-nds.omf share/omf/gpl/gpl-oc.omf share/omf/gpl/gpl-pa.omf share/omf/gpl/gpl-sv.omf share/omf/gpl/gpl-uk.omf share/omf/gpl/gpl-vi.omf share/omf/gpl/gpl-zh_CN.omf share/omf/lgpl/lgpl-C.omf share/omf/lgpl/lgpl-ar.omf share/omf/lgpl/lgpl-de.omf share/omf/lgpl/lgpl-el.omf share/omf/lgpl/lgpl-es.omf share/omf/lgpl/lgpl-eu.omf share/omf/lgpl/lgpl-fi.omf share/omf/lgpl/lgpl-fr.omf share/omf/lgpl/lgpl-hu.omf share/omf/lgpl/lgpl-ko.omf share/omf/lgpl/lgpl-oc.omf share/omf/lgpl/lgpl-pa.omf share/omf/lgpl/lgpl-sv.omf share/omf/lgpl/lgpl-uk.omf share/omf/lgpl/lgpl-vi.omf share/omf/lgpl/lgpl-zh_CN.omf share/pixmaps/apple-green.png share/pixmaps/apple-red.png share/pixmaps/gnome-aorta.png share/pixmaps/gnome-applets.png share/pixmaps/gnome-background-image.png share/pixmaps/gnome-background-pattern.png share/pixmaps/gnome-background.png share/pixmaps/gnome-calc2.png share/pixmaps/gnome-calc3.png share/pixmaps/gnome-calendar.png share/pixmaps/gnome-ccbackground.png share/pixmaps/gnome-ccdesktop.png share/pixmaps/gnome-ccdialog.png share/pixmaps/gnome-ccmime.png share/pixmaps/gnome-ccperiph.png share/pixmaps/gnome-ccscreensaver.png share/pixmaps/gnome-ccwindowmanager.png share/pixmaps/gnome-color-browser.png share/pixmaps/gnome-color-xterm.png share/pixmaps/gnome-computer.png share/pixmaps/gnome-cromagnon.png share/pixmaps/gnome-day.png share/pixmaps/gnome-debian.png share/pixmaps/gnome-diskfree.png share/pixmaps/gnome-emacs.png share/pixmaps/gnome-eterm.png share/pixmaps/gnome-file-c.png share/pixmaps/gnome-file-h.png share/pixmaps/gnome-folder.png share/pixmaps/gnome-gemvt.png share/pixmaps/gnome-gimp.png share/pixmaps/gnome-gmenu.png share/pixmaps/gnome-gmush.png share/pixmaps/gnome-gnomoku.png share/pixmaps/gnome-home.png share/pixmaps/gnome-html.png share/pixmaps/gnome-image-gif.png share/pixmaps/gnome-image-jpeg.png share/pixmaps/gnome-irc.png share/pixmaps/gnome-laptop.png share/pixmaps/gnome-log.png share/pixmaps/gnome-logo-icon-transparent.png share/pixmaps/gnome-logo-icon.png share/pixmaps/gnome-logo-large.png share/pixmaps/gnome-mdi.png share/pixmaps/gnome-mnemonic.png share/pixmaps/gnome-month.png share/pixmaps/gnome-mouse.png share/pixmaps/gnome-news.png share/pixmaps/gnome-note.png share/pixmaps/gnome-qeye.png share/pixmaps/gnome-set-time.png share/pixmaps/gnome-spider.png share/pixmaps/gnome-squeak.png share/pixmaps/gnome-suse.png share/pixmaps/gnome-talk.png share/pixmaps/gnome-term-linux.png share/pixmaps/gnome-term-linux2.png share/pixmaps/gnome-term-night.png share/pixmaps/gnome-term-tiger.png share/pixmaps/gnome-term.png share/pixmaps/gnome-tigert.png share/pixmaps/gnome-touristinfo.png share/pixmaps/gnome-user-interface.png share/pixmaps/gnome-week.png share/pixmaps/gnome-windows.png share/pixmaps/gnome-word.png share/pixmaps/gnome-xterm.png share/pixmaps/gtkvim.png share/pixmaps/kterm.xpm share/pixmaps/monitor.png share/pixmaps/netbsd-logo-icon-transparent.png share/pixmaps/netbsd-logo-icon.png share/pixmaps/vnterm.xpm
{ "pile_set_name": "Github" }
Pod::Spec.new do |s| s.name = 'NIMSDK_LITE' s.version = '7.9.1' s.summary = 'Netease IM Lite SDK' s.homepage = 'http://netease.im' s.license = { :'type' => 'Copyright', :'text' => ' Copyright 2019 Netease '} s.authors = 'Netease IM Team' s.source = { :http => 'http://yx-web.nos.netease.com/package/1599806229/NIM_iOS_SDK_IM_v7.9.1.zip'} s.platform = :ios, '9.0' s.vendored_frameworks = '**/NIMSDK.framework' s.frameworks = 'SystemConfiguration', 'AVFoundation', 'CoreTelephony', 'AudioToolbox', 'CoreMedia' , 'VideoToolbox' s.libraries = 'sqlite3.0', 'z', 'c++' end
{ "pile_set_name": "Github" }
library IEEE user IEEE.std_logic_1164.all; use IEEE.numeric_std.all; entity COUNT16 is port ( cOut :out std_logic_vector(15 downto 0); -- counter output clkEn :in std_logic; -- count enable clk :in std_logic; -- clock input rst :in std_logic -- reset input ); end entity; architecture count_rtl of COUNT16 is signal count :std_logic_vector (15 downto 0); begin process (clk, rst) begin if(rst = '1') then count <= (others=>'0'); elsif(rising_edge(clk)) then if(clkEn = '1') then count <= count + 1; end if; end if; end process; cOut <= count; end architecture;
{ "pile_set_name": "Github" }
<html> <head></head> <body>ÐÂ</body> </html>
{ "pile_set_name": "Github" }
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@include file="/WEB-INF/jsp/common/header.jsp"%> <%@include file="/WEB-INF/jsp/common/taglibs.jsp"%> <spring:eval var="showAdminControls" expression="T(org.sentilo.web.catalog.security.SecurityUtils).showAdminControls('READ', application)"/> <spring:eval var="showActiveSubscriptionsTab" expression="T(org.sentilo.web.catalog.security.SecurityUtils).showAdminControls('READ', application)"/> <spring:url value="/admin/application/${application.id}/edit" var="editApplicationLink" /> <spring:url value="/admin/application/list?nameTableRecover=applicationTable&fromBack=true" var="backURL" /> <c:set var="providerTableId" value="applicationDetailProviderTable" /> <%@include file="/WEB-INF/jsp/common/include_tab_classes.jsp"%> <div class="container-fluid"> <div class="content"> <div class="row-fluid"> <div class="span3"> <%@include file="/WEB-INF/jsp/common/include_sidebar.jsp"%> </div> <div class="span9"> <div class="row-fluid"> <div class="span12"> <%@include file="/WEB-INF/jsp/common/include_background_logo.jsp"%> <%@include file="/WEB-INF/jsp/common/messages.jsp"%> <h1 class="lead"> ${application.name}<br /> <small><spring:message code="id" /> ${application.id}</small> </h1> <div class="tabbable"> <ul class="nav nav-tabs"> <li class="${tab1Class}"><a href="#tab1" data-toggle="tab"><spring:message code="application.detail.title" /> </a></li> <li class="${tab2Class}"><a href="#tab2" data-toggle="tab"><spring:message code="application.permissions" /> </a></li> <c:if test="${showActiveSubscriptionsTab}"> <li class="${tab3Class}"><a href="#tab3" data-toggle="tab"><spring:message code="subscriptions.active.tab.label" /> </a></li> </c:if> </ul> <div class="tab-content"> <div class="${tab1PaneClass}" id="tab1"> <div class="accordion" id="detailAccordion"> <div class="accordion-group"> <div class="accordion-heading"> <a class="accordion-toggle" data-toggle="collapse" data-parent="#detailAccordion" href="#detailAccordionCollapse"> <i class="icon-th"></i> <spring:message code="data" /> <i class="icon-chevron-down pull-right"></i> </a> </div> <div id="detailAccordionCollapse" class="accordion-body collapse in"> <div class="accordion-inner"> <div class="row-fluid"> <div class="span4"> <strong><spring:message code="token" /> </strong> </div> <div class="span8">${application.token}</div> </div> <div class="row-fluid"> <div class="span4"> <strong><spring:message code="application.description" /> </strong> </div> <div class="span8"> <spring:eval expression="application.description" /> </div> </div> <div class="row-fluid"> <div class="span4"> <strong><spring:message code="application.restHttps" /> </strong> </div> <c:set var="restHttpsChecked" value="${fn:contains(application.restHttps, 'true') ? 'checked' : ''}"/> <div class="span8"><input type="checkbox" ${restHttpsChecked} disabled="disabled" onclick="javascript:return false;"/></div> </div> <div class="row-fluid"> <div class="span4"> <strong><spring:message code="application.createdAt" /> </strong> </div> <div class="span8"> <spring:eval expression="application.createdAt" /> </div> </div> <div class="row-fluid"> <div class="span4"> <strong><spring:message code="application.updatedAt" /> </strong> </div> <div class="span8"> <spring:eval expression="application.updatedAt" /> </div> </div> <div class="row-fluid"> <div class="span4"> <strong><spring:message code="application.email" /> </strong> </div> <div class="span8"> <a href="mailto:${application.email}">${application.email}</a> </div> </div> </div> </div> </div> </div> <div class="row-fluid"> <div class="span12"> <div class="control-group pull-right"> <%@include file="/WEB-INF/jsp/common/include_input_back.jsp"%> <c:if test="${showAdminControls}"> <a href="${editApplicationLink}" class="btn btn-primary"> <spring:message code="application.edit.title" /> </a> </c:if> </div> </div> </div> </div> <div class="${tab2PaneClass}" id="tab2"> <c:set var="applicationId" scope="request" value="${application.id}" /> <jsp:include page="/WEB-INF/jsp/common/include_permission_list.jsp" /> </div> <c:if test="${showActiveSubscriptionsTab}"> <div class="${tab3PaneClass}" id="tab3"> <c:set var="applicationId" scope="request" value="${application.id}" /> <jsp:include page="/WEB-INF/jsp/common/include_subscriptions.jsp" /> <div class="control-group pull-right"> <%@include file="/WEB-INF/jsp/common/include_input_back.jsp"%> </div> </div> </c:if> </div> </div> </div> </div> </div> </div> </div> </div> <%@include file="/WEB-INF/jsp/common/footer.jsp"%>
{ "pile_set_name": "Github" }
def main(): print('TEST SUCEEDED!')
{ "pile_set_name": "Github" }
import { i18nMark } from "@lingui/react"; import { pipe } from "rxjs"; import { isObject as isObjectUtil, findNestedPropertyInObject, } from "#SRC/js/utils/Util"; import { JobOutput, FormError, UcrImageKind, JobSpec, ConstraintOperator, } from "./JobFormData"; import { OperatorTypes } from "./Constants"; type MetronomeValidators = Record<string, (formData: JobOutput) => FormError[]>; // TODO: can be removed once we're on TS3, as it seems flatMap-support has landed there. const flatMap = <A, B>(map: (x: A, i: number) => B[], xs: A[]): B[] => xs.reduce((acc, x, i) => acc.concat(map(x, i)), [] as B[]); const validation = <T>( isValid: (val: T) => boolean, defaultMessage: string ) => (path: (i: number) => string, values: T[], message = defaultMessage) => ( errors: FormError[] ) => errors.concat( flatMap( (value, index) => isValid(value) ? [] : [{ message, path: path(index).split(".") }], values ) ); const stringMsg = i18nMark("Must be a string"); const presentMsg = i18nMark("Must be present"); const isBoolean = validation<boolean | undefined>( (x) => x === undefined || typeof x === "boolean", i18nMark("Must be a boolean") ); const isNumber = validation<number | undefined>( (x) => x === undefined || typeof x === "number", i18nMark("Must be a number") ); const isObject = validation<object | undefined>( (x) => x === undefined || isObjectUtil(x), i18nMark("Must be an object") ); const isPresent = validation<any>( (x) => x !== undefined && x !== "", presentMsg ); const isString = validation<string | undefined>( (x) => x === undefined || typeof x === "string", stringMsg ); const isArray = validation<any[] | undefined>( (x) => x === undefined || Array.isArray(x), i18nMark("Constraints must be an array") ); const allUniq = validation<any[]>( (list) => new Set(list).size === list.length, i18nMark("All elements must be unique") ); const isUniqIn = <T>(list: T[]) => validation<T>( (el: T) => list.filter((x) => x === el).length < 2, i18nMark("Must be unique") ); const isOnlyWhitespace = (str: unknown): boolean => !`${str}`.replace(/\s/g, "").length; const ensureArray = <T>(something?: T[]): T[] => Array.isArray(something) ? something : []; export const MetronomeSpecValidators: MetronomeValidators = { validate(formData: JobOutput): FormError[] { const { run } = formData; const parameters = ensureArray(run.docker && run.docker.parameters); const constraints = ensureArray(run.placement && run.placement.constraints); // prettier-ignore return pipe( // IS BOOLEAN isBoolean(_ => "run.docker.forcePullImage", [run.docker && run.docker.forcePullImage]), isBoolean(_ => "run.docker.privileged", [run.docker && run.docker.privileged]), isBoolean(_ => "run.ucr.privileged", [run.ucr && run.ucr.privileged]), isBoolean(_ => "run.ucr.image.forcePull", [run.ucr && run.ucr.image&& run.ucr.image.forcePull]), // IS NUMBER isNumber(_ => "run.cpus", [run.cpus]), isNumber(_ => "run.disk", [run.disk]), isNumber(_ => "run.gpus", [run.gpus]), isNumber(_ => "run.maxLaunchDelay", [run.maxLaunchDelay]), isNumber(_ => "run.mem", [run.mem]), isNumber(_ => "run.restart.activeDeadlineSeconds", [run.restart && run.restart.activeDeadlineSeconds]), isNumber(_ => "run.taskKillGracePeriodSeconds", [run.taskKillGracePeriodSeconds]), // IS OBJECT isObject(_ => "labels", [formData.labels]), isObject(_ => "run.docker", [run.docker]), isObject(_ => "run.env", [run.env]), isObject(_ => "run.ucr", [run.ucr]), isObject(_ => "run.ucr.image", [run.ucr && run.ucr.image]), // IS PRESENT isPresent(_ => "id", [formData.id]), isPresent(_ => "run.cpus", [run.cpus]), isPresent(_ => "run.disk", [run.disk]), isPresent(_ => "run.mem", [run.mem]), isPresent(i => `labels.${i}.key`, Object.keys(formData.labels || [])), isPresent(i => `run.artifacts.${i}.uri`, (run.artifacts || []).map(_ => _.uri)), isPresent(i => `run.docker.parameters.${i}.key`, parameters.map(_ => _.key)), isPresent(i => `run.docker.parameters.${i}.value`, parameters.map(_ => _.value)), // IS STRING isString(_ => "id", [formData.id]), isString(_ => "run.cmd", [run.cmd]), isString(_ => "run.docker.image", [run.docker && run.docker.image]), isString(_ => "run.restart.policy", [run.restart && run.restart.policy]), isString(_ => "run.ucr.image.id", [run.ucr && run.ucr.image && run.ucr.image.id]), isString(_ => "run.user", [run.user]), isString(i => `labels.${i}.key`, Object.keys(formData.labels || [])), isString(i => `labels.${i}.value`, Object.values(formData.labels || [])), isString(i => `run.args.${i}`, run.args || []), isString(i => `run.artifacts.${i}.uri`, (run.artifacts || []).map(_ => _.uri)), isString(i => `run.docker.parameters.${i}.key`, parameters.map(_ => _.key)), isString(i => `run.docker.parameters.${i}.value`, parameters.map(_ => _.value)), isString(i => `job.run.placement.constraints.${i}.operator`, constraints.map(_ => _.operator)), isString(i => `job.run.placement.constraints.${i}.attribute`, constraints.map(_ => _.attribute)), isString(i => `job.run.placement.constraints.${i}.value`, constraints.map(_ => _.value)) // pipe only infers 10 steps, so we need a cast here )([]) as FormError[]; }, /** * Ensure ID contains only allowed characters. */ jobIdIsValid(formData: JobOutput): FormError[] { const jobId = findNestedPropertyInObject(formData, "id"); const jobIdRegex = /^([a-z0-9]([a-z0-9-]*[a-z0-9]+)*)([.][a-z0-9]([a-z0-9-]*[a-z0-9]+)*)*$/; const message = i18nMark( "ID must be at least 1 character and may only contain digits (`0-9`), dashes (`-`), and lowercase letters (`a-z`). The ID may not begin or end with a dash" ); if (jobId == undefined) { return []; } // we're currently testing for a trailing "-" separately because the regex crashes // browsers for longer strings that end with a "-". return jobId && !jobId.endsWith("-") && jobIdRegex.test(jobId) ? [] : [{ path: ["id"], message }]; }, /** * Ensure that the user has provided either one of `cmd` or `args`, or a container image field. * Ensure that the user has not provided both `cmd` and `args`. */ containsCmdArgsOrContainer(job: JobOutput): FormError[] { const hasCmd = findNestedPropertyInObject(job, "run.cmd"); const hasArgs = findNestedPropertyInObject(job, "run.args") && (job.run.args as string[]).length; // Dont accept both `args` and `cmd` if (hasCmd && hasArgs) { const notBothMessage = i18nMark( "Please specify only one of `cmd` or `args`" ); return [ { path: ["run", "cmd"], message: notBothMessage, }, { path: ["run", "args"], message: notBothMessage, }, ]; } // Check if we have either of them if (hasCmd || hasArgs) { return []; } // Additional checks if we have container const docker = findNestedPropertyInObject(job, "run.docker"); const ucr = findNestedPropertyInObject(job, "run.ucr"); if (docker || ucr) { // Check if it specifies a docker container with image if (docker && docker.image) { return []; } // Check if it specifies a UCR container with image and image.id if (ucr && ucr.image && ucr.image.id) { return []; } } const message = i18nMark( "You must specify a command, an argument or a container with an image" ); const containerImageErrorPath = job.run.ucr ? ["run", "ucr", "image", "id"] : job.run.docker ? ["run", "docker", "image"] : []; return [ { path: ["run", "cmd"], message }, { path: ["run", "args"], message }, { path: containerImageErrorPath, message }, ]; }, /** * Ensure there is a container image if a container is specified */ mustContainImageOnDockerOrUCR(formData: JobOutput) { const docker = findNestedPropertyInObject(formData, "run.docker"); if (docker && !docker.image) { return [ { path: ["run", "docker", "image"], message: i18nMark( "Must be specified when using the Docker Engine runtime" ), }, ]; } const ucr = findNestedPropertyInObject(formData, "run.ucr"); if (ucr && (!ucr.image || !ucr.image.id)) { return [ { path: ["run", "ucr", "image", "id"], message: i18nMark("Must be specified when using UCR"), }, ]; } return []; }, /** * Ensure GPUs are used only with UCR */ gpusOnlyWithUCR(formData: JobOutput) { const gpus = findNestedPropertyInObject(formData, "run.gpus"); const docker = findNestedPropertyInObject(formData, "run.docker"); if ((gpus || gpus === 0) && docker) { return [ { path: ["run", "gpus"], message: i18nMark("GPUs are only available with UCR"), }, ]; } return []; }, oneOfUcrOrDocker(formData: JobOutput) { const docker = findNestedPropertyInObject(formData, "run.docker"); const ucr = findNestedPropertyInObject(formData, "run.ucr"); if (docker && ucr) { return [ { path: ["run", "docker"], message: i18nMark("Only one of UCR or Docker is allowed"), }, { path: ["run", "ucr"], message: i18nMark("Only one of UCR or Docker is allowed"), }, ]; } return []; }, checkTypesOfUcrProps(formData: JobOutput) { const ucr = findNestedPropertyInObject(formData, "run.ucr"); const errors: FormError[] = []; if (ucr == undefined) { return errors; } const kind = findNestedPropertyInObject(formData, "run.ucr.image.kind"); if ( kind != undefined && kind !== UcrImageKind.Docker && kind !== UcrImageKind.Appc ) { errors.push({ path: ["run", "ucr", "image", "kind"], message: i18nMark("Image kind must be one of `docker` or `appc`"), }); } return errors; }, valuesAreWithinRange(formData: JobOutput) { const cpus = findNestedPropertyInObject(formData, "run.cpus"); const mem = findNestedPropertyInObject(formData, "run.mem"); const disk = findNestedPropertyInObject(formData, "run.disk"); const errors: any[] = []; if (cpus != undefined && typeof cpus === "number" && cpus < 0.01) { errors.push({ path: ["run", "cpus"], message: i18nMark("Minimum value is 0.01"), }); } if (mem != undefined && typeof mem === "number" && mem < 32) { errors.push({ path: ["run", "mem"], message: i18nMark("Minimum value is 32"), }); } if (disk != undefined && typeof disk === "number" && disk < 0) { errors.push({ path: ["run", "disk"], message: i18nMark("Minimum value is 0"), }); } return errors; }, gpusWithinRange(formData: JobOutput) { const gpus = findNestedPropertyInObject(formData, "run.gpus"); if (gpus && typeof gpus === "number" && gpus < 0) { return [ { path: ["run", "gpus"], message: i18nMark("Minimum value is 0"), }, ]; } return []; }, noEmptyArgs(formData: JobOutput) { const args = formData.run.args; const errors: FormError[] = []; if (args && Array.isArray(args)) { args.forEach((arg, index) => { if (arg === "" || arg == undefined) { errors.push({ path: ["run", "args", `${index}`], message: i18nMark("Arg cannot be empty"), }); } }); } return errors; }, argsUsedOnlyWithDocker(formData: JobOutput) { const args = formData.run.args; const docker = formData.run.docker; if (args && !docker) { return [ { path: ["run", "args"], message: i18nMark("Args can only be used with Docker"), }, ]; } return []; }, noDuplicateArgs(formData: JobOutput) { const args = formData.run && formData.run.args; const errors: FormError[] = []; const map: { [key: string]: number } = {}; const dupIndex: number[] = []; if (args && Array.isArray(args)) { args.forEach((arg, index) => { if (!map.hasOwnProperty(arg)) { map[arg] = index; return; } if (dupIndex.length === 0) { dupIndex.push(map[arg]); } dupIndex.push(index); }); dupIndex.forEach((errorIndex) => { errors.push({ path: ["run", "args", `${errorIndex}`], message: i18nMark("No duplicate args"), }); }); } return errors; }, noDuplicateParams(formData: JobOutput) { const docker = formData.run && formData.run.docker; const errors: FormError[] = []; const map: { [key: string]: number } = {}; const dupIndex: number[] = []; if (docker && docker.parameters && Array.isArray(docker.parameters)) { docker.parameters.forEach((param, index) => { const paramId = `${param.key}-${param.value}`; if (!map.hasOwnProperty(paramId)) { map[paramId] = index; return; } if (dupIndex.length === 0) { dupIndex.push(map[paramId]); } dupIndex.push(index); }); dupIndex.forEach((errorIndex) => { errors.push({ path: ["run", "docker", "parameters", `${errorIndex}`], message: i18nMark("No duplicate parameters"), }); }); } return errors; }, scheduleHasId(formData: JobOutput) { const { schedules } = formData; if ( schedules && Array.isArray(schedules) && schedules.length && !schedules[0].id ) { return [ { path: ["schedules", "0", "id"], message: i18nMark("ID is required"), }, ]; } return []; }, scheduleHasCron(formData: JobOutput) { const { schedules } = formData; if ( schedules && Array.isArray(schedules) && schedules.length && !schedules[0].cron ) { return [ { path: ["schedules", "0", "cron"], message: i18nMark("CRON schedule is required"), }, ]; } return []; }, scheduleIdIsValid(formData: JobOutput) { const { schedules } = formData; const idRegex = /^([a-z0-9][a-z0-9\\-]*[a-z0-9]+)$/; const message = i18nMark( "ID must be at least 2 characters and may only contain digits (`0-9`), dashes (`-`), and lowercase letters (`a-z`). The ID may not begin or end with a dash" ); if (!schedules || !Array.isArray(schedules) || !schedules.length) { return []; } const schedule = schedules[0]; if (schedule.id && typeof schedule.id !== "string") { return [ { path: ["schedules", "0", "id"], message: i18nMark("Schedule ID must be a string"), }, ]; } return schedule && schedule.id && idRegex.test(schedule.id) ? [] : [{ path: ["schedules", "0", "id"], message }]; }, scheduleStartingDeadlineIsValid(formData: JobOutput) { const { schedules } = formData; const errors: any[] = []; if ( schedules && Array.isArray(schedules) && schedules.length && schedules[0].startingDeadlineSeconds != undefined ) { if (typeof schedules[0].startingDeadlineSeconds !== "number") { errors.push({ path: ["schedules", "0", "startingDeadlineSeconds"], message: i18nMark("Starting deadline must be a number"), }); } if (schedules[0].startingDeadlineSeconds < 1) { errors.push({ path: ["schedules", "0", "startingDeadlineSeconds"], message: i18nMark("Minimum value is 1"), }); } } return errors; }, constraintsAreArray(formData: JobOutput): FormError[] { const path = "run.placement.constraints"; return isArray((_) => path, [ findNestedPropertyInObject(formData, `job.${path}`), ])([]); }, }; function volumesAreComplete(formData: JobSpec) { const volumes = findNestedPropertyInObject(formData, "job.run.volumes"); const errors: FormError[] = []; if (volumes && Array.isArray(volumes)) { volumes.forEach((volume, index) => { if ( (volume.containerPath == null || volume.containerPath === "") && (volume.hostPath == null || volume.hostPath === "") && (volume.mode == null || volume.mode === "") ) { return; } if (volume.containerPath == null || volume.containerPath === "") { errors.push({ path: ["run", "volumes", `${index}`, "containerPath"], message: i18nMark("Container path is required"), }); } if (!volume.hasOwnProperty("secret")) { if (volume.hostPath == null || volume.hostPath === "") { errors.push({ path: ["run", "volumes", `${index}`, "hostPath"], message: i18nMark("Host path is required"), }); } if (volume.mode == null || volume.mode === "") { errors.push({ path: ["run", "volumes", `${index}`, "mode"], message: i18nMark("Mode is required"), }); } } }); } return errors; } function checkVolumePropertyTypes(formData: JobSpec) { const volumes = findNestedPropertyInObject(formData, "job.run.volumes"); const errors: FormError[] = []; if (volumes && Array.isArray(volumes)) { volumes.forEach((volume, index) => { if ( (volume.containerPath == null || volume.containerPath === "") && (volume.hostPath == null || volume.hostPath === "") && (volume.mode == null || volume.mode === "") ) { return; } if (typeof volume.containerPath !== "string") { errors.push({ path: ["run", "volumes", `${index}`, "containerPath"], message: stringMsg, }); } if (!volume.hasOwnProperty("secret")) { if (typeof volume.hostPath !== "string") { errors.push({ path: ["run", "volumes", `${index}`, "hostPath"], message: stringMsg, }); } if (typeof volume.mode !== "string") { errors.push({ path: ["run", "volumes", `${index}`, "mode"], message: stringMsg, }); } else if (volume.mode !== "RO" && volume.mode !== "RW") { errors.push({ path: ["run", "volumes", `${index}`, "mode"], message: i18nMark("Mode must be one of: RO, RW"), }); } } }); } return errors; } export function constraintOperatorsArePermitted(formData: JobSpec) { const path = "job.run.placement.constraints"; const operators = (findNestedPropertyInObject(formData, path) || []).map( (_: any) => _.operator ); return validation( (op) => Object.values(ConstraintOperator).includes(op) || op === "EQ", i18nMark("Operator must be one of: IS, LIKE, UNLIKE, EQ") )( (i) => `${path}.${i}.operator`, operators )([]); } export function constraintsAreComplete(formData: JobSpec) { const placement = findNestedPropertyInObject(formData, "job.run.placement"); const errors: FormError[] = []; if ( placement && placement.constraints && Array.isArray(placement.constraints) ) { placement.constraints.forEach((constraint: any, i: number) => { const { operator, attribute, value } = constraint; if (!(attribute || operator || value)) { return; } if (operator == null || operator === "" || isOnlyWhitespace(operator)) { errors.push({ path: ["run", "placement", "constraints", `${i}`, "operator"], message: i18nMark("Operator is required"), }); } if ( attribute == null || attribute === "" || isOnlyWhitespace(attribute) ) { errors.push({ path: ["run", "placement", "constraints", `${i}`, "attribute"], message: i18nMark("Field is required"), }); } if ( ((OperatorTypes as any)[operator] || {}).requiresValue && (value == null || value === "" || isOnlyWhitespace(value)) ) { errors.push({ path: ["run", "placement", "constraints", `${i}`, "value"], message: i18nMark("Value is required"), }); } }); } return errors; } // We sometimes need to validate the spec instead of the formOutput to make sure // that e.g. two ENV-params don't have the same key. we need to allow for // that UX-wise, as if you have `DB_HOST` and type `DB_HOSTNAME` in the next // field you'd run into trouble when using a POJO as the backing model. export function validateSpec(jobSpec: JobSpec): FormError[] { const run = jobSpec.job.run || {}; const envsMsg = i18nMark( "Cannot have multiple environment variables with the same key" ); const labels = (jobSpec.job.labels || []).map(([k]) => k); const labelsMsg = i18nMark("Cannot have multiple labels with the same key"); const envVarsErrors: FormError[] = []; const map: { [key: string]: number[] } = {}; (run.env || []).forEach(([k, v], i) => { if (k) { if (map[k] != null) { map[k].push(i); } else { map[k] = [i]; } } if (v && !isObjectUtil(v)) { if (k == null || k === "") { envVarsErrors.push({ path: ["run", "env", `${i}`], message: presentMsg, }); } if (typeof v !== "string") { envVarsErrors.push({ path: ["run", "env", k, "value", `${i}`], message: stringMsg, }); } } if (k && (v == null || v === "")) { envVarsErrors.push({ path: ["run", "env", k, "value", `${i}`], message: presentMsg, }); } }); Object.keys(map).forEach((envVarKey) => { if (map[envVarKey].length > 1) { map[envVarKey].forEach((index) => { envVarsErrors.push({ path: ["run", "env", `${index}`], message: envsMsg, }); }); } }); const constraintErrors = constraintsAreComplete(jobSpec).concat( constraintOperatorsArePermitted(jobSpec) ); const volumesErrors = volumesAreComplete(jobSpec).concat( checkVolumePropertyTypes(jobSpec) ); return pipe( allUniq((_) => "labels", [labels], labelsMsg), isUniqIn(labels)((i) => `labels.${i}`, labels, labelsMsg) )([]) .concat(envVarsErrors) .concat(volumesErrors) .concat(constraintErrors); }
{ "pile_set_name": "Github" }
function *foo () { yield 5 } (function *() { console.log(foo().next().value) })().next(); (function *() { })(); (function * () { yield yield 3 })();
{ "pile_set_name": "Github" }
#if !defined(BOOST_PROTO_DONT_USE_PREPROCESSED_FILES) #include <boost/proto/transform/detail/preprocessed/when.hpp> #elif !defined(BOOST_PP_IS_ITERATING) #if defined(__WAVE__) && defined(BOOST_PROTO_CREATE_PREPROCESSED_FILES) #pragma wave option(preserve: 2, line: 0, output: "preprocessed/when.hpp") #endif /////////////////////////////////////////////////////////////////////////////// /// \file when.hpp /// Definition of when transform. // // Copyright 2008 Eric Niebler. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #if defined(__WAVE__) && defined(BOOST_PROTO_CREATE_PREPROCESSED_FILES) #pragma wave option(preserve: 1) #endif #define BOOST_PP_ITERATION_PARAMS_1 \ (3, (0, BOOST_PROTO_MAX_ARITY, <boost/proto/transform/detail/when.hpp>)) #include BOOST_PP_ITERATE() #if defined(__WAVE__) && defined(BOOST_PROTO_CREATE_PREPROCESSED_FILES) #pragma wave option(output: null) #endif #else #define N BOOST_PP_ITERATION() /// \brief A grammar element and a PrimitiveTransform that associates /// a transform with the grammar. /// /// Use <tt>when\<\></tt> to override a grammar's default transform /// with a custom transform. It is for used when composing larger /// transforms by associating smaller transforms with individual /// rules in your grammar, as in the following transform which /// counts the number of terminals in an expression. /// /// \code /// // Count the terminals in an expression tree. /// // Must be invoked with initial state == mpl::int_<0>(). /// struct CountLeaves /// : or_< /// when<terminal<_>, mpl::next<_state>()> /// , otherwise<fold<_, _state, CountLeaves> > /// > /// {}; /// \endcode /// /// The <tt>when\<G, R(A0,A1,...)\></tt> form accepts either a /// CallableTransform or an ObjectTransform as its second parameter. /// <tt>when\<\></tt> uses <tt>is_callable\<R\>::value</tt> to /// distinguish between the two, and uses <tt>call\<\></tt> to /// evaluate CallableTransforms and <tt>make\<\></tt> to evaluate /// ObjectTransforms. template<typename Grammar, typename R BOOST_PP_ENUM_TRAILING_PARAMS(N, typename A)> struct when<Grammar, R(BOOST_PP_ENUM_PARAMS(N, A))> : detail::when_impl<Grammar, R, R(BOOST_PP_ENUM_PARAMS(N, A))> {}; #if N > 0 /// \brief A grammar element and a PrimitiveTransform that associates /// a transform with the grammar. /// /// Use <tt>when\<\></tt> to override a grammar's default transform /// with a custom transform. It is for used when composing larger /// transforms by associating smaller transforms with individual /// rules in your grammar, as in the following transform which /// counts the number of terminals in an expression. /// /// \code /// // Count the terminals in an expression tree. /// // Must be invoked with initial state == mpl::int_<0>(). /// struct CountLeaves /// : or_< /// when<terminal<_>, mpl::next<_state>()> /// , otherwise<fold<_, _state, CountLeaves> > /// > /// {}; /// \endcode /// /// The <tt>when\<G, R(A0,A1,...)\></tt> form accepts either a /// CallableTransform or an ObjectTransform as its second parameter. /// <tt>when\<\></tt> uses <tt>is_callable\<R\>::value</tt> to /// distinguish between the two, and uses <tt>call\<\></tt> to /// evaluate CallableTransforms and <tt>make\<\></tt> to evaluate /// ObjectTransforms. template<typename Grammar, typename R BOOST_PP_ENUM_TRAILING_PARAMS(N, typename A)> struct when<Grammar, R(BOOST_PP_ENUM_PARAMS(N, A)...)> : detail::when_impl<Grammar, R, R(BOOST_PP_ENUM_PARAMS(N, A)...)> {}; #endif #undef N #endif
{ "pile_set_name": "Github" }
/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #ifndef UV_WIN_HANDLE_INL_H_ #define UV_WIN_HANDLE_INL_H_ #include <assert.h> #include <io.h> #include "uv.h" #include "internal.h" #define DECREASE_ACTIVE_COUNT(loop, handle) \ do { \ if (--(handle)->activecnt == 0 && \ !((handle)->flags & UV_HANDLE_CLOSING)) { \ uv__handle_stop((handle)); \ } \ assert((handle)->activecnt >= 0); \ } while (0) #define INCREASE_ACTIVE_COUNT(loop, handle) \ do { \ if ((handle)->activecnt++ == 0) { \ uv__handle_start((handle)); \ } \ assert((handle)->activecnt > 0); \ } while (0) #define DECREASE_PENDING_REQ_COUNT(handle) \ do { \ assert(handle->reqs_pending > 0); \ handle->reqs_pending--; \ \ if (handle->flags & UV_HANDLE_CLOSING && \ handle->reqs_pending == 0) { \ uv_want_endgame(loop, (uv_handle_t*)handle); \ } \ } while (0) #define uv__handle_closing(handle) \ do { \ assert(!((handle)->flags & UV_HANDLE_CLOSING)); \ \ if (!(((handle)->flags & UV_HANDLE_ACTIVE) && \ ((handle)->flags & UV_HANDLE_REF))) \ uv__active_handle_add((uv_handle_t*) (handle)); \ \ (handle)->flags |= UV_HANDLE_CLOSING; \ (handle)->flags &= ~UV_HANDLE_ACTIVE; \ } while (0) #define uv__handle_close(handle) \ do { \ QUEUE_REMOVE(&(handle)->handle_queue); \ uv__active_handle_rm((uv_handle_t*) (handle)); \ \ (handle)->flags |= UV_HANDLE_CLOSED; \ \ if ((handle)->close_cb) \ (handle)->close_cb((uv_handle_t*) (handle)); \ } while (0) INLINE static void uv_want_endgame(uv_loop_t* loop, uv_handle_t* handle) { if (!(handle->flags & UV_HANDLE_ENDGAME_QUEUED)) { handle->flags |= UV_HANDLE_ENDGAME_QUEUED; handle->endgame_next = loop->endgame_handles; loop->endgame_handles = handle; } } INLINE static void uv_process_endgames(uv_loop_t* loop) { uv_handle_t* handle; while (loop->endgame_handles) { handle = loop->endgame_handles; loop->endgame_handles = handle->endgame_next; handle->flags &= ~UV_HANDLE_ENDGAME_QUEUED; switch (handle->type) { case UV_TCP: uv_tcp_endgame(loop, (uv_tcp_t*) handle); break; case UV_NAMED_PIPE: uv_pipe_endgame(loop, (uv_pipe_t*) handle); break; case UV_TTY: uv_tty_endgame(loop, (uv_tty_t*) handle); break; case UV_UDP: uv_udp_endgame(loop, (uv_udp_t*) handle); break; case UV_POLL: uv_poll_endgame(loop, (uv_poll_t*) handle); break; case UV_TIMER: uv__timer_close((uv_timer_t*) handle); uv__handle_close(handle); break; case UV_PREPARE: case UV_CHECK: case UV_IDLE: uv_loop_watcher_endgame(loop, handle); break; case UV_ASYNC: uv_async_endgame(loop, (uv_async_t*) handle); break; case UV_SIGNAL: uv_signal_endgame(loop, (uv_signal_t*) handle); break; case UV_PROCESS: uv_process_endgame(loop, (uv_process_t*) handle); break; case UV_FS_EVENT: uv_fs_event_endgame(loop, (uv_fs_event_t*) handle); break; case UV_FS_POLL: uv__fs_poll_endgame(loop, (uv_fs_poll_t*) handle); break; default: assert(0); break; } } } INLINE static HANDLE uv__get_osfhandle(int fd) { /* _get_osfhandle() raises an assert in debug builds if the FD is invalid. * But it also correctly checks the FD and returns INVALID_HANDLE_VALUE for * invalid FDs in release builds (or if you let the assert continue). So this * wrapper function disables asserts when calling _get_osfhandle. */ HANDLE handle; UV_BEGIN_DISABLE_CRT_ASSERT(); handle = (HANDLE) _get_osfhandle(fd); UV_END_DISABLE_CRT_ASSERT(); return handle; } #endif /* UV_WIN_HANDLE_INL_H_ */
{ "pile_set_name": "Github" }
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1997 - 2009, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * * $Id: splay.c,v 1.13 2009-06-10 02:49:43 yangtse Exp $ ***************************************************************************/ #include "setup.h" #include "splay.h" /* * This macro compares two node keys i and j and returns: * * negative value: when i is smaller than j * zero : when i is equal to j * positive when : when i is larger than j */ #define compare(i,j) Curl_splaycomparekeys((i),(j)) /* * Splay using the key i (which may or may not be in the tree.) The starting * root is t. */ struct Curl_tree *Curl_splay(struct timeval i, struct Curl_tree *t) { struct Curl_tree N, *l, *r, *y; long comp; if(t == NULL) return t; N.smaller = N.larger = NULL; l = r = &N; for (;;) { comp = compare(i, t->key); if(comp < 0) { if(t->smaller == NULL) break; if(compare(i, t->smaller->key) < 0) { y = t->smaller; /* rotate smaller */ t->smaller = y->larger; y->larger = t; t = y; if(t->smaller == NULL) break; } r->smaller = t; /* link smaller */ r = t; t = t->smaller; } else if(comp > 0) { if(t->larger == NULL) break; if(compare(i, t->larger->key) > 0) { y = t->larger; /* rotate larger */ t->larger = y->smaller; y->smaller = t; t = y; if(t->larger == NULL) break; } l->larger = t; /* link larger */ l = t; t = t->larger; } else break; } l->larger = t->smaller; /* assemble */ r->smaller = t->larger; t->smaller = N.larger; t->larger = N.smaller; return t; } /* Insert key i into the tree t. Return a pointer to the resulting tree or NULL if something went wrong. */ struct Curl_tree *Curl_splayinsert(struct timeval i, struct Curl_tree *t, struct Curl_tree *node) { static struct timeval KEY_NOTUSED = {-1,-1}; /* key that will *NEVER* appear */ if(node == NULL) return t; if(t != NULL) { t = Curl_splay(i,t); if(compare(i, t->key)==0) { /* There already exists a node in the tree with the very same key. Build a linked list of nodes. We make the new 'node' struct the new master node and make the previous node the first one in the 'same' list. */ node->same = t; node->key = i; node->smaller = t->smaller; node->larger = t->larger; t->smaller = node; /* in the sub node for this same key, we use the smaller pointer to point back to the master node */ t->key = KEY_NOTUSED; /* and we set the key in the sub node to NOTUSED to quickly identify this node as a subnode */ return node; /* new root node */ } } if(t == NULL) { node->smaller = node->larger = NULL; } else if(compare(i, t->key) < 0) { node->smaller = t->smaller; node->larger = t; t->smaller = NULL; } else { node->larger = t->larger; node->smaller = t; t->larger = NULL; } node->key = i; node->same = NULL; /* no identical node (yet) */ return node; } #if 0 /* Deletes 'i' from the tree if it's there (with an exact match). Returns a pointer to the resulting tree. Function not used in libcurl. */ struct Curl_tree *Curl_splayremove(struct timeval i, struct Curl_tree *t, struct Curl_tree **removed) { struct Curl_tree *x; *removed = NULL; /* default to no removed */ if(t==NULL) return NULL; t = Curl_splay(i,t); if(compare(i, t->key) == 0) { /* found it */ /* FIRST! Check if there is a list with identical sizes */ if((x = t->same) != NULL) { /* there is, pick one from the list */ /* 'x' is the new root node */ x->key = t->key; x->larger = t->larger; x->smaller = t->smaller; *removed = t; return x; /* new root */ } if(t->smaller == NULL) { x = t->larger; } else { x = Curl_splay(i, t->smaller); x->larger = t->larger; } *removed = t; return x; } else return t; /* It wasn't there */ } #endif /* Finds and deletes the best-fit node from the tree. Return a pointer to the resulting tree. best-fit means the node with the given or lower key */ struct Curl_tree *Curl_splaygetbest(struct timeval i, struct Curl_tree *t, struct Curl_tree **removed) { struct Curl_tree *x; if(!t) { *removed = NULL; /* none removed since there was no root */ return NULL; } t = Curl_splay(i,t); if(compare(i, t->key) < 0) { /* too big node, try the smaller chain */ if(t->smaller) t=Curl_splay(t->smaller->key, t); else { /* fail */ *removed = NULL; return t; } } if(compare(i, t->key) >= 0) { /* found it */ /* FIRST! Check if there is a list with identical keys */ x = t->same; if(x) { /* there is, pick one from the list */ /* 'x' is the new root node */ x->key = t->key; x->larger = t->larger; x->smaller = t->smaller; *removed = t; return x; /* new root */ } if(t->smaller == NULL) { x = t->larger; } else { x = Curl_splay(i, t->smaller); x->larger = t->larger; } *removed = t; return x; } else { *removed = NULL; /* no match */ return t; /* It wasn't there */ } } /* Deletes the very node we point out from the tree if it's there. Stores a pointer to the new resulting tree in 'newroot'. Returns zero on success and non-zero on errors! TODO: document error codes. When returning error, it does not touch the 'newroot' pointer. NOTE: when the last node of the tree is removed, there's no tree left so 'newroot' will be made to point to NULL. */ int Curl_splayremovebyaddr(struct Curl_tree *t, struct Curl_tree *removenode, struct Curl_tree **newroot) { static struct timeval KEY_NOTUSED = {-1,-1}; /* key that will *NEVER* appear */ struct Curl_tree *x; if(!t || !removenode) return 1; if(compare(KEY_NOTUSED, removenode->key) == 0) { /* Key set to NOTUSED means it is a subnode within a 'same' linked list and thus we can unlink it easily. The 'smaller' link of a subnode links to the parent node. */ if(removenode->smaller == NULL) return 3; removenode->smaller->same = removenode->same; if(removenode->same) removenode->same->smaller = removenode->smaller; /* Ensures that double-remove gets caught. */ removenode->smaller = NULL; /* voila, we're done! */ *newroot = t; /* return the same root */ return 0; } t = Curl_splay(removenode->key, t); /* First make sure that we got the same root node as the one we want to remove, as otherwise we might be trying to remove a node that isn't actually in the tree. We cannot just compare the keys here as a double remove in quick succession of a node with key != KEY_NOTUSED && same != NULL could return the same key but a different node. */ if(t != removenode) return 2; /* Check if there is a list with identical sizes, as then we're trying to remove the root node of a list of nodes with identical keys. */ x = t->same; if(x) { /* 'x' is the new root node, we just make it use the root node's smaller/larger links */ x->key = t->key; x->larger = t->larger; x->smaller = t->smaller; } else { /* Remove the root node */ if(t->smaller == NULL) x = t->larger; else { x = Curl_splay(removenode->key, t->smaller); x->larger = t->larger; } } *newroot = x; /* store new root pointer */ return 0; } #ifdef DEBUGBUILD void Curl_splayprint(struct Curl_tree * t, int d, char output) { struct Curl_tree *node; int i; int count; if(t == NULL) return; Curl_splayprint(t->larger, d+1, output); for (i=0; i<d; i++) if(output) fprintf(stderr, " "); if(output) { #ifdef TEST_SPLAY fprintf(stderr, "%ld[%d]", (long)t->key.tv_usec, i); #else fprintf(stderr, "%ld.%ld[%d]", (long)t->key.tv_sec, (long)t->key.tv_usec, i); #endif } for(count=0, node = t->same; node; node = node->same, count++) ; if(output) { if(count) fprintf(stderr, " [%d more]\n", count); else fprintf(stderr, "\n"); } Curl_splayprint(t->smaller, d+1, output); } #endif #ifdef TEST_SPLAY /*#define TEST2 */ #define MAX 50 #define TEST2 /* A sample use of these functions. Start with the empty tree, insert some stuff into it, and then delete it */ int main(int argc, argv_item_t argv[]) { struct Curl_tree *root, *t; void *ptrs[MAX]; int adds=0; int rc; static const long sizes[]={ 50, 60, 50, 100, 60, 200, 120, 300, 400, 200, 256, 122, 60, 120, 200, 300, 220, 80, 90, 50, 100, 60, 200, 120, 300, 400, 200, 256, 122, 60, 120, 200, 300, 220, 80, 90, 50, 100, 60, 200, 120, 300, 400, 200, 256, 122, 60, 120, 200, 300, 220, 80, 90}; int i; root = NULL; /* the empty tree */ for (i = 0; i < MAX; i++) { struct timeval key; ptrs[i] = t = malloc(sizeof(struct Curl_tree)); key.tv_sec = 0; #ifdef TEST2 key.tv_usec = sizes[i]; #elif defined(TEST1) key.tv_usec = (541*i)%1023; #elif defined(TEST3) key.tv_usec = 100; #endif t->payload = (void *)key.tv_usec; /* for simplicity */ if(!t) { puts("out of memory!"); return 0; } root = Curl_splayinsert(key, root, t); } #if 0 puts("Result:"); Curl_splayprint(root, 0, 1); #endif #if 1 for (i = 0; i < MAX; i++) { int rem = (i+7)%MAX; struct Curl_tree *r; printf("Tree look:\n"); Curl_splayprint(root, 0, 1); printf("remove pointer %d, payload %ld\n", rem, (long)((struct Curl_tree *)ptrs[rem])->payload); rc = Curl_splayremovebyaddr(root, (struct Curl_tree *)ptrs[rem], &root); if(rc) /* failed! */ printf("remove %d failed!\n", rem); } #endif return 0; } #endif /* TEST_SPLAY */
{ "pile_set_name": "Github" }
; RTL - A Formal Theory of Register-Transfer Logic and Computer Arithmetic ; Copyright (C) 1995-2013 Advanced Mirco Devices, Inc. ; ; Contact: ; David Russinoff ; 1106 W 9th St., Austin, TX 78703 ; http://www.russsinoff.com/ ; ; See license file books/rtl/rel9/license.txt. ; ; Author: David M. Russinoff (david@russinoff.com) (in-package "ACL2") (set-enforce-redundancy t) (local (include-book "../support/top/top")) (set-inhibit-warnings "theory") ; avoid warning in the next event (local (in-theory nil)) ;;;********************************************************************** ;;; FLOOR and CEILING ;;;********************************************************************** (defund fl (x) (declare (xargs :guard (real/rationalp x))) (floor x 1)) (defthm fl-def (and (integerp (fl x)) (implies (case-split (rationalp x)) (and (<= (fl x) x) (< x (1+ (fl x)))))) :rule-classes ((:linear :corollary (implies (case-split (rationalp x)) (and (<= (fl x) x) (< x (1+ (fl x)))))) (:type-prescription :corollary (integerp (fl x))))) (defthm fl-unique (implies (and (rationalp x) (integerp n) (<= n x) (< x (1+ n))) (equal (fl x) n)) :rule-classes ()) (defthm fl-integerp (equal (equal (fl x) x) (integerp x))) (defthm quot-bnd (implies (and (<= 0 x) (<= 0 y) (rationalp x) (rationalp y)) (<= (* y (fl (/ x y))) x)) :rule-classes :linear) (defthm fl-monotone-linear (implies (and (<= x y) (rationalp x) (rationalp y)) (<= (fl x) (fl y))) :rule-classes :linear) (defthm n<=fl-linear (implies (and (<= n x) (rationalp x) (integerp n)) (<= n (fl x))) :rule-classes :linear) (defthm fl+int-rewrite (implies (and (integerp n) (rationalp x)) (equal (fl (+ x n)) (+ (fl x) n)))) (defthm fl/int-rewrite (implies (and (integerp n) (<= 0 n) (rationalp x)) (equal (fl (* (fl x) (/ n))) (fl (/ x n))))) (defthm fl/int-rewrite-alt (implies (and (integerp n) (<= 0 n) (rationalp x)) (equal (fl (* (/ n) (fl x))) (fl (/ x n))))) (defthmd fl-minus (implies (rationalp x) (equal (fl (* -1 x)) (if (integerp x) (* -1 x) (1- (* -1 (fl x))))))) (defthm fl-m-n (implies (and (< 0 n) (integerp m) (integerp n)) (= (fl (- (/ m n))) (1- (- (fl (/ (1- m) n)))))) :rule-classes ()) (defund cg (x) (declare (xargs :guard (real/rationalp x))) (- (fl (- x)))) (defthm cg-def (and (integerp (cg x)) (implies (case-split (rationalp x)) (and (>= (cg x) x) (> (1+ x) (cg x))))) :rule-classes ((:linear :corollary (implies (case-split (rationalp x)) (and (>= (cg x) x) (> (1+ x) (cg x))))) (:type-prescription :corollary (integerp (cg x))))) (defthm cg-unique (implies (and (rationalp x) (integerp n) (>= n x) (> (1+ x) n)) (equal (cg x) n)) :rule-classes ()) (defthm cg-integerp (implies (rationalp x) (equal (equal (cg x) x) (integerp x)))) (defthm cg-monotone-linear (implies (and (rationalp x) (rationalp y) (<= x y)) (<= (cg x) (cg y))) :rule-classes :linear) (defthm n>=cg-linear (implies (and (>= n x) (rationalp x) (integerp n)) (>= n (cg x))) :rule-classes :linear) (defthm cg+int-rewrite (implies (and (integerp n) (rationalp x)) (equal (cg (+ x n)) (+ (cg x) n)))) (defthm cg/int-rewrite (implies (and (integerp n) (> n 0) (rationalp x)) (equal (cg (* (cg x) (/ n))) (cg (/ x n))))) (defthm cg/int-rewrite-alt (implies (and (integerp n) (> n 0) (rationalp x)) (equal (cg (* (/ n) (cg x))) (cg (/ x n))))) (defthm fl-cg (implies (rationalp x) (equal (cg x) (if (integerp x) (fl x) (1+ (fl x))))) :rule-classes ()) ;;;********************************************************************** ;;; MOD ;;;********************************************************************** (in-theory (disable mod)) (defthm mod-def (implies (case-split (acl2-numberp x)) (equal (mod x y) (- x (* y (fl (/ x y)))))) :rule-classes ()) (defthm mod-0 (and (equal (mod 0 y) 0) (equal (mod x 0) (fix x)))) (defthm rationalp-mod (implies (rationalp x) (rationalp (mod x y))) :rule-classes (:rewrite :type-prescription)) (defthm integerp-mod (implies (and (integerp m) (integerp n)) (integerp (mod m n))) :rule-classes (:rewrite :type-prescription)) (defthm natp-mod (implies (and (natp m) (natp n)) (natp (mod m n))) :rule-classes ((:type-prescription :typed-term (mod m n)))) (defthm natp-mod-2 (implies (and (integerp m) (integerp n) (> n 0)) (natp (mod m n))) :rule-classes ((:type-prescription :typed-term (mod m n)))) (defthm mod-bnd-1 (implies (and (case-split (< 0 n)) (case-split (not (complex-rationalp m))) (case-split (not (complex-rationalp n)))) (< (mod m n) n)) :rule-classes :linear) (defthm mod-by-1 (implies (integerp m) (equal (mod m 1) 0))) (defthm mod-bnd-2 (implies (and (<= 0 m) (case-split (rationalp m))) (<= (mod m n) m)) :rule-classes :linear) (defthm mod-does-nothing (implies (and (< m n) (<= 0 m) (case-split (rationalp m))) (equal (mod m n) m))) (defthm mod-0-fl (implies (acl2-numberp m) (iff (= (mod m n) 0) (= m (* (fl (/ m n)) n)))) :rule-classes ()) (defthm mod-0-int (implies (and (integerp m) (integerp n) (not (= n 0))) (iff (= (mod m n) 0) (integerp (/ m n)))) :rule-classes ()) (defthm mod-mult-n (equal (mod (* a n) n) (* n (mod a 1)))) (defthm mod-mult-n-alt (equal (mod (* n a) n) (* n (mod a 1)))) (defthm mod-squeeze (implies (and (= (mod m n) 0) (< m (* (1+ a) n)) (< (* (1- a) n) m) (integerp a) (integerp m) (integerp n)) (= m (* a n))) :rule-classes ()) (defthm mod-must-be-n (implies (and (= (mod m n) 0) (< m (* 2 n)) (< 0 m) (rationalp m) (rationalp n)) (= m n)) :rule-classes ()) (defthm mod-0-0 (implies (and (integerp p) (rationalp m) (rationalp n)) (iff (= (mod m (* n p)) 0) (and (= (mod m n) 0) (= (mod (fl (/ m n)) p) 0)))) :rule-classes ()) (defthm mod-equal-int (implies (and (= (mod a n) (mod b n)) (rationalp a) (rationalp b)) (integerp (/ (- a b) n))) :rule-classes ()) (defthm mod-equal-int-reverse (implies (and (integerp (/ (- a b) n)) (rationalp a) (rationalp b) (rationalp n) (< 0 n)) (= (mod a n) (mod b n))) :rule-classes ()) (defthm mod-force-equal (implies (and (< (abs (- a b)) n) (rationalp a) (rationalp b) (integerp n)) (iff (= (mod a n) (mod b n)) (= a b))) :rule-classes ()) (defthmd mod-mult (implies (and (integerp a) (rationalp m) (rationalp n)) (equal (mod (+ m (* a n)) n) (mod m n)))) (defthm mod-force (implies (and (<= (* a n) m) (< m (* (1+ a) n)) (integerp a) (rationalp m) (rationalp n)) (= (mod m n) (- m (* a n)))) :rule-classes ()) (defthm mod-bnd-3 (implies (and (< m (+ (* a n) r)) (<= (* a n) m) (integerp a) (case-split (rationalp m)) (case-split (rationalp n))) (< (mod m n) r)) :rule-classes :linear) (defthmd mod-sum (implies (and (rationalp a) (rationalp b)) (equal (mod (+ a (mod b n)) n) (mod (+ a b) n)))) (defthmd mod-mod-sum (implies (and (rationalp a) (rationalp b)) (equal (mod (+ (mod a n) (mod b n)) n) (mod (+ a b) n)))) (defthmd mod-diff (implies (and (case-split (rationalp a)) (case-split (rationalp b))) (equal (mod (- a (mod b n)) n) (mod (- a b) n)))) (defthmd mod-of-mod (implies (and (case-split (natp k)) (case-split (natp n))) (equal (mod (mod x (* k n)) n) (mod x n)))) (defthmd mod-of-mod-cor (implies (and (<= b a) (case-split (integerp b)) (case-split (integerp a))) (equal (mod (mod x (expt 2 a)) (expt 2 b)) (mod x (expt 2 b))))) (defthmd mod-prod (implies (and (rationalp m) (rationalp n) (rationalp k)) (equal (mod (* k m) (* k n)) (* k (mod m n))))) (defthm mod012 (implies (integerp m) (or (equal (mod m 2) 0) (equal (mod m 2) 1))) :rule-classes ()) (defthm mod-plus-mod-2 (implies (and (integerp a) (integerp b)) (iff (= (mod (+ a b) 2) (mod a 2)) (= (mod b 2) 0))) :rule-classes ()) (defthm mod-mod-2-not-equal (implies (acl2-numberp m) (not (= (mod m 2) (mod (1+ m) 2)))) :rule-classes ()) (defthm mod-2*m+1-rewrite (implies (integerp m) (equal (mod (1+ (* 2 m)) 2) 1))) (defthm mod-mod-times (implies (and (integerp a) (integerp b) (integerp n) (> n 0)) (= (mod (* (mod a n) b) n) (mod (* a b) n))) :rule-classes ()) (defthm mod-times-mod (implies (and (integerp a) (integerp b) (integerp c) (not (zp n)) (= (mod a n) (mod b n))) (= (mod (* a c) n) (mod (* b c) n))) :rule-classes ()) (defthm mod-plus-mod (implies (and (integerp a) (integerp b) (integerp c) (not (zp n)) (= (mod a n) (mod b n))) (= (mod (+ a c) n) (mod (+ b c) n))) :rule-classes ())
{ "pile_set_name": "Github" }
/* * ucontext coroutine initialization code * * Copyright (C) 2006 Anthony Liguori <anthony@codemonkey.ws> * Copyright (C) 2011 Kevin Wolf <kwolf@redhat.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.0 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, see <http://www.gnu.org/licenses/>. */ /* XXX Is there a nicer way to disable glibc's stack check for longjmp? */ #ifdef _FORTIFY_SOURCE #undef _FORTIFY_SOURCE #endif #include "qemu/osdep.h" #include <ucontext.h> #include "qemu-common.h" #include "qemu/coroutine_int.h" #ifdef CONFIG_VALGRIND_H #include <valgrind/valgrind.h> #endif #if defined(__SANITIZE_ADDRESS__) || __has_feature(address_sanitizer) #ifdef CONFIG_ASAN_IFACE_FIBER #define CONFIG_ASAN 1 #include <sanitizer/asan_interface.h> #endif #endif typedef struct { Coroutine base; void *stack; size_t stack_size; sigjmp_buf env; #ifdef CONFIG_VALGRIND_H unsigned int valgrind_stack_id; #endif } CoroutineUContext; /** * Per-thread coroutine bookkeeping */ static __thread CoroutineUContext leader; static __thread Coroutine *current; /* * va_args to makecontext() must be type 'int', so passing * the pointer we need may require several int args. This * union is a quick hack to let us do that */ union cc_arg { void *p; int i[2]; }; static void finish_switch_fiber(void *fake_stack_save) { #ifdef CONFIG_ASAN const void *bottom_old; size_t size_old; __sanitizer_finish_switch_fiber(fake_stack_save, &bottom_old, &size_old); if (!leader.stack) { leader.stack = (void *)bottom_old; leader.stack_size = size_old; } #endif } static void start_switch_fiber(void **fake_stack_save, const void *bottom, size_t size) { #ifdef CONFIG_ASAN __sanitizer_start_switch_fiber(fake_stack_save, bottom, size); #endif } static void coroutine_trampoline(int i0, int i1) { union cc_arg arg; CoroutineUContext *self; Coroutine *co; void *fake_stack_save = NULL; finish_switch_fiber(NULL); arg.i[0] = i0; arg.i[1] = i1; self = arg.p; co = &self->base; /* Initialize longjmp environment and switch back the caller */ if (!sigsetjmp(self->env, 0)) { start_switch_fiber(&fake_stack_save, leader.stack, leader.stack_size); siglongjmp(*(sigjmp_buf *)co->entry_arg, 1); } finish_switch_fiber(fake_stack_save); while (true) { co->entry(co->entry_arg); qemu_coroutine_switch(co, co->caller, COROUTINE_TERMINATE); } } Coroutine *qemu_coroutine_new(void) { CoroutineUContext *co; ucontext_t old_uc, uc; sigjmp_buf old_env; union cc_arg arg = {0}; void *fake_stack_save = NULL; /* The ucontext functions preserve signal masks which incurs a * system call overhead. sigsetjmp(buf, 0)/siglongjmp() does not * preserve signal masks but only works on the current stack. * Since we need a way to create and switch to a new stack, use * the ucontext functions for that but sigsetjmp()/siglongjmp() for * everything else. */ if (getcontext(&uc) == -1) { abort(); } co = g_malloc0(sizeof(*co)); co->stack_size = COROUTINE_STACK_SIZE; co->stack = qemu_alloc_stack(&co->stack_size); co->base.entry_arg = &old_env; /* stash away our jmp_buf */ uc.uc_link = &old_uc; uc.uc_stack.ss_sp = co->stack; uc.uc_stack.ss_size = co->stack_size; uc.uc_stack.ss_flags = 0; #ifdef CONFIG_VALGRIND_H co->valgrind_stack_id = VALGRIND_STACK_REGISTER(co->stack, co->stack + co->stack_size); #endif arg.p = co; makecontext(&uc, (void (*)(void))coroutine_trampoline, 2, arg.i[0], arg.i[1]); /* swapcontext() in, siglongjmp() back out */ if (!sigsetjmp(old_env, 0)) { start_switch_fiber(&fake_stack_save, co->stack, co->stack_size); swapcontext(&old_uc, &uc); } finish_switch_fiber(fake_stack_save); return &co->base; } #ifdef CONFIG_VALGRIND_H #if defined(CONFIG_PRAGMA_DIAGNOSTIC_AVAILABLE) && !defined(__clang__) /* Work around an unused variable in the valgrind.h macro... */ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-but-set-variable" #endif static inline void valgrind_stack_deregister(CoroutineUContext *co) { VALGRIND_STACK_DEREGISTER(co->valgrind_stack_id); } #if defined(CONFIG_PRAGMA_DIAGNOSTIC_AVAILABLE) && !defined(__clang__) #pragma GCC diagnostic pop #endif #endif void qemu_coroutine_delete(Coroutine *co_) { CoroutineUContext *co = DO_UPCAST(CoroutineUContext, base, co_); #ifdef CONFIG_VALGRIND_H valgrind_stack_deregister(co); #endif qemu_free_stack(co->stack, co->stack_size); g_free(co); } /* This function is marked noinline to prevent GCC from inlining it * into coroutine_trampoline(). If we allow it to do that then it * hoists the code to get the address of the TLS variable "current" * out of the while() loop. This is an invalid transformation because * the sigsetjmp() call may be called when running thread A but * return in thread B, and so we might be in a different thread * context each time round the loop. */ CoroutineAction __attribute__((noinline)) qemu_coroutine_switch(Coroutine *from_, Coroutine *to_, CoroutineAction action) { CoroutineUContext *from = DO_UPCAST(CoroutineUContext, base, from_); CoroutineUContext *to = DO_UPCAST(CoroutineUContext, base, to_); int ret; void *fake_stack_save = NULL; current = to_; ret = sigsetjmp(from->env, 0); if (ret == 0) { start_switch_fiber(action == COROUTINE_TERMINATE ? NULL : &fake_stack_save, to->stack, to->stack_size); siglongjmp(to->env, action); } finish_switch_fiber(fake_stack_save); return ret; } Coroutine *qemu_coroutine_self(void) { if (!current) { current = &leader.base; } return current; } bool qemu_in_coroutine(void) { return current && current->caller; }
{ "pile_set_name": "Github" }