Exemplo n.º 1
0
 /// <summary>
 /// Initializes a new instance of the <see cref="IModelo2D"/> class.
 /// </summary>
 /// <param name="ModelType">Type of the model.</param>
 public IModelo2D(ModelType ModelType)
 {
     this.ModelType = ModelType;
     LayerDepth = 0;
     SourceRectangle = null;
     Rotation = 0;
 }
Exemplo n.º 2
0
        public static void GenConvertToModel(StringBuilder builder, ModelType Model)
        {
            string ModelName = Model.Name.Value;

            builder.AppendLine(GeneratorUtil.TabString(1) + @"public static " + ModelName + " " + GetConvertName(Model.Name.Value) + "(DataRow row )");
            builder.AppendLine(GeneratorUtil.TabString(1) + "{");
            builder.AppendLine(GeneratorUtil.TabString(2)   + ModelName + " info = new " + ModelName + "();");
            foreach (FieldType field in Model.MyFields)
            {
                string systemType = field.SystemType.Value;
                string fieldName = field.Name.Value;
                string columnName = field.ColumnName.Value;

                builder.AppendLine(GeneratorUtil.TabString(2) + "if ( row[\"" + columnName + "\"] == DBNull.Value)");
                builder.AppendLine(GeneratorUtil.TabString(2) + "{");
                if (!field.NullAble.Value)
                {
                    builder.AppendLine(GeneratorUtil.TabString(3) + "info." + fieldName + " = default(" + systemType + ");");
                }
                builder.AppendLine(GeneratorUtil.TabString(2) + "}");
                builder.AppendLine(GeneratorUtil.TabString(2) + "else");
                builder.AppendLine(GeneratorUtil.TabString(2) + "{");
                builder.AppendLine(GeneratorUtil.TabString(3) + "info." + fieldName + " = (" + systemType + ")row[\"" + columnName + "\"];");
                builder.AppendLine(GeneratorUtil.TabString(2) + "}");
            }
            builder.AppendLine(GeneratorUtil.TabString(2) + "return info;");
            builder.AppendLine(GeneratorUtil.TabString(1) + "}");
        }
Exemplo n.º 3
0
 public MyModel(Project1Game game, VertexPositionColor[] shapeArray, String textureName)
 {
     this.vertices = Buffer.Vertex.New(game.GraphicsDevice, shapeArray);
     this.inputLayout = VertexInputLayout.New<VertexPositionColor>(0);
     vertexStride = Utilities.SizeOf<VertexPositionColor>();
     modelType = ModelType.Colored;
 }
Exemplo n.º 4
0
    public HandRepresentation(int handID, Hand hand, Chirality chirality, ModelType modelType) {
      HandID = handID;
      this.MostRecentHand = hand;
      this.RepChirality = chirality;
      this.RepType = modelType;

    }
        public NewDbContextTemplateModel(string dbContextName, ModelType modelType)
        {
            if (dbContextName == null)
            {
                throw new ArgumentNullException(nameof(dbContextName));
            }

            if (modelType == null)
            {
                throw new ArgumentNullException(nameof(modelType));
            }

            var modelNamespace = modelType.Namespace;

            ModelTypeName = modelType.Name;
            RequiredNamespaces = new HashSet<string>();

            var classNameModel = new ClassNameModel(dbContextName);

            DbContextTypeName = classNameModel.ClassName;
            DbContextNamespace = classNameModel.NamespaceName;

            if (!string.IsNullOrEmpty(modelNamespace) &&
                !string.Equals(modelNamespace, DbContextNamespace, StringComparison.Ordinal))
            {
                RequiredNamespaces.Add(modelNamespace);
            }
        }
Exemplo n.º 6
0
 internal JsonInstance(ModelType type, string id)
 {
     this.Type = type;
     this.Id = id;
     this.instance = new ModelInstance(this);
     instanceProperties = new object[Type.Properties.Count];
 }
Exemplo n.º 7
0
 public static bool IsASupportedModelType(ModelType modelType)
 {
     switch(modelType)
     {
         case ModelType.Truss1D:
             return false;
         case ModelType.Beam1D:
             return true;
         case ModelType.Truss2D:
             return false;
         case ModelType.Frame2D:
             return true;
         case ModelType.Slab2D:
             return true;
         case ModelType.Membrane2D:
             return false;
         case ModelType.Truss3D:
             return false;
         case ModelType.Membrane3D:
             return false;
         case ModelType.MultiStorey2DSlab:
             return true;
         case ModelType.Full3D:
             return true;
         default:
             throw new NotImplementedException(string.Format(
                 System.Globalization.CultureInfo.InvariantCulture,
                 "Linear3DBeam.IsSupportedModelType(ModelType) has not been defined for a model type of {0}",
                 modelType));
     }
 }
Exemplo n.º 8
0
        private async void LoadData(Uri location, ModelType modelType = ModelType.Line)
        {
            if (HttpClient != null)
            {
                _httpClient.BaseAddress = location;
                var response = await _httpClient.GetAsync(_httpClient.BaseAddress);
                response.EnsureSuccessStatusCode();
                var jsonResult = response.Content.ReadAsStringAsync().Result;

                var resultArray = JsonConvert.DeserializeObject(jsonResult);
                var result = resultArray as JArray;

                switch (modelType)
                {
                    case ModelType.Line:                        
                        foreach (JObject jsonObj in result)
                        {
                            Line line = JsonConvert.DeserializeObject<Line>(jsonObj.ToString());
                            Lines.Add(line);
                        }                        
                        break;

                    case ModelType.Stop:
                        foreach (var jsonObj in result)
                        {
                            var stop = JsonConvert.DeserializeObject<Stop>(jsonObj.ToString());
                            Stops.Add(stop);
                        }
                        break;

                    default:
                        break;
                }
            }
        }
Exemplo n.º 9
0
        public override HandRepresentation MakeHandRepresentation(Leap.Hand hand, ModelType modelType)
        {
            HandRepresentation handRep = null;
              for (int i = 0; i < ModelPool.Count; i++) {
            IHandModel model = ModelPool[i];

            bool isCorrectHandedness;
            if(model.Handedness == Chirality.Either) {
              isCorrectHandedness = true;
            } else {
              Chirality handChirality = hand.IsRight ? Chirality.Right : Chirality.Left;
              isCorrectHandedness = model.Handedness == handChirality;
            }

            bool isCorrectModelType;
            isCorrectModelType = model.HandModelType == modelType;

            if(isCorrectHandedness && isCorrectModelType) {
              ModelPool.RemoveAt(i);
              handRep = new HandProxy(this, model, hand);
              break;
            }
              }
              return handRep;
        }
Exemplo n.º 10
0
 private void SaveResearchInfo(Guid researchID, 
     string researchName,
     ResearchType rType,
     ModelType mType,
     int realizationCount)
 {
     throw new NotImplementedException();
 }
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="dsElementName"></param>
 /// <param name="dataType"></param>
 /// <param name="alias"></param>
 /// <param name="allowsNull"></param>
 public DisplaySetServiceArgumentInfo(string name, string dsElementName, ModelType dataType, string alias, bool allowsNull)
 {
     mName = name;
     mDSElementName = dsElementName;
     mDataType = dataType;
     mAlias = alias;
     mAllowsNull = allowsNull;
 }
Exemplo n.º 12
0
 protected ModelMethodParameter(ModelMethod method, string name, Type parameterType, ModelType referenceType, bool isList)
 {
     this.Method = method;
     this.Name = name;
     this.ParameterType = parameterType;
     this.ReferenceType = referenceType;
     this.IsList = isList;
 }
Exemplo n.º 13
0
 public MyModel(LabGame game, VertexPositionColor[] shapeArray, String textureName, float collisionRadius)
 {
     this.vertices = Buffer.Vertex.New(game.GraphicsDevice, shapeArray);
     this.inputLayout = VertexInputLayout.New<VertexPositionColor>(0);
     vertexStride = Utilities.SizeOf<VertexPositionColor>();
     modelType = ModelType.Colored;
     this.collisionRadius = collisionRadius;
 }
Exemplo n.º 14
0
 public HandProxy(HandPool parent, Hand hand, Chirality repChirality, ModelType repType) :
   base(hand.Id, hand, repChirality, repType)
 {
   this.parent = parent;
   this.RepChirality = repChirality;
   this.RepType = repType;
   this.MostRecentHand = hand;
 }
        /// <summary>
        /// Constructor
        /// </summary>
        public ModelInfo(string projectId, string modelId, List<Guid> elementIds, ModelType modelType)
        {
            ProjectId = projectId;
            ModelId = modelId;
            ElementIds = elementIds;
            ModelType = modelType;

            _controller = DataController.Instance;
        }
Exemplo n.º 16
0
        /// <summary>
        /// Apply display format by default for all data types
        /// All the values will be shown using those formats
        /// </summary>
        /// <param name="value">Value.</param>
        /// <param name="dataType">Data type.</param>
        /// <returns>string.</returns>
        public static string ApplyDisplayFormat(object value, ModelType dataType)
        {
            if (value == null)
            {
                return string.Empty;
            }
            try
            {
                string format = GetDefaultDisplayMask(dataType);
                switch (dataType)
                {
                    case ModelType.Date:
                        DateTime DateAux = System.Convert.ToDateTime(value, CultureManager.Culture);
                        return DateAux.ToString(format);

                    case ModelType.DateTime:
                        DateTime DateTimeAux = System.Convert.ToDateTime(value, CultureManager.Culture);
                        return DateTimeAux.ToString(format);

                    case ModelType.Time:
                        DateTime TimeAux = System.Convert.ToDateTime(value.ToString(), CultureManager.Culture);
                        return TimeAux.ToString(format);

                    case ModelType.Autonumeric:
                    case ModelType.Int:
                        int IntAux = System.Convert.ToInt32(value);
                        return IntAux.ToString(format);

                    case ModelType.Nat:
                        UInt32 NatAux = System.Convert.ToUInt32(value);
                        return NatAux.ToString(format);

                    case ModelType.Real:
                        Decimal RealAux = System.Convert.ToDecimal(value);
                        return RealAux.ToString(format);

                    case ModelType.String:
                    case ModelType.Password:
                    case ModelType.Blob:
                    case ModelType.Text:
                        string StringAux = System.Convert.ToString(value);
                        return StringAux.ToString(CultureManager.Culture);

                    case ModelType.Bool:
                        bool BoolAux = System.Convert.ToBoolean(value);
                        return BoolAux.ToString(CultureManager.Culture);

                    default:
                        return value.ToString();
                }
            }
            catch
            {
                return value.ToString();
            }
        }
Exemplo n.º 17
0
 public GH_Model(ModelType modelType)
 {
     this.ModelType = modelType;
     this.Model = new FiniteElementModel(ModelType);
     this.Nodes = new List<FiniteElementNode>();
     this.Points = new List<Point3d>();
     this.Results = null;
     this.Elements = new List<GH_Element>();
     this.Loads = new List<GH_Load>();
     this.Supports = new List<GH_Support>();
 }
Exemplo n.º 18
0
        /// <summary>
        /// Creates a new <see cref="ModelSource"/> for the specified root type and path.
        /// </summary>
        /// <param name="rootType">The root type name, which is required for instance paths</param>
        /// <param name="path">The source path, which is either an instance path or a static path</param>
        public ModelSource(ModelType rootType, string path)
        {
            // Raise an error if the specified path is not valid
            if (!pathValidation.IsMatch(path))
                throw new ArgumentException("The specified path, '" + path + "', was not valid path syntax.");

            // Raise an error if the specified path is not valid
            ModelProperty property;
            if (!InitializeFromTypeAndPath(rootType, path, out property))
                throw new ArgumentException("The specified path, '" + path + "', was not valid for the root type of '" + rootType.Name + "'.", "path");
        }
        /// <summary>
        /// Retrieves available analyze options for specified research type and model type.
        /// </summary>
        /// <param name="rt">Research type.</param>
        /// <param name="mt">Model type.</param>
        /// <returns>Available analyze options.</returns>
        /// <note>Analyze option is available for research, if it is available 
        /// both for research type and model type.</note>
        public static AnalyzeOption GetAvailableAnalyzeOptions(ResearchType rt, ModelType mt)
        {
            ResearchTypeInfo[] rInfo = (ResearchTypeInfo[])rt.GetType().GetField(rt.ToString()).GetCustomAttributes(typeof(ResearchTypeInfo), false);
            Type researchType = Type.GetType(rInfo[0].Implementation, true);

            AvailableAnalyzeOption rAvailableOptions = ((AvailableAnalyzeOption[])researchType.GetCustomAttributes(typeof(AvailableAnalyzeOption), true))[0];

            ModelTypeInfo[] mInfo = (ModelTypeInfo[])mt.GetType().GetField(mt.ToString()).GetCustomAttributes(typeof(ModelTypeInfo), false);
            Type modelType = Type.GetType(mInfo[0].Implementation, true);

            AvailableAnalyzeOption mAvailableOptions = ((AvailableAnalyzeOption[])modelType.GetCustomAttributes(typeof(AvailableAnalyzeOption), true))[0];

            return rAvailableOptions.Options & mAvailableOptions.Options;
        }
Exemplo n.º 20
0
        public ModelTypeInfo GetModelTypeInfo(ModelType type)
        {
            // Create the set of type instance information if not initialized
            if (Instances == null)
                Instances = new Dictionary<string, ModelTypeInfo>();

            // Get or initialize the model type instance information store
            ModelTypeInfo typeInfo;
            if (!Instances.TryGetValue(type.Name, out typeInfo))
                Instances[type.Name] = typeInfo = new ModelTypeInfo();

            // Return the requested value
            return typeInfo;
        }
Exemplo n.º 21
0
        /// <summary>
        /// Creates a new instance of the 'IntroductionPattern' class for numeric values (Int or Nat).
        /// </summary>
        /// <param name="dataType">Data type of the introduction pattern.</param>
        /// <param name="minValue">Minimum value of the introduction pattern.</param>
        /// <param name="maxValue">Maximum value of the introduction pattern.</param>
        /// <param name="maxIntegerDigits">Maximum integer digits of the introduction pattern.</param>
        /// <param name="ipValidationMessage">Validation message of the introduction pattern.</param>
        public IntroductionPattern(
			ModelType dataType,
			decimal? minValue,
			decimal? maxValue,
			string ipValidationMessage)
        {
            DataType = dataType;
            MinValue = minValue;
            MaxValue = maxValue;

            if (minValue == null || maxValue == null)
            {
                // If one of the two limits is not specified, it can not be restricted the max number of digits.
                mMaxIntegerDigits = null;
            }
            else
            {
                // Calculate the maximum number of integer positions, based on the max value and the min value.
                int? lMaxIntegerDigitsFromMaxValue = null;
                int? lMaxIntegerDigitsFromMinValue = null;
                if (maxValue != null)
                {
                    lMaxIntegerDigitsFromMaxValue = 1;
                    if (maxValue.Value != 0)
                    {
                        maxValue = Math.Abs(maxValue.Value); // Get the unsigned value, because Log10 returns NaN for negative values.
                        double lMaxValue = Math.Truncate(Math.Abs(Math.Log10((double)maxValue.Value))) + 1;
                        lMaxIntegerDigitsFromMaxValue = Convert.ToInt32(lMaxValue);
                    }
                }
                if (minValue != null)
                {
                    lMaxIntegerDigitsFromMinValue = 1;
                    if (minValue.Value != 0)
                    {
                        minValue = Math.Abs(minValue.Value); // Get the unsigned value, because Log10 returns NaN for negative values.
                        double lMinValue = Math.Truncate(Math.Abs(Math.Log10((double)minValue.Value))) + 1;
                        lMaxIntegerDigitsFromMinValue = Convert.ToInt32(lMinValue);
                    }
                }
                if (lMaxIntegerDigitsFromMaxValue != null && lMaxIntegerDigitsFromMinValue != null)
                {
                    // Get the maximum value between the max number of digits for maxValue and the max number of digits for minValue.
                    mMaxIntegerDigits = Math.Max(lMaxIntegerDigitsFromMaxValue.Value, lMaxIntegerDigitsFromMinValue.Value);
                }
            }

            IPValidationMessage = ipValidationMessage;
        }
Exemplo n.º 22
0
 /// <summary>
 /// Get a scene or create it (And add it in the scene list)
 /// </summary>
 /// <param name="idAnimation"></param>
 /// <returns></returns>
 protected KineapScene GetOrCreateScene(int idAnimation, ModelType modelType)
 {
     KineapScene matchingSkeleton = sceneList.Where(animTmp => animTmp.SceneId == idAnimation)
                         .FirstOrDefault();
     Scene matchingScene = null;
     if (matchingSkeleton == null)
     {
         matchingScene = new Scene();
         matchingSkeleton = new KineapScene(idAnimation, matchingScene);
         matchingSkeleton.ModelType = modelType;
         this.sceneList.Add(matchingSkeleton);
     }
     else
         matchingScene = matchingSkeleton.Scene;
     return matchingSkeleton;
 }
Exemplo n.º 23
0
 protected internal ModelValueProperty(ModelType declaringType, string name, string label, string helptext, string format, bool isStatic, Type propertyType, TypeConverter converter, bool isList = false, bool isReadOnly = false, bool isPersisted = true, Attribute[] attributes = null, LambdaExpression defaultValue = null)
     : base(declaringType, name, label, helptext, format, isStatic, isList, isReadOnly, isPersisted, attributes)
 {
     this.PropertyType = propertyType;
     this.Converter = converter;
     this.AutoConvert = converter != null && converter.CanConvertTo(typeof(object));
     this.FormatProvider = declaringType.GetFormatProvider(propertyType);
     if (defaultValue != null)
     {
         if (defaultValue.Parameters.Count > 0)
             throw new ArgumentException("Default value expressions cannot have parameters.");
         if (propertyType.IsAssignableFrom(defaultValue.Type))
             throw new ArgumentException("Default value expressions must match the type of the property they are for.");
         this.DefaultValue = defaultValue;
     }
 }
Exemplo n.º 24
0
 /// <summary>
 /// Instanciranje novog modela prema tipu modela.
 /// </summary>
 /// <param name="type"></param>
 /// <returns></returns>
 public static Model NewModelInstance(ModelType type)
 {
     if (type == ModelType.Users)
         return new UsersModel();
     else if (type == ModelType.ClassesInSchools)
         return new ClassesInSchoolsModel();
     else if (type == ModelType.Courses)
         return new CoursesModel();
     else if (type == ModelType.CourseRubrics)
         return new CourseRubricsModel();
     else if (type == ModelType.Grades)
         return new GradesModel();
     else if(type == ModelType.Classes)
         return new ClassesModel();
     return null;
 }
Exemplo n.º 25
0
        public JsonModel JsonToObject(string json, ModelType type)
        {
            switch (type)
            {
                case ModelType.Current:
                    return JsonConvert.DeserializeObject<CurrentJsonModel>(json);

                case ModelType.Forecast5Days:
                    return JsonConvert.DeserializeObject<Forecast5DaysJsonModel>(json);

                case ModelType.Forecast16Days:
                    return JsonConvert.DeserializeObject<Forecast16DaysJsonModel>(json);

                default:
                    return null;
            }
        }
Exemplo n.º 26
0
 /**
  * MakeHandRepresentation receives a Hand and combines that with an IHandModel to create a HandRepresentation
  * @param hand The Leap Hand data to be drive an IHandModel
  * @param modelType Filters for a type of hand model, for example, physics or graphics hands.
  */
 public override HandRepresentation MakeHandRepresentation(Hand hand, ModelType modelType)
 {
     Chirality handChirality = hand.IsRight ? Chirality.Right : Chirality.Left;
       HandRepresentation handRep = new HandProxy(this, hand, handChirality, modelType);
       for (int i = 0; i < ModelPool.Count; i++) {
     ModelGroup group = ModelPool[i];
     if (group.IsEnabled) {
       IHandModel model = group.TryGetModel(handChirality, modelType);
       if (model != null) {
     handRep.AddModel(model);
     modelToHandRepMapping.Add(model, handRep);
       }
     }
       }
       activeHandReps.Add(handRep);
       return handRep;
 }
Exemplo n.º 27
0
        internal static POSModel TrainPOSModel(ModelType type = ModelType.Maxent) {

            var p = new TrainingParameters();
            switch (type) {
                case ModelType.Maxent:
                    p.Set(Parameters.Algorithm, "MAXENT");
                    break;
                case ModelType.Perceptron:
                    p.Set(Parameters.Algorithm, "PERCEPTRON");
                    break;
                default:
                    throw new NotSupportedException();
            }

            p.Set(Parameters.Iterations, "100");
            p.Set(Parameters.Cutoff, "5");

            return POSTaggerME.Train("en", CreateSampleStream(), p, new POSTaggerFactory());
        }
Exemplo n.º 28
0
        /// <summary>
        /// Initializes a new instance of the 'ArgumentDVController' class.
        /// </summary>
        /// <param name="name">Name of the data-valued Argument.</param>
        /// <param name="alias">Alias of the data-valued Argument.</param>
        /// <param name="idXML">IdXML of the data-valued Argument.</param>
        /// <param name="modelType">ModelType of the data-valued Argument.</param>
        /// <param name="nullAllowed">Indicates whether the data-valued Argument allows null values.</param>
        /// <param name="options">List of options of the defined selection.</param>
        /// <param name="optionsDefaultValue">Default selected option for the defined seelction.</param>
        /// <param name="parent">Parent controller.</param>
        public ArgumentDVController(
			string name,
			string alias,
			string idXML,
			ModelType modelType,
			bool nullAllowed,
			List<KeyValuePair<object, string>> options,
			object optionsDefaultValue,
			IUController parent)
            : base(name, parent, alias, idXML, nullAllowed, false)
        {
            mModelType = modelType;
            mOptions = options;
            // Add the 'null' value to the options list.
            if (nullAllowed)
            {
                mOptions.Insert(0, new KeyValuePair<object, string>(null, string.Empty));
            }
            mOptionsDefaultValue = optionsDefaultValue;
        }
Exemplo n.º 29
0
        public void GivenTheCurrentSceneContainsAModelResourceListWithAMeshResourceNamed(ModelType type, string modelName)
        {
            IDTFScene currentScene = ScenarioContext.Current.Get<IDTFScene>();

            ModelResource m1 = null;

            switch (type)
            {
                case ModelType.MESH:
                    m1 = new ModelResource(ModelType.MESH);
                    break;
                case ModelType.LINE_SET:
                    m1 = new ModelResource(ModelType.LINE_SET);
                    break;
            }

            m1.Name = modelName;
            currentScene.ModelResources.Add(modelName, m1);
            ScenarioContext.Current.Set<ModelResource>(m1, modelName);
        }
Exemplo n.º 30
0
        public XmlModel XmlToObject(StreamReader str, ModelType type)
        {
            switch (type)
            {
                case ModelType.Current:
                    serializer = new XmlSerializer(typeof(CurrentXmlModel));
                    return (CurrentXmlModel)serializer.Deserialize(str);

                case ModelType.Forecast5Days:
                    serializer = new XmlSerializer(typeof(Forecast5DaysXmlModel));
                    return (Forecast5DaysXmlModel)serializer.Deserialize(str);

                case ModelType.Forecast16Days:
                    serializer = new XmlSerializer(typeof(Forecast16DaysXmlModel));
                    return (Forecast16DaysXmlModel)serializer.Deserialize(str);

                default:
                    return null;
            }
        }
Exemplo n.º 31
0
    private string processQueryString()
    {
        string retval = "";

        _sCaseName = "";
        if (Request.QueryString["CaseName"] != null)
        {
            _sCaseName = Request.QueryString["CaseName"];
        }
        if (_sCaseName == "")
        {
            retval = "ERROR: CaseName cannot be null\r\n";
        }

        Random   randomGen = new Random();
        DateTime dNow      = DateTime.Now;
        //string sNow = dNow.Year.ToString() + dNow.Month.ToString() + dNow.Day.ToString() + dNow.Hour.ToString() + dNow.Minute.ToString() + dNow.Second.ToString() + dNow.Millisecond.ToString();
        string sNow = dNow.Millisecond.ToString();

        _FileName = _sCaseName + "_" + sNow + "_" + randomGen.Next(10000, 99999);

        string sModelType = "";

        if (Request.QueryString["ModelType"] != null)
        {
            sModelType = Request.QueryString["ModelType"];
        }

        switch (sModelType.ToUpper())
        {
        case "OILSPILL":
            _eModelType = ModelType.OilModel;
            break;

        case "CHEMSPILL":
            _eModelType = ModelType.ChemModel;
            break;

        default:
            retval += "ERROR: Unrecognized Model Type: " + sModelType + "\r\n";
            break;
        }

        string[] sDateFormats = new string[] { "yyyyMMddTHH:mm:ss", "yyyyMMddTHH:mm",
                                               "MM/dd/yyyyTHH:mm:ss", "MM/dd/yyyyTHH:mm",
                                               "dd/MM/yyyyTHH:mm:ss", "dd/MM/yyyyTHH:mm" };

        if (Request.QueryString["StartDate"] != null)
        {
            if (!(DateTime.TryParseExact(Request.QueryString["StartDate"], sDateFormats, new CultureInfo("en-US"), System.Globalization.DateTimeStyles.None, out _StartDate)))
            {
                retval += "ERROR: StartDate is invalid: " + Request.QueryString["StartDate"] + "\r\n";
                retval += "Needs to be in one of the following formats:\r\n" + sDateFormats[0] + "r\n" +
                          sDateFormats[1] + "\r\n" +
                          sDateFormats[2] + "\r\n" +
                          sDateFormats[3] + "\r\n" +
                          sDateFormats[4] + "\r\n" +
                          sDateFormats[5] + "\r\n";
            }
        }
        else
        {
            retval += "ERROR: Start Date is missing.\r\n";
        }

        _SpillAmount = 0;
        if (Request.QueryString["Volume"] != null)
        {
            _SpillAmount = int.Parse(Request.QueryString["Volume"]);
        }

        _OilUnits = 4; //default to Tonnes
        if (Request.QueryString["OilUnits"] != null)
        {
            _OilUnits = int.Parse(Request.QueryString["OilUnits"]);
        }

        _Duration = 0;
        if (Request.QueryString["Duration"] != null)
        {
            _Duration = int.Parse(Request.QueryString["Duration"]);
        }

        _SimLength = 24; //default to one day
        if (Request.QueryString["SimLength"] != null)
        {
            _SimLength = int.Parse(Request.QueryString["SimLength"]);
        }

        _EndDate = _StartDate.AddHours(_SimLength);

        _sLocation = "";
        if (Request.QueryString["Location"] != null)
        {
            _sLocation = Request.QueryString["Location"];
        }

        double lat = 0;

        if (Request.QueryString["IncLat"] != null)
        {
            lat = Convert.ToDouble(Request.QueryString["IncLat"]);
        }

        double lon = 0;

        if (Request.QueryString["IncLon"] != null)
        {
            lon = Convert.ToDouble(Request.QueryString["IncLon"]);
        }
        _IncidentSite = new LatLon(lat, lon);

        _AOI = CalculateAOI(_IncidentSite, _Duration); // new BoundingBox(Request.QueryString["BBox"]);

        _Winds = -999;                                 //default to no winds
        if (Request.QueryString["Winds"] != null)
        {
            _Winds = int.Parse(Request.QueryString["Winds"]);
        }

        _Currents = -999; //default to no currents
        if (Request.QueryString["Currents"] != null)
        {
            _Currents = int.Parse(Request.QueryString["Currents"]);
        }

        _EcopWinds = "";
        if (Request.QueryString["EcopWinds"] != null)
        {
            _EcopWinds = Request.QueryString["EcopWinds"];
        }

        _EcopCurrents = "";
        if (Request.QueryString["EcopCurrents"] != null)
        {
            _EcopCurrents = Request.QueryString["EcopCurrents"];
        }

        _WindMag = 0;
        if (Request.QueryString["WindMag"] != null)
        {
            _WindMag = int.Parse(Request.QueryString["WindMag"]);
        }

        _WindDir = 0;
        if (Request.QueryString["WindDir"] != null)
        {
            string myDir = Request.QueryString["WindDir"];
            _WindDir = GetDirectionFromString(myDir) + 180; //to get into direction from
            if (_WindDir > 360)
            {
                _WindDir -= 360;
            }
        }

        _CurrMag = 0;
        if (Request.QueryString["CurrMag"] != null)
        {
            _CurrMag = int.Parse(Request.QueryString["CurrMag"]);
        }

        _groupIDShare = "62f6db44ba6d42a7b66334db5f0f0fe2";
        if (Request.QueryString["group"] != null)
        {
            _groupIDShare = Request.QueryString["group"];
        }

        _scriptID = "Model2Shape";
        if (Request.QueryString["scriptid"] != null)
        {
            _scriptID = Request.QueryString["scriptid"];
        }

        _ShareEveryone = "false";
        if (Request.QueryString["every1share"] != null)
        {
            _ShareEveryone = Request.QueryString["every1share"];
        }

        _CurrDir = 0;
        if (Request.QueryString["CurrDir"] != null)
        {
            string myDir = Request.QueryString["CurrDir"];
            _CurrDir = GetDirectionFromString(myDir);
        }

        _OilType = "Diesel"; //default to Diesel
        if (Request.QueryString["OilType"] != null)
        {
            _OilType = Request.QueryString["OilType"];
        }

        //_ChemType = "Benzene"; //default to benzene
        //if (Request.QueryString["ChemID"] != null)
        //    _ChemType = Request.QueryString["ChemID"];

        //_bIsRivers = false;
        //if (Request.QueryString["River"] != null)
        //    _bIsRivers = Convert.ToBoolean(Request.QueryString["River"]);

        _ModelMethod = true; //default to Fast method
        if (Request.QueryString["Speed"] != null)
        {
            _ModelMethod = (Request.QueryString["Speed"].ToUpper() == "FAST");
        }

        string sWaterTemp = "15C";

        if (Request.QueryString["WaterTemp"] != null)
        {
            sWaterTemp = Request.QueryString["WaterTemp"];
        }

        _WaterTemp = double.Parse(sWaterTemp.Substring(0, sWaterTemp.Length - 1));
        if (sWaterTemp.Substring(sWaterTemp.Length - 1, 1) == "F")
        {
            _WaterTemp = (_WaterTemp - 32) * (5 / 9);
        }

        _ClientKey = "";
        if (Request.QueryString["ClientKey"] != null)
        {
            _ClientKey = Request.QueryString["ClientKey"];
        }

        return(retval);
    }
Exemplo n.º 32
0
        public void GenerateSimpleType_Ambiguous_Issue()
        {
            // Umbraco returns nice, pascal-cased names.
            var type1 = new TypeModel
            {
                Id       = 1,
                Alias    = "type1",
                ClrName  = "Type1",
                ParentId = 0,
                BaseType = null,
                ItemType = TypeModel.ItemTypes.Content,
            };

            type1.Properties.Add(new PropertyModel
            {
                Alias        = "foo",
                ClrName      = "Foo",
                ModelClrType = typeof(IEnumerable <>).MakeGenericType(ModelType.For("foo")),
            });

            var type2 = new TypeModel
            {
                Id       = 2,
                Alias    = "foo",
                ClrName  = "Foo",
                ParentId = 0,
                BaseType = null,
                ItemType = TypeModel.ItemTypes.Element,
            };

            TypeModel[] types = new[] { type1, type2 };

            var modelsBuilderConfig = new ModelsBuilderSettings();
            var builder             = new TextBuilder(modelsBuilderConfig, types)
            {
                ModelsNamespace = "Umbraco.Cms.Web.Common.PublishedModels"
            };

            var sb1 = new StringBuilder();

            builder.Generate(sb1, builder.GetModelsToGenerate().Skip(1).First());
            var gen1 = sb1.ToString();

            Console.WriteLine(gen1);

            var sb = new StringBuilder();

            builder.Generate(sb, builder.GetModelsToGenerate().First());
            var gen = sb.ToString();

            SemVersion version  = ApiVersion.Current.Version;
            var        expected = @"//------------------------------------------------------------------------------
// <auto-generated>
//   This code was generated by a tool.
//
//    Umbraco.ModelsBuilder.Embedded v" + version + @"
//
//   Changes to this file will be lost if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

using System;
using System.Linq.Expressions;
using Umbraco.Cms.Core.Models.PublishedContent;
using Umbraco.Cms.Core.PublishedCache;
using Umbraco.Cms.Infrastructure.ModelsBuilder;
using Umbraco.Cms.Core;
using Umbraco.Extensions;

namespace Umbraco.Cms.Web.Common.PublishedModels
{
	[PublishedModel(""type1"")]
	public partial class Type1 : PublishedContentModel
	{
		// helpers
#pragma warning disable 0109 // new is redundant
		[global::System.CodeDom.Compiler.GeneratedCodeAttribute(""Umbraco.ModelsBuilder.Embedded"", """         + version + @""")]
		public new const string ModelTypeAlias = ""type1"";
		[global::System.CodeDom.Compiler.GeneratedCodeAttribute(""Umbraco.ModelsBuilder.Embedded"", """         + version + @""")]
		public new const PublishedItemType ModelItemType = PublishedItemType.Content;
		[global::System.CodeDom.Compiler.GeneratedCodeAttribute(""Umbraco.ModelsBuilder.Embedded"", """         + version + @""")]
		[return: global::System.Diagnostics.CodeAnalysis.MaybeNull]
		public new static IPublishedContentType GetModelContentType(IPublishedSnapshotAccessor publishedSnapshotAccessor)
			=> PublishedModelUtility.GetModelContentType(publishedSnapshotAccessor, ModelItemType, ModelTypeAlias);
		[global::System.CodeDom.Compiler.GeneratedCodeAttribute(""Umbraco.ModelsBuilder.Embedded"", """         + version + @""")]
		[return: global::System.Diagnostics.CodeAnalysis.MaybeNull]
		public static IPublishedPropertyType GetModelPropertyType<TValue>(IPublishedSnapshotAccessor publishedSnapshotAccessor, Expression<Func<Type1, TValue>> selector)
			=> PublishedModelUtility.GetModelPropertyType(GetModelContentType(publishedSnapshotAccessor), selector);
#pragma warning restore 0109

		private IPublishedValueFallback _publishedValueFallback;

		// ctor
		public Type1(IPublishedContent content, IPublishedValueFallback publishedValueFallback)
			: base(content, publishedValueFallback)
		{
			_publishedValueFallback = publishedValueFallback;
		}

		// properties

		[global::System.CodeDom.Compiler.GeneratedCodeAttribute(""Umbraco.ModelsBuilder.Embedded"", """         + version + @""")]
		[global::System.Diagnostics.CodeAnalysis.MaybeNull]
		[ImplementPropertyType(""foo"")]
		public virtual global::System.Collections.Generic.IEnumerable<global::"         + modelsBuilderConfig.ModelsNamespace + @".Foo> Foo => this.Value<global::System.Collections.Generic.IEnumerable<global::" + modelsBuilderConfig.ModelsNamespace + @".Foo>>(_publishedValueFallback, ""foo"");
	}
}
";

            Console.WriteLine(gen);
            Assert.AreEqual(expected.ClearLf(), gen);
        }
    //清除匹配的model列表
    public bool ClearAllMatchModels()
    {
        bool needFill = false;

        for (int y = 0; y < yRow; y++)
        {
            for (int x = 0; x < xCol; x++)
            {
                if (models[x, y].CanClear())
                {
                    List <ModelBase> matchList = MatchModels(models[x, y], x, y);
                    if (matchList != null)
                    {
                        int num = matchList.Count;
                        //根据消除个数处理分数
                        if (gameBegin)
                        {
                            switch (num)
                            {
                            case 3:
                                scoreStep = 20;
                                score    += scoreStep;
                                ScoreAddEffect(0);
                                break;

                            case 4:
                                Excellent(0);
                                scoreStep = 60;
                                score    += scoreStep;
                                ScoreAddEffect(1);
                                break;

                            case 5:
                                scoreStep = 80;
                                score    += scoreStep;
                                if (isSkill == false)
                                {
                                    gameTime     += 6f;
                                    curLevelTime += 6;
                                    Excellent(1);
                                    PlayerPrefs.SetInt("TimeAddNums", PlayerPrefs.GetInt("TimeAddNums", 0) + 6);    //记录累计加时
                                }
                                ScoreAddEffect(2);
                                break;

                            case 6:
                                matchSixTimes++;
                                scoreStep = 180;
                                score    += scoreStep;
                                if (isSkill == false)
                                {
                                    gameTime     += 10;
                                    curLevelTime += 10;
                                    Excellent(2);
                                    PlayerPrefs.SetInt("TimeAddNums", PlayerPrefs.GetInt("TimeAddNums", 0) + 10);    //记录累计加时
                                }
                                ScoreAddEffect(3);
                                break;

                            case 7:
                                scoreStep = 310;
                                score    += scoreStep;
                                if (isSkill == false)
                                {
                                    curLevelTime += 15;
                                    gameTime     += 15;
                                    Excellent(3);
                                    PlayerPrefs.SetInt("TimeAddNums", PlayerPrefs.GetInt("TimeAddNums", 0) + 15);    //记录累计加时
                                }
                                PlayerPrefs.SetInt("Diamand", PlayerPrefs.GetInt("Diamand", 0) + award);
                                diamandText.text = award + "";
                                ScoreAddEffect(4);
                                showTaskFinishedPanel = true;
                                break;
                            }
                            //生成奖励球
                            ModelType specialModelType = ModelType.Count;//是否产生特殊奖励
                            ModelBase model            = matchList[UnityEngine.Random.Range(0, matchList.Count)];
                            //ModelBase model = models[UnityEngine.Random.Range(0, xCol), UnityEngine.Random.Range(0, yRow)];
                            int specialModelX = model.X;
                            int specialModelY = model.Y;
                            if (matchList.Count == 5)
                            {
                                specialModelType = ModelType.CrossClear;
                            }
                            else if (matchList.Count >= 6 && !isSkill)
                            {
                                specialModelType = ModelType.RainBow;
                                Debug.Log("rainbow " + matchList.Count);
                            }

                            if (isSkill)
                            {
                                specialModelType = ModelType.Count;
                            }
                            matchList.Add(models[model.x, model.y]);
                            foreach (var m in matchList)
                            {
                                if (ClearModel(m.X, m.Y))
                                {
                                    needFill = true;
                                }
                            }
                            if (specialModelType != ModelType.Count)
                            {
                                isSkill = true;
                            }
                            if (specialModelType != ModelType.Count && gameBegin)
                            {
                                if (models[specialModelX, specialModelY].type == ModelType.Empty)
                                {
                                    Destroy(models[specialModelX, specialModelY]);
                                    ModelBase newModel = CreatNewModel(specialModelX, specialModelY, specialModelType);
                                    if (specialModelType == ModelType.CrossClear && newModel.CanColor() && matchList[0].CanColor())
                                    {
                                        newModel.ModelColorComponent.SetColor(ModelColor.ColorType.Cross);
                                    }
                                    //Rainbow
                                    else if (specialModelType == ModelType.RainBow && newModel.CanColor())
                                    {
                                        newModel.ModelColorComponent.SetColor(ModelColor.ColorType.Rainbow);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return(needFill);
    }
        /**
         * Updates HandRepresentations based in the specified HandRepresentation Dictionary.
         * Active HandRepresentation instances are updated if the hand they represent is still
         * present in the Provider's CurrentFrame; otherwise, the HandRepresentation is removed. If new
         * Leap Hand objects are present in the Leap HandRepresentation Dictionary, new HandRepresentations are
         * created and added to the dictionary.
         * @param all_hand_reps = A dictionary of Leap Hand ID's with a paired HandRepresentation
         * @param modelType Filters for a type of hand model, for example, physics or graphics hands.
         * @param frame The Leap Frame containing Leap Hand data for each currently tracked hand
         */
        void UpdateHandRepresentations(Dictionary <int, HandRepresentation> all_hand_reps, ModelType modelType, Frame frame)
        {
            foreach (Leap.Hand curHand in frame.Hands)
            {
                HandRepresentation rep;
                if (!all_hand_reps.TryGetValue(curHand.Id, out rep))
                {
                    rep = Factory.MakeHandRepresentation(curHand, modelType);
                    if (rep != null)
                    {
                        all_hand_reps.Add(curHand.Id, rep);
                    }
                }
                if (rep != null)
                {
                    rep.IsMarked = true;
                    rep.UpdateRepresentation(curHand, modelType);
                    rep.LastUpdatedTime = (int)frame.Timestamp;
                }
            }

            /** Mark-and-sweep to finish unused HandRepresentations */
            HandRepresentation toBeDeleted = null;

            foreach (KeyValuePair <int, HandRepresentation> r in all_hand_reps)
            {
                if (r.Value != null)
                {
                    if (r.Value.IsMarked)
                    {
                        r.Value.IsMarked = false;
                    }
                    else
                    {
                        /** Initialize toBeDeleted with a value to be deleted */
                        //Debug.Log("Finishing");
                        toBeDeleted = r.Value;
                    }
                }
            }

            /**Inform the representation that we will no longer be giving it any hand updates
             * because the corresponding hand has gone away */
            if (toBeDeleted != null)
            {
                all_hand_reps.Remove(toBeDeleted.HandID);
                toBeDeleted.Finish();
            }
        }
Exemplo n.º 35
0
 /// <summary>
 /// Creates a model data
 /// </summary>
 /// <param name="name">Name of model</param>
 /// <param name="modelName">Internal name of model</param>
 /// <param name="type">Type of model</param>
 public ModelData(string name, string modelName, ModelType type)
 {
     Name      = name;
     ModelName = modelName;
     Type      = type;
 }
 public asteroidInfo(ModelType modelname, CollisionSphere[] spheres)
 {
     this.model            = modelname;
     this.collisionSpheres = spheres;
 }
Exemplo n.º 37
0
        protected static List <IPrediction> DeserializePredictions(ModelType modelType,
                                                                   dynamic jsonObject)
        {
            var propertyValues = (JObject)jsonObject.data;

            var data = new List <IPrediction>();

            if (propertyValues.Count > 0)
            {
                string typeName = modelType.Prediction.Name;
                switch (typeName)
                {
                case "Color":
                {
                    foreach (dynamic color in jsonObject.data.colors)
                    {
                        data.Add(Color.Deserialize(color));
                    }
                    break;
                }

                case "Concept":
                {
                    foreach (dynamic concept in jsonObject.data.concepts)
                    {
                        data.Add(Concept.Deserialize(concept));
                    }
                    break;
                }

                case "Demographics":
                {
                    foreach (dynamic demographics in jsonObject.data.regions)
                    {
                        data.Add(Demographics.Deserialize(demographics));
                    }
                    break;
                }

                case "Embedding":
                {
                    foreach (dynamic embedding in jsonObject.data.embeddings)
                    {
                        data.Add(Embedding.Deserialize(embedding));
                    }
                    break;
                }

                case "FaceConcepts":
                {
                    foreach (dynamic faceConcepts in
                             jsonObject.data.regions)
                    {
                        data.Add(FaceConcepts.Deserialize(faceConcepts));
                    }
                    break;
                }

                case "FaceDetection":
                {
                    foreach (dynamic faceDetection in jsonObject.data.regions)
                    {
                        data.Add(FaceDetection.Deserialize(faceDetection));
                    }
                    break;
                }

                case "FaceEmbedding":
                {
                    foreach (dynamic faceEmbedding in jsonObject.data.regions)
                    {
                        data.Add(FaceEmbedding.Deserialize(faceEmbedding));
                    }
                    break;
                }

                case "Focus":
                {
                    foreach (dynamic focus in jsonObject.data.regions)
                    {
                        data.Add(Focus.Deserialize(focus,
                                                   (decimal)jsonObject.data.focus.value));
                    }
                    break;
                }

                case "Frame":
                {
                    foreach (dynamic frame in jsonObject.data.frames)
                    {
                        data.Add(Frame.Deserialize(frame));
                    }
                    break;
                }

                case "Logo":
                {
                    foreach (dynamic logo in jsonObject.data.regions)
                    {
                        data.Add(Logo.Deserialize(logo));
                    }
                    break;
                }

                default:
                {
                    throw new ClarifaiException(
                              string.Format("Unknown output type `{0}`", typeName));
                }
                }
            }
            return(data);
        }
 public ActionResult Dosomething(ModelType model)
 {
     //your code
     return(View());
 }
Exemplo n.º 39
0
        public void Compile(string fileNameBase, string fileNameDefinition, string fileNameOutput)
        {
            if (_OutputListener == null)
            {
                _OutputListener = new ConsoleOutputListener();
            }

            XmlSerializer serializer = new XmlSerializer(typeof(ModelType));
            StreamReader  streamBase = new StreamReader(fileNameBase);
            StreamReader  streamDef  = new StreamReader(fileNameDefinition);

            using (streamBase)
            {
                var        modelBM = (ModelType)serializer.Deserialize(streamBase);
                FMTreeNode root    = MAXTreeNodeUtils.ToTree(modelBM, treeNodes);
                baseName = root.baseModelObject.name;

                using (streamDef)
                {
                    ModelType modelCI   = (ModelType)serializer.Deserialize(streamDef);
                    var       objectsCI = new Dictionary <string, ObjectType>();
                    foreach (ObjectType maxObj in modelCI.objects)
                    {
                        objectsCI[maxObj.id] = maxObj;
                    }

                    /**
                     * Bind compiler instructions to the related base element nodes
                     * and add new nodes.
                     *
                     * TODO: Child nodes may come before (new) parent is added. Figure out how to fix this.
                     */
                    foreach (RelationshipType rel in modelCI.relationships)
                    {
                        /**
                         * Check if destination is inside Profile Definition.
                         * E.g. for internal relationships in Profile Definition or for new elements.
                         * Then create empty PLACEHOLDER, cleaned up afterwards.
                         */
                        if (!treeNodes.ContainsKey(rel.destId) && objectsCI.ContainsKey(rel.destId))
                        {
                            FMTreeNode placeholder = new FMTreeNode();
                            placeholder.baseModelObject = objectsCI[rel.destId];
                            placeholder.isNew           = true;
                            placeholder.isPlaceholder   = true;
                            treeNodes[rel.destId]       = placeholder;
                            if (DEBUG)
                            {
                                _OutputListener.writeOutput("[DEBUG] Created PLACEHOLDER for {0}", objectsCI[rel.destId].name);
                            }
                        }

                        /**
                         * Check if both source and destination objects are there, if not ignore this relationship.
                         */
                        if (treeNodes.ContainsKey(rel.destId) && objectsCI.ContainsKey(rel.sourceId))
                        {
                            FMTreeNode node = treeNodes[rel.destId];

                            /**
                             * Dependency with Generalization/Aggregation-stereotype is used as Work-around
                             * for Package Generalization/Aggregation (which is not possible / allowed in UML)
                             * e.g. used for new Functions
                             */
                            if (rel.type == RelationshipTypeEnum.Dependency)
                            {
                                if ("Generalization".Equals(rel.stereotype))
                                {
                                    rel.type = RelationshipTypeEnum.Generalization;
                                }
                                if ("Aggregation".Equals(rel.stereotype))
                                {
                                    rel.type = RelationshipTypeEnum.Aggregation;
                                }
                            }

                            /**
                             * Generalization relationship means this is a change to an existing base model element
                             */
                            if (rel.type == RelationshipTypeEnum.Generalization)
                            {
                                node.instructionObject = objectsCI[rel.sourceId];
                                node.includeInProfile  = true;
                            }

                            /**
                             * Aggregation relationship means this is a new child element
                             */
                            else if (rel.type == RelationshipTypeEnum.Aggregation)
                            {
                                if (treeNodes.ContainsKey(rel.sourceId) && treeNodes[rel.sourceId].isPlaceholder)
                                {
                                    FMTreeNode placeholder = treeNodes[rel.sourceId];
                                    placeholder.parent           = node;
                                    placeholder.isPlaceholder    = false;
                                    placeholder.includeInProfile = true;
                                    setCompilerInclusionReason(placeholder, "New from ProfileDefinition; via PLACEHOLDER");

                                    node.children.Add(placeholder);
                                    if (!node.includeInProfile)
                                    {
                                        node.includeInProfile = true;
                                        setCompilerInclusionReason(node, "Because of new child");
                                    }
                                }
                                else if (objectsCI[rel.sourceId].tag != null && objectsCI[rel.sourceId].tag.Any(t => TV_INCLUSIONREASON.Equals(t.name)))
                                {
                                    _OutputListener.writeOutput("[WARN] Already new {0}. Check Aggregation relationships!", objectsCI[rel.sourceId].name);
                                }
                                else
                                {
                                    // Create the new node
                                    FMTreeNode newNode = new FMTreeNode();
                                    newNode.baseModelObject          = objectsCI[rel.sourceId];
                                    newNode.baseModelObject.parentId = node.baseModelObject.id;
                                    newNode.parent           = node;
                                    newNode.isNew            = true;
                                    newNode.includeInProfile = true;
                                    setCompilerInclusionReason(newNode, "New from ProfileDefinition");

                                    node.children.Add(newNode);
                                    if (!node.includeInProfile)
                                    {
                                        node.includeInProfile = true;
                                        setCompilerInclusionReason(node, "Because of new child");
                                    }
                                    treeNodes[rel.sourceId] = newNode;
                                }
                            }

                            /**
                             * Other relationship types not supported
                             */
                            else
                            {
                                if (DEBUG)
                                {
                                    _OutputListener.writeOutput("[DEBUG] Ignored {0}", rel.type);
                                }
                            }
                        }
                        else
                        {
                            if (DEBUG)
                            {
                                /**
                                 * Check if destination is inside Profile Definition.
                                 * E.g. for internal relationships in Profile Definition or for new elements.
                                 */
                                if (objectsCI.ContainsKey(rel.destId))
                                {
                                    string srcName = rel.sourceId;
                                    if (objectsCI[rel.sourceId].name != null)
                                    {
                                        srcName = objectsCI[rel.sourceId].name.Split(new[] { ' ' })[0];
                                    }
                                    string dstName = rel.sourceId;
                                    if (objectsCI[rel.destId].name != null)
                                    {
                                        dstName = objectsCI[rel.destId].name.Split(new[] { ' ' })[0];
                                    }
                                    _OutputListener.writeOutput("[DEBUG] Ignored {0} from {1} to {2} inside ProfileDefinition", rel.type, srcName, dstName, parseIdForConsole(rel.sourceId));
                                }
                                else
                                {
                                    // E.g. for ExternalReferences
                                    _OutputListener.writeOutput("[DEBUG] Ignored {0} from {1} to id={2} outside BaseModel", rel.type, objectsCI[rel.sourceId].name, rel.destId, parseIdForConsole(rel.sourceId));
                                }
                            }
                        }
                    }

                    ObjectType profileDefinition = objectsCI.Values.Single(o => R2Const.ST_FM_PROFILEDEFINITION.Equals(o.stereotype));
                    string     rootid            = root.baseModelObject.id;
                    root.baseModelObject = new ObjectType()
                    {
                        id            = rootid,
                        name          = profileDefinition.name,
                        stereotype    = R2Const.ST_FM_PROFILE,
                        type          = ObjectTypeEnum.Package,
                        typeSpecified = true,
                        tag           = profileDefinition.tag
                    };
                }

                // Only follow ConsequenceLinks for ProfileType != Companion
                bool doFollowConsequenceLinks = true;
                if (root.baseModelObject.tag.Any(t => "Type".Equals(t.name)))
                {
                    TagType typeTag = FirstOrDefaultNonEmptyValue(root.baseModelObject.tag, "Type");
                    doFollowConsequenceLinks = !"Companion".Equals(typeTag.value);
                }

                // Exclude and exclude consequenceLinks when Criterion is Excluded
                exclude(root);

                // Now auto include parents and criterions and included consequenceLinks
                autoInclude(root, doFollowConsequenceLinks);

                // Compile aka execute compiler instructions
                executeInstructions(root, PRIORITY_ESSENTIALNOW);

                // Give profile elements new unique ids
                // Only what is still in the Tree!
                List <ObjectType>           objects     = root.ToObjectList();
                Dictionary <string, string> idOrg2idNew = new Dictionary <string, string>();
                foreach (ObjectType maxObj in objects)
                {
                    string idOrg = maxObj.id;
                    string idNew = Guid.NewGuid().ToString();
                    idOrg2idNew[idOrg] = idNew;
                    maxObj.id          = idNew;
                    // Also remove modified date
                    maxObj.modifiedSpecified = false;
                }

                // Set new (gu)id's in objects parentId
                foreach (ObjectType maxObj in objects)
                {
                    if (!string.IsNullOrEmpty(maxObj.parentId))
                    {
                        if (idOrg2idNew.ContainsKey(maxObj.parentId))
                        {
                            maxObj.parentId = idOrg2idNew[maxObj.parentId];
                        }
                        else
                        {
                            // object already has new id assigned, which is also not an integer!
                            _OutputListener.writeOutput("[WARN] Already has new id: {0}", maxObj.name.Split(new[] { ' ' })[0], -1);
                        }
                    }
                }

                // Set new (gu)id's for relationships
                List <RelationshipType> relationships = root.ToRelationshipList();
                foreach (RelationshipType maxRel in relationships)
                {
                    if (idOrg2idNew.ContainsKey(maxRel.sourceId))
                    {
                        maxRel.sourceId = idOrg2idNew[maxRel.sourceId];
                    }
                    if (idOrg2idNew.ContainsKey(maxRel.destId))
                    {
                        maxRel.destId = idOrg2idNew[maxRel.destId];
                    }
                }

                // Remove relationships to objects that are not included
                foreach (RelationshipType maxRel in relationships.ToArray())
                {
                    if (!objects.Any(t => t.id == maxRel.sourceId))
                    {
                        string sourceId = idOrg2idNew.Single(t => t.Value == maxRel.sourceId).Key;
                        string destName = objects.Single(t => t.id == maxRel.destId).name;
                        _OutputListener.writeOutput("[WARN] Relationship from not included object removed (sourceId={0} destId={1} stereotype={2} destName={3})", sourceId, maxRel.destId, maxRel.stereotype, destName);
                        relationships.Remove(maxRel);
                    }
                    if (!objects.Any(t => t.id == maxRel.destId))
                    {
                        string sourceId   = idOrg2idNew.Single(t => t.Value == maxRel.sourceId).Key;
                        string sourceName = objects.Single(t => t.id == maxRel.sourceId).name;
                        _OutputListener.writeOutput("[WARN] Relationship to not included object removed (sourceId={0} destId={1} stereotype={2} sourceName={3})", sourceId, maxRel.destId, maxRel.stereotype, sourceName);
                        relationships.Remove(maxRel);
                    }
                }
                // Convert back to MAX model
                ModelType model = new ModelType();
                model.exportDate    = Util.FormatLastModified(DateTime.Now);
                model.objects       = objects.ToArray();
                model.relationships = relationships.ToArray();

                // Save compiled profile as MAX XML
                XmlWriterSettings settings = new XmlWriterSettings();
                settings.Indent       = true;
                settings.NewLineChars = "\n";
                using (XmlWriter writer = XmlWriter.Create(fileNameOutput, settings))
                {
                    serializer.Serialize(writer, model);
                }
            }
        }
Exemplo n.º 40
0
        /// <summary>
        /// Generates code that implements standard features of a model, including
        /// equality checks, hash code generation, cloning methods, and a friendly ToString().
        /// </summary>
        /// <param name="modelType">The type of model.</param>
        /// <returns>
        /// Generated code that implements the standard features for the specified model type.
        /// </returns>
        public static string GenerateCodeForModelImplementation(
            this ModelType modelType)
        {
            new { modelType }.AsArg().Must().NotBeNull();

            var modelImplementationItems = new List <string>();

            if (modelType.RequiresEquality)
            {
                modelImplementationItems.Add(string.Empty);

                modelImplementationItems.Add(modelType.GenerateEqualityMethods());
            }

            if (modelType.RequiresComparability)
            {
                modelImplementationItems.Add(string.Empty);

                modelImplementationItems.Add(modelType.GenerateComparableMethods());
            }

            if (modelType.RequiresHashing)
            {
                var hashingMethods = modelType.GenerateHashingMethods();

                if (!string.IsNullOrWhiteSpace(hashingMethods))
                {
                    modelImplementationItems.Add(string.Empty);

                    modelImplementationItems.Add(hashingMethods);
                }
            }

            if (modelType.RequiresDeepCloning)
            {
                modelImplementationItems.Add(string.Empty);

                modelImplementationItems.Add(modelType.GenerateCloningMethods());
            }

            if (modelType.RequiresStringRepresentation)
            {
                var stringRepresentationMethods = modelType.GenerateStringRepresentationMethods();

                if (!string.IsNullOrWhiteSpace(stringRepresentationMethods))
                {
                    modelImplementationItems.Add(string.Empty);

                    modelImplementationItems.Add(stringRepresentationMethods);
                }
            }

            var modelImplementationCode = modelImplementationItems.Where(_ => _ != null).ToNewLineDelimited();

            var codeTemplate = typeof(ModelImplementationGeneration).GetCodeTemplate(CodeTemplateKind.Model, KeyMethodKinds.Both);

            var result = codeTemplate
                         .Replace(Tokens.UsingStatementsToken, modelType.GetUsingStatementsForModelObject())
                         .Replace(Tokens.CodeGenAssemblyNameToken, GenerationShared.GetCodeGenAssemblyName())
                         .Replace(Tokens.CodeGenAssemblyVersionToken, GenerationShared.GetCodeGenAssemblyVersion())
                         .Replace(Tokens.ModelTypeNamespaceToken, modelType.TypeNamespace)
                         .Replace(Tokens.ModelTypeNameInCodeToken, modelType.TypeNameInCodeString)
                         .Replace(Tokens.RequiredInterfacesToken, modelType.RequiredInterfaces.Select(_ => _.ToStringReadable()).ToDelimitedString(", "))
                         .Replace(Tokens.ModelImplementationToken, modelImplementationCode);

            return(result);
        }
Exemplo n.º 41
0
        public override int GetHashCode()
        {
            int hash = 1;

            if (ModelName.Length != 0)
            {
                hash ^= ModelName.GetHashCode();
            }
            if (ModelType.Length != 0)
            {
                hash ^= ModelType.GetHashCode();
            }
            if (InputBlob.Length != 0)
            {
                hash ^= InputBlob.GetHashCode();
            }
            if (OutputBlob.Length != 0)
            {
                hash ^= OutputBlob.GetHashCode();
            }
            if (WeightFile.Length != 0)
            {
                hash ^= WeightFile.GetHashCode();
            }
            if (ProtoFile.Length != 0)
            {
                hash ^= ProtoFile.GetHashCode();
            }
            if (ClassifyThreshold != 0F)
            {
                hash ^= ClassifyThreshold.GetHashCode();
            }
            if (ClassifyResizeWidth != 0)
            {
                hash ^= ClassifyResizeWidth.GetHashCode();
            }
            if (ClassifyResizeHeight != 0)
            {
                hash ^= ClassifyResizeHeight.GetHashCode();
            }
            if (Scale != 0F)
            {
                hash ^= Scale.GetHashCode();
            }
            if (MeanB != 0F)
            {
                hash ^= MeanB.GetHashCode();
            }
            if (MeanG != 0F)
            {
                hash ^= MeanG.GetHashCode();
            }
            if (MeanR != 0F)
            {
                hash ^= MeanR.GetHashCode();
            }
            if (IsBgr != false)
            {
                hash ^= IsBgr.GetHashCode();
            }
            return(hash);
        }
Exemplo n.º 42
0
        public static string GenerateCodeForTests(
            this ModelType modelType,
            GenerateFor kind)
        {
            var testImplementationItems = new List <string>();

            if (modelType.RequiresStringRepresentation)
            {
                var stringFieldsCode = modelType.GenerateStringRepresentationTestFields().ReplaceCodeAnalysisSuppressionTokensInTestCode();

                if (!string.IsNullOrWhiteSpace(stringFieldsCode))
                {
                    testImplementationItems.Add(string.Empty);

                    testImplementationItems.Add(stringFieldsCode);
                }
            }

            if (modelType.RequiresModel)
            {
                var constructorFieldsCode = modelType.GenerateConstructorTestFields().ReplaceCodeAnalysisSuppressionTokensInTestCode();

                if (constructorFieldsCode != null)
                {
                    testImplementationItems.Add(string.Empty);

                    testImplementationItems.Add(constructorFieldsCode);
                }
            }

            if (modelType.RequiresDeepCloning)
            {
                var deepCloneWithFieldsCode = modelType.GenerateDeepCloneWithTestFields().ReplaceCodeAnalysisSuppressionTokensInTestCode();

                if (!string.IsNullOrWhiteSpace(deepCloneWithFieldsCode))
                {
                    testImplementationItems.Add(string.Empty);

                    testImplementationItems.Add(deepCloneWithFieldsCode);
                }
            }

            if (modelType.RequiresEquality || modelType.RequiresHashing)
            {
                var equalityFieldsCode = modelType.GenerateEqualityTestFields().ReplaceCodeAnalysisSuppressionTokensInTestCode();

                if (equalityFieldsCode != null)
                {
                    testImplementationItems.Add(string.Empty);

                    testImplementationItems.Add(equalityFieldsCode);
                }
            }

            if (modelType.RequiresComparability)
            {
                var comparableTestFields = modelType.GenerateComparableTestFields().ReplaceCodeAnalysisSuppressionTokensInTestCode();

                testImplementationItems.Add(string.Empty);

                testImplementationItems.Add(comparableTestFields);
            }

            var structuralTestMethodsCode = modelType.GenerateStructuralTestMethods().ReplaceCodeAnalysisSuppressionTokensInTestCode();

            testImplementationItems.Add(string.Empty);

            testImplementationItems.Add(structuralTestMethodsCode);

            if (modelType.RequiresStringRepresentation)
            {
                var stringTestMethodsCode = modelType.GenerateStringRepresentationTestMethods().ReplaceCodeAnalysisSuppressionTokensInTestCode();

                if (!string.IsNullOrWhiteSpace(stringTestMethodsCode))
                {
                    testImplementationItems.Add(string.Empty);

                    testImplementationItems.Add(stringTestMethodsCode);
                }
            }

            if (modelType.RequiresModel)
            {
                var constructorTestMethodsCode = modelType.GenerateConstructorTestMethods().ReplaceCodeAnalysisSuppressionTokensInTestCode();

                if (constructorTestMethodsCode != null)
                {
                    testImplementationItems.Add(string.Empty);

                    testImplementationItems.Add(constructorTestMethodsCode);
                }
            }

            if (modelType.RequiresDeepCloning)
            {
                var cloningTestMethodsCode = modelType.GenerateCloningTestMethods().ReplaceCodeAnalysisSuppressionTokensInTestCode();

                testImplementationItems.Add(string.Empty);

                testImplementationItems.Add(cloningTestMethodsCode);
            }

            if (kind.HasFlag(GenerateFor.ModelImplementationTestsPartialClassWithSerialization) && modelType.RequiresModel)
            {
                var serializationTestMethodsCode = modelType.GenerateSerializationTestMethods().ReplaceCodeAnalysisSuppressionTokensInTestCode();

                testImplementationItems.Add(string.Empty);

                testImplementationItems.Add(serializationTestMethodsCode);
            }

            if (modelType.RequiresEquality)
            {
                var equalityTestMethodsCode = modelType.GenerateEqualityTestMethods().ReplaceCodeAnalysisSuppressionTokensInTestCode();

                testImplementationItems.Add(string.Empty);

                testImplementationItems.Add(equalityTestMethodsCode);
            }

            if (modelType.RequiresHashing)
            {
                var hashingTestMethodsCode = modelType.GenerateHashingTestMethods().ReplaceCodeAnalysisSuppressionTokensInTestCode();

                testImplementationItems.Add(string.Empty);

                testImplementationItems.Add(hashingTestMethodsCode);
            }

            if (modelType.RequiresComparability)
            {
                var comparabilityTestMethodsCode = modelType.GenerateComparabilityTestMethods().ReplaceCodeAnalysisSuppressionTokensInTestCode();

                testImplementationItems.Add(string.Empty);

                testImplementationItems.Add(comparabilityTestMethodsCode);
            }

            var testImplementationCode = testImplementationItems.Where(_ => _ != null).ToNewLineDelimited();

            var codeTemplate = typeof(ModelImplementationGeneration).GetCodeTemplate(CodeTemplateKind.Test, KeyMethodKinds.Both);

            var result = codeTemplate
                         .Replace(Tokens.UsingStatementsToken, modelType.GetUsingStatementsForTestClass(kind))
                         .Replace(Tokens.CodeGenAssemblyNameToken, GenerationShared.GetCodeGenAssemblyName())
                         .Replace(Tokens.CodeGenAssemblyVersionToken, GenerationShared.GetCodeGenAssemblyVersion())
                         .Replace(Tokens.ModelTypeNamespaceToken, modelType.TypeNamespace)
                         .Replace(Tokens.ModelTypeNameInCodeToken, modelType.TypeNameInCodeString)
                         .Replace(Tokens.ModelTypeNameInTestClassNameToken, modelType.TypeNameInTestClassNameString)
                         .Replace(Tokens.TestImplementationToken, testImplementationCode);

            return(result);
        }
Exemplo n.º 43
0
        /**
         * Updates HandRepresentations based in the specified HandRepresentation Dictionary.
         * Active HandRepresentation instances are updated if the hand they represent is still
         * present in the Provider's CurrentFrame; otherwise, the HandRepresentation is removed. If new
         * Leap Hand objects are present in the Leap HandRepresentation Dictionary, new HandRepresentations are
         * created and added to the dictionary.
         * @param all_hand_reps = A dictionary of Leap Hand ID's with a paired HandRepresentation
         * @param modelType Filters for a type of hand model, for example, physics or graphics hands.
         * @param frame The Leap Frame containing Leap Hand data for each currently tracked hand
         */
        protected virtual void UpdateHandRepresentations(Dictionary <int, HandRepresentation> all_hand_reps, ModelType modelType, Frame frame)
        {
            for (int i = 0; i < frame.Hands.Count; i++)
            {
                var curHand = frame.Hands[i];
                HandRepresentation rep;
                if (!all_hand_reps.TryGetValue(curHand.Id, out rep))
                {
                    rep = factory.MakeHandRepresentation(curHand, modelType);
                    if (rep != null)
                    {
                        all_hand_reps.Add(curHand.Id, rep);
                    }
                }
                if (rep != null)
                {
                    rep.IsMarked = true;
                    rep.UpdateRepresentation(curHand);
                    rep.LastUpdatedTime = (int)frame.Timestamp;
                }
            }

            /** Mark-and-sweep to finish unused HandRepresentations */
            HandRepresentation toBeDeleted = null;

            for (var it = all_hand_reps.GetEnumerator(); it.MoveNext();)
            {
                var r = it.Current;
                if (r.Value != null)
                {
                    if (r.Value.IsMarked)
                    {
                        r.Value.IsMarked = false;
                    }
                    else
                    {
                        /** Initialize toBeDeleted with a value to be deleted */
                        //Debug.Log("Finishing");
                        toBeDeleted = r.Value;
                    }
                }
            }

            /**Inform the representation that we will no longer be giving it any hand updates
             * because the corresponding hand has gone away */
            if (toBeDeleted != null)
            {
                all_hand_reps.Remove(toBeDeleted.HandID);
                toBeDeleted.Finish();
            }
        }
Exemplo n.º 44
0
        public static AbstractResearchDraw CreateResearchDraw(ResearchType researchType, ModelType modelType)
        {
            switch (researchType)
            {
            case ResearchType.Basic:
                return(new BasicResearchDraw(modelType));

            case ResearchType.Activation:
                return(new ActivationResearchDraw());

            case ResearchType.Evolution:
                return(new EvolutionResearchDraw());

            default:
                Debug.Assert(false);
                return(null);
            }
        }
 public ModelSaberOnlineUserControl(MainWindow mainWindow, ModelType modelType)
 {
     InitializeComponent();
     ViewModel   = new ModelSaberOnlineUserControlViewModel(mainWindow, this, modelType);
     DataContext = ViewModel;
 }
Exemplo n.º 46
0
 public RazorPageWithContextTemplateModel2(ModelType modelType, string dbContextFullTypeName)
     : base(modelType, dbContextFullTypeName)
 {
 }
Exemplo n.º 47
0
 public GenConverDtoTotEF(ModelType model, ColumnSetNode columnSetNode)
 {
     this.Model         = model;
     this.ColumnSetNode = columnSetNode;
 }
 public BussinessException(ModelType modelID, ushort innerExceptionID, string message = null)
     : base((byte)modelID, innerExceptionID, message)
 {
 }
Exemplo n.º 49
0
        /// <summary>
        /// Attempt to infer a query request from an instance object.
        /// </summary>
        /// <param name="instance"></param>
        /// <param name="type"></param>
        /// <param name="roots"></param>
        /// <param name="isList"></param>
        /// <returns></returns>
        internal static bool TryConvertQueryInstance(object instance, out ModelType type, out ModelInstance[] roots, out bool isList)
        {
            // Default the out parameters to null
            type   = null;
            roots  = null;
            isList = false;

            // Immediately return null if the query instance is null
            if (instance == null)
            {
                return(false);
            }

            // Get the current model context
            var context = ModelContext.Current;

            // Determine if the instance is a model instance
            type = context.GetModelType(instance);
            if (type != null)
            {
                roots = new ModelInstance[] { type.GetModelInstance(instance) };

                if (roots[0].Type.Properties.Any())
                {
                    roots[0].OnPropertyGet(roots[0].Type.Properties.First());
                }

                isList = false;
                return(true);
            }

            // Otherwise, determine if the instance is a list of model instances
            else if (instance is IEnumerable)
            {
                // Convert the list to an array of model instances
                roots =
                    (
                        from element in ((IEnumerable)instance).Cast <object>()
                        let elementType = context.GetModelType(element)
                                          where elementType != null
                                          select elementType.GetModelInstance(element)
                    ).ToArray();

                // Indicate that the instance represents a list
                isList = true;

                // If the array contains at least one model instance, determine the base model type
                if (roots.Length > 0)
                {
                    type = roots[0].Type;
                    foreach (var rootType in roots.Select(r => r.Type))
                    {
                        if (rootType.IsSubType(type))
                        {
                            type = rootType;
                        }
                        else if (type != rootType)
                        {
                            while (!(type.IsSubType(rootType)))
                            {
                                type = type.BaseType;
                            }
                        }
                    }
                    return(true);
                }

                // Otherwise, attempt to infer the model type from the type of the list
                else
                {
                    // First see if the type implements IEnumerable<T>
                    var listType = instance.GetType();
                    foreach (Type interfaceType in listType.GetInterfaces())
                    {
                        if (interfaceType.IsGenericType && interfaceType.GetGenericTypeDefinition() == typeof(ICollection <>))
                        {
                            type = context.GetModelType(interfaceType.GetGenericArguments()[0]);
                            if (type != null)
                            {
                                return(true);
                            }
                        }
                    }

                    // Then see if the type implements IList and has a strongly-typed Item property indexed by an integer value
                    if (typeof(IList).IsAssignableFrom(listType))
                    {
                        PropertyInfo itemProperty = listType.GetProperty("Item", new Type[] { typeof(int) });
                        if (itemProperty != null)
                        {
                            type = context.GetModelType(itemProperty.PropertyType);
                            if (type != null)
                            {
                                return(true);
                            }
                        }
                    }
                }
            }

            // Return false to indicate that the instance could not be coerced into a valid query definition
            return(false);
        }
Exemplo n.º 50
0
 public GenRepository(ModelType model)
 {
     this.Model = model;
 }
Exemplo n.º 51
0
 protected ProductBaseModel([NotNull] DeclarationSymbol symbol, ModelType modelType)
     : base(symbol, modelType)
 {
 }
        public void GenerateShipHulk(SpaceShip ship, ShipData shipData, ModelType mesh1, ModelType mesh2)
        {
            if (shipData.numChunks <= 0)
            {
                return;
            }

            //chunks are evenly distributed to the front and rear of the ship. The
            // front chunks are propelled forward, and rear chunks are propelled backward.

            for (int i = 0; i < shipData.numChunks; i++)
            {
                //first, find  a random spot to spawn the hulk within the ship bounding perimeter.
                Vector2 spawnPos = Vector2.Zero; //X = WIDTH, Y = LENGTH.
                spawnPos.X = MathHelper.Lerp(shipData.shipWidth / -2, shipData.shipWidth / 2,
                                             (float)FrameworkCore.r.NextDouble());
                spawnPos.Y = MathHelper.Lerp(0.1f, shipData.shipLength / 2,
                                             (float)FrameworkCore.r.NextDouble());

                if (i % 2 == 0)
                {
                    spawnPos.Y *= -1f;
                }

                Matrix  orientationMatrix = Matrix.CreateFromQuaternion(ship.Rotation);
                Vector3 spawnPosition     = ship.Position +
                                            orientationMatrix.Forward * spawnPos.Y +
                                            orientationMatrix.Right * spawnPos.X;


                //now, generate the direction the hulk will move.
                Vector3 moveDir = Vector3.Zero;
                if (spawnPos.Y > 0)
                {
                    //chunk spawned in front of ship. propel it forward.
                    moveDir = orientationMatrix.Forward;
                }
                else
                {
                    moveDir = orientationMatrix.Backward;
                }


                //add some random variance to the move direction.
                moveDir += orientationMatrix.Right * MathHelper.Lerp(-0.5f, 0.5f, (float)FrameworkCore.r.NextDouble());
                moveDir += orientationMatrix.Up * MathHelper.Lerp(-0.5f, 0.5f, (float)FrameworkCore.r.NextDouble());

                ModelType mesh = ModelType.debrisHulk1;

                if (i % 2 == 0)
                {
                    mesh = mesh1;
                }
                else
                {
                    mesh = mesh2;
                }

                //spawn the hulk.
                AddHulk(mesh, ship, spawnPosition, moveDir);

                for (int k = 0; k < 16; k++)
                {
                    Vector3 debrisMoveDir = moveDir;

                    debrisMoveDir += orientationMatrix.Right * MathHelper.Lerp(-0.5f, 0.5f, (float)FrameworkCore.r.NextDouble());
                    debrisMoveDir += orientationMatrix.Up * MathHelper.Lerp(-0.5f, 0.5f, (float)FrameworkCore.r.NextDouble());



                    FrameworkCore.debrisManager.AddDebris(getRandomDebris(),
                                                          spawnPosition, debrisMoveDir);
                }
            }
        }
Exemplo n.º 53
0
 public void OnTypeChange(int value)
 {
     type = (ModelType)(value + 1);
 }
Exemplo n.º 54
0
        private (PublishedContentType, PublishedContentType) CreateContentTypes()
        {
            Current.Reset();

            var logger   = Mock.Of <ILogger>();
            var profiler = Mock.Of <IProfiler>();
            var proflog  = new ProfilingLogger(logger, profiler);

            PropertyEditorCollection editors = null;
            var editor = new NestedContentPropertyEditor(logger, new Lazy <PropertyEditorCollection>(() => editors));

            editors = new PropertyEditorCollection(new DataEditorCollection(new DataEditor[] { editor }));

            var dataType1 = new DataType(editor)
            {
                Id            = 1,
                Configuration = new NestedContentConfiguration
                {
                    MinItems     = 1,
                    MaxItems     = 1,
                    ContentTypes = new[]
                    {
                        new NestedContentConfiguration.ContentType {
                            Alias = "contentN1"
                        }
                    }
                }
            };

            var dataType2 = new DataType(editor)
            {
                Id            = 2,
                Configuration = new NestedContentConfiguration
                {
                    MinItems     = 1,
                    MaxItems     = 99,
                    ContentTypes = new[]
                    {
                        new NestedContentConfiguration.ContentType {
                            Alias = "contentN1"
                        }
                    }
                }
            };

            var dataType3 = new DataType(new TextboxPropertyEditor(logger))
            {
                Id = 3
            };

            // mocked dataservice returns nested content preValues
            var dataTypeService = new TestObjects.TestDataTypeService(dataType1, dataType2, dataType3);

            var publishedModelFactory = new Mock <IPublishedModelFactory>();

            // mocked model factory returns model type
            var modelTypes = new Dictionary <string, Type>
            {
                { "contentN1", typeof(TestElementModel) }
            };

            publishedModelFactory
            .Setup(x => x.MapModelType(It.IsAny <Type>()))
            .Returns((Type type) => ModelType.Map(type, modelTypes));

            // mocked model factory creates models
            publishedModelFactory
            .Setup(x => x.CreateModel(It.IsAny <IPublishedElement>()))
            .Returns((IPublishedElement element) =>
            {
                if (element.ContentType.Alias.InvariantEquals("contentN1"))
                {
                    return(new TestElementModel(element));
                }
                return(element);
            });

            // mocked model factory creates model lists
            publishedModelFactory
            .Setup(x => x.CreateModelList(It.IsAny <string>()))
            .Returns((string alias) =>
            {
                return(alias == "contentN1"
                        ? (IList) new List <TestElementModel>()
                        : (IList) new List <IPublishedElement>());
            });

            var contentCache      = new Mock <IPublishedContentCache>();
            var publishedSnapshot = new Mock <IPublishedSnapshot>();

            // mocked published snapshot returns a content cache
            publishedSnapshot
            .Setup(x => x.Content)
            .Returns(contentCache.Object);

            var publishedSnapshotAccessor = new Mock <IPublishedSnapshotAccessor>();

            // mocked published snapshot accessor returns a facade
            publishedSnapshotAccessor
            .Setup(x => x.PublishedSnapshot)
            .Returns(publishedSnapshot.Object);

            var converters = new PropertyValueConverterCollection(new IPropertyValueConverter[]
            {
                new NestedContentSingleValueConverter(publishedSnapshotAccessor.Object, publishedModelFactory.Object, proflog),
                new NestedContentManyValueConverter(publishedSnapshotAccessor.Object, publishedModelFactory.Object, proflog),
            });

            var factory = new PublishedContentTypeFactory(publishedModelFactory.Object, converters, dataTypeService);

            var propertyType1  = factory.CreatePropertyType("property1", 1);
            var propertyType2  = factory.CreatePropertyType("property2", 2);
            var propertyTypeN1 = factory.CreatePropertyType("propertyN1", 3);

            var contentType1  = factory.CreateContentType(1, "content1", new[] { propertyType1 });
            var contentType2  = factory.CreateContentType(2, "content2", new[] { propertyType2 });
            var contentTypeN1 = factory.CreateContentType(2, "contentN1", new[] { propertyTypeN1 });

            // mocked content cache returns content types
            contentCache
            .Setup(x => x.GetContentType(It.IsAny <string>()))
            .Returns((string alias) =>
            {
                if (alias.InvariantEquals("contentN1"))
                {
                    return(contentTypeN1);
                }
                return(null);
            });

            return(contentType1, contentType2);
        }
Exemplo n.º 55
0
        // Constructors

        /// <summary>
        ///   Initializes new instance of this type.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <param name="path">The path.</param>
        public HintTarget(ModelType model, string path)
        {
            this.model = model;
            this.path  = path;
        }
Exemplo n.º 56
0
 /// <summary>
 /// Creates a new instance of ArgumentInfo. Type is indicated as ModelType. Value is not set.
 /// </summary>
 /// <param name="name">Name of the argument.</param>
 /// <param name="type">Type of the argument.</param>
 public ArgumentInfo(string name, ModelType type, string className)
     : this(name, type, null, className)
 {
 }
Exemplo n.º 57
0
 public InvalidPropertyException(ModelType type, string name)
     : base("Invalid property: " + type.Name + "." + name)
 {
 }
Exemplo n.º 58
0
    void Awake()
    {
        MasterClientManager = FindObjectOfType <MasterClientManager>();

        //Force SpawnCollection Awake() method for initialization
        SpawnCollection spawnCollection = FindObjectOfType <SpawnCollection>();

        spawnCollection.gameObject.SetActive(false);
        spawnCollection.gameObject.SetActive(true);

        //Force SkillCollection Awake() method for initialization
        SkillCollection skillList = FindObjectOfType <SkillCollection>();

        skillList.gameObject.SetActive(false);
        skillList.gameObject.SetActive(true);

        AuthoryClient = new AuthoryClient(MasterClientManager.GetMapServerAuthString());
        AuthoryClient.Connect(MasterClientManager.MapServerIP, MasterClientManager.MapServerPort, MasterClientManager.MapServerUID);

        NetIncomingMessage msgIn;
        bool     playerInfoArrived = false;
        DateTime start             = DateTime.Now.AddSeconds(5);

        while (playerInfoArrived != true)
        {
            if (start < DateTime.Now)
            {
                return;
            }
            else
            {
                while ((msgIn = AuthoryClient.Client.ReadMessage()) != null)
                {
                    if (msgIn.MessageType == NetIncomingMessageType.Data)
                    {
                        if (((MessageType)msgIn.ReadByte()) == MessageType.PlayerID)
                        {
                            ushort Id   = msgIn.ReadUInt16();
                            string Name = msgIn.ReadString();

                            int maxHealth = msgIn.ReadInt32();
                            int health    = msgIn.ReadInt32();

                            int maxMana = msgIn.ReadInt32();

                            int mana = msgIn.ReadInt32();

                            byte      level     = msgIn.ReadByte();
                            ModelType modelType = (ModelType)msgIn.ReadByte();


                            float x             = msgIn.ReadFloat();
                            float z             = msgIn.ReadFloat();
                            float movementSpeed = msgIn.ReadFloat();

                            ushort END = msgIn.ReadUInt16();
                            ushort STR = msgIn.ReadUInt16();
                            ushort AGI = msgIn.ReadUInt16();
                            ushort INT = msgIn.ReadUInt16();
                            ushort KNW = msgIn.ReadUInt16();
                            ushort LCK = msgIn.ReadUInt16();

                            long experience    = msgIn.ReadInt64();
                            long maxExperience = msgIn.ReadInt64();

                            AuthoryClient.Handler.SetMapSize(msgIn.ReadInt32());

                            GameObject entity = AuthoryClient.Handler.GetEntityObjectByModelType(modelType).gameObject;

                            GameObject.Destroy(entity.GetComponent <Entity>());

                            PlayerEntity playerEntity = entity.AddComponent <PlayerEntity>();
                            entity.AddComponent <PlayerMove>();

                            Camera.main.GetComponent <CameraOrbit>().Target = playerEntity.transform;

                            AuthoryData.Instance.SetPlayer(playerEntity, Id, Name);

                            playerEntity.transform.position = new Vector3(x, 0, z);

                            playerEntity.SetMaxHealth(maxHealth);
                            playerEntity.SetHealth((ushort)health);

                            playerEntity.SetMaxMana(maxMana);
                            playerEntity.SetMana((ushort)mana);

                            playerEntity.Level = level;

                            playerEntity.MovementSpeed = movementSpeed;

                            playerEntity.Attributes.Endurance    = END;
                            playerEntity.Attributes.Strength     = STR;
                            playerEntity.Attributes.Agility      = AGI;
                            playerEntity.Attributes.Intelligence = INT;
                            playerEntity.Attributes.Knowledge    = KNW;
                            playerEntity.Attributes.Luck         = LCK;

                            AuthoryClient.UIController.Player = playerEntity;
                            AuthoryClient.UIController.UpdateMaxExperience(maxExperience, experience);

                            playerInfoArrived = true;
                            break;
                        }
                    }
                }
            }
        }
        AuthorySender.Movement();
    }
Exemplo n.º 59
0
        public static GameObject MountModel(string _id, Transform _parent, MaterialPair _materialPair, ModelType _type = ModelType.AnturaForniture)
        {
            CleanTranformChildren(_parent);
            GameObject returnObject = MountModel(_id, _parent, _type);
            Reward     actualReward = RewardSystemManager.GetRewardById(_id);

            SwitchMaterial(returnObject, _materialPair);
            return(returnObject);
        }
Exemplo n.º 60
0
 /// <summary>
 /// Initializes a new instance of the <see cref="NodeRepository" /> class.
 /// </summary>
 /// <param name="typeOfModel">The type of model for which to store nodes</param>
 public NodeRepository(ModelType typeOfModel)
 {
     this.ModelType = typeOfModel;
 }