Here are the examples of the csharp api System.Collections.Generic.IEnumerable.Skip(int) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
4393 Examples
19
Source : LocalizationConverter.cs
with MIT License
from aksoftware98
with MIT License
from aksoftware98
public override object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
if (values.Any(item => item == null))
{
return null;
}
var localization = (Application.Current as IServiceProviderHost).ServiceProvider.GetService<ILanguageContainerService>();
if (localization == null)
{
return null;
}
var key = (string)values[0];
var keyValues = new Dictionary<string, object>();
if (values.Length > 1)
{
foreach (var o in values.Skip(1))
{
var val = (string) o;
var parts = val.Split(":");
if (parts.Length == 2)
{
keyValues[parts[0]] = parts[1];
}
}
}
return localization[key, keyValues];
}
19
Source : PagedList.cs
with MIT License
from aksoftware98
with MIT License
from aksoftware98
private void PrepareData(IEnumerable<T> data, int page, int pageSize)
{
Records = Records ?? new List<T>();
Records.Clear();
var pageData = data.Skip((page - 1) * pageSize).Take(pageSize);
Records.AddRange(pageData);
ItemsCount = data.Count();
TotalPages = ItemsCount / PageSize;
if ((ItemsCount % PageSize) > 0)
TotalPages++;
}
19
Source : Program.cs
with MIT License
from Alan-FGR
with MIT License
from Alan-FGR
static void Main(string[] args)
{
String[] files = {"Registry", "ArchetypePool"};
string path = "Archetypes";
Console.WriteLine("C# VARIADIC GENERATOR. VALID TAGS:");
foreach (var modeFunction in modeFunctions)
{
Console.WriteLine($" {modeFunction.Key}");
Console.WriteLine($" Description: {modeFunction.Value.descr}");
}
foreach (string file in Directory.GetFiles(path, "*.cs", SearchOption.AllDirectories))
{
var pathElements = file.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries);
if (pathElements.Contains("obj"))
continue;
if (!files.Contains(Path.GetFileName(file)) && !files.Contains(Path.GetFileNameWithoutExtension(file)))
continue;
var code = File.ReadAllLines(file);
var generatedCode = new StringWriter();
Console.WriteLine($"PARSING FILE: {file}...");
var regions = new List<(int qty, List<string> lines)>();
List<string> currentRegion = null;
foreach (string line in code)
{
if (line.ToLowerInvariant().Contains("#region variadic"))
{
currentRegion = new List<string>();
regions.Add((int.Parse(line.Trim().Split(' ')[2]), currentRegion));
continue;
}
if (line.ToLowerInvariant().Contains("#endregion"))
{
currentRegion = null;
continue;
}
currentRegion?.Add(line);
}
foreach (var tuple in regions)
{
curRegion = tuple.lines;
for (int qti = 2; qti <= tuple.qty; qti++)
{
curQty = qti;
for (var i = 0; i < tuple.lines.Count; i++)
{
string line = tuple.lines[i];
var trimmed = line.TrimStart(' ');
if (trimmed.Length >= 2)
{
string substring = trimmed.Substring(0, 2);
if (substring == "//")
continue;
if (substring == "/*")
Console.WriteLine($"MULTILINE COMMENT BLOCKS (DETECTED ON LINE {i}) NOT SUPPORTED." +
"YOU CAN USE THEM FOR COMMENTS AS USUAL BUT MAKE SURE THERE ARE NO TAGS IN THEM.");
}
if (line.ToLowerInvariant().Contains("genvariadic"))
{
var pars = line.Split("genvariadic")[1].Split(' ', StringSplitOptions.RemoveEmptyEntries);
Console.WriteLine(
$"found variadic on line {i}, {pars.Length} parameters: {string.Join(", ", pars)}");
if (pars.Length < 1)
{
Console.WriteLine("NO PARAMETERS!");
continue;
}
var mode = pars.First();
var options = pars.Skip(1).ToArray();
if (modeFunctions.TryGetValue(mode, out var value))
{
var str = value.Item2(options, i);
generatedCode.WriteLine(str);
}
else
{
string err = $"INVALID MODE: {mode}";
Console.WriteLine(err);
generatedCode.WriteLine(err);
}
}
else
{
generatedCode.WriteLine(line);
}
}
}
}
Console.WriteLine($"PARSED FILE: {file}\n");
var allcode = "";
foreach (string line in code)
{
var trimmed = (line.Trim());
if (trimmed.Length > 6)
if (trimmed.Substring(0, 5) == "using")
allcode += line+"\r\n";
}
allcode += $"public unsafe partial clreplaced {Path.GetFileNameWithoutExtension(file)} {{";
allcode += generatedCode.ToString();
allcode += "}";
File.WriteAllText(Path.Combine(path, Path.GetFileNameWithoutExtension(file)+"GeneratedVariadic.cs"), allcode);
}
//Console.ReadKey();
}
19
Source : Program.cs
with MIT License
from Alan-FGR
with MIT License
from Alan-FGR
public void Run()
{
for (int i = 0; i < 32; i++)
Bench();
Console.WriteLine($"avg after warmup: {resultList_.Skip(8).Average()}");
Console.ReadKey();
}
19
Source : QueryableExtensions.cs
with MIT License
from albyho
with MIT License
from albyho
public static async Task<Page<T>> GetPageAsync<T>(this IQueryable<T> sourceQuery, PagingInfo pagingInfo, ICollection<T> topQuery = null) where T : clreplaced
{
if (sourceQuery == null)
{
throw new ArgumentNullException(nameof(sourceQuery));
}
sourceQuery = sourceQuery.AsNoTracking();
var page = new Page<T>();
// 跳过记录集无记录
if (topQuery == null || topQuery.Count == 0)
{
page.List = await sourceQuery.Skip(pagingInfo.PageIndex * pagingInfo.PageSize).Take(pagingInfo.PageSize).ToListAsync();
if (!pagingInfo.IsExcludeMetaData)
{
page.TotalItemCount = await sourceQuery.CountAsync();
}
}
else
{
// 跳过的记录数
int topItemCount = topQuery.Count;
// 跳过的页数,比如一页显示10条,跳过4条、14条或24条,则跳过的页数为0、1或2
int skipPage = (int)Math.Floor((double)topItemCount / pagingInfo.PageSize);
// 如果目标页数在跳过的页数范围内,直接从topItems获取
if (skipPage > pagingInfo.PageIndex)
{
page.List = topQuery.Skip(pagingInfo.PageIndex * pagingInfo.PageSize).Take(pagingInfo.PageSize).ToList();
if (!pagingInfo.IsExcludeMetaData)
{
page.TotalItemCount = await sourceQuery.CountAsync() + topItemCount;
}
}
else
{
int topSkipCount = skipPage * pagingInfo.PageSize;
int topTakeCount = topItemCount % pagingInfo.PageSize;
var topItems = topQuery.Skip(topSkipCount).Take(topTakeCount);
int sourceSkipCount = (pagingInfo.PageIndex - skipPage) * pagingInfo.PageSize;
int sourceTakeCount = pagingInfo.PageSize - topTakeCount;
var sourceItems = await sourceQuery.Skip(sourceSkipCount).Take(sourceTakeCount).ToListAsync();
page.List = topItems.Concat(sourceItems).ToList();
if (!pagingInfo.IsExcludeMetaData)
{
// 查询集记录数
int sourceItemCount = await sourceQuery.CountAsync();
page.TotalItemCount = sourceItemCount + topItemCount;
}
}
}
page.TotalPageCount = (int)Math.Ceiling(page.TotalItemCount / (double)pagingInfo.PageSize);
return page;
}
19
Source : QueryableExtensions.cs
with MIT License
from albyho
with MIT License
from albyho
public static async Task<Page<T>> GetPageAsync<T>(this IQueryable<T> sourceQuery, PagingInfo pagingInfo, ICollection<T> topQuery = null) where T : clreplaced
{
if (sourceQuery == null)
{
throw new ArgumentNullException(nameof(sourceQuery));
}
sourceQuery = sourceQuery.AsNoTracking();
var page = new Page<T>();
// 跳过记录集无记录
if (topQuery == null || topQuery.Count == 0)
{
page.List = await sourceQuery.Skip(pagingInfo.PageIndex * pagingInfo.PageSize).Take(pagingInfo.PageSize).ToListAsync();
if (!pagingInfo.IsExcludeMetaData)
{
page.TotalItemCount = await sourceQuery.CountAsync();
}
}
else
{
// 跳过的记录数
int topItemCount = topQuery.Count;
// 跳过的页数,比如一页显示10条,跳过4条、14条或24条,则跳过的页数为0、1或2
int skipPage = (int)Math.Floor((double)topItemCount / pagingInfo.PageSize);
// 如果目标页数在跳过的页数范围内,直接从topItems获取
if (skipPage > pagingInfo.PageIndex)
{
page.List = topQuery.Skip(pagingInfo.PageIndex * pagingInfo.PageSize).Take(pagingInfo.PageSize).ToList();
if (!pagingInfo.IsExcludeMetaData)
{
page.TotalItemCount = await sourceQuery.CountAsync() + topItemCount;
}
}
else
{
int topSkipCount = skipPage * pagingInfo.PageSize;
int topTakeCount = topItemCount % pagingInfo.PageSize;
var topItems = topQuery.Skip(topSkipCount).Take(topTakeCount);
int sourceSkipCount = (pagingInfo.PageIndex - skipPage) * pagingInfo.PageSize;
int sourceTakeCount = pagingInfo.PageSize - topTakeCount;
var sourceItems = await sourceQuery.Skip(sourceSkipCount).Take(sourceTakeCount).ToListAsync();
page.List = topItems.Concat(sourceItems).ToList();
if (!pagingInfo.IsExcludeMetaData)
{
// 查询集记录数
int sourceItemCount = await sourceQuery.CountAsync();
page.TotalItemCount = sourceItemCount + topItemCount;
}
}
}
page.TotalPageCount = (int)Math.Ceiling(page.TotalItemCount / (double)pagingInfo.PageSize);
return page;
}
19
Source : QueryableExtensions.cs
with MIT License
from albyho
with MIT License
from albyho
public static IQueryable<TResult> LeftJoin<TOuter, TInner, TKey, TResult>(
this IQueryable<TOuter> outer,
IQueryable<TInner> inner,
Expression<Func<TOuter, TKey>> outerKeySelector,
Expression<Func<TInner, TKey>> innerKeySelector,
Expression<Func<TOuter, TInner, TResult>> resultSelector)
{
MethodInfo groupJoin = typeof(Queryable).GetMethods()
.Single(m => m.ToString() == "System.Linq.IQueryable`1[TResult] GroupJoin[TOuter,TInner,TKey,TResult](System.Linq.IQueryable`1[TOuter], System.Collections.Generic.IEnumerable`1[TInner], System.Linq.Expressions.Expression`1[System.Func`2[TOuter,TKey]], System.Linq.Expressions.Expression`1[System.Func`2[TInner,TKey]], System.Linq.Expressions.Expression`1[System.Func`3[TOuter,System.Collections.Generic.IEnumerable`1[TInner],TResult]])")
.MakeGenericMethod(typeof(TOuter), typeof(TInner), typeof(TKey), typeof(LeftJoinIntermediate<TOuter, TInner>));
MethodInfo selectMany = typeof(Queryable).GetMethods()
.Single(m => m.ToString() == "System.Linq.IQueryable`1[TResult] SelectMany[TSource,TCollection,TResult](System.Linq.IQueryable`1[TSource], System.Linq.Expressions.Expression`1[System.Func`2[TSource,System.Collections.Generic.IEnumerable`1[TCollection]]], System.Linq.Expressions.Expression`1[System.Func`3[TSource,TCollection,TResult]])")
.MakeGenericMethod(typeof(LeftJoinIntermediate<TOuter, TInner>), typeof(TInner), typeof(TResult));
var groupJoinResultSelector = (Expression<Func<TOuter, IEnumerable<TInner>, LeftJoinIntermediate<TOuter, TInner>>>)
((oneOuter, manyInners) => new LeftJoinIntermediate<TOuter, TInner> { OneOuter = oneOuter, ManyInners = manyInners });
MethodCallExpression exprGroupJoin = Expression.Call(groupJoin, outer.Expression, inner.Expression, outerKeySelector, innerKeySelector, groupJoinResultSelector);
var selectManyCollectionSelector = (Expression<Func<LeftJoinIntermediate<TOuter, TInner>, IEnumerable<TInner>>>)
(t => t.ManyInners.DefaultIfEmpty());
ParameterExpression paramUser = resultSelector.Parameters.First();
ParameterExpression paramNew = Expression.Parameter(typeof(LeftJoinIntermediate<TOuter, TInner>), "t");
MemberExpression propExpr = Expression.Property(paramNew, "OneOuter");
LambdaExpression selectManyResultSelector = Expression.Lambda(new Replacer(paramUser, propExpr).Visit(resultSelector.Body) ?? throw new InvalidOperationException(), paramNew, resultSelector.Parameters.Skip(1).First());
MethodCallExpression exprSelectMany = Expression.Call(selectMany, exprGroupJoin, selectManyCollectionSelector, selectManyResultSelector);
return outer.Provider.CreateQuery<TResult>(exprSelectMany);
}
19
Source : Extension.cs
with MIT License
from AlenToma
with MIT License
from AlenToma
internal static List<string> ConvertExpressionToIncludeList(this Expression[] actions, bool onlyLast = false)
{
var result = new List<string>();
if (actions == null) return result;
foreach (var exp in actions)
{
var tempList = new List<string>();
var expString = exp.ToString().Split('.');
var propTree = "";
foreach (var item in expString)
{
var x = item.Trim().Replace("(", "").Replace(")", "").Replace("&&", "").Replace("||", "").Trim();
if (x.Any(char.IsWhiteSpace) || x.Contains("="))
continue;
propTree += ("." + x);
if (propTree.Split('.').Length == 4)
{
propTree = string.Join(".", propTree.Split('.').ToList().Skip(2).Cast<string>().ToArray());
}
tempList.Add(propTree.TrimStart('.'));
}
if (!onlyLast)
result.AddRange(tempList);
else if (tempList.Any())
{
var str = tempList.Last();
str = str?.Split('.').Length >= 2 ? string.Join(".", str.Split('.').Reverse().Take(2).Cast<string>().Reverse()) : str;
result.Add(str);
}
}
return result;
}
19
Source : DataCipher.cs
with MIT License
from AlenToma
with MIT License
from AlenToma
public string Decrypt(string cipherText)
{
if (!cipherText.IsBase64String())
return cipherText;
var cipherTextBytesWithSaltAndIv = Convert.FromBase64String(cipherText);
var v = Encoding.UTF8.GetString(cipherTextBytesWithSaltAndIv.Take(_Keysize / 8).ToArray());
if (v != salt256 && v != salt128)
return cipherText;
var cipherTextBytes = cipherTextBytesWithSaltAndIv.Skip((_Keysize / 8) * 2).Take(cipherTextBytesWithSaltAndIv.Length - ((_Keysize / 8) * 2)).ToArray();
using (var preplacedword = new Rfc2898DeriveBytes(_preplacedPhrase, saltStringBytes, DerivationIterations))
{
var keyBytes = preplacedword.GetBytes(_Keysize / 8);
using (var symmetricKey = new RijndaelManaged())
{
symmetricKey.Mode = CipherMode.CBC;
symmetricKey.Padding = PaddingMode.PKCS7;
symmetricKey.BlockSize = _Keysize;
using (var decryptor = symmetricKey.CreateDecryptor(keyBytes, ivStringBytes))
{
using (var memoryStream = new MemoryStream(cipherTextBytes))
{
using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
{
var plainTextBytes = new byte[cipherTextBytes.Length];
var decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
memoryStream.Close();
cryptoStream.Close();
return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
}
}
}
}
}
}
19
Source : ByteCipher.cs
with MIT License
from AlenToma
with MIT License
from AlenToma
public byte[] Decrypt(byte[] cipherTextBytesWithSaltAndIv)
{
if (cipherTextBytesWithSaltAndIv.Length <= 0)
return cipherTextBytesWithSaltAndIv;
var v = Encoding.UTF8.GetString(cipherTextBytesWithSaltAndIv.Take(_Keysize / 8).ToArray());
if (v != salt256 && v != salt128)
return cipherTextBytesWithSaltAndIv;
var cipherTextBytes = cipherTextBytesWithSaltAndIv.Skip((_Keysize / 8) * 2).Take(cipherTextBytesWithSaltAndIv.Length - ((_Keysize / 8) * 2)).ToArray();
using (var preplacedword = new Rfc2898DeriveBytes(_preplacedPhrase, saltStringBytes, DerivationIterations))
{
var keyBytes = preplacedword.GetBytes(_Keysize / 8);
using (var symmetricKey = new RijndaelManaged())
{
symmetricKey.Mode = CipherMode.CBC;
symmetricKey.Padding = PaddingMode.PKCS7;
symmetricKey.BlockSize = _Keysize;
using (var decryptor = symmetricKey.CreateDecryptor(keyBytes, ivStringBytes))
{
using (var memoryStream = new MemoryStream(cipherTextBytes))
{
using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
{
var plainTextBytes = new byte[cipherTextBytes.Length];
var decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
memoryStream.Close();
cryptoStream.Close();
return plainTextBytes;
}
}
}
}
}
}
19
Source : PaginatedList.cs
with MIT License
from AlexanderFroemmgen
with MIT License
from AlexanderFroemmgen
public static PaginatedList<T> Create(IEnumerable<T> source, int pageIndex, int pageSize)
{
var count = source.Count();
var items = source.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
return new PaginatedList<T>(items, count, pageIndex, pageSize);
}
19
Source : PaginatedMessagesControlViewModel.cs
with GNU General Public License v3.0
from alexdillon
with GNU General Public License v3.0
from alexdillon
private async Task<IEnumerable<Message>> GetFromGroupMeAsync(Message startAt, Message endAt)
{
var result = new List<Message>(this.MessagesPerPage);
long.TryParse(startAt.Id, out var startId);
long.TryParse(endAt.Id, out var endId);
// GroupMe only allows before_id searches on Chat's (not after_id), so we have to go backwards...
// Add 1 to include the endAt message in the returned data.
long currentId = endId + 1;
while (currentId > startId)
{
var msgs = await this.replacedociateWith.GetMessagesAsync(GroupMeClientApi.MessageRetreiveMode.BeforeId, currentId.ToString());
result.AddRange(msgs);
currentId = long.Parse(msgs.Last().Id);
}
// Since we went backwards, reverse the list.
result.Reverse();
// GroupMe block sizes might not align with the pagination page-sizes.
// Cut to match the expected page size.
int startIndex = result.FindIndex(m => m.Id == startAt.Id);
return result.Skip(startIndex);
}
19
Source : Logger.cs
with MIT License
from AlexGyver
with MIT License
from AlexGyver
private bool OpenExistingLogFile() {
if (!File.Exists(fileName))
return false;
try {
String line;
using (StreamReader reader = new StreamReader(fileName))
line = reader.ReadLine();
if (string.IsNullOrEmpty(line))
return false;
identifiers = line.Split(',').Skip(1).ToArray();
} catch {
identifiers = null;
return false;
}
if (identifiers.Length == 0) {
identifiers = null;
return false;
}
sensors = new ISensor[identifiers.Length];
SensorVisitor visitor = new SensorVisitor(sensor => {
for (int i = 0; i < identifiers.Length; i++)
if (sensor.Identifier.ToString() == identifiers[i])
sensors[i] = sensor;
});
visitor.VisitComputer(computer);
return true;
}
19
Source : DnsRecordBase.cs
with Apache License 2.0
from alexreinert
with Apache License 2.0
from alexreinert
internal void ParseUnknownRecordData(string[] stringRepresentation)
{
if (stringRepresentation.Length < 2)
throw new FormatException();
if (stringRepresentation[0] != @"\#")
throw new FormatException();
int length = Int32.Parse(stringRepresentation[1]);
byte[] byteData = String.Join("", stringRepresentation.Skip(2)).FromBase16String();
if (length != byteData.Length)
throw new FormatException();
ParseRecordData(byteData, 0, length);
}
19
Source : IpSecKeyRecord.cs
with Apache License 2.0
from alexreinert
with Apache License 2.0
from alexreinert
internal override void ParseRecordData(DomainName origin, string[] stringRepresentation)
{
if (stringRepresentation.Length < 5)
throw new FormatException();
Precedence = Byte.Parse(stringRepresentation[0]);
GatewayType = (IpSecGatewayType) Byte.Parse(stringRepresentation[1]);
Algorithm = (IpSecAlgorithm) Byte.Parse(stringRepresentation[2]);
Gateway = stringRepresentation[3];
PublicKey = String.Join(String.Empty, stringRepresentation.Skip(4)).FromBase64String();
}
19
Source : SshFpRecord.cs
with Apache License 2.0
from alexreinert
with Apache License 2.0
from alexreinert
internal override void ParseRecordData(DomainName origin, string[] stringRepresentation)
{
if (stringRepresentation.Length < 3)
throw new FormatException();
Algorithm = (SshFpAlgorithm) Byte.Parse(stringRepresentation[0]);
FingerPrintType = (SshFpFingerPrintType) Byte.Parse(stringRepresentation[1]);
FingerPrint = String.Join("", stringRepresentation.Skip(2)).FromBase16String();
}
19
Source : WksRecord.cs
with Apache License 2.0
from alexreinert
with Apache License 2.0
from alexreinert
internal override void ParseRecordData(DomainName origin, string[] stringRepresentation)
{
if (stringRepresentation.Length < 2)
throw new FormatException();
Address = IPAddress.Parse(stringRepresentation[0]);
Ports = stringRepresentation.Skip(1).Select(UInt16.Parse).ToList();
}
19
Source : DlvRecord.cs
with Apache License 2.0
from alexreinert
with Apache License 2.0
from alexreinert
internal override void ParseRecordData(DomainName origin, string[] stringRepresentation)
{
if (stringRepresentation.Length < 4)
throw new FormatException();
KeyTag = UInt16.Parse(stringRepresentation[0]);
Algorithm = (DnsSecAlgorithm) Byte.Parse(stringRepresentation[1]);
DigestType = (DnsSecDigestType) Byte.Parse(stringRepresentation[2]);
Digest = String.Join(String.Empty, stringRepresentation.Skip(3)).FromBase16String();
}
19
Source : RrSigRecord.cs
with Apache License 2.0
from alexreinert
with Apache License 2.0
from alexreinert
internal override void ParseRecordData(DomainName origin, string[] stringRepresentation)
{
if (stringRepresentation.Length < 9)
throw new FormatException();
TypeCovered = RecordTypeHelper.ParseShortString(stringRepresentation[0]);
Algorithm = (DnsSecAlgorithm) Byte.Parse(stringRepresentation[1]);
Labels = Byte.Parse(stringRepresentation[2]);
OriginalTimeToLive = Int32.Parse(stringRepresentation[3]);
SignatureExpiration = DateTime.ParseExact(stringRepresentation[4], "yyyyMMddHHmmss", CultureInfo.InvariantCulture, DateTimeStyles.replacedumeUniversal);
SignatureInception = DateTime.ParseExact(stringRepresentation[5], "yyyyMMddHHmmss", CultureInfo.InvariantCulture, DateTimeStyles.replacedumeUniversal);
KeyTag = UInt16.Parse(stringRepresentation[6]);
SignersName = ParseDomainName(origin, stringRepresentation[7]);
Signature = String.Join(String.Empty, stringRepresentation.Skip(8)).FromBase64String();
}
19
Source : SigRecord.cs
with Apache License 2.0
from alexreinert
with Apache License 2.0
from alexreinert
internal override void ParseRecordData(DomainName origin, string[] stringRepresentation)
{
if (stringRepresentation.Length < 9)
throw new FormatException();
TypeCovered = RecordTypeHelper.ParseShortString(stringRepresentation[0]);
Algorithm = (DnsSecAlgorithm) Byte.Parse(stringRepresentation[1]);
Labels = Byte.Parse(stringRepresentation[2]);
OriginalTimeToLive = Int32.Parse(stringRepresentation[3]);
SignatureExpiration = DateTime.ParseExact(stringRepresentation[4], "yyyyMMddHHmmss", CultureInfo.InvariantCulture);
SignatureInception = DateTime.ParseExact(stringRepresentation[5], "yyyyMMddHHmmss", CultureInfo.InvariantCulture);
KeyTag = UInt16.Parse(stringRepresentation[6]);
SignersName = ParseDomainName(origin, stringRepresentation[7]);
Signature = String.Join(String.Empty, stringRepresentation.Skip(8)).FromBase64String();
}
19
Source : CSyncRecord.cs
with Apache License 2.0
from alexreinert
with Apache License 2.0
from alexreinert
internal override void ParseRecordData(DomainName origin, string[] stringRepresentation)
{
if (stringRepresentation.Length < 3)
throw new FormatException();
SerialNumber = UInt32.Parse(stringRepresentation[0]);
Flags = (CSyncFlags) UInt16.Parse(stringRepresentation[1]);
Types = stringRepresentation.Skip(2).Select(RecordTypeHelper.ParseShortString).ToList();
}
19
Source : DnsKeyRecord.cs
with Apache License 2.0
from alexreinert
with Apache License 2.0
from alexreinert
internal override void ParseRecordData(DomainName origin, string[] stringRepresentation)
{
if (stringRepresentation.Length < 4)
throw new FormatException();
Flags = (DnsKeyFlags) UInt16.Parse(stringRepresentation[0]);
Protocol = Byte.Parse(stringRepresentation[1]);
Algorithm = (DnsSecAlgorithm) Byte.Parse(stringRepresentation[2]);
PublicKey = String.Join(String.Empty, stringRepresentation.Skip(3)).FromBase64String();
}
19
Source : Nsec3Record.cs
with Apache License 2.0
from alexreinert
with Apache License 2.0
from alexreinert
internal override void ParseRecordData(DomainName origin, string[] stringRepresentation)
{
if (stringRepresentation.Length < 5)
throw new FormatException();
HashAlgorithm = (NSec3HashAlgorithm) Byte.Parse(stringRepresentation[0]);
Flags = Byte.Parse(stringRepresentation[1]);
Iterations = UInt16.Parse(stringRepresentation[2]);
Salt = (stringRepresentation[3] == "-") ? new byte[] { } : stringRepresentation[3].FromBase16String();
NextHashedOwnerName = stringRepresentation[4].FromBase32HexString();
Types = stringRepresentation.Skip(5).Select(RecordTypeHelper.ParseShortString).ToList();
}
19
Source : NSecRecord.cs
with Apache License 2.0
from alexreinert
with Apache License 2.0
from alexreinert
internal override void ParseRecordData(DomainName origin, string[] stringRepresentation)
{
if (stringRepresentation.Length < 2)
throw new FormatException();
NextDomainName = ParseDomainName(origin, stringRepresentation[0]);
Types = stringRepresentation.Skip(1).Select(RecordTypeHelper.ParseShortString).ToList();
}
19
Source : Zone.cs
with Apache License 2.0
from alexreinert
with Apache License 2.0
from alexreinert
private static List<DnsRecordBase> ParseRecords(StreamReader reader, DomainName origin, int ttl, DnsRecordBase lastRecord)
{
List<DnsRecordBase> records = new List<DnsRecordBase>();
while (!reader.EndOfStream)
{
string line = ReadRecordLine(reader);
if (!String.IsNullOrEmpty(line))
{
string[] parts = _lineSplitterRegex.Matches(line).Cast<Match>().Select(x => x.Groups.Cast<Group>().Last(g => g.Success).Value.FromMasterfileLabelRepresentation()).ToArray();
if (parts[0].Equals("$origin", StringComparison.InvariantCultureIgnoreCase))
{
origin = DomainName.ParseFromMasterfile(parts[1]);
}
if (parts[0].Equals("$ttl", StringComparison.InvariantCultureIgnoreCase))
{
ttl = Int32.Parse(parts[1]);
}
if (parts[0].Equals("$include", StringComparison.InvariantCultureIgnoreCase))
{
FileStream fileStream = reader.BaseStream as FileStream;
if (fileStream == null)
throw new NotSupportedException("Includes only supported when loading files");
// ReSharper disable once replacedignNullToNotNullAttribute
string path = Path.Combine(new FileInfo(fileStream.Name).DirectoryName, parts[1]);
DomainName includeOrigin = (parts.Length > 2) ? DomainName.ParseFromMasterfile(parts[2]) : origin;
using (StreamReader includeReader = new StreamReader(path))
{
records.AddRange(ParseRecords(includeReader, includeOrigin, ttl, lastRecord));
}
}
else
{
string domainString;
RecordType recordType;
RecordClreplaced recordClreplaced;
int recordTtl;
string[] rrData;
if (Int32.TryParse(parts[0], out recordTtl))
{
// no domain, starts with ttl
if (RecordClreplacedHelper.TryParseShortString(parts[1], out recordClreplaced, false))
{
// second is record clreplaced
domainString = null;
recordType = RecordTypeHelper.ParseShortString(parts[2]);
rrData = parts.Skip(3).ToArray();
}
else
{
// no record clreplaced
domainString = null;
recordClreplaced = RecordClreplaced.Invalid;
recordType = RecordTypeHelper.ParseShortString(parts[1]);
rrData = parts.Skip(2).ToArray();
}
}
else if (RecordClreplacedHelper.TryParseShortString(parts[0], out recordClreplaced, false))
{
// no domain, starts with record clreplaced
if (Int32.TryParse(parts[1], out recordTtl))
{
// second is ttl
domainString = null;
recordType = RecordTypeHelper.ParseShortString(parts[2]);
rrData = parts.Skip(3).ToArray();
}
else
{
// no ttl
recordTtl = 0;
domainString = null;
recordType = RecordTypeHelper.ParseShortString(parts[1]);
rrData = parts.Skip(2).ToArray();
}
}
else if (RecordTypeHelper.TryParseShortString(parts[0], out recordType))
{
// no domain, start with record type
recordTtl = 0;
recordClreplaced = RecordClreplaced.Invalid;
domainString = null;
rrData = parts.Skip(2).ToArray();
}
else
{
domainString = parts[0];
if (Int32.TryParse(parts[1], out recordTtl))
{
// domain, second is ttl
if (RecordClreplacedHelper.TryParseShortString(parts[2], out recordClreplaced, false))
{
// third is record clreplaced
recordType = RecordTypeHelper.ParseShortString(parts[3]);
rrData = parts.Skip(4).ToArray();
}
else
{
// no record clreplaced
recordClreplaced = RecordClreplaced.Invalid;
recordType = RecordTypeHelper.ParseShortString(parts[2]);
rrData = parts.Skip(3).ToArray();
}
}
else if (RecordClreplacedHelper.TryParseShortString(parts[1], out recordClreplaced, false))
{
// domain, second is record clreplaced
if (Int32.TryParse(parts[2], out recordTtl))
{
// third is ttl
recordType = RecordTypeHelper.ParseShortString(parts[3]);
rrData = parts.Skip(4).ToArray();
}
else
{
// no ttl
recordTtl = 0;
recordType = RecordTypeHelper.ParseShortString(parts[2]);
rrData = parts.Skip(3).ToArray();
}
}
else
{
// domain with record type
recordType = RecordTypeHelper.ParseShortString(parts[1]);
recordTtl = 0;
recordClreplaced = RecordClreplaced.Invalid;
rrData = parts.Skip(2).ToArray();
}
}
DomainName domain;
if (String.IsNullOrEmpty(domainString))
{
domain = lastRecord.Name;
}
else if (domainString == "@")
{
domain = origin;
}
else if (domainString.EndsWith("."))
{
domain = DomainName.ParseFromMasterfile(domainString);
}
else
{
domain = DomainName.ParseFromMasterfile(domainString) + origin;
}
if (recordClreplaced == RecordClreplaced.Invalid)
{
recordClreplaced = lastRecord.RecordClreplaced;
}
if (recordType == RecordType.Invalid)
{
recordType = lastRecord.RecordType;
}
if (recordTtl == 0)
{
recordTtl = ttl;
}
else
{
ttl = recordTtl;
}
lastRecord = DnsRecordBase.Create(recordType);
lastRecord.RecordType = recordType;
lastRecord.Name = domain;
lastRecord.RecordClreplaced = recordClreplaced;
lastRecord.TimeToLive = recordTtl;
if ((rrData.Length > 0) && (rrData[0] == @"\#"))
{
lastRecord.ParseUnknownRecordData(rrData);
}
else
{
lastRecord.ParseRecordData(origin, rrData);
}
records.Add(lastRecord);
}
}
}
return records;
}
19
Source : CertRecord.cs
with Apache License 2.0
from alexreinert
with Apache License 2.0
from alexreinert
internal override void ParseRecordData(DomainName origin, string[] stringRepresentation)
{
if (stringRepresentation.Length < 4)
throw new FormatException();
Type = (CertType) UInt16.Parse(stringRepresentation[0]);
KeyTag = UInt16.Parse(stringRepresentation[1]);
Algorithm = (DnsSecAlgorithm) Byte.Parse(stringRepresentation[2]);
Certificate = String.Join(String.Empty, stringRepresentation.Skip(3)).FromBase64String();
}
19
Source : HipRecord.cs
with Apache License 2.0
from alexreinert
with Apache License 2.0
from alexreinert
internal override void ParseRecordData(DomainName origin, string[] stringRepresentation)
{
if (stringRepresentation.Length < 3)
throw new FormatException();
Algorithm = (IpSecKeyRecord.IpSecAlgorithm) Byte.Parse(stringRepresentation[0]);
Hit = stringRepresentation[1].FromBase16String();
PublicKey = stringRepresentation[2].FromBase64String();
RendezvousServers = stringRepresentation.Skip(3).Select(x => ParseDomainName(origin, x)).ToList();
}
19
Source : TlsaRecord.cs
with Apache License 2.0
from alexreinert
with Apache License 2.0
from alexreinert
internal override void ParseRecordData(DomainName origin, string[] stringRepresentation)
{
if (stringRepresentation.Length < 4)
throw new FormatException();
CertificateUsage = (TlsaCertificateUsage) Byte.Parse(stringRepresentation[0]);
Selector = (TlsaSelector) Byte.Parse(stringRepresentation[1]);
MatchingType = (TlsaMatchingType) Byte.Parse(stringRepresentation[2]);
CertificatereplacedociationData = String.Join(String.Empty, stringRepresentation.Skip(3)).FromBase16String();
}
19
Source : App.cs
with Apache License 2.0
from alexyakunin
with Apache License 2.0
from alexyakunin
public void Run(Options options)
{
// Applying options
if (!string.IsNullOrEmpty(options.GCLatencyMode))
GCSettings.LatencyMode = Enum.Parse<GCLatencyMode>(options.GCLatencyMode);
if (options.Duration.HasValue)
BurnTester.DefaultDuration = TimeSpan.FromSeconds(options.Duration.Value);
BurnTester.DefaultMaxSize = ArgumentHelper.ParseRelativeValue(
options.MaxSize, BurnTester.DefaultMaxSize, true);
ParallelRunner.ThreadCount = (int) ArgumentHelper.ParseRelativeValue(
options.ThreadCount, ParallelRunner.ThreadCount, true);
var tests = options.Tests?.ToLowerInvariant() ?? "";
var ramSizeGb = HardwareInfo.GetRamSize() ?? 4;
var staticSetSizeGb = 0;
if (!string.IsNullOrEmpty(options.StaticSetSize)) {
tests += "b";
staticSetSizeGb = (int) ArgumentHelper.ParseRelativeValue(options.StaticSetSize, ramSizeGb, true);
}
var outputMode = options.OutputMode ?? "f";
if (outputMode == "f") {
// Dumping environment info
Writer.AppendValue("Launch parameters", string.Join(" ", Environment.GetCommandLineArgs().Skip(1)));
using (Writer.Section("Software:")) {
Writer.AppendValue("Runtime", ".NET Core");
using (Writer.Indent()) {
Writer.AppendValue("Version", RuntimeInformation.FrameworkDescription);
Writer.AppendValue("GC mode", GCInfo.GetGCMode());
}
Writer.AppendValue("OS",
$"{RuntimeInformation.OSDescription.Trim()} ({RuntimeInformation.OSArchitecture})");
}
using (Writer.Section("Hardware:")) {
var coreCountAddon = ParallelRunner.ThreadCount != Environment.ProcessorCount
? $", {ParallelRunner.ThreadCount} used by test"
: "";
Writer.AppendValue("CPU", HardwareInfo.GetCpuModelName());
Writer.AppendValue("CPU core count", $"{Environment.ProcessorCount}{coreCountAddon}");
Writer.AppendValue("RAM size", $"{ramSizeGb:N0} GB");
}
Writer.AppendLine();
}
RunWarmup();
if (tests == "") {
RunSpeedTest();
RunBurnTest("--- Stateless server (no static set) ---", 0);
RunBurnTest("--- Worker / typical server (static set = 20% RAM) ---", (long) (ramSizeGb * Sizes.GB / 5));
RunBurnTest("--- Caching / compute server (static set = 50% RAM) ---", (long) (ramSizeGb * Sizes.GB / 2));
return;
}
if (tests.Contains("a")) {
RunSpeedTest();
}
if (tests.Contains("b")) {
var replacedle = $"--- Static set = {staticSetSizeGb} GB ({staticSetSizeGb * 100.0 / ramSizeGb:0.##} % RAM) ---";
RunBurnTest(replacedle, (long) (staticSetSizeGb * Sizes.GB));
}
}
19
Source : JsonConfigurationProvider.cs
with MIT License
from aliencube
with MIT License
from aliencube
private static string RetrieveErrorContext(JsonReaderException e, IEnumerable<string> fileContent)
{
string errorLine = null;
if (e.LineNumber >= 2)
{
var errorContext = fileContent.Skip(e.LineNumber - 2).Take(2).ToList();
// Handle situations when the line number reported is out of bounds
if (errorContext.Count() >= 2)
{
errorLine = errorContext[0].Trim() + Environment.NewLine + errorContext[1].Trim();
}
}
if (string.IsNullOrEmpty(errorLine))
{
var possibleLineContent = fileContent.Skip(e.LineNumber - 1).FirstOrDefault();
errorLine = possibleLineContent ?? string.Empty;
}
return errorLine;
}
19
Source : MapServer.cs
with MIT License
from AliFlux
with MIT License
from AliFlux
Task Serve(IHttpContext context, Func<Task> next)
{
string prefix = context.Request.RequestParameters[0];
if (prefix == "tiles")
{
int z = Convert.ToInt32(context.Request.RequestParameters[1]);
int x = Convert.ToInt32(context.Request.RequestParameters[2]);
int y = Convert.ToInt32(context.Request.RequestParameters[3]);
y = (int)(Math.Pow(2, z) - y - 1);
return ServeTile(context, next, x, y, z);
}
else if (prefix == "glyphs")
{
var components = context.Request.RequestParameters
.Skip(1)
.Select(p => Uri.UnescapeDataString(p))
.ToArray();
var path = System.IO.Path.Combine(components);
return ServeGlyph(context, next, path);
}
else
{
context.Response = new HttpResponse(HttpResponseCode.NotFound, "404 Not Found.", null, true, null);
return Task.Factory.GetCompleted();
}
}
19
Source : SampleLauncher.cs
with MIT License
from AliakseiFutryn
with MIT License
from AliakseiFutryn
static void CheckSingletonInMulreplacedhreadingMode()
{
Thread[] threads = new Thread[ThreadsCount];
Meeting[] meetings = new Meeting[ThreadsCount];
EventWaitHandle threadsFinishedEvent = new EventWaitHandle(false, EventResetMode.AutoReset);
using (Barrier startBarrier = new Barrier(ThreadsCount), finishBarrier = new Barrier(ThreadsCount, barrier => threadsFinishedEvent.Set()))
{
for (int index = 0; index < ThreadsCount; index++)
{
threads[index] = new Thread(threadIndex =>
{
// Synchronizes all threads before start.
startBarrier.SignalAndWait();
try
{
int currentIndex = (int)threadIndex;
meetings[currentIndex] = currentIndex >= ThreadsCount / 2 ? DoubleCheckedSingleton<Meeting>.Instance : LazySingleton<Meeting>.Instance;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
// Synhronizes all threads before finish.
finishBarrier.SignalAndWait();
}
});
threads[index].Start(index);
}
threadsFinishedEvent.WaitOne();
Meeting lazySingletonInstance = LazySingleton<Meeting>.Instance;
Meeting doubleCheckedSingletonInstance = DoubleCheckedSingleton<Meeting>.Instance;
// There is an operation which is responsible for increasing some value of nearly
// created instances and then it should be compared with all other instances which
// were created in different threads.
lazySingletonInstance.ParticipantsCount++;
doubleCheckedSingletonInstance.ParticipantsCount++;
Console.WriteLine("The participants count are equal in both instances of singleton: {0}", meetings.Take(ThreadsCount / 2).All(m => m.ParticipantsCount == lazySingletonInstance.ParticipantsCount));
Console.WriteLine("The participants count are equal in both instances of singleton: {0}", meetings.Skip(ThreadsCount / 2).All(m => m.ParticipantsCount == lazySingletonInstance.ParticipantsCount));
}
}
19
Source : SkiaCanvas.cs
with MIT License
from AliFlux
with MIT License
from AliFlux
SKPath getPathFromGeometry(List<Point> geometry)
{
SKPath path = new SKPath
{
FillType = SKPathFillType.EvenOdd,
};
var firstPoint = geometry[0];
path.MoveTo((float)firstPoint.X, (float)firstPoint.Y);
foreach (var point in geometry.Skip(1))
{
var lastPoint = path.LastPoint;
path.LineTo((float)point.X, (float)point.Y);
}
return path;
}
19
Source : Style.cs
with MIT License
from AliFlux
with MIT License
from AliFlux
private bool validateUsingFilter(object[] filterArray, Dictionary<string, object> attributes)
{
if (filterArray.Count() == 0)
{
}
var operation = filterArray[0] as string;
bool result;
if (operation == "all")
{
foreach (object[] subFilter in filterArray.Skip(1))
{
if (!validateUsingFilter(subFilter, attributes))
{
return false;
}
}
return true;
}
else if (operation == "any")
{
foreach (object[] subFilter in filterArray.Skip(1))
{
if (validateUsingFilter(subFilter, attributes))
{
return true;
}
}
return false;
}
else if (operation == "none")
{
result = false;
foreach (object[] subFilter in filterArray.Skip(1))
{
if (validateUsingFilter(subFilter, attributes))
{
result = true;
}
}
return !result;
}
switch (operation)
{
case "==":
case "!=":
case ">":
case ">=":
case "<":
case "<=":
var key = (string)filterArray[1];
if (operation == "==")
{
if (!attributes.ContainsKey(key))
{
return false;
}
}
else
{
// special case, comparing inequality with non existent attribute
if (!attributes.ContainsKey(key))
{
return true;
}
}
if (!(attributes[key] is IComparable))
{
throw new NotImplementedException("Comparing colors probably");
return false;
}
var valueA = (IComparable)attributes[key];
var valueB = getValue(filterArray[2], attributes);
if (isNumber(valueA) && isNumber(valueB))
{
valueA = Convert.ToDouble(valueA);
valueB = Convert.ToDouble(valueB);
}
if (key is string)
{
if (key == "capital")
{
}
}
if (valueA.GetType() != valueB.GetType())
{
return false;
}
var comparison = valueA.CompareTo(valueB);
if (operation == "==")
{
return comparison == 0;
}
else if (operation == "!=")
{
return comparison != 0;
}
else if (operation == ">")
{
return comparison > 0;
}
else if (operation == "<")
{
return comparison < 0;
}
else if (operation == ">=")
{
return comparison >= 0;
}
else if (operation == "<=")
{
return comparison <= 0;
}
break;
}
if (operation == "has")
{
return attributes.ContainsKey(filterArray[1] as string);
}
else if (operation == "!has")
{
return !attributes.ContainsKey(filterArray[1] as string);
}
if (operation == "in")
{
var key = filterArray[1] as string;
if (!attributes.ContainsKey(key))
{
return false;
}
var value = attributes[key];
foreach (object item in filterArray.Skip(2))
{
if (getValue(item, attributes).Equals(value))
{
return true;
}
}
return false;
}
else if (operation == "!in")
{
var key = filterArray[1] as string;
if (!attributes.ContainsKey(key))
{
return true;
}
var value = attributes[key];
foreach (object item in filterArray.Skip(2))
{
if (getValue(item, attributes).Equals(value))
{
return false;
}
}
return true;
}
return false;
}
19
Source : MaderatorActionVisibilityConverter.cs
with MIT License
from aliprogrammer69
with MIT License
from aliprogrammer69
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) {
var items = values.OfType<bool>();
if (!items.Any())
return Visibility.Visible;
if (items.First() == false)
return Visibility.Collapsed;
foreach (var item in items.Skip(1))
if (item)
return Visibility.Collapsed;
return Visibility.Visible;
}
19
Source : GridifyExtensionsShould.cs
with MIT License
from alirezanet
with MIT License
from alirezanet
[Fact]
public void ApplyEverything_EmptyGridifyQuery()
{
var gq = new GridifyQuery();
var actual = _fakeRepository.AsQueryable()
.ApplyFilteringOrderingPaging(gq)
.ToList();
var expected = _fakeRepository.Skip(0).Take(GridifyExtensions.DefaultPageSize).ToList();
replacedert.Equal(expected.Count, actual.Count);
replacedert.Equal(expected, actual);
replacedert.True(actual.Any());
}
19
Source : GridifyExtensions.cs
with MIT License
from alirezanet
with MIT License
from alirezanet
public static IQueryable<T> ApplyPaging<T>(this IQueryable<T> query, IGridifyPagination? gridifyPagination)
{
if (gridifyPagination == null) return query;
gridifyPagination = gridifyPagination.FixPagingData();
return query.Skip((gridifyPagination.Page - 1) * gridifyPagination.PageSize).Take(gridifyPagination.PageSize);
}
19
Source : GridifyExtensions.cs
with MIT License
from alirezanet
with MIT License
from alirezanet
public static IQueryable<IGrouping<T2, T>> ApplyPaging<T, T2>(this IQueryable<IGrouping<T2, T>> query, IGridifyPagination? gridifyPagination)
{
if (gridifyPagination == null) return query;
gridifyPagination = gridifyPagination.FixPagingData();
return query.Skip((gridifyPagination.Page - 1) * gridifyPagination.PageSize).Take(gridifyPagination.PageSize);
}
19
Source : GridifyExtensionsShould.cs
with MIT License
from alirezanet
with MIT License
from alirezanet
[Theory]
[InlineData(1, 5)]
[InlineData(2, 5)]
[InlineData(1, 10)]
[InlineData(4, 3)]
[InlineData(5, 3)]
[InlineData(1, 15)]
[InlineData(20, 10)]
public void ApplyPaging_UsingCustomValues(int page, int pageSize)
{
var gq = new GridifyQuery { Page = page, PageSize = pageSize };
var actual = _fakeRepository.AsQueryable()
.ApplyPaging(gq)
.ToList();
var skip = (page - 1) * pageSize;
var expected = _fakeRepository.Skip(skip)
.Take(pageSize).ToList();
replacedert.Equal(expected.Count, actual.Count);
replacedert.Equal(expected, actual);
}
19
Source : Splitting.cs
with MIT License
from Alkl58
with MIT License
from Alkl58
private static void PySceneDetectParse()
{
// Reads first line of the csv file generated by pyscenedetect
string line = File.ReadLines(Path.Combine(Global.temp_path, Global.temp_path_folder, Global.temp_path_folder + "-Scenes.csv")).First();
// Splits the line after "," and skips the first line, then adds the result to list
List<string> scenes = line.Split(',').Skip(1).ToList<string>();
// Temporary value used for creating the ffmpeg command line
string previousScene = "00:00:00.000";
// Clears the Args List to avoid conflicts in Batch Encode Mode
FFmpegArgs.Clear();
// Iterates over the list of time codes and creates the args for ffmpeg
foreach (string sc in scenes)
{
FFmpegArgs.Add("-ss " + previousScene + " -to " + sc);
previousScene = sc;
}
// Has to be last, to "tell" ffmpeg to seek / encode until end of video
FFmpegArgs.Add("-ss " + previousScene);
// Writes splitting arguments to text file
foreach (string lineArg in FFmpegArgs)
{
using (StreamWriter sw = File.AppendText(Path.Combine(Global.temp_path, Global.temp_path_folder, "splits.txt")))
{
sw.WriteLine(lineArg);
sw.Close();
}
}
if (File.Exists(Path.Combine(Global.temp_path, Global.temp_path_folder, "splits.txt")))
{
Global.Video_Chunks = File.ReadAllLines(Path.Combine(Global.temp_path, Global.temp_path_folder, "splits.txt")); // Reads the split file for VideoEncode() function
}
}
19
Source : IterationManager.cs
with MIT License
from alkampfergit
with MIT License
from alkampfergit
public IEnumerable<IterationInfo> GetAllIterationsForTeamProject(string teamProjectName)
{
var project = _connectionManager.GetTeamProject(teamProjectName);
NodeInfo[] nodes = _connectionManager
.CommonStructureService.ListStructures(
project.Uri.AbsoluteUri);
var iterationRootNode = nodes.Single(n => n.Name.Equals("iteration", StringComparison.OrdinalIgnoreCase));
List<IterationInfo> retValue = new List<IterationInfo>();
var itRoot = _connectionManager
.CommonStructureService
.GetNodesXml(new string[] { iterationRootNode.Uri }, true);
var rootNode = itRoot.FirstChild as XmlElement;
var xml = rootNode.OuterXml;
var element = XElement.Parse(xml);
var xmlNodes = element.Descendants("Node");
foreach (var node in xmlNodes)
{
var path = node.Attribute("Path").Value.Trim('\\', '/');
var splitted = path.Split('\\');
var normalizedPath = splitted[0] + "\\" + String.Join("\\", splitted.Skip(2));
retValue.Add(new IterationInfo()
{
Name = node.Attribute("Name").Value.Trim('\\', '/'),
Path = normalizedPath,
StartDate = node.Attribute("StartDate")?.Value,
EndDate = node.Attribute("FinishDate")?.Value,
}) ;
}
return retValue;
}
19
Source : WorkItemManger.cs
with MIT License
from alkampfergit
with MIT License
from alkampfergit
public List<LinkedWorkItem> ExecuteHierarchicQuery(string wiqlQuery, String[] types)
{
if (types.Length == 0)
return new List<LinkedWorkItem>();
var queryResult = ExecuteQuery(wiqlQuery);
var resultList = queryResult
.Where(wi => wi.Type.Name.Equals(types[0], StringComparison.OrdinalIgnoreCase))
.Select(wi => new LinkedWorkItem(wi))
.ToList();
//ok we need to start crawling up the hierarcy up to the final type.
IEnumerable<LinkedWorkItem> actualList = resultList;
foreach (var type in types.Skip(1))
{
var allParentId = actualList
.Where(wi => wi.ParentId.HasValue)
.Select(wi => wi.ParentId.Value);
//now we need to query all the parent, TODO: execute in block and not with a single query.
var listOfParentWorkItems = LoadListOfWorkItems(allParentId)
.Select(wi => new LinkedWorkItem(wi))
.ToList();
//now create a dictionary to simplify the lookup
var actualDictionaryList = listOfParentWorkItems.ToDictionary(wi => wi.WorkItem.Id);
foreach (var item in actualList.Where(wi => wi.ParentId.HasValue))
{
if (actualDictionaryList.TryGetValue(item.ParentId.Value, out var parentWorkItem))
{
item.Parent = parentWorkItem;
}
}
actualList = listOfParentWorkItems;
}
return resultList;
}
19
Source : WordManipulator.cs
with MIT License
from alkampfergit
with MIT License
from alkampfergit
public WordManipulator FillTable(
Boolean skipHeader,
IEnumerable<IEnumerable<Object>> data)
{
var table = _doreplacedent.MainDoreplacedentPart.Doreplacedent.Body
.Descendants<Table>()
.FirstOrDefault();
if (table != null)
{
//remove every rows but first save the first two rows for the formatting.
var rows = table.Elements<TableRow>().ToList();
Int32 skip = skipHeader ? 1 : 0;
foreach (var row in rows.Skip(skip))
{
row.Remove();
}
Boolean isFirstRow = true;
foreach (var dataRow in data)
{
TableRow row = null;
TableRow templateRow;
//template rows depends from skipping or not skipping the header template.
if (skipHeader)
{
//header is skipped, take the second row if present.
templateRow = rows.Skip(1).FirstOrDefault();
}
else
{
//we do not want to skip header
var rowToSkip = isFirstRow || rows.Count < 2 ? 0 : 1;
templateRow = rows.Skip(rowToSkip).FirstOrDefault();
}
if (templateRow == null)
{
row = new TableRow();
foreach (var dataCell in dataRow)
{
var cell = new TableCell();
// Specify the table cell content.
cell.Append(new Paragraph(new Run(new Text(dataCell.ToString()))));
// Append the table cell to the table row.
row.Append(cell);
}
}
else
{
row = (TableRow)templateRow.CloneNode(true);
//Grab all the run style of first row to copy on all subsequence cell.
var runs = templateRow.Descendants<TableCell>()
.Select(_ => _.Descendants<Run>().FirstOrDefault())
.ToList();
var cells = row.Descendants<TableCell>().ToList();
Int32 cellIndex = 0;
foreach (var dataCell in dataRow)
{
if (cellIndex < cells.Count)
{
var cell = cells[cellIndex];
var run = runs[cellIndex];
// Specify the table cell content.
Run runToAdd = new Run(new Text(dataCell.ToString()));
CopyPropertiesFromRun(run, runToAdd);
//we can have two distinct situation, we have or we do not have paragraph
var paragraph = cell.Descendants<Paragraph>().FirstOrDefault();
if (paragraph == null)
{
cell.Append(new Paragraph(runToAdd));
}
else
{
paragraph.RemoveAllChildren<Run>();
paragraph.Append(runToAdd);
}
}
cellIndex++;
}
}
table.Append(row);
isFirstRow = false;
}
}
return this;
}
19
Source : WordManipulator.cs
with MIT License
from alkampfergit
with MIT License
from alkampfergit
public WordManipulator FillCompositeTable(
Boolean skipHeader,
IEnumerable<Dictionary<String, Object>> data)
{
var table = _doreplacedent.MainDoreplacedentPart.Doreplacedent.Body
.Descendants<Table>()
.FirstOrDefault();
if (table != null)
{
//remove every rows but keep formatting row.
var rows = table.Elements<TableRow>().ToList();
Int32 skip = skipHeader ? 1 : 0;
TableRow templateRow = rows.Skip(skip).FirstOrDefault();
table.RemoveChild(templateRow);
if (templateRow != null)
{
foreach (var dataRow in data)
{
var row = (TableRow)templateRow.CloneNode(true);
//Grab all the run style of first row to copy on all subsequence cell.
var paragraph = row.Descendants<Paragraph>().ToList();
var realReplaceList = dataRow.ToDictionary(dr => CreateSubsreplacedutionTokenFromName(dr.Key), dr => ManipulateRowDataForTables(dr.Value));
SubsreplaceduteInParagraph(realReplaceList, paragraph);
table.Append(row);
//Sometimes in case of word corruption, it could be nice to dump all intermediate
//version of the doc.
//_doreplacedent.SaveAs($@"C:\temp\workitem_{count++}_{dataRow["Id"]}.docx");
}
}
}
return this;
}
19
Source : WordManipulator.cs
with MIT License
from alkampfergit
with MIT License
from alkampfergit
public WordManipulator FillTableWithSingleFieldWorkItems(
Boolean skipHeader,
IEnumerable<WorkItem> workItems)
{
var table = _doreplacedent.MainDoreplacedentPart.Doreplacedent.Body
.Descendants<Table>()
.FirstOrDefault();
if (table != null)
{
//remove every rows but first save the first two rows for the formatting.
var rows = table.Elements<TableRow>().ToList();
Int32 skip = skipHeader ? 1 : 0;
var rowWithField = rows.Skip(skip).First();
List<List<String>> workItemCellsData = new List<List<string>>();
List<String> cellFields = new List<string>();
var cells = rowWithField.Descendants<TableCell>().ToList();
foreach (var dataCell in cells)
{
//ok for each cell we need to grab the field name
//in this first version we support only a field for each column
var dataCellText = dataCell.InnerText;
var match = Regex.Match(dataCellText, @"\{\{(?<name>.*?)\}\}");
if (match.Success)
{
cellFields.Add(match.Groups["name"].Value);
}
else
{
cellFields.Add("");
}
}
foreach (var workItem in workItems)
{
List<String> row = new List<string>();
var properties = workItem.CreateDictionaryFromWorkItem();
foreach (var field in cellFields)
{
if (properties.TryGetValue(field, out var value))
{
row.Add(value as String);
}
else
{
row.Add(String.Empty);
}
}
workItemCellsData.Add(row);
}
FillTable(true, workItemCellsData);
}
return this;
}
19
Source : AutomataDictionary.cs
with Apache License 2.0
from allenai
with Apache License 2.0
from allenai
private static void EmitSearchNextCore(ILGenerator il, LocalBuilder bytesSpan, LocalBuilder key, Action<KeyValuePair<string, int>> onFound, Action onNotFound, AutomataNode[] nexts, int count)
{
if (count < 4)
{
// linear-search
AutomataNode[] valueExists = nexts.Take(count).Where(x => x.Value != -1).ToArray();
AutomataNode[] childrenExists = nexts.Take(count).Where(x => x.HasChildren).ToArray();
Label gotoSearchNext = il.DefineLabel();
Label gotoNotFound = il.DefineLabel();
{
// bytesSpan.Length
il.EmitLdloca(bytesSpan);
il.EmitCall(typeof(ReadOnlySpan<byte>).GetRuntimeProperty(nameof(ReadOnlySpan<byte>.Length)).GetMethod);
if (childrenExists.Length != 0 && valueExists.Length == 0)
{
il.Emit(OpCodes.Brfalse, gotoNotFound); // if(bytesSpan.Length == 0)
}
else
{
il.Emit(OpCodes.Brtrue, gotoSearchNext); // if(bytesSpan.Length != 0)
}
}
{
Label[] ifValueNexts = Enumerable.Range(0, Math.Max(valueExists.Length - 1, 0)).Select(_ => il.DefineLabel()).ToArray();
for (int i = 0; i < valueExists.Length; i++)
{
Label notFoundLabel = il.DefineLabel();
if (i != 0)
{
il.MarkLabel(ifValueNexts[i - 1]);
}
il.EmitLdloc(key);
il.EmitULong(valueExists[i].Key);
il.Emit(OpCodes.Bne_Un, notFoundLabel);
// found
onFound(new KeyValuePair<string, int>(valueExists[i].OriginalKey, valueExists[i].Value));
// notfound
il.MarkLabel(notFoundLabel);
if (i != valueExists.Length - 1)
{
il.Emit(OpCodes.Br, ifValueNexts[i]);
}
else
{
onNotFound();
}
}
}
il.MarkLabel(gotoSearchNext);
Label[] ifRecNext = Enumerable.Range(0, Math.Max(childrenExists.Length - 1, 0)).Select(_ => il.DefineLabel()).ToArray();
for (int i = 0; i < childrenExists.Length; i++)
{
Label notFoundLabel = il.DefineLabel();
if (i != 0)
{
il.MarkLabel(ifRecNext[i - 1]);
}
il.EmitLdloc(key);
il.EmitULong(childrenExists[i].Key);
il.Emit(OpCodes.Bne_Un, notFoundLabel);
// found
childrenExists[i].EmitSearchNext(il, bytesSpan, key, onFound, onNotFound);
// notfound
il.MarkLabel(notFoundLabel);
if (i != childrenExists.Length - 1)
{
il.Emit(OpCodes.Br, ifRecNext[i]);
}
else
{
onNotFound();
}
}
il.MarkLabel(gotoNotFound);
onNotFound();
}
else
{
// binary-search
var midline = count / 2;
var mid = nexts[midline].Key;
AutomataNode[] l = nexts.Take(count).Take(midline).ToArray();
AutomataNode[] r = nexts.Take(count).Skip(midline).ToArray();
Label gotoRight = il.DefineLabel();
// if(key < mid)
il.EmitLdloc(key);
il.EmitULong(mid);
il.Emit(OpCodes.Bge_Un, gotoRight);
EmitSearchNextCore(il, bytesSpan, key, onFound, onNotFound, l, l.Length);
// else
il.MarkLabel(gotoRight);
EmitSearchNextCore(il, bytesSpan, key, onFound, onNotFound, r, r.Length);
}
}
19
Source : Program.cs
with GNU Lesser General Public License v3.0
from Alois-xx
with GNU Lesser General Public License v3.0
from Alois-xx
static string GetQuotedArgs()
{
string args = "";
string currArg;
foreach (var arg in Environment.GetCommandLineArgs().Skip(1))
{
currArg = arg;
if (currArg.Contains(" "))
{
currArg = "\"" + currArg + "\"";
}
args += currArg + " ";
}
return args;
}
19
Source : IOPath.cs
with Apache License 2.0
from aloneguid
with Apache License 2.0
from aloneguid
public static string RelativeTo(string path, string root)
{
string[] pathParts = Split(path);
string[] rootParts = Split(root);
if(pathParts == null || rootParts == null || rootParts.Length >= pathParts.Length)
return RootFolderPath;
// make sure that root parts are the same as path parts
for(int i = 0; i < rootParts.Length; i++)
{
if(rootParts[i] != pathParts[i])
return RootFolderPath;
}
return Combine(pathParts.Skip(rootParts.Length));
}
19
Source : IOPath.cs
with Apache License 2.0
from aloneguid
with Apache License 2.0
from aloneguid
public static string RemoveRoot(string path)
{
string[] parts = Split(path);
if(parts.Length == 1)
return path;
return Combine(parts.Skip(1));
}
19
Source : TypeExtensions.cs
with MIT License
from AlphaYu
with MIT License
from AlphaYu
private static string ReplaceGenericParametersInGenericTypeName(this string typeName, Type type)
{
var genericArguments = type.GetTypeInfo().GetAllGenericArguments();
const string regexForGenericArguments = @"`[1-9]\d*";
var rgx = new Regex(regexForGenericArguments);
typeName = rgx.Replace(typeName, match =>
{
var currentGenericArgumentNumbers = int.Parse(match.Value.Substring(1));
var currentArguments = string.Join(",", genericArguments.Take(currentGenericArgumentNumbers).Select(ToGenericTypeString));
genericArguments = genericArguments.Skip(currentGenericArgumentNumbers).ToArray();
return string.Concat("<", currentArguments, ">");
});
return typeName;
}
See More Examples