public IronPython.Runtime.List Compare(Mat frame, PythonTuple offset1, PythonTuple offset2, PythonTuple size, int threshold = 64, int count = 5)
        {
            try
            {
                var areaLists = this.Compare(frame, new OpenCvSharp.Point((int)offset1[0], (int)offset1[1]), new OpenCvSharp.Point((int)offset2[0], (int)offset2[1]), new OpenCvSharp.Size((int)size[0], (int)size[1]), threshold, count);
                if (areaLists == null)
                {
                    throw new Exception();
                }

                var pythonAreaLists = new IronPython.Runtime.List();
                foreach (var areaList in areaLists)
                {
                    var pythonAreaList = new IronPython.Runtime.List();
                    foreach (var area in areaList)
                    {
                        var pythonArea = new PythonTuple(new object[] { area.X, area.Y, area.Width, area.Height });
                        pythonAreaList.Add(pythonArea);
                    }
                    pythonAreaLists.Add(pythonAreaList);
                }

                return(pythonAreaLists);
            }
            catch (Exception)
            {
                return(null);
            }
        }
    private void ExecutePythonSouce()
    {
        string WallList = GetWallStatus(robot.transform.position);

        using (StreamReader sr = new StreamReader(FilePath, System.Text.Encoding.UTF8))
        {
            script = sr.ReadToEnd();
        }
        scriptEngine = Python.CreateEngine();                               // Pythonスクリプト実行エンジン
        scriptScope  = scriptEngine.CreateScope();                          // 実行エンジンに渡す値を設定する
        scriptSource = scriptEngine.CreateScriptSourceFromString(script);   // Pythonのソースを設定

        scriptScope.SetVariable("PYTHON_LIB_PATH", PythonLibPath);
        scriptScope.SetVariable("ROBOTSTATE", robotState);
        scriptScope.SetVariable("preSONZAI", PreSONZAI);
        scriptScope.SetVariable("SONZAI", SONZAI);
        scriptScope.SetVariable("ACTION", action);
        scriptScope.SetVariable("WALL", WallList);
        scriptScope.SetVariable("tmpWALLS", WallsState);

        scriptSource.Execute(scriptScope);      // ソースを実行する

        PreSONZAI = scriptScope.GetVariable <IronPython.Runtime.List>("preSONZAI");
        SONZAI    = scriptScope.GetVariable <IronPython.Runtime.List>("SONZAI");

        canInput    = true;
        canViewProb = true;
    }
    void Astar()
    {
        using (StreamReader sr = new StreamReader(filename, System.Text.Encoding.UTF8))
        {
            script = sr.ReadToEnd();
        }
        scriptEngine = Python.CreateEngine();                             // Pythonスクリプト実行エンジン
        scriptScope  = scriptEngine.CreateScope();                        // 実行エンジンに渡す値を設定する
        scriptSource = scriptEngine.CreateScriptSourceFromString(script); // pythonのソースを指定

        // IronPythonで実装されているリスト
        var openlist = new IronPython.Runtime.List {
            "S"
        };
        var closedlist = new IronPython.Runtime.List {
        };

        // 初期状態をOpenListに入れ、Closedリストを空に初期化する
        scriptScope.SetVariable("OPENLIST", openlist);
        scriptScope.SetVariable("GOAL", "G");
        scriptScope.SetVariable("CLOSEDLIST", closedlist);

        scriptSource.Execute(scriptScope);              // ソースを実行する

        var Result = scriptScope.GetVariable <IronPython.Runtime.List>("CLOSEDLIST");

        // ロボットが移動します
        stateList = Result.Cast <string>().ToList();
        moveTheRobot();
    }
Exemplo n.º 4
0
        /// <summary>
        /// ItemCF推荐
        /// 给用户id为user_id的用户推荐电影
        /// </summary>
        /// <param name="user_id"></param>
        /// <returns></returns>
        public static ArrayList recommendItemCF(int user_id)
        {
            string        serverpath = pyScriptPath + "ItemCFRecommend.py";
            ScriptRuntime pyRuntime  = Python.CreateRuntime();
            ScriptEngine  Engine     = pyRuntime.GetEngine("python");

            ICollection <string> Paths = Engine.GetSearchPaths();

            Paths.Add("D:\\Anaconda2-32\\Lib");
            Paths.Add("D:\\Anaconda2-32\\DLLs");
            Paths.Add("D:\\Anaconda2-32\\Lib\\site-packages");

            Engine.SetSearchPaths(Paths);

            ScriptScope pyScope = Engine.CreateScope();

            dynamic pyScript = Engine.ExecuteFile(serverpath, pyScope);

            IronPython.Runtime.List user_item_list = getUserLikeItem(user_id);

            PythonDictionary similar_matrix = getItemSimilarityMatrix(user_item_list);


            IronPython.Runtime.List result = pyScript.recommend_item_cf(user_item_list, similar_matrix, 3);

            return(getRecommendMovie(result));
        }
Exemplo n.º 5
0
    // Returns a list of all MDbg commands defined in loaded python scripts or at the command line.
    private static List <IMDbgCommand> RescanPythonCommands()
    {
        object r = g_python.Evaluate("dir()");

        IronPython.Runtime.List namesList = r as IronPython.Runtime.List;
        if (namesList == null)
        {
            return(null);
        }

        List <IMDbgCommand> scannedCommands = new List <IMDbgCommand>();

        foreach (string name in namesList)
        {
            // test if it is an mdbg command
            try
            {
                r = g_python.Evaluate(string.Format("{0}.__doc__", name));
            }
            catch
            {
                r = null;
            }
            string       docString = r as string;
            IMDbgCommand mdbgCmd   = ParseCommandDocString(name, docString);
            if (mdbgCmd != null)
            {
                scannedCommands.Add(mdbgCmd);
            }
        }
        return(scannedCommands);
    }
    void FirstParticle()
    {
        startPosition = robot.transform.position;

        string script;
        string filename = Application.dataPath + "/../Python/Chapter9/ParticleFilter.py";

        using (StreamReader sr = new StreamReader(filename, System.Text.Encoding.UTF8))
        {
            script = sr.ReadToEnd();
        }
        // Pythonスクリプト実行エンジン
        scriptEngine = Python.CreateEngine();
        // 実行エンジンに渡す値を設定する
        scriptScope = scriptEngine.CreateScope();
        // pythonのソースを指定
        scriptSource = scriptEngine.CreateScriptSourceFromString(script);
        scriptScope.SetVariable("TimeCount", TrialCount);
        scriptScope.SetVariable("PA", PA);
        scriptScope.SetVariable("SIZE", SIZE);
        // Moderator.pyのソースを実行する
        scriptSource.Execute(scriptScope);

        PRTCL = scriptScope.GetVariable <IronPython.Runtime.List>("PRTCL");

        if (ParticleNumOn)
        {
            viewProb(PRTCL);
        }
        input = true;
    }
    void viewProb(IronPython.Runtime.List prob)
    {
        GameObject    moderator = GameObject.Find("GameObject");
        List <double> stateVal  = prob.Cast <double>().ToList();

        moderator.SendMessage("ViewProb", stateVal);
    }
Exemplo n.º 8
0
        /// <summary>
        /// 通过推荐列表中的movieId找到相关的电影的全部信息
        /// </summary>
        /// <param name="result"></param>
        /// <returns></returns>
        private static ArrayList getRecommendMovie(IronPython.Runtime.List result)
        {
            ArrayList recommendMovie = new ArrayList();

            for (int i = 0; i < result.Count; i++)
            {
                PythonTuple pySet = result.ElementAt(i) as PythonTuple;

                int movieId = (int)pySet.ElementAt(0);

                RecommendMovie rdMovie = new RecommendMovie();
                rdMovie.Similarity = (double)pySet.ElementAt(1);
                try
                {
                    rdMovie.Movie = MovieHelper.GetMovieById(movieId);
                }
                catch (Exception e)
                {
                    throw (e);
                }

                recommendMovie.Add(rdMovie);
            }

            return(recommendMovie);
        }
    void Start()
    {
        robot = GameObject.Find("RobotPy");

        walk  = false;
        input = false;

        ParticleNum   = GameObject.Find("ParticleNum").GetComponent <Toggle>();
        ParticleNumOn = ParticleNum.isOn;

        string script;
        string moderaterfile = Application.dataPath + "/../Python/Chapter9/Moderator.py";

        using (StreamReader sr = new StreamReader(moderaterfile, System.Text.Encoding.UTF8))
        {
            script = sr.ReadToEnd();
        }

        // Pythonスクリプト実行エンジン
        scriptEngine = Python.CreateEngine();
        // 実行エンジンに渡す値を設定する
        scriptScope = scriptEngine.CreateScope();
        // pythonのソースを指定
        scriptSource = scriptEngine.CreateScriptSourceFromString(script);
        // Moderator.pyのソースを実行する
        scriptSource.Execute(scriptScope);

        SIZE    = scriptScope.GetVariable <int>("SIZE");
        TRANS   = scriptScope.GetVariable <double>("TRANS");
        KANSOKU = scriptScope.GetVariable <double>("KANSOKU");
        PA      = scriptScope.GetVariable <int>("PA");
        WALLS   = scriptScope.GetVariable <IronPython.Runtime.List>("WALLS");
    }
Exemplo n.º 10
0
            private static NltkResultListString TokenizeCall(string funcName, string text)
            {
                IronPython.Runtime.List list = Call(funcName, text);

                return(new NltkResultListString()
                {
                    AsPython = list,
                });
            }
Exemplo n.º 11
0
        public static void PopulateWithNewMod(ModContentPack rwmodInfo)
        {
            var    path       = new ComparablePath(rwmodInfo.PythonFolder()); //will throw ex if rwmodInfo is null, which is fine
            string scriptPath = Path.Combine(path.reconstructedPath, "main.py");

            if (!Directory.Exists(path.ToString()) || !File.Exists(scriptPath))
            {
                return;
            }

            ScriptSource mainScriptSource = Py.Engine.CreateScriptSourceFromFile(scriptPath);
            string       packageName      = PythonMod.MakeHiddenPackageName(rwmodInfo.Identifier);

            PythonModManager inst = Instance; //getting this after several potential points of failure, to avoid pointless instantiation

            if (!inst.ordered.TrueForAll(m => m.rwmodInfo != rwmodInfo))
            {
                throw new ArgumentException(
                          "The mod with that ModContentPack has already been added");
            }

            //create and import package
            var pkg      = IronPython.Modules.PythonImport.new_module(DefaultContext.Default, packageName);
            var pkg_dict = (PythonDictionary)typeof(IronPython.Runtime.PythonModule).InvokeMember("_dict",
                                                                                                  BindingFlags.GetField | BindingFlags.NonPublic | BindingFlags.Instance,
                                                                                                  null, pkg, null);
            {
                var __path__ = new IronPython.Runtime.List();
                __path__.Add(path.reconstructedPath);
                pkg_dict["__path__"]       = __path__;
                pkg_dict["__file__"]       = scriptPath;
                SystemModules[packageName] = pkg;
            }

            //setup scope
            ScriptScope scope = Py.CreateScope();

            scope.SetVariable("__contentpack__", rwmodInfo);
            scope.GetModuleContext().AddExtensionType(typeof(StandardScriptingExtensions));

            // MAKE MOD OBJECT
            var mod = new PythonMod(rwmodInfo, packageName, scope, mainScriptSource);

            inst.ordered.Add(mod);

            //run main.py
            try
            {
                mainScriptSource.Execute(scope);
            }
            catch (Exception e)
            {
                string msg = "Exception while loading " + scriptPath + ": " + e.ToString() + "\n" + Py.GetFullErrorMessage(e);
                Verse.Log.Error(msg);
                pkg_dict["__error__"] = e;
            }
        }
Exemplo n.º 12
0
    private static void SetWords(IronPython.Runtime.List newWords)
    {
        List <IronPython.Runtime.PythonDictionary> dotNetWords = new List <IronPython.Runtime.PythonDictionary>();

        foreach (IronPython.Runtime.PythonDictionary word in newWords)
        {
            dotNetWords.Add(word);
        }
        SetWords(dotNetWords);
    }
Exemplo n.º 13
0
        public static Dictionary <T1, T2> ToNetDictionary <T1, T2>(IronPython.Runtime.List list)
        {
            Dictionary <T1, T2> result = new Dictionary <T1, T2>();

            foreach (PythonTuple item in list)
            {
                result.Add((T1)item[0], (T2)item[1]);
            }

            return(result);
        }
Exemplo n.º 14
0
        public static IronPython.Runtime.List ToIronPythonList <T>(this IEnumerable <T> list)
        {
            var result = new IronPython.Runtime.List();

            foreach (var item in list)
            {
                result.Add(item);
            }

            return(result);
        }
    private void GetProb()
    {
        List <float> stateVal = new List <float>();

        IronPython.Runtime.List tmp = new IronPython.Runtime.List();

        tmp = controller.PRTCL;

        var tmpList = tmp.Cast <double>().ToList();

        stateVal = tmpList.ConvertAll(x => (float)(double)x);
        ViewProb(stateVal);
    }
Exemplo n.º 16
0
    static void SetPyEnv(ScriptRuntime runtime, string pyscript, string[] args)
    {
        ScriptScope scope = Python.ImportModule(runtime, "sys");

        scope.SetVariable("version", "ironpython");

        IronPython.Runtime.List lst =
            (IronPython.Runtime.List)scope.GetVariable("argv");

        lst.Clear();
        lst.append(pyscript);
        foreach (string arg in args)
        {
            lst.append(arg);
        }
    }
Exemplo n.º 17
0
        public dynamic PassingParameterTest2()
        {
            ScriptEngine engine = Python.CreateEngine();
            ScriptScope  scope  = engine.CreateScope();

            List <string> calledStuff = new List <string>();

            engine.SetTrace(
                delegate(TraceBackFrame frame, string res, object payload)
            {
                if (frame.f_code == null)
                {
                    return(null);
                }

                switch (res)
                {
                case "call":
                    Console.WriteLine("Call: {0}", frame.f_code.co_name);
                    calledStuff.Add(frame.f_code.co_name);
                    break;

                case "return":
                    break;
                }

                return(null);
            }
                );

            string script = @"
class simple_class():
    def avg(self,a,b,c):
        return (a+b+c)/3

x = simple_class()
print x.avg(1,2,3)
";

            ScriptSource source = engine.CreateScriptSourceFromString(script, SourceCodeKind.Statements);

            source.Execute(scope);

            //Debug.Assert.IsTrue(calledStuff.Count > 0);
            return(calledStuff.Count);
        }
Exemplo n.º 18
0
    protected IronPython.Runtime.List Shuffled(System.Random rng, IronPython.Runtime.List list)
    {
        IronPython.Runtime.List list_copy = new IronPython.Runtime.List();
        foreach (var item in list)
        {
            list_copy.Add(item);
        }

        IronPython.Runtime.List returnList = new IronPython.Runtime.List();

        while (list_copy.Count > 0)
        {
            returnList.Add(list_copy.pop(rng.Next(list_copy.Count)));
        }

        return(returnList);
    }
Exemplo n.º 19
0
    protected Dictionary <string, IronPython.Runtime.List> BuildCategoryToWordDict(System.Random rng, IronPython.Runtime.List list)
    {
        Dictionary <string, IronPython.Runtime.List> categoriesToWords = new Dictionary <string, IronPython.Runtime.List>();
        int totalWordCount = list.Count;

        foreach (IronPython.Runtime.PythonDictionary item in list)
        {
            string category = (string)item["category"];
            if (!categoriesToWords.ContainsKey(category))
            {
                categoriesToWords[category] = new IronPython.Runtime.List();
            }
            categoriesToWords[category].Add(item);
            categoriesToWords[category] = Shuffled(rng, categoriesToWords[category]);
        }
        return(categoriesToWords);
    }
Exemplo n.º 20
0
 private Shotgun()
 {
     lock (this) {
         if (_pythonModule == null)
         {
             // Find out where our files are
             Assembly exAssembly  = System.Reflection.Assembly.GetExecutingAssembly();
             Uri      uriCodeBase = new Uri(exAssembly.CodeBase);
             String   installBase = Path.GetDirectoryName(uriCodeBase.LocalPath.ToString());
             // Initialize IronPython
             ScriptRuntime           ipy  = Python.CreateRuntime();
             IronPython.Runtime.List path = ipy.GetSysModule().GetVariable("path");
             // Point IronPython to our files
             path.append(Path.Combine(installBase, "Python", "PythonStatic.zip"));
             _pythonModule = ipy.UseFile(Path.Combine(installBase, "Python", "shotgun_config.py"));
         }
     }
 }
        public bool DrawRectangles(Mat frame, IronPython.Runtime.List areas, uint color = 0xffff0000)
        {
            try
            {
                var csAreaList = new List <OpenCvSharp.Rect>();
                foreach (var area in areas)
                {
                    var pythonArea = area as PythonTuple;
                    csAreaList.Add(new OpenCvSharp.Rect((int)pythonArea[0], (int)pythonArea[1], (int)pythonArea[2], (int)pythonArea[3]));
                }

                return(this.DrawRectangles(frame, csAreaList, color));
            }
            catch (Exception)
            {
                return(false);
            }
        }
Exemplo n.º 22
0
    void FromTheSecondTime()
    {
        TrialCount++;
        startPosition = robot.transform.position;

        string WallList = getWallStatus(startPosition);

        string script;
        string filename = Application.dataPath + "/../Python/Chapter8/BayesianFilter.py";

        using (StreamReader sr = new StreamReader(filename, System.Text.Encoding.UTF8))
        {
            script = sr.ReadToEnd();
        }
        // Pythonスクリプト実行エンジン
        scriptEngine = Python.CreateEngine();
        // 実行エンジンに渡す値を設定する
        scriptScope = scriptEngine.CreateScope();
        // pythonのソースを指定
        scriptSource = scriptEngine.CreateScriptSourceFromString(script);
        scriptScope.SetVariable("TimeCount", TrialCount);
        scriptScope.SetVariable("SIZE", SIZE);
        scriptScope.SetVariable("TRANS", TRANS);
        scriptScope.SetVariable("KANSOKU", KANSOKU);
        scriptScope.SetVariable("preSONZAI", preSONZAI);
        scriptScope.SetVariable("SONZAI", SONZAI);
        scriptScope.SetVariable("Colli", Colli);
        scriptScope.SetVariable("ACTION", action);
        scriptScope.SetVariable("WALL", WallList);
        scriptScope.SetVariable("tmpWALLS", WALLS);
        // Moderator.pyのソースを実行する
        scriptSource.Execute(scriptScope);

        preSONZAI = scriptScope.GetVariable <IronPython.Runtime.List>("preSONZAI");
        SONZAI    = scriptScope.GetVariable <IronPython.Runtime.List>("SONZAI");

        if (ExistenceProbabilityOn)
        {
            viewProb(SONZAI);
        }
        input = true;
    }
    private void GetProb()
    {
        List <float> stateVal = new List <float>();

        IronPython.Runtime.List tmp = new IronPython.Runtime.List();

        if (controller.robotState == "INITIAL")
        {
            tmp = controller.PreSONZAI;
        }
        else
        {
            tmp = controller.SONZAI;
        }

        var tmpList = tmp.Cast <double>().ToList();

        stateVal = tmpList.ConvertAll(x => (float)(double)x);
        ViewProb(stateVal);
    }
Exemplo n.º 24
0
        /// <summary>
        /// UserCF推荐
        /// 给用户id为user_id的用户推荐电影
        /// </summary>
        /// <param name="user_id"></param>
        /// <returns></returns>
        public static ArrayList recommendUserCF(int user_id)
        {
            PythonDictionary pyDic = null;

            try
            {
                pyDic = getUserItem(user_id);
            }
            catch (Exception e)
            {
                throw (e);
            }

            string        serverpath = pyScriptPath + "UserCFRecommend.py";
            ScriptRuntime pyRuntime  = Python.CreateRuntime();
            ScriptEngine  Engine     = pyRuntime.GetEngine("python");

            ICollection <string> Paths = Engine.GetSearchPaths();

            Paths.Add("D:\\Anaconda2-32\\Lib");
            Paths.Add("D:\\Anaconda2-32\\DLLs");
            Paths.Add("D:\\Anaconda2-32\\Lib\\site-packages");

            Engine.SetSearchPaths(Paths);

            ScriptScope pyScope = Engine.CreateScope();

            FileStream readStream = new FileStream(srcPath + "user_similar_matrix\\user_similar_matrix.txt", FileMode.Open, FileAccess.Read, FileShare.Read);

            BinaryFormatter formatter = new BinaryFormatter();

            PythonDictionary similar_matrix = (PythonDictionary)formatter.Deserialize(readStream);

            readStream.Close();

            dynamic pyScript = Engine.ExecuteFile(serverpath, pyScope);

            IronPython.Runtime.List result = pyScript.recommend_user_cf(user_id, pyDic, similar_matrix, 3);

            return(getRecommendMovie(result));
        }
Exemplo n.º 25
0
        /// <summary>
        /// pyItemList为与用户相关联的所有电影ID
        /// 找到这些电影与其他电影的相似矩阵,并拼接成一个总体的相似矩阵
        /// </summary>
        /// <param name="pyItemList"></param>
        /// <returns></returns>
        private static PythonDictionary getItemSimilarityMatrix(IronPython.Runtime.List pyItemList)
        {
            PythonDictionary pyDic = new PythonDictionary();

            for (int i = 0; i < pyItemList.Count; i++)
            {
                int itemId = (int)pyItemList.ElementAt(i);

                FileStream readStream = new FileStream(srcPath + "item_similar_matrix\\item" + itemId + "_similar_matrix.txt", FileMode.Open, FileAccess.Read, FileShare.Read);

                BinaryFormatter formatter = new BinaryFormatter();

                IronPython.Runtime.List similarityList = (List)formatter.Deserialize(readStream);

                readStream.Close();

                pyDic.Add(itemId, similarityList);
            }

            return(pyDic);
        }
Exemplo n.º 26
0
        public dynamic PassingParametersTest()
        {
            ScriptEngine engine = Python.CreateEngine();
            ScriptScope  scope  = engine.CreateScope();

            // define function

            string add = @"
def Add(a, b):
    return a + b
";

            // compile

            ScriptSource source   = engine.CreateScriptSourceFromString(add, SourceCodeKind.Statements);
            CompiledCode compiled = source.Compile();

            compiled.Execute(scope);

            // execute

            dynamic fAdd = scope.GetVariable("Add");

            dynamic result = engine.Operations.Invoke(fAdd, 2, 4);

            //Debug.Assert.IsTrue(result == 6);

            result = engine.Operations.Invoke(fAdd, "2", "4");
            //Debug.Assert.IsTrue(result == "24");

            var parameters = new List <object>();

            parameters.Add(2);
            parameters.Add(4);

            result = engine.Operations.Invoke(fAdd, parameters.ToArray());
            //Debug.Assert.IsTrue(result == 6);

            return(result);
        }
    void startDepthFirstSearch()
    {
        using (StreamReader sr = new StreamReader(depthFile, System.Text.Encoding.UTF8))
        {
            script = sr.ReadToEnd();
        }
        scriptEngine = Python.CreateEngine();                             // Pythonスクリプト実行エンジン
        scriptScope  = scriptEngine.CreateScope();                        // 実行エンジンに渡す値を設定する
        scriptSource = scriptEngine.CreateScriptSourceFromString(script); // pythonのソースを指定

        // IronPythonで実装されているリスト
        var openlist = new IronPython.Runtime.List {
            "S"
        };
        var closedlist = new IronPython.Runtime.List {
        };

        // 初期状態をOpenListに入れ、Closedリストを空に初期化する
        scriptScope.SetVariable("OPENLIST", openlist);
        scriptScope.SetVariable("GOAL", "G");
        scriptScope.SetVariable("CLOSEDLIST", closedlist);

        scriptSource.Execute(scriptScope);              // ソースを実行する

        var Result = scriptScope.GetVariable <IronPython.Runtime.List>("CLOSEDLIST");

        // ロボットが移動します
        stateList  = Result.Cast <string>().ToList();
        totalState = stateList.Count;
        if (totalState > 12)
        {
            UnityEngine.Debug.Log("smooth mode");
        }
        else
        {
            UnityEngine.Debug.Log("teleport mode");
        }
        moveTheRobot();
    }
Exemplo n.º 28
0
    protected IronPython.Runtime.List ReadWordsFromPoolTxt(string path, bool isCategoryPool)
    {
        string[] lines = GetWordpoolLines(path);
        IronPython.Runtime.List words = new IronPython.Runtime.List();

        for (int i = 0; i < lines.Length; i++)
        {
            IronPython.Runtime.PythonDictionary word = new IronPython.Runtime.PythonDictionary();
            if (isCategoryPool)
            {
                string   line = lines[i];
                string[] category_and_word = line.Split('\t');
                word["category"] = category_and_word[0];
                word["word"]     = category_and_word[1];
            }
            else
            {
                word["word"] = lines[i];
            }
            words.Add(word);
        }

        return(words);
    }
Exemplo n.º 29
0
 internal Interactive(SuiteStatement suite)
     : this() {
     _body = ConvertStatements(suite);
 }
Exemplo n.º 30
0
 public Assign(PythonList targets, expr value, [Optional]int? lineno, [Optional]int? col_offset)
     : this() {
     _targets = targets;
     _value = value;
     _lineno = lineno;
     _col_offset = col_offset;
 }
Exemplo n.º 31
0
 public ImportFrom(FromImportStatement stmt)
     : this() {
     _module = stmt.Root.MakeString();
     _module = string.IsNullOrEmpty(_module) ? null : _module;
     _names = ConvertAliases(stmt.Names, stmt.AsNames);
     if (stmt.Root is RelativeModuleName)
         _level = ((RelativeModuleName)stmt.Root).DotCount;
 }
Exemplo n.º 32
0
            internal Call(CallExpression call)
                : this() {
                _args = PythonOps.MakeEmptyList(call.Args.Count);
                _keywords = new PythonList();
                _func = Convert(call.Target);
                foreach (IronPython.Compiler.Ast.Arg arg in call.Args) {

                    if (arg.Name == null)
                        _args.Add(Convert(arg.Expression));
                    else if (arg.Name == "*")
                        _starargs = Convert(arg.Expression);
                    else if (arg.Name == "**")
                        _kwargs = Convert(arg.Expression);
                    else
                        _keywords.Add(new keyword(arg));
                }
            }
Exemplo n.º 33
0
    public static void ConfigureExperiment(ushort newWordsSeen, ushort newSessionNumber, IronPython.Runtime.List newWords = null)
    {
        wordsSeen = newWordsSeen;
        session   = newSessionNumber;
        settings  = FRExperimentSettings.GetSettingsByName(UnityEPL.GetExperimentName());
        bool isEvenNumberSession = newSessionNumber % 2 == 0;
        bool isTwoParter         = settings.isTwoParter;

        if (words == null)
        {
            SetWords(settings.wordListGenerator.GenerateListsAndWriteWordpool(settings.numberOfLists, settings.wordsPerList, settings.isCategoryPool, isTwoParter, isEvenNumberSession, UnityEPL.GetParticipants()[0]));
        }
        SaveState();
    }
Exemplo n.º 34
0
 internal comprehension(ComprehensionFor listFor, ComprehensionIf[] listIfs)
     : this() {
     _target = Convert(listFor.Left, Store.Instance);
     _iter = Convert(listFor.List);
     _ifs = PythonOps.MakeEmptyList(listIfs.Length);
     foreach (ComprehensionIf listIf in listIfs)
         _ifs.Add(Convert(listIf.Test));
 }
Exemplo n.º 35
0
 internal BoolOp(AndExpression and)
     : this() {
     _values = PythonOps.MakeListNoCopy(Convert(and.Left), Convert(and.Right));
     _op = And.Instance;
 }
Exemplo n.º 36
0
 internal While(WhileStatement stmt)
     : this() {
     _test = Convert(stmt.Test);
     _body = ConvertStatements(stmt.Body);
     _orelse = ConvertStatements(stmt.ElseStatement, true);
 }
Exemplo n.º 37
0
            internal static PythonList Convert(ComprehensionIterator[] iters) {
                PythonList comps = new PythonList();
                int start = 1;
                for (int i = 0; i < iters.Length; i++) {
                    if (i == 0 || iters[i] is ComprehensionIf)
                        if (i == iters.Length - 1)
                            i++;
                        else
                            continue;

                    ComprehensionIf[] ifs = new ComprehensionIf[i - start];
                    Array.Copy(iters, start, ifs, 0, ifs.Length);
                    comps.Add(new comprehension((ComprehensionFor)iters[start - 1], ifs));
                    start = i + 1;
                }
                return comps;
            }
Exemplo n.º 38
0
 internal TryFinally(PythonList body, PythonList finalbody)
     : this() {
     _body = body;
     _finalbody = finalbody;
 }
Exemplo n.º 39
0
            internal Print(PrintStatement stmt)
                : this() {
                if (stmt.Destination != null)
                    _dest = Convert(stmt.Destination);

                _values = PythonOps.MakeEmptyList(stmt.Expressions.Count);
                foreach (Compiler.Ast.Expression expr in stmt.Expressions)
                    _values.Add(Convert(expr));

                _nl = !stmt.TrailingComma;
            }
Exemplo n.º 40
0
 internal ListComp(ListComprehension comp)
     : this() {
     _elt = Convert(comp.Item);
     _generators = Convert(comp.Iterators);
 }
Exemplo n.º 41
0
 internal Compare(BinaryExpression expr, cmpop op)
     : this() {
     _left = Convert(expr.Left);
     _ops = PythonOps.MakeListNoCopy(op);
     _comparators = PythonOps.MakeListNoCopy(Convert(expr.Right));
 }
Exemplo n.º 42
0
 public static List <T> ToNetList <T>(this IronPython.Runtime.List list)
 => list.Cast <T>().ToList();
Exemplo n.º 43
0
 internal Module(SuiteStatement suite)
     : this() {
     _body = ConvertStatements(suite);
 }
Exemplo n.º 44
0
 internal Dict(DictionaryExpression expr)
     : this() {
     _keys = PythonOps.MakeEmptyList(expr.Items.Count);
     _values = PythonOps.MakeEmptyList(expr.Items.Count);
     foreach (SliceExpression item in expr.Items) {
         _keys.Add(Convert(item.SliceStart));
         _values.Add(Convert(item.SliceStop));
     }
 }
Exemplo n.º 45
0
            internal TryExcept(TryStatement stmt)
                : this() {
                _body = ConvertStatements(stmt.Body);

                _handlers = PythonOps.MakeEmptyList(stmt.Handlers.Count);
                foreach (TryStatementHandler tryStmt in stmt.Handlers)
                    _handlers.Add(Convert(tryStmt));

                _orelse = ConvertStatements(stmt.Else, true);
            }
Exemplo n.º 46
0
            internal ExceptHandler(TryStatementHandler stmt)
                : this() {
                if (stmt.Test != null)
                    _type = Convert(stmt.Test);
                if (stmt.Target != null)
                    _name = Convert(stmt.Target, Store.Instance);

                _body = ConvertStatements(stmt.Body);
            }
Exemplo n.º 47
0
            internal Tuple(TupleExpression list, expr_context ctx)
                : this() {
                _elts = PythonOps.MakeEmptyList(list.Items.Count);
                foreach (Compiler.Ast.Expression expr in list.Items)
                    _elts.Add(Convert(expr, ctx));

                _ctx = ctx;
            }
Exemplo n.º 48
0
 internal ExtSlice(PythonList dims)
     : this() {
     _dims = dims;
 }
Exemplo n.º 49
0
            internal With(WithStatement with)
                : this() {
                _context_expr = Convert(with.ContextManager);
                if (with.Variable != null)
                    _optional_vars = Convert(with.Variable);

                _body = ConvertStatements(with.Body);
            }
Exemplo n.º 50
0
 internal For(ForStatement stmt)
     : this() {
     _target = Convert(stmt.Left, Store.Instance);
     _iter = Convert(stmt.List);
     _body = ConvertStatements(stmt.Body);
     _orelse = ConvertStatements(stmt.Else, true);
 }
Exemplo n.º 51
0
 internal arguments(IList<Parameter> parameters)
     : this() {
     _args = PythonOps.MakeEmptyList(parameters.Count);
     _defaults = PythonOps.MakeEmptyList(parameters.Count);
     foreach (Parameter param in parameters) {
         if (param.IsList)
             _vararg = param.Name;
         else if (param.IsDictionary)
             _kwarg = param.Name;
         else {
             args.Add(new Name(param.Name, Param.Instance));
             if (param.DefaultValue != null)
                 defaults.Add(Convert(param.DefaultValue));
         }
     }
 }
Exemplo n.º 52
0
            internal FunctionDef(FunctionDefinition def)
                : this() {
                _name = def.Name;
                _args = new arguments(def.Parameters);
                _body = ConvertStatements(def.Body);

                if (def.Decorators != null) {
                    _decorators = PythonOps.MakeEmptyList(def.Decorators.Count);
                    foreach (Compiler.Ast.Expression expr in def.Decorators)
                        _decorators.Add(Convert(expr));
                } else
                    _decorators = PythonOps.MakeEmptyList(0);
            }
Exemplo n.º 53
0
            internal Assign(AssignmentStatement stmt)
                : this() {
                _targets = PythonOps.MakeEmptyList(stmt.Left.Count);
                foreach (Compiler.Ast.Expression expr in stmt.Left)
                    _targets.Add(Convert(expr, Store.Instance));

                _value = Convert(stmt.Right);
            }
Exemplo n.º 54
0
 internal GeneratorExp(GeneratorExpression expr)
     : this() {
     ExtractListComprehensionIterators walker = new ExtractListComprehensionIterators();
     expr.Function.Body.Walk(walker);
     ComprehensionIterator[] iters = walker.Iterators;
     Debug.Assert(iters.Length != 0, "A generator expression cannot have zero iterators.");
     iters[0] = new ComprehensionFor(((ComprehensionFor)iters[0]).Left, expr.Iterable);
     _elt = Convert(walker.Yield.Expression);
     _generators = Convert(iters);
 }
Exemplo n.º 55
0
 internal BoolOp(OrExpression or)
     : this() {
     _values = PythonOps.MakeListNoCopy(Convert(or.Left), Convert(or.Right));
     _op = Or.Instance;
 }
Exemplo n.º 56
0
 internal Global(GlobalStatement stmt)
     : this() {
     _names = new PythonList(stmt.Names);
 }
Exemplo n.º 57
0
 internal ClassDef(ClassDefinition def)
     : this() {
     _name = def.Name;
     _bases = PythonOps.MakeEmptyList(def.Bases.Count);
     foreach (Compiler.Ast.Expression expr in def.Bases)
         _bases.Add(Convert(expr));
     _body = ConvertStatements(def.Body);
     _decorator_list = new PythonList(); // TODO Actually fill in the decorators here
 }
Exemplo n.º 58
0
 internal void Initialize(IfStatementTest ifTest) {
     _test = Convert(ifTest.Test);
     _body = ConvertStatements(ifTest.Body);
 }
Exemplo n.º 59
0
 internal Delete(DelStatement stmt)
     : this() {
     _targets = PythonOps.MakeEmptyList(stmt.Expressions.Count);
     foreach (Compiler.Ast.Expression expr in stmt.Expressions)
         _targets.Add(Convert(expr, Del.Instance));
 }
Exemplo n.º 60
0
 internal Import(ImportStatement stmt)
     : this() {
     _names = ConvertAliases(stmt.Names, stmt.AsNames);
 }