public static int Main()
 {
     Thread[] threads = new Thread[1];
     Gen obj = new Gen();
     threads[0] = new Thread(new ThreadStart(obj.Target));
     return 100;
 }
 void OnJointBreak(float breakForce)
 {
     if (_gen == null)
         {
             _gen = GameObject.Find("Charachter").GetComponent<Gen>();
         }
         Debug.Log("Joint Break " + breakForce);
         _gen.Reset();
 }
Beispiel #3
0
        static void Main(string[] args)
        {
            Gen<int> iOb;

            iOb = new Gen<int>(102);

            iOb.Showtype();

            int v = iOb.GetOb();

            Console.WriteLine("Value : " + v);
            Console.WriteLine();

            Gen<string> strOb = new Gen<string>("Generics add power.");

            strOb.Showtype();

            string str = strOb.GetOb();
            Console.WriteLine("Value : " + str);
        }
Beispiel #4
0
 public static Arbitrary <ConverterPropertyGroup> Converter()
 {
     return(Gen
            .Elements(
                new ConverterPropertyGroup(
                    new EnglishNumeralConverter(),
                    NumeralModule.toEnglish,
                    NumeralModule.tryParseEnglish),
                new ConverterPropertyGroup(
                    new DanishNumeralConverter(),
                    NumeralModule.toDanish,
                    NumeralModule.tryParseDanish),
                new ConverterPropertyGroup(
                    new FarsiNumeralConverter(),
                    NumeralModule.toFarsi,
                    NumeralModule.tryParseFarsi),
                new ConverterPropertyGroup(
                    new PolishNumeralConverter(),
                    NumeralModule.toPolish,
                    NumeralModule.tryParsePolish),
                new ConverterPropertyGroup(
                    new DutchNumeralConverter(),
                    NumeralModule.toDutch,
                    NumeralModule.tryParseDutch),
                new ConverterPropertyGroup(
                    new RussianNumeralConverter(),
                    NumeralModule.toRussian,
                    NumeralModule.tryParseRussian),
                new ConverterPropertyGroup(
                    new CatalanNumeralConverter(),
                    NumeralModule.toCatalan,
                    NumeralModule.tryParseCatalan),
                new ConverterPropertyGroup(
                    new BerneseNumeralConverter(),
                    NumeralModule.toBernese,
                    NumeralModule.tryParseBernese)
                )
            .ToArbitrary());
 }
Beispiel #5
0
        protected virtual void Ignite()
        {
            Map map = Map;

            Destroy();
            float ignitionChance = def.projectile.explosionChanceToStartFire;
            var   radius         = def.projectile.explosionRadius;
            var   cellsToAffect  = SimplePool <List <IntVec3> > .Get();

            cellsToAffect.Clear();
            cellsToAffect.AddRange(def.projectile.damageDef.Worker.ExplosionCellsToHit(Position, map, radius));

            MoteMaker.MakeStaticMote(Position, map, ThingDefOf.Mote_ExplosionFlash, radius * 4f);
            for (int i = 0; i < 4; i++)
            {
                MoteMaker.ThrowSmoke(Position.ToVector3Shifted() + Gen.RandomHorizontalVector(radius * 0.7f), map, radius * 0.6f);
            }

            if (Rand.Chance(ignitionChance))
            {
                foreach (var vec3 in cellsToAffect)
                {
                    var fireSize = radius - vec3.DistanceTo(Position);
                    if (fireSize > 0.1f)
                    {
                        FireUtility.TryStartFireIn(vec3, map, fireSize);
                    }
                }
            }

            //Fire explosion should be tiny.
            if (this.def.projectile.explosionEffect != null)
            {
                Effecter effecter = this.def.projectile.explosionEffect.Spawn();
                effecter.Trigger(new TargetInfo(this.Position, map, false), new TargetInfo(this.Position, map, false));
                effecter.Cleanup();
            }
            GenExplosion.DoExplosion(this.Position, map, this.def.projectile.explosionRadius, this.def.projectile.damageDef, this.launcher, this.def.projectile.GetDamageAmount(1, null), this.def.projectile.GetArmorPenetration(1, null), this.def.projectile.soundExplode, this.equipmentDef, this.def, null, this.def.projectile.postExplosionSpawnThingDef, this.def.projectile.postExplosionSpawnChance, this.def.projectile.postExplosionSpawnThingCount, this.def.projectile.applyDamageToExplosionCellsNeighbors, this.def.projectile.preExplosionSpawnThingDef, this.def.projectile.preExplosionSpawnChance, this.def.projectile.preExplosionSpawnThingCount, this.def.projectile.explosionChanceToStartFire, this.def.projectile.explosionDamageFalloff);
        }
Beispiel #6
0
        private void DefineRelationship(VCExpr /*!*/ aExpr, BigNum aValue,
                                        VCExpr /*!*/ bExpr, BigNum bValue)
        {
            Contract.Requires(aValue < bValue);
            Contract.Requires(aExpr != null);
            Contract.Requires(bExpr != null);

            BigNum dist     = bValue - aValue;
            VCExpr distExpr = Gen.Function(VCExpressionGenerator.SubIOp, bExpr, aExpr);

            if (dist <= ConstantDistanceTPO)
            {
                // constants that are sufficiently close to each other are put
                // into a precise relationship
                AddAxiom(Gen.Eq(distExpr, Gen.Integer(dist)));
            }
            else
            {
                AddAxiom(Gen.Function(VCExpressionGenerator.GtOp,
                                      distExpr, Gen.Integer(ConstantDistanceTPO)));
            }
        }
        private void CacheItems()
        {
            this.CheckCreateSorters();
            this.cachedItems.Clear();
            List <Thing> list = CaravanInventoryUtility.AllInventoryItems(base.SelCaravan);
            int          seed = 0;

            for (int i = 0; i < list.Count; i++)
            {
                TransferableImmutable transferableImmutable = TransferableUtility.TransferableMatching <TransferableImmutable>(list[i], this.cachedItems, TransferAsOneMode.Normal);
                if (transferableImmutable == null)
                {
                    transferableImmutable = new TransferableImmutable();
                    this.cachedItems.Add(transferableImmutable);
                }
                transferableImmutable.things.Add(list[i]);
                seed = Gen.HashCombineInt(seed, list[i].GetHashCode());
            }
            this.cachedItems      = this.cachedItems.OrderBy((TransferableImmutable tr) => tr, this.sorter1.Comparer).ThenBy((TransferableImmutable tr) => tr, this.sorter2.Comparer).ThenBy(new Func <TransferableImmutable, float>(TransferableUIUtility.DefaultListOrderPriority)).ToList <TransferableImmutable>();
            this.cachedItemsCount = list.Count;
            this.cachedItemsHash  = seed;
        }
Beispiel #8
0
        private void SearchForFlowers(Map map, bool forced = false)
        {
            int interval = Props.updateTicks;

            if (Find.TickManager.CurTimeSpeed >= TimeSpeed.Superfast &&
                (GenLocalDate.Season(parent.Map) == Season.Winter ||
                 (foundThingsInt != null && foundThingsInt.Count > 1)
                )
                )
            {
                interval += 5000; // return;
            }
            if (!forced && !Gen.IsHashIntervalTick(parent, interval))
            {
                return;
            }

            // Update flowers if needed
            IEnumerable <Thing> foundThings = FindValidThingsInRange(map);

            foundThingsInt = foundThings.ToList();
        }
Beispiel #9
0
        public override VCExpr VisitSubtypeOp(VCExprNAry node, VariableBindings bindings)
        {
            Contract.Requires((bindings != null));
            Contract.Requires((node != null));
            Contract.Ensures(Contract.Result <VCExpr>() != null);
            // UGLY: the code for tracking polarities should be factored out
            int oldPolarity = Eraser.Polarity;

            Eraser.Polarity = 0;

            VCExpr /*!*/ res =
                Gen.Function(VCExpressionGenerator.Subtype3Op,
                             AxBuilder.Type2Term(node[0].Type,
                                                 bindings.TypeVariableBindings),
                             AxBuilder.Cast(Eraser.Mutate(node[0], bindings),
                                            AxBuilder.U),
                             AxBuilder.Cast(Eraser.Mutate(node[1], bindings),
                                            AxBuilder.U));

            Eraser.Polarity = oldPolarity;
            return(res);
        }
 public static int Main()
 {
     Gen<string>
     gs
     =
     new
     Gen<string>
     ();
     Gen<object>
     go
     =
     new
     Gen<object>
     ();
     gs.newArr
     (3);
     go.newArr
     (3);
     return
     work
     ();
 }
Beispiel #11
0
        public static int IncidentCountThisInterval(IIncidentTarget target, int randSeedSalt, float minDaysPassed, float onDays, float offDays, float minSpacingDays, float minIncidents, float maxIncidents, float acceptFraction = 1f)
        {
            int num  = DaysToIntervals(minDaysPassed);
            int num2 = QueueIntervalsPassed - num;

            if (num2 < 0)
            {
                return(0);
            }
            int num3 = DaysToIntervals(onDays);
            int num4 = DaysToIntervals(offDays);
            int minSpacingIntervals = DaysToIntervals(minSpacingDays);
            int num5     = num3 + num4;
            int num6     = num2 / num5;
            int fixedHit = -9999999;

            for (int i = 0; i <= num6; i++)
            {
                int seed  = Gen.HashCombineInt(Find.World.info.persistentRandomValue, target.ConstantRandSeed, randSeedSalt, i);
                int start = i * num5;
                if (hits.Count > 0)
                {
                    fixedHit = hits[hits.Count - 1];
                }
                hits.Clear();
                GenerateHitList(seed, start, num3, minIncidents, maxIncidents, minSpacingIntervals, acceptFraction, fixedHit);
            }
            int num7 = 0;

            for (int j = 0; j < hits.Count; j++)
            {
                if (hits[j] == num2)
                {
                    num7++;
                }
            }
            hits.Clear();
            return(num7);
        }
    public static int Main()
    {
        int _int1 = 1;
        int _int2 = -1;

        Gen <int> .PassAsParameter(_int1, _int2);

        double _double1 = 1;
        double _double2 = -1;

        Gen <double> .PassAsParameter(_double1, _double2);

        string _string1 = "string1";
        string _string2 = "string2";

        Gen <string> .PassAsParameter(_string1, _string2);

        object _object1 = (object)_string1;
        object _object2 = (object)_string2;

        Gen <object> .PassAsParameter(_object1, _object2);

        Guid _Guid1 = new Guid(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1);
        Guid _Guid2 = new Guid(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);

        Gen <Guid> .PassAsParameter(_Guid1, _Guid2);

        if (result)
        {
            Console.WriteLine("Test Passed");
            return(100);
        }
        else
        {
            Console.WriteLine("Test Failed");
            return(1);
        }
    }
Beispiel #13
0
    public static int Main()
    {
        Gen <int> .TryEnterTest();

        /*Gen<double>.TryEnterTest();
         * Gen<string>.TryEnterTest();
         * Gen<object>.TryEnterTest();
         * Gen<Guid>.TryEnterTest();
         *
         * Gen<int[]>.TryEnterTest();
         * Gen<double[,]>.TryEnterTest();
         * Gen<string[][][]>.TryEnterTest();
         * Gen<object[,,,]>.TryEnterTest();
         * Gen<Guid[][,,,][]>.TryEnterTest();
         *
         * Gen<RefX1<int>[]>.TryEnterTest();
         * Gen<RefX1<double>[,]>.TryEnterTest();
         * Gen<RefX1<string>[][][]>.TryEnterTest();
         * Gen<RefX1<object>[,,,]>.TryEnterTest();
         * Gen<RefX1<Guid>[][,,,][]>.TryEnterTest();
         *
         * Gen<ValX1<int>[]>.TryEnterTest();
         * Gen<ValX1<double>[,]>.TryEnterTest();
         * Gen<ValX1<string>[][][]>.TryEnterTest();
         * Gen<ValX1<object>[,,,]>.TryEnterTest();
         * Gen<ValX1<Guid>[][,,,][]>.TryEnterTest();*/

        if (result)
        {
            Console.WriteLine("Test Passed");
            return(100);
        }
        else
        {
            Console.WriteLine("Test Failed");
            return(1);
        }
    }
Beispiel #14
0
        ////////////////////////////////////////////////////////////////////////////

        private VCExpr AssembleOpExpression(OpTypesPair opTypes, IEnumerable <VCExpr /*!*/> /*!*/ oldArgs,
                                            VariableBindings bindings)
        {
            Contract.Requires(bindings != null);
            Contract.Requires(cce.NonNullElements(oldArgs));
            Contract.Ensures(Contract.Result <VCExpr>() != null);
            // UGLY: the code for tracking polarities should be factored out
            int oldPolarity = Eraser.Polarity;

            Eraser.Polarity = 0;

            List <VCExpr /*!*/> /*!*/
            newArgs = new List <VCExpr /*!*/>();

            // explicit type parameters
            foreach (Type /*!*/ t in opTypes.Types)
            {
                Contract.Assert(newArgs != null);
                newArgs.Add(AxBuilder.Type2Term(t, bindings.TypeVariableBindings));
            }

            // and the actual value parameters
            Function /*!*/
                newFun = ((VCExprBoogieFunctionOp)opTypes.Op).Func;
            // ^ we only allow this operator at this point
            int i = opTypes.Types.Count;

            foreach (VCExpr /*!*/ arg in oldArgs)
            {
                Contract.Assert(arg != null);
                newArgs.Add(AxBuilder.Cast(Eraser.Mutate(arg, bindings),
                                           cce.NonNull(newFun.InParams[i]).TypedIdent.Type));
                i = i + 1;
            }

            Eraser.Polarity = oldPolarity;
            return(Gen.Function(opTypes.Op, newArgs));
        }
Beispiel #15
0
    public static int Main()
    {
        Gen <int> .ThreadPoolTest <object>();

        Gen <double> .ThreadPoolTest <string>();

        Gen <string> .ThreadPoolTest <Guid>();

        Gen <object> .ThreadPoolTest <int>();

        Gen <Guid> .ThreadPoolTest <double>();

        if (result)
        {
            Console.WriteLine("Test Passed");
            return(100);
        }
        else
        {
            Console.WriteLine("Test Failed");
            return(1);
        }
    }
Beispiel #16
0
 public static Gen <BaseEvent> BaseEvent()
 {
     return(Gen.OneOf(new[] {
         Arb.Generate <EventNodeHeartbeat>().Select(e => e as BaseEvent),
         Arb.Generate <EventTaskHeartbeat>().Select(e => e as BaseEvent),
         Arb.Generate <EventInstanceConfigUpdated>().Select(e => e as BaseEvent),
         Arb.Generate <EventProxyCreated>().Select(e => e as BaseEvent),
         Arb.Generate <EventProxyDeleted>().Select(e => e as BaseEvent),
         Arb.Generate <EventProxyFailed>().Select(e => e as BaseEvent),
         Arb.Generate <EventProxyStateUpdated>().Select(e => e as BaseEvent),
         Arb.Generate <EventCrashReported>().Select(e => e as BaseEvent),
         Arb.Generate <EventRegressionReported>().Select(e => e as BaseEvent),
         Arb.Generate <EventFileAdded>().Select(e => e as BaseEvent),
         Arb.Generate <EventTaskFailed>().Select(e => e as BaseEvent),
         Arb.Generate <EventTaskStopped>().Select(e => e as BaseEvent),
         Arb.Generate <EventTaskStateUpdated>().Select(e => e as BaseEvent),
         Arb.Generate <EventScalesetFailed>().Select(e => e as BaseEvent),
         Arb.Generate <EventScalesetResizeScheduled>().Select(e => e as BaseEvent),
         Arb.Generate <EventScalesetStateUpdated>().Select(e => e as BaseEvent),
         Arb.Generate <EventNodeDeleted>().Select(e => e as BaseEvent),
         Arb.Generate <EventNodeCreated>().Select(e => e as BaseEvent),
     }));
 }
Beispiel #17
0
        public void Test()
        {
            Check.One(Config, Prop.forAll(Arb.from <List <int> >(), FSharpFunc <List <int>, Property> .FromConverter(xs =>
            {
                return(Prop.forAll(Arb.fromGen(Gen.choose(0, xs.Count - 1)), FSharpFunc <int, Property> .FromConverter(n =>
                {
                    return Prop.forAll(Arb.fromGen(Gen.choose(n, xs.Count)), FSharpFunc <int, Property> .FromConverter(m =>
                    {
                        var slice = xs.Slice(n, m).ToList();
                        string label;
                        switch (slice.Count)
                        {
                        case 0: label = "none"; break;

                        case 1: label = "one"; break;

                        default: label = (slice.Count == xs.Count) ? "whole" : "part"; break;
                        }
                        return Prop.collect <string, bool>(label).Invoke(xs.ContainsSlice(slice));
                    }));
                })));
            })));
        }
        internal static Graphic _GhostGraphicFor(Graphic baseGraphic, ThingDef thingDef, Color ghostCol)
        {
            int     key = Gen.HashCombineStruct <Color>(Gen.HashCombine <ThingDef>(Gen.HashCombine <Graphic>(0, baseGraphic), thingDef), ghostCol);
            Graphic graphic;

            if (!_GhostDrawer._ghostGraphics.TryGetValue(key, out graphic))
            {
                graphic =
                    (thingDef.graphicData.Linked) ||
                    (
                        (thingDef.thingClass == typeof(Building_Door)) ||
                        (thingDef.thingClass.IsSubclassOf(typeof(Building_Door)))
                    )
                    ? GraphicDatabase.Get <Graphic_Single>(thingDef.uiIconPath, ShaderDatabase.Transparent, thingDef.graphicData.drawSize, ghostCol)
                    : (
                        (baseGraphic == null)
                        ? GraphicDatabase.Get(thingDef.graphic.GetType(), thingDef.graphic.path, ShaderDatabase.Transparent, thingDef.graphic.drawSize, ghostCol, Color.white)
                        : GraphicDatabase.Get(baseGraphic.GetType(), baseGraphic.path, ShaderDatabase.Transparent, baseGraphic.drawSize, ghostCol, Color.white)
                        );
                _GhostDrawer._ghostGraphics.Add(key, graphic);
            }
            return(graphic);
        }
Beispiel #19
0
    public static void ThreadPoolTest()
    {
        ManualResetEvent[] evts = new ManualResetEvent[Test_thread12.nThreads];
        WaitHandle[]       hdls = new WaitHandle[Test_thread12.nThreads];

        for (int i = 0; i < Test_thread12.nThreads; i++)
        {
            evts[i] = new ManualResetEvent(false);
            hdls[i] = (WaitHandle)evts[i];
        }

        IGen <T> obj = new Gen <T>();

        for (int i = 0; i < Test_thread12.nThreads; i++)
        {
            WaitCallback cb = new WaitCallback(obj.Target);
            ThreadPool.QueueUserWorkItem(cb, evts[i]);
        }

        WaitHandle.WaitAll(hdls);
        Test_thread12.Eval(Test_thread12.Xcounter == Test_thread12.nThreads);
        Test_thread12.Xcounter = 0;
    }
Beispiel #20
0
        private static List <Dictionary <string, object> > GetMockedEvents(int recordsToGenerate)
        {
            var recordsList = new List <Dictionary <string, object> >();

            for (var i = 0; i < recordsToGenerate; i++)
            {
                recordsList.Add(new Dictionary <string, object>
                {
                    { "Event_ID", Gen.Sample(7, 1, Gen.OneOf(Arb.Generate <int>())).HeadOrDefault },
                    { "Congregation_Name", Gen.Sample(75, 1, Gen.OneOf(Arb.Generate <string>())).HeadOrDefault },
                    { "Congregation_ID", Gen.Sample(7, 1, Gen.OneOf(Arb.Generate <int>())).HeadOrDefault },
                    { "Site", Gen.Sample(10, 1, Gen.OneOf(Arb.Generate <string>())).HeadOrDefault },
                    { "Event_Title", Gen.Sample(75, 1, Gen.OneOf(Arb.Generate <string>())).HeadOrDefault },
                    { "Event_Type_ID", Gen.Sample(1, 1, Gen.OneOf(Arb.Generate <int>())).HeadOrDefault },
                    { "Event_Start_Date", Gen.Sample(1, 1, Gen.OneOf(Arb.Generate <DateTime>())).HeadOrDefault },
                    { "Event_End_Date", Gen.Sample(1, 1, Gen.OneOf(Arb.Generate <DateTime>())).HeadOrDefault },
                    { "Parent_Event_ID", Gen.Sample(7, 1, Gen.OneOf(Arb.Generate <int>())).HeadOrDefault },
                    { "Template", Gen.Sample(7, 1, Gen.OneOf(Arb.Generate <bool>())).HeadOrDefault }
                });
            }

            return(recordsList);
        }
Beispiel #21
0
    public static void ThreadPoolTest <U>()
    {
        ManualResetEvent[] evts = new ManualResetEvent[Test.nThreads];
        WaitHandle[]       hdls = new WaitHandle[Test.nThreads];

        for (int i = 0; i < Test.nThreads; i++)
        {
            evts[i] = new ManualResetEvent(false);
            hdls[i] = (WaitHandle)evts[i];
        }
#pragma warning disable 219
        Gen <T> obj = new Gen <T>();
#pragma warning restore
        for (int i = 0; i < Test.nThreads; i++)
        {
            WaitCallback cb = new WaitCallback(Gen <T> .Target <U>);
            ThreadPool.QueueUserWorkItem(cb, evts[i]);
        }

        WaitHandle.WaitAll(hdls);
        Test.Eval(Test.Xcounter == Test.nThreads);
        Test.Xcounter = 0;
    }
Beispiel #22
0
 public static void Main(string[] args)
 {
     try
     {
         if (!Lex.ProcessArguments(args))
         {
             return;
         }
     }
     catch (ApplicationException ex)
     {
         if (Lex.currentOption != null)
         {
             Console.WriteLine("Option '{0}', value '{1}'.", Lex.currentOption, Lex.currentValue);
         }
         Console.WriteLine(ex.Message);
         Console.WriteLine();
         Environment.ExitCode = 1;
     }
     try
     {
         Gen gen = new Gen(Lex.inFile, Lex.outFile, Lex.version);
         gen.Generate();
     }
     catch (ApplicationException ex2)
     {
         Console.WriteLine(ex2.Message);
         Console.WriteLine();
         Environment.ExitCode = 1;
     }
     catch (Exception ex3)
     {
         Console.WriteLine(ex3.Message);
         Console.WriteLine(ex3.StackTrace);
         Environment.ExitCode = 1;
     }
 }
Beispiel #23
0
        public bool buyBooks(Carte carte, short numberOfBooks)
        {
            using (bibContext) {
                Autor autor = carte.Autor;
                Gen   gen   = carte.Gen;

                Console.WriteLine(autor);
                if (!autorRepository.autorAlreadyExists(autor.nume, autor.prenume))
                {
                    autor = autorRepository.insertObject(autor);
                    Console.WriteLine("AFTER SAVE AUTOR {0}", autor);
                }

                if (!genderRepository.genderAlreadyExists(gen.descriere))
                {
                    gen = genderRepository.insertObject(gen);
                }

                bookRepository.saveChanges();
                Carte bookToSave = new Carte()
                {
                    autorId  = autor.autorId,
                    genId    = gen.genId,
                    titlu    = carte.titlu,
                    Imprumut = new List <Imprumut>()
                };

                while (numberOfBooks > 0)
                {
                    bookRepository.insertObject(bookToSave);
                    numberOfBooks--;
                }

                bookRepository.saveChanges();
                return(true);
            }
        }
            private Arbitrary <TelemetryGen> Telemetry()
            {
                Gen <int> ChooseInt(int min, int max)
                {
                    return(Arb.From(Gen.Choose(min, max)).Generator);
                }

                var gen =
                    from negMs in ChooseInt(0, MaxRandomMs)
                    from deviceId in ChooseInt(1, NumDevices)
                    from propertyId in ChooseInt(1, NumProperties)
                    select new TelemetryGen(negMs, deviceId, propertyId);

                var arb = Arb.From(gen, ShrinkTelemetryGen);

                IEnumerable <TelemetryGen> ShrinkTelemetryGen(TelemetryGen x)
                {
                    if (x.DevId != 1)
                    {
                        yield return(x.With(DevId: 1));
                    }

                    if (x.PropId != 1)
                    {
                        yield return(x.With(PropId: 1));
                    }

                    if (x.NegMs != 0)
                    {
                        yield return(x.With(NegMs: x.NegMs / 2));

                        yield return(x.With(NegMs: x.NegMs - 1));
                    }
                }

                return(arb);
            }
Beispiel #25
0
        public bool ThingsAvailableAnywhere(ThingDefCountClass need, Pawn pawn)
        {
            int key = Gen.HashCombine(need.GetHashCode(), pawn.Faction);

            if (!cachedResults.TryGetValue(key, out bool value))
            {
                List <Thing> list = map.listerThings.ThingsOfDef(need.thingDef);
                int          num  = 0;
                for (int i = 0; i < list.Count; i++)
                {
                    if (!list[i].IsForbidden(pawn))
                    {
                        num += list[i].stackCount;
                        if (num >= need.count)
                        {
                            break;
                        }
                    }
                }
                value = (num >= need.count);
                cachedResults.Add(key, value);
            }
            return(value);
        }
        public override VCExpr Visit(VCExprLet node, FlattenerState state)
        {
            Contract.Requires(node != null);
            Contract.Ensures(Contract.Result <VCExpr>() != null);
            if (state.InTerm)
            {
                return(GetVarFor(node));
            }

            VCExprLet prelimRes = (VCExprLet)cce.NonNull(base.Visit(node, state));

            List <VCExprLetBinding /*!*/> /*!*/ allBindings = new List <VCExprLetBinding /*!*/> ();

            allBindings.AddRange(prelimRes);

            // Check whether any of the extracted terms contain variables
            // bound by this binder. In this case, we have to add
            // let-binders and remove the extracted terms
            bool cont = true;

            while (cont)
            {
                List <VCExprLetBinding /*!*/> /*!*/ localBindings =
                    RemoveBindingsWithVars(prelimRes.BoundVars, new List <TypeVariable /*!*/>());
                if (localBindings.Count > 0)
                {
                    allBindings.AddRange(FlattenBindings(localBindings, state));
                }
                else
                {
                    cont = false;
                }
            }

            return(Gen.Let(allBindings, prelimRes.Body));
        }
        public override VCExpr Visit(VCExprQuantifier node, FlattenerState state)
        {
            Contract.Requires(node != null);
            Contract.Ensures(Contract.Result <VCExpr>() != null);
            if (state.InTerm)
            {
                return(GetVarFor(node));
            }

            // we only flatten within the matrix of the quantified formula,
            // not within the triggers (since SMT-solvers do not seem to
            // appreciate triggers with let-binders)
            VCExpr newBody = Mutate(node.Body, state);

            // Check whether any of the extracted terms contain variables
            // bound by this quantifier. In this case, we have to add
            // let-binders and remove the extracted terms
            bool cont = true;

            while (cont)
            {
                List <VCExprLetBinding /*!*/> /*!*/ localBindings =
                    RemoveBindingsWithVars(node.BoundVars, node.TypeParameters);
                Contract.Assert(cce.NonNullElements(localBindings));
                if (localBindings.Count > 0)
                {
                    newBody = AddBindings(localBindings, newBody, state);
                }
                else
                {
                    cont = false;
                }
            }

            return(Gen.Quantify(node.Quan, node.TypeParameters, node.BoundVars, node.Triggers, node.Infos, newBody));
        }
Beispiel #28
0
    public static int Main()
    {
        Gen <int> GenInt = new Gen <int>();

        Eval(((IGenX <int>)GenInt).m(5).Equals("IGenX.m"));
        Eval(((IGenY <int>)GenInt).m(5).Equals("IGenY.m"));

        Gen <string> GenString = new Gen <string>();

        Eval(((IGenX <string>)GenString).m("S").Equals("IGenX.m"));
        Eval(((IGenY <string>)GenString).m("S").Equals("IGenY.m"));


        if (result)
        {
            Console.WriteLine("Test Passed");
            return(100);
        }
        else
        {
            Console.WriteLine("Test Failed");
            return(1);
        }
    }
    // Finds labels and changes them to a globally unique label:
    protected override VCExpr /*!*/ UpdateModifiedNode(VCExprNAry /*!*/ originalNode,
      List<VCExpr /*!*/> /*!*/ newSubExprs,
      bool changed,
      bool arg)
    {
      //Contract.Ensures(Contract.Result<VCExpr>() != null);

      VCExpr ret;
      if (changed)
        ret = Gen.Function(originalNode.Op,
          newSubExprs, originalNode.TypeArguments);
      else
        ret = originalNode;

      if (!(ret is VCExprNAry)) return ret;
      VCExprNAry retnary = (VCExprNAry) ret;
      if (!(retnary.Op is VCExprBoogieFunctionOp))
        return ret;

      var fcall = (retnary.Op as VCExprBoogieFunctionOp).Func.Name;
      if (procNames.Contains(fcall))
        return VCExpressionGenerator.True;
      return ret;
    }
Beispiel #30
0
        public static Arbitrary <IDictionary <string, string> > Model()
        {
            var tagOpeningChars =
                "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
            var tagOtherChars =
                tagOpeningChars + "0123456789";

            Func <char, char[], string> merge = (first, rest) =>
            {
                var target = new char[rest.Length + 1];
                target[0] = first;
                Array.Copy(rest, 0, target, 1, rest.Length);
                return(new string(target));
            };

            var tagGen =
                from opening in
                Gen.Elements(tagOpeningChars.ToCharArray())
                from rest in
                Gen.ArrayOf(Gen.Elements(tagOtherChars.ToCharArray()))
                from replacement in
                Arb.Generate <NonNull <string> >()
                select
                new KeyValuePair <string, string>(merge(opening, rest),
                                                  replacement.Get);

            var modelGen =
                Gen.NonEmptyListOf(tagGen)
                .Select(tags =>
                        new Dictionary <string, string>(
                            tags.GroupBy(kv => kv.Key)
                            .Select(g => g.First()))
                        as IDictionary <string, string>);

            return(Arb.From(modelGen));
        }
        protected void PushParamsOrLocalsToStack(int paramArrayIndex)
        {
            byte currentByRefParam = 0;

            for (int i = 0, count = ParamTypes.Length; i < count; ++i)
            {
                Type paramType = ParamTypes[i];
                if (paramType.IsByRef)
                {
                    Gen.Emit(OpCodes.Ldloca_S, currentByRefParam);
                    currentByRefParam++;
                }
                else
                {
                    ldarg(paramArrayIndex);
                    Gen.Emit(OpCodes.Ldc_I4, i);
                    Gen.Emit(OpCodes.Ldelem_Ref);
                    if (paramType != typeof(object))
                    {
                        Gen.Emit(paramType.IsValueType ? OpCodes.Unbox_Any : OpCodes.Castclass, paramType);
                    }
                }
            }
        }
Beispiel #32
0
        /**
         * Returns a copy of this cnode such that all the i-nodes below it are
         * copied to the specified generation `ngen`.
         */
        public CNode <K, V> renewed(Gen ngen, ConcurrentTrieDictionary <K, V> ct)
        {
            int i = 0;

            BasicNode[] arr = array;
            int         len = arr.Length;

            BasicNode[] narr = new BasicNode[len];
            while (i < len)
            {
                BasicNode elem = arr[i];
                if (elem is INode <K, V> )
                {
                    INode <K, V> _in = (INode <K, V>)elem;
                    narr[i] = _in.copyToGen(ngen, ct);
                }
                else if (elem is BasicNode)
                {
                    narr[i] = elem;
                }
                i += 1;
            }
            return(new CNode <K, V>(bitmap, narr, ngen));
        }
Beispiel #33
0
        public static List <DamageOverlay> GetOverlays(Thing b)
        {
            ThingsToxicDamageSectionLayerUtility.overlays.Clear();
            ThingsToxicDamageSectionLayerUtility.overlaysWorkingList.Clear();
            ThingsToxicDamageSectionLayerUtility.overlaysWorkingList.AddRange(ThingsToxicDamageSectionLayerUtility.GetAvailableOverlays(b));
            if (!ThingsToxicDamageSectionLayerUtility.overlaysWorkingList.Any <DamageOverlay>())
            {
                return(ThingsToxicDamageSectionLayerUtility.overlays);
            }
            Rand.PushState();
            Rand.Seed = Gen.HashCombineInt(b.thingIDNumber, 1958376471);
            int damageOverlaysCount = ThingsToxicDamageSectionLayerUtility.GetDamageOverlaysCount(b, b.Map.GetComponent <MapComponent_MapEvents>().ToxicDamages[b]);
            int num = 0;

            while (num < damageOverlaysCount && ThingsToxicDamageSectionLayerUtility.overlaysWorkingList.Any <DamageOverlay>())
            {
                DamageOverlay item = ThingsToxicDamageSectionLayerUtility.overlaysWorkingList.RandomElement <DamageOverlay>();
                ThingsToxicDamageSectionLayerUtility.overlaysWorkingList.Remove(item);
                ThingsToxicDamageSectionLayerUtility.overlays.Add(item);
                num++;
            }
            Rand.PopState();
            return(ThingsToxicDamageSectionLayerUtility.overlays);
        }
        public static void DrawDropSpotShadow(Vector3 center, Rot4 rot, Material material, Vector2 shadowSize, int ticksToImpact)
        {
            if (rot.IsHorizontal)
            {
                Gen.Swap <float>(ref shadowSize.x, ref shadowSize.y);
            }
            ticksToImpact = Mathf.Max(ticksToImpact, 0);
            Vector3 pos = center;

            pos.y = AltitudeLayer.Shadows.AltitudeFor();
            float   num   = 1f + (float)ticksToImpact / 100f;
            Vector3 s     = new Vector3(num * shadowSize.x, 1f, num * shadowSize.y);
            Color   white = Color.white;

            if (ticksToImpact > 150)
            {
                white.a = Mathf.InverseLerp(200f, 150f, (float)ticksToImpact);
            }
            Skyfaller.shadowPropertyBlock.SetColor(ShaderPropertyIDs.Color, white);
            Matrix4x4 matrix = default(Matrix4x4);

            matrix.SetTRS(pos, rot.AsQuat, s);
            Graphics.DrawMesh(MeshPool.plane10Back, matrix, material, 0, null, 0, Skyfaller.shadowPropertyBlock);
        }
        public VM.CompiledScript Compile(ICharStream input)
        {
            try
            {
                LSLTreeAdaptor lslAdaptor = new LSLTreeAdaptor();


                //
                // Initial parse and AST creation
                //
                LSLLexer lex = new LSLLexer(input);
                CommonTokenStream tokens = new CommonTokenStream(lex);
                LSLParser p = new LSLParser(tokens);
                p.TreeAdaptor = lslAdaptor;
                p.TraceDestination = _traceRedirect;
                lex.TraceDestination = _traceRedirect;
                LSLParser.prog_return r = p.prog();

                if (p.NumberOfSyntaxErrors > 0)
                {
                    _listener.Error(Convert.ToString(p.NumberOfSyntaxErrors) + " syntax error(s)");
                    return null;
                }


                //
                // Definitions
                //
                CommonTree t = (CommonTree)r.Tree;
                CommonTreeNodeStream nodes = new CommonTreeNodeStream(lslAdaptor, t);
                nodes.TokenStream = tokens;

                SymbolTable symtab = new SymbolTable(tokens, Defaults.SystemMethods.Values, DefaultConstants.Constants.Values);
                symtab.StatusListener = _listener;

                Def def = new Def(nodes, symtab);
                def.TraceDestination = _traceRedirect;
                def.Downup(t);

                nodes.Reset();

                if (_listener.HasErrors() || def.NumberOfSyntaxErrors > 0)
                {
                    return null;
                }


                //
                // Type and more semantic checks
                //
                Compiler.Types types = new Compiler.Types(nodes, symtab);
                types.TraceDestination = _traceRedirect;
                types.Downup(t);

                nodes.Reset();

                if (_listener.HasErrors() || types.NumberOfSyntaxErrors > 0)
                {
                    return null;
                }


                StringTemplateGroup templates;
                using (TextReader fr = new StreamReader(Path.Combine(_templatePath, "ByteCode.stg")))
                {
                    templates = new StringTemplateGroup(fr);
                    fr.Close();
                }

                if (_outputAstGraph)
                {
                    DotTreeGenerator dotgen = new DotTreeGenerator();
                    string dot = dotgen.ToDot(t);

                    TextWriter tw = new StreamWriter("ast.txt");
                    tw.WriteLine(dot);
                    tw.Close();
                }

                Analyze analyze = new Analyze(nodes, symtab);
                analyze.TraceDestination = _traceRedirect;
                analyze.Downup(t);

                nodes.Reset();

                foreach (Compiler.BranchAnalyze.FunctionBranch b in analyze.FunctionBranches.Where(pred => pred.Type != null))
                {
                    if (!b.AllCodePathsReturn())
                    {
                        if (_listener != null)
                        {
                            _listener.Error("line: " + b.Node.Line + ":" +
                                b.Node.CharPositionInLine + " " + b.Node.Text + "(): Not all control paths return a value");
                        }
                    }
                }

                if (_listener.HasErrors() || analyze.NumberOfSyntaxErrors > 0)
                {
                    return null;
                }


                //
                // Bytecode generation
                //
                Gen g = new Gen(nodes, symtab);
                g.TemplateGroup = templates;
                g.TraceDestination = _traceRedirect;

                Gen.script_return ret = g.script();

                if (_listener.HasErrors() || g.NumberOfSyntaxErrors > 0)
                {
                    return null;
                }

                if (ret.Template == null)
                {
                    return null;
                }

                StringTemplate template = ret.Template;

                if (_byteCodeDebugging)
                {
                    _byteCode = template.ToString();
                }

                //
                // Bytecode compilation
                //
                AssemblerLexer alex = new AssemblerLexer(new ANTLRStringStream(template.ToString()));
                CommonTokenStream atokens = new CommonTokenStream(alex);
                AssemblerParser ap = new AssemblerParser(atokens);
                BytecodeGenerator bcgen = new BytecodeGenerator(Defaults.SystemMethods.Values);

                ap.SetGenerator(bcgen);
                ap.TraceDestination = _traceRedirect;

                try
                {
                    ap.program();

                    if (_listener.HasErrors() || p.NumberOfSyntaxErrors > 0)
                    {
                        _listener.Error(Convert.ToString(ap.NumberOfSyntaxErrors) + " bytecode generation error(s)");
                        return null;
                    }

                    return bcgen.Result;
                }
                catch (GenerationException e)
                {
                    _listener.Error(e.Message);
                }

                return null;
            }
            catch (TooManyErrorsException e)
            {
                _listener.Error(String.Format("Too many errors {0}", e.InnerException.Message));
            }
            catch (RecognitionException e)
            {
                _listener.Error("line: " + e.Line.ToString() + ":" + e.CharPositionInLine.ToString() + " " + e.Message);
            }
            catch (Exception e)
            {
                _listener.Error(e.Message);    
            }

            return null;
        }
        public string Compile(ICharStream input)
        {
            try
            {
                LSLTreeAdaptor lslAdaptor = new LSLTreeAdaptor();

                LSLLexer lex = new LSLLexer(input);
                CommonTokenStream tokens = new CommonTokenStream(lex);
                LSLParser p = new LSLParser(tokens);
                p.TreeAdaptor = lslAdaptor;
                p.TraceDestination = _traceDestination;
                lex.TraceDestination = _traceDestination;
                LSLParser.prog_return r = p.prog();

                if (p.NumberOfSyntaxErrors > 0)
                {
                    if (_listener != null)
                    {
                        _listener.Error(Convert.ToString(p.NumberOfSyntaxErrors) + " syntax error(s)");
                    }

                    return null;
                }

                CommonTree t = (CommonTree)r.Tree;
                CommonTreeNodeStream nodes = new CommonTreeNodeStream(lslAdaptor, t);
                nodes.TokenStream = tokens;

                SymbolTable symtab = new SymbolTable(tokens, Defaults.SystemMethods.Values, DefaultConstants.Constants.Values);

                if (this.Listener != null)
                {
                    symtab.StatusListener = this.Listener;
                }

                Def def = new Def(nodes, symtab);
                def.TraceDestination = _traceDestination;
                def.Downup(t);

                CommonTreeNodeStream nodes2 = new CommonTreeNodeStream(lslAdaptor, t);
                nodes2.TokenStream = tokens;

                Types types = new Types(nodes2, symtab);
                types.TraceDestination = _traceDestination;
                types.Downup(t);

                if (_listener != null)
                {
                    if (_listener.HasErrors()) return null;
                }

                CommonTreeNodeStream nodes4 = new CommonTreeNodeStream(lslAdaptor, t);
                nodes4.TokenStream = tokens;

                CommonTreeNodeStream nodes3 = new CommonTreeNodeStream(lslAdaptor, t);
                nodes3.TokenStream = tokens;

                TextReader fr = new StreamReader("ByteCode.stg");
                StringTemplateGroup templates = new StringTemplateGroup(fr);
                fr.Close();

                DotTreeGenerator dotgen = new DotTreeGenerator();
                string dot = dotgen.ToDot(t);

                TextWriter tw = new StreamWriter("ast.txt");
                tw.WriteLine(dot);
                tw.Close();

                Analyze analyze = new Analyze(nodes4, symtab);
                types.TraceDestination = _traceDestination;
                analyze.Downup(t);

                foreach (FunctionBranch b in analyze.FunctionBranches.Where(pred => pred.Type != null))
                {
                    if (!b.AllCodePathsReturn())
                    {
                        if (_listener != null)
                        {
                            _listener.Error("line: " + b.Node.Line + ":" +
                                b.Node.CharPositionInLine + " " + b.Node.Text + "(): Not all control paths return a value");
                        }
                    }
                }

                Gen g = new Gen(nodes3, symtab);
                g.TemplateGroup = templates;
                g.TraceDestination = _traceDestination;
                StringTemplate template = g.script().Template;


                if (template != null)
                {
                    string bcOut = template.ToString();
                    Console.WriteLine("** byte code **\n" + bcOut);
                    return bcOut;
                }
            }
            catch (TooManyErrorsException e)
            {
                if (_listener != null)
                {
                    _listener.Error(String.Format("Too many errors {0}", e.InnerException.Message));
                }
            }
            catch (RecognitionException e)
            {
                if (_listener != null)
                {
                    _listener.Error("line: " + e.Line.ToString() + ":" + e.CharPositionInLine.ToString() + " " + e.Message);
                }
            }
            catch (Exception e)
            {
                if (_listener != null)
                {
                    _listener.Error(e.Message);
                }
            }

            return null;
        }
Beispiel #37
0
  /// <summary>
  /// 文字列をその頻度が多い順に列挙します。
  /// </summary>
  /// <param name="d_tok">文字列と頻度のペアを格納した Dictionary を返します。</param>
  /// <returns>文字列の列挙子を返します。</returns>
  static Gen::IEnumerable<string> EnumFreqOrder(Gen::Dictionary<string,int> d_tok){
    // 頻度順に並び替え
    int c=d_tok.Count;
    string[] tokens=new string[c];
    int[] freqs=new int[c];
    int j=0;
    foreach(string k in d_tok.Keys){
      tokens[j]=k;
      freqs[j]=d_tok[k];
      j++;
    }
    /*
    for(j=0;j<c;j++)
      args.WriteLine("token pair({0}, {1})",freqs[j],tokens[j]);
    args.WriteLine("---- sort ----");
    //*/
    System.Array.Sort(freqs,tokens);
    /*
    for(j=0;j<c;j++)
      args.WriteLine("token pair#{2}({0}, {1})",freqs[j],tokens[j],j);
    //*/

    // 列挙
    for(int i=c-1;i>=0;i--){
      yield return tokens[i];
    }
  }
Beispiel #38
0
    public static int work () {
	Gen<string> gs = new Gen<string> ();
	Gen<object> go = new Gen<object> ();

	MethodInfo miObj = typeof (Gen<object>).GetMethod ("newArr", BindingFlags.Public | BindingFlags.Instance);
	MethodInfo miStr = typeof (Gen<string>).GetMethod ("newArr", BindingFlags.Public | BindingFlags.Instance);

	if (miObj == miStr) {
	    Console.WriteLine ("methods equal");
	    return 1;
	}

	ObjArrDel oad = go.newObjDel ();
	StrArrDel sad = gs.newStrDel ();
	StrArrDel sad2 = (StrArrDel)Delegate.CreateDelegate (typeof (StrArrDel), null, miStr);

	if (oad.Method != miObj) {
	    Console.WriteLine ("wrong object method");
	    if (oad.Method == miStr)
		Console.WriteLine ("object method is string");
	    return 1;
	}

	if (sad.Method != miStr) {
	    Console.WriteLine ("wrong string method");
	    if (sad.Method == miObj)
		Console.WriteLine ("string method is object");
	    else
		return 1;
	} else {
	    Console.WriteLine ("right string method");
	}

	if (sad2.Method != miStr) {
	    Console.WriteLine ("wrong string2 method");
	    if (sad2.Method == miObj)
		Console.WriteLine ("string2 method is object");
	    return 1;
	}

	Console.WriteLine ("calling object del");
	if (oad (go, 3).GetType () != typeof (object [])) {
	    Console.WriteLine ("not object array");
	    return 1;
	}

	Console.WriteLine ("calling string del");
	if (sad (gs, 3).GetType () != typeof (string [])) {
	    Console.WriteLine ("not string array");
	    return 1;
	}

	Console.WriteLine ("calling string del2");
	if (sad2 (gs, 3).GetType () != typeof (string [])) {
	    Console.WriteLine ("not string2 array");
	    return 1;
	}

	try {
	    StrArrDel sad3 = (StrArrDel)Delegate.CreateDelegate (typeof (StrArrDel), null, miObj);
	    Console.WriteLine ("object method for string delegate");
	    return 1;
	} catch (ArgumentException) {
	}

	/*
	DelObj delObj = (DelObj)Delegate.CreateDelegate (typeof (DelObj), null, miObj);

	if (delObj (go, 3).GetType () != typeof (object []))
	    return 1;

	DelStr delStr = (DelStr)Delegate.CreateDelegate (typeof (DelStr), null, miStr);

	if (delStr (gs, 3).GetType () != typeof (string []))
	    return 1;
	*/

	/*
	ArrDel ad = go.newDel ();
	if (ad (3).GetType () != typeof (object []))
	    return 1;

	ad = gs.newDel ();
	if (ad (3).GetType () != typeof (string []))
	    return 1;
	*/

	Console.WriteLine ("done");

	return 0;
    }
 private static Gen<Invariant> GenAnyInvariant(Gen<bool> pass)
 =>  from g in
         Gen.Frequency
           ( Tuple.Create(1, GenInvariant1(pass))
           , Tuple.Create(2, GenInvariantGroup(2, pass))
           )
     select g;
 private static Gen<Invariant> GenInvariantGroup
   ( int depth
   , Gen<bool> pass
   )
 =>  from n in Gen.Choose(1, 4)
     from inv in
         Gen.ArrayOf(n, Gen.Sized(s => GenGroup(depth, s, pass)))
     select "Group".All(inv);
 private static Gen<Invariant> GenGroup
   ( int depth
   , int s
   , Gen<bool> pass
   )
 =>  Gen.OneOf
       ( s > 0 && depth > 0
         ? new[]
           { Gen.Resize(s - 20, GenInvariantGroup(depth - 1, pass))
           , GenInvariant1(pass)
           }
         : new[] { GenInvariant1(pass) }
       );
 private static Gen<Invariant> GenInvariant1(Gen<bool> pass)
 =>  from p in pass
     from g in Gen.Constant(ConstantInvariant(p))
     select g;