public PyDataType TrashItems(PyList itemIDs, CallInformation call) { foreach (PyDataType itemID in itemIDs) { // ignore non integer values and the current if (itemID is PyInteger integer == false) { continue; } PyInteger value = itemID as PyInteger; // do not trash the active ship if (value == call.Client.ShipID) { throw new CantMoveActiveShip(); } ItemEntity item = this.ItemManager.GetItem(itemID as PyInteger); // store it's location id int oldLocationID = item.LocationID; // remove the item off the ItemManager this.ItemManager.DestroyItem(item); // notify the client of the change call.Client.NotifyItemLocationChange(item, item.Flag, oldLocationID); } return(null); }
public static Task <double[, ]> VectorizeDocumentsTFIDF(IEnumerable <string> documents) { return(Task.Run(() => { try { using (Py.GIL()) { dynamic sklear_feature_extraction_text = Py.Import("sklearn.feature_extraction.text"); dynamic tfidfVectorizer = sklear_feature_extraction_text.TfidfVectorizer(); dynamic countMatrixObject = tfidfVectorizer.fit_transform(documents); PyList countMatrix = PyList.AsList(countMatrixObject.toarray()); var matrix = (double[][])countMatrix.AsManagedObject(typeof(double[][])); return ConvertMatrix(matrix); } } catch (PythonException e) { if (e.Message.Contains("NoneType")) { return new double[0, 0]; } else { throw e; } } })); }
public PyDataType Page(PyList destinationMailboxes, PyString subject, PyString message, CallInformation call) { int callerCharacterID = call.Client.EnsureCharacterIsSelected(); foreach (PyDataType destinationID in destinationMailboxes) { // only mail to integer channel id's are supported if (destinationID is PyInteger == false) { continue; } ulong messageID = this.MessagesDB.StoreMail(destinationID as PyInteger, callerCharacterID, subject, message, out string mailboxType); // send notification to the destination PyTuple notification = new PyTuple(5) { [0] = destinationMailboxes, [1] = messageID, [2] = callerCharacterID, [3] = subject, [4] = DateTime.UtcNow.ToFileTimeUtc() }; // *multicastID are a special broadcast type that allows to notify different users based on things like charid or corpid // under the same notification, making things easier for us // sadly supporting that is more painful that actually spamming the cluster controller with single corpid or charid type broadcast // but supporting multicastIDs would be perfect // the list of id's on a *multicastID would be a PyTuple with the type and the id in it, instead of just a list of integers call.Client.ClusterConnection.SendNotification("OnMessage", mailboxType, destinationID as PyInteger, notification); } return(null); }
public PyDataType AccessControl(PyInteger channelID, PyInteger characterID, PyInteger accessLevel, CallInformation call) { int callerCharacterID = call.Client.EnsureCharacterIsSelected(); if (this.DB.IsCharacterOperatorOrAdminOfChannel(channelID, callerCharacterID) == false) { throw new LSCCannotAccessControl("Insufficient permissions"); } this.DB.UpdatePermissionsForCharacterOnChannel(channelID, characterID, accessLevel); PyTuple args = new PyTuple(6) { [0] = characterID, [1] = accessLevel, [2] = new PyNone(), [3] = accessLevel, [4] = "", [5] = accessLevel == ChatDB.CHATROLE_CREATOR }; PyDataType notification = GenerateLSCNotification("AccessControl", channelID, args, call.Client); // get users in the channel that are online now PyList characters = this.DB.GetOnlineCharsOnChannel(channelID); call.Client.ClusterConnection.SendNotification("OnLSC", "charid", characters, notification); // TODO: CHECK IF THIS IS A CHARACTER'S ADDRESS BOOK AND CHECK FOR OTHER CHARACTER'S ADDRESSBOOK STATUS // TODO: TO ENSURE THEY DON'T HAVE US BLOCKED return(null); }
/// <summary> /// Simple helper method that creates a correct IntegerIntegerListDictionary and returns /// it's PyDataType representation, ready to be sent to the EVE Online client /// /// IMPORTANT: The first field MUST be ordered (direction doesn't matter) for this method /// to properly work /// </summary> /// <param name="reader">The MySqlDataReader to read the data from</param> /// <returns></returns> public static PyDictionary <PyInteger, PyList <PyInteger> > FromMySqlDataReader(MySqlDataReader reader) { PyDictionary <PyInteger, PyList <PyInteger> > result = new PyDictionary <PyInteger, PyList <PyInteger> >(); Type keyType = reader.GetFieldType(0); Type valType = reader.GetFieldType(1); if (keyType != typeof(long) && keyType != typeof(int) && keyType != typeof(short) && keyType != typeof(byte) && keyType != typeof(ulong) && keyType != typeof(uint) && keyType != typeof(ushort) && keyType != typeof(sbyte) && valType != typeof(long) && valType != typeof(int) && valType != typeof(short) && valType != typeof(byte) && valType != typeof(ulong) && valType != typeof(uint) && valType != typeof(ushort) && valType != typeof(sbyte)) { throw new InvalidDataException("Expected two fields of type int"); } // get first key and start preparing the values int key = 0; PyList <PyInteger> currentList = new PyList <PyInteger>(); while (reader.Read() == true) { // ignore null keys if (reader.IsDBNull(0) == true) { continue; } int newKey = reader.GetInt32(0); int val = 0; // if the read key doesn't match the one read earlier if (newKey != key) { // do not add an entry to the dict unless the old id was present if (key != 0) { result[key] = currentList; } currentList = new PyList <PyInteger>(); key = newKey; } if (reader.IsDBNull(1) == false) { val = reader.GetInt32(1); } // add the current value to the list currentList.Add(val); } // ensure the last key is saved to the list result[key] = currentList; return(result); }
public PyDataType GetGuests(CallInformation call) { if (call.Client.StationID == null) { throw new CanOnlyDoInStations(); } Station station = this.ItemManager.GetStation((int)call.Client.StationID); PyList result = new PyList(); foreach (KeyValuePair <int, Character> pair in station.Guests) { // TODO: UPDATE WHEN FACTION WARS ARE SUPPORTED result.Add(new PyTuple(4) { [0] = pair.Value.CharacterID, [1] = pair.Value.Corporation.ID, [2] = pair.Value.Corporation.AllianceID, [3] = 0 // facWarID } ); } return(result); }
public PyDataType GetCharacterAppearanceList(PyList ids, CallInformation call) { PyList result = new PyList(ids.Count); int index = 0; foreach (PyDataType id in ids) { // ignore non-integers if (id is PyInteger == false) { continue; } Rowset dbResult = this.DB.GetCharacterAppearanceInfo(id as PyInteger); if (dbResult.Rows.Count != 0) { result[index] = dbResult; } index++; } return(result); }
public CodeExpression VisitList(PyList l) { return(m.ListInitializer( l.elts .Where(e => e != null) .Select(e => e.Accept(this)))); }
public PyDataType LeaveChannels(PyList channels, PyDataType boolUnsubscribe, PyInteger role, CallInformation call) { foreach (PyDataType channelInfo in channels) { if (channelInfo is PyTuple == false) { Log.Error("LSC received a channel identifier in LeaveChannels that doesn't resemble anything we know"); continue; } PyTuple tuple = channelInfo as PyTuple; if (tuple.Count != 2) { Log.Error( "LSC received a tuple for channel in LeaveChannels that doesn't resemble anything we know"); return(null); } PyDataType channelID = tuple[0]; PyBool announce = tuple[1] as PyBool; this.LeaveChannel(channelID, announce, call); } return(null); }
/// <summary> /// Gets the symbols/string from a PyObject /// </summary> /// <param name="pyObject">PyObject containing symbols</param> /// <returns>List of symbols</returns> public List <Symbol> GetSymbolsFromPyObject(PyObject pyObject) { using (Py.GIL()) { // If not a PyList, convert it into one if (!PyList.IsListType(pyObject)) { var tmp = new PyList(); tmp.Append(pyObject); pyObject = tmp; } var symbols = new List <Symbol>(); foreach (PyObject item in pyObject) { var symbol = (Symbol)item.AsManagedObject(typeof(Symbol)); if (string.IsNullOrWhiteSpace(symbol.Value)) { continue; } symbols.Add(symbol); } return(symbols.Count == 0 ? null : symbols); } }
private PyList ArrayToPyList(dynamic arr) { using (Py.GIL()) { System.Type NestedType = arr.GetType().GetElementType(); PyList res = new PyList(); if (NestedType == typeof(int)) { foreach (int d in arr) { res.Append(d.ToPython()); } } else if (NestedType == typeof(double)) { foreach (double d in arr) { res.Append(d.ToPython()); } } else { throw new PythonException("Nested Datatype not supported!"); } return(res); } }
/// <summary> /// Try to get the length of arguments of a method /// </summary> /// <param name="pyObject">Object representing a method</param> /// <param name="length">Lenght of arguments</param> /// <returns>True if pyObject is a method</returns> private static bool TryGetArgLength(PyObject pyObject, out long length) { using (Py.GIL()) { var inspect = lazyInspect.Value; if (inspect.isfunction(pyObject)) { var args = inspect.getargspec(pyObject).args as PyObject; var pyList = new PyList(args); length = pyList.Length(); pyList.Dispose(); args.Dispose(); return(true); } if (inspect.ismethod(pyObject)) { var args = inspect.getargspec(pyObject).args as PyObject; var pyList = new PyList(args); length = pyList.Length() - 1; pyList.Dispose(); args.Dispose(); return(true); } } length = 0; return(false); }
/// <summary> /// Simple helper method that creates a correct tupleset and returns /// it's PyDataType representation, ready to be sent to the EVE Online client /// </summary> /// <param name="reader">The MySqlDataReader to read the data from</param> /// <returns></returns> public static PyDataType FromMySqlDataReader(MySqlDataReader reader) { if (reader.FieldCount == 0) { return(new PyTuple(0)); } PyList columns = new PyList(reader.FieldCount); PyList rows = new PyList(); for (int i = 0; i < columns.Count; i++) { columns[i] = new PyString(reader.GetName(i)); } while (reader.Read() == true) { PyList linedata = new PyList(columns.Count); for (int i = 0; i < columns.Count; i++) { linedata[i] = Utils.ObjectFromColumn(reader, i); } rows.Add(linedata); } return(new PyTuple(new PyDataType[] { columns, rows })); }
public string GetStringValueFromObject(PyObject obj) { string type = GetTypeName(obj); switch (type) { case "str": return(new PyStr(obj.BaseAddress, MemoryReader).String); case "unicode": return(new PyUnicode(obj.BaseAddress, MemoryReader).String); case "float": return(new PyFloat(obj.BaseAddress, MemoryReader).Float.ToString()); case "int": return(new PyInt(obj.BaseAddress, MemoryReader).Int.ToString()); case "bool": return(new PyBool(obj.BaseAddress, MemoryReader).Bool.ToString()); case "list": PyList list = new PyList(obj.BaseAddress, MemoryReader); return("List with " + ((list.Items == null) ? 0 : list.Items.Length).ToString() + " elements"); default: return(obj.BaseAddress.ToString("x")); } }
public void NotifyByCharacterID(PyPacket packet, PyAddressBroadcast destination) { lock (this.Clients) { PyList idlist = destination.IDsOfInterest; foreach (PyDataType idData in idlist) { PyInteger id = idData as PyInteger; foreach (KeyValuePair <long, ClientConnection> entry in this.Clients) { if (entry.Value.CharacterID == id) { // use the key instead of AccountID as this should be faster packet.UserID = entry.Key; // change the ids of interest to hide the character's we've notified destination.IDsOfInterest = new PyDataType[] { id }; // queue the packet for the user entry.Value.Socket.Send(packet); } } } } }
public void TestEmptyCtor() { var s = new PyList(); Assert.IsInstanceOf(typeof(PyList), s); Assert.AreEqual(0, s.Length()); }
/// <summary> /// Generate the asset allocation pie chart using the python libraries. /// </summary> public override string Render() { var backtestSeries = Metrics.AssetAllocations(_backtestPortfolios); var liveSeries = Metrics.AssetAllocations(_livePortfolios); PyObject result; using (Py.GIL()) { var data = new PyList(); var liveData = new PyList(); data.Append(backtestSeries.SortBy(x => - x).Where(x => x.Value != 0).Keys.Select(x => x.Value).ToList().ToPython()); data.Append(backtestSeries.SortBy(x => - x).Where(x => x.Value != 0).Values.ToList().ToPython()); liveData.Append(liveSeries.SortBy(x => - x).Where(x => x.Value != 0).Keys.Select(x => x.Value).ToList().ToPython()); liveData.Append(liveSeries.SortBy(x => - x).Where(x => x.Value != 0).Values.ToList().ToPython()); result = Charting.GetAssetAllocation(data, liveData); } var base64 = result.ConvertToDictionary <string, string>(); if (base64.ContainsKey("Live Asset Allocation")) { return(base64["Live Asset Allocation"]); } return(base64["Backtest Asset Allocation"]); }
public PyDataType DestroyChannel(PyInteger channelID, CallInformation call) { int callerCharacterID = call.Client.EnsureCharacterIsSelected(); // ensure the character has enough permissions if (this.DB.IsCharacterAdminOfChannel(channelID, callerCharacterID) == false) { throw new LSCCannotDestroy("Insufficient permissions"); } // get users in the channel that are online now PyList characters = this.DB.GetOnlineCharsOnChannel(channelID); // remove channel off the database this.DB.DestroyChannel(channelID); // notify everyone in the channel only when it should PyDataType notification = GenerateLSCNotification("DestroyChannel", channelID, new PyTuple(0), call.Client); // notify all characters in the channel call.Client.ClusterConnection.SendNotification("OnLSC", "charid", characters, notification); return(null); }
public PyObject(bool isType2, PyTuple header, PyList list = null, PyDictionary dict = null) : base(PyObjectType.Object) { this.IsType2 = isType2; this.Header = header; this.List = list ?? new PyList(); this.Dictionary = dict ?? new PyDictionary(); }
/// <summary> /// <seealso cref="Marshal.ProcessObject"/> /// /// Opcodes supported: /// <seealso cref="Opcode.ObjectType1"/> /// <seealso cref="Opcode.ObjectType2"/> /// </summary> /// <param name="opcode">Type of object to parse</param> /// <returns>The decoded python type</returns> /// <exception cref="InvalidDataException">If any error was found in the data</exception> protected virtual PyDataType ProcessObject(Opcode opcode) { if (opcode != Opcode.ObjectType1 && opcode != Opcode.ObjectType2) { throw new InvalidDataException($"Trying to parse a {opcode} as ObjectEx"); } PyTuple header = this.Process(false) as PyTuple; PyList list = new PyList(); PyDictionary dict = new PyDictionary(); while (this.mReader.PeekChar() != Marshal.PACKED_TERMINATOR) { list.Add(this.Process(false)); } // ignore packed terminator this.mReader.ReadByte(); while (this.mReader.PeekChar() != Marshal.PACKED_TERMINATOR) { PyString key = this.Process(false) as PyString; PyDataType value = this.Process(false); dict[key] = value; } // ignore packed terminator this.mReader.ReadByte(); return(new PyObject(opcode == Opcode.ObjectType2, header, list, dict)); }
/// <summary> /// Generate the daily returns plot using the python libraries. /// </summary> public override string Render() { var backtestReturns = ResultsUtil.EquityPoints(_backtest); var liveReturns = ResultsUtil.EquityPoints(_live); var backtestSeries = new Series <DateTime, double>(backtestReturns.Keys, backtestReturns.Values); var liveSeries = new Series <DateTime, double>(liveReturns.Keys, liveReturns.Values); // The following two operations are equivalent to the Pandas `DataFrame.resample(...)` method var backtestResampled = backtestSeries.PercentChange().ResampleEquivalence(date => date.Date, s => s.Sum()) * 100; var liveResampled = liveSeries.PercentChange().ResampleEquivalence(date => date.Date, s => s.Sum()) * 100; var base64 = ""; using (Py.GIL()) { var backtestList = new PyList(); backtestList.Append(backtestResampled.Keys.ToList().ToPython()); backtestList.Append(backtestResampled.Values.ToList().ToPython()); var liveList = new PyList(); liveList.Append(liveResampled.Keys.ToList().ToPython()); liveList.Append(liveResampled.Values.ToList().ToPython()); base64 = Charting.GetDailyReturns(backtestList, liveList); backtestList.Dispose(); liveList.Dispose(); } return(base64); }
/// <summary> /// <seealso cref="Marshal.ProcessList"/> /// /// Opcodes supported: /// <seealso cref="Opcode.ListEmpty"/> /// <seealso cref="Opcode.List"/> /// </summary> /// <param name="opcode">Type of object to parse</param> /// <returns>The decoded python type</returns> /// <exception cref="InvalidDataException">If any error was found in the data</exception> protected virtual PyDataType ProcessList(Opcode opcode) { switch (opcode) { case Opcode.ListEmpty: return(new PyList()); case Opcode.ListOne: return(new PyList(1) { [0] = this.Process(false) }); case Opcode.List: { uint count = this.mReader.ReadSizeEx(); PyList list = new PyList((int)count); for (int i = 0; i < count; i++) { list[i] = this.Process(false); } return(list); } default: throw new InvalidDataException($"Trying to parse a {opcode} as List"); } }
public PyDataType GetMembers(PyList characterIDs, int corporationID, SparseRowsetHeader header, Dictionary <PyDataType, int> rowsIndex) { // TODO: GENERATE PROPER FIELDS FOR THE FOLLOWING FIELDS // TODO: titleMask, grantableRoles, grantableRolesAtHQ, grantableRolesAtBase, grantableRolesAtOther // TODO: divisionID, squadronID // TODO: CHECK IF THIS startDateTime IS THE CORP'S MEMBERSHIP OR CHARACTER'S MEMBERSHIP Dictionary <string, object> parameters = new Dictionary <string, object>(); string query = "SELECT" + " characterID, title, startDateTime, corpRole AS roles, rolesAtHQ, rolesAtBase, rolesAtOther," + " titleMask, 0 AS grantableRoles, 0 AS grantableRolesAtHQ, 0 AS grantableRolesAtBase," + " 0 AS grantableRolesAtOther, 0 AS divisionID, 0 AS squadronID, 0 AS baseID, " + " 0 AS blockRoles, gender " + "FROM chrInformation " + "WHERE corporationID=@corporationID AND characterID IN ("; foreach (PyDataType id in characterIDs) { parameters["@characterID" + parameters.Count.ToString("X")] = (int)(id as PyInteger); } // prepare the correct list of arguments query += String.Join(',', parameters.Keys) + ")"; parameters["@corporationID"] = corporationID; MySqlConnection connection = null; MySqlDataReader reader = Database.PrepareQuery(ref connection, query, parameters); using (connection) using (reader) { return(header.DataFromMySqlReader(0, reader, rowsIndex)); } }
public PyDataType GetOffices(PyList itemIDs, int corporationID, SparseRowsetHeader header, Dictionary <PyDataType, int> rowsIndex) { Dictionary <string, object> parameters = new Dictionary <string, object>(); string query = "SELECT" + " itemID, stationID, typeID, officeFolderID " + "FROM chrInformation " + "LEFT JOIN invItems ON invItems.itemID = chrInformation.activeCloneID " + "WHERE corporationID=@corporationID AND itemID IN ("; foreach (PyDataType id in itemIDs) { parameters["@itemID" + parameters.Count.ToString("X")] = (int)(id as PyInteger); } // prepare the correct list of arguments query += String.Join(',', parameters.Keys) + ")"; parameters["@corporationID"] = corporationID; // TODO: GENERATE PROPER FIELDS FOR THE FOLLOWING FIELDS // TODO: titleMask, grantableRoles, grantableRolesAtHQ, grantableRolesAtBase, grantableRolesAtOther // TODO: divisionID, squadronID // TODO: CHECK IF THIS startDateTime IS THE CORP'S MEMBERSHIP OR CHARACTER'S MEMBERSHIP MySqlConnection connection = null; MySqlDataReader reader = Database.PrepareQuery(ref connection, query, parameters); using (connection) using (reader) { return(header.DataFromMySqlReader(0, reader, rowsIndex)); } }
public CRowset(DBRowDescriptor descriptor) { this.Header = descriptor; this.Rows = new PyList(); this.PrepareColumnNames(); }
public void UnaryMinus_ThrowsOnBadType() { dynamic list = new PyList(); var error = Assert.Throws <PythonException>(() => list = -list); Assert.AreEqual("TypeError", error.Type.Name); }
public CRowset(DBRowDescriptor descriptor, PyList rows) { this.Header = descriptor; this.Rows = rows; this.PrepareColumnNames(); }
/// <summary> /// Get list of symbols from a PyObject /// </summary> /// <param name="pyObject">PyObject containing a list of tickers</param> /// <returns>List of Symbol</returns> private List <Symbol> GetSymbolsFromPyObject(PyObject pyObject, bool isEquity = false) { using (Py.GIL()) { // If not a PyList, convert it into one if (!PyList.IsListType(pyObject)) { var tmp = new PyList(); tmp.Append(pyObject); pyObject = tmp; } var symbols = new List <Symbol>(); foreach (PyObject item in pyObject) { var symbol = (Symbol)item.AsManagedObject(typeof(Symbol)); if (isEquity && string.IsNullOrWhiteSpace(symbol.Value)) { var ticker = (string)item.AsManagedObject(typeof(string)); symbol = new Symbol(SecurityIdentifier.GenerateEquity(ticker, Market.USA), ticker); } symbols.Add(symbol); } return(symbols.Count == 0 || string.IsNullOrEmpty(symbols.First().Value) ? null : symbols); } }
/// <summary> /// Simple helper method that creates a correct IndexRowset and returns /// it's PyDataType representation, ready to be sent to the EVE Online client /// /// </summary> /// <param name="reader">The MySqlDataReader to read the data from</param> /// <returns></returns> public static IndexRowset FromMySqlDataReader(MySqlDataReader reader, int indexField) { string indexFieldName = reader.GetName(indexField); PyList headers = new PyList(reader.FieldCount); for (int i = 0; i < reader.FieldCount; i++) { headers[i] = reader.GetName(i); } IndexRowset rowset = new IndexRowset(indexFieldName, headers); while (reader.Read() == true) { PyList row = new PyList(reader.FieldCount); for (int i = 0; i < row.Count; i++) { row[i] = Utils.ObjectFromColumn(reader, i); } rowset.AddRow(reader.GetInt32(indexField), row); } return(rowset); }
/// <summary> /// Generate the rolling sharpe using the python libraries. /// </summary> public override string Render() { var backtestPoints = ResultsUtil.EquityPoints(_backtest); var livePoints = ResultsUtil.EquityPoints(_live); var backtestRollingSharpe = Rolling.Sharpe(new Series <DateTime, double>(backtestPoints), 6).DropMissing(); var liveRollingSharpe = Rolling.Sharpe(new Series <DateTime, double>(livePoints), 6).DropMissing(); var base64 = ""; using (Py.GIL()) { var backtestList = new PyList(); var liveList = new PyList(); backtestList.Append(backtestRollingSharpe.Keys.ToList().ToPython()); backtestList.Append(backtestRollingSharpe.Values.ToList().ToPython()); liveList.Append(liveRollingSharpe.Keys.ToList().ToPython()); liveList.Append(liveRollingSharpe.Values.ToList().ToPython()); base64 = Charting.GetRollingSharpeRatio(backtestList, liveList); } return(base64); }
public static PyObject DBResultToPackedRowList(ref MySqlDataReader result) { PyList res = new PyList(); DBRowDescriptor header = new DBRowDescriptor(ref result); while (result.Read()) { res.Items.Add(CreatePackedRow(header, ref result)); } return res; }
public bool Decode(PyObject info) { if (info.Type != PyObjectType.ObjectData) { Log.Error("NodeInfo", "Wrong type for ObjectData"); return false; } PyObjectData data = info.As<PyObjectData>(); if (data.Name != "machoNet.nodeInfo") { Log.Error("NodeInfo", "Wrong object name, expected machoNet.nodeInfo but got " + data.Name); return false; } if (data.Arguments.Type != PyObjectType.Tuple) { Log.Error("NodeInfo", "Wrong type for ObjectData arguments, expected Tuple"); return false; } PyTuple args = data.Arguments.As<PyTuple>(); if (args.Items[0].Type != PyObjectType.Long) { Log.Error("NodeInfo", "Wrong type for tuple0 item0, expected int"); return false; } nodeID = args.Items[0].As<PyInt>().Value; if (args.Items[1].Type != PyObjectType.List) { Log.Error("NodeInfo", "Wrong type for tuple0 item1, expected list"); return false; } solarSystems = args.Items[1].As<PyList>(); return true; }
private static string PrintList(PyList list) { return "[PyList " + list.Items.Count + " items]"; }
public void VisitList(PyList l) { throw new NotImplementedException(); }
public static PyObject DBResultToTupleSet(ref MySqlDataReader result) { int column = result.FieldCount; if (column == 0) return new PyTuple(); int r = 0; PyTuple res = new PyTuple(); PyList cols = new PyList(); PyList reslist = new PyList(); for (r = 0; r < column; r++) { cols.Items.Add(new PyString(result.GetName(r))); } while (result.Read()) { PyList linedata = new PyList(); for (r = 0; r < column; r++) { linedata.Items.Add(DBColumnToPyObject(r, ref result)); } reslist.Items.Add(linedata); } res.Items.Add(cols); res.Items.Add(reslist); return res; }
public static PyObject DBResultToRowset(ref MySqlDataReader dat) { int column = dat.FieldCount; if (column == 0) { return new PyObjectData("util.Rowset", new PyDict()); } PyDict args = new PyDict(); PyList header = new PyList(); for (int i = 0; i < column; i++) { header.Items.Add(new PyString(dat.GetName(i))); } args.Set("header", header); args.Set("RowClass", new PyToken("util.Row")); PyList rowlist = new PyList(); while (dat.Read()) { PyList linedata = new PyList(); for (int r = 0; r < column; r++) { linedata.Items.Add(DBColumnToPyObject(r, ref dat)); } rowlist.Items.Add(linedata); } dat.Close(); return new PyObjectData("util.Rowset", args); }