protected override Node Evaluate(Env env) { Guard.ExpectMinArguments(2, Arguments.Count, this, Index); Guard.ExpectMaxArguments(3, Arguments.Count, this, Index); Guard.ExpectAllNodes<Color>(Arguments.Take(2), this, Index); double weight = 50; if (Arguments.Count == 3) { Guard.ExpectNode<Number>(Arguments[2], this, Index); weight = ((Number) Arguments[2]).Value; } var colors = Arguments.Take(2).Cast<Color>().ToArray(); // Note: this algorithm taken from http://github.com/nex3/haml/blob/0e249c844f66bd0872ed68d99de22b774794e967/lib/sass/script/functions.rb var p = weight/100.0; var w = p*2 - 1; var a = colors[0].Alpha - colors[1].Alpha; var w1 = (((w*a == -1) ? w : (w + a)/(1 + w*a)) + 1)/2.0; var w2 = 1 - w1; var rgb = colors[0].RGB.Select((x, i) => x*w1 + colors[1].RGB[i]*w2).ToArray(); var alpha = colors[0].Alpha*p + colors[1].Alpha*(1 - p); var color = new Color(rgb[0], rgb[1], rgb[2], alpha); return color; }
public override void AppendCSS(Env env) { env.Output .Append("alpha(opacity=") .Append(Value) .Append(")"); }
public void AddExtension(Selector selector, Extend extends, Env env) { foreach (var extending in extends.Exact) { Extender match = null; if ((match = Extensions.OfType<ExactExtender>().FirstOrDefault(e => e.BaseSelector.ToString().Trim() == extending.ToString().Trim())) == null) { match = new ExactExtender(extending, extends); Extensions.Add(match); } match.AddExtension(selector, env); } foreach (var extending in extends.Partial) { Extender match = null; if ((match = Extensions.OfType<PartialExtender>().FirstOrDefault(e => e.BaseSelector.ToString().Trim() == extending.ToString().Trim())) == null) { match = new PartialExtender(extending, extends); Extensions.Add(match); } match.AddExtension(selector, env); } }
protected override void AppendCSS(Env env, Context context) { if (env.Compress && Rules != null && !Rules.Any()) return; env.Output.Append(Name); if (!string.IsNullOrEmpty(Identifier)) { env.Output.Append(" "); env.Output.Append(Identifier); } if (Rules != null) { // Append pre comments as we out put each rule ourselves if (Rules.PreComments) { env.Output.Append(Rules.PreComments); } AppendRules(env); env.Output.Append("\n"); } else { env.Output .Append(" ") .Append(Value) .Append(";\n"); } }
public void Execute(LiteEngine engine, StringScanner s, Display display, InputCommand input, Env env) { var col = this.ReadCollection(engine, s); var index = s.Scan(this.FieldPattern).Trim(); display.WriteResult(engine.Max(col, index.Length == 0 ? "_id" : index)); }
public override string ToCSS(Env env) { if (!string.IsNullOrEmpty(_css)) return _css; return _css = Elements.Select(e => e.ToCSS(env)).JoinStrings(""); }
public override string ToCSS(Env env) { if (Variable) return ""; return Name + (env.Compress ? ":" : ": ") + Value.ToCSS(env) + ";"; }
public override Node Evaluate(Env env) { if (env == null) { throw new ArgumentNullException("env"); } var args = Arguments.Select(a => a.Evaluate(env)); var function = env.GetFunction(Name); if (function != null) { function.Name = Name; function.Location = Location; return function.Call(env, args).ReducedFrom<Node>(this); } env.Output.Push(); env.Output .Append(Name) .Append("(") .AppendMany(args, env.Compress ? "," : ", ") .Append(")"); var css = env.Output.Pop(); return new TextNode(css.ToString()).ReducedFrom<Node>(this); }
public override Node Evaluate(Env env) { if (Values.Count == 1 && string.IsNullOrEmpty(Important)) return Values[0].Evaluate(env); return new Value(Values.Select(n => n.Evaluate(env)), Important); }
protected override Node Evaluate(Env env) { Guard.ExpectNumArguments(1, Arguments.Count, this, Location); var color = Guard.ExpectNode<Color>(Arguments[0], this, Location); return new TextNode(color.ToArgb()); }
public BDB43(string file, string table, bool create, DBFormat format, bool allowDuplicates, Env environment) { this.env = environment; db_create(out dbp, environment.envptr, 0); funcs = (dbstruct)Marshal.PtrToStructure((IntPtr)((int)dbp+268), typeof(dbstruct)); uint dbflags = DB_DIRECT_DB; if (allowDuplicates) dbflags |= DB_DUP; // DB_DUPSORT; funcs.set_flags(dbp, dbflags); int type = (int)format; uint flags = DB_DIRTY_READ; // | DB_AUTO_COMMIT; int chmod_mode = 0; if (create) flags |= DB_CREATE; // if file & database are null, db is held in-memory // on file is taken as UTF8 (is this call right?) int ret = funcs.open(dbp, env.Txn, file, table, type, flags, chmod_mode); CheckError(ret); binfmt = new Serializer(); }
protected override void AppendCSS(Env env, Context context) { env.Output.Append(Name); if (Rules != null) { env.Output .Append(env.Compress ? "{" : " {\n") .Push() .AppendMany(Rules, "\n") .Trim() .Indent(env.Compress ? 0 : 2) .PopAndAppend() .Append(env.Compress ? "}" : "\n}\n"); return; } env.Output .Append(" ") .Append(Value) .Append(";\n"); }
public List<Closure> Find(Env env, Selector selector, Ruleset self) { self = self ?? this; var rules = new List<Closure>(); var key = selector.ToCSS(env); if (_lookups.ContainsKey(key)) return _lookups[key]; foreach (var rule in Rulesets().Where(rule => rule != self)) { if (rule.Selectors && rule.Selectors.Any(selector.Match)) { if (selector.Elements.Count > 1) { var remainingSelectors = new Selector(new NodeList<Element>(selector.Elements.Skip(1))); var closures = rule.Find(env, remainingSelectors, self); foreach (var closure in closures) { closure.Context.Insert(0, rule); } rules.AddRange(closures); } else rules.Add(new Closure { Ruleset = rule, Context = new List<Ruleset> { rule } }); } } return _lookups[key] = rules; }
public override void AppendCSS(Env env) { if (!Rules.Any()) return; ((Ruleset) Evaluate(env)).AppendCSS(env, new Context()); }
private UtilsManager(Env env, string serverName, string catalog) { _serverName = serverName; _catalog = catalog; this._env = env; _valuesForCombo = new Dictionary<string, IEnumerable<string>>(); }
protected override Node Evaluate(Env env) { Guard.ExpectNumArguments(1, Arguments.Count, this, Location); Guard.ExpectNode<TextNode>(Arguments[0], this, Location); var argument = ((TextNode) Arguments[0]); string rgb; if (!argument.Value.StartsWith("#")) { var color = Color.GetColorFromKeyword(argument.Value); if (color != null) { return color; } rgb = argument.Value; } else { rgb = argument.Value.TrimStart('#'); } try { return new Color(rgb); } catch (FormatException ex) { throw new ParsingException(string.Format("Invalid RGB color string '{0}'", rgb), ex, Location, null); } }
public ISemantReturn<ImmutableList<Tuple<Env, ExternDecln>>> GetExternDecln(Env env) { var storageClass = this.Specs.GetStorageClass(); var baseType = Semant(this.Specs.GetExprType, ref env); var name = this.Declr.Name; var type = Semant(this.Declr.DecorateType, baseType, ref env); var funcType = type as FunctionType; if (funcType == null) { throw new InvalidOperationException("Expected a function Type."); } switch (storageClass) { case StorageClass.AUTO: case StorageClass.EXTERN: case StorageClass.STATIC: env = env.PushEntry(Env.EntryKind.GLOBAL, name, type); break; case StorageClass.TYPEDEF: default: throw new InvalidOperationException("Invalid storage class specifier for function definition."); } env = env.InScope(); env = env.SetCurrentFunction(funcType); var stmt = SemantStmt(this.Stmt.GetStmt, ref env); env = env.OutScope(); return SemantReturn.Create(env, ImmutableList.Create(Tuple.Create(env, new ABT.FuncDef(name, storageClass, funcType, stmt) as ExternDecln))); }
static void Main(string[] args) { StreamReader srd = null; StreamWriter swr = null; Env env = new Env(); try { srd = new StreamReader( args[0], Encoding.GetEncoding("Shift_JIS")); env.srd = srd; } catch (Exception e) { Console.WriteLine(e.Message); } try { swr = new StreamWriter( args[1], false, Encoding.GetEncoding("Shift_JIS")); env.swr = swr; } catch (Exception e) { Console.WriteLine(e.Message); } probLoop(env); swr.Close(); }
public override void AppendCSS(Env env) { if (Variable) return; var value = Value; env.Output .Append(Name) .Append(PostNameComments) .Append(env.Compress ? ":" : ": "); env.Output.Push() .Append(value); if (env.Compress) { env.Output.Reset(Regex.Replace(env.Output.ToString(), @"(\s)+", " ").Replace(", ", ",")); } env.Output.PopAndAppend(); if (IsSemiColonRequired) { env.Output.Append(";"); } }
public override void AppendCSS(Env env) { env.Output .Append('(') .Append(Value) .Append(')'); }
public override Node Evaluate(Env env) { var args = Arguments.Select(a => a.Evaluate(env)); if (env != null) { var function = env.GetFunction(Name); if (function != null) { function.Name = Name; function.Index = Index; return function.Call(env, args); } } env.Output.Push(); env.Output .Append(Name) .Append("(") .AppendMany(Arguments.Select(a => a.Evaluate(env)), ", ") .Append(")"); var css = env.Output.Pop(); return new TextNode(css.ToString()); }
public override void AppendCSS(Env env) { env.Output .Append(First) .Append("/") .Append(Second); }
public override Node Evaluate(Env env) { var a = First.Evaluate(env); var b = Second.Evaluate(env); if (a is Number && b is Color) { if (Operator == "*" || Operator == "+") { var temp = b; b = a; a = temp; } else throw new ParsingException("Can't substract or divide a color from a number", Index); } try { var operable = a as IOperable; if (operable != null) return operable.Operate(this, b).ReducedFrom<Node>(this); throw new ParsingException(string.Format("Cannot apply operator {0} to the left hand side: {1}", Operator, a.ToCSS(env)), Index); } catch (DivideByZeroException e) { throw new ParsingException(e, Index); } catch (InvalidOperationException e) { throw new ParsingException(e, Index); } }
public override Node Evaluate(Env env) { if(Evaluated) return this; try { env = env ?? new Env(); env.Frames.Push(this); NodeHelper.ExpandNodes<Import>(env, Rules); env.Frames.Pop(); var clone = new Root(new NodeList(Rules), Error, OriginalRuleset); clone = DoVisiting(clone, env, VisitorPluginType.BeforeEvaluation); clone.ReducedFrom<Root>(this); clone.EvaluateRules(env); clone.Evaluated = true; clone = DoVisiting(clone, env, VisitorPluginType.AfterEvaluation); return clone; } catch (ParsingException e) { throw Error(e); } }
public override void AppendCSS(Env env) { env.Output .Append("url(") .Append(Value) .Append(")"); }
public override void AppendCSS(Env env) { env.Output .Append(Key) .Append("=") .Append(Value); }
protected override Node Evaluate(Env env) { if (Arguments.Count == 0) return new Quoted("", false); Func<Node, string> stringValue = n => n is Quoted ? ((Quoted)n).Value : n.ToCSS(env); var str = stringValue(Arguments[0]); var args = Arguments.Skip(1).ToArray(); var i = 0; MatchEvaluator replacement = m => { var value = (m.Value == "%s") ? stringValue(args[i++]) : args[i++].ToCSS(env); return char.IsUpper(m.Value[1]) ? Uri.EscapeDataString(value) : value; }; str = Regex.Replace(str, "%[sda]", replacement, RegexOptions.IgnoreCase); var quote = Arguments[0] is Quoted ? (Arguments[0] as Quoted).Quote : null; return new Quoted(str, quote); }
public override Node Evaluate(Env env) { int blockIndex = env.MediaBlocks.Count; env.MediaBlocks.Add(this); env.MediaPath.Push(this); env.Frames.Push(Ruleset); NodeHelper.ExpandNodes<Import>(env, Ruleset.Rules); env.Frames.Pop(); var features = Features.Evaluate(env); var ruleset = Ruleset.Evaluate(env) as Ruleset; var media = new Media(features, ruleset,Extensions).ReducedFrom<Media>(this); env.MediaPath.Pop(); env.MediaBlocks[blockIndex] = media; if (env.MediaPath.Count == 0) { return media.EvalTop(env); } else { return media.EvalNested(env, features, ruleset); } }
public override EvaluationResult Evaluate(Env env) { int left = (int)Left.Evaluate(env).Result; int right = (int)Right.Evaluate(env).Result; bool result; switch (RELOP) { case "==": result = left == right; break; case "!=": result = left != right; break; case ">": result = left > right; break; case "<": result = left < right; break; case ">=": result = left >= right; break; case "<=": result = left <= right; break; default: throw new InvalidOperationException("Unknown operator: " + RELOP); } return new EvaluationResult { Result = result }; }
protected override Node Evaluate(Env env) { Guard.ExpectNumArguments(1, Arguments.Count, this, Location); Guard.ExpectNode<TextNode>(Arguments[0], this, Location); return new Color(((TextNode)Arguments[0]).Value.TrimStart('#')); }
public virtual MixinMatch MatchArguments(List <NamedArgument> arguments, Env env) { return((arguments == null || arguments.Count == 0) ? MixinMatch.Pass : MixinMatch.ArgumentMismatch); }
/// <summary> /// Before Save /// </summary> /// <param name="newRecord">new</param> /// <returns>true</returns> protected override Boolean BeforeSave(Boolean newRecord) { // By vikas // Get Old Value of AttributeSetInstance_ID _mvlOldAttId = Util.GetValueOfInt(Get_ValueOld("M_AttributeSetInstance_ID")); // Set Line No if (GetLine() == 0) { String sql = "SELECT COALESCE(MAX(Line),0)+10 AS DefaultValue FROM M_MovementLine WHERE M_Movement_ID=" + GetM_Movement_ID(); int ii = DB.GetSQLValue(Get_TrxName(), sql); SetLine(ii); } // Check Locator For Header Warehouse MMovement mov = new MMovement(GetCtx(), GetM_Movement_ID(), Get_TrxName()); VAdvantage.Model.MLocator loc = new VAdvantage.Model.MLocator(GetCtx(), GetM_Locator_ID(), Get_TrxName()); Tuple <string, string, string> aInfo = null; if (Env.HasModulePrefix("DTD001_", out aInfo)) { if (mov.GetDTD001_MWarehouseSource_ID() == loc.GetM_Warehouse_ID()) { } else { String sql = "SELECT M_Locator_ID FROM M_Locator WHERE M_Warehouse_ID=" + mov.GetDTD001_MWarehouseSource_ID() + " AND IsDefault = 'Y'"; int ii = DB.GetSQLValue(Get_TrxName(), sql); SetM_Locator_ID(ii); } } if (GetM_Locator_ID() == GetM_LocatorTo_ID()) { log.SaveError("Error", Msg.ParseTranslation(GetCtx(), "'From @M_Locator_ID@' and '@M_LocatorTo_ID@' cannot be same."));//change message according to requirement return(false); } if (Env.Signum(GetMovementQty()) == 0 && Util.GetValueOfInt(GetTargetQty()) == 0) { log.SaveError("FillMandatory", Msg.GetElement(GetCtx(), "MovementQty")); return(false); } //Amit Tuple <String, String, String> mInfo = null; if (Env.HasModulePrefix("DTD001_", out mInfo)) { if (!newRecord && Util.GetValueOfInt(Get_ValueOld("M_Product_ID")) != GetM_Product_ID()) { log.SaveError("Message", Msg.GetMsg(GetCtx(), "DTD001_ProdNotChanged")); return(false); } if (!newRecord && Util.GetValueOfInt(Get_ValueOld("M_Locator_ID")) != GetM_Locator_ID()) { log.SaveError("Message", Msg.GetMsg(GetCtx(), "DTD001_LocatorNotChanged")); return(false); } if (!newRecord && Util.GetValueOfInt(Get_ValueOld("M_RequisitionLine_ID")) != GetM_RequisitionLine_ID()) { log.SaveError("Message", Msg.GetMsg(GetCtx(), "DTD001_ReqNotChanged")); return(false); } } if (Util.GetValueOfInt(DB.ExecuteScalar("SELECT COUNT(AD_MODULEINFO_ID) FROM AD_MODULEINFO WHERE PREFIX='VA203_'", null, null)) > 0) { if (GetM_RequisitionLine_ID() > 0) { VAdvantage.Model.MRequisitionLine reqline = new VAdvantage.Model.MRequisitionLine(GetCtx(), GetM_RequisitionLine_ID(), null); if (GetM_AttributeSetInstance_ID() != reqline.GetM_AttributeSetInstance_ID()) { log.SaveError("Message", Msg.GetMsg(GetCtx(), "VA203_AttributeInstanceMustBeSame")); return(false); } } } // IF Doc Status = InProgress then No record Save MMovement move = new MMovement(GetCtx(), GetM_Movement_ID(), null); if (newRecord && move.GetDocStatus() == "IP") { log.SaveError("Message", Msg.GetMsg(GetCtx(), "DTD001_CannotCreate")); return(false); } // Qty Precision if (newRecord || Is_ValueChanged("QtyEntered")) { SetMovementQty(GetMovementQty()); } int M_Warehouse_ID = 0; VAdvantage.Model.MWarehouse wh = null; string qry = "select m_warehouse_id from m_locator where m_locator_id=" + GetM_Locator_ID(); M_Warehouse_ID = Util.GetValueOfInt(DB.ExecuteScalar(qry)); wh = VAdvantage.Model.MWarehouse.Get(GetCtx(), M_Warehouse_ID); qry = "SELECT NVL(SUM(NVL(QtyOnHand,0)),0) AS QtyOnHand FROM M_Storage where m_locator_id=" + GetM_Locator_ID() + " and m_product_id=" + GetM_Product_ID(); if (GetM_AttributeSetInstance_ID() != 0) { qry += " AND M_AttributeSetInstance_ID=" + GetM_AttributeSetInstance_ID(); } OnHandQty = Convert.ToDecimal(DB.ExecuteScalar(qry)); // when record is in completed & closed & Reversed stage - then no need to check qty availablity in warehouse if (wh.IsDisallowNegativeInv() == true && (!(move.GetDocStatus() == "CO" || move.GetDocStatus() == "CL" || move.GetDocStatus() == "RE"))) { if (GetDescription() != "RC") { if (GetMovementQty() < 0) { log.SaveError("Error", Msg.GetMsg(GetCtx(), "Qty Available " + OnHandQty)); //ShowMessage.Info("Qty Available " + OnHandQty, true, null, null); return(false); } else if ((OnHandQty - GetMovementQty()) < 0) { log.SaveError("Error", Msg.GetMsg(GetCtx(), "Qty Available " + OnHandQty)); //ShowMessage.Info("Qty Available " + OnHandQty, true, null, null); return(false); } } } if (Env.HasModulePrefix("DTD001_", out mInfo)) { qry = "SELECT NVL(SUM(NVL(QtyOnHand,0)- qtyreserved),0) AS QtyAvailable FROM M_Storage where m_locator_id=" + GetM_Locator_ID() + " and m_product_id=" + GetM_Product_ID(); if (GetM_AttributeSetInstance_ID() != 0) { qry += " AND M_AttributeSetInstance_ID=" + GetM_AttributeSetInstance_ID(); } qtyAvailable = Convert.ToDecimal(DB.ExecuteScalar(qry)); qtyReserved = Util.GetValueOfDecimal(Get_ValueOld("MovementQty")); if (wh.IsDisallowNegativeInv() == true) { if ((qtyAvailable < (GetMovementQty() - qtyReserved))) { log.SaveError("Message", Msg.GetElement(GetCtx(), "DTD001_QtyNotAvailable")); return(false); } } } // Mandatory Instance if (GetM_AttributeSetInstanceTo_ID() == 0) { if (GetM_AttributeSetInstance_ID() != 0) // Set to from { SetM_AttributeSetInstanceTo_ID(GetM_AttributeSetInstance_ID()); } else { if (Env.HasModulePrefix("DTD001_", out mInfo)) { VAdvantage.Model.MProduct product = GetProduct(); if (product != null && product.GetM_AttributeSet_ID() != 0) { //MAttributeSet mas = MAttributeSet.Get(GetCtx(), product.GetM_AttributeSet_ID()); //if (mas.IsInstanceAttribute() // && (mas.IsMandatory() || mas.IsMandatoryAlways())) //{ // log.SaveError("FillMandatory", Msg.GetElement(GetCtx(), "M_AttributeSetInstanceTo_ID")); // return false; //} // Code Addeded by Bharat as Discussed with Mukesh Sir if (String.IsNullOrEmpty(GetDTD001_AttributeNumber())) { return(true); } else { if (GetDTD001_AttributeNumber() == "" || GetDTD001_AttributeNumber() == null) { log.SaveError("FillMandatory", Msg.GetElement(GetCtx(), "DTD001_AttributeNumber")); return(false); } } } else { if (product != null) { if (product.GetM_AttributeSet_ID() == 0 && (GetDTD001_AttributeNumber() == "" || GetDTD001_AttributeNumber() == null)) { return(true); } else { //log.SaveError("FillMandatory", Msg.GetElement(GetCtx(), "DTD001_AttributeNumber")); //ShowMessage.Info("a", true, "Product is not of Attribute Type", null); log.SaveError("Product is not of Attribute Type", Msg.GetElement(GetCtx(), "DTD001_AttributeNumber")); return(false); } //Check No Of Attributes Are Equal To Quantity Or Less Than int Count = CountAttributes(GetDTD001_AttributeNumber()); if (Count != GetMovementQty()) { if (Count > GetMovementQty()) { log.SaveError("Error", Msg.GetMsg(GetCtx(), "DTD001_MovementAttrbtGreater")); return(false); } else { log.SaveError("Error", Msg.GetMsg(GetCtx(), "DTD001_MovementAttrbtLess")); return(false); } } } } } else { VAdvantage.Model.MProduct product = GetProduct(); if (product != null && product.GetM_AttributeSet_ID() != 0) { VAdvantage.Model.MAttributeSet mas = VAdvantage.Model.MAttributeSet.Get(GetCtx(), product.GetM_AttributeSet_ID()); if (mas.IsInstanceAttribute() && (mas.IsMandatory() || mas.IsMandatoryAlways())) { log.SaveError("FillMandatory", Msg.GetElement(GetCtx(), "M_AttributeSetInstanceTo_ID")); return(false); } } } } } // ASI return(true); }
public Object marshal(Env env, Value value, Class expectedClass) { return(value.toUnicodeValue(env)); }
[ConditionalFact(typeof(Environment), nameof(Environment.Is64BitProcess))] // x86 fails with "An attempt was made to load a program with an incorrect format." void TestOldSavingAndLoading() { if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { return; } var modelFile = "squeezenet/00000001/model.onnx"; var samplevector = GetSampleArrayData(); var dataView = ComponentCreation.CreateDataView(Env, new TestData[] { new TestData() { data_0 = samplevector } }); var inputNames = new[] { "data_0" }; var outputNames = new[] { "softmaxout_1" }; var est = new OnnxScoringEstimator(Env, modelFile, inputNames, outputNames); var transformer = est.Fit(dataView); var result = transformer.Transform(dataView); var resultRoles = new RoleMappedData(result); using (var ms = new MemoryStream()) { TrainUtils.SaveModel(Env, Env.Start("saving"), ms, null, resultRoles); ms.Position = 0; var loadedView = ModelFileUtils.LoadTransforms(Env, dataView, ms); loadedView.Schema.TryGetColumnIndex(outputNames[0], out int softMaxOut1); using (var cursor = loadedView.GetRowCursor(col => col == softMaxOut1)) { VBuffer <float> softMaxValue = default; var softMaxGetter = cursor.GetGetter <VBuffer <float> >(softMaxOut1); float sum = 0f; int i = 0; while (cursor.MoveNext()) { softMaxGetter(ref softMaxValue); var values = softMaxValue.DenseValues(); foreach (var val in values) { sum += val; if (i == 0) { Assert.InRange(val, 0.00004, 0.00005); } if (i == 1) { Assert.InRange(val, 0.003844, 0.003845); } if (i == 999) { Assert.InRange(val, 0.0029566, 0.0029567); } i++; } } Assert.InRange(sum, 1.0, 1.00001); } } }
public void TestOldSavingAndLoading(int?gpuDeviceId, bool fallbackToCpu) { var modelFile = "squeezenet/00000001/model.onnx"; var samplevector = GetSampleArrayData(); var dataView = ML.Data.LoadFromEnumerable( new TestData[] { new TestData() { data_0 = samplevector } }); var inputNames = new[] { "data_0" }; var outputNames = new[] { "softmaxout_1" }; var est = ML.Transforms.ApplyOnnxModel(outputNames, inputNames, modelFile, gpuDeviceId, fallbackToCpu); var transformer = est.Fit(dataView); var result = transformer.Transform(dataView); var resultRoles = new RoleMappedData(result); using (var ms = new MemoryStream()) { TrainUtils.SaveModel(Env, Env.Start("saving"), ms, null, resultRoles); ms.Position = 0; var loadedView = ModelFileUtils.LoadTransforms(Env, dataView, ms); var sofMaxOut1Col = loadedView.Schema[outputNames[0]]; using (var cursor = loadedView.GetRowCursor(sofMaxOut1Col)) { VBuffer <float> softMaxValue = default; var softMaxGetter = cursor.GetGetter <VBuffer <float> >(sofMaxOut1Col); float sum = 0f; int i = 0; while (cursor.MoveNext()) { softMaxGetter(ref softMaxValue); var values = softMaxValue.DenseValues(); foreach (var val in values) { sum += val; if (i == 0) { Assert.InRange(val, 0.00004, 0.00005); } if (i == 1) { Assert.InRange(val, 0.003844, 0.003845); } if (i == 999) { Assert.InRange(val, 0.0029566, 0.0029567); } i++; } } Assert.InRange(sum, 0.99999, 1.00001); } (transformer as IDisposable)?.Dispose(); } }
private static GlobalRef GetMethod(string name, string signature) { return(Env.GetMethodId(ClassPtr.Ptr, name, signature)); }
/** * Before Save * @param newRecord new * @return true */ protected override bool BeforeSave(bool newRecord) { if (Is_ValueChanged("DueAmt")) { log.Fine("beforeSave"); SetIsValid(false); } oldDueAmt = Util.GetValueOfDecimal(Get_ValueOld("DueAmt")); if (Env.IsModuleInstalled("VA009_")) { // get invoice currency for rounding MCurrency currency = MCurrency.Get(GetCtx(), GetC_Currency_ID()); SetDueAmt(Decimal.Round(GetDueAmt(), currency.GetStdPrecision())); SetVA009_PaidAmntInvce(Decimal.Round(GetVA009_PaidAmntInvce(), currency.GetStdPrecision())); // when invoice schedule have payment reference then need to check payment mode on payment window & update here if (GetC_Payment_ID() > 0) { #region for payment MPayment payment = new MPayment(GetCtx(), GetC_Payment_ID(), Get_Trx()); SetVA009_PaymentMethod_ID(payment.GetVA009_PaymentMethod_ID()); // get payment method detail -- update to here DataSet dsPaymentMethod = DB.ExecuteDataset(@"SELECT VA009_PaymentMode, VA009_PaymentType, VA009_PaymentTrigger FROM VA009_PaymentMethod WHERE VA009_PaymentMethod_ID = " + payment.GetVA009_PaymentMethod_ID(), null, Get_Trx()); if (dsPaymentMethod != null && dsPaymentMethod.Tables.Count > 0 && dsPaymentMethod.Tables[0].Rows.Count > 0) { if (!String.IsNullOrEmpty(Util.GetValueOfString(dsPaymentMethod.Tables[0].Rows[0]["VA009_PaymentMode"]))) { SetVA009_PaymentMode(Util.GetValueOfString(dsPaymentMethod.Tables[0].Rows[0]["VA009_PaymentMode"])); } if (!String.IsNullOrEmpty(Util.GetValueOfString(dsPaymentMethod.Tables[0].Rows[0]["VA009_PaymentType"]))) { SetVA009_PaymentType(Util.GetValueOfString(dsPaymentMethod.Tables[0].Rows[0]["VA009_PaymentType"])); } SetVA009_PaymentTrigger(Util.GetValueOfString(dsPaymentMethod.Tables[0].Rows[0]["VA009_PaymentTrigger"])); } #endregion } else if (GetC_CashLine_ID() > 0) { #region For Cash // when invoice schedule have cashline reference then need to check // payment mode of "Cash" type having currency is null on "Payment Method" window & update here DataSet dsPaymentMethod = (DB.ExecuteDataset(@"SELECT VA009_PaymentMethod_ID, VA009_PaymentMode, VA009_PaymentType, VA009_PaymentTrigger FROM VA009_PaymentMethod WHERE IsActive = 'Y' AND AD_Client_ID = " + GetAD_Client_ID() + @" AND VA009_PaymentBaseType = 'B' AND NVL(C_Currency_ID , 0) = 0", null, Get_Trx())); if (dsPaymentMethod != null && dsPaymentMethod.Tables.Count > 0 && dsPaymentMethod.Tables[0].Rows.Count > 0) { SetVA009_PaymentMethod_ID(Util.GetValueOfInt(dsPaymentMethod.Tables[0].Rows[0]["VA009_PaymentMethod_ID"])); if (!String.IsNullOrEmpty(Util.GetValueOfString(dsPaymentMethod.Tables[0].Rows[0]["VA009_PaymentMode"]))) { SetVA009_PaymentMode(Util.GetValueOfString(dsPaymentMethod.Tables[0].Rows[0]["VA009_PaymentMode"])); } if (!String.IsNullOrEmpty(Util.GetValueOfString(dsPaymentMethod.Tables[0].Rows[0]["VA009_PaymentType"]))) { SetVA009_PaymentType(Util.GetValueOfString(dsPaymentMethod.Tables[0].Rows[0]["VA009_PaymentType"])); } SetVA009_PaymentTrigger(Util.GetValueOfString(dsPaymentMethod.Tables[0].Rows[0]["VA009_PaymentTrigger"])); } else { #region when we not found record of "Cash" then we will create a new rcord on Payment Method for Cash string sql = @"SELECT AD_TABLE_ID FROM AD_TABLE WHERE tablename LIKE 'VA009_PaymentMethod' AND IsActive = 'Y'"; int tableId = Util.GetValueOfInt(DB.ExecuteScalar(sql, null, null)); MTable tbl = new MTable(GetCtx(), tableId, Get_Trx()); PO po = tbl.GetPO(GetCtx(), 0, Get_Trx()); po.SetAD_Client_ID(GetAD_Client_ID()); po.SetAD_Org_ID(0); // Recod will be created in (*) Organization po.Set_Value("Value", "By Cash"); po.Set_Value("VA009_Name", "By Cash"); po.Set_Value("IsActive", true); po.Set_Value("VA009_PaymentBaseType", "B"); po.Set_Value("VA009_PaymentRule", "M"); po.Set_Value("VA009_PaymentMode", "C"); po.Set_Value("VA009_PaymentType", "S"); po.Set_Value("VA009_PaymentTrigger", "S"); po.Set_Value("C_Currency_ID", null); po.Set_Value("VA009_InitiatePay", false); if (!po.Save(Get_Trx())) { ValueNamePair pp = VLogger.RetrieveError(); log.Info("Error Occured when try to save record on Payment Method for Cash. Error Type : " + pp.GetValue()); } else { SetVA009_PaymentMethod_ID(Util.GetValueOfInt(po.Get_Value("VA009_PaymentMethod_ID"))); SetVA009_PaymentMode("C"); SetVA009_PaymentType("S"); SetVA009_PaymentTrigger("S"); } #endregion } #endregion } } // to set processing false because in case of new schedule processing is set to be false if (newRecord) { SetProcessing(false); // when schedile is not paid and invoice hedaer having "Hold Payment", then set "Hold payment" on schedule also if (Get_ColumnIndex("IsHoldPayment") > 0 && (GetC_Payment_ID() == 0 && GetC_CashLine_ID() == 0)) { String sql = "SELECT IsHoldPayment FROM C_Invoice WHERE C_Invoice_ID = " + GetC_Invoice_ID(); String IsHoldPayment = Util.GetValueOfString(DB.ExecuteScalar(sql, null, Get_Trx())); SetIsHoldPayment(IsHoldPayment.Equals("Y")); } } // if payment refrence not found on schedule the set withholdimh amount as ZERO if (GetC_Payment_ID() <= 0) { SetBackupWithholdingAmount(0); SetWithholdingAmt(0); } return(true); }
/// <summary> /// Complete Document /// </summary> /// <returns>new status (Complete, In Progress, Invalid, Waiting ..)</returns> public String CompleteIt() { // Re-Check if (!m_justPrepared) { String status = PrepareIt(); if (!DocActionVariables.STATUS_INPROGRESS.Equals(status)) { return(status); } } // Implicit Approval if (!IsApproved()) { ApproveIt(); } log.Info("completeIt - " + ToString()); int _CountVA034 = Util.GetValueOfInt(DB.ExecuteScalar("SELECT COUNT(AD_MODULEINFO_ID) FROM AD_MODULEINFO WHERE PREFIX='VA034_' AND IsActive = 'Y'")); // Set Payment reconciled MBankStatementLine[] lines = GetLines(false); //Changes by SUkhwinder on 20 April, if all lines are not matched then dont allow complete. foreach (MBankStatementLine line in lines) { // if Transaction amount exist but no payment reference or Charge amount exist with no Charge then give message for Unmatched lines if ((line.GetTrxAmt() != Env.ZERO && line.GetC_Payment_ID() == 0) || (line.GetChargeAmt() != Env.ZERO && line.GetC_Charge_ID() == 0)) { m_processMsg = Msg.GetMsg(Env.GetCtx(), "LinesNotMatchedYet"); return(DocActionVariables.STATUS_INVALID); } } //Changes by SUkhwinder on 20 April, if all lines are not matched then dont allow complete. Decimal transactionAmt = 0; //Arpit to update only transaction amount in Bank Account UnMatched Balance asked by Ashish Gandhi for (int i = 0; i < lines.Length; i++) { MBankStatementLine line = lines[i]; transactionAmt += line.GetTrxAmt(); if (line.GetC_Payment_ID() != 0) { MPayment payment = new MPayment(GetCtx(), line.GetC_Payment_ID(), Get_TrxName()); payment.SetIsReconciled(true); if (_CountVA034 > 0) { payment.SetVA034_DepositSlipNo(line.GetVA012_VoucherNo()); } payment.Save(Get_TrxName()); } //Pratap 1-2-16 ///// Set Cash Line reconciled int _CountVA012 = Util.GetValueOfInt(DB.ExecuteScalar("SELECT COUNT(AD_MODULEINFO_ID) FROM AD_MODULEINFO WHERE PREFIX='VA012_' AND IsActive = 'Y'")); if (_CountVA012 > 0) { if (line.GetC_CashLine_ID() != 0) { MCashLine cashLine = new MCashLine(GetCtx(), line.GetC_CashLine_ID(), Get_TrxName()); cashLine.SetVA012_IsReconciled(true); cashLine.Save(Get_TrxName()); } } //// } // Update Bank Account MBankAccount ba = MBankAccount.Get(GetCtx(), GetC_BankAccount_ID()); ba.SetCurrentBalance(GetEndingBalance()); ba.SetUnMatchedBalance(Decimal.Subtract(ba.GetUnMatchedBalance(), transactionAmt));//Arpit ba.Save(Get_TrxName()); //VA009----------------------------------Anuj---------------------- //int _CountVA009 = Util.GetValueOfInt(DB.ExecuteScalar("SELECT COUNT(AD_MODULEINFO_ID) FROM AD_MODULEINFO WHERE PREFIX='VA009_' AND IsActive = 'Y'")); if (Env.IsModuleInstalled("VA009_")) { MBankStatementLine[] STlines = GetLines(false); for (int i = 0; i < STlines.Length; i++) { MBankStatementLine line = STlines[i]; if (line.GetC_Payment_ID() != 0) { MPayment payment = new MPayment(GetCtx(), line.GetC_Payment_ID(), Get_TrxName()); payment.SetVA009_ExecutionStatus("R"); if (_CountVA034 > 0) { payment.SetVA034_DepositSlipNo(line.GetVA012_VoucherNo()); } payment.Save(Get_TrxName()); //MInvoicePaySchedule inp = new MInvoicePaySchedule(GetCtx(), payment.GetC_InvoicePaySchedule_ID(), Get_TrxName()); //inp.SetVA009_ExecutionStatus("R"); //inp.Save(Get_TrxName()); // update execution status as received on Invoice Schedule - for those payment which are completed or closed if (payment.GetDocStatus() == DOCSTATUS_Closed || payment.GetDocStatus() == DOCSTATUS_Completed) { int no = Util.GetValueOfInt(DB.ExecuteQuery(@"UPDATE C_InvoicePaySchedule SET VA009_ExecutionStatus = 'R' WHERE C_Payment_ID = " + line.GetC_Payment_ID(), null, Get_Trx())); } } } } //END----------------------------------Anuj---------------------- // User Validation String valid = ModelValidationEngine.Get().FireDocValidate(this, ModalValidatorVariables.DOCTIMING_AFTER_COMPLETE); if (valid != null) { m_processMsg = valid; return(DocActionVariables.STATUS_INVALID); } SetProcessed(true); SetDocAction(DOCACTION_Close); return(DocActionVariables.STATUS_COMPLETED); }
} // getKeyColumns // getKeyColumns /// <summary> /// Get Persistency Class for table /// </summary> /// <param name="tableName"></param> /// <returns></returns> public Type GetClass(string tableName) { // Not supported if (tableName == null || tableName.EndsWith("_Trl")) { return(null); } // Import Tables (Name conflict) if (tableName.StartsWith("I_")) { Type className = GetPOclass("VAdvantage.Process.X_" + tableName); if (className != null) { return(className); } log.Warning("No class for table: " + tableName); return(null); } //Special Naming for (int i = 0; i < _special.Length; i++) { if (_special[i++].Equals(tableName)) { Type clazzsn = GetPOclass(_special[i]); if (clazzsn != null) { return(clazzsn); } break; } } // Strip table name prefix (e.g. AD_) Customizations are 3/4 String classNm = tableName; int index = classNm.IndexOf('_'); if (index > 0) { if (index < 3) // AD_, A_ { classNm = classNm.Substring(index + 1); } else { String prefix = classNm.Substring(0, index); if (prefix.Equals("Fact")) // keep custom prefix { classNm = classNm.Substring(index + 1); } } } // Remove underlines classNm = classNm.Replace("_", ""); // Search packages //String[] packages = getPackages(GetCtx()); //for (int i = 0; i < packages.length; i++) //{ string namspace = ""; /*********** Module Section **************/ Tuple <String, String, String> moduleInfo; Assembly asm = null; //////Check MClasses through list for (int i = 0; i < _projectClasses.Length; i++) { namspace = _projectClasses[i] + classNm; if (_projectClasses.Contains("X_")) { namspace = _projectClasses[i] + tableName; } Type clazzsn = GetFromCustomizationPOclass(namspace); if (clazzsn != null) { return(clazzsn); } } //Modules if (Env.HasModulePrefix(tableName, out moduleInfo)) { asm = GetAssembly(moduleInfo.Item1); if (asm != null) { for (int i = 0; i < _moduleClasses.Length; i++) { namspace = moduleInfo.Item2 + _moduleClasses[i] + classNm; if (_moduleClasses.Contains("X_")) { namspace = moduleInfo.Item2 + _moduleClasses[i] + tableName; } Type clazzsn = GetClassFromAsembly(asm, namspace); if (clazzsn != null) { return(clazzsn); } } } } /******** End **************/ for (int i = 0; i < _productClasses.Length; i++) { namspace = _productClasses[i] + classNm; if (_productClasses.Contains("X_")) { namspace = _productClasses[i] + tableName; } Type clazzsn = GetPOclass(namspace); if (clazzsn != null) { return(clazzsn); } } return(null); }
public virtual void AppendCSS(Env env, Context context) { var rules = new List <StringBuilder>(); // node.Ruleset instances int nonCommentRules = 0; var paths = new Context(); // Current selectors if (!IsRoot) { if (!env.Compress && env.Debug && Location != null) { env.Output.Append(string.Format("/* {0}:L{1} */\n", Location.FileName, Zone.GetLineNumber(Location))); } paths.AppendSelectors(context, Selectors); } env.Output.Push(); foreach (var node in Rules) { if (node.IgnoreOutput()) { continue; } var comment = node as Comment; if (comment != null && !comment.IsValidCss) { continue; } var ruleset = node as Ruleset; if (ruleset != null) { ruleset.AppendCSS(env, paths); } else { var rule = node as Rule; if (rule && rule.Variable) { continue; } if (!IsRoot) { if (!comment) { nonCommentRules++; } env.Output.Push() .Append(node); rules.Add(env.Output.Pop()); } else { env.Output .Append(node); if (!env.Compress) { env.Output .Append("\n"); } } } } var rulesetOutput = env.Output.Pop(); // If this is the root node, we don't render // a selector, or {}. // Otherwise, only output if this ruleset has rules. if (IsRoot) { env.Output.AppendMany(rules, env.Compress ? "" : "\n"); } else { if (nonCommentRules > 0) { foreach (var s in Selectors.Where(s => s.Elements.First().Value != null)) { var local = context.Clone(); local.AppendSelectors(context, new[] { s }); var finalString = local.ToCss(env); var extensions = env.FindExactExtension(finalString); if (extensions != null) { paths.AppendSelectors(context.Clone(), extensions.ExtendedBy); } var partials = env.FindPartialExtensions(finalString); if (partials != null) { paths.AppendSelectors(context.Clone(), partials.SelectMany(p => p.Replacements(finalString))); } } paths.AppendCSS(env); env.Output.Append(env.Compress ? "{" : " {\n "); env.Output.AppendMany(rules.ConvertAll(stringBuilder => stringBuilder.ToString()).Distinct(), env.Compress ? "" : "\n "); if (env.Compress) { env.Output.TrimRight(';'); } env.Output.Append(env.Compress ? "}" : "\n}\n"); } } env.Output.Append(rulesetOutput); }
public List <Closure> Find <TRuleset>(Env env, Selector selector, Ruleset self) where TRuleset : Ruleset { self = self ?? this; var rules = new List <Closure>(); var key = typeof(TRuleset).ToString() + ":" + selector.ToCSS(env); if (_lookups.ContainsKey(key)) { return(_lookups[key]); } var validRulesets = Rulesets().Where(rule => { if (!typeof(TRuleset).IsAssignableFrom(rule.GetType())) { return(false); } if (rule != self) { return(true); } MixinDefinition mixinRule = rule as MixinDefinition; if (mixinRule != null) { return(mixinRule.Condition != null); } return(false); }); foreach (var rule in validRulesets) { if (rule.Selectors && rule.Selectors.Any(selector.Match)) { if ((selector.Elements.Count == 1) || rule.Selectors.Any(s => s.ToCSS(new Env()) == selector.ToCSS(new Env()))) { rules.Add(new Closure { Ruleset = rule, Context = new List <Ruleset> { rule } }); } else if (selector.Elements.Count > 1) { var remainingSelectors = new Selector(new NodeList <Element>(selector.Elements.Skip(1))); var closures = rule.Find <Ruleset>(env, remainingSelectors, self); foreach (var closure in closures) { closure.Context.Insert(0, rule); } rules.AddRange(closures); } } } return(_lookups[key] = rules); }
/** * Opens a socket */ public static SocketInputOutput fsockopen(Env env, string host, @Optional int port, @Optional @Reference Value errno,
protected override void AppendCSS(Env env, Context context) { base.AppendCSS(env); // should throw InvalidOperationException }
public ValueIterator(Env env, ObjectValue obj) : base(env, obj) { }
public Object marshal(Env env, Expr expr, Class expectedClass) { return(expr.eval(env).toUnicodeValue(env)); }
/** * Evaluates the equality as a boolean. */ public Value eval(Env env) { return(_expr.evalBoolean(env) ? BooleanValue.FALSE : BooleanValue.TRUE); }
public Value unmarshal(Env env, Object value) { if (value instanceof UnicodeValue) { return((UnicodeValue)value); }
public void open(Env env, string savePath, string sessionName) { _open.call(env, env.createString(savePath), env.createString(sessionName)); }
/************************************************************************** * Calculate/Set Tax Base Amt from Invoice Lines * @return true if tax calculated */ public bool CalculateTaxFromLines() { Decimal?taxBaseAmt = Env.ZERO; Decimal taxAmt = Env.ZERO; // bool documentLevel = GetTax().IsDocumentLevel(); MTax tax = GetTax(); // String sql = "SELECT il.LineNetAmt, COALESCE(il.TaxAmt,0), i.IsSOTrx " + "FROM C_InvoiceLine il" + " INNER JOIN C_Invoice i ON (il.C_Invoice_ID=i.C_Invoice_ID) " + "WHERE il.C_Invoice_ID=" + GetC_Invoice_ID() + " AND il.C_Tax_ID=" + GetC_Tax_ID(); IDataReader idr = null; try { idr = DataBase.DB.ExecuteReader(sql, null, Get_TrxName()); while (idr.Read()) { // BaseAmt Decimal baseAmt = Utility.Util.GetValueOfDecimal(idr[0]); taxBaseAmt = Decimal.Add((Decimal)taxBaseAmt, baseAmt); // TaxAmt Decimal amt = Utility.Util.GetValueOfDecimal(idr[1]); //if (amt == null) // amt = Env.ZERO; bool isSOTrx = "Y".Equals(idr[2].ToString()); // if (documentLevel || Env.Signum(baseAmt) == 0) { amt = Env.ZERO; } else if (Env.Signum(amt) != 0 && !isSOTrx) // manually entered { ; } else // calculate line tax { amt = tax.CalculateTax(baseAmt, IsTaxIncluded(), GetPrecision()); } // taxAmt = Decimal.Add(taxAmt, amt); } idr.Close(); } catch (Exception e) { if (idr != null) { idr.Close(); } log.Log(Level.SEVERE, "setTaxBaseAmt", e); taxBaseAmt = null; } if (taxBaseAmt == null) { return(false); } // Calculate Tax if (documentLevel || Env.Signum(taxAmt) == 0) { taxAmt = tax.CalculateTax((Decimal)taxBaseAmt, IsTaxIncluded(), GetPrecision()); } SetTaxAmt(taxAmt); // Set Base if (IsTaxIncluded()) { SetTaxBaseAmt(Decimal.Subtract((Decimal)taxBaseAmt, taxAmt)); } else { SetTaxBaseAmt((Decimal)taxBaseAmt); } return(true); }
public void Leafs_compressed_CRUD(int iterationCount, int size, bool sequentialKeys, int seed) { using (var tx = Env.WriteTransaction()) { tx.CreateTree("tree", flags: TreeFlags.LeafsCompressed); tx.Commit(); } HashSet <string> ids; var random = new Random(seed); if (sequentialKeys) { ids = new HashSet <string>(Enumerable.Range(0, iterationCount).Select(x => $"{x:d5}")); } else { ids = new HashSet <string>(); while (ids.Count < iterationCount) { ids.Add(random.Next().ToString()); } } var bytes = new byte[size]; random.NextBytes(bytes); // insert using (var tx = Env.WriteTransaction()) { var tree = tx.ReadTree("tree"); Assert.True(tree.State.Flags.HasFlag(TreeFlags.LeafsCompressed)); foreach (var id in ids) { tree.Add(id, new MemoryStream(bytes)); AssertReads(tx, new[] { id }, bytes); } var compressedLeafs = tree.AllPages() .Select(x => tree.GetReadOnlyTreePage(x)) .Where(p => p.Flags.HasFlag(PageFlags.Compressed)) .ToList(); Assert.NotEmpty(compressedLeafs); tx.Commit(); } using (var tx = Env.ReadTransaction()) { AssertReads(tx, ids, bytes); } // update using (var tx = Env.WriteTransaction()) { var tree = tx.ReadTree("tree"); Assert.True(tree.State.Flags.HasFlag(TreeFlags.LeafsCompressed)); foreach (var id in ids) { tree.Add(id, new MemoryStream(bytes)); } var compressedLeafs = tree.AllPages() .Select(x => tree.GetReadOnlyTreePage(x)) .Where(p => p.Flags.HasFlag(PageFlags.Compressed)) .ToList(); Assert.NotEmpty(compressedLeafs); tx.Commit(); } using (var tx = Env.ReadTransaction()) { AssertReads(tx, ids, bytes); } // deletes - partial var deleted = new HashSet <string>(); using (var tx = Env.WriteTransaction()) { var tree = tx.ReadTree("tree"); Assert.True(tree.State.Flags.HasFlag(TreeFlags.LeafsCompressed)); foreach (var id in ids) { if (random.Next() % 2 == 0) { tree.Delete(id); deleted.Add(id); } } tx.Commit(); } using (var tx = Env.ReadTransaction()) { AssertReads(tx, ids.Except(deleted), bytes); AssertDeletes(tx, deleted); } // deletes - everything using (var tx = Env.WriteTransaction()) { var tree = tx.ReadTree("tree"); Assert.True(tree.State.Flags.HasFlag(TreeFlags.LeafsCompressed)); foreach (var id in ids) { tree.Delete(id); } tx.Commit(); } using (var tx = Env.WriteTransaction()) { AssertDeletes(tx, ids); } }
protected override bool AfterSave(bool newRecord, bool success) { Tuple <String, String, String> mInfo = null; if (Env.HasModulePrefix("DTD001_", out mInfo)) { if (!newRecord && GetM_RequisitionLine_ID() != 0 && GetConfirmedQty() == 0) { VAdvantage.Model.MRequisitionLine requisition = new VAdvantage.Model.MRequisitionLine(GetCtx(), GetM_RequisitionLine_ID(), null); requisition.SetDTD001_ReservedQty(requisition.GetDTD001_ReservedQty() + (GetMovementQty() - qtyReserved)); if (!requisition.Save()) { return(false); } storage = VAdvantage.Model.MStorage.Get(GetCtx(), GetM_Locator_ID(), GetM_Product_ID(), GetM_AttributeSetInstance_ID(), null); if (storage == null) { storage = VAdvantage.Model.MStorage.GetCreate(GetCtx(), GetM_Locator_ID(), GetM_Product_ID(), 0, null); } storage.SetQtyReserved(storage.GetQtyReserved() + (GetMovementQty() - qtyReserved)); if (!storage.Save()) { return(false); } } //vikas 11/21/2014 _mvlNewAttId = GetM_AttributeSetInstance_ID(); if (_mvlOldAttId != _mvlNewAttId && !newRecord && GetM_RequisitionLine_ID() != 0) { // Set QtyReserved On Storage Correspng to New attributesetinstc_id storage = VAdvantage.Model.MStorage.Get(GetCtx(), GetM_Locator_ID(), GetM_Product_ID(), GetM_AttributeSetInstance_ID(), null); if (storage == null) { storage = VAdvantage.Model.MStorage.GetCreate(GetCtx(), GetM_Locator_ID(), GetM_Product_ID(), 0, null); } storage.SetQtyReserved(storage.GetQtyReserved() + qtyReserved); if (!storage.Save()) { return(false); } storage = VAdvantage.Model.MStorage.Get(GetCtx(), GetM_Locator_ID(), GetM_Product_ID(), _mvlOldAttId, null); if (storage == null) { storage = VAdvantage.Model.MStorage.GetCreate(GetCtx(), GetM_Locator_ID(), GetM_Product_ID(), 0, null); } storage.SetQtyReserved(storage.GetQtyReserved() - qtyReserved); if (!storage.Save()) { return(false); } }//vikas if (newRecord && GetM_RequisitionLine_ID() != 0 && GetDescription() != "RC") { VAdvantage.Model.MRequisitionLine requisition = new VAdvantage.Model.MRequisitionLine(GetCtx(), GetM_RequisitionLine_ID(), null); requisition.SetDTD001_ReservedQty(requisition.GetDTD001_ReservedQty() + GetMovementQty()); if (!requisition.Save()) { return(false); } storage = VAdvantage.Model.MStorage.Get(GetCtx(), GetM_Locator_ID(), GetM_Product_ID(), GetM_AttributeSetInstance_ID(), null); if (storage == null) { storage = VAdvantage.Model.MStorage.GetCreate(GetCtx(), GetM_Locator_ID(), GetM_Product_ID(), 0, null); } storage.SetQtyReserved(storage.GetQtyReserved() + GetMovementQty()); if (!storage.Save()) { return(false); } } } return(true); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { var env = new Env(); ConfigureRateLimiting(services); if (env.IsDevelopment) { DotEnv.Config(true, ".env.development"); } services.AddSingleton <CdsServiceClientWrapper, CdsServiceClientWrapper>(); services.AddTransient <IOrganizationService>(sp => sp.GetService <CdsServiceClientWrapper>().CdsServiceClient?.Clone()); services.AddTransient <IOrganizationServiceAdapter, OrganizationServiceAdapter>(); services.AddTransient <ICrmService, CrmService>(); services.AddScoped <IStore, Store>(); services.AddScoped <DbConfiguration, DbConfiguration>(); services.AddSingleton <IMetricService, MetricService>(); services.AddSingleton <INotificationClientAdapter, NotificationClientAdapter>(); services.AddSingleton <IGeocodeClientAdapter, GeocodeClientAdapter>(); services.AddSingleton <ICandidateAccessTokenService, CandidateAccessTokenService>(); services.AddSingleton <ICandidateMagicLinkTokenService, CandidateMagicLinkTokenService>(); services.AddSingleton <INotifyService, NotifyService>(); services.AddSingleton <IClientManager, ClientManager>(); services.AddSingleton <IHangfireService, HangfireService>(); services.AddSingleton <IRedisService, RedisService>(); services.AddSingleton <IPerformContextAdapter, PerformContextAdapter>(); services.AddSingleton <ICallbackBookingService, CallbackBookingService>(); services.AddSingleton <IEnv>(env); var connectionString = DbConfiguration.DatabaseConnectionString(env); services.AddDbContext <GetIntoTeachingDbContext>(b => DbConfiguration.ConfigPostgres(connectionString, b)); services.AddAuthentication("ApiClientHandler") .AddScheme <ApiClientSchemaOptions, ApiClientHandler>("ApiClientHandler", op => { }); services.AddControllers(o => { o.ModelBinderProviders.Insert(0, new TrimStringModelBinderProvider()); }) .AddFluentValidation(c => { c.RegisterValidatorsFromAssemblyContaining <Startup>(); }) .AddJsonOptions(o => { o.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()); o.JsonSerializerOptions.Converters.Add(new TrimStringJsonConverter()); o.JsonSerializerOptions.Converters.Add(new EmptyStringToNullJsonConverter()); }); services.Configure <KestrelServerOptions>(options => { // Workaround for https://github.com/dotnet/aspnetcore/issues/8302 // caused by Prometheus.HttpMetrics.HttpRequestDurationMiddleware options.AllowSynchronousIO = true; }); services.AddSwaggerGen(c => { c.SwaggerDoc( "v1", new OpenApiInfo { Title = "Get into Teaching API - V1", Version = "v1", Description = @" Provides a RESTful API for integrating with the Get into Teaching CRM. The Get into Teaching (GIT) API sits in front of the GIT CRM, which uses the [Microsoft Dynamics365](https://docs.microsoft.com/en-us/dynamics365/) platform (the [Customer Engagement](https://docs.microsoft.com/en-us/dynamics365/customerengagement/on-premises/developer/overview) module is used for storing Candidate information and the [Marketing](https://docs.microsoft.com/en-us/dynamics365/marketing/developer/using-events-api) module for managing Events). The GIT API aims to provide: * Simple, task-based RESTful APIs. * Message queueing (while the GIT CRM is offline for updates). * Validation to ensure consistency across services writing to the GIT CRM. ", License = new OpenApiLicense { Name = "MIT License", Url = new Uri("https://opensource.org/licenses/MIT"), }, }); c.AddSecurityDefinition("apiKey", new OpenApiSecurityScheme { Type = SecuritySchemeType.ApiKey, Name = "Authorization", In = ParameterLocation.Header, }); c.OperationFilter <AuthOperationFilter>(); c.EnableAnnotations(); c.AddFluentValidationRules(); }); services.AddHangfire((provider, config) => { var automaticRetry = new AutomaticRetryAttribute { Attempts = JobConfiguration.Attempts(env), DelaysInSeconds = new[] { JobConfiguration.RetryIntervalInSeconds(env) }, OnAttemptsExceeded = AttemptsExceededAction.Delete, }; config .SetDataCompatibilityLevel(CompatibilityLevel.Version_170) .UseSimpleAssemblyNameTypeSerializer() .UseRecommendedSerializerSettings() .UseFilter(automaticRetry); if (env.IsTest) { config.UseMemoryStorage().WithJobExpirationTimeout(JobConfiguration.ExpirationTimeout); } else { config.UsePostgreSqlStorage(DbConfiguration.HangfireConnectionString(env)); } }); }
public SmtpClient(Env env) { this.env = env; }
abstract public bool isDecodable(Env env, StringValue str);
getIterator(Env env, ObjectValue qThis) { return new EntryIterator(env, qThis); }
public override Node Evaluate(Env env) { var closures = env.FindRulesets(Selector); if (closures == null) { throw new ParsingException(Selector.ToCSS(env).Trim() + " is undefined", Location); } env.Rule = this; var rules = new NodeList(); if (PreComments) { rules.AddRange(PreComments); } var rulesetList = closures.ToList(); // To address bug https://github.com/dotless/dotless/issues/136, where a mixin and ruleset selector may have the same name, we // need to favour matching a MixinDefinition with the required Selector and only fall back to considering other Ruleset types // if no match is found. // However, in order to support having a regular ruleset with the same name as a parameterized // mixin (see https://github.com/dotless/dotless/issues/387), we need to take argument counts into account, so we make the // decision after evaluating for argument match. var mixins = rulesetList.Where(c => c.Ruleset is MixinDefinition).ToList(); var defaults = new List <Closure>(); bool foundMatches = false, foundExactMatches = false, foundDefaultMatches = false; foreach (var closure in mixins) { var ruleset = (MixinDefinition)closure.Ruleset; var matchType = ruleset.MatchArguments(Arguments, env); if (matchType == MixinMatch.ArgumentMismatch) { continue; } if (matchType == MixinMatch.Default) { defaults.Add(closure); foundDefaultMatches = true; continue; } foundMatches = true; if (matchType == MixinMatch.GuardFail) { continue; } foundExactMatches = true; try { var closureEnvironment = env.CreateChildEnvWithClosure(closure); rules.AddRange(ruleset.Evaluate(Arguments, closureEnvironment).Rules); } catch (ParsingException e) { throw new ParsingException(e.Message, e.Location, Location); } } if (!foundExactMatches && foundDefaultMatches) { foreach (var closure in defaults) { try { var closureEnvironment = env.CreateChildEnvWithClosure(closure); var ruleset = (MixinDefinition)closure.Ruleset; rules.AddRange(ruleset.Evaluate(Arguments, closureEnvironment).Rules); } catch (ParsingException e) { throw new ParsingException(e.Message, e.Location, Location); } } foundMatches = true; } if (!foundMatches) { var regularRulesets = rulesetList.Except(mixins); foreach (var closure in regularRulesets) { if (closure.Ruleset.Rules != null) { var nodes = (NodeList)closure.Ruleset.Rules.Clone(); NodeHelper.ExpandNodes <MixinCall>(env, nodes); rules.AddRange(nodes); } foundMatches = true; } } if (PostComments) { rules.AddRange(PostComments); } env.Rule = null; if (!foundMatches) { var message = String.Format("No matching definition was found for `{0}({1})`", Selector.ToCSS(env).Trim(), Arguments.Select(a => a.Value.ToCSS(env)).JoinStrings(env.Compress ? "," : ", ")); throw new ParsingException(message, Location); } rules.Accept(new ReferenceVisitor(IsReference)); if (Important) { return(MakeRulesImportant(rules)); } return(rules); }
public Iterator<Value> getValueIterator(Env env, ObjectValue qThis) { return new ValueIterator(env, (ObjectValue) qThis); }
public EntryIterator(Env env, ObjectValue obj) { super(env, obj); }
/// <summary> /// Void Document. /// </summary> /// <returns>false</returns> public bool VoidIt() { log.Info(ToString()); if (DOCSTATUS_Closed.Equals(GetDocStatus()) || DOCSTATUS_Reversed.Equals(GetDocStatus()) || DOCSTATUS_Voided.Equals(GetDocStatus())) { m_processMsg = "Document Closed: " + GetDocStatus(); SetDocAction(DOCACTION_None); return(false); } // Not Processed if (DOCSTATUS_Drafted.Equals(GetDocStatus()) || DOCSTATUS_Invalid.Equals(GetDocStatus()) || DOCSTATUS_InProgress.Equals(GetDocStatus()) || DOCSTATUS_Approved.Equals(GetDocStatus()) || DOCSTATUS_NotApproved.Equals(GetDocStatus())) { ; } // Std Period open? else { if (!MPeriod.IsOpen(GetCtx(), GetStatementDate(), MDocBaseType.DOCBASETYPE_BANKSTATEMENT)) { m_processMsg = "@PeriodClosed@"; return(false); } // is Non Business Day? // JID_1205: At the trx, need to check any non business day in that org. if not fund then check * org. if (MNonBusinessDay.IsNonBusinessDay(GetCtx(), GetStatementDate(), GetAD_Org_ID())) { m_processMsg = Common.Common.NONBUSINESSDAY; return(false); } if (MFactAcct.Delete(Table_ID, GetC_BankStatement_ID(), Get_TrxName()) < 0) { return(false); // could not delete } } // Set lines to 0 Decimal transactionAmt = 0; //To update transaction amount in unMatched Balance in case of void MBankStatementLine[] lines = GetLines(true); for (int i = 0; i < lines.Length; i++) { MBankStatementLine line = lines[i]; transactionAmt += line.GetTrxAmt(); if (line.GetStmtAmt().CompareTo(Env.ZERO) != 0) { String description = Msg.Translate(GetCtx(), "Voided") + " (" + Msg.Translate(GetCtx(), "StmtAmt") + "=" + line.GetStmtAmt(); if (line.GetTrxAmt().CompareTo(Env.ZERO) != 0) { description += ", " + Msg.Translate(GetCtx(), "TrxAmt") + "=" + line.GetTrxAmt(); } if (line.GetChargeAmt().CompareTo(Env.ZERO) != 0) { description += ", " + Msg.Translate(GetCtx(), "ChargeAmt") + "=" + line.GetChargeAmt(); } if (line.GetInterestAmt().CompareTo(Env.ZERO) != 0) { description += ", " + Msg.Translate(GetCtx(), "InterestAmt") + "=" + line.GetInterestAmt(); } description += ")"; line.AddDescription(description); line.SetStmtAmt(Env.ZERO); line.SetTrxAmt(Env.ZERO); line.SetChargeAmt(Env.ZERO); line.SetInterestAmt(Env.ZERO); line.Save(Get_TrxName()); if (line.GetC_Payment_ID() != 0) { MPayment payment = new MPayment(GetCtx(), line.GetC_Payment_ID(), Get_TrxName()); payment.SetIsReconciled(false); payment.Save(Get_TrxName()); } } } AddDescription(Msg.Translate(GetCtx(), "Voided")); Decimal voidedDifference = GetStatementDifference(); SetStatementDifference(Env.ZERO); //VA009----------------------------------Anuj---------------------- //int _CountVA009 = Util.GetValueOfInt(DB.ExecuteScalar("SELECT COUNT(AD_MODULEINFO_ID) FROM AD_MODULEINFO WHERE PREFIX='VA009_' AND IsActive = 'Y'")); if (Env.IsModuleInstalled("VA009_")) { MBankStatementLine[] STlines = GetLines(false); string status = "R"; // Received for (int i = 0; i < STlines.Length; i++) { MBankStatementLine line = STlines[i]; if (line.GetC_Payment_ID() != 0) { MPayment payment = new MPayment(GetCtx(), line.GetC_Payment_ID(), Get_TrxName()); string _paymentMethod = Util.GetValueOfString(DB.ExecuteScalar("Select va009_paymentbaseType from va009_paymentmethod where va009_paymentmethod_id=" + payment.GetVA009_PaymentMethod_ID() + " And IsActive = 'Y' AND AD_Client_ID = " + GetAD_Client_ID())); if (_paymentMethod == "S") // Check { status = "B"; // Bounced } else { status = "C"; // Rejected } payment.SetVA009_ExecutionStatus(status); payment.Save(Get_TrxName()); //MInvoicePaySchedule inp = new MInvoicePaySchedule(GetCtx(), payment.GetC_InvoicePaySchedule_ID(), Get_TrxName()); //inp.SetVA009_ExecutionStatus(status); //inp.Save(Get_TrxName()); // update execution status as set on Payment on Invoice Schedule - for those payment which are completed or closed if (payment.GetDocStatus() == DOCSTATUS_Closed || payment.GetDocStatus() == DOCSTATUS_Completed) { int no = Util.GetValueOfInt(DB.ExecuteQuery(@"UPDATE C_InvoicePaySchedule SET VA009_ExecutionStatus = '" + payment.GetVA009_ExecutionStatus() + @"' WHERE C_Payment_ID = " + line.GetC_Payment_ID(), null, Get_Trx())); } } } } //END----------------------------------Anuj---------------------- // Update Bank Account MBankAccount ba = MBankAccount.Get(GetCtx(), GetC_BankAccount_ID()); ba.SetCurrentBalance(Decimal.Subtract(ba.GetCurrentBalance(), voidedDifference)); ba.SetUnMatchedBalance(Decimal.Add(ba.GetUnMatchedBalance(), transactionAmt)); //Arpit ba.Save(Get_TrxName()); SetProcessed(true); SetDocAction(DOCACTION_None); return(true); }
public void FlushingLogsShouldNotCauseExceptions() { // this test reproduces the issue RavenDB-2850 - very rare corner case that involves the journal applicator and the scratch buffer // Issue description: during ApplyLogsToDataFile (operation #1) we create write transactions to be sure that nobody else does writes at the same time. // However the problem is that write transactions allocate a page for transactions header. During this allocation by using the scratch buffer we might notice // that we are close to the scratch buffer size limit, so we are forcing ApplyLogsToDataFile (operation #2). This operation is performed on the same thread so // locking mechanism will not prevent it from doing this. // Operation #2 applies pages, removes journal files that are not longer in use and successfully finishes. Scratch buffer continues the allocation and returns // a page for the transaction header initiated by operation #1. Operation #1 keep working but during an attempt to delete old journals it throws // InvalidOperationException("Sequence contains no matching element") because operation #2 already did it. var random = new Random(1); var size = 0; while (Env.ScratchBufferPool.GetPagerStatesOfAllScratches().Count < 2) { using (var txw = Env.NewTransaction(TransactionFlags.ReadWrite)) { var value = new byte[size]; random.NextBytes(value); txw.State.Root.Add("items/", value); txw.Commit(); } size += AbstractPager.PageSize; } for (int i = 0; i < 100; i++) { using (var txw = Env.NewTransaction(TransactionFlags.ReadWrite)) { var tree = Env.CreateTree(txw, "foo"); var value = new byte[AbstractPager.PageSize]; random.NextBytes(value); tree.Add("key", value); txw.Commit(); } } using (var txw = Env.NewTransaction(TransactionFlags.ReadWrite)) { var tree = Env.CreateTree(txw, "foo/1"); var value = new byte[40 * AbstractPager.PageSize]; random.NextBytes(value); tree.Add("items/", value); txw.Commit(); } Assert.DoesNotThrow(() => Env.FlushLogToDataFile()); }