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
19
Source : XIVAPIController.cs
with BSD 3-Clause "New" or "Revised" License
from anoyetta
with BSD 3-Clause "New" or "Revised" License
from anoyetta
public async Task DownloadActionIcons(
string saveDirectory,
IEnumerable<ActionModel> actions,
ProgressDownloadCallbak callback = null)
{
// ファイル名に使えない文字を取得しておく
var invalidChars = Path.GetInvalidFileNameChars();
var iconBaseDirectory = Path.Combine(
saveDirectory,
"Action icons");
var iconBaseDirectoryBack = iconBaseDirectory + ".back";
if (Directory.Exists(iconBaseDirectory))
{
if (Directory.Exists(iconBaseDirectoryBack))
{
Directory.Delete(iconBaseDirectoryBack, true);
}
Directory.Move(iconBaseDirectory, iconBaseDirectoryBack);
}
var i = 1;
var jobIDs = Jobs.PopularJobIDs
.Select(x => new
{
No = i++,
ID = x,
Name = Jobs.Find(x)?.NameEN
});
using (var wc = new WebClient())
{
foreach (var jobID in jobIDs)
{
var actionsByJob =
from x in actions
where
x.ContainsJob(jobID.ID)
group x by
x.Name;
var dirName = $"{jobID.No:00}_{jobID.Name}";
var dir = Path.Combine(iconBaseDirectory, dirName);
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
var current = 1;
foreach (var group in actionsByJob)
{
var action = group.First();
var fileName = $"{(action.ID ?? 0):0000}_{action.Name}.png";
// ファイル名に使えない文字を除去する
fileName = string.Concat(fileName.Where(c =>
!invalidChars.Contains(c)));
var file = Path.Combine(dir, fileName);
if (File.Exists(file))
{
File.Delete(file);
}
var uri = BaseAddress.ToString() + "/" + action.Icon;
await wc.DownloadFileTaskAsync(uri, file);
if (callback != null)
{
callback.Invoke(new DownloadProgressEventArgs()
{
Current = current,
Max = actionsByJob.Count(),
CurrentObject = Path.Combine(dirName, fileName),
});
}
current++;
await Task.Delay(1);
}
}
}
if (Directory.Exists(iconBaseDirectoryBack))
{
Directory.Delete(iconBaseDirectoryBack, true);
}
}
19
Source : ActionEchoesModel.cs
with MIT License
from anoyetta-academy
with MIT License
from anoyetta-academy
public async Task SaveLogAsync()
{
if (this.echoes.Count < 1)
{
return;
}
var fileName = string.Empty;
lock (this)
{
var encounter = ActGlobals.oFormActMain?.ActiveZone?.ActiveEncounter;
var zone = !string.IsNullOrEmpty(encounter?.ZoneName) ?
encounter?.ZoneName :
this.Zone;
var replacedle = !string.IsNullOrEmpty(encounter?.replacedle) ?
encounter?.replacedle :
"UNKNOWN";
fileName =
$"{DateTime.Now:yyMMdd_HHmmss}_{this.PlayerName}[{this.PlayerJob}]_{zone}({replacedle}).json";
// 無効な文字を取り除く
fileName = string.Concat(fileName.Where(c => !Path.GetInvalidFileNameChars().Contains(c)));
}
if (string.IsNullOrEmpty(this.Config.LogDirectory))
{
return;
}
await Task.Run(async () =>
{
if (!Directory.Exists(this.Config.LogDirectory))
{
Directory.CreateDirectory(this.Config.LogDirectory);
}
var f = Path.Combine(this.Config.LogDirectory, fileName);
try
{
this.toFile = true;
File.WriteAllText(
f,
await this.ParseJsonAsync(),
new UTF8Encoding(false));
}
finally
{
this.toFile = false;
}
});
}
19
Source : ExpressionBuilder.cs
with MIT License
from ansel86castro
with MIT License
from ansel86castro
public IQueryable<T> OrderBy(IQueryable<T> query, string expression)
{
var method = typeof(Queryable).GetMember("OrderBy")[0] as MethodInfo;
var methodDesc = typeof(Queryable).GetMember("OrderByDescending")[0] as MethodInfo;
var thenBy = typeof(Queryable).GetMember("ThenBy")[0] as MethodInfo;
var thenByDesc = typeof(Queryable).GetMember("ThenByDescending")[0] as MethodInfo;
Expression current = Parameter;
while (current != null && !(current is ParameterExpression))
{
current = ((MemberExpression)current).Expression;
}
var parts = expression.Split(',');
IQueryable<T> ordered = query;
var index = 0;
QueryParser parser = new QueryParser();
foreach (var part in parts)
{
var value = part.Trim();
string property;
bool descend = false;
if (value.Contains(' '))
{
var split = value.Split(' ');
descend = split[1].Trim().ToLowerInvariant() == "desc";
property = split[0].Trim();
}
else
{
property = value;
}
var astExp = parser.Parse(property);
astExp.CheckSemantic(this);
Expression exp = astExp.GenerateLinqExpression(this);
MethodInfo orderByMethod;
if (index == 0)
{
orderByMethod = descend ? methodDesc : method;
}
else
{
orderByMethod = descend ? thenByDesc : thenBy;
}
index++;
var lambda = Expression.Lambda(exp, (ParameterExpression)current);
ordered = ordered.Provider.CreateQuery<T>(Expression.Call(null, orderByMethod.MakeGenericMethod(new Type[] { typeof(T), exp.Type }), new Expression[] { ordered.Expression, Expression.Quote(lambda) }));
}
return ordered;
}
19
Source : MathConverter.cs
with MIT License
from antfu
with MIT License
from antfu
private string GetNextToken(string mathEquation)
{
// If we're at the end of the equation, return string.empty
if (mathEquation == string.Empty)
{
return string.Empty;
}
// Get next operator or numeric value in equation and return it
string tmp = "";
foreach (char c in mathEquation)
{
if (_allOperators.Contains(c))
{
return (tmp == "" ? c.ToString() : tmp);
}
else
{
tmp += c;
}
}
return tmp;
}
19
Source : SettingsUtils.cs
with MIT License
from Aragas
with MIT License
from Aragas
public static SettingsPropertyGroupDefinition GetGroupForRecursive(char subGroupDelimiter, string groupName, SettingsPropertyGroupDefinition sgp, ISettingsPropertyDefinition sp)
{
while (true)
{
if (groupName.Contains(subGroupDelimiter))
{
// Need to go deeper
var topGroupName = GetTopGroupName(subGroupDelimiter, groupName, out var truncatedGroupName);
var topGroup = sgp.GetGroupFor(topGroupName);
if (topGroup is null)
{
// Order will not be preplaceded to the subgroup
topGroup = new SettingsPropertyGroupDefinition(sp.GroupName, topGroupName);
sgp.Add(topGroup);
}
groupName = truncatedGroupName;
sgp = topGroup;
}
else
{
// Reached the bottom level, can return the final group.
var group = sgp.GetGroup(groupName);
if (group is null)
{
group = new SettingsPropertyGroupDefinition(sp.GroupName, groupName, sp.GroupOrder);
sgp.Add(group);
}
return group;
}
}
}
19
Source : HangmanGame.cs
with MIT License
from ardalis
with MIT License
from ardalis
public void Guess(char guessChar)
{
// TODO: Consider using Ardalis.GuardClauses
// TODO: Consider returning Ardalis.Result
if (char.IsWhiteSpace(guessChar)) throw new InvalidGuessException("Guess cannot be blank.");
if (!Regex.IsMatch(guessChar.ToString(), "^[A-Z]$")) throw new InvalidGuessException("Guess must be a capital letter A through Z");
if (IsOver) throw new InvalidGuessException("Can't make guesses after game is over.");
if (PreviousGuesses.Any(g => g == guessChar)) throw new DuplicateGuessException();
PreviousGuesses.Add(guessChar);
if (_secretWord.IndexOf(guessChar) >= 0)
{
if (!CurrentMaskedWord.Contains(_maskChar))
{
Result = GameResult.Won;
}
return;
}
if(GuessesRemaining <= 0)
{
Result = GameResult.Lost;
}
}
19
Source : FakeFileSystem.cs
with GNU General Public License v3.0
from asimmon
with GNU General Public License v3.0
from asimmon
private bool TryGetFile(string path, out FakeFileInfo file)
{
file = null;
if (path == null)
{
return false;
}
if (!path.Contains('.'))
{
return false;
}
path = path.Replace(ForwardSlash, BackSlash).TrimEnd(BackSlash);
return this._fileInfos.TryGetValue(path, out file);
}
19
Source : DiscordHelpers.cs
with GNU Affero General Public License v3.0
from asmejkal
with GNU Affero General Public License v3.0
from asmejkal
public static string EscapeMarkdown(this string text)
{
var result = new StringBuilder(text);
foreach (var c in text)
{
if (MarkdownCharacters.Contains(c))
result.Append('\\');
result.Append(c);
}
return MarkdownQuoteRegex.Replace(result.ToString(), @"\> ");
}
19
Source : StringFormattingExtensions.cs
with GNU Affero General Public License v3.0
from asmejkal
with GNU Affero General Public License v3.0
from asmejkal
public static string Trim(this string value, IEnumerable<char> trimChars, int occurences)
{
int begin, end;
for (begin = 0; begin < occurences; ++begin)
{
if (begin >= value.Length || !trimChars.Contains(value[begin]))
break;
}
for (end = value.Length - 1; end >= value.Length - occurences; --end)
{
if (end < begin || !trimChars.Contains(value[end]))
break;
}
return (begin == 0 && end == value.Length - 1) ? value : value.Substring(begin, end - begin + 1);
}
19
Source : StringParsingExtensions.cs
with GNU Affero General Public License v3.0
from asmejkal
with GNU Affero General Public License v3.0
from asmejkal
public static IEnumerable<Token> Tokenize(this string value, params char[] textQualifiers)
{
if (string.IsNullOrEmpty(value))
yield break;
char prevChar = '\0', nextChar = '\0', currentChar = '\0';
bool inString = false;
StringBuilder token = new StringBuilder();
int begin = -1;
for (int i = 0; i < value.Length; i++)
{
currentChar = value[i];
prevChar = i > 0 ? prevChar = value[i - 1] : '\0';
nextChar = i + 1 < value.Length ? value[i + 1] : '\0';
if (textQualifiers.Contains(currentChar) && (prevChar == '\0' || char.IsWhiteSpace(prevChar)) && !inString)
{
inString = true;
if (begin < 0)
begin = i;
continue;
}
if (textQualifiers.Contains(currentChar) && (nextChar == '\0' || char.IsWhiteSpace(nextChar)) && inString && prevChar != '\\')
{
inString = false;
continue;
}
if (char.IsWhiteSpace(currentChar) && !inString)
{
if (token.Length > 0)
{
yield return new Token { Begin = begin, End = i, Value = token.ToString() };
token = token.Remove(0, token.Length);
}
begin = -1;
continue;
}
if (begin < 0)
begin = i;
token = token.Append(currentChar);
}
if (token.Length > 0)
yield return new Token { Begin = begin, End = value.Length, Value = token.ToString() };
}
19
Source : OwinHelpers.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
private static string QuoteIfNeeded(string value)
{
if (string.IsNullOrWhiteSpace(value))
{
// Ignore
}
else if (value.Contains(','))
{
if (value[0] != '"' || value[value.Length - 1] != '"')
{
value = '"' + value + '"';
}
}
return value;
}
19
Source : DefaultLoader.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
private Action<IAppBuilder> LoadImplementation(string startupName, IList<string> errorDetails)
{
Tuple<Type, string> typeAndMethod = null;
startupName = startupName ?? string.Empty;
// Auto-discovery or Friendly name?
if (!startupName.Contains(','))
{
typeAndMethod = GetDefaultConfiguration(startupName, errorDetails);
}
if (typeAndMethod == null && !string.IsNullOrWhiteSpace(startupName))
{
typeAndMethod = GetTypeAndMethodNameForConfigurationString(startupName, errorDetails);
}
if (typeAndMethod == null)
{
return null;
}
Type type = typeAndMethod.Item1;
// default to the "Configuration" method if only the type name was provided
string methodName = !string.IsNullOrWhiteSpace(typeAndMethod.Item2) ? typeAndMethod.Item2 : Constants.Configuration;
Action<IAppBuilder> startup = MakeDelegate(type, methodName, errorDetails);
if (startup == null)
{
return null;
}
return builder =>
{
if (builder == null)
{
throw new ArgumentNullException("builder");
}
object value;
if (!builder.Properties.TryGetValue(Constants.HostAppName, out value) ||
String.IsNullOrWhiteSpace(Convert.ToString(value, CultureInfo.InvariantCulture)))
{
builder.Properties[Constants.HostAppName] = type.FullName;
}
startup(builder);
};
}
19
Source : AzureAppConfigurationBuilder.cs
with MIT License
from aspnet
with MIT License
from aspnet
protected override void LazyInitialize(string name, NameValueCollection config)
{
// Default 'Optional' to false. base.LazyInitialize() will override if specified in config.
Optional = false;
base.LazyInitialize(name, config);
// keyFilter
_keyFilter = UpdateConfigSettingWithAppSettings(keyFilterTag);
if (String.IsNullOrWhiteSpace(_keyFilter))
_keyFilter = null;
// labelFilter
// Place some restrictions on label filter, similar to the .net core provider.
// The idea is to restrict queries to one label, and one label only. Even if that
// one label is the "empty" label. Doing so will remove the decision making process
// from this builders hands about which key/value/label tuple to choose when there
// are multiple.
_labelFilter = UpdateConfigSettingWithAppSettings(labelFilterTag);
if (String.IsNullOrWhiteSpace(_labelFilter)) {
_labelFilter = null;
}
else if (_labelFilter.Contains('*') || _labelFilter.Contains(',')) {
throw new ArgumentException("The characters '*' and ',' are not supported in label filters.", labelFilterTag);
}
// acceptDateTime
_dateTimeFilter = DateTimeOffset.TryParse(UpdateConfigSettingWithAppSettings(dateTimeFilterTag), out _dateTimeFilter) ? _dateTimeFilter : DateTimeOffset.MinValue;
// Azure Key Vault Integration
_useKeyVault = (UpdateConfigSettingWithAppSettings(useKeyVaultTag) != null) ? Boolean.Parse(config[useKeyVaultTag]) : _useKeyVault;
if (_useKeyVault)
_kvClientCache = new ConcurrentDictionary<Uri, SecretClient>(EqualityComparer<Uri>.Default);
// Always allow 'connectionString' to override black magic. But we expect this to be null most of the time.
_connectionString = UpdateConfigSettingWithAppSettings(connectionStringTag);
if (String.IsNullOrWhiteSpace(_connectionString))
{
_connectionString = null;
// Use Endpoint instead
string uri = UpdateConfigSettingWithAppSettings(endpointTag);
if (!String.IsNullOrWhiteSpace(uri))
{
try
{
_endpoint = new Uri(uri);
_client = new ConfigurationClient(_endpoint, new DefaultAzureCredential());
}
catch (Exception ex)
{
if (!Optional)
throw new ArgumentException($"Exception encountered while creating connection to Azure App Configuration store.", ex);
}
}
else
{
throw new ArgumentException($"An endpoint URI or connection string must be provided for connecting to Azure App Configuration service via the '{endpointTag}' or '{connectionStringTag}' attribute.");
}
}
else
{
// If we get here, then we should try to connect with a connection string.
try
{
_client = new ConfigurationClient(_connectionString);
}
catch (Exception ex)
{
if (!Optional)
throw new ArgumentException($"Exception encountered while creating connection to Azure App Configuration store.", ex);
}
}
// At this point we've got all our ducks in a row and are ready to go. And we know that
// we will be used, because this is the 'lazy' initializer. But let's handle one oddball case
// before we go.
// If we have a keyFilter set, then we will always query a set of values instead of a single
// value, regardless of whether we are in strict/expand/greedy mode. But if we're not in
// greedy mode, then the base KeyValueConfigBuilder will still request each key/value it is
// interested in one at a time, and only cache that one result. So we will end up querying the
// same set of values from the AppConfig service for every value. Let's only do this once and
// cache the entire set to make those calls to GetValueInternal read from the cache instead of
// hitting the service every time.
if (_keyFilter != null && Mode != KeyValueMode.Greedy)
EnsureGreedyInitialized();
}
19
Source : AzureAppConfigurationBuilder.cs
with MIT License
from aspnet
with MIT License
from aspnet
public override bool ValidateKey(string key)
{
// From - https://docs.microsoft.com/en-us/azure/azure-app-configuration/concept-key-value
// You can use any unicode character in key names entered into App Configuration except for *, ,, and \. These characters are
// reserved.If you need to include a reserved character, you must escape it by using \{ Reserved Character}.
if (String.IsNullOrWhiteSpace(key))
return false;
if (key.Contains('*') || key.Contains(','))
return false;
// We don't want to completely disallow '\' since it is used for escaping. But writing a full parser for someone elses
// naming format could be error prone. If we see a '\' followed by a '{', just call it good. Don't bother with the Regex
// if there aren't any backslashes though.
if (key.Contains('\\'))
return !Regex.IsMatch(key, @"\\[^{]");
return true;
}
19
Source : AppFileProvider.cs
with MIT License
from aspnetrun
with MIT License
from aspnetrun
public virtual string Combine(params string[] paths)
{
var path = Path.Combine(paths.SelectMany(p => p.Split('\\', '/')).ToArray());
if (path.Contains('/'))
path = "/" + path;
return path;
}
19
Source : SecureStringExtensions.cs
with GNU General Public License v3.0
from atomex-me
with GNU General Public License v3.0
from atomex-me
public static bool ContainsSpecials(this SecureString s)
{
return s.ContainsChar(c => SpecialsCharacters.Contains(c));
}
19
Source : TextUtils.cs
with GNU General Public License v3.0
from AtomCrafty
with GNU General Public License v3.0
from AtomCrafty
public static bool IsFullWidthCharacter(char ch) {
return ch >= 0x3000 && ch < 0x3040 // replacedanese-style punctuation
|| ch >= 0x3040 && ch < 0x30A0 // Hiragana
|| ch >= 0x30A0 && ch < 0x3100 // Katakana
|| ch >= 0xFF00 && ch < 0xFF70 // Full-width roman characters
|| ch >= 0x4E00 && ch < 0x9FB0 // CJK unified ideographs - Common and uncommon kanji
|| ch >= 0x3400 && ch < 0x4DC0 // CJK unified ideographs Extension A - Rare kanji
|| ch >= 0x2600 && ch < 0x2700 // Miscellaneous Symbols
|| "─".Contains(ch);
}
19
Source : Chart.cs
with MIT License
from audfx
with MIT License
from audfx
public static KshChart Create(string fileName, StreamReader reader)
{
var chart = new KshChart
{
FileName = fileName,
Metadata = KshChartMetadata.Create(reader)
};
chart.FxDefines["Retrigger"] = new KshEffectDef(KshEffectKind.Retrigger, null);
chart.FxDefines["Gate"] = new KshEffectDef(KshEffectKind.Gate, null);
chart.FxDefines["Flanger"] = new KshEffectDef(KshEffectKind.Flanger, null);
chart.FxDefines["PitchShift"] = new KshEffectDef(KshEffectKind.PitchShift, null);
chart.FxDefines["BitCrusher"] = new KshEffectDef(KshEffectKind.BitCrusher, null);
chart.FxDefines["Wobble"] = new KshEffectDef(KshEffectKind.Wobble, null);
chart.FxDefines["Phaser"] = new KshEffectDef(KshEffectKind.Phaser, null);
chart.FxDefines["TapeStop"] = new KshEffectDef(KshEffectKind.TapeStop, null);
chart.FxDefines["Echo"] = new KshEffectDef(KshEffectKind.Echo, null);
chart.FxDefines["SideChain"] = new KshEffectDef(KshEffectKind.SideChain, null);
chart.FilterDefines["peak"] = new KshEffectDef(KshEffectKind.Peak, null);
chart.FilterDefines["lpf1"] = new KshEffectDef(KshEffectKind.LowPreplaced, null);
chart.FilterDefines["hpf1"] = new KshEffectDef(KshEffectKind.HighPreplaced, null);
chart.FilterDefines["bitc"] = new KshEffectDef(KshEffectKind.BitCrusher, new Dictionary<string, IEffectParam>()
{
["reduction"] = new EffectParamI(4, 45, Ease.InExpo),
});
chart.FilterDefines["fx;bitc"] = chart.FilterDefines["bitc"];
var block = new KshBlock();
var tick = new KshTick();
string line, lastFx = "00";
while ((line = reader.ReadLine()) != null)
{
if (string.IsNullOrEmpty(line))
continue;
line = line.Trim();
if (line[0] == '#')
{
Dictionary<string, IEffectParam> GetParameterList(string args, out KshEffectKind effectKind)
{
var result = new Dictionary<string, IEffectParam>();
effectKind = KshEffectKind.None;
foreach (string a in args.Split(';'))
{
if (!a.TrySplit('=', out string k, out string v))
continue;
k = k.Trim();
v = v.Trim();
if (k == "type")
{
Logger.Log($"ksh fx type: { v }");
switch (v.ToLower())
{
case "retrigger": effectKind = KshEffectKind.Retrigger; break;
case "gate": effectKind = KshEffectKind.Gate; break;
case "flanger": effectKind = KshEffectKind.Flanger; break;
case "pitchshift": effectKind = KshEffectKind.PitchShift; break;
case "bitcrusher": effectKind = KshEffectKind.BitCrusher; break;
case "wobble": effectKind = KshEffectKind.Wobble; break;
case "phaser": effectKind = KshEffectKind.Phaser; break;
case "tapestop": effectKind = KshEffectKind.TapeStop; break;
case "echo": effectKind = KshEffectKind.Echo; break;
case "sidechain": effectKind = KshEffectKind.SideChain; break;
}
}
else
{
// NOTE(local): We aren't worried about on/off state for now, if ever
if (v.Contains('>')) v = v.Substring(v.IndexOf('>') + 1).Trim();
bool isRange = v.TrySplit('-', out string v0, out string v1);
// TODO(local): this will ONLY allow ranges of the same type, so 0.5-1/8 is illegal (but are these really ever used?)
// (kinda makes sense for Hz-kHz but uh shh)
IEffectParam pv;
if (v.Contains("on") || v.Contains("off"))
{
if (isRange)
pv = new EffectParamI(v0.Contains("on") ? 1 : 0,
v1.Contains("on") ? 1 : 0, Ease.Linear);
else pv = new EffectParamI(v.Contains("on") ? 1 : 0);
}
else if (v.Contains('/'))
{
if (isRange)
{
pv = new EffectParamX(
int.Parse(v0.Substring(v0.IndexOf('/') + 1)),
int.Parse(v1.Substring(v1.IndexOf('/') + 1)));
}
else pv = new EffectParamX(int.Parse(v.Substring(v.IndexOf('/') + 1)));
}
else if (v.Contains('%'))
{
if (isRange)
pv = new EffectParamF(int.Parse(v0.Substring(0, v0.IndexOf('%'))) / 100.0f,
int.Parse(v1.Substring(0, v1.IndexOf('%'))) / 100.0f, Ease.Linear);
else pv = new EffectParamF(int.Parse(v.Substring(0, v.IndexOf('%'))) / 100.0f);
}
else if (v.Contains("samples"))
{
if (isRange)
pv = new EffectParamF(int.Parse(v0.Substring(0, v0.IndexOf("samples"))),
int.Parse(v1.Substring(0, v1.IndexOf("samples"))), Ease.Linear);
else pv = new EffectParamF(int.Parse(v.Substring(0, v.IndexOf("samples"))));
}
else if (v.Contains("ms"))
{
if (isRange)
pv = new EffectParamF(int.Parse(v0.Substring(0, v0.IndexOf("ms"))) / 1000.0f,
int.Parse(v1.Substring(0, v1.IndexOf("ms"))) / 1000.0f, Ease.Linear);
else pv = new EffectParamF(int.Parse(v.Substring(0, v.IndexOf("ms"))) / 1000.0f);
}
else if (v.Contains("s"))
{
if (isRange)
pv = new EffectParamF(int.Parse(v0.Substring(0, v0.IndexOf("s"))) / 1000.0f,
int.Parse(v1.Substring(0, v1.IndexOf("s"))) / 1000.0f, Ease.Linear);
else pv = new EffectParamF(int.Parse(v.Substring(0, v.IndexOf("s"))) / 1000.0f);
}
else if (v.Contains("kHz"))
{
if (isRange)
pv = new EffectParamF(float.Parse(v0.Substring(0, v0.IndexOf("kHz"))) * 1000.0f,
float.Parse(v1.Substring(0, v1.IndexOf("kHz"))) * 1000.0f, Ease.Linear);
else pv = new EffectParamF(float.Parse(v.Substring(0, v.IndexOf("kHz"))) * 1000.0f);
}
else if (v.Contains("Hz"))
{
if (isRange)
pv = new EffectParamF(float.Parse(v0.Substring(0, v0.IndexOf("Hz"))),
float.Parse(v1.Substring(0, v1.IndexOf("Hz"))), Ease.Linear);
else pv = new EffectParamF(float.Parse(v.Substring(0, v.IndexOf("Hz"))));
}
else if (v.Contains("dB"))
{
if (isRange)
pv = new EffectParamF(float.Parse(v0.Substring(0, v0.IndexOf("dB"))),
float.Parse(v1.Substring(0, v1.IndexOf("dB"))), Ease.Linear);
else pv = new EffectParamF(float.Parse(v.Substring(0, v.IndexOf("dB"))));
}
else if (float.TryParse(isRange ? v0 : v, out float floatValue))
{
if (isRange)
pv = new EffectParamF(floatValue, float.Parse(v1), Ease.Linear);
else pv = new EffectParamF(floatValue);
}
else pv = new EffectParamS(v);
Logger.Log($" ksh fx param: { k } = { pv }");
result[k] = pv;
}
}
return result;
}
if (!line.TrySplit(' ', out string defKind, out string defKey, out string argList))
continue;
Logger.Log($">> ksh { defKind } \"{ defKey }\"");
var pars = GetParameterList(argList, out KshEffectKind effectType);
KshEffectDef def = new KshEffectDef(effectType, pars);
if (defKind == "#define_fx")
chart.FxDefines[defKey] = def;
else if (defKind == "#define_filter")
chart.FilterDefines[defKey] = def;
}
if (line == SEP)
{
chart.m_blocks.Add(block);
block = new KshBlock();
}
else if (line.StartsWith("//"))
{
tick.Comments.Add(line.Substring(2).Trim());
}
if (line.TrySplit('=', out string key, out string value))
{
// defined fx should probably be named different than the defaults,
// so it's like slightly safe to replacedume that failing to create
// a built-in definition from this for either means its a defined effect?
if (key == "fx-l" || key == "fx-r" || key == "filtertype")
{
if (string.IsNullOrWhiteSpace(value))
tick.Settings.Add(new KshTickSetting(key, Variant.Null));
else
{
string effectName = value, effectParam = null;
if (value != "fx;bitc" && value.TrySplit(';', out string name, out string param))
{
effectName = name;
effectParam = param;
}
var effectRef = new Variant(new KshEffectRef(effectName, effectParam));
tick.Settings.Add(new KshTickSetting(key, effectRef));
}
}
else tick.Settings.Add(new KshTickSetting(key, value));
}
else
{
if (!line.TrySplit('|', out string bt, out string fx, out string vol))
continue;
if (vol.Length > 2)
{
string add = vol.Substring(2);
vol = vol.Substring(0, 2);
if (add.Length >= 2)
{
string[] args = add.Substring(2).Split(';');
char c = add[0];
switch (c)
{
case '@':
{
char d = add[1];
switch (d)
{
case '(': case ')': tick.Add.Kind = KshAddKind.Spin; break;
case '<': case '>': tick.Add.Kind = KshAddKind.Swing; break;
}
switch (d)
{
case '(': case '<': tick.Add.Direction = -1; break;
case ')': case '>': tick.Add.Direction = 1; break;
}
ParseArg(0, out tick.Add.Duration);
tick.Add.Amplitude = 100;
} break;
case 'S':
{
char d = add[1];
tick.Add.Kind = KshAddKind.Wobble;
tick.Add.Direction = d == '<' ? -1 : (d == '>' ? 1 : 0);
ParseArg(0, out tick.Add.Duration);
ParseArg(1, out tick.Add.Amplitude);
ParseArg(2, out tick.Add.Frequency);
ParseArg(3, out tick.Add.Decay);
} break;
}
void ParseArg(int i, out int v)
{
if (args.Length > i) int.TryParse(args[i], out v);
else v = 0;
}
}
}
for (int i = 0; i < MathL.Min(4, bt.Length); i++)
{
char c = bt[i];
switch (c)
{
case '0': tick.Bt[i].State = KshButtonState.Off; break;
case '1': tick.Bt[i].State = KshButtonState.Chip; break;
case '2': tick.Bt[i].State = KshButtonState.Hold; break;
}
}
for (int i = 0; i < MathL.Min(2, fx.Length); i++)
{
char c = fx[i];
switch (c)
{
case '0': tick.Fx[i].State = KshButtonState.Off; break;
case '1': tick.Fx[i].State = KshButtonState.Hold; break;
case '2': tick.Fx[i].State = KshButtonState.Chip; break;
case '3': tick.Fx[i].State = KshButtonState.ChipSample; break;
default:
{
var kind = (KshOldFxHoldKind)c;
if (Enum.IsDefined(typeof(KshOldFxHoldKind), kind) && kind != KshOldFxHoldKind.None)
{
tick.Fx[i].State = KshButtonState.Hold;
if (lastFx[i] != c)
{
kind.GetEffectInfo(out string effectName, out string effectParam);
var effectRef = new Variant(new KshEffectRef(effectName, effectParam));
tick.Settings.Add(new KshTickSetting(i == 0 ? "fx-l" : "fx-r", effectRef));
}
}
} break;
}
}
lastFx = fx;
for (int i = 0; i < MathL.Min(2, vol.Length); i++)
{
char c = vol[i];
switch (c)
{
case '-': tick.Laser[i].State = KshLaserState.Inactive; break;
case ':': tick.Laser[i].State = KshLaserState.Lerp; break;
default:
{
tick.Laser[i].State = KshLaserState.Position;
tick.Laser[i].Position.Image = c;
} break;
}
}
block.Ticks.Add(tick);
tick = new KshTick();
}
}
return chart;
}
19
Source : FFMetaData.cs
with GNU General Public License v3.0
from audiamus
with GNU General Public License v3.0
from audiamus
private string escape (string s) {
if (s is null)
return null;
var chars = new List <char>();
foreach (char c in s) {
if (Escapes.Contains(c))
chars.Add ('\\');
chars.Add (c);
}
return new string (chars.ToArray());
}
19
Source : ExtensionMethods.cs
with GNU General Public License v3.0
from audiamus
with GNU General Public License v3.0
from audiamus
public static string Prune (this string s, char[] invalid) {
char[] doubtful = null;
if (s is null)
return null;
if (invalid is null) {
invalid = InvalidFileNameChars;
doubtful = DoubtfulFileNameChars;
}
StringBuilder sb = new StringBuilder ();
foreach (char c in s) {
if (invalid.Contains (c))
continue;
//sb.Append (',');
else if (doubtful?.Contains (c) ?? false)
continue;
else
sb.Append (c);
}
return sb.ToString ();
}
19
Source : LocalizationExporter.cs
with MIT License
from Auros
with MIT License
from Auros
private string EscapeCsvValue(string value)
{
if (string.IsNullOrEmpty(value)) return null;
if (!value.Contains(',') && !value.Contains('"') && !value.Contains('\n')) return value;
return "\"" + value.Replace("\"", "\"\"") + "\"";
}
19
Source : GeneratedFont.cs
with MIT License
from AvantiPoint
with MIT License
from AvantiPoint
private bool HasKey(out string key, params string[] searchNames)
{
key = null;
foreach (var name in searchNames)
{
key = _mappings.Keys.FirstOrDefault(x =>
x.Equals(name, StringComparison.InvariantCultureIgnoreCase) ||
name.Equals($"{Prefix}-{x}", StringComparison.InvariantCultureIgnoreCase) ||
x.Replace("-", string.Empty).Equals(name, StringComparison.InvariantCultureIgnoreCase));
if (!string.IsNullOrEmpty(key))
{
return true;
}
var prefixedName = $"{Prefix}-{name}";
key = _mappings.Keys.FirstOrDefault(x => x.Equals(prefixedName, StringComparison.InvariantCultureIgnoreCase));
if (!string.IsNullOrEmpty(key))
{
return true;
}
if (!name.Contains('-') && name.Where(x => char.IsUpper(x)).Count() > 1)
{
var searchKey = string.Empty;
for (int i = 0; i < name.Length; i++)
{
searchKey += i > 0 && char.IsUpper(name[i]) ? $"-{name[i]}" : $"{name[i]}";
}
return HasKey(out key, searchKey.ToLower());
}
else if (name.StartsWith($"{Alias}-"))
{
return HasKey(out key, name.Substring($"{Alias}-".Length));
}
}
return false;
}
19
Source : Get-SSMLatestEC2Image-Cmdlet.cs
with Apache License 2.0
from aws
with Apache License 2.0
from aws
protected override void ProcessRecord()
{
var parameters = new Dictionary<string, object>(MyInvocation.BoundParameters);
parameters.Remove(nameof(Path));
parameters.Remove(nameof(ImageName));
bool matchSingleImage = ImageName != null && !ImageName.Contains('*') && !ImageName.Contains('?');
#if DESKTOP
var cmdlet = matchSingleImage ? "Get-SSMParameterValue" : "Get-SSMParametersByPath";
#else
var cmdlet = matchSingleImage ? new CmdletInfo("Get-SSMParameterValue", typeof(GetSSMParameterValueCmdlet))
: new CmdletInfo("Get-SSMParametersByPath", typeof(GetSSMParametersByPathCmdlet));
#endif
var path = $"/aws/service/{Path}";
Regex regex = null;
if (matchSingleImage)
{
parameters.Add(nameof(GetSSMParameterValueCmdlet.Name), $"{path}/{ImageName}");
parameters.Add(nameof(GetSSMParameterValueCmdlet.Select), nameof(GetParametersResponse.Parameters));
}
else
{
parameters.Add(nameof(GetSSMParametersByPathCmdlet.Path), path);
parameters.Add(nameof(GetSSMParametersByPathCmdlet.Select), nameof(GetParametersByPathResponse.Parameters));
if (ImageName != null)
{
regex = new Regex($"^{path}/{Regex.Escape(ImageName). Replace("\\*", ".*").Replace("\\?", ".")}$", RegexOptions.IgnoreCase);
}
}
IEnumerable<PSObject> results = ExecuteCmdlet(cmdlet, parameters);
var output = new CmdletOutput
{
PipelineOutput = results
};
if (results != null)
{
//Best effort conversion of a Parameter to a PSObject, if the value is in json, we will try to parse it and extract the image_id field.
output.PipelineOutput = results.Select<PSObject, object>(psObject =>
{
var ssmParameter = psObject.BaseObject as Parameter;
if (ssmParameter == null || !(regex?.IsMatch(ssmParameter.Name) ?? true))
{
return null;
}
string value = ssmParameter.Value;
if (value.Contains('{'))
{
try
{
var jsonData = JsonMapper.ToObject(value);
var imageId = jsonData["image_id"];
if (imageId?.IsString ?? false)
{
value = (string)imageId;
}
}
catch
{
//If we can't parse the value as json and extract image_id, we will return the full value
}
}
if (matchSingleImage)
{
return value;
}
else
{
var result = new PSObject();
result.Properties.Add(new PSNoteProperty("Name", ssmParameter.Name.Substring(path.Length + 1)));
result.Properties.Add(new PSNoteProperty("Value", value));
return result;
}
}).Where(value => value != null).ToArray();
}
ProcessOutput(output);
}
19
Source : GLSLESProgramWriter.cs
with GNU Lesser General Public License v2.1
from axiom3d
with GNU Lesser General Public License v2.1
from axiom3d
private void CacheDependencyFunctions(string libName)
{
if (this.cachedFunctionLibraries.ContainsKey(libName))
{
return; //lib is already in cach
}
string libFileName = libName + ".glsles";
var dataStream = ResourceGroupManager.Instance.OpenResource(libFileName);
var reader = new StreamReader(dataStream, Encoding.Default);
var functionCache = new Dictionary<string, string>();
string line;
while (!reader.EndOfStream)
{
line = reader.ReadLine();
//Ignore empty lines and comments
if (line.Length > 0)
{
line = line.Trim();
if (line[0] == '/' && line[1] == '*')
{
bool endFound = false;
while (!endFound)
{
//Get the next line
line = reader.ReadLine();
//Skip empties
if (line.Length > 0)
{
//Look for the ending sequence
if (line.Contains("*/"))
{
endFound = true;
}
}
}
}
else if (line.Length > 1 && line[0] != '/' && line[1] != '/')
{
//Break up the line.
string[] tokens = line.Split(' ', '(', '\n', '\r');
//Cache #defines
if (tokens[0] == "#define")
{
this.definesMap.Add(line, libName);
continue;
}
// Try to identify a function definition
// First, look for a return type
if (IsBasicType(tokens[0]) && ((tokens.Length < 3) || tokens[2] != "="))
{
string functionSig = string.Empty;
string functionBody = string.Empty;
FunctionInvocation functionInvoc = null;
//Return type
functionSig = tokens[0];
functionSig += " ";
//Function name
functionSig += tokens[1];
functionSig += "(";
bool foundEndOfSignature = false;
//Now look for all the paraemters, the may span multiple lines
while (!foundEndOfSignature)
{
//Trim whitespace from both sides of the line
line = line.Trim();
//First we want to get everything right of the paren
string[] paramTokens;
if (line.Contains('('))
{
string[] lineTokens = line.Split(')');
paramTokens = lineTokens[1].Split(',');
}
else
{
paramTokens = line.Split(',');
}
foreach (var itParam in paramTokens)
{
functionSig += itParam;
if (!itParam.Contains(')'))
{
functionSig += ",";
}
}
if (line.Contains(')'))
{
foundEndOfSignature = true;
}
line = reader.ReadLine();
}
functionInvoc = CreateInvocationFromString(functionSig);
//Ok, now if we have founc the signature, iterate throug the file until we find the found
//of the function
bool foundEndOfBody = false;
int braceCount = 0;
while (!foundEndOfBody)
{
functionBody += line;
if (line.Contains('{'))
{
braceCount++;
}
if (line.Contains('}'))
{
braceCount--;
}
if (braceCount == 0)
{
foundEndOfBody = true;
//Remove first and last brace
int pos = -1;
for (int i = 0; i < functionBody.Length; i++)
{
if (functionBody[i] == '{')
{
pos = i;
break;
}
}
functionBody.Remove(pos, 1);
this.functionCacheMap.Add(functionInvoc, functionBody);
}
functionBody += "\n";
line = reader.ReadLine();
}
}
}
}
}
reader.Close();
}
19
Source : Parameter.cs
with GNU Lesser General Public License v2.1
from axiom3d
with GNU Lesser General Public License v2.1
from axiom3d
public override string ToString()
{
string val = value.ToString();
if (val.Contains('.') == false)
{
val += ".0";
}
return val;
}
19
Source : GLES2Support.cs
with GNU Lesser General Public License v2.1
from axiom3d
with GNU Lesser General Public License v2.1
from axiom3d
internal virtual void InitializeExtensions()
{
//Set version string
var pcVer = GL.GetString( OpenTK.Graphics.ES20.All.Version );
if ( pcVer == null || pcVer.Length == 0 )
{
pcVer = "UNKOWN";
}
string tmpStr = pcVer;
LogManager.Instance.Write( "GL_VERSION = " + tmpStr );
int spacePos = -1;
for ( int i = 0; i < tmpStr.Length; i++ )
{
if ( tmpStr[ i ] == ' ' )
{
spacePos = i;
break;
}
}
if ( spacePos != -1 )
{
this._version = tmpStr.Substring( 0, spacePos );
}
else if ( tmpStr.Contains( ' ' ) )
{
this._version = tmpStr.Remove( ' ' );
}
else
{
this._version = tmpStr;
}
//Get vendor
tmpStr = GL.GetString( OpenTK.Graphics.ES20.All.Vendor );
if ( tmpStr == null || tmpStr == string.Empty )
{
tmpStr = "UNKOWN";
}
LogManager.Instance.Write( "GL_VENDOR = " + tmpStr );
spacePos = -1;
for ( int i = 0; i < tmpStr.Length; i++ )
{
if ( tmpStr[ i ] == ' ' )
{
spacePos = i;
break;
}
}
if ( spacePos != -1 )
{
this._vendor = tmpStr.Substring( 0, spacePos );
}
else if ( tmpStr.Contains( ' ' ) )
{
this._vendor = tmpStr.Remove( ' ' );
}
else
{
this._vendor = tmpStr;
}
//Get renderer
tmpStr = GL.GetString( OpenTK.Graphics.ES20.All.Vendor );
if ( tmpStr == null || tmpStr == string.Empty )
{
tmpStr = "UNKOWN";
}
LogManager.Instance.Write( "GL_RENDERER = " + tmpStr );
//Set extension list
var pcExt = GL.GetString( OpenTK.Graphics.ES20.All.Extensions );
if ( pcExt == null )
{
pcExt = string.Empty;
}
LogManager.Instance.Write( "GL_EXTENSIONS = " + pcExt );
this.ExtensionList = pcExt;
}
19
Source : IfElseConverter.cs
with MIT License
from ay2015
with MIT License
from ay2015
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
/*
parameter:v1|v2|v3:r1:2
*/
var _1 = Formatter.ToObjectString();
if (_1 == "")
{
return "";
}
if (_1.IndexOf(',') > -1)
{
string[] arrayEndGroup = _1.Split(groupEndSplit);
string[] array1 = arrayEndGroup[0].Split(groupSplit);
string valStr = value.ToObjectString();
for (int i = 0; i < array1.Length; i++)
{
var _21 = array1[i];
string[] array = _21.Split(expressionSplit);
if (array[0].Contains(valueSplit[0]))
{
string[] valStrArray = array[0].Split(valueSplit);
if (valStrArray.Contains(valStr))
{
return array[1].Replace("{0}", value.ToObjectString());
}
}
else
{
if (valStr.Equals(array[0]))
{
return array[1].Replace("{0}", value.ToObjectString());
}
}
}
if (arrayEndGroup.Length == 2)
{
return arrayEndGroup[1].Replace("{0}", value.ToObjectString());
}
return "";
}
else
{
string[] array = _1.Split(expressionSplit);
if (value == null)
return array[1];
string valStr = value.ToString();
if (string.IsNullOrEmpty(valStr))
return array[1];
if (array[0].Contains("|"))
{
string[] valStrArray = array[0].Split(valueSplit);
return valStrArray.Contains(valStr) ? array[1].Replace("{0}", value.ToObjectString()) : array[2].Replace("{0}", value.ToObjectString());
}
else
{
return valStr.Equals(array[0]) ? array[1].Replace("{0}", value.ToObjectString()) : array[2].Replace("{0}", value.ToObjectString());
}
}
}
19
Source : MainProgram.cs
with GNU General Public License v3.0
from Az-21
with GNU General Public License v3.0
from Az-21
public static void Main(string[] args) {
// Load preferences [creates an immutable object (record)]
var prefs = Preferences.LoadConfig();
// Process input arguments
bool makeChangesPermanent = false;
bool includeFolders = false;
string libraryPath = prefs.LibraryPath;
if(args.Any()) {
if(args[0].Replace('\\', '/').Contains('/')) {
libraryPath = args[0]; // if path is provided by argument, overrule config.json path
}
Console.WriteLine($"\nLibrary path: {Print.InfoText(libraryPath)}");
// Flags
string cliFlags = string.Join(" ", args).ToLowerInvariant();
if(cliFlags.Contains("--rename")) { makeChangesPermanent = true; }
if(cliFlags.Contains("--includefolders")) { includeFolders = true; }
}
// Update runtime preferences
prefs.MakeChangesPermanent = makeChangesPermanent;
prefs.RenameFolders = includeFolders;
// Init counters (unchanged, conflict, renamed)
var counter = new Counter(0, 0, 0);
// Rename folders
if(prefs.RenameFolders) {
var folders = Scan.Folders(libraryPath, prefs);
if(folders.Any()) {
if(Print.FolderConfirmation(folders, makeChangesPermanent)) {
for(int i = folders.Length - 1; i >= 0; i--) {
// WARNING: Reversed loop order becasuse innermost folder must be renamed first
// Simplifying the outermost folder first will break address of inner folders
string fullPath = folders[i];
Rename.SimplifyFolder(prefs, fullPath, ref counter);
}
}
}
Console.WriteLine("\n\n");
}
// Rename files
var files = Scan.Files(libraryPath, prefs);
if(files.Any()) {
if(Print.FilesConfirmation(files, makeChangesPermanent)) {
foreach(var fullPath in files) {
Rename.SimplifyFile(prefs, fullPath, ref counter);
}
}
}
// Print results
Print.Results(counter.Renamed, counter.Conflict, counter.Unchanged);
}
19
Source : LatLng.cs
with MIT License
from azist
with MIT License
from azist
private double parseDeg(string val)
{
if (val.Contains('°'))
{
var ideg = val.IndexOf('°');
var deg = val.Substring(0, ideg);
val = val.Substring(ideg+1);
var imin = val.IndexOf("'");
var min = "";
if (imin>0)
{
min = val.Substring(0, imin);
val = val.Substring(imin+1);
}
var isec = val.IndexOf("''");
var sec = "";
if (imin>0)
{
sec = val.Substring(0, isec);
}
var dd = deg.AsDouble(handling: ConvertErrorHandling.Throw);
return dd < 0 ?
dd -
(min.AsDouble(handling: ConvertErrorHandling.Throw)/60d) -
(sec.AsDouble(handling: ConvertErrorHandling.Throw)/3600d)
:
dd +
(min.AsDouble(handling: ConvertErrorHandling.Throw)/60d) +
(sec.AsDouble(handling: ConvertErrorHandling.Throw)/3600d);
}
return double.Parse(val, System.Globalization.NumberStyles.Number);
}
19
Source : Utils.cs
with MIT License
from azist
with MIT License
from azist
public static string ParseFieldNameToDescription(this string fieldName, bool capitalize)
{
if (fieldName.IsNullOrWhiteSpace()) return string.Empty;
var builder = new StringBuilder();
char prev = fieldName[0];
builder.Append(prev);
var length = fieldName.Length;
for (int i = 1; i < length; i++)
{
var curr = fieldName[i];
if (
!FIELD_NAME_DELIMETERS.Contains(prev) &&
!FIELD_NAME_DELIMETERS.Contains(curr) &&
(charCaseTransition(prev, curr) || charDigitTransition(prev, curr))
)
{
builder.Append(SPACE);
}
builder.Append(curr);
prev = curr;
}
var name = builder.ToString();
var segs = name.Split(FIELD_NAME_DELIMETERS, StringSplitOptions.RemoveEmptyEntries);
var result = capitalize ?
segs.Select(s => s.Trim().ToLowerInvariant().CapitalizeFirstChar()).Aggregate((s1,s2) => s1+SPACE+s2) :
segs.Select(s => s.Trim().ToLowerInvariant()).Aggregate((s1,s2) => s1+SPACE+s2);
return result;
}
19
Source : pg_Util.cs
with MIT License
from azsumas
with MIT License
from azsumas
public static Color ColorWithString(string value)
{
string valid = "01234567890.,";
value = new string(value.Where(c => valid.Contains(c)).ToArray());
string[] rgba = value.Split(',');
// BRIGHT pink
if(rgba.Length < 4)
return new Color(1f, 0f, 1f, 1f);
return new Color(
float.Parse(rgba[0]),
float.Parse(rgba[1]),
float.Parse(rgba[2]),
float.Parse(rgba[3]));
}
19
Source : CatSystem2Unpacker.cs
with MIT License
from Azukee
with MIT License
from Azukee
private static string DeobfuscateFileName(string fileName, uint seed)
{
const string keyspace = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
var sb = new StringBuilder(fileName.Length);
uint key = MersenneTwister.GenRand(seed);
int shift = (byte) ((key >> 24) + (key >> 16) + (key >> 8) + key);
for (int i = 0; i < fileName.Length; i++, shift++) {
char c = fileName[i];
// the crypto is basically caesar cipher on reversed keyspace, with shifting index
if (keyspace.Contains(c)) {
int idx = keyspace.IndexOf(c);
int reverseIdx = keyspace.Length - idx - 1;
c = keyspace[mod(reverseIdx - shift, keyspace.Length)];
}
sb.Append(c);
// mod function, because % operator is remainder
int mod(int x, int m) => (x % m + m) % m;
}
return sb.ToString();
}
19
Source : GitExeRepository.cs
with Apache License 2.0
from Azure-App-Service
with Apache License 2.0
from Azure-App-Service
public IEnumerable<string> ListFiles(string path, SearchOption searchOption, params string[] lookupList)
{
path = PathUtilityFactory.Instance.CleanPath(path);
if (!FileSystemHelpers.IsSubfolder(RepositoryPath, path))
{
throw new NotSupportedException("Only paths relative to the repository root path are supported, path provided: '{0}' is not a child folder of '{1}'".FormatCurrentCulture(path, RepositoryPath));
}
if (Directory.Exists(path))
{
// TODO: Consider an implementation where the gitExe returns the list of files as a list (not storing the files list output as a blob)
// In-order to conserve memory consumption
string output = DecodeGitLsOutput(Execute(@"ls-files {0}", String.Join(" ", lookupList), RepositoryPath));
if (!String.IsNullOrEmpty(output))
{
IEnumerable<string> lines = output.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
lines = lines
.Select(line => Path.Combine(RepositoryPath, line.Trim().Trim('"').Replace('/', Path.DirectorySeparatorChar)))
.Where(p => p.StartsWith(path, StringComparison.OrdinalIgnoreCase));
switch (searchOption)
{
case SearchOption.TopDirectoryOnly:
lines = lines.Where(line => !line.Substring(path.Length).TrimStart(Path.DirectorySeparatorChar).Contains(Path.DirectorySeparatorChar));
break;
case SearchOption.AllDirectories:
break;
default:
throw new NotSupportedException("Search option {0} is not supported".FormatCurrentCulture(searchOption));
}
return lines;
}
}
return Enumerable.Empty<string>();
}
19
Source : GitExeRepository.cs
with Apache License 2.0
from Azure-App-Service
with Apache License 2.0
from Azure-App-Service
public static string DecodeGitLsOutput(string original)
{
string output = original;
// When characters are represented as the octal values of its utf8 encoding
// e.g. å becomes \303\245 in git.exe output
if (original.Contains('"'))
{
output = System.Text.RegularExpressions.Regex.Unescape(original);
byte[] rawBytes = Encoding.GetEncoding(1252).GetBytes(output);
output = Encoding.UTF8.GetString(rawBytes);
}
return output;
}
19
Source : DebugExtensionMiddleware.cs
with Apache License 2.0
from Azure-App-Service
with Apache License 2.0
from Azure-App-Service
public async Task Invoke (HttpContext context)
{
int tunnelPort = -1;
if (context.Request.Headers.ContainsKey("AppsvcTunnelPort"))
{
tunnelPort = int.Parse(context.Request.Headers["AppsvcTunnelPort"].First());
}
int bufferSize = 65536;
if (context.Request.Headers.ContainsKey("AppsvcTunnelBuffer"))
{
bufferSize = int.Parse(context.Request.Headers["AppsvcTunnelBuffer"].First());
}
_logger.LogInformation("Appsvc: " + tunnelPort + " " + bufferSize);
string ipAddress = null;
try
{
ipAddress = Environment.GetEnvironmentVariable("APPSVC_TUNNEL_IP");
_logger.LogInformation("HandleWebSocketConnection: Found IP Address from APPSVC_TUNNEL_IP: " + ipAddress);
}
catch (Exception)
{
}
bool continueIpCheck = true;
int debugPort = 2222;
try
{
if (ipAddress == null)
{
ipAddress = System.IO.File.ReadAllText("/appsvctmp/ipaddr_" + Environment.GetEnvironmentVariable("WEBSITE_ROLE_INSTANCE_ID"));
if(ipAddress != null && ipAddress.Contains(':'))
{
string[] ipAddrPortStr = ipAddress.Split(":");
ipAddress = ipAddrPortStr[0];
debugPort = Int32.Parse(ipAddrPortStr[1]);
continueIpCheck = false;
_logger.LogInformation("HandleWebSocketConnection: VNET Conatiner PORT : " + tunnelPort);
}
_logger.LogInformation("HandleWebSocketConnection: Found IP Address from appsvctmp file: " + ipAddress);
}
}
catch (Exception)
{
}
try
{
if (continueIpCheck && ipAddress == null)
{
ipAddress = System.IO.File.ReadAllText("/home/site/ipaddr_" + Environment.GetEnvironmentVariable("WEBSITE_ROLE_INSTANCE_ID"));
_logger.LogInformation("HandleWebSocketConnection: Found IP Address from share file: " + ipAddress);
}
}
catch (Exception)
{
}
if (ipAddress == null)
{
ipAddress = "127.0.0.1";
}
_logger.LogInformation("HandleWebSocketConnection: Final IP Address: " + ipAddress);
if (continueIpCheck)
{
try
{
debugPort = Int32.Parse(Environment.GetEnvironmentVariable("APPSVC_TUNNEL_PORT"));
if (debugPort <= 0)
{
throw new Exception("Debuggee not found. Please start your site in debug mode and then attach debugger.");
}
}
catch (Exception)
{
debugPort = 2222;
}
}
string remoteDebug = "FALSE";
int remoteDebugPort = -1;
try
{
remoteDebug = System.IO.File.ReadAllText("/appsvctmp/remotedebug_" + Environment.GetEnvironmentVariable("WEBSITE_ROLE_INSTANCE_ID"));
_logger.LogInformation("HandleWebSocketConnection: Found remote debug file: " + remoteDebug);
if (!string.IsNullOrWhiteSpace(remoteDebug) && !remoteDebug.Contains("FALSE"))
{
// remote debug is enabled
if (int.TryParse(remoteDebug, out remoteDebugPort))
{
debugPort = remoteDebugPort;
_logger.LogInformation("HandleWebSocketConnection: Found remote debug port from file: " + debugPort);
}
}
}
catch (Exception)
{
}
if (tunnelPort > 0)
{
// this is coming from client side.. override.
debugPort = tunnelPort;
}
_logger.LogInformation("HandleWebSocketConnection: Final Port: " + debugPort);
if (context.WebSockets.IsWebSocketRequest)
{
_logger.LogInformation("Got websocket request");
WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync();
await HandleWebSocketConnection(webSocket, ipAddress, debugPort, bufferSize);
}
else
{
// Case insensitive test+comparison of the query string key
if (context.Request.QueryString.HasValue &&
context.Request.QueryString.Value.IndexOf("GetStatus", StringComparison.OrdinalIgnoreCase) >= 0)
{
_logger.LogInformation("Got a status request... connecting to " + ipAddress + ":" + debugPort);
// The GetStatusAPI response is a plain text or a json(version 2) depending upon the API version
bool IsV2StatusAPIRequest = context.Request.QueryString.HasValue
&& context.Request.QueryString.Value.IndexOf("GetStatusAPIVer", StringComparison.OrdinalIgnoreCase) >= 0
&& context.Request.Query["GetStatusAPIVer"].ToString() == "2";
_logger.LogInformation("GetStatusAPIV2Request ? : " + IsV2StatusAPIRequest);
// if the file does not exist, it implies that the container has not started
var lSiteStatus = "STOPPED";
try
{
String content = System.IO.File.ReadAllText("/appsvctmp/status.txt").ToLower();
_logger.LogInformation("\n\nContent : " + content);
if (content.Equals("startedlsite"))
{
lSiteStatus = "STARTED";
}
else if (content.Equals("startinglsite"))
{
lSiteStatus = "STARTING";
}
}
catch (IOException)
{
// preplaced, since if the file is not present implies
// web app is not started yet
}
catch (Exception ex)
{
// This should never happen
_logger.LogError("Could not read web app state : " + ex.Message);
}
_logger.LogInformation("Site Status" + lSiteStatus);
try
{
using (Socket testSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
testSocket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true);
testSocket.Connect(new IPEndPoint(IPAddress.Parse(ipAddress), debugPort));
context.Response.StatusCode = 200;
_logger.LogInformation("GetStats success " + ipAddress + ":" + debugPort);
if (IsV2StatusAPIRequest)
{
var response = new LSiteStatusResponse(lSiteStatus, debugPort, true);
var json = JsonConvert.SerializeObject(response);
await context.Response.WriteAsync(json);
}
else
{
await context.Response.WriteAsync("SUCCESS:" + debugPort);
}
}
}
catch (Exception ex)
{
_logger.LogError(ex.ToString());
context.Response.StatusCode = 200;
if (IsV2StatusAPIRequest)
{
var response = new LSiteStatusResponse(lSiteStatus, debugPort, false, "Unable to connect to WebApp");
var json = JsonConvert.SerializeObject(response);
await context.Response.WriteAsync(json);
}
else
{
await context.Response.WriteAsync("FAILURE:" + debugPort + ":" + "Unable to connect to WebApp");
}
}
}
else
{
context.Response.StatusCode = 400;
}
}
}
19
Source : LinuxProcessController.cs
with Apache License 2.0
from Azure-App-Service
with Apache License 2.0
from Azure-App-Service
private string GetIpAddress()
{
try
{
string ipAddress = System.IO.File.ReadAllText(Constants.AppServiceTempPath + Environment.GetEnvironmentVariable(Constants.AzureWebsiteRoleInstanceId));
if (ipAddress != null)
{
if (ipAddress.Contains(':'))
{
string[] ipAddrPortStr = ipAddress.Split(":");
return ipAddrPortStr[0];
}
else
{
return ipAddress;
}
}
}
catch (Exception)
{
}
return string.Empty;
}
19
Source : MicrosoftIdentityPlatformApplicationManager.cs
with MIT License
from AzureAD
with MIT License
from AzureAD
private async Task<IEnumerable<IGrouping<string, ResourceAndScope>>?> AddApiPermissions(
ApplicationParameters applicationParameters,
GraphServiceClient graphServiceClient,
Application application)
{
// Case where the app calls a downstream API
List<RequiredResourceAccess> apiRequests = new List<RequiredResourceAccess>();
string? calledApiScopes = applicationParameters?.CalledApiScopes;
IEnumerable<IGrouping<string, ResourceAndScope>>? scopesPerResource = null;
if (!string.IsNullOrEmpty(calledApiScopes))
{
string[] scopes = calledApiScopes.Split(' ', '\t', StringSplitOptions.RemoveEmptyEntries);
scopesPerResource = scopes.Select(s => (!s.Contains('/'))
// Microsoft Graph shortcut scopes (for instance "User.Read")
? new ResourceAndScope("https://graph.microsoft.com", s)
// Proper AppIdUri/scope
: new ResourceAndScope(s.Substring(0, s.LastIndexOf('/')), s[(s.LastIndexOf('/') + 1)..])
).GroupBy(r => r.Resource)
.ToArray(); // We want to modify these elements to cache the service principal ID
foreach (var g in scopesPerResource)
{
await AddPermission(graphServiceClient, apiRequests, g);
}
}
if (apiRequests.Any())
{
application.RequiredResourceAccess = apiRequests;
}
return scopesPerResource;
}
19
Source : TransitionMany.cs
with MIT License
from b3b00
with MIT License
from b3b00
public override bool Match(char input)
{
return TransitionToken.Contains(input);
}
19
Source : JsonPath.cs
with MIT License
from baking-bad
with MIT License
from baking-bad
public static bool TryParse(string path, out JsonPath[] res)
{
res = (path.Contains('"')
? Regex.Matches(path, @"(?:""(?:(?:\\"")|(?:[^""]))*"")|(?:[^"".]+)").Select(x => x.Value)
: path.Split("."))
.Select(x => new JsonPath(x))
.ToArray();
return res.All(x => x.Type != JsonPathType.None);
}
19
Source : CRefPath.cs
with MIT License
from barry-jones
with MIT License
from barry-jones
public ReflectedMember FindIn(TypeDef type)
{
// TODO: Move to the TypeDef clreplaced
if(type == null) throw new ArgumentNullException("type");
if(this.PathType == CRefTypes.Namespace || this.PathType == CRefTypes.Type || this.PathType == CRefTypes.Error)
{
throw new InvalidOperationException(string.Format("Can not find member in a type when the path type is '{0}'", this.PathType.ToString()));
}
ReflectedMember member = null;
List<ReflectedMember> foundMembers = new List<ReflectedMember>();
// find all potential members
switch(this.PathType)
{
case CRefTypes.Event:
foundMembers.AddRange(type.Events.FindAll(e => string.Compare(e.Name, this.ElementName, true) == 0).ToArray());
break;
case CRefTypes.Field:
foundMembers.AddRange(type.Fields.FindAll(e => string.Compare(e.Name, this.ElementName, true) == 0).ToArray());
break;
case CRefTypes.Method:
string elementName = this.ElementName.Replace('#', '.');
int genParameters = 0;
if(elementName.Contains('`'))
{
genParameters = int.Parse(elementName.Substring(elementName.Length - 1, 1));
elementName = elementName.Substring(0, elementName.IndexOf('`'));
}
MethodDef[] foundMethods = type.Methods.FindAll(e => string.Compare(e.Name, elementName, true) == 0).ToArray();
if(foundMethods.Length > 1 && genParameters > 0)
{
for(int i = 0; i < foundMethods.Length; i++)
{
if(foundMethods[i].GenericTypes != null && foundMethods[i].GenericTypes.Count == genParameters)
{
foundMembers.Add(foundMethods[i]);
}
}
}
else
{
foundMembers.AddRange(foundMethods);
}
break;
case CRefTypes.Property:
foundMembers.AddRange(type.Properties.FindAll(e => string.Compare(e.Name, this.ElementName, true) == 0).ToArray());
break;
}
if(foundMembers.Count == 1)
{
member = foundMembers[0];
}
else if(foundMembers.Count > 1)
{
// the elements will differ by the parameters, this is slow!
foreach(ReflectedMember current in foundMembers)
{
string found = CRefPath.Create(current).ToString();
if(string.Compare(found, this.ToString(), true) == 0)
{
member = current;
break;
}
}
}
return member;
}
19
Source : ArgHelper.cs
with MIT License
from bartoszlenar
with MIT License
from bartoszlenar
public static IReadOnlyList<ArgPlaceholder> ExtractPlaceholders(string message)
{
ThrowHelper.NullArgument(message, nameof(message));
string[] matches = CurlyBracketsRegex.Matches(message)
.Cast<Match>()
.Select(m => m.Value)
.Distinct()
.ToArray();
var placeholders = new List<ArgPlaceholder>(matches.Length);
foreach (var match in matches)
{
string[] parts = match.Split(Divider);
var name = parts.FirstOrDefault();
if (string.IsNullOrWhiteSpace(name))
{
continue;
}
var placeholder = $"{{{match}}}";
if (parts.Length == 1)
{
placeholders.Add(new ArgPlaceholder
{
Placeholder = placeholder,
Name = name,
Parameters = EmptyParametersDictionary
});
}
else
{
Dictionary<string, string> parameters = null;
var invalidPart = false;
for (var i = 1; i < parts.Length; ++i)
{
var item = parts.ElementAt(i);
if (!item.Contains(replacedignment))
{
invalidPart = true;
break;
}
string[] groups = item.Split(replacedignment).Where(p => !string.IsNullOrWhiteSpace(p)).ToArray();
if (groups.Length != 2)
{
invalidPart = true;
break;
}
if (parameters == null)
{
parameters = new Dictionary<string, string>();
}
if (parameters.ContainsKey(groups.ElementAt(0)))
{
invalidPart = true;
break;
}
parameters.Add(groups.ElementAt(0), groups.ElementAt(1));
}
if (invalidPart)
{
continue;
}
placeholders.Add(new ArgPlaceholder
{
Placeholder = placeholder,
Name = name,
Parameters = parameters ?? EmptyParametersDictionary
});
}
}
return placeholders;
}
19
Source : AbstractQueryValidator.cs
with MIT License
from bbartels
with MIT License
from bbartels
public static string GetExpandString(string expression)
{
var split = expression.Split(new[] { "=>" }, StringSplitOptions.None).ToList();
var properties = new List<string>();
foreach(var str in split)
{
if(!str.Contains('.')) { continue; }
var propSplit = str.Split('.');
for(int i = 1; i < propSplit.Length; i++)
{
if (!propSplit[i].StartsWith("Select"))
{
properties.Add(propSplit[i].Trim(')').Trim('('));
}
}
}
return properties.Aggregate((x, y) => x + '.' + y);
}
19
Source : AsagiThreadConsumer.cs
with MIT License
from bbepis
with MIT License
from bbepis
public static string CleanComment(string inputComment)
{
if (string.IsNullOrWhiteSpace(inputComment))
return string.Empty;
if (!inputComment.Contains('<') && !inputComment.Contains('['))
{
if (!inputComment.Contains('&'))
{
// No HTML encoding has been done at all
return inputComment.Trim();
}
// Only escaping has been done
return HttpUtility.HtmlDecode(inputComment).Trim();
}
// Copied wholesale from https://github.com/bibanon/asagi/blob/master/src/main/java/net/easymodo/asagi/YotsubaAbstract.java
// SOPA spoilers
//text = text.replaceAll("<span clreplaced=\"spoiler\"[^>]*>(.*?)</spoiler>(</span>)?", "$1");
// Admin-Mod-Dev quotelinks
inputComment = quoteLinkRegex.Replace(inputComment, "");
// Non-public tags
inputComment = nonPublicTagRegex.Replace(inputComment, "[$1:lit]");
// Comment too long, also EXIF tag toggle
inputComment = toggleExpansionRegex.Replace(inputComment, "");
// EXIF data
inputComment = exifCleanRegex.Replace(inputComment, "");
// DRAW data
inputComment = drawCleanRegex.Replace(inputComment, "");
// Banned/Warned text
inputComment = bannedRegex.Replace(inputComment, "[banned]$1[/banned]");
// moot inputComment
inputComment = mootCommentRegex.Replace(inputComment, "[moot]$1[/moot]");
// fortune inputComment
inputComment = fortuneRegex.Replace(inputComment, "\n\n[fortune color=\"$1\"]$2[/fortune]");
// bold inputComment
inputComment = boldRegex.Replace(inputComment, "[b]$1[/b]");
// code tags
inputComment = codeTagRegex.Replace(inputComment, "[code]");
inputComment = inputComment.Replace("</pre>", "[/code]");
// math tags
inputComment = mathTagRegex.Replace(inputComment, "[math]$1[/math]");
inputComment = mathTag2Regex.Replace(inputComment, "[eqn]$1[/eqn]");
// > implying I'm quoting someone
inputComment = quoteTagRegex.Replace(inputComment, "$1");
inputComment = quoteTag2Regex.Replace(inputComment, "$1");
inputComment = quoteTag3Regex.Replace(inputComment, "$1");
// Links
inputComment = linkTagRegex.Replace(inputComment, "$1");
// old spoilers
inputComment = oldSpoilerTagRegex.Replace(inputComment, "[spoiler]$1[/spoiler]");
// ShiftJIS
inputComment = shiftjisTagRegex.Replace(inputComment, "[shiftjis]$1[/shiftjis]");
// new spoilers
inputComment = inputComment.Replace("<s>", "[spoiler]");
inputComment = inputComment.Replace("</s>", "[/spoiler]");
// new line/wbr
inputComment = newLineRegex.Replace(inputComment, "\n");
inputComment = inputComment.Replace("<wbr>", "");
return HttpUtility.HtmlDecode(inputComment).Trim();
}
19
Source : QueryableExtensions.cs
with Apache License 2.0
from bcgov
with Apache License 2.0
from bcgov
private static Expression<Func<T, RT>> GeneratePropertyPathLambda<T, RT>(string path)
where T : clreplaced
{
if (!path.Contains('.')) return null;
var parameter = Expression.Parameter(typeof(T), "x");
return Expression.Lambda<Func<T, RT>>(path.Split('.').Aggregate((Expression)parameter, Expression.PropertyOrField), parameter);
}
19
Source : ModPatchExporter.cs
with MIT License
from bcssov
with MIT License
from bcssov
public IEnumerable<string> GetPatchFiles(ModPatchExporterParameters parameters)
{
var path = GetPatchRootPath(parameters.RootPath, parameters.PatchPath);
var files = new List<string>();
if (Directory.Exists(path))
{
foreach (var item in Directory.EnumerateFiles(path, "*", SearchOption.AllDirectories))
{
var relativePath = item.Replace(path, string.Empty).Trim(Path.DirectorySeparatorChar);
if (relativePath.Contains(Path.DirectorySeparatorChar) && !relativePath.Contains(StateHistory, StringComparison.OrdinalIgnoreCase))
{
files.Add(relativePath);
}
}
}
return files;
}
19
Source : DiskFileReader.cs
with MIT License
from bcssov
with MIT License
from bcssov
public virtual IReadOnlyCollection<IFileInfo> Read(string path, IEnumerable<string> allowedPaths, bool searchSubFolders = true)
{
var files = Directory.GetFiles(path, "*", searchSubFolders ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);
if (files?.Length > 0)
{
var result = new List<IFileInfo>();
foreach (var file in files)
{
var relativePath = file.Replace(path, string.Empty).Trim(Path.DirectorySeparatorChar);
if (searchSubFolders)
{
if (!relativePath.Contains(Path.DirectorySeparatorChar) ||
relativePath.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries).Any(s => s.StartsWith(".")) ||
(allowedPaths?.Count() > 0 && !allowedPaths.Any(p => relativePath.StartsWith(p, StringComparison.OrdinalIgnoreCase))))
{
continue;
}
}
var info = DIResolver.Get<IFileInfo>();
var fileInfo = new System.IO.FileInfo(file);
info.IsReadOnly = fileInfo.IsReadOnly;
info.Size = fileInfo.Length;
using var stream = File.OpenRead(file);
info.FileName = relativePath;
if (Constants.TextExtensions.Any(s => file.EndsWith(s, StringComparison.OrdinalIgnoreCase)))
{
using var streamReader = new StreamReader(stream, true);
var text = streamReader.ReadToEnd();
streamReader.Close();
streamReader.Dispose();
info.IsBinary = false;
info.Content = text.SplitOnNewLine(false);
info.ContentSHA = text.CalculateSHA();
}
else
{
info.IsBinary = true;
using var fs = new FileStream(file, FileMode.Open, FileAccess.Read);
info.ContentSHA = fs.CalculateSHA();
}
result.Add(info);
}
return result;
}
return null;
}
19
Source : IronyClipboard.cs
with MIT License
from bcssov
with MIT License
from bcssov
private string CleanupCarriageReturns(string text)
{
if (text.Contains('\r') || text.Contains('\n'))
{
return text.SplitOnNewLine().ToList()[0];
}
return text;
}
19
Source : EightyCodeGenerator.cs
with MIT License
from benjamin-hodgson
with MIT License
from benjamin-hodgson
protected static string IndefiniteArticle(string noun)
=> noun == "html"
|| noun.Length <= 2 && _vowelSoundingLetters.Contains(noun[0])
|| _vowels.Contains(noun[0])
? "an"
: "a";
19
Source : SpaceExtension.cs
with MIT License
from benruehl
with MIT License
from benruehl
protected virtual bool TryParseExpression(string expression, out double factor, out double offset)
{
factor = 0;
offset = 0;
if (String.IsNullOrEmpty(expression))
return false;
char sign;
if (expression.Substring(1).Contains('+'))
sign = '+';
else if (expression.Substring(1).Contains('-'))
sign = '-';
else
return double.TryParse(expression, NumberStyles.Any, CultureInfo.InvariantCulture, out factor);
string[] expressionParts = expression.Split(sign);
if (expressionParts[0] == String.Empty) // first char was <sign>
expressionParts = new[] { '-' + expressionParts[1], expressionParts[2] };
if (expressionParts.Length != 2)
return false;
bool canParseFactor = double.TryParse(expressionParts[0], NumberStyles.Any, CultureInfo.InvariantCulture, out factor);
bool canParseOffset = double.TryParse(expressionParts[1], NumberStyles.Any, CultureInfo.InvariantCulture, out offset);
if (sign == '-')
offset *= -1;
return canParseFactor && canParseOffset;
}
19
Source : ConfigDefinition.cs
with GNU Lesser General Public License v2.1
from BepInEx
with GNU Lesser General Public License v2.1
from BepInEx
private static void CheckInvalidConfigChars(string val, string name)
{
if (val == null) throw new ArgumentNullException(name);
if (val != val.Trim())
throw new ArgumentException("Cannot use whitespace characters at start or end of section and key names",
name);
if (val.Any(c => _invalidConfigChars.Contains(c)))
throw new
ArgumentException(@"Cannot use any of the following characters in section and key names: = \n \t \ "" ' [ ]",
name);
}
See More Examples