private void InitializePython() { if (string.IsNullOrEmpty(SelectedScript)) { return; } var engine = IronPython.Hosting.Python.CreateEngine(); var script = ScriptsLocation + SelectedScript; var source = engine.CreateScriptSourceFromFile(script); var eIO = engine.Runtime.IO; var errors = new MemoryStream(); eIO.SetErrorOutput(errors, Encoding.Default); var results = new MemoryStream(); eIO.SetOutput(results, Encoding.Default); var scope = engine.CreateScope(); source.Execute(scope); IronPython.Runtime.List vars = scope.GetVariable("arguments"); foreach (var arg in vars) { MessageBox.Show(arg.ToString()); } }
private void button2_Click(object sender, EventArgs e) { ScriptRuntime pyRuntime = Python.CreateRuntime(); dynamic obj = pyRuntime.UseFile(@"recommend.py"); IronPython.Runtime.List mustlst = new IronPython.Runtime.List(); IronPython.Runtime.List wantlst = new IronPython.Runtime.List(); foreach (int i in index_must) { mustlst.Add(i); } foreach (int i in index_want) { wantlst.Add(i); } string result = obj.getPeople(mustlst, wantlst); purl = obj.getUrl(mustlst, wantlst); pname = result; MessageBox.Show("为你推荐:" + pname); People infofr = new People(pname, purl); infofr.Show(); }
private static void TestNltkResultClass() { var corpus = new Nltk.Corpus.Inaugural(); // example of using NltkResult class var fileidsResult = corpus.FileIds(); List <string> fileidsNet = fileidsResult.AsNet; // Get .NET List<string> IronPython.Runtime.List fileidsPython = fileidsResult.AsPython; // Get IronPython.Runtime.List dynamic fileids = fileidsResult; // Cast to Dynamic to access object fields in Python-like style // using DynamicObject Console.WriteLine(fileids[0]); Console.WriteLine(fileids.__len__()); // access sentences (list of list of strings) var sentencesResult = corpus.Sents(); dynamic sentences = sentencesResult; Console.WriteLine(sentences[0][0]); // Manipulating with Python object: first word in first sentense List <List <string> > netSentences = sentencesResult.AsNet; Console.WriteLine(netSentences[0][0]); // the same with .NET object Console.WriteLine(netSentences.First().First()); // using LINQ }
public ILArray(IronPython.Runtime.List list) { List <int> size = new List <int>(); Type type = typeof(double); PythonListHelper.GetListDimensionsAndType(ref size, list, ref type); if (!PythonListHelper.CheckList(ref size, list, 0, ref type)) { throw new ArgumentException("List is not rectangular or not of constant type!"); } if (type != typeof(BaseT)) { throw new ArgumentException("Array type does not match list type!"); } try { m_dimensions = new ILDimension(true, size.ToArray()); bool dummy; m_data = ILMemoryPool.Pool.New <BaseT>(m_dimensions.NumberOfElements, true, out dummy); m_name = ""; IncreaseReference(); } catch (Exception e) { throw new Exception("Error creating new ILArray object.", e); } int[] indices = new int[size.Count]; FillILArrayFromList <BaseT>(ref size, list, 0, ref type, ref m_data, 0, 1); }
public List <string> add_songs_to_playlist(string playlist_id, List <string> song_ids) { var pySongs_IDs = song_ids.AsPyList(); IronPython.Runtime.List tmp = pyMobileclient.add_songs_to_playlist(playlist_id, pySongs_IDs); return(tmp.ToList <string>()); }
public List <RadioStation> get_all_stations(bool incremental = false, bool include_deleted = false, DateTime updated_after = default(DateTime)) { dynamic pyDateTime = pyConvDateTime(updated_after); IronPython.Runtime.List tmp = pyMobileclient.get_all_stations(incremental, include_deleted, pyDateTime); return(tmp.ToList <RadioStation>()); }
public static IronPython.Runtime.List ComplexArray_to_List(ComplexF[] complex_array) { IronPython.Runtime.List l = new IronPython.Runtime.List(); System.Threading.Tasks.Parallel.ForEach(complex_array, item => { l.append(new System.Numerics.Complex(item.Re, item.Im)); }); return(l); }
public List <string> remove_entries_from_playlist(List <string> entry_ids) { //throw new NotImplementedException(); //TODO convert to python List var pyEntry_IDs = entry_ids.AsPyList(); IronPython.Runtime.List tmp = pyMobileclient.remove_entries_from_playlist(pyEntry_IDs); return(tmp.ToList <string>()); }
internal static IronPython.Runtime.List ComplexArray_to_List(ComplexF[] complex_array) { IronPython.Runtime.List l = new IronPython.Runtime.List(); foreach (var item in complex_array) { l.append(new System.Numerics.Complex(item.Re,item.Im)); } return l; }
private void SetupArguments(ScriptEngine engine, List <string> arguments) { // setup arguments (sets sys.argv) // engine.Setup.Options["Arguments"] = arguments; // engine.Runtime.Setup.HostArguments = new List<object>(arguments); var sysmodule = engine.GetSysModule(); var pythonArgv = new IronPython.Runtime.List(); pythonArgv.extend(arguments); sysmodule.SetVariable("argv", pythonArgv); }
public static void GetListDimensionsAndType(ref List <int> size, IronPython.Runtime.List list, ref Type type) { size.Add(list.Count); if (list[0] is IronPython.Runtime.List) { IronPython.Runtime.List newList = (IronPython.Runtime.List)list[0]; GetListDimensionsAndType(ref size, newList, ref type); } else { type = list[0].GetType(); } }
private void addListDictionary(string type, int startPosition, Dictionary <int, List <string> > otherParamDictionary) { int index = int.Parse(type.Substring(startPosition, 1)); IronPython.Runtime.List templateArgsList = aiAction[type] as IronPython.Runtime.List; List <string> templateArgsTempList = new List <string>(); for (int i = 0; i < templateArgsList.Count; ++i) { templateArgsTempList.Add(templateArgsList[i].ToString()); } otherParamDictionary[index] = templateArgsTempList; }
private void SetupArguments(ref ScriptRuntime runtime) { // setup arguments (sets sys.argv) // engine.Setup.Options["Arguments"] = arguments; // engine.Runtime.Setup.HostArguments = new List<object>(arguments); var sysmodule = Engine.GetSysModule(); var pythonArgv = new IronPython.Runtime.List(); // for python make sure the first argument is the script pythonArgv.append(runtime.ScriptSourceFile); pythonArgv.extend(runtime.ScriptRuntimeConfigs.Arguments); sysmodule.SetVariable("argv", pythonArgv); }
/// <summary> /// 获取玩家未结束的任务 /// </summary> /// <returns></returns> public virtual List <T> Get(int currTaskId) { List <T> taskList = new List <T>(); if (_isUsedPy) { IronPython.Runtime.List list = _taskScope.get(UserId, currTaskId); foreach (var item in list) { taskList.Add((T)item); } } return(taskList); }
public string[] GetCollectionsList() { IronPython.Runtime.List CollectionsList = appCore.GetCollectionsList(); string[] FileNames = new string[CollectionsList.__len__()]; int i = 0; foreach (var CurrKey in CollectionsList) { FileNames[i] = CurrKey as string; i++; } return(FileNames); }
public string[] GetTagsList() { IronPython.Runtime.List TagsCollection = appCore.GetTagsList(); string[] FileTags = new string[TagsCollection.__len__()]; int i = 0; foreach (var CurrKey in TagsCollection) { FileTags[i] = CurrKey as string; i++; } return(FileTags); }
public static double[] PyToNET(object arg) { double[] ans = new double[0]; if (arg.GetType() == typeof(IronPython.Runtime.List)) { IronPython.Runtime.List lst = (IronPython.Runtime.List)arg; ans = new double[lst.Count]; for (int i = 0; i < lst.Count; i++) { ans[i] = double.Parse(lst[i].ToString()); } return(ans); } return(null); }
public string[] GetFilesList() { IronPython.Runtime.List FilesCollection = appCore.QueryAllFiles(); string [] FileNames = new string[FilesCollection.__len__()]; int i = 0; foreach (var CurrKey in FilesCollection) { FileNames[i] = CurrKey as string; i++; } return(FileNames); }
public static String[] VoiceIdentCall(String called_number, String ident_code) { String[] ret = new String[10]; try{ var voiceidentcall = scope.GetVariable <Func <Object, Object, Object> > ("voice_ident_call"); IronPython.Runtime.List result = (IronPython.Runtime.List)voiceidentcall(called_number, ident_code); if (result != null) { result.CopyTo(ret, 0); } } catch (Exception ex) { Logger.Fatal("PythonEnginer", "VoiceIdentCall", "exception was happended!!!", ex); } return(ret); }
public static String[] OriginateCall(String caller_number, String called_number) { String[] ret = new String[10]; try{ var originatecall = scope.GetVariable <Func <Object, Object, Object> > ("double_call"); IronPython.Runtime.List result = (IronPython.Runtime.List)originatecall(caller_number, called_number); if (result != null) { result.CopyTo(ret, 0); } } catch (Exception ex) { Logger.Fatal("PythonEnginer", "DoubleCall", "exception was happended!!!", ex); } return(ret); }
internal static void FillILArrayFromList <BaseT>(ref List <int> size, IronPython.Runtime.List list, int dimension, ref Type type, ref BaseT[] m_data, int index, int stride) { for (int i = 0; i < list.Count; ++i) { if (list[i] is IronPython.Runtime.List) { IronPython.Runtime.List newList = (IronPython.Runtime.List)list[i]; FillILArrayFromList <BaseT>(ref size, newList, dimension + 1, ref type, ref m_data, index, stride * size[dimension]); index += stride; } else { m_data[index] = (BaseT)Convert.ChangeType(list[i], typeof(BaseT)); index += stride; } } }
public override void Execute(EventDescription token) { if (code == "") { code = "None"; } for (int i = 0; i < input_count; i++) { AppGlobals.PySetVar("in" + (i + 1).ToString(), InputNodes[i].Object); } object result = null; AppGlobals.PyExecute(code, Microsoft.Scripting.SourceCodeKind.Statements); for (int i = 0; i < output_count; i++) { var name = "out" + (i + 1).ToString(); if (AppGlobals.PyVarExists(name)) { result = AppGlobals.PyGetVar(name); if (result.GetType() == typeof(IronPython.Runtime.List)) { IronPython.Runtime.List lst = (IronPython.Runtime.List)result; //var tmp = new List<object>(); //foreach (var item in lst) //{ // tmp.Add(item); //} result = lst;// tmp.ToArray(); } var tmp = PyToNET(result); if (tmp != null) { OutputNodes[i].Object = (double[])tmp; } else { OutputNodes[i].Object = result; } } AppGlobals.PyRemVar(name); } for (int i = 0; i < input_count; i++) { AppGlobals.PyRemVar("in" + (i + 1).ToString()); } }
public static bool CheckList(ref List <int> size, IronPython.Runtime.List list, int dimension, ref Type type) { bool passed = true; if (list.Count != size[dimension]) { return(false); } if (dimension < (size.Count - 1)) { for (int i = 0; i < list.Count; ++i) { if (list[i] is IronPython.Runtime.List) { IronPython.Runtime.List newList = (IronPython.Runtime.List)list[i]; passed = passed && CheckList(ref size, newList, dimension + 1, ref type); } else { passed = false; break; } } } else { for (int i = 0; i < list.Count; ++i) { if (list[i].GetType() != type) { // allow a mixture of integers and doubles, but set type to double if ((type == typeof(Int32)) && (list[i].GetType() == typeof(Double))) { type = typeof(Double); } else if (!((type == typeof(Double)) && (list[i].GetType() == typeof(Int32)))) { passed = false; break; } } } } return(passed); }
public string[] QueryFiles(string TagName) { IronPython.Runtime.List TagsCollection = appCore.QueryFiles(TagName); if (TagsCollection == null) { return(null); } string[] FileNames = new string[TagsCollection.__len__()]; int i = 0; foreach (var CurrKey in TagsCollection) { FileNames[i] = CurrKey as string; i++; } return(FileNames); }
public static List <T> ToList <T>(this IronPython.Runtime.List source) where T : class { T someObject = New <T> .Instance(); List <T> someList = new List <T>(); Type someObjectType = someObject.GetType(); foreach (var item in source) { T newValue = null; try { if (item.GetType() == typeof(IronPython.Runtime.List)) { MethodInfo method = typeof(ObjectExtensions).GetMethod("ToList"); MethodInfo generic = method.MakeGenericMethod(someObjectType.GenericTypeArguments[0]); newValue = (T)generic.Invoke(null, new object[] { (IronPython.Runtime.PythonDictionary)item }); } else if (item.GetType() == typeof(IronPython.Runtime.PythonDictionary)) { MethodInfo method = typeof(ObjectExtensions).GetMethod("ToObject"); MethodInfo generic = method.MakeGenericMethod(someObjectType); newValue = (T)generic.Invoke(null, new object[] { (IronPython.Runtime.PythonDictionary)item }); } else { newValue = (T)item; } someList.Add(newValue); } catch (Exception ex) { Console.WriteLine("Unable to add:" + newValue.ToString()); Console.WriteLine(ex.Message); } } return(someList); }
public static ComplexF[] List_to_ComplexArray(IronPython.Runtime.List list_object) { ComplexF[] _fft = new ComplexF[list_object.Count]; System.Threading.Tasks.Parallel.For(0, _fft.Length, i => { try { if (list_object[i].GetType() == typeof(System.Numerics.Complex)) { System.Numerics.Complex c = (System.Numerics.Complex)list_object[i]; _fft[i] = new ComplexF((float)c.Real, (float)c.Imaginary); } else { _fft[i] = new ComplexF(float.Parse(list_object[i].ToString()), 0); } } catch (Exception) { throw; } }); return(_fft); }
public void ReDrawDiagram(string index) { int id = int.Parse(index); AIInitParams["id"] = index; var ipy = Python.CreateRuntime(); dynamic test = ipy.UseFile("Code\\monster_ai_data.py"); IronPython.Runtime.PythonDictionary data = test.data; aiAction = data[id] as IronPython.Runtime.PythonDictionary; init(); IronPython.Runtime.List Trigger = aiAction["trigger"] as IronPython.Runtime.List; triggerName = Convert.ToString(Trigger[0]); for (int i = 1; i < Trigger.Count; ++i) { triggerParamList.Add(Convert.ToString(Trigger[i])); } foreach (var key in aiAction.Keys) { SelectDictionary(Convert.ToString(key)); } }
private void button2_Click(object sender, EventArgs e) { ScriptRuntime pyRuntime = Python.CreateRuntime(); dynamic obj = pyRuntime.UseFile(@"cities.py"); IronPython.Runtime.List hadlst = new IronPython.Runtime.List(); foreach (int i in index_had) { hadlst.Add(i); } string result = obj.getPeople(hadlst); iurl = obj.getUrl(hadlst); iname = result; MessageBox.Show("为你推荐:" + iname); People infofr = new People(iname, iurl); infofr.Show(); }
/// <summary> /// Convert IronPython List into ILBaseArray /// </summary> /// <param name="list">IronPython List (must be filled with Python ints or floats)</param> /// <returns>ILBaseArray</returns> public static ILBaseArray array(IronPython.Runtime.List list) { List <int> size = new List <int>(); Type type = typeof(double); PythonListHelper.GetListDimensionsAndType(ref size, list, ref type); if (!PythonListHelper.CheckList(ref size, list, 0, ref type)) { throw new ArgumentException("List is not rectangular or not of constant type!"); } if (type == typeof(Double)) { return(new ILArray <Double>(list)); } else if (type == typeof(Int32)) { return(new ILArray <Int32>(list)); } else { throw new ArgumentException("List type is not int or float"); } }
public static IronPython.Runtime.List AsPyList(this IList source) { var pyList = new IronPython.Runtime.List(); Type someObjectType = source.GetType(); foreach (var item in source) { object newValue = null; try { if ((item.GetType().GetInterfaces().Contains(typeof(System.Collections.IList)))) { MethodInfo method = typeof(ObjectExtensions).GetMethod("AsPyList"); MethodInfo generic = method.MakeGenericMethod(someObjectType.GenericTypeArguments[0]); newValue = generic.Invoke(null, new object[] { item }); } else if (item.GetType().Namespace == typeof(ObjectExtensions).Namespace) { MethodInfo method = typeof(ObjectExtensions).GetMethod("AsPyDictionary"); newValue = method.Invoke(null, new object[] { item }); } else { newValue = item; } pyList.Add(newValue); } catch (Exception ex) { Console.WriteLine("Unable to add:" + newValue.ToString()); Console.WriteLine(ex.Message); } } return(pyList); }
public IronPython.Runtime.List this[IronPython.Runtime.Slice xslice, IronPython.Runtime.Slice yslice] { get { if ((xslice.start == null) || (xslice.stop == null) || (yslice.start == null) || (yslice.stop == null)) { throw new ILArgumentException("mgrid: start and stop of slices must be provided"); } double xStep = 1, yStep = 1, xStart = 0, yStart = 0, xStop = 1, yStop = 1; // if (xslice.start is int) xStart = (double)(int)(xslice.start); if (xslice.start is double) xStart = (double)(xslice.start); if (xslice.stop is int) xStop = (double)(int)(xslice.stop); if (xslice.stop is double) xStop = (double)(xslice.stop); // if (yslice.start is int) yStart = (double)(int)(yslice.start); if (yslice.start is double) yStart = (double)(yslice.start); if (yslice.stop is int) yStop = (double)(int)(yslice.stop); if (yslice.stop is double) yStop = (double)(yslice.stop); // if (xslice.step == null) { if (xStop >= xStart) xStep = 1; else xStep = -1; } else { if (xslice.step is int) xStep = (double)(int)(xslice.step); if (xslice.step is double) xStep = (double)(xslice.step); } if (yslice.step == null) { if (yStop >= yStart) yStep = 1; else yStep = -1; } else { if (yslice.step is int) yStep = (double)(int)(yslice.step); if (yslice.step is double) yStep = (double)(yslice.step); } // IronPython.Runtime.List list = new IronPython.Runtime.List(); int nx = (int)Math.Floor((xStop - xStart) / xStep) + 1; int ny = (int)Math.Floor((yStop - yStart) / yStep) + 1; ILArray<double> x = ILMath.counter(xStart, xStep, nx); ILArray<double> y = ILMath.counter(yStart, yStep, ny); List<ILArray<double>> meshgrid = ILMath.meshgrid(x, y); list.Add(meshgrid[0]); list.Add(meshgrid[1]); return list; } }
public List <Track> get_all_songs(bool incremental = false, bool include_deleted = false) { IronPython.Runtime.List tmp = pyMobileclient.get_all_songs(incremental, include_deleted); return(tmp.ToList <Track>()); }
public static IronPython.Runtime.List ToPythonList(LinkedList<object> nativeList) { IronPython.Runtime.List list = new IronPython.Runtime.List(); foreach (object obj in nativeList) { if (obj is Dictionary<string, object>) { list.Add(ToPythonDict(obj as Dictionary<string, object>)); } else if (obj is LinkedList<object>) { list.Add(ToPythonList(obj as LinkedList<object>)); } else { list.Add(obj); } } return list; }
public static string RunIronPython(string directory, string str_script_url, List<string> args) { GenUtils.LogMsg("status", "Utils.run_ironpython: " + str_script_url, args[0] + "," + args[1] + "," + args[2]); //var app_domain_name = "ironpython"; string result = ""; try { /* string domain_id = app_domain_name; var setup = new AppDomainSetup(); setup.ApplicationName = app_domain_name; setup.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory; var python_domain = AppDomain.CreateDomain(domain_id, securityInfo: null, info: setup); */ var options = new Dictionary<string, object>(); options["LightweightScopes"] = true; var python = Python.CreateEngine(options); var paths = new List<string>(); paths.Add(directory + "Lib"); // standard python lib paths.Add(directory + "Lib\\site-packages"); paths.Add(directory + "ElmcityLib"); // Elmcity python lib GenUtils.LogMsg("status", "Utils.run_ironpython", String.Join(":", paths.ToArray())); python.SetSearchPaths(paths); var ipy_args = new IronPython.Runtime.List(); foreach (var item in args) ipy_args.Add(item); var s = HttpUtils.FetchUrl(new Uri(str_script_url)).DataAsString(); try { var common_script_url = BlobStorage.MakeAzureBlobUri("admin", "common.py", false); var common_script = HttpUtils.FetchUrl(common_script_url).DataAsString(); s = s.Replace("#include common.py", common_script); } catch (Exception e) { GenUtils.PriorityLogMsg("exception", "RunIronPython: cannot #include common.py", e.Message); } var source = python.CreateScriptSourceFromString(s, SourceCodeKind.Statements); var scope = python.CreateScope(); var sys = python.GetSysModule(); //sys.SetVariable("argv", new PythonArgs() { args = ipy_args } ); sys.SetVariable("argv", args); source.Execute(scope); try { result = scope.GetVariable("result").ToString(); } catch { // GenUtils.LogMsg("info", "RunIronPython: " + str_script_url, "no result"); } python.Runtime.Shutdown(); //AppDomain.Unload(python_domain); } catch (Exception e) { result = e.Message.ToString() + e.StackTrace.ToString(); } return result; }