internal DirectSystemScanResult(DirectEve directEve, PyObject pyResult) : base(directEve) { PyResult = pyResult; Id = (string) pyResult.Attribute("id"); ScanGroupName = (string) pyResult.Attribute("scanGroupName").ToUnicodeString(); GroupName = (string) pyResult.Attribute("groupName").ToUnicodeString(); TypeName = (string) pyResult.Attribute("typeName").ToUnicodeString(); SignalStrength = (double) pyResult.Attribute("certainty"); Deviation = (double) pyResult.Attribute("deviation"); IsPointResult = (string) PyResult.Attribute("data").Attribute("__class__").Attribute("__name__") == "Vector3"; IsSpereResult = (string) PyResult.Attribute("data").Attribute("__class__").Attribute("__name__") == "float"; IsCircleResult = (!IsPointResult && !IsSpereResult); if (IsPointResult) { X = (double?) pyResult.Attribute("data").Attribute("x"); Y = (double?) pyResult.Attribute("data").Attribute("y"); Z = (double?) pyResult.Attribute("data").Attribute("z"); } else if (IsCircleResult) { X = (double?) pyResult.Attribute("data").Attribute("point").Attribute("x"); Y = (double?) pyResult.Attribute("data").Attribute("point").Attribute("y"); Z = (double?) pyResult.Attribute("data").Attribute("point").Attribute("z"); } // If SphereResult: X,Y,Z is probe location if (X.HasValue && Y.HasValue && Z.HasValue) { var myship = directEve.ActiveShip.Entity; Distance = Math.Sqrt((X.Value - myship.X)*(X.Value - myship.X) + (Y.Value - myship.Y)*(Y.Value - myship.Y) + (Z.Value - myship.Z)*(Z.Value - myship.Z)); } }
public PyObjectEx(bool isType2, PyObject header) : base(PyObjectType.ObjectEx) { IsType2 = isType2; Header = header; Dictionary = new Dictionary<PyObject, PyObject>(); }
public PySetObject(DkmProcess process, ulong address) : base(process, address) { InitializeStruct(this, out _fields); CheckPyType<PySetObject>(); _dummy = Process.GetOrCreateDataItem(() => new DummyHolder(Process)).Dummy.TryRead(); }
internal DirectMarketActionWindow(DirectEve directEve, PyObject pyWindow) : base(directEve, pyWindow) { IsReady = (bool) pyWindow.Attribute("ready"); IsBuyAction = Name == "marketbuyaction"; IsSellAction = Name == "marketsellaction"; Item = new DirectItem(directEve); Item.PyItem = pyWindow.Attribute("sr").Attribute("sellItem"); var order = pyWindow.Attribute("sr").Attribute("currentOrder"); Price = (double?) order.Attribute("price"); RemainingVolume = (double?) order.Attribute("volRemaining"); Range = (int?) order.Attribute("range"); OrderId = (long?) order.Attribute("orderID"); EnteredVolume = (int?) order.Attribute("volEntered"); MinimumVolume = (int?) order.Attribute("minVolume"); IsBid = (bool?) order.Attribute("bid"); Issued = (DateTime?) order.Attribute("issued"); Duration = (int?) order.Attribute("duration"); StationId = (long?) order.Attribute("stationID"); RegionId = (long?) order.Attribute("regionID"); SolarSystemId = (long?) order.Attribute("solarSystemID"); Jumps = (int?) order.Attribute("jumps"); }
internal DirectFleetMember(DirectEve directEve, PyObject memberObject) : base(directEve) { CharacterId = (int) memberObject.Attribute("charID"); SquadID = (long) memberObject.Attribute("squadID"); WingID = (long) memberObject.Attribute("wingID"); Skills = new List<int> { (int) memberObject.Attribute("skills").ToList()[0], (int) memberObject.Attribute("skills").ToList()[1], (int) memberObject.Attribute("skills").ToList()[2] }; if ((int) memberObject.Attribute("job") == (int) directEve.Const.FleetJobCreator) Job = JobRole.Boss; else Job = JobRole.RegularMember; if ((int) memberObject.Attribute("role") == (int) directEve.Const.FleetRoleLeader) Role = FleetRole.FleetCommander; else if ((int) memberObject.Attribute("role") == (int) directEve.Const.FleetRoleWingCmdr) Role = FleetRole.WingCommander; else if ((int) memberObject.Attribute("role") == (int) directEve.Const.FleetRoleSquadCmdr) Role = FleetRole.SquadCommander; else if ((int) memberObject.Attribute("role") == (int) directEve.Const.FleetRoleMember) Role = FleetRole.Member; ShipTypeID = (int?) memberObject.Attribute("shipTypeID"); SolarSystemID = (int) memberObject.Attribute("solarSystemID"); }
internal DirectReprocessingQuoteRecoverable(DirectEve directEve, PyObject recoverable) : base(directEve) { TypeId = (int) recoverable.Item(0); YouReceive = (long) recoverable.Item(1); WeTake = (long) recoverable.Item(2); Unrecoverable = (long) recoverable.Item(3); }
public static void NotifyClients(PyObject notify) { foreach (Client client in clients) { client.Send(notify); } }
internal DirectOrder(DirectEve directEve, PyObject pyOrder) : base(directEve) { PyOrder = pyOrder; OrderId = -1; Price = (double) pyOrder.Attribute("price"); VolumeRemaining = (int) pyOrder.Attribute("volRemaining"); TypeId = (int) pyOrder.Attribute("typeID"); if ((int) pyOrder.Attribute("range") == (int) DirectEve.Const.RangeSolarSystem) Range = DirectOrderRange.SolarSystem; else if ((int) pyOrder.Attribute("range") == (int) DirectEve.Const.RangeConstellation) Range = DirectOrderRange.Constellation; else if ((int) pyOrder.Attribute("range") == (int) DirectEve.Const.RangeRegion) Range = DirectOrderRange.Region; else if ((int) pyOrder.Attribute("range") == (int) DirectEve.Const.RangeStation) Range = DirectOrderRange.Station; else RangeAbsolute = (int) pyOrder.Attribute("range"); OrderId = (long) pyOrder.Attribute("orderID"); VolumeEntered = (int) pyOrder.Attribute("volEntered"); MinimumVolume = (int) pyOrder.Attribute("minVolume"); IsBid = (bool) pyOrder.Attribute("bid"); IssuedOn = (DateTime) pyOrder.Attribute("issued"); Duration = (int) pyOrder.Attribute("duration"); StationId = (int) pyOrder.Attribute("stationID"); RegionId = (int) pyOrder.Attribute("regionID"); SolarSystemId = (int) pyOrder.Attribute("solarSystemID"); Jumps = (int) pyOrder.Attribute("jumps"); }
internal DirectConstellation(DirectEve directEve, PyObject pyo) : base(directEve) { Id = (long) pyo.Attribute("constellationID"); Name = (string) DirectEve.PySharp.Import("__builtin__").Attribute("cfg").Attribute("evelocations").Call("Get", Id).Attribute("name"); RegionId = (long) pyo.Attribute("regionID"); FactionId = (long?) pyo.Attribute("factionID"); }
internal DirectBookmarkFolder(DirectEve directEve, PyObject pyFolder) : base(directEve) { Id = (long) pyFolder.Attribute("folderID"); Name = (string) pyFolder.Attribute("folderName"); OwnerId = (long) pyFolder.Attribute("ownerID"); CreatorId = (long?) pyFolder.Attribute("creatorID"); }
Register__Py_NotImplementedStruct(IntPtr address) { PyObject notimpl = new PyObject(); notimpl.ob_refcnt = 1; notimpl.ob_type = this.PyNotImplemented_Type; Marshal.StructureToPtr(notimpl, address, false); this.map.Associate(address, PythonOps.NotImplemented); }
Register__Py_EllipsisObject(IntPtr address) { PyObject ellipsis = new PyObject(); ellipsis.ob_refcnt = 1; ellipsis.ob_type = this.PyEllipsis_Type; Marshal.StructureToPtr(ellipsis, address, false); this.map.Associate(address, Builtin.Ellipsis); }
Register__Py_NoneStruct(IntPtr address) { PyObject none = new PyObject(); none.ob_refcnt = 1; none.ob_type = this.PyNone_Type; Marshal.StructureToPtr(none, address, false); // no need to Associate: None/null is special-cased }
private PyObject Evaluate(PySharp.PySharp pySharp, PyObject pyObject) { // TODO: Better part splitting (e.g. bla('bla', const.bla) var parts = _evaluate.Split('.'); if (parts.Length == 0) { // TODO: List imports return null; } if (pyObject == null) pyObject = pySharp.Import(parts[0]); for (var i = 1; i < parts.Length; i++) { if (parts[i].Contains("(")) { // TODO: Call } else if (parts[i].Contains("[")) { var attr = parts[i].Substring(0, parts[i].IndexOf('[')); var key = parts[i].Substring(parts[i].IndexOf('[') + 1, parts[i].IndexOf(']') - parts[i].IndexOf('[') - 1); if (key.StartsWith("'") || key.StartsWith("\"")) key = key.Substring(1, key.Length - 2); if (!string.IsNullOrEmpty(attr)) pyObject = pyObject.Attribute(attr); if (pyObject.GetPyType() == PyType.DictType || pyObject.GetPyType() == PyType.DerivedDictType || pyObject.GetPyType() == PyType.DictProxyType || pyObject.GetPyType() == PyType.DerivedDictProxyType) { var dict = pyObject.ToDictionary(); pyObject = PySharp.PySharp.PyZero; foreach (var dictItem in dict) { if (GetPyValue(dictItem.Key) == key) pyObject = dictItem.Value; } } else { int index; pyObject = int.TryParse(key, out index) ? pyObject.Item(index) : PySharp.PySharp.PyZero; } } else { pyObject = pyObject.Attribute(parts[i]); } } return pyObject; }
/* This should never be used in the node, just the Cache Tool */ public bool Decode(PyObject from) { PyTuple data = (from as PyObjectData).Arguments as PyTuple; // Just decode the cache info for now.. cache = data.Items[4] as PyBuffer; return true; }
protected void Initialize() { if (!Initialized) { Module = new PyObject(Python.InitModule(Name, Methods.ToArray()), ReferenceType.Borrowed); Module.IncRef(); Initialized = true; } }
internal DirectTradeWindow(DirectEve directEve, PyObject pyWindow) : base(directEve, pyWindow) { MyAccepted = (int) PyWindow.Attribute("sr").Attribute("myAccept").Attribute("state") == 1; HerAccepted = (int) PyWindow.Attribute("sr").Attribute("herAccept").Attribute("state") == 1; HerCharacterId = (int) PyWindow.Attribute("sr").Attribute("herinfo").Attribute("ownerID"); HerName = (string) PyWindow.Attribute("sr").Attribute("herinfo").Attribute("ownerName").ToUnicodeString(); MyOfferedIsk = (string) PyWindow.Attribute("sr").Attribute("myMoney").Attribute("text").ToUnicodeString(); HerOfferedIsk = (string) PyWindow.Attribute("sr").Attribute("herMoney").Attribute("text").ToUnicodeString(); }
StoreTyped(IDictionary dictMgd) { PyObject dict = new PyObject(); dict.ob_refcnt = 1; dict.ob_type = this.PyDict_Type; IntPtr dictPtr = this.allocator.Alloc((uint)Marshal.SizeOf(typeof(PyObject))); Marshal.StructureToPtr(dict, dictPtr, false); this.map.Associate(dictPtr, dictMgd); return dictPtr; }
internal DirectScannerWindow(DirectEve directEve, PyObject pyWindow) : base(directEve, pyWindow) { var charId = DirectEve.Session.CharacterId; var obj = PyWindow.Attribute("busy"); var analyseBtnEnabled = (bool)pyWindow.Attribute("sr").Attribute("analyzeBtn").Attribute("enabled"); //Log("obj type = " + obj.GetPyType().ToString()); //Log("obj value = " + ((bool) obj).ToString()); IsReady = charId != null && obj.IsValid && (bool)obj == false && analyseBtnEnabled; }
internal DirectSolarSystem(DirectEve directEve, PyObject pyo) : base(directEve) { Id = (int) pyo.Attribute("solarSystemID"); Name = (string) DirectEve.PySharp.Import("__builtin__").Attribute("cfg").Attribute("evelocations").Call("Get", Id).Attribute("name"); ConstellationId = (long) pyo.Attribute("constellationID"); FactionId = (long?) pyo.Attribute("factionID"); Security = (double) pyo.Attribute("securityStatus"); IsWormholeSystem = ((long) directEve.Const.MapWormholeSystemMin < Id && Id < (long) directEve.Const.MapWormholeSystemMax); }
internal DirectAgentMissionBookmark(DirectEve directEve, PyObject pyBookmark) : base(directEve, pyBookmark) { AgentId = (long?) pyBookmark.Attribute("agentID"); IsDeadspace = (bool?) pyBookmark.Attribute("deadspace"); Flag = (int?) pyBookmark.Attribute("flag"); LocationNumber = (int?) pyBookmark.Attribute("locationNumber"); LocationType = (string) pyBookmark.Attribute("locationType"); Title = (string) pyBookmark.Attribute("hint"); SolarSystemId = (long?) pyBookmark.Attribute("solarsystemID"); }
public static void NotifyClient(int clientID, PyObject notify) { try { GetClient(clientID).Send(notify); } catch (Exception) { } }
//private DirectEve DirectEve; internal DirectContainerWindow(DirectEve directEve, PyObject pyWindow) : base(directEve, pyWindow) { //IsReady = (bool) pyWindow.Attribute("startedUp"); IsOneWay = (bool) pyWindow.Attribute("oneWay"); ItemId = (long) pyWindow.Attribute("itemID"); LocationFlag = (int) pyWindow.Attribute("locationFlag"); HasCapacity = (bool) pyWindow.Attribute("hasCapacity"); currInvIdName = (string) PyWindow.Attribute("currInvID").ToList().First(); currInvIdItem = (long) PyWindow.Attribute("currInvID").ToList().Last(); }
internal DirectStation(DirectEve directEve, PyObject pyo) : base(directEve) { Id = (int) pyo.Attribute("stationID"); Name = (string) pyo.Attribute("stationName"); X = (double) pyo.Attribute("x"); Y = (double) pyo.Attribute("y"); Z = (double) pyo.Attribute("z"); TypeId = (int) pyo.Attribute("stationTypeID"); SolarSystemId = (int) pyo.Attribute("solarSystemID"); }
public PyObject this[PyObject key] { get { return Dictionary[key]; } set { Dictionary[key] = value; } }
internal DirectContainer(DirectEve directEve, PyObject pyInventory, PyObject pyFlag) : base(directEve) { _pyInventory = pyInventory; _pyFlag = pyFlag; TypeId = (int) pyInventory.Attribute("typeID"); if (!pyInventory.Attribute("listed").IsValid || pyInventory.Attribute("listed").IsNull || pyInventory.Attribute("listed").IsNone) DirectItem.RefreshItems(directEve, pyInventory, pyFlag); }
public static byte[] Process(PyObject obj) { var ret = new MemoryStream(100); ret.WriteByte(Unmarshal.HeaderByte); // we have no support for save lists right now ret.WriteByte(0x00); ret.WriteByte(0x00); ret.WriteByte(0x00); ret.WriteByte(0x00); obj.Encode(new BinaryWriter(ret)); return ret.ToArray(); }
internal DirectReprocessingQuote(DirectEve directEve, long itemId, PyObject quote) : base(directEve) { ItemId = itemId; QuantityToProcess = (long) quote.Attribute("quantityToProcess"); LeftOvers = (long) quote.Attribute("leftOvers"); PlayerStanding = (float) quote.Attribute("olayerStanding"); Recoverables = new List<DirectReprocessingQuoteRecoverable>(); foreach (var recoverable in quote.Attribute("recoverables").Attribute("lines").ToList()) Recoverables.Add(new DirectReprocessingQuoteRecoverable(DirectEve, recoverable)); }
public bool Decode( PyObject data) { if (data.Type != PyObjectType.Tuple) { Log.Error("VipKeyCommand", "Wrong type"); return false; } PyTuple tmp = data.As<PyTuple>(); if (tmp.Items.Count != 3) { Log.Error("VipKeyCommand", "Wrong size, expected 3 but got " + tmp.Items.Count); return false; } if (tmp.Items[0].Type != PyObjectType.None) { Log.Error("VipKeyCommand", "Wrong type for item 1"); return false; } if (tmp.Items[1].Type != PyObjectType.String) { Log.Error("VipKeyCommand", "Wrong type for item 2"); return false; } if (tmp.Items[2].Type != PyObjectType.String) { Log.Error("VipKeyCommand", "Wrong type for item 3"); return false; } PyString command = tmp.Items[1].As<PyString>(); if (command.Value != "VK") { Log.Error("VipKeyCommand", "Wrong command name, expected VK but got \"" + command.Value + "\""); return false; } /* We cant check the vipKey, because the client sends different vipKeys, who know why ? PyString vipKey = tmp.Items[2].As<PyString>(); if (vipKey.Value != vipkey) { Log.Error("VipKeyCommand", "Wrong vipKey value, expected \"" + vipkey + "\" but got \"" + vipKey.Value + "\""); return false; }*/ return true; }
internal DirectEntity(DirectEve directEve, PyObject ballpark, PyObject ball, PyObject slimItem, long id) : base(directEve) { _ballpark = ballpark; _ball = ball; _slimItem = slimItem; Id = id; TypeId = (int) slimItem.Attribute("typeID"); Attacks = new List<string>(); ElectronicWarfare = new List<string>(); }
public static bool IsSlice(this PyObject obj) { return(obj.IsInstance(PySliceType)); }
/// <summary> /// Creates a new FilteredIdentity indicator for the symbol The indicator will be automatically /// updated on the symbol's subscription resolution /// </summary> /// <param name="symbol">The symbol whose values we want as an indicator</param> /// <param name="resolution">The desired resolution of the data</param> /// <param name="selector">Selects a value from the BaseData, if null defaults to the .Value property (x => x.Value)</param> /// <param name="filter">Filters the IBaseData send into the indicator, if null defaults to true (x => true) which means no filter</param> /// <param name="fieldName">The name of the field being selected</param> /// <returns>A new FilteredIdentity indicator for the specified symbol and selector</returns> public FilteredIdentity FilteredIdentity(Symbol symbol, TimeSpan resolution, PyObject selector = null, PyObject filter = null, string fieldName = null) { var name = string.Format("{0}({1}_{2})", symbol, fieldName ?? "close", resolution); var pyselector = PythonUtil.ToFunc <IBaseData, IBaseDataBar>(selector); var pyfilter = PythonUtil.ToFunc <IBaseData, bool>(filter); var filteredIdentity = new FilteredIdentity(name, pyfilter); RegisterIndicator(symbol, filteredIdentity, ResolveConsolidator(symbol, resolution), pyselector); return(filteredIdentity); }
/// <summary> /// Creates a new FilteredIdentity indicator for the symbol The indicator will be automatically /// updated on the symbol's subscription resolution /// </summary> /// <param name="symbol">The symbol whose values we want as an indicator</param> /// <param name="selector">Selects a value from the BaseData, if null defaults to the .Value property (x => x.Value)</param> /// <param name="filter">Filters the IBaseData send into the indicator, if null defaults to true (x => true) which means no filter</param> /// <param name="fieldName">The name of the field being selected</param> /// <returns>A new FilteredIdentity indicator for the specified symbol and selector</returns> public FilteredIdentity FilteredIdentity(Symbol symbol, PyObject selector = null, PyObject filter = null, string fieldName = null) { var resolution = GetSubscription(symbol).Resolution; return(FilteredIdentity(symbol, resolution, selector, filter, fieldName)); }
/// <summary> /// Gets the historical data for the specified symbols over the requested span. /// The symbols must exist in the Securities collection. /// </summary> /// <param name="type">The data type of the symbols</param> /// <param name="symbol">The symbol to retrieve historical data for</param> /// <param name="span">The span over which to retrieve recent historical data</param> /// <param name="resolution">The resolution to request</param> /// <returns>pandas.DataFrame containing the requested historical data</returns> public PyObject History(PyObject type, Symbol symbol, TimeSpan span, Resolution?resolution = null) { return(History(type, symbol, Time - span, Time, resolution)); }
/// <summary> /// Gets the historical data for the specified symbols over the requested span. /// The symbols must exist in the Securities collection. /// </summary> /// <param name="type">The data type of the symbols</param> /// <param name="tickers">The symbols to retrieve historical data for</param> /// <param name="span">The span over which to retrieve recent historical data</param> /// <param name="resolution">The resolution to request</param> /// <returns>pandas.DataFrame containing the requested historical data</returns> public PyObject History(PyObject type, PyObject tickers, TimeSpan span, Resolution?resolution = null) { return(History(type, tickers, Time - span, Time, resolution)); }
/// <summary> /// Initializes a new instance of the <see cref="CustomUniverseSelectionModel"/> class /// </summary> /// <param name="securityType">The security type of the universe</param> /// <param name="name">A unique name for this universe</param> /// <param name="market">The market of the universe</param> /// <param name="selector">Function delegate that accepts a DateTime and returns a collection of string symbols</param> /// <param name="universeSettings">The settings used when adding symbols to the algorithm, specify null to use algorithm.UniverseSettings</param> /// <param name="interval">The interval at which selection should be performed</param> public CustomUniverseSelectionModel(SecurityType securityType, string name, string market, PyObject selector, UniverseSettings universeSettings, TimeSpan interval) : this( securityType, name, market, selector.ConvertToDelegate <Func <DateTime, object> >().ConvertToUniverseSelectionStringDelegate(), universeSettings, interval ) { }
/// <summary> /// Converts the sequence of PyObject objects into an array of dynamic objects that represent indicators of the same type /// </summary> /// <returns>Array of dynamic objects with indicator</returns> private dynamic[] GetIndicatorArray(PyObject first, PyObject second = null, PyObject third = null, PyObject fourth = null) { using (Py.GIL()) { var array = new[] { first, second, third, fourth } .Select(x => { if (x == null) { return(null); } var type = (Type)x.GetPythonType().AsManagedObject(typeof(Type)); return((dynamic)x.AsManagedObject(type)); }).ToArray(); var types = array.Where(x => x != null).Select(x => GetIndicatorBaseType(x.GetType())).Distinct(); if (types.Count() > 1) { throw new Exception("QCAlgorithm.GetIndicatorArray(). All indicators must be of the same type: data point, bar or tradebar."); } return(array); } }
public static bool IsNone(this PyObject obj) { return(obj.IsInstance(PyNone.GetPythonType())); }
public PyTuple ToTuple() { PyObject[] a = new PyObject[] { new PyFloat(oldval), new PyFloat(newval) }; return(new PyTuple(a)); }
public Adam(float alpha = 0.001f, float beta1 = 0.9f, float beta2 = 0.999f, float eps = 1e-08f, float eta = 1.0f, float weight_decay_rate = 0, bool amsgrad = false) { _Adam = Chainer.Optimizers["Adam"].Call(alpha, beta1, beta2, eps, eta, weight_decay_rate, amsgrad); }
/// <summary> /// Sets the margin call model /// </summary> /// <param name="pyObject">Model that represents a portfolio's model to executed margin call orders.</param> public void SetMarginCallModel(PyObject pyObject) { SetMarginCallModel(new MarginCallModelPythonWrapper(pyObject)); }
public void Setup(PyObject link) { _Adam["setup"].Call(link); }
protected override void Execute(CodeActivityContext context) { string currentdir = System.IO.Directory.GetCurrentDirectory(); try { System.IO.Directory.SetCurrentDirectory(Interfaces.Extensions.ProjectsDirectory); var code = Code.Get(context); var language = Language.Get(context); var variables = new Dictionary <string, Type>(); var variablevalues = new Dictionary <string, object>(); var vars = context.DataContext.GetProperties(); foreach (dynamic v in vars) { Type rtype = v.PropertyType as Type; var value = v.GetValue(context.DataContext); if (rtype == null && value != null) { rtype = value.GetType(); } if (rtype == null) { continue; } variables.Add(v.DisplayName, rtype); variablevalues.Add(v.DisplayName, value); } string sourcecode = code; if (namespaces == null) { throw new Exception("InvokeCode is missing namespaces, please open workflow in designer and save changes"); } if (language == "VB") { var header = GetVBHeaderText(variables, "Expression", namespaces); sourcecode = header + code + GetVBFooterText(); int numLines = header.Split('\n').Length; Log.Debug("Header (add to line numbers): " + numLines); } if (language == "C#") { var header = GetCSharpHeaderText(variables, "Expression", namespaces); sourcecode = header + code + GetCSharpFooterText(); int numLines = header.Split('\n').Length; Log.Debug("Header (add to line numbers): " + numLines); } if (language == "PowerShell") { if (runspace == null) { runspace = RunspaceFactory.CreateRunspace(); runspace.Open(); } using (var pipeline = runspace.CreatePipeline()) { Command cmd = new Command(sourcecode, true); foreach (var parameter in variablevalues) { // cmd.Parameters.Add(parameter.Key, parameter.Value); runspace.SessionStateProxy.SetVariable(parameter.Key, parameter.Value); } pipeline.Commands.Add(cmd); var res = pipeline.Invoke(); foreach (var o in res) { if (o != null) { Log.Output(o.ToString()); } } foreach (dynamic v in vars) { var value = runspace.SessionStateProxy.GetVariable(v.DisplayName); var myVar = context.DataContext.GetProperties().Find(v.DisplayName, true); try { if (myVar != null && value != null) { //var myValue = myVar.GetValue(context.DataContext); myVar.SetValue(context.DataContext, value); } } catch (Exception ex) { Log.Error(ex.ToString()); } } PipelineOutput.Set(context, res); } return; } if (language == "AutoHotkey") { AppDomain Temporary = null; try { AppDomainSetup domaininfo = new AppDomainSetup(); domaininfo.ApplicationBase = global.CurrentDirectory; System.Security.Policy.Evidence adevidence = AppDomain.CurrentDomain.Evidence; Temporary = AppDomain.CreateDomain("Temporary", adevidence, domaininfo); Temporary.AssemblyResolve += AHKProxy.CurrentDomain_AssemblyResolve; //var ahk = (AutoHotkey.Interop.AutoHotkeyEngine)Temporary.CreateInstanceAndUnwrap("sharpAHK, Version=1.0.0.5, Culture=neutral, PublicKeyToken=null", "AutoHotkey.Interop.AutoHotkeyEngine"); Type type = typeof(AHKProxy); var ahk = (AHKProxy)Temporary.CreateInstanceAndUnwrap(type.Assembly.FullName, type.FullName); foreach (var parameter in variablevalues) { if (parameter.Value == null) { continue; } ahk.SetVar(parameter.Key, parameter.Value.ToString()); } ahk.ExecRaw(code); foreach (dynamic v in vars) { var value = ahk.GetVar(v.DisplayName); PropertyDescriptor myVar = context.DataContext.GetProperties().Find(v.DisplayName, true); if (myVar != null && value != null) { if (myVar.PropertyType == typeof(string)) { myVar.SetValue(context.DataContext, value); } else if (myVar.PropertyType == typeof(int)) { myVar.SetValue(context.DataContext, int.Parse(value.ToString())); } else if (myVar.PropertyType == typeof(bool)) { myVar.SetValue(context.DataContext, bool.Parse(value.ToString())); } else { Log.Information("Ignorering variable " + v.DisplayName + " of type " + myVar.PropertyType.FullName); } } } } catch (Exception ex) { Log.Error(ex.ToString()); throw; } finally { if (Temporary != null) { AppDomain.Unload(Temporary); } } return; } if (language == "Python") { try { GenericTools.RunUI(() => { if (PluginConfig.use_embedded_python) { System.IO.Directory.SetCurrentDirectory(Python.Included.Installer.EmbeddedPythonHome); } IntPtr lck = IntPtr.Zero; try { lck = PythonEngine.AcquireLock(); using (var scope = Py.CreateScope()) { foreach (var parameter in variablevalues) { PyObject pyobj = parameter.Value.ToPython(); scope.Set(parameter.Key, pyobj); } try { PythonOutput output = new PythonOutput(); dynamic sys = Py.Import("sys"); sys.stdout = output; sys.stderr = output; // PythonEngine.RunSimpleString(@" //import sys //from System import Console //class output(object): // def write(self, msg): // Console.Out.Write(msg) // def writelines(self, msgs): // for msg in msgs: // Console.Out.Write(msg) // def flush(self): // pass // def close(self): // pass //sys.stdout = sys.stderr = output() //"); } catch (Exception ex) { Log.Debug(ex.ToString()); } scope.Exec(code); foreach (var parameter in variablevalues) { PyObject pyobj = scope.Get(parameter.Key); if (pyobj == null) { continue; } PropertyDescriptor myVar = context.DataContext.GetProperties().Find(parameter.Key, true); if (myVar.PropertyType == typeof(string)) { myVar.SetValue(context.DataContext, pyobj.ToString()); } else if (myVar.PropertyType == typeof(int)) { myVar.SetValue(context.DataContext, int.Parse(pyobj.ToString())); } else if (myVar.PropertyType == typeof(bool)) { myVar.SetValue(context.DataContext, bool.Parse(pyobj.ToString())); } else { Log.Information("Ignorering variable " + parameter.Key + " of type " + myVar.PropertyType.FullName); } } } //lck = PythonEngine.AcquireLock(); //PythonEngine.Exec(code); } catch (Exception) { //Log.Error(ex.ToString()); throw; } finally { PythonEngine.ReleaseLock(lck); } }); //using (Python.Runtime.Py.GIL()) //{ // IntPtr lck = Python.Runtime.PythonEngine.AcquireLock(); // Python.Runtime.PythonEngine.Exec(code); // Python.Runtime.PythonEngine.ReleaseLock(lck); // //// create a Python scope // //using (var scope = Python.Runtime.Py.CreateScope()) // //{ // // //// convert the Person object to a PyObject // // //PyObject pyPerson = person.ToPython(); // // // create a Python variable "person" // // // scope.Set("person", pyPerson); // // // the person object may now be used in Python // // // string code = "fullName = person.FirstName + ' ' + person.LastName"; // // scope.Exec(code); // //} //} } catch (Exception) { throw; } finally { try { // Python.Runtime.PythonEngine.Shutdown(); } catch (Exception ex) { Log.Error(ex.ToString()); } } return; } var assemblyLocations = GetAssemblyLocations(); CompileAndRun(language, sourcecode, assemblyLocations.ToArray(), variablevalues, context); } finally { System.IO.Directory.SetCurrentDirectory(currentdir); } }
public PyRangeAccess(PyObject obj) { this.obj = obj; }
// auto-generated class public Sigmoid(PyObject pyobj) : base(pyobj) { }
public PyTuple ToTuple() { PyObject[] a = new PyObject[] { new PyInt(btn), new PyFloat(rt) }; return(new PyTuple(a)); }
public override PyObject Run(PyTuple args, object client) { Log.Debug("machoNet", "Called GetInitVals stub"); if (Cache.LoadCacheFor("machoNet.serviceInfo") == false) { // Cache does not exists, create it PyDict dict = new PyDict(); dict.Set("trademgr", new PyString("station")); dict.Set("tutorialSvc", new PyString("station")); dict.Set("bookmark", new PyString("station")); dict.Set("slash", new PyString("station")); dict.Set("wormholeMgr", new PyString("station")); dict.Set("account", new PyString("station")); dict.Set("gangSvc", new PyString("station")); dict.Set("contractMgr", new PyString("station")); dict.Set("LSC", new PyString("location")); dict.Set("station", new PyString("location")); dict.Set("config", new PyString("locationPreferred")); dict.Set("scanMgr", new PyString("solarsystem")); dict.Set("keeper", new PyString("solarsystem")); dict.Set("stationSvc", new PyNone()); dict.Set("zsystem", new PyNone()); dict.Set("invbroker", new PyNone()); dict.Set("droneMgr", new PyNone()); dict.Set("userSvc", new PyNone()); dict.Set("map", new PyNone()); dict.Set("beyonce", new PyNone()); dict.Set("standing2", new PyNone()); dict.Set("ram", new PyNone()); dict.Set("DB", new PyNone()); dict.Set("posMgr", new PyNone()); dict.Set("voucher", new PyNone()); dict.Set("entity", new PyNone()); dict.Set("damageTracker", new PyNone()); dict.Set("agentMgr", new PyNone()); dict.Set("dogmaIM", new PyNone()); dict.Set("machoNet", new PyNone()); dict.Set("dungeonExplorationMgr", new PyNone()); dict.Set("watchdog", new PyNone()); dict.Set("ship", new PyNone()); dict.Set("DB2", new PyNone()); dict.Set("market", new PyNone()); dict.Set("dungeon", new PyNone()); dict.Set("npcSvc", new PyNone()); dict.Set("sessionMgr", new PyNone()); dict.Set("allianceRegistry", new PyNone()); dict.Set("cache", new PyNone()); dict.Set("character", new PyNone()); dict.Set("factory", new PyNone()); dict.Set("facWarMgr", new PyNone()); dict.Set("corpStationMgr", new PyNone()); dict.Set("authentication", new PyNone()); dict.Set("effectCompiler", new PyNone()); dict.Set("charmgr", new PyNone()); dict.Set("BSD", new PyNone()); dict.Set("reprocessingSvc", new PyNone()); dict.Set("billingMgr", new PyNone()); dict.Set("billMgr", new PyNone()); dict.Set("lookupSvc", new PyNone()); dict.Set("emailreader", new PyNone()); dict.Set("lootSvc", new PyNone()); dict.Set("http", new PyNone()); dict.Set("repairSvc", new PyNone()); dict.Set("gagger", new PyNone()); dict.Set("dataconfig", new PyNone()); dict.Set("lien", new PyNone()); dict.Set("i2", new PyNone()); dict.Set("pathfinder", new PyNone()); dict.Set("alert", new PyNone()); dict.Set("director", new PyNone()); dict.Set("dogma", new PyNone()); dict.Set("aggressionMgr", new PyNone()); dict.Set("corporationSvc", new PyNone()); dict.Set("certificateMgr", new PyNone()); dict.Set("clones", new PyNone()); dict.Set("jumpCloneSvc", new PyNone()); dict.Set("insuranceSvc", new PyNone()); dict.Set("corpmgr", new PyNone()); dict.Set("warRegistry", new PyNone()); dict.Set("corpRegistry", new PyNone()); dict.Set("objectCaching", new PyNone()); dict.Set("counter", new PyNone()); dict.Set("petitioner", new PyNone()); dict.Set("LPSvc", new PyNone()); dict.Set("clientStatsMgr", new PyNone()); dict.Set("jumpbeaconsvc", new PyNone()); dict.Set("debug", new PyNone()); dict.Set("languageSvc", new PyNone()); dict.Set("skillMgr", new PyNone()); dict.Set("voiceMgr", new PyNone()); dict.Set("onlineStatus", new PyNone()); dict.Set("gangSvcObjectHandler", new PyNone()); Cache.SaveCacheFor("machoNet.serviceInfo", dict, DateTime.Now.ToFileTime()); } PyObject srvInfo = Cache.GetCacheData("machoNet.serviceInfo"); PyTuple res = new PyTuple(); res.Items.Add(srvInfo); res.Items.Add(new PyNone()); // Rest of the cache data return(res); }
/// <summary> /// Constructor for initialising the <see cref="FeeModelPythonWrapper"/> class with wrapped <see cref="PyObject"/> object /// </summary> /// <param name="model">Represents a model that simulates order fees</param> public FeeModelPythonWrapper(PyObject model) { _model = model; }
/// <summary> /// Initializes a new instance of the <see cref="CustomUniverseSelectionModel"/> class /// for <see cref="Market.USA"/> and <see cref="SecurityType.Equity"/> /// using the algorithm's universe settings /// </summary> /// <param name="name">A unique name for this universe</param> /// <param name="selector">Function delegate that accepts a DateTime and returns a collection of string symbols</param> public CustomUniverseSelectionModel(string name, PyObject selector) : this(SecurityType.Equity, name, Market.USA, selector, null, Time.OneDay) { }
/// <summary> /// Constructor for initialising the <see cref="IRiskManagementModel"/> class with wrapped <see cref="PyObject"/> object /// </summary> /// <param name="model">Model defining how risk is managed</param> public RiskManagementModelPythonWrapper(PyObject model) { _model = model.ValidateImplementationOf <IRiskManagementModel>(); }
/// <summary> /// Sets the brokerage to emulate in backtesting or paper trading. /// This can be used to set a custom brokerage model. /// </summary> /// <param name="model">The brokerage model to use</param> public void SetBrokerageModel(PyObject model) { SetBrokerageModel(new BrokerageModelPythonWrapper(model)); }
/// <summary> /// Internally-consumed variation on issubclass that assesses if a given object is a child of a /// given class. This is a simplified helper for getting the type of o first and then figuring out /// issubclass on that type. /// </summary> /// <param name="o">The object to test.</param> /// <param name="parent">The type of the class to test against this object</param> /// <returns>True if o's class type is derived from parent. False otherwise.</returns> public static bool issubclass(PyObject o, PyClass parent) { return(issubclass(builtin_type(o), parent)); }
/// <summary> /// AddData a new user defined data source, requiring only the minimum config options. /// </summary> /// <param name="type">Data source type</param> /// <param name="symbol">Key/Symbol for data</param> /// <param name="resolution">Resolution of the Data Required</param> /// <param name="timeZone">Specifies the time zone of the raw data</param> /// <param name="fillDataForward">When no data available on a tradebar, return the last data that was generated</param> /// <param name="leverage">Custom leverage per security</param> /// <returns>The new <see cref="Security"/></returns> public Security AddData(PyObject type, string symbol, Resolution resolution, DateTimeZone timeZone, bool fillDataForward = false, decimal leverage = 1.0m) { return(AddData(CreateType(type), symbol, resolution, timeZone, fillDataForward, leverage)); }
public static bool isinstance(PyObject obj, PyClass _class) { return(obj.__class__ == _class); }
/// <summary> /// AddData a new user defined data source, requiring only the minimum config options. /// The data is added with a default time zone of NewYork (Eastern Daylight Savings Time) /// </summary> /// <param name="type">Data source type</param> /// <param name="symbol">Key/Symbol for data</param> /// <param name="resolution">Resolution of the data</param> /// <returns>The new <see cref="Security"/></returns> public Security AddData(PyObject type, string symbol, Resolution resolution = Resolution.Minute) { return(AddData(type, symbol, resolution, TimeZones.NewYork, false, 1m)); }
public static PyClass builtin_type(PyObject obj) { return(obj.__class__); }
/// <summary> /// Creates a new FilteredIdentity indicator for the symbol The indicator will be automatically /// updated on the symbol's subscription resolution /// </summary> /// <param name="symbol">The symbol whose values we want as an indicator</param> /// <param name="resolution">The desired resolution of the data</param> /// <param name="selector">Selects a value from the BaseData, if null defaults to the .Value property (x => x.Value)</param> /// <param name="filter">Filters the IBaseData send into the indicator, if null defaults to true (x => true) which means no filter</param> /// <param name="fieldName">The name of the field being selected</param> /// <returns>A new FilteredIdentity indicator for the specified symbol and selector</returns> public FilteredIdentity FilteredIdentity(Symbol symbol, Resolution resolution, PyObject selector = null, PyObject filter = null, string fieldName = null) { var name = CreateIndicatorName(symbol, fieldName ?? "close", resolution); var pyselector = PythonUtil.ToFunc <IBaseData, IBaseDataBar>(selector); var pyfilter = PythonUtil.ToFunc <IBaseData, bool>(filter); var filteredIdentity = new FilteredIdentity(name, pyfilter); RegisterIndicator(symbol, filteredIdentity, resolution, pyselector); return(filteredIdentity); }
/// <summary> /// Implements the dir() command used to dump methods and properties of this PyObject. /// </summary> /// <param name="o">The object to inspect</param> /// <returns>A PyList of the names of the methods and properties of this PyObject.</returns> //public static async Task<PyList> dir(IInterpreter interpreter, FrameContext context, PyObject o) public static async Task <object> dir(IInterpreter interpreter, FrameContext context, PyObject o) { // TODO: Figure out how to switch to Task<PyList> signature without everything hanging. var internalList = new List <PyObject>(); foreach (var name in o.__dict__.Keys) { internalList.Add(PyString.Create(name)); } // Alphabetize them. It's how Python does it and it is quite useful for scanning through the output anyways. internalList.Sort((a, b) => a.ToString().CompareTo(b.ToString())); var retList = (PyList)await PyListClass.Instance.Call(interpreter, context, new object[0]); retList.SetList(internalList); return(retList); }
public static bool IsString(this PyObject obj) { return(PyString.IsStringType(obj)); }
public static bool IsInt(this PyObject obj) { return(PyInt.IsIntType(obj)); }