public static void PerformModuleReload(PythonContext /*!*/ context, PythonDictionary /*!*/ dict) { var exception = context.EnsureModuleException("pyexpaterror", dict, "ExpatError", "xml.parsers.expat"); dict["error"] = exception; dict["ExpatError"] = exception; context.GetOrCreateModuleState(_errorsKey, () => { dict.Add("errors", context.GetBuiltinModule("pyexpat.errors")); dict.Add("model", context.GetBuiltinModule("pyexpat.model")); return(dict); }); }
public static void PerformModuleReload(PythonContext/*!*/ context, PythonDictionary/*!*/ dict) { context.GetOrCreateModuleState(_keyFields, () => { dict.Add(_keyDefaultAction, "default"); dict.Add(_keyOnceRegistry, new PythonDictionary()); dict.Add(_keyFilters, new List() { // Default filters PythonTuple.MakeTuple("ignore", null, PythonExceptions.PendingDeprecationWarning, null, 0), PythonTuple.MakeTuple("ignore", null, PythonExceptions.ImportWarning, null, 0), PythonTuple.MakeTuple("ignore", null, PythonExceptions.BytesWarning, null, 0) }); return dict; }); }
public static void PerformModuleReload(PythonContext /*!*/ context, PythonDictionary /*!*/ dict) { context.GetOrCreateModuleState(_keyFields, () => { dict.Add(_keyDefaultAction, "default"); dict.Add(_keyOnceRegistry, new PythonDictionary()); dict.Add(_keyFilters, new List() { // Default filters PythonTuple.MakeTuple("ignore", null, PythonExceptions.PendingDeprecationWarning, null, 0), PythonTuple.MakeTuple("ignore", null, PythonExceptions.ImportWarning, null, 0), PythonTuple.MakeTuple("ignore", null, PythonExceptions.BytesWarning, null, 0) }); return(dict); }); }
private object eval(IFreeDocument doc) { var value = doc[Column]; var dictionary = new PythonDictionary(); foreach (var data1 in doc) { dictionary.Add(data1.Key, data1.Value); } scope.SetVariable("data", dictionary); scope.SetVariable("value", value); foreach (var data in doc) { scope.SetVariable(data.Key, data.Value); } dynamic d; try { d = compiledCode.Execute(scope); } catch (Exception ex) { d = ex.Message; } return(d); }
public static void PerformModuleReload(PythonContext/*!*/ context, PythonDictionary/*!*/ dict) { List defaultFilters = new List(); if (context.PythonOptions.WarnPython30) { defaultFilters.AddNoLock(PythonTuple.MakeTuple("ignore", null, PythonExceptions.DeprecationWarning, null, 0)); } defaultFilters.AddNoLock(PythonTuple.MakeTuple("ignore", null, PythonExceptions.PendingDeprecationWarning, null, 0)); defaultFilters.AddNoLock(PythonTuple.MakeTuple("ignore", null, PythonExceptions.ImportWarning, null, 0)); defaultFilters.AddNoLock(PythonTuple.MakeTuple("ignore", null, PythonExceptions.BytesWarning, null, 0)); context.GetOrCreateModuleState(_keyFields, () => { dict.Add(_keyDefaultAction, "default"); dict.Add(_keyOnceRegistry, new PythonDictionary()); dict.Add(_keyFilters, defaultFilters); return dict; }); }
public static PythonDictionary match_template(string template, string path) { if (template == null) { throw new ArgumentNullException(nameof(template)); } if (path == null) { throw new ArgumentNullException(nameof(path)); } var routeTemplate = TemplateParser.Parse(template); var values = new RouteValueDictionary(); var templateMatcher = new TemplateMatcher(routeTemplate, values); var isMatch = templateMatcher.TryMatch(path, values); var resultValues = new PythonDictionary(); foreach (var value in values) { resultValues.Add(value.Key, Convert.ToString(value.Value, CultureInfo.InvariantCulture)); } return(new PythonDictionary { ["is_match"] = isMatch, ["values"] = resultValues }); }
public PythonDictionary Restore() { var pythonDictionary = new PythonDictionary(); foreach (var item in internalDictionary) { pythonDictionary.Add(item); } return(pythonDictionary); }
public static void PerformModuleReload(PythonContext /*!*/ context, PythonDictionary /*!*/ dict) { List defaultFilters = new List(); if (!context.PythonOptions.WarnPython30) { defaultFilters.AddNoLock(PythonTuple.MakeTuple("ignore", null, PythonExceptions.DeprecationWarning, null, 0)); } defaultFilters.AddNoLock(PythonTuple.MakeTuple("ignore", null, PythonExceptions.PendingDeprecationWarning, null, 0)); defaultFilters.AddNoLock(PythonTuple.MakeTuple("ignore", null, PythonExceptions.ImportWarning, null, 0)); defaultFilters.AddNoLock(PythonTuple.MakeTuple("ignore", null, PythonExceptions.BytesWarning, null, 0)); context.GetOrCreateModuleState(_keyFields, () => { dict.Add(_keyDefaultAction, "default"); dict.Add(_keyOnceRegistry, new PythonDictionary()); dict.Add(_keyFilters, defaultFilters); return(dict); }); }
public static PythonModule Build(string code, params object[] args) { PythonObject compilation; using (PythonException.Checker) compilation = Python.Py_CompileString(code, $"{nameof(PythonTest)}.{nameof(Evaluate)}", Python.Py_file_input); PythonModule module = new PythonModule("__main__"); PythonDictionary globals = module.Dictionary; PythonDictionary locals = new PythonDictionary(); locals.Add("clr", PyNetModule.ClrObject); // FIXME locals.Add("args", new PythonTuple(args.Select(a => (PythonObject)ObjectManager.ToPython(a)))); using (PythonException.Checker) Python.PyImport_ExecCodeModule(module.Name, compilation); return(module); }
public override int Run(InterpretedFrame frame) { PythonDictionary annotations = null; if (_annotationCount > 0) { annotations = new PythonDictionary(); for (int i = 0; i < _annotationCount; i++) { annotations.Add(frame.Pop(), frame.Pop()); } } PythonDictionary kwdefaults = null; if (_kwdefaultCount > 0) { kwdefaults = new PythonDictionary(); for (int i = 0; i < _kwdefaultCount; i++) { kwdefaults.Add(frame.Pop(), frame.Pop()); } } object[] defaults; if (_defaultCount > 0) { defaults = new object[_defaultCount]; for (int i = 0; i < _defaultCount; i++) { defaults[i] = frame.Pop(); } } else { defaults = ArrayUtils.EmptyObjects; } object modName; if (_name != null) { modName = _name.RawValue; } else { modName = frame.Pop(); } CodeContext context = (CodeContext)frame.Pop(); frame.Push(PythonOps.MakeFunction(context, _def.FunctionCode, modName, defaults, kwdefaults, annotations)); return(+1); }
public static PythonDictionary ToDict(this Dictionary <string, OpenCvSharp.Point> dict) { var pythonDict = new PythonDictionary(); foreach (var pair in dict) { pythonDict.Add(pair.Key, pair.Value); } return(pythonDict); }
public PythonDictionary ToDict() { var pythonDict = new PythonDictionary(); foreach (var pair in this) { pythonDict.Add(pair.Key, pair.Value); } return(pythonDict); }
public static object ToPython(object value) { if (value is PythonDictionary) { return(value); } if (value is string) { return(value); } if (value is int) { return(value); } if (value is float) { return(value); } if (value is bool) { return(value); } if (value is IDictionary dictionary) { var pythonDictionary = new PythonDictionary(); foreach (DictionaryEntry dictionaryEntry in dictionary) { pythonDictionary.Add(dictionaryEntry.Key, ToPython(dictionaryEntry.Value)); } return(pythonDictionary); } if (value is IEnumerable enumerable) { var pythonList = new List(); foreach (var item in enumerable) { pythonList.Add(ToPython(item)); } return(pythonList); } return(value); }
public PythonDictionary SendMail(string from, string to, string subject, string body, bool isHtml = true) { PythonDictionary result = new PythonDictionary(); try { SmtpClient client = new SmtpClient("127.0.0.1"); MailMessage mm = new MailMessage(from, to, subject, body) { IsBodyHtml = isHtml }; client.Send(mm); result.Add("success", true); result.Add("message", string.Empty); } catch (Exception ex) { result.Add("success", false); result.Add("message", ex.Message); } return(result); }
public static void PerformModuleReload(PythonContext /*!*/ context, PythonDictionary /*!*/ dict) { PythonList defaultFilters = new PythonList(); defaultFilters.AddNoLock(PythonTuple.MakeTuple("ignore", null, PythonExceptions.DeprecationWarning, null, 0)); defaultFilters.AddNoLock(PythonTuple.MakeTuple("ignore", null, PythonExceptions.PendingDeprecationWarning, null, 0)); defaultFilters.AddNoLock(PythonTuple.MakeTuple("ignore", null, PythonExceptions.ImportWarning, null, 0)); string bytesWarningAction = context.PythonOptions.BytesWarning switch { Severity.Ignore => "ignore", Severity.Warning => "default", _ => "error" }; defaultFilters.AddNoLock(PythonTuple.MakeTuple(bytesWarningAction, null, PythonExceptions.BytesWarning, null, 0)); context.GetOrCreateModuleState(_keyFields, () => { dict.Add(_keyDefaultAction, "default"); dict.Add(_keyOnceRegistry, new PythonDictionary()); dict.Add(_keyFilters, defaultFilters); return(dict); }); }
/// <summary> /// recommend辅助函数 /// 获取user_id和movie_id的关联字典 /// </summary> /// <param name="user_id"></param> /// <returns></returns> private static PythonDictionary getUserItem(int user_id) { MySqlCommand mySqlCommand = new MySqlCommand(); mySqlCommand.Connection = DataBaseProvider.getConnection(); string sqlStr = @"select userId,movieId from rating"; mySqlCommand.CommandText = sqlStr; mySqlCommand.Connection.OpenAsync(); MySqlDataReader reader = mySqlCommand.ExecuteReader(); PythonDictionary pyDic = new PythonDictionary(); try { while (reader.Read()) { if (reader.HasRows) { int userId = reader.GetInt32(0); int movieId = reader.GetInt32(1); if (!pyDic.Keys.Contains(userId)) { pyDic.Add(userId, new ArrayList()); } ArrayList subList = pyDic[userId] as ArrayList; subList.Add(movieId); } } } catch (Exception e) { throw (e); } finally { mySqlCommand.Connection.CloseAsync(); } return(pyDic); }
public static PythonDictionary ToPythonDictionary(IDictionary <object, object> source) { if (source == null) { return(null); } if (source is PythonDictionary pythonDictionary) { return(pythonDictionary); } pythonDictionary = new PythonDictionary(); foreach (var item in source) { pythonDictionary.Add(item.Key, item.Value); } return(pythonDictionary); }
public static PythonObject Evaluate(string code, params object[] args) { PythonObject compilation; using (PythonException.Checker) compilation = Python.Py_CompileString(code, $"{nameof(PythonTest)}.{nameof(Evaluate)}", Python.Py_eval_input); PythonModule module = new PythonModule("__main__"); PythonDictionary globals = module.Dictionary; PythonDictionary locals = new PythonDictionary(); //locals.Add("clr", PyNetModule.ClrObject); locals.Add("args", new PythonTuple(args.Select(a => (PythonObject)ObjectManager.ToPython(a)))); PythonObject result; using (PythonException.Checker) result = Python.PyEval_EvalCode(compilation, globals, locals); return(result); }
/// <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); }
/// <summary> /// Detect and register all available controller in the system /// </summary> /// <param name="context">CodeContext, passed from IronPython automatically</param> public static void register_all(CodeContext context) { // Get all Controller in the current scope var items = MvcApplication.Host.DefaultScope.ScriptScope.GetItems(); var pythonController = DynamicHelpers.GetPythonTypeFromType(typeof(AspNetMvcAPI.Controller)); foreach (var item in items) { // Check type and get controller if (item.Value is PythonType) { var pt = (PythonType)item.Value; var baseType = pt.__getattribute__(context, "__base__"); // If is controlelr if (baseType == pythonController) { // Add to controller list __controllers.Add(item.Key.Replace("Controller", ""), pt); } } } // Register routes var routes = System.Web.Routing.RouteTable.Routes; routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); IControllerFactory factory = new CustomControllerFactory(); ControllerBuilder.Current.SetControllerFactory(factory); }
public static PythonDictionary ToPythonDictionary(IDictionary dictionary) { if (dictionary == null) { return(null); } if (dictionary is PythonDictionary pythonDictionary) { return(pythonDictionary); } var newPythonDictionary = new PythonDictionary(); foreach (var entry in dictionary.Keys) { var key = Convert.ToString(entry, CultureInfo.InvariantCulture); newPythonDictionary.Add(key, ToPython(dictionary[entry])); } return(newPythonDictionary); }
public static object ToPython(object value) { if (value is PythonDictionary) { return(value); } if (value is List) { return(value); } if (value is null || value is string || value is bool) { return(value); } if (value is int || value is float || value is long || value is double || value is Complex) { return(value); } if (value is IDictionary <object, object> dictionary) { var pythonDictionary = new PythonDictionary(); foreach (var entryKey in dictionary.Keys) { pythonDictionary.Add(entryKey, ToPython(dictionary[entryKey])); } return(pythonDictionary); } if (value is MulticastDelegate) { return(value); } if (value is Delegate) { return(value); } // Convert JSON stuff. if (value is JArray array) { var result = new List(); // This is a python list. foreach (var item in array) { result.Add(ToPython(item)); } return(result); } if (value is JObject @object) { var result = new PythonDictionary(); foreach (var property in @object.Properties()) { result.Add(property.Name, ToPython(property.Value)); } return(result); } if (value is JValue jValue) { if (jValue.Type == JTokenType.Null) { return(null); } return(ToPython(jValue.ToObject <object>())); } if (value is IEnumerable items) { var result = new List(); // This is a python list. foreach (var item in items) { result.Add(ToPython(item)); } return(result); } return(value); }
public static void warn_explicit(CodeContext context, object message, PythonType category, string filename, int lineno, string module = null, PythonDictionary registry = null, object module_globals = null) { PythonContext pContext = context.LanguageContext; PythonDictionary fields = (PythonDictionary)pContext.GetModuleState(_keyFields); object warnings = pContext.GetWarningsModule(); PythonExceptions.BaseException msg; string text; // message text if (string.IsNullOrEmpty(module)) { module = (filename == null || filename == "") ? "<unknown>" : filename; if (module.EndsWith(".py")) { module = module.Substring(0, module.Length - 3); } } if (registry == null) { registry = new PythonDictionary(); } if (PythonOps.IsInstance(message, PythonExceptions.Warning)) { msg = (PythonExceptions.BaseException)message; text = msg.ToString(); category = DynamicHelpers.GetPythonType(msg); } else { text = message.ToString(); msg = PythonExceptions.CreatePythonThrowable(category, message.ToString()); } PythonTuple key = PythonTuple.MakeTuple(text, category, lineno); if (registry.ContainsKey(key)) { return; } string action = Converter.ConvertToString(fields[_keyDefaultAction]); PythonTuple last_filter = null; bool loop_break = false; List filters = (List)fields[_keyFilters]; if (warnings != null) { filters = PythonOps.GetBoundAttr(context, warnings, "filters") as List; if (filters == null) { throw PythonOps.ValueError("_warnings.filters must be a list"); } } foreach (PythonTuple filter in filters) { last_filter = filter; action = (string)filter._data[0]; PythonRegex.RE_Pattern fMsg = (PythonRegex.RE_Pattern)filter._data[1]; PythonType fCat = (PythonType)filter._data[2]; PythonRegex.RE_Pattern fMod = (PythonRegex.RE_Pattern)filter._data[3]; int fLno; if (filter._data[4] is int) { fLno = (int)filter._data[4]; } else { fLno = (Extensible <int>)filter._data[4]; } if ((fMsg == null || fMsg.match(text) != null) && category.IsSubclassOf(fCat) && (fMod == null || fMod.match(module) != null) && (fLno == 0 || fLno == lineno)) { loop_break = true; break; } } if (!loop_break) { action = Converter.ConvertToString(fields[_keyDefaultAction]); } switch (action) { case "ignore": registry.Add(key, 1); return; case "error": throw msg.GetClrException(); case "once": registry.Add(key, 1); PythonTuple onceKey = PythonTuple.MakeTuple(text, category); PythonDictionary once_reg = (PythonDictionary)fields[_keyOnceRegistry]; if (once_reg.ContainsKey(onceKey)) { return; } once_reg.Add(key, 1); break; case "always": break; case "module": registry.Add(key, 1); PythonTuple altKey = PythonTuple.MakeTuple(text, category, 0); if (registry.ContainsKey(altKey)) { return; } registry.Add(altKey, 1); break; case "default": registry.Add(key, 1); break; default: throw PythonOps.RuntimeError("Unrecognized action ({0}) in warnings.filters:\n {1}", action, last_filter); } if (warnings != null) { object show_fxn = PythonOps.GetBoundAttr(context, warnings, "showwarning"); if (show_fxn != null) { PythonCalls.Call( context, show_fxn, msg, category, filename, lineno, null, null); } else { showwarning(context, msg, category, filename, lineno, null, null); } } else { showwarning(context, msg, category, filename, lineno, null, null); } }
private object eval(IFreeDocument doc) { var value = doc[Column]; var dictionary = new PythonDictionary(); foreach (var data1 in doc) { dictionary.Add(data1.Key, data1.Value); } scope.SetVariable("data", dictionary); scope.SetVariable("value", value); foreach (var data in doc) { scope.SetVariable(data.Key, data.Value); } dynamic d; try { d = compiledCode.Execute(scope); } catch (Exception ex) { d = ex.Message; } return d; }
/// <summary> /// Given a path to a Zip archive, build a dict, mapping file names /// (local to the archive, using SEP as a separator) to toc entries. /// /// A toc_entry is a tuple: /// (__file__, # value to use for __file__, available for all files /// compress, # compression kind; 0 for uncompressed /// data_size, # size of compressed data on disk /// file_size, # size of decompressed data /// file_offset, # offset of file header from start of archive /// time, # mod time of file (in dos format) /// date, # mod data of file (in dos format) /// crc, # crc checksum of the data /// ) /// Directories can be recognized by the trailing SEP in the name, /// data_size and file_offset are 0. /// </summary> /// <param name="archive"></param> /// <returns></returns> private PythonDictionary ReadDirectory(string archive) { string path, name = string.Empty; BinaryReader fp = null; int header_position, header_size, header_offset, count, compress; int time, date, crc, data_size, name_size, file_size, file_offset; int arc_offset; // offset from beginning of file to start of zip-archive PythonDictionary files = null; byte[] endof_central_dir = new byte[22]; if (archive.Length > MAXPATHLEN) { throw PythonOps.OverflowError("Zip path name is too long"); } path = archive; try { try { fp = new BinaryReader(new FileStream(archive, FileMode.Open, FileAccess.Read)); } catch { throw MakeError("can't open Zip file: '{0}'", archive); } if (fp.BaseStream.Length < 2) { throw MakeError("can't read Zip file: '{0}'", archive); } fp.BaseStream.Seek(-22, SeekOrigin.End); header_position = (int)fp.BaseStream.Position; if (fp.Read(endof_central_dir, 0, 22) != 22) { throw MakeError("can't read Zip file: '{0}'", archive); } if (BitConverter.ToUInt32(endof_central_dir, 0) != 0x06054B50) { // Bad: End of Central Dir signature fp.Close(); throw MakeError("not a Zip file: '{0}'", archive); } header_size = BitConverter.ToInt32(endof_central_dir, 12); header_offset = BitConverter.ToInt32(endof_central_dir, 16); arc_offset = header_position - header_offset - header_size; header_offset += arc_offset; files = new PythonDictionary(); path += Path.DirectorySeparatorChar; // Start of Central Directory count = 0; while (true) { name = string.Empty; fp.BaseStream.Seek(header_offset, SeekOrigin.Begin); // Start of file header int l = fp.ReadInt32(); if (l != 0x02014B50) { break; // Bad: Central Dir File Header } fp.BaseStream.Seek(header_offset + 10, SeekOrigin.Begin); compress = fp.ReadInt16(); time = fp.ReadInt16(); date = fp.ReadInt16(); crc = fp.ReadInt32(); data_size = fp.ReadInt32(); file_size = fp.ReadInt32(); name_size = fp.ReadInt16(); header_size = 46 + name_size + fp.ReadInt16() + fp.ReadInt16(); fp.BaseStream.Seek(header_offset + 42, SeekOrigin.Begin); file_offset = fp.ReadInt32() + arc_offset; if (name_size > MAXPATHLEN) name_size = MAXPATHLEN; for (int i = 0; i < name_size; i++) { char c = fp.ReadChar(); if (c == '/') c = Path.DirectorySeparatorChar; name += c; } header_offset += header_size; PythonTuple t = PythonOps.MakeTuple(path + name, compress, data_size, file_size, file_offset, time, date, crc); files.Add(name, t); count++; } } catch { throw; } finally { if (fp != null) { fp.Close(); } } return files; }
public object load_module(CodeContext /*!*/ context, string fullname) { fullname = MakeValidPath(fullname, resolved_subpath); string code = null; GenericModuleCodeType moduleType; bool ispackage = false; string modpath = null; string fullFileName = null; PythonModule mod; PythonDictionary dict = null; // Go through available import types by search-order foreach (var order in _search_order) { string tempCode = this.resolver.GetScriptSource(fullname.Replace(".", "/") + order.Key); if (tempCode != null) { moduleType = order.Value; code = tempCode; modpath = fullname; fullFileName = fullname.Replace(".", "/") + order.Key; if ((order.Value & GenericModuleCodeType.Package) == GenericModuleCodeType.Package) { ispackage = true; } break; } } // of no code was loaded if (code == null) { return(null); } ScriptCode scriptCode = null; mod = context.LanguageContext.CompileModule(fullFileName, fullname, new SourceUnit(context.LanguageContext, new SourceStringContentProvider(code), modpath, SourceCodeKind.File), ModuleOptions.None, out scriptCode); dict = mod.Get__dict__(); // Set values before execute script dict.Add("__name__", fullname.Split('.').Last()); dict.Add("__loader__", this); dict.Add("__package__", null); if (ispackage) { // Add path string fullpath = RESOLVER_PATH_NAME + "." + string.Format(fullname.Replace("/", ".")); //_rel_path = fullpath; paths.Add(fullpath); List pkgpath = PythonOps.MakeList(fullpath); if (dict.ContainsKey("__path__")) { dict["__path__"] = pkgpath; } else { dict.Add("__path__", pkgpath); } } else { StringBuilder packageName = new StringBuilder(); string[] packageParts = fullname.Split(new char[] { '/' }); for (int i = 0; i < packageParts.Length - 1; i++) { if (i > 0) { packageName.Append("."); } packageName.Append(packageParts[i]); } dict["__package__"] = packageName.ToString(); } scriptCode.Run(mod.Scope); return(mod); }