Beispiel #1
0
        private void CheckServerStatus()
        {
            if (_activeClients?.Exists(user => user.OnScene) == true)
            {
                var sceneUser = _activeClients.Find(user => user.OnScene);

                DrawBox(new Rect(0, 0, Screen.width - 40, 3),
                        sceneUser.Id == SystemInfo.deviceUniqueIdentifier ? Color.yellow : Color.red);
            }
            else
            {
                DrawBox(new Rect(0, 0, Screen.width - 40, 3), Color.green);
            }


            switch (_socket?.State)
            {
            case WebSocketState.Open:
                DrawBox(new Rect(Screen.width - 38, 0, 38, 3), Color.green);
                break;

            case WebSocketState.Closed:
            case WebSocketState.Closing:
                DrawBox(new Rect(Screen.width - 38, 0, 38, 3),
                        DateTime.Now.Second % 2 == 0 ? Color.yellow : Color.red);
                break;

            default:
                DrawBox(new Rect(Screen.width - 38, 0, 38, 3), Color.yellow);
                break;
            }
        }
        private static long TwentyOne()
        {
            const int LIMIT = 10000;
            
            long a;
            long b;

            List<long> divisors;
            List<long> amicable = new List<long>();

            long sum;

            for (a = 1; a < LIMIT; a++)
            {
                divisors = Utils.GetFactors(a);
                sum = divisors.Sum();
                b = sum -= a;
                if ((Utils.GetFactors(b).Sum() - b) == a)
                {
                    if (a != b)
                    {
                        if (false == amicable.Exists(x => x == a) && false == amicable.Exists(x => x == b))
                        {
                            amicable.Add(a);
                            amicable.Add(b);
                        }
                    }
                }
            }

            return amicable.Sum();
        }
Beispiel #3
0
    private Solution Constants(Statement st) {
      IVariable lv = null;
      List<Expression> callArgs;
      var result = new List<Expression>();
      InitArgs(st, out lv, out callArgs);
      Contract.Assert(lv != null, Error.MkErr(st, 8));
      Contract.Assert(callArgs.Count == 1, Error.MkErr(st, 0, 1, callArgs.Count));

      foreach(var arg1 in ResolveExpression(callArgs[0])) {
        var expression = arg1 as Expression;
        Contract.Assert(expression != null, Error.MkErr(st, 1, "Term"));
        var expt = ExpressionTree.ExpressionToTree(expression);
        var leafs = expt.GetLeafData();
        foreach(var leaf in leafs) {
          if(leaf is LiteralExpr) {
            if(!result.Exists(j => (j as LiteralExpr)?.Value == (leaf as LiteralExpr)?.Value)) {
              result.Add(leaf);
            }
          } else if(leaf is ExprDotName) {
            var edn = leaf as ExprDotName;
            if (!result.Exists(j => SingletonEquality(j, edn))) {
              result.Add(leaf);
            }
          }
        }

      }

      return AddNewLocal(lv, result);
    }
Beispiel #4
0
    public static void Main (string[] args) {
        var l = new List<string> {
            "A", "A", "B", "C", "D"
        };

        Console.WriteLine(l.Exists((s) => s == "A") ? "1" : "0");
        Console.WriteLine(l.Exists((s) => s == "Q") ? "1" : "0");
    }
        /// <summary>
        /// Creates a post request based on the provided parameters
        /// </summary>
        /// <param name="requestParameters">List of IRequestParameters thtat will be used for request creation </param>
        /// <param name="request">An instance of PostRequest can be provided to be populated with data. Returned result will be the same instance but updated with params data.</param>
        /// <returns>An instance of PostRequest</returns>
        public static PostRequest CreateRequest(List<IRequestParameter> requestParameters, PostRequest request = null)
        {
            if (requestParameters == null || requestParameters.Count == 0)
            {
                throw new ArgumentException("You need to specify at least one parameter, otherwise it is not possible to create a post request.");
            }

            if (requestParameters.Exists(p => p.ParameterType == RequestParameterType.Basic)
               && requestParameters.Exists(p => p.ParameterType != RequestParameterType.Basic))
            {
                throw new ApplicationException("You cannot have, for the same request, a mix from basic parameters and other types. Basic parameters should not be used in combination with other types of parameters.");
            }

            if (request == null)
            {
                request = new PostRequest();
            }

            InitContentTypeHeader(request, requestParameters[0]);

            foreach (var param in requestParameters)
            {
                if (param == null)
                {
                    continue;
                }

                switch (param.ParameterType)
                {
                    case RequestParameterType.Basic:
                        AddBasicParameterToBodyContent(request, (BasicRequestParameter) param);
                        break;

                    case RequestParameterType.Text:
                        AddTextParameterToBodyContent(request, (TextRequestParameter)param);
                        break;

                    case RequestParameterType.Binary:
                        AddBinaryParameterToBodyContent(request, (BinaryRequestParameter)param);
                        break;

                    default:
                        throw new ApplicationException(string.Format("{0} is an unknown type of RequestParameter.", param.GetType().Name));
                }
            }

            //Add end boundary delimiter to the end of the request for the multipart request
            if (requestParameters[0].ParameterType != RequestParameterType.Basic)
            {
                request.BodyBuilder.Append(string.Format(EndBoundaryTemplate, request.BoundaryValue));
            }

            return request;
        }
        public static void UpdatePerahpsReferenceObjectList(MonoBehaviour component, List<PerhapsReferenceObject> list)
        {
            // analytics  source code.
            var monoScript = MonoScript.FromMonoBehaviour(component);
            var uniqueClassList = SceneObjectUtility.SceneUniqueComponentName();

            foreach (var text in monoScript.text.Split(';')) {

                foreach( var methodPattern in getComponentFunctionPattern)
                {

                    Match m = Regex.Match (text, methodPattern);

                    if (m.Success) {
                        var className = m.Groups ["call"].ToString ();

                        if(! list.Exists (item =>  item.compType == component.GetType() && item.referenceMonobehaviourName == className) )
                        {
                            var method = new PerhapsReferenceObject ()
                            {
                                compType = component.GetType(),
                                referenceMonobehaviourName = className,
                                monoscript = monoScript,
                            };
                            list.Add (method);

                            uniqueClassList.RemoveAll( item => item.Name == className );
                        }
                    }
                }

                foreach( var className in uniqueClassList)
                {
                    if( component.GetType() == className )
                        continue;
                    var result = text.IndexOf(className.Name ) ;
                    if(result != -1 && result != 0 )
                    {
                        if(! list.Exists (item =>  item.compType == component.GetType() && item.referenceMonobehaviourName == className.Name) )
                        {
                            var method = new PerhapsReferenceObject ()
                            {
                                compType = component.GetType(),
                                referenceMonobehaviourName = className.Name,
                                monoscript = monoScript,
                            };
                            list.Add (method);
                            continue;
                        }
                    }
                }
            }
        }
 private void addSubscriberType(List<Type> existingSubscriberTypes, Type subscriberType)
 {
     if (!existingSubscriberTypes.Exists(existingSubscriberType => existingSubscriberType == subscriberType))
     {
         var list = existingSubscriberTypes.FindAll(subscriberType.IsAssignableFrom);
         list.ForEach(subSubscriberType => existingSubscriberTypes.Remove(subSubscriberType));
         if (
             !existingSubscriberTypes.Exists(
                 existingSubscriberType => existingSubscriberType.IsAssignableFrom(subscriberType)))
         {
             existingSubscriberTypes.Add(subscriberType);
         }
     }
 }
Beispiel #8
0
        public ClaimsIdentity BuildClaimsIdentityForUser(string UserName )
        {
            var identity = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, UserName) },
                    DefaultAuthenticationTypes.ApplicationCookie,
                    ClaimTypes.Name,
                    ClaimTypes.Role);

            var claims = new List<Claim>();

            // Build claims for Pool Users and Admins
            var adminCount = 0;
            var userCount = 0;
            var group = String.Empty;
            foreach (Pool p in this.Pools)
            {
                group = p.ActiveDirectoryAdminGroup;
                if (group != null &&
                    !claims.Exists(c => c.Value.Equals(group, StringComparison.InvariantCultureIgnoreCase)) &&
                    this.Auth.UserIsInGroup(UserName, group))
                {

                    claims.Add(new Claim(ClaimTypes.Role, group));
                    adminCount++;
                }

                group = p.ActiveDirectoryUserGroup;
                if (group != null &&
                    !claims.Exists(c => c.Value.Equals(group, StringComparison.InvariantCultureIgnoreCase)) &&
                    this.Auth.UserIsInGroup(UserName, group))
                {
                    claims.Add(new Claim(ClaimTypes.Role, group));
                    userCount++;
                }

            }
            if (adminCount> 0) { claims.Add(new Claim(ClaimTypes.UserData, APPLICATION_POOL_ADMINISTRATOR)); }
            if (userCount> 0) { claims.Add(new Claim(ClaimTypes.UserData, APPLICATION_POOL_USER)); }

            // Last Check: Is the User An Administrator of the Application?
            if (Auth.UserIsInGroup(UserName, this.AdminGroup))
            {
                claims.Add(new Claim(ClaimTypes.Role, this.AdminGroup));
                claims.Add(new Claim(ClaimTypes.UserData, APPLICATION_ADMINISTRATOR));
            }

            identity.AddClaims(claims);

            return identity;
        }
        public void ShowWD_SucCot(Object sender, EventArgs e)
        {
            dtSucIniCot.Text = "";
            dtSucFinCot.Text = "";

            if (Session["Permisos"] != null)
            {
                List<int> Permisos = new List<int>((int[])Session["Permisos"]);
                bool find;
                find = Permisos.Exists(delegate(int i) { return i == 11; });//i = ID Permiso a buscar
                if (find == false)
                {
                    X.Msg.Confirm("Sin acceso!!!", "No tiene los permisos suficientes para consultar este reporte, verifique con el administrador.",
                    new MessageBoxButtonsConfig
                    {
                        Yes = new MessageBoxButtonConfig
                        {
                            Handler = "Prybe.Yes()",
                            Text = "Aceptar"
                        }
                    }).Show();
                } // Si no tiene el permiso manda niega acceso
                else
                {
                    wdFechaSucCot.Show();
                }
            }
            else
            {
                Response.Redirect("/Login/Login.aspx");//Si Session["Permisos"] es null manda a loguin para cargar permisos
            }



        }
Beispiel #10
0
 public async Task GetUserClaimTest()
 {
     var db = UnitTestHelper.CreateDefaultDb();
     var manager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(db));
     var user = new IdentityUser("u1");
     var result = await manager.CreateAsync(user);
     UnitTestHelper.IsSuccess(result);
     Assert.NotNull(user);
     var claims = new[]
     {
         new Claim("c1", "v1"),
         new Claim("c2", "v2"),
         new Claim("c3", "v3")
     };
     foreach (Claim c in claims)
     {
         UnitTestHelper.IsSuccess(await manager.AddClaimAsync(user.Id, c));
     }
     var userClaims = new List<Claim>(await manager.GetClaimsAsync(user.Id));
     Assert.Equal(3, userClaims.Count);
     foreach (Claim c in claims)
     {
         Assert.True(userClaims.Exists(u => u.Type == c.Type && u.Value == c.Value));
     }
 }
Beispiel #11
0
 internal static string ParseCPUTreeUsageInfo(List<string> processStrings, List<string> errorStrings)
 {
     if (processStrings.Count == 1) return processStrings[0];
     if (errorStrings.Count > 0 && errorStrings.Exists(s => s.Contains("NoSuchProcess"))) throw new InvalidOperationException("Process could not be found. Output from CPU sampler is:"+string.Join(",", processStrings.ToArray()));
     throw new ApplicationException(
         string.Format("Could not process cpu snapshot output. StdOutput: {0}, ErrOutput: {1}", string.Join(",", processStrings.ToArray()), string.Join(",", errorStrings.ToArray())));
 }
Beispiel #12
0
        private bool CheckKey(string key)
        {
            List<string> list = new List<string>();
            list.Add("ZhuiMeng");

            return list.Exists(p => p == key);
        }
Beispiel #13
0
 //ランダムで生成位置を作る
 public Transform[] GetRandomSpownPosition(int count)
 {
     int max = StageSpawnPosition.Count;
     
     if( max < count)
     {
         return null;
     }
     
     List<int> _createdId = new List<int>();
     Transform[] createPosition = new Transform[count];
     for(int i = 0 ; i < count; ++i)
     {
         while(true)
         {
             int RandomId = Random.Range( 0, max);
             if( _createdId.Exists( x => x == RandomId) )
                 continue;
                 _createdId.Add( RandomId);
             createPosition[i] = StageSpawnPosition[RandomId];
             break;
         }   
     }
     
     return createPosition;
 }
		public override List<IMethod> GetMethods()
		{
			List<IMethod> l = new List<IMethod>();
			using (var busyLock = busyManager.Enter(this)) {
				if (busyLock.Success) {
					l.AddRange(c.Methods);
					if (c.AddDefaultConstructorIfRequired && !c.IsStatic) {
						// A constructor is added for classes that do not have a default constructor;
						// and for all structs.
						if (c.ClassType == ClassType.Class && !l.Exists(m => m.IsConstructor)) {
							l.Add(Constructor.CreateDefault(c));
						} else if (c.ClassType == ClassType.Struct || c.ClassType == ClassType.Enum) {
							l.Add(Constructor.CreateDefault(c));
						}
					}
					
					if (c.ClassType == ClassType.Interface) {
						if (c.BaseTypes.Count == 0) {
							AddMethodsFromBaseType(l, c.ProjectContent.SystemTypes.Object);
						} else {
							foreach (IReturnType baseType in c.BaseTypes) {
								AddMethodsFromBaseType(l, baseType);
							}
						}
					} else {
						AddMethodsFromBaseType(l, c.BaseType);
					}
				}
			}
			return l;
		}
Beispiel #15
0
	public static void AddButton(ComboBox box, string text)
	{
		//Debug.Log("Adding button...");
		GameObject panel = box.transform.FindChild("Panel").gameObject;
		List<GameObject> children = new List<GameObject>(box.transform.FindChild("Panel").childCount);
		for (int i = 0; i < box.transform.FindChild("Panel").childCount; i++)
			children.Add(panel.transform.GetChild(i).gameObject);
		if (children.Exists(child => child.transform.FindChild("Text").GetComponent<Text>().text == text)) return;
		GameObject newButton = GameObject.Instantiate(box.transform.FindChild("ComboButton").gameObject) as GameObject;
		GameObject parent = box.transform.parent.gameObject;
		float canvasScaleFactor = box.RootCanvas.GetComponent<Canvas>().scaleFactor;
		newButton.transform.SetParent(box.gameObject.transform.FindChild("Panel"));	
		newButton.GetComponent<Button>().onClick.RemoveAllListeners();
		newButton.GetComponent<Button>().onClick.AddListener(() => box.comboButtonPressed(newButton));
		newButton.transform.FindChild("Text").GetComponent<Text>().text = text;
		RectTransform buttonTransform = newButton.GetComponent<RectTransform>();
		RectTransform panelTransform = box.gameObject.transform.FindChild("Panel").gameObject.GetComponent<RectTransform>();
		Rect buttonRect = buttonTransform.rect;
		Rect panelRect = panelTransform.rect;
		//float distance = box.ButtonDistance / canvasScaleFactor;
		//Debug.Log(distance);
		float offset = buttonRect.height * (box.buttons.Count); //+ distance;
		Vector2 panelPos = panelTransform.anchoredPosition;
		//Debug.Log(panelPos);
		Vector2 buttonPos = new Vector2(panelTransform.anchoredPosition.x, panelTransform.anchoredPosition.y - offset);
		//Debug.Log (buttonPos);
		buttonTransform.anchoredPosition = buttonPos;
		float newHeigth = buttonRect.height * (box.buttons.Count + 1.0f);// + distance;
		panelTransform.sizeDelta = new Vector2(panelRect.width, newHeigth);
		newButton.transform.localScale = newButton.transform.localScale * canvasScaleFactor;
		box.buttons.Add(newButton);
		if (box.buttons.Count == 1)
			box.transform.FindChild("ComboButton").FindChild("Text").gameObject.GetComponent<Text>().text = text;
	}
Beispiel #16
0
        public void Add( List<Namespace> namespaces, IDocumentationMember association )
        {
            try
            {
                if( association.TargetType.Namespace != null )
                {
                    //throw new NullReferenceException(
                    //    string.Format("There was no namespace found for {0}",
                    //                  association.TargetType.AssemblyQualifiedName));

                    var ns = Identifier.FromNamespace( association.TargetType.Namespace );

                    if( !namespaces.Exists( x => x.IsIdentifiedBy( ns ) ) )
                    {
                        var doc = Namespace.Unresolved( ns );
                        matchedAssociations.Add( association.Name.CloneAsNamespace(), doc );
                        namespaces.Add( doc );
                    }
                }

            }
            catch( Exception )
            {
            }
        }
Beispiel #17
0
        public static List<XmlSchemaElement> extractElements(XmlSchema schema)
        {
            List<XmlSchemaElement> elements = new List<XmlSchemaElement>();
            foreach (object item in schema.Elements)
            {
                if (item is DictionaryEntry)
                {
                    DictionaryEntry entry = (DictionaryEntry)item;
                    XmlSchemaElement element = entry.Value as XmlSchemaElement;
                    if (element != null)
                    {
                        elements.Add(element);
                    }
                }
            }
            foreach (object item in schema.Items)
            {
                if (item is XmlSchemaElement)
                {
                    XmlSchemaElement element = item as XmlSchemaElement;
                    if( !elements.Exists(el => el == element ))
                        elements.Add(element);
                }
            }

            return elements;
        }
 private bool DoAuthorized(List<UserRole> userRoles, string controllerName, string actionName)
 {
     if (userRoles == null || userRoles.Count == 0)
         return false;
     if (userRoles.Exists(ur => ur.Role.RoleName == "superAdmin"))
         return true;
     var controllerAction = CaService.GetControllerActionByName(controllerName, actionName);
     if (controllerAction == null)
         return false;
     //            var rolePermission = userRoles.SelectMany(c => c.Role.RolePermissions).Select(c=>new{c.ControllerAction.Id,c.IsAllowed}).ToList();
     //            rolePermission = rolePermission.Where(p=>p.Id == controllerAction.Id).ToList();
     //            if (rolePermission.Exists(p=> p.IsAllowed))
     //                return true;
     var isAllowed = false;
     foreach (var role in userRoles)
     {
         if (role.Role.RolePermissions.Any(permission => permission.IsAllowed && permission.ControllerAction.Id == controllerAction.Id))
         {
             isAllowed = true;
         }
         if (isAllowed)
             break;
     }
     return isAllowed;
 }
        //Return value indicates whether any attendances were added
        public bool GenerateAttendancesIfNeeded(DateTime startDate, DateTime finishDate,
            List<Student> students, List<Attendance> existingAttendances)
        {
            var currentDate = startDate;
            var attendancesAdded = false;

            while (currentDate <= finishDate)
            {
                foreach (var student in students)
                {
                    if (!(existingAttendances.Exists(x => x.StudentID == student.StudentID
                        && x.AttendanceDate.Equals(currentDate))))
                    {
                        attendancesAdded = true;
                        student.Attendances.Add(new Attendance
                        {
                            StudentID = student.StudentID,
                            AttendanceDate = currentDate,
                            Attended = false
                        });
                    }
                }
                currentDate = currentDate.AddDays(DAYS_IN_WEEK);
            }
            if (attendancesAdded)
            {
                db.SaveChanges();
            }
            return attendancesAdded;
        }
        /// <summary>
        /// Menus the specified date range.
        /// </summary>
        /// <param name="dateRange">The date range.</param>
        /// <returns>Archive widget</returns>
        public PartialViewResult Menu(string dateRange = null)
        {
            ViewBag.SelectedArchive = dateRange;

            IEnumerable<DateTime> dates = this.repository.Articles
                                            .Select(b => b.Modified)
                                            .Distinct()
                                            .OrderByDescending(b => b);

            List<string> dateRanges = new List<string>();

            foreach(DateTime date in dates)
            {
                StringBuilder archiveName = new StringBuilder();

                archiveName.Append(CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(date.Month));
                archiveName.Append(" ");
                archiveName.Append(date.Year.ToString());

                if (!dateRanges.Exists(d => d == archiveName.ToString()))
                {
                    dateRanges.Add(archiveName.ToString());
                }
            }

            return PartialView(dateRanges.AsEnumerable());
        }
Beispiel #21
0
        private FrmViewer(long tweetId, List<MediaInfo> lst)
        {
            this.m_lst = lst;
            this.m_containsVideo = lst.Exists(e => e.MediaType == MediaTypes.Video);
            this.TweetId = tweetId;

            InitializeComponent();
            this.Text = "[ 0 / 0 ] Azpe";

            this.SuspendLayout();

            this.m_pic			= new ImageViwer();
            this.m_pic.Dock		= DockStyle.Fill;
            this.m_pic.Visible	= false;
            this.Controls.Add(this.m_pic);

            if (this.m_containsVideo)
            {
                this.m_media		= new VideoViewer();
                this.m_host			= new ElementHost();
                this.m_host.Visible	= false;
                this.m_host.Dock	= DockStyle.Fill;
                this.m_host.Child	= this.m_media;
                this.Controls.Add(this.m_host);
            }

            this.ResumeLayout(false);

            lst.ForEach(e => { e.SetParent(this); e.StartDownload(); });

            if (Settings.Left != -1)	this.Left	= Settings.Left;
            if (Settings.Top != -1)		this.Top	= Settings.Top;
            if (Settings.Width != -1)	this.Width	= Settings.Width;
            if (Settings.Height != -1)	this.Height	= Settings.Height;
        }
Beispiel #22
0
        static void Main(string[] args)
        {
            string cadena = Console.ReadLine();

            double result = 0;
            int lenCadena = cadena.Length;
            List<string> listaNumerosCadena = new List<string>();
            listaNumerosCadena.Add(cadena);
            string subcadena = string.Empty;

            for (int i = 0; i < lenCadena; i++)
            {
                for(int j=i;j<lenCadena;j++)
                {
                     subcadena = cadena.Substring(i, lenCadena-j);
                     if (!listaNumerosCadena.Exists(p => p == subcadena) && subcadena != string.Empty)
                     {
                            listaNumerosCadena.Add(subcadena);
                     }
                }
            }

            foreach(var lst in listaNumerosCadena)
            {

                    var x = Convert.ToDouble(lst) % (Math.Pow(10, 9) + 7);
                    result += Convert.ToDouble(x);

            }

            Console.WriteLine(result % (Math.Pow(10, 9) + 7));
            Console.ReadLine();
        }
        public void Add()
        {
            var criteria = new List<IIterationStopCriterium<Complex32>>
                           {
                               new FailureStopCriterium(),
                               new DivergenceStopCriterium(),
                               new IterationCountStopCriterium(),
                               new ResidualStopCriterium()
                           };
            var iterator = new Iterator();
            Assert.AreEqual(0, iterator.NumberOfCriteria, "Incorrect criterium count");

            foreach (var criterium in criteria)
            {
                iterator.Add(criterium);
                Assert.IsTrue(iterator.Contains(criterium), "Missing criterium");
            }

            // Check that we have all the criteria
            Assert.AreEqual(criteria.Count, iterator.NumberOfCriteria, "Incorrect criterium count");
            var enumerator = iterator.StoredStopCriteria;
            while (enumerator.MoveNext())
            {
                var criterium = enumerator.Current;
                Assert.IsTrue(criteria.Exists( c => ReferenceEquals(c, criterium)), "Criterium missing");
            }
        }
Beispiel #24
0
        private void btnLogin_Click(object sender, EventArgs e)
        {
            db = new DBPOS();
            users = db.GetUserAccounts();
            current = 0;

            if (String.IsNullOrEmpty(txtBxUserName.Text) && String.IsNullOrEmpty(txtBxPassword.Text))
            {
                lblLoginErrorMsg.Text = "Please ensure all fields are entered";
                txtBxUserName.ResetText();
                txtBxPassword.ResetText();
            }
            else if (users.Exists(u => u.Username.Equals(txtBxUserName.Text)))
            {
                current = users.FindIndex(u => u.Username.Equals(txtBxUserName.Text));
                if (users[current].Username.Equals(txtBxUserName.Text) && users[current].Password.Equals(txtBxPassword.Text))
                {
                    lblLoginErrorMsg.Text = "";
                    txtBxUserName.ResetText();
                    txtBxPassword.ResetText();
                    MessageBox.Show(string.Format("Welcome {0}! Your AccountType is {1}.", users[current].Username, users[current].AccountType));
                    UserControlPanel cp = new UserControlPanel();
                    cp.CurrentUser = users[current];
                    cp.ShowDialog();
                }
            }

            else
            {
                txtBxUserName.ResetText();
                txtBxPassword.ResetText();
                lblLoginErrorMsg.Text = "Either the username or password was incorrect.";
            }
        }
        public List<Column> GetAllColumnsAndStories()
        {
            using (var query = new DataQuery(_provider).WithStoredProcedure("up_GetAllColumnsAndStorries"))
            {
                var reader = query.ExecuteQuery();

                List<Column> columns = new List<Column>();

                while (reader.Read())
                {
                    Story story = null;

                    int colIndex = reader.GetOrdinal("StoryId");
                    if (!reader.IsDBNull(colIndex))
                    {
                        story = _mapper.MapStory(reader);
                    }

                    var columnName = (string)reader["ColumnName"];

                    if (columns.Exists(x => x.ColumnName == columnName))
                    {
                        var column = columns.Find(x => x.ColumnName == columnName);
                        column.Stories.Add(story);
                    }
                    else
                    {
                        var column = _mapper.MapColumn(reader);
                        columns.Add(column);
                        column.Stories.Add(story);
                    }
                }
                return columns;
            }
        }
        private List<int> Arvonta()
        {
            MikaLotto();

            int seuraavaNro = 0;
            
            List<int> rndList = new List<int>();

            for (int i = 0; i < lkmNumero; i++)
            {
                if (tyyppi == "Eurojackpot" && i >= 5)
                {
                    suurinNumero = 10;
                }

                do
                {
                    seuraavaNro = random.Next(pieninNumero, suurinNumero);
                } while (rndList.Exists(x => x == seuraavaNro));

                rndList.Add(seuraavaNro);
            }

            return rndList;
        }
Beispiel #27
0
      public void ClearLevelAndPointsNotIn(int zoom, List<DrawTile> list)
      {
         Lock.AcquireWriterLock();
         try
         {
            if(zoom < Levels.Count)
            {
               var l = Levels[zoom];

               tmp.Clear();

               foreach(var t in l)
               {
                  if(!list.Exists(p => p.PosXY == t.Key))
                  {
                     tmp.Add(t);
                  }
               }

               foreach(var r in tmp)
               {
                  l.Remove(r.Key);
                  r.Value.Dispose();
               }

               tmp.Clear();
            }
         }
         finally
         {
            Lock.ReleaseWriterLock();
         }
      }
Beispiel #28
0
		async void NewGame(int size)
		{
			// Preferences
			var preferences = this.GetSharedPreferences(GetString(Resource.String.app_name), FileCreationMode.Private);
			_highScore = preferences.GetInt(string.Format("HighScore_{0}", size), 0);
			_highScoreTv.Text = _highScore.ToString();

			_grid.ColumnCount = size;
			_grid.RowCount = size;
			_mines = new List<Mine>();
			_subViews = new LinearLayout[size * size];
			_checked = new List<Tile>();
			for(int i = 0; i < size; i++)
			{
				int x;
				int y;
				do
				{
					x = new Random().Next(size);
					y = new Random().Next(size);
				} while (_mines.Exists(m => m.X == x && m.Y == y));
				_mines.Add(new Mine { X = x, Y = y });
			}

			await DrawBoard(size * size);
		}
Beispiel #29
0
        private void BuildOrgTree(AjaxTreeNode tn, List<string> dataPriveleges)
        {
            IDictionary<string, object> dic = new Dictionary<string, object>();
            dic.Add("ParentID", tn.ID);
            dic.Add("Status", "0");
            IList<Organization> orgs = repository.FindAll<Organization>(dic).Where(o => IsAdmin || dataPriveleges.Exists(p => o.OwnerOrg.StartsWith(p))).OrderBy(o => o.SortOrder).ToList();

            if (orgs.Count == 0) return;
            foreach (var item in orgs)
            {
                string value = string.Format("{0}/{1}", tn.Value, item.ID);

                AjaxTreeNode node = new AjaxTreeNode()
                {
                    ID = item.ID,
                    Text = item.Name,
                    Value = value,
                    Tag = "Org",
                    NodeIcoSrc = tn.NodeIcoSrc,
                    IcoSrc = string.Format("{0}Plugins/Authorize/Content/Themes/{1}/Images/{2}", WebUtil.GetRootPath(), Skin, getResourceIcon(item.Type.Cast<ResourceType>(ResourceType.Menu))),
                    LinkUrl = string.Format("{0}AuthorizeCenter/OrgUserList.aspx?orgid={1}", WebUtil.GetRootPath(), item.ID),
                    Target = "ifrMain"
                };

                tn.ChildNodes.Add(node);
                BuildOrgTree(node, dataPriveleges);
            }
        }
Beispiel #30
0
        protected void btneliminarGridView_Command(object sender, CommandEventArgs e)
        {
            try
            {
                if (e.CommandName != "Page")
                {
                    BllTipoBandeja.TipoBandeja Row = new BllTipoBandeja.TipoBandeja();

                    List<BllTipoBandeja.TipoBandeja> Rows = new List<BllTipoBandeja.TipoBandeja>();

                    Rows = (List<BllTipoBandeja.TipoBandeja>)Session["ListTipoBandeja"];
                    Session["CodigoActividad"] = e.CommandArgument;

                    if (Rows.Exists(b => b.TiBaCodi.ToString() == e.CommandArgument.ToString()))
                    {
                        Row = Rows.Where(b => b.TiBaCodi.ToString() == e.CommandArgument.ToString()).First();

                        Row.TiBaEsta = false;
                        int r = Row.Desactivar();
                        if (r > 0)
                        {
                            FillTipoBandeja();
                            mensaje(Constantes.Eliminado);
                            updateGrid.Update();
                        }

                    }
                }
            }
            catch (Exception ex) { mensaje(Constantes.ErrorAlConsultarDatos); }
        }
 public static void AddToDiscountList(DiscountModel discount, List<DiscountModel> discounts)
 {
     if (!discounts.Exists(x => x.DiscountCode.Equals(discount.DiscountCode)))
     {
         discounts.Add(discount);
     }
 }
Beispiel #32
0
        private bool CheckPolicy(string policy)
        {
            if (policy?.Length < 1)
            {
                return(true);
            }
            if (policy?.Length > 2 && policy[1] == ':')
            {
                var key = policy.Substring(0, 2);
                policy = policy.Substring(2);
                switch (key)
                {
                case "c:":
                    if (policy.IndexOf('=') > -1)
                    {
                        var split = policy.Split('=');
                        if (GetInformation <object>(split[0]).ToString() == split[1].Trim())
                        {
                            return(true);
                        }
                        throw new Exception($"Claim '{policy}' Don't have valid data.");
                    }
                    if (_claims.ContainsKey(policy))
                    {
                        return(true);
                    }
                    throw new Exception($"Claim '{policy}' Not Found!!!");

                case "r:":
                    if (_roles.Exists(x => x == policy))
                    {
                        return(true);
                    }
                    throw new Exception($"Role '{policy}' Not Found!!!");

                case "p:":
                    if (_permissions.Exists(x => x == policy))
                    {
                        return(true);
                    }
                    throw new Exception($"Permission '{policy}' Not Found!!!");
                }
            }
            if (_permissions?.Exists(x => x == policy) == true)
            {
                return(true);
            }
            throw new Exception($"Permission '{policy}' Not Found!!!");
        }
Beispiel #33
0
        /// <summary> Planet or Moon definition </summary>
        public Body(string bodyName, long?bodyId, List <IDictionary <string, object> > parents, decimal?distanceLs, bool?tidallylocked, TerraformState terraformstate, PlanetClass planetClass, AtmosphereClass atmosphereClass, List <AtmosphereComposition> atmosphereCompositions, Volcanism volcanism, decimal?earthmass, decimal?radiusKm, decimal gravity, decimal?temperatureKelvin, decimal?pressureAtm, bool?landable, List <MaterialPresence> materials, List <SolidComposition> solidCompositions, decimal?semimajoraxisLs, decimal?eccentricity, decimal?orbitalinclinationDegrees, decimal?periapsisDegrees, decimal?orbitalPeriodDays, decimal?rotationPeriodDays, decimal?axialtiltDegrees, List <Ring> rings, ReserveLevel reserveLevel, bool?alreadydiscovered, bool?alreadymapped, string systemName = null, long?systemAddress = null)
        {
            this.bodyname = bodyName;
            this.bodyType = (bool)parents?.Exists(p => p.ContainsKey("Planet"))
                        ? BodyType.FromEDName("Moon") : BodyType.FromEDName("Planet");
            this.rings       = rings;
            this.temperature = temperature;
            this.bodyId      = bodyId;

            // Planet or Moon specific items
            this.planetClass            = planetClass;
            this.earthmass              = earthmass;
            this.radius                 = radiusKm;
            this.gravity                = gravity;
            this.temperature            = temperatureKelvin;
            this.pressure               = pressureAtm;
            this.tidallylocked          = tidallylocked;
            this.landable               = landable;
            this.atmosphereclass        = atmosphereClass;
            this.atmospherecompositions = atmosphereCompositions;
            this.solidcompositions      = solidCompositions;
            this.volcanism              = volcanism;
            this.reserveLevel           = reserveLevel;
            this.materials              = materials;
            this.terraformState         = terraformstate;

            // Orbital characteristics
            this.distance         = distanceLs;
            this.parents          = parents;
            this.orbitalperiod    = orbitalPeriodDays;
            this.rotationalperiod = rotationPeriodDays;
            this.semimajoraxis    = semimajoraxisLs;
            this.eccentricity     = eccentricity;
            this.inclination      = orbitalinclinationDegrees;
            this.periapsis        = periapsisDegrees;
            this.tilt             = axialtiltDegrees;

            // System details
            this.systemname    = systemName; // This is needed to derive the "shortname" property
            this.systemAddress = systemAddress;

            // Scan details
            this.alreadydiscovered = alreadydiscovered;
            this.alreadymapped     = alreadymapped;

            // Other calculations
            this.density = GetDensity();
        }
Beispiel #34
0
        public List <Tuple <int, int> > GetHexListForBuildingAndSatellite(FactionName name, List <Tuple <int, int> > satelist = null)
        {
            var list = new List <Tuple <int, int> >();

            for (int i = 0; i < m_mapHeight; i++)
            {
                for (int j = 0; j < m_mapWidth; j++)
                {
                    if ((HexArray[i, j] != null && (HexArray[i, j].FactionBelongTo == name || (HexArray[i, j].Satellite?.Contains(name)).GetValueOrDefault())) ||
                        (satelist?.Exists(x => x.Item1 == i && x.Item2 == j)).GetValueOrDefault())
                    {
                        list.Add(new Tuple <int, int>(i, j));
                    }
                }
            }
            return(list);
        }
Beispiel #35
0
        private bool AddElementsSequentially(string setName, IEnumerable <string> elements)
        {
            bool retVal = false;

            if (string.IsNullOrEmpty(setName))
            {
                setName = this.HostConfig.Set;
            }

            string        cmdTemplate = $"sudo nft add element {HostConfig.Table} {setName} {{{{0}}}}";
            List <string> cmdList     = new List <string>();

            foreach (string element in elements)
            {
                cmdList.Add($"sudo nft add element {HostConfig.Table} {setName} {{{element}}}");
            }

            List <bool> result = Connector.ExecuteCommands(cmdList) as List <bool>;

            return(result?.Exists(x => x == false) ?? false);
        }
Beispiel #36
0
        public static bool CheckEmail(this string email)
        {
            List <Archer> ArcherList = new List <Archer>();

            using (ArcheryDbContext Db = new ArcheryDbContext()) {
                foreach (Archer element in Db.Archers)
                {
                    Archer ar = element;
                    ArcherList.Add(ar);
                }
                if (ArcherList?.Exists(x => x.Email == email) == null)
                {
                    bool check = true;
                    return(check);
                }
                else
                {
                    bool check = false;
                    return(check);
                }
            }
        }
        public ActionResult Edit(int?id, string UrlReferrer, string HostingEntityName, string AssociatedType, string defaultview)
        {
            if (!User.CanEdit("T_ReasonforHire") || !CustomAuthorizationBeforeEdit(id, HostingEntityName, AssociatedType))
            {
                return(RedirectToAction("Index", "Error"));
            }
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            T_ReasonforHire t_reasonforhire = db.T_ReasonforHires.Find(id);

            // NEXT-PREVIOUS DROP DOWN CODE
            TempData.Keep();
            string json = "";

            if (TempData["T_ReasonforHirelist"] == null)
            {
                json = Newtonsoft.Json.JsonConvert.SerializeObject(db.T_ReasonforHires.Select(z => new { ID = z.Id, DisplayValue = z.DisplayValue }).ToList());
            }
            else
            {
                ViewBag.EntityT_ReasonforHireDisplayValueEdit = TempData["T_ReasonforHirelist"];
                json = Newtonsoft.Json.JsonConvert.SerializeObject(TempData["T_ReasonforHirelist"]);
            }

            Newtonsoft.Json.JsonSerializerSettings serSettings = new    Newtonsoft.Json.JsonSerializerSettings();
            serSettings.ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver();
            var lst = Newtonsoft.Json.JsonConvert.DeserializeObject <IEnumerable <object> >(json, serSettings);

            ViewBag.EntityT_ReasonforHireDisplayValueEdit = new SelectList(lst, "ID", "DisplayValue");
            //
            if (t_reasonforhire == null)
            {
                return(HttpNotFound());
            }
            if (string.IsNullOrEmpty(defaultview))
            {
                defaultview = "Edit";
            }
            GetTemplatesForEdit(defaultview);
            // NEXT-PREVIOUS DROP DOWN CODE
            SelectList            selitm  = new SelectList(lst, "ID", "DisplayValue");
            List <SelectListItem> newList = selitm.ToList();

            if (Request.UrlReferrer != null && Request.UrlReferrer.AbsolutePath.EndsWith("/T_ReasonforHire/Create"))
            {
                newList.Insert(0, (new SelectListItem {
                    Text = t_reasonforhire.DisplayValue, Value = t_reasonforhire.Id.ToString()
                }));
                ViewBag.EntityT_ReasonforHireDisplayValueEdit = newList;
                TempData["T_ReasonforHirelist"] = newList.Select(z => new { ID = z.Value, DisplayValue = z.Text });
            }
            else if (!newList.Exists(p => p.Value == Convert.ToString(t_reasonforhire.Id)))
            {
                if (newList.Count > 0)
                {
                    newList[0].Text  = t_reasonforhire.DisplayValue;
                    newList[0].Value = t_reasonforhire.Id.ToString();
                }
                else
                {
                    newList.Insert(0, (new SelectListItem {
                        Text = t_reasonforhire.DisplayValue, Value = t_reasonforhire.Id.ToString()
                    }));
                }
                ViewBag.EntityT_ReasonforHireDisplayValueEdit = newList;
                TempData["T_ReasonforHirelist"] = newList.Select(z => new { ID = z.Value, DisplayValue = z.Text });
            }
            //
            if (UrlReferrer != null)
            {
                ViewData["T_ReasonforHireParentUrl"] = UrlReferrer;
            }
            if (ViewData["T_ReasonforHireParentUrl"] == null && Request.UrlReferrer != null && !Request.UrlReferrer.AbsolutePath.EndsWith("/T_ReasonforHire") && !Request.UrlReferrer.AbsolutePath.EndsWith("/T_ReasonforHire/Edit/" + t_reasonforhire.Id + "") && !Request.UrlReferrer.AbsolutePath.EndsWith("/T_ReasonforHire/Create"))
            {
                ViewData["T_ReasonforHireParentUrl"] = Request.UrlReferrer;
            }
            ViewData["HostingEntityName"] = HostingEntityName;
            ViewData["AssociatedType"]    = AssociatedType;
            LoadViewDataBeforeOnEdit(t_reasonforhire);
            ViewBag.T_ReasonforHireIsHiddenRule       = checkHidden("T_ReasonforHire", "OnEdit", false);
            ViewBag.T_ReasonforHireIsGroupsHiddenRule = checkHidden("T_ReasonforHire", "OnEdit", true);
            ViewBag.T_ReasonforHireIsSetValueUIRule   = checkSetValueUIRule("T_ReasonforHire", "OnEdit");
            return(View(t_reasonforhire));
        }
        /// <summary>
        /// Method responsible for drawing inter link peptide
        /// </summary>
        /// <param name="peptide1"></param>
        /// <param name="peptide2"></param>
        /// <param name="anotationAlfa"></param>
        /// <param name="anotationBeta"></param>
        /// <param name="xlPos1"></param>
        /// <param name="xlPos2"></param>
        public void DrawInterLink(string peptide1, string peptide2, string anotationAlfa, string anotationBeta, int xlPos1, int xlPos2)
        {
            #region Setting Values
            Peptide1      = peptide1;
            Peptide2      = peptide2;
            AnotationAlfa = anotationAlfa;
            AnotationBeta = anotationBeta;
            XlPos1        = xlPos1;
            XlPos2        = xlPos2;
            #endregion

            imageBuffer          = new Bitmap(panelAnotator.Width, panelAnotator.Height);
            graphicsPeptAnotator = Graphics.FromImage(imageBuffer);
            graphicsPeptAnotator.Clear(Color.White);

            double xLastPosPept1 = 0.0;
            double xLastPosPept2 = 0.0;
            double yLastPosPept1 = 0.0;
            double yLastPosPept2 = 0.0;

            //Getting Series b and y
            List <AnnotationItem> myAnnotationsAlfa = ParseAnnotation(anotationAlfa);
            List <AnnotationItem> myAnnotationsBeta = ParseAnnotation(anotationBeta);
            //Setting font
            Font f = new System.Drawing.Font("Courier New", FONTSIZE);

            #region Calculating offset
            //Find out who will get an offset
            int DeltaXLOffset = xlPos1 - xlPos2;
            if (xlPos1 > xlPos2)
            {
                //Add spaces to peptide 2
                for (int i = 0; i < DeltaXLOffset; i++)
                {
                    peptide2 = " " + peptide2;
                }
                xlPos2 += DeltaXLOffset;
            }
            else if (xlPos2 > xlPos1)
            {
                //Add spaces to peptide 1
                for (int i = 0; i < Math.Abs(DeltaXLOffset); i++)
                {
                    peptide1 = " " + peptide1;
                }
                xlPos1 += Math.Abs(DeltaXLOffset);
            }
            #endregion

            #region Writing peptides

            using (graphicsPeptAnotator)
            {
                graphicsPeptAnotator.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;

                //Draw Peptide 1
                for (int i = 0; i < peptide1.Length; i++)
                {
                    graphicsPeptAnotator.DrawString(peptide1[i].ToString(), f, Brushes.Green, new Point((i * SPACER) + X1OFFSET, Y1OFFSET));

                    //Write the b series
                    int increment = 0;
                    if (xlPos2 - DeltaXLOffset > xlPos1)
                    {
                        increment = Math.Abs(DeltaXLOffset);
                    }

                    if (myAnnotationsAlfa.Exists(a => a.Series.Equals("b") && a.IonNo == i - increment))
                    {
                        DrawLeftBreak((i * SPACER) + X1OFFSET + 2, 4 + Y1OFFSET);
                    }

                    //Write the y series
                    if (myAnnotationsAlfa.Exists(a => a.Series.Equals("y") && a.IonNo == i - increment))
                    {
                        DrawRightBreak(((peptide1.Length - (i - increment)) * SPACER) + X1OFFSET + 2, 4 + Y1OFFSET);
                    }
                }
                xLastPosPept1 = ((peptide1.Length - 1) * SPACER) + X1OFFSET;
                yLastPosPept1 = Y1OFFSET + FONTSIZE + 4;

                //Draw Peptide 2
                for (int i = 0; i < peptide2.Length; i++)
                {
                    int increment = 0;
                    if (xlPos1 - DeltaXLOffset < xlPos2)
                    {
                        increment = DeltaXLOffset;
                    }

                    if (myAnnotationsBeta.Exists(a => a.Series.Equals("b") && a.IonNo == i - increment))
                    {
                        DrawLeftBreak((i * SPACER) + X1OFFSET + 2, Y1OFFSET + (3 * FONTSIZE) - 2);
                    }

                    //Write the y series
                    if (myAnnotationsBeta.Exists(a => a.Series.Equals("y") && a.IonNo == i - increment))
                    {
                        DrawRightBreak(((peptide2.Length - (i - increment)) * SPACER) + X1OFFSET + 2, Y1OFFSET + (3 * FONTSIZE) - 2);
                    }

                    graphicsPeptAnotator.DrawString(peptide2[i].ToString(), f, Brushes.Green, new Point((i * SPACER) + X1OFFSET, Y1OFFSET + (3 * FONTSIZE) - 5));
                }
                xLastPosPept2 = ((peptide2.Length - 1) * SPACER) + X1OFFSET;
                yLastPosPept2 = Y1OFFSET + FONTSIZE + 4;

                //Draw the Interlinker
                Pen p = new Pen(Brushes.Black);
                p.Width = 3;
                Point p1 = new Point(((xlPos1 - 1) * SPACER) + X1OFFSET + (FONTSIZE / 2) + 2, Y1OFFSET + FONTSIZE + 5);
                Point p2 = new Point(((xlPos1 - 1) * SPACER) + X1OFFSET + (FONTSIZE / 2) + 2, Y1OFFSET + FONTSIZE + (2 * FONTSIZE));
                graphicsPeptAnotator.DrawLine(p, p1, p2);
            }
            #endregion

            int       newHeightRect = (int)(yLastPosPept1 + yLastPosPept2 + (2 * FONTSIZE));
            int       newWidthRect  = (int)(xLastPosPept1 > xLastPosPept2 ? xLastPosPept1 : xLastPosPept2);
            Rectangle cropRect      = new Rectangle(0, 0, newWidthRect + FONTSIZE, newHeightRect);
            imageBuffer = this.CropImage(imageBuffer, cropRect);
            panelAnotator.BackgroundImage = imageBuffer;
        }
Beispiel #39
0
 public bool Contains(string username)
 {
     return(pool.Exists(u => u.Username.Equals(username)));
 }
        public RuntimeMultiViewCompilerProvider(IHttpContextAccessor contextAccessor,
                                                ApplicationPartManager applicationPartManager,
                                                IOptions <RazorMultiViewEngineOptions> optionsAccessor,
                                                IDictionary <string, RazorProjectEngine> razorProjectEngines,
                                                PublicCSharpCompiler csharpCompiler,
                                                ILoggerFactory loggerFactory)
        {
            this.contextAccessor = contextAccessor ?? throw new ArgumentNullException(nameof(contextAccessor));
            this.options         = optionsAccessor?.Value ?? throw new ArgumentNullException(nameof(optionsAccessor));
            this.logger          = loggerFactory.CreateLogger <RuntimeMultiViewCompiler>();

            var feature = new ViewsFeature();

            applicationPartManager.PopulateFeature(feature);

            var defaultViews = new List <CompiledViewDescriptor>();

            var defaultEngine = razorProjectEngines.First();

            foreach (var descriptor in feature.ViewDescriptors.Where(f => f.Item.Type.Assembly.GetName().Name.Equals(options.DefaultViewLibrary?.AssemblyName) ||
                                                                     f.Item.Type.Assembly.GetName().Name.Equals(options.DefaultViewLibrary?.AssemblyName + ".Views", StringComparison.Ordinal)))
            {
                if (!defaultViews.Exists(v => v.RelativePath.Equals(descriptor.RelativePath, StringComparison.OrdinalIgnoreCase)))
                {
                    defaultViews.Add(descriptor);
                }
            }

            compilers.Add("default", new RuntimeMultiViewCompiler(new Dictionary <string, RazorProjectEngine> {
                { defaultEngine.Key, defaultEngine.Value }
            }, csharpCompiler, defaultViews, logger));

            // A cache list of libraries and their compiled views
            var libraryViewList = new Dictionary <string, List <CompiledViewDescriptor> >();

            foreach (var option in options.ViewLibraryConfig)
            {
                var optionEngines = new Dictionary <string, RazorProjectEngine>();

                if (compilers.ContainsKey(option.Key))
                {
                    continue;
                }

                // A list of descriptors for this option
                var viewDescriptors = new List <CompiledViewDescriptor>();

                // Loop the requested libraries
                foreach (var library in option.Value)
                {
                    if (razorProjectEngines.TryGetValue(library + ".Views", out var engine))
                    {
                        if (!optionEngines.ContainsKey(library))
                        {
                            optionEngines.Add(library + ".Views", engine);
                        }
                    }

                    if (!libraryViewList.TryGetValue(library, out var liblist))
                    {
                        liblist = feature.ViewDescriptors.Where(d => d.Item.Type.Assembly.GetName().Name.Equals($"{library}") || d.Item.Type.Assembly.GetName().Name.Equals($"{library}.Views")).ToList();
                    }

                    foreach (var descriptor in liblist)
                    {
                        if (viewDescriptors.Exists(v => v.RelativePath.Equals(descriptor.RelativePath, StringComparison.OrdinalIgnoreCase)))
                        {
                            continue;
                        }
                        viewDescriptors.Add(descriptor);
                    }
                }

                // Add any missing views from the default library
                foreach (var descriptor in defaultViews)
                {
                    if (viewDescriptors.Exists(v => v.RelativePath.Equals(descriptor.RelativePath, StringComparison.OrdinalIgnoreCase)))
                    {
                        continue;
                    }
                    viewDescriptors.Add(descriptor);
                }

                optionEngines.Add(defaultEngine.Key, defaultEngine.Value);

                compilers.Add(option.Key, new RuntimeMultiViewCompiler(optionEngines, csharpCompiler, viewDescriptors, logger));
            }
        }
Beispiel #41
0
        public bool DeleteAccount(int acctId)
        {
            accountDtos?.RemoveAll(x => x.AcctId == acctId);

            return((!accountDtos?.Exists(x => x.AcctId == acctId)) ?? true);
        }
        public static bool AddSnipeItem(ISession session, MSniperInfo2 item, bool byPassValidation = false)
        {
            if (isBlocking)
            {
                return(false);
            }
            //this pokemon has been recorded as expires
            if (item.EncounterId > 0 && expiredCache.Get(item.EncounterId.ToString()) != null)
            {
                return(false);
            }

            //fake & annoy data
            if (Math.Abs(item.Latitude) > 90 || Math.Abs(item.Longitude) > 180 || item.Iv > 100)
            {
                return(false);
            }

            lock (locker)
            {
                Func <MSniperInfo2, bool> checkExisting = (MSniperInfo2 x) =>
                {
                    return((x.EncounterId > 0 && x.EncounterId == item.EncounterId) ||
                           (x.EncounterId == 0 && Math.Round(x.Latitude, 6) == Math.Round(item.Latitude, 6) &&
                            Math.Round(x.Longitude, 6) == Math.Round(item.Longitude, 6) &&
                            x.PokemonId == item.PokemonId));
                };

                //remove existing item that
                autoSnipePokemons.RemoveAll(x => checkExisting(x));
                pokedexSnipePokemons.RemoveAll(x => checkExisting(x));
                manualSnipePokemons.RemoveAll(x => checkExisting(x));
            }

            if (!byPassValidation &&
                session.LogicSettings.AutoSnipeMaxDistance > 0 &&
                LocationUtils.CalculateDistanceInMeters(session.Settings.DefaultLatitude, session.Settings.DefaultLongitude, item.Latitude, item.Longitude) > session.LogicSettings.AutoSnipeMaxDistance * 1000)
            {
                return(false);
            }

            lock (locker)
            {
                item.AddedTime = DateTime.Now;
                //just keep pokemon in last 2 min
                autoSnipePokemons.RemoveAll(x => x.AddedTime.AddSeconds(SNIPE_SAFE_TIME) < DateTime.Now);
                pokedexSnipePokemons.RemoveAll(x => x.AddedTime.AddMinutes(SNIPE_SAFE_TIME) < DateTime.Now);
            }
            if (OutOffBallBlock > DateTime.Now ||
                autoSnipePokemons.Exists(x => x.EncounterId == item.EncounterId && item.EncounterId > 0) ||
                (item.EncounterId > 0 && session.Cache[item.EncounterId.ToString()] != null))
            {
                return(false);
            }

            item.Iv = Math.Round(item.Iv, 2);
            if (session.LogicSettings.SnipePokemonNotInPokedex)
            {
                //sometime the API return pokedex not correct, we need cahe this list, need lean everyetime peopellogi
                var pokedex = session.Inventory.GetPokeDexItems().Select(x => x.InventoryItemData?.PokedexEntry?.PokemonId).Where(x => x != null).ToList();
                var update  = pokedex.Where(x => !pokedexList.Contains(x.Value)).ToList();

                pokedexList.AddRange(update.Select(x => x.Value));

                //Logger.Debug($"Pokedex Entry : {pokedexList.Count()}");

                if (pokedexList.Count > 0 &&
                    !pokedexList.Exists(x => x == (PokemonId)item.PokemonId) &&
                    !pokedexSnipePokemons.Exists(p => p.PokemonId == item.PokemonId) &&
                    (!session.LogicSettings.AutosnipeVerifiedOnly ||
                     (session.LogicSettings.AutosnipeVerifiedOnly && item.IsVerified())))
                {
                    session.EventDispatcher.Send(new WarnEvent()
                    {
                        Message = session.Translation.GetTranslation(TranslationString.SnipePokemonNotInPokedex,
                                                                     session.Translation.GetPokemonTranslation((PokemonId)item.PokemonId))
                    });
                    item.Priority = 0;
                    pokedexSnipePokemons.Add(item); //Add as hight priority snipe entry
                    return(true);
                }
            }
            var         pokemonId = (PokemonId)item.PokemonId;
            SnipeFilter filter    = session.LogicSettings.PokemonSnipeFilters.GetFilter <SnipeFilter>(pokemonId);

            lock (locker)
            {
                if (byPassValidation)
                {
                    item.Priority = -1;
                    manualSnipePokemons.Add(item);

                    Logger.Write($"(MANUAL SNIPER) Pokemon added |  {(PokemonId)item.PokemonId} [{item.Latitude},{item.Longitude}] IV {item.Iv}%");
                    return(true);
                }

                item.Priority = filter.Priority;

                if (filter.VerifiedOnly && item.EncounterId == 0)
                {
                    return(false);
                }

                //check candy
                int candy = session.Inventory.GetCandyCount(pokemonId);
                if (candy < filter.AutoSnipeCandy)
                {
                    autoSnipePokemons.Add(item);
                    return(true);
                }

                if (filter.IsMatch(item.Iv, item.Move1, item.Move2, item.Level, item.EncounterId > 0))
                {
                    autoSnipePokemons.Add(item);
                    return(true);
                }
            }
            return(false);
        }
Beispiel #43
0
 public virtual bool IsObjectSpawned(string path)
 {
     return(spawnedObjects?.Exists(o => o.State.Path.EqualsFast(path)) ?? false);
 }
Beispiel #44
0
 public bool IsMessageCommand(string message)
 {
     return(Command.Exists(x => x.CheckMessage(message)));
 }
Beispiel #45
0
        /// <summary>
        /// 生成首页数据
        /// </summary>
        /// <param name="websiteOwnerList">站点列表</param>
        /// <param name="date">日期</param>
        public void BuildDashboardInfo(List <string> websiteList, DateTime nDate)
        {
            if (websiteList.Count == 0)
            {
                return;
            }

            int nDateInt      = DateTimeHelper.ToDateInt8ByDateTime(nDate);
            int lastDate7Int  = DateTimeHelper.ToDateInt8ByDateTime(nDate.AddDays(-6));
            int lastDate30Int = DateTimeHelper.ToDateInt8ByDateTime(nDate.AddDays(-29));
            List <DashboardLog>  dashLogList  = GetDashboardLogList(null, lastDate30Int, nDateInt);
            List <DashboardInfo> dashInfoList = GetDashboardInfoList();

            List <DashboardLog> uvDashLogList = new List <DashboardLog>();

            #region 访客记录统计

            List <MonitorEventDetailsInfo> uvList             = GetDashboardUVList(null, nDate.AddDays(-29).ToString("yyyy-MM-dd"), nDate.ToString("yyyy-MM-dd"));
            List <DashboardMonitorInfo>    uvDashboardLogList = GetColList <DashboardMonitorInfo>(int.MaxValue, 1, "1=1", "DetailID");
            //ExecuteSql("truncate table ZCJ_DashboardMonitorInfo");//清除原30天UV记录
            if (uvList.Count > 0)
            {
                List <DashboardMonitorInfo> uvGroupList = uvList.GroupBy(p => new
                {
                    p.WebsiteOwner,
                    p.EventUserID
                }).Select(g => new DashboardMonitorInfo
                {
                    WebsiteOwner = g.Key.WebsiteOwner,
                    EventUserID  = g.Key.EventUserID,
                    DetailID     = g.Max(p => p.DetailID).Value
                }).OrderByDescending(x => x.DetailID).ToList();

                //删除数据
                List <int> delIdList = uvDashboardLogList.Where(p => !uvGroupList.Exists(pi => pi.DetailID == p.DetailID)).Select(pid => pid.DetailID).ToList();
                if (delIdList.Count > 0)
                {
                    DeleteMultByKey <DashboardMonitorInfo>("DetailID", ZentCloud.Common.MyStringHelper.ListToStr(delIdList, "", ","));
                }

                List <int> addIdList = uvGroupList.Where(p => !uvDashboardLogList.Exists(pi => pi.DetailID == p.DetailID)).Select(pid => pid.DetailID).ToList();

                List <DashboardMonitorInfo> uvAddDashboardList = uvList.Where(p => addIdList.Exists(pi => pi == p.DetailID.Value)).Select(g => new DashboardMonitorInfo
                {
                    DetailID       = g.DetailID.Value,
                    WebsiteOwner   = g.WebsiteOwner,
                    EventUserID    = g.EventUserID,
                    EventDate      = g.EventDate.Value,
                    SourceIP       = g.SourceIP,
                    IPLocation     = g.IPLocation,
                    EventBrowserID = g.EventBrowserID
                }).ToList();

                if (uvAddDashboardList.Count > 0)
                {
                    string          userIds  = MyStringHelper.ListToStr(uvAddDashboardList.Select(p => p.EventUserID).Distinct().ToList(), "'", ",");
                    List <UserInfo> userList = GetColMultListByKey <UserInfo>(int.MaxValue, 1, "UserID", userIds, "AutoID,UserID,TrueName,Phone,WXNickname,WXHeadimgurl");
                    for (int i = 0; i < uvAddDashboardList.Count; i++)
                    {
                        UserInfo nuser = userList.FirstOrDefault(p => p.UserID == uvAddDashboardList[i].EventUserID);
                        if (nuser != null)
                        {
                            uvAddDashboardList[i].EventUserWXNikeName = nuser.WXNickname;
                            uvAddDashboardList[i].EventUserTrueName   = nuser.TrueName;
                            uvAddDashboardList[i].EventUserWXImg      = nuser.WXHeadimgurl;
                            uvAddDashboardList[i].EventUserPhone      = nuser.Phone;
                        }
                        Add(uvAddDashboardList[i]);
                    }
                }

                uvDashLogList = uvList.Where(ni => uvGroupList.Exists(pi => pi.DetailID == ni.DetailID)).GroupBy(p => new
                {
                    p.WebsiteOwner,
                    Value = DateTimeHelper.ToDateInt8ByDateTime(p.EventDate.Value)
                }).Select(g => new DashboardLog
                {
                    WebsiteOwner  = g.Key.WebsiteOwner,
                    Date          = g.Key.Value,
                    DashboardType = "UV",
                    Num           = g.Count()
                }).OrderByDescending(x => x.Date).ThenBy(x => x.WebsiteOwner).ToList();
            }
            #endregion

            List <DashboardLog> fansDashLogList = new List <DashboardLog>();
            #region 粉丝记录统计
            List <Log> fansList = GetDashboardSubscribeList(null, nDate.AddDays(-29).ToString("yyyy-MM-dd"), nDate.ToString("yyyy-MM-dd"));
            if (fansList.Count > 0)
            {
                fansDashLogList = fansList.GroupBy(p => new
                {
                    p.WebsiteOwner,
                    p.UserID
                }).Select(g => new Log
                {
                    WebsiteOwner = g.Key.WebsiteOwner,
                    UserID       = g.Key.UserID,
                    InsertDate   = g.Max(p => p.InsertDate)
                }).GroupBy(e => new
                {
                    e.WebsiteOwner,
                    Value = DateTimeHelper.ToDateInt8ByDateTime(e.InsertDate)
                }).Select(f => new DashboardLog
                {
                    WebsiteOwner  = f.Key.WebsiteOwner,
                    Date          = f.Key.Value,
                    DashboardType = "Fans",
                    Num           = f.Count()
                }).OrderByDescending(x => x.Date).ThenBy(x => x.WebsiteOwner).ToList();
            }
            #endregion

            List <TotalInfo> memberTotalList = GetAllDashboardRegUserTotal();
            List <TotalInfo> uvTotalList     = GetAllDashboardUVTotal();
            List <TotalInfo> fansTotalList   = GetAllDashboardSubscribeTotal();
            List <TotalInfo> orderTotalList  = GetAllDashboardOrderTotal("0,1,2,3");
            List <TotalInfo> visitTotalList  = GetAllDashboardMonitorEventDetailsTotal();

            foreach (string web in websiteList)
            {
                DashboardInfo ndi = dashInfoList.FirstOrDefault(p => p.WebsiteOwner == web);
                //if (ndi!=null && ndi.Date == nDateInt) continue;
                DashboardJson nDashboardJson = new DashboardJson();
                nDashboardJson.visit_num_lastday  = dashLogList.Where(p => p.WebsiteOwner == web && p.DashboardType == "WebAccessLog" && p.Date == nDateInt).Sum(p => p.Num);
                nDashboardJson.order_num_lastday  = dashLogList.Where(p => p.WebsiteOwner == web && p.DashboardType == "WXMallOrder" && p.Date == nDateInt).Sum(p => p.Num);
                nDashboardJson.member_num_lastday = dashLogList.Where(p => p.WebsiteOwner == web && p.DashboardType == "Member" && p.Date == nDateInt).Sum(p => p.Num);
                nDashboardJson.uv_num_lastday     = uvDashLogList.Where(p => p.WebsiteOwner == web && p.Date == nDateInt).Sum(p => p.Num);
                nDashboardJson.fans_num_lastday   = fansDashLogList.Where(p => p.WebsiteOwner == web && p.Date == nDateInt).Sum(p => p.Num);

                nDashboardJson.visit_num_lastweek  = dashLogList.Where(p => p.WebsiteOwner == web && p.DashboardType == "WebAccessLog" && p.Date >= lastDate7Int && p.Date <= nDateInt).Sum(p => p.Num);
                nDashboardJson.order_num_lastweek  = dashLogList.Where(p => p.WebsiteOwner == web && p.DashboardType == "WXMallOrder" && p.Date >= lastDate7Int && p.Date <= nDateInt).Sum(p => p.Num);
                nDashboardJson.member_num_lastweek = dashLogList.Where(p => p.WebsiteOwner == web && p.DashboardType == "Member" && p.Date >= lastDate7Int && p.Date <= nDateInt).Sum(p => p.Num);
                nDashboardJson.uv_num_lastweek     = uvDashLogList.Where(p => p.WebsiteOwner == web && p.Date >= lastDate7Int && p.Date <= nDateInt).Sum(p => p.Num);
                nDashboardJson.fans_num_lastweek   = fansDashLogList.Where(p => p.WebsiteOwner == web && p.Date >= lastDate7Int && p.Date <= nDateInt).Sum(p => p.Num);

                nDashboardJson.visit_num_lastmonth  = dashLogList.Where(p => p.WebsiteOwner == web && p.DashboardType == "WebAccessLog" && p.Date >= lastDate30Int && p.Date <= nDateInt).Sum(p => p.Num);
                nDashboardJson.order_num_lastmonth  = dashLogList.Where(p => p.WebsiteOwner == web && p.DashboardType == "WXMallOrder" && p.Date >= lastDate30Int && p.Date <= nDateInt).Sum(p => p.Num);
                nDashboardJson.member_num_lastmonth = dashLogList.Where(p => p.WebsiteOwner == web && p.DashboardType == "Member" && p.Date >= lastDate30Int && p.Date <= nDateInt).Sum(p => p.Num);
                nDashboardJson.uv_num_lastmonth     = uvDashLogList.Where(p => p.WebsiteOwner == web && p.Date >= lastDate30Int && p.Date <= nDateInt).Sum(p => p.Num);
                nDashboardJson.fans_num_lastmonth   = fansDashLogList.Where(p => p.WebsiteOwner == web && p.Date >= lastDate30Int && p.Date <= nDateInt).Sum(p => p.Num);

                TotalInfo memberTotal = memberTotalList.FirstOrDefault(p => p.WebsiteOwner == web);
                if (memberTotal != null)
                {
                    nDashboardJson.member_total = memberTotal.Total;
                }

                TotalInfo uvTotal = uvTotalList.FirstOrDefault(p => p.WebsiteOwner == web);
                if (uvTotal != null)
                {
                    nDashboardJson.uv_total = uvTotal.Total;
                }

                TotalInfo fansTotal = fansTotalList.FirstOrDefault(p => p.WebsiteOwner == web);
                if (fansTotal != null)
                {
                    nDashboardJson.fans_total = fansTotal.Total;
                }

                TotalInfo orderTotal = orderTotalList.FirstOrDefault(p => p.WebsiteOwner == web);
                if (orderTotal != null)
                {
                    nDashboardJson.order_total = orderTotal.Total;
                }

                TotalInfo visitTotal = visitTotalList.FirstOrDefault(p => p.WebsiteOwner == web);
                if (visitTotal != null)
                {
                    nDashboardJson.visit_total = visitTotal.Total;
                }

                for (DateTime i = nDate; i >= nDate.AddDays(-29); i = i.AddDays(-1))
                {
                    int    rDateInt    = ZentCloud.Common.DateTimeHelper.ToDateInt8ByDateTime(i);
                    string rDateString = i.ToString("yyyy-MM-dd");
                    nDashboardJson.day_list.Add(rDateString);
                    DashboardLog rVisitLog = dashLogList.FirstOrDefault(p => p.WebsiteOwner == web && p.DashboardType == "WebAccessLog" && p.Date == rDateInt);
                    if (rVisitLog == null)
                    {
                        nDashboardJson.visit_num_list.Add(0);
                    }
                    else
                    {
                        nDashboardJson.visit_num_list.Add(rVisitLog.Num);
                    }
                    DashboardLog rOrderLog = dashLogList.FirstOrDefault(p => p.WebsiteOwner == web && p.DashboardType == "WXMallOrder" && p.Date == rDateInt);
                    if (rOrderLog == null)
                    {
                        nDashboardJson.order_num_list.Add(0);
                    }
                    else
                    {
                        nDashboardJson.order_num_list.Add(rOrderLog.Num);
                    }
                    DashboardLog rMemberLog = dashLogList.FirstOrDefault(p => p.WebsiteOwner == web && p.DashboardType == "Member" && p.Date == rDateInt);
                    if (rMemberLog == null)
                    {
                        nDashboardJson.member_num_list.Add(0);
                    }
                    else
                    {
                        nDashboardJson.member_num_list.Add(rMemberLog.Num);
                    }

                    DashboardLog rUVLog = uvDashLogList.FirstOrDefault(p => p.WebsiteOwner == web && p.Date == rDateInt);
                    if (rUVLog == null)
                    {
                        nDashboardJson.uv_num_list.Add(0);
                    }
                    else
                    {
                        nDashboardJson.uv_num_list.Add(rUVLog.Num);
                    }

                    DashboardLog rFansLog = fansDashLogList.FirstOrDefault(p => p.WebsiteOwner == web && p.Date == rDateInt);
                    if (rFansLog == null)
                    {
                        nDashboardJson.fans_num_list.Add(0);
                    }
                    else
                    {
                        nDashboardJson.fans_num_list.Add(rFansLog.Num);
                    }
                }
                nDashboardJson.timestamp = DateTimeHelper.DateTimeToUnixTimestamp(DateTime.Now);

                string nJson = JsonConvert.SerializeObject(nDashboardJson);
                if (ndi == null)
                {
                    Add(new DashboardInfo()
                    {
                        WebsiteOwner = web, Date = nDateInt, Json = nJson
                    });
                }
                else
                {
                    Update(new DashboardInfo()
                    {
                        WebsiteOwner = web, Date = nDateInt, Json = nJson
                    });
                }
            }
        }
Beispiel #46
0
 public static bool OrderExist(int id)
 {
     return(OrderList.Exists(item => item.ID == id));
 }
Beispiel #47
0
 public bool gameExist(int processId)
 {
     return(gameList.Exists(i => i.process.Id == processId));
 }
Beispiel #48
0
 public bool Contains(string group)
 {
     return(_storages?.Exists(s => s.Group == group) ?? false);
 }
Beispiel #49
0
 public static bool Existe(out XMLNodoEntity nodo, Sistema.Nodo tipo, List <XMLNodoEntity> lstNodos)
 {
     nodo = lstNodos?.Find(i => i.TipoNodo == tipo) ?? new XMLNodoEntity();
     return(lstNodos?.Exists(i => i.TipoNodo == tipo) == true);
 }
Beispiel #50
0
        public override void Update()
        {
            // Raises the events only when the given interval has
            // passed since the last event, so it is okay to call every frame
            _tickEngine.Pulse();
            if (!OverlayWindow.IsVisible)
            {
                return;
            }
            if (!MouseDown)
            {
                FollowTargetWindow();
            }
            Combatant        self  = Program.mem?.GetSelfCombatant();
            List <Combatant> clist = Program.mem?._getCombatantList();

            if (self != null && clist != null)
            {
                clist.RemoveAll(c => c.OwnerID == self.ID);
                foreach (uint ID in clist.Where(c => c.Type == ObjectType.PC).Select(x => x.ID).ToList())
                {
                    clist.RemoveAll(c => c.OwnerID == ID);
                }
                RemoveUnvantedCombatants(self, clist);

                double centerY = OverlayWindow.Height / 2;
                double centerX = OverlayWindow.Width / 2;
                foreach (Combatant c in clist)
                {                                                                        //ridiculous posx+posy as key, no idea what else to use
                    if (c.ID == 3758096384 && !miscDrawMap.ContainsKey(c.PosX + c.PosY)) //for aetherytes, npcs, and other stuff;
                    {
                        miscDrawMap.Add(c.PosX + c.PosY, new EntityOverlayControl(c));
                        OverlayWindow.Add(miscDrawMap[c.PosX + c.PosY]);
                    }
                    else if (!drawMap.ContainsKey(c.ID))
                    {
                        drawMap.Add(c.ID, new EntityOverlayControl(c, c.ID == self.ID));
                        OverlayWindow.Add(drawMap[c.ID]);
                    }

                    double Top  = (c.PosY - self.PosY);
                    double Left = (c.PosX - self.PosX);
                    Top  += centerY + (Top * OverlayWindow.Height * .003 * Properties.Settings.Default.RadarZoom);
                    Left += centerX + (Left * OverlayWindow.Width * .003 * Properties.Settings.Default.RadarZoom);
                    if (drawMap.ContainsKey(c.ID))
                    {
                        drawMap[c.ID].Update(c);
                        Top  -= (drawMap[c.ID].ActualHeight / 2);
                        Left -= (drawMap[c.ID].ActualWidth / 2);
                        if (Top < 0)
                        {
                            Canvas.SetTop(drawMap[c.ID], 0);
                        }
                        else if (Top > OverlayWindow.Height - drawMap[c.ID].ActualHeight)
                        {
                            Canvas.SetTop(drawMap[c.ID], OverlayWindow.Height - drawMap[c.ID].ActualHeight);
                        }
                        else
                        {
                            Canvas.SetTop(drawMap[c.ID], Top);
                        }

                        if (Left < 0)
                        {
                            Canvas.SetLeft(drawMap[c.ID], 0);
                        }
                        else if (Left > OverlayWindow.Width - drawMap[c.ID].ActualWidth)
                        {
                            Canvas.SetLeft(drawMap[c.ID], OverlayWindow.Width - drawMap[c.ID].ActualWidth);
                        }
                        else
                        {
                            Canvas.SetLeft(drawMap[c.ID], Left);
                        }
                    }
                    else if (miscDrawMap.ContainsKey(c.PosX + c.PosY))
                    {
                        miscDrawMap[c.PosX + c.PosY].Update(c);
                        Top  -= (miscDrawMap[c.ID].ActualHeight / 2);
                        Left -= (miscDrawMap[c.ID].ActualWidth / 2);
                        Canvas.SetTop(miscDrawMap[c.PosX + c.PosY], Top);
                        Canvas.SetLeft(miscDrawMap[c.PosX + c.PosY], Left);
                    }
                }
            }

            //cleanup
            foreach (KeyValuePair <uint, EntityOverlayControl> entry in drawMap.ToArray())
            {
                //Hide hoard/cairn, after Banded Coffer appeared... hmm Hoard will re-appear if going out of "sight" and in again
                if (entry.Value.GetName().Equals("Hoard!") && (clist?.Any(c => c.EventType == EObjType.Banded) ?? false))
                {
                    entry.Value.Visibility = Visibility.Collapsed;
                    if (!hoardsDiscovered.Contains(entry.Key))
                    {
                        hoardsDiscovered.Add(entry.Key);
                    }
                    continue;
                }

                if (clist?.Exists(c => c.ID == entry.Key) ?? false)
                {
                    continue;
                }
                else
                {
                    entry.Value.Visibility = Visibility.Collapsed;
                    drawMap.Remove(entry.Key);
                }
            }
            foreach (KeyValuePair <float, EntityOverlayControl> entry in miscDrawMap.ToArray())
            {
                if (clist?.Exists(c => c.PosX + c.PosY == entry.Key) ?? false)
                {
                    continue;
                }
                else
                {
                    entry.Value.Visibility = Visibility.Collapsed;
                    miscDrawMap.Remove(entry.Key);
                }
            }
        }
Beispiel #51
0
 public bool HasTranslationCategory(string name)
 {
     return(translationCategories.Exists(t => t.Name.TrimStart('_') == name.TrimStart('_')));
 }
Beispiel #52
0
 public bool Exists(Player p)
 {
     return(records.Exists(x => x.Nik == p.Nik && x.DateRecord == p.DateRecord && x.Record == p.Record));
 }
 public bool ContainsInside(Vector2 a_pos)
 {
     return(Outside.ContainsInside(a_pos) && !m_holes.Exists(h => h.ContainsInside(a_pos) || h.OnBoundary(a_pos)));
 }
Beispiel #54
0
 public bool Contains(System.Predicate <Item> predicate)
 {
     return(items?.Exists(predicate) ?? false);
 }
Beispiel #55
0
        /// <summary>
        /// 更新评选活动的项目分数
        /// </summary>
        /// <param name="reviewId"></param>
        /// <returns></returns>
        public virtual async Task UpdateReviewProjectScore(int reviewId)
        {
            var review = await GetByIdAsync(reviewId);

            if (review.ReviewStatus != ReviewStatus.Reviewed)
            {
                //每次专家打分均重新计算排名
                //return;
            }
            var maxRound  = review.ReviewRounds.Max(o => o.Round);
            var lastRound = review.ReviewRounds.Where(o => o.Round == maxRound && o.Turn == 1).Single();
            //评选活动的所有项目
            var sourceProjectIds = review.ReviewRounds.First().SourceProjectIDs.Split(',').Select(o => int.Parse(o));
            var projects         = await ProjectRepository.GetAll().Where(o => sourceProjectIds.Contains(o.Id)).ToListAsync();

            //清空项目评分缓存
            foreach (var project in projects)
            {
                await CacheManager.GetCache <int, object>("ProjectResultCache").RemoveAsync(project.Id);
            }
            await CacheManager.GetCache <int, List <ProjectReviewSummary> >("ProjectReviewSummary")
            .RemoveAsync(reviewId);

            //获取评选的所有项目数据
            var projectReviewSummaries = await GetAllProjectRanks(review);

            //待重排名的奖项
            List <Prizes.Prize> prizes = new List <Prizes.Prize>();
            //如果投票专家超过10个,则补投权重为0.01,否则为0.1
            var subRatial = review.ReviewExperts.Count > 10 ? 100 : 10;

            foreach (var project in projects)
            {
                if (!prizes.Exists(o => o.Id == project.Prize.Id))
                {
                    //将项目的奖项加入待重排名列表
                    prizes.Add(project.Prize);
                }
                //统一转换为100分制计算轮次加权总分
                //rate=100/o.MaxScore 如果要转换为100分制
                var rate     = 1;
                var maxround = review.ReviewRounds.Max(o => o.Round);
                var score    = projectReviewSummaries.Where(o => o.Id == project.Id).Sum(o =>
                {
                    //var subScore = (o.SubScores.Count > 0 ? Convert.ToDecimal(o.SubScores.Average()) : 0)/10;
                    var subScore = CaculateIntScoresByIndex(o.SubScores.ToArray(), subRatial);
                    //加上补充评审分数
                    return((o.Score + subScore) * rate * Convert.ToDecimal(Math.Pow(10, o.Round - 1)));
                }) / Convert.ToDecimal(Math.Pow(10, maxround - 1));
                if (review.ReviewType == ReviewType.Champion)
                {
                    //决赛项目直接设置分数
                    project.ScoreChampion = score;
                }
                else if (project.Prize.PrizeType != Prizes.PrizeType.Multiple ||
                         (review.ReviewType == ReviewType.Finish && project.Prize.PrizeType == Prizes.PrizeType.Multiple))
                {
                    //非综合类项目或者终评的综合类奖项直接设置分数
                    if (review.ReviewType == ReviewType.Initial)
                    {
                        project.ScoreInitial = score;
                    }
                    else
                    {
                        project.ScoreFinal = score;
                    }
                }
                else
                {
                    //综合类奖项需要将每个专业的分数保存
                    var projectMajorInfos   = project.ProjectMajorInfos;
                    var currentProjectMajor = projectMajorInfos.Single(o => o.MajorId == review.SubMajorId);
                    if (review.ReviewType == ReviewType.Initial)
                    {
                        currentProjectMajor.ScoreInitial = score;
                    }
                    else
                    {
                        currentProjectMajor.ScoreFinal = score;
                    }
                    //计算综合类权重总分
                    var prizeSubMajors = project.Prize.PrizeSubMajors;
                    project.ScoreInitial = 0;
                    project.ScoreFinal   = 0;
                    foreach (var projectMajorInfo in projectMajorInfos.Where(o => o.MajorId != null))
                    {
                        var prizeSubMajor = prizeSubMajors.SingleOrDefault(o => o.MajorId == projectMajorInfo.MajorId);
                        if (prizeSubMajor != null)
                        {
                            if (projectMajorInfo.ScoreInitial != null)
                            {
                                //原创项目需要乘加成系数
                                project.ScoreInitial += projectMajorInfo.ScoreInitial.Value * prizeSubMajor.Percent.Value / 100 * ((prizeSubMajor.Ratio == null || !project.IsOriginal)?1:prizeSubMajor.Ratio.Value);
                            }
                            if (projectMajorInfo.ScoreFinal != null)
                            {
                                //原创项目需要乘加成系数
                                project.ScoreFinal += projectMajorInfo.ScoreFinal.Value * prizeSubMajor.Percent.Value / 100 * ((prizeSubMajor.Ratio == null || !project.IsOriginal) ? 1 : prizeSubMajor.Ratio.Value);
                            }
                        }
                    }
                }
            }
            await CurrentUnitOfWork.SaveChangesAsync();

            //对项目排名重新计算
            if (review.ReviewType == ReviewType.Champion)
            {
                var i = 1;
                foreach (var project in projects.OrderByDescending(o => o.ScoreChampion))
                {
                    project.RankChampion = i++;
                }
            }
            else
            {
                await ReRankProjects(prizes, review.ReviewType);
            }
        }
        private void SetupPropellants(bool moveNext)
        {
            try
            {
                Current_propellant = fuel_mode < _propellants.Count ? _propellants[fuel_mode] : _propellants.FirstOrDefault();

                if ((Current_propellant.SupportedEngines & type) != type)
                {
                    _rep++;
                    togglePropellant(moveNext);
                    return;
                }

                Propellant new_propellant = Current_propellant.Propellant;

                List <Propellant> list_of_propellants = new List <Propellant>();
                list_of_propellants.Add(new_propellant);

                // if all propellant exist
                if (!list_of_propellants.Exists(prop => PartResourceLibrary.Instance.GetDefinition(prop.name) == null))
                {
                    //Get the Ignition state, i.e. is the engine shutdown or activated
                    var engineState = _attached_engine.getIgnitionState;

                    _attached_engine.Shutdown();

                    ConfigNode newPropNode = new ConfigNode();
                    foreach (var prop in list_of_propellants)
                    {
                        ConfigNode propellantConfigNode = newPropNode.AddNode("PROPELLANT");
                        propellantConfigNode.AddValue("name", prop.name);
                        propellantConfigNode.AddValue("ratio", prop.ratio);
                        propellantConfigNode.AddValue("DrawGauge", "true");
                    }
                    _attached_engine.Load(newPropNode);

                    if (engineState == true)
                    {
                        _attached_engine.Activate();
                    }
                }
                else if (_rep < _propellants.Count)
                {
                    _rep++;
                    togglePropellant(moveNext);
                    return;
                }

                if (HighLogic.LoadedSceneIsFlight)
                {
                    // you can have any fuel you want in the editor but not in flight
                    var allVesselResourcesNames = part.vessel.parts.SelectMany(m => m.Resources).Select(m => m.resourceName).Distinct();
                    if (!list_of_propellants.All(prop => allVesselResourcesNames.Contains(prop.name.Replace("LqdWater", "Water"))) && _rep < _propellants.Count)
                    {
                        _rep++;
                        togglePropellant(moveNext);
                        return;
                    }
                }

                _rep = 0;
            }
            catch (Exception e)
            {
                UnityEngine.Debug.LogError("[KSPI] - SetupPropellants ElectricEngineControllerFX " + e.Message);
            }
        }
Beispiel #57
0
 public bool HasCompletedHunt(string huntID)
 {
     return(_completedHunts.Exists(x => x.ID == huntID));
 }
Beispiel #58
0
        public async Task ImportAllExchangePairs()
        {
            var result = await _cryptoCompareGateway.AllExchangePairs();

            List <ExchangePairsDTO> exchangePairsDTOs = result?.Content;
            List <Exchange>         exchanges         = _coreDBContext.Exchanges.AsEnumerable().Where(e => exchangePairsDTOs?.Exists(d => d.Name == e.Name) == true).ToList();
            List <Currency>         currencies        = await _coreDBContext.Currencies.ToListAsync();

            List <ExchangePair> exchangePairs = new List <ExchangePair>();

            if (exchangePairsDTOs?.Any() == true)
            {
                foreach (var exchangeDto in exchangePairsDTOs)
                {
                    Exchange exchange = exchanges?.FirstOrDefault(e => e.Name == exchangeDto.Name);
                    if (exchange != null)
                    {
                        foreach (var pair in exchangeDto.Pairs)
                        {
                            Currency currencyFrom = currencies?.FirstOrDefault(c => c.Symbol == pair.CurrencyFrom);
                            Currency currencyTo   = currencies?.FirstOrDefault(c => c.Symbol == pair.CurrencyTo);
                            if (currencyFrom != null && currencyTo != null)
                            {
                                var exchangePair = new ExchangePair
                                {
                                    ExchangeId     = exchange.Id,
                                    CurrencyFromId = currencyFrom.Id,
                                    CurrencyToId   = currencyTo.Id,
                                };
                                exchangePairs.Add(exchangePair);
                            }
                        }
                    }
                }
            }

            if (exchangePairs.Any())
            {
                await _coreDBContext.AddRangeAsync(exchangePairs);

                await _coreDBContext.SaveChangesAsync();
            }
        }
Beispiel #59
0
 public bool Any(Predicate <T> callback) => _list?.Exists(callback) == true;
Beispiel #60
0
        private void RefreshForm()
        {
            if (!IsValid(selectedGame))
            {
                InactiveForm();
                return;
            }

            btnInstall.Text              = "安装MOD管理器模块到游戏";
            btnRestore.Enabled           = false;
            additionallyGroupBox.Visible = false;

            gamePath = "";
            if (string.IsNullOrEmpty(selectedGameParams.Path) || !Directory.Exists(selectedGameParams.Path))
            {
                var result = FindGameFolder(selectedGame.Folder);
                if (string.IsNullOrEmpty(result))
                {
                    InactiveForm();
                    btnOpenFolder.ForeColor          = Color.Red;
                    btnOpenFolder.Text               = "选择游戏主目录";
                    folderBrowserDialog.SelectedPath = null;
                    Log.Print($"游戏主目录“{selectedGame.Folder}”不存在!");
                    return;
                }
                Log.Print($"已检测到游戏主目录“{result}”。");
                selectedGameParams.Path = result;
            }

            if (!Utils.IsUnixPlatform() && !Directory.GetFiles(selectedGameParams.Path, "*.exe", SearchOption.TopDirectoryOnly).Any())
            {
                InactiveForm();
                Log.Print("请选择游戏可执行文件所在的目录。");
                return;
            }

            Utils.TryParseEntryPoint(selectedGame.EntryPoint, out var assemblyName);

            gamePath = selectedGameParams.Path;
            btnOpenFolder.ForeColor          = Color.Green;
            btnOpenFolder.Text               = new DirectoryInfo(gamePath).Name;
            folderBrowserDialog.SelectedPath = gamePath;
            managedPath               = FindManagedFolder(gamePath);
            managerPath               = Path.Combine(managedPath, nameof(UnityModManager));
            entryAssemblyPath         = Path.Combine(managedPath, assemblyName);
            injectedEntryAssemblyPath = entryAssemblyPath;
            managerAssemblyPath       = Path.Combine(managerPath, typeof(UnityModManager).Module.Name);
            entryPoint          = selectedGame.EntryPoint;
            injectedEntryPoint  = selectedGame.EntryPoint;
            assemblyDef         = null;
            injectedAssemblyDef = null;
            managerDef          = null;

            gameExePath = !string.IsNullOrEmpty(selectedGame.GameExe) ? Path.Combine(gamePath, selectedGame.GameExe) : string.Empty;

            doorstopPath       = Path.Combine(gamePath, doorstopFilename);
            doorstopConfigPath = Path.Combine(gamePath, doorstopConfigFilename);

            libraryPaths = new string[libraryFiles.Length];
            for (int i = 0; i < libraryFiles.Length; i++)
            {
                libraryPaths[i] = Path.Combine(managerPath, libraryFiles[i]);
            }

            var parent = new DirectoryInfo(Application.StartupPath).Parent;

            for (int i = 0; i < 3; i++)
            {
                if (parent == null)
                {
                    break;
                }

                if (parent.FullName == gamePath)
                {
                    InactiveForm();
                    Log.Print("Unity游戏MOD管理器不能定位游戏主目录!");
                    return;
                }
                parent = parent.Parent;
            }

            try
            {
                assemblyDef = ModuleDefMD.Load(File.ReadAllBytes(entryAssemblyPath));
            }
            catch (Exception e)
            {
                InactiveForm();
                Log.Print(e.ToString());
                return;
            }

            var useOldPatchTarget = false;

            GameInfo.filepathInGame = Path.Combine(managerPath, "Config.xml");
            if (File.Exists(GameInfo.filepathInGame))
            {
                var gameConfig = GameInfo.ImportFromGame();
                if (gameConfig == null || !Utils.TryParseEntryPoint(gameConfig.EntryPoint, out assemblyName))
                {
                    InactiveForm();
                    return;
                }
                injectedEntryPoint        = gameConfig.EntryPoint;
                injectedEntryAssemblyPath = Path.Combine(managedPath, assemblyName);
            }
            else if (!string.IsNullOrEmpty(selectedGame.OldPatchTarget))
            {
                if (!Utils.TryParseEntryPoint(selectedGame.OldPatchTarget, out assemblyName))
                {
                    InactiveForm();
                    return;
                }
                useOldPatchTarget         = true;
                injectedEntryPoint        = selectedGame.OldPatchTarget;
                injectedEntryAssemblyPath = Path.Combine(managedPath, assemblyName);
            }

            try
            {
                if (injectedEntryAssemblyPath == entryAssemblyPath)
                {
                    injectedAssemblyDef = assemblyDef;
                }
                else
                {
                    injectedAssemblyDef = ModuleDefMD.Load(File.ReadAllBytes(injectedEntryAssemblyPath));
                }
                if (File.Exists(managerAssemblyPath))
                {
                    managerDef = ModuleDefMD.Load(File.ReadAllBytes(managerAssemblyPath));
                }
            }
            catch (Exception e)
            {
                InactiveForm();
                Log.Print(e.ToString());
                return;
            }

            var disabledMethods    = new List <InstallType>();
            var unavailableMethods = new List <InstallType>();

            var managerType = typeof(UnityModManager);
            var starterType = typeof(Injection.UnityModManagerStarter);

Rescan:
            var v0_12_Installed = injectedAssemblyDef.Types.FirstOrDefault(x => x.Name == managerType.Name);
            var newWayInstalled     = injectedAssemblyDef.Types.FirstOrDefault(x => x.Name == starterType.Name);
            var hasInjectedAssembly = v0_12_Installed != null || newWayInstalled != null;

            if (useOldPatchTarget && !hasInjectedAssembly)
            {
                useOldPatchTarget         = false;
                injectedEntryPoint        = selectedGame.EntryPoint;
                injectedEntryAssemblyPath = entryAssemblyPath;
                injectedAssemblyDef       = assemblyDef;
                goto Rescan;
            }

            if (Utils.IsUnixPlatform() || !File.Exists(gameExePath))
            {
                unavailableMethods.Add(InstallType.DoorstopProxy);
                selectedGameParams.InstallType = InstallType.Assembly;
            }
            else if (File.Exists(doorstopPath))
            {
                disabledMethods.Add(InstallType.Assembly);
                selectedGameParams.InstallType = InstallType.DoorstopProxy;
            }

            if (hasInjectedAssembly)
            {
                disabledMethods.Add(InstallType.DoorstopProxy);
                selectedGameParams.InstallType = InstallType.Assembly;
            }

            foreach (var ctrl in installTypeGroup.Controls)
            {
                if (ctrl is RadioButton btn)
                {
                    if (unavailableMethods.Exists(x => x.ToString() == btn.Name))
                    {
                        btn.Visible = false;
                        btn.Enabled = false;
                        continue;
                    }
                    if (disabledMethods.Exists(x => x.ToString() == btn.Name))
                    {
                        btn.Visible = true;
                        btn.Enabled = false;
                        continue;
                    }

                    btn.Visible = true;
                    btn.Enabled = true;
                    btn.Checked = btn.Name == selectedGameParams.InstallType.ToString();
                }
            }

            if (selectedGameParams.InstallType == InstallType.Assembly)
            {
                btnRestore.Enabled = IsDirty(injectedAssemblyDef) && File.Exists($"{injectedEntryAssemblyPath}.original_");
            }

            tabControl.TabPages[1].Enabled = true;

            managerDef = managerDef ?? injectedAssemblyDef;

            var managerInstalled = managerDef.Types.FirstOrDefault(x => x.Name == managerType.Name);

            if (managerInstalled != null && (hasInjectedAssembly || selectedGameParams.InstallType == InstallType.DoorstopProxy))
            {
                btnInstall.Text    = "更新MOD管理器模块";
                btnInstall.Enabled = false;
                btnRemove.Enabled  = true;

                Version version2;
                if (v0_12_Installed != null)
                {
                    var versionString = managerInstalled.Fields.First(x => x.Name == nameof(UnityModManager.version)).Constant.Value.ToString();
                    version2 = Utils.ParseVersion(versionString);
                }
                else
                {
                    version2 = managerDef.Assembly.Version;
                }

                installedVersion.Text = version2.ToString();
                if (version > version2 && v0_12_Installed == null)
                {
                    btnInstall.Enabled = true;
                }
            }
            else
            {
                installedVersion.Text = "-";
                btnInstall.Enabled    = true;
                btnRemove.Enabled     = false;
            }

            if (!string.IsNullOrEmpty(selectedGame.Additionally))
            {
                notesTextBox.Text            = selectedGame.Additionally;
                additionallyGroupBox.Visible = true;
            }
        }