System.Collections.Generic.List.Contains(int)

Here are the examples of the csharp api System.Collections.Generic.List.Contains(int) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1442 Examples 7

19 View Source File : ExpressionResolverTests.cs
License : MIT License
Project Creator : 17MKH

[Fact]
        public void ResolveExpressionTest13()
        {
            var ids = new List<int> { 10, 15 };

            Expression<Func<ArticleEnreplacedy, bool>> exp = m => ids.Contains(m.Id);

            var parameters = new QueryParameters();
            var sql = ExpressionResolver.Resolve(_queryBody, exp, parameters);

            replacedert.Equal("`Id` IN (10,15)", sql);
        }

19 View Source File : MultiTableExpressionResolverTests.cs
License : MIT License
Project Creator : 17MKH

[Fact]
        public void ResolveExpressionTest13()
        {
            var ids = new List<int> { 10, 15 };

            Expression<Func<IQueryableJoins<ArticleEnreplacedy, CategoryEnreplacedy>, bool>> exp = m => ids.Contains(m.T1.Id);

            var parameters = new QueryParameters();
            var sql = ExpressionResolver.Resolve(_queryBody, exp, parameters);

            replacedert.Equal("T1.`Id` IN (10,15)", sql);
        }

19 View Source File : RepositoryTest.cs
License : MIT License
Project Creator : 17MKH

[Fact]
        public async void ListTest()
        {
            await ClearAndAdd();

            var list = await _articleRepository.Find().ToList();

            replacedert.Equal(10, list.Count);

            list = await _articleRepository.Find(m => m.Id > 5).OrderBy(m => m.Id).ToList();
            replacedert.Equal("mkh10", list[4].replacedle);

            list = await _articleRepository.Find(m => m.Id == 7).ToList();
            replacedert.Single(list);
            replacedert.Equal("mkh7", list.First().replacedle);

            list = await _articleRepository.Find(m => m.replacedle.Contains("9")).ToList();
            replacedert.Single(list);

            list = await _articleRepository.Find(m => m.replacedle.StartsWith("mkh")).ToList();
            replacedert.Equal(6, list.Count);

            list = await _articleRepository.Find(m => m.replacedle.EndsWith("9") || m.replacedle.EndsWith("1")).ToList();
            replacedert.Equal(2, list.Count);

            var ids = new List<int> { 3, 5, 9 };
            list = await _articleRepository.Find(m => ids.Contains(m.Id)).ToList();
            replacedert.Equal(3, list.Count);
            replacedert.Equal("mkh5", list[1].replacedle);

            list = await _articleRepository.Find(m => ids.NotContains(m.Id)).ToList();
            replacedert.Equal(7, list.Count);
            replacedert.Equal("test1", list[0].replacedle);

            var sql = _articleRepository.Find(m => m.Id > 10).ToListSql();
            replacedert.Equal(Select + " WHERE [Id] > @P1 AND [Deleted] = 0", sql);

            sql = _articleRepository.Find(m => m.Id > 10).ToListSqlNotUseParameters();
            replacedert.Equal(Select + " WHERE [Id] > 10 AND [Deleted] = 0", sql);
        }

19 View Source File : ExpressionResolverTests.cs
License : MIT License
Project Creator : 17MKH

[Fact]
        public void ResolveExpressionTest13()
        {
            var ids = new List<int> { 10, 15 };

            Expression<Func<ArticleEnreplacedy, bool>> exp = m => ids.Contains(m.Id);

            var parameters = new QueryParameters();
            var sql = ExpressionResolver.Resolve(_queryBody, exp, parameters);

            replacedert.Equal("[Id] IN (10,15)", sql);
        }

19 View Source File : RepositoryTest.cs
License : MIT License
Project Creator : 17MKH

[Fact]
        public async void ListTest()
        {
            await ClearAndAdd();

            var list = await _articleRepository.Find().ToList();

            replacedert.Equal(10, list.Count);

            list = await _articleRepository.Find(m => m.Id > 5).OrderBy(m => m.Id).ToList();
            replacedert.Equal("mkh10", list[4].replacedle);

            list = await _articleRepository.Find(m => m.Id == 7).ToList();
            replacedert.Single(list);
            replacedert.Equal("mkh7", list.First().replacedle);

            list = await _articleRepository.Find(m => m.replacedle.Contains("9")).ToList();
            replacedert.Single(list);

            list = await _articleRepository.Find(m => m.replacedle.StartsWith("mkh")).ToList();
            replacedert.Equal(6, list.Count);

            list = await _articleRepository.Find(m => m.replacedle.EndsWith("9") || m.replacedle.EndsWith("1")).ToList();
            replacedert.Equal(2, list.Count);

            var ids = new List<int> { 3, 5, 9 };
            list = await _articleRepository.Find(m => ids.Contains(m.Id)).ToList();
            replacedert.Equal(3, list.Count);
            replacedert.Equal("mkh5", list[1].replacedle);

            list = await _articleRepository.Find(m => ids.NotContains(m.Id)).ToList();
            replacedert.Equal(7, list.Count);
            replacedert.Equal("test1", list[0].replacedle);

            var sql = _articleRepository.Find(m => m.Id > 10).ToListSql();
            replacedert.Equal(Select + " WHERE `Id` > @P1 AND `Deleted` = 0", sql);

            sql = _articleRepository.Find(m => m.Id > 10).ToListSqlNotUseParameters();
            replacedert.Equal(Select + " WHERE `Id` > 10 AND `Deleted` = 0", sql);
        }

19 View Source File : MultiTableExpressionResolverTests.cs
License : MIT License
Project Creator : 17MKH

[Fact]
        public void ResolveExpressionTest13()
        {
            var ids = new List<int> { 10, 15 };

            Expression<Func<IQueryableJoins<ArticleEnreplacedy, CategoryEnreplacedy>, bool>> exp = m => ids.Contains(m.T1.Id);

            var parameters = new QueryParameters();
            var sql = ExpressionResolver.Resolve(_queryBody, exp, parameters);

            replacedert.Equal("T1.[Id] IN (10,15)", sql);
        }

19 View Source File : YmlFormatUtil.cs
License : Apache License 2.0
Project Creator : 214175590

public static List<YmlLine> FormatYml(string content, bool beautify = false)
        {
            List<YmlLine> list = new List<YmlLine>();
            string[] lines = content.Split('\n');
            YmlLine ylText = null;
            int index1 = -1, index2 = -1, count = 0, num = 0;
            string startStr = null, endStr = null, line = "";
            string key = null, value = null, mh = ":";
            List<int> levels = new List<int>();
            for(int i = 0, k = lines.Length; i < k; i++){
                line = lines[i];

                if(line.TrimStart().StartsWith("#")){
                    ylText = new YmlLine()
                    {
                        Text = line + "\n",
                        Color = Color.Gray
                    };
                    list.Add(ylText);
                }
                else
                {
                    // 非整行注释

                    // 美化
                    if (beautify)
                    {
                        count = StartSpaceCount(line);
                        if (count == 0)
                        {
                            levels.Clear();
                        }
                        // level
                        if (!levels.Contains(count))
                        {
                            levels.Add(count);
                            levels.Sort();
                        }
                        num = levels.IndexOf(count) * 4;
                        if (num > count)
                        {
                            line = GetSpace(num - count) + line;
                        }
                    }                    

                    // 行中有井号,但不是首位#
                    index2 = line.IndexOf("#");
                    if(index2 > 0){
                        startStr = line.Substring(0, index2);

                        index1 = startStr.IndexOf(":");
                        if (index1 > 0)
                        {
                            // key
                            key = startStr.Substring(0, index1);
                            ylText = new YmlLine()
                            {
                                Text = key,
                                Color = Color.OrangeRed
                            };
                            list.Add(ylText);
                            // :
                            ylText = new YmlLine()
                            {
                                Text = mh,
                                Color = Color.Violet
                            };
                            list.Add(ylText);
                            // value
                            value = startStr.Substring(index1 + 1);
                            ylText = new YmlLine()
                            {
                                Text = value,
                                Color = getTextColor(value)
                            };
                            list.Add(ylText);
                        }
                        else
                        {
                            ylText = new YmlLine()
                            {
                                Text = "#" + startStr,
                                Color = Color.Gray
                            };
                            list.Add(ylText);
                        }

                        // 注释掉的部分
                        endStr = line.Substring(index2);
                        ylText = new YmlLine()
                        {
                            Text = endStr + "\n",
                            Color = Color.Gray
                        };
                        list.Add(ylText);
                    }
                    else
                    {
                        // 行中无井号
                        startStr = line;

                        index1 = startStr.IndexOf(":");
                        if (index1 > 0)
                        {
                            // key
                            key = startStr.Substring(0, index1);
                            ylText = new YmlLine()
                            {
                                Text = key,
                                Color = Color.OrangeRed
                            };
                            list.Add(ylText);
                            // :
                            ylText = new YmlLine()
                            {
                                Text = mh,
                                Color = Color.Violet
                            };
                            list.Add(ylText);
                            // value
                            value = startStr.Substring(index1 + 1);
                            ylText = new YmlLine()
                            {
                                Text = value + "\n",
                                Color = getTextColor(value)
                            };
                            list.Add(ylText);
                        }
                        else
                        {
                            // 行中无井号,且是不合规的配置值
                            if (string.IsNullOrWhiteSpace(line))
                            {
                                ylText = new YmlLine()
                                {
                                    Text = line + "\n",
                                    Color = Color.OrangeRed
                                };
                            }
                            else
                            {
                                ylText = new YmlLine()
                                {
                                    Text = "#" + line + "\n",
                                    Color = Color.Gray
                                };
                            }                            
                            list.Add(ylText);                            
                        }
                    }
                }
            }
            return list;
        }

19 View Source File : LandLord.cs
License : Apache License 2.0
Project Creator : 2881099

public void SearchBomb()
        {
            ////if (_two.Contains((int)LordPokerValueNoColorEnum.p3)) _bomb33.Add((int)LordPokerValueNoColorEnum.p3);
            ////if (_two.Contains((int)LordPokerValueNoColorEnum.p15)) _bomb22.Add((int)LordPokerValueNoColorEnum.p15);
            if (_one.Contains((int)LordPokerValueNoColorEnum.jokers16) && _one.Contains((int)LordPokerValueNoColorEnum.jokersb17))
            {
                _doubleKing.Add((int)LordPokerValueNoColorEnum.jokers16);
                _doubleKing.Add((int)LordPokerValueNoColorEnum.jokersb17);
            }
            _bomb4List = new List<int>(_four);
        }

19 View Source File : LandLord.cs
License : Apache License 2.0
Project Creator : 2881099

public void Search123()
        {
            _single = new List<int>(_one);
            _double = new List<int>(_two);
            if (_double.Contains((int)LordPokerValueNoColorEnum.p3)) _double.Remove((int)LordPokerValueNoColorEnum.p3);
            if (_double.Contains((int)LordPokerValueNoColorEnum.p15)) _double.Remove((int)LordPokerValueNoColorEnum.p15);
            _threeList = new List<int>(_three);
        }

19 View Source File : LandLord.cs
License : Apache License 2.0
Project Creator : 2881099

public void SearchLinkerPair()
        {
            if (_shouPai.Count < 6) return;//不足6个牌就不处理的
            List<int> _temptwo = new List<int>(_two);
            if (_temptwo.Contains((int)LordPokerValueNoColorEnum.p15)) _temptwo.Remove((int)LordPokerValueNoColorEnum.p15);    // ,2 不能组成连子   
            if (_temptwo.Count < 3) return;//不足6个牌就不处理的

            List<int> _minLinker = new List<int>();
            for (int i = 0; i < _temptwo.Count - 1; i++)
            {
                if (_temptwo[i] - 1 == _temptwo[i + 1])
                {
                    _minLinker.Add(_temptwo[i]);
                    if (i + 1 == _temptwo.Count - 1) _minLinker.Add(_temptwo[i + 1]);//最后一个要加上
                }
                else
                {//可能会出现刚才好3个,而后还有牌,搜索不到
                    _minLinker.Add(_temptwo[i]);
                    if (_minLinker.Count >= 3) _linkerPair.Add(_minLinker);
                    _minLinker = new List<int>();
                }
            }
            if (_minLinker.Count >= 3) _linkerPair.Add(_minLinker);
        }

19 View Source File : LandLord.cs
License : Apache License 2.0
Project Creator : 2881099

public void SearchStraight()
        {
            if (_shouPai.Count < 5) return;//不足5个牌就不处理的
            List<int> _tempone = new List<int>(_one);
            if (_tempone.Contains((int)LordPokerValueNoColorEnum.p15)) _tempone.Remove((int)LordPokerValueNoColorEnum.p15);    // ,2,小王,大王 不能组成连子
            if (_tempone.Contains((int)LordPokerValueNoColorEnum.jokers16)) _tempone.Remove((int)LordPokerValueNoColorEnum.jokers16);
            if (_tempone.Contains((int)LordPokerValueNoColorEnum.jokersb17)) _tempone.Remove((int)LordPokerValueNoColorEnum.jokersb17);
            if (_tempone.Count < 5) return;//不足5个牌就不处理的
            List<int> _minStraight = new List<int>();
            for (int i = 0; i < _tempone.Count - 1; i++)
            {
                if (_tempone[i] - 1 == _tempone[i + 1])
                {
                    _minStraight.Add(_tempone[i]);
                    if (i + 1 == _tempone.Count - 1) _minStraight.Add(_tempone[i + 1]);//最后一个要加上
                }
                else
                {//可能会出现刚才好5个,而后还有牌,搜索不到
                    _minStraight.Add(_tempone[i]);
                    if (_minStraight.Count >= 5) _straight.Add(_minStraight);
                    _minStraight = new List<int>();
                }
            }
            if (_minStraight.Count >= 5) _straight.Add(_minStraight);//最后一组必须加进去 不然一个长连子没搜索到
        }

19 View Source File : LandLord.cs
License : Apache License 2.0
Project Creator : 2881099

public static List<int> GetPaiColor(List<int> _shoupai, List<int> pokervalue)
        {
            List<int> _ASCList = new List<int>(pokervalue);
            //带上花色,有点小复杂 
            Dictionary<int, int> _dicPoker2Count = GetPoker_Count(_ASCList);
            Dictionary<int, int> _dicPoker2CountUsed = new Dictionary<int, int>();
            for (int j = 0; j < _ASCList.Count; j++)
            {
                if (!_dicPoker2CountUsed.ContainsKey(_ASCList[j])) _dicPoker2CountUsed.Add(_ASCList[j], 1);

                for (int c = _dicPoker2CountUsed[_ASCList[j]]; c <= 4; c++)
                {
                    _dicPoker2CountUsed[_ASCList[j]]++;
                    if (_shoupai.Contains(_ASCList[j] + 100 * c))
                    {
                        _ASCList[j] = _ASCList[j] + 100 * c;
                        break;
                    }
                }
            }
            return _ASCList;
        }

19 View Source File : LandLord.cs
License : Apache License 2.0
Project Creator : 2881099

public static List<int> OrderPaiLordWithColor(List<int> paiarr)
        {
            List<int> _tempList = new List<int>(paiarr);
            for (int i = 0; i < _tempList.Count; i++)
            {
                if (_tempList[i] > 100) _tempList[i] %= 100;
            }
            int[] temparr = _tempList.ToArray<int>();
            Array.Sort<int>(temparr);
            List<int> _ASCList = temparr.ToList<int>();
            _ASCList.Reverse();//默认是升序反转一下就降序了

            //带上花色,有点小复杂 
            Dictionary<int, int> _dicPoker2Count = GetPoker_Count(_ASCList);
            Dictionary<int, int> _dicPoker2CountUsed = new Dictionary<int, int>();
            for (int j = 0; j < _ASCList.Count; j++)
            {
                if (!_dicPoker2CountUsed.ContainsKey(_ASCList[j])) _dicPoker2CountUsed.Add(_ASCList[j], 1);

                for (int c = _dicPoker2CountUsed[_ASCList[j]]; c <= 4; c++)
                {
                    _dicPoker2CountUsed[_ASCList[j]]++;
                    if (paiarr.Contains(_ASCList[j] + 100 * c))
                    {
                        _ASCList[j] = _ASCList[j] + 100 * c;
                        break;
                    }
                }
            }
            return _ASCList;
        }

19 View Source File : LandLord.cs
License : Apache License 2.0
Project Creator : 2881099

public int GetSingleToPlaneWith(List<int> planeList, List<int> _existonelist)
        {
            if (_single.Count == 0) return -1;
            int _tempSingle = 0;
            for (int i = _single.Count - 1; i >= 0; i--)
            {//不能是三带一中的牌 
                if (_single[i] == (int)LordPokerValueNoColorEnum.p15) continue;//2不带用于三带1 只有最后一个手三带一可以用 
                if (_single[i] == (int)LordPokerValueNoColorEnum.jokers16 || _single[i] == (int)LordPokerValueNoColorEnum.jokersb17)
                {
                    continue;//王不带用于三带1 只有最后一个手三带一可以用
                }
                bool _issametoPlane = false;
                foreach (int plane in planeList)
                {
                    if (plane == _single[i]) _issametoPlane = true;
                }
                if (_issametoPlane) continue;
                _tempSingle = _single[i];
                if (_existonelist.Contains(_tempSingle))
                {
                    _tempSingle = -1;
                    continue;
                }
                break;
            }
            return _tempSingle;
        }

19 View Source File : IdUtil.cs
License : MIT License
Project Creator : 404Lcc

public static int Generate()
        {
            if (countList.Count == 0)
            {
                id++;
                return id;
            }
            for (int i = 1; i <= countList.Count; i++)
            {
                if (!countList.Contains(i))
                {
                    return i;
                }
            }
            id++;
            return id;
        }

19 View Source File : PersonAppServices.cs
License : MIT License
Project Creator : 52ABP

[AbpAuthorize(PersonAppPermissions.Person_BatchDeletePersons)]
        public async Task BatchDeletePersonsAsync(List<int> input)
        {
            //TODO:批量删除前的逻辑判断,是否允许删除
            await _personRepository.DeleteAsync(s => input.Contains(s.Id));
        }

19 View Source File : NpcCommandHandler.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826

private bool CheckField(PlayerEnreplacedy player, string field, string strValue, string strRelation)
        {
            try
            {
                var relations = GetRelations(strRelation);// 1 大于,0 等于 ,-1 小于

                var fieldProp = GetFieldPropertyInfo(player, field);
                if (fieldProp == null)
                {
                    return false;
                }

                var objectValue = fieldProp.GetValue(player);
                var typeCode = Type.GetTypeCode(fieldProp.GetType());
                switch (typeCode)
                {
                    case TypeCode.Int32:
                        return relations.Contains(Convert.ToInt32(strValue).CompareTo(Convert.ToInt32(objectValue)));

                    case TypeCode.Int64:
                        return relations.Contains(Convert.ToInt64(strValue).CompareTo(Convert.ToInt64(objectValue)));

                    case TypeCode.Decimal:
                        return relations.Contains(Convert.ToDecimal(strValue).CompareTo(Convert.ToDecimal(objectValue)));

                    case TypeCode.Double:
                        return relations.Contains(Convert.ToDouble(strValue).CompareTo(Convert.ToDouble(objectValue)));

                    case TypeCode.Boolean:
                        return relations.Contains(Convert.ToBoolean(strValue).CompareTo(Convert.ToBoolean(objectValue)));

                    case TypeCode.DateTime:
                        return relations.Contains(Convert.ToDateTime(strValue).CompareTo(Convert.ToDateTime(objectValue)));

                    case TypeCode.String:
                        return relations.Contains(strValue.CompareTo(objectValue));

                    default:
                        throw new Exception($"不支持的数据类型: {typeCode}");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError($"CheckField Exception:{ex}");
                return false;
            }
        }

19 View Source File : NpcCommandHandler.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826

private async Task<bool> CheckWare(int playerId, string wareName, string number, string strRelation)
        {
            if (!int.TryParse(number, out int numberValue))
            {
                return false;
            }

            var ware = await _wareDomainService.Get(x => x.Name == wareName);
            if (ware == null)
            {
                return false;
            }

            var playerWare = await _playerWareDomainService.Get(x => x.WareId == ware.Id && x.PlayerId == playerId);
            if (playerWare == null)
            {
                return false;
            }

            var relations = GetRelations(strRelation);
            return relations.Contains(playerWare.Number.CompareTo(numberValue));
        }

19 View Source File : NpcAppService.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826

public async Task<ResultDto> Update(int id, NpcInput item, List<int> scriptIds)
        {
            var result = new ResultDto { Message = "" };
            try
            {
                var npc = await _npcDomainService.Get(id);
                if (npc == null)
                {
                    result.Message = $"Npc {id} 不存在!";
                    return result;
                }
                var content = npc.ComparisonTo(item);
                _mapper.Map(item, npc);


                await _npcDomainService.Update(npc);

                var npcScripts = (await _npcScriptDomainService.GetAll()).Where(x => x.NpcId == id);
                foreach (var npcScript in npcScripts)
                {
                    if (!scriptIds.Contains(npcScript.ScriptId))
                    {
                        await _npcScriptDomainService.Delete(npcScript);
                    }
                    else
                    {
                        scriptIds.Remove(npcScript.ScriptId);
                    }
                }


                foreach (var scriptId in scriptIds)
                {
                    await _npcScriptDomainService.Add(new NpcScriptEnreplacedy { NpcId = id, ScriptId = scriptId });
                }


                await _operatorLogDomainService.AddSuccess(new OperatorLogEnreplacedy
                {
                    Type = OperatorLogType.修改Npc,
                    Content = $"Id = {id},Data = {content}"
                });

                await Commit();

                result.IsSuccess = true;
            }
            catch (Exception ex)
            {
                result.Message = ex.Message;
                await _operatorLogDomainService.AddError(new OperatorLogEnreplacedy
                {
                    Type = OperatorLogType.修改Npc,
                    Content = $"Data={JsonConvert.SerializeObject(item)},ErrorMessage={result.Message}"
                });
                await Commit();
            }
            return result;
        }

19 View Source File : NpcAppService.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826

public async Task<Dictionary<int, List<ScriptEnreplacedy>>> GetScripts(List<int> ids)
        {
            var dic = new Dictionary<int, List<ScriptEnreplacedy>>();

            var queryNpcScript = await _npcScriptDomainService.GetAll();
            var npcScripts = queryNpcScript.Where(x => ids.Contains(x.NpcId)).ToList();

            var scriptIds = npcScripts.Select(x => x.ScriptId);

            var queryScript = await _scriptDomainService.GetAll();
            var scripts = queryScript.Where(x => scriptIds.Contains(x.Id)).ToList();

            foreach (var id in ids)
            {
                scriptIds = npcScripts.Where(x => x.NpcId == id).Select(x => x.ScriptId);
                var myScripts = scripts.Where(x => scriptIds.Contains(x.Id)).ToList();

                dic.TryAdd(id, myScripts);
            }

            return dic;
        }

19 View Source File : DynamicDNAConverterBehaviourEditor.cs
License : Apache License 2.0
Project Creator : A7ocin

public override void OnInspectorGUI()
		{
			serializedObject.Update();
			if (!initialized)
				this.Init();

			//Style for Tips
			var foldoutTipStyle = new GUIStyle(EditorStyles.foldout);
			foldoutTipStyle.fontStyle = FontStyle.Bold;
			//DISPLAY VALUE
			EditorGUILayout.PropertyField(serializedObject.FindProperty("DisplayValue"));
			//
			//=============DNA replacedET AND EDITOR============//
			SerializedProperty dnareplacedet = serializedObject.FindProperty("dnareplacedet");
			dnareplacedet.isExpanded = EditorGUILayout.Foldout(dnareplacedet.isExpanded, "Dynamic DNA", foldoutTipStyle);
			if (dnareplacedet.isExpanded)
			{
				GUIHelper.BeginVerticalPadded(3, new Color(0.75f, 0.875f, 1f, 0.3f));
				EditorGUI.indentLevel++;
				dnareplacedetInfoExpanded = EditorGUILayout.Foldout(dnareplacedetInfoExpanded, "INFO");
				if (dnareplacedetInfoExpanded)
					EditorGUILayout.HelpBox("The DynmicDNAreplacedet is the DNA this converter will apply to the skeleton. The DNA consists of names and replacedociated values. Often you display these names as 'sliders'. The values set by these sliders change an Avatar's body proportions by modifying its skeleton bones by the dna value, according to the 'DNA Converter Settings' you set in the 'DNA Converter Settings' section.", MessageType.Info);
				
				if(dnareplacedet.objectReferenceValue == null)
				{
					//show a tip that people need to create or replacedign a dna replacedet
					EditorGUILayout.HelpBox("Create or replacedign a DNA replacedet this converter will use", MessageType.Info);
				}
				EditorGUI.BeginChangeCheck();
				EditorGUILayout.PropertyField(dnareplacedet, new GUIContent("DNA replacedet", "A DynamireplacedADnareplacedet contains a list of names that define the 'DNA' that will be used to modify the Avatars Skeleton. Often displayed in the UI as 'sliders'"));
				if (EditorGUI.EndChangeCheck())
				{
					UpdateDnaNames();
					serializedObject.ApplyModifiedProperties();
					serializedObject.Update();//?
					if (minimalMode)
					{
						//force the Avatar to update its dna and dnaconverter dictionaries
						umaData.umaRecipe.ClearDna();
						umaData.umaRecipe.ClearDNAConverters();
					}
				}
				//If there is no dna replacedet replacedigned show a button to make one
				if (dnareplacedet.objectReferenceValue == null)
				{
					GUILayout.BeginHorizontal();
					GUILayout.Space(EditorGUI.indentLevel * 15);
					if (GUILayout.Button(new GUIContent("Create Dynamic DNA replacedet")))
					{
						var suggestedPath = replacedetDatabase.GetreplacedetPath(target);
						var suggestedName = target.name + "DNAreplacedet";
						var path = EditorUtility.SaveFilePanelInProject("Create a new Dynamic DNA replacedet", suggestedName, "replacedet", "some message", suggestedPath);
						if (path != "")
						{
							var newDnareplacedet = CustomreplacedetUtility.Createreplacedet<DynamireplacedADnareplacedet>(path, false);
							if (newDnareplacedet != null)
							{
								//set this replacedet as the used replacedet
								dnareplacedet.objectReferenceValue = newDnareplacedet;
								serializedObject.ApplyModifiedProperties();
								createDnareplacedetName = "";
							}
							UpdateDnaNames();
							if (minimalMode)
							{
								//force the Avatar to update its dna and dnaconverter dictionaries
								umaData.umaRecipe.ClearDna();
								umaData.umaRecipe.ClearDNAConverters();
							}
						}
					}
					GUILayout.EndHorizontal();
				}
				//Otherwise show the DNA replacedets Editor
				else
				{
					if (thisDUDA == null)
					{
						thisDUDA = Editor.CreateEditor((DynamireplacedADnareplacedet)dnareplacedet.objectReferenceValue, typeof(UMA.CharacterSystem.Editors.DynamireplacedADnareplacedetEditor));
					}
					else if (thisDUDA.target != (DynamireplacedADnareplacedet)dnareplacedet.objectReferenceValue)
					{
						thisDUDA = Editor.CreateEditor((DynamireplacedADnareplacedet)dnareplacedet.objectReferenceValue, typeof(UMA.CharacterSystem.Editors.DynamireplacedADnareplacedetEditor));
					}
					EditorGUI.BeginChangeCheck();
					thisDUDA.OnInspectorGUI();
					if (EditorGUI.EndChangeCheck())
					{
						UpdateDnaNames();
					}
				}
				EditorGUI.indentLevel--;
				GUIHelper.EndVerticalPadded(3);
			}
			serializedObject.ApplyModifiedProperties();
			//===========END DNA replacedET AND EDITOR============//
			//
			EditorGUILayout.Space();
			//
			//=============CONVERTER VALUES AND EDITOR=============//
			SerializedProperty hashList = serializedObject.FindProperty("hashList");
			SerializedProperty skeletonModifiers = serializedObject.FindProperty("skeletonModifiers");
			string converterTips = "";
			if (minimalMode)
			{
				converterTips = "Skeleton Modifiers control how the values of the DNA you set above are applied to the skeleton. So for example 'Upper Weight' affects the scale of the Spine, breast, belly and shoulder bones in different ways. The best way to edit these modifiers is to set the DNA slider you want to adjust in the game view, to either its minimum or maximum position. Then add or edit a skeleton modifier in the list below to use that value to modify the skeleton. The 'Value Modifiers' part of a Skeleton Modifier, takes the incoming value, modifies it by the settings and applies it to the bone. The Min and Max values are what that result will be 'clamped' to. Avoid changing the starting 'Value' as changes to this will persist even if the dna is not itself applied (if you want to do this use the starting pose below instead).";
			}
			else
			{
				converterTips = "Skeleton Modifiers control how the values of the DNA you set above are applied to the skeleton.  So for example 'Upper Weight' affects the scale of the Spine, breast, belly and shoulder bones in different ways. Add bones you wish to make available to modify in the 'BoneHashes' section. Then add or edit a skeleton modifier in the list below to use a given dna value to modify the skeleton. The 'Value Modifiers' part of a Skeleton Modifier, takes the incoming value, modifies it by the settings and applies it to the bone. The Min and Max values are what that result will be 'clamped' to. Avoid changing the starting 'Value' as changes to this will persist even if the dna is not itself applied (if you want to do this use the starting pose below instead).";
			}
			skeletonModifiersExpanded = EditorGUILayout.Foldout(skeletonModifiersExpanded, "DNA Converter Settings", foldoutTipStyle);
			if (skeletonModifiersExpanded)
			{
				GUIHelper.BeginVerticalPadded(3, new Color(0.75f, 0.875f, 1f, 0.3f));
				if (!minimalMode)
				{
					EditorGUILayout.HelpBox("TIP: Setting up your DNA Converter's Skeleton Modifiers is much easier if you use the 'DNA Converter Bahaviour Customizer' scene as it can automatically populate the list of available bones with the ones in the generated Avatar's skeleton.", MessageType.Info);
				}
				EditorGUI.indentLevel++;
				skeletonModifiersInfoExpanded = EditorGUILayout.Foldout(skeletonModifiersInfoExpanded, "INFO");
				if (skeletonModifiersInfoExpanded)
					EditorGUILayout.HelpBox(converterTips, MessageType.Info);
				if (!minimalMode)//in minimal mode we dont need to show these because we will have a skeleton that we can get the bonehash list from
				{
					int hashListCount = hashList.arraySize;
					hashList.isExpanded = EditorGUILayout.Foldout(hashList.isExpanded, new GUIContent("Bone Hashes", "These are the bones you have identified that the converter will work on. If you use the Dynamic DNA Customizer Scene these can be set automatically when you add Modifiers") );
					if (hashList.isExpanded)
					{
						EditorGUI.indentLevel++;
						extraBonesAddDelOptsExpanded = EditorGUILayout.Foldout(extraBonesAddDelOptsExpanded, "Add/Delete Bones Options");
						EditorGUI.indentLevel--;
						if (extraBonesAddDelOptsExpanded)
						{
							//make a drop area for importing bone hashes from another DynamicDnaConverter
							var dropArea = GUILayoutUtility.GetRect(0.0f, 60.0f, GUILayout.ExpandWidth(true));
							dropArea.xMin = dropArea.xMin + (EditorGUI.indentLevel * 15);
							GUI.Box(dropArea, "Drag DynamicDNAConverterBahaviours here to import their names");//cant click to pick unfortunately because this is a prefab
							var AddMethods = new GUIContent[dnaNamesAddOpts.Count];
							for (int i = 0; i < dnaNamesAddOpts.Count; i++)
								AddMethods[i] = new GUIContent(dnaNamesAddOpts[i]);
							Rect selectedAddMethodRect = dropArea;
							selectedAddMethodRect.yMin = dropArea.yMax - EditorGUIUtility.singleLineHeight - 5;
							selectedAddMethodRect.xMin = dropArea.xMin - ((EditorGUI.indentLevel * 10) - 10);
							selectedAddMethodRect.xMax = dropArea.xMax - ((EditorGUI.indentLevel * 10) + 10);
							selectedBonesAddMethod = EditorGUI.Popup(selectedAddMethodRect, new GUIContent("On Import", "Choose whether to 'Add' the bones to the current list, or 'Replace' them with the imported  ones"), selectedBonesAddMethod, AddMethods);

							ImportConverterDropArea(dropArea, selectedBonesAddMethod, AddDNAConverterHashes);

							EditorGUILayout.Space();

							//Clear all and Add Defaults Buttons
							Rect clearAndDefaultsRect = GUILayoutUtility.GetRect(0.0f, EditorGUIUtility.singleLineHeight, GUILayout.ExpandWidth(true));
							clearAndDefaultsRect.xMin = clearAndDefaultsRect.xMin + (EditorGUI.indentLevel * 15);
							var defaultsButRect = clearAndDefaultsRect;
							var clearButRect = clearAndDefaultsRect;
							defaultsButRect.width = clearAndDefaultsRect.width / 2;
							clearButRect.xMin = defaultsButRect.xMax;
							clearButRect.width = clearAndDefaultsRect.width / 2;
							if (GUI.Button(defaultsButRect, new GUIContent("Add Default Hashes", "Adds the default bone hashes as used by UMA Human Male DNA")))
							{
								AddDefaultBoneHashes();
								//once we add these we need to update the hashnames so the dropdown has the right stuff in
								hashList.serializedObject.ApplyModifiedProperties();
								serializedObject.Update();
								UpdateHashNames();
							}
							EditorGUI.BeginDisabledGroup(hashList.arraySize == 0);
							if (GUI.Button(clearButRect, new GUIContent("Clear All Bone Hashes", "Clears the current Bone Hashes. Cannot be undone.")))
							{
								bool proceed = true;
								//if there are any skeleton modifiers that are using these bone hashes warn the user that clearing this list will break them
								if (skeletonModifiers.arraySize > 0)
									proceed = EditorUtility.DisplayDialog("Really Clear All Bone Hashes?", "This will delete all the bone hashes in the list and make any skeleton modifiers you have added not work. Are you sure?", "Yes", "Cancel");
								if (proceed)
								{
									(target as DynamicDNAConverterBehaviour).hashList = new List<DynamicDNAConverterBehaviour.HashLisreplacedem>();
									hashList.serializedObject.ApplyModifiedProperties();
									serializedObject.Update();
									UpdateHashNames();
								}
							}
							EditorGUI.EndDisabledGroup();
							EditorGUILayout.Space();
						}
						//create an add field for adding new hashes
						EditorGUILayout.BeginHorizontal();
						//var buttonDisabled = newHashName == "";
						bool canAdd = true;
						bool notFoundInSkeleton = false;
						bool didAdd = false;
						EditorGUI.BeginChangeCheck();
						newHashName = EditorGUILayout.TextField(newHashName);
						if (EditorGUI.EndChangeCheck())
						{
							if (newHashName != "" && canAdd)
							{
								//buttonDisabled = false;
							}
						}
						if (newHashName != "")
						{
							for (int ni = 0; ni < hashList.arraySize; ni++)
							{
								if (hashList.GetArrayElementAtIndex(ni).FindPropertyRelative("hashName").stringValue == newHashName)
								{
									canAdd = false;
									//buttonDisabled = true;
								}
							}
							//if we have a skeleton available we can also check that the bone the user is trying to add exists
							if (umaData)
								if (umaData.skeleton != null)
								{
									if (umaData.skeleton.HasBone(UMAUtils.StringToHash(newHashName)) == false)
									{
										canAdd = false;
										//buttonDisabled = true;
										notFoundInSkeleton = true;
									}
								}
						}
						//Dont disable because it stops looking like what you want to do, just make it do nothing if nothing is entered
						/*if (buttonDisabled)
						{
							EditorGUI.BeginDisabledGroup(true);
						}*/

						if (GUILayout.Button("Add Bone Hash"))
						{
							if (canAdd)
							{
								var newHash = UMAUtils.StringToHash(newHashName);
								(target as DynamicDNAConverterBehaviour).hashList.Insert(0, new DynamicDNAConverterBehaviour.HashLisreplacedem(newHashName, newHash));
								hashList.serializedObject.ApplyModifiedProperties();
								serializedObject.Update();
								didAdd = true;
								UpdateHashNames();
								//reset the bloody text field!
								EditorGUIUtility.keyboardControl = 0;
							}
						}
						/*if (buttonDisabled)
						{
							EditorGUI.EndDisabledGroup();
						}*/
						EditorGUILayout.EndHorizontal();
						if (canAdd == false)
						{
							if (notFoundInSkeleton == true)
							{
								EditorGUILayout.HelpBox("That name was not found in the skeleton. (Standard Bone names start with a capital letter in CamelCase)", MessageType.Warning);
							}
							else
							{
								EditorGUILayout.HelpBox("That name is already in use.", MessageType.Warning);
							}
						}
						if (didAdd)
						{
							newHashName = "";
						}

						//THE ACTUAL BONE HASH LIST
						GUIHelper.BeginVerticalPadded(3, new Color(0.75f, 0.875f, 1f, 0.3f));
						EditorGUILayout.LabelField("Bone Hash List (" + hashListCount + ")", EditorStyles.helpBox);
						//Search Bone Hashes Controls
						if (hashList.arraySize > 0)
							boneHashFilter = EditorGUILayout.TextField("Search Bones", boneHashFilter);
						EditorGUI.indentLevel++;
						if (hashList.arraySize > 0)
						{
							for (int i = 0; i < hashList.arraySize; i++)
							{
								var thisHashEl = hashList.GetArrayElementAtIndex(i);
								//Search Bone Hashes Method
								if (boneHashFilter.Length >= 3)
								{
									if (thisHashEl.displayName.IndexOf(boneHashFilter, StringComparison.CurrentCultureIgnoreCase) == -1)
										continue;
								}
								EditorGUILayout.BeginHorizontal();
								thisHashEl.isExpanded = EditorGUILayout.Foldout(thisHashEl.isExpanded, thisHashEl.displayName);
								//DeleteButton
								Rect hDelButR = EditorGUILayout.GetControlRect(false);
								hDelButR.x = hDelButR.x + hDelButR.width - 100f;
								hDelButR.width = 100f;
								if (GUI.Button(hDelButR, "Delete"))
								{
									hashList.DeleteArrayElementAtIndex(i);
									continue;
								}
								EditorGUILayout.EndHorizontal();
								if (thisHashEl.isExpanded)
								{
									EditorGUI.indentLevel++;
									string origName = thisHashEl.FindPropertyRelative("hashName").stringValue;
									string newName = origName;
									EditorGUI.BeginChangeCheck();
									newName = EditorGUILayout.TextField("Hash Name", origName);
									if (EditorGUI.EndChangeCheck())
									{
										if (newName != origName && newName != "")
										{
											thisHashEl.FindPropertyRelative("hashName").stringValue = newName;
											int newHash = UMAUtils.StringToHash(newName);
											thisHashEl.FindPropertyRelative("hash").intValue = newHash;
											serializedObject.ApplyModifiedProperties();
										}
									}
									EditorGUI.BeginDisabledGroup(true);
									EditorGUILayout.IntField("Hash", thisHashEl.FindPropertyRelative("hash").intValue);
									EditorGUI.EndDisabledGroup();
									EditorGUI.indentLevel--;
								}
							}
							hashList.serializedObject.ApplyModifiedProperties();
							EditorGUILayout.Space();
						}	
						EditorGUI.indentLevel--;
						GUIHelper.EndVerticalPadded(3);
					}
				}
				//SKELETON MODIFIERS SECTION
				skeletonModifiers.isExpanded = EditorGUILayout.Foldout(skeletonModifiers.isExpanded, "Skeleton Modifiers");
				if (skeletonModifiers.isExpanded)
				{
					//If dnaNames is null or empty show a warning
					bool showDNANamesWarning = false;
					if (serializedObject.FindProperty("dnareplacedet").objectReferenceValue == null)
						showDNANamesWarning = true;
					else if((serializedObject.FindProperty("dnareplacedet").objectReferenceValue as DynamireplacedADnareplacedet).Names.Length == 0)
						showDNANamesWarning = true;
					if(showDNANamesWarning)
						EditorGUILayout.HelpBox("You need to have your DNA Names set up above in order for the Skeleton Modifiers to make any modifications", MessageType.Warning);
					//If bone hashes is empty show a warning
					if(hashList.arraySize == 0 && !minimalMode)
						EditorGUILayout.HelpBox("You need to add the bones you want the Skeleton Modifiers to be able to modify to the 'Bone Hashes' section above.", MessageType.Warning);

					EditorGUI.indentLevel++;
					extraSkelAddDelOptsExpanded = EditorGUILayout.Foldout(extraSkelAddDelOptsExpanded, "Add/Delete Modifier Options");
					EditorGUI.indentLevel--;
					if (extraSkelAddDelOptsExpanded)
					{
						//make a drop area for importing skeletonModifiers from another DynamicDnaConverter
						var dropArea = GUILayoutUtility.GetRect(0.0f, 60.0f, GUILayout.ExpandWidth(true));
						dropArea.xMin = dropArea.xMin + (EditorGUI.indentLevel * 15);
						GUI.Box(dropArea, "Drag DynamicDNAConverterBahaviours here to import their Skeleton Modifiers");//cant click to pick unfortunately because this is a prefab
						var AddMethods = new GUIContent[dnaNamesAddOpts.Count];
						for (int i = 0; i < dnaNamesAddOpts.Count; i++)
							AddMethods[i] = new GUIContent(dnaNamesAddOpts[i]);
						Rect selectedAddMethodRect = dropArea;
						selectedAddMethodRect.yMin = dropArea.yMax - EditorGUIUtility.singleLineHeight - 5;
						selectedAddMethodRect.xMin = dropArea.xMin - ((EditorGUI.indentLevel * 10) - 10);
						selectedAddMethodRect.xMax = dropArea.xMax - ((EditorGUI.indentLevel * 10) + 10);
						selectedModifiersAddMethod = EditorGUI.Popup(selectedAddMethodRect, new GUIContent("On Import", "Choose whether to 'Add' the modifiers to the current list, or 'Replace' the modifiers with the imported list"), selectedModifiersAddMethod, AddMethods);

						ImportConverterDropArea(dropArea, selectedModifiersAddMethod, AddDNAConverterModifiers);

						//Clear all button
						GUILayout.BeginHorizontal();
						GUILayout.Space(EditorGUI.indentLevel * 15);
						EditorGUI.BeginDisabledGroup(skeletonModifiers.arraySize == 0);
						if (GUILayout.Button("Clear All Modifiers"))
						{
							if (EditorUtility.DisplayDialog("Really Clear All Modifiers?", "This will delete all the skeleton modifiers in the list and cannot be undone. Are you sure?", "Yes", "Cancel"))
							{
								(target as DynamicDNAConverterBehaviour).skeletonModifiers = new List<DynamicDNAConverterBehaviour.SkeletonModifier>();
								skeletonModifiers.serializedObject.ApplyModifiedProperties();
								serializedObject.Update();
							}
						}
						EditorGUI.EndDisabledGroup();
						GUILayout.EndHorizontal();
						EditorGUILayout.Space();
					}


					//Add new Skeleton Modifier UI
					Rect addSkelButsR = EditorGUILayout.GetControlRect(false);
					var addSkelLabel = addSkelButsR;
					var addSkelBone = addSkelButsR;
					var addSkelProp = addSkelButsR;
					var addSkelAddBut = addSkelButsR;
					addSkelLabel.width = 100;
					addSkelAddBut.width = 70;
					addSkelBone.width = addSkelProp.width = (addSkelButsR.width - (addSkelLabel.width + (addSkelAddBut.width + 5))) / 2;
					addSkelBone.x = addSkelLabel.xMax;
					addSkelProp.x = addSkelBone.xMax;
					addSkelAddBut.x = addSkelProp.xMax + 5;
					EditorGUI.LabelField(addSkelLabel, new GUIContent("Add Modifier", "Add a modifier for the selected bone in the skeleton, that will modify its 'Position', 'Rotation' or 'Scale'"));
					EditorGUI.indentLevel--;
					List<string> thisBoneNames = new List<string>(0);
					//string[] boneNames = new string[0];
					/*if(minimalMode == false)
					{
						bonesInSkeleton = new List<string>( hashNames.ToArray());
					}
					else
					{
						bonesInSkeleton = new List<string>(umaData.skeleton.BoneNames);
					}
					bonesInSkeleton.Sort();*/
					//Array.Sort(boneNames);
					thisBoneNames = new List<string>(bonesInSkeleton);
					thisBoneNames.Insert(0, "Choose Bone");

					EditorGUI.BeginChangeCheck();
					selectedAddHash = EditorGUI.Popup(addSkelBone, selectedAddHash, thisBoneNames.ToArray());
					string[] propertyArray = new string[] { "Position", "Rotation", "Scale" };
					selectedAddProp = EditorGUI.Popup(addSkelProp, selectedAddProp, propertyArray);
					if (EditorGUI.EndChangeCheck())
					{
						if (selectedAddHash > 0)
						{
							addSkelBoneName = thisBoneNames[selectedAddHash];
							addSkelBoneHash = UMAUtils.StringToHash(addSkelBoneName);
						}
						else
						{
							addSkelBoneName = "";
							addSkelBoneHash = 0;
							canAddSkel = false;
						}
					}
					if (addSkelBoneName != "" && addSkelBoneHash != 0)
					{
						canAddSkel = true;
						alreadyExistedSkel = false;
						//we need to check if there is already a modifier for that bone for the selected property
						for (int i = 0; i < skeletonModifiers.arraySize; i++)
						{
							var thisSkelMod = skeletonModifiers.GetArrayElementAtIndex(i);
							if (thisSkelMod.FindPropertyRelative("property").enumValueIndex == selectedAddProp && thisSkelMod.FindPropertyRelative("hash").intValue == addSkelBoneHash)
							{
								canAddSkel = false;
								alreadyExistedSkel = true;
							}
						}
					}
					if (canAddSkel == false)
					{
						EditorGUI.BeginDisabledGroup(true);
					}
					if (GUI.Button(addSkelAddBut, "Add It!"))
					{
						if (minimalMode)
						{
							if (!hashes.Contains(addSkelBoneHash))
							{
								(target as DynamicDNAConverterBehaviour).hashList.Insert(0, new DynamicDNAConverterBehaviour.HashLisreplacedem(addSkelBoneName, addSkelBoneHash));
								hashList.serializedObject.ApplyModifiedProperties();
								serializedObject.Update();
								UpdateHashNames();
							}
						}
						(target as DynamicDNAConverterBehaviour).skeletonModifiers.Insert(0, new DynamicDNAConverterBehaviour.SkeletonModifier(addSkelBoneName, addSkelBoneHash, (DynamicDNAConverterBehaviour.SkeletonModifier.SkeletonPropType)selectedAddProp));
						skeletonModifiers.serializedObject.ApplyModifiedProperties();
						serializedObject.Update();
						addSkelBoneHash = 0;
						addSkelBoneName = "";
						selectedAddHash = 0;
						EditorGUIUtility.keyboardControl = 0;
					}
					if (canAddSkel == false)
					{
						EditorGUI.EndDisabledGroup();
					}
					if (alreadyExistedSkel == true)
					{
						EditorGUILayout.HelpBox("There was already a modifier for that bone with that property. You can serach the existing modifiers to find it.", MessageType.Warning);
					}
					EditorGUI.indentLevel++;
					//Search Filters Controls- dont show if we dont have any modifiers
					EditorGUILayout.Space();

					//THE ACTUAL MODIFIER LIST
					GUIHelper.BeginVerticalPadded(3, new Color(0.75f, 0.875f, 1f, 0.3f));
					EditorGUILayout.LabelField("Skeleton Modifiers (" + skeletonModifiers.arraySize + ")", EditorStyles.helpBox);
					if (skeletonModifiers.arraySize > 0)
					{
						Rect searchR = EditorGUILayout.GetControlRect();
						var searchL = searchR;
						var searchF = searchR;
						var searchTL = searchR;
						var searchTF = searchR;
						searchL.width = 130;
						searchF.width = (searchR.width / 3) * 2 - searchL.width;
						searchF.x = searchR.x + searchL.width;
						searchTL.width = 35;
						searchTL.x = searchF.xMax;
						searchTF.width = (searchR.width / 3) - searchTL.width + (EditorGUI.indentLevel * 15);
						searchTF.x = searchTL.xMax - (EditorGUI.indentLevel * 15);
						EditorGUI.LabelField(searchL, "Search Modifiers");
						EditorGUI.indentLevel--;
						skeletonModifiersFilter = EditorGUI.TextField(searchF, skeletonModifiersFilter);
						EditorGUI.LabelField(searchTL, "By");
						skeletonModifiersFilterType = EditorGUI.Popup(searchTF, skeletonModifiersFilterType, skeletonModifiersFilterTypeList);
						EditorGUI.indentLevel++;
					}
					EditorGUI.indentLevel++;
					for (int i = 0; i < skeletonModifiers.arraySize; i++)
					{
						var thisSkelEl = skeletonModifiers.GetArrayElementAtIndex(i);
						//Search Filters Method
						if (skeletonModifiersFilterTypeList[skeletonModifiersFilterType] != "DNA")
						{
							if (skeletonModifiersFilterType == 1 || skeletonModifiersFilterType == 2 || skeletonModifiersFilterType == 3)
							{
								string thisProperty = thisSkelEl.FindPropertyRelative("property").enumNames[thisSkelEl.FindPropertyRelative("property").enumValueIndex];
								if (skeletonModifiersFilterType == 1)//Position Modifiers
								{
									if (thisProperty.IndexOf("position", StringComparison.CurrentCultureIgnoreCase) == -1)
										continue;
								}
								else if (skeletonModifiersFilterType == 2)//Rotation Modifiers
								{
									if (thisProperty.IndexOf("rotation", StringComparison.CurrentCultureIgnoreCase) == -1)
										continue;
								}
								else if (skeletonModifiersFilterType == 3)//scale Modifiers
								{
									if (thisProperty.IndexOf("scale", StringComparison.CurrentCultureIgnoreCase) == -1)
										continue;
								}
							}
							else if (skeletonModifiersFilterType == 5)//Adjust Bones
							{
								if (thisSkelEl.displayName.IndexOf("adjust", StringComparison.CurrentCultureIgnoreCase) == -1)
									continue;
							}
							else if (skeletonModifiersFilterType == 6)//Non Adjust Bones
							{
								if (thisSkelEl.displayName.IndexOf("adjust", StringComparison.CurrentCultureIgnoreCase) > -1)
									continue;
							}
						}
						if (skeletonModifiersFilter.Length >= 3)
						{
							if (skeletonModifiersFilterTypeList[skeletonModifiersFilterType] != "DNA")
							{
								if (thisSkelEl.displayName.IndexOf(skeletonModifiersFilter, StringComparison.CurrentCultureIgnoreCase) == -1)
									continue;
							}
							else //Searches for Modifiers that use a given DNA Value- slow but super handy
							{
								string[] XYZ = new string[] { "X", "Y", "Z" };
								SerializedProperty mods;
								SerializedProperty thisMod;
								int modsi;
								bool _continue = true;
								foreach (string xyz in XYZ)
								{
									mods = thisSkelEl.FindPropertyRelative("values" + xyz).FindPropertyRelative("val").FindPropertyRelative("modifiers");
									for (int mi = 0; mi < mods.arraySize; mi++)
									{
										thisMod = mods.GetArrayElementAtIndex(mi);
										modsi = thisMod.FindPropertyRelative("modifier").enumValueIndex;
										if (modsi > 3)
										{
											if (thisMod.FindPropertyRelative("DNATypeName").stringValue.IndexOf(skeletonModifiersFilter, StringComparison.CurrentCultureIgnoreCase) > -1)
												_continue = false;
										}
									}
								}
								if (_continue)
								{
									continue;
								}
							}
						}
						Rect currentRect = EditorGUILayout.GetControlRect(false, _skelModPropDrawer.GetPropertyHeight(thisSkelEl, GUIContent.none));
						//Delete button
						Rect sDelButR = currentRect;
						sDelButR.x = sDelButR.x + sDelButR.width - 100f;
						sDelButR.width = 100f;
						sDelButR.height = EditorGUIUtility.singleLineHeight;
						if (GUI.Button(sDelButR, "Delete"))
						{
							skeletonModifiers.DeleteArrayElementAtIndex(i);
							continue;
						}
						Rect thisSkelRect = new Rect(currentRect.xMin, currentRect.yMin, currentRect.width, _skelModPropDrawer.GetPropertyHeight(thisSkelEl, GUIContent.none));
						_skelModPropDrawer.OnGUI(thisSkelRect, thisSkelEl, new GUIContent(thisSkelEl.displayName));
					}
					GUIHelper.EndVerticalPadded(3);
					EditorGUI.indentLevel--;
					//we want to discourage users from using the starting values to customise their models (if they have any modifiers set up
					if (skeletonModifiers.arraySize > 0)
					{
						_skelModPropDrawer.enableSkelModValueEditing = enableSkelModValueEditing = EditorGUILayout.ToggleLeft("Enable editing of starting Value (not reccommended)", enableSkelModValueEditing);
						//and make it easy to set the starting values back to the defaults
						GUILayout.BeginHorizontal();
						GUILayout.Space(EditorGUI.indentLevel * 15);
						if (GUILayout.Button("Reset All Starting Values to Default"))
						{
							for (int i = 0; i < skeletonModifiers.arraySize; i++)
							{
								var thisSkeModProp = skeletonModifiers.GetArrayElementAtIndex(i).FindPropertyRelative("property").enumNames[skeletonModifiers.GetArrayElementAtIndex(i).FindPropertyRelative("property").enumValueIndex];
								if (thisSkeModProp != "")
								{
									if (thisSkeModProp == "Position" || thisSkeModProp == "Rotation")
									{
										skeletonModifiers.GetArrayElementAtIndex(i).FindPropertyRelative("valuesX").FindPropertyRelative("val").FindPropertyRelative("value").floatValue = 0f;
										skeletonModifiers.GetArrayElementAtIndex(i).FindPropertyRelative("valuesY").FindPropertyRelative("val").FindPropertyRelative("value").floatValue = 0f;
										skeletonModifiers.GetArrayElementAtIndex(i).FindPropertyRelative("valuesZ").FindPropertyRelative("val").FindPropertyRelative("value").floatValue = 0f;
									}
									if (thisSkeModProp == "Scale")
									{
										skeletonModifiers.GetArrayElementAtIndex(i).FindPropertyRelative("valuesX").FindPropertyRelative("val").FindPropertyRelative("value").floatValue = 1f;
										skeletonModifiers.GetArrayElementAtIndex(i).FindPropertyRelative("valuesY").FindPropertyRelative("val").FindPropertyRelative("value").floatValue = 1f;
										skeletonModifiers.GetArrayElementAtIndex(i).FindPropertyRelative("valuesZ").FindPropertyRelative("val").FindPropertyRelative("value").floatValue = 1f;
									}
								}
							}
							skeletonModifiers.serializedObject.ApplyModifiedProperties();
						}
						GUILayout.EndHorizontal();
					}
					EditorGUILayout.Space();
				}
				EditorGUILayout.Space();
				serializedObject.FindProperty("overallModifiersEnabled").boolValue = EditorGUILayout.ToggleLeft("Enable Overall Modifiers", serializedObject.FindProperty("overallModifiersEnabled").boolValue);
				SerializedProperty overallModifiersEnabledProp = serializedObject.FindProperty("overallModifiersEnabled");
				bool overallModifiersEnabled = overallModifiersEnabledProp.boolValue;
				if (overallModifiersEnabled)
				{
					EditorGUI.BeginChangeCheck();
					EditorGUILayout.PropertyField(serializedObject.FindProperty("overallScale"));
					EditorGUILayout.PropertyField(serializedObject.FindProperty("tightenBounds"));
					EditorGUILayout.PropertyField(serializedObject.FindProperty("boundsAdjust"));
					//EditorGUILayout.PropertyField(serializedObject.FindProperty("heightModifiers"));
					EditorGUILayout.PropertyField(serializedObject.FindProperty("radiusAdjust"));
					EditorGUILayout.PropertyField(serializedObject.FindProperty("mreplacedModifiers"));
					if (EditorGUI.EndChangeCheck())
					{
						serializedObject.ApplyModifiedProperties();
					}
				}
				EditorGUI.indentLevel--;
				GUIHelper.EndVerticalPadded(3);
			}
			serializedObject.ApplyModifiedProperties();
			//===========END CONVERTER VALUES AND EDITOR============//
			//
			EditorGUILayout.Space();
			//
			//===========BONEPOSE replacedET AND EDITOR===========//
			startingPoseExpanded = EditorGUILayout.Foldout(startingPoseExpanded, "Starting Pose", foldoutTipStyle);
			if (startingPoseExpanded)
			{
				GUIHelper.BeginVerticalPadded(3, new Color(0.75f, 0.875f, 1f, 0.3f));
				EditorGUI.indentLevel++;
				startingPoseInfoExpanded = EditorGUILayout.Foldout(startingPoseInfoExpanded, "INFO");
				if (startingPoseInfoExpanded)
					EditorGUILayout.HelpBox("The 'Starting Pose'is the initial position/rotation/scale of all the bones in this Avatar's skeleton. Use this to completely transform the mesh of your character. You could (for example) transform standard UMA characters into a backwards compatible 'Short Squat Dwarf' or a 'Bobble- headded Toon'. Optionally, you can create an UMABonePose replacedet from an FBX model using the UMA > Pose Tools > Bone Pose Builder and add the resulting replacedet here. After you have added or created a UMABonePose replacedet, you can add and edit the position, rotation and scale settings for any bone in the active character's skeleton in the 'Bone Poses' section.'.", MessageType.Info);
				EditorGUI.BeginChangeCheck();
				EditorGUILayout.PropertyField(serializedObject.FindProperty("startingPose"), new GUIContent("Starting UMABonePose", "Define an replacedet that will set the starting bone poses of any Avatar using this converter"));
				if (EditorGUI.EndChangeCheck())
				{
					serializedObject.ApplyModifiedProperties();
					//If this gets set we need to back it up
					thisDDCC.BackupConverter();
				}
				//Draw the poses array from the replacedet if set or show controls to create a new replacedet.
				SerializedProperty bonePosereplacedet = serializedObject.FindProperty("startingPose");
				if (bonePosereplacedet.objectReferenceValue != null)
				{
					EditorGUILayout.PropertyField(serializedObject.FindProperty("startingPoseWeight"));
					if (thisUBP == null)
					{
						thisUBP = Editor.CreateEditor((UMA.PoseTools.UMABonePose)bonePosereplacedet.objectReferenceValue, typeof(UMA.PoseTools.UMABonePoseEditor));
						((UMA.PoseTools.UMABonePoseEditor)thisUBP).dynamicDNAConverterMode = true;
						if (umaData != null)
						{
							((UMA.PoseTools.UMABonePoseEditor)thisUBP).context = new UMA.PoseTools.UMABonePoseEditorContext();
							((UMA.PoseTools.UMABonePoseEditor)thisUBP).context.activeUMA = umaData;
						}
					}
					else if (thisUBP.target != (UMA.PoseTools.UMABonePose)bonePosereplacedet.objectReferenceValue)
					{
						thisUBP = Editor.CreateEditor((UMA.PoseTools.UMABonePose)bonePosereplacedet.objectReferenceValue, typeof(UMA.PoseTools.UMABonePoseEditor));
						((UMA.PoseTools.UMABonePoseEditor)thisUBP).dynamicDNAConverterMode = true;
						if (umaData != null)
						{
							((UMA.PoseTools.UMABonePoseEditor)thisUBP).context = new UMA.PoseTools.UMABonePoseEditorContext();
							((UMA.PoseTools.UMABonePoseEditor)thisUBP).context.activeUMA = umaData;
						}
					}
					EditorGUI.BeginChangeCheck();
					thisUBP.OnInspectorGUI();
					if (EditorGUI.EndChangeCheck())
					{
						//Currently we dont need to do anything here as the change is picked up by DynamicDNAConverterCustomizer an this triggers an UMA update
						//this may change though if we have a method in future for modifying the TPose
					}
				}
				else
				{
					if (thisDDCC != null)
					{
						var createPosereplacedetR = EditorGUILayout.GetControlRect(false);
						var createPosereplacedetRLabel = createPosereplacedetR;
						var createPosereplacedetRField = createPosereplacedetR;
						var createPosereplacedetRButton = createPosereplacedetR;
						createPosereplacedetRLabel.width = createPosereplacedetRLabel.width / 3 + 7;
						createPosereplacedetRButton.width = 70f;
						createPosereplacedetRField.width = ((createPosereplacedetRField.width / 3) * 2) - 82;
						createPosereplacedetRField.x = createPosereplacedetRLabel.xMax;
						createPosereplacedetRButton.x = createPosereplacedetRField.xMax + 5;
						EditorGUI.LabelField(createPosereplacedetRLabel, new GUIContent("New BonePose replacedet", "Create a new empty UMABonePose with the name of your choosing."));
						createBonePosereplacedetName = EditorGUI.TextField(createPosereplacedetRField, createBonePosereplacedetName);
						if (GUI.Button(createPosereplacedetRButton, "Create It"))//need to do the button enabled thing here
						{
							var newDnareplacedet = thisDDCC.CreatePosereplacedet("", createBonePosereplacedetName);
							if (newDnareplacedet != null)
							{
								//set this replacedet as the used replacedet
								bonePosereplacedet.objectReferenceValue = newDnareplacedet;
								serializedObject.ApplyModifiedProperties();
								createBonePosereplacedetName = "";
							}
						}
					}
					else
					{
						EditorGUILayout.HelpBox("Edit a character that uses this converter in the 'DynamicDna Converter Behaviour Customizer' scene and you can create a StartingPosereplacedet automatically here", MessageType.Info);
					}
				}
				if (minimalMode && umaData.skeleton != null && bonePosereplacedet.objectReferenceValue == null)
				{
					EditorGUILayout.Space();
					EditorGUILayout.LabelField("Create Poses from Current DNA state");
					EditorGUILayout.HelpBox("Create bone poses from Avatar's current dna modified state. Applies the pose and sets DNA values back to 0. Smaller margin of error equals greater accuracy but more poses to apply on DNA Update.", MessageType.Info);
					if (thisDDCC != null)
					{
						//[Range(0.000005f, 0.0005f)]
						EditorGUI.BeginChangeCheck();
						var thisAccuracy = EditorGUILayout.Slider(new GUIContent("Margin Of Error","The smaller the margin of error, the more accurate the Pose will be, but it will also have more bonePoses to apply when DNA is updated"), thisDDCC.bonePoseAccuracy * 1000, 0.5f, 0.005f);
						if (EditorGUI.EndChangeCheck())
						{
							thisDDCC.bonePoseAccuracy = thisAccuracy / 1000;
							GUI.changed = false;
						}
					}
					GUILayout.BeginHorizontal();
					GUILayout.Space(EditorGUI.indentLevel * 20);
					if (GUILayout.Button(/*createFromDnaButR, */"Create Poses"))
					{
						if (thisDDCC != null)
						{
							if (thisDDCC.CreateBonePosesFromCurrentDna(createBonePosereplacedetName))
							{
								serializedObject.Update();
							}
						}
					}
					GUILayout.EndHorizontal();

				}
				EditorGUI.indentLevel--;
				GUIHelper.EndVerticalPadded(3);
			}
			serializedObject.ApplyModifiedProperties();
			//=============END BONEPOSE replacedET AND EDITOR============//
			//
			EditorGUILayout.Space();

		}

19 View Source File : UMAData.cs
License : Apache License 2.0
Project Creator : A7ocin

public void EnsureAllDNAPresent()
			{
				List<int> requiredDnas = new List<int>();
				if (raceData != null)
				{
					foreach (var converter in raceData.dnaConverterList)
					{
						var dnaTypeHash = converter.DNATypeHash;
						//'old' dna converters return a typehash based on the type name. 
						//Dynamic DNA Converters return the typehash of their dna replacedet or 0 if none is replacedigned- we dont want to include those
						if (dnaTypeHash == 0)
						continue;
						requiredDnas.Add(dnaTypeHash);
                        if (!umaDna.ContainsKey(dnaTypeHash))
						{
							var dna = converter.DNAType.GetConstructor(System.Type.EmptyTypes).Invoke(null) as UMADnaBase;
							dna.DNATypeHash = dnaTypeHash;
							//DynamireplacedADna:: needs the DNAreplacedet from the converter - moved because this might change
							if (converter is DynamicDNAConverterBehaviourBase)
							{
								((DynamireplacedADnaBase)dna).dnareplacedet = ((DynamicDNAConverterBehaviourBase)converter).dnareplacedet;
							}
							umaDna.Add(dnaTypeHash, dna);
							dnaValues.Add(dna);
						}
						else if (converter is DynamicDNAConverterBehaviourBase)
						{
							var dna = umaDna[dnaTypeHash];
							((DynamireplacedADnaBase)dna).dnareplacedet = ((DynamicDNAConverterBehaviourBase)converter).dnareplacedet;
						}
					}
				}
				foreach (var slotData in slotDataList)
				{
					if (slotData != null && slotData.replacedet.slotDNA != null)
					{
						var dnaTypeHash = slotData.replacedet.slotDNA.DNATypeHash;
						//'old' dna converters return a typehash based on the type name. 
						//Dynamic DNA Converters return the typehash of their dna replacedet or 0 if none is replacedigned- we dont want to include those
						if (dnaTypeHash == 0)
							continue;
						requiredDnas.Add(dnaTypeHash);
						if (!umaDna.ContainsKey(dnaTypeHash))
						{
							var dna = slotData.replacedet.slotDNA.DNAType.GetConstructor(System.Type.EmptyTypes).Invoke(null) as UMADnaBase;
							dna.DNATypeHash = dnaTypeHash;
							//DynamireplacedADna:: needs the DNAreplacedet from the converter TODO are there other places where I heed to sort out this slotDNA?
							if (slotData.replacedet.slotDNA is DynamicDNAConverterBehaviourBase)
							{
								((DynamireplacedADnaBase)dna).dnareplacedet = ((DynamicDNAConverterBehaviourBase)slotData.replacedet.slotDNA).dnareplacedet;
							}
							umaDna.Add(dnaTypeHash, dna);
							dnaValues.Add(dna);
						}
						else if (slotData.replacedet.slotDNA is DynamicDNAConverterBehaviourBase)
						{
							var dna = umaDna[dnaTypeHash];
							((DynamireplacedADnaBase)dna).dnareplacedet = ((DynamicDNAConverterBehaviourBase)slotData.replacedet.slotDNA).dnareplacedet;
						}
                    }
				}
				foreach (int addedDNAHash in umaDnaConverter.Keys)
				{
					requiredDnas.Add(addedDNAHash);
				}

				//now remove any we no longer need
				var keysToRemove = new List<int>();
				foreach(var kvp in umaDna)
				{
					if (!requiredDnas.Contains(kvp.Key))
						keysToRemove.Add(kvp.Key);
				}
				for(int i = 0; i < keysToRemove.Count; i++)
				{
					RemoveDna(keysToRemove[i]);
				}
				
			}

19 View Source File : UMAExpressionSet.cs
License : Apache License 2.0
Project Creator : A7ocin

private void ValidateBoneHashes()
        {
            if (boneHashes == null)
            {
                List<int> boneHashList = new List<int>();
                foreach (PosePair pair in posePairs)
                {
                    if (pair.primary != null)
                    {
                        foreach (UMABonePose.PoseBone bone in pair.primary.poses)
                        {
                            if (!boneHashList.Contains(bone.hash))
                            {
                                boneHashList.Add(bone.hash);
                            }
                        }
                    }
                    if (pair.inverse != null)
                    {
                        foreach (UMABonePose.PoseBone bone in pair.inverse.poses)
                        {
                            if (!boneHashList.Contains(bone.hash))
                            {
                                boneHashList.Add(bone.hash);
                            }
                        }
                    }
                }

                boneHashes = boneHashList.ToArray();
            }
        }

19 View Source File : AttackServer.cs
License : Apache License 2.0
Project Creator : AantCoder

public AttackHostFromSrv RequestHost(AttackHostToSrv fromClient)
        {
            //Loger.Log($"Server AttackOnlineHost RequestHost State: {State} -> {fromClient.State}");
            lock (SyncObj)
            {
                //первые 5 минут не проверяем на отключения, т.к. загрузка может быть долгой (а дисконектит уже после 10 сек)
                if ((fromClient.State == 10 || (DateTime.UtcNow - CreateTime).TotalSeconds > 8*60)
                    && CheckConnect(false))
                {
                    return new AttackHostFromSrv()
                    {
                        State = State
                    };
                }
                if (fromClient.State < State)
                {
                    return new AttackHostFromSrv()
                    {
                        ErrorText = "Unexpected request " + fromClient.State.ToString() + ". Was expected" + State.ToString()
                    };
                }

                if (fromClient.State == 2)
                {
                    State = 2;
                    return new AttackHostFromSrv()
                    {
                        State = State,
                        HostPlaceServerId = HostPlaceServerId,
                        InitiatorPlaceServerId = InitiatorPlaceServerId,
                        StartInitiatorPlayer = Attacker.Public.Login,
                        TestMode = TestMode,
                    };
                }

                if (fromClient.State == 4)
                {
                    MapSize = fromClient.MapSize;
                    TerrainDefNameCell = fromClient.TerrainDefNameCell;
                    TerrainDefName = fromClient.TerrainDefName;
                    Thing = fromClient.Thing;
                    ThingCell = fromClient.ThingCell;
                    State = 4;
                    return new AttackHostFromSrv()
                    {
                        State = State,
                    };
                }

                if (fromClient.State == 5)
                {
                    State = 5;
                    return new AttackHostFromSrv()
                    {
                        State = State,
                        Pawns = Pawns
                    };
                }

                if (fromClient.State == 10)
                {
                    State = 10;

                    if (VictoryAttacker == null) VictoryAttacker = fromClient.VictoryAttacker;

                    if (fromClient.NewPawnsId.Count > 0
                        || fromClient.NewThingsId.Count > 0
                        || fromClient.NewCorpses.Count > 0
                        || fromClient.Delete.Count > 0)
                    {
                        //удаляем из Delete если сейчас команда добавить с таким id
                        foreach (var n in fromClient.NewPawnsId)
                        {
                            var index = Delete.IndexOf(n);
                            if (index >= 0) Delete.RemoveAt(index);
                        }
                        foreach (var n in fromClient.NewThingsId)
                        {
                            var index = Delete.IndexOf(n);
                            if (index >= 0) Delete.RemoveAt(index);
                        }
                        foreach (var corps in fromClient.NewCorpses)
                        {
                            var index = Delete.IndexOf(corps.CorpseId);
                            if (index >= 0) Delete.RemoveAt(index);
                        }

                        //объединяем
                        for (int i = 0; i < fromClient.NewPawnsId.Count; i++)
                        {
                            if (NewPawnsId.Contains(fromClient.NewPawnsId[i])) continue;
                            NewPawnsId.Add(fromClient.NewPawnsId[i]);
                            NewPawns.Add(fromClient.NewPawns[i]);
                        }
                        for (int i = 0; i < fromClient.NewThingsId.Count; i++)
                        {
                            if (NewThingsId.Contains(fromClient.NewThingsId[i])) continue;
                            NewThingsId.Add(fromClient.NewThingsId[i]);
                            NewThings.Add(fromClient.NewThings[i]);
                        }
                        for (int i = 0; i < NewCorpses.Count; i++)
                        {
                            if (fromClient.NewCorpses.Any(c => c.PawnId == NewCorpses[i].PawnId || c.CorpseId == NewCorpses[i].CorpseId))
                            {
                                NewCorpses.RemoveAt(i--);
                            }
                        }
                        for (int i = 0; i < fromClient.NewCorpses.Count; i++)
                        {
                            NewCorpses.Add(fromClient.NewCorpses[i]);
                        }
                        for (int i = 0; i < fromClient.Delete.Count; i++)
                        {
                            if (Delete.Contains(fromClient.Delete[i])) continue;
                            Delete.Add(fromClient.Delete[i]);
                        }
                        for (int i = 0; i < fromClient.NewCorpses.Count; i++)
                        {
                            if (Delete.Contains(fromClient.NewCorpses[i].PawnId)) continue;
                            Delete.Add(fromClient.NewCorpses[i].PawnId);
                        }

                        //на всякий случай корректируем: удаляем из добавляемых те, что на удаление
                        foreach (var n in Delete)
                        {
                            var index = NewPawnsId.IndexOf(n);
                            if (index >= 0)
                            {
                                NewPawnsId.RemoveAt(index);
                                NewPawns.RemoveAt(index);
                            }
                            index = NewThingsId.IndexOf(n);
                            if (index >= 0)
                            {
                                NewThingsId.RemoveAt(index);
                                NewThings.RemoveAt(index);
                            }

                            for (int i = 0; i < NewCorpses.Count; i++)
                            {
                                if (n == NewCorpses[i].CorpseId)
                                {
                                    NewCorpses.RemoveAt(i--);
                                }
                            }
                        }
                    }


                    if (fromClient.UpdateState.Count > 0)
                    {
                        //объединяем
                        for (int i = 0; i < fromClient.UpdateState.Count; i++)
                        {
                            var id = fromClient.UpdateState[i].HostThingID;
                            UpdateState[id] = fromClient.UpdateState[i];
                        }
                    }

                    var res = new AttackHostFromSrv()
                    {
                        State = State,
                        UpdateCommand = UpdateCommand.Values.ToList(),
                        NeedNewThingIDs = NeedNewThingIDs.ToList(),
                        SetPauseOnTime = SetPauseOnTimeToHost == null ? DateTime.MinValue : SetPauseOnTimeToHost.Value,
                        VictoryHost = VictoryHostToHost,
                        TerribleFatalError = TerribleFatalError,
                    };

                    UpdateCommand = new Dictionary<int, AttackPawnCommand>();
                    NeedNewThingIDs = new HashSet<int>();

                    if (SetPauseOnTimeToHost != null) Loger.Log("Server Send SetPauseOnTimeToHost=" + SetPauseOnTimeToHost.Value.ToGoodUtcString());

                    Host.PVPHostLastTime = DateTime.UtcNow;
                    SetPauseOnTimeToHost = null;
                    VictoryHostToHost = false;
                    return res;
                }

                return new AttackHostFromSrv()
                {
                    ErrorText = "Unexpected request " + fromClient.State.ToString() + "! Was expected" + State.ToString()
                };
            }
        }

19 View Source File : ServerNetworkingBase.cs
License : MIT License
Project Creator : Abaudat

public void SendToClient(int connectionId, byte[] data)
    {
        if(connections.Contains(connectionId))
        {
            NetworkTransport.Send(hostId, connectionId, reliableChannelId, data, data.Length, out error);
            if ((NetworkError)error != NetworkError.Ok)
            {
                Debug.Log("WARNING: " + (NetworkError)error);
            }
        }
        else
        {
            Debug.LogWarning("WARNING: Trying to send to disconnected client " + connectionId);
        }
    }

19 View Source File : ServerNetworkingBase.cs
License : MIT License
Project Creator : Abaudat

public void SendUpdateToClient(int connectionId, byte[] data)
    {
        if (connections.Contains(connectionId))
        {
            NetworkTransport.Send(hostId, connectionId, stateUpdateChannelId, data, data.Length, out error);
            if ((NetworkError)error != NetworkError.Ok)
            {
                Debug.Log("WARNING: " + (NetworkError)error);
            }
        }
        else
        {
            Debug.LogWarning("WARNING: Trying to send to disconnected client " + connectionId);
        }
    }

19 View Source File : ServerNetworkingBase.cs
License : MIT License
Project Creator : Abaudat

void OnClientConnection(int connectionId)
    {
        if (connections.Contains(connectionId))
        {
            Debug.Log("SERVER: Reconnection from connection number " + connectionId + ".");
        }
        else
        {
            Debug.Log("SERVER: New connection from connection number " + connectionId + ".");
            connections.Add(connectionId);
        }
    }

19 View Source File : FindSquares.cs
License : GNU General Public License v3.0
Project Creator : AdamWhiteHat

public static GNFS FindSquares(CancellationToken cancelToken, GNFS gnfs)
		{
			if (cancelToken.IsCancellationRequested)
			{
				return gnfs;
			}

			Logging.LogMessage();
			Logging.LogMessage($"# of solution sets: {gnfs.CurrentRelationsProgress.FreeRelations.Count}");
			Logging.LogMessage();


			BigInteger polyBase = gnfs.PolynomialBase;
			List<List<Relation>> freeRelations = gnfs.CurrentRelationsProgress.FreeRelations;

			int freeRelationIndex = 0;
			bool solutionFound = false;

			// Below randomly selects a solution set to try and find a square root of the polynomial in.

			// Each time this step is stopped and restarted, it will try a different solution set.
			// Previous used sets are tracked with the List<int> triedFreeRelationIndices

			while (!solutionFound)
			{
				if (triedFreeRelationIndices.Count == freeRelations.Count) // If we have exhausted our solution sets, alert the user. Number wont factor for some reason.
				{
					Logging.LogMessage("ERROR: ALL RELATION SETS HAVE BEEN TRIED...?");
					Logging.LogMessage($"If the number of solution sets ({freeRelations.Count}) is low, you may need to sieve some more and then re-run the matrix solving step.");
					Logging.LogMessage("If there are many solution sets, and you have tried them all without finding non-trivial factors, then something is wrong...");
					Logging.LogMessage();
					return gnfs;
				}

				do
				{
					freeRelationIndex = StaticRandom.Next(0, freeRelations.Count);
				}
				while (triedFreeRelationIndices.Contains(freeRelationIndex));

				triedFreeRelationIndices.Add(freeRelationIndex); // Add current selection to our list

				List<Relation> selectedRelationSet = freeRelations[freeRelationIndex]; // Get the solution set

				SquareFinder squareRootFinder = new SquareFinder(gnfs, selectedRelationSet); // If you want to solve for a new solution set, create a new instance

				Logging.LogMessage($"Selected solution set # {freeRelationIndex + 1}");
				Logging.LogMessage();
				Logging.LogMessage($"Selected set (a,b) pairs (count: {selectedRelationSet.Count}): {string.Join(" ", selectedRelationSet.Select(rel => $"({rel.A},{rel.B})"))}");
				Logging.LogMessage();
				Logging.LogMessage();
				Logging.LogMessage();
				Logging.LogMessage($"ƒ'(m)     = {squareRootFinder.PolynomialDerivative}");
				Logging.LogMessage($"ƒ'(m)^2   = {squareRootFinder.PolynomialDerivativeSquared}");
				Logging.LogMessage();
				Logging.LogMessage("Calculating Rational Square Root.");
				Logging.LogMessage("Please wait...");

				squareRootFinder.CalculateRationalSide();

				Logging.LogMessage("Completed.");
				Logging.LogMessage();
				Logging.LogMessage($"γ²        = {squareRootFinder.RationalProduct} IsSquare? {squareRootFinder.RationalProduct.IsSquare()}");
				Logging.LogMessage($"(γ  · ƒ'(m))^2 = {squareRootFinder.RationalSquare} IsSquare? {squareRootFinder.RationalSquare.IsSquare()}");
				Logging.LogMessage();
				Logging.LogMessage();
				Logging.LogMessage("Calculating Algebraic Square Root.");
				Logging.LogMessage("Please wait...");

				Tuple<BigInteger, BigInteger> foundFactors = squareRootFinder.CalculateAlgebraicSide(cancelToken);
				BigInteger P = foundFactors.Item1;
				BigInteger Q = foundFactors.Item2;

				if (cancelToken.IsCancellationRequested && P == 1 && Q == 1)
				{
					Logging.LogMessage("Square root search aborted!");
					return gnfs;
				}

				bool nonTrivialFactorsFound = (P != 1 || Q != 1);
				if (!nonTrivialFactorsFound)
				{
					Logging.LogMessage();
					Logging.LogMessage("Unable to locate a square root in solution set!");
					Logging.LogMessage();
					Logging.LogMessage("Trying a different solution set...");
					Logging.LogMessage();
					continue;
				}
				else
				{
					solutionFound = true;
				}

				Logging.LogMessage("NON-TRIVIAL FACTORS FOUND!");
				Logging.LogMessage();

				Polynomial S = squareRootFinder.S;
				Polynomial SRingSquare = squareRootFinder.SRingSquare;

				BigInteger prodS = SRingSquare.Evaluate(polyBase);

				Polynomial reducedS = Polynomial.Field.Modulus(S, gnfs.N);

				BigInteger totalProdS = squareRootFinder.TotalS.Evaluate(polyBase) * squareRootFinder.PolynomialDerivative;
				BigInteger totalProdModN = totalProdS % gnfs.N;
				BigInteger prodSmodN = prodS % gnfs.N;

				List<BigInteger> algebraicNumberFieldSquareRoots = squareRootFinder.AlgebraicResults;

				BigInteger rationalSquareRoot = squareRootFinder.RationalSquareRootResidue;
				BigInteger algebraicSquareRoot = squareRootFinder.AlgebraicSquareRootResidue;


				Logging.LogMessage($"∏ Sᵢ =");
				Logging.LogMessage($"{squareRootFinder.TotalS}");
				Logging.LogMessage();
				Logging.LogMessage($"∏ Sᵢ (mod ƒ) =");
				Logging.LogMessage($"{reducedS}");
				Logging.LogMessage();
				Logging.LogMessage("Polynomial ring:");
				Logging.LogMessage($"({string.Join(") * (", squareRootFinder.PolynomialRing.Select(ply => ply.ToString()))})");
				Logging.LogMessage();
				Logging.LogMessage("Primes:");
				Logging.LogMessage($"{string.Join(" * ", squareRootFinder.AlgebraicPrimes)}"); // .RelationsSet.Select(rel => rel.B).Distinct().OrderBy(relB => relB))
				Logging.LogMessage();
				Logging.LogMessage();
				Logging.LogMessage($"X² / ƒ(m) = {squareRootFinder.AlgebraicProductModF}  IsSquare? {squareRootFinder.AlgebraicProductModF.IsSquare()}");
				Logging.LogMessage();
				Logging.LogMessage($"");
				Logging.LogMessage($"AlgebraicPrimes: {squareRootFinder.AlgebraicPrimes.FormatString(false)}");
				Logging.LogMessage($"AlgebraicResults: {squareRootFinder.AlgebraicResults.FormatString(false)}");
				Logging.LogMessage($"");
				Logging.LogMessage($"*****************************");
				Logging.LogMessage($"");
				Logging.LogMessage($"AlgebraicSquareRootResidue: {squareRootFinder.AlgebraicSquareRootResidue}");
				Logging.LogMessage($"");
				Logging.LogMessage($"AlgebraicNumberFieldSquareRoots: {algebraicNumberFieldSquareRoots.FormatString(false)}");
				Logging.LogMessage($"");
				Logging.LogMessage($" RationalSquareRoot : {rationalSquareRoot}");
				Logging.LogMessage($" AlgebraicSquareRoot: {algebraicSquareRoot} ");
				Logging.LogMessage($"");
				Logging.LogMessage($"*****************************");
				Logging.LogMessage($"S (x)       = {prodSmodN}  IsSquare? {prodSmodN.IsSquare()}");
				Logging.LogMessage();
				Logging.LogMessage("Roots of S(x):");
				Logging.LogMessage($"{{{string.Join(", ", squareRootFinder.RootsOfS.Select(tup => (tup.Item2 > 1) ? $"{tup.Item1}/{tup.Item2}" : $"{tup.Item1}"))}}}");
				Logging.LogMessage();
				Logging.LogMessage();
				Logging.LogMessage($"TTL: {totalProdS} IsSquare? {totalProdS.IsSquare()}");
				Logging.LogMessage($"TTL%N: {totalProdModN}  IsSquare? {totalProdModN.IsSquare()}");
				//Logging.LogMessage();
				//Logging.LogMessage($"∏(a + mb) = {squareRootFinder.RationalProduct}");
				//Logging.LogMessage($"∏ƒ(a/b)   = {squareRootFinder.AlgebraicProduct}");
				Logging.LogMessage("-------------------------------------------");
				Logging.LogMessage();
				Logging.LogMessage();
				Logging.LogMessage($"RationalSquareRootResidue:        = {squareRootFinder.RationalSquareRootResidue}   IsSquare? {squareRootFinder.RationalSquareRootResidue.IsSquare()}");
				Logging.LogMessage($"AlgebraicSquareRootResidue:       = {squareRootFinder.AlgebraicSquareRootResidue}  IsSquare? {squareRootFinder.RationalSquareRootResidue.IsSquare()}");
				Logging.LogMessage();
				Logging.LogMessage();

				/*	Non-trivial factors also recoverable by doing the following:

				BigInteger min = BigInteger.Min(squareRootFinder.RationalSquareRootResidue, squareRootFinder.AlgebraicSquareRootResidue);
				BigInteger max = BigInteger.Max(squareRootFinder.RationalSquareRootResidue, squareRootFinder.AlgebraicSquareRootResidue);
				BigInteger A = max + min;
				BigInteger B = max - min;
				BigInteger P = GCD.FindGCD(gnfs.N, A);
				BigInteger Q = GCD.FindGCD(gnfs.N, B);

				*/

				StringBuilder sb = new StringBuilder();
				sb.AppendLine($"N = {gnfs.N}");
				sb.AppendLine();
				sb.AppendLine($"P = {BigInteger.Max(P, Q)}");
				sb.AppendLine($"Q = {BigInteger.Min(P, Q)}");
				sb.AppendLine();

				string path = Path.Combine(gnfs.SaveLocations.SaveDirectory, "Solution.txt");

				File.WriteAllText(path, sb.ToString());

				Logging.LogMessage();
				Logging.LogMessage(Environment.NewLine + sb.ToString());
			}

			return gnfs;
		}

19 View Source File : ModEntry.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn

private static void chooseStoneType_Postfix(MineShaft __instance, ref StardewValley.Object __result, Vector2 tile)
        {
            if(__result == null)
            {
                return;
            }
            List<int> ores = new List<int>() { 765, 764, 290, 751 };
            var x = __result.ParentSheetIndex;
            if (!(x >= 31 && x <= 42 || x >= 47 && x <= 54 || ores.Contains(x)))
            {
                return;
            }

            if (__instance.getMineArea(-1) == 0 || __instance.getMineArea(-1) == 10)
            {
                double chanceForOre = 0.029 * Config.ChanceForOresMultiplierInMines - 0.029;

                if (__instance.mineLevel != 1 && __instance.mineLevel % 5 != 0 && Game1.random.NextDouble() < chanceForOre)
                {
                    __result = new StardewValley.Object(tile, 751, "Stone", true, false, false, false)
                    {
                        MinutesUntilReady = 3
                    };
                }
            }
            else if (__instance.getMineArea(-1) == 40)
            {
                double chanceForOre = 0.029 * Config.ChanceForOresMultiplierInMines - 0.029;
                if (__instance.mineLevel % 5 != 0 && Game1.random.NextDouble() < chanceForOre)
                {
                    __result = new StardewValley.Object(tile, 290, "Stone", true, false, false, false)
                    {
                        MinutesUntilReady = 4
                    };
                }
            }
            else if (__instance.getMineArea(-1) == 80)
            {
                double chanceForOre = 0.029 * Config.ChanceForOresMultiplierInMines - 0.029;
                if (__instance.mineLevel % 5 != 0 && Game1.random.NextDouble() < chanceForOre)
                {
                    __result = new StardewValley.Object(tile, 764, "Stone", true, false, false, false)
                    {
                        MinutesUntilReady = 8
                    };
                }
            }
            else if (__instance.getMineArea(-1) == 77377)
            {
                return;
            }
            else
            {
                int skullCavernMineLevel = __instance.mineLevel - 120;
                double chanceForOre = 0.02 + (double)skullCavernMineLevel * 0.0005;
                if (__instance.mineLevel >= 130)
                {
                    chanceForOre += 0.01 * (double)((float)(Math.Min(100, skullCavernMineLevel) - 10) / 10f);
                }
                double iridiumBoost = 0.0;
                if (__instance.mineLevel >= 130)
                {
                    iridiumBoost += 0.001 * (double)((float)(skullCavernMineLevel - 10) / 10f);
                }
                iridiumBoost = Math.Min(iridiumBoost, 0.004);
                if (skullCavernMineLevel > 100)
                {
                    iridiumBoost += (double)skullCavernMineLevel / 1000000.0;
                }

                chanceForOre = chanceForOre * Config.ChanceForOreMultiplier - chanceForOre;

                if (ores.Contains(x) || Game1.random.NextDouble() < chanceForOre) // if already an ore, don't check again
                {
                    double chanceForIridium = (double)Math.Min(100, skullCavernMineLevel) * (0.0003 + iridiumBoost);
                    double chanceForGold = 0.01 + (double)(__instance.mineLevel - Math.Min(150, skullCavernMineLevel)) * 0.0005;
                    double chanceForIron = Math.Min(0.5, 0.1 + (double)(__instance.mineLevel - Math.Min(200, skullCavernMineLevel)) * 0.005);

                    chanceForIridium *= Config.ChanceForIridiumMultiplier;
                    chanceForGold *= Config.ChanceForGoldMultiplier;
                    chanceForIron *= Config.ChanceForIronMultiplier;

                    if (Game1.random.NextDouble() < chanceForIridium)
                    {
                        __result = new StardewValley.Object(tile, 765, "Stone", true, false, false, false)
                        {
                            MinutesUntilReady = 16
                        };
                    }
                    else if (Game1.random.NextDouble() < chanceForGold)
                    {
                        __result = new StardewValley.Object(tile, 764, "Stone", true, false, false, false)
                        {
                            MinutesUntilReady = 8
                        };
                    }
                    else if (Game1.random.NextDouble() < chanceForIron)
                    {
                        __result = new StardewValley.Object(tile, 290, "Stone", true, false, false, false)
                        {
                            MinutesUntilReady = 4
                        };
                    }
                    else
                    {
                        __result = new StardewValley.Object(tile, 751, "Stone", true, false, false, false)
                        {
                            MinutesUntilReady = 2
                        };
                    }
                }
            }

            /*
            if (!ores.Contains(__result.ParentSheetIndex))
            {
                foreach(CustomOreNode node in CustomOreNodeData)
                {

                }
            }
            */
        }

19 View Source File : ModEntry.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn

private static bool IsRock(OverlaidDictionary objects, int x, int y)
        {
            return objects.ContainsKey(new Vector2(x, y)) && (rocks.Contains(objects[new Vector2(x, y)].parentSheetIndex) || treasures.Contains(objects[new Vector2(x, y)].parentSheetIndex));
        }

19 View Source File : ModEntry.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn

private static bool Object_draw_Prefix(Object __instance, SpriteBatch spriteBatch, int x, int y, float alpha)
        {
            if (!(Game1.currentLocation is MineShaft))
                return true;


            if (rocks.Contains(__instance.parentSheetIndex) || treasures.Contains(__instance.parentSheetIndex))
            {

                if (!flippedObjects.ContainsKey(new Vector2(x, y)))
                {
                    flippedObjects[new Vector2(x, y)] = Game1.random.NextDouble() < 0.5;
                }

                bool flip = flippedObjects[new Vector2(x, y)];

                Vector2 origin = new Vector2(8f, 8f);
                GetTileInfo(Game1.currentLocation.objects, x, y, __instance.parentSheetIndex, flip, out int tileIndex);
                if (tileIndex == -1)
                    return true;

                Rectangle sourceRect = new Rectangle(tileIndex * 16 % (sheetWidth* 16), tileIndex * 16 / (sheetWidth * 16) * 16, 16, 16);
                Vector2 position = Game1.GlobalToLocal(Game1.viewport, new Vector2(x * 64 + 32 + ((__instance.shakeTimer > 0) ? Game1.random.Next(-1, 2) : 0), y * 64 + 32 + ((__instance.shakeTimer > 0) ? Game1.random.Next(-1, 2) : 0)));
                spriteBatch.Draw(tilesheet, position, sourceRect, Color.White, 0, origin, (__instance.scale.Y > 1f) ? __instance.getScale().Y : 4f, flip ? SpriteEffects.FlipHorizontally : SpriteEffects.None, (__instance.isPreplacedable() ? __instance.getBoundingBox(new Vector2(x, y)).Top : __instance.getBoundingBox(new Vector2(x, y)).Bottom) / 10000f);
                if (treasures.Contains(__instance.parentSheetIndex))
                {
                    Rectangle treasureRect = new Rectangle((treasures.IndexOf(__instance.parentSheetIndex) % sheetWidth) * 16, (10 + treasures.IndexOf(__instance.parentSheetIndex) / sheetWidth) * 16, 16, 16);
                    spriteBatch.Draw(tilesheet, position, treasureRect, Color.White, 0, origin, (__instance.scale.Y > 1f) ? __instance.getScale().Y : 4f, flip ? SpriteEffects.FlipHorizontally : SpriteEffects.None, (__instance.isPreplacedable() ? __instance.getBoundingBox(new Vector2(x, y)).Top : __instance.getBoundingBox(new Vector2(x, y)).Bottom) / 10000f + 0.001f);
                }

                return false;
            }
            return true;
        }

19 View Source File : ModEntry.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn

private static void chooseStoneType_Postfix(MineShaft __instance, ref Object __result, Vector2 tile)
        {
            if (__result == null)
                return;

            int difficulty = __instance.mineLevel > 120 ? Game1.netWorldState.Value.SkullCavesDifficulty : Game1.netWorldState.Value.MinesDifficulty;

            List<int> ores = new List<int>() { 765, 764, 290, 751 };
            if (!ores.Contains(__result.ParentSheetIndex))
            {
                float totalChance = 0;
                for (int i = 0; i < customOreNodesList.Count; i++)
                {
                    CustomOreNode node = customOreNodesList[i];
                    foreach(OreLevelRange range in node.oreLevelRanges)
                    {
                        if ((range.minLevel < 1 || __instance.mineLevel >= range.minLevel) && (range.maxLevel < 1 || __instance.mineLevel <= range.maxLevel) && (range.minDifficulty <= difficulty) && (range.maxDifficulty < 0 || range.maxDifficulty >= difficulty))
                        {
                            totalChance += node.spawnChance * range.spawnChanceMult;
                            break;
                        }
                    }
                }
                double ourChance = Game1.random.NextDouble() * 100;
                if (ourChance < totalChance)
                {
                    // SMonitor.Log($"Chance of custom ore: {ourChance}%");
                    float replacedulativeChance = 0f;
                    for (int i = 0; i < customOreNodesList.Count; i++)
                    {
                        CustomOreNode node = customOreNodesList[i];
                        OreLevelRange gotRange = null;
                        foreach (OreLevelRange range in node.oreLevelRanges)
                        {
                            if (IsInRange(range, __instance, true))
                            {
                                gotRange = range;
                                break;
                            }
                        }
                        if (gotRange == null)
                        {
                            continue;
                        }
                        replacedulativeChance += node.spawnChance * gotRange.spawnChanceMult;
                        if (ourChance < replacedulativeChance)
                        {
                            SMonitor.Log($"Switching to custom ore \"{node.nodeDesc}\": {replacedulativeChance}% / {ourChance}% (rolled)");

                            int index = node.parentSheetIndex;
                            //SMonitor.Log($"Displaying stone at index {index}", LogLevel.Debug);
                            __result = new Object(tile, index, "Stone", true, false, false, false)
                            {
                                MinutesUntilReady = node.durability
                            };

                            return;
                        }
                    }
                }
            }
        }

19 View Source File : ModEntry.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn

private Dictionary<string, string> MakeDialogue(RNPC rnpc)
        {
            Dictionary<string, string> data = new Dictionary<string, string>();
            List<string> intros = GetHighestRankedStrings(rnpc.npcString, RNPCdialogueData.introductions, 7);
            data.Add("Introduction", intros[Game1.random.Next(0, intros.Count)]);

            // make dialogue

            string[] dow = { "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun" };

            NPC npc = Game1.getCharacterFromName(rnpc.nameID);
            int hearts = Game1.player.getFriendshipHeartLevelForNPC(rnpc.nameID);

            if (!Config.RequireHeartsForDialogue)
            {
                hearts = 10;
            }

            string question = GetRandomDialogue(rnpc, RNPCdialogueData.questions);
            List<string> farmerQuestions = RNPCdialogueData.farmer_questions;
            List<string> rejections = GetHighestRankedStrings(rnpc.npcString, RNPCdialogueData.rejections, 7);


            string questionString = "$q 4242 question_asked#" + question;

            int fqi = 0;

            questionString += "#$r 4343 0 fquest_" + (fqi) + "#" + farmerQuestions[fqi];
            if (hearts >= 2) // allow asking about personality
            {
                string manner = GetRandomDialogue(rnpc, RNPCdialogueData.manner);
                string anxiety = GetRandomDialogue(rnpc, RNPCdialogueData.anxiety);
                string optimism = GetRandomDialogue(rnpc, RNPCdialogueData.optimism);

                string infoResponse = GetRandomDialogue(rnpc, RNPCdialogueData.info_responses);

                data.Add("fquest_" + (fqi), infoResponse.Replace("$name", rnpc.name).Replace("$manner", manner).Replace("$anxiety", anxiety).Replace("$optimism", optimism));
            }
            else
            {
                data.Add("fquest_" + (fqi), rejections[Game1.random.Next(0, rejections.Count)]);
            }
            fqi++;

            questionString += "#$r 4343 0 fquest_" + (fqi) + "#" + farmerQuestions[fqi];
            if (hearts >= 4) // allow asking about plans
            {
                string morning = "THIS IS AN ERROR";
                string afternoon = "THIS IS AN ERROR";
                foreach (RNPCSchedule schedule in RNPCSchedules)
                {
                    if (schedule.npc.nameID == rnpc.nameID)
                    {
                        morning = GetRandomDialogue(rnpc, RNPCdialogueData.places[schedule.morningLoc.Split(' ')[0]]);
                        afternoon = GetRandomDialogue(rnpc, RNPCdialogueData.places[schedule.afternoonLoc.Split(' ')[0]]);
                        break;
                    }
                }
                string scheduleDialogue = GetRandomDialogue(rnpc, RNPCdialogueData.schedules);
                data.Add("fquest_" + (fqi), scheduleDialogue.Replace("@", morning).Replace("#", afternoon));
            }
            else
            {
                data.Add("fquest_" + (fqi), rejections[Game1.random.Next(0, rejections.Count)]);
            }
            fqi++;

            questionString += "#$r 4343 0 fquest_" + (fqi) + "#" + farmerQuestions[fqi];
            if (hearts >= 6) // allow asking about advice
            {
                string advice = GetRandomDialogue(rnpc, RNPCdialogueData.advice);
                data.Add("fquest_" + (fqi), advice);
            }
            else
            {
                data.Add("fquest_" + (fqi), rejections[Game1.random.Next(0, rejections.Count)]);
            }
            fqi++;

            questionString += "#$r 4343 0 fquest_" + (fqi) + "#" + farmerQuestions[fqi];
            if (hearts >= 6) // allow asking about help
            {
                int quizType = Game1.random.Next(0, 5);
                string quiz;
                int friendship = 10;
                List<string> quiza = new List<string>();
                List<string> rl = new List<string>();
                string[] ra;
                string[] quizA;
                switch (quizType)
                {
                    case 0:
                        quiz = GetRandomDialogue(rnpc, RNPCdialogueData.quiz_types["where"]);
                        rl = RNPCdialogueData.quiz_where_answers.OrderBy(n => Guid.NewGuid()).ToList();
                        for (int i = 0; i < 4; i++)
                        {
                            ra = rl[i].Split('|');
                            string ra1 = ra[1];
                            foreach (string str in SDVNPCS)
                            {
                                string str1 = str;
                                if (Game1.getCharacterFromName(str) != null)
                                {
                                    str1 = Game1.getCharacterFromName(str).getName();
                                    if (!str.Equals(str1))
                                    {
                                        ra1 = ra1.Replace(str, str1); // replace with display name
                                    }
                                }
                            }
                            if (Game1.getCharacterFromName(ra[0]) != null)
                            {
                                ra[0] = Game1.getCharacterFromName(ra[0]).getName();
                            }
                            if (i == 0) // right answer
                            {
                                quiza.Add(friendship + " quiz_right#" + ra1);
                                quiz = quiz.Replace("$who", ra[0]); // replace name in question
                            }
                            else
                            {
                                if (ra[1] == rl[0].Split('|')[1]) // same answer
                                    continue;
                                quiza.Add("-" + friendship + " quiz_wrong#" + ra[1]);
                            }
                        }
                        break;
                    case 1:
                        quizA = GetRandomDialogue(rnpc, RNPCdialogueData.quiz_types["when"]).Split('|');
                        quiz = quizA[0];
                        rl = RNPCdialogueData.quiz_when_answers.OrderBy(n => Guid.NewGuid()).ToList();

                        bool open = Game1.random.Next(0, 1) == 0;
                        ra = rl[0].Split('|');
                        quiz = quiz.Replace("$where", ra[0]).Replace("$openclose", open ? quizA[1] : quizA[2]); // replace values in question
                        int h = int.Parse(open ? ra[1] : ra[2]);
                        quiza.Add(friendship + " quiz_right#" + quizA[3].Replace("$time", h > 12 ? (h - 12) + quizA[5] : h + quizA[4]));

                        List<int> hours = new List<int>
                        {
                            h
                        };
                        while (quiza.Count < 4)
                        {
                            int rhour;
                            if (open)
                                rhour = Game1.random.Next(6, 12);
                            else
                                rhour = Game1.random.Next(15, 23);

                            if (hours.Contains(rhour)) // don't duplicate
                                continue;

                            hours.Add(rhour);

                            quiza.Add("-" + friendship + " quiz_wrong#" + quizA[3].Replace("$time", rhour > 12 ? (rhour - 12) + quizA[5] : rhour + quizA[4]));
                        }

                        break;
                    case 2:
                        quizA = GetRandomDialogue(rnpc, RNPCdialogueData.quiz_types["howmuch"]).Split('|');
                        quiz = quizA[0];

                        string item = RNPCdialogueData.quiz_howmuch_items[Game1.random.Next(0, RNPCdialogueData.quiz_howmuch_items.Count)];
                        int where = Game1.random.Next(0, 1);
                        ra = item.Split('|');
                        quiza.Add(friendship + " quiz_right#" + quizA[1].Replace("$gold", ra[1 + where]));
                        quiz = quiz.Replace("$what", ra[0]); // replace name in question
                        quiz = quiz.Replace("$where", RNPCdialogueData.quiz_howmuch_places[where]); // replace name in question

                        int price = int.Parse(ra[1 + where]);
                        List<int> prices = new List<int>
                        {
                            price
                        };
                        int price1 = int.Parse(ra[where == 1 ? 1 : 2]);
                        prices.Add(price1);

                        quiza.Add("-" + friendship + " quiz_wrong#" + quizA[1].Replace("$gold", price1.ToString()));

                        while (quiza.Count < 4)
                        {
                            int rprice = int.Parse(RNPCdialogueData.quiz_howmuch_items[Game1.random.Next(0, RNPCdialogueData.quiz_howmuch_items.Count)].Split('|')[1]);
                            if (prices.Contains(rprice))
                                continue;
                            prices.Add(rprice);

                            quiza.Add("-" + friendship + " quiz_wrong#" + quizA[1].Replace("$gold", rprice.ToString()));
                        }

                        break;
                    case 3:
                        quizA = GetRandomDialogue(rnpc, RNPCdialogueData.quiz_types["who"]).Split('|');
                        quiz = quizA[0];

                        string who = RNPCdialogueData.quiz_who_answers[Game1.random.Next(0, RNPCdialogueData.quiz_who_answers.Count)];
                        ra = who.Split('|');

                        quiza.Add(friendship + " quiz_right#" + quizA[1].Replace("$what", ra[0]).Replace("$who", Game1.getCharacterFromName(ra[1]).getName()));
                        quiz = quiz.Replace("$what", ra[0]); // replace name in question

                        List<string> people = new List<string>
                        {
                            ra[1]
                        };

                        while (quiza.Count < 4)
                        {
                            string rname = SDVNPCS[Game1.random.Next(0, SDVNPCS.Length)];
                            if (people.Contains(rname))
                                continue;
                            people.Add(rname);
                            if (Game1.getCharacterFromName(rname) != null)
                            {
                                rname = Game1.getCharacterFromName(rname).getName();
                            }
                            quiza.Add("-" + friendship + " quiz_wrong#" + quizA[1].Replace("$what", ra[0]).Replace("$who", rname));
                        }

                        break;
                    case 4:
                    default:
                        string tmp = GetRandomDialogue(rnpc, RNPCdialogueData.quiz_types["quest"]);
                        string[] quiz4 = tmp.Replace("$what", Game1.objectInformation[rnpc.quesreplacedem].Split('/')[0]).Split('|');
                        quiz = quiz4[0];

                        quiza.Add("2 accept_npc_quest_"+(rnpc.npcID+4200)+"#" + quiz4[1]);
                        quiza.Add("0 decline_npc_quest#" + quiz4[2]);
                        data.Add("accept_npc_quest_" + (rnpc.npcID + 4200), quiz4[3]);
                        data.Add("decline_npc_quest", quiz4[4]);
                        break;
                }


                string quizq = "$q 4242 questq_answered#" + quiz;
                string quizRight = GetRandomDialogue(rnpc, RNPCdialogueData.quizRight);
                string quizWrong = GetRandomDialogue(rnpc, RNPCdialogueData.quizWrong);
                string quizUnknown = GetRandomDialogue(rnpc, RNPCdialogueData.quizUnknown);

                if(quizType != 4)
                {
                    quiza = quiza.OrderBy(n => Guid.NewGuid()).ToList();
                    quiza.Add("0 quiz_unknown#" + RNPCdialogueData.quiz_dont_know);
                }

                for (int i = 0; i < quiza.Count; i++)
                {
                    quizq += "#$r 4343 " + quiza[i];
                }

                Alert("NPC quiz: fquest_"+quizq);

                data.Add("fquest_" + (fqi), quizq);

                data.Add("quiz_right", quizRight);
                data.Add("quiz_wrong", quizWrong);
                data.Add("quiz_unknown", quizUnknown);
            }
            else
            {
                data.Add("fquest_" + (fqi), rejections[Game1.random.Next(0, rejections.Count)]);
            }
            fqi++;

            if (!npc.datingFarmer)
            {
                questionString += "#$r 4343 0 fquest_" + (fqi) + "#" + farmerQuestions[fqi];
                if (hearts >= 8) // allow asking about datability
                {
                    string datable = GetRandomDialogue(rnpc, RNPCdialogueData.datable);

                    data.Add("fquest_" + (fqi), npc.datable ? datable.Split('^')[0] : datable.Split('^')[1]);
                }
                else
                {
                    data.Add("fquest_" + (fqi), rejections[Game1.random.Next(0, rejections.Count)]);
                }
            }
            /*
            fqi++;
            questionString += "#$r 4343 0 fquest_" + (fqi) + "#" + farmerQuestions[fqi];
            data.Add("fquest_" + (fqi), "...");
            */
            //base.Monitor.Log(questionString, LogLevel.Alert);

            foreach (string d in dow)
            {
                data.Add(d, questionString);
            }

            return data;
        }

19 View Source File : GUIBase.cs
License : GNU General Public License v3.0
Project Creator : aelariane

private static int GetLayer(int layerToSet, string name)
        {
            lock (usedLayers)
            {
                if (layerToSet >= 0)
                {
                    if (usedLayers.Contains(layerToSet))
                    {
                        Debug.LogError($"Attemption to create GUIBase with already existing layer. Please make sure you wanted to use this one. Layer: {layerToSet}, GUIBase name: {name}");
                        return GetLayer(++layerToSet, name);
                    }
                    usedLayers.Add(layerToSet);
                    UpdateMaxLayer();
                    return layerToSet;
                }
                maxLayer = usedLayers.Max();
                usedLayers.Add(++maxLayer);
                return maxLayer;
            }
        }

19 View Source File : GameModes.cs
License : GNU General Public License v3.0
Project Creator : aelariane

public static bool AntiReviveAdd(int id)
        {
            if (AntiReviveEnabled() && IN_GAME_MAIN_CAMERA.GameMode != GameMode.Racing &&
                FengGameManagerMKII.Level.RespawnMode != RespawnMode.DEATHMATCH &&
                FengGameManagerMKII.FGM.logic.RoundTime > 10f)
            {
                if (antiReviveList.Contains(id))
                {
                    return false;
                }

                antiReviveList.Add(id);
                return true;
            }

            return false;
        }

19 View Source File : GameModes.cs
License : GNU General Public License v3.0
Project Creator : aelariane

public static bool AntiReviveCheck(int id, HERO hero)
        {
            if (AntiReviveEnabled())
            {
                if (antiReviveList.Contains(id))
                {
                    hero.BasePV.RPC("netDie2", PhotonTargets.All, -1, "Anti-Revive ");
                    return true;
                }

                return false;
            }

            return false;
        }

19 View Source File : PhotonNetwork.cs
License : GNU General Public License v3.0
Project Creator : aelariane

public static int AllocateViewID(int ownerId)
    {
        if (ownerId == 0)
        {
            int num = lastUsedViewSubIdStatic;
            int num2 = ownerId * MAX_VIEW_IDS;
            for (int i = 1; i < MAX_VIEW_IDS; i++)
            {
                num = (num + 1) % MAX_VIEW_IDS;
                if (num != 0)
                {
                    int num3 = num + num2;
                    if (!NetworkingPeer.photonViewList.ContainsKey(num3))
                    {
                        lastUsedViewSubIdStatic = num;
                        return num3;
                    }
                }
            }
            throw new Exception(string.Format("AllocateViewID() failed. Room (user {0}) is out of subIds, as all room viewIDs are used.", ownerId));
        }
        int num4 = lastUsedViewSubId;
        int num5 = ownerId * MAX_VIEW_IDS;
        for (int j = 1; j < MAX_VIEW_IDS; j++)
        {
            num4 = (num4 + 1) % MAX_VIEW_IDS;
            if (num4 != 0)
            {
                int num6 = num4 + num5;
                if (!NetworkingPeer.photonViewList.ContainsKey(num6) && !manuallyAllocatedViewIds.Contains(num6))
                {
                    lastUsedViewSubId = num4;
                    return num6;
                }
            }
        }
        throw new Exception(string.Format("AllocateViewID() failed. User {0} is out of subIds, as all viewIDs are used.", ownerId));
    }

19 View Source File : TreasuryContract.cs
License : MIT License
Project Creator : AElfProject

public override Empty InitialTreasuryContract(Empty input)
        {
            replacedert(!State.Initialized.Value, "Already initialized.");

            State.ProfitContract.Value =
                Context.GetContractAddressByName(SmartContractConstants.ProfitContractSystemName);

            // Create profit schemes: `Treasury`, `CitizenWelfare`, `BackupSubsidy`, `MinerReward`,
            // `MinerBasicReward`, `WelcomeReward`, `FlexibleReward`
            var profireplacedemNameList = new List<string>
            {
                "Treasury", "MinerReward", "Subsidy", "Welfare", "Basic Reward", "Flexible Reward",
                "Welcome Reward"
            };
            for (var i = 0; i < 7; i++)
            {
                var index = i;
                Context.LogDebug(() => profireplacedemNameList[index]);
                State.ProfitContract.CreateScheme.Send(new CreateSchemeInput
                {
                    IsReleaseAllBalanceEveryTimeByDefault = true,
                    // Distribution of Citizen Welfare will delay one period.
                    DelayDistributePeriodCount = i == 3 ? 1 : 0,
                    // Subsidy, Flexible Reward and Welcome Reward can remove beneficiary directly (due to replaceable.)
                    CanRemoveBeneficiaryDirectly = new List<int> {2, 5, 6}.Contains(i)
                });
            }

            State.Initialized.Value = true;

            State.SymbolList.Value = new SymbolList
            {
                Value = {Context.Variables.NativeSymbol}
            };

            return new Empty();
        }

19 View Source File : DataReader.cs
License : GNU General Public License v3.0
Project Creator : aenemenate

public static string GetNextTip()
        {
            string tip = "";

            XElement root = XElement.Load("res/data/GameTipList.xml");
            IEnumerable<XElement> tips =
                from el in root.Elements("tip")
                select el;

            List<XElement> tipList = new List<XElement>();

            foreach (XElement el in tips)
                tipList.Add(el);

            if (tipList.Count == 0)
                throw new System.Exception();

            int index = Program.RNG.Next(0, tipList.Count);
            if (readTips.Count == tipList.Count)
                readTips = new List<int>();
            while (readTips.Contains(index))
            {
                index = Program.RNG.Next(0, tipList.Count);
            }
            tip = ReadAttribute(tipList[index].Attribute("text"));
            readTips.Add(index);

            return tip;
        }

19 View Source File : Map.cs
License : GNU General Public License v3.0
Project Creator : AHeroicLlama

static int DrawLegend(Font font, Graphics imageGraphic)
		{
			if (FormMaster.legendItems.Count == 0)
			{
				return 0;
			}

			Dictionary<int, string> overridingLegendText = FormMaster.GatherOverriddenLegendTexts();
			List<int> drawnGroups = new List<int>();

			// Calculate the total height of all legend strings with their plot icons beside, combined
			int legendTotalHeight = 0;
			foreach (MapItem mapItem in FormMaster.legendItems)
			{
				// Skip legend groups that are merged/overridden and have already been accounted for
				if (drawnGroups.Contains(mapItem.legendGroup) && overridingLegendText.ContainsKey(mapItem.legendGroup))
				{
					continue;
				}

				legendTotalHeight += Math.Max(
					(int)Math.Ceiling(imageGraphic.MeasureString(mapItem.GetLegendText(false), font, legendBounds).Height),
					SettingsPlot.IsIconOrTopographic() ? SettingsPlotIcon.iconSize : 0);

				drawnGroups.Add(mapItem.legendGroup);
			}

			int skippedLegends = 0; // How many legend items did not fit onto the map

			// The initial Y coord where first legend item should be written, in order to Y-center the entire legend
			int legendCaretHeight = (mapDimension / 2) - (legendTotalHeight / 2);

			// Reset the drawn groups list, as we need to iterate over the items again
			drawnGroups = new List<int>();

			// Loop over every MapItem and draw the legend
			foreach (MapItem mapItem in FormMaster.legendItems)
			{
				// Skip legend groups that are merged/overridden and have already been drawn
				if (drawnGroups.Contains(mapItem.legendGroup) && overridingLegendText.ContainsKey(mapItem.legendGroup))
				{
					continue;
				}

				// Calculate positions and color for legend text (plus icon)
				int fontHeight = (int)Math.Ceiling(imageGraphic.MeasureString(mapItem.GetLegendText(false), font, legendBounds).Height);

				PlotIcon icon = mapItem.GetIcon();
				Image plotIconImg = SettingsPlot.IsIconOrTopographic() ? icon.GetIconImage() : null;

				Color legendColor = SettingsPlot.IsTopographic() ? SettingsPlotTopograph.legendColor : mapItem.GetLegendColor();
				Brush textBrush = new SolidBrush(legendColor);

				int iconHeight = SettingsPlot.IsIconOrTopographic() ?
					plotIconImg.Height :
					0;

				int legendHeight = Math.Max(fontHeight, iconHeight);

				// If the icon is taller than the text, offset the text it so it sits Y-centrally against the icon
				int textOffset = 0;
				if (iconHeight > fontHeight)
				{
					textOffset = (iconHeight - fontHeight) / 2;
				}

				// If the legend text/item fits on the map vertically
				if (legendCaretHeight > 0 && legendCaretHeight + legendHeight < mapDimension)
				{
					if (SettingsPlot.IsIconOrTopographic())
					{
						imageGraphic.DrawImage(plotIconImg, (float)(legendIconX - (plotIconImg.Width / 2d)), (float)(legendCaretHeight - (plotIconImg.Height / 2d) + (legendHeight / 2d)));
					}

					imageGraphic.DrawString(mapItem.GetLegendText(false), font, textBrush, new RectangleF(legendXMin, legendCaretHeight + textOffset, legendWidth, legendHeight));
				}
				else
				{
					skippedLegends++;
				}

				drawnGroups.Add(mapItem.legendGroup);
				legendCaretHeight += legendHeight; // Move the 'caret' down for the next item, enough to fit the icon and the text
			}

			GC.Collect();
			return skippedLegends;
		}

19 View Source File : MainWindow_Dat.cs
License : GNU Affero General Public License v3.0
Project Creator : aianlinb

private void OnCellLoaded(object sender, RoutedEventArgs e) {
			var dc = (DataGridCell)sender;
			var border = (Border)VisualTreeHelper.GetChild(dc, 0);
			var row = DataGridRow.GetRowContainingElement(dc).GetIndex();
			var col = dc.Column.DisplayIndex;
			if (col == 0 && toMark.Contains(row) || col == 2 && toMark.Contains(row + 1)) {
				border.Background = Brushes.Red;
				border.BorderThickness = new Thickness(0);
			}
		}

19 View Source File : RecordServiceTasks.cs
License : GNU General Public License v3.0
Project Creator : aiportal

private void ScanWinSessionsToRecordOrEnd(object state)
		{
			int[] winSessions = WTSEngine.GetActiveSessions();
			var rcdProcesses = GetRcordingProcesses();

			// if not recording, record it.
			foreach (int sid in winSessions)
			{
				if (Array.Find(rcdProcesses, p => p.SessionId == sid) == null)
				{
					string user = WTSEngine.GetDomainUserBySessionId(sid);
					if (UserPolicy.IsUserRecording(user))
					{
						TraceLogger.Instance.WriteLineInfo("Start recording by configuration. user: " + user);
						this.SessionLogon(sid);
					}
				}
			}

			// if exclude recoding, kill it.
			//foreach (var proc in rcdProcesses)
			//{
			//    string user = WTSEngine.GetDomainUserBySessionId(proc.SessionId);
			//    if (!IsUserRecording(user))
			//    {
			//        TraceLogger.Instance.WriteLineInfo("Stop recording by configuration. user: " + user);
			//        try { proc.Kill(); }
			//        catch (Exception) { }
			//        this.SessionLogoff(proc.SessionId);
			//    }
			//}

			// if session not active, remove watcher.
			foreach (int sid in _watchers.Keys)
			{
				if (!Array.Exists(winSessions, s => s == sid))
					this.SessionLogoff(sid);
			}

			///? bug fix: double agent process in windows 7.
			List<int> sessions = new List<int>();
			foreach (var proc in rcdProcesses)
			{
				if (sessions.Contains(proc.SessionId))
				{
					TraceLogger.Instance.WriteLineInfo("Kill recording agent because double process. sessionId: " + proc.SessionId);
					try { proc.Kill(); }
					catch (Exception) { }
				}
				else
				{
					sessions.Add(proc.SessionId);
				}
			}

			// dispose
			Array.ForEach(rcdProcesses, p => p.Dispose());
		}

19 View Source File : PatternScanner.cs
License : MIT License
Project Creator : Akaion

private int[] GenerateLookupTable(List<string> pattern)
        {
            var wildcardIndexes = pattern.Select((wildcard, index) => wildcard == "??" ? index : -1).Where(index => index != -1).ToList();
            
            // Generate a lookup table

            var lookupTable = new int[byte.MaxValue + 1];
            
            for (var tableIndex = 0; tableIndex < lookupTable.Length; tableIndex += 1)
            {
                lookupTable[tableIndex] = pattern.Count;
            }
            
            // Initialise the pattern in the lookup table

            for (var patternIndex = 0; patternIndex < pattern.Count - 1; patternIndex += 1)
            {
                if (!wildcardIndexes.Contains(patternIndex))
                {
                    lookupTable[int.Parse(pattern[patternIndex], NumberStyles.HexNumber)] = pattern.Count - patternIndex - 1;
                }
            }

            return lookupTable;
        }

19 View Source File : JSONTransformComponent.cs
License : GNU General Public License v2.0
Project Creator : albertogeniola

private int ProcessObject(JObject obj, ref PipelineBuffer inputbuffer)
        {
            bool cancel = false;

            // Each objects corresponds to an output row.
            int res = 0;

            AddOutputRow(ref inputbuffer);

            // For each column requested from metadata, look for data into the object we parsed.
            Parallel.ForEach<IOMapEntry>(_iomap, _opt, delegate (IOMapEntry e) {
                int colIndex = _outColsMaps[e.OutputColName];

                // If the user wants to get raw json, we should parse nothing: simply return all the json as a string
                if (e.OutputJsonColumnType == JsonTypes.RawJson)
                {
                    string val = null;
                    var vals = obj.SelectTokens(e.InputFieldPath);
                    if (vals.Count() == 0) {
                        val = null;
                    }else if (vals.Count() == 1)
                    {
                        val = vals.ElementAt(0).ToString();
                    }
                    else
                    {
                        JArray arr = new JArray();
                        foreach (var t in vals)
                        {
                            arr.Add(t);
                        }
                        val = arr.ToString();
                    }

                    try
                    {
                        _outputBuffer[colIndex] = val;
                        res++;
                    }
                    catch (DoesNotFitBufferException ex)
                    {
                        bool fireAgain = false;
                        ComponentMetaData.FireError(ComponentConstants.ERROR_INVALID_BUFFER_SIZE, ComponentMetaData.Name, String.Format("Maximum size of column {0} is smaller than provided data. Please increase buffer size.", e.OutputColName), null, 0, out fireAgain);
                        throw ex;
                    }
                }
                else
                {
                    // If it's not a json raw type, parse the value.
                    try
                    {
                        IEnumerable<JToken> tokens = obj.SelectTokens(e.InputFieldPath);
                        int count = tokens.Count();
                        if (count == 0)
                        {
                            if (!_warnNotified.Contains(colIndex))
                            {
                                _warnNotified.Add(colIndex);
                                ComponentMetaData.FireWarning(ComponentConstants.RUNTIME_GENERIC_ERROR, ComponentMetaData.Name, String.Format("No value has been found when parsing jsonpath {0} on column {1}. Is the jsonpath correct?", e.InputFieldPath, e.OutputColName), null, 0);
                            }
                        }
                        else if (count == 1)
                        {
                            try
                            {
                                res++;
                                _outputBuffer[colIndex] = tokens.ElementAt(0);
                            }
                            catch (DoesNotFitBufferException ex)
                            {
                                bool fireAgain = false;
                                ComponentMetaData.FireError(ComponentConstants.ERROR_INVALID_BUFFER_SIZE, ComponentMetaData.Name, String.Format("Maximum size of column {0} is smaller than provided data. Please increase buffer size.", e.OutputColName), null, 0, out fireAgain);
                                throw ex;
                            }
                        }
                        else
                        {
                            if (!_warnNotified.Contains(colIndex))
                            {
                                _warnNotified.Add(colIndex);
                                ComponentMetaData.FireWarning(ComponentConstants.RUNTIME_GENERIC_ERROR, ComponentMetaData.Name, String.Format("Multiple values have been found when parsing jsonpath {0} on column {1}. This will led to line explosion, so I won't explode this here to save memory. Put a filter in pipeline to explode the lines, if needed.", e.InputFieldPath, e.OutputColName), null, 0);
                            }
                            // This case requires explosions. We cannot perform it here, so we output raw json
                            JArray arr = new JArray();
                            foreach (var t in tokens)
                            {
                                arr.Add(t);
                            }
                            
                            try
                            {
                                _outputBuffer[colIndex] = arr.ToString();
                            }
                            catch (DoesNotFitBufferException ex)
                            {
                                bool fireAgain = false;
                                ComponentMetaData.FireError(ComponentConstants.ERROR_INVALID_BUFFER_SIZE, ComponentMetaData.Name, String.Format("Maximum size of column {0} is smaller than provided data. Please increase buffer size.", e.OutputColName), null, 0, out fireAgain);
                                throw ex;
                            }
                        }
                    }
                    catch (Newtonsoft.Json.JsonException ex)
                    {
                        bool fireAgain = false;
                        ComponentMetaData.FireError(ComponentConstants.ERROR_SELECT_TOKEN, ComponentMetaData.Name, "SelectToken failed. This may be due to an invalid Xpath syntax / member name. However this error still happens if multiple tokens are returned and the value expected is single. Specific error was: " + ex.Message, null, 0, out fireAgain);
                        throw ex;
                    }
                }

            });

            return res;
        }

19 View Source File : MultiObjectSelectionToolbar.cs
License : MIT License
Project Creator : AlFasGD

public void AddIndex(int index)
        {
            if (!selectedTabIndices.Contains(index))
                selectedTabIndices.Add(index);
        }

19 View Source File : MultiObjectSelectionToolbar.cs
License : MIT License
Project Creator : AlFasGD

public void AddIndices(List<int> indices)
        {
            foreach (int i in indices)
                if (!selectedTabIndices.Contains(i))
                    selectedTabIndices.Add(i);
        }

19 View Source File : MultiObjectSelectionToolbarTab.cs
License : MIT License
Project Creator : AlFasGD

public void AddIndex(int index)
        {
            if (!selectedPageIndices.Contains(index))
                selectedPageIndices.Add(index);
        }

19 View Source File : MultiObjectSelectionToolbarTabPage.cs
License : MIT License
Project Creator : AlFasGD

public void AddIndex(int index)
        {
            if (!selectedItemIndices.Contains(index))
                selectedItemIndices.Add(index);
        }

19 View Source File : MultiObjectSelectionToolbarTabPage.cs
License : MIT License
Project Creator : AlFasGD

public void AddIndices(List<int> indices)
        {
            foreach (int i in indices)
                if (!selectedItemIndices.Contains(i))
                    selectedItemIndices.Add(i);
        }

19 View Source File : MultiObjectSelectionToolbarTab.cs
License : MIT License
Project Creator : AlFasGD

public void AddIndices(List<int> indices)
        {
            foreach (int i in indices)
                if (!selectedPageIndices.Contains(i))
                    selectedPageIndices.Add(i);
        }

See More Examples