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); } }
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; } }
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); }
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); }
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); }
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); }
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); }
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; }
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; }
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); }
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; }
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); }
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)); } }
public IronPython.Runtime.List GenerateListsOptionalCategory(int numberOfLists, int lengthOfEachList, bool isCategoryPool, System.Random rng, bool isTwoParter, bool isEvenNumberSession, string participantCode) { //////////////////////Load the python wordpool code Microsoft.Scripting.Hosting.ScriptScope scope = BuildPythonScope(); //////////////////////Load the word pool IronPython.Runtime.List all_words; if (isCategoryPool) { all_words = ReadWordsFromPoolTxt("ram_categorized_en", isCategoryPool); } else { all_words = ReadWordsFromPoolTxt("ram_wordpool_en", isCategoryPool); } //////////////////////For two part experiments, reliably shuffle according to participant name and construct halves, then shuffle again /// Otherwise, just shuffle if (isTwoParter) { System.Random reliable_random = new System.Random(participantCode.GetHashCode()); if (!isCategoryPool) { all_words = Shuffled(reliable_random, all_words); } else { all_words = CategoryShuffle(reliable_random, all_words, 12); } if (isEvenNumberSession) { all_words = (IronPython.Runtime.List)all_words.__getslice__(0, all_words.Count / 2); } else { all_words = (IronPython.Runtime.List)all_words.__getslice__(all_words.Count / 2, all_words.Count); } } if (isCategoryPool) { all_words = CategoryShuffle(rng, all_words, lengthOfEachList); } else { all_words = Shuffled(rng, all_words); } ////////////////////////////////////////////Call list creation functions from python //////////////////////Concatenate into lists with numbers var assign_list_numbers_from_word_list = scope.GetVariable("assign_list_numbers_from_word_list"); var words_with_listnos = assign_list_numbers_from_word_list(all_words, numberOfLists); //////////////////////Build type lists and assign tpyes IronPython.Runtime.List stim_nostim_list = new IronPython.Runtime.List(); for (int i = 0; i < STIM_LIST_COUNT; i++) { stim_nostim_list.Add("STIM"); } for (int i = 0; i < NONSTIM_LIST_COUNT; i++) { stim_nostim_list.Add("NON-STIM"); } stim_nostim_list = Shuffled(rng, stim_nostim_list); var assign_list_types_from_type_list = scope.GetVariable("assign_list_types_from_type_list"); var words_with_types = assign_list_types_from_type_list(words_with_listnos, BASELINE_LIST_COUNT, stim_nostim_list, num_ps: PS_LIST_COUNT); //////////////////////Build stim channel lists and assign stim channels IronPython.Runtime.List stim_channels_list = new IronPython.Runtime.List(); for (int i = 0; i < A_STIM_COUNT; i++) { stim_channels_list.Add(new IronPython.Runtime.PythonTuple(new int[] { 0 })); } for (int i = 0; i < B_STIM_COUNT; i++) { stim_channels_list.Add(new IronPython.Runtime.PythonTuple(new int[] { 1 })); } for (int i = 0; i < AB_STIM_COUNT; i++) { stim_channels_list.Add(new IronPython.Runtime.PythonTuple(new int[] { 0, 1 })); } stim_channels_list = Shuffled(rng, stim_channels_list); var assign_multistim_from_stim_channels_list = scope.GetVariable("assign_multistim_from_stim_channels_list"); var words_with_stim_channels = assign_multistim_from_stim_channels_list(words_with_types, stim_channels_list); ////////////////////Build amplitude index list and assign amplitude indeces IronPython.Runtime.List amplitude_index_list = new IronPython.Runtime.List(); int lists_per_amplitude_index = 0; if (AMPLITUDE_COUNT != 0) { lists_per_amplitude_index = STIM_LIST_COUNT / AMPLITUDE_COUNT; } for (int amplitude_index = 0; amplitude_index < AMPLITUDE_COUNT; amplitude_index++) { for (int i = 0; i < lists_per_amplitude_index; i++) { amplitude_index_list.Add(amplitude_index); } } amplitude_index_list = Shuffled(rng, amplitude_index_list); var assign_amplitudes_from_amplitude_index_list = scope.GetVariable("assign_amplitudes_from_amplitude_index_list"); var words_with_amplitude_indices = assign_amplitudes_from_amplitude_index_list(words_with_stim_channels, amplitude_index_list); return(words_with_amplitude_indices); }
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)); } }
internal static PythonList Convert(ComprehensionIterator[] iters) { Generic.List<ComprehensionFor> cfCollector = new Generic.List<ComprehensionFor>(); Generic.List<Generic.List<ComprehensionIf>> cifCollector = new Generic.List<Generic.List<ComprehensionIf>>(); Generic.List<ComprehensionIf> cif = null; for (int i = 0; i < iters.Length; i++) { if (iters[i] is ComprehensionFor) { ComprehensionFor cf = (ComprehensionFor)iters[i]; cfCollector.Add(cf); cif = new Generic.List<ComprehensionIf>(); cifCollector.Add(cif); } else { ComprehensionIf ci = (ComprehensionIf)iters[i]; cif.Add(ci); } } PythonList comps = new PythonList(); for (int i = 0; i < cfCollector.Count; i++) comps.Add(new comprehension(cfCollector[i], cifCollector[i].ToArray())); return comps; }
internal Set(SetExpression setExpression) : this() { _elts = new PythonList(setExpression.Items.Count); foreach (AstExpression item in setExpression.Items) { _elts.Add(Convert(item)); } }
internal Compare(BinaryExpression expr) : this() { _left = Convert(expr.Left); _ops = PythonOps.MakeList(); _comparators = PythonOps.MakeList(); while (BinaryExpression.IsComparison(expr.Right)) { BinaryExpression right = (BinaryExpression)expr.Right; // start accumulating ops and comparators _ops.Add(Convert(expr.Operator)); _comparators.Add(Convert(right.Left)); expr = right; } _ops.Add(Convert(expr.Operator)); _comparators.Add(Convert(expr.Right)); }
internal ClassDef(ClassDefinition def) : this() { _name = def.Name; _bases = PythonOps.MakeEmptyList(def.Bases.Count); foreach (AstExpression expr in def.Bases) _bases.Add(Convert(expr)); _body = ConvertStatements(def.Body); if (def.Decorators != null) { _decorator_list = PythonOps.MakeEmptyList(def.Decorators.Count); foreach (AstExpression expr in def.Decorators) _decorator_list.Add(Convert(expr)); } else _decorator_list = PythonOps.MakeEmptyList(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)); }
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); }
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)); }
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 }
/// <summary> /// Requires that the words in the list have a category entry and that categories have some multiple of four words in each of them. /// /// Shuffles into lists of 12 words appended without delineation to the return list. /// </summary> /// <returns>The shuffled list of words.</returns> /// <param name="rng">Rng.</param> /// <param name="list">List.</param> /// <param name="lengthOfEachList">Length of each list.</param> protected IronPython.Runtime.List CategoryShuffle(System.Random rng, IronPython.Runtime.List list, int lengthOfEachList) { if (lengthOfEachList != 12) { throw new UnityException("Currently only lists of 12 words are supported by CatFR."); } /////////////in order to select words from appropriate categories, build a dict with categories as keys and a list of words as values Dictionary <string, IronPython.Runtime.List> categoriesToWords = BuildCategoryToWordDict(rng, list); /////////////we will append words to this in the proper order and then return it IronPython.Runtime.List returnList = new IronPython.Runtime.List(); bool finished = false; int iterations = 0; do { iterations++; if (iterations > 1000) { finished = true; throw new UnityException("Error while shuffle catFR list"); } ////////////if there are less than three categories remaining, we are on the last list and can't complete it validly ////////////this is currently handled by simply trying the whole process again if (categoriesToWords.Count < 3) { //start over categoriesToWords = BuildCategoryToWordDict(rng, list); returnList = new IronPython.Runtime.List(); continue; } List <string> keyList = new List <string>(categoriesToWords.Keys); //////////find three random unique categories string randomCategoryA = keyList[rng.Next(keyList.Count)]; string randomCategoryB; do { randomCategoryB = keyList[rng.Next(keyList.Count)]; }while (randomCategoryB.Equals(randomCategoryA)); string randomCategoryC; do { randomCategoryC = keyList[rng.Next(keyList.Count)]; }while (randomCategoryC.Equals(randomCategoryA) | randomCategoryC.Equals(randomCategoryB)); //////////get four words from each of these categories IronPython.Runtime.List groupA = new IronPython.Runtime.List(); IronPython.Runtime.List groupB = new IronPython.Runtime.List(); IronPython.Runtime.List groupC = new IronPython.Runtime.List(); for (int i = 0; i < 4; i++) { groupA.Add(categoriesToWords[randomCategoryA].pop()); } for (int i = 0; i < 4; i++) { groupB.Add(categoriesToWords[randomCategoryB].pop()); } for (int i = 0; i < 4; i++) { groupC.Add(categoriesToWords[randomCategoryC].pop()); } //////////remove categories from dict if all 12 words have been used if (categoriesToWords[randomCategoryA].Count == 0) { categoriesToWords.Remove(randomCategoryA); } if (categoriesToWords[randomCategoryB].Count == 0) { categoriesToWords.Remove(randomCategoryB); } if (categoriesToWords[randomCategoryC].Count == 0) { categoriesToWords.Remove(randomCategoryC); } //////////integers 0, 1, 2, 0, 1, 2 representing the order in which to present pairs of words from categories (A == 1, B == 2, etc.) //////////make sure to fulfill the requirement that both halves have ABC and the end of the first half is not the beginning of the second IronPython.Runtime.List groups = new IronPython.Runtime.List(); for (int i = 0; i < 3; i++) { groups.Add(i); } groups = Shuffled(rng, groups); int index = 0; int first_half_last_item = 0; foreach (int item in groups) { if (index == 2) { first_half_last_item = item; } index++; } IronPython.Runtime.List secondHalf = new IronPython.Runtime.List(); for (int i = 0; i < 3; i++) { secondHalf.Add(i); } secondHalf.Remove(first_half_last_item); secondHalf = Shuffled(rng, secondHalf); bool insertAtEnd = rng.Next(2) == 0; if (insertAtEnd) { secondHalf.Insert(secondHalf.Count, first_half_last_item); } else { secondHalf.Insert(secondHalf.Count - 1, first_half_last_item); } foreach (int item in secondHalf) { groups.append(item); } //////////append words to the final list according to the integers gotten above foreach (int groupNo in groups) { if (groupNo == 0) { returnList.append(groupA.pop()); returnList.append(groupA.pop()); } if (groupNo == 1) { returnList.append(groupB.pop()); returnList.append(groupB.pop()); } if (groupNo == 2) { returnList.append(groupC.pop()); returnList.append(groupC.pop()); } } //////////if there are no more categories left, we're done if (categoriesToWords.Count == 0) { finished = true; } }while (!finished); return(returnList); }