public void TestCase() { Function teleport = new Function ("teleport", 0x02); Function wall = new Function ("wall", 0x03); Function l = new Function ("l", 0x00); IFunctionInstance fiaa = (IFunctionInstance)teleport.CreateInstance (new FunctionIntegerInstance ("3"), new FunctionIntegerInstance ("3")); IFunctionInstance fiab = (IFunctionInstance)teleport.CreateInstance (new FunctionIntegerInstance ("3"), new FunctionIntegerInstance ("3")); Assert.IsTrue (fiaa.Equals (fiab)); Assert.IsTrue (fiab.Equals (fiaa)); Assert.AreEqual (fiaa.GetHashCode (), fiaa.GetHashCode ()); Assert.AreEqual (fiaa.GetHashCode (), fiab.GetHashCode ()); IFunctionInstance fiba = (IFunctionInstance)wall.CreateInstance (new FunctionIntegerInstance ("3"), new FunctionIntegerInstance ("3"), (IFunctionInstance)l.CreateInstance ()); IFunctionInstance fibb = (IFunctionInstance)wall.CreateInstance (new FunctionIntegerInstance ("3"), new FunctionIntegerInstance ("3"), (IFunctionInstance)l.CreateInstance ()); Assert.IsTrue (fiba.Equals (fibb)); Assert.IsTrue (fibb.Equals (fiba)); Assert.AreEqual (fiba.GetHashCode (), fiba.GetHashCode ()); Assert.AreEqual (fiba.GetHashCode (), fibb.GetHashCode ()); Assert.IsFalse (fiaa.Equals (fiba)); Assert.IsFalse (fiaa.Equals (fibb)); Assert.IsFalse (fiab.Equals (fiba)); Assert.IsFalse (fiab.Equals (fibb)); Assert.IsFalse (fiba.Equals (fiaa)); Assert.IsFalse (fiba.Equals (fiab)); Assert.IsFalse (fibb.Equals (fiaa)); Assert.IsFalse (fibb.Equals (fiab)); }
public functionInfoMassiveElement[] get_functions_info_massive() { delete_all_comments(); functionInfoMassiveElement[] function_info_massive = new functionInfoMassiveElement[1]; int functionInfoMassiveLength = 1; StringBuilder currentFunctionText; string currentFunctionName = "Глобальная область программы"; Function currentFunction = new Function(text.ToString()); function_info_massive[0].functionName = currentFunctionName; function_info_massive[0].functionVariables = currentFunction.get_function_identifiers_massive(null); identifiersMassiveElement[] globalIdentifiers = function_info_massive[0].functionVariables; int functionBeginIndex = 0, functionEndIndex = 0; while(condition_to_continue_watch_text(ref currentFunctionName,ref functionBeginIndex,ref functionEndIndex)) { functionInfoMassiveLength++; Array.Resize<functionInfoMassiveElement>(ref function_info_massive, functionInfoMassiveLength); currentFunctionText = new StringBuilder(text.ToString().Substring(functionBeginIndex + currentFunctionName.Length, functionEndIndex - functionBeginIndex - currentFunctionName.Length + 1)); currentFunction = new Function(currentFunctionText.ToString()); function_info_massive[functionInfoMassiveLength - 1].functionName = currentFunctionName; function_info_massive[functionInfoMassiveLength - 1].functionVariables = currentFunction.get_function_identifiers_massive(globalIdentifiers); } return function_info_massive; }
public void RemoveSubFunction(Function f) { if (!_subFunctions.Contains(f)) return; _subFunctions.Remove(f); OnPropertyChanged("SubFunctions"); }
//Converts the bytes into an object of type Data public Data(byte[] data) { //The first four bytes store the length of the name int nameLen = BitConverter.ToInt32(data, 0); //This check makes sure that strName has been passed in the array of bytes if (nameLen > 0) this.strName = Encoding.UTF8.GetString(data, 4, nameLen); else this.strName = null; //The next four store the function this.function = (Function)BitConverter.ToInt32(data, 4 + nameLen); //The rest store the dynamically stored parameters byte[] objectData = new byte[1024]; //I am making a new array with only the parameters, could probably find a better way Array.Copy(data, 8 + nameLen, objectData, 0, 512); BinaryFormatter formatter = new BinaryFormatter(); MemoryStream ms = new MemoryStream(objectData); this.objects = (object[])formatter.Deserialize(ms); }
/// <summary> /// Insert a <see cref="Function"/> passed as an argument via Stored Procedure that returns the newly inserted Function Key /// </summary> /// <param name="aFunction">A <see cref="Function"/>.</param> /// <exception cref="ArgumentNullException">If <c>aFunction</c> argument is <c>null</c>.</exception> public static void Insert(Function aFunction) { if (aFunction == null) { throw new ArgumentNullException("aFunction"); } using (var vSqlCommand = new SqlCommand() { CommandType = CommandType.Text, Connection = new SqlConnection(Connection.Instance.SqlConnectionString) }) { var vStringBuilder = new StringBuilder(); vStringBuilder.AppendLine("insert into FNC_Function"); vStringBuilder.AppendLine(" (FNC_Code, FNC_Name)"); vStringBuilder.AppendLine("values"); vStringBuilder.AppendLine(" (@FNCCode, @FNCName)"); vStringBuilder.AppendLine(";"); vStringBuilder.AppendLine("select SCOPE_IDENTITY()"); ObjectToData(vSqlCommand, aFunction); vSqlCommand.CommandText = vStringBuilder.ToString(); vSqlCommand.Connection.Open(); aFunction.FncKey = Convert.ToInt32(vSqlCommand.ExecuteScalar()); vSqlCommand.Connection.Close(); } }
public static void AddMethod(Function func, HookType type) { switch (type) { case HookType.Update: UpdateLoop += func; break; case HookType.Render: RenderLoop += func; break; case HookType.GUI: GUILoop += func; break; case HookType.FixedUpdate: FixedUpdateLoop += func; break; case HookType.LateUpdate: LateUpdateLoop += func; break; case HookType.PreRender: PreRenderLoop += func; break; case HookType.PostRender: PostRenderLoop += func; break; case HookType.Dispose: DisposeFunc += func; break; } }
public void AddSubFunction(Function f) { if (_subFunctions.Contains(f) || f == this) return; _subFunctions.Add(f); OnPropertyChanged("SubFunctions"); }
public void SeriesChangesWhenFunctionBindingListChanges() { IFunction function = new Function(); IVariable yVariable = new Variable<double>("y"); IVariable xVariable = new Variable<double>("x"); function.Arguments.Add(xVariable); function.Components.Add(yVariable); function[1.0] = 2.0; function[2.0] = 5.0; function[3.0] = 1.0; ILineChartSeries ls = ChartSeriesFactory.CreateLineSeries(); ls.YValuesDataMember = function.Components[0].DisplayName; ls.XValuesDataMember = function.Arguments[0].DisplayName; var synchronizeObject = new Control(); synchronizeObject.Show(); var functionBindingList = new FunctionBindingList(function) { SynchronizeInvoke = synchronizeObject }; ls.DataSource = functionBindingList; //a change in the function should change the series function[1.0] = 20.0; while(functionBindingList.IsProcessing) { Application.DoEvents(); } Assert.AreEqual(20, ls.YValues[0]); }
public override bool VisitFunctionDecl(Function function) { if (!VisitDeclaration(function)) return false; var ret = function.ReturnType; string msg; if (HasInvalidType(ret.Type, out msg)) { function.ExplicitlyIgnore(); Log.Debug("Function '{0}' was ignored due to {1} return decl", function.Name, msg); return false; } foreach (var param in function.Parameters) { if (HasInvalidDecl(param, out msg)) { function.ExplicitlyIgnore(); Log.Debug("Function '{0}' was ignored due to {1} param", function.Name, msg); return false; } if (HasInvalidType(param.Type, out msg)) { function.ExplicitlyIgnore(); Log.Debug("Function '{0}' was ignored due to {1} param", function.Name, msg); return false; } var decayedType = param.Type.Desugar() as DecayedType; if (decayedType != null) { function.ExplicitlyIgnore(); Log.Debug("Function '{0}' was ignored due to unsupported decayed type param", function.Name); return false; } if (param.Kind == ParameterKind.IndirectReturnType) { Class retClass; param.Type.Desugar().TryGetClass(out retClass); if (retClass == null) { function.ExplicitlyIgnore(); Log.Debug( "Function '{0}' was ignored due to an indirect return param not of a tag type", function.Name); return false; } } } return true; }
public override bool VisitFunctionDecl(Function function) { if (!base.VisitFunctionDecl(function) || function.Ignore) return false; Generator.CurrentOutputNamespace = function.TranslationUnit.Module.OutputNamespace; var overloadIndices = new List<int>(function.Parameters.Count); foreach (var parameter in function.Parameters.Where(p => p.DefaultArgument != null)) { var result = parameter.DefaultArgument.String; if (PrintExpression(parameter.Type, parameter.DefaultArgument, ref result) == null) overloadIndices.Add(function.Parameters.IndexOf(parameter)); if (string.IsNullOrEmpty(result)) { parameter.DefaultArgument = null; foreach (var p in function.Parameters.TakeWhile(p => p != parameter)) p.DefaultArgument = null; } else parameter.DefaultArgument.String = result; } GenerateOverloads(function, overloadIndices); return true; }
public static IQueryable<Function> GetFunctions(List<string> functionMethodList) { var data = dataAccess(); var autoAdded = false; //var functionMethodList = FSM.Functions.FSMFunctionLoader.GetFunctionList(); var functions = data.GetFunctions(); var functionList = functions.ToDictionary(f => f.FunctionName, f => f); foreach (var functionName in functionMethodList) { if(!functionList.ContainsKey(functionName)) { autoAdded = true; var newFunction = new Function(); newFunction.FunctionName = functionName; newFunction.Description = functionName + " @Added Automatically"; newFunction.FunctionURI = ""; CreateFunction(newFunction); } } functions = autoAdded ? data.GetFunctions() : functions; return functions; }
private Function defunImple(Context context, ScriptList arguments, bool addToScope) { var functionName = ArgumentType<String>(arguments[0]); List<ArgumentInfo> argumentInfo = null; try { argumentInfo = ArgumentInfo.ParseArguments(this, ArgumentType<ScriptList>(arguments[1])); } catch (ScriptError e) { context.RaiseNewError(e.Message, context.currentNode); return null; } var functionBody = ArgumentType<ParseNode>(arguments[2]); var newFunction = new Function( functionName, argumentInfo, "Script-defined function", functionBody, CopyScope(context.Scope)); newFunction.shortHelp = ScriptObject.AsString(arguments[3]); if (addToScope) newFunction.declarationScope.PushVariable(newFunction.name, newFunction); return newFunction; }
public string GetTopFunctionList() { string sql = "SELECT * FROM dbo.FunctionList WHERE parentId IS NULL ORDER BY orderFlag"; IList<Function> TopFunctionList = new List<Function>(); using (DataTable table = SqlHelper.ExecuteDataset(CommonInfo.ConQJVRMS, CommandType.Text, sql).Tables[0]) { foreach (DataRow row in table.Rows) { Function f = new Function(); f.Description = row["Description"].ToString(); f.FunctionName = row["FunctionName"].ToString(); f.UrlPath = row["UrlPath"].ToString(); f.FunctionID = new Guid(row["FunctionId"].ToString()); f.OrderFlag = int.Parse(row["orderFlag"].ToString()); if (row["parentid"] == DBNull.Value) { f.ParentFunctionId = null; } else { f.ParentFunctionId = new Guid(row["parentId"].ToString()); } TopFunctionList.Add(f); } } SerializeObjectFactory sof = new SerializeObjectFactory(); return sof.SerializeToBase64(TopFunctionList); }
public override sealed void Function(Function action) { if (_callingFunction) base.Function(action); else _functions[action.Name] = action; }
public double Integrate(Function f, int numberOfNodes) { this.initializeListOfQuadratures(numberOfNodes); double result = this.Integrator(f); this.quadratures.Clear(); return result; }
public static Function Pow(Function f, double a) { // Allow special handling of a few special cases (while not guaranteed to be numerically identical). if (a == 1.0) { return f; } if (a == 0.5) { return Sqrt(f); } if (a == 2.0) { return Sqr(f); } ConstantFunction f0 = f as ConstantFunction; if (f0 != null) { return Math.Pow(f0.Constant, a); } return new PowConstantFunction(f, a); }
public void GetArgumentDependentVariables() { IFunction f = new Function(); IVariable c1 = new Variable<int>("c1"); IVariable c2 = new Variable<int>("c2"); IVariable x = new Variable<int>("x"); f.Components.Add(c1); f.Components.Add(c2); IDictionary<IVariable, IEnumerable<IVariable>> dependentVariables = MemoryFunctionStoreHelper.GetDependentVariables(f.Store.Functions); //no argument dependencies yet Assert.AreEqual(2, dependentVariables.Count); Assert.AreEqual(new IVariable[0],dependentVariables[c1].ToArray()); Assert.AreEqual(new IVariable[0], dependentVariables[c2].ToArray()); f.Arguments.Add(x); dependentVariables = MemoryFunctionStoreHelper.GetDependentVariables(f.Store.Functions); Assert.AreEqual(3, dependentVariables.Count); Assert.AreEqual(2, dependentVariables[x].Count()); Assert.AreEqual(new[]{c1,c2},dependentVariables[x]); //Assert.IsTrue(dependentVariables[x].Contains(c1)); }
/* ============================================================================ Blink functions ============================================================================ */ public IEnumerator Blink(bool fc, bool fa, float als, float ae, bool fr, float rs, float re, bool fg, float gs, float ge, bool fb, float bs, float be, EaseType et, float t) { this.Clear(); this.fadeChildren = fc; this.fadeAlpha = fa; this.alphaStart = als; this.alphaEnd = ae; this.alphaDistance = ae - als; this.fadeRed = fr; this.redStart = rs; this.redEnd = re; this.redDistance = re - rs; this.fadeGreen = fg; this.greenStart = gs; this.greenEnd = ge; this.greenDistance = ge - gs; this.fadeBlue = fb; this.blueStart = bs; this.blueEnd = be; this.blueDistance = be - bs; this.interpolate = Interpolate.Ease(et); this.time = 0; this.time2 = t; yield return null; this.fading = true; this.flash = true; this.blink = true; }
private void startScanToolStripMenuItem_Click(object sender, EventArgs e) { string pathcook = ME3Directory.cookedPath; DebugOutput.StartDebugger("ScriptDB"); string[] files = Directory.GetFiles(pathcook, "*.pcc"); int count = 1; database = new List<ScriptEntry>(); foreach (string file in files) { DebugOutput.PrintLn(count + "\\" + files.Length + " : Scanning " + Path.GetFileName(file) + " ..."); PCCObject pcc = new PCCObject(file); int count2 = 0; foreach (PCCObject.ExportEntry ent in pcc.Exports) { if (ent.ClassName == "Function") { Function f = new Function(ent.Data, pcc); ScriptEntry n = new ScriptEntry(); n.file = Path.GetFileName(file); n.name = ent.PackageFullName + "." + ent.ObjectName; n.script = f.ToRawText(false); database.Add(n); DebugOutput.PrintLn("\tFound \"" + n.name + "\"",false); } count2++; } { pb1.Maximum = files.Length; pb1.Value = count; } count++; } RefreshList(); }
public void TestAsArgument() { IVariable<IFeatureLocation> a = new Variable<IFeatureLocation>("argument"); IVariable<double> c1 = new Variable<double>("value"); IVariable<string> c2 = new Variable<string>("description"); // f = (a, p)(h) IFunction f = new Function("rating curve"); f.Arguments.Add(a); f.Components.Add(c1); f.Components.Add(c2); SimpleFeature simpleFeature = new SimpleFeature(10.0); IFeatureLocation featureLocation = new FeatureLocation { Feature = simpleFeature }; // value based argument referencing. f[featureLocation] = new object[] { 1.0, "jemig de pemig" }; IMultiDimensionalArray<double> c1Value = f.GetValues<double>(new ComponentFilter(f.Components[0]), new VariableValueFilter<IFeatureLocation>( f.Arguments[0], new FeatureLocation {Feature = simpleFeature})); Assert.AreEqual(1.0, c1Value[0], 1.0e-6); //IMultiDimensionalArray<string> c2Value = f.GetValues<string>(new ComponentFilter(f.Components[1]), // new VariableValueFilter<IFeatureLocation>( // f.Arguments[0], featureLocation)); //Assert.AreEqual("jemig de pemig", c2Value[0]); }
//add function to list private void AddFuncButton_Click(object sender, EventArgs e) { //validate input if (FunctionBox.Text.Equals("") || RangeLowText.Text.Equals("") || RangeHighText.Text.Equals("") || IncrementText.Text.Equals("")) { MessageBox.Show("Missing inputs"); return; } //validate the function Function userInput = null; try { userInput = new Function(this.FunctionBox.Text, this.RangeLowText.Text, this.RangeHighText.Text, this.IncrementText.Text); } catch (Exception ex) { MessageBox.Show(ex.Message); } if (userInput == null) return; //add valid function to list funcList.Add(userInput); this.FunctionlistBox.Items.Add(funcList[funcList.Count-1].ToString()); //draw new pts this.redrawGraph(); }
private List<Point> ChebyshevInterpolation(Function func) { List<Point> interpolated; int numberOfNodes; float a, b, jump; if (float.TryParse(tbJump.Text, out jump) && float.TryParse(tbBegin.Text, out a) && float.TryParse(tbEnd.Text, out b) && int.TryParse(tbNodesNumber.Text, out numberOfNodes)) { NewtonChebyshevInterpolation interpolator = new NewtonChebyshevInterpolation(); List<Point> nodes = new List<Point>(); List<double> domain = new List<double>(); nodes = ChebyshevNodes(numberOfNodes, a, b, func.GetValue); for (double x = nodes[0].x; x < b; x += jump) { domain.Add(x); } interpolated = interpolator.Interpolate(nodes, domain); FormPlot form = new FormPlot(nodes, interpolated, func.GetValue); form.Show(); } else { MessageBox.Show("Wrong arguments. Note that a floating point number separator is coma (ex. 1,5).", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return null; } return interpolated; }
public void Parse(string stmt) { if (string.IsNullOrEmpty(stmt)) throw new Exception("Syntax Error: nil statement"); stmt = stmt.Trim(); if (string.IsNullOrEmpty(stmt)) throw new Exception("Syntax Error: nil statement"); if (!Regex.IsMatch(stmt, @"^(\w{1}|\w+(.*)(\w+|\)))$")) { throw new Exception("Syntax Error: Invalid statement."); } List<Identifier> idlist = new List<Identifier>(); var funcs = Regex.Matches(stmt, @"\b[a-zA-Z]\w*\((\s*\w+(\s*\,\s*\w+)*)\s*\)"); int lastFuncEnd = 0; foreach (Match m in funcs) { Function func = new Function(m.Groups[0].Value, m.Groups[1].Value); //parse any identifiers before the function ParseIdentifiers(idlist, stmt, lastFuncEnd, m.Index); lastFuncEnd = m.Index + m.Length; idlist.Add(func); } //parse the identifiers after the last function ParseIdentifiers(idlist, stmt, lastFuncEnd, stmt.Length); _identifiers = idlist.ToArray(); }
public ProcessDescriptor CreateProcess(Process.EProcessKind kind, Function func, params ISignalOrPortDescriptor[] sensitivity) { func.Name = _dpb._psName + "_FuPs" + _dpb._nextFUProcessIndex + "_" + func.Name; var result = _orgBinder.CreateProcess(kind, func, sensitivity); ++_dpb._nextFUProcessIndex; return result; }
public Documentation Process(Function f, EnumProcessor processor) { Documentation docs = null; if (DocumentationCache.ContainsKey(f.WrappedDelegate.Name)) { return DocumentationCache[f.WrappedDelegate.Name]; } else { var file = Settings.FunctionPrefix + f.WrappedDelegate.Name + ".xml"; if (!DocumentationFiles.ContainsKey(file)) file = Settings.FunctionPrefix + f.TrimmedName + ".xml"; if (!DocumentationFiles.ContainsKey(file)) file = Settings.FunctionPrefix + f.TrimmedName.TrimEnd(numbers) + ".xml"; docs = (DocumentationFiles.ContainsKey(file) ? ProcessFile(DocumentationFiles[file], processor) : null) ?? new Documentation { Summary = String.Empty, Parameters = f.Parameters.Select(p => new DocumentationParameter(p.Name, String.Empty)).ToList() }; DocumentationCache.Add(f.WrappedDelegate.Name, docs); } return docs; }
CachedFunction(Function f, Cache c) { this.f = f; this.cache = c; this.unique_id = count; ++count; }
public void Prepare(Function fn, ClassRemotes.Remote remote) { remoteDisplay.Clear(); remoteDisplay.AnyTextChanged += SomeTextChanged; // Do things differently basen on whether we are using this // form to add a new remote repo, rename it or we are editing // an existing remote repo switch (fn) { case Function.Add: remoteDisplay.Enable(true, true); remote.Name = "origin"; remote.PushCmd = ""; remoteDisplay.Set(remote); Text = "Add a new remote repository"; btOK.Enabled = false; break; case Function.Edit: Text = "Edit remote repository '" + remote.Name + "'"; remoteDisplay.Enable(false, true); remoteDisplay.Set(remote); break; case Function.Rename: Text = "Rename remote repository '" + remote.Name + "'"; remoteDisplay.Enable(true, false); remoteDisplay.Set(remote); break; } }
public override bool VisitFunctionDecl(Function function) { if (!VisitDeclaration(function)) return false; if (function.IsReturnIndirect) { var indirectParam = new Parameter() { Kind = ParameterKind.IndirectReturnType, QualifiedType = function.ReturnType, Name = "return", }; function.Parameters.Insert(0, indirectParam); function.ReturnType = new QualifiedType(new BuiltinType( PrimitiveType.Void)); } if (function.HasThisReturn) { // This flag should only be true on methods. var method = (Method) function; var classType = new QualifiedType(new TagType(method.Namespace), new TypeQualifiers {IsConst = true}); function.ReturnType = new QualifiedType(new PointerType(classType)); } // TODO: Handle indirect parameters return true; }
private void PopulateFunctionInfoFromDeclaration(Function aFunction) { var functionSections = Regex.Match(aFunction.Declaration, @"(\w+)( \w+)? (\w+)\((.+?)\)"); ReturnType = functionSections.Groups[1].Value; Parameters = functionSections.Groups[4].Value; FunctionName = functionSections.Groups[3].Value; }
private void WriteIteratorScopes(Function function) { if (function.IteratorScopes.Count == 0) return; var buffer = new ByteBuffer(); buffer.WriteByte(4); buffer.WriteByte(1); buffer.Align(4); buffer.WriteByte(4); buffer.WriteByte(3); buffer.Align(4); var scopes = function.IteratorScopes; buffer.WriteInt32(scopes.Count * 8 + 12); buffer.WriteInt32(scopes.Count); foreach (var scope in scopes) { buffer.WriteInt32(scope.Offset); buffer.WriteInt32(scope.Offset + scope.Length); } pdb.SetSymAttribute(function.Token, "MD2", buffer.length, buffer.buffer); }
/// <summary> /// Calback from the training in order to inform user about trining progress /// </summary> /// <param name="trParams"></param> /// <param name="trainer"></param> /// <param name="network"></param> /// <param name="mbs"></param> /// <param name="epoch"></param> /// <param name="progress"></param> /// <param name="device"></param> /// <returns></returns> protected override ProgressData progressTraining(TrainingParameters trParams, Trainer trainer, Function network, MinibatchSourceEx mbs, int epoch, TrainingProgress progress, DeviceDescriptor device) { //calculate average training loss and evaluation var mbAvgLoss = trainer.PreviousMinibatchLossAverage(); var mbAvgEval = trainer.PreviousMinibatchEvaluationAverage(); //get training dataset double trainEval = mbAvgEval; //sometimes when the data set is huge validation model against // full training dataset could take time, so we can skip it by setting parameter 'FullTrainingSetEval' if (trParams.FullTrainingSetEval) { var evParams = new EvaluationParameters() { MinibatchSize = trParams.BatchSize, MBSource = new MinibatchSourceEx(mbs.Type, StreamConfigurations.ToArray(), mbs.TrainingDataFile, null, MinibatchSource.FullDataSweep, false), Ouptut = OutputVariables, Input = InputVariables, }; var result = MLEvaluator.EvaluateFunction(trainer.Model(), evParams, device); trainEval = MLEvaluator.CalculateMetrics(trainer.EvaluationFunction().Name, result.actual, result.predicted, device); } string bestModelPath = m_bestModelPath; double validEval = 0; //in case validation data set is empty don't perform testminibatch if (!string.IsNullOrEmpty(mbs.ValidationDataFile)) { var evParams = new EvaluationParameters() { MinibatchSize = trParams.BatchSize, //StrmsConfig = StreamConfigurations.ToArray(), MBSource = new MinibatchSourceEx(mbs.Type, StreamConfigurations.ToArray(), mbs.ValidationDataFile, null, MinibatchSource.FullDataSweep, false), Ouptut = OutputVariables, Input = InputVariables, }; // var result = MLEvaluator.EvaluateFunction(trainer.Model(), evParams, device); validEval = MLEvaluator.CalculateMetrics(trainer.EvaluationFunction().Name, result.actual, result.predicted, device); } //here we should decide if the current model worth to be saved into temp location // depending of the Evaluation function which sometimes can be better if it is greater that previous (e.g. ClassificationAccuracy) if (isBetterThanPrevious(trainEval, validEval, StatMetrics.IsGoalToMinimize(trainer.EvaluationFunction())) && trParams.SaveModelWhileTraining) { //save model var strFilePath = $"{trParams.ModelTempLocation}\\model_at_{epoch}of{trParams.Epochs}_epochs_TimeSpan_{DateTime.Now.Ticks}"; if (!Directory.Exists(trParams.ModelTempLocation)) { Directory.CreateDirectory(trParams.ModelTempLocation); } //save temp model network.Save(strFilePath); //set training and validation evaluation to previous state m_PrevTrainingEval = trainEval; m_PrevValidationEval = validEval; bestModelPath = strFilePath; var tpl = Tuple.Create <double, double, string>(trainEval, validEval, strFilePath); m_ModelEvaluations.Add(tpl); } m_bestModelPath = bestModelPath; //create progressData object var prData = new ProgressData(); prData.EpochTotal = trParams.Epochs; prData.EpochCurrent = epoch; prData.EvaluationFunName = trainer.EvaluationFunction().Name; prData.TrainEval = trainEval; prData.ValidationEval = validEval; prData.MinibatchAverageEval = mbAvgEval; prData.MinibatchAverageLoss = mbAvgLoss; //prData.BestModel = bestModelPath; //the progress is only reported if satisfied the following condition if (progress != null && (epoch % trParams.ProgressFrequency == 0 || epoch == 1 || epoch == trParams.Epochs)) { //add info to the history m_trainingHistory.Add(new Tuple <int, float, float, float, float>(epoch, (float)mbAvgLoss, (float)mbAvgEval, (float)trainEval, (float)validEval)); //send progress progress(prData); // //Console.WriteLine($"Epoch={epoch} of {trParams.Epochs} processed."); } //return progress data return(prData); }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { NodeModel node = null; var obj = JObject.Load(reader); var type = Type.GetType(obj["$type"].Value <string>()); // If we can't find this type - try to look in our load from assemblies, // but only during testing - this is required during testing because some dlls are loaded // using Assembly.LoadFrom using the assemblyHelper - which loads dlls into loadFrom context - // dlls loaded with LoadFrom context cannot be found using Type.GetType() - this should // not be an issue during normal dynamo use but if it is we can enable this code. if (type == null && this.isTestMode == true) { List <Assembly> resultList; var typeName = obj["$type"].Value <string>().Split(',').FirstOrDefault(); // This assemblyName does not usually contain version information... var assemblyName = obj["$type"].Value <string>().Split(',').Skip(1).FirstOrDefault().Trim(); if (assemblyName != null) { if (this.loadedAssemblies.TryGetValue(assemblyName, out resultList)) { var matchingTypes = resultList.Select(x => x.GetType(typeName)).ToList(); type = matchingTypes.FirstOrDefault(); } } } // Check for and attempt to resolve an unknown type before proceeding if (type == null) { // Attempt to resolve the type using `AlsoKnownAs` var unresolvedName = obj["$type"].Value <string>().Split(',').FirstOrDefault(); Type newType; nodeFactory.ResolveType(unresolvedName, out newType); // If resolved update the type if (newType != null) { type = newType; } } // If the id is not a guid, makes a guid based on the id of the node var guid = GuidUtility.tryParseOrCreateGuid(obj["Id"].Value <string>()); var replication = obj["Replication"].Value <string>(); var inPorts = obj["Inputs"].ToArray().Select(t => t.ToObject <PortModel>()).ToArray(); var outPorts = obj["Outputs"].ToArray().Select(t => t.ToObject <PortModel>()).ToArray(); var resolver = (IdReferenceResolver)serializer.ReferenceResolver; string assemblyLocation = objectType.Assembly.Location; bool remapPorts = true; // If type is still null at this point return a dummy node if (type == null) { node = CreateDummyNode(obj, assemblyLocation, inPorts, outPorts); } // Attempt to create a valid node using the type else if (type == typeof(Function)) { var functionId = Guid.Parse(obj["FunctionSignature"].Value <string>()); CustomNodeDefinition def = null; CustomNodeInfo info = null; bool isUnresolved = !manager.TryGetCustomNodeData(functionId, null, false, out def, out info); Function function = manager.CreateCustomNodeInstance(functionId, null, false, def, info); node = function; if (isUnresolved) { function.UpdatePortsForUnresolved(inPorts, outPorts); } } else if (type == typeof(CodeBlockNodeModel)) { var code = obj["Code"].Value <string>(); CodeBlockNodeModel codeBlockNode = new CodeBlockNodeModel(code, guid, 0.0, 0.0, libraryServices, ElementResolver); node = codeBlockNode; // If the code block node is in an error state read the extra port data // and initialize the input and output ports if (node.IsInErrorState) { List <string> inPortNames = new List <string>(); var inputs = obj["Inputs"]; foreach (var input in inputs) { inPortNames.Add(input["Name"].ToString()); } // NOTE: This could be done in a simpler way, but is being implemented // in this manner to allow for possible future port line number // information being available in the file List <int> outPortLineIndexes = new List <int>(); var outputs = obj["Outputs"]; int outputLineIndex = 0; foreach (var output in outputs) { outPortLineIndexes.Add(outputLineIndex++); } codeBlockNode.SetErrorStatePortData(inPortNames, outPortLineIndexes); } } else if (typeof(DSFunctionBase).IsAssignableFrom(type)) { var mangledName = obj["FunctionSignature"].Value <string>(); var priorNames = libraryServices.GetPriorNames(); var functionDescriptor = libraryServices.GetFunctionDescriptor(mangledName); string newName; // Update the function descriptor if a newer migrated version of the node exists if (priorNames.TryGetValue(mangledName, out newName)) { functionDescriptor = libraryServices.GetFunctionDescriptor(newName); } // Use the functionDescriptor to try and restore the proper node if possible if (functionDescriptor == null) { node = CreateDummyNode(obj, assemblyLocation, inPorts, outPorts); } else { if (type == typeof(DSVarArgFunction)) { node = new DSVarArgFunction(functionDescriptor); // The node syncs with the function definition. // Then we need to make the inport count correct var varg = (DSVarArgFunction)node; varg.VarInputController.SetNumInputs(inPorts.Count()); } else if (type == typeof(DSFunction)) { node = new DSFunction(functionDescriptor); } } } else if (type == typeof(DSVarArgFunction)) { var functionId = Guid.Parse(obj["FunctionSignature"].Value <string>()); node = manager.CreateCustomNodeInstance(functionId); } else if (type.ToString() == "CoreNodeModels.Formula") { node = (NodeModel)obj.ToObject(type); } else { node = (NodeModel)obj.ToObject(type); // if node is an customNode input symbol - assign the element resolver. if (node is Nodes.CustomNodes.Symbol) { (node as Nodes.CustomNodes.Symbol).ElementResolver = ElementResolver; } // We don't need to remap ports for any nodes with json constructors which pass ports remapPorts = false; } if (remapPorts) { RemapPorts(node, inPorts, outPorts, resolver, manager.AsLogger()); } // Cannot set Lacing directly as property is protected node.UpdateValue(new UpdateValueParams("ArgumentLacing", replication)); node.GUID = guid; // Add references to the node and the ports to the reference resolver, // so that they are available for entities which are deserialized later. serializer.ReferenceResolver.AddReference(serializer.Context, node.GUID.ToString(), node); foreach (var p in node.InPorts) { serializer.ReferenceResolver.AddReference(serializer.Context, p.GUID.ToString(), p); } foreach (var p in node.OutPorts) { serializer.ReferenceResolver.AddReference(serializer.Context, p.GUID.ToString(), p); } return(node); }
public void OnEnable() { StartCoroutine(FillGauge()); Function.StopGame(); }
protected void GenerateAggregatedCode(MibCFile mibFile, VariableType instanceType, string switchSelector, bool generateDeclarations = true, bool generateImplementations = true) { if (this.getMethodRequired) { FunctionDeclaration getMethodDecl = new FunctionDeclaration(this.GetMethodName, isStatic: true); getMethodDecl.Parameter.Add(instanceType); getMethodDecl.Parameter.Add(new VariableType("value", VariableType.VoidString, "*")); getMethodDecl.ReturnType = new VariableType(null, LwipDefs.Vt_S16); if (generateDeclarations) { mibFile.Declarations.Add(getMethodDecl); } if (generateImplementations) { Function getMethod = Function.FromDeclaration(getMethodDecl); GenerateGetMethodCode(getMethod, switchSelector); mibFile.Implementation.Add(getMethod); } } if (this.testMethodRequired) { FunctionDeclaration testMethodDecl = new FunctionDeclaration(this.TestMethodName, isStatic: true); testMethodDecl.Parameter.Add(instanceType); testMethodDecl.Parameter.Add(new VariableType("len", LwipDefs.Vt_U16)); testMethodDecl.Parameter.Add(new VariableType("value", VariableType.VoidString, "*")); testMethodDecl.ReturnType = new VariableType(null, LwipDefs.Vt_Snmp_err); if (generateDeclarations) { mibFile.Declarations.Add(testMethodDecl); } if (generateImplementations) { Function testMethod = Function.FromDeclaration(testMethodDecl); GenerateTestMethodCode(testMethod, switchSelector); mibFile.Implementation.Add(testMethod); } } if (this.setMethodRequired) { FunctionDeclaration setMethodDecl = new FunctionDeclaration(this.SetMethodName, isStatic: true); setMethodDecl.Parameter.Add(instanceType); setMethodDecl.Parameter.Add(new VariableType("len", LwipDefs.Vt_U16)); setMethodDecl.Parameter.Add(new VariableType("value", VariableType.VoidString, "*")); setMethodDecl.ReturnType = new VariableType(null, LwipDefs.Vt_Snmp_err); if (generateDeclarations) { mibFile.Declarations.Add(setMethodDecl); } if (generateImplementations) { Function setMethod = Function.FromDeclaration(setMethodDecl); GenerateSetMethodCode(setMethod, switchSelector); mibFile.Implementation.Add(setMethod); } } }
private void AddFunction(Function function, IDictionary<string, object> environmentRefVariables) { var environmentVariables = function.Environment.ToDictionary(kv => kv.Key, kv => (dynamic)kv.Value); environmentVariables["TIER"] = _module.Settings.Tier; environmentVariables["MODULE"] = _module.Name; environmentVariables["DEADLETTERQUEUE"] = _module.Settings.DeadLetterQueueUrl; environmentVariables["LOGGINGTOPIC"] = _module.Settings.LoggingTopicArn; environmentVariables["LAMBDARUNTIME"] = function.Runtime; foreach(var environmentRefVariable in environmentRefVariables) { environmentVariables[environmentRefVariable.Key] = environmentRefVariable.Value; } // check if function as a VPC configuration Lambda.FunctionTypes.VpcConfig vpcConfig = null; if(function.VPC != null) { vpcConfig = new Lambda.FunctionTypes.VpcConfig { SubnetIds = function.VPC.SubnetIds, SecurityGroupIds = function.VPC.SecurityGroupIds }; } // create function definition _stack.Add(function.Name, new Lambda.Function { FunctionName = ToAppResourceName(function.Name), Description = function.Description, Runtime = function.Runtime, Handler = function.Handler, Timeout = function.Timeout, MemorySize = function.Memory, ReservedConcurrentExecutions = function.ReservedConcurrency, Role = Fn.GetAtt("ModuleRole", "Arn"), Code = new Lambda.FunctionTypes.Code { S3Bucket = _module.Settings.DeploymentBucketName, S3Key = function.PackageS3Key }, DeadLetterConfig = new Lambda.FunctionTypes.DeadLetterConfig { TargetArn = _module.Settings.DeadLetterQueueArn }, Environment = new Lambda.FunctionTypes.Environment { Variables = environmentVariables }, VpcConfig = vpcConfig, Tags = new List<Tag> { new Tag { Key = "lambdasharp:tier", Value = _module.Settings.Tier }, new Tag { Key = "lambdasharp:module", Value = _module.Name } } }); // check if function has any SNS topic event sources var topicSources = function.Sources.OfType<TopicSource>(); if(topicSources.Any()) { foreach(var topicSource in topicSources) { // find the resource that matches the declared topic name var parameter = _module.Parameters .OfType<AResourceParameter>() .FirstOrDefault(p => p.Name == topicSource.TopicName); // determine how to reference the resource object resourceReference; switch(parameter) { case ReferencedResourceParameter reference: resourceReference = reference.Resource.ResourceArn; break; case CloudFormationResourceParameter cloudformation: resourceReference = Fn.Ref(topicSource.TopicName); break; default: throw new ArgumentOutOfRangeException( nameof(parameter), parameter?.GetType().Name ?? "<null>", "parameter resource type must be either ReferencedResourceParameter or CloudFormationResourceParameter" ); } _stack.Add($"{function.Name}{topicSource.TopicName}SnsPermission", new Lambda.Permission { Action = "lambda:InvokeFunction", SourceArn = resourceReference, FunctionName = Fn.GetAtt(function.Name, "Arn"), Principal = "sns.amazonaws.com" }); _stack.Add($"{function.Name}{topicSource.TopicName}Subscription", new SNS.Subscription { Endpoint = Fn.GetAtt(function.Name, "Arn"), Protocol = "lambda", TopicArn = resourceReference }); } } // check if function has any API gateway event sources var scheduleSources = function.Sources.OfType<ScheduleSource>().ToList(); if(scheduleSources.Any()) { for(var i = 0; i < scheduleSources.Count; ++i) { var name = function.Name + "ScheduleEvent" + (i + 1).ToString("00"); _stack.Add(name, new Events.Rule { ScheduleExpression = scheduleSources[i].Expression, Targets = new List<Events.RuleTypes.Target> { new Events.RuleTypes.Target { Id = ToAppResourceName(name), Arn = Fn.GetAtt(function.Name, "Arn"), InputTransformer = new Events.RuleTypes.InputTransformer { InputPathsMap = new Dictionary<string, dynamic> { ["version"] = "$.version", ["id"] = "$.id", ["source"] = "$.source", ["account"] = "$.account", ["time"] = "$.time", ["region"] = "$.region" }, InputTemplate = @"{ ""Version"": <version>, ""Id"": <id>, ""Source"": <source>, ""Account"": <account>, ""Time"": <time>, ""Region"": <region>, ""tName"": """ + scheduleSources[i].Name + @""" }" } } } }); } _stack.Add(function.Name + "ScheduleEventPermission", new Lambda.Permission { Action = "lambda:InvokeFunction", SourceAccount = _module.Settings.AwsAccountId, FunctionName = Fn.GetAtt(function.Name, "Arn"), Principal = "events.amazonaws.com" }); } // check if function has any API gateway event sources var apiSources = function.Sources.OfType<ApiGatewaySource>().ToList(); if(apiSources.Any()) { foreach(var apiEvent in apiSources) { _apiGatewayRoutes.Add(new ApiRoute { Method = apiEvent.Method, Path = apiEvent.Path, Integration = apiEvent.Integration, Function = function }); } } // check if function has any S3 event sources var s3Sources = function.Sources.OfType<S3Source>().ToList(); if(s3Sources.Any()) { foreach(var source in s3Sources.Distinct(source => source.BucketArn)) { _stack.Add($"{function.Name}{source.Bucket}S3Permission", new Lambda.Permission { Action = "lambda:InvokeFunction", SourceAccount = _module.Settings.AwsAccountId, SourceArn = source.BucketArn, FunctionName = Fn.GetAtt(function.Name, "Arn"), Principal = "s3.amazonaws.com" }); } } // check if function has any SQS event sources var sqsSources = function.Sources.OfType<SqsSource>().ToList(); if(sqsSources.Any()) { foreach(var source in sqsSources) { _stack.Add($"{function.Name}{source.Queue}EventMapping", new Lambda.EventSourceMapping { BatchSize = source.BatchSize, Enabled = true, EventSourceArn = Fn.GetAtt(source.Queue, "Arn"), FunctionName = Fn.Ref(function.Name) }); } } // check if function has any Alexa event sources var alexaSources = function.Sources.OfType<AlexaSource>().ToList(); if(alexaSources.Any()) { var index = 0; foreach(var source in alexaSources) { ++index; var suffix = (source.EventSourceToken != null) ? source.EventSourceToken.ToMD5Hash().Substring(0, 7) : index.ToString(); _stack.Add($"{function.Name}AlexaPermission{suffix}", new Lambda.Permission { Action = "lambda:InvokeFunction", FunctionName = Fn.GetAtt(function.Name, "Arn"), Principal = "alexa-appkit.amazon.com", EventSourceToken = source.EventSourceToken }); } } }
public static void IsolatedFunction(ICompilateurInstance comp, IProcessInstance proc, ICodeConverter converter, IsolatedFunctionDelegate d) { if (converter.CurrentFunction.IsStaticControlFlow) { Dictionary <string, IParameter> varNames, leftNames; Action <KeyValuePair <string, IParameter> > action; TypedVariable tv; IFunction prec = converter.CurrentFunction; IFunction thisFunc = new Function(); thisFunc.IndentSize = prec.IndentSize; thisFunc.IsVisible = true; thisFunc.StrictName = "inner_" + comp.Unique.ComputeNewString(); thisFunc.PropagateControlFlow(prec); // ajoute la fonction dans la liste converter.ImplementedFunctions.Add(thisFunc); // change la fonction courante converter.SetCurrentFunction(thisFunc); d(); // retourne à la fonction précédente pour traiter le changement de type converter.SetCurrentFunction(prec); // supprime la fonction de la liste converter.ImplementedFunctions.Remove(thisFunc); leftNames = new Dictionary <string, IParameter>(); // élimine les variables passées en paramètre qui n'ont pas changé de type thisFunc.Parameters.ForEach(new Action <IParameter>(delegate(IParameter par) { if (!leftNames.ContainsKey(par.VariableName) && par.Order != EnumParameterOrder.E_NEW) { leftNames.Add(par.VariableName, par); } })); // enregistre le nom distinct des variables passées en paramètre qui soient mutable et initiale varNames = new Dictionary <string, IParameter>(); thisFunc.Parameters.ForEach(new Action <IParameter>(delegate(IParameter par) { if (!varNames.ContainsKey(par.VariableName) && leftNames.ContainsKey(par.VariableName) && par.IsMutableParameter && par.Order == EnumParameterOrder.E_NEW) { varNames.Add(par.VariableName, par); } })); // modifie toutes les variables en SimpleType action = new Action <KeyValuePair <string, IParameter> >(delegate(KeyValuePair <string, IParameter> kv) { Regex reg = new Regex(@"\$\[([^:]*):([a-z]+_" + kv.Key + @")\]"); thisFunc.Source = reg.Replace(thisFunc.Source, new MatchEvaluator(delegate(Match m) { string type = m.Groups[1].Value; string name = m.Groups[2].Value; int pos = name.IndexOf('_'); string result = String.Empty; if (pos != -1) { result = "$[" + type + ":st_" + name.Substring(pos + 1) + "]"; } else { result = "$[" + type + ":st_" + name + "]"; } return(result); })); tv = new TypedVariable(kv.Value.VariableName, kv.Value.FormalParameter, kv.Value.DataType, EnumDataType.E_SIMPLETYPE); tv.MoveType(converter, proc.CurrentScope); }); foreach (KeyValuePair <string, IParameter> kv in varNames.Except(leftNames)) { action(kv); } // copie de l'implémentation de cette fonction dans la fonction en cours prec.Source += thisFunc.Source; // copies des variables locales de cette fonction dans la fonction en cours thisFunc.LocalVariables.ForEach(new Action <IStructure>(delegate(IStructure loc) { if (!converter.CurrentFunction.LocalVariables.Exists(new Predicate <IStructure>(delegate(IStructure cur) { return(cur.PrefixedFieldName == loc.PrefixedFieldName); }))) { converter.CurrentFunction.LocalVariables.Add(loc); } })); // mettre à jour les paramètres foreach (KeyValuePair <string, IParameter> kv in varNames.Except(leftNames)) { List <IParameter> pars = thisFunc.Parameters.FindAll(new Predicate <IParameter>(delegate(IParameter par) { return(par.VariableName == kv.Key); })); if (pars.Count > 1) { pars.ForEach(new Action <IParameter>(delegate(IParameter update) { if (update.Order == EnumParameterOrder.E_LAST) { tv = new TypedVariable(update.VariableName, update.FormalParameter, EnumDataType.E_SIMPLETYPE, update.DataType); tv.MoveType(converter, proc.CurrentScope); } })); } else if (pars.Count == 1) { tv = new TypedVariable(pars[0].VariableName, pars[0].FormalParameter, EnumDataType.E_SIMPLETYPE, pars[0].DataType); tv.MoveType(converter, proc.CurrentScope); } } } else { d(); } }
/// <summary> /// constructor. gets mission and name as params, /// type gets defines here because it's always "Single" /// </summary> /// <param name="mission"></param> /// <param name="Name"></param> public SingleMission(Function mission, String Name) { this.mission = mission; this.name = Name; this.type = "Single"; }
public ActionResult Index() { GetRootDirect(); string language = UtilRequest.getCookieValue(Request, "UserSettings", "language"); if (language == null) { language = "zh-cn"; } StSystemConfig sysCfg = new stsyscfgBll().GetSystemSetting(); Parameter.CURRENT_SYSTEM_CONFIG = sysCfg; this.ViewData["sysCfg"] = JavaScriptConvert.SerializeObject(Parameter.CURRENT_SYSTEM_CONFIG); Parameter.CURRENT_USER_OPEN_MODE = "Normal"; if (sysCfg.ScSBAD == "Y") { if (User.Identity.Name.ToString().Equals("")) { return(this.RedirectToAction("Index", "Error")); } if (this.HttpContext.Session[Constant.SESSION_CURRENT_USER] == null) { this.HttpContext.Session[Constant.SESSION_CURRENT_USER] = User.Identity.Name.ToString(); //get current AD user } } else { if (this.HttpContext.Session[Constant.SESSION_CURRENT_USER] == null) { return(this.RedirectToAction("Index", "Logon")); } } if (this.HttpContext.Session[Constant.SESSION_AUTHORIZATION] == null) { this.HttpContext.Session[Constant.SESSION_AUTHORIZATION] = new AuthorizationBll().GetAuthorization(Function.GetCurrentUser(), Parameter.APPLICATION_NAME);; this.HttpContext.Session[Constant.SESSION_CURRENT_STAFF] = ((AuthorizationMdl)this.HttpContext.Session[Constant.SESSION_AUTHORIZATION]).User.sfid; } this.HttpContext.Session[Constant.SESSION_CURRENT_MUF] = new MenuConfigBll().getMUFForSession(); ViewData["lang"] = language; ViewData["contextPath"] = Parameter.VIRTURE_DIRECT; ViewData["currentEnvironment"] = Common.ConfigReader.getEnvironmentName(); this.render(); return(View("Index")); }
private static ValueEval invoke(Function function, ValueEval xArray, ValueEval yArray) { ValueEval[] args = new ValueEval[] { xArray, yArray, }; return(function.Evaluate(args, -1, (short)-1)); }
/// <summary> /// Requests the specified animation dictionary. /// </summary> /// <param name="dictionary"></param> public static void RequestAnimationDictionary(string dictionary) { Function.Call(Hash.REQUEST_ANIM_DICT, dictionary); }
public bool TryCreateVariant(Function function, out Function variant, Project core) { variant = null; return(false); }
public override void WritePage(UdnManifest Manifest, string OutputPath) { using (UdnWriter Writer = new UdnWriter(OutputPath)) { Writer.WritePageHeader(Name, PageCrumbs, BriefDescription); // Write the hierarchy if (HierarchyNode != null) { Writer.EnterSection("hierarchy", "Inheritance Hierarchy"); Writer.EnterTag("[REGION:hierarchy]"); APIHierarchy.WriteHierarchy(Writer, HierarchyNode, "hrch"); Writer.LeaveTag("[/REGION]"); Writer.LeaveSection(); } // Write the record definition if (!Utility.IsNullOrWhitespace(Definition)) { Writer.EnterSection("syntax", "Syntax"); WriteDefinition(Writer); Writer.LeaveSection(); } // Write the class description if (!Utility.IsNullOrWhitespace(FullDescription)) { Writer.EnterSection("description", "Remarks"); Writer.WriteLine(FullDescription.Replace("<", "<").Replace(">", ">")); Writer.LeaveSection(); } // Write the main body section Writer.EnterRegion("syntax"); // Build a list of all the functions List <APIFunction> AllFunctions = new List <APIFunction>(); AllFunctions.AddRange(Children.OfType <APIFunction>().Where(x => x.Protection != APIProtection.Private && !x.IsDeprecated())); AllFunctions.AddRange(Children.OfType <APIFunctionGroup>().SelectMany(x => x.Children.OfType <APIFunction>()).Where(x => x.Protection != APIProtection.Private && !x.IsDeprecated())); AllFunctions.Sort((x, y) => String.Compare(x.Name, y.Name)); // Write all the specializations if (TemplateSpecializations.Count > 0) { Writer.EnterSection("specializations", "Specializations"); foreach (APIRecord Specialization in TemplateSpecializations) { Writer.WriteLine("[{0}]({1}) ", Specialization.Name, Specialization.LinkPath); } Writer.LeaveSection(); } // Write all the variables APIVariable.WriteListSection(Writer, "variables", "Variables", Children.OfType <APIVariable>().Where(x => x.Protection != APIProtection.Private && !x.IsDeprecated()).OrderBy(x => x.Name)); // Write all the constructors if (!APIFunction.WriteListSection(Writer, "constructor", "Constructors", AllFunctions.Where(x => x.FunctionType == APIFunctionType.Constructor).OrderBy(x => x.LinkPath), false) && HasAnyPrivateFunction(Name)) { Writer.EnterSection("constructor", "Constructors"); Writer.WriteLine("No constructors are accessible with public or protected access."); Writer.LeaveSection(); } // Write all the destructors if (!APIFunction.WriteListSection(Writer, "destructor", "Destructors", AllFunctions.Where(x => x.FunctionType == APIFunctionType.Destructor), false) && HasAnyPrivateFunction("~" + Name)) { Writer.EnterSection("destructors", "Destructors"); Writer.WriteLine("No destructors are accessible with public or protected access."); Writer.LeaveSection(); } // Find a list of base classes List <APIRecord> AllBaseRecords = new List <APIRecord>(); FindAllBaseRecords(AllBaseRecords); // Build a list of functions for each base record List <APIFunction>[] AllBaseFunctions = AllBaseRecords.Select(x => new List <APIFunction>()).ToArray(); foreach (APIFunction Function in AllFunctions.Where(x => x.FunctionType == APIFunctionType.Normal && !x.IsExecFunction())) { int BaseRecordIdx = AllBaseRecords.IndexOf(Function.GetBaseImplementation().FindParent <APIRecord>()); AllBaseFunctions[Math.Max(0, BaseRecordIdx)].Add(Function); } // Write the functions for (int Idx = 0; Idx < AllBaseFunctions.Length; Idx++) { List <APIFunction> BaseFunctions = AllBaseFunctions[Idx]; if (BaseFunctions.Count > 0) { string Id = String.Format("functions_{0}", Idx); string Label = (Idx == 0) ? "Functions" : String.Format("Overridden from {0}", AllBaseRecords[Idx].Name); APIFunction.WriteListSection(Writer, Id, Label, AllBaseFunctions[Idx], true); } } // Write the operator list APIFunction.WriteListSection(Writer, "operators", "Operators", AllFunctions.Where(x => x.FunctionType == APIFunctionType.UnaryOperator || x.FunctionType == APIFunctionType.BinaryOperator), true); // Write all the inner structures Writer.WriteListSection("classes", "Classes", "Name", "Description", Children.OfType <APIRecord>().Where(x => x.Protection != APIProtection.Private).OrderBy(x => x.Name).Select(x => x.GetListItem())); // Write all the enums Writer.WriteListSection("enums", "Enums", "Name", "Description", Children.OfType <APIEnum>().OrderBy(x => x.Name).Select(x => x.GetListItem())); // Write all the typedefs Writer.WriteListSection("typedefs", "Typedefs", "Name", "Description", Children.OfType <APITypeDef>().Select(x => x.GetListItem())); // Write all the constants Writer.WriteListSection("constants", "Constants", "Name", "Description", Children.OfType <APIConstant>().Select(x => x.GetListItem())); // Leave the body Writer.LeaveRegion(); // Write the marshalling parameters if (DelegateEventParameters != null) { Writer.EnterSection("marshalling", "Marshalling"); Writer.WriteLine("Parameters are marshalled using [{0}]({1})", DelegateEventParameters.FullName, DelegateEventParameters.LinkPath); Writer.LeaveSection(); } // Write the @see directives WriteSeeAlsoSection(Writer, SeeAlso); // Write the references WriteReferencesSection(Writer, Entity); } }
public static float ValidateModel(string modelFile, MinibatchSource testMinibatchSource, int[] imageDim, int numClasses, string featureInputName, string labelInputName, DeviceDescriptor device, int maxCount = 1000, List <List <float> > X = null, List <float> Y = null, bool useConvolution = true) { Function model = Function.Load(modelFile, device); var imageInput = model.Arguments[0]; var labelOutput = model.Output; var featureStreamInfo = testMinibatchSource.StreamInfo(featureInputName); var labelStreamInfo = testMinibatchSource.StreamInfo(labelInputName); int batchSize = 1000; int miscountTotal = 0, totalCount = 0; while (true) { var minibatchData = testMinibatchSource.GetNextMinibatch((uint)batchSize, device); if (minibatchData == null || minibatchData.Count == 0) { break; } totalCount += (int)minibatchData[featureStreamInfo].numberOfSamples; // expected labels are in the minibatch data. var labelData = minibatchData[labelStreamInfo].data.GetDenseData <float>(labelOutput); var expectedLabels = labelData.Select(l => l.IndexOf(l.Max())).ToList(); var inputDataMap = new Dictionary <Variable, Value>() { { imageInput, minibatchData[featureStreamInfo].data } }; var outputDataMap = new Dictionary <Variable, Value>() { { labelOutput, null } }; model.Evaluate(inputDataMap, outputDataMap, device); var faetureData = minibatchData[featureStreamInfo].data.GetDenseData <float>(CNTKLib.InputVariable(minibatchData[featureStreamInfo].data.Shape, DataType.Float, model.Arguments[0].Name)); var outputData = outputDataMap[labelOutput].GetDenseData <float>(labelOutput); var actualLabels = outputData.Select(l => l.IndexOf(l.Max())).ToList(); int misMatches = actualLabels.Zip(expectedLabels, (a, b) => a.Equals(b) ? 0 : 1).Sum(); miscountTotal += misMatches; Console.WriteLine($"Validating Model: Total Samples = {totalCount}, Mis-classify Count = {miscountTotal}"); if (totalCount > 10001) { //writes some result in to array for (int i = 0; i < outputData.Count && X != null && Y != null; i++) { var imgDIm = imageDim.Aggregate(1, (acc, val) => acc * val); var inputVector = faetureData[0].Skip(imgDIm * i).Take(imgDIm).Select(x => (float)x).ToList(); X.Add(inputVector); var currLabel = actualLabels[i]; Y.Add(currLabel); } ; break; } } float errorRate = 1.0F * miscountTotal / totalCount; Console.WriteLine($"Model Validation Error = {errorRate}"); return(errorRate); }
public bool TryCreateOverload(Function function, out ImplementedFunction overload, Project core) { // SuperInvoke currently can't properly marshal string spans, so we need to help out. var sb = new StringBuilder(); var pl = new List <Parameter>(); var ep = new List <string>(); var varied = false; sb.AppendLine("// StringArrayOverloader"); pl.AddRange(function.Parameters); for (var i = 0; i < pl.Count; i++) { var parameter = pl[i]; if (parameter.Type.ToString() == "char**" || parameter.Type.ToString() == "byte**") { pl[i] = new ParameterSignatureBuilder(parameter).WithType ( new Type { Name = "string", ArrayDimensions = 1 } ) .WithName(parameter.Name + "Sa") .Build(); varied = true; sb.AppendLine ( $"var {parameter.Name} = ({parameter.Type}) SilkMarshal.MarshalStringArrayToPtr({parameter.Name}Sa);" ); ep.Add($"SilkMarshal.CopyPtrToStringArray((IntPtr) {parameter.Name}, {parameter.Name}Sa);"); } } if (function.ReturnType.ToString() != "void") { sb.Append("var ret = "); } sb.AppendLine ( $"{function.Name}" + $"({string.Join(", ", function.Parameters.Select(x => (x.Type.IsByRef ? "ref " : string.Empty) + x.Name))});" ); foreach (var epilogueLine in ep) { sb.AppendLine(epilogueLine); } if (function.ReturnType.ToString() != "void") { sb.AppendLine("return ret;"); } if (varied) { overload = new ImplementedFunction (new FunctionSignatureBuilder(function).WithParameters(pl).Build(), sb, function); return(true); } overload = null; return(false); }
public override bool VisitFunctionDecl(Function function) { if (!VisitDeclaration(function) || function.IsSynthetized || function.IsExplicitlyGenerated) { return(false); } if (function.IsDependent && !(function.Namespace is Class)) { function.GenerationKind = GenerationKind.None; Diagnostics.Debug("Function '{0}' was ignored due to dependent context", function.Name); return(false); } var ret = function.OriginalReturnType; string msg; if (HasInvalidType(ret.Type, function, out msg)) { function.ExplicitlyIgnore(); Diagnostics.Debug("Function '{0}' was ignored due to {1} return decl", function.Name, msg); return(false); } foreach (var param in function.Parameters) { if (HasInvalidDecl(param, out msg)) { function.ExplicitlyIgnore(); Diagnostics.Debug("Function '{0}' was ignored due to {1} param", function.Name, msg); return(false); } if (HasInvalidType(param, out msg)) { function.ExplicitlyIgnore(); Diagnostics.Debug("Function '{0}' was ignored due to {1} param", function.Name, msg); return(false); } if (CheckDecayedTypes) { var decayedType = param.Type.Desugar() as DecayedType; if (decayedType != null) { function.ExplicitlyIgnore(); Diagnostics.Debug("Function '{0}' was ignored due to unsupported decayed type param", function.Name); return(false); } } if (param.Kind == ParameterKind.IndirectReturnType) { Class retClass; param.Type.Desugar().TryGetClass(out retClass); if (retClass == null) { function.ExplicitlyIgnore(); Diagnostics.Debug( "Function '{0}' was ignored due to an indirect return param not of a tag type", function.Name); return(false); } } } return(true); }
public static double ComputeFunction(string fHead, Function f, Argument arg) { Expression e = new Expression(fHead, f, arg); return(e.calculate()); }
/** * A Vector3[] variation of the Transform[] NewBezier() function. * Same functionality but using Vector3s to define bezier curve. */ public static IEnumerable <Vector3> NewBezier(Function ease, Vector3[] points, float duration) { IEnumerable <float> timer = NewTimer(duration); return(NewBezier <Vector3>(ease, points, Identity, duration, timer)); }
public static async Task Tick() { int CreateBlipForPlayer(int playerId, int pedId) { int blip = Function.Call <int>((Hash)0x23f74c2fda6e7c61, 422991367, pedId); Function.Call(Hash.SET_BLIP_NAME_TO_PLAYER_NAME, playerId); Function.Call(Hash.SET_BLIP_SCALE, blip, 0.90f); return(blip); } int CreateGamerTagForPlayer(int playerPed, string playerName) { return(Function.Call <int>(Hash.CREATE_FAKE_MP_GAMER_TAG, playerPed, playerName, true, true, "CFX", 3)); } for (int i = 0; i < 32; i++) { int ped = API.GetPlayerPed(i); string name = Function.Call <string>(Hash.GET_PLAYER_NAME, i); if (Function.Call <bool>(Hash.NETWORK_IS_PLAYER_CONNECTED, i)) { if (!players.ContainsKey(i) || players[i].State == State.Disconnected) { players[i] = new PlayerInfo { State = State.Connected }; } else if (players[i].State == State.Connected) { if (Function.Call <bool>(Hash.DOES_ENTITY_EXIST, ped)) { players[i].PedId = ped; players[i].State = State.HasGamerTag; if (ped != API.PlayerPedId()) { if (!Function.Call <bool>(Hash.DOES_BLIP_EXIST, players[i].BlipId)) { players[i].BlipId = CreateBlipForPlayer(i, ped); } if (!Function.Call <bool>(Hash.IS_MP_GAMER_TAG_ACTIVE, players[i].GamerTagId)) { players[i].GamerTagId = CreateGamerTagForPlayer(ped, name); } Debug.WriteLine($"Created gamer tag and blip for {name}"); } else { Debug.WriteLine("Skipped creating gamer tag for local player"); } } } else if (players[i].State == State.HasGamerTag) { if (ped != API.PlayerPedId()) { if (ped != players[i].PedId) { Function.Call(Hash.REMOVE_MP_GAMER_TAG, players[i].GamerTagId); Function.Call(Hash.REMOVE_BLIP, players[i].BlipId); players[i].PedId = ped; players[i].BlipId = CreateBlipForPlayer(i, ped); players[i].GamerTagId = CreateGamerTagForPlayer(i, name); Debug.WriteLine($"Re-created gamer tag and blip for {name}"); } } } } else if (players.ContainsKey(i) && players[i].State != State.Disconnected) { players[i].State = State.Disconnected; } } await Task.FromResult(0); }
/** * Returns sequence generator from the first node to the last node over * duration time using the points in-between the first and last node * as control points of a bezier curve used to generate the interpolated points * in the sequence. If there are no control points (ie. only two nodes, first * and last) then this behaves exactly the same as NewEase(). In other words * a zero-degree bezier spline curve is just the easing method. The sequence * is generated as it is accessed using the Time.deltaTime to calculate the * portion of duration that has elapsed. */ public static IEnumerable <Vector3> NewBezier(Function ease, Transform[] nodes, float duration) { IEnumerable <float> timer = Interpolate.NewTimer(duration); return(NewBezier <Transform>(ease, nodes, TransformDotPosition, duration, timer)); }
/** * A Vector3[] variation of the Transform[] NewBezier() function. * Same functionality but using Vector3s to define bezier curve. */ public static IEnumerable <Vector3> NewBezier(Function ease, Vector3[] points, int slices) { IEnumerable <float> counter = NewCounter(0, slices + 1, 1); return(NewBezier <Vector3>(ease, points, Identity, slices + 1, counter)); }
/** * Instead of easing based on time, generate n interpolated points (slices) * between the start and end positions. */ public static IEnumerator NewEase(Function ease, Vector3 start, Vector3 end, int slices) { IEnumerable <float> counter = Interpolate.NewCounter(0, slices + 1, 1); return(NewEase(ease, start, end, slices + 1, counter)); }
/** * Instead of interpolating based on time, generate n interpolated points * (slices) between the first and last node. */ public static IEnumerable <Vector3> NewBezier(Function ease, Transform[] nodes, int slices) { IEnumerable <float> counter = NewCounter(0, slices + 1, 1); return(NewBezier <Transform>(ease, nodes, TransformDotPosition, slices + 1, counter)); }
public Task <byte[]> Send(Function function, params byte[] payload) { return(Send(function, CancellationToken.None, payload)); }
/** * Returns the static method that implements the given easing type for scalars. * Use this method to easily switch between easing interpolation types. * * All easing methods clamp elapsedTime so that it is always <= duration. * * var ease = Interpolate.Ease(EaseType.EaseInQuad); * i = ease(start, distance, elapsedTime, duration); */ public static Function Ease(EaseType type) { // Source Flash easing functions: // http://gizma.com/easing/ // http://www.robertpenner.com/easing/easing_demo.html // // Changed to use more friendly variable names, that follow my Lerp // conventions: // start = b (start value) // distance = c (change in value) // elapsedTime = t (current time) // duration = d (time duration) Function f = null; switch (type) { case EaseType.Linear: f = Interpolate.Linear; break; case EaseType.EaseInQuad: f = Interpolate.EaseInQuad; break; case EaseType.EaseOutQuad: f = Interpolate.EaseOutQuad; break; case EaseType.EaseInOutQuad: f = Interpolate.EaseInOutQuad; break; case EaseType.EaseInCubic: f = Interpolate.EaseInCubic; break; case EaseType.EaseOutCubic: f = Interpolate.EaseOutCubic; break; case EaseType.EaseInOutCubic: f = Interpolate.EaseInOutCubic; break; case EaseType.EaseInQuart: f = Interpolate.EaseInQuart; break; case EaseType.EaseOutQuart: f = Interpolate.EaseOutQuart; break; case EaseType.EaseInOutQuart: f = Interpolate.EaseInOutQuart; break; case EaseType.EaseInQuint: f = Interpolate.EaseInQuint; break; case EaseType.EaseOutQuint: f = Interpolate.EaseOutQuint; break; case EaseType.EaseInOutQuint: f = Interpolate.EaseInOutQuint; break; case EaseType.EaseInSine: f = Interpolate.EaseInSine; break; case EaseType.EaseOutSine: f = Interpolate.EaseOutSine; break; case EaseType.EaseInOutSine: f = Interpolate.EaseInOutSine; break; case EaseType.EaseInExpo: f = Interpolate.EaseInExpo; break; case EaseType.EaseOutExpo: f = Interpolate.EaseOutExpo; break; case EaseType.EaseInOutExpo: f = Interpolate.EaseInOutExpo; break; case EaseType.EaseInCirc: f = Interpolate.EaseInCirc; break; case EaseType.EaseOutCirc: f = Interpolate.EaseOutCirc; break; case EaseType.EaseInOutCirc: f = Interpolate.EaseInOutCirc; break; } return(f); }
// http://www.ecma-international.org/ecma-262/5.1/#sec-10.5 public void DeclarationBindingInstantiation(DeclarationBindingType declarationBindingType, IList <FunctionDeclaration> functionDeclarations, IList <VariableDeclaration> variableDeclarations, FunctionInstance functionInstance, JsValue[] arguments) { var env = ExecutionContext.VariableEnvironment.Record; bool configurableBindings = declarationBindingType == DeclarationBindingType.EvalCode; var strict = StrictModeScope.IsStrictModeCode; if (declarationBindingType == DeclarationBindingType.FunctionCode) { var argCount = arguments.Length; var n = 0; foreach (var argName in functionInstance.FormalParameters) { n++; var v = n > argCount ? Undefined.Instance : arguments[n - 1]; var argAlreadyDeclared = env.HasBinding(argName); if (!argAlreadyDeclared) { env.CreateMutableBinding(argName); } env.SetMutableBinding(argName, v, strict); } } foreach (var f in functionDeclarations) { var fn = f.Id.Name; var fo = Function.CreateFunctionObject(f); var funcAlreadyDeclared = env.HasBinding(fn); if (!funcAlreadyDeclared) { env.CreateMutableBinding(fn, configurableBindings); } else { if (env == GlobalEnvironment.Record) { var go = Global; var existingProp = go.GetProperty(fn); if (existingProp.Configurable.Value) { go.DefineOwnProperty(fn, new PropertyDescriptor( value: Undefined.Instance, writable: true, enumerable: true, configurable: configurableBindings ), true); } else { if (existingProp.IsAccessorDescriptor() || (!existingProp.Enumerable.Value)) { throw new JavaScriptException(TypeError); } } } } env.SetMutableBinding(fn, fo, strict); } var argumentsAlreadyDeclared = env.HasBinding("arguments"); if (declarationBindingType == DeclarationBindingType.FunctionCode && !argumentsAlreadyDeclared) { var argsObj = ArgumentsInstance.CreateArgumentsObject(this, functionInstance, functionInstance.FormalParameters, arguments, env, strict); if (strict) { var declEnv = env as DeclarativeEnvironmentRecord; if (declEnv == null) { throw new ArgumentException(); } declEnv.CreateImmutableBinding("arguments"); declEnv.InitializeImmutableBinding("arguments", argsObj); } else { env.CreateMutableBinding("arguments"); env.SetMutableBinding("arguments", argsObj, false); } } // process all variable declarations in the current parser scope foreach (var d in variableDeclarations.SelectMany(x => x.Declarations)) { var dn = d.Id.Name; var varAlreadyDeclared = env.HasBinding(dn); if (!varAlreadyDeclared) { env.CreateMutableBinding(dn, configurableBindings); env.SetMutableBinding(dn, Undefined.Instance, strict); } } }
/** * Returns sequence generator from start to end over duration using the * given easing function. The sequence is generated as it is accessed * using the Time.deltaTime to calculate the portion of duration that has * elapsed. */ public static IEnumerator NewEase(Function ease, Vector3 start, Vector3 end, float duration) { IEnumerable <float> timer = Interpolate.NewTimer(duration); return(NewEase(ease, start, end, duration, timer)); }
public abstract void GenerateBody(Function decl, CodeWriter s);
// Ln(f(x)) or Log[a](f(x)) public Logarithm(Function f, double a = Math.E) { _a = a; _innerF = f; }
private void button1_Click(object sender, EventArgs e) { string sql; double sl, SLcon, tong, Tongmoi, s2, SLDoi; double tongmoi, ThanhTiensua, tt2; // Lưu thông tin của các mặt hàng if (cboMaHang.Text.Trim().Length == 0) { MessageBox.Show("Bạn phải nhập mã hàng", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information); cboMaHang.Focus(); return; } if ((txtSoLuong.Text.Trim().Length == 0) || (txtSoLuong.Text == "0")) { MessageBox.Show("Bạn phải nhập số lượng", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information); txtSoLuong.Text = ""; txtSoLuong.Focus(); return; } if (txtGiamGia.Text.Trim().Length == 0) { MessageBox.Show("Bạn phải nhập giảm giá", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information); txtGiamGia.Focus(); return; } // Kiểm tra xem số lượng hàng trong kho có đủ ko sl = Convert.ToDouble(Function.GetFieldValues("SELECT SoLuong FROM DienThoai WHERE MaDienThoai = N'" + cboMaHang.Text + "'")); if (Convert.ToDouble(txtSoLuong.Text) > sl) { MessageBox.Show("Số lượng điện thoại này chỉ còn " + sl, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information); txtSoLuong.Text = ""; txtSoLuong.Focus(); return; } tt2 = Convert.ToDouble(Function.GetFieldValues("SELECT ThanhTien FROM ChiTietHDBan WHERE MaHDBan = N'" + txtMaHDBan.Text + "' AND MaDienThoai = N'" + cboMaHang.Text + "'")); s2 = Convert.ToDouble(Function.GetFieldValues("SELECT SoLuong FROM ChiTietHDBan WHERE MaDienThoai = N'" + cboMaHang.Text + "' AND MaHDBan=N'" + txtMaHDBan.Text + "'")); sql = "UPDATE ChiTietHDBan SET SoLuong =" + Convert.ToDouble(txtSoLuong.Text) + ",GiamGia=" + txtGiamGia.Text + ",ThanhTien=" + Convert.ToDouble(txtThanhTien.Text) + " WHERE MaHDBan = N'" + txtMaHDBan.Text + "' AND MaDienThoai=N'" + cboMaHang.Text + "'"; Function.RunSQL(sql); LoadDataGridView(); // Cập nhật lại số lượng của mặt hàng vào bảng Hang SLDoi = Convert.ToDouble(txtSoLuong.Text) - s2; SLcon = sl - SLDoi; sql = "UPDATE DienThoai SET SoLuong =" + SLcon + " WHERE MaDienThoai= N'" + cboMaHang.Text + "'"; Function.RunSQL(sql); // Cập nhật lại tổng tiền cho hóa qđơn bán // Cập nhật lại tổng tiền cho hóa đơn bán tong = Convert.ToDouble(Function.GetFieldValues("SELECT TongTien FROM HDBan WHERE MaHDBan = N'" + txtMaHDBan.Text + "'")); ThanhTiensua = Convert.ToDouble(txtThanhTien.Text) - tt2; tongmoi = tong + ThanhTiensua; sql = "UPDATE HDBan SET TongTien =" + tongmoi + " WHERE MaHDBan = N'" + txtMaHDBan.Text + "'"; Function.RunSQL(sql); txtTongTien.Text = tongmoi.ToString(); LoadDataGridView(); ResetValuesHang(); btnXoa.Enabled = true; btnThem.Enabled = true; btnInHoaDon.Enabled = true; button1.Enabled = false; }
public Engine(Action <Options> options) { _executionContexts = new Stack <ExecutionContext>(); Global = GlobalObject.CreateGlobalObject(this); Object = ObjectConstructor.CreateObjectConstructor(this); Function = FunctionConstructor.CreateFunctionConstructor(this); Array = ArrayConstructor.CreateArrayConstructor(this); String = StringConstructor.CreateStringConstructor(this); RegExp = RegExpConstructor.CreateRegExpConstructor(this); Number = NumberConstructor.CreateNumberConstructor(this); Boolean = BooleanConstructor.CreateBooleanConstructor(this); Date = DateConstructor.CreateDateConstructor(this); Math = MathInstance.CreateMathObject(this); Json = JsonInstance.CreateJsonObject(this); Error = ErrorConstructor.CreateErrorConstructor(this, "Error"); EvalError = ErrorConstructor.CreateErrorConstructor(this, "EvalError"); RangeError = ErrorConstructor.CreateErrorConstructor(this, "RangeError"); ReferenceError = ErrorConstructor.CreateErrorConstructor(this, "ReferenceError"); SyntaxError = ErrorConstructor.CreateErrorConstructor(this, "SyntaxError"); TypeError = ErrorConstructor.CreateErrorConstructor(this, "TypeError"); UriError = ErrorConstructor.CreateErrorConstructor(this, "URIError"); // Because the properties might need some of the built-in object // their configuration is delayed to a later step Global.Configure(); Object.Configure(); Object.PrototypeObject.Configure(); Function.Configure(); Function.PrototypeObject.Configure(); Array.Configure(); Array.PrototypeObject.Configure(); String.Configure(); String.PrototypeObject.Configure(); RegExp.Configure(); RegExp.PrototypeObject.Configure(); Number.Configure(); Number.PrototypeObject.Configure(); Boolean.Configure(); Boolean.PrototypeObject.Configure(); Date.Configure(); Date.PrototypeObject.Configure(); Math.Configure(); Json.Configure(); Error.Configure(); Error.PrototypeObject.Configure(); // create the global environment http://www.ecma-international.org/ecma-262/5.1/#sec-10.2.3 GlobalEnvironment = LexicalEnvironment.NewObjectEnvironment(this, Global, null, false); // create the global execution context http://www.ecma-international.org/ecma-262/5.1/#sec-10.4.1.1 EnterExecutionContext(GlobalEnvironment, GlobalEnvironment, Global); Options = new Options(this); if (options != null) { options(Options); } Eval = new EvalFunctionInstance(this, new string[0], LexicalEnvironment.NewDeclarativeEnvironment(this, ExecutionContext.LexicalEnvironment), StrictModeScope.IsStrictModeCode); Global.FastAddProperty("eval", Eval, true, false, true); _statements = new StatementInterpreter(this); _expressions = new ExpressionInterpreter(this); if (Options._IsClrAllowed) { Global.FastAddProperty("System", new NamespaceReference(this, "System"), false, false, false); Global.FastAddProperty("importNamespace", new ClrFunctionInstance(this, (thisObj, arguments) => { return(new NamespaceReference(this, TypeConverter.ToString(arguments.At(0)))); }), false, false, false); } ClrTypeConverter = new DefaultTypeConverter(this); BreakPoints = new List <BreakPoint>(); DebugHandler = new DebugHandler(this); }