System.Collections.Generic.IEnumerable.Contains(char)

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

1263 Examples 7

19 Source : FaceDancer.cs
with MIT License
from 001SPARTaN

static void Main(string[] args)
        {
            int procId;
            string file;

            if (args.Length < 2)
            {
                file = "whoami /priv";
                if (args.Length == 0)
                {
                    // If we don't have a process ID as an argument, find winlogon.exe
                    procId = Process.GetProcessesByName("winlogon").First().Id;
                }
                else if (args[0].Contains('.'))
                {
                    procId = Process.GetProcessesByName("winlogon").First().Id;
                    if (args != null)
                    {
                        file = args[0];
                    }
                }
                else
                {
                    procId = Convert.ToInt32(args[0]);
                }
            }
            else
            {
                procId = Convert.ToInt32(args[0]);
                file = args[1];
            }
            Console.WriteLine("Stealing token from PID " + procId);

            IntPtr tokenHandle = IntPtr.Zero;
            IntPtr dupHandle = IntPtr.Zero;

            SafeWaitHandle procHandle = new SafeWaitHandle(Process.GetProcessById(procId).Handle, true);
            Console.WriteLine("Process handle: True");

            bool procToken = OpenProcessToken(procHandle.DangerousGetHandle(), (uint)TokenAccessLevels.MaximumAllowed, out tokenHandle);
            Console.WriteLine("OpenProcessToken: " + procToken);

            bool duplicateToken = DuplicateTokenEx(tokenHandle, (uint)TokenAccessLevels.MaximumAllowed, IntPtr.Zero, 
                (uint)TokenImpersonationLevel.Impersonation, TOKEN_TYPE.TokenImpersonation, out dupHandle);
            Console.WriteLine("DuplicateTokenEx: " + duplicateToken);
            WindowsIdenreplacedy ident = new WindowsIdenreplacedy(dupHandle);
            Console.WriteLine("Impersonated user: " + ident.Name);

            STARTUPINFO startInfo = new STARTUPINFO();

            PipeSecurity sec = new PipeSecurity();
            sec.SetAccessRule(new PipeAccessRule("NT AUTHORITY\\Everyone", PipeAccessRights.FullControl, AccessControlType.Allow));

            using (AnonymousPipeServerStream pipeServer = new AnonymousPipeServerStream(PipeDirection.In, HandleInheritability.Inheritable, 4096, sec))
            {
                using (AnonymousPipeClientStream pipeClient = new AnonymousPipeClientStream(PipeDirection.Out, pipeServer.ClientSafePipeHandle))
                {
                    // Set process to use anonymous pipe for input/output
                    startInfo.hStdOutput = pipeClient.SafePipeHandle.DangerousGetHandle();
                    startInfo.hStdError = pipeClient.SafePipeHandle.DangerousGetHandle();
                    startInfo.dwFlags = STARTF.STARTF_USESTDHANDLES | STARTF.STARTF_USESHOWWINDOW;
                    // END NAME PIPE INITIALIZATION

                    PROCESS_INFORMATION newProc = new PROCESS_INFORMATION();
                    using (StreamReader reader = new StreamReader(pipeServer))
                    {
                        bool createProcess = CreateProcessWithTokenW(dupHandle, IntPtr.Zero, null, file, IntPtr.Zero, IntPtr.Zero, "C:\\Temp", ref startInfo, out newProc);
                        Process proc = Process.GetProcessById(newProc.dwProcessId);
                        while (!proc.HasExited)
                        {
                            Thread.Sleep(1000);
                        }
                        pipeClient.Close();
                        string output = reader.ReadToEnd();
                        Console.WriteLine("Started process with ID " + newProc.dwProcessId);
                        Console.WriteLine("CreateProcess return code: " + createProcess);
                        Console.WriteLine("Process output: " + output);
                    }
                    
                    CloseHandle(tokenHandle);
                    CloseHandle(dupHandle);
                }
            }
        }

19 Source : StringEx.cs
with GNU General Public License v3.0
from 2dust

public static bool BeginWithAny(this string s, IEnumerable<char> chars)
        {
            if (s.IsNullOrEmpty()) return false;
            return chars.Contains(s[0]);
        }

19 Source : GCodeParser.cs
with MIT License
from 3RD-Dimension

static void Parse(string line, int lineNumber)
		{
			MatchCollection matches = GCodeSplitter.Matches(line);

			List<Word> Words = new List<Word>(matches.Count);

			foreach (Match match in matches)
			{
				Words.Add(new Word() { Command = match.Groups[1].Value[0], Parameter = double.Parse(match.Groups[2].Value, Constants.DecimalParseFormat) });
			}

			for (int i = 0; i < Words.Count; i++)
			{
				if (Words[i].Command == 'N')
				{
					Words.RemoveAt(i--);
					continue;
				}

				if (IgnoreAxes.Contains(Words[i].Command) && Properties.Settings.Default.IgnoreAdditionalAxes)
				{
					Words.RemoveAt(i--);
					continue;
				}

				if (!ValidWords.Contains(Words[i].Command))
				{
					Warnings.Add($"ignoring unknown word (letter): \"{Words[i]}\". (line {lineNumber})");
					Words.RemoveAt(i--);
					continue;
				}

				if (Words[i].Command != 'F')
					continue;

				State.Feed = Words[i].Parameter;
				if (State.Unit == ParseUnit.Imperial)
					State.Feed *= 25.4;
				Words.RemoveAt(i--);
				continue;
			}

			for (int i = 0; i < Words.Count; i++)
			{
				if (Words[i].Command == 'M')
				{
					int param = (int)Words[i].Parameter;

					if (param != Words[i].Parameter || param < 0)
						throw new ParseException("M code can only have positive integer parameters", lineNumber);

					Commands.Add(new MCode() { Code = param, LineNumber = lineNumber });

					Words.RemoveAt(i);
					i--;
					continue;
				}

				if (Words[i].Command == 'S')
				{
					double param = Words[i].Parameter;

					if (param < 0)
						Warnings.Add($"spindle speed must be positive. (line {lineNumber})");

					Commands.Add(new Spindle() { Speed = Math.Abs(param), LineNumber = lineNumber });

					Words.RemoveAt(i);
					i--;
					continue;
				}

				if (Words[i].Command == 'G' && !MotionCommands.Contains(Words[i].Parameter))
				{
					#region UnitPlaneDistanceMode

					double param = Words[i].Parameter;

					if (param == 90)
					{
						State.DistanceMode = ParseDistanceMode.Absolute;
						Words.RemoveAt(i);
						i--;
						continue;
					}
					if (param == 91)
					{
						State.DistanceMode = ParseDistanceMode.Incremental;
						Words.RemoveAt(i);
						i--;
						continue;
					}
					if (param == 90.1)
					{
						State.ArcDistanceMode = ParseDistanceMode.Absolute;
						Words.RemoveAt(i);
						continue;
					}
					if (param == 91.1)
					{
						State.ArcDistanceMode = ParseDistanceMode.Incremental;
						Words.RemoveAt(i);
						i--;
						continue;
					}
					if (param == 21)
					{
						State.Unit = ParseUnit.Metric;
						Words.RemoveAt(i);
						i--;
						continue;
					}
					if (param == 20)
					{
						State.Unit = ParseUnit.Imperial;
						Words.RemoveAt(i);
						i--;
						continue;
					}
					if (param == 17)
					{
						State.Plane = ArcPlane.XY;
						Words.RemoveAt(i);
						i--;
						continue;
					}
					if (param == 18)
					{
						State.Plane = ArcPlane.ZX;
						Words.RemoveAt(i);
						i--;
						continue;
					}
					if (param == 19)
					{
						State.Plane = ArcPlane.YZ;
						Words.RemoveAt(i);
						i--;
						continue;
					}
					if (param == 4)
					{
						if (Words.Count >= 2 && Words[i + 1].Command == 'P')
						{
							if (Words[i + 1].Parameter < 0)
								Warnings.Add($"dwell time must be positive. (line {lineNumber})");

							Commands.Add(new Dwell() { Seconds = Math.Abs(Words[i + 1].Parameter), LineNumber = lineNumber });
							Words.RemoveAt(i + 1);
							Words.RemoveAt(i);
							i--;
							continue;
						}
					}

					Warnings.Add($"ignoring unknown command G{param}. (line {lineNumber})");
					Words.RemoveAt(i--);
					#endregion
				}
			}

			if (Words.Count == 0)
				return;

			int MotionMode = State.LastMotionMode;

			if (Words.First().Command == 'G')
			{
				MotionMode = (int)Words.First().Parameter;
				State.LastMotionMode = MotionMode;
				Words.RemoveAt(0);
			}

			if (MotionMode < 0)
				throw new ParseException("no motion mode active", lineNumber);

			double UnitMultiplier = (State.Unit == ParseUnit.Metric) ? 1 : 25.4;

			Vector3 EndPos = State.Position;

			if (State.DistanceMode == ParseDistanceMode.Incremental && State.PositionValid.Any(isValid => !isValid))
			{
				throw new ParseException("incremental motion is only allowed after an absolute position has been established (eg. with \"G90 G0 X0 Y0 Z5\")", lineNumber);
			}

			if ((MotionMode == 2 || MotionMode == 3) && State.PositionValid.Any(isValid => !isValid))
			{
				throw new ParseException("arcs (G2/G3) are only allowed after an absolute position has been established (eg. with \"G90 G0 X0 Y0 Z5\")", lineNumber);
			}

			#region FindEndPos
			{
				int Incremental = (State.DistanceMode == ParseDistanceMode.Incremental) ? 1 : 0;

				for (int i = 0; i < Words.Count; i++)
				{
					if (Words[i].Command != 'X')
						continue;
					EndPos.X = Words[i].Parameter * UnitMultiplier + Incremental * EndPos.X;
					Words.RemoveAt(i);
					State.PositionValid[0] = true;
					break;
				}

				for (int i = 0; i < Words.Count; i++)
				{
					if (Words[i].Command != 'Y')
						continue;
					EndPos.Y = Words[i].Parameter * UnitMultiplier + Incremental * EndPos.Y;
					Words.RemoveAt(i);
					State.PositionValid[1] = true;
					break;
				}

				for (int i = 0; i < Words.Count; i++)
				{
					if (Words[i].Command != 'Z')
						continue;
					EndPos.Z = Words[i].Parameter * UnitMultiplier + Incremental * EndPos.Z;
					Words.RemoveAt(i);
					State.PositionValid[2] = true;
					break;
				}
			}
			#endregion

			if (MotionMode != 0 && State.Feed <= 0)
			{
				throw new ParseException("feed rate undefined", lineNumber);
			}

			if (MotionMode == 1 && State.PositionValid.Any(isValid => !isValid))
			{
				Warnings.Add($"a feed move is used before an absolute position is established, height maps will not be applied to this motion. (line {lineNumber})");
			}

			if (MotionMode <= 1)
			{
				if (Words.Count > 0)
					Warnings.Add($"motion command must be last in line (ignoring unused words {string.Join(" ", Words)} in block). (line {lineNumber})");

				Line motion = new Line();
				motion.Start = State.Position;
				motion.End = EndPos;
				motion.Feed = State.Feed;
				motion.Rapid = MotionMode == 0;
				motion.LineNumber = lineNumber;
				State.PositionValid.CopyTo(motion.PositionValid, 0);

				Commands.Add(motion);
				State.Position = EndPos;
				return;
			}

			double U, V;

			bool IJKused = false;

			switch (State.Plane)
			{
				default:
					U = State.Position.X;
					V = State.Position.Y;
					break;
				case ArcPlane.YZ:
					U = State.Position.Y;
					V = State.Position.Z;
					break;
				case ArcPlane.ZX:
					U = State.Position.Z;
					V = State.Position.X;
					break;
			}

			#region FindIJK
			{
				int ArcIncremental = (State.ArcDistanceMode == ParseDistanceMode.Incremental) ? 1 : 0;

				for (int i = 0; i < Words.Count; i++)
				{
					if (Words[i].Command != 'I')
						continue;

					switch (State.Plane)
					{
						case ArcPlane.XY:
							U = Words[i].Parameter * UnitMultiplier + ArcIncremental * State.Position.X;
							break;
						case ArcPlane.YZ:
							throw new ParseException("current plane is YZ, I word is invalid", lineNumber);
						case ArcPlane.ZX:
							V = Words[i].Parameter * UnitMultiplier + ArcIncremental * State.Position.X;
							break;
					}

					IJKused = true;
					Words.RemoveAt(i);
					break;
				}

				for (int i = 0; i < Words.Count; i++)
				{
					if (Words[i].Command != 'J')
						continue;

					switch (State.Plane)
					{
						case ArcPlane.XY:
							V = Words[i].Parameter * UnitMultiplier + ArcIncremental * State.Position.Y;
							break;
						case ArcPlane.YZ:
							U = Words[i].Parameter * UnitMultiplier + ArcIncremental * State.Position.Y;
							break;
						case ArcPlane.ZX:
							throw new ParseException("current plane is ZX, J word is invalid", lineNumber);
					}

					IJKused = true;
					Words.RemoveAt(i);
					break;
				}

				for (int i = 0; i < Words.Count; i++)
				{
					if (Words[i].Command != 'K')
						continue;

					switch (State.Plane)
					{
						case ArcPlane.XY:
							throw new ParseException("current plane is XY, K word is invalid", lineNumber);
						case ArcPlane.YZ:
							V = Words[i].Parameter * UnitMultiplier + ArcIncremental * State.Position.Z;
							break;
						case ArcPlane.ZX:
							U = Words[i].Parameter * UnitMultiplier + ArcIncremental * State.Position.Z;
							break;
					}

					IJKused = true;
					Words.RemoveAt(i);
					break;
				}
			}
			#endregion

			#region ResolveRadius
			for (int i = 0; i < Words.Count; i++)
			{
				if (Words[i].Command != 'R')
					continue;

				if (IJKused)
					throw new ParseException("both IJK and R notation used", lineNumber);

				if (State.Position == EndPos)
					throw new ParseException("arcs in R-notation must have non-coincident start and end points", lineNumber);

				double Radius = Words[i].Parameter * UnitMultiplier;

				if (Radius == 0)
					throw new ParseException("radius can't be zero", lineNumber);

				double A, B;

				switch (State.Plane)
				{
					default:
						A = EndPos.X;
						B = EndPos.Y;
						break;
					case ArcPlane.YZ:
						A = EndPos.Y;
						B = EndPos.Z;
						break;
					case ArcPlane.ZX:
						A = EndPos.Z;
						B = EndPos.X;
						break;
				}

				A -= U;     //(AB) = vector from start to end of arc along the axes of the current plane
				B -= V;

				//see grbl/gcode.c
				double h_x2_div_d = 4.0 * (Radius * Radius) - (A * A + B * B);
				if (h_x2_div_d < 0)
				{
					throw new ParseException("arc radius too small to reach both ends", lineNumber);
				}

				h_x2_div_d = -Math.Sqrt(h_x2_div_d) / Math.Sqrt(A * A + B * B);

				if (MotionMode == 3 ^ Radius < 0)
				{
					h_x2_div_d = -h_x2_div_d;
				}

				U += 0.5 * (A - (B * h_x2_div_d));
				V += 0.5 * (B + (A * h_x2_div_d));

				Words.RemoveAt(i);
				break;
			}
			#endregion

			if (Words.Count > 0)
				Warnings.Add($"motion command must be last in line (ignoring unused words {string.Join(" ", Words)} in block). (line {lineNumber})");

			Arc arc = new Arc();
			arc.Start = State.Position;
			arc.End = EndPos;
			arc.Feed = State.Feed;
			arc.Direction = (MotionMode == 2) ? ArcDirection.CW : ArcDirection.CCW;
			arc.U = U;
			arc.V = V;
			arc.LineNumber = lineNumber;
			arc.Plane = State.Plane;

			Commands.Add(arc);
			State.Position = EndPos;
			return;
		}

19 Source : EditMacroItemWindow.xaml.cs
with MIT License
from 3RD-Dimension

private void ButtonOk_Click(object sender, RoutedEventArgs e)
		{
			if (MacroName.Contains(':') || MacroName.Contains(';') || Commands.Contains(':') || Commands.Contains(';'))
			{
				MessageBox.Show("Name and Commands can't include ':' or ';'");
				return;
			}
			Ok = true;
			Close();
		}

19 Source : Repository.cs
with Apache License 2.0
from AantCoder

public static string NormalizeLogin(string login)
        {
            char[] invalidFileChars = Path.GetInvalidFileNameChars();
            foreach (var c in invalidFileChars) if (login.Contains(c)) login = login.Replace(c, '_');
            return login.ToLowerInvariant();
        }

19 Source : ClusterDef.cs
with MIT License
from abdullin

public void AddService(string svc, Func<IEnv, IEngine> run) {
            if (!svc.Contains(':')) {
                var count = Services.Count(p => p.Key.Machine == svc);
                
                svc = svc + ":svc" + count;
            }
            Services.Add(new ServiceId(svc), run);
        }

19 Source : FeatureBuilder.cs
with Apache License 2.0
from acblog

public FeatureBuilder AddFeature(params string[] names)
        {
            foreach (var name in names)
            {
                if (!name.Contains(','))
                {
                    Inner.Add(name);
                }
                else
                {
                    throw new Exception($"Invalid feature name: {name}.");
                }
            }
            return this;
        }

19 Source : KeywordBuilder.cs
with Apache License 2.0
from acblog

public KeywordBuilder AddKeyword(params string[] names)
        {
            foreach (var name in names)
            {
                if (!name.Contains(';'))
                {
                    Inner.Add(name);
                }
                else
                {
                    throw new Exception($"Invalid keyword name: {name}.");
                }
            }
            return this;
        }

19 Source : CommandParameterHelpers.cs
with GNU Affero General Public License v3.0
from ACEmulator

public static bool ResolveACEParameters(Session session, IEnumerable<string> aceParsedParameters, IEnumerable<ACECommandParameter> parameters, bool rawIncluded = false)
        {
            string parameterBlob = "";
            if (rawIncluded)
            {
                parameterBlob = aceParsedParameters.First();
            }
            else
            {
                parameterBlob = aceParsedParameters.Count() > 0 ? aceParsedParameters.Aggregate((a, b) => a + " " + b).Trim(new char[] { ' ', ',' }) : string.Empty;
            }
            int commaCount = parameterBlob.Count(x => x == ',');

            List<ACECommandParameter> acps = parameters.ToList();
            for (int i = acps.Count - 1; i > -1; i--)
            {
                ACECommandParameter acp = acps[i];
                acp.ParameterNo = i + 1;
                if (parameterBlob.Length > 0)
                {
                    try
                    {
                        switch (acp.Type)
                        {
                            case ACECommandParameterType.PositiveLong:
                                Match match4 = Regex.Match(parameterBlob, @"(-?\d+)$", RegexOptions.IgnoreCase);
                                if (match4.Success)
                                {
                                    if (!long.TryParse(match4.Groups[1].Value, out long val))
                                    {
                                        return false;
                                    }
                                    if (val <= 0)
                                    {
                                        return false;
                                    }
                                    acp.Value = val;
                                    acp.Defaulted = false;
                                    parameterBlob = (match4.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, match4.Groups[1].Index).Trim(new char[] { ' ' });
                                }
                                break;
                            case ACECommandParameterType.Long:
                                Match match3 = Regex.Match(parameterBlob, @"(-?\d+)$", RegexOptions.IgnoreCase);
                                if (match3.Success)
                                {
                                    if (!long.TryParse(match3.Groups[1].Value, out long val))
                                    {
                                        return false;
                                    }
                                    acp.Value = val;
                                    acp.Defaulted = false;
                                    parameterBlob = (match3.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, match3.Groups[1].Index).Trim(new char[] { ' ', ',' });
                                }
                                break;
                            case ACECommandParameterType.ULong:
                                Match match2 = Regex.Match(parameterBlob, @"(-?\d+)$", RegexOptions.IgnoreCase);
                                if (match2.Success)
                                {
                                    if (!ulong.TryParse(match2.Groups[1].Value, out ulong val))
                                    {
                                        return false;
                                    }
                                    acp.Value = val;
                                    acp.Defaulted = false;
                                    parameterBlob = (match2.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, match2.Groups[1].Index).Trim(new char[] { ' ', ',' });
                                }
                                break;
                            case ACECommandParameterType.Location:
                                Position position = null;
                                Match match = Regex.Match(parameterBlob, @"([\d\.]+[ns])[^\d\.]*([\d\.]+[ew])$", RegexOptions.IgnoreCase);
                                if (match.Success)
                                {
                                    string ns = match.Groups[1].Value;
                                    string ew = match.Groups[2].Value;
                                    if (!TryParsePosition(new string[] { ns, ew }, out string errorMessage, out position))
                                    {
                                        if (session != null)
                                        {
                                            ChatPacket.SendServerMessage(session, errorMessage, ChatMessageType.Broadcast);
                                        }
                                        else
                                        {
                                            Console.WriteLine(errorMessage);
                                        }
                                        return false;
                                    }
                                    else
                                    {
                                        acp.Value = position;
                                        acp.Defaulted = false;
                                        int coordsStartPos = Math.Min(match.Groups[1].Index, match.Groups[2].Index);
                                        parameterBlob = (coordsStartPos == 0) ? string.Empty : parameterBlob.Substring(0, coordsStartPos).Trim(new char[] { ' ', ',' });
                                    }
                                }
                                break;
                            case ACECommandParameterType.OnlinePlayerName:
                                if (i != 0)
                                {
                                    throw new Exception("Player parameter must be the first parameter, since it can contain spaces.");
                                }
                                parameterBlob = parameterBlob.TrimEnd(new char[] { ' ', ',' });
                                Player targetPlayer = PlayerManager.GetOnlinePlayer(parameterBlob);
                                if (targetPlayer == null)
                                {
                                    string errorMsg = $"Unable to find player {parameterBlob}";
                                    if (session != null)
                                    {
                                        ChatPacket.SendServerMessage(session, errorMsg, ChatMessageType.Broadcast);
                                    }
                                    else
                                    {
                                        Console.WriteLine(errorMsg);
                                    }
                                    return false;
                                }
                                else
                                {
                                    acp.Value = targetPlayer;
                                    acp.Defaulted = false;
                                }
                                break;
                            case ACECommandParameterType.OnlinePlayerNameOrIid:
                                if (i != 0)
                                {
                                    throw new Exception("Player parameter must be the first parameter, since it can contain spaces.");
                                }

                                if (!parameterBlob.Contains(' '))
                                {
                                    if (uint.TryParse(parameterBlob, out uint iid))
                                    {
                                        Player targetPlayer2 = PlayerManager.GetOnlinePlayer(iid);
                                        if (targetPlayer2 == null)
                                        {
                                            string logMsg = $"Unable to find player with iid {iid}";
                                            if (session != null)
                                            {
                                                ChatPacket.SendServerMessage(session, logMsg, ChatMessageType.Broadcast);
                                            }
                                            else
                                            {
                                                Console.WriteLine(logMsg);
                                            }
                                            return false;
                                        }
                                        else
                                        {
                                            acp.Value = targetPlayer2;
                                            acp.Defaulted = false;
                                            break;
                                        }
                                    }
                                }
                                Player targetPlayer3 = PlayerManager.GetOnlinePlayer(parameterBlob);
                                if (targetPlayer3 == null)
                                {
                                    string logMsg = $"Unable to find player {parameterBlob}";
                                    if (session != null)
                                    {
                                        ChatPacket.SendServerMessage(session, logMsg, ChatMessageType.Broadcast);
                                    }
                                    else
                                    {
                                        Console.WriteLine(logMsg);
                                    }

                                    return false;
                                }
                                else
                                {
                                    acp.Value = targetPlayer3;
                                    acp.Defaulted = false;
                                }
                                break;
                            case ACECommandParameterType.OnlinePlayerIid:
                                Match matcha5 = Regex.Match(parameterBlob, /*((i == 0) ? "" : @"\s+") +*/ @"(\d{10})$|(0x[0-9a-f]{8})$", RegexOptions.IgnoreCase);
                                if (matcha5.Success)
                                {
                                    string strIid = "";
                                    if (matcha5.Groups[2].Success)
                                    {
                                        strIid = matcha5.Groups[2].Value;
                                    }
                                    else if (matcha5.Groups[1].Success)
                                    {
                                        strIid = matcha5.Groups[1].Value;
                                    }
                                    try
                                    {
                                        uint iid = 0;
                                        if (strIid.StartsWith("0x"))
                                        {
                                            iid = Convert.ToUInt32(strIid, 16);
                                        }
                                        else
                                        {
                                            iid = uint.Parse(strIid);
                                        }

                                        Player targetPlayer2 = PlayerManager.GetOnlinePlayer(iid);
                                        if (targetPlayer2 == null)
                                        {
                                            string logMsg = $"Unable to find player with iid {strIid}";
                                            if (session != null)
                                            {
                                                ChatPacket.SendServerMessage(session, logMsg, ChatMessageType.Broadcast);
                                            }
                                            else
                                            {
                                                Console.WriteLine(logMsg);
                                            }
                                            return false;
                                        }
                                        else
                                        {
                                            acp.Value = targetPlayer2;
                                            acp.Defaulted = false;
                                            parameterBlob = (matcha5.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, matcha5.Groups[1].Index).Trim(new char[] { ' ', ',' });
                                        }
                                    }
                                    catch (Exception)
                                    {
                                        string errorMsg = $"Unable to parse {strIid} into a player iid";
                                        if (session != null)
                                        {
                                            ChatPacket.SendServerMessage(session, errorMsg, ChatMessageType.Broadcast);
                                        }
                                        else
                                        {
                                            Console.WriteLine(errorMsg);
                                        }
                                        return false;
                                    }
                                }
                                break;
                            case ACECommandParameterType.PlayerName:
                                if (i != 0)
                                {
                                    throw new Exception("Player name parameter must be the first parameter, since it can contain spaces.");
                                }
                                parameterBlob = parameterBlob.TrimEnd(new char[] { ' ', ',' });
                                if (string.IsNullOrWhiteSpace(parameterBlob))
                                {
                                    break;
                                }
                                else
                                {
                                    acp.Value = parameterBlob;
                                    acp.Defaulted = false;
                                }
                                break;
                            case ACECommandParameterType.Uri:
                                Match match5 = Regex.Match(parameterBlob, @"(https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*))$", RegexOptions.IgnoreCase);
                                if (match5.Success)
                                {
                                    string strUri = match5.Groups[1].Value;
                                    try
                                    {
                                        Uri url = new Uri(strUri);
                                        acp.Value = url;
                                        acp.Defaulted = false;
                                        parameterBlob = (match5.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, match5.Groups[1].Index).Trim(new char[] { ' ', ',' });
                                    }
                                    catch (Exception)
                                    {
                                        return false;
                                    }
                                }
                                break;
                            case ACECommandParameterType.DoubleQuoteEnclosedText:
                                Match match6 = Regex.Match(parameterBlob.TrimEnd(), @"(\"".*\"")$", RegexOptions.IgnoreCase);
                                if (match6.Success)
                                {
                                    string txt = match6.Groups[1].Value;
                                    try
                                    {
                                        acp.Value = txt.Trim('"');
                                        acp.Defaulted = false;
                                        parameterBlob = (match6.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, match6.Groups[1].Index).Trim(new char[] { ' ', ',' });
                                    }
                                    catch (Exception)
                                    {
                                        return false;
                                    }
                                }
                                break;
                            case ACECommandParameterType.CommaPrefixedText:
                                if (i == 0)
                                {
                                    throw new Exception("this parameter type is not appropriate as the first parameter");
                                }
                                if (i == acps.Count - 1 && !acp.Required && commaCount < acps.Count - 1)
                                {
                                    break;
                                }
                                Match match7 = Regex.Match(parameterBlob.TrimEnd(), @"\,\s*([^,]*)$", RegexOptions.IgnoreCase);
                                if (match7.Success)
                                {
                                    string txt = match7.Groups[1].Value;
                                    try
                                    {
                                        acp.Value = txt.TrimStart(new char[] { ' ', ',' });
                                        acp.Defaulted = false;
                                        parameterBlob = (match7.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, match7.Groups[1].Index).Trim(new char[] { ' ', ',' });
                                    }
                                    catch (Exception)
                                    {
                                        return false;
                                    }
                                }
                                break;
                            case ACECommandParameterType.SimpleWord:
                                Match match8 = Regex.Match(parameterBlob.TrimEnd(), @"([a-zA-Z1-9_]+)\s*$", RegexOptions.IgnoreCase);
                                if (match8.Success)
                                {
                                    string txt = match8.Groups[1].Value;
                                    try
                                    {
                                        acp.Value = txt.TrimStart(' ');
                                        acp.Defaulted = false;
                                        parameterBlob = (match8.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, match8.Groups[1].Index).Trim(new char[] { ' ', ',' });
                                    }
                                    catch (Exception)
                                    {
                                        return false;
                                    }
                                }
                                break;
                            case ACECommandParameterType.Enum:
                                if (acp.PossibleValues == null)
                                {
                                    throw new Exception("The enum parameter type must be accompanied by the PossibleValues");
                                }
                                if (!acp.PossibleValues.IsEnum)
                                {
                                    throw new Exception("PossibleValues must be an enum type");
                                }
                                Match match9 = Regex.Match(parameterBlob.TrimEnd(), @"([a-zA-Z1-9_]+)\s*$", RegexOptions.IgnoreCase);
                                if (match9.Success)
                                {
                                    string txt = match9.Groups[1].Value;
                                    try
                                    {
                                        txt = txt.Trim(new char[] { ' ', ',' });
                                        Array etvs = Enum.GetValues(acp.PossibleValues);
                                        foreach (object etv in etvs)
                                        {
                                            if (etv.ToString().ToLower() == txt.ToLower())
                                            {
                                                acp.Value = etv;
                                                acp.Defaulted = false;
                                                parameterBlob = (match9.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, match9.Groups[1].Index).Trim(new char[] { ' ' });
                                                break;
                                            }
                                        }
                                    }
                                    catch (Exception)
                                    {
                                        return false;
                                    }
                                }
                                break;
                        }
                    }
                    catch
                    {
                        return false;
                    }
                }
                if (acp.Defaulted)
                {
                    acp.Value = acp.DefaultValue;
                }

                if (acp.Required && acp.Defaulted)
                {
                    if (!string.IsNullOrWhiteSpace(acp.ErrorMessage))
                    {
                        if (session != null)
                        {
                            ChatPacket.SendServerMessage(session, acp.ErrorMessage, ChatMessageType.Broadcast);
                        }
                        else
                        {
                            Console.WriteLine(acp.ErrorMessage);
                        }
                    }

                    return false;
                }
            }
            return true;
        }

19 Source : MutationCache.cs
with GNU Affero General Public License v3.0
from ACEmulator

public static EffectArgumentType GetEffectArgumentType(Effect effect, string operand)
        {
            if (IsNumber(operand) || Enum.TryParse(operand, out WieldRequirement wieldRequirement) || Enum.TryParse(operand, out Skill skill) || Enum.TryParse(operand, out ImbuedEffectType imbuedEffectType))
            {
                if (operand.Contains('.'))
                    return EffectArgumentType.Double;
                else if (effect.Quality != null && effect.Quality.StatType == StatType.Int64)
                    return EffectArgumentType.Int64;
                else
                    return EffectArgumentType.Int;
            }
            else if (GetStatType(operand) != StatType.Undef)
            {
                return EffectArgumentType.Quality;
            }
            else if (operand.StartsWith("Random", StringComparison.OrdinalIgnoreCase))
                return EffectArgumentType.Random;
            else if (operand.StartsWith("Variable", StringComparison.OrdinalIgnoreCase))
                return EffectArgumentType.Variable;
            else
                return EffectArgumentType.Invalid;
        }

19 Source : PublishArtifact.cs
with MIT License
from actions

public async Task RunAsync(
            RunnerActionPluginExecutionContext context,
            CancellationToken token)
        {
            string artifactName = context.GetInput(PublishArtifactInputNames.ArtifactName, required: false);  // Back compat since we rename input `artifactName` to `name`
            if (string.IsNullOrEmpty(artifactName))
            {
                artifactName = context.GetInput(PublishArtifactInputNames.Name, required: true);
            }

            string targetPath = context.GetInput(PublishArtifactInputNames.Path, required: true);
            string defaultWorkingDirectory = context.GetGitHubContext("workspace");

            targetPath = Path.IsPathFullyQualified(targetPath) ? targetPath : Path.GetFullPath(Path.Combine(defaultWorkingDirectory, targetPath));

            if (String.IsNullOrWhiteSpace(artifactName))
            {
                throw new ArgumentException($"Artifact name can not be empty string");
            }

            if (Path.GetInvalidFileNameChars().Any(x => artifactName.Contains(x)))
            {
                throw new ArgumentException($"Artifact name is not valid: {artifactName}. It cannot contain '\\', '/', \"', ':', '<', '>', '|', '*', and '?'");
            }

            // Build ID
            string buildIdStr = context.Variables.GetValueOrDefault(SdkConstants.Variables.Build.BuildId)?.Value ?? string.Empty;
            if (!int.TryParse(buildIdStr, out int buildId))
            {
                throw new ArgumentException($"Run Id is not an Int32: {buildIdStr}");
            }

            string fullPath = Path.GetFullPath(targetPath);
            bool isFile = File.Exists(fullPath);
            bool isDir = Directory.Exists(fullPath);
            if (!isFile && !isDir)
            {
                // if local path is neither file nor folder
                throw new FileNotFoundException($"Path does not exist {targetPath}");
            }

            // Container ID
            string containerIdStr = context.Variables.GetValueOrDefault(SdkConstants.Variables.Build.ContainerId)?.Value ?? string.Empty;
            if (!long.TryParse(containerIdStr, out long containerId))
            {
                throw new ArgumentException($"Container Id is not an Int64: {containerIdStr}");
            }

            context.Output($"Uploading artifact '{artifactName}' from '{fullPath}' for run #{buildId}");

            FileContainerServer fileContainerHelper = new FileContainerServer(context.VssConnection, projectId: Guid.Empty, containerId, artifactName);
            var propertiesDictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);

            long size = 0;

            try
            {
                size = await fileContainerHelper.CopyToContainerAsync(context, fullPath, token);

                propertiesDictionary.Add("artifactsize", size.ToString());

                context.Output($"Uploaded '{size}' bytes from '{fullPath}' to server");
            }
            // if any of the results were successful, make sure to attach them to the build
            finally
            {
                // Definition ID is a dummy value only used by HTTP client routing purposes
                int definitionId = 1;

                PipelinesServer pipelinesHelper = new PipelinesServer(context.VssConnection);

                var artifact = await pipelinesHelper.replacedociateActionsStorageArtifactAsync(
                    definitionId,
                    buildId,
                    containerId,
                    artifactName,
                    size,
                    token);

                context.Output($"replacedociated artifact {artifactName} ({artifact.ContainerId}) with run #{buildId}"); 
            }
        }

19 Source : BigDecimal.cs
with MIT License
from AdamWhiteHat

public static BigDecimal Parse(string input)
		{
			if (string.IsNullOrWhiteSpace(input))
			{
				return new BigInteger(0);
			}

			int exponent = 0;
			int decimalPlace = 0;
			bool isNegative = false;
			string localInput = new string(input.Trim().Where(c => NumericCharacters.Contains(c)).ToArray());

			if (localInput.StartsWith(BigDecimalNumberFormatInfo.NegativeSign))
			{
				isNegative = true;
				localInput = localInput.Replace(BigDecimalNumberFormatInfo.NegativeSign, string.Empty);
			}

			if (localInput.Contains(BigDecimalNumberFormatInfo.NumberDecimalSeparator))
			{
				decimalPlace = localInput.IndexOf(BigDecimalNumberFormatInfo.NumberDecimalSeparator);

				exponent = ((decimalPlace + 1) - (localInput.Length));
				localInput = localInput.Replace(BigDecimalNumberFormatInfo.NumberDecimalSeparator, string.Empty);
			}

			BigInteger mantessa = BigInteger.Parse(localInput);
			if (isNegative)
			{
				mantessa = BigInteger.Negate(mantessa);
			}

			return new BigDecimal(mantessa, exponent);
		}

19 Source : BigDecimal.cs
with MIT License
from AdamWhiteHat

private static int GetSignifigantDigits(BigInteger value)
		{
			if (value.IsZero)
			{
				return 0;
			}

			string valueString = value.ToString();
			if (string.IsNullOrWhiteSpace(valueString))
			{
				return 0;
			}

			valueString = new string(valueString.Trim().Where(c => NumericCharacters.Contains(c)).ToArray());
			valueString = valueString.Replace(BigDecimalNumberFormatInfo.NegativeSign, string.Empty);
			valueString = valueString.Replace(BigDecimalNumberFormatInfo.PositiveSign, string.Empty);
			valueString = valueString.TrimEnd(new char[] { '0' });
			valueString = valueString.Replace(BigDecimalNumberFormatInfo.NumberDecimalSeparator, string.Empty);

			return valueString.Length;
		}

19 Source : RazorEngineCompilationOptionsBuilder.cs
with MIT License
from adoconnection

private string RenderTypeName(Type type)
        {
            string result = type.Namespace + "." + type.Name;

            if (result.Contains('`'))
            {
                result = result.Substring(0, result.IndexOf("`"));
            }

            if (type.GenericTypeArguments.Length == 0)
            {
                return result;
            }

            return result + "<" + string.Join(",", type.GenericTypeArguments.Select(this.RenderTypeName)) + ">";
        }

19 Source : EntityGridController.cs
with MIT License
from Adoxio

[HttpPost]
		[JsonHandlerError]
		[AjaxValidateAntiForgeryToken]
		public ActionResult DownloadAsExcel(string viewName, IEnumerable<LayoutColumn> columns, string base64SecureConfiguration, string sortExpression, string search, string filter,
			string metaFilter, int page = 1, int pageSize = DefaultPageSize, int timezoneOffset = 0)
		{
			var viewConfiguration = ConvertSecureStringToViewConfiguration(base64SecureConfiguration);

			if (viewConfiguration == null)
			{
				return new HttpStatusCodeResult(HttpStatusCode.Forbidden, ResourceManager.GetString("Invalid_Request"));
			}

			var dataAdapterDependencies = new PortalConfigurationDataAdapterDependencies(requestContext: Request.RequestContext, portalName: viewConfiguration.PortalName);

			// override the page parameters
			page = 1;
			pageSize = new SettingDataAdapter(dataAdapterDependencies, HttpContext.GetWebsite())
				.GetIntegerValue("Grid/Download/MaximumResults")
				.GetValueOrDefault(Fetch.MaximumPageSize);
			viewConfiguration.PageSize = pageSize;
			
			var json = GetData(viewConfiguration, sortExpression, search, filter, metaFilter, page, pageSize, true, false, null, null, null, null, true) as JsonResult;

			if (json == null)
			{
				return new HttpStatusCodeResult(HttpStatusCode.NoContent);
			}

			if (json.Data is EnreplacedyPermissionResult)
			{
				return json;
			}

			var data = json.Data as PaginatedGridData;

			if (data == null)
			{
				return new HttpStatusCodeResult(HttpStatusCode.NoContent);
			}

			var stream = new MemoryStream();

			var spreadsheet = SpreadsheetDoreplacedent.Create(stream, SpreadsheetDoreplacedentType.Workbook);

			var workbookPart = spreadsheet.AddWorkbookPart();
			workbookPart.Workbook = new Workbook();

			var worksheetPart = workbookPart.AddNewPart<WorksheetPart>();
			var sheet = new Sheet { Id = spreadsheet.WorkbookPart.GetIdOfPart(worksheetPart), SheetId = 1, Name = viewName.Truncate(30) };

			var sheets = new Sheets();
			sheets.Append(sheet);

			var sheetData = new SheetData();

			var rowIndex = 1;
			var columnIndex = 1;

			var firstRow = new Row { RowIndex = (uint)rowIndex };

			var dataColumns = columns.Where(col => col.LogicalName != "col-action").ToArray();

			foreach (var column in dataColumns)
			{
				var cell = new Cell { CellReference = CreateCellReference(columnIndex) + rowIndex, DataType = CellValues.InlineString };

				var inlineString = new InlineString { Text = new Text { Text = column.Name } };

				cell.AppendChild(inlineString);

				firstRow.AppendChild(cell);

				columnIndex++;
			}

			sheetData.Append(firstRow);

			foreach (var record in data.Records)
			{
				var row = new Row { RowIndex = (uint)++rowIndex };

				columnIndex = 0;

				foreach (var column in dataColumns)
				{
					columnIndex++;

					var attribute = record.Attributes.FirstOrDefault(a => a.Name == column.LogicalName);

					if (attribute == null) continue;

					var isDateTime = attribute.AttributeMetadata.AttributeType == AttributeTypeCode.DateTime;

					var cell = new Cell { CellReference = CreateCellReference(columnIndex) + rowIndex, DataType = CellValues.InlineString };

					var inlineString = new InlineString { Text = new Text { Text = isDateTime ? this.GetFormattedDateTime(attribute, timezoneOffset) : attribute.DisplayValue as string } };

					cell.AppendChild(inlineString);

					row.AppendChild(cell);
				}

				sheetData.Append(row);
			}

			worksheetPart.Worksheet = new Worksheet(sheetData);

			spreadsheet.WorkbookPart.Workbook.AppendChild(sheets);

			workbookPart.Workbook.Save();

			spreadsheet.Close();

			var filename = new string(viewName.Where(c => !Path.GetInvalidFileNameChars().Contains(c)).ToArray());

			var sessionKey = "{0:s}|{1}.xlsx".FormatWith(DateTime.UtcNow, filename);

			stream.Position = 0; // Reset the stream to the beginning and save to session.

			Session[sessionKey] = stream;

			return Json(new { success = true, sessionKey }, JsonRequestBehavior.AllowGet);
		}

19 Source : EntityGridController.cs
with MIT License
from Adoxio

[HttpPost]
		[JsonHandlerError]
		[AjaxValidateAntiForgeryToken]
		public ActionResult DownloadAsCsv(string viewName, IEnumerable<LayoutColumn> columns, string base64SecureConfiguration, string sortExpression, string search, string filter,
			string metaFilter, int page = 1, int pageSize = DefaultPageSize)
		{
			var viewConfiguration = ConvertSecureStringToViewConfiguration(base64SecureConfiguration);
			using (PerformanceProfiler.Instance.StartMarker(PerformanceMarkerName.EnreplacedyGridController, PerformanceMarkerArea.Crm, PerformanceMarkerTagName.DownloadAsCsv))
			{
				if (viewConfiguration == null)
				{
					return new HttpStatusCodeResult(HttpStatusCode.Forbidden, ResourceManager.GetString("Invalid_Request"));
				}

				var dataAdapterDependencies = new PortalConfigurationDataAdapterDependencies(requestContext: Request.RequestContext, portalName: viewConfiguration.PortalName);
		
				// override the page parameters
				page = 1;
				pageSize = new SettingDataAdapter(dataAdapterDependencies, HttpContext.GetWebsite())
					.GetIntegerValue("Grid/Download/MaximumResults")
					.GetValueOrDefault(Fetch.MaximumPageSize);
				viewConfiguration.PageSize = pageSize;
			
				var json = GetData(viewConfiguration, sortExpression, search, filter, metaFilter, page, pageSize, true, false, null, null, null, null, true) as JsonResult;

				if (json == null)
				{
					return new HttpStatusCodeResult(HttpStatusCode.NoContent);
				}

				if (json.Data is EnreplacedyPermissionResult)
				{
					return json;
				}

				var data = json.Data as PaginatedGridData;

				if (data == null)
				{
					return new HttpStatusCodeResult(HttpStatusCode.NoContent);
				}

				var csv = new StringBuilder();

				var dataColumns = columns.Where(col => col.LogicalName != "col-action").ToArray();

				foreach (var column in dataColumns)
				{
					csv.Append(EncodeCommaSeperatedValue(column.Name));
				}

				csv.AppendLine();

				foreach (var record in data.Records)
				{
					foreach (var column in dataColumns)
					{
						var attribute = record.Attributes.FirstOrDefault(a => a.Name == column.LogicalName);

						if (attribute == null) continue;

						csv.Append(EncodeCommaSeperatedValue(attribute.DisplayValue as string));
					}

					csv.AppendLine();
				}

				var filename = new string(viewName.Where(c => !Path.GetInvalidFileNameChars().Contains(c)).ToArray());

				var sessionKey = "{0:s}|{1}.csv".FormatWith(DateTime.UtcNow, filename);

				Session[sessionKey] = csv.ToString();

				return Json(new { success = true, sessionKey }, JsonRequestBehavior.AllowGet);
			}
		}

19 Source : IdentifierParser.cs
with MIT License
from AgathokakologicalBit

private static bool IsMatching(char c, Tokenizer.State state)
        {
            const string possible = @"!?@#$%,^&|*/\_+~-<=>";
            if (Char.IsLetter(c) || possible.Contains(c))
            {
                if (c > 127)
                {
                    // If identifier contains non-ascii letters
                    // it will be written as error to state
                    state.ErrorCode = (uint)ErrorCodes.T_InvalidIdentifier;
                    state.ErrorMessage =
                        "Identifier can contains only:\n" +
                        "  - latin letters\n" +
                        $"  - '{possible}' symbols";
                }

                return true;
            }

            return false;
        }

19 Source : WebFileDownloader.cs
with MIT License
from afxw

public async void DownloadFile(string url)
        {
            var response = await httpClient.GetAsync(url);

            if (!response.IsSuccessStatusCode)
                return;

            byte[] fileBytes = await response.Content.ReadAsByteArrayAsync();

            string fileName = string.Empty;
            string extension = string.Empty;

            var splitUrl = url.Split('/');

            var possibleFile = splitUrl[splitUrl.Length - 1];

            if (possibleFile.Contains("."))
            {
                var temp = possibleFile.Split('.');

                fileName = temp[0];

                if (temp[1].Contains('?'))
                {
                    temp[1] = temp[1].Split('?')[0];
                }

                extension = temp[1];

                fileName = $"{fileName}.{extension}";
            }
            else
            {
                fileName = possibleFile;
            }

            if (response.Content.Headers.ContentDisposition != null)
            {
                fileName = response.Content.Headers.ContentDisposition.FileName;
            }

            if (response.Content.Headers.ContentType != null)
            {
                extension = MimeTypeMap.GetExtension(response.Content.Headers.ContentType.MediaType);
            }

            File.WriteAllBytes(Path.Combine(Environment.CurrentDirectory, fileName), fileBytes);
        }

19 Source : Utilities.cs
with MIT License
from Aiko-IT-Systems

public static bool Contains(this string str, params char[] characters)
        {
            foreach (var xc in str)
                if (characters.Contains(xc))
                    return true;

            return false;
        }

19 Source : INIFile.cs
with GNU General Public License v3.0
from akaAgar

private void ParseINIString(string iniString)
        {
            string[] lines = (iniString + "\n").Replace("\r\n", "\n").Split('\n');

            Clear();

            string section = null;

            foreach (string li in lines)
            {
                string l = li.Trim(' ', '\t'); // Trim line
                if (l.StartsWith(";")) continue; // Line is a comment

                if (l.StartsWith("[")) // found a new section
                {
                    // try to get section name, make sure it's valid
                    section = l.Trim('[', ']', ' ', '\t', ':').ToLowerInvariant();
                    string parentSection = null;

                    if (section.Contains(':')) // Sections inherits another section, name declared in the [SECTION:PARENT_SECTION] format
                    {
                        try
                        {
                            string sectionWithParent = section;
                            section = sectionWithParent.Split(':')[0].Trim();
                            parentSection = sectionWithParent.Split(':')[1].Trim();
                        }
                        catch (Exception)
                        {
                            section = l.Trim('[', ']', ' ', '\t', ':').ToLowerInvariant();
                            parentSection = null;
                        }
                    }

                    bool abstractSection = section.StartsWith("_");

                    if (string.IsNullOrEmpty(section)) { section = null; continue; }

                    if (!Sections.ContainsKey(section))
                        Sections.Add(section, new INIFileSection(abstractSection, parentSection));

                    continue;
                }

                if (l.Contains('=')) // The line contains an "equals" sign, it means we found a value
                {
                    if (section == null) continue; // we're not in a section, ignore

                    string[] v = l.Split(new char[] { '=' }, 2); // Split the line at the first "equal" sign: key = value
                    if (v.Length < 2) continue;

                    string key = v[0].Trim().Trim('"').ToLowerInvariant();
                    string value = v[1].Trim().Trim('"');
                    WriteValue(section, key, value);
                }
            }
        }

19 Source : LogEntry.cs
with Apache License 2.0
from alaatm

List<TextSpan> ExtractSpans()
        {
            var spans = new List<TextSpan>();
            var current = 0;

            foreach (Match m in _propRegex.Matches(MessageTemplate))
            {
                var prop = m.Groups[0].Value;
                var name = m.Groups[1].Value;
                name = name.Contains(':') ? name.Substring(0, name.IndexOf(':')) : name;

                var value = Properties.FirstOrDefault(p => p.Name == name)?.Value;

                var startIdx = MessageTemplate.IndexOf(prop, current);
                var endIdx = startIdx + prop.Length;
                var section = MessageTemplate.Substring(current, startIdx - current);

                spans.Add(new TextSpan
                {
                    Text = section,
                });

                if (!string.IsNullOrEmpty(value))
                {
                    var isNumber = double.TryParse(value, out var _);
                    spans.Add(new TextSpan
                    {
                        Kind = isNumber ? "num" : "str",
                        Text = value,
                    });
                }
                else
                {
                    spans.Add(new TextSpan
                    {
                        Text = prop,
                    });
                }

                current = endIdx;
            }

            spans.Add(new TextSpan
            {
                Text = MessageTemplate.Substring(current),
            });

            var result = spans.Where(p => !string.IsNullOrEmpty(p.Text)).ToList();
            return result;
        }

19 Source : Program.cs
with MIT License
from Alan-FGR

public static string FormatSignature(string declStr, int genQty)
    {
        var func = new GenericFormatter();
        var parameters = new List<GenericFormatter>();

        var split = declStr.Split('(');
        var pars = split.Last().Split(')').First().Split(',');

        var split2 = split.First().Split('<');

        func.preText = split2.First();
        func.postText = "";

        func.generics = split2.Last().Split('>').First().Split(',').ToList();

        foreach (string par in pars)
        {
            if (par.Contains('<'))
            {
                var nam = par.Split('<').First();
                var pgens = par.Split('<').Last().Split('>').First().Split(',').ToList();
                var e = par.Split('<').Last().Split('>').Last();
                parameters.Add(new GenericFormatter(nam, e, pgens));
            }
            else
            {
                parameters.Add(new GenericFormatter(par, "", null));
                //if parameter is a generic (todo get generic parameters) repeat for qty
                if (par.Split(' ').Any(x => x == "T0"))
                {
                    for (int i = 1; i < genQty; i++)
                    {
                        parameters.Add(new GenericFormatter(Utils.IncrementGeneric(par, i), "", null));
                    }
                }
            }
        }

        return $"{func.Format(genQty)}({string.Join(", ",parameters.Select(x=>x.Format(genQty)))})";
    }

19 Source : ActionMods.cs
with MIT License
from AlbertMN

public static Tuple<bool, string, bool> ExecuteModAction(string name, string parameter = "") {
            MainProgram.DoDebug("[MOD ACTION] Running mod action \"" + name + "\"");
            string actionErrMsg = "No error message set",
                modLocation = Path.Combine(MainProgram.actionModsPath, modActions[name]),
                infoJsonFile = Path.Combine(modLocation, "info.json");

            if (File.Exists(infoJsonFile)) {
                string modFileContent = ReadInfoFile(infoJsonFile);
                if (modFileContent != null) {
                    try {
                        dynamic jsonTest = JsonConvert.DeserializeObject<dynamic>(modFileContent);
                        if (jsonTest != null) {
                            if (ValidateInfoJson(jsonTest)) {
                                //JSON is valid - get script file
                                string scriptFile = jsonTest["options"]["file_name"], scriptFileLocation = Path.Combine(modLocation, scriptFile);
                                bool actionIsFatal = jsonTest["options"]["is_fatal"] ?? false,
                                    requiresParameter = jsonTest["options"]["requires_param"] ?? false,
                                    requiresSecondaryParameter = jsonTest["options"]["require_second_param"] ?? false;

                                if (requiresParameter ? !String.IsNullOrEmpty(parameter) : true) {
                                    Console.WriteLine("Requires parameter? " + requiresParameter);
                                    Console.WriteLine("Has parameter? " + !String.IsNullOrEmpty(parameter));

                                    string[] secondaryParameters = ActionChecker.GetSecondaryParam(parameter);
                                    if (requiresSecondaryParameter ? secondaryParameters.Length > 1 : true) { //Also returns the first parameter
                                        if (File.Exists(scriptFileLocation)) {
                                            string accArg = requiresParameter && requiresSecondaryParameter ? JsonConvert.SerializeObject(ActionChecker.GetSecondaryParam(parameter)) : (requiresParameter ? parameter : "");

                                            try {
                                                ProcessStartInfo p = new ProcessStartInfo {
                                                    UseShellExecute = false,
                                                    CreateNoWindow = true,
                                                    RedirectStandardOutput = true,
                                                    RedirectStandardError = true
                                                };

                                                string theExtension = Path.GetExtension(scriptFile);

                                                if (theExtension == ".ps1") {
                                                    //Is powershell - open it correctly
                                                    p.FileName = "powershell.exe";
                                                    p.Arguments = String.Format("-WindowStyle Hidden -file \"{0}\" \"{1}\"", scriptFileLocation, accArg);
                                                } else if (theExtension == ".py") {
                                                    //Python - open it correctly
                                                    string minPythonVersion = (jsonTest["options"]["min_python_version"] ?? ""),
                                                        maxPythonVersion = (jsonTest["options"]["max_python_version"] ?? ""),
                                                        pythonPath = GetPythonPath(minPythonVersion, maxPythonVersion);

                                                    if (pythonPath != "") {
                                                        p.FileName = GetPythonPath();
                                                        p.Arguments = String.Format("{0} \"{1}\"", scriptFileLocation, accArg);
                                                    } else {
                                                        //No python version (or one with the min-max requirements) not found.
                                                        string pythonErr;

                                                        if (minPythonVersion == "" && maxPythonVersion == "") {
                                                            //Python just not found
                                                            pythonErr = "We could not locate Python on your computer. Please either download Python or specify its path in the ACC settings if it's already installed.";
                                                        } else {
                                                            if (minPythonVersion != "" && maxPythonVersion != "") {
                                                                //Both min & max set
                                                                pythonErr = "We could not locate a version of Python between v" + minPythonVersion + " and v" + maxPythonVersion + ". Please either download a version of Python in between the specified versions, or specify its path in the ACC settings if it's already installed.";
                                                            } else {
                                                                if (minPythonVersion != "") {
                                                                    //Min only
                                                                    pythonErr = "We could not locate a version of Python greater than v" + minPythonVersion + ". Please either download Python (min version " + minPythonVersion + ") or specify its path in the ACC settings if it's already installed.";
                                                                } else {
                                                                    //Max only
                                                                    pythonErr = "We could not locate a version of Python lower than v" + maxPythonVersion + ". Please either download Python (max version " + maxPythonVersion + ") or specify its path in the ACC settings if it's already installed.";
                                                                }
                                                            }
                                                        }

                                                        return Tuple.Create(false, pythonErr, false);
                                                    }
                                                } else if (theExtension == ".bat" || theExtension == ".cmd" || theExtension == ".btm") {
                                                    //Is batch - open it correctly (https://en.wikipedia.org/wiki/Batch_file#Filename_extensions)
                                                    p.FileName = "cmd.exe";
                                                    p.Arguments = String.Format("/c {0} \"{1}\"", scriptFileLocation, accArg);
                                                } else {
                                                    //"Other" filetype. Simply open file.
                                                    p.FileName = scriptFileLocation;
                                                    p.Arguments = accArg;
                                                }

                                                Process theP = Process.Start(p);

                                                if (!theP.WaitForExit(5000)) {
                                                    MainProgram.DoDebug("Action mod timed out");
                                                    theP.Kill();
                                                }
                                                string output = theP.StandardOutput.ReadToEnd();

                                                using (StringReader reader = new StringReader(output)) {
                                                    string line;
                                                    while ((line = reader.ReadLine()) != null) {
                                                        if (line.Length >= 17) {
                                                            if (line.Substring(0, 12) == "[ACC RETURN]") {
                                                                //Return for ACC
                                                                string returnContent = line.Substring(13),
                                                                    comment = returnContent.Contains(',') ? returnContent.Split(',')[1] : "";
                                                                bool actionSuccess = returnContent.Substring(0, 4) == "true";

                                                                if (comment.Length > 0 && char.IsWhiteSpace(comment, 0)) {
                                                                    comment = comment.Substring(1);
                                                                }

                                                                if (actionSuccess) {
                                                                    //Action was successfull
                                                                    Console.WriteLine("Action successful!");
                                                                } else {
                                                                    //Action was not successfull
                                                                    Console.WriteLine("Action failed :(");
                                                                }

                                                                Console.WriteLine("Comment; " + comment);
                                                                return Tuple.Create(actionSuccess, (comment.Length > 0 ? comment : "Action mod returned no reason for failing"), actionIsFatal);
                                                            }
                                                        }
                                                    }
                                                }

                                                return Tuple.Create(false, "Action mod didn't return anything to ACC", false);
                                            } catch (Exception e) {
                                                //Process init failed - it shouldn't, but better safe than sorry
                                                actionErrMsg = "Process initiation failed";
                                                Console.WriteLine(e);
                                            }
                                        } else {
                                            //Script file doesn't exist
                                            actionErrMsg = "Action mod script doesn't exist";
                                        }
                                    } else {
                                        actionErrMsg = "Action \"" + name + "\" requires a secondary parameter to be set";
                                    }
                                } else {
                                    actionErrMsg = "Action \"" + name + "\" requires a parameter to be set";
                                }
                            } else {
                                //JSON is not valid; validateErrMsg
                                actionErrMsg = validateErrMsg;
                            }
                        } else {
                            //JSON is invalid or failed
                            actionErrMsg = "Action mod JSON is invalid";
                        }
                    } catch (Exception e) {
                        //Failed to parse
                        actionErrMsg = "Failed to parse action mod JSON";
                        Console.WriteLine(e.Message);
                    }
                } else {
                    //Couldn't read file
                    MainProgram.DoDebug("1");
                }
            } else {
                MainProgram.DoDebug("0; " + modLocation);
            }

            return Tuple.Create(false, actionErrMsg, false);
        }

19 Source : MKMCsvUtils.cs
with GNU Affero General Public License v3.0
from alexander-pick

public static DataTable ConvertCSVtoDataTable(StreamReader sr)
    {
      DataTable dt = new DataTable();
      char separator = ',';
      try
      {
        // detect the separator - this replacedumes it's ether semicolon or comma and that semicolon cannot be part of column names
        string firstLine = sr.ReadLine();
        if (firstLine.Contains(';'))
          separator = ';';
        List<string> headers = parseCSVRow(firstLine, separator);
        foreach (string header in headers)
          dt.Columns.Add(header);
      }
      catch (Exception eError)
      {
        throw new FormatException("Wrong format of the header of CSV file: " + eError.Message);
      }
      while (!sr.EndOfStream)
      {
        try
        {
          List<string> row = parseCSVRow(sr.ReadLine(), separator);
          DataRow dr = dt.NewRow();
          for (int i = 0; i < row.Count; i++)
            dr[i] = row[i];
          dt.Rows.Add(dr);
        }
        catch (Exception eError)
        {
          // technically it is the (dt.Rows.Count + 1)th row, but in the file the first row is the header so this should
          // give the user the number of the row in the actual file
          throw new FormatException("Wrong format of the CSV file on row " + (dt.Rows.Count + 2) + ": " + eError.Message);
        }
      }
      return dt;
    }

19 Source : ValidatorBase.cs
with Apache License 2.0
from alexreinert

private async Task<ValidationResult> CheckHostInternalAsync(IPAddress ip, DomainName domain, string sender, bool expandExplanation, State state, CancellationToken token)
		{
			if ((domain == null) || (domain.Equals(DomainName.Root)))
			{
				return new ValidationResult() { Result = SpfQualifier.None, Explanation = String.Empty };
			}

			if (String.IsNullOrEmpty(sender))
			{
				sender = "postmaster@unknown";
			}
			else if (!sender.Contains('@'))
			{
				sender = "postmaster@" + sender;
			}

			LoadRecordResult loadResult = await LoadRecordsAsync(domain, token);

			if (!loadResult.CouldBeLoaded)
			{
				return new ValidationResult() { Result = loadResult.ErrorResult, Explanation = String.Empty };
			}

			T record = loadResult.Record;

			if ((record.Terms == null) || (record.Terms.Count == 0))
				return new ValidationResult() { Result = SpfQualifier.Neutral, Explanation = String.Empty };

			if (record.Terms.OfType<SpfModifier>().GroupBy(m => m.Type).Where(g => (g.Key == SpfModifierType.Exp) || (g.Key == SpfModifierType.Redirect)).Any(g => g.Count() > 1))
				return new ValidationResult() { Result = SpfQualifier.PermError, Explanation = String.Empty };

			ValidationResult result = new ValidationResult() { Result = loadResult.ErrorResult };

			#region Evaluate mechanism
			foreach (SpfMechanism mechanism in record.Terms.OfType<SpfMechanism>())
			{
				if (state.DnsLookupCount > DnsLookupLimit)
					return new ValidationResult() { Result = SpfQualifier.PermError, Explanation = String.Empty };

				SpfQualifier qualifier = await CheckMechanismAsync(mechanism, ip, domain, sender, state, token);

				if (qualifier != SpfQualifier.None)
				{
					result.Result = qualifier;
					break;
				}
			}
			#endregion

			#region Evaluate modifiers
			if (result.Result == SpfQualifier.None)
			{
				SpfModifier redirectModifier = record.Terms.OfType<SpfModifier>().FirstOrDefault(m => m.Type == SpfModifierType.Redirect);
				if (redirectModifier != null)
				{
					if (++state.DnsLookupCount > 10)
						return new ValidationResult() { Result = SpfQualifier.PermError, Explanation = String.Empty };

					DomainName redirectDomain = await ExpandDomainAsync(redirectModifier.Domain ?? String.Empty, ip, domain, sender, token);

					if ((redirectDomain == null) || (redirectDomain == DomainName.Root) || (redirectDomain.Equals(domain)))
					{
						result.Result = SpfQualifier.PermError;
					}
					else
					{
						result = await CheckHostInternalAsync(ip, redirectDomain, sender, expandExplanation, state, token);

						if (result.Result == SpfQualifier.None)
							result.Result = SpfQualifier.PermError;
					}
				}
			}
			else if ((result.Result == SpfQualifier.Fail) && expandExplanation)
			{
				SpfModifier expModifier = record.Terms.OfType<SpfModifier>().FirstOrDefault(m => m.Type == SpfModifierType.Exp);
				if (expModifier != null)
				{
					DomainName target = await ExpandDomainAsync(expModifier.Domain, ip, domain, sender, token);

					if ((target == null) || (target.Equals(DomainName.Root)))
					{
						result.Explanation = String.Empty;
					}
					else
					{
						DnsResolveResult<TxtRecord> dnsResult = await ResolveDnsAsync<TxtRecord>(target, RecordType.Txt, token);
						if ((dnsResult != null) && (dnsResult.ReturnCode == ReturnCode.NoError))
						{
							TxtRecord txtRecord = dnsResult.Records.FirstOrDefault();
							if (txtRecord != null)
							{
								result.Explanation = (await ExpandMacroAsync(txtRecord.TextData, ip, domain, sender, token)).ToString();
							}
						}
					}
				}
			}
			#endregion

			if (result.Result == SpfQualifier.None)
				result.Result = SpfQualifier.Neutral;

			return result;
		}

19 Source : CustomEditorGenerator.cs
with Apache License 2.0
from Algoryx

public static void Synchronize( bool regenerate = false )
    {
      // Newer versions replaces '.' with '+' so if our files
      // doesn't contains any '+' we regenerate all.
      {
        regenerate = regenerate ||
                     GetEditorFileInfos().FirstOrDefault( info => info.Name.StartsWith( "AGXUnity" ) &&
                                                                  !info.Name.Contains( '+' )
                                                        ) != null;

        if ( regenerate ) {
          Debug.Log( "Regenerating custom editors..." );
          foreach ( var info in GetEditorFileInfos() )
            DeleteFile( info );
        }
      }

      bool replacedetDatabaseDirty = false;

      // Removing editors which clreplacedes has been removed.
      {
        var replacedembly = GetAGXUnityreplacedembly();
        var editorreplacedembly = replacedembly.Load( Manager.AGXUnityEditorreplacedemblyName );
        foreach ( var info in GetEditorFileInfos() ) {
          var clreplacedName            = GetClreplacedName( info.Name );
          var type                 = replacedembly.GetType( clreplacedName, false );
          var editorClreplacedName      = "AGXUnityEditor.Editors." + GetClreplacedName( type ) + "Editor";
          var editorType           = editorreplacedembly.GetType( editorClreplacedName, false );
          var isEditorBaseMismatch = editorType != null && editorType.BaseType != typeof( InspectorEditor );
          if ( !IsMatch( type ) || isEditorBaseMismatch ) {
            Debug.Log( "Mismatching editor for clreplaced: " + clreplacedName + ", removing custom editor." );
            DeleteFile( info );
            replacedetDatabaseDirty = true;
          }
        }
      }

      // Generating missing editors.
      {
        var types = GetAGXUnityTypes();
        foreach ( var type in types ) {
          FileInfo info = new FileInfo( GetFilename( type, true ) );
          if ( !info.Exists ) {
            Debug.Log( "Custom editor for clreplaced " + type.ToString() + " is missing. Generating." );
            GenerateEditor( type, Path );
            replacedetDatabaseDirty = true;
          }
        }
      }

      if ( replacedetDatabaseDirty )
        replacedetDatabase.Refresh();
    }

19 Source : Lexer.cs
with MIT License
from alirezanet

public SyntaxToken NextToken()
      {
         if (_position >= _text.Length) return new SyntaxToken(SyntaxKind.End, _position, "\0");

         var peek = Peek(1);
         switch (Current)
         {
            case '(':
               return new SyntaxToken(SyntaxKind.OpenParenthesisToken, _position++, "(");
            case ')':
               return new SyntaxToken(SyntaxKind.CloseParenthesis, _position++, ")");
            case ',':
               return new SyntaxToken(SyntaxKind.And, _position++, ",");
            case '|':
               return new SyntaxToken(SyntaxKind.Or, _position++, "|");
            case '^':
            {
               _waitingForValue = true;
               return new SyntaxToken(SyntaxKind.StartsWith, _position++, "^");
            }
            case '$':
            {
               _waitingForValue = true;
               return new SyntaxToken(SyntaxKind.EndsWith, _position++, "$");
            }
            case '!' when peek == '^':
            {
               _waitingForValue = true;
               return new SyntaxToken(SyntaxKind.NotStartsWith, _position += 2, "!^");
            }
            case '!' when peek == '$':
            {
               _waitingForValue = true;
               return new SyntaxToken(SyntaxKind.NotEndsWith, _position += 2, "!$");
            }
            case '=' when peek == '*':
            {
               _waitingForValue = true;
               return new SyntaxToken(SyntaxKind.Like, _position += 2, "=*");
            }
            case '=':
            {
               _waitingForValue = true;
               return new SyntaxToken(SyntaxKind.Equal, _position ++ , "=");
            }
            case '!' when peek == '=':
            {
               _waitingForValue = true;
               return new SyntaxToken(SyntaxKind.NotEqual, _position += 2, "!=");
            }
            case '!' when peek == '*':
            {
               _waitingForValue = true;
               return new SyntaxToken(SyntaxKind.NotLike, _position += 2, "!*");
            }
            case '/' when peek == 'i':
               return new SyntaxToken(SyntaxKind.CaseInsensitive, _position += 2, "/i");
            case '<':
            {
               _waitingForValue = true;
               return peek == '=' ? new SyntaxToken(SyntaxKind.LessOrEqualThan, _position += 2, "<=") :
                  new SyntaxToken(SyntaxKind.LessThan, _position++, "<");
            }
            case '>':
            {
               _waitingForValue = true;
               return peek == '=' ? new SyntaxToken(SyntaxKind.GreaterOrEqualThan, _position += 2, ">=") : 
                  new SyntaxToken(SyntaxKind.GreaterThan, _position++, ">");
            }
         }

         if (Current == '[')
         {
            Next();
            var start = _position; 
            while (char.IsDigit(Current))  
               Next();
      
            var length = _position - start;
            var text = _text.Substring(start, length);

            if (Current == ']')
            {
               _position++;
               return new SyntaxToken(SyntaxKind.FieldIndexToken, start, text);
            }
            
            _diagnostics.Add($"bad character input: '{peek.ToString()}' at {_position++.ToString()}. expected ']' ");
            return new SyntaxToken(SyntaxKind.BadToken, _position, Current.ToString());

         }

         if (char.IsLetter(Current) && !_waitingForValue)
         {
            var start = _position;

            while (char.IsLetterOrDigit(Current) || Current is '_')  
               Next();

            var length = _position - start;
            var text = _text.Substring(start, length);
            
            return new SyntaxToken(SyntaxKind.FieldToken, start, text);
         }
         

         if (char.IsWhiteSpace(Current))
         {
            var start = _position;

            // skipper
            while (char.IsWhiteSpace(Current))
               Next();

            var length = _position - start;
            var text = _text.Substring(start, length);

            return new SyntaxToken(SyntaxKind.WhiteSpace, start, text);
         }

         if (_waitingForValue)
         {
            var start = _position;

            var exitCharacters = new[] {'(', ')', ',', '|'};
            var lastChar = '\0';
            while ((!exitCharacters.Contains(Current) || exitCharacters.Contains(Current) && lastChar == '\\') &&
                   _position < _text.Length &&
                   (!(Current == '/' && Peek(1) == 'i') || (Current == '/' && Peek(1) == 'i') && lastChar == '\\')) // exit on case-insensitive operator
            {
               lastChar = Current;
               Next();
            }

            var text = new StringBuilder();
            for (var i = start; i < _position; i++)
            {
               var current = _text[i];

               if (current != '\\') // ignore escape character
                  text.Append(current);
               else if (current == '\\' && i > 0) // escape escape character
                  if (_text[i - 1] == '\\')
                     text.Append(current);
            }

            _waitingForValue = false;
            return new SyntaxToken(SyntaxKind.ValueToken, start, text.ToString());
         }

         _diagnostics.Add($"bad character input: '{Current.ToString()}' at {_position.ToString()}");
         return new SyntaxToken(SyntaxKind.BadToken, _position++, string.Empty);
      }

19 Source : DumpCreator.cs
with GNU Lesser General Public License v3.0
from Alois-xx

private string GetProcDumpArgs(string[] procdumpArgs)
        {
            StringBuilder sb = new StringBuilder();
            foreach(var arg in procdumpArgs)
            {
                if( arg.Contains(' '))
                {
                    sb.Append($"\"{arg}\" ");
                }
                else
                {
                    sb.Append(arg);
                    sb.Append(' ');
                }
            }

            return sb.ToString();
        }

19 Source : SolutionLoader.cs
with MIT License
from Aminator

private async Task ApplyChangesToTemporaryFolderAsync(IReadOnlyList<StorageLibraryChange> changes)
        {
            if (RootFolder is null || TemporarySolutionFolder is null) return;

            foreach (StorageLibraryChange change in changes)
            {
                if (Path.GetFileName(change.Path).StartsWith(".")
                    || Path.GetFileName(change.PreviousPath).StartsWith(".")) continue;

                switch (change.ChangeType)
                {
                    case StorageLibraryChangeType.Created:
                    case StorageLibraryChangeType.ContentsChanged:
                    case StorageLibraryChangeType.MovedIntoLibrary:
                    case StorageLibraryChangeType.ContentsReplaced:
                        {
                            string relativePath = StorageExtensions.GetRelativePath(RootFolder.Path, change.Path);
                            string relativeDirectory = Path.GetDirectoryName(relativePath);

                            IStorageItem? destinationItem = relativePath.Contains(Path.DirectorySeparatorChar) ? await TemporarySolutionFolder.TryGereplacedemAsync(relativeDirectory) : TemporarySolutionFolder;
                            IStorageItem? item = await change.GetStorageItemAsync();

                            if (destinationItem is IStorageFolder destinationFolder)
                            {
                                if (item is IStorageFile file)
                                {
                                    await file.CopyAsync(destinationFolder, file.Name, NameCollisionOption.ReplaceExisting);
                                }
                                else if (item is IStorageFolder folder)
                                {
                                    await folder.CopyAsync(destinationFolder, NameCollisionOption.ReplaceExisting);
                                }
                            }
                        }
                        break;
                    case StorageLibraryChangeType.Deleted:
                    case StorageLibraryChangeType.MovedOutOfLibrary:
                        {
                            string relativePath = StorageExtensions.GetRelativePath(RootFolder.Path, change.Path);
                            IStorageItem? item = await TemporarySolutionFolder.TryGereplacedemAsync(relativePath);

                            if (item != null)
                            {
                                await item.DeleteAsync();
                            }
                        }
                        break;
                    case StorageLibraryChangeType.MovedOrRenamed:
                        {
                            string relativePath = StorageExtensions.GetRelativePath(RootFolder.Path, change.Path);
                            string relativeDirectory = Path.GetDirectoryName(relativePath);
                            string previousRelativePath = StorageExtensions.GetRelativePath(RootFolder.Path, change.PreviousPath);

                            IStorageItem? destinationItem = relativePath.Contains(Path.DirectorySeparatorChar) ? await TemporarySolutionFolder.TryGereplacedemAsync(relativeDirectory) : TemporarySolutionFolder;
                            IStorageItem? item = await TemporarySolutionFolder.GereplacedemAsync(previousRelativePath);

                            if (item != null)
                            {
                                if (Path.GetDirectoryName(change.Path).Equals(Path.GetDirectoryName(change.PreviousPath), StringComparison.OrdinalIgnoreCase))
                                {
                                    await item.RenameAsync(Path.GetFileName(change.Path));
                                }
                                else
                                {
                                    if (destinationItem is IStorageFolder destinationFolder)
                                    {
                                        if (item is IStorageFile file)
                                        {
                                            await file.MoveAsync(destinationFolder, file.Name, NameCollisionOption.ReplaceExisting);
                                        }
                                        else if (item is IStorageFolder folder)
                                        {
                                            await folder.MoveAsync(destinationFolder, NameCollisionOption.ReplaceExisting);
                                        }
                                    }
                                }
                            }
                        }
                        break;
                }

            }
        }

19 Source : SingleValueCodegenTypeFactory.cs
with MIT License
from Aminator

public static CodegenType MakeCodegenType(string name, Schema schema)
        {
            CodegenType returnType = new CodegenType();
            EnforceRestrictionsOnSetValues(returnType, name, schema);

            if (schema.Format == "uriref")
            {
                switch (schema.UriType)
                {
                    case UriType.Application:
                    case UriType.Image:
                    case UriType.Text:
                        returnType.CodeType = new CodeTypeReference(typeof(string));
                        returnType.AdditionalMembers.Add(Helpers.CreateMethodThatChecksIfTheValueOfAMemberIsNotEqualToAnotherExpression(name, new CodePrimitiveExpression(null)));
                        break;
                    case UriType.None:
                        throw new InvalidDataException("UriType must be specified in the schema");
                }

                return returnType;
            }

            if (schema.Type.Count > 1)
            {
                returnType.CodeType = new CodeTypeReference(typeof(object));
                returnType.AdditionalMembers.Add(Helpers.CreateMethodThatChecksIfTheValueOfAMemberIsNotEqualToAnotherExpression(name, new CodePrimitiveExpression(null)));
                return returnType;
            }

            var typeRef = schema.Type[0];
            if (typeRef.IsReference)
            {
                throw new NotImplementedException();
            }

            if (typeRef.Name == "object")
            {
                if (schema.Enum != null || schema.Default != null)
                {
                    throw new NotImplementedException();
                }

                if (schema.replacedle != null)
                {
                    returnType.CodeType = new CodeTypeReference(Helpers.ToPascalCase(schema.replacedle));
                    returnType.AdditionalMembers.Add(Helpers.CreateMethodThatChecksIfTheValueOfAMemberIsNotEqualToAnotherExpression(name, new CodePrimitiveExpression(null)));
                    return returnType;
                }
                throw new NotImplementedException();
            }

            if (typeRef.Name == "number")
            {
                if (schema.Enum != null)
                {
                    throw new NotImplementedException();
                }

                if (schema.Default != null)
                {
                    returnType.DefaultValue = new CodePrimitiveExpression(((JsonElement)schema.Default).GetSingle());
                    returnType.AdditionalMembers.Add(Helpers.CreateMethodThatChecksIfTheValueOfAMemberIsNotEqualToAnotherExpression(name, returnType.DefaultValue));
                }
                else if (!schema.IsRequired)
                {
                    returnType.CodeType = new CodeTypeReference(typeof(float?));
                    returnType.AdditionalMembers.Add(Helpers.CreateMethodThatChecksIfTheValueOfAMemberIsNotEqualToAnotherExpression(name, new CodePrimitiveExpression(null)));
                    return returnType;
                }

                returnType.CodeType = new CodeTypeReference(typeof(float));
                return returnType;
            }

            if (typeRef.Name == "string")
            {
                if (schema.Enum != null && !((string)schema.Enum[0]).Contains('/'))
                {
                    returnType.Attributes.Add(
                        new CodeAttributeDeclaration("System.Text.Json.Serialization.JsonConverterAttribute",
                        new[] { new CodeAttributeArgument(new CodeTypeOfExpression(typeof(System.Text.Json.Serialization.JsonStringEnumConverter))) }));
                    var enumType = GenStringEnumType(name, schema);
                    returnType.AdditionalMembers.Add(enumType);

                    if (schema.Default != null)
                    {
                        returnType.CodeType = new CodeTypeReference(enumType.Name);
                        for (var i = 0; i < enumType.Members.Count; i++)
                        {
                            if (enumType.Members[i].Name.Equals(((JsonElement)schema.Default).GetString(), StringComparison.OrdinalIgnoreCase))
                            {
                                returnType.DefaultValue = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(enumType.Name), enumType.Members[i].Name);
                                returnType.AdditionalMembers.Add(Helpers.CreateMethodThatChecksIfTheValueOfAMemberIsNotEqualToAnotherExpression(name, returnType.DefaultValue));
                                return returnType;
                            }
                        }
                        throw new InvalidDataException("The default value is not in the enum list");
                    }
                    // TODO: System.Text.Json.Serialization.JsonStringEnumConverter cannot handle nullable enums.
                    else if (!schema.IsRequired)
                    {
                        returnType.CodeType = new CodeTypeReference(typeof(Nullable<>));
                        returnType.CodeType.TypeArguments.Add(new CodeTypeReference(enumType.Name));
                        returnType.AdditionalMembers.Add(Helpers.CreateMethodThatChecksIfTheValueOfAMemberIsNotEqualToAnotherExpression(name, new CodePrimitiveExpression(null)));
                        return returnType;
                    }

                    returnType.CodeType = new CodeTypeReference(enumType.Name);
                    return returnType;
                }

                if (schema.Default != null)
                {
                    returnType.DefaultValue = new CodePrimitiveExpression(((JsonElement)schema.Default).GetString());
                    returnType.AdditionalMembers.Add(Helpers.CreateMethodThatChecksIfTheValueOfAMemberIsNotEqualToAnotherExpression(name, returnType.DefaultValue));
                }
                else
                {
                    returnType.AdditionalMembers.Add(Helpers.CreateMethodThatChecksIfTheValueOfAMemberIsNotEqualToAnotherExpression(name, new CodePrimitiveExpression(null)));
                }
                returnType.CodeType = new CodeTypeReference(typeof(string));
                return returnType;
            }

            if (typeRef.Name == "integer")
            {
                if (schema.Enum != null)
                {
                    var enumType = GenIntEnumType(name, schema);
                    returnType.AdditionalMembers.Add(enumType);

                    if (schema.Default != null)
                    {
                        returnType.DefaultValue = GetEnumField(enumType, ((JsonElement)schema.Default).GetInt32());
                        returnType.AdditionalMembers.Add(Helpers.CreateMethodThatChecksIfTheValueOfAMemberIsNotEqualToAnotherExpression(name, returnType.DefaultValue));
                    }
                    else if (!schema.IsRequired)
                    {
                        returnType.CodeType = new CodeTypeReference(typeof(Nullable<>));
                        returnType.CodeType.TypeArguments.Add(new CodeTypeReference(enumType.Name));
                        returnType.AdditionalMembers.Add(Helpers.CreateMethodThatChecksIfTheValueOfAMemberIsNotEqualToAnotherExpression(name, new CodePrimitiveExpression(null)));
                        return returnType;
                    }

                    returnType.CodeType = new CodeTypeReference(enumType.Name);
                    return returnType;
                }

                if (schema.Default != null)
                {
                    returnType.DefaultValue = new CodePrimitiveExpression(((JsonElement)schema.Default).GetInt32());
                    returnType.AdditionalMembers.Add(Helpers.CreateMethodThatChecksIfTheValueOfAMemberIsNotEqualToAnotherExpression(name, returnType.DefaultValue));
                }
                else if (!schema.IsRequired)
                {
                    returnType.CodeType = new CodeTypeReference(typeof(int?));
                    returnType.AdditionalMembers.Add(Helpers.CreateMethodThatChecksIfTheValueOfAMemberIsNotEqualToAnotherExpression(name, new CodePrimitiveExpression(null)));
                    return returnType;
                }

                returnType.CodeType = new CodeTypeReference(typeof(int));
                return returnType;
            }

            if (typeRef.Name == "boolean")
            {
                if (schema.Enum != null)
                {
                    throw new NotImplementedException();
                }

                if (schema.Default != null)
                {
                    returnType.DefaultValue = new CodePrimitiveExpression(((JsonElement)schema.Default).GetBoolean());
                    returnType.AdditionalMembers.Add(Helpers.CreateMethodThatChecksIfTheValueOfAMemberIsNotEqualToAnotherExpression(name, returnType.DefaultValue));
                }
                else if (!schema.IsRequired)
                {
                    returnType.CodeType = new CodeTypeReference(typeof(bool?));
                    returnType.AdditionalMembers.Add(Helpers.CreateMethodThatChecksIfTheValueOfAMemberIsNotEqualToAnotherExpression(name, new CodePrimitiveExpression(null)));
                    return returnType;
                }
                returnType.CodeType = new CodeTypeReference(typeof(bool));
                return returnType;
            }

            // other types: array, null

            throw new NotImplementedException(typeRef.Name);
        }

19 Source : FilterCriteriaObject.cs
with MIT License
from Analogy-LogViewer

[MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static bool Match(string rowLine, string criteria, PreDefinedQueryType type)
        {
            if (string.IsNullOrEmpty(criteria))
            {
                return false;
            }

            List<string> includeTexts = new List<string>(1) { criteria.Trim() };

            bool orOperationInInclude = false;
            if (criteria.Contains('|'))
            {
                orOperationInInclude = true;
                var split = criteria.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries).ToList();
                includeTexts = split.Select(itm => itm.Trim()).ToList();
            }

            if (criteria.Contains("&") || criteria.Contains('+'))
            {
                var split = criteria.Split(new[] { '&', '+' }, StringSplitOptions.RemoveEmptyEntries).ToList();
                includeTexts = split.Select(itm => itm.Trim()).ToList();
            }

            if (orOperationInInclude)
            {
                switch (type)
                {
                    case PreDefinedQueryType.Contains:
                        return includeTexts.Any(t =>
                            rowLine.Contains(t, StringComparison.InvariantCultureIgnoreCase) &&
                            !string.IsNullOrEmpty(t));
                    case PreDefinedQueryType.Equals:
                        return includeTexts.Any(t =>
                            rowLine.Equals(t, StringComparison.InvariantCultureIgnoreCase) && !string.IsNullOrEmpty(t));
                    default:
                        throw new ArgumentOutOfRangeException(nameof(type), type, null);
                }
            }
            else
            {
                switch (type)
                {
                    case PreDefinedQueryType.Contains:
                        return includeTexts.All(t => rowLine.Contains(t, StringComparison.InvariantCultureIgnoreCase) && !string.IsNullOrEmpty(t));
                    case PreDefinedQueryType.Equals:
                        return includeTexts.All(t => rowLine.Equals(t, StringComparison.InvariantCultureIgnoreCase) && !string.IsNullOrEmpty(t));
                    default:
                        throw new ArgumentOutOfRangeException(nameof(type), type, null);
                }
            }
        }

19 Source : FilterCriteriaObject.cs
with MIT License
from Analogy-LogViewer

[MethodImpl(MethodImplOptions.AggressiveInlining)]
        public string GetSqlExpression(bool orLogLevel)
        {

            StringBuilder sqlString = new StringBuilder();
            List<string> includeTexts = new List<string> { EscapeLikeValue(TextInclude.Trim()) };

            bool orOperationInInclude = false;
            bool orOperationInexclude = false;
            var text = EscapeLikeValue(TextInclude.Trim());
            if (text.Contains('|'))
            {
                orOperationInInclude = true;
                var split = text.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries).ToList();
                includeTexts = split.Select(itm => itm.Trim()).ToList();
            }

            if (text.Contains("&") || text.Contains('+'))
            {
                var split = text.Split(new[] { '&', '+' }, StringSplitOptions.RemoveEmptyEntries).ToList();
                includeTexts = split.Select(itm => itm.Trim()).ToList();
            }
            List<string> excludedTexts = new List<string>(0);
            if (!string.IsNullOrEmpty(TextExclude))
            {
                excludedTexts.Add(EscapeLikeValue(TextExclude.Trim()));
            }

            text = EscapeLikeValue(TextExclude.Trim());
            if (text.Contains("|"))
            {
                orOperationInexclude = true;
                var split = text.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries).ToList();
                excludedTexts = split.Select(itm => itm.Trim()).Where(w => !string.IsNullOrEmpty(w)).ToList();
            }
            if (text.Contains("&") || text.Contains("+"))
            {
                var split = text.Split(new[] { '&', '+' }, StringSplitOptions.RemoveEmptyEntries).ToList();
                excludedTexts = split.Select(itm => itm.Trim()).ToList();
            }

            sqlString.Append(UserSettingsManager.UserSettings.SearchAlsoInSourceAndModule ? "((" : "(");

            sqlString.Append(orOperationInInclude
                ? string.Join(" Or ", includeTexts.Select(t => $" Text like '%{t}%'"))
                : string.Join(" and ", includeTexts.Select(t => $" Text like '%{t}%'")));

            sqlString.Append(")");

            if (UserSettingsManager.UserSettings.SearchAlsoInSourceAndModule)
            {
                //also in source
                sqlString.Append(" or (");
                if (orOperationInInclude)
                {
                    sqlString.Append(string.Join(" Or ", includeTexts.Select(t => $" Source like '%{t}%'")));
                }
                else
                {
                    sqlString.Append(string.Join(" And ", includeTexts.Select(t => $" Source like '%{t}%'")));
                }

                sqlString.Append(")");
                //also in module
                sqlString.Append(" or (");
                if (orOperationInInclude)
                {
                    sqlString.Append(string.Join(" Or ", includeTexts.Select(t => $" Module like '%{t}%'")));
                }
                else
                {
                    sqlString.Append(string.Join(" And ", includeTexts.Select(t => $" Module like '%{t}%'")));
                }

                sqlString.Append("))");
            }

            if (excludedTexts.Any())
            {
                sqlString.Append(" and (");
                sqlString.Append(orOperationInexclude
                    ? string.Join(" and ", excludedTexts.Select(t => $" NOT Text like '%{t}%'"))
                    : string.Join(" Or ", excludedTexts.Select(t => $" NOT Text like '%{t}%'")));

                sqlString.Append(")");
            }

            if (Sources != null && Sources.Any())
            {
                sqlString.Append(" and (");
                sqlString.Append(string.Join(" Or ", Sources.Select(l => $" Source like '%{EscapeLikeValue(l)}%'")));
                sqlString.Append(")");
            }
            if (ExcludedSources != null && ExcludedSources.Any())
            {
                sqlString.Append(" and (");
                sqlString.Append(string.Join(" and ", ExcludedSources.Select(l => $" NOT Source like '%{EscapeLikeValue(l)}%'")));
                sqlString.Append(")");
            }
            if (ExcludedModules != null && ExcludedModules.Any())
            {
                sqlString.Append(" and (");
                sqlString.Append(string.Join(" and", ExcludedModules.Select(l => $" NOT Module like '%{EscapeLikeValue(l)}%'")));
                sqlString.Append(")");
            }

            if (Modules != null && Modules.Any())
            {
                sqlString.Append(" and (");
                sqlString.Append(string.Join(" Or ", Modules.Select(l => $" Module like '%{EscapeLikeValue(l)}%'")));
                sqlString.Append(")");
            }

            string andOr = orLogLevel ? "or" : "and";
            if (Levels != null && Levels.Any())
            {
                string sTemp = string.Join(",", Levels.Select(l => $"'{l}'"));
                sqlString.Append($" {andOr} Level in (" + sTemp + ")");
            }

            string dateFilter = $" AND (Date >= '{NewerThan}' and Date <= '{OlderThan}')";

            sqlString.Append(dateFilter);

            if (includeTexts.Any())
            {
                var includeColumns = IncludeFilterCriteriaUIOptions.Where(f => f.CheckMember);
                foreach (FilterCriteriaUIOption include in includeColumns)
                {
                    sqlString.Append(" or (");
                    string op = (orOperationInInclude) ? "or" : "and";
                    sqlString.Append(string.Join($" {op} ",
                        includeTexts.Select(l =>
                            $" [{EscapeLikeValue(include.ValueMember)}] like '%{EscapeLikeValue(l)}%'")));
                    sqlString.Append(")");
                }
            }

            if (excludedTexts.Any())
            {
                var excludeColumns = ExcludeFilterCriteriaUIOptions.Where(f => f.CheckMember);
                foreach (FilterCriteriaUIOption exclude in excludeColumns)
                {
                    sqlString.Append(" and (");
                    string op = (orOperationInexclude) ? "and" : "or";
                    sqlString.Append(string.Join($" {op} ",
                        excludedTexts.Select(l =>
                            $" NOT [{EscapeLikeValue(exclude.ValueMember)}] like '%{EscapeLikeValue(l)}%'")));
                    sqlString.Append(")");
                }
            }

            return sqlString.ToString();
        }

19 Source : CronYearParser.cs
with Apache License 2.0
from Anapher

private static int? GetNextYear(string yearExp, int year)
        {
            if (yearExp == "*")
                return year;

            if (yearExp.Contains('/'))
            {
                // Every years(s) starting in
                var split = yearExp.Split('/');
                var startingYear = int.Parse(split[0]);
                var every = int.Parse(split[1]);

                if (startingYear > year) return null;
                if (startingYear == year) return year;

                return startingYear + (int) Math.Ceiling((year - startingYear) / (every * 1.0)) * every;
            }

            if (yearExp.Contains("-"))
            {
                // Every year between and 
                var split = yearExp.Split('-');
                var val1 = int.Parse(split[0]);
                var val2 = int.Parse(split[1]);

                var start = Math.Min(val1, val2);
                var end = Math.Max(val1, val2);

                if (year > end) return null;
                if (start > year) return start;

                return year;
            }

            // specific years
            var specificYears = yearExp.Split(',', StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToList();
            if (specificYears.Contains(year)) return year;

            var nextYear = specificYears.Where(x => x > year).OrderBy(x => x).Select(x => (int?) x).FirstOrDefault();
            return nextYear;
        }

19 Source : _term.cs
with MIT License
from ancientproject

private static void _error<T>(ErrorToken<T> token, string source)
        {
            var col = token.ErrorResult.Remainder.Column;
            var lin = token.ErrorResult.Remainder.Line;
            var exp = token.ErrorResult.Expectations.First();
            var rem = token.ErrorResult.Remainder.Current;

            var nestedLine = source.Split('\n')[lin-1];
            var replaced = getFromMiddle(nestedLine, col, nestedLine.Length - col, true);
            var startOffset = source.IndexOf(nestedLine, StringComparison.InvariantCultureIgnoreCase);
            var nameOffset = (startOffset + col - 1);

            var doc2 = new StringDoreplacedent("", source);
            var highlightRegion = new SourceRegion(new SourceSpan(doc2, startOffset, nestedLine.Length));

            var focusRegion = new SourceRegion(
                new SourceSpan(doc2, nameOffset, replaced.Length));
            var replacedle = $"{token.ErrorResult.getWarningCode().To<string>().Pastel(Color.Orange)}";
            var message = $"character '{exp}' expected".Pastel(Color.Orange);

            string Render(MarkupNode node, params NodeRenderer[] extraRenderers)
            {
                var writer = new StringWriter();
                var terminal = new TextWriterTerminal(writer, 160, Encoding.ASCII);
                var log = new TerminalLog(terminal).WithRenderers(extraRenderers);
                log.Log(node);
                return writer.ToString();
            }

            var result = Render(
                new HighlightedSource(highlightRegion, focusRegion), 
                new HighlightedSourceRenderer(3, Colors.Red));
            WriteLine($" :: {replacedle} - {message}");
            var ses = result.Split('\n');
            var flag1 = false;
            foreach (var (value, index) in ses.Select((value, index) => (value, index)))
            {
                var next = ses.Select((value, index) => new {value, index}).FirstOrDefault(x => x.index == index + 1);
                if (next != null && (next.value.Contains('~') && next.value.Contains('^')) && !flag1)
                    WriteLine(value.Replace(replaced, replaced.Pastel(Color.Red)));
                else if (value.Contains('~') && value.Contains('^'))
                {
                    if (flag1) 
                        continue;
                    WriteLine(value.Pastel(Color.Red));
                    flag1 = true;
                }
                else
                    WriteLine($"{value} ");
            }
        }

19 Source : SqlNameMangling.cs
with GNU General Public License v3.0
from anderson-joyle

public static string GetValidSqlName(string nameOfField, int arrayIndex)
        {
            // Support for Table Extension
            nameOfField = nameOfField.Contains(ExtensionNameSeparator) ? nameOfField.Replace(ExtensionNameSeparator, '$') : nameOfField;
            nameOfField = nameOfField.ToUpperInvariant();

            if (nameOfField[0] == '.')
            {
                nameOfField = "$" + nameOfField.Substring(1);
            }
            else if (nameOfField[0] == ':')
            {
                nameOfField = X + nameOfField.Substring(1);
            }
            else if (nameOfField[0] == '_')
            {
                nameOfField = X + nameOfField.Substring(1);
            }

            StringBuilder filtered = new StringBuilder(nameOfField.Length);
            for (int i = 0; i < nameOfField.Length; i++)
            {
                char current = nameOfField[i];
                if (current > 127)
                {
                    filtered.Append(X);
                }
                else
                {
                    filtered.Append(current);
                }
            }
            nameOfField = filtered.ToString();

            if (arrayIndex > 1)
            {
                // generate array fields like Dim, Dim2_, Dim3_ ...
                nameOfField += arrayIndex + "_";
            }
            // handle reserved keywords like "key", "percent" etc.
            else if (ReservedKeywordsSet.Contains(nameOfField))
            {
                nameOfField += "_";
            }

            return nameOfField;
        }

19 Source : DirectoryInfoExtensions.cs
with GNU General Public License v3.0
from AndreiFedarets

public static FileInfo[] GetFilesFixed(this DirectoryInfo directoryinfo, string searchPattern)
        {
            if (((searchPattern.Length - (searchPattern.LastIndexOf('.') + 1)) == 3) && !
            searchPattern.Substring(searchPattern.LastIndexOf('.')).Contains('*'))
                return directoryinfo.GetFiles(searchPattern).ToList().FindAll
                (F => F.Extension.Length == 4).ToArray();
            return directoryinfo.GetFiles(searchPattern);
        }

19 Source : DirectoryInfoExtensions.cs
with GNU General Public License v3.0
from AndreiFedarets

public static FileInfo[] GetFilesFixed(this DirectoryInfo directoryinfo, string searchPattern, SearchOption searchOption)
        {
            if (((searchPattern.Length - (searchPattern.LastIndexOf('.') + 1)) == 3) && !
            searchPattern.Substring(searchPattern.LastIndexOf('.')).Contains('*'))
                return directoryinfo.GetFiles(searchPattern, searchOption).ToList().FindAll
                (f => f.Extension.Length == 4).ToArray();
            return directoryinfo.GetFiles(searchPattern);
        }

19 Source : CodeStructureParser.cs
with MIT License
from AndresTraks

private static SourceItemDefinition CreateFoldersOnPath(string path, RootFolderDefinition rootFolder)
        {
            SourceItemDefinition folder = rootFolder;

            while (path.Contains('/'))
            {
                var index = path.IndexOf('/');
                string folderName = path.Substring(0, path.IndexOf('/'));
                var existingFolder = folder.Children.FirstOrDefault(c => c.Name == folderName);
                if (existingFolder != null)
                {
                    folder = existingFolder;
                }
                else
                {
                    var newFolder = new FolderDefinition(folderName) { Parent = folder };
                    folder.Children.Add(newFolder);
                    folder = newFolder;
                }
                path = path.Substring(index + 1);
            }

            return folder;
        }

19 Source : StringBuilderExtensions.cs
with MIT License
from AndreyAkinshin

public static StringBuilder TrimEnd([CanBeNull] this StringBuilder builder, params char[] trimChars)
        {
            if (builder == null)
                return null;

            int length = builder.Length;
            if (trimChars.Any())
                while (length > 0 && trimChars.Contains(builder[length - 1]))
                    length--;
            else
                while (length > 0 && char.IsWhiteSpace(builder[length - 1]))
                    length--;

            builder.Length = length;
            return builder;
        }

19 Source : CustomHelpers.cs
with MIT License
from andruzzzhka

public static string CheckHex(string input)
        {
            input = input.ToUpper();
            if(input.All(x => hexChars.Contains(x)))
            {
                return input;
            }
            else
            {
                return "";
            }
        }

19 Source : Convert.cs
with MIT License
from Andy53

public static string HexToAscii(string hex)
        {
            if (hex.Length % 2 != 0)
            {
                hex = "0" + hex;
            }

            foreach (char c in hex)
            {
                if (!HEX_CHARS.Contains(c))
                {
                    return string.Empty;
                }
            }

            try
            {
                string ascii = string.Empty;

                for (int i = 0; i < hex.Length; i += 2)
                {
                    String hs = string.Empty;

                    hs = hex.Substring(i, 2);
                    uint decval = System.Convert.ToUInt32(hs, 16);
                    char character = System.Convert.ToChar(decval);
                    ascii += character;

                }

                return ascii;
            }
            catch (Exception ex) { Console.WriteLine(ex.Message); }

            return string.Empty;
        }

19 Source : Sql.cs
with MIT License
from anet-team

public static string[] GetParamNames(object param)
        {
            if (param == null)
            {
                return new string[] { };
            }

            if (param is string str)
            {
                if (str.Contains(','))
                    return str
                        .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                        .Select(x => x.Trim()).ToArray();
                return new[] { str };
            }

            if (param is IEnumerable<string> array)
            {
                return array.ToArray();
            }

            if (param is DynamicParameters dynamicParameters)
            {
                return dynamicParameters.ParameterNames.ToArray();
            }

            var type = param is Type ? (param as Type) : param.GetType();

            return type
                .GetProperties()
                .Where(x => x.PropertyType.IsSimpleType() || x.PropertyType.GetAnyElementType().IsSimpleType())
                .Select(x => x.Name).ToArray();
        }

19 Source : PostfixedAttributeMatcher.cs
with MIT License
from AngleSharp

private static bool NameHasPostfixSeparator(string ctrlName)
        {
            return ctrlName.Contains(':');
        }

19 Source : Program.cs
with MIT License
from AnkitSharma-007

internal static void removeduplicate(string str)
        {
            /* input:- csharpcorner ; output:- csharpone
             * 
             */
            string result = string.Empty;

            for (int i = 0; i < str.Length; i++)
            {
                if (!result.Contains(str[i]))
                {
                    result += str[i];
                }
            }
            Console.WriteLine(result);
        }

19 Source : WordListReducer.cs
with Apache License 2.0
from AnkiUniversal

public static bool IsSpecialChar(char c)
        {
            return specialChars.Contains(c);
        }

19 Source : RomaConvert.cs
with Apache License 2.0
from AnkiUniversal

public static string ConvertKataToRomaFullLoop(StringBuilder builder)
        {
            for (int i = 0; i < NUMBER_OF_WORD; i++)
            {
                builder.Replace(HiraRomaKata[i, KATAKANA], HiraRomaKata[i, ROMAJI]);
            }
            builder.Replace("ッ", " ");
            string results = builder.ToString();

            if (results.Contains('ー'))
            {
                return results.Replace('ー', '-');
            }
            else
                return results;
        }

19 Source : StringHelper.cs
with Apache License 2.0
from AnkiUniversal

public static string RemapCharIfNeeded(this string str)
        {
            foreach(var c in RemapCharList)
            {
                if (str.Contains(c))
                    str = str.Replace(c, GetCharacterRemap(c));
            }
            return str;
        }

19 Source : ISpeachController.cs
with BSD 3-Clause "New" or "Revised" License
from anoyetta

public static string GetCacheFileName(
            this ISpeechController ctrl,
            string ttsType,
            string tts,
            string parameter,
            bool isMp3 = false)
        {
            var ext = !isMp3 ? "wav" : "mp3";
            var hash = parameter.GetHashCode().ToString("X4");
            var cacheName = $"{ttsType}.{tts}.{hash}.{ext}";

            // ファイル名に使用できない文字を除去する
            cacheName = string.Concat(cacheName.Where(c => !InvalidCars.Contains(c)));

            var fileName = Path.Combine(
                CacheDirectory,
                cacheName);

            if (!Directory.Exists(Path.GetDirectoryName(fileName)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(fileName));
            }

            return fileName;
        }

19 Source : XIVLogPlugin.cs
with BSD 3-Clause "New" or "Revised" License
from anoyetta

private string GetZoneNameForFile()
        {
            var zone = this.currentZoneName;

            if (string.IsNullOrEmpty(zone))
            {
                zone = "Unknown Zone";
            }
            else
            {
                zone = string.Concat(zone.Where(c => !InvalidChars.Contains(c)));
            }

            zone = zone.Replace(" ", "_");

            return zone;
        }

19 Source : EnmityInfoWorker.cs
with BSD 3-Clause "New" or "Revised" License
from anoyetta

private async void WriteEnmityLog(
            IEnumerable<EnmityEntry> enmityEntryList)
        {
            var config = Settings.Instance.Enmity;

            if (string.IsNullOrEmpty(config.LogDirectory))
            {
                return;
            }

            var player = CombatantsManager.Instance.Player;
            if (player == null)
            {
                return;
            }

#if !DEBUG
            if (SharlayanHelper.Instance.PartyMemberCount < 4)
            {
                return;
            }
#endif

            if (enmityEntryList.Count() < 1)
            {
                return;
            }

            if (!Directory.Exists(config.LogDirectory))
            {
                Directory.CreateDirectory(config.LogDirectory);
            }

            var now = DateTime.Now;

            await Task.Run(() =>
            {
                lock (LogLocker)
                {
                    var inCombat = XIVPluginHelper.Instance.InCombat;
                    if (this.currentInCombat != inCombat)
                    {
                        this.currentInCombat = inCombat;

                        if (this.currentInCombat)
                        {
                            this.currentTake++;
                        }
                        else
                        {
                            this.logStream?.Flush();
                        }
                    }

                    var zone = ActGlobals.oFormActMain.CurrentZone;
                    if (this.currentZone != zone)
                    {
                        this.currentZone = zone;
                        this.logStream?.Flush();
                    }

                    var f = $"{now:yyyy-MM-dd}.Enmity.{zone}.take{this.currentTake}.csv";
                    f = string.Concat(f.Where(c => !Path.GetInvalidFileNameChars().Contains(c)));

                    var fileName = Path.Combine(
                        config.LogDirectory,
                        f);

                    if (string.IsNullOrEmpty(this.currentLogFile) ||
                        this.currentLogFile != fileName)
                    {
                        this.currentLogFile = fileName;

                        if (this.logStream != null)
                        {
                            this.logStream.Flush();
                            this.logStream.Close();
                            this.logStream = null;
                        }

                        this.logStream = new StreamWriter(
                            this.currentLogFile,
                            false,
                            new UTF8Encoding(false));
                    }

                    if (this.logStream != null)
                    {
                        var fields = new List<string>(24);

                        fields.Add(now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
                        fields.Add("\"" + this.TargetInfo.Name + "\"");

                        var party = CombatantsManager.Instance.GetPartyList();

                        foreach (var member in party)
                        {
                            Thread.Yield();

                            var enmityData = enmityEntryList.FirstOrDefault(x =>
                                x.ID == member.ID);

                            fields.Add("\"" + member.Name + "\"");
                            fields.Add("\"" + member.JobID.ToString() + "\"");
                            fields.Add((enmityData?.Enmity ?? 0).ToString("#"));
                        }

                        this.logStream.WriteLine(string.Join(",", fields));
                    }
                }
            });
        }

See More Examples