Here are the examples of the csharp api string.Remove(int) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1069 Examples
19
View Source File : ClusterAdapter.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
void RefershClusterNodes()
{
foreach (var testConnection in _clusterConnectionStrings)
{
RegisterClusterNode(testConnection);
//尝试求出其他节点,并缓存slot
try
{
var cnodes = AdapterCall<string>("CLUSTER".SubCommand("NODES"), rt => rt.ThrowOrValue<string>()).Split('\n');
foreach (var cnode in cnodes)
{
if (string.IsNullOrEmpty(cnode)) continue;
var dt = cnode.Trim().Split(' ');
if (dt.Length < 9) continue;
if (!dt[2].StartsWith("master") && !dt[2].EndsWith("master")) continue;
if (dt[7] != "connected") continue;
var endpoint = dt[1];
var at40 = endpoint.IndexOf('@');
if (at40 != -1) endpoint = endpoint.Remove(at40);
if (endpoint.StartsWith("127.0.0.1"))
endpoint = $"{DefaultRedisSocket.SplitHost(testConnection.Host).Key}:{endpoint.Substring(10)}";
else if (endpoint.StartsWith("localhost", StringComparison.CurrentCultureIgnoreCase))
endpoint = $"{DefaultRedisSocket.SplitHost(testConnection.Host).Key}:{endpoint.Substring(10)}";
ConnectionStringBuilder connectionString = testConnection.ToString();
connectionString.Host = endpoint;
RegisterClusterNode(connectionString);
for (var slotIndex = 8; slotIndex < dt.Length; slotIndex++)
{
var slots = dt[slotIndex].Split('-');
if (ushort.TryParse(slots[0], out var tryslotStart) &&
ushort.TryParse(slots[1], out var tryslotEnd))
{
for (var slot = tryslotStart; slot <= tryslotEnd; slot++)
_slotCache.AddOrUpdate(slot, connectionString.Host, (k1, v1) => connectionString.Host);
}
}
}
break;
}
catch
{
_ib.TryRemove(testConnection.Host, true);
}
}
if (_ib.GetKeys().Length == 0)
throw new RedisClientException($"All \"clusterConnectionStrings\" failed to connect");
}
19
View Source File : Resp3HelperTests.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
[Fact]
public void Command()
{
string UFString(string text)
{
if (text.Length <= 1) return text.ToUpper();
else return text.Substring(0, 1).ToUpper() + text.Substring(1, text.Length - 1);
}
var rt = rds.Command();
var sb = string.Join("\r\n\r\n", (rt.Value).OrderBy(a1 => (a1 as List<object>)[0].ToString()).Select(a1 =>
{
var a = a1 as List<object>;
var plen = int.Parse(a[1].ToString());
var firstKey = int.Parse(a[3].ToString());
var lastKey = int.Parse(a[4].ToString());
var stepCount = int.Parse(a[5].ToString());
var parms = "";
if (plen > 1)
{
for (var x = 1; x < plen; x++)
{
if (x == firstKey) parms += "string key, ";
else parms += "string parm, ";
}
parms = parms.Remove(parms.Length - 2);
}
if (plen < 0)
{
for (var x = 1; x < -plen; x++)
{
if (x == firstKey) parms += "string key, ";
else parms += "string parm, ";
}
if (parms.Length > 0)
parms = parms.Remove(parms.Length - 2);
}
return [email protected]"
//{string.Join(", ", a[2] as List<object>)}
//{string.Join(", ", a[6] as List<object>)}
public void {UFString(a[0].ToString())}({parms}) {{ }}";
}));
}
19
View Source File : CommandFlagsTests.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
[Fact]
public void Command()
{
string UFString(string text)
{
if (text.Length <= 1) return text.ToUpper();
else return text.Substring(0, 1).ToUpper() + text.Substring(1, text.Length - 1);
}
var rt = cli.Command();
//var rt = cli.CommandInfo("mset", "mget", "set", "get", "rename");
var flags = new List<string>();
var flags7 = new List<string>();
var diccmd = new Dictionary<string, (string[], string[])>();
var sb = string.Join("\r\n\r\n", (rt).OrderBy(a1 => (a1 as object[])[0].ToString()).Select(a1 =>
{
var a = a1 as object[];
var cmd = a[0].ToString();
var plen = int.Parse(a[1].ToString());
var firstKey = int.Parse(a[3].ToString());
var lastKey = int.Parse(a[4].ToString());
var stepCount = int.Parse(a[5].ToString());
var aflags = (a[2] as object[]).Select(a => a.ToString()).ToArray();
var fopts = (a[6] as object[]).Select(a => a.ToString()).ToArray();
flags.AddRange(aflags);
flags7.AddRange(fopts);
diccmd.Add(cmd.ToUpper(), (aflags, fopts));
var parms = "";
if (plen > 1)
{
for (var x = 1; x < plen; x++)
{
if (x == firstKey) parms += "string key, ";
else parms += $"string arg{x}, ";
}
parms = parms.Remove(parms.Length - 2);
}
if (plen < 0)
{
for (var x = 1; x < -plen; x++)
{
if (x == firstKey)
{
if (firstKey != lastKey) parms += "string[] keys, ";
else parms += "string key, ";
}
else
{
if (firstKey != lastKey) parms += $"string[] arg{x}, ";
else parms += $"string arg{x}, ";
}
}
if (parms.Length > 0)
parms = parms.Remove(parms.Length - 2);
}
return [email protected]"
//{string.Join(", ", a[2] as object[])}
//{string.Join(", ", a[6] as object[])}
public void {UFString(cmd)}({parms}) {{ }}";
}));
flags = flags.Distinct().ToList();
flags7 = flags7.Distinct().ToList();
var sboptions = new StringBuilder();
foreach (var cmd in CommandSets._allCommands)
{
if (diccmd.TryGetValue(cmd, out var tryv))
{
sboptions.Append([email protected]"
[""{cmd}""] = new CommandSets(");
for (var x = 0; x < tryv.Item1.Length; x++)
{
if (x > 0) sboptions.Append(" | ");
sboptions.Append($"ServerFlag.{tryv.Item1[x].Replace("readonly", "@readonly")}");
}
sboptions.Append(", ");
for (var x = 0; x < tryv.Item2.Length; x++)
{
if (x > 0) sboptions.Append(" | ");
sboptions.Append($"ServerTag.{tryv.Item2[x].TrimStart('@').Replace("string", "@string")}");
}
sboptions.Append(", LocalStatus.none),");
}
else
{
sboptions.Append([email protected]"
[""{cmd}""] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none), ");
}
}
var optioncode = sboptions.ToString();
}
19
View Source File : ConsoleApp.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
public static (string info, string warn, string err) ShellRun(string cddir, params string[] bat) {
if (bat == null || bat.Any() == false) return ("", "", "");
if (string.IsNullOrEmpty(cddir)) cddir = Directory.GetCurrentDirectory();
var proc = new System.Diagnostics.Process();
proc.StartInfo = new System.Diagnostics.ProcessStartInfo {
CreateNoWindow = true,
FileName = "cmd.exe",
UseShellExecute = false,
RedirectStandardError = true,
RedirectStandardInput = true,
RedirectStandardOutput = true,
WorkingDirectory = cddir
};
proc.Start();
foreach (var cmd in bat)
proc.StandardInput.WriteLine(cmd);
proc.StandardInput.WriteLine("exit");
var outStr = proc.StandardOutput.ReadToEnd();
var errStr = proc.StandardError.ReadToEnd();
proc.Close();
var idx = outStr.IndexOf($">{bat[0]}");
if (idx != -1) {
idx = outStr.IndexOf("\n", idx);
if (idx != -1) outStr = outStr.Substring(idx + 1);
}
idx = outStr.LastIndexOf(">exit");
if (idx != -1) {
idx = outStr.LastIndexOf("\n", idx);
if (idx != -1) outStr = outStr.Remove(idx);
}
outStr = outStr.Trim();
if (outStr == "") outStr = null;
if (errStr == "") errStr = null;
return (outStr, string.IsNullOrEmpty(outStr) ? null : errStr, string.IsNullOrEmpty(outStr) ? errStr : null);
}
19
View Source File : InternalExtensions.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
internal static string DisplayCsharp(this Type type, bool isNameSpace = true)
{
if (type == null) return null;
if (type == typeof(void)) return "void";
if (type.IsGenericParameter) return type.Name;
if (type.IsArray) return $"{DisplayCsharp(type.GetElementType())}[]";
var sb = new StringBuilder();
var nestedType = type;
while (nestedType.IsNested)
{
sb.Insert(0, ".").Insert(0, DisplayCsharp(nestedType.DeclaringType, false));
nestedType = nestedType.DeclaringType;
}
if (isNameSpace && string.IsNullOrWhiteSpace(nestedType.Namespace) == false)
sb.Insert(0, ".").Insert(0, nestedType.Namespace);
if (type.IsGenericType == false)
return sb.Append(type.Name).ToString();
var genericParameters = type.GetGenericArguments();
if (type.IsNested && type.DeclaringType.IsGenericType)
{
var dic = genericParameters.ToDictionary(a => a.Name);
foreach (var nestedGenericParameter in type.DeclaringType.GetGenericArguments())
if (dic.ContainsKey(nestedGenericParameter.Name))
dic.Remove(nestedGenericParameter.Name);
genericParameters = dic.Values.ToArray();
}
if (genericParameters.Any() == false)
return sb.Append(type.Name).ToString();
sb.Append(type.Name.Remove(type.Name.IndexOf('`'))).Append("<");
var genericTypeIndex = 0;
foreach (var genericType in genericParameters)
{
if (genericTypeIndex++ > 0) sb.Append(", ");
sb.Append(DisplayCsharp(genericType, true));
}
return sb.Append(">").ToString();
}
19
View Source File : TypeExtension.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
public static string DisplayCsharp(this Type type, bool isNameSpace = true)
{
if (type == null) return null;
if (type == typeof(void)) return "void";
if (type.IsGenericParameter) return type.Name;
if (type.IsArray) return $"{DisplayCsharp(type.GetElementType())}[]";
var sb = new StringBuilder();
var nestedType = type;
while (nestedType.IsNested)
{
sb.Insert(0, ".").Insert(0, DisplayCsharp(nestedType.DeclaringType, false));
nestedType = nestedType.DeclaringType;
}
if (isNameSpace && string.IsNullOrWhiteSpace(nestedType.Namespace) == false)
sb.Insert(0, ".").Insert(0, nestedType.Namespace);
if (type.IsGenericType == false)
return sb.Append(type.Name).ToString();
var genericParameters = type.GetGenericArguments();
if (type.IsNested && type.DeclaringType.IsGenericType)
{
var dic = genericParameters.ToDictionary(a => a.Name);
foreach (var nestedGenericParameter in type.DeclaringType.GetGenericArguments())
if (dic.ContainsKey(nestedGenericParameter.Name))
dic.Remove(nestedGenericParameter.Name);
genericParameters = dic.Values.ToArray();
}
if (genericParameters.Any() == false)
return sb.Append(type.Name).ToString();
sb.Append(type.Name.Remove(type.Name.IndexOf('`'))).Append("<");
var genericTypeIndex = 0;
foreach (var genericType in genericParameters)
{
if (genericTypeIndex++ > 0) sb.Append(", ");
sb.Append(DisplayCsharp(genericType, true));
}
return sb.Append(">").ToString();
}
19
View Source File : DynamicProxyExtensions.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
internal static string DisplayCsharp(this Type type, bool isNameSpace = true)
{
if (type == null) return null;
if (type == typeof(void)) return "void";
if (type.IsGenericParameter) return type.Name;
if (type.IsArray) return $"{DisplayCsharp(type.GetElementType())}[]";
var sb = new StringBuilder();
var nestedType = type;
while (nestedType.IsNested)
{
sb.Insert(0, ".").Insert(0, DisplayCsharp(nestedType.DeclaringType, false));
nestedType = nestedType.DeclaringType;
}
if (isNameSpace && string.IsNullOrEmpty(nestedType.Namespace) == false)
sb.Insert(0, ".").Insert(0, nestedType.Namespace);
if (type.IsGenericType == false)
return sb.Append(type.Name).ToString();
var genericParameters = type.GetGenericArguments();
if (type.IsNested && type.DeclaringType.IsGenericType)
{
var dic = genericParameters.ToDictionary(a => a.Name);
foreach (var nestedGenericParameter in type.DeclaringType.GetGenericArguments())
if (dic.ContainsKey(nestedGenericParameter.Name))
dic.Remove(nestedGenericParameter.Name);
genericParameters = dic.Values.ToArray();
}
if (genericParameters.Any() == false)
return sb.Append(type.Name).ToString();
sb.Append(type.Name.Remove(type.Name.IndexOf('`'))).Append("<");
var genericTypeIndex = 0;
foreach (var genericType in genericParameters)
{
if (genericTypeIndex++ > 0) sb.Append(", ");
sb.Append(DisplayCsharp(genericType, true));
}
return sb.Append(">").ToString();
}
19
View Source File : BeatmapConverter.cs
License : MIT License
Project Creator : 39M
License : MIT License
Project Creator : 39M
static void Convert()
{
Debug.Log(string.Format("Source path: {0}", beatmapPath));
// 每个目录代表一首歌,里面按字典序放置至多三个谱面,依次为 Easy, Normal, Hard
string[] sourceDirectories = Directory.GetDirectories(beatmapPath);
foreach (string directoryPath in sourceDirectories)
{
Music music = new Music();
// 遍历单个目录下的所有 osu 文件,对每个文件创建一个 Beatmap 对象,加到 Music 对象里面
string[] sourceFiles = Directory.GetFiles(directoryPath, "*.osu");
int count = 0;
foreach (string filepath in sourceFiles)
{
string[] lines = File.ReadAllLines(filepath);
Beatmap beatmap = new Beatmap();
music.beatmapList.Add(beatmap);
#region Set Difficulty
beatmap.difficultyName = difficultyNames[Mathf.Min(count, difficultyNames.Length - 1)];
beatmap.difficultyDisplayColor = new SimpleColor(difficultyColors[Mathf.Min(count, difficultyNames.Length - 1)]);
count++;
#endregion
#region Processing file line by line
bool startProcessNotes = false;
foreach (string line in lines)
{
if (line.StartsWith("[HitObjects]"))
{
startProcessNotes = true;
continue;
}
if (!startProcessNotes)
{
// 处理谱面信息
int lastIndex = line.LastIndexOf(':');
if (lastIndex < 0)
{
// 如果不是有效信息行则跳过
continue;
}
string value = line.Substring(lastIndex + 1).Trim();
if (line.StartsWith("replacedle"))
{
music.replacedle = value;
}
else if (line.StartsWith("Artist"))
{
music.artist = value;
}
else if (line.StartsWith("AudioFilename"))
{
value = value.Remove(value.LastIndexOf('.'));
music.audioFilename = value;
music.bannerFilename = value;
music.soundEffectFilename = value;
}
else if (line.StartsWith("PreviewTime"))
{
music.previewTime = float.Parse(value) / 1000;
}
else if (line.StartsWith("Creator"))
{
beatmap.creator = value;
}
else if (line.StartsWith("Version"))
{
beatmap.version = value;
}
}
else
{
// 开始处理 HitObject
string[] noteInfo = line.Split(',');
int type = int.Parse(noteInfo[3]);
if ((type & 0x01) != 0)
{
// Circle
beatmap.noteList.Add(new Note
{
x = int.Parse(noteInfo[0]),
y = int.Parse(noteInfo[1]),
time = float.Parse(noteInfo[2]) / 1000,
// 其他 Circle 相关的处理
});
}
else if ((type & 0x02) != 0)
{
// Slider
beatmap.noteList.Add(new Note
{
x = int.Parse(noteInfo[0]),
y = int.Parse(noteInfo[1]),
time = float.Parse(noteInfo[2]) / 1000,
// 其他 Slider 相关的处理
});
}
else if ((type & 0x08) != 0)
{
// Spinner
beatmap.noteList.Add(new Note
{
x = int.Parse(noteInfo[0]),
y = int.Parse(noteInfo[1]),
time = float.Parse(noteInfo[2]) / 1000,
// 其他 Spinner 相关的处理
});
beatmap.noteList.Add(new Note
{
x = int.Parse(noteInfo[0]),
y = int.Parse(noteInfo[1]),
time = float.Parse(noteInfo[5]) / 1000,
// 其他 Spinner 相关的处理
});
}
}
}
#endregion
}
string targetPath = directoryPath + ".json";
if (File.Exists(targetPath))
{
File.Delete(targetPath);
}
File.WriteAllText(targetPath, music.ToJson());
Debug.Log(string.Format("Converted osu! beatmap\n[{0}]\nto json file\n[{1}]", directoryPath, targetPath));
}
Debug.Log(string.Format("All done, converted {0} files.", sourceDirectories.Length));
}
19
View Source File : Utils.cs
License : MIT License
Project Creator : 39M
License : MIT License
Project Creator : 39M
public static string RemoveExtensionName(string path)
{
int index = path.LastIndexOf('.');
if (index >= 0)
{
if (extensionNameList.Contains(path.Substring(index)))
{
path = path.Remove(index);
}
}
return path;
}
19
View Source File : Program.cs
License : GNU Affero General Public License v3.0
Project Creator : 3CORESec
License : GNU Affero General Public License v3.0
Project Creator : 3CORESec
public static Dictionary<string, dynamic> DeserializeYamlFile(string ruleFilePath, Options o)
{
var contents = File.ReadAllText(ruleFilePath);
if (!contents.Contains("tags"))
{
Console.WriteLine($"Ignoring rule {ruleFilePath} (no tags)");
return null;
}
if (o.Warning)
contents = contents.Replace(Environment.NewLine + Environment.NewLine,
Environment.NewLine)
.Remove(0, contents.IndexOf("tags", StringComparison.Ordinal));
if (contents.Contains("---"))
contents = contents.Remove(contents.IndexOf("---", StringComparison.Ordinal));
var deserializer = new YamlDotNet.Serialization.Deserializer();
var dict = deserializer.Deserialize<Dictionary<string, dynamic>>(contents);
return dict;
}
19
View Source File : GCodeParser.cs
License : MIT License
Project Creator : 3RD-Dimension
License : MIT License
Project Creator : 3RD-Dimension
static string CleanupLine(string line, int lineNumber)
{
int commentIndex = line.IndexOf(';');
if (commentIndex > -1)
line = line.Remove(commentIndex);
int start = -1;
while ((start = line.IndexOf('(')) != -1)
{
int end = line.IndexOf(')');
if (end < start)
throw new ParseException("mismatched parentheses", lineNumber);
line = line.Remove(start, end - start);
}
return line;
}
19
View Source File : GrblSettingsWindow.xaml.cs
License : MIT License
Project Creator : 3RD-Dimension
License : MIT License
Project Creator : 3RD-Dimension
public void LineReceived(string line)
{
// Recieve GRBL Controller Version number and display - $i
// Recieved in format [VER: ... and [OPT:
if (!line.StartsWith("$") && !line.StartsWith("[VER:") && !line.StartsWith("[OPT:"))
return;
if (line.StartsWith("$"))
{
try
{
Match m = settingParser.Match(line);
int number = int.Parse(m.Groups[1].Value);
double value = double.Parse(m.Groups[2].Value, Util.Constants.DecimalParseFormat);
// Value = Setting Value, Number = Setting Code
if (!CurrentSettings.ContainsKey(number))
{
RowDefinition rowDef = new RowDefinition();
rowDef.Height = new GridLength(25);
gridMain.RowDefinitions.Add(rowDef);
TextBox valBox = new TextBox // Value of Setting Textbox
{
Text = value.ToString(Util.Constants.DecimalOutputFormat),
VerticalAlignment = VerticalAlignment.Center
};
// Define Mouseclick for textbox to open GRBLStepsCalcWindow for setting $100, $101, $102
if (number == 100) { valBox.Name = "Set100"; valBox.MouseDoubleClick += openStepsCalc; }
else if (number == 101) { valBox.Name = "Set101"; valBox.MouseDoubleClick += openStepsCalc; }
else if (number == 102) { valBox.Name = "Set102"; valBox.MouseDoubleClick += openStepsCalc; }
Grid.SetRow(valBox, gridMain.RowDefinitions.Count - 1);
Grid.SetColumn(valBox, 1);
gridMain.Children.Add(valBox);
TextBlock num = new TextBlock
{
Text = $"${number}=",
HorizontalAlignment = HorizontalAlignment.Right,
VerticalAlignment = VerticalAlignment.Center
};
Grid.SetRow(num, gridMain.RowDefinitions.Count - 1);
Grid.SetColumn(num, 0);
gridMain.Children.Add(num);
if (Util.GrblCodeTranslator.Settings.ContainsKey(number))
{
Tuple<string, string, string> labels = Util.GrblCodeTranslator.Settings[number];
TextBlock name = new TextBlock
{
Text = labels.Item1,
VerticalAlignment = VerticalAlignment.Center
};
Grid.SetRow(name, gridMain.RowDefinitions.Count - 1);
Grid.SetColumn(name, 0);
gridMain.Children.Add(name);
TextBlock unit = new TextBlock
{
Text = labels.Item2,
VerticalAlignment = VerticalAlignment.Center
};
Grid.SetRow(unit, gridMain.RowDefinitions.Count - 1);
Grid.SetColumn(unit, 2);
gridMain.Children.Add(unit);
valBox.ToolTip = $"{labels.Item1} ({labels.Item2}):\n{labels.Item3}";
}
CurrentSettings.Add(number, value);
SettingsBoxes.Add(number, valBox);
}
else
{
SettingsBoxes[number].Text = value.ToString(Util.Constants.DecimalOutputFormat);
CurrentSettings[number] = value;
}
}
catch { }
}
// If the line starts with [VER: then we know we are getting the version and options
else if (line.StartsWith("[VER:") || line.StartsWith("[OPT:"))
{
// Frist need to remove front [ and rear ]
string VerOptInput; // Input string
string[] VerOptTrimmed;
VerOptInput = line.Remove(0, 1); // Remove [ from the start
VerOptInput = VerOptInput.Remove(VerOptInput.Length - 1);
// Next, split the values in half at the : - we only want VER/OPT and then the values
VerOptTrimmed = VerOptInput.Split(':');
// Now we fill in the boxes depending on which one
switch (VerOptTrimmed[0])
{
case "VER":
controllerInfo += "Version: " + VerOptTrimmed[1];
break;
case "OPT":
// First we have to split commas
string[] optSplit;
optSplit = VerOptTrimmed[1].Split(','); // Splits Options into 3. 0=Options, 1=blockBufferSize, 2=rxBufferSize
var individualChar = optSplit[0].ToCharArray();// Now split optSplit[0] into each option character
controllerInfo += " | Options: " + VerOptTrimmed[1]; // Full Options Non-Decoded String
foreach (char c in individualChar)
{
// Lookup what each code is and display.... buildCodes Dictionary
if (Util.GrblCodeTranslator.BuildCodes.ContainsKey(c.ToString()))
{
// Now lets try and create and append to a string and then bind it to a ToolTip? or some other way
controllerInfo += Environment.NewLine + Util.GrblCodeTranslator.BuildCodes[c.ToString()];
}
}
controllerInfo += Environment.NewLine + "Block Buffer Size: " + optSplit[1];
controllerInfo += Environment.NewLine + "RX Buffer Size: " + optSplit[2];
GRBL_Controller_Info.Text = controllerInfo.ToString();
break;
}
}
}
19
View Source File : GenericTypeExtensions.cs
License : MIT License
Project Creator : Abdulrhman5
License : MIT License
Project Creator : Abdulrhman5
public static string GetGenericTypeName(this Type type)
{
var typeName = string.Empty;
if (type.IsGenericType)
{
var genericTypes = string.Join(",", type.GetGenericArguments().Select(t => t.Name).ToArray());
typeName = $"{type.Name.Remove(type.Name.IndexOf('`'))}<{genericTypes}>";
}
else
{
typeName = type.Name;
}
return typeName;
}
19
View Source File : PackageManifestUpdater.cs
License : Apache License 2.0
Project Creator : abist-co-ltd
License : Apache License 2.0
Project Creator : abist-co-ltd
internal static void EnsureMSBuildForUnity()
{
PackageManifest manifest = null;
string manifestPath = GetPackageManifestFilePath();
if (string.IsNullOrWhiteSpace(manifestPath))
{
return;
}
// Read the package manifest into a list of strings (for easy finding of entries)
// and then deserialize.
List<string> manifestFileLines = new List<string>();
using (FileStream manifestStream = new FileStream(manifestPath, FileMode.Open, FileAccess.Read))
{
using (StreamReader reader = new StreamReader(manifestStream))
{
// Read the manifest file a line at a time.
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
manifestFileLines.Add(line);
}
// Go back to the start of the file.
manifestStream.Seek(0, 0);
// Deserialize the scoped registries portion of the package manifest.
manifest = JsonUtility.FromJson<PackageManifest>(reader.ReadToEnd());
}
}
if (manifest == null)
{
Debug.LogError($"Failed to read the package manifest file ({manifestPath})");
return;
}
// Ensure that pre-existing scoped registries are retained.
List<ScopedRegistry> scopedRegistries = new List<ScopedRegistry>();
if ((manifest.scopedRegistries != null) && (manifest.scopedRegistries.Length > 0))
{
scopedRegistries.AddRange(manifest.scopedRegistries);
}
// Attempt to find an entry in the scoped registries collection for the MSBuild for Unity URL
bool needToAddRegistry = true;
foreach (ScopedRegistry registry in scopedRegistries)
{
if (registry.url == MSBuildRegistryUrl)
{
needToAddRegistry = false;
}
}
// If no entry was found, add one.
if (needToAddRegistry)
{
ScopedRegistry registry = new ScopedRegistry();
registry.name = MSBuildRegistryName;
registry.url = MSBuildRegistryUrl;
registry.scopes = MSBuildRegistryScopes;
scopedRegistries.Add(registry);
}
// Update the manifest's scoped registries, as the collection may have been modified.
manifest.scopedRegistries = scopedRegistries.ToArray();
int dependenciesStartIndex = -1;
int scopedRegistriesStartIndex = -1;
int scopedRegistriesEndIndex = -1;
int packageLine = -1;
// Presume that we need to add the MSBuild for Unity package. If this value is false,
// we will check to see if the currently configured version meets or exceeds the
// minimum requirements.
bool needToAddPackage = true;
// Attempt to find the MSBuild for Unity package entry in the dependencies collection
// This loop also identifies the dependencies collection line and the start / end of a
// pre-existing scoped registries collections
for (int i = 0; i < manifestFileLines.Count; i++)
{
if (manifestFileLines[i].Contains("\"scopedRegistries\":"))
{
scopedRegistriesStartIndex = i;
}
if (manifestFileLines[i].Contains("],") && (scopedRegistriesStartIndex != -1) && (scopedRegistriesEndIndex == -1))
{
scopedRegistriesEndIndex = i;
}
if (manifestFileLines[i].Contains("\"dependencies\": {"))
{
dependenciesStartIndex = i;
}
if (manifestFileLines[i].Contains(MSBuildPackageName))
{
packageLine = i;
needToAddPackage = false;
}
}
// If no package was found add it to the dependencies collection.
if (needToAddPackage)
{
// Add the package to the collection (pad the entry with four spaces)
manifestFileLines.Insert(dependenciesStartIndex + 1, $" \"{MSBuildPackageName}\": \"{MSBuildPackageVersion}\",");
}
else
{
// Replace the line that currently exists
manifestFileLines[packageLine] = $" \"{MSBuildPackageName}\": \"{MSBuildPackageVersion}\",";
}
// Update the manifest file.
// First, serialize the scoped registry collection.
string serializedRegistriesJson = JsonUtility.ToJson(manifest, true);
// Ensure that the file is truncated to ensure it is always valid after writing.
using (FileStream outFile = new FileStream(manifestPath, FileMode.Truncate, FileAccess.Write))
{
using (StreamWriter writer = new StreamWriter(outFile))
{
bool scopedRegistriesWritten = false;
// Write each line of the manifest back to the file.
for (int i = 0; i < manifestFileLines.Count; i++)
{
if ((i >= scopedRegistriesStartIndex) && (i <= scopedRegistriesEndIndex))
{
// Skip these lines, they will be replaced.
continue;
}
if (!scopedRegistriesWritten && (i > 0))
{
// Trim the leading '{' and '\n' from the serialized scoped registries
serializedRegistriesJson = serializedRegistriesJson.Remove(0, 2);
// Trim, the trailing '\n' and '}'
serializedRegistriesJson = serializedRegistriesJson.Remove(serializedRegistriesJson.Length - 2);
// Append a trailing ',' to close the scopedRegistries node
serializedRegistriesJson = serializedRegistriesJson.Insert(serializedRegistriesJson.Length, ",");
writer.WriteLine(serializedRegistriesJson);
scopedRegistriesWritten = true;
}
writer.WriteLine(manifestFileLines[i]);
}
}
}
}
19
View Source File : _Host.cshtml.cs
License : Apache License 2.0
Project Creator : acblog
License : Apache License 2.0
Project Creator : acblog
public async Task<string> Getreplacedle()
{
string path = HttpContext.Request.Path.ToString().Trim('/');
{
int indFrag = path.IndexOf('#');
if (indFrag != -1)
path = path.Remove(indFrag);
}
string[] pathSegs = path.Split('/');
List<string> result = new List<string>
{
"AcBlog"
};
if (pathSegs.Length > 0)
{
switch (pathSegs[0])
{
case "posts":
await GeneratePostreplacedle(pathSegs[1..], result, "Posts");
break;
case "articles":
await GeneratePostreplacedle(pathSegs[1..], result, "Articles");
break;
case "slides":
await GeneratePostreplacedle(pathSegs[1..], result, "Slides");
break;
case "notes":
await GeneratePostreplacedle(pathSegs[1..], result, "Notes");
break;
case "categories":
// await GenerateCategoryreplacedle(pathSegs[1..], result);
break;
case "keywords":
// await GenerateKeywordreplacedle(pathSegs[1..], result);
break;
}
}
result.Reverse();
return string.Join(" - ", result);
}
19
View Source File : CalendarPage.xaml.cs
License : MIT License
Project Creator : Actipro
License : MIT License
Project Creator : Actipro
private void ClearAndPopulateCalendar() {
coreGrid.Children.Clear();
Month month = this.Month;
Day startDay = this.StartDay;
int totalDays;
daysPerMonth.TryGetValue(month, out totalDays);
if (totalDays == 0)
return;
// Populate blank day boxes
Day currentDay = Day.Sunday;
for (int i = 0; i < (int)startDay; i++) {
// Create a border and set parameters
Border border = new Border() {
BorderBrush = new SolidColorBrush(Colors.Black),
BorderThickness = new Thickness(0)
};
Grid.SetColumn(border, (int)currentDay);
Grid.SetRow(border, 0);
// Create a grid
Grid grid = new Grid();
// Make the grid a child of the border
border.Child = grid;
// Color the current day
grid.Background = new SolidColorBrush(Color.FromArgb(255, 224, 224, 224));
// Add the border to the core grid
coreGrid.Children.Add(border);
// Increment the current day
currentDay++;
}
// Iterate through all the days of the month
currentDay = startDay;
for (int i = 0; i < totalDays; i++) {
// Create a border and set parameters
Border border = new Border() {
BorderBrush = new SolidColorBrush(Colors.Black),
BorderThickness = new Thickness(1)
};
Grid.SetColumn(border, (int)currentDay);
Grid.SetRow(border, (int)((i + (int)startDay) / 7));
// Create a grid and configure it
Grid grid = new Grid();
grid.RowDefinitions.Add(new RowDefinition() {
Height = new GridLength(0, GridUnitType.Auto)
});
grid.RowDefinitions.Add(new RowDefinition());
// Make the grid a child of the border
border.Child = grid;
// Create the text block that displays the day number and set parameters
TextBlock textBox = new TextBlock() {
Text = (i + 1).ToString(),
FontSize = 10,
Margin = new Thickness(1, 1, 0, 0)
};
// Make the text block that displays the day number a child of the grid
grid.Children.Add(textBox);
// Generate this day's holiday string
string holidayString = "";
foreach (var holiday in holidays) {
if (holiday.Day == i + 1)
holidayString += holiday.HolidayName + Environment.NewLine;
}
if (!String.IsNullOrEmpty(holidayString))
holidayString = holidayString.Remove(holidayString.Length - 2);
// Create the text block that displays holiday information
textBox = new TextBlock() {
Text = holidayString,
FontSize = 8,
Margin = new Thickness(1, 0, 0, 0),
VerticalAlignment = VerticalAlignment.Bottom
};
// Set the grid row of the text block that displays holiday information to 1
Grid.SetRow(textBox, 1);
// Make the text block that displays the holiday information a child of the grid
grid.Children.Add(textBox);
// Color the current day
if ((DateTime.Now.Month == ((int)Month) + 1) && (DateTime.Now.Day == (i + 1)))
grid.Background = new SolidColorBrush(Color.FromArgb(255, 255, 255, 150));
// Color days that contain holidays
else if (!String.IsNullOrEmpty(holidayString))
grid.Background = new SolidColorBrush(Color.FromArgb(255, 158, 211, 255));
// Add the border to the core grid
coreGrid.Children.Add(border);
// Increment the current day
if (currentDay != Day.Saturday)
currentDay++;
else
currentDay = Day.Sunday;
}
int cell = (int)startDay + totalDays;
int row = (int)(cell / 7);
int column = cell % 7;
while (row < 6) {
// Create a border and set parameters
Border border = new Border() {
BorderBrush = new SolidColorBrush(Colors.Black),
BorderThickness = new Thickness(0)
};
Grid.SetColumn(border, column);
Grid.SetRow(border, row);
// Create a grid
Grid grid = new Grid();
// Make the grid a child of the border
border.Child = grid;
// Color the current day
grid.Background = new SolidColorBrush(Color.FromArgb(255, 224, 224, 224));
// Add the border to the core grid
coreGrid.Children.Add(border);
// Increment the cell
column++;
if (column > 6) {
column = 0;
row++;
}
}
}
19
View Source File : ChildrenCodeTemplate.cs
License : MIT License
Project Creator : adamant
License : MIT License
Project Creator : adamant
public string PopIndent()
{
string returnValue = "";
if ((this.indentLengths.Count > 0))
{
int indentLength = this.indentLengths[(this.indentLengths.Count - 1)];
this.indentLengths.RemoveAt((this.indentLengths.Count - 1));
if ((indentLength > 0))
{
returnValue = this.currentIndentField.Substring((this.currentIndentField.Length - indentLength));
this.currentIndentField = this.currentIndentField.Remove((this.currentIndentField.Length - indentLength));
}
}
return returnValue;
}
19
View Source File : POComment.cs
License : MIT License
Project Creator : adams85
License : MIT License
Project Creator : adams85
public static bool TryParse(string value, out POSourceReference result)
{
if (value == null)
throw new ArgumentNullException(nameof(value));
var index = value.LastIndexOf(':');
if (index >= 0 && int.TryParse(value.Substring(index + 1), NumberStyles.Integer, CultureInfo.InvariantCulture, out int line))
value = value.Remove(index);
else
line = default(int);
var length = value.Length;
if (length > 0 && value[0] == '"')
if (length > 1 && value[length - 1] == '"')
value = value.Substring(1, length - 2);
else
{
result = default(POSourceReference);
return false;
}
result = new POSourceReference(value, line);
return true;
}
19
View Source File : POComment.cs
License : MIT License
Project Creator : adams85
License : MIT License
Project Creator : adams85
internal static bool TryParse(string value, string keyStringNewLine, out POPreviousValueComment result)
{
if (value == null)
throw new ArgumentNullException(nameof(value));
string idKindToken = null;
value = value.Trim();
var index = value.FindIndex(char.IsWhiteSpace);
if (index >= 0)
{
idKindToken = value.Remove(index);
value = value.Substring(index + 1).TrimStart();
}
int length;
POIdKind idKind;
StringBuilder sb;
if (index < 0 ||
(length = value.Length) < 2 || value[0] != '"' || value[length - 1] != '"' ||
(idKind = POKey.GetIdKind(idKindToken)) == POIdKind.Unknown ||
POString.Decode(sb = new StringBuilder(), value, 1, length - 2, keyStringNewLine) >= 0)
{
result = null;
return false;
}
result = new POPreviousValueComment { IdKind = idKind, Value = sb.ToString() };
return true;
}
19
View Source File : CrmContactRoleProvider.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public static string GetDefaultApplicationName()
{
try
{
string applicationVirtualPath = HostingEnvironment.ApplicationVirtualPath;
if (!string.IsNullOrEmpty(applicationVirtualPath)) return applicationVirtualPath;
applicationVirtualPath = Process.GetCurrentProcess().MainModule.ModuleName;
int index = applicationVirtualPath.IndexOf('.');
if (index != -1)
{
applicationVirtualPath = applicationVirtualPath.Remove(index);
}
if (!string.IsNullOrEmpty(applicationVirtualPath)) return applicationVirtualPath;
return "/";
}
catch
{
return "/";
}
}
19
View Source File : ContentMapUrlMapping.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
private static bool ParseParentPath(string path, out string parentPath, out string lastPathComponent)
{
parentPath = null;
lastPathComponent = null;
if (path == "/") return false;
var lastIndex = path.LastIndexOf('/');
if (lastIndex >= 0)
{
var newPath = path.Remove(lastIndex + 1);
if (newPath == string.Empty)
{
parentPath = "/";
lastPathComponent = path.Remove(0, 1);
return true;
}
parentPath = newPath;
lastPathComponent = path.Remove(0, newPath.Length);
return true;
}
return false;
}
19
View Source File : Utility.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public static string GetDefaultApplicationName()
{
try
{
string applicationVirtualPath = HostingEnvironment.ApplicationVirtualPath;
if (!string.IsNullOrEmpty(applicationVirtualPath)) return applicationVirtualPath;
applicationVirtualPath = Process.GetCurrentProcess().MainModule.ModuleName;
int index = applicationVirtualPath.IndexOf('.');
if (index != -1)
{
applicationVirtualPath = applicationVirtualPath.Remove(index);
}
if (!string.IsNullOrEmpty(applicationVirtualPath)) return applicationVirtualPath;
return "/";
}
catch
{
return "/";
}
}
19
View Source File : UrlMapping.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
private static bool ParseParentPath(string path, out string parentPath, out string lastPathComponent)
{
parentPath = null;
lastPathComponent = null;
if (path == "/") return false;
var lastIndex = path.LastIndexOf('/');
if (lastIndex >= 0)
{
var newPath = path.Remove(lastIndex);
if (newPath == string.Empty)
{
parentPath = "/";
lastPathComponent = path.Remove(0, 1);
return true;
}
parentPath = newPath;
lastPathComponent = path.Remove(0, newPath.Length + 1);
return true;
}
return false;
}
19
View Source File : AduPasswordBox.cs
License : GNU General Public License v3.0
Project Creator : aduskin
License : GNU General Public License v3.0
Project Creator : aduskin
private void ZPreplacedwordBox_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
{
if (!this.mIsHandledTextChanged)
return;
foreach (TextChange c in e.Changes)
{
//从密码文中根据本次Change对象的索引和长度删除对应个数的字符
this.Preplacedword = this.Preplacedword.Remove(c.Offset, c.RemovedLength);
//将Text新增的部分记录给密码文
this.Preplacedword = this.Preplacedword.Insert(c.Offset, Text.Substring(c.Offset, c.AddedLength));
}
if (!this.ShowPreplacedword)
{
this.SetText(ConvertToPreplacedwordChar(Text.Length));
}
//将光标放到最后面
this.SelectionStart = this.Text.Length + 1;
}
19
View Source File : ConsoleObservable.cs
License : MIT License
Project Creator : afucher
License : MIT License
Project Creator : afucher
private string BuildLine(string content, ConsoleKeyInfo newKey)
{
if (newKey.Key == ConsoleKey.Backspace)
return content == "" ? content : content.Remove(content.Length-1);
return content + newKey.KeyChar;
}
19
View Source File : CreditCardNumberValidator.cs
License : MIT License
Project Creator : afucher
License : MIT License
Project Creator : afucher
private bool IsValidLuhnAlgorithm(string cleanCreditCardNumber)
{
// Store the last digit (check digit)
var checkDigit = cleanCreditCardNumber[cleanCreditCardNumber.Length - 1];
// Remove the last digit (check digit)
cleanCreditCardNumber = cleanCreditCardNumber.Remove(cleanCreditCardNumber.Length - 1);
// Reverse all digits
cleanCreditCardNumber = new string(cleanCreditCardNumber.Reverse().ToArray());
// Convert the clean credit card number into a int list
var creditCardNumArr = cleanCreditCardNumber.ToCharArray().Select(x => (int)char.GetNumericValue(x)).ToList();
// Multiply odd position digits by 2
var creditCardNumArrTemp = new List<int>();
for (int i = 0; i < creditCardNumArr.Count; i++)
{
if ((i + 1) % 2 != 0)
{
creditCardNumArrTemp.Add(creditCardNumArr[i] * 2);
}
else
{
creditCardNumArrTemp.Add(creditCardNumArr[i]);
}
}
creditCardNumArr = creditCardNumArrTemp;
// Subtract 9 to all numbers above 9
creditCardNumArr = creditCardNumArr.Select(x =>
{
if (x > 9)
{
return x - 9;
}
return x;
}).ToList();
// Get numbers total
var ccNumbersTotal = creditCardNumArr.Sum();
// Get modulo of total
var moduloOfNumbersTotal = (10 - (ccNumbersTotal % 10)) % 10;
// If modulo of total is equal to the check digit
return moduloOfNumbersTotal == (int)char.GetNumericValue(checkDigit);
}
19
View Source File : PercentageValidator.cs
License : MIT License
Project Creator : afucher
License : MIT License
Project Creator : afucher
public bool Validate(string value)
{
try
{
if (value.EndsWith("%"))
{
value = value.Remove(value.Length - 1);
}
var number = float.Parse(value);
return number >= 0 && number <= 100;
}
catch (Exception)
{
return false;
}
}
19
View Source File : NpcSpawnHelper.cs
License : GNU General Public License v3.0
Project Creator : AHeroicLlama
License : GNU General Public License v3.0
Project Creator : AHeroicLlama
public static string TrimNPCName(string name)
{
// Drop the plurals
if (name.EndsWith("s"))
{
name = name.Remove(name.Length - 1);
}
// Drop the ESSChance prefix
name = new StringBuilder(name)
.Replace("ESSChanceSub", string.Empty)
.Replace("ESSChanceMain", string.Empty)
// Drop the editor labels
.Replace("LARGE", string.Empty)
.Replace("GIANTONLY", string.Empty)
// Convert names
.Replace("Rat", "Rad Rat")
.Replace("Toad", "Rad Toad")
.Replace("RadAnt", "Rad Ant")
.Replace("Scorpions", "Rad Scorpion")
.Replace("MoleMiner", "Mole Miner")
.Replace("ViciousDog", "Vicious Dog")
.Replace("SuperMutant", "Super Mutant")
.Replace("Megasloth", "Mega Sloth")
.Replace("Molerat", "Mole Rat")
.Replace("YaoGuai", "Yao Guai")
.Replace("FogCrawler", "Fog Crawler")
.Replace("HoneyBeast", "Honey Beast")
.Replace("CaveCricket", "Cave Cricket")
.Replace("Mutations", "Snallygaster")
.Replace("GraftonMonster", "Grafton Monster")
.ToString();
return name;
}
19
View Source File : MainWindow.xaml.cs
License : GNU Affero General Public License v3.0
Project Creator : aianlinb
License : GNU Affero General Public License v3.0
Project Creator : aianlinb
private void OnButtonAddClick(object sender, RoutedEventArgs e)
{
BundleRecord bundleToSave = (BundleRecord)(((ItemModel)View1.SelectedItem)?.Record);
if (MessageBox.Show(
(bundleToSave == null ? "This will import all files to the smallest of all loaded bundles (doesn't contain which were filtered)." : "This will import all files to \"" + bundleToSave.Name + "\"") + Environment.NewLine
+ "All files to be imported must be defined by the _.index.bin." + Environment.NewLine
+ "Are you sure you want to do this?",
"Import Confirm",
MessageBoxButton.OKCancel, MessageBoxImage.Question, MessageBoxResult.Cancel) == MessageBoxResult.OK)
{
var fbd = new OpenFolderDialog();
if (fbd.ShowDialog() == true)
{
var fileNames = Directory.GetFiles(fbd.DirectoryPath, "*", SearchOption.AllDirectories);
RunBackground(() =>
{
Dispatcher.Invoke(() => { CurrentBackground.Message.Text = "Checking files . . ."; });
foreach (var f in fileNames)
{
var path = f.Remove(0, fbd.DirectoryPath.Length + 1).Replace("\\", "/");
if (!ic.Paths.Contains(path))
{
MessageBox.Show("The index didn't define the file:" + Environment.NewLine + path, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
}
if (bundleToSave == null)
bundleToSave = ic.GetSmallestBundle(loadedBundles);
string str = "Imported {0}/" + fileNames.Length.ToString() + " Files";
int count = 0;
foreach (var f in fileNames)
{
var path = f.Remove(0, fbd.DirectoryPath.Length + 1).Replace("\\", "/");
var fr = ic.FindFiles[IndexContainer.FNV1a64Hash(path)];
fr.Write(File.ReadAllBytes(f));
fr.Move(bundleToSave);
++count;
Dispatcher.Invoke(() => { CurrentBackground.Message.Text = string.Format(str, count); });
}
if (count > 0)
changed.Add(bundleToSave);
});
ButtonSave.IsEnabled = true;
MessageBox.Show("Imported " + fileNames.Length.ToString() + " files into " + bundleToSave.Name, "Done");
}
}
}
19
View Source File : AssetDanshariHandlerDemo.cs
License : MIT License
Project Creator : akof1314
License : MIT License
Project Creator : akof1314
private void OnDependenciesLoadDataMore(string resPath, List<replacedetTreeModel.replacedetInfo> resInfos, replacedetTreeModel treeModel)
{
// 去代码定义文件去查找
if (resPath != "\"replacedets/Simple UI/PNG\"")
{
return;
}
int preLen = resPath.Length - "PNG".Length - 2;
string codePath = "replacedets/Demo/UISpriteDefine.cs";
try
{
string text = File.ReadAllText(codePath);
foreach (var replacedetInfo in resInfos)
{
string searchText = replacedetInfo.fileRelativePath.Substring(preLen);
searchText = searchText.Remove(searchText.Length - 4);
if (text.Contains(searchText))
{
replacedetTreeModel.replacedetInfo info = treeModel.GenreplacedetInfo(codePath);
info.isExtra = true;
replacedetInfo.AddChild(info);
}
}
}
catch (Exception ex)
{
Debug.LogError(ex.Message);
}
}
19
View Source File : MainWindow.xaml.cs
License : GNU Affero General Public License v3.0
Project Creator : akshinmustafayev
License : GNU Affero General Public License v3.0
Project Creator : akshinmustafayev
public string ConvertArgumentsToCMD(List<Answer> Answers)
{
string powerShellArguments = "";
foreach (Answer answer in Answers)
{
powerShellArguments = powerShellArguments + answer.AnswerResult + " ";
}
if (powerShellArguments.EndsWith(" "))
{
powerShellArguments = powerShellArguments.Remove(powerShellArguments.Length - 1);
}
return powerShellArguments;
}
19
View Source File : MainWindow.xaml.cs
License : GNU Affero General Public License v3.0
Project Creator : akshinmustafayev
License : GNU Affero General Public License v3.0
Project Creator : akshinmustafayev
public string ConvertArgumentsToPowerShell(List<Answer> Answers)
{
string powerShellArguments = "";
foreach (Answer answer in Answers)
{
powerShellArguments = powerShellArguments + answer.AnswerResult + " ";
}
if (powerShellArguments.EndsWith(" "))
{
powerShellArguments = powerShellArguments.Remove(powerShellArguments.Length - 1);
}
return powerShellArguments;
}
19
View Source File : MagicPathParser.cs
License : GNU General Public License v3.0
Project Creator : AlanMorel
License : GNU General Public License v3.0
Project Creator : AlanMorel
public static CoordF ParseCoordWithoutLastChar(string input)
{
if (input.EndsWith(','))
{
return ParseCoordFromString(input.Remove(input.Length - 1));
}
return ParseCoordFromString(input);
}
19
View Source File : ChineseIdCardNumberAttribute.cs
License : MIT License
Project Creator : albyho
License : MIT License
Project Creator : albyho
private static bool CheckIDCard18(string id)
{
if (!long.TryParse(id.Remove(17), out var n) || n < Math.Pow(10, 16) || !long.TryParse(id.Replace('x', '0').Replace('X', '0'), out _))
{
return false;//数字验证
}
if (AddressCode.IndexOf(id.Remove(2)) == -1)
{
return false;//省份验证
}
var birth = id.Substring(6, 8).Insert(6, "-").Insert(4, "-");
if (!DateTime.TryParse(birth, out _))
{
return false;//生日验证
}
var varifyCodes = ("1,0,x,9,8,7,6,5,4,3,2").Split(',');
var wi = ("7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2").Split(',');
var ai = id.Remove(17).ToCharArray();
var sum = 0;
for (var i = 0; i < 17; i++)
{
sum += int.Parse(wi[i]) * int.Parse(ai[i].ToString());
}
Math.DivRem(sum, 11, out int y);
if (varifyCodes[y] != id.Substring(17, 1).ToLower())
{
return false;//校验码验证
}
return true;//符合GB11643-1999标准
}
19
View Source File : ChineseIdCardNumberAttribute.cs
License : MIT License
Project Creator : albyho
License : MIT License
Project Creator : albyho
private static bool CheckIDCard15(string id)
{
if (!long.TryParse(id, out var n) || n < Math.Pow(10, 14))
{
return false;//数字验证
}
if (AddressCode.IndexOf(id.Remove(2)) == -1)
{
return false;//省份验证
}
var birth = id.Substring(6, 6).Insert(4, "-").Insert(2, "-");
if (!DateTime.TryParse(birth, out var _))
{
return false;//生日验证
}
return true;//符合15位身份证标准
}
19
View Source File : Extension.cs
License : MIT License
Project Creator : AlenToma
License : MIT License
Project Creator : AlenToma
public static string TrimEnd(this string source, string value)
{
return !source.EndsWith(value) ? source : source.Remove(source.LastIndexOf(value, StringComparison.Ordinal));
}
19
View Source File : Querys.cs
License : MIT License
Project Creator : AlenToma
License : MIT License
Project Creator : AlenToma
public QueryConditions Column<T, P>(Expression<Func<T, P>> action)
{
var member = action.Body is UnaryExpression ? ((MemberExpression)((UnaryExpression)action.Body).Operand) : (action.Body is MethodCallExpression ? ((MemberExpression)((MethodCallExpression)action.Body).Object) : (MemberExpression)action.Body);
if (member == null) return new QueryConditions(_sql, DataBaseTypes);
var key = member.Member.Name;
var type = typeof(P);
if (Nullable.GetUnderlyingType(type) != null)
type = Nullable.GetUnderlyingType(type);
var col = key;
if (col.ToLower().Contains(" as "))
col = col.Remove(col.ToLower().IndexOf(" as ", StringComparison.Ordinal));
if (type == typeof(decimal) || type == typeof(double) || type == typeof(float))
_sql += DataBaseTypes == DataBaseTypes.Mssql ? " " + "CONVERT(decimal(18,5),[" + col + "]) " : " Cast(" + DataBaseTypes.GetValidSqlName(col) + " AS decimal(18,5)) ";
else if (type == typeof(int) || type == typeof(long))
_sql += DataBaseTypes == DataBaseTypes.Mssql ? " " + "CONVERT(decimal(18,5),[" + col + "]) " : " Cast(" + DataBaseTypes.GetValidSqlName(col) + " AS bigint) ";
else if (type == typeof(Guid))
_sql += DataBaseTypes.GetValidSqlName(col);
else
_sql += DataBaseTypes == DataBaseTypes.Mssql ? " " + "CONVERT(nvarchar(max),[" + col + "]) " : (DataBaseTypes == DataBaseTypes.Sqllight ? " Cast(" + DataBaseTypes.GetValidSqlName(col) + " AS nvarchar(4000)) " : " Cast(" + DataBaseTypes.GetValidSqlName(col) + " AS varchar(4000)) ");
return new QueryConditions(_sql, DataBaseTypes);
}
19
View Source File : Querys.cs
License : MIT License
Project Creator : AlenToma
License : MIT License
Project Creator : AlenToma
public QueryConditions Column<T>(string columnName)
{
var col = columnName;
if (col.ToLower().Contains(" as "))
col = col.Remove(col.ToLower().IndexOf(" as ", StringComparison.Ordinal));
var type = typeof(T);
if (Nullable.GetUnderlyingType(type) != null)
type = Nullable.GetUnderlyingType(type);
if (type == typeof(decimal) || type == typeof(double) || type == typeof(float))
_sql += DataBaseTypes == DataBaseTypes.Mssql ? " " + "CONVERT(decimal(18,5),[" + col + "]) " : " Cast(" + DataBaseTypes.GetValidSqlName(col) + " AS decimal(18,5)) ";
else if (type == typeof(int) || type == typeof(long))
_sql += DataBaseTypes == DataBaseTypes.Mssql ? " " + "CONVERT(decimal(18,5),[" + col + "]) " : " Cast(" + DataBaseTypes.GetValidSqlName(col) + " AS bigint) ";
else if (type == typeof(Guid))
_sql += DataBaseTypes.GetValidSqlName(col);
else
_sql += DataBaseTypes == DataBaseTypes.Mssql ? " " + "CONVERT(nvarchar(max),[" + col + "]) " : (DataBaseTypes == DataBaseTypes.Sqllight ? " Cast(" + DataBaseTypes.GetValidSqlName(col) + " AS nvarchar(4000)) " : " Cast(" + DataBaseTypes.GetValidSqlName(col) + " AS varchar(4000)) ");
return new QueryConditions(_sql, DataBaseTypes);
}
19
View Source File : PostSubdirectoryHelper.cs
License : MIT License
Project Creator : AlexCSDev
License : MIT License
Project Creator : AlexCSDev
public static string CreateNameFromPattern(PatreonCrawledUrl crawledUrl, string pattern)
{
string postreplacedle = crawledUrl.replacedle?.Trim() ?? "No replacedle";
while (postreplacedle.Length > 1 && postreplacedle[^1] == '.')
postreplacedle = postreplacedle.Remove(postreplacedle.Length - 1).Trim();
string retString = pattern.ToLowerInvariant()
.Replace("%publishedat%", crawledUrl.PublishedAt.ToString("yyyy-MM-dd"))
.Replace("%postreplacedle%", postreplacedle)
.Replace("%postid%", crawledUrl.PostId);
return PathSanitizer.SanitizePath(retString);
}
19
View Source File : HttpServer.cs
License : MIT License
Project Creator : AlexGyver
License : MIT License
Project Creator : AlexGyver
private string GenerateJSON(Node n) {
string JSON = "{\"id\": " + nodeCount + ", \"Text\": \"" + n.Text
+ "\", \"Children\": [";
nodeCount++;
foreach (Node child in n.Nodes)
JSON += GenerateJSON(child) + ", ";
if (JSON.EndsWith(", "))
JSON = JSON.Remove(JSON.LastIndexOf(","));
JSON += "]";
if (n is SensorNode) {
JSON += ", \"Min\": \"" + ((SensorNode)n).Min + "\"";
JSON += ", \"Value\": \"" + ((SensorNode)n).Value + "\"";
JSON += ", \"Max\": \"" + ((SensorNode)n).Max + "\"";
JSON += ", \"ImageURL\": \"images/transparent.png\"";
} else if (n is HardwareNode) {
JSON += ", \"Min\": \"\"";
JSON += ", \"Value\": \"\"";
JSON += ", \"Max\": \"\"";
JSON += ", \"ImageURL\": \"images_icon/" +
GetHardwareImageFile((HardwareNode)n) + "\"";
} else if (n is TypeNode) {
JSON += ", \"Min\": \"\"";
JSON += ", \"Value\": \"\"";
JSON += ", \"Max\": \"\"";
JSON += ", \"ImageURL\": \"images_icon/" +
GetTypeImageFile((TypeNode)n) + "\"";
} else {
JSON += ", \"Min\": \"\"";
JSON += ", \"Value\": \"\"";
JSON += ", \"Max\": \"\"";
JSON += ", \"ImageURL\": \"images_icon/computer.png\"";
}
JSON += "}";
return JSON;
}
19
View Source File : StringHelper.cs
License : MIT License
Project Creator : AlexGyver
License : MIT License
Project Creator : AlexGyver
public static string CreateValidFileName(string replacedle, string extension)
{
string validFileName = replacedle.Trim();
var invalidFileNameChars = "/?<>\\:*|\0\t\r\n".ToCharArray();
foreach (char invalChar in invalidFileNameChars)
{
validFileName = validFileName.Replace(invalChar.ToString(), string.Empty);
}
foreach (char invalChar in invalidFileNameChars)
{
validFileName = validFileName.Replace(invalChar.ToString(), string.Empty);
}
if (validFileName.Length > 160)
{
// safe value threshold is 260
validFileName = validFileName.Remove(156) + "...";
}
return validFileName + extension;
}
19
View Source File : IOUtils.cs
License : MIT License
Project Creator : alexismorin
License : MIT License
Project Creator : alexismorin
public static void GetShaderName( out string shaderName, out string fullPathname, string defaultName, string customDatapath )
{
string currDatapath = String.IsNullOrEmpty( customDatapath ) ? Application.dataPath : customDatapath;
fullPathname = EditorUtility.SaveFilePanelInProject( "Select Shader to save", defaultName, "shader", SaveShaderStr, currDatapath );
if ( !String.IsNullOrEmpty( fullPathname ) )
{
shaderName = fullPathname.Remove( fullPathname.Length - 7 ); // -7 remove .shader extension
string[] subStr = shaderName.Split( '/' );
if ( subStr.Length > 0 )
{
shaderName = subStr[ subStr.Length - 1 ]; // Remove pathname
}
}
else
{
shaderName = string.Empty;
}
}
19
View Source File : Extensions.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
public static int DecimalsCount(this string value)
{
value = value.Replace(",", ".");
while (value.Length > 0 &&
value.EndsWith("0"))
{
value = value.Remove(value.Length - 1);
}
if (value.Split('.').Length == 1)
{
return 0;
}
return value.Split('.')[1].Length;
}
19
View Source File : BybitRestRequestBuilder.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
public static JToken CreatePrivatePostQuery(Client client, string end_point, Dictionary<string, string> parameters)
{
parameters.Add("timestamp", (Utils.GetMillisecondsFromEpochStart()).ToString());
Dictionary<string, string> sorted_params = parameters.OrderBy(pair => pair.Key).ToDictionary(pair => pair.Key, pair => pair.Value);
StringBuilder sb = new StringBuilder();
foreach (var param in sorted_params)
{
if (param.Value == "false" || param.Value == "true")
sb.Append("\"" + param.Key + "\":" + param.Value + ",");
else
sb.Append("\"" + param.Key + "\":\"" + param.Value + "\",");
}
StringBuilder sb_signer = new StringBuilder();
foreach (var param in sorted_params)
{
sb_signer.Append(param.Key + $"=" + param.Value + $"&");
}
string str_signer = sb_signer.ToString();
str_signer = str_signer.Remove(str_signer.Length - 1);
sb.Append("\"sign\":\"" + BybitSigner.CreateSignature(client, str_signer) + "\""); // api_key=bLP2z8x0sEeFHgt14S&close_on_trigger=False&order_link_id=&order_type=Limit&price=11018.00&qty=1&side=Buy&symbol=BTCUSD&time_in_force=GoodTillCancel×tamp=1600513511844
// api_key=bLP2z8x0sEeFHgt14S&close_on_trigger=False&order_link_id=&order_type=Limit&price=10999.50&qty=1&side=Buy&symbol=BTCUSD&time_in_force=GoodTillCancel×tamp=1600514673126
// {"api_key":"bLP2z8x0sEeFHgt14S","close_on_trigger":"False","order_link_id":"","order_type":"Limit","price":"11050.50","qty":"1","side":"Buy","symbol":"BTCUSD","time_in_force":"GoodTillCancel","timestamp":"1600515164173","sign":"fb3c69fa5d30526810a4b60fe4b8f216a3baf2c81745289ff7ddc21ab8232ccc"}
string url = client.RestUrl + end_point;
string str_data = "{" + sb.ToString() + "}";
byte[] data = Encoding.UTF8.GetBytes(str_data);
Uri uri = new Uri(url);
var http_web_request = (HttpWebRequest)WebRequest.Create(uri);
http_web_request.Method = "POST";
http_web_request.ContentType = "application/json";
http_web_request.ContentLength = data.Length;
using (Stream req_tream = http_web_request.GetRequestStream())
{
req_tream.Write(data, 0, data.Length);
}
HttpWebResponse httpWebResponse = (HttpWebResponse)http_web_request.GetResponse();
string response_msg;
using (var stream = httpWebResponse.GetResponseStream())
{
using (StreamReader reader = new StreamReader(stream))
{
response_msg = reader.ReadToEnd();
}
}
httpWebResponse.Close();
return JToken.Parse(response_msg);
}
19
View Source File : ConnectorCandlesUi.xaml.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
private void ComboBoxSecuritiesOnKeyDown(object sender, KeyEventArgs e)
{
List<IServer> serversAll = ServerMaster.GetServers();
IServer server = serversAll.Find(server1 => server1.ServerType == _selectedType);
if (server == null)
{
return;
}
if (e.Key == Key.LeftCtrl || e.Key == Key.RightCtrl ||
e.Key == Key.LeftAlt || e.Key == Key.RightAlt ||
e.Key == Key.LeftShift || e.Key == Key.RightShift ||
e.Key == Key.Enter)
{
return;
}
string curText = ComboBoxSecurities.Text;
ComboBoxSecurities.Items.Clear();
// upload instruments matching the search terms
// грузим инструменты подходящие под условия поиска
List<Security> needSecurities = null;
string findStr = "";
if (curText != null)
{
findStr = curText;
}
if (e.Key == Key.Back)
{
if (findStr.Length != 0)
findStr = findStr.Remove(findStr.Length - 1);
}
else
{
findStr += e.Key;
}
ComboBoxSecurities.Text = findStr;
ComboBoxSecurities.Items.Add(findStr);
ComboBoxSecurities.SelectedItem = findStr;
needSecurities = server.Securities.FindAll(
sec => sec.Name.StartsWith(ComboBoxSecurities.Text, StringComparison.CurrentCultureIgnoreCase));
for (int i = 0;
needSecurities != null &&
i < needSecurities.Count;
i++)
{
string clreplacedSec = needSecurities[i].NameClreplaced;
if (ComboBoxClreplaced.SelectedItem != null && clreplacedSec == ComboBoxClreplaced.SelectedItem.ToString())
{
ComboBoxSecurities.Items.Add(needSecurities[i].Name);
//ComboBoxSecurities.SelectedItem = needSecurities[i];
}
}
}
19
View Source File : BitfinexClient.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
private string[] ParseData(string msg)
{
var iterFirst = msg.Substring(9);
int index = iterFirst.Length - 2;
var iterSecond = iterFirst.Remove(index).Replace("\"", "");
string[] values = iterSecond.Split(',');
return values;
}
19
View Source File : BitMaxProServer.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
public void SendOrder(Order order)
{
var guid = Guid.NewGuid().ToString().Replace('-', '0');
string needId = guid;
while (needId.Length > 32)
{
needId = needId.Remove(needId.Length - 1);
}
var result = _client.SendOrder(order, needId);
if (result == null || result.Code != 0)
{
order.State = OrderStateType.Fail;
MyOrderEvent?.Invoke(order);
SendLogMessage($"Order placement error № {result?.Code}.", LogMessageType.Error);
}
else if (result.Data.Status == "Ack")
{
var newCoupler = new OrderCoupler()
{
OsOrderNumberUser = order.NumberUser,
OrderNumberMarket = result.Data.Info.OrderId,
};
_couplers.Add(newCoupler);
order.State = OrderStateType.Activ;
order.NumberMarket = result.Data.Info.OrderId;
MyOrderEvent?.Invoke(order);
}
else if (result.Data.Status == "DONE")
{
var newCoupler = new OrderCoupler()
{
OsOrderNumberUser = order.NumberUser,
OrderNumberMarket = result.Data.Info.OrderId,
};
_couplers.Add(newCoupler);
order.State = OrderStateType.Done;
order.NumberMarket = result.Data.Info.OrderId;
MyOrderEvent?.Invoke(order);
}
}
19
View Source File : BitMaxProServer.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
public void CancelOrder(Order order)
{
var guid = Guid.NewGuid().ToString().Replace('-', '0');
string needId = guid;
while (needId.Length > 32)
{
needId = needId.Remove(needId.Length - 1);
}
var needCoupler = _couplers.Find(c => c.OrderNumberMarket == order.NumberMarket);
if (needCoupler != null)
{
needCoupler.OrderCancelId = needId;
}
_client.CancelOrder(order, needId);
}
19
View Source File : LimitedMessage.cs
License : MIT License
Project Creator : alfa-laboratory
License : MIT License
Project Creator : alfa-laboratory
public static string ToLimitedMessage(this string str, int? size)
{
var _str = str;
if (size is not null)
{
_str = _str.Remove((int)size) + Constants.END_STRING;
}
return _str;
}
19
View Source File : PathExpansionPack.cs
License : MIT License
Project Creator : AlFasGD
License : MIT License
Project Creator : AlFasGD
public static PathItemType DeterminePathItemType(string path)
{
if (EndsWithVolumeSeparator(path) || EndsWithVolumeSeparator(path.Remove(path.Length - 1)))
return PathItemType.Volume;
if (EndsWithDirectorySeparator(path) || IsNullOrWhiteSpace(GetExtension(path)))
return PathItemType.Directory;
return PathItemType.File;
}
See More Examples