Esempio n. 1
0
		public void GetValueTest()
		{
			IDictionary<String, String> d = new Dictionary<String, String>();
			d["Test1"] = "Test";
			Assert.AreEqual("Test", d.GetValue("Test1"));
			Assert.AreEqual(null, d.GetValue("Test2"));
		}
Esempio n. 2
0
    protected SVGGradientElement(SVGParser xmlImp, Dictionary<string, string> attrList)
    {
        _attrList = attrList;
        _xmlImp = xmlImp;
        _stopList = new List<SVGStopElement>();
        _id = _attrList.GetValue("id");
        _gradientUnits = SVGGradientUnit.ObjectBoundingBox;
        if (_attrList.GetValue("gradiantUnits") == "userSpaceOnUse")
        {
            _gradientUnits = SVGGradientUnit.UserSpaceOnUse;
        }

        //------
        // TODO: It's probably a bug that the value is not innoculated for CaSe
        // VaRiAtIoN in GetValue, below:
        _spreadMethod = SVGSpreadMethod.Pad;
        if (_attrList.GetValue("spreadMethod") == "reflect")
        {
            _spreadMethod = SVGSpreadMethod.Reflect;
        }
        else if (_attrList.GetValue("spreadMethod") == "repeat")
        {
            _spreadMethod = SVGSpreadMethod.Repeat;
        }

        GetElementList();
    }
		public void GetValueTest()
		{
			var d = new Dictionary<int?, string> { { 1, "a" } };

			AssertSome(d.GetValue(1), "a");
			AssertNothing(d.GetValue(2));
			AssertNothing(d.GetValue(null));
		}
Esempio n. 4
0
        public void ReturnsNullableValue()
        {
            var dict = new Dictionary<Type, string>() {{typeof(int), "1"}, {typeof(double), "2.0"}};

            Assert.Equal("1", dict.GetValue(typeof(int)));
            Assert.Equal(null, dict.GetValue(typeof(string)));

        }
Esempio n. 5
0
    public SVGCircleElement(Dictionary<string, string> attrList,
		SVGTransformList inheritTransformList,
		SVGPaintable inheritPaintable,
		SVGGraphics render)
        : base(attrList, inheritTransformList, inheritPaintable, render)
    {
        _cx = new SVGLength(attrList.GetValue("cx"));
        _cy = new SVGLength(attrList.GetValue("cy"));
        _r = new SVGLength(attrList.GetValue("r"));
    }
 public void SetValue()
 {
     IDictionary<string, int> Test = new Dictionary<string, int>();
     Test.Add("Q", 4);
     Test.Add("Z", 2);
     Test.Add("C", 3);
     Test.Add("A", 1);
     Assert.Equal(4, Test.GetValue("Q"));
     Test.SetValue("Q", 40);
     Assert.Equal(40, Test.GetValue("Q"));
 }
Esempio n. 7
0
 public SVGStopElement(Dictionary<string, string> attrList)
 {
     _stopColor = new SVGColor(attrList.GetValue("stop-color"));
     string temp = attrList.GetValue("offset").Trim();
     if(temp != "") {
       if(temp.EndsWith("%"))
     _offset = float.Parse(temp.TrimEnd(new[] { '%' }), System.Globalization.CultureInfo.InvariantCulture);
       else
     _offset = float.Parse(temp, System.Globalization.CultureInfo.InvariantCulture) * 100;
     }
 }
 public void GetValue()
 {
     IDictionary<string, int> Test = new Dictionary<string, int>();
     Test.Add("Q", 4);
     Test.Add("Z", 2);
     Test.Add("C", 3);
     Test.Add("A", 1);
     Assert.Equal(4, Test.GetValue("Q"));
     Assert.Equal(0, Test.GetValue("V"));
     Assert.Equal(123, Test.GetValue("B", 123));
 }
        public void GetValue()
        {
            var d = new Dictionary<int, int>
                {
                    {1, 2}
                };
            Assert.AreEqual(2, d.GetValue(1, 0));
            Assert.AreEqual(0, d.GetValue(2, 0));

            Assert.AreEqual(Maybe<int>.Empty, d.GetValue(10));
            Assert.AreEqual(2, d.GetValue(1).Value);
        }
Esempio n. 10
0
 public SVGEllipseElement(Dictionary<string, string> attrList,
                        SVGTransformList inheritTransformList,
                        SVGPaintable inheritPaintable,
                        SVGGraphics render)
     : base(attrList, inheritTransformList, inheritPaintable, render)
 {
     _cx = new SVGLength(attrList.GetValue("cx"));
     _cy = new SVGLength(attrList.GetValue("cy"));
     _rx = new SVGLength(attrList.GetValue("rx"));
     _ry = new SVGLength(attrList.GetValue("ry"));
     currentTransformList = new SVGTransformList(attrList.GetValue("transform"));
 }
Esempio n. 11
0
 public SVGLineElement(Dictionary<string, string> attrList,
                     SVGTransformList inheritTransformList,
                     SVGPaintable inheritPaintable,
                     SVGGraphics render)
     : base(inheritTransformList)
 {
     _paintable = new SVGPaintable(inheritPaintable, attrList);
     _render = render;
     _x1 = new SVGLength(attrList.GetValue("x1"));
     _y1 = new SVGLength(attrList.GetValue("y1"));
     _x2 = new SVGLength(attrList.GetValue("x2"));
     _y2 = new SVGLength(attrList.GetValue("y2"));
 }
Esempio n. 12
0
 internal Cookie(RemoteSession session, Dictionary dict) {
     _session = session;
     try {
         _name = dict.GetValue("name", string.Empty);
         _value = dict.GetValue("value", string.Empty);
         _path = dict.GetValue("path", string.Empty);
         _domain = dict.GetValue("domain", string.Empty);
         _secure = Convert.ToBoolean(dict.Get("secure", false));
         _expiry = Convert.ToDouble(dict.Get("expiry", 0));
     } catch (Errors.KeyNotFoundError ex) {
         throw new DeserializeException(typeof(Cookie), ex);
     } catch (Exception ex) {
         throw new SeleniumException(ex);
     }
 }
Esempio n. 13
0
        public static ArchiveProperties PropertiesFromMap(Dictionary<string, string> properties)
        {
            Contract.Requires(properties != null);

            var result = new ArchiveProperties { Name = properties.GetValue("Path") };
            if (string.IsNullOrEmpty(result.Name)) {
                throw new ArgumentException("Archive properties do not contain path.", nameof(properties));
            }

            result.Type = Archive.StringToType(properties.GetValue("Type"));
            result.Size = SevenZipTools.LongFromString(properties.GetValue("Size"));
            result.PhysicalSize = SevenZipTools.LongFromString(properties.GetValue("Physical Size"));
            result.TotalPhysicalSize = SevenZipTools.LongFromString(properties.GetValue("Total Physical Size"));
            return result;
        }
Esempio n. 14
0
        public void Restore(Session session, NetClient netClient, Dictionary <string, string> target)
        {
            var cnt = netClient ?? session?.NetClient;

            var data = target?.GetValue(KeyPrefix);

            if (data.IsNullOrEmpty() || cnt == null)
            {
                return;
            }

            try
            {
                var bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                var ms = new MemoryStream(Convert.FromBase64String(data));
                var cookieContainer = bf.Deserialize(ms) as CookieContainer;
                ms.Close();

                if (cookieContainer != null)
                {
                    cnt.CookieContainer = cookieContainer;
                }
            }
            catch (Exception e)
            {
            }
        }
Esempio n. 15
0
 public VarietyPairSurrogate(VarietyPair vp)
 {
     Variety1 = vp.Variety1.Name;
     Variety2 = vp.Variety2.Name;
     var wordPairSurrogates = new Dictionary<WordPair, WordPairSurrogate>();
     _wordPairs = vp.WordPairs.Select(wp => wordPairSurrogates.GetValue(wp, () => new WordPairSurrogate(wp))).ToList();
     PhoneticSimilarityScore = vp.PhoneticSimilarityScore;
     LexicalSimilarityScore = vp.LexicalSimilarityScore;
     DefaultSoundCorrespondenceProbability = vp.DefaultSoundCorrespondenceProbability;
     _cognateSoundCorrespondenceFrequencyDistribution = new Dictionary<SoundContextSurrogate, Tuple<string[], int>[]>();
     foreach (SoundContext lhs in vp.CognateSoundCorrespondenceFrequencyDistribution.Conditions)
     {
         FrequencyDistribution<Ngram<Segment>> freqDist = vp.CognateSoundCorrespondenceFrequencyDistribution[lhs];
         _cognateSoundCorrespondenceFrequencyDistribution[new SoundContextSurrogate(lhs)] = freqDist.ObservedSamples.Select(ngram => Tuple.Create(ngram.Select(seg => seg.StrRep).ToArray(), freqDist[ngram])).ToArray();
     }
     _cognateSoundCorrespondenceByPosition = new Dictionary<string, List<SoundCorrespondenceSurrogate>>();
     foreach (KeyValuePair<FeatureSymbol, SoundCorrespondenceCollection> kvp in vp.CognateSoundCorrespondencesByPosition)
     {
         string pos;
         if (kvp.Key == CogFeatureSystem.Onset)
             pos = "onset";
         else if (kvp.Key == CogFeatureSystem.Nucleus)
             pos = "nucleus";
         else
             pos = "coda";
         _cognateSoundCorrespondenceByPosition[pos] = kvp.Value.Select(corr => new SoundCorrespondenceSurrogate(wordPairSurrogates, corr)).ToList();
     }
 }
        public void GetValue_Absent_Empty()
        {
            var dictiionary = new Dictionary<string, int> { { "A", 1 } };
            Option<int> item = dictiionary.GetValue("B");

            Assert.False(item.HasValue);
        }
		/// <summary>
		/// 认证
		/// </summary>
		/// <param name="strUserID"></param>
		/// <param name="strPassword"></param>
		/// <param name="context">一些额外的参数</param>
		/// <returns></returns>
		public ISignInUserInfo Authenticate(string strUserID, string strPassword, Dictionary<string, object> context)
		{
			LogOnIdentity loi = new LogOnIdentity(strUserID, strPassword);

			DefaultSignInUserInfo signInUserInfo = new DefaultSignInUserInfo();

			string authCode = context.GetValue("AuthenticationCode", string.Empty);

			//是否使用验证码认证
			if (authCode.IsNotEmpty())
			{
				AuthenticationCodeAdapter.Instance.CheckAuthenticationCode(authCode, strPassword);
			}
			else
			{
				if (AuthenticateUser(loi) == false)
				{
					IEnumerable<string> alternativeUserIDs = context.GetValue("AlternativeUserIDs", (IEnumerable<string>)null);

					if (AuthenticateAlternativeUserIDs(alternativeUserIDs, strPassword, context) == false)
						AuthenticateException.ThrowAuthenticateException(loi.LogOnNameWithoutDomain);
				}
			}

			signInUserInfo.UserID = loi.LogOnNameWithoutDomain;
			signInUserInfo.Domain = loi.Domain;

			return signInUserInfo;
		}
Esempio n. 18
0
    public SVGPolylineElement(Dictionary<string,string> attrList,
		SVGTransformList inheritTransformList,
		SVGPaintable inheritPaintable,
		SVGGraphics render)
        : base(attrList, inheritTransformList, inheritPaintable, render)
    {
        _listPoints = ExtractPoints(attrList.GetValue("points"));
    }
        public void GetValue_Exists_Value()
        {
            var dictiionary = new Dictionary<string, int> { { "A", 1 } };
            Option<int> item = dictiionary.GetValue("A");

            Assert.True(item.HasValue);
            Assert.Equal(1, item.Value);
        }
Esempio n. 20
0
    public SVGRadialGradientElement(SVGParser xmlImp, Dictionary<string, string> attrList)
        : base(xmlImp, attrList)
    {
        string temp = attrList.GetValue("cx");
        _cx = new SVGLength((temp == "") ? "50%" : temp);

        temp = attrList.GetValue("cy");
        _cy = new SVGLength((temp == "") ? "50%" : temp);

        temp = attrList.GetValue("r");
        _r = new SVGLength((temp == "") ? "50%" : temp);

        temp = attrList.GetValue("fx");
        _fx = new SVGLength((temp == "") ? "50%" : temp);

        temp = attrList.GetValue("fy");
        _fy = new SVGLength((temp == "") ? "50%" : temp);
    }
Esempio n. 21
0
		PositionedNode MatchNode(PositionedNode oldNode, Dictionary<int, PositionedNode> newNodeMap)
		{
			PositionedNode newNodeFound = newNodeMap.GetValue(oldNode.ObjectNode.HashCode);
			if ((newNodeFound != null) && IsSameAddress(oldNode, newNodeFound))	{
				return newNodeFound;
			} else {
				return null;
			}
		}
Esempio n. 22
0
 /// <summary>
 /// Stores the message with the given headers and body data, delaying it until the specified <paramref name="approximateDueTime"/>
 /// </summary>
 public async Task Defer(DateTimeOffset approximateDueTime, Dictionary<string, string> headers, byte[] body)
 {
     lock (_deferredMessages)
     {
         _deferredMessages
             .AddOrUpdate(headers.GetValue(Headers.MessageId),
                 id => new DeferredMessage(approximateDueTime, headers, body),
                 (id, existing) => existing);
     }
 }
Esempio n. 23
0
    public SVGRadialGradientElement(SVGParser xmlImp, Dictionary<string, string> attrList)
        : base(xmlImp, attrList)
    {
        // TODO: Override GetValue to return `null` and use `||`.
        string temp = attrList.GetValue("cx");
        _cx = new SVGLength((temp == "") ? "50%" : temp);

        temp = attrList.GetValue("cy");
        _cy = new SVGLength((temp == "") ? "50%" : temp);

        temp = attrList.GetValue("r");
        _r = new SVGLength((temp == "") ? "50%" : temp);

        temp = attrList.GetValue("fx");
        _fx = new SVGLength((temp == "") ? "50%" : temp);

        temp = attrList.GetValue("fy");
        _fy = new SVGLength((temp == "") ? "50%" : temp);
    }
Esempio n. 24
0
        public override void ExecuteCommand(WebSocket session, WebSocketCommandInfo commandInfo)
        {
            var dict = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);

            commandInfo.Text.ParseMimeHeader(dict);

            string websocketVersion = dict.GetValue(m_WebSocketVersion, string.Empty);

            if (!session.NotSpecifiedVersion)
            {
                if (string.IsNullOrEmpty(websocketVersion))
                    session.FireError(new Exception("the server doesn't support the websocket protocol version your client was using"));
                else
                    session.FireError(new Exception(string.Format("the server(version: {0}) doesn't support the websocket protocol version your client was using", websocketVersion)));
                session.CloseWithoutHandshake();
                return;
            }

            if (string.IsNullOrEmpty(websocketVersion))
            {
                session.FireError(new Exception("unknown server protocol version"));
                session.CloseWithoutHandshake();
                return;
            }

            var versions = websocketVersion.Split(',');

            versions = versions.Where((x) => x.Trim().Length > 0).ToArray();

            var versionValues = new int[versions.Length];

            for (var i = 0; i < versions.Length; i++)
            {
                try
                {
                    int value = int.Parse(versions[i]);
                    versionValues[i] = value;
                }
                catch (FormatException)
                {
                    session.FireError(new Exception("invalid websocket version"));
                    session.CloseWithoutHandshake();
                    return;
                }
            }

            if (!session.GetAvailableProcessor(versionValues))
            {
                session.FireError(new Exception("unknown server protocol version"));
                session.CloseWithoutHandshake();
                return;
            }

            session.ProtocolProcessor.SendHandshake(session);
        }
Esempio n. 25
0
        public async Task Defer(DateTimeOffset approximateDueTime, Dictionary<string, string> headers, byte[] body)
        {
            var newTimeout = new Timeout(headers, body, approximateDueTime.UtcDateTime);
            _log.Debug("Deferring message with ID {0} until {1} (doc ID {2})", headers.GetValue(Headers.MessageId), approximateDueTime, newTimeout.Id);

            using (var session = _documentStore.OpenAsyncSession())
            {
                await session.StoreAsync(newTimeout);
                await session.SaveChangesAsync();
            }
        }
Esempio n. 26
0
        public override void ExecuteCommand(WebSocket session, WebSocketCommandInfo commandInfo)
        {
            var dict = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
            var verbLine = string.Empty;

            commandInfo.Text.ParseMimeHeader(dict, out verbLine);

            string websocketVersion = dict.GetValue(m_WebSocketVersion, string.Empty);

            if (!session.NotSpecifiedVersion)
            {
                if (string.IsNullOrEmpty(websocketVersion))
                    session.FireError(new Exception("the server doesn't support the websocket protocol version your client was using"));
                else
                    session.FireError(new Exception(string.Format("the server(version: {0}) doesn't support the websocket protocol version your client was using", websocketVersion)));
                session.CloseWithoutHandshake();
                return;
            }

            if (string.IsNullOrEmpty(websocketVersion))
            {
                session.FireError(new Exception("unknown server protocol version"));
                session.CloseWithoutHandshake();
                return;
            }

            var versions = websocketVersion.Split(m_ValueSeparator, StringSplitOptions.RemoveEmptyEntries);

            var versionValues = new int[versions.Length];

            for (var i = 0; i < versions.Length; i++)
            {
                int value;

                if (!int.TryParse(versions[i], out value))
                {
                    session.FireError(new Exception("invalid websocket version"));
                    session.CloseWithoutHandshake();
                    return;
                }

                versionValues[i] = value;
            }

            if (!session.GetAvailableProcessor(versionValues))
            {
                session.FireError(new Exception("unknown server protocol version"));
                session.CloseWithoutHandshake();
                return;
            }

            session.ProtocolProcessor.SendHandshake(session);
        }
        public void GetValueShouldStoreNewValuesAfterCallingTheValueInitializerOnce()
        {
            var dictionary = new Dictionary<string, string>
            {
                { "foo", "bar" }
            };

            var dictionaryLock = new object();

            // Arrange
            dictionary.GetValue("bar", dictionaryLock, () => "qak");

            // Act
            dictionary.GetValue(
                "bar",
                dictionaryLock,
                () =>
                {
                    // Assert
                    Assert.Fail("Value initializer should not have been called a second time.");
                    return null;
                });
        }
Esempio n. 28
0
    public SVGSVGElement(SVGParser xmlImp,
                       SVGTransformList inheritTransformList,
                       SVGPaintable inheritPaintable,
                       SVGGraphics r)
        : base(inheritTransformList)
    {
        _render = r;
        _attrList = xmlImp.Node.Attributes;
        var paintable = new SVGPaintable(inheritPaintable, _attrList);
        _width = new SVGLength(_attrList.GetValue("width"));
        _height = new SVGLength(_attrList.GetValue("height"));

        SetViewBox();

        ViewBoxTransform();

        SVGTransform temp = new SVGTransform(_cachedViewBoxTransform);
        SVGTransformList t_currentTransformList = new SVGTransformList();
        t_currentTransformList.AppendItem(temp);
        currentTransformList = t_currentTransformList; // use setter only once, since it also updates other lists

        xmlImp.GetElementList(_elementList, paintable, _render, summaryTransformList);
    }
        protected override string GenerateContent(IDataContext context, string outputFolder)
        {
            const string caTopicId = "CA_Chunks";
              var caLibrary = XmlHelpers.CreateHmTopic(caTopicId);
              var tablesByLanguage = new Dictionary<string, XElement>();
              var sortedActions = context.GetComponent<IContextActionTable>().AllActions.OrderBy(ca => ca.Name);
              var caPath = GeneralHelpers.GetCaPath(context);

              caLibrary.Root.Add(
            new XComment("Total context actions in ReSharper " +
                     GeneralHelpers.GetCurrentVersion() + ": " +
                     sortedActions.Count()));
              foreach (var ca in sortedActions)
              {
            var lang = ca.Group ?? "Unknown";

            if (!tablesByLanguage.ContainsKey(lang))
              tablesByLanguage.Add(lang,
            XmlHelpers.CreateTwoColumnTable("Name",
              "Description", "40%"));

            var exampleTable = ExtractExamples(ca, caPath, lang);

            tablesByLanguage.GetValue(lang).Add(new XElement("tr",
              new XElement("td", new XElement("b", ca.Name)),
              new XElement("td",
            ca.Description ?? "", exampleTable,
            XmlHelpers.CreateInclude("CA_Static_Chunks",
              ca.MergeKey.NormalizeStringForAttribute()))));
              }

              foreach (var table in tablesByLanguage)
              {
            var languageChunk =
              XmlHelpers.CreateChunk("ca_" +
                                 table.Key
                                   .NormalizeStringForAttribute());
            string langText = table.Key == "Common"
              ? "common use"
              : table.Key;
            languageChunk.Add(new XElement("p",
              "ReSharper provides the following context actions for " +
              langText + ":"));
            languageChunk.Add(table.Value);
            caLibrary.Root.Add(languageChunk);
              }

              caLibrary.Save(Path.Combine(outputFolder, caTopicId + ".xml"));
              return "Context actions";
        }
        public void GetValueShouldReturnExistingValueWithoutUsingTheLock()
        {
            var dictionary = new Dictionary<string, string>
            {
                { "foo", "bar" }
            };

            // Act
            // null can't be used as a lock and will throw an exception if attempted
            var value = dictionary.GetValue("foo", null, null);

            // Assert
            Assert.AreEqual("bar", value);
        }
Esempio n. 31
0
        public ListSegmentMappings(Segmenter segmenter, IEnumerable<UnorderedTuple<string, string>> mappings, bool implicitComplexSegments)
        {
            _segmenter = segmenter;
            _mappings = mappings.ToList();
            _implicitComplexSegments = implicitComplexSegments;

            _mappingLookup = new Dictionary<string, Dictionary<string, List<Tuple<Environment, Environment>>>>();
            foreach (UnorderedTuple<string, string> mapping in _mappings)
            {
                FeatureSymbol leftEnv1, rightEnv1, leftEnv2, rightEnv2;
                string str1, str2;
                if (Normalize(_segmenter, mapping.Item1, out str1, out leftEnv1, out rightEnv1) && Normalize(_segmenter, mapping.Item2, out str2, out leftEnv2, out rightEnv2))
                {
                    var env1 = new Environment(leftEnv1, rightEnv1);
                    var env2 = new Environment(leftEnv2, rightEnv2);
                    Dictionary<string, List<Tuple<Environment, Environment>>> segments = _mappingLookup.GetValue(str1, () => new Dictionary<string, List<Tuple<Environment, Environment>>>());
                    List<Tuple<Environment, Environment>> contexts = segments.GetValue(str2, () => new List<Tuple<Environment, Environment>>());
                    contexts.Add(Tuple.Create(env1, env2));
                    segments = _mappingLookup.GetValue(str2, () => new Dictionary<string, List<Tuple<Environment, Environment>>>());
                    contexts = segments.GetValue(str1, () => new List<Tuple<Environment, Environment>>());
                    contexts.Add(Tuple.Create(env2, env1));
                }
            }
        }
Esempio n. 32
0
        private PaymentFacade(PayGatewayTypes gatewayType, CommonPayConfig payConfig)
        {
            if (payConfig == null)
            {
                throw new ArgumentNullException(nameof(payConfig), "未提供支付平台配置");
            }

            _paymentGateway = gatewayType switch
            {
                PayGatewayTypes.WxJsApiPay => new WxJsApiPayGateway(payConfig),
                _ => _gatewayBuilders?.GetValue(gatewayType)?.Invoke(payConfig)
            };

            if (_paymentGateway == null)
            {
                throw new ArgumentOutOfRangeException("gatewayType", "未知的支付方式");
            }
            _paymentGateway.GatewayType = gatewayType;
        }
        public void Restore(Session session, NetClient netClient, Dictionary <string, string> target)
        {
            if (session == null)
            {
                return;
            }

            var data = target?.GetValue(KeyPrefix);

            if (data == null)
            {
                return;
            }

            var host = new HostContext(session);
            var fp   = JsonConvert.DeserializeObject <FingerprintInfo>(data);

            host.FingerprintInfo = fp;
            host.SetFingerprintInfoToSession();
        }
 /// <summary>
 /// 获得指定的属性
 /// </summary>
 /// <typeparam name="T">属性值类型</typeparam>
 /// <param name="key">键名</param>
 /// <returns>指定的键值</returns>
 public T GetProperty <T>(string key)
 {
     return((T)Properties.GetValue(key));
 }
Esempio n. 35
0
 public double this[string key] {
     get { return(_Statistics.GetValue(key)); } set { _Statistics[key] = value; }
 }
Esempio n. 36
0
 public string GetNotice(NoticeType notice) => noticeDic.GetValue(notice);
Esempio n. 37
0
        public IBidirectionalGraph <GlobalCorrespondencesGraphVertex, GlobalCorrespondencesGraphEdge> GenerateGlobalCorrespondencesGraph(SyllablePosition syllablePosition, IEnumerable <Variety> varieties)
        {
            var        varietiesSet = new HashSet <Variety>(varieties);
            CogProject project      = _projectService.Project;
            var        graph        = new BidirectionalGraph <GlobalCorrespondencesGraphVertex, GlobalCorrespondencesGraphEdge>();
            var        vertices     = new Dictionary <object, GlobalSegmentVertex>();
            var        edges        = new Dictionary <UnorderedTuple <object, object>, GlobalCorrespondencesGraphEdge>();
            int        maxFreq      = 0;

            if (syllablePosition == SyllablePosition.Nucleus)
            {
                graph.AddVertexRange(new GlobalCorrespondencesGraphVertex[]
                {
                    new VowelBacknessVertex(VowelBackness.Front),
                    new VowelBacknessVertex(VowelBackness.Central),
                    new VowelBacknessVertex(VowelBackness.Back),

                    new VowelHeightVertex(VowelHeight.Close),
                    new VowelHeightVertex(VowelHeight.CloseMid),
                    new VowelHeightVertex(VowelHeight.OpenMid),
                    new VowelHeightVertex(VowelHeight.Open)
                });

                foreach (VarietyPair vp in project.VarietyPairs.Where(vp => varietiesSet.Contains(vp.Variety1) && varietiesSet.Contains(vp.Variety2)))
                {
                    foreach (SoundCorrespondence corr in vp.CognateSoundCorrespondencesByPosition[CogFeatureSystem.Nucleus])
                    {
                        VowelHeight   height1, height2;
                        VowelBackness backness1, backness2;
                        bool          round1, round2;
                        if (GetVowelInfo(corr.Segment1, out height1, out backness1, out round1) && GetVowelInfo(corr.Segment2, out height2, out backness2, out round2) &&
                            (height1 != height2 || backness1 != backness2 || round1 != round2))
                        {
                            Tuple <VowelHeight, VowelBackness, bool> key1 = Tuple.Create(height1, backness1, round1);
                            GlobalSegmentVertex vertex1 = vertices.GetValue(key1, () => new GlobalVowelVertex(height1, backness1, round1));
                            vertex1.StrReps.Add(corr.Segment1.StrRep);
                            Tuple <VowelHeight, VowelBackness, bool> key2 = Tuple.Create(height2, backness2, round2);
                            GlobalSegmentVertex vertex2 = vertices.GetValue(key2, () => new GlobalVowelVertex(height2, backness2, round2));
                            vertex2.StrReps.Add(corr.Segment2.StrRep);
                            int freq = AddEdge(edges, corr, key1, vertex1, key2, vertex2);
                            maxFreq = Math.Max(freq, maxFreq);
                        }
                    }
                }
            }
            else
            {
                graph.AddVertexRange(new GlobalCorrespondencesGraphVertex[]
                {
                    new ConsonantPlaceVertex(ConsonantPlace.Bilabial),
                    new ConsonantPlaceVertex(ConsonantPlace.Labiodental),
                    new ConsonantPlaceVertex(ConsonantPlace.Dental),
                    new ConsonantPlaceVertex(ConsonantPlace.Alveolar),
                    new ConsonantPlaceVertex(ConsonantPlace.Postalveolar),
                    new ConsonantPlaceVertex(ConsonantPlace.Retroflex),
                    new ConsonantPlaceVertex(ConsonantPlace.Palatal),
                    new ConsonantPlaceVertex(ConsonantPlace.Velar),
                    new ConsonantPlaceVertex(ConsonantPlace.Uvular),
                    new ConsonantPlaceVertex(ConsonantPlace.Pharyngeal),
                    new ConsonantPlaceVertex(ConsonantPlace.Glottal),

                    new ConsonantMannerVertex(ConsonantManner.Nasal),
                    new ConsonantMannerVertex(ConsonantManner.Stop),
                    new ConsonantMannerVertex(ConsonantManner.Affricate),
                    new ConsonantMannerVertex(ConsonantManner.Fricative),
                    new ConsonantMannerVertex(ConsonantManner.Approximant),
                    new ConsonantMannerVertex(ConsonantManner.FlapOrTap),
                    new ConsonantMannerVertex(ConsonantManner.Trill),
                    new ConsonantMannerVertex(ConsonantManner.LateralFricative),
                    new ConsonantMannerVertex(ConsonantManner.LateralApproximant)
                });

                foreach (VarietyPair vp in project.VarietyPairs.Where(vp => varietiesSet.Contains(vp.Variety1) && varietiesSet.Contains(vp.Variety2)))
                {
                    SoundCorrespondenceCollection corrs = null;
                    switch (syllablePosition)
                    {
                    case SyllablePosition.Onset:
                        corrs = vp.CognateSoundCorrespondencesByPosition[CogFeatureSystem.Onset];
                        break;

                    case SyllablePosition.Coda:
                        corrs = vp.CognateSoundCorrespondencesByPosition[CogFeatureSystem.Coda];
                        break;
                    }
                    Debug.Assert(corrs != null);
                    foreach (SoundCorrespondence corr in corrs)
                    {
                        ConsonantPlace  place1, place2;
                        ConsonantManner manner1, manner2;
                        bool            voiced1, voiced2;
                        if (GetConsonantPosition(corr.Segment1, out place1, out manner1, out voiced1) && GetConsonantPosition(corr.Segment2, out place2, out manner2, out voiced2) &&
                            (place1 != place2 || manner1 != manner2 || voiced1 != voiced2))
                        {
                            Tuple <ConsonantPlace, ConsonantManner, bool> key1 = Tuple.Create(place1, manner1, voiced1);
                            GlobalSegmentVertex vertex1 = vertices.GetValue(key1, () => new GlobalConsonantVertex(place1, manner1, voiced1));
                            vertex1.StrReps.Add(corr.Segment1.StrRep);
                            Tuple <ConsonantPlace, ConsonantManner, bool> key2 = Tuple.Create(place2, manner2, voiced2);
                            GlobalSegmentVertex vertex2 = vertices.GetValue(key2, () => new GlobalConsonantVertex(place2, manner2, voiced2));
                            vertex2.StrReps.Add(corr.Segment2.StrRep);

                            int freq = AddEdge(edges, corr, key1, vertex1, key2, vertex2);
                            maxFreq = Math.Max(freq, maxFreq);
                        }
                    }
                }
            }

            graph.AddVertexRange(vertices.Values);
            foreach (GlobalCorrespondencesGraphEdge edge in edges.Values)
            {
                edge.NormalizedFrequency = (double)edge.Frequency / maxFreq;
                graph.AddEdge(edge);
            }

            return(graph);
        }
Esempio n. 38
0
 /// <summary>
 /// get property value
 /// </summary>
 /// <typeparam name="VT"></typeparam>
 /// <param name="propertyName"></param>
 /// <returns></returns>
 public VT GetPropertyValue <VT>(string propertyName)
 {
     return(valueDict.GetValue <VT>(propertyName));
 }
Esempio n. 39
0
 public IEnumerable <string> GetHeaderValues(string headerName)
 {
     return(headers.GetValue(headerName.ToLower(), null));
 }
Esempio n. 40
0
 public TValue Get(TKey key, bool shouldLog404 = true)
 {
     return(dictionary.GetValue(key, shouldLog404));
 }
Esempio n. 41
0
 public DonationTransaction this[string id] {
     get { return(Transactions.GetValue(id)); }
 }
Esempio n. 42
0
 public string GetInventory(InventoryType inventory) => inventoryDic.GetValue(inventory);
Esempio n. 43
0
 public System ReferenceObject(object obj)
 {
     return(systems_by_target.GetValue(obj));
 }
Esempio n. 44
0
        private void ExecuteTestForTab(string test, TabInfo tab, FriendlyUrlSettings settings, Dictionary <string, string> testFields)
        {
            var    httpAlias    = testFields["Alias"];
            var    defaultAlias = testFields.GetValue("DefaultAlias", String.Empty);
            var    tabName      = testFields["Page Name"];
            var    scheme       = testFields["Scheme"];
            var    parameters   = testFields["Params"];
            var    result       = testFields["Expected Url"];
            var    customPage   = testFields.GetValue("Custom Page Name", _defaultPage);
            string vanityUrl    = testFields.GetValue("VanityUrl", String.Empty);

            var httpAliasFull  = scheme + httpAlias + "/";
            var expectedResult = result.Replace("{alias}", httpAlias)
                                 .Replace("{usealias}", defaultAlias)
                                 .Replace("{tabName}", tabName)
                                 .Replace("{tabId}", tab.TabID.ToString())
                                 .Replace("{vanityUrl}", vanityUrl)
                                 .Replace("{defaultPage}", _defaultPage);


            if (!String.IsNullOrEmpty(parameters) && !parameters.StartsWith("&"))
            {
                parameters = "&" + parameters;
            }

            var userName = testFields.GetValue("UserName", String.Empty);

            if (!String.IsNullOrEmpty(userName))
            {
                var user = UserController.GetUserByName(PortalId, userName);
                if (user != null)
                {
                    expectedResult = expectedResult.Replace("{userId}", user.UserID.ToString());
                    parameters     = parameters.Replace("{userId}", user.UserID.ToString());
                }
            }


            var    baseUrl = httpAliasFull + "Default.aspx?TabId=" + tab.TabID + parameters;
            string testUrl;

            if (test == "Base")
            {
                testUrl = AdvancedFriendlyUrlProvider.BaseFriendlyUrl(tab,
                                                                      baseUrl,
                                                                      customPage,
                                                                      httpAlias,
                                                                      settings);
            }
            else
            {
                testUrl = AdvancedFriendlyUrlProvider.ImprovedFriendlyUrl(tab,
                                                                          baseUrl,
                                                                          customPage,
                                                                          httpAlias,
                                                                          true,
                                                                          settings,
                                                                          Guid.Empty);
            }

            Assert.AreEqual(expectedResult, testUrl);
        }
 /// <summary>Gets the factory of the entity with the .NET type specified</summary>
 /// <param name="typeOfEntity">The type of entity.</param>
 /// <returns>factory to use or null if not found</returns>
 public static IEntityFactory2 GetFactory(Type typeOfEntity)
 {
     return(_factoryPerType.GetValue(typeOfEntity));
 }
 public XRButtonDatum GetButtonDatum(XRInputName inputName)
 {
     return(ButtonDatums.GetValue((int)inputName));
 }
Esempio n. 47
0
        /***************************************************/
        /****              Public methods               ****/
        /***************************************************/

        public static Floor ToRevitFloor(this oM.Physical.Elements.Floor floor, Document document, RevitSettings settings = null, Dictionary <Guid, List <int> > refObjects = null)
        {
            if (floor == null || floor.Construction == null || document == null)
            {
                return(null);
            }

            Floor revitFloor = refObjects.GetValue <Floor>(document, floor.BHoM_Guid);

            if (revitFloor != null)
            {
                return(revitFloor);
            }

            PlanarSurface planarSurface = floor.Location as PlanarSurface;

            if (planarSurface == null)
            {
                return(null);
            }

            settings = settings.DefaultIfNull();

            FloorType floorType = floor.Construction?.ToRevitElementType(document, new List <BuiltInCategory> {
                BuiltInCategory.OST_Floors
            }, settings, refObjects) as FloorType;

            if (floorType == null)
            {
                floorType = floor.ElementType(document, settings);
            }

            if (floorType == null)
            {
                Compute.ElementTypeNotFoundWarning(floor);
                return(null);
            }

            double bottomElevation = floor.Location.IBounds().Min.Z;
            Level  level           = document.LevelBelow(bottomElevation.FromSI(UnitType.UT_Length), settings);

            oM.Geometry.Plane sketchPlane = new oM.Geometry.Plane {
                Origin = new BH.oM.Geometry.Point {
                    Z = bottomElevation
                }, Normal = Vector.ZAxis
            };
            ICurve     curve      = planarSurface.ExternalBoundary.IProject(sketchPlane);
            CurveArray curveArray = Create.CurveArray(curve.IToRevitCurves());

            BH.oM.Geometry.Plane slabPlane = planarSurface.FitPlane();
            if (1 - Math.Abs(Vector.ZAxis.DotProduct(slabPlane.Normal)) <= settings.AngleTolerance)
            {
                revitFloor = document.Create.NewFloor(curveArray, floorType, level, true);
            }
            else
            {
                Vector normal = slabPlane.Normal;
                if (normal.Z < 0)
                {
                    normal = -slabPlane.Normal;
                }

                double angle = normal.Angle(Vector.ZAxis);
                double tan   = Math.Tan(angle);

                XYZ dir = normal.Project(oM.Geometry.Plane.XY).ToRevit().Normalize();
                BH.oM.Geometry.Line ln = slabPlane.PlaneIntersection(sketchPlane);
                XYZ start = ln.ClosestPoint(curveArray.get_Item(0).GetEndPoint(0).PointFromRevit(), true).ToRevit();
                Autodesk.Revit.DB.Line line = Autodesk.Revit.DB.Line.CreateBound(start, start + dir);

                revitFloor = document.Create.NewSlab(curveArray, level, line, -tan, true);
                revitFloor.SetParameter(BuiltInParameter.ELEM_TYPE_PARAM, floorType.Id);
            }

            revitFloor.CheckIfNullPush(floor);
            if (revitFloor == null)
            {
                return(null);
            }

            document.Regenerate();

            if (planarSurface.InternalBoundaries != null)
            {
                foreach (ICurve hole in planarSurface.InternalBoundaries)
                {
                    document.Create.NewOpening(revitFloor, Create.CurveArray(hole.IProject(slabPlane).IToRevitCurves()), true);
                }
            }

            foreach (BH.oM.Physical.Elements.IOpening opening in floor.Openings)
            {
                PlanarSurface openingLocation = opening.Location as PlanarSurface;
                if (openingLocation == null)
                {
                    BH.Engine.Reflection.Compute.RecordWarning(String.Format("Conversion of a floor opening to Revit failed because its location is not a planar surface. Floor BHoM_Guid: {0}, Opening BHoM_Guid: {1}", floor.BHoM_Guid, opening.BHoM_Guid));
                    continue;
                }

                document.Create.NewOpening(revitFloor, Create.CurveArray(openingLocation.ExternalBoundary.IToRevitCurves()), true);

                if (!(opening is BH.oM.Physical.Elements.Void))
                {
                    BH.Engine.Reflection.Compute.RecordWarning(String.Format("Revit allows only void openings in floors, therefore the BHoM opening of type {0} has been converted to a void opening. Floor BHoM_Guid: {1}, Opening BHoM_Guid: {2}", opening.GetType().Name, floor.BHoM_Guid, opening.BHoM_Guid));
                }
            }

            double offset = revitFloor.LookupParameterDouble(BuiltInParameter.FLOOR_HEIGHTABOVELEVEL_PARAM);

            // Copy parameters from BHoM object to Revit element
            revitFloor.CopyParameters(floor, settings);

            // Update the offset in case the level had been overwritten.
            if (revitFloor.LevelId.IntegerValue != level.Id.IntegerValue)
            {
                Level newLevel = document.GetElement(revitFloor.LevelId) as Level;
                offset += (level.ProjectElevation - newLevel.ProjectElevation).ToSI(UnitType.UT_Length);
            }

            revitFloor.SetParameter(BuiltInParameter.FLOOR_HEIGHTABOVELEVEL_PARAM, offset);

            refObjects.AddOrReplace(floor, revitFloor);
            return(revitFloor);
        }
 protected override void BeforeSave(Dictionary <string, string> dic, S_UI_Form formInfo, bool isNew)
 {
     ValidateConfirmNode(dic.GetValue("InvoiceID"), dic.GetValue("InvoiceConfirmID"));
 }
Esempio n. 49
0
 public string GetKeyActionName(KeyActionType ui) => keyActionDic.GetValue(ui);
Esempio n. 50
0
        /// <summary>
        /// Subscribes to additional scripting events that are not called directly;
        /// MUST be called in GameStartDone or later because World is used
        /// </summary>
        public static void InitEvents()
        {
            // A lot of other methods are already calling InvokeScriptEvents(..) directly.
            // Here are just the ones that need to be attached to actual events.
            // See enum ScriptEvents and it's usages for a full list of supported scripting events.

            // Called when a player got kicked due to failed EAC check
            EacTools.PlayerKicked += delegate(ClientInfo clientInfo, GameUtils.KickPlayerData kickPlayerData)
            {
                InvokeScriptEvents(ScriptEvent.eacPlayerKicked, () => new EacPlayerKickedEventArgs()
                {
                    reason     = kickPlayerData.ToString(),
                    clientInfo = clientInfo,
                });
            };

            // Called when a player successfully passed the EAC check
            EacTools.AuthenticationSuccessful += delegate(ClientInfo clientInfo)
            {
                InvokeScriptEvents(ScriptEvent.eacPlayerAuthenticated, () => new EacPlayerAuthenticatedEventArgs()
                {
                    clientInfo = clientInfo,
                });
            };

            // Called when the server was registered with Steam and announced to the master servers (also done for non-public dedicated servers)
            Steam.Masterserver.Server.AddEventServerRegistered(delegate()
            {
                InvokeScriptEvents(ScriptEvent.serverRegistered, () => new ServerRegisteredEventArgs()
                {
                    gameInfos = Steam.Masterserver.Server.LocalGameInfo.GetDisplayValues() // dictionary of all relevant game infos
                });
            });

            // Called when ANY Unity thread logs an error message, incl. the main thread
            Application.logMessageReceivedThreaded += delegate(string condition, string trace, LogType logType)
            {
                InvokeScriptEvents(ScriptEvent.logMessageReceived, () => new LogMessageReceivedEventArgs()
                {
                    logType   = logType.ToString(),
                    condition = condition.TrimEnd(),
                    trace     = trace.TrimEnd(),
                });
            };

            var world = GameManager.Instance.World ?? throw new NullReferenceException(Resources.ErrorWorldNotReady);

            // Called when any entity (zombie, item, air drop, player, ...) is spawned in the world, both loaded and newly created
            world.EntityLoadedDelegates += delegate(Entity entity)
            {
                InvokeScriptEvents(ScriptEvent.entityLoaded, () => new EntityLoadedEventArgs()
                {
                    entityType = entity.GetType().ToString(),
                    entityId   = entity.entityId,
                    entityName = (entity as EntityAlive)?.EntityName,
                    position   = entity.GetBlockPosition(),
                });
            };

            // Called when any entity (zombie, item, air drop, player, ...) disappears from the world, e.g. it got killed, picked up, despawned, logged off, ...
            world.EntityUnloadedDelegates += delegate(Entity entity, EnumRemoveEntityReason reason)
            {
                InvokeScriptEvents(ScriptEvent.entityUnloaded, () => new EntityUnloadedEventArgs()
                {
                    reason     = reason.ToString(),
                    entityType = entity.GetType().ToString(),
                    entityId   = entity.entityId,
                    entityName = (entity as EntityAlive)?.EntityName,
                    position   = entity.GetBlockPosition(),
                });
            };

            // Called when chunks change display status, i.e. either get displayed or stop being displayed.
            // chunkLoaded   -> Called when a chunk is loaded into the game engine because a player needs it. Called frequently - use with care!
            // chunkUnloaded -> Called when a chunk is unloaded from the game engine because it is not used by any player anymore. Called frequently - use with care!
            world.ChunkCache.OnChunkVisibleDelegates += delegate(long chunkKey, bool displayed)
            {
                InvokeScriptEvents(displayed ? ScriptEvent.chunkLoaded : ScriptEvent.chunkUnloaded, () => new ChunkLoadedUnloadedEventArgs()
                {
                    chunkKey = chunkKey,
                    chunkPos = ChunkTools.ChunkKeyToChunkXZ(chunkKey)
                });
            };

            // Called when game stats change including EnemyCount and AnimalCount, so it's called frequently. Use with care!
            GameStats.OnChangedDelegates += delegate(EnumGameStats gameState, object newValue)
            {
                // Often this event is called for values that are not actually changed, so we keep track whether the value was *actually* changed
                object oldValue;
                bool   valueChanged;
                lock (_lastGameStats)
                {
                    oldValue     = _lastGameStats.GetValue(gameState);
                    valueChanged = (oldValue == null || !oldValue.Equals(newValue));
                    if (valueChanged)
                    {
                        _lastGameStats[gameState] = newValue;
                    }
                }
                if (valueChanged)
                {
                    InvokeScriptEvents(ScriptEvent.gameStatsChanged, () =>
                    {
                        // Save values of a supported types as it is, all others as string for JSON output
                        var jsonSupportedOld = (oldValue == null || oldValue is int || oldValue is long || oldValue is float || oldValue is double || oldValue is bool);
                        var jsonSupportedNew = (newValue == null || newValue is int || newValue is long || newValue is float || newValue is double || newValue is bool);
                        return(new GameStatsChangedEventArgs()
                        {
                            gameState = gameState.ToString(),
                            oldValue = jsonSupportedOld ? oldValue : oldValue.ToString(),
                            newValue = jsonSupportedNew ? newValue : newValue.ToString(),
                        });
                    });
                }
            };

            #region Event notes

            // ------------ Events intentionally removed -----------
            // - Steam.Instance.PlayerConnectedEv
            //   Called first when a player is connecting before any authentication.
            //   Removed because Api.PlayerLogin is also called before authentication and also contains clientInfo.networkPlayer.
            // - Steam.Instance.ApplicationQuitEv
            //   Called first when the server shuts, but sometimes called twice or three times, and sometimes not even once.
            //   Removed because it doesn't add much value and is unreliable.
            // - Steam.Instance.DestroyEv
            //   Called right before the game process ends as last event of shutdown.
            //   Removed because it doesn't add much value.
            // - Steam.Instance.DisconnectedFromServerEv
            //   Called after the game has disconnected from Steam servers and shuts down.
            //   Removed because it doesn't add much value.
            // - Steam.Instance.UpdateEv
            //   Invoked on every tick.
            //   Removed because too big performance impact for scripting event.
            // - Steam.Instance.LateUpdateEv
            //   Invoked on every tick.
            //   Removed because too big performance impact for scripting event.
            // - Steam.Instance.PlayerDisconnectedEv
            //   Called after a player disconnected, a chat message was distributed, and all associated game data has been unloaded.
            //   Removed because it's similar to "playerDisconnected" and the passed networkPlayer cannot be used on a disconnected client anyway.
            // - Application.logMessageReceived
            //   Called when main Unity thread logs an error message.
            //   Removed because it is included in logMessageReceivedThreaded.
            // - GameManager.Instance.OnWorldChanged
            //   Called on shutdown when the world becomes null. Not called on startup apparently.
            //   Removed because not useful
            // - GameManager.Instance.World.ChunkClusters.ChunkClusterChangedDelegates.
            //   Called on shutdown when the chunkCache is cleared; idx remains 0 tho. Not called on startup apparently.
            //   Removed because not useful.

            // --------- Events never invoked on dedicated server ----------
            // - Steam.ConnectedToServerEv
            // - Steam.FailedToConnectEv
            // - Steam.ServerInitializedEv
            // - GameManager.Instance.OnLocalPlayerChanged
            // - World.OnWorldChanged
            // - ChunkCluster.OnChunksFinishedDisplayingDelegates
            // - ChunkCluster.OnChunksFinishedLoadingDelegates
            // - MapObjectManager.ChangedDelegates
            // - ServerListManager.GameServerDetailsEvent
            // - MenuItemEntry.ItemClicked
            // - LocalPlayerManager.*
            // - Inventory.OnToolbeltItemsChangedInternal
            // - BaseObjective.ValueChanged
            // - UserProfile.*
            // - CraftingManager.RecipeUnlocked
            // - QuestJournal.* (from EntityPlayer.QuestJournal)
            // - QuestEventManager.*
            // - UserProfileManager.*

            // -------- TODO: Events to explore further --------
            // - MapVisitor - needs patching to attach to always newly created object; use-case questionable
            // - AIWanderingHordeSpawner.HordeArrivedDelegate hordeArrivedDelegate_0
            // - Entity.* for each zombie/player entity

            // ----------- TODO: More event ideas --------------
            // - Custom geo fencing: Ttrigger event when a player (or zombie) gets into a predefined area
            // - Trigger server events on quest progress/completion. - So server admins could award questing further, or even unlock account features like forum access on quest completions.
            // - Event for Explosions (TNT, dynamite, fuel barrel)
            // - Event for large collapses (say more than 50 blocks)
            // - Event for destruction of a car(e.g.to spawn a new car somewhere else)
            // - Event for idling more than X minutes
            // - Event for blacing bed
            // - Event for placing LCB
            // - Event on zombie/entity proximity (triggered when a player gets or leaves withing reach of X meters of a zombie) [Xyth]
            // - Exploring of new land
            // - Bloodmoon starting/ending
            // - Item was dropped [Xyth]
            // - Item durability hits zero [Xyth]
            // - Screamer spawned for a chunk/player/xyz [kenyer]
            // - AirDrop spawned
            // - Player banned
            // - Player unbanned
            // - New Player connected for first time
            // - Events for ScriptingMod things
            // - Command that triggers when someone is in the air for more than X seconds, to catch hackers [war4head]

            #endregion

            Log.Out("Subscribed to all relevant game events.");
        }
Esempio n. 51
0
 public SampleState(Dictionary serialized)
     : base(serialized)
 {
     Foo = serialized.GetValue <Integer>("foo");
     Bar = serialized.GetValue <Text>("bar");
 }
Esempio n. 52
0
 public string GetUIName(UIType ui) => uiDic.GetValue(ui);
Esempio n. 53
0
        public ITextDocument GetOpenDocument(FullPath path)
        {
            var fetchFromRdtOnce = _firstRun.Value;

            return(_openDocuments.GetValue(path));
        }
 public SourceSubmitContext GetContext(IOrderSubmitEventSource source)
 {
     return(_sources.GetValue(source));
 }
 public Maybe <TpProfilerStatisticRecord> this[ProfilerTarget target]
 {
     get { return(_data.GetValue(target)); }
 }
        public JsonResult ApproveWorkHourList(string SelectedData, string State)
        {
            Action action = () =>
            {
                if (string.IsNullOrEmpty(State))
                {
                    throw new Formula.Exceptions.BusinessException("未传入State,无法操作");
                }
                var       list      = JsonHelper.ToList(SelectedData);
                var       fo        = new WorkHourFO();
                SQLHelper hrDB      = SQLHelper.CreateSqlHelper(ConnEnum.HR);
                var       enumDef   = EnumBaseHelper.GetEnumDef("HR.WorkHourState");
                var       enumItems = new List <EnumItemInfo>();
                if (enumDef != null)
                {
                    enumItems = enumDef.EnumItem.ToList();
                }
                var _state = State;
                if (State == "Locked")
                {
                    _state = "Confirm";
                }
                var fieldDt = GetFieldTable(hrDB, "S_W_UserWorkHour");
                foreach (var item in list)
                {
                    var itemStateLevel = 0d;
                    var itemState      = item.GetValue("State");
                    if (enumItems.Any(a => a.Code == itemState))
                    {
                        itemStateLevel = enumItems.FirstOrDefault(a => a.Code == itemState).SortIndex.Value;
                    }
                    var fnStateLevel = 0d;
                    if (enumItems.Any(a => a.Code == State))
                    {
                        fnStateLevel = enumItems.FirstOrDefault(a => a.Code == State).SortIndex.Value;
                    }
                    if (fnStateLevel < itemStateLevel)
                    {
                        throw new Formula.Exceptions.BusinessException("已经【" + enumItems.FirstOrDefault(a => a.Code == itemState).Name
                                                                       + "】的数据不能再【" + enumItems.FirstOrDefault(a => a.Code == State).Name + "】,无法保存");
                    }
                    if (!item.ContainsKey(_state + "Value"))
                    {
                        throw new Formula.Exceptions.BusinessException("列表中不包含【" + _state + "Value】字段,无法保存");
                    }
                    if (!item.ContainsKey(_state + "Day"))
                    {
                        throw new Formula.Exceptions.BusinessException("列表中不包含【" + _state + "Day】字段,无法保存");
                    }
                    if (!item.ContainsKey(_state + "User"))
                    {
                        throw new Formula.Exceptions.BusinessException("列表中不包含【" + _state + "User】字段,无法保存");
                    }
                    if (!item.ContainsKey(_state + "Date"))
                    {
                        throw new Formula.Exceptions.BusinessException("列表中不包含【" + _state + "Date】字段,无法保存");
                    }
                    if (!item.ContainsKey("Is" + _state))
                    {
                        throw new Formula.Exceptions.BusinessException("列表中不包含【Is" + _state + "】字段,无法保存");
                    }
                    var id = item.GetValue("ID");

                    item.SetValue(_state + "User", this.CurrentUserInfo.UserID);
                    item.SetValue(_state + "UserName", this.CurrentUserInfo.UserName);
                    item.SetValue(_state + "Date", System.DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"));
                    item.SetValue("Is" + _state, "1");
                    item.SetValue("State", State);

                    decimal?workHourValue = null;
                    if (!string.IsNullOrEmpty(item.GetValue("WorkHourValue")))
                    {
                        workHourValue = decimal.Parse(item.GetValue("WorkHourValue"));
                    }
                    decimal?approveValue = null;
                    if (!string.IsNullOrEmpty(item.GetValue(_state + "Value")))
                    {
                        approveValue = decimal.Parse(item.GetValue(_state + "Value"));
                    }
                    if (approveValue == null)
                    {
                        approveValue = workHourValue;//审批工时为空时,默认审批工时=填报工时;
                    }
                    item.SetValue(_state + "Value", approveValue);
                    decimal?approveDay = fo.ConvertHourToDay(approveValue, workHourType, NormalHoursMax);
                    item.SetValue(_state + "Day", approveDay);

                    var sb = new StringBuilder();
                    sb.AppendLine(CreateUpdateSql(item, hrDB, "S_W_UserWorkHour", id, fieldDt));

                    var detailDic = new Dictionary <string, object>();
                    detailDic.SetValue("ID", FormulaHelper.CreateGuid());
                    detailDic.SetValue("S_W_UserWorkHourID", id);
                    detailDic.SetValue("SortIndex", 0);
                    detailDic.SetValue("ApproveValue", approveValue);
                    detailDic.SetValue("ApproveDay", approveDay);
                    detailDic.SetValue("ApproveDate", item.GetValue(_state + "Date"));
                    detailDic.SetValue("ApproveStep", State);
                    detailDic.SetValue("ApproveUser", this.CurrentUserInfo.UserID);
                    detailDic.SetValue("ApproveUserName", this.CurrentUserInfo.UserName);
                    sb.AppendLine(detailDic.CreateInsertSql(hrDB, "S_W_UserWorkHour_ApproveDetail", detailDic.GetValue("ID")));

                    var sql = sb.ToString();
                    hrDB.ExecuteNonQuery(sql);

                    if (State == "Locked")
                    {
                        #region 工时审批通过后写入成本数据
                        S_W_UserWorkHour workHourInfo = new S_W_UserWorkHour();
                        UpdateEntity <S_W_UserWorkHour>(workHourInfo, item);
                        workHourInfo.ImportToCost();
                        #endregion
                    }
                }
            };

            if (System.Configuration.ConfigurationManager.AppSettings["UseMsdtc"].ToLower() == "true")
            {
                using (TransactionScope ts = new TransactionScope())
                {
                    action();
                    ts.Complete();
                }
            }
            else
            {
                action();
            }

            return(Json(""));
        }
        public JsonResult RevertWorkHourList(string SelectedData)
        {
            Action action = () =>
            {
                var list   = JsonHelper.ToList(SelectedData);
                var fields = new string[] { "Step1Date", "Step1Day", "Step1Value", "Step1User", "Step1UserName",
                                            "Step2Date", "Step2Day", "Step2Value", "Step2User", "Step2UserName",
                                            "ConfirmDate", "ConfirmDay", "ConfirmValue", "ConfirmUser", "ConfirmUserName" };
                var       setStr = string.Join("= null,", fields) + "= null,IsStep1='0',IsStep2='0',IsConfirm='0',State='Create'";
                SQLHelper hrDB   = SQLHelper.CreateSqlHelper(ConnEnum.HR);
                foreach (var item in list)
                {
                    var id = item.GetValue("ID");
                    var sb = new StringBuilder();
                    sb.AppendLine(string.Format("update S_W_UserWorkHour set {0} where ID = '{1}'", setStr, id));

                    var detailDic = new Dictionary <string, object>();
                    detailDic.SetValue("ID", FormulaHelper.CreateGuid());
                    detailDic.SetValue("S_W_UserWorkHourID", id);
                    detailDic.SetValue("SortIndex", 0);
                    detailDic.SetValue("ApproveValue", 0);
                    detailDic.SetValue("ApproveDay", 0);
                    detailDic.SetValue("ApproveDate", System.DateTime.Now);
                    detailDic.SetValue("ApproveStep", "Revert");
                    detailDic.SetValue("ApproveUser", this.CurrentUserInfo.UserID);
                    detailDic.SetValue("ApproveUserName", this.CurrentUserInfo.UserName);
                    sb.AppendLine(detailDic.CreateInsertSql(hrDB, "S_W_UserWorkHour_ApproveDetail", detailDic.GetValue("ID")));

                    var sql = sb.ToString();
                    hrDB.ExecuteNonQuery(sql);

                    S_W_UserWorkHour workHourInfo = new S_W_UserWorkHour();
                    UpdateEntity <S_W_UserWorkHour>(workHourInfo, item);
                    workHourInfo.RevertCost();
                }
            };

            if (System.Configuration.ConfigurationManager.AppSettings["UseMsdtc"].ToLower() == "true")
            {
                using (TransactionScope ts = new TransactionScope())
                {
                    action();
                    ts.Complete();
                }
            }
            else
            {
                action();
            }

            return(Json(""));
        }
Esempio n. 58
0
        private async Task <Source> ProcessShow(ImportStats stats, Artist artist, PhishinShow fullShow, ArtistUpstreamSource src, Source dbSource, PerformContext ctx)
        {
            dbSource.has_jamcharts = fullShow.tags.Count(t => t.name == "Jamcharts") > 0;
            dbSource = await _sourceService.Save(dbSource);

            var sets = new Dictionary <string, SourceSet>();

            foreach (var track in fullShow.tracks)
            {
                var set = sets.GetValue(track.set);

                if (set == null)
                {
                    set = new SourceSet()
                    {
                        source_id  = dbSource.id,
                        index      = SetIndexForIdentifier(track.set),
                        name       = track.set_name,
                        is_encore  = track.set[0] == 'E',
                        updated_at = dbSource.updated_at
                    };

                    // this needs to be set after loading from the db
                    set.tracks = new List <SourceTrack>();

                    sets[track.set] = set;
                }
            }

            var setMaps = (await _sourceSetService.UpdateAll(dbSource, sets.Values))
                          .GroupBy(s => s.index)
                          .ToDictionary(kvp => kvp.Key, kvp => kvp.Single());

            foreach (var kvp in setMaps)
            {
                kvp.Value.tracks = new List <SourceTrack>();
            }

            foreach (var track in fullShow.tracks)
            {
                var set = setMaps[SetIndexForIdentifier(track.set)];
                set.tracks.Add(new SourceTrack()
                {
                    source_set_id  = set.id,
                    source_id      = dbSource.id,
                    title          = track.title,
                    duration       = track.duration / 1000,
                    track_position = track.position,
                    slug           = SlugifyTrack(track.title),
                    mp3_url        = track.mp3.Replace("http:", "https:"),
                    updated_at     = dbSource.updated_at,
                    artist_id      = artist.id
                });
            }

            stats.Created += (await _sourceTrackService.InsertAll(dbSource, setMaps.SelectMany(kvp => kvp.Value.tracks))).Count();

            await ProcessSetlistShow(stats, fullShow, artist, src, dbSource, sets);

            ResetTrackSlugCounts();

            return(dbSource);
        }
Esempio n. 59
0
 protected override void AfterSave(Dictionary <string, string> dic, S_UI_Form formInfo, bool isNew)
 {
     LoggerHelper.InserLogger("S_C_ProjectVideo", isNew ? EnumOperaType.Add : EnumOperaType.Update, dic.GetValue("ID"), dic.GetValue("EngineeringInfoID"), dic.GetValue("Title"));
 }
Esempio n. 60
0
 public List <DialogContent> GetDialogContentList(int index) => dialogDic.GetValue(index);