hexsha
stringlengths
40
40
size
int64
30
1.05M
ext
stringclasses
24 values
lang
stringclasses
5 values
max_stars_repo_path
stringlengths
4
355
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
sequence
max_stars_count
float64
1
208k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
355
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
sequence
max_issues_count
float64
1
77k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
355
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
sequence
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
30
1.05M
avg_line_length
float64
2.67
1.04M
max_line_length
int64
9
1.04M
alphanum_fraction
float64
0.01
1
1e043b2f10cc664834fe820a974eb1711b7d3b14
8,259
cs
C#
src/contrib/Analyzers/AR/ArabicAnalyzer.cs
danipen/lucene.net
205912d9a763df16f503279eb36a453f7c884dc2
[ "Apache-2.0" ]
2
2017-02-23T15:16:08.000Z
2021-11-24T13:44:52.000Z
src/contrib/Analyzers/AR/ArabicAnalyzer.cs
danipen/lucene.net
205912d9a763df16f503279eb36a453f7c884dc2
[ "Apache-2.0" ]
5
2019-08-07T09:05:30.000Z
2021-04-13T07:38:20.000Z
src/contrib/Analyzers/AR/ArabicAnalyzer.cs
danipen/lucene.net
205912d9a763df16f503279eb36a453f7c884dc2
[ "Apache-2.0" ]
9
2017-04-12T19:01:40.000Z
2021-02-18T16:35:13.000Z
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.IO; using System.Collections; using System.Linq; using Lucene.Net.Analysis; using Version = Lucene.Net.Util.Version; using Lucene.Net.Support.Compatibility; namespace Lucene.Net.Analysis.AR { /* * <see cref="Analyzer"/> for Arabic. * <p/> * This analyzer implements light-stemming as specified by: * <i> * Light Stemming for Arabic Information Retrieval * </i> * http://www.mtholyoke.edu/~lballest/Pubs/arab_stem05.pdf * <p/> * The analysis package contains three primary components: * <ul> * <li><see cref="ArabicNormalizationFilter"/>: Arabic orthographic normalization.</li> * <li><see cref="ArabicStemFilter"/>: Arabic light stemming</li> * <li>Arabic stop words file: a set of default Arabic stop words.</li> * </ul> * */ public class ArabicAnalyzer : Analyzer { /* * File containing default Arabic stopwords. * * Default stopword list is from http://members.unine.ch/jacques.savoy/clef/index.html * The stopword list is BSD-Licensed. */ public static string DEFAULT_STOPWORD_FILE = "ArabicStopWords.txt"; /* * Contains the stopwords used with the StopFilter. */ private readonly ISet<string> stoptable; /*<summary> * The comment character in the stopwords file. All lines prefixed with this will be ignored * </summary> */ [Obsolete("Use WordListLoader.GetWordSet(FileInfo, string) directly")] public static string STOPWORDS_COMMENT = "#"; /// <summary> /// Returns an unmodifiable instance of the default stop-words set /// </summary> /// <returns>Returns an unmodifiable instance of the default stop-words set</returns> public static ISet<string> GetDefaultStopSet() { return DefaultSetHolder.DEFAULT_STOP_SET; } private static class DefaultSetHolder { internal static ISet<string> DEFAULT_STOP_SET; static DefaultSetHolder() { try { DEFAULT_STOP_SET = LoadDefaultStopWordSet(); } catch (System.IO.IOException) { // default set should always be present as it is part of the // distribution (JAR) throw new Exception("Unable to load default stopword set"); } } internal static ISet<string> LoadDefaultStopWordSet() { using (StreamReader reader = new StreamReader(System.Reflection.Assembly.GetAssembly(typeof(ArabicAnalyzer)).GetManifestResourceStream("Lucene.Net.Analysis.AR." + DEFAULT_STOPWORD_FILE))) { return CharArraySet.UnmodifiableSet(CharArraySet.Copy(WordlistLoader.GetWordSet(reader, STOPWORDS_COMMENT))); } } } private Version matchVersion; /* * Builds an analyzer with the default stop words: <see cref="DEFAULT_STOPWORD_FILE"/>. */ public ArabicAnalyzer(Version matchVersion) : this(matchVersion, DefaultSetHolder.DEFAULT_STOP_SET) { } /// <summary> /// Builds an analyzer with the given stop words. /// </summary> /// <param name="matchVersion">Lucene compatibility version</param> /// <param name="stopwords">a stopword set</param> public ArabicAnalyzer(Version matchVersion, ISet<string> stopwords) { stoptable = CharArraySet.UnmodifiableSet(CharArraySet.Copy(stopwords)); this.matchVersion = matchVersion; } /* * Builds an analyzer with the given stop words. */ [Obsolete("Use ArabicAnalyzer(Version, Set) instead")] public ArabicAnalyzer(Version matchVersion, params string[] stopwords) : this(matchVersion, StopFilter.MakeStopSet(stopwords)) { } /* * Builds an analyzer with the given stop words. */ [Obsolete("Use ArabicAnalyzer(Version, Set) instead")] public ArabicAnalyzer(Version matchVersion, IDictionary<string, string> stopwords) : this(matchVersion, stopwords.Keys.ToArray()) { } /* * Builds an analyzer with the given stop words. Lines can be commented out using <see cref="STOPWORDS_COMMENT"/> */ public ArabicAnalyzer(Version matchVersion, FileInfo stopwords) : this(matchVersion, WordlistLoader.GetWordSet(stopwords, STOPWORDS_COMMENT)) { } /* * Creates a <see cref="TokenStream"/> which tokenizes all the text in the provided <see cref="TextReader"/>. * * <returns>A <see cref="TokenStream"/> built from an <see cref="ArabicLetterTokenizer"/> filtered with * <see cref="LowerCaseFilter"/>, <see cref="StopFilter"/>, <see cref="ArabicNormalizationFilter"/> * and <see cref="ArabicStemFilter"/>.</returns> */ public override TokenStream TokenStream(string fieldName, TextReader reader) { TokenStream result = new ArabicLetterTokenizer(reader); result = new LowerCaseFilter(result); // the order here is important: the stopword list is not normalized! result = new StopFilter(StopFilter.GetEnablePositionIncrementsVersionDefault(matchVersion), result, stoptable); result = new ArabicNormalizationFilter(result); result = new ArabicStemFilter(result); return result; } private class SavedStreams { internal Tokenizer Source; internal TokenStream Result; }; /* * Returns a (possibly reused) <see cref="TokenStream"/> which tokenizes all the text * in the provided <see cref="TextReader"/>. * * <returns>A <see cref="TokenStream"/> built from an <see cref="ArabicLetterTokenizer"/> filtered with * <see cref="LowerCaseFilter"/>, <see cref="StopFilter"/>, <see cref="ArabicNormalizationFilter"/> * and <see cref="ArabicStemFilter"/>.</returns> */ public override TokenStream ReusableTokenStream(string fieldName, TextReader reader) { SavedStreams streams = (SavedStreams)PreviousTokenStream; if (streams == null) { streams = new SavedStreams(); streams.Source = new ArabicLetterTokenizer(reader); streams.Result = new LowerCaseFilter(streams.Source); // the order here is important: the stopword list is not normalized! streams.Result = new StopFilter(StopFilter.GetEnablePositionIncrementsVersionDefault(matchVersion), streams.Result, stoptable); streams.Result = new ArabicNormalizationFilter(streams.Result); streams.Result = new ArabicStemFilter(streams.Result); PreviousTokenStream = streams; } else { streams.Source.Reset(reader); } return streams.Result; } } }
39.898551
203
0.613028
1e05f0ee49dca31ccf81a088b02e7bed57088da7
2,309
cshtml
C#
WebUI/Views/Variables/Add.cshtml
adoconnection/AspNetDeploy
310ce15d31f002bf855805dd2a46f5e6c5c56738
[ "Apache-2.0" ]
11
2015-06-05T09:41:22.000Z
2019-09-04T07:04:34.000Z
WebUI/Views/Variables/Add.cshtml
adoconnection/AspNetDeploy
310ce15d31f002bf855805dd2a46f5e6c5c56738
[ "Apache-2.0" ]
null
null
null
WebUI/Views/Variables/Add.cshtml
adoconnection/AspNetDeploy
310ce15d31f002bf855805dd2a46f5e6c5c56738
[ "Apache-2.0" ]
1
2016-09-28T12:20:10.000Z
2016-09-28T12:20:10.000Z
@using Environment = AspNetDeploy.Model.Environment @model AspNetDeploy.WebUI.Models.VariableEditModel @{ ViewBag.Title = "Index"; ViewBag.PageClass = "variablesPage"; Layout = "~/Views/Shared/_Layout.cshtml"; Environment environment = this.ViewBag.Environment; } <div class="container"> <div>@Html.ActionLink("Назад", "Details", "Environments", new { id = environment.Id }, new {})</div> <h1>Add variable on @environment.Name</h1> <hr /> @using (Html.BeginForm("Save", "Variables", new { }, FormMethod.Post, new { Class = "form-horizontal" })) { @Html.AntiForgeryToken() @Html.HiddenFor( m => m.EnvironmentId) @Html.HiddenFor(m => m.MachineId) <div class="row"> <div class="col-md-12 "> <div class="form-group"> <label class="col-sm-2 control-label">Name</label> <div class="col-sm-10"> @Html.TextBoxFor(m => m.Name, new { Class = "form-control", placeholder = "Name" }) @Html.ValidationMessageFor(m => m.Name) </div> </div> <div class="form-group"> <label class="col-sm-2 control-label">Value</label> <div class="col-sm-10"> @Html.TextAreaFor(m => m.Value, new { Class = "form-control", placeholder = "", style="height:400px" }) @Html.ValidationMessageFor(m => m.Value) </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-2"> <div class="checkbox"> <label> @Html.CheckBoxFor(m => m.IsSensitive, new { }) Is sensitive @Html.ValidationMessageFor(m => m.IsSensitive) </label> </div> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-8"> <button type="submit" class="btn btn-default">Save</button> </div> </div> </div> </div> } </div>
37.241935
127
0.470333
1e06a5f9ed8203d3315d63a8d4e52d145d03406e
1,965
cs
C#
Workday.RevenueManagement/Salary_Over_The_Cap_Type_DataType.cs
matteofabbri/Workday.WebServices
a7fbcd3f484e6887dbf578b0e54f86bb70c5feb0
[ "MIT" ]
18
2018-11-08T21:28:42.000Z
2022-02-24T21:48:23.000Z
Workday.RevenueManagement/Salary_Over_The_Cap_Type_DataType.cs
matteofabbri/Workday.WebServices
a7fbcd3f484e6887dbf578b0e54f86bb70c5feb0
[ "MIT" ]
3
2019-08-15T13:19:02.000Z
2022-02-16T08:48:10.000Z
Workday.RevenueManagement/Salary_Over_The_Cap_Type_DataType.cs
matteofabbri/Workday.WebServices
a7fbcd3f484e6887dbf578b0e54f86bb70c5feb0
[ "MIT" ]
5
2019-08-22T15:21:59.000Z
2022-02-14T19:05:48.000Z
using System; using System.CodeDom.Compiler; using System.ComponentModel; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Xml.Serialization; namespace Workday.RevenueManagement { [GeneratedCode("System.Xml", "4.6.1590.0"), DesignerCategory("code"), DebuggerStepThrough, XmlType(Namespace = "urn:com.workday/bsvc")] [Serializable] public class Salary_Over_The_Cap_Type_DataType : INotifyPropertyChanged { private string salary_Over_The_Cap_Type_IDField; private string salary_Over_The_Cap_Type_NameField; private bool inactiveField; private bool inactiveFieldSpecified; [method: CompilerGenerated] [CompilerGenerated] public event PropertyChangedEventHandler PropertyChanged; [XmlElement(Order = 0)] public string Salary_Over_The_Cap_Type_ID { get { return this.salary_Over_The_Cap_Type_IDField; } set { this.salary_Over_The_Cap_Type_IDField = value; this.RaisePropertyChanged("Salary_Over_The_Cap_Type_ID"); } } [XmlElement(Order = 1)] public string Salary_Over_The_Cap_Type_Name { get { return this.salary_Over_The_Cap_Type_NameField; } set { this.salary_Over_The_Cap_Type_NameField = value; this.RaisePropertyChanged("Salary_Over_The_Cap_Type_Name"); } } [XmlElement(Order = 2)] public bool Inactive { get { return this.inactiveField; } set { this.inactiveField = value; this.RaisePropertyChanged("Inactive"); } } [XmlIgnore] public bool InactiveSpecified { get { return this.inactiveFieldSpecified; } set { this.inactiveFieldSpecified = value; this.RaisePropertyChanged("InactiveSpecified"); } } protected void RaisePropertyChanged(string propertyName) { PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if (propertyChanged != null) { propertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } } }
21.358696
136
0.738422
1e071b177915dca8191a2c024570d39ab1fd1f95
3,870
cs
C#
src/Nest/Cluster/ClusterReroute/Commands/AllocateClusterRerouteCommandBase.cs
jslicer/elasticsearch-net
8948a9e2a9e87843f9f91c42e2806fd1d3f2a818
[ "Apache-2.0" ]
null
null
null
src/Nest/Cluster/ClusterReroute/Commands/AllocateClusterRerouteCommandBase.cs
jslicer/elasticsearch-net
8948a9e2a9e87843f9f91c42e2806fd1d3f2a818
[ "Apache-2.0" ]
null
null
null
src/Nest/Cluster/ClusterReroute/Commands/AllocateClusterRerouteCommandBase.cs
jslicer/elasticsearch-net
8948a9e2a9e87843f9f91c42e2806fd1d3f2a818
[ "Apache-2.0" ]
null
null
null
using Newtonsoft.Json; namespace Nest { public interface IAllocateClusterRerouteCommand : IClusterRerouteCommand { [JsonProperty("index")] IndexName Index { get; set; } [JsonProperty("shard")] int Shard { get; set; } [JsonProperty("node")] string Node { get; set; } } public interface IAllocateReplicaClusterRerouteCommand : IAllocateClusterRerouteCommand { } public interface IAllocateEmptyPrimaryRerouteCommand : IAllocateClusterRerouteCommand { [JsonProperty("accept_data_loss")] bool AcceptDataLoss { get; set; } } public interface IAllocateStalePrimaryRerouteCommand : IAllocateClusterRerouteCommand { [JsonProperty("accept_data_loss")] bool AcceptDataLoss { get; set; } } public abstract class AllocateClusterRerouteCommandBase : IAllocateClusterRerouteCommand { public abstract string Name { get; } public IndexName Index { get; set; } public int Shard { get; set; } public string Node { get; set; } } public class AllocateReplicaClusterRerouteCommand : AllocateClusterRerouteCommandBase, IAllocateReplicaClusterRerouteCommand { public override string Name => "allocate_replica"; } public class AllocateEmptyPrimaryRerouteCommand : AllocateClusterRerouteCommandBase, IAllocateEmptyPrimaryRerouteCommand { public override string Name => "allocate_empty_primary"; public bool AcceptDataLoss { get; set; } } public class AllocateStalePrimaryRerouteCommand : AllocateClusterRerouteCommandBase, IAllocateStalePrimaryRerouteCommand { public override string Name => "allocate_stale_primary"; public bool AcceptDataLoss { get; set; } } public abstract class AllocateClusterRerouteCommandDescriptorBase<TDescriptor, TInterface> : DescriptorBase<TDescriptor, TInterface>, IAllocateClusterRerouteCommand where TDescriptor : AllocateClusterRerouteCommandDescriptorBase<TDescriptor, TInterface>, TInterface, IAllocateClusterRerouteCommand where TInterface : class, IAllocateClusterRerouteCommand { string IClusterRerouteCommand.Name => Name; public abstract string Name { get; } IndexName IAllocateClusterRerouteCommand.Index { get; set; } int IAllocateClusterRerouteCommand.Shard { get; set; } string IAllocateClusterRerouteCommand.Node { get; set; } public TDescriptor Index(IndexName index) => Assign(a => a.Index = index); public TDescriptor Index<T>() where T : class => Assign(a => a.Index = typeof(T)); public TDescriptor Shard(int shard) => Assign(a => a.Shard = shard); public TDescriptor Node(string node) => Assign(a => a.Node = node); } public class AllocateReplicaClusterRerouteCommandDescriptor : AllocateClusterRerouteCommandDescriptorBase<AllocateReplicaClusterRerouteCommandDescriptor, IAllocateReplicaClusterRerouteCommand>, IAllocateReplicaClusterRerouteCommand { public override string Name => "allocate_replica"; } public class AllocateEmptyPrimaryRerouteCommandDescriptor : AllocateClusterRerouteCommandDescriptorBase<AllocateEmptyPrimaryRerouteCommandDescriptor, IAllocateEmptyPrimaryRerouteCommand>, IAllocateEmptyPrimaryRerouteCommand { public override string Name => "allocate_empty_primary"; bool IAllocateEmptyPrimaryRerouteCommand.AcceptDataLoss { get; set; } public AllocateEmptyPrimaryRerouteCommandDescriptor AcceptDataLoss(bool acceptDataLoss) => Assign(a => a.AcceptDataLoss = acceptDataLoss); } public class AllocateStalePrimaryRerouteCommandDescriptor : AllocateClusterRerouteCommandDescriptorBase<AllocateStalePrimaryRerouteCommandDescriptor, IAllocateStalePrimaryRerouteCommand>, IAllocateStalePrimaryRerouteCommand { public override string Name => "allocate_stale_primary"; bool IAllocateStalePrimaryRerouteCommand.AcceptDataLoss { get; set; } public AllocateStalePrimaryRerouteCommandDescriptor AcceptDataLoss(bool acceptDataLoss) => Assign(a => a.AcceptDataLoss = acceptDataLoss); } }
34.247788
173
0.803876
1e09e84fa9624736ef43510275064c6f048660cf
1,535
cs
C#
sdk/dotnet/WafV2/Inputs/WebAclRuleStatementNotStatementStatementAndStatementStatementAndStatementStatementRegexPatternSetReferenceStatementTextTransformationArgs.cs
alexbowers/pulumi-aws
7dbdb03b1e4f7c0d51d5b5d17233ff4465c3eff5
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
sdk/dotnet/WafV2/Inputs/WebAclRuleStatementNotStatementStatementAndStatementStatementAndStatementStatementRegexPatternSetReferenceStatementTextTransformationArgs.cs
alexbowers/pulumi-aws
7dbdb03b1e4f7c0d51d5b5d17233ff4465c3eff5
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
sdk/dotnet/WafV2/Inputs/WebAclRuleStatementNotStatementStatementAndStatementStatementAndStatementStatementRegexPatternSetReferenceStatementTextTransformationArgs.cs
alexbowers/pulumi-aws
7dbdb03b1e4f7c0d51d5b5d17233ff4465c3eff5
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Aws.WafV2.Inputs { public sealed class WebAclRuleStatementNotStatementStatementAndStatementStatementAndStatementStatementRegexPatternSetReferenceStatementTextTransformationArgs : Pulumi.ResourceArgs { /// <summary> /// The relative processing order for multiple transformations that are defined for a rule statement. AWS WAF processes all transformations, from lowest priority to highest, before inspecting the transformed content. /// </summary> [Input("priority", required: true)] public Input<int> Priority { get; set; } = null!; /// <summary> /// The transformation to apply, you can specify the following types: `NONE`, `COMPRESS_WHITE_SPACE`, `HTML_ENTITY_DECODE`, `LOWERCASE`, `CMD_LINE`, `URL_DECODE`. See the [documentation](https://docs.aws.amazon.com/waf/latest/APIReference/API_TextTransformation.html) for more details. /// </summary> [Input("type", required: true)] public Input<string> Type { get; set; } = null!; public WebAclRuleStatementNotStatementStatementAndStatementStatementAndStatementStatementRegexPatternSetReferenceStatementTextTransformationArgs() { } } }
47.96875
293
0.730945
1e0b185327f483bbf1ffe4e6215acf36684e509f
3,815
cs
C#
src/IdHelper/IdWorker/IdWorker.cs
JTOne123/IdHelper
e06a956c5d696af32a4bdff7ad66a2a392d6b4a0
[ "Apache-2.0" ]
85
2019-09-11T14:46:48.000Z
2022-01-22T07:40:32.000Z
src/IdHelper/IdWorker/IdWorker.cs
JTOne123/IdHelper
e06a956c5d696af32a4bdff7ad66a2a392d6b4a0
[ "Apache-2.0" ]
1
2019-10-09T14:19:16.000Z
2019-10-10T01:12:07.000Z
src/IdHelper/IdWorker/IdWorker.cs
JTOne123/IdHelper
e06a956c5d696af32a4bdff7ad66a2a392d6b4a0
[ "Apache-2.0" ]
28
2019-09-12T02:11:36.000Z
2022-01-22T07:40:39.000Z
using System; namespace Coldairarrow.Util { /// <summary> /// https://github.com/ccollie/snowflake-net /// </summary> internal class IdWorker { public const long Twepoch = 1288834974657L; const int WorkerIdBits = 10; const int DatacenterIdBits = 0; const int SequenceBits = 12; const long MaxWorkerId = -1L ^ (-1L << WorkerIdBits); const long MaxDatacenterId = -1L ^ (-1L << DatacenterIdBits); private const int WorkerIdShift = SequenceBits; private const int DatacenterIdShift = SequenceBits + WorkerIdBits; public const int TimestampLeftShift = SequenceBits + WorkerIdBits + DatacenterIdBits; private const long SequenceMask = -1L ^ (-1L << SequenceBits); private long _sequence = 0L; private long _lastTimestamp = -1L; public IdWorker(long workerId, long sequence = 0L) { WorkerId = workerId; DatacenterId = 0; _sequence = sequence; // sanity check for workerId if (workerId > MaxWorkerId || workerId < 0) { throw new ArgumentException(String.Format("worker Id can't be greater than {0} or less than 0", MaxWorkerId)); } //if (datacenterId > MaxDatacenterId || datacenterId < 0) //{ // throw new ArgumentException(String.Format("datacenter Id can't be greater than {0} or less than 0", MaxDatacenterId)); //} //log.info( // String.Format("worker starting. timestamp left shift {0}, datacenter id bits {1}, worker id bits {2}, sequence bits {3}, workerid {4}", // TimestampLeftShift, DatacenterIdBits, WorkerIdBits, SequenceBits, workerId) // ); } public long WorkerId { get; protected set; } public long DatacenterId { get; protected set; } public long Sequence { get { return _sequence; } internal set { _sequence = value; } } // def get_timestamp() = System.currentTimeMillis readonly object _lock = new Object(); public virtual long NextId() { lock (_lock) { var timestamp = TimeGen(); if (timestamp < _lastTimestamp) { //exceptionCounter.incr(1); //log.Error("clock is moving backwards. Rejecting requests until %d.", _lastTimestamp); throw new InvalidSystemClock(String.Format( "Clock moved backwards. Refusing to generate id for {0} milliseconds", _lastTimestamp - timestamp)); } if (_lastTimestamp == timestamp) { _sequence = (_sequence + 1) & SequenceMask; if (_sequence == 0) { timestamp = TilNextMillis(_lastTimestamp); } } else { _sequence = 0; } _lastTimestamp = timestamp; var id = ((timestamp - Twepoch) << TimestampLeftShift) | (DatacenterId << DatacenterIdShift) | (WorkerId << WorkerIdShift) | _sequence; return id; } } protected virtual long TilNextMillis(long lastTimestamp) { var timestamp = TimeGen(); while (timestamp <= lastTimestamp) { timestamp = TimeGen(); } return timestamp; } protected virtual long TimeGen() { return System.CurrentTimeMillis(); } } }
33.464912
153
0.520577
1e0c1efb465759c999362380a37cd7d5c06813ad
6,534
cs
C#
IL2CXX.Tests/MarshalTests.cs
shin1m/IL2CXX
b69d39a18756d10eaca96913e263a58e75bf2d3f
[ "Unlicense", "MIT" ]
4
2021-03-11T22:13:36.000Z
2022-02-10T05:34:28.000Z
IL2CXX.Tests/MarshalTests.cs
shin1m/IL2CXX
b69d39a18756d10eaca96913e263a58e75bf2d3f
[ "Unlicense", "MIT" ]
null
null
null
IL2CXX.Tests/MarshalTests.cs
shin1m/IL2CXX
b69d39a18756d10eaca96913e263a58e75bf2d3f
[ "Unlicense", "MIT" ]
null
null
null
using System; using System.Numerics; using System.Runtime.InteropServices; using NUnit.Framework; namespace IL2CXX.Tests { [Parallelizable] class MarshalTests { struct Point { public int X; public int Y; } static int SizeOfType() { var n = Marshal.SizeOf<Point>(); Console.WriteLine($"{n}"); return n == 8 ? 0 : 1; } static int SizeOfInstance() { var n = Marshal.SizeOf(new Point { X = 0, Y = 1 }); Console.WriteLine($"{n}"); return n == 8 ? 0 : 1; } [StructLayout(LayoutKind.Sequential, Pack = 4)] struct Name { public string First; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 4)] public string Last; } static int SizeOfByValTStr() { var n = Marshal.SizeOf<Name>(); Console.WriteLine($"{n}"); return n == Marshal.SizeOf<IntPtr>() + 4 ? 0 : 1; } static int StructureToPtr() { var p = Marshal.AllocHGlobal(Marshal.SizeOf<Name>()); try { Marshal.StructureToPtr(new Name { First = "abcdefgh", Last = "ABCDEFGH" }, p, false); var name = Marshal.PtrToStructure<Name>(p); return name.First == "abcdefgh" && name.Last == "ABC" ? 0 : 1; } finally { Marshal.DestroyStructure<Name>(p); Marshal.FreeHGlobal(p); } } [StructLayout(LayoutKind.Explicit)] struct Union { [FieldOffset(4)] public int X; [FieldOffset(4)] public int Y; } static int Explicit() { var x = new Union { X = 1 }; x.Y = 2; return x.X == 2 ? 0 : 1; } [StructLayout(LayoutKind.Explicit)] struct UnionWithReference { [FieldOffset(8)] public string X; [FieldOffset(8)] public string Y; } static int ExplicitWithReference() { var x = new UnionWithReference { X = "foo" }; x.Y = "bar"; return x.X == "bar" ? 0 : 1; } [StructLayout(LayoutKind.Explicit)] struct Child { [FieldOffset(0)] public Vector3 Min; [FieldOffset(12)] public int Index; [FieldOffset(16)] public Vector3 Max; [FieldOffset(28)] public int Count; } [StructLayout(LayoutKind.Explicit)] struct Node { [FieldOffset(0)] public Child A; [FieldOffset(32)] public Child B; } static int ExplicitComposite() { var x = new Node { B = { Count = 1 } }; var y = x; return x.B.Count == 1 ? 0 : 1; } static void Foo(IntPtr x, IntPtr y) { } static int GetFunctionPointerForDelegate() => Marshal.GetFunctionPointerForDelegate((Action<IntPtr, IntPtr>)Foo) == IntPtr.Zero ? 1 : 0; delegate IntPtr BarDelegate(IntPtr x, ref IntPtr y); static IntPtr Bar(IntPtr x, ref IntPtr y) => new IntPtr((int)x + (int)y); static int GetDelegateForFunctionPointer() { var p = Marshal.GetFunctionPointerForDelegate((BarDelegate)Bar); var d = Marshal.GetDelegateForFunctionPointer<BarDelegate>(p); var y = new IntPtr(2); if (d(new IntPtr(1), ref y) != new IntPtr(3)) return 1; return p == Marshal.GetFunctionPointerForDelegate(d) ? 0 : 1; } struct utsname { [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 65)] public string sysname; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 65)] public string nodename; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 65)] public string release; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 65)] public string version; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 65)] public string machine; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 65)] public string extra; } [DllImport("libc")] static extern void uname(out utsname name); static int Parameter() { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) return 0; uname(out var name); Console.WriteLine($"sysname: {name.sysname}"); Console.WriteLine($"nodename: {name.nodename}"); Console.WriteLine($"release: {name.release}"); Console.WriteLine($"version: {name.version}"); Console.WriteLine($"machine: {name.machine}"); return 0; } static int Run(string[] arguments) => arguments[1] switch { nameof(SizeOfType) => SizeOfType(), nameof(SizeOfInstance) => SizeOfInstance(), nameof(SizeOfByValTStr) => SizeOfByValTStr(), nameof(StructureToPtr) => StructureToPtr(), nameof(Explicit) => Explicit(), nameof(ExplicitWithReference) => ExplicitWithReference(), nameof(ExplicitComposite) => ExplicitComposite(), nameof(GetFunctionPointerForDelegate) => GetFunctionPointerForDelegate(), nameof(GetDelegateForFunctionPointer) => GetDelegateForFunctionPointer(), nameof(Parameter) => Parameter(), _ => -1 }; string build; [OneTimeSetUp] public void OneTimeSetUp() => build = Utilities.Build(Run); [Test] public void Test( [Values( nameof(SizeOfType), nameof(SizeOfInstance), nameof(SizeOfByValTStr), nameof(StructureToPtr), nameof(Explicit), nameof(ExplicitWithReference), nameof(ExplicitComposite), nameof(GetFunctionPointerForDelegate), nameof(GetDelegateForFunctionPointer), nameof(Parameter) )] string name, [Values] bool cooperative ) => Utilities.Run(build, cooperative, name); } }
32.834171
102
0.514539
1e0c7bda1abad5b59959d73c78f7e852ac798b6d
19,826
cs
C#
BTDB/EventStoreLayer/DictionaryTypeDescriptor.cs
klesta490/BTDB
bcb09cd3a8928dc72470531350c6e48ee4170e47
[ "MIT" ]
null
null
null
BTDB/EventStoreLayer/DictionaryTypeDescriptor.cs
klesta490/BTDB
bcb09cd3a8928dc72470531350c6e48ee4170e47
[ "MIT" ]
null
null
null
BTDB/EventStoreLayer/DictionaryTypeDescriptor.cs
klesta490/BTDB
bcb09cd3a8928dc72470531350c6e48ee4170e47
[ "MIT" ]
null
null
null
using BTDB.FieldHandler; using BTDB.IL; using BTDB.ODBLayer; using BTDB.StreamLayer; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; namespace BTDB.EventStoreLayer; class DictionaryTypeDescriptor : ITypeDescriptor, IPersistTypeDescriptor { readonly ITypeDescriptorCallbacks _typeSerializers; Type? _type; Type? _keyType; Type? _valueType; ITypeDescriptor? _keyDescriptor; ITypeDescriptor? _valueDescriptor; string? _name; readonly ITypeConvertorGenerator _convertorGenerator; public DictionaryTypeDescriptor(ITypeDescriptorCallbacks typeSerializers, Type type) { _convertorGenerator = typeSerializers.ConvertorGenerator; _typeSerializers = typeSerializers; _type = type; var genericArguments = type.GetGenericArguments(); _keyType = genericArguments[0]; _valueType = genericArguments[1]; } public DictionaryTypeDescriptor(ITypeDescriptorCallbacks typeSerializers, ref SpanReader reader, DescriptorReader nestedDescriptorReader) : this(typeSerializers, nestedDescriptorReader(ref reader), nestedDescriptorReader(ref reader)) { } DictionaryTypeDescriptor(ITypeDescriptorCallbacks typeSerializers, ITypeDescriptor keyDesc, ITypeDescriptor valueDesc) { _convertorGenerator = typeSerializers.ConvertorGenerator; _typeSerializers = typeSerializers; InitFromKeyValueDescriptors(keyDesc, valueDesc); } void InitFromKeyValueDescriptors(ITypeDescriptor keyDescriptor, ITypeDescriptor valueDescriptor) { if (_keyDescriptor == keyDescriptor && _valueDescriptor == valueDescriptor && _name != null) return; _keyDescriptor = keyDescriptor; _valueDescriptor = valueDescriptor; if ((_keyDescriptor.Name?.Length ?? 0) == 0 || (_valueDescriptor.Name?.Length ?? 0) == 0) return; Sealed = _keyDescriptor.Sealed && _valueDescriptor.Sealed; Name = $"Dictionary<{_keyDescriptor.Name}, {_valueDescriptor.Name}>"; } public bool Equals(ITypeDescriptor other) { return Equals(other, new HashSet<ITypeDescriptor>(ReferenceEqualityComparer<ITypeDescriptor>.Instance)); } public string Name { get { if (_name == null) InitFromKeyValueDescriptors(_keyDescriptor!, _valueDescriptor!); return _name!; } private set => _name = value; } public bool FinishBuildFromType(ITypeDescriptorFactory factory) { var keyDescriptor = factory.Create(_keyType!); if (keyDescriptor == null) return false; var valueDescriptor = factory.Create(_valueType!); if (valueDescriptor == null) return false; InitFromKeyValueDescriptors(keyDescriptor, valueDescriptor); return true; } public void BuildHumanReadableFullName(StringBuilder text, HashSet<ITypeDescriptor> stack, uint indent) { text.Append("Dictionary<"); _keyDescriptor!.BuildHumanReadableFullName(text, stack, indent); text.Append(", "); _valueDescriptor!.BuildHumanReadableFullName(text, stack, indent); text.Append(">"); } public bool Equals(ITypeDescriptor other, HashSet<ITypeDescriptor> stack) { var o = other as DictionaryTypeDescriptor; if (o == null) return false; return _keyDescriptor!.Equals(o._keyDescriptor!, stack) && _valueDescriptor!.Equals(o._valueDescriptor!, stack); } public Type GetPreferredType() { if (_type == null) { _keyType = _typeSerializers.LoadAsType(_keyDescriptor!); _valueType = _typeSerializers.LoadAsType(_valueDescriptor!); _type = typeof(IDictionary<,>).MakeGenericType(_keyType, _valueType); } return _type; } static Type GetInterface(Type type) => type.GetInterface("IOrderedDictionary`2") ?? type.GetInterface("IDictionary`2") ?? type; public Type GetPreferredType(Type targetType) { if (_type == targetType) return _type; var targetIDictionary = GetInterface(targetType); var targetTypeArguments = targetIDictionary.GetGenericArguments(); var keyType = _typeSerializers.LoadAsType(_keyDescriptor!, targetTypeArguments[0]); var valueType = _typeSerializers.LoadAsType(_valueDescriptor!, targetTypeArguments[1]); return targetType.GetGenericTypeDefinition().MakeGenericType(keyType, valueType); } public bool AnyOpNeedsCtx() { return !_keyDescriptor!.StoredInline || !_valueDescriptor!.StoredInline || _keyDescriptor.AnyOpNeedsCtx() || _valueDescriptor.AnyOpNeedsCtx(); } public void GenerateLoad(IILGen ilGenerator, Action<IILGen> pushReader, Action<IILGen> pushCtx, Action<IILGen> pushDescriptor, Type targetType) { if (targetType == typeof(object)) targetType = GetPreferredType(); var localCount = ilGenerator.DeclareLocal(typeof(int)); var targetIDictionary = GetInterface(targetType); var targetTypeArguments = targetIDictionary.GetGenericArguments(); var keyType = _typeSerializers.LoadAsType(_keyDescriptor!, targetTypeArguments[0]); var valueType = _typeSerializers.LoadAsType(_valueDescriptor!, targetTypeArguments[1]); var dictionaryTypeGenericDefinition = targetType.InheritsOrImplements(typeof(IOrderedDictionary<,>)) ? typeof(OrderedDictionaryWithDescriptor<,>) : typeof(DictionaryWithDescriptor<,>); var dictionaryType = dictionaryTypeGenericDefinition.MakeGenericType(keyType, valueType); if (!targetType.IsAssignableFrom(dictionaryType)) throw new InvalidOperationException(); var localDict = ilGenerator.DeclareLocal(dictionaryType); var loadFinished = ilGenerator.DefineLabel(); var next = ilGenerator.DefineLabel(); ilGenerator .Ldnull() .Stloc(localDict) .Do(pushReader) .Call(typeof(SpanReader).GetMethod(nameof(SpanReader.ReadVUInt32))!) .ConvI4() .Dup() .LdcI4(1) .Sub() .Stloc(localCount) .Brfalse(loadFinished) .Ldloc(localCount) .Do(pushDescriptor) .Newobj(dictionaryType.GetConstructor(new[] { typeof(int), typeof(ITypeDescriptor) })!) .Stloc(localDict) .Mark(next) .Ldloc(localCount) .Brfalse(loadFinished) .Ldloc(localCount) .LdcI4(1) .Sub() .Stloc(localCount) .Ldloc(localDict); _keyDescriptor.GenerateLoadEx(ilGenerator, pushReader, pushCtx, il => il.Do(pushDescriptor).LdcI4(0).Callvirt(() => default(ITypeDescriptor).NestedType(0)), keyType, _convertorGenerator); _valueDescriptor.GenerateLoadEx(ilGenerator, pushReader, pushCtx, il => il.Do(pushDescriptor).LdcI4(1).Callvirt(() => default(ITypeDescriptor).NestedType(0)), valueType, _convertorGenerator); ilGenerator .Callvirt(dictionaryType.GetMethod(nameof(IDictionary.Add))!) .Br(next) .Mark(loadFinished) .Ldloc(localDict) .Castclass(targetType); } public ITypeNewDescriptorGenerator? BuildNewDescriptorGenerator() { if (_keyDescriptor!.Sealed && _valueDescriptor!.Sealed) return null; return new TypeNewDescriptorGenerator(this); } class TypeNewDescriptorGenerator : ITypeNewDescriptorGenerator { readonly DictionaryTypeDescriptor _owner; public TypeNewDescriptorGenerator(DictionaryTypeDescriptor owner) { _owner = owner; } public void GenerateTypeIterator(IILGen ilGenerator, Action<IILGen> pushObj, Action<IILGen> pushCtx, Type type) { var finish = ilGenerator.DefineLabel(); var next = ilGenerator.DefineLabel(); if (type == typeof(object)) type = _owner.GetPreferredType(); var targetIDictionary = GetInterface(type); var targetTypeArguments = targetIDictionary.GetGenericArguments(); var keyType = _owner._typeSerializers.LoadAsType(_owner._keyDescriptor!, targetTypeArguments[0]); var valueType = _owner._typeSerializers.LoadAsType(_owner._valueDescriptor!, targetTypeArguments[1]); if (_owner._type == null) _owner._type = type; var isDict = type.GetGenericTypeDefinition() == typeof(Dictionary<,>); var typeAsIDictionary = isDict ? type : typeof(IDictionary<,>).MakeGenericType(keyType, valueType); var getEnumeratorMethod = isDict ? typeAsIDictionary.GetMethods() .Single( m => m.Name == nameof(IEnumerable.GetEnumerator) && m.ReturnType.IsValueType && m.GetParameters().Length == 0) : typeAsIDictionary.GetInterface("IEnumerable`1")!.GetMethod(nameof(IEnumerable.GetEnumerator)); var typeAsIEnumerator = getEnumeratorMethod!.ReturnType; var currentGetter = typeAsIEnumerator.GetProperty(nameof(IEnumerator.Current))!.GetGetMethod(); var typeKeyValuePair = currentGetter!.ReturnType; var localEnumerator = ilGenerator.DeclareLocal(typeAsIEnumerator); var localPair = ilGenerator.DeclareLocal(typeKeyValuePair); ilGenerator .Do(pushObj) .Castclass(typeAsIDictionary) .Callvirt(getEnumeratorMethod) .Stloc(localEnumerator) .Try() .Mark(next) .Do(il => { if (isDict) { il .Ldloca(localEnumerator) .Call(typeAsIEnumerator.GetMethod(nameof(IEnumerator.MoveNext))!); } else { il .Ldloc(localEnumerator) .Callvirt(() => default(IEnumerator).MoveNext()); } }) .Brfalse(finish) .Do(il => { if (isDict) { il .Ldloca(localEnumerator) .Call(currentGetter); } else { il .Ldloc(localEnumerator) .Callvirt(currentGetter); } }) .Stloc(localPair); if (!_owner._keyDescriptor.Sealed) { ilGenerator .Do(pushCtx) .Ldloca(localPair) .Call(typeKeyValuePair.GetProperty("Key")!.GetGetMethod()!) .Callvirt(typeof(IDescriptorSerializerLiteContext).GetMethod(nameof(IDescriptorSerializerLiteContext.StoreNewDescriptors))!); } if (!_owner._valueDescriptor.Sealed) { ilGenerator .Do(pushCtx) .Ldloca(localPair) .Call(typeKeyValuePair.GetProperty("Value")!.GetGetMethod()!) .Callvirt(typeof(IDescriptorSerializerLiteContext).GetMethod(nameof(IDescriptorSerializerLiteContext.StoreNewDescriptors))!); } ilGenerator .Br(next) .Mark(finish) .Finally() .Do(il => { if (isDict) { il .Ldloca(localEnumerator) .Constrained(typeAsIEnumerator); } else { il.Ldloc(localEnumerator); } }) .Callvirt(() => default(IDisposable).Dispose()) .EndTry(); } } public ITypeDescriptor? NestedType(int index) { return index switch { 0 => _keyDescriptor, 1 => _valueDescriptor, _ => null }; } public void MapNestedTypes(Func<ITypeDescriptor, ITypeDescriptor> map) { InitFromKeyValueDescriptors(map(_keyDescriptor), map(_valueDescriptor)); } public bool Sealed { get; private set; } public bool StoredInline => true; public bool LoadNeedsHelpWithConversion => false; public void ClearMappingToType() { _type = null; _keyType = null; _valueType = null; } public bool ContainsField(string name) { return false; } public IEnumerable<KeyValuePair<string, ITypeDescriptor>> Fields => Array.Empty<KeyValuePair<string, ITypeDescriptor>>(); public void Persist(ref SpanWriter writer, DescriptorWriter nestedDescriptorWriter) { nestedDescriptorWriter(ref writer, _keyDescriptor!); nestedDescriptorWriter(ref writer, _valueDescriptor!); } public void GenerateSave(IILGen ilGenerator, Action<IILGen> pushWriter, Action<IILGen> pushCtx, Action<IILGen> pushValue, Type saveType) { var notnull = ilGenerator.DefineLabel(); var completeFinish = ilGenerator.DefineLabel(); var notDictionary = ilGenerator.DefineLabel(); var keyType = saveType.GetGenericArguments()[0]; var valueType = saveType.GetGenericArguments()[1]; var typeAsIDictionary = typeof(IDictionary<,>).MakeGenericType(keyType, valueType); var typeAsICollection = typeAsIDictionary.GetInterface("ICollection`1"); var localDict = ilGenerator.DeclareLocal(typeAsIDictionary); ilGenerator .Do(pushValue) .Castclass(typeAsIDictionary) .Stloc(localDict) .Ldloc(localDict) .Brtrue(notnull) .Do(pushWriter) .Call(typeof(SpanWriter).GetMethod(nameof(SpanWriter.WriteByteZero))!) .Br(completeFinish) .Mark(notnull) .Do(pushWriter) .Ldloc(localDict) .Callvirt(typeAsICollection!.GetProperty(nameof(ICollection.Count))!.GetGetMethod()!) .LdcI4(1) .Add() .Call(typeof(SpanWriter).GetMethod(nameof(SpanWriter.WriteVUInt32))!); { var typeAsDictionary = typeof(Dictionary<,>).MakeGenericType(keyType, valueType); var getEnumeratorMethod = typeAsDictionary.GetMethods() .Single(m => m.Name == nameof(IEnumerable.GetEnumerator) && m.ReturnType.IsValueType && m.GetParameters().Length == 0); var typeAsIEnumerator = getEnumeratorMethod.ReturnType; var currentGetter = typeAsIEnumerator.GetProperty(nameof(IEnumerator.Current))!.GetGetMethod(); var typeKeyValuePair = currentGetter!.ReturnType; var localEnumerator = ilGenerator.DeclareLocal(typeAsIEnumerator); var localPair = ilGenerator.DeclareLocal(typeKeyValuePair); var finish = ilGenerator.DefineLabel(); var next = ilGenerator.DefineLabel(); ilGenerator .Ldloc(localDict) .Isinst(typeAsDictionary) .Brfalse(notDictionary) .Ldloc(localDict) .Castclass(typeAsDictionary) .Callvirt(getEnumeratorMethod) .Stloc(localEnumerator) .Try() .Mark(next) .Ldloca(localEnumerator) .Call(typeAsIEnumerator.GetMethod(nameof(IEnumerator.MoveNext))!) .Brfalse(finish) .Ldloca(localEnumerator) .Call(currentGetter) .Stloc(localPair); _keyDescriptor!.GenerateSaveEx(ilGenerator, pushWriter, pushCtx, il => il.Ldloca(localPair).Call(typeKeyValuePair.GetProperty("Key")!.GetGetMethod()!), keyType); _valueDescriptor!.GenerateSaveEx(ilGenerator, pushWriter, pushCtx, il => il.Ldloca(localPair).Call(typeKeyValuePair.GetProperty("Value")!.GetGetMethod()!), valueType); ilGenerator .Br(next) .Mark(finish) .Finally() .Ldloca(localEnumerator) .Constrained(typeAsIEnumerator) .Callvirt(() => default(IDisposable).Dispose()) .EndTry() .Br(completeFinish); } { var getEnumeratorMethod = typeAsIDictionary.GetInterface("IEnumerable`1")!.GetMethod(nameof(IEnumerable.GetEnumerator)); var typeAsIEnumerator = getEnumeratorMethod!.ReturnType; var currentGetter = typeAsIEnumerator.GetProperty(nameof(IEnumerator.Current))!.GetGetMethod(); var typeKeyValuePair = currentGetter!.ReturnType; var localEnumerator = ilGenerator.DeclareLocal(typeAsIEnumerator); var localPair = ilGenerator.DeclareLocal(typeKeyValuePair); var finish = ilGenerator.DefineLabel(); var next = ilGenerator.DefineLabel(); ilGenerator .Mark(notDictionary) .Ldloc(localDict) .Callvirt(getEnumeratorMethod) .Stloc(localEnumerator) .Try() .Mark(next) .Ldloc(localEnumerator) .Callvirt(() => default(IEnumerator).MoveNext()) .Brfalse(finish) .Ldloc(localEnumerator) .Callvirt(currentGetter) .Stloc(localPair); _keyDescriptor.GenerateSaveEx(ilGenerator, pushWriter, pushCtx, il => il.Ldloca(localPair).Call(typeKeyValuePair.GetProperty("Key")!.GetGetMethod()!), keyType); _valueDescriptor.GenerateSaveEx(ilGenerator, pushWriter, pushCtx, il => il.Ldloca(localPair).Call(typeKeyValuePair.GetProperty("Value")!.GetGetMethod()!), valueType); ilGenerator .Br(next) .Mark(finish) .Finally() .Ldloc(localEnumerator) .Callvirt(() => default(IDisposable).Dispose()) .EndTry() .Mark(completeFinish); } } public void GenerateSkip(IILGen ilGenerator, Action<IILGen> pushReader, Action<IILGen> pushCtx) { var localCount = ilGenerator.DeclareLocal(typeof(uint)); var skipFinished = ilGenerator.DefineLabel(); var next = ilGenerator.DefineLabel(); ilGenerator .Do(pushReader) .Call(typeof(SpanReader).GetMethod(nameof(SpanReader.ReadVUInt32))!) .Stloc(localCount) .Ldloc(localCount) .Brfalse(skipFinished) .Mark(next) .Ldloc(localCount) .LdcI4(1) .Sub() .Stloc(localCount) .Ldloc(localCount) .Brfalse(skipFinished); _keyDescriptor!.GenerateSkipEx(ilGenerator, pushReader, pushCtx); _valueDescriptor!.GenerateSkipEx(ilGenerator, pushReader, pushCtx); ilGenerator .Br(next) .Mark(skipFinished); } public ITypeDescriptor CloneAndMapNestedTypes(ITypeDescriptorCallbacks typeSerializers, Func<ITypeDescriptor, ITypeDescriptor> map) { var keyDesc = map(_keyDescriptor); var valueDesc = map(_valueDescriptor); if (_typeSerializers == typeSerializers && keyDesc == _keyDescriptor && valueDesc == _valueDescriptor) return this; return new DictionaryTypeDescriptor(typeSerializers, keyDesc, valueDesc); } }
42.453961
199
0.609805
1e0cdf37fb05c4d1364c91a770dd1ec3cdd01165
2,120
cs
C#
MyDashboard.Domain/Entities/Customer.cs
maschdev/Gemni.MyDashboard-API
25dcfa0eb2fcf80850c7fdb12a454368ade34b93
[ "MIT" ]
null
null
null
MyDashboard.Domain/Entities/Customer.cs
maschdev/Gemni.MyDashboard-API
25dcfa0eb2fcf80850c7fdb12a454368ade34b93
[ "MIT" ]
null
null
null
MyDashboard.Domain/Entities/Customer.cs
maschdev/Gemni.MyDashboard-API
25dcfa0eb2fcf80850c7fdb12a454368ade34b93
[ "MIT" ]
null
null
null
using MyDashboard.Domain.ValueObjects; using MyDashboard.Shared.Entities; using System; using System.Text; namespace MyDashboard.Domain.Entities { public class Customer : Entity { protected Customer() { } public Customer(Name name, Email email, User user, Document document, string phone) { Name = name; Email = email; Document = document; User = user; Phone = phone; } public Document Document { get; private set; } public Email Email { get; private set; } public Name Name { get; private set; } public User User { get; private set; } public Guid UserId { get; private set; } public string Phone { get; private set; } public bool Enable { get; private set; } public void Active() => Enable = true; public void Deactivate() => Enable = false; public void Update(Name name, Email email, Document document, string phone) { Name.Update(name.FirstName, name.LastName); Email.Udpate(email.Address); Document.Update(document.Number); //User.Update(user.Name); Phone = phone; } public bool Authenticate(string email, string password) { if (Email.Address.Trim() == email.Trim() && User.Password.Trim() == EncryptPassword(password).Trim()) return true; AddNotification("Password", "Usuário ou senha inválidos"); return false; } private static string EncryptPassword(string pass) { if (string.IsNullOrEmpty(pass)) return ""; var password = (pass += "|2d331cca-f6c0-40c0-bb43-6e32989c2881"); var md5 = System.Security.Cryptography.MD5.Create(); var data = md5.ComputeHash(Encoding.Default.GetBytes(password)); var sbString = new StringBuilder(); for (int i = 0; i < data.Length; i++) sbString.Append(data[i].ToString("x2")); return sbString.ToString(); } } }
32.121212
113
0.575472
1e1112b477dc394ff175f5c5a6903063afc4a4d1
5,107
cs
C#
src/tests/Equinor.ProCoSys.Preservation.WebApi.Tests/Controllers/Tags/UploadAttachmentForceOverwriteDtoValidatorTests.cs
hbjorgo/procosys-preservation-api
9ae1826bb78e6fdc6748091bce3118a0fb4556b8
[ "MIT" ]
5
2019-10-09T10:46:36.000Z
2021-02-22T15:13:04.000Z
src/tests/Equinor.ProCoSys.Preservation.WebApi.Tests/Controllers/Tags/UploadAttachmentForceOverwriteDtoValidatorTests.cs
hbjorgo/procosys-preservation-api
9ae1826bb78e6fdc6748091bce3118a0fb4556b8
[ "MIT" ]
217
2019-11-08T12:35:41.000Z
2022-03-01T23:03:11.000Z
src/tests/Equinor.ProCoSys.Preservation.WebApi.Tests/Controllers/Tags/UploadAttachmentForceOverwriteDtoValidatorTests.cs
hbjorgo/procosys-preservation-api
9ae1826bb78e6fdc6748091bce3118a0fb4556b8
[ "MIT" ]
3
2019-12-10T11:36:08.000Z
2022-02-17T11:12:52.000Z
using System.IO; using System.Threading; using System.Threading.Tasks; using Equinor.ProCoSys.Preservation.BlobStorage; using Equinor.ProCoSys.Preservation.Domain; using Equinor.ProCoSys.Preservation.WebApi.Controllers.Tags; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Options; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; namespace Equinor.ProCoSys.Preservation.WebApi.Tests.Controllers.Tags { [TestClass] public class UploadAttachmentForceOverwriteDtoValidatorTests { private UploadAttachmentForceOverwriteDtoValidator _dut; private BlobStorageOptions _options; [TestInitialize] public void Setup() { var blobStorageOptionsMock = new Mock<IOptionsSnapshot<BlobStorageOptions>>(); _options = new BlobStorageOptions { MaxSizeMb = 2, BlobContainer = "bc", BlockedFileSuffixes = new[] {".exe", ".zip"} }; blobStorageOptionsMock .Setup(x => x.Value) .Returns(_options); _dut = new UploadAttachmentForceOverwriteDtoValidator(blobStorageOptionsMock.Object); } [TestMethod] public void Validate_OK() { var uploadAttachmentDto = new UploadAttachmentForceOverwriteDto { File = new TestFile("picture.gif", 1000) }; var result = _dut.Validate(uploadAttachmentDto); Assert.IsTrue(result.IsValid); } [TestMethod] public void Fail_When_FileNotGiven() { var uploadAttachmentDto = new UploadAttachmentForceOverwriteDto(); var result = _dut.Validate(uploadAttachmentDto); Assert.IsFalse(result.IsValid); Assert.AreEqual(1, result.Errors.Count); Assert.AreEqual(result.Errors[0].ErrorMessage, "'File' must not be empty."); } [TestMethod] public void Fail_WhenFileNameNotExists() { var uploadAttachmentDto = new UploadAttachmentForceOverwriteDto { File = new TestFile(null, 1000) }; var result = _dut.Validate(uploadAttachmentDto); Assert.IsFalse(result.IsValid); Assert.AreEqual(1, result.Errors.Count); Assert.AreEqual(result.Errors[0].ErrorMessage, "Filename not given!"); } [TestMethod] public void Fail_WhenFileNameIsTooLong() { var uploadAttachmentDto = new UploadAttachmentForceOverwriteDto { File = new TestFile(new string('x', Attachment.FileNameLengthMax + 1), 1000) }; var result = _dut.Validate(uploadAttachmentDto); Assert.IsFalse(result.IsValid); Assert.AreEqual(1, result.Errors.Count); Assert.IsTrue(result.Errors[0].ErrorMessage.StartsWith("Filename to long! Max")); } [TestMethod] public void Fail_When_FileToBig() { var uploadAttachmentDto = new UploadAttachmentForceOverwriteDto { File = new TestFile("picture.gif", (_options.MaxSizeMb * 1024 * 1024) + 1) }; var result = _dut.Validate(uploadAttachmentDto); Assert.IsFalse(result.IsValid); Assert.AreEqual(1, result.Errors.Count); Assert.AreEqual(result.Errors[0].ErrorMessage, $"Maximum file size is {_options.MaxSizeMb}MB!"); } [TestMethod] public void Fail_When_IllegalFileType() { var uploadAttachmentDto = new UploadAttachmentForceOverwriteDto { File = new TestFile("picture.exe", 500) }; var result = _dut.Validate(uploadAttachmentDto); Assert.IsFalse(result.IsValid); Assert.AreEqual(1, result.Errors.Count); Assert.AreEqual(result.Errors[0].ErrorMessage, $"File {uploadAttachmentDto.File.FileName} is not a valid file for upload!"); } class TestFile : IFormFile { public TestFile(string fileName, long lengthInBytes) { ContentDisposition = null; ContentType = null; FileName = fileName; Headers = null; Length = lengthInBytes; Name = null; } public void CopyTo(Stream target) => throw new System.NotImplementedException(); public Task CopyToAsync(Stream target, CancellationToken cancellationToken = new CancellationToken()) => throw new System.NotImplementedException(); public Stream OpenReadStream() => throw new System.NotImplementedException(); public string ContentDisposition { get; } public string ContentType { get; } public string FileName { get; } public IHeaderDictionary Headers { get; } public long Length { get; } public string Name { get; } } } }
34.506757
160
0.602115
1e113a9f21097fc09ce1143d3393bae72e0f1121
8,052
cs
C#
src/Cake.Common/Tools/NuGet/Pack/NuspecTransformer.cs
RichiCoder1/cake
bdc3a070880dd6b7e4bdd3d5ea3c18ee2fe82bb6
[ "MIT" ]
1
2017-02-06T14:02:26.000Z
2017-02-06T14:02:26.000Z
src/Cake.Common/Tools/NuGet/Pack/NuspecTransformer.cs
RichiCoder1/cake
bdc3a070880dd6b7e4bdd3d5ea3c18ee2fe82bb6
[ "MIT" ]
null
null
null
src/Cake.Common/Tools/NuGet/Pack/NuspecTransformer.cs
RichiCoder1/cake
bdc3a070880dd6b7e4bdd3d5ea3c18ee2fe82bb6
[ "MIT" ]
1
2021-05-03T14:12:03.000Z
2021-05-03T14:12:03.000Z
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Xml; using Cake.Core; namespace Cake.Common.Tools.NuGet.Pack { internal static class NuspecTransformer { private static readonly Dictionary<string, Func<NuGetPackSettings, string>> _mappings; private static readonly List<string> _cdataElements; private const string NuSpecXsd = "http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd"; static NuspecTransformer() { _mappings = new Dictionary<string, Func<NuGetPackSettings, string>> { { "id", settings => ToString(settings.Id) }, { "version", settings => ToString(settings.Version) }, { "title", settings => ToString(settings.Title) }, { "authors", settings => ToCommaSeparatedString(settings.Authors) }, { "owners", settings => ToCommaSeparatedString(settings.Owners) }, { "description", settings => ToString(settings.Description) }, { "summary", settings => ToString(settings.Summary) }, { "licenseUrl", settings => ToString(settings.LicenseUrl) }, { "projectUrl", settings => ToString(settings.ProjectUrl) }, { "iconUrl", settings => ToString(settings.IconUrl) }, { "requireLicenseAcceptance", settings => ToString(settings.RequireLicenseAcceptance) }, { "copyright", settings => ToString(settings.Copyright) }, { "releaseNotes", settings => ToMultiLineString(settings.ReleaseNotes) }, { "tags", settings => ToSpaceSeparatedString(settings.Tags) } }; _cdataElements = new List<string> { "releaseNotes" }; } public static void Transform(XmlDocument document, NuGetPackSettings settings) { // Create the namespace manager. var namespaceManager = new XmlNamespaceManager(document.NameTable); namespaceManager.AddNamespace("nu", NuSpecXsd); foreach (var elementName in _mappings.Keys) { var content = _mappings[elementName](settings); if (content != null) { // Replace the node content. var node = FindOrCreateElement(document, namespaceManager, elementName); if (_cdataElements.Contains(elementName)) { node.AppendChild(document.CreateCDataSection(content)); } else { node.InnerText = content; } } } if (settings.Files != null && settings.Files.Count > 0) { var filesPath = string.Format(CultureInfo.InvariantCulture, "//*[local-name()='package']//*[local-name()='files']"); var filesElement = document.SelectSingleNode(filesPath, namespaceManager); if (filesElement == null) { // Get the package element. var package = GetPackageElement(document); filesElement = document.CreateAndAppendElement(package, "files"); } // Add the files filesElement.RemoveAll(); foreach (var file in settings.Files) { var fileElement = document.CreateAndAppendElement(filesElement, "file"); fileElement.AddAttributeIfSpecified(file.Source, "src"); fileElement.AddAttributeIfSpecified(file.Exclude, "exclude"); fileElement.AddAttributeIfSpecified(file.Target, "target"); } } if (settings.Dependencies != null && settings.Dependencies.Count > 0) { var dependenciesElement = FindOrCreateElement(document, namespaceManager, "dependencies"); // Add the files dependenciesElement.RemoveAll(); foreach (var dependency in settings.Dependencies) { var fileElement = document.CreateAndAppendElement(dependenciesElement, "dependency"); fileElement.AddAttributeIfSpecified(dependency.Id, "id"); fileElement.AddAttributeIfSpecified(dependency.Version, "version"); } } } private static XmlNode GetPackageElement(XmlDocument document) { var package = document.SelectSingleNode("//*[local-name()='package']"); if (package == null) { throw new CakeException("Nuspec file is missing package root."); } return package; } private static XmlNode FindOrCreateElement(XmlDocument document, XmlNamespaceManager ns, string name) { var path = string.Format(CultureInfo.InvariantCulture, "//*[local-name()='package']//*[local-name()='metadata']//*[local-name()='{0}']", name); var node = document.SelectSingleNode(path, ns); if (node == null) { var parent = document.SelectSingleNode("//*[local-name()='package']//*[local-name()='metadata']", ns); if (parent == null) { // Get the package element. var package = GetPackageElement(document); // Create the metadata element. parent = document.CreateElement("metadata", NuSpecXsd); package.PrependChild(parent); } node = document.CreateAndAppendElement(parent, name); } return node; } private static XmlNode CreateAndAppendElement(this XmlDocument document, XmlNode parent, string name) { // If the parent didn't have a namespace specified, then skip adding one. // Otherwise add the parent's namespace. This is a little hackish, but it // will avoid empty namespaces. This should probably be done better... return parent.AppendChild( string.IsNullOrWhiteSpace(parent.NamespaceURI) ? document.CreateElement(name) : document.CreateElement(name, parent.NamespaceURI)); } private static void AddAttributeIfSpecified(this XmlNode element, string value, string name) { if (string.IsNullOrWhiteSpace(value) || element.OwnerDocument == null || element.Attributes == null) { return; } var attr = element.OwnerDocument.CreateAttribute(name); attr.Value = value; element.Attributes.Append(attr); } private static string ToString(string value) { return string.IsNullOrWhiteSpace(value) ? null : value; } private static string ToString(Uri value) { return value == null ? null : value.ToString().TrimEnd('/'); } private static string ToString(bool value) { return value.ToString().ToLowerInvariant(); } private static string ToCommaSeparatedString(IEnumerable<string> values) { return values != null ? string.Join(",", values) : null; } private static string ToMultiLineString(IEnumerable<string> values) { return values != null ? string.Join("\r\n", values).NormalizeLineEndings() : null; } private static string ToSpaceSeparatedString(IEnumerable<string> values) { return values != null ? string.Join(" ", values.Select(x => x.Replace(" ", "-"))) : null; } } }
41.505155
155
0.551043
1e1601a77069aa09f2c517994159fdc15e5179a1
25,729
cs
C#
Ash.DefaultEC/UI/Containers/Container.cs
JonSnowbd/Nez
3fb72cd82370df607026c22c77c811cfbfcf7c77
[ "MIT" ]
3
2020-10-25T22:46:45.000Z
2021-02-22T19:41:21.000Z
Ash.DefaultEC/UI/Containers/Container.cs
JonSnowbd/Ash
3fb72cd82370df607026c22c77c811cfbfcf7c77
[ "MIT" ]
null
null
null
Ash.DefaultEC/UI/Containers/Container.cs
JonSnowbd/Ash
3fb72cd82370df607026c22c77c811cfbfcf7c77
[ "MIT" ]
null
null
null
using System; using Microsoft.Xna.Framework; namespace Ash.UI { /// <summary> /// A group with a single child that sizes and positions the child using constraints. This provides layout similar to a /// {@link Table} with a single cell but is more lightweight. /// </summary> public class Container : Group { #region ILayout public override float MinWidth => GetMinWidth(); public override float MinHeight => GetPrefHeight(); public override float PreferredWidth => GetPrefWidth(); public override float PreferredHeight => GetPrefHeight(); public override float MaxWidth => GetMaxWidth(); public override float MaxHeight => GetMaxHeight(); #endregion Element _element; Value _minWidthValue = Value.MinWidth, _minHeightValue = Value.MinHeight; Value _prefWidthValue = Value.PrefWidth, _prefHeightValue = Value.PrefHeight; Value _maxWidthValue = Value.Zero, _maxHeightValue = Value.Zero; Value _padTop = Value.Zero, _padLeft = Value.Zero, _padBottom = Value.Zero, _padRight = Value.Zero; float _fillX, _fillY; int _align; IDrawable _background; bool _clip; bool _round = true; /// <summary> /// Creates a container with no element /// </summary> public Container() { SetTouchable(Touchable.ChildrenOnly); transform = false; } public Container(Element element) : this() { SetElement(element); } public override void Draw(Batcher batcher, float parentAlpha) { Validate(); if (transform) { ApplyTransform(batcher, ComputeTransform()); DrawBackground(batcher, parentAlpha, 0, 0); if (_clip) { //batcher.flush(); //float padLeft = this.padLeft.get( this ), padBottom = this.padBottom.get( this ); //if( clipBegin( padLeft, padBottom,minWidthValueh() - padLeft - padRight.get( tmaxWidth // getHeight() - padBottom - padTop.get( this ) ) ) { DrawChildren(batcher, parentAlpha); //batcher.flush(); //clipEnd(); } } else { DrawChildren(batcher, parentAlpha); } ResetTransform(batcher); } else { DrawBackground(batcher, parentAlpha, GetX(), GetY()); base.Draw(batcher, parentAlpha); } } /// <summary> /// Called to draw the background, before clipping is applied (if enabled). Default implementation draws the background drawable. /// </summary> /// <param name="batcher">Batcher.</param> /// <param name="parentAlpha">Parent alpha.</param> /// <param name="x">The x coordinate.</param> /// <param name="y">The y coordinate.</param> protected void DrawBackground(Batcher batcher, float parentAlpha, float x, float y) { if (_background == null) return; _background.Draw(batcher, x, y, GetWidth(), GetHeight(), ColorExt.Create(color, (int) (color.A * parentAlpha))); } /// <summary> /// Sets the background drawable and adjusts the container's padding to match the background. /// </summary> /// <param name="background">Background.</param> public Container SetBackground(IDrawable background) { return SetBackground(background, true); } /// <summary> /// Sets the background drawable and, if adjustPadding is true, sets the container's padding to /// {@link Drawable#getBottomHeight()} , {@link Drawable#getTopHeight()}, {@link Drawable#getLeftWidth()}, and /// {@link Drawable#getRightWidth()}. /// If background is null, the background will be cleared and padding removed. /// </summary> /// <param name="background">Background.</param> /// <param name="adjustPadding">If set to <c>true</c> adjust padding.</param> public Container SetBackground(IDrawable background, bool adjustPadding) { if (_background == background) return this; _background = background; if (adjustPadding) { if (background == null) SetPad(Value.Zero); else SetPad(background.TopHeight, background.LeftWidth, background.BottomHeight, background.RightWidth); Invalidate(); } return this; } public IDrawable GetBackground() { return _background; } public override void Layout() { if (_element == null) return; float padLeft = _padLeft.Get(this), padBottom = _padBottom.Get(this); float containerWidth = GetWidth() - padLeft - _padRight.Get(this); float containerHeight = GetHeight() - padBottom - _padTop.Get(this); float minWidth = _minWidthValue.Get(_element), minHeight = _minHeightValue.Get(_element); float prefWidth = _prefWidthValue.Get(_element), prefHeight = _prefHeightValue.Get(_element); float maxWidth = _maxWidthValue.Get(_element), maxHeight = _maxHeightValue.Get(_element); float width; if (_fillX > 0) width = containerWidth * _fillX; else width = Math.Min(prefWidth, containerWidth); if (width < minWidth) width = minWidth; if (maxWidth > 0 && width > maxWidth) width = maxWidth; float height; if (_fillY > 0) height = containerHeight * _fillY; else height = Math.Min(prefHeight, containerHeight); if (height < minHeight) height = minHeight; if (maxHeight > 0 && height > maxHeight) height = maxHeight; var x = padLeft; if ((_align & AlignInternal.Right) != 0) x += containerWidth - width; else if ((_align & AlignInternal.Left) == 0) // center x += (containerWidth - width) / 2; var y = padBottom; if ((_align & AlignInternal.Top) != 0) y += containerHeight - height; else if ((_align & AlignInternal.Bottom) == 0) // center y += (containerHeight - height) / 2; if (_round) { x = Mathf.Round(x); y = Mathf.Round(y); width = Mathf.Round(width); height = Mathf.Round(height); } _element.SetBounds(x, y, width, height); if (_element is ILayout) ((ILayout) _element).Validate(); } /// <summary> /// element may be null /// </summary> /// <returns>The element.</returns> /// <param name="element">element.</param> public virtual Element SetElement(Element element) { if (element == this) throw new Exception("element cannot be the Container."); if (element == _element) return element; if (_element != null) base.RemoveElement(_element); _element = element; if (element != null) return AddElement(element); return null; } /// <summary> /// May be null /// </summary> /// <returns>The element.</returns> public T GetElement<T>() where T : Element { return _element as T; } /// <summary> /// May be null /// </summary> /// <returns>The element.</returns> public Element GetElement() { return _element; } public override bool RemoveElement(Element element) { if (element != _element) return false; SetElement(null); return true; } /// <summary> /// Sets the minWidth, prefWidth, maxWidth, minHeight, prefHeight, and maxHeight to the specified value /// </summary> /// <param name="size">Size.</param> public Container SetSize(Value size) { if (size == null) throw new Exception("size cannot be null."); _minWidthValue = size; _minHeightValue = size; _prefWidthValue = size; _prefHeightValue = size; _maxWidthValue = size; _maxHeightValue = size; return this; } /// <summary> /// Sets the minWidth, prefWidth, maxWidth, minHeight, prefHeight, and maxHeight to the specified values /// </summary> /// <param name="width">Width.</param> /// <param name="height">Height.</param> public Container SetSize(Value width, Value height) { if (width == null) throw new Exception("width cannot be null."); if (height == null) throw new Exception("height cannot be null."); _minWidthValue = width; _minHeightValue = height; _prefWidthValue = width; _prefHeightValue = height; _maxWidthValue = width; _maxHeightValue = height; return this; } /// <summary> /// Sets the minWidth, prefWidth, maxWidth, minHeight, prefHeight, and maxHeight to the specified value /// </summary> /// <param name="size">Size.</param> public Container SetSize(float size) { SetSize(new Value.Fixed(size)); return this; } /// <summary> /// Sets the minWidth, prefWidth, maxWidth, minHeight, prefHeight, and maxHeight to the specified values /// </summary> /// <param name="width">Width.</param> /// <param name="height">Height.</param> public new Container SetSize(float width, float height) { SetSize(new Value.Fixed(width), new Value.Fixed(height)); return this; } /// <summary> /// Sets the minWidth, prefWidth, and maxWidth to the specified value /// </summary> /// <param name="width">Width.</param> public Container SetWidth(Value width) { if (width == null) throw new Exception("width cannot be null."); _minWidthValue = width; _prefWidthValue = width; _maxWidthValue = width; return this; } /// <summary> /// Sets the minWidth, prefWidth, and maxWidth to the specified value /// </summary> /// <param name="width">Width.</param> public new Container SetWidth(float width) { SetWidth(new Value.Fixed(width)); return this; } /// <summary> /// Sets the minHeight, prefHeight, and maxHeight to the specified value. /// </summary> /// <param name="height">Height.</param> public Container SetHeight(Value height) { if (height == null) throw new Exception("height cannot be null."); _minHeightValue = height; _prefHeightValue = height; _maxHeightValue = height; return this; } /// <summary> /// Sets the minHeight, prefHeight, and maxHeight to the specified value /// </summary> /// <param name="height">Height.</param> public new Container SetHeight(float height) { SetHeight(new Value.Fixed(height)); return this; } /// <summary> /// Sets the minWidth and minHeight to the specified value /// </summary> /// <param name="size">Size.</param> public Container SetMinSize(Value size) { if (size == null) throw new Exception("size cannot be null."); _minWidthValue = size; _minHeightValue = size; return this; } /// <summary> /// Sets the minimum size. /// </summary> /// <param name="width">Width.</param> /// <param name="height">Height.</param> public Container SetMinSize(Value width, Value height) { if (width == null) throw new Exception("width cannot be null."); if (height == null) throw new Exception("height cannot be null."); _minWidthValue = width; _minHeightValue = height; return this; } public Container SetMinWidth(Value minWidth) { if (minWidth == null) throw new Exception("minWidth cannot be null."); _minWidthValue = minWidth; return this; } public Container SetMinHeight(Value minHeight) { if (minHeight == null) throw new Exception("minHeight cannot be null."); _minHeightValue = minHeight; return this; } /// <summary> /// Sets the minWidth and minHeight to the specified value /// </summary> /// <param name="size">Size.</param> public Container SetMinSize(float size) { SetMinSize(new Value.Fixed(size)); return this; } /// <summary> /// Sets the minWidth and minHeight to the specified values /// </summary> /// <param name="width">Width.</param> /// <param name="height">Height.</param> public Container SetMinSize(float width, float height) { SetMinSize(new Value.Fixed(width), new Value.Fixed(height)); return this; } public Container SetMinWidth(float minWidth) { _minWidthValue = new Value.Fixed(minWidth); return this; } public Container SetMinHeight(float minHeight) { _minHeightValue = new Value.Fixed(minHeight); return this; } /// <summary> /// Sets the prefWidth and prefHeight to the specified value. /// </summary> /// <param name="size">Size.</param> public Container PrefSize(Value size) { if (size == null) throw new Exception("size cannot be null."); _prefWidthValue = size; _prefHeightValue = size; return this; } /// <summary> /// Sets the prefWidth and prefHeight to the specified values. /// </summary> /// <param name="width">Width.</param> /// <param name="height">Height.</param> public Container PrefSize(Value width, Value height) { if (width == null) throw new Exception("width cannot be null."); if (height == null) throw new Exception("height cannot be null."); _prefWidthValue = width; _prefHeightValue = height; return this; } public Container SetPrefWidth(Value prefWidth) { if (prefWidth == null) throw new Exception("prefWidth cannot be null."); _prefWidthValue = prefWidth; return this; } public Container SetPrefHeight(Value prefHeight) { if (prefHeight == null) throw new Exception("prefHeight cannot be null."); _prefHeightValue = prefHeight; return this; } /// <summary> /// Sets the prefWidth and prefHeight to the specified value. /// </summary> /// <param name="width">Width.</param> /// <param name="height">Height.</param> public Container SetPrefSize(float width, float height) { PrefSize(new Value.Fixed(width), new Value.Fixed(height)); return this; } /// <summary> /// Sets the prefWidth and prefHeight to the specified values /// </summary> /// <param name="size">Size.</param> public Container SetPrefSize(float size) { PrefSize(new Value.Fixed(size)); return this; } public Container SetPrefWidth(float prefWidth) { _prefWidthValue = new Value.Fixed(prefWidth); return this; } public Container SetPrefHeight(float prefHeight) { _prefHeightValue = new Value.Fixed(prefHeight); return this; } /// <summary> /// Sets the maxWidth and maxHeight to the specified value. /// </summary> /// <param name="size">Size.</param> public Container SetMaxSize(Value size) { if (size == null) throw new Exception("size cannot be null."); _maxWidthValue = size; _maxHeightValue = size; return this; } /// <summary> /// Sets the maxWidth and maxHeight to the specified values /// </summary> /// <param name="width">Width.</param> /// <param name="height">Height.</param> public Container SetMaxSize(Value width, Value height) { if (width == null) throw new Exception("width cannot be null."); if (height == null) throw new Exception("height cannot be null."); _maxWidthValue = width; _maxHeightValue = height; return this; } public Container SetMaxWidth(Value maxWidth) { if (maxWidth == null) throw new Exception("maxWidth cannot be null."); _maxWidthValue = maxWidth; return this; } public Container SetMaxHeight(Value maxHeight) { if (maxHeight == null) throw new Exception("maxHeight cannot be null."); _maxHeightValue = maxHeight; return this; } /// <summary> /// Sets the maxWidth and maxHeight to the specified value /// </summary> /// <param name="size">Size.</param> public Container SetMaxSize(float size) { SetMaxSize(new Value.Fixed(size)); return this; } /// <summary> /// Sets the maxWidth and maxHeight to the specified values /// </summary> /// <param name="width">Width.</param> /// <param name="height">Height.</param> public Container SetMaxSize(float width, float height) { SetMaxSize(new Value.Fixed(width), new Value.Fixed(height)); return this; } public Container SetMaxWidth(float maxWidth) { _maxWidthValue = new Value.Fixed(maxWidth); return this; } public Container SetMaxHeight(float maxHeight) { _maxHeightValue = new Value.Fixed(maxHeight); return this; } /// <summary> /// Sets the padTop, padLeft, padBottom, and padRight to the specified value. /// </summary> /// <param name="pad">Pad.</param> public Container SetPad(Value pad) { if (pad == null) throw new Exception("pad cannot be null."); _padTop = pad; _padLeft = pad; _padBottom = pad; _padRight = pad; return this; } public Container SetPad(Value top, Value left, Value bottom, Value right) { if (top == null) throw new Exception("top cannot be null."); if (left == null) throw new Exception("left cannot be null."); if (bottom == null) throw new Exception("bottom cannot be null."); if (right == null) throw new Exception("right cannot be null."); _padTop = top; _padLeft = left; _padBottom = bottom; _padRight = right; return this; } public Container SetPadTop(Value padTop) { if (padTop == null) throw new Exception("padTop cannot be null."); _padTop = padTop; return this; } public Container SetPadLeft(Value padLeft) { if (padLeft == null) throw new Exception("padLeft cannot be null."); _padLeft = padLeft; return this; } public Container SetPadBottom(Value padBottom) { if (padBottom == null) throw new Exception("padBottom cannot be null."); _padBottom = padBottom; return this; } public Container SetPadRight(Value padRight) { if (padRight == null) throw new Exception("padRight cannot be null."); _padRight = padRight; return this; } /// <summary> /// Sets the padTop, padLeft, padBottom, and padRight to the specified value /// </summary> /// <param name="pad">Pad.</param> public Container SetPad(float pad) { Value value = new Value.Fixed(pad); _padTop = value; _padLeft = value; _padBottom = value; _padRight = value; return this; } public Container SetPad(float top, float left, float bottom, float right) { _padTop = new Value.Fixed(top); _padLeft = new Value.Fixed(left); _padBottom = new Value.Fixed(bottom); _padRight = new Value.Fixed(right); return this; } public Container SetPadTop(float padTop) { _padTop = new Value.Fixed(padTop); return this; } public Container SetPadLeft(float padLeft) { _padLeft = new Value.Fixed(padLeft); return this; } public Container SetPadBottom(float padBottom) { _padBottom = new Value.Fixed(padBottom); return this; } public Container SetPadRight(float padRight) { _padRight = new Value.Fixed(padRight); return this; } /// <summary> /// Sets fillX and fillY to 1 /// </summary> public Container SetFill() { _fillX = 1f; _fillY = 1f; return this; } /// <summary> /// Sets fillX to 1 /// </summary> public Container SetFillX() { _fillX = 1f; return this; } /// <summary> /// Sets fillY to 1 /// </summary> public Container SetFillY() { _fillY = 1f; return this; } public Container SetFill(float x, float y) { _fillX = x; _fillY = y; return this; } /// <summary> /// Sets fillX and fillY to 1 if true, 0 if false /// </summary> /// <param name="x">If set to <c>true</c> x.</param> /// <param name="y">If set to <c>true</c> y.</param> public Container SetFill(bool x, bool y) { _fillX = x ? 1f : 0; _fillY = y ? 1f : 0; return this; } /// <summary> /// Sets fillX and fillY to 1 if true, 0 if false /// </summary> /// <param name="fill">If set to <c>true</c> fill.</param> public Container SetFill(bool fill) { _fillX = fill ? 1f : 0; _fillY = fill ? 1f : 0; return this; } /// <summary> /// Sets the alignment of the element within the container. Set to {@link Align#center}, {@link Align#top}, {@link Align#bottom}, /// {@link Align#left}, {@link Align#right}, or any combination of those. /// </summary> /// <param name="align">Align.</param> public Container SetAlign(Align align) { _align = (int) align; return this; } /// <summary> /// Sets the alignment of the element within the container to {@link Align#center}. This clears any other alignment. /// </summary> public Container SetAlignCenter() { _align = AlignInternal.Center; return this; } /// <summary> /// Sets {@link Align#top} and clears {@link Align#bottom} for the alignment of the element within the container. /// </summary> public Container SetTop() { _align |= AlignInternal.Top; _align &= ~AlignInternal.Bottom; return this; } /// <summary> /// Sets {@link Align#left} and clears {@link Align#right} for the alignment of the element within the container. /// </summary> public Container SetLeft() { _align |= AlignInternal.Left; _align &= ~AlignInternal.Right; return this; } /// <summary> /// Sets {@link Align#bottom} and clears {@link Align#top} for the alignment of the element within the container. /// </summary> public Container SetBottom() { _align |= AlignInternal.Bottom; _align &= ~AlignInternal.Top; return this; } /// <summary> /// Sets {@link Align#right} and clears {@link Align#left} for the alignment of the element within the container. /// </summary> public Container SetRight() { _align |= AlignInternal.Right; _align &= ~AlignInternal.Left; return this; } public float GetMinWidth() { return _minWidthValue.Get(_element) + _padLeft.Get(this) + _padRight.Get(this); } public Value GetMinHeightValue() { return _minHeightValue; } public float GetMinHeight() { return _minHeightValue.Get(_element) + _padTop.Get(this) + _padBottom.Get(this); } public Value GetPrefWidthValue() { return _prefWidthValue; } public float GetPrefWidth() { float v = _prefWidthValue.Get(_element); if (_background != null) v = Math.Max(v, _background.MinWidth); return Math.Max(GetMinWidth(), v + _padLeft.Get(this) + _padRight.Get(this)); } public Value GetPrefHeightValue() { return _prefHeightValue; } public float GetPrefHeight() { float v = _prefHeightValue.Get(_element); if (_background != null) v = Math.Max(v, _background.MinHeight); return Math.Max(GetMinHeight(), v + _padTop.Get(this) + _padBottom.Get(this)); } public Value GetMaxWidthValue() { return _maxWidthValue; } public float GetMaxWidth() { float v = _maxWidthValue.Get(_element); if (v > 0) v += _padLeft.Get(this) + _padRight.Get(this); return v; } public Value GetMaxHeightValue() { return _maxHeightValue; } public float GetMaxHeight() { float v = _maxHeightValue.Get(_element); if (v > 0) v += _padTop.Get(this) + _padBottom.Get(this); return v; } /// <summary> /// May be null if this value is not set /// </summary> /// <returns>The pad top value.</returns> public Value GetPadTopValue() { return _padTop; } public float GetPadTop() { return _padTop.Get(this); } /// <summary> /// May be null if this value is not set /// </summary> /// <returns>The pad left value.</returns> public Value GetPadLeftValue() { return _padLeft; } public float GetPadLeft() { return _padLeft.Get(this); } /// <summary> /// May be null if this value is not set /// </summary> /// <returns>The pad bottom value.</returns> public Value GetPadBottomValue() { return _padBottom; } public float GetPadBottom() { return _padBottom.Get(this); } /// <summary> /// May be null if this value is not set /// </summary> /// <returns>The pad right value.</returns> public Value GetPadRightValue() { return _padRight; } public float GetPadRight() { return _padRight.Get(this); } /// <summary> /// Returns {@link #getPadLeft()} plus {@link #getPadRight()}. /// </summary> /// <returns>The pad x.</returns> public float GetPadX() { return _padLeft.Get(this) + _padRight.Get(this); } /// <summary> /// Returns {@link #getPadTop()} plus {@link #getPadBottom()} /// </summary> /// <returns>The pad y.</returns> public float GetPadY() { return _padTop.Get(this) + _padBottom.Get(this); } public float GetFillX() { return _fillX; } public float GetFillY() { return _fillY; } public int GetAlign() { return _align; } /// <summary> /// If true (the default), positions and sizes are rounded to integers /// </summary> /// <param name="round">If set to <c>true</c> round.</param> public void SetRound(bool round) { _round = round; } /// <summary> /// Causes the contents to be clipped if they exceed the container bounds. Enabling clipping will set /// {@link #setTransform(bool)} to true /// </summary> /// <param name="enabled">If set to <c>true</c> enabled.</param> public void SetClip(bool enabled) { _clip = enabled; transform = enabled; Invalidate(); } public bool GetClip() { return _clip; } public override Element Hit(Vector2 point) { if (_clip) { if (GetTouchable() == Touchable.Disabled) return null; if (point.X < 0 || point.X >= GetWidth() || point.Y < 0 || point.Y >= GetHeight()) return null; } return base.Hit(point); } public override void DebugRender(Batcher batcher) { Validate(); if (transform) { ApplyTransform(batcher, ComputeTransform()); if (_clip) { //shapes.flush(); //float padLeft = this.padLeft.get( this ), padBottom = this.padBottom.get( this ); //bool draw = background == null ? clipBegin( 0, 0, getWidth(), getHeight() ) : clipBegin( padLeft, padBottom, // getWidth() - padLeft - padRight.get( this ), getHeight() - padBottom - padTop.get( this ) ); var draw = true; if (draw) { DebugRenderChildren(batcher, 1f); //clipEnd(); } } else { DebugRenderChildren(batcher, 1f); } ResetTransform(batcher); } else { base.DebugRender(batcher); } } } }
22.066038
153
0.645264
1e163df4522d851f615fc286e9518f119ceea23a
4,822
cs
C#
SmartMapController/SmartMapControllerDefinition.cs
joshooaj/mipsdk-samples-plugin
0bb103aad9d1e9dfd0b13095437d86cc78d17c6e
[ "MIT" ]
6
2021-02-25T11:52:52.000Z
2022-01-30T13:37:55.000Z
SmartMapController/SmartMapControllerDefinition.cs
joshooaj/mipsdk-samples-plugin
0bb103aad9d1e9dfd0b13095437d86cc78d17c6e
[ "MIT" ]
null
null
null
SmartMapController/SmartMapControllerDefinition.cs
joshooaj/mipsdk-samples-plugin
0bb103aad9d1e9dfd0b13095437d86cc78d17c6e
[ "MIT" ]
5
2021-03-04T12:44:19.000Z
2022-03-30T09:03:44.000Z
using System; using System.Collections.Generic; using System.Drawing; using SmartMapController.Client; using VideoOS.Platform; using VideoOS.Platform.Client; namespace SmartMapController { /// <summary> /// This sample is a Smart Client view item plugin. It demonstrates how to use Message Communication to navigate /// Smart Map and listen to the information of the Smart Map position changes. /// </summary> public class SmartMapControllerDefinition : PluginDefinition { private static System.Drawing.Image _treeNodeImage; internal static Guid SmartMapControllerPluginId = new Guid("4b8e9e95-1443-4193-9332-619a9ecfb0e9"); internal static Guid SmartMapControllerKind = new Guid("49eaf8d2-eb12-4b2c-9197-82ff42fb5b90"); internal static Guid SmartMapControllerViewItemPlugin = new Guid("b4957ad3-edc3-4c67-b8ff-66ae05e2bb98"); #region Private fields // // Note that all the plugin are constructed during application start, and the constructors // should only contain code that references their own dll, e.g. resource load. private List<ViewItemPlugin> _viewItemPlugins = new List<ViewItemPlugin>(); #endregion #region Initialization /// <summary> /// Load resources /// </summary> static SmartMapControllerDefinition() { _treeNodeImage = Properties.Resources.DummyItem; } /// <summary> /// Get the icon for the plugin /// </summary> internal static Image TreeNodeImage { get { return _treeNodeImage; } } /// <summary> /// This method is called when the environment is up and running. /// Registration of Messages via RegisterReceiver can be done at this point. /// </summary> public override void Init() { // Populate all relevant lists with your plugins etc. if (EnvironmentManager.Instance.EnvironmentType == EnvironmentType.SmartClient) { _viewItemPlugins.Add(new SmartMapControllerViewItemPlugin()); } } #endregion #region Cleanup /// <summary> /// The main application is about to be in an undetermined state, either logging off or exiting. /// You can release resources at this point, it should match what you acquired during Init, so additional call to Init() will work. /// </summary> public override void Close() { _viewItemPlugins.Clear(); } #endregion #region Identification Properties /// <summary> /// Gets the unique id identifying this plugin component /// </summary> public override Guid Id { get { return SmartMapControllerPluginId; } } /// <summary> /// This Guid can be defined on several different IPluginDefinitions with the same value, /// and will result in a combination of this top level ProductNode for several plugins. /// Set to Guid.Empty if no sharing is enabled. /// </summary> public override Guid SharedNodeId { get { return PluginSamples.Common.SampleTopNode; } } /// <summary> /// Name of top level Tree node - e.g. A product name /// </summary> public override string Name { get { return "SmartMapController"; } } /// <summary> /// Top level name /// </summary> public override string SharedNodeName { get { return PluginSamples.Common.SampleNodeName; } } /// <summary> /// Company name /// </summary> public override string Manufacturer { get { return PluginSamples.Common.ManufacturerName; } } /// <summary> /// Version of this plugin. /// </summary> public override string VersionString { get { return "1.0.0.0"; } } /// <summary> /// Icon to be used on top level - e.g. a product or company logo /// </summary> public override System.Drawing.Image Icon { get { return null; } } #endregion #region Client related methods and properties /// <summary> /// A list of Client side definitions for Smart Client /// </summary> public override List<ViewItemPlugin> ViewItemPlugins { get { return _viewItemPlugins; } } #endregion } }
30.1375
139
0.574658
1e1762a3351a23add8e70c82b58b2c27968aed75
8,065
cs
C#
src/ImageInputInterface.cs
NicolasCaous/ImageInputInterface
6c59ee8559b426df5009bdad8a3832af7f999bc2
[ "MIT" ]
null
null
null
src/ImageInputInterface.cs
NicolasCaous/ImageInputInterface
6c59ee8559b426df5009bdad8a3832af7f999bc2
[ "MIT" ]
null
null
null
src/ImageInputInterface.cs
NicolasCaous/ImageInputInterface
6c59ee8559b426df5009bdad8a3832af7f999bc2
[ "MIT" ]
null
null
null
using System; using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; using UnityEngine; public class ImageInputInterface : MonoBehaviour { [DllImport("ImageInputInterface")] private static extern void AddBox(int id); [DllImport("ImageInputInterface")] private static extern void RemoveBox(int id); [DllImport("ImageInputInterface")] private static extern void Init(int mainThreadDeltaMs, int boxThreadDeltaMs, int blueThreshValue, int greenThreshValue, int redThreshValue); [DllImport("ImageInputInterface")] private static extern void Stop(); [DllImport("ImageInputInterface")] private static extern int GetStatus(); [DllImport("ImageInputInterface")] private static extern int GetMatType(); [DllImport("ImageInputInterface")] private static extern double GetBoxValue(int id); [DllImport("ImageInputInterface")] private static extern void SetBaseValues(); [DllImport("ImageInputInterface")] private static extern void GetRawImage(IntPtr data, int width, int height); [DllImport("ImageInputInterface")] private static extern void GetRawButtonMaskImage(int id, IntPtr data, int width, int height); [DllImport("ImageInputInterface")] private static extern void GetRawButtonImage(int id, IntPtr data, int width, int height); [DllImport("ImageInputInterface")] private static extern void GetMaskDetectionOutput(IntPtr data, int width, int height); [DllImport("ImageInputInterface")] public static extern int GetRawImageArrayLenght(); [DllImport("ImageInputInterface")] public static extern int GetRawImageHeight(); [DllImport("ImageInputInterface")] public static extern int GetRawImageWidth(); public int mainThreadDeltaMs; public int boxThreadDeltaMs; public int blueThreshValue = 200; public int greenThreshValue = 200; public int redThreshValue = 200; void Awake() { Debug.Log("Initialized"); Init(mainThreadDeltaMs, boxThreadDeltaMs, blueThreshValue, greenThreshValue, redThreshValue); } void OnApplicationQuit() { Debug.Log("Finished"); Stop(); } public static int GetStatusFromModule() { return GetStatus(); } public static int GetMatTypeFromModule() { return GetMatType(); } public static double GetBoxValueFromModule(int id) { return GetBoxValue(id); } public static void SetBaseValuesFromModule() { SetBaseValues(); } public sealed class RawImageSession { private static RawImageSession instance = null; private static readonly object padlock = new object(); private Texture2D tex; private Color32[] pixel32; private GCHandle pixelHandle; private RawImageSession() { this.tex = new Texture2D( ImageInputInterface.GetRawImageWidth(), ImageInputInterface.GetRawImageHeight(), TextureFormat.ARGB32, false ); this.pixel32 = tex.GetPixels32(); this.pixelHandle = GCHandle.Alloc(this.pixel32, GCHandleType.Pinned); } ~RawImageSession() { this.pixelHandle.Free(); } public static RawImageSession GetInstance() { lock (padlock) { if (instance == null) { instance = new RawImageSession(); } return instance; } } public void UpdateRawImageBytes() { GetRawImage(this.pixelHandle.AddrOfPinnedObject(), this.tex.width, this.tex.height); this.tex.SetPixels32(this.pixel32); this.tex.Apply(); } public Texture2D GetCurrent2DTexture() { return this.tex; } } public sealed class RawMaskSession { private static RawMaskSession instance = null; private static readonly object padlock = new object(); private Texture2D tex; private Color32[] pixel32; private GCHandle pixelHandle; private RawMaskSession() { this.tex = new Texture2D( ImageInputInterface.GetRawImageWidth(), ImageInputInterface.GetRawImageHeight(), TextureFormat.ARGB32, false ); this.pixel32 = tex.GetPixels32(); this.pixelHandle = GCHandle.Alloc(this.pixel32, GCHandleType.Pinned); } ~RawMaskSession() { this.pixelHandle.Free(); } public static RawMaskSession GetInstance() { lock (padlock) { if (instance == null) { instance = new RawMaskSession(); } return instance; } } public void UpdateRawImageBytes() { GetMaskDetectionOutput(this.pixelHandle.AddrOfPinnedObject(), this.tex.width, this.tex.height); this.tex.SetPixels32(this.pixel32); this.tex.Apply(); } public Texture2D GetCurrent2DTexture() { return this.tex; } } public sealed class ButtonImageSession { private static SortedDictionary<int, ButtonImageSession> instances = null; private static readonly object padlock = new object(); private bool active; private int id; private Texture2D tex; private Color32[] pixel32; private GCHandle pixelHandle; private ButtonImageSession(int id) { this.id = id; this.tex = new Texture2D( ImageInputInterface.GetRawImageWidth(), ImageInputInterface.GetRawImageHeight(), TextureFormat.ARGB32, false ); this.pixel32 = tex.GetPixels32(); this.pixelHandle = GCHandle.Alloc(this.pixel32, GCHandleType.Pinned); AddBox(this.id); this.active = true; } ~ButtonImageSession() { this.Deactivate(); } public static ButtonImageSession GetInstance(int id) { lock (padlock) { if (instances == null) { instances = new SortedDictionary<int, ButtonImageSession>(); } if (!instances.ContainsKey(id)) { instances[id] = new ButtonImageSession(id); } else if (!instances[id].active) { instances[id] = new ButtonImageSession(id); } return instances[id]; } } public static void DeactivateAll() { if (instances != null) { foreach (var instance in instances) { instance.Value.Deactivate(); } } } public void Deactivate() { this.pixelHandle.Free(); RemoveBox(this.id); this.active = false; } public void UpdateRawMaskImageBytes() { GetRawButtonMaskImage(this.id, this.pixelHandle.AddrOfPinnedObject(), this.tex.width, this.tex.height); this.tex.SetPixels32(this.pixel32); this.tex.Apply(); } public void UpdateRawImageBytes() { GetRawButtonImage(this.id, this.pixelHandle.AddrOfPinnedObject(), this.tex.width, this.tex.height); this.tex.SetPixels32(this.pixel32); this.tex.Apply(); } public Texture2D GetCurrent2DTexture() { return this.tex; } public double GetValue() { return GetBoxValue(this.id); } } }
27.714777
144
0.573342
1e17c31c9eb7c6b0b62b2d2c3872121e6154389e
6,321
cs
C#
sdk/dotnet/CustomerInsights/GetPrediction.cs
pulumi-bot/pulumi-azure-native
f7b9490b5211544318e455e5cceafe47b628e12c
[ "Apache-2.0" ]
null
null
null
sdk/dotnet/CustomerInsights/GetPrediction.cs
pulumi-bot/pulumi-azure-native
f7b9490b5211544318e455e5cceafe47b628e12c
[ "Apache-2.0" ]
null
null
null
sdk/dotnet/CustomerInsights/GetPrediction.cs
pulumi-bot/pulumi-azure-native
f7b9490b5211544318e455e5cceafe47b628e12c
[ "Apache-2.0" ]
null
null
null
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.CustomerInsights { public static class GetPrediction { /// <summary> /// The prediction resource format. /// API Version: 2017-04-26. /// </summary> public static Task<GetPredictionResult> InvokeAsync(GetPredictionArgs args, InvokeOptions? options = null) => Pulumi.Deployment.Instance.InvokeAsync<GetPredictionResult>("azure-native:customerinsights:getPrediction", args ?? new GetPredictionArgs(), options.WithVersion()); } public sealed class GetPredictionArgs : Pulumi.InvokeArgs { /// <summary> /// The name of the hub. /// </summary> [Input("hubName", required: true)] public string HubName { get; set; } = null!; /// <summary> /// The name of the Prediction. /// </summary> [Input("predictionName", required: true)] public string PredictionName { get; set; } = null!; /// <summary> /// The name of the resource group. /// </summary> [Input("resourceGroupName", required: true)] public string ResourceGroupName { get; set; } = null!; public GetPredictionArgs() { } } [OutputType] public sealed class GetPredictionResult { /// <summary> /// Whether do auto analyze. /// </summary> public readonly bool AutoAnalyze; /// <summary> /// Description of the prediction. /// </summary> public readonly ImmutableDictionary<string, string>? Description; /// <summary> /// Display name of the prediction. /// </summary> public readonly ImmutableDictionary<string, string>? DisplayName; /// <summary> /// The prediction grades. /// </summary> public readonly ImmutableArray<Outputs.PredictionResponseGrades> Grades; /// <summary> /// Resource ID. /// </summary> public readonly string Id; /// <summary> /// Interaction types involved in the prediction. /// </summary> public readonly ImmutableArray<string> InvolvedInteractionTypes; /// <summary> /// KPI types involved in the prediction. /// </summary> public readonly ImmutableArray<string> InvolvedKpiTypes; /// <summary> /// Relationships involved in the prediction. /// </summary> public readonly ImmutableArray<string> InvolvedRelationships; /// <summary> /// Definition of the link mapping of prediction. /// </summary> public readonly Outputs.PredictionResponseMappings Mappings; /// <summary> /// Resource name. /// </summary> public readonly string Name; /// <summary> /// Negative outcome expression. /// </summary> public readonly string NegativeOutcomeExpression; /// <summary> /// Positive outcome expression. /// </summary> public readonly string PositiveOutcomeExpression; /// <summary> /// Name of the prediction. /// </summary> public readonly string? PredictionName; /// <summary> /// Primary profile type. /// </summary> public readonly string PrimaryProfileType; /// <summary> /// Provisioning state. /// </summary> public readonly string ProvisioningState; /// <summary> /// Scope expression. /// </summary> public readonly string ScopeExpression; /// <summary> /// Score label. /// </summary> public readonly string ScoreLabel; /// <summary> /// System generated entities. /// </summary> public readonly Outputs.PredictionResponseSystemGeneratedEntities SystemGeneratedEntities; /// <summary> /// The hub name. /// </summary> public readonly string TenantId; /// <summary> /// Resource type. /// </summary> public readonly string Type; [OutputConstructor] private GetPredictionResult( bool autoAnalyze, ImmutableDictionary<string, string>? description, ImmutableDictionary<string, string>? displayName, ImmutableArray<Outputs.PredictionResponseGrades> grades, string id, ImmutableArray<string> involvedInteractionTypes, ImmutableArray<string> involvedKpiTypes, ImmutableArray<string> involvedRelationships, Outputs.PredictionResponseMappings mappings, string name, string negativeOutcomeExpression, string positiveOutcomeExpression, string? predictionName, string primaryProfileType, string provisioningState, string scopeExpression, string scoreLabel, Outputs.PredictionResponseSystemGeneratedEntities systemGeneratedEntities, string tenantId, string type) { AutoAnalyze = autoAnalyze; Description = description; DisplayName = displayName; Grades = grades; Id = id; InvolvedInteractionTypes = involvedInteractionTypes; InvolvedKpiTypes = involvedKpiTypes; InvolvedRelationships = involvedRelationships; Mappings = mappings; Name = name; NegativeOutcomeExpression = negativeOutcomeExpression; PositiveOutcomeExpression = positiveOutcomeExpression; PredictionName = predictionName; PrimaryProfileType = primaryProfileType; ProvisioningState = provisioningState; ScopeExpression = scopeExpression; ScoreLabel = scoreLabel; SystemGeneratedEntities = systemGeneratedEntities; TenantId = tenantId; Type = type; } } }
31.924242
178
0.595001
1e184ed8ea321a6ecf4b19736bdd6c8be9712ab8
2,058
cs
C#
xZune.Bass/Interop/Core/Dx8Chorus.cs
higankanshi/xZune.Bass
cacacc288ac3a9b08c213676ab9b0d2d6eba2eb1
[ "WTFPL" ]
11
2016-02-15T14:20:25.000Z
2018-12-21T11:49:35.000Z
xZune.Bass/Interop/Core/Dx8Chorus.cs
higankanshi/xZune.Bass
cacacc288ac3a9b08c213676ab9b0d2d6eba2eb1
[ "WTFPL" ]
null
null
null
xZune.Bass/Interop/Core/Dx8Chorus.cs
higankanshi/xZune.Bass
cacacc288ac3a9b08c213676ab9b0d2d6eba2eb1
[ "WTFPL" ]
2
2016-02-19T05:34:21.000Z
2016-11-03T01:38:37.000Z
// Project: xZune.Bass (https://github.com/higankanshi/xZune.Bass) // Filename: Dx8Chorus.cs // Version: 20160216 using System.Runtime.InteropServices; using xZune.Bass.Interop.Flags; namespace xZune.Bass.Interop.Core { /// <summary> /// Used with <see cref="FXGetParameters" /> and <see cref="FXSetParameters" /> to retrieve and set the parameters of a /// DX8 chorus effect. /// </summary> [StructLayout(LayoutKind.Sequential)] public struct Dx8Chorus { /// <summary> /// Ratio of wet (processed) signal to dry (unprocessed) signal. Must be in the range from 0 through 100 (all wet). The /// default value is 50. /// </summary> public float WetDryMix; /// <summary> /// Percentage by which the delay time is modulated by the low-frequency oscillator (LFO). Must be in the range from 0 /// through 100. The default value is 10. /// </summary> public float Depth; /// <summary> /// Percentage of output signal to feed back into the effect's input, in the range from -99 to 99. The default value is /// 25. /// </summary> public float Feedback; /// <summary> /// Frequency of the LFO, in the range from 0 to 10. The default value is 1.1. /// </summary> public float Frequency; /// <summary> /// Waveform of the LFO... 0 = triangle, 1 = sine. By default, the waveform is sine. /// </summary> public uint WaveFormat; /// <summary> /// Number of milliseconds the input is delayed before it is played back, in the range from 0 to 20. The default value /// is 16 ms. /// </summary> public float Delay; /// <summary> /// Phase differential between left and right LFOs, one of <see cref="Dx8PhaseType" />. The default value is /// <see cref="Dx8PhaseType.Phase90" />. /// </summary> public uint Phase; } }
36.105263
131
0.580661
1e1883ff6c8b842de7666011eae77f0bb0b4450d
2,254
cs
C#
NActiviti/Sys.Bpm.Rest.API/events/integration/BaseIntegrationEventImpl.cs
zhangzihan/nactivity
89f9f17ddad95f76e1a6d9221810dab631db288e
[ "Apache-2.0" ]
62
2019-06-18T00:50:33.000Z
2021-11-25T03:13:27.000Z
NActiviti/Sys.Bpm.Rest.API/events/integration/BaseIntegrationEventImpl.cs
landonzeng/nactivity
239fb02082158ad86472f17d03d314f68bc807dd
[ "Apache-2.0" ]
20
2020-04-30T06:11:37.000Z
2022-03-02T04:29:23.000Z
NActiviti/Sys.Bpm.Rest.API/events/integration/BaseIntegrationEventImpl.cs
landonzeng/nactivity
239fb02082158ad86472f17d03d314f68bc807dd
[ "Apache-2.0" ]
18
2019-05-15T12:48:04.000Z
2021-08-03T07:42:06.000Z
/* * Copyright 2017 Alfresco, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Sys.Workflow.Cloud.Services.Events.Integration { /// <summary> /// /// </summary> public abstract class BaseIntegrationEventImpl : AbstractProcessEngineEvent, IIntegrationEvent { /// <summary> /// /// </summary> public override abstract string EventType { get; } private readonly string integrationContextId; private readonly string flowNodeId; /// <summary> /// /// </summary> //used to deserialize from jsons public BaseIntegrationEventImpl() { } /// <summary> /// /// </summary> public BaseIntegrationEventImpl(string appName, string appVersion, string serviceName, string serviceFullName, string serviceType, string serviceVersion, string executionId, string processDefinitionId, string processInstanceId, string integrationContextId, string flowNodeId) : base(appName, appVersion, serviceName, serviceFullName, serviceType, serviceVersion, executionId, processDefinitionId, processInstanceId) { this.integrationContextId = integrationContextId; this.flowNodeId = flowNodeId; } /// <summary> /// /// </summary> public virtual string IntegrationContextId { get { return integrationContextId; } } /// <summary> /// /// </summary> public virtual string FlowNodeId { get { return flowNodeId; } } } }
28.175
423
0.616681
1e18a5336f730b497259e6abcc41d58cfff054e5
15,860
cs
C#
PdfSharp/PdfSharp.Pdf.AcroForms/PdfAcroField.cs
alexiej/YATE
378bf2e540f77f8363da0ac68056213462ffd7e1
[ "MS-PL" ]
18
2015-10-03T19:25:15.000Z
2021-08-18T03:56:51.000Z
PdfSharp/PdfSharp.Pdf.AcroForms/PdfAcroField.cs
alexiej/YATE
378bf2e540f77f8363da0ac68056213462ffd7e1
[ "MS-PL" ]
null
null
null
PdfSharp/PdfSharp.Pdf.AcroForms/PdfAcroField.cs
alexiej/YATE
378bf2e540f77f8363da0ac68056213462ffd7e1
[ "MS-PL" ]
7
2016-07-25T04:13:07.000Z
2021-08-18T03:56:56.000Z
#region PDFsharp - A .NET library for processing PDF // // Authors: // Stefan Lange (mailto:Stefan.Lange@pdfsharp.com) // // Copyright (c) 2005-2009 empira Software GmbH, Cologne (Germany) // // http://www.pdfsharp.com // http://sourceforge.net/projects/pdfsharp // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Diagnostics; using System.Collections; using PdfSharp.Pdf.Advanced; using PdfSharp.Pdf.Internal; namespace PdfSharp.Pdf.AcroForms { /// <summary> /// Represents the base class for all interactive field dictionaries. /// </summary> public abstract class PdfAcroField : PdfDictionary { /// <summary> /// Initializes a new instance of PdfAcroField. /// </summary> internal PdfAcroField(PdfDocument document) : base(document) { } /// <summary> /// Initializes a new instance of the <see cref="PdfAcroField"/> class. Used for type transformation. /// </summary> protected PdfAcroField(PdfDictionary dict) : base(dict) { } /// <summary> /// Gets the name of this field. /// </summary> public string Name { get { string name = Elements.GetString(Keys.T); return name; } } /// <summary> /// Gets the field flags of this instance. /// </summary> public PdfAcroFieldFlags Flags { // TODO: This entry is inheritable, thus the implementation is incorrect... id:102 gh:103 get { return (PdfAcroFieldFlags)Elements.GetInteger(Keys.Ff); } } internal PdfAcroFieldFlags SetFlags { get { return (PdfAcroFieldFlags)Elements.GetInteger(Keys.Ff); } set { Elements.SetInteger(Keys.Ff, (int)value); } } /// <summary> /// Gets or sets the value of the field. /// </summary> public PdfItem Value { get { return Elements[Keys.V]; } set { if (ReadOnly) throw new InvalidOperationException("The field is read only."); if (value is PdfString || value is PdfName) Elements[Keys.V] = value; else throw new NotImplementedException("Values other than string cannot be set."); } } /// <summary> /// Gets or sets a value indicating whether the field is read only. /// </summary> public bool ReadOnly { get { return (Flags & PdfAcroFieldFlags.ReadOnly) != 0; } set { if (value) SetFlags |= PdfAcroFieldFlags.ReadOnly; else SetFlags &= ~PdfAcroFieldFlags.ReadOnly; } } /// <summary> /// Gets the field with the specified name. /// </summary> public PdfAcroField this[string name] { get { return GetValue(name); } } /// <summary> /// Gets a child field by name. /// </summary> protected virtual PdfAcroField GetValue(string name) { if (name == null || name.Length == 0) return this; if (HasKids) return Fields.GetValue(name); return null; } /// <summary> /// Indicates whether the field has child fields. /// </summary> public bool HasKids { get { PdfItem item = Elements[Keys.Kids]; if (item == null) return false; if (item is PdfArray) return ((PdfArray)item).Elements.Count > 0; return false; } } /// <summary> /// Gets the names of all descendants of this field. /// </summary> public string[] DescendantNames { get { List<PdfName> names = new List<PdfName>(); if (HasKids) { PdfAcroFieldCollection fields = Fields; fields.GetDescendantNames(ref names, null); } List<string> temp = new List<string>(); foreach (PdfName name in names) temp.Add(name.ToString()); return temp.ToArray(); } } internal virtual void GetDescendantNames(ref List<PdfName> names, string partialName) { if (HasKids) { PdfAcroFieldCollection fields = Fields; string t = Elements.GetString(Keys.T); Debug.Assert(t != ""); if (t.Length > 0) { if (partialName != null && partialName.Length > 0) partialName += "." + t; else partialName = t; fields.GetDescendantNames(ref names, partialName); } } else { string t = Elements.GetString(Keys.T); Debug.Assert(t != ""); if (t.Length > 0) { if (!String.IsNullOrEmpty(partialName)) names.Add(new PdfName(partialName + "." + t)); else names.Add(new PdfName(t)); } } } /// <summary> /// Gets the collection of fields within this field. /// </summary> public PdfAcroField.PdfAcroFieldCollection Fields { get { if (this.fields == null) { object o = Elements.GetValue(Keys.Kids, VCF.CreateIndirect); this.fields = (PdfAcroField.PdfAcroFieldCollection)o; } return this.fields; } } PdfAcroField.PdfAcroFieldCollection fields; /// <summary> /// Holds a collection of interactive fields. /// </summary> public sealed class PdfAcroFieldCollection : PdfArray { PdfAcroFieldCollection(PdfArray array) : base(array) { } /// <summary> /// Gets the names of all fields in the collection. /// </summary> public string[] Names { get { int count = Elements.Count; string[] names = new string[count]; for (int idx = 0; idx < count; idx++) names[idx] = ((PdfDictionary)((PdfReference)Elements[idx]).Value).Elements.GetString(Keys.T); return names; } } /// <summary> /// Gets an array of all descendant names. /// </summary> public string[] DescendantNames { get { List<PdfName> names = new List<PdfName>(); GetDescendantNames(ref names, null); List<string> temp = new List<string>(); foreach (PdfName name in names) temp.Add(name.ToString()); return temp.ToArray(); } } internal void GetDescendantNames(ref List<PdfName> names, string partialName) { int count = Elements.Count; for (int idx = 0; idx < count; idx++) { PdfAcroField field = this[idx]; Debug.Assert(field != null); if (field != null) field.GetDescendantNames(ref names, partialName); } } /// <summary> /// Gets a field from the collection. For your convenience an instance of a derived class like /// PdfTextField or PdfCheckBox is returned if PDFsharp can guess the actual type of the dictionary. /// If the actual type cannot be guessed by PDFsharp the function returns an instance /// of PdfGenericField. /// </summary> public PdfAcroField this[int index] { get { PdfItem item = Elements[index]; Debug.Assert(item is PdfReference); PdfDictionary dict = ((PdfReference)item).Value as PdfDictionary; Debug.Assert(dict != null); PdfAcroField field = dict as PdfAcroField; if (field == null && dict != null) { // Do type transformation field = CreateAcroField(dict); //Elements[index] = field.XRef; } return field; } } /// <summary> /// Gets the field with the specified name. /// </summary> public PdfAcroField this[string name] { get { return GetValue(name); } } internal PdfAcroField GetValue(string name) { if (name == null || name.Length == 0) return null; int dot = name.IndexOf('.'); string prefix = dot == -1 ? name : name.Substring(0, dot); string suffix = dot == -1 ? "" : name.Substring(dot + 1); int count = Elements.Count; for (int idx = 0; idx < count; idx++) { PdfAcroField field = this[idx]; if (field.Name == prefix) return field.GetValue(suffix); } return null; } /// <summary> /// Create a derived type like PdfTextField or PdfCheckBox if possible. /// If the actual cannot be guessed by PDFsharp the function returns an instance /// of PdfGenericField. /// </summary> PdfAcroField CreateAcroField(PdfDictionary dict) { string ft = dict.Elements.GetName(Keys.FT); PdfAcroFieldFlags flags = (PdfAcroFieldFlags)dict.Elements.GetInteger(Keys.Ff); switch (ft) { case "/Btn": if ((flags & PdfAcroFieldFlags.Pushbutton) != 0) return new PdfPushButtonField(dict); else if ((flags & PdfAcroFieldFlags.Radio) != 0) return new PdfRadioButtonField(dict); else return new PdfCheckBoxField(dict); case "/Tx": return new PdfTextField(dict); case "/Ch": if ((flags & PdfAcroFieldFlags.Combo) != 0) return new PdfComboBoxField(dict); else return new PdfListBoxField(dict); case "/Sig": return new PdfSignatureField(dict); default: return new PdfGenericField(dict); } } } /// <summary> /// Predefined keys of this dictionary. /// The description comes from PDF 1.4 Reference. /// </summary> public class Keys : KeysBase { /// <summary> /// (Required for terminal fields; inheritable) The type of field that this dictionary /// describes: /// Btn Button /// Tx Text /// Ch Choice /// Sig (PDF 1.3) Signature /// Note: This entry may be present in a nonterminal field (one whose descendants /// are themselves fields) in order to provide an inheritable FT value. However, a /// nonterminal field does not logically have a type of its own; it is merely a container /// for inheritable attributes that are intended for descendant terminal fields of /// any type. /// </summary> [KeyInfo(KeyType.Name | KeyType.Required)] public const string FT = "/FT"; /// <summary> /// (Required if this field is the child of another in the field hierarchy; absent otherwise) /// The field that is the immediate parent of this one (the field, if any, whose Kids array /// includes this field). A field can have at most one parent; that is, it can be included /// in the Kids array of at most one other field. /// </summary> [KeyInfo(KeyType.Dictionary)] public const string Parent = "/Parent"; /// <summary> /// (Optional) An array of indirect references to the immediate children of this field. /// </summary> [KeyInfo(KeyType.Array | KeyType.Optional, typeof(PdfAcroField.PdfAcroFieldCollection))] public const string Kids = "/Kids"; /// <summary> /// (Optional) The partial field name. /// </summary> [KeyInfo(KeyType.TextString | KeyType.Optional)] public const string T = "/T"; /// <summary> /// (Optional; PDF 1.3) An alternate field name, to be used in place of the actual /// field name wherever the field must be identified in the user interface (such as /// in error or status messages referring to the field). This text is also useful /// when extracting the document�s contents in support of accessibility to disabled /// users or for other purposes. /// </summary> [KeyInfo(KeyType.TextString | KeyType.Optional)] public const string TU = "/TU"; /// <summary> /// (Optional; PDF 1.3) The mapping name to be used when exporting interactive form field /// data from the document. /// </summary> [KeyInfo(KeyType.TextString | KeyType.Optional)] public const string TM = "/TM"; /// <summary> /// (Optional; inheritable) A set of flags specifying various characteristics of the field. /// Default value: 0. /// </summary> [KeyInfo(KeyType.Integer | KeyType.Optional)] public const string Ff = "/Ff"; /// <summary> /// (Optional; inheritable) The field�s value, whose format varies depending on /// the field type; see the descriptions of individual field types for further information. /// </summary> [KeyInfo(KeyType.Various | KeyType.Optional)] public const string V = "/V"; /// <summary> /// (Optional; inheritable) The default value to which the field reverts when a /// reset-form action is executed. The format of this value is the same as that of V. /// </summary> [KeyInfo(KeyType.Various | KeyType.Optional)] public const string DV = "/DV"; /// <summary> /// (Optional; PDF 1.2) An additional-actions dictionary defining the field�s behavior /// in response to various trigger events. This entry has exactly the same meaning as /// the AA entry in an annotation dictionary. /// </summary> [KeyInfo(KeyType.Dictionary | KeyType.Optional)] public const string AA = "/AA"; // ----- Additional entries to all fields containing variable text -------------------------- /// <summary> /// (Required; inheritable) A resource dictionary containing default resources /// (such as fonts, patterns, or color spaces) to be used by the appearance stream. /// At a minimum, this dictionary must contain a Font entry specifying the resource /// name and font dictionary of the default font for displaying the field�s text. /// </summary> [KeyInfo(KeyType.Dictionary | KeyType.Required)] public const string DR = "/DR"; /// <summary> /// (Required; inheritable) The default appearance string, containing a sequence of /// valid page-content graphics or text state operators defining such properties as /// the field�s text size and color. /// </summary> [KeyInfo(KeyType.String | KeyType.Required)] public const string DA = "/DA"; /// <summary> /// (Optional; inheritable) A code specifying the form of quadding (justification) /// to be used in displaying the text: /// 0 Left-justified /// 1 Centered /// 2 Right-justified /// Default value: 0 (left-justified). /// </summary> [KeyInfo(KeyType.Integer | KeyType.Optional)] public const string Q = "/Q"; } } }
32.836439
106
0.597163
1e18c2c634e095a57cb94b7c470675351eac63bb
4,868
cs
C#
src/libraries/Common/src/System/Security/Cryptography/Asn1/Pkcs7/EncryptedContentInfoAsn.xml.cs
belav/runtime
bf1b5cca64a43d7e8d309fc74e83bcdf363c5090
[ "MIT" ]
null
null
null
src/libraries/Common/src/System/Security/Cryptography/Asn1/Pkcs7/EncryptedContentInfoAsn.xml.cs
belav/runtime
bf1b5cca64a43d7e8d309fc74e83bcdf363c5090
[ "MIT" ]
null
null
null
src/libraries/Common/src/System/Security/Cryptography/Asn1/Pkcs7/EncryptedContentInfoAsn.xml.cs
belav/runtime
bf1b5cca64a43d7e8d309fc74e83bcdf363c5090
[ "MIT" ]
null
null
null
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #pragma warning disable SA1028 // ignore whitespace warnings for generated code using System; using System.Formats.Asn1; using System.Runtime.InteropServices; namespace System.Security.Cryptography.Asn1.Pkcs7 { [StructLayout(LayoutKind.Sequential)] internal partial struct EncryptedContentInfoAsn { internal string ContentType; internal System.Security.Cryptography.Asn1.AlgorithmIdentifierAsn ContentEncryptionAlgorithm; internal ReadOnlyMemory<byte>? EncryptedContent; internal void Encode(AsnWriter writer) { Encode(writer, Asn1Tag.Sequence); } internal void Encode(AsnWriter writer, Asn1Tag tag) { writer.PushSequence(tag); try { writer.WriteObjectIdentifier(ContentType); } catch (ArgumentException e) { throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding, e); } ContentEncryptionAlgorithm.Encode(writer); if (EncryptedContent.HasValue) { writer.WriteOctetString( EncryptedContent.Value.Span, new Asn1Tag(TagClass.ContextSpecific, 0) ); } writer.PopSequence(tag); } internal static EncryptedContentInfoAsn Decode( ReadOnlyMemory<byte> encoded, AsnEncodingRules ruleSet ) { return Decode(Asn1Tag.Sequence, encoded, ruleSet); } internal static EncryptedContentInfoAsn Decode( Asn1Tag expectedTag, ReadOnlyMemory<byte> encoded, AsnEncodingRules ruleSet ) { try { AsnValueReader reader = new AsnValueReader(encoded.Span, ruleSet); DecodeCore(ref reader, expectedTag, encoded, out EncryptedContentInfoAsn decoded); reader.ThrowIfNotEmpty(); return decoded; } catch (AsnContentException e) { throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding, e); } } internal static void Decode( ref AsnValueReader reader, ReadOnlyMemory<byte> rebind, out EncryptedContentInfoAsn decoded ) { Decode(ref reader, Asn1Tag.Sequence, rebind, out decoded); } internal static void Decode( ref AsnValueReader reader, Asn1Tag expectedTag, ReadOnlyMemory<byte> rebind, out EncryptedContentInfoAsn decoded ) { try { DecodeCore(ref reader, expectedTag, rebind, out decoded); } catch (AsnContentException e) { throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding, e); } } private static void DecodeCore( ref AsnValueReader reader, Asn1Tag expectedTag, ReadOnlyMemory<byte> rebind, out EncryptedContentInfoAsn decoded ) { decoded = default; AsnValueReader sequenceReader = reader.ReadSequence(expectedTag); ReadOnlySpan<byte> rebindSpan = rebind.Span; int offset; ReadOnlySpan<byte> tmpSpan; decoded.ContentType = sequenceReader.ReadObjectIdentifier(); System.Security.Cryptography.Asn1.AlgorithmIdentifierAsn.Decode( ref sequenceReader, rebind, out decoded.ContentEncryptionAlgorithm ); if ( sequenceReader.HasData && sequenceReader .PeekTag() .HasSameClassAndValue(new Asn1Tag(TagClass.ContextSpecific, 0)) ) { if ( sequenceReader.TryReadPrimitiveOctetString( out tmpSpan, new Asn1Tag(TagClass.ContextSpecific, 0) ) ) { decoded.EncryptedContent = rebindSpan.Overlaps(tmpSpan, out offset) ? rebind.Slice(offset, tmpSpan.Length) : tmpSpan.ToArray(); } else { decoded.EncryptedContent = sequenceReader.ReadOctetString( new Asn1Tag(TagClass.ContextSpecific, 0) ); } } sequenceReader.ThrowIfNotEmpty(); } } }
32.026316
101
0.549096
1e1a657058f85b7a96851a85c3d18a0fef02bbdf
4,276
cs
C#
WWCP_OICPv2.3/DataTypes/Enums/RFIDTypes.cs
OpenChargingCloud/WWCP_OICP
a245e7b9ae0cdcd46002adbf5d45761af5accabd
[ "Apache-2.0" ]
4
2016-12-25T13:52:49.000Z
2020-10-18T12:03:29.000Z
WWCP_OICPv2.3/DataTypes/Enums/RFIDTypes.cs
OpenChargingCloud/WWCP_OICP
a245e7b9ae0cdcd46002adbf5d45761af5accabd
[ "Apache-2.0" ]
null
null
null
WWCP_OICPv2.3/DataTypes/Enums/RFIDTypes.cs
OpenChargingCloud/WWCP_OICP
a245e7b9ae0cdcd46002adbf5d45761af5accabd
[ "Apache-2.0" ]
1
2021-09-17T19:24:16.000Z
2021-09-17T19:24:16.000Z
/* * Copyright (c) 2014-2021 GraphDefined GmbH * This file is part of WWCP OICP <https://github.com/OpenChargingCloud/WWCP_OICP> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #region Usings using System; #endregion namespace cloud.charging.open.protocols.OICPv2_3 { /// <summary> /// Extentions methods for RFID types. /// </summary> public static class RFIDTypesExtentions { #region Parse (Text) /// <summary> /// Parses the given text-representation of a RFID type. /// </summary> /// <param name="Text">A text-representation of a RFID type.</param> public static RFIDTypes Parse(String Text) { if (TryParse(Text, out RFIDTypes rfidType)) return rfidType; throw new ArgumentException("Undefined RFID type '" + Text + "'!"); } #endregion #region TryParse(Text) /// <summary> /// Parses the given text-representation of a RFID type. /// </summary> /// <param name="Text">A text-representation of a RFID type.</param> public static RFIDTypes? TryParse(String Text) { if (TryParse(Text, out RFIDTypes rfidType)) return rfidType; return default; } #endregion #region TryParse(Text, out RFIDType) /// <summary> /// Parses the given text-representation of a RFID type. /// </summary> /// <param name="Text">A text-representation of a RFID type.</param> /// <param name="RFIDType">The parsed RFID type.</param> public static Boolean TryParse(String Text, out RFIDTypes RFIDType) { switch (Text?.Trim()) { case "mifareCls": RFIDType = RFIDTypes.MifareClassic; return true; case "mifareDes": RFIDType = RFIDTypes.MifareDESFire; return true; case "calypso": RFIDType = RFIDTypes.Calypso; return true; case "nfc": RFIDType = RFIDTypes.NFC; return true; case "mifareFamily": RFIDType = RFIDTypes.MifareFamily; return true; default: RFIDType = RFIDTypes.MifareFamily; return false; }; } #endregion #region AsString(RFIDType) /// <summary> /// Return a text-representation of the given RFID type. /// </summary> /// <param name="RFIDType">A RFID type.</param> public static String AsString(this RFIDTypes RFIDType) => RFIDType switch { RFIDTypes.MifareClassic => "mifareCls", RFIDTypes.MifareDESFire => "mifareDes", RFIDTypes.Calypso => "calypso", RFIDTypes.NFC => "nfc", RFIDTypes.MifareFamily => "mifareFamily", _ => "unknown", }; #endregion } /// <summary> /// RFID types. /// </summary> public enum RFIDTypes { /// <summary> /// MiFare classic. /// </summary> MifareClassic, /// <summary> /// MiFare DESFire. /// </summary> MifareDESFire, /// <summary> /// Calypso. /// </summary> Calypso, /// <summary> /// NFC. /// </summary> NFC, /// <summary> /// MiFare family. /// </summary> MifareFamily } }
25.915152
82
0.521749
1e1cb9fb9d8c014f3689f29b86f60fa4963e886d
2,104
cs
C#
src/Workspaces/Core/Portable/PatternMatching/SimplePatternMatcher.cs
frandesc/roslyn
72a99a8279c9ccbb2ef3a99d5a8bf116a14ebf3b
[ "MIT" ]
17,923
2015-01-14T23:40:37.000Z
2022-03-31T18:10:52.000Z
src/Workspaces/Core/Portable/PatternMatching/SimplePatternMatcher.cs
open-dotnet/roslyn
2e26701b0d1cb1a902a24f4ad8b8c5fe70514581
[ "MIT" ]
48,991
2015-01-15T00:29:35.000Z
2022-03-31T23:48:56.000Z
src/Workspaces/Core/Portable/PatternMatching/SimplePatternMatcher.cs
open-dotnet/roslyn
2e26701b0d1cb1a902a24f4ad8b8c5fe70514581
[ "MIT" ]
5,209
2015-01-14T23:40:24.000Z
2022-03-30T20:15:03.000Z
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Globalization; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Collections; namespace Microsoft.CodeAnalysis.PatternMatching { internal partial class PatternMatcher { private sealed partial class SimplePatternMatcher : PatternMatcher { private PatternSegment _fullPatternSegment; public SimplePatternMatcher( string pattern, CultureInfo culture, bool includeMatchedSpans, bool allowFuzzyMatching) : base(includeMatchedSpans, culture, allowFuzzyMatching) { pattern = pattern.Trim(); _fullPatternSegment = new PatternSegment(pattern, allowFuzzyMatching); _invalidPattern = _fullPatternSegment.IsInvalid; } public override void Dispose() { base.Dispose(); _fullPatternSegment.Dispose(); } /// <summary> /// Determines if a given candidate string matches under a multiple word query text, as you /// would find in features like Navigate To. /// </summary> /// <returns>If this was a match, a set of match types that occurred while matching the /// patterns. If it was not a match, it returns null.</returns> public override bool AddMatches(string candidate, ref TemporaryArray<PatternMatch> matches) { if (SkipMatch(candidate)) { return false; } return MatchPatternSegment(candidate, in _fullPatternSegment, ref matches, fuzzyMatch: false) || MatchPatternSegment(candidate, in _fullPatternSegment, ref matches, fuzzyMatch: true); } } } }
36.912281
112
0.60884
1e1e6381c46b6059d0c487d71f09b3fbbb7c28e8
1,510
cs
C#
Assets/Scripts/Enemigos/Enemy.cs
XenMoros/ProjectAlpaca
0eab5a670a6d385a4e2cfa1463a04bb66b0fbbd3
[ "MIT" ]
1
2022-01-20T23:56:32.000Z
2022-01-20T23:56:32.000Z
Assets/Scripts/Enemigos/Enemy.cs
XenMoros/ProjectAlpaca
0eab5a670a6d385a4e2cfa1463a04bb66b0fbbd3
[ "MIT" ]
null
null
null
Assets/Scripts/Enemigos/Enemy.cs
XenMoros/ProjectAlpaca
0eab5a670a6d385a4e2cfa1463a04bb66b0fbbd3
[ "MIT" ]
null
null
null
using UnityEngine; public class Enemy : MonoBehaviour, IActivable { // Clase padre de todos los enemigos public bool pausa = true, active = true; // Los enemigos pueden pausarse o estar desactivados public EnemyManager enemyManager; // El manager de enemigos public enum TipoEnemigo { Guardia, Camara}; public TipoEnemigo tipoEnemigo; private void OnEnable() { StaticManager.OnPauseChange += SetPause; } private void OnDisable() { StaticManager.OnPauseChange -= SetPause; } public virtual void SetPause() { // Funcion para poner la pausa segun la clase estatica pausa = StaticManager.pause; } public virtual void SetActivationState(bool activateState) { // Activar o desactivar el enemigo segun entrada active = activateState; } public void SetActivationState() { // Activar el enemigo (sin entrada se activa automaticamente) SetActivationState(true); } public void SetActivationState(int activateState) { // Activar enemigo segun entrada numerica, 0 desactivado sino activado if (activateState > 0) { SetActivationState(true); } SetActivationState(false); } public void SetEnemyManager(EnemyManager manager) { // Set de el enemyManager segun entrada enemyManager = manager; } public virtual void AlertarEnemigo(Vector3 position) { } }
27.454545
98
0.646358
1e1ee98c74b40db0c874db9498a896442907e070
11,324
cs
C#
Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/UrlParamsMapperBase.cs
Sitefinity/feather
036ee2054f076281cae79ce54103f5eb1eba5242
[ "Apache-2.0" ]
89
2015-01-06T14:03:34.000Z
2021-11-22T21:34:54.000Z
Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/UrlParamsMapperBase.cs
Sitefinity/feather
036ee2054f076281cae79ce54103f5eb1eba5242
[ "Apache-2.0" ]
1,643
2015-01-06T09:48:36.000Z
2022-01-27T20:02:02.000Z
Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/UrlParamsMapperBase.cs
Sitefinity/feather
036ee2054f076281cae79ce54103f5eb1eba5242
[ "Apache-2.0" ]
84
2015-01-06T08:35:07.000Z
2021-05-17T14:00:48.000Z
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Web.Mvc; using System.Web.Routing; using Telerik.Sitefinity.Abstractions; using Telerik.Sitefinity.Configuration; namespace Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Routing { /// <summary> /// A base URL params mapper that provides responsibility chain logic. /// </summary> internal abstract class UrlParamsMapperBase : IUrlParamsMapper { /// <summary> /// Initializes a new instance of the <see cref="UrlParamsMapperBase"/> class. /// </summary> /// <param name="controller">The controller.</param> public UrlParamsMapperBase(ControllerBase controller) { this.Controller = controller; } /// <summary> /// Gets a value indicating whether to require parameter naming in the widget routings. /// </summary> /// <value> /// <c>true</c> if the routes will work only with named params (e.g /tag/sofia/page/2); otherwise, <c>false</c> when the route will be /sofia/2. /// </value> public static bool UseNamedParametersRouting { get { return Config.Get<FeatherConfig>().UseNamedParametersRouting; } } /// <inheritdoc /> public IUrlParamsMapper Next { get { return this.next; } } /// <inheritdoc /> public IUrlParamsMapper SetNext(IUrlParamsMapper nextResolver) { this.next = nextResolver; return this.Next; } /// <inheritdoc /> public void ResolveUrlParams(string[] urlParams, RequestContext requestContext) { this.ResolveUrlParams(urlParams, requestContext, null); } /// <inheritdoc /> public void ResolveUrlParams(string[] urlParams, RequestContext requestContext, string urlKeyPrefix) { var isMatch = this.TryMatchUrl(urlParams, requestContext, urlKeyPrefix); if (!isMatch && this.Next != null) this.Next.ResolveUrlParams(urlParams, requestContext, urlKeyPrefix); } /// <summary> /// Gets the controller. /// </summary> /// <value> /// The controller. /// </value> protected ControllerBase Controller { get; private set; } /// <summary> /// Creates parameter map in order to map the URL parameters to the provided URL template /// </summary> /// <param name="actionMethod">The action method.</param> /// <param name="metaParams">The meta parameters.</param> /// <param name="urlParams">The URL parameters.</param> /// <param name="urlParamNames">The URL parameter names.</param> /// <returns></returns> protected virtual IList<UrlSegmentInfo> MapParams(MethodInfo actionMethod, string[] metaParams, string[] urlParams, string[] urlParamNames) { var useNamedParams = UrlParamsMapperBase.UseNamedParametersRouting; if (!useNamedParams && (metaParams.Length != urlParams.Length || metaParams.Length != urlParamNames.Length)) return null; if (useNamedParams && ((2 * metaParams.Length) != urlParams.Length || metaParams.Length != urlParamNames.Length)) return null; var parameterInfos = new List<UrlSegmentInfo>(); for (int i = 0; i < urlParamNames.Length; i++) { string currentParam = useNamedParams ? this.MapNamedParam(urlParams, urlParamNames[i], i) : urlParams[i]; if (metaParams[i].Length > 2 && metaParams[i].First() == '{' && metaParams[i].Last() == '}') { var routeParam = metaParams[i].Sub(1, metaParams[i].Length - 2); routeParam = useNamedParams ? this.MapNamedRouteParam(urlParams, urlParamNames[i], i, routeParam) : routeParam; if (!this.TryResolveRouteParam(actionMethod, routeParam, currentParam, parameterInfos)) return null; } else if (!string.Equals(metaParams[i], currentParam, StringComparison.OrdinalIgnoreCase)) { return null; } } return parameterInfos; } /// <summary> /// Maps the URL parameter to a value from the provided URL template /// </summary> /// <param name="urlParams">The URL parameters.</param> /// <param name="urlParamName">The URL parameter name.</param> /// <param name="paramNameIndex">The index of the named parameter in the URL.</param> /// <returns></returns> protected virtual string MapNamedParam(string[] urlParams, string urlParamName, int paramNameIndex) { string currentParam; var urlParamActualIndex = 2 * paramNameIndex; if (urlParamName != FeatherActionInvoker.TaxonNamedParamter) { var namedParamIndex = Array.IndexOf(urlParams, urlParamName); if (namedParamIndex == -1 || urlParams.Length < namedParamIndex) return null; currentParam = urlParams[namedParamIndex + 1]; } else if (urlParamName == FeatherActionInvoker.TaxonNamedParamter && urlParams.Length > (urlParamActualIndex + 1)) { // in this case, in the url will be presented the name of the taxonomy, ex. tag/tag1/page/2 ; category/cat1/page/2 currentParam = urlParams[urlParamActualIndex + 1]; var taxonomyName = urlParams[urlParamActualIndex]; if (taxonomyName.ToLowerInvariant() == "categories") taxonomyName = "category"; if (taxonomyName.ToLowerInvariant() == "tags") taxonomyName = "tag"; var isResolverRegistered = ObjectFactory.IsTypeRegistered<IRouteParamResolver>(taxonomyName.ToLowerInvariant()); if (!isResolverRegistered) return null; } else return null; return currentParam; } /// <summary> /// Maps the classification URL parameter to a value from the provided URL template /// </summary> /// <param name="urlParams">The URL parameters.</param> /// <param name="urlParamName">The URL parameter name.</param> /// <param name="paramNameIndex">The index of the named parameter in the URL.</param> /// <param name="routeParam">The value of the route param from meta params.</param> /// <returns></returns> protected virtual string MapNamedRouteParam(string[] urlParams, string urlParamName, int paramNameIndex, string routeParam) { var urlParamActualIndex = 2 * paramNameIndex; if (routeParam.IndexOf(":") > 0 && urlParamName == FeatherActionInvoker.TaxonNamedParamter && urlParams.Length > (urlParamActualIndex + 1)) { // in this case, in the url will be presented the name of the taxonomy, ex. tag/tag1/page/2 ; category/cat1/page/2 var taxonomyName = urlParams[urlParamActualIndex]; if (taxonomyName.ToLowerInvariant() == "categories") taxonomyName = "category"; if (taxonomyName.ToLowerInvariant() == "tags") taxonomyName = "tag"; var isResolverRegistered = ObjectFactory.IsTypeRegistered<IRouteParamResolver>(taxonomyName.ToLowerInvariant()); if (!isResolverRegistered) return null; var parts = routeParam.Split(':'); return parts[0] + ":" + taxonomyName; } return routeParam; } /// <summary> /// Tries to resolve route parameters and map them to specific part of the url. /// </summary> /// <remarks> /// If needed tries to interpret the route value through <see cref="Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Routing.IRouteParamResolver"/> /// </remarks> /// <param name="actionMethod">The action method.</param> /// <param name="routeParam">The route parameter.</param> /// <param name="urlParam">The URL parameter.</param> /// <param name="parameterInfos">The parameter info.</param> /// <returns></returns> protected bool TryResolveRouteParam(MethodInfo actionMethod, string routeParam, string urlParam, IList<UrlSegmentInfo> parameterInfos) { if (routeParam.IsNullOrEmpty()) return false; var parts = routeParam.Split(':'); var paramName = parts[0]; object paramValue = urlParam; if (parts.Length >= 2) { var actionParam = actionMethod.GetParameters().FirstOrDefault(p => p.Name == paramName); if (actionParam != null) { var routeConstraints = parts[1] .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries) .Select(r => r.Trim()); IRouteParamResolver first = null; IRouteParamResolver last = null; foreach (var resolverName in routeConstraints) { var resolver = ObjectFactory.Resolve<IRouteParamResolver>(resolverName); if (resolver != null) { if (last != null) { last = last.SetNext(resolver); } else { first = last = resolver; } } } if (first == null || first.TryResolveParam(urlParam, out paramValue) == false) return false; } } var paramInfo = new UrlSegmentInfo(); paramInfo.ParameterName = paramName; if (parts.Length >= 2) { paramInfo.ResolverName = parts[1]; } paramInfo.ParameterValue = paramValue; parameterInfos.Add(paramInfo); return true; } /// <summary> /// Matches the URL parameters. /// </summary> /// <param name="urlParams">The URL parameters.</param> /// <param name="requestContext">The request context.</param> /// <param name="urlKeyPrefix">The URL key prefix.</param> /// <returns>true if resolving was successful. In this case does not fallback to next mappers. Else returns false</returns> protected abstract bool TryMatchUrl(string[] urlParams, RequestContext requestContext, string urlKeyPrefix); /// <summary> /// The action name key for the RouteData values. /// </summary> protected const string ActionNameKey = "action"; private IUrlParamsMapper next; } }
41.940741
153
0.565525
1e1ef09fcf2780a789504b591778373e3d28a423
2,175
cs
C#
BizHawk.Client.Common/tools/Watch/SeparatorWatch.cs
tustin2121/tpp-BizHawk2
5fc985ef61044799753fced4489b534524523666
[ "MIT" ]
29
2017-10-25T15:16:23.000Z
2021-02-23T04:49:18.000Z
BizHawk.Client.Common/tools/Watch/SeparatorWatch.cs
tustin2121/tpp-BizHawk2
5fc985ef61044799753fced4489b534524523666
[ "MIT" ]
1
2021-06-08T10:20:02.000Z
2021-06-08T10:20:02.000Z
BizHawk.Client.Common/tools/Watch/SeparatorWatch.cs
tustin2121/tpp-BizHawk2
5fc985ef61044799753fced4489b534524523666
[ "MIT" ]
9
2017-10-29T05:28:15.000Z
2020-03-24T02:11:01.000Z
using System.Collections.Generic; namespace BizHawk.Client.Common { /// <summary> /// This class holds a separator for RamWatch /// Use the static property Instance to get it /// </summary> public sealed class SeparatorWatch : Watch { /// <summary> /// Initializes a new instance of the <see cref="SeparatorWatch"/> class. /// </summary> internal SeparatorWatch() : base(null, 0, WatchSize.Separator, DisplayType.Separator, true, "") { } /// <summary> /// Gets the separator instance /// </summary> public static SeparatorWatch Instance => new SeparatorWatch(); /// <summary> /// Get the appropriate DisplayType /// </summary> /// <returns>DisplayType.Separator nothing else</returns> public override IEnumerable<DisplayType> AvailableTypes() { yield return DisplayType.Separator; } /// <summary> /// Ignore that stuff /// </summary> public override int Value => 0; /// <summary> /// Ignore that stuff /// </summary> public override int ValueNoFreeze => 0; /// <summary> /// Ignore that stuff /// </summary> public override int Previous => 0; /// <summary> /// Ignore that stuff /// </summary> public override string ValueString => ""; /// <summary> /// Ignore that stuff /// </summary> public override string PreviousStr => ""; /// <summary> /// TTransform the current instance into a displayable (short representation) string /// It's used by the "Display on screen" option in the RamWatch window /// </summary> /// <returns>A well formatted string representation</returns> public override string ToDisplayString() { return "----"; } /// <summary> /// Ignore that stuff /// </summary> public override bool Poke(string value) { return false; } /// <summary> /// Ignore that stuff /// </summary> public override void ResetPrevious() { } /// <summary> /// Ignore that stuff /// </summary> public override string Diff => ""; /// <summary> /// Ignore that stuff /// </summary> public override uint MaxValue => 0; /// <summary> /// Ignore that stuff /// </summary> public override void Update() { } } }
21.534653
86
0.634943
1e1f2b009be29f7860be6f4d385d8e71b32936cf
4,081
cs
C#
MvxBitmap.Droid/ConcurrentImageCache.cs
SeeD-Seifer/MvxBitmap
cdffb965e3745140c55bd429e05251e973f9afd5
[ "MIT" ]
1
2016-04-08T17:39:46.000Z
2016-04-08T17:39:46.000Z
MvxBitmap.Droid/ConcurrentImageCache.cs
SeeD-Seifer/MvxBitmap
cdffb965e3745140c55bd429e05251e973f9afd5
[ "MIT" ]
null
null
null
MvxBitmap.Droid/ConcurrentImageCache.cs
SeeD-Seifer/MvxBitmap
cdffb965e3745140c55bd429e05251e973f9afd5
[ "MIT" ]
null
null
null
// MvxImageCache.cs // (c) Copyright Cirrious Ltd. http://www.cirrious.com // MvvmCross is licensed using Microsoft Public License (Ms-PL) // Contributions and inspirations noted in readme.md and license.txt // // Project Lead - Stuart Lodge, @slodge, me@slodge.com using MvvmCross.Platform; using MvvmCross.Platform.Core; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using MvvmCross.Plugins.DownloadCache; using System.Collections.Concurrent; namespace MvxBitmap.Droid { public class ConcurrentImageCache<T> : MvxAllThreadDispatchingObject , IMvxImageCache<T> { private readonly ConcurrentDictionary<string, Entry> _entriesByHttpUrl = new ConcurrentDictionary<string, Entry>(); private readonly IMvxFileDownloadCache _fileDownloadCache; private readonly int _maxInMemoryBytes; private readonly int _maxInMemoryFiles; private readonly bool _disposeOnRemove; public ConcurrentImageCache(IMvxFileDownloadCache fileDownloadCache, int maxInMemoryFiles, int maxInMemoryBytes, bool disposeOnRemove) { _fileDownloadCache = fileDownloadCache; _maxInMemoryFiles = maxInMemoryFiles; _maxInMemoryBytes = maxInMemoryBytes; _disposeOnRemove = disposeOnRemove; } #region IMvxImageCache<T> Members public Task<T> RequestImage(string url) { var tcs = new TaskCompletionSource<T>(); Task.Run(() => { Entry entry; if (_entriesByHttpUrl.TryGetValue(url, out entry)) { entry.WhenLastAccessedUtc = DateTime.UtcNow; tcs.TrySetResult(entry.Image.RawImage); return; } try { _fileDownloadCache.RequestLocalFilePath(url, async s => { var image = await Parse(s).ConfigureAwait(false); _entriesByHttpUrl.TryAdd(url, new Entry(url, image)); tcs.TrySetResult(image.RawImage); }, exception => { tcs.TrySetException(exception); }); } finally { ReduceSizeIfNecessary(); } }); return tcs.Task; } #endregion IMvxImageCache<T> Members private void ReduceSizeIfNecessary() { RunSyncOrAsyncWithLock(() => { var entries = _entriesByHttpUrl.ToArray ().Select (kvp => kvp.Value).ToList (); var currentSizeInBytes = entries.Sum(x => x.Image.GetSizeInBytes()); var currentCountFiles = entries.Count; if (currentCountFiles <= _maxInMemoryFiles && currentSizeInBytes <= _maxInMemoryBytes) return; // we don't use LINQ OrderBy here because of AOT/JIT problems on MonoTouch entries.Sort(new MvxImageComparer()); var entriesToRemove = new List<Entry>(); while (currentCountFiles > _maxInMemoryFiles || currentSizeInBytes > _maxInMemoryBytes) { var toRemove = entries[0]; entries.RemoveAt(0); if (!_entriesByHttpUrl.TryRemove(toRemove.Url, out toRemove)) { continue; } entriesToRemove.Add (toRemove); currentSizeInBytes -= toRemove.Image.GetSizeInBytes(); currentCountFiles--; } if (_disposeOnRemove && entriesToRemove.Count > 0) { DisposeImagesOnMainThread (entriesToRemove); } }); } private void DisposeImagesOnMainThread (List<Entry> entries) { InvokeOnMainThread (() => { entries.ForEach (e => e.Image.RawImage.DisposeIfDisposable ()); }); } private class MvxImageComparer : IComparer<Entry> { public int Compare(Entry x, Entry y) { return x.WhenLastAccessedUtc.CompareTo(y.WhenLastAccessedUtc); } } protected Task<MvxImage<T>> Parse(string path) { var loader = Mvx.Resolve<IMvxLocalFileImageLoader<T>>(); return loader.Load(path, false, 0, 0); } #region Nested type: Entry private class Entry { public Entry(string url, MvxImage<T> image) { Url = url; Image = image; WhenLastAccessedUtc = DateTime.UtcNow; } public string Url { get; private set; } public MvxImage<T> Image { get; private set; } public DateTime WhenLastAccessedUtc { get; set; } } #endregion Nested type: Entry } }
25.347826
136
0.689047
1e1f3e5920603c2bde47710b03d90b16d83510a8
3,826
cs
C#
sdk/dotnet/Network/V20190601/Outputs/ProbeResponse.cs
pulumi-bot/pulumi-azure-native
f7b9490b5211544318e455e5cceafe47b628e12c
[ "Apache-2.0" ]
null
null
null
sdk/dotnet/Network/V20190601/Outputs/ProbeResponse.cs
pulumi-bot/pulumi-azure-native
f7b9490b5211544318e455e5cceafe47b628e12c
[ "Apache-2.0" ]
null
null
null
sdk/dotnet/Network/V20190601/Outputs/ProbeResponse.cs
pulumi-bot/pulumi-azure-native
f7b9490b5211544318e455e5cceafe47b628e12c
[ "Apache-2.0" ]
null
null
null
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.Network.V20190601.Outputs { [OutputType] public sealed class ProbeResponse { /// <summary> /// A unique read-only string that changes whenever the resource is updated. /// </summary> public readonly string? Etag; /// <summary> /// Resource ID. /// </summary> public readonly string? Id; /// <summary> /// The interval, in seconds, for how frequently to probe the endpoint for health status. Typically, the interval is slightly less than half the allocated timeout period (in seconds) which allows two full probes before taking the instance out of rotation. The default value is 15, the minimum value is 5. /// </summary> public readonly int? IntervalInSeconds; /// <summary> /// The load balancer rules that use this probe. /// </summary> public readonly ImmutableArray<Outputs.SubResourceResponse> LoadBalancingRules; /// <summary> /// Gets name of the resource that is unique within the set of probes used by the load balancer. This name can be used to access the resource. /// </summary> public readonly string? Name; /// <summary> /// The number of probes where if no response, will result in stopping further traffic from being delivered to the endpoint. This values allows endpoints to be taken out of rotation faster or slower than the typical times used in Azure. /// </summary> public readonly int? NumberOfProbes; /// <summary> /// The port for communicating the probe. Possible values range from 1 to 65535, inclusive. /// </summary> public readonly int Port; /// <summary> /// The protocol of the end point. If 'Tcp' is specified, a received ACK is required for the probe to be successful. If 'Http' or 'Https' is specified, a 200 OK response from the specifies URI is required for the probe to be successful. /// </summary> public readonly string Protocol; /// <summary> /// Gets the provisioning state of the public IP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. /// </summary> public readonly string? ProvisioningState; /// <summary> /// The URI used for requesting health status from the VM. Path is required if a protocol is set to http. Otherwise, it is not allowed. There is no default value. /// </summary> public readonly string? RequestPath; /// <summary> /// Type of the resource. /// </summary> public readonly string Type; [OutputConstructor] private ProbeResponse( string? etag, string? id, int? intervalInSeconds, ImmutableArray<Outputs.SubResourceResponse> loadBalancingRules, string? name, int? numberOfProbes, int port, string protocol, string? provisioningState, string? requestPath, string type) { Etag = etag; Id = id; IntervalInSeconds = intervalInSeconds; LoadBalancingRules = loadBalancingRules; Name = name; NumberOfProbes = numberOfProbes; Port = port; Protocol = protocol; ProvisioningState = provisioningState; RequestPath = requestPath; Type = type; } } }
38.646465
312
0.621798
1e203c761f144b02dc5114006776a4656a5bcebe
1,907
cs
C#
DirectN/DirectN/Generated/IPin.cs
Steph55/DirectN
000594170c4c60dc297412628f167555a001531d
[ "MIT" ]
124
2018-11-17T06:03:58.000Z
2022-03-29T06:35:03.000Z
DirectN/DirectN/Generated/IPin.cs
Steph55/DirectN
000594170c4c60dc297412628f167555a001531d
[ "MIT" ]
24
2018-12-31T19:55:08.000Z
2022-01-21T07:21:52.000Z
DirectN/DirectN/Generated/IPin.cs
Steph55/DirectN
000594170c4c60dc297412628f167555a001531d
[ "MIT" ]
16
2018-12-23T20:37:20.000Z
2022-02-23T14:14:00.000Z
// c:\program files (x86)\windows kits\10\include\10.0.22000.0\um\strmif.h(1253,5) using System; using System.Runtime.InteropServices; namespace DirectN { [ComImport, Guid("56a86891-0ad4-11ce-b03a-0020af0ba770"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public partial interface IPin { [PreserveSig] HRESULT Connect(/* [in] */ IPin pReceivePin, /* optional(_AMMediaType) */ IntPtr pmt); [PreserveSig] HRESULT ReceiveConnection(/* [in] */ IPin pConnector, /* [in] */ ref _AMMediaType pmt); [PreserveSig] HRESULT Disconnect(); [PreserveSig] HRESULT ConnectedTo(/* [annotation][out] _Out_ */ out IPin pPin); [PreserveSig] HRESULT ConnectionMediaType(/* [annotation][out] _Out_ */ out _AMMediaType pmt); [PreserveSig] HRESULT QueryPinInfo(/* [annotation][out] _Out_ */ out _PinInfo pInfo); [PreserveSig] HRESULT QueryDirection(/* [annotation][out] _Out_ */ out _PinDirection pPinDir); [PreserveSig] HRESULT QueryId(/* [annotation][out] _Out_ */ out IntPtr Id); [PreserveSig] HRESULT QueryAccept(/* [in] */ ref _AMMediaType pmt); [PreserveSig] HRESULT EnumMediaTypes(/* [annotation][out] _Out_ */ out IEnumMediaTypes ppEnum); [PreserveSig] HRESULT QueryInternalConnections(/* optional(IPin) */ out IntPtr apPin, /* [out][in] */ ref uint nPin); [PreserveSig] HRESULT EndOfStream(); [PreserveSig] HRESULT BeginFlush(); [PreserveSig] HRESULT EndFlush(); [PreserveSig] HRESULT NewSegment(/* [in] */ long tStart, /* [in] */ long tStop, /* [in] */ double dRate); } }
34.053571
115
0.568432
1e207c51ce33a0343f6db41663d055d696489b51
1,944
cs
C#
Singonet.ir.UI.SQL_Connection/SQL_Connection_Class.cs
ShayanFiroozi/SQL_Server_Connection_Manager
620ca0d3562849425e3c482e0c3f1037f1ed5894
[ "MIT" ]
1
2018-10-20T11:39:36.000Z
2018-10-20T11:39:36.000Z
Singonet.ir.UI.SQL_Connection/SQL_Connection_Class.cs
ShayanFiroozi/SQL_Server_Connection_Manager
620ca0d3562849425e3c482e0c3f1037f1ed5894
[ "MIT" ]
null
null
null
Singonet.ir.UI.SQL_Connection/SQL_Connection_Class.cs
ShayanFiroozi/SQL_Server_Connection_Manager
620ca0d3562849425e3c482e0c3f1037f1ed5894
[ "MIT" ]
null
null
null
/******************************************************************* * Forever Persian Gulf , Forever Persia * * * * ----> Singonet.ir <---- * * * * C# Singnet.ir * * * * By Shayan Firoozi 2017 Bandar Abbas - Iran * * EMail : Singonet.ir@gmail.com * * Phone : +98 936 517 5800 * * * *******************************************************************/ using System; using System.Data.SqlClient; namespace Singonet.ir.UI.SQL_Connection { public static class SQL_Connection_Class { private static frm_theme_default _frm_connection; // main sql connection for user public static SqlConnection _SQL_Connection { get; internal set; } public enum UI_Theme { Default_Theme = 0, } public static void Show_SQL_Connection_Manager(string ApplicationName,UI_Theme _UI_Theme = UI_Theme.Default_Theme) { if (string.IsNullOrEmpty(ApplicationName)==true) { throw new Exception("Invalid Application Name."); } // Theme selection if (_UI_Theme == UI_Theme.Default_Theme) { _frm_connection = new frm_theme_default(ApplicationName); _frm_connection.ShowDialog(); } } } }
25.578947
123
0.354424
1e21338d8a8ff6e5197c96d6e47355400b44d5a8
1,103
cs
C#
sdk/dotnet/CloudRun/Inputs/ServiceTemplateSpecContainerPortArgs.cs
pjbizon/pulumi-gcp
0d09cbc1dcf50093a177531f7596c27db11a2e58
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
sdk/dotnet/CloudRun/Inputs/ServiceTemplateSpecContainerPortArgs.cs
pjbizon/pulumi-gcp
0d09cbc1dcf50093a177531f7596c27db11a2e58
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
sdk/dotnet/CloudRun/Inputs/ServiceTemplateSpecContainerPortArgs.cs
pjbizon/pulumi-gcp
0d09cbc1dcf50093a177531f7596c27db11a2e58
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Gcp.CloudRun.Inputs { public sealed class ServiceTemplateSpecContainerPortArgs : Pulumi.ResourceArgs { /// <summary> /// Port number the container listens on. This must be a valid port number, 0 &lt; x &lt; 65536. /// </summary> [Input("containerPort")] public Input<int>? ContainerPort { get; set; } /// <summary> /// Volume's name. /// </summary> [Input("name")] public Input<string>? Name { get; set; } /// <summary> /// Protocol for port. Must be "TCP". Defaults to "TCP". /// </summary> [Input("protocol")] public Input<string>? Protocol { get; set; } public ServiceTemplateSpecContainerPortArgs() { } } }
29.026316
104
0.608341
1e21ae1eacc870e6f1804f68bed5ee2c4c80e851
2,773
cs
C#
src/TimeTracker.Library/Services/Interpretation/EasyDateParser.cs
integral-io/time-tracker
b2c48e20c425b5d32ea441e847bff56f80c79d29
[ "Apache-2.0" ]
3
2019-04-10T13:50:09.000Z
2019-10-29T16:08:14.000Z
src/TimeTracker.Library/Services/Interpretation/EasyDateParser.cs
integral-io/time-tracker
b2c48e20c425b5d32ea441e847bff56f80c79d29
[ "Apache-2.0" ]
12
2018-07-18T22:22:36.000Z
2019-07-31T18:05:47.000Z
src/TimeTracker.Library/Services/Interpretation/EasyDateParser.cs
integral-io/time-tracker
b2c48e20c425b5d32ea441e847bff56f80c79d29
[ "Apache-2.0" ]
1
2018-07-24T13:43:34.000Z
2018-07-24T13:43:34.000Z
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; namespace TimeTracker.Library.Services.Interpretation { /// <summary> /// interprets dates in human readable form and returns them in datetime object UTC /// </summary> public static class EasyDateParser { private static readonly List<string> SupportedDateFormats = new List<string> { "yyyy-MM-d", // ex: 2018-12-9 "MMM-d", // ex: jan-3 "MMMM-d-yyyy", // ex: December-9-2017 "MMM-d-yyyy" // ex: Dec-9-2017 }; public static DateTime ParseEasyDate(string date) { if (string.IsNullOrWhiteSpace(date)) return GetUtcNow(); var supportedValues = new Dictionary<Func<string, bool>, Func<string, DateTime>> { { x => x.Equals("yesterday", StringComparison.OrdinalIgnoreCase), x => GetUtcNow().AddDays(-1)}, { IsSupportedDateFormat, FromSupportedDateFormat } }; foreach (var supportedValue in supportedValues) { if (supportedValue.Key(date)) return supportedValue.Value(date); } return GetUtcNow(); } public static bool IsSupportedDate(string text) { if (string.IsNullOrWhiteSpace(text)) return false; var supportedValues = new List<Func<string, bool>> { x => x.Equals("yesterday", StringComparison.OrdinalIgnoreCase), IsSupportedDateFormat }; foreach (var supportedValue in supportedValues) { if (supportedValue(text)) return true; } return false; } private static bool IsSupportedDateFormat(string text) { return SupportedDateFormats.Any(format => DateTime.TryParseExact(text, format, new CultureInfo("en-US"), DateTimeStyles.None, out _)); } private static DateTime FromSupportedDateFormat(string text) { var supportedDateFormat = SupportedDateFormats.First(format => DateTime.TryParseExact(text, format, new CultureInfo("en-US"), DateTimeStyles.None, out _)); return DateTime.ParseExact(text, supportedDateFormat, new CultureInfo("en-US"), DateTimeStyles.None); } /// <summary> /// Gets current UTC date but at beginning of day so as not to have TZ issues /// </summary> /// <returns></returns> public static DateTime GetUtcNow() { return DateTime.UtcNow.Date; } } }
33.817073
167
0.566534
1e2221ab2860d19ea63ba1a2471bc6fc66d57923
6,212
cs
C#
src/Controls/src/Core/SwipeView.cs
mauroa/maui
454a09728d2722a50b7fddbe58eee6e2dc740858
[ "MIT" ]
null
null
null
src/Controls/src/Core/SwipeView.cs
mauroa/maui
454a09728d2722a50b7fddbe58eee6e2dc740858
[ "MIT" ]
null
null
null
src/Controls/src/Core/SwipeView.cs
mauroa/maui
454a09728d2722a50b7fddbe58eee6e2dc740858
[ "MIT" ]
null
null
null
using System; using System.ComponentModel; using System.Runtime.CompilerServices; namespace Microsoft.Maui.Controls { [ContentProperty(nameof(Content))] public partial class SwipeView : ContentView, IElementConfiguration<SwipeView>, ISwipeViewController { readonly Lazy<PlatformConfigurationRegistry<SwipeView>> _platformConfigurationRegistry; public SwipeView() { _platformConfigurationRegistry = new Lazy<PlatformConfigurationRegistry<SwipeView>>(() => new PlatformConfigurationRegistry<SwipeView>(this)); } public static readonly BindableProperty ThresholdProperty = BindableProperty.Create(nameof(Threshold), typeof(double), typeof(SwipeView), default(double)); public static readonly BindableProperty LeftItemsProperty = BindableProperty.Create(nameof(LeftItems), typeof(SwipeItems), typeof(SwipeView), null, BindingMode.OneWay, null, defaultValueCreator: SwipeItemsDefaultValueCreator, propertyChanged: OnSwipeItemsChanged); public static readonly BindableProperty RightItemsProperty = BindableProperty.Create(nameof(RightItems), typeof(SwipeItems), typeof(SwipeView), null, BindingMode.OneWay, null, defaultValueCreator: SwipeItemsDefaultValueCreator, propertyChanged: OnSwipeItemsChanged); public static readonly BindableProperty TopItemsProperty = BindableProperty.Create(nameof(TopItems), typeof(SwipeItems), typeof(SwipeView), null, BindingMode.OneWay, null, defaultValueCreator: SwipeItemsDefaultValueCreator, propertyChanged: OnSwipeItemsChanged); public static readonly BindableProperty BottomItemsProperty = BindableProperty.Create(nameof(BottomItems), typeof(SwipeItems), typeof(SwipeView), null, BindingMode.OneWay, null, defaultValueCreator: SwipeItemsDefaultValueCreator, propertyChanged: OnSwipeItemsChanged); public double Threshold { get { return (double)GetValue(ThresholdProperty); } set { SetValue(ThresholdProperty, value); } } public SwipeItems LeftItems { get { return (SwipeItems)GetValue(LeftItemsProperty); } set { SetValue(LeftItemsProperty, value); } } public SwipeItems RightItems { get { return (SwipeItems)GetValue(RightItemsProperty); } set { SetValue(RightItemsProperty, value); } } public SwipeItems TopItems { get { return (SwipeItems)GetValue(TopItemsProperty); } set { SetValue(TopItemsProperty, value); } } public SwipeItems BottomItems { get { return (SwipeItems)GetValue(BottomItemsProperty); } set { SetValue(BottomItemsProperty, value); } } bool ISwipeViewController.IsOpen { get => ((ISwipeView)this).IsOpen; set => ((ISwipeView)this).IsOpen = value; } static void OnSwipeItemsChanged(BindableObject bindable, object oldValue, object newValue) { if (bindable is not SwipeView swipeView) return; swipeView.UpdateSwipeItemsParent((SwipeItems)newValue); if(oldValue is SwipeItems oldItems) { oldItems.CollectionChanged -= SwipeItemsCollectionChanged; oldItems.PropertyChanged -= SwipeItemsPropertyChanged; } if(newValue is SwipeItems newItems) { newItems.CollectionChanged += SwipeItemsCollectionChanged; newItems.PropertyChanged += SwipeItemsPropertyChanged; } void SwipeItemsPropertyChanged(object sender, PropertyChangedEventArgs e) => SendChange((SwipeItems)sender); void SwipeItemsCollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) => SendChange((SwipeItems)sender); void SendChange(SwipeItems swipeItems) { if (swipeItems == swipeView.LeftItems) swipeView?.Handler?.UpdateValue(nameof(LeftItems)); if (swipeItems == swipeView.RightItems) swipeView?.Handler?.UpdateValue(nameof(RightItems)); if (swipeItems == swipeView.TopItems) swipeView?.Handler?.UpdateValue(nameof(TopItems)); if (swipeItems == swipeView.BottomItems) swipeView?.Handler?.UpdateValue(nameof(BottomItems)); } } public event EventHandler<SwipeStartedEventArgs> SwipeStarted; public event EventHandler<SwipeChangingEventArgs> SwipeChanging; public event EventHandler<SwipeEndedEventArgs> SwipeEnded; [EditorBrowsable(EditorBrowsableState.Never)] public event EventHandler<OpenRequestedEventArgs> OpenRequested; [EditorBrowsable(EditorBrowsableState.Never)] public event EventHandler<CloseRequestedEventArgs> CloseRequested; public void Open(OpenSwipeItem openSwipeItem, bool animated = true) { OpenRequested?.Invoke(this, new OpenRequestedEventArgs(openSwipeItem, animated)); ((ISwipeView)this).RequestOpen(new SwipeViewOpenRequest(openSwipeItem, animated)); } public void Close(bool animated = true) { CloseRequested?.Invoke(this, new CloseRequestedEventArgs(animated)); ((ISwipeView)this).RequestClose(new SwipeViewCloseRequest(animated)); } void ISwipeViewController.SendSwipeStarted(SwipeStartedEventArgs args) => SwipeStarted?.Invoke(this, args); void ISwipeViewController.SendSwipeChanging(SwipeChangingEventArgs args) => SwipeChanging?.Invoke(this, args); void ISwipeViewController.SendSwipeEnded(SwipeEndedEventArgs args) => SwipeEnded?.Invoke(this, args); protected override void OnBindingContextChanged() { base.OnBindingContextChanged(); object bc = BindingContext; if (LeftItems != null) SetInheritedBindingContext(LeftItems, bc); if (RightItems != null) SetInheritedBindingContext(RightItems, bc); if (TopItems != null) SetInheritedBindingContext(TopItems, bc); if (BottomItems != null) SetInheritedBindingContext(BottomItems, bc); } SwipeItems SwipeItemsDefaultValueCreator() => new SwipeItems(); static object SwipeItemsDefaultValueCreator(BindableObject bindable) { return ((SwipeView)bindable).SwipeItemsDefaultValueCreator(); } public IPlatformElementConfiguration<T, SwipeView> On<T>() where T : IConfigPlatform { return _platformConfigurationRegistry.Value.On<T>(); } void UpdateSwipeItemsParent(SwipeItems swipeItems) { if (swipeItems.Parent == null) swipeItems.Parent = this; foreach (var item in swipeItems) { if (item is Element swipeItem && swipeItem.Parent == null) swipeItem.Parent = swipeItems; } } } }
33.76087
170
0.769961
1e225b9b0cdd3356d431bded8ea387e0c8f82a17
6,809
cs
C#
Assets/Plugins/SuperTiled2Unity/Scripts/Editor/Importers/TiledAssetImporter.cs
Greentwip/MegaMan-Revenge-of-the-Future
3c20f388a79b748e271bc79bd4c1ca0fc43e3359
[ "MIT" ]
17
2020-06-05T07:50:16.000Z
2021-11-19T11:48:56.000Z
Assets/Plugins/SuperTiled2Unity/Scripts/Editor/Importers/TiledAssetImporter.cs
Greentwip/MegaMan-Revenge-of-the-Future
3c20f388a79b748e271bc79bd4c1ca0fc43e3359
[ "MIT" ]
1
2020-09-20T08:27:14.000Z
2020-09-26T03:00:38.000Z
Assets/Plugins/SuperTiled2Unity/Scripts/Editor/Importers/TiledAssetImporter.cs
Greentwip/MegaMan-Revenge-of-the-Future
3c20f388a79b748e271bc79bd4c1ca0fc43e3359
[ "MIT" ]
1
2019-04-08T00:06:09.000Z
2019-04-08T00:06:09.000Z
using System; using System.Linq; using System.Xml.Linq; using UnityEditor; using UnityEditor.Experimental.AssetImporters; using UnityEngine; using UnityEngine.Tilemaps; // All tiled assets we want imported should use this class namespace SuperTiled2Unity.Editor { public abstract class TiledAssetImporter : SuperImporter { [SerializeField] private float m_PixelsPerUnit = 0.0f; public float PixelsPerUnit { get { return m_PixelsPerUnit; } } [SerializeField] private int m_EdgesPerEllipse = 0; #pragma warning disable 414 [SerializeField] private int m_NumberOfObjectsImported = 0; #pragma warning restore 414 private RendererSorter m_RendererSorter; public RendererSorter RendererSorter { get { return m_RendererSorter; } } public SuperImportContext SuperImportContext { get; private set; } public void AddSuperCustomProperties(GameObject go, XElement xProperties) { AddSuperCustomProperties(go, xProperties, null); } public void AddSuperCustomProperties(GameObject go, XElement xProperties, string typeName) { AddSuperCustomProperties(go, xProperties, null, typeName); } public void AddSuperCustomProperties(GameObject go, XElement xProperties, SuperTile tile, string typeName) { // Load our "local" properties first var component = go.AddComponent<SuperCustomProperties>(); var properties = CustomPropertyLoader.LoadCustomPropertyList(xProperties); // Do we have any properties from a tile to add? if (tile != null) { properties.CombineFromSource(tile.m_CustomProperties); } // Add properties from our object type (this should be last) properties.AddPropertiesFromType(typeName, SuperImportContext); // Sort the properties alphabetically component.m_Properties = properties.OrderBy(p => p.m_Name).ToList(); AssignUnityTag(component); AssignUnityLayer(component); } public void AssignTilemapSorting(TilemapRenderer renderer) { var sortLayerName = m_RendererSorter.AssignTilemapSort(renderer); CheckSortingLayerName(sortLayerName); } public void AssignSpriteSorting(SpriteRenderer renderer) { var sortLayerName = m_RendererSorter.AssignSpriteSort(renderer); CheckSortingLayerName(sortLayerName); } public void AssignMaterial(Renderer renderer, string match) { // Do we have a registered material match? var matchedMaterial = SuperImportContext.Settings.MaterialMatchings.FirstOrDefault(m => m.m_LayerName.Equals(match, StringComparison.OrdinalIgnoreCase)); if (matchedMaterial != null) { renderer.material = matchedMaterial.m_Material; return; } // Has the user chosen to override the material used for our tilemaps and sprite objects? if (SuperImportContext.Settings.DefaultMaterial != null) { renderer.material = SuperImportContext.Settings.DefaultMaterial; } } public void ApplyTemplateToObject(XElement xObject) { var template = xObject.GetAttributeAs("template", ""); if (!string.IsNullOrEmpty(template)) { var asset = RequestAssetAtPath<ObjectTemplate>(template); if (asset != null) { xObject.CombineWithTemplate(asset.m_ObjectXml); } else { ReportError("Missing template file: {0}", template); } } } public void ApplyDefaultSettings() { var settings = ST2USettings.GetOrCreateST2USettings(); m_PixelsPerUnit = settings.PixelsPerUnit; m_EdgesPerEllipse = settings.EdgesPerEllipse; EditorUtility.SetDirty(this); } protected override void InternalOnImportAsset() { m_RendererSorter = new RendererSorter(); WrapImportContext(AssetImportContext); } protected override void InternalOnImportAssetCompleted() { m_RendererSorter = null; m_NumberOfObjectsImported = SuperImportContext.GetNumberOfObjects(); } protected void AssignUnityTag(SuperCustomProperties properties) { // Do we have a 'unity:tag' property? CustomProperty prop; if (properties.TryGetCustomProperty(StringConstants.Unity_Tag, out prop)) { string tag = prop.m_Value; CheckTagName(tag); properties.gameObject.tag = tag; } } protected void AssignUnityLayer(SuperCustomProperties properties) { // Do we have a 'unity:layer' property? CustomProperty prop; if (properties.TryGetCustomProperty(StringConstants.Unity_Layer, out prop)) { string layer = prop.m_Value; if (!UnityEditorInternal.InternalEditorUtility.layers.Contains(layer)) { string report = string.Format("Layer '{0}' is not defined in the Tags and Layers settings.", layer); ReportError(report); } else { properties.gameObject.layer = LayerMask.NameToLayer(layer); } } else { // Inherit the layer of our parent var parent = properties.gameObject.transform.parent; if (parent != null) { properties.gameObject.layer = parent.gameObject.layer; } } } private void WrapImportContext(AssetImportContext ctx) { var settings = ST2USettings.GetOrCreateST2USettings(); settings.RefreshCustomObjectTypes(); // Create a copy of our settings that we can override based on importer settings settings = Instantiate(settings); if (m_PixelsPerUnit == 0) { m_PixelsPerUnit = settings.PixelsPerUnit; } if (m_EdgesPerEllipse == 0) { m_EdgesPerEllipse = settings.EdgesPerEllipse; } settings.PixelsPerUnit = m_PixelsPerUnit; settings.EdgesPerEllipse = m_EdgesPerEllipse; SuperImportContext = new SuperImportContext(ctx, settings); } } }
35.649215
165
0.598766
1e22603576dca61280827385429c6e3b74830653
3,274
cs
C#
src/contrib/DistributedSearch/Distributed/Configuration/DistributedSearchers.cs
Anomalous-Software/Lucene.NET
20c64cd59d6cdbc6d6102f13c11e2422eec0445f
[ "Apache-2.0" ]
null
null
null
src/contrib/DistributedSearch/Distributed/Configuration/DistributedSearchers.cs
Anomalous-Software/Lucene.NET
20c64cd59d6cdbc6d6102f13c11e2422eec0445f
[ "Apache-2.0" ]
null
null
null
src/contrib/DistributedSearch/Distributed/Configuration/DistributedSearchers.cs
Anomalous-Software/Lucene.NET
20c64cd59d6cdbc6d6102f13c11e2422eec0445f
[ "Apache-2.0" ]
null
null
null
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Configuration; using System.Xml; namespace Lucene.Net.Distributed.Configuration { /// <summary> /// Definition of a configurable set of search indexes made accessible by the /// LuceneServer windows service for a consuming application. These search indexes /// are defined in the configuration file of an application. The locations defined /// in a DistributedSearcher match the exposed object URIs as defined in the LuceneServer service. /// /// An example configuration would look like the following: /// <code> /// <DistributedSearchers> /// <DistributedSearcher wsid="1" SearchMethod="0" location="c:\localindexes\LocalIndex1" /> /// <DistributedSearcher wsid="2" SearchMethod="1" location="tcp://192.168.1.100:1089/RemoteIndex1" /> /// <DistributedSearcher wsid="3" SearchMethod="1" location="tcp://192.168.1.101:1089/RemoteIndex2" /> /// </DistributedSearchers> /// </code> /// </summary> public class DistributedSearchers { private DistributedSearcher[] _arDistributedSearcherArray; /// <summary> /// Accessor method for the configurable DistributedSearchers. /// </summary> public static DistributedSearchers GetConfig { get { return (DistributedSearchers)ConfigurationManager.GetSection("DistributedSearchers"); } } /// <summary> /// Public constructor for DistributedSearchers. A DistributedSearcher is defined /// in XML configuration and is loaded via a custom configuration handler. /// </summary> /// <param name="xSection">The Xml definition in the configuration file</param> public DistributedSearchers(XmlNode xSection) { this._arDistributedSearcherArray = new DistributedSearcher[xSection.ChildNodes.Count]; int x=0; foreach (XmlNode c in xSection.ChildNodes) { if (c.Name.ToLower()=="DistributedSearcher") { DistributedSearcher ws = new DistributedSearcher(c); this._arDistributedSearcherArray[x] = ws; x++; } } } /// <summary> /// Strongly-typed array of DistributedSearcher objects as defined in /// a configuration section. /// </summary> public DistributedSearcher[] DistributedSearcherArray { get {return this._arDistributedSearcherArray;} } } }
39.445783
115
0.678681
1e237b9c57d6c0e4162e36afd834bdedefbe9a5c
16,474
cs
C#
Panuon.UI.Silver/Helpers/Others/AnimationHelper.cs
PettyHandSome/PanuonUI.Silver
39b7f5ff97e2ff08bd0464e25fe98f29ad0beb16
[ "MIT" ]
1
2021-01-23T07:49:32.000Z
2021-01-23T07:49:32.000Z
Panuon.UI.Silver/Helpers/Others/AnimationHelper.cs
PettyHandSome/PanuonUI.Silver
39b7f5ff97e2ff08bd0464e25fe98f29ad0beb16
[ "MIT" ]
null
null
null
Panuon.UI.Silver/Helpers/Others/AnimationHelper.cs
PettyHandSome/PanuonUI.Silver
39b7f5ff97e2ff08bd0464e25fe98f29ad0beb16
[ "MIT" ]
null
null
null
using System; using System.Windows; using System.Windows.Media; using System.Windows.Media.Animation; namespace Panuon.UI.Silver { public class AnimationHelper { #region FadeIn /// <summary> /// 使控件立即进行透明度从0至1的渐变动画。若控件尚未加载完成,则将在其加载完成后再执行动画。 /// </summary> public static readonly DependencyProperty FadeInProperty = DependencyProperty.RegisterAttached("FadeIn", typeof(bool), typeof(AnimationHelper), new PropertyMetadata(OnFadeInChanged)); public static bool GetFadeIn(DependencyObject obj) { return (bool)obj.GetValue(FadeInProperty); } public static void SetFadeIn(DependencyObject obj, bool value) { obj.SetValue(FadeInProperty, value); } private static void OnFadeInChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var element = d as FrameworkElement; if (element == null) return; element.Opacity = 0; if (element.IsLoaded) element.BeginAnimation(FrameworkElement.OpacityProperty, GetDoubleAnimation(1,element)); else { element.Loaded += delegate { element.BeginAnimation(FrameworkElement.OpacityProperty, GetDoubleAnimation(1, element)); }; } } #endregion #region FadeOut public static bool GetFadeOut(DependencyObject obj) { return (bool)obj.GetValue(FadeOutProperty); } public static void SetFadeOut(DependencyObject obj, bool value) { obj.SetValue(FadeOutProperty, value); } public static readonly DependencyProperty FadeOutProperty = DependencyProperty.RegisterAttached("FadeOut", typeof(bool), typeof(AnimationHelper), new PropertyMetadata(OnFadeOutChanged)); private static void OnFadeOutChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var element = d as FrameworkElement; if (element == null) return; if (element.IsLoaded) element.BeginAnimation(FrameworkElement.OpacityProperty, GetDoubleAnimation(0, element)); else { element.Loaded += delegate { element.BeginAnimation(FrameworkElement.OpacityProperty, GetDoubleAnimation(0, element)); }; } } #endregion #region SlideIn /// <summary> /// 使控件立即进行从相对右侧偏移20px的位置,移动至当前位置的渐变动画。若控件尚未加载完成,则将在其加载完成后再执行动画。 /// </summary> public static readonly DependencyProperty SlideInFromRightProperty = DependencyProperty.RegisterAttached("SlideInFromRight", typeof(bool), typeof(AnimationHelper), new PropertyMetadata(OnSlideInFromRightChanged)); public static bool GetSlideInFromRight(DependencyObject obj) { return (bool)obj.GetValue(SlideInFromRightProperty); } public static void SetSlideInFromRight(DependencyObject obj, bool value) { obj.SetValue(SlideInFromRightProperty, value); } private static void OnSlideInFromRightChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var element = d as FrameworkElement; if (element == null) return; var transform = new TranslateTransform() { X = 20, }; if (element.RenderTransform != null) { if (element.RenderTransform.GetType() == typeof(TransformGroup)) { ((TransformGroup)element.RenderTransform).Children.Add(transform); } else if (element.RenderTransform.GetType() == typeof(Transform)) { var group = new TransformGroup(); group.Children.Add((Transform)element.RenderTransform); group.Children.Add(transform); } else { element.RenderTransform = transform; } } else { element.RenderTransform = transform; } if (element.IsLoaded) transform.BeginAnimation(TranslateTransform.XProperty, GetDoubleAnimation(0, element)); else { element.Loaded += delegate { transform.BeginAnimation(TranslateTransform.XProperty, GetDoubleAnimation(0, element)); }; } } /// <summary> /// 使控件立即进行从相对左侧偏移20px的位置,移动至当前位置的渐变动画。若控件尚未加载完成,则将在其加载完成后再执行动画。 /// </summary> public static readonly DependencyProperty SlideInFromLeftProperty = DependencyProperty.RegisterAttached("SlideInFromLeft", typeof(bool), typeof(AnimationHelper), new PropertyMetadata(OnSlideInFromLeftChanged)); public static bool GetSlideInFromLeft(DependencyObject obj) { return (bool)obj.GetValue(SlideInFromLeftProperty); } public static void SetSlideInFromLeft(DependencyObject obj, bool value) { obj.SetValue(SlideInFromLeftProperty, value); } private static void OnSlideInFromLeftChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var element = d as FrameworkElement; if (element == null) return; var transform = new TranslateTransform() { X = -20, }; if (element.RenderTransform != null) { if (element.RenderTransform.GetType() == typeof(TransformGroup)) { ((TransformGroup)element.RenderTransform).Children.Add(transform); } else if (element.RenderTransform.GetType() == typeof(Transform)) { var group = new TransformGroup(); group.Children.Add((Transform)element.RenderTransform); group.Children.Add(transform); } else { element.RenderTransform = transform; } } else { element.RenderTransform = transform; } if (element.IsLoaded) transform.BeginAnimation(TranslateTransform.XProperty, GetDoubleAnimation(0, element)); else { element.Loaded += delegate { transform.BeginAnimation(TranslateTransform.XProperty, GetDoubleAnimation(0, element)); }; } } /// <summary> /// 使控件立即进行从相对顶部偏移20px的位置,移动至当前位置的渐变动画。若控件尚未加载完成,则将在其加载完成后再执行动画。 /// </summary> public static readonly DependencyProperty SlideInFromTopProperty = DependencyProperty.RegisterAttached("SlideInFromTop", typeof(bool), typeof(AnimationHelper), new PropertyMetadata(OnSlideInFromTopChanged)); public static bool GetSlideInFromTop(DependencyObject obj) { return (bool)obj.GetValue(SlideInFromTopProperty); } public static void SetSlideInFromTop(DependencyObject obj, bool value) { obj.SetValue(SlideInFromTopProperty, value); } private static void OnSlideInFromTopChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var element = d as FrameworkElement; if (element == null) return; var transform = new TranslateTransform() { Y = -20, }; if (element.RenderTransform != null) { if (element.RenderTransform.GetType() == typeof(TransformGroup)) { ((TransformGroup)element.RenderTransform).Children.Add(transform); } else if (element.RenderTransform.GetType() == typeof(Transform)) { var group = new TransformGroup(); group.Children.Add((Transform)element.RenderTransform); group.Children.Add(transform); } else { element.RenderTransform = transform; } } else { element.RenderTransform = transform; } if (element.IsLoaded) transform.BeginAnimation(TranslateTransform.YProperty, GetDoubleAnimation(0, element)); else { element.Loaded += delegate { transform.BeginAnimation(TranslateTransform.YProperty, GetDoubleAnimation(0, element)); }; } } /// <summary> /// 使控件立即进行从相对底部偏移20px的位置,移动至当前位置的渐变动画。若控件尚未加载完成,则将在其加载完成后再执行动画。 /// </summary> public static readonly DependencyProperty SlideInFromBottomProperty = DependencyProperty.RegisterAttached("SlideInFromBottom", typeof(bool), typeof(AnimationHelper), new PropertyMetadata(OnSlideInFromBottomChanged)); public static bool GetSlideInFromBottom(DependencyObject obj) { return (bool)obj.GetValue(SlideInFromBottomProperty); } public static void SetSlideInFromBottom(DependencyObject obj, bool value) { obj.SetValue(SlideInFromBottomProperty, value); } private static void OnSlideInFromBottomChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var element = d as FrameworkElement; if (element == null) return; var transform = new TranslateTransform() { Y = 20, }; if (element.RenderTransform != null) { if (element.RenderTransform.GetType() == typeof(TransformGroup)) { ((TransformGroup)element.RenderTransform).Children.Add(transform); } else if (element.RenderTransform.GetType() == typeof(Transform)) { var group = new TransformGroup(); group.Children.Add((Transform)element.RenderTransform); group.Children.Add(transform); } else { element.RenderTransform = transform; } } else { element.RenderTransform = transform; } if (element.IsLoaded) transform.BeginAnimation(TranslateTransform.YProperty, GetDoubleAnimation(0, element)); else { element.Loaded += delegate { transform.BeginAnimation(TranslateTransform.YProperty, GetDoubleAnimation(0, element)); }; } } #endregion #region GradualIn public static bool GetGradualIn(DependencyObject obj) { return (bool)obj.GetValue(GradualInProperty); } public static void SetGradualIn(DependencyObject obj, bool value) { obj.SetValue(GradualInProperty, value); } public static readonly DependencyProperty GradualInProperty = DependencyProperty.RegisterAttached("GradualIn", typeof(bool), typeof(AnimationHelper), new PropertyMetadata(OnGradualInChanged)); private static void OnGradualInChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var element = d as FrameworkElement; var collection = new GradientStopCollection(); var stop1 = new GradientStop() { Offset = 0, Color = Colors.White }; var stop2 = new GradientStop() { Offset = 0, Color = Colors.Transparent }; collection.Add(stop1); collection.Add(stop2); var brush = new LinearGradientBrush() { StartPoint = new Point(0, 0), EndPoint = new Point(0, 1), GradientStops = collection, }; element.OpacityMask = brush; if (element.IsLoaded) { var duration = GetDurationSeconds(element); var beginSeconds = GetBeginTimeSeconds(element); stop2.BeginAnimation(GradientStop.OffsetProperty, GetDoubleAnimation(1, TimeSpan.FromSeconds(duration), TimeSpan.FromSeconds(beginSeconds))); stop2.BeginAnimation(GradientStop.ColorProperty, GetColorAnimation(Colors.White, TimeSpan.FromSeconds(duration / 0.5), TimeSpan.FromSeconds(duration * 0.75))); } else { element.Loaded += delegate { var duration = GetDurationSeconds(element); var beginSeconds = GetBeginTimeSeconds(element); stop2.BeginAnimation(GradientStop.OffsetProperty, GetDoubleAnimation(1, TimeSpan.FromSeconds(duration), TimeSpan.FromSeconds(beginSeconds))); stop2.BeginAnimation(GradientStop.ColorProperty, GetColorAnimation(Colors.White, TimeSpan.FromSeconds(duration / 0.5), TimeSpan.FromSeconds(duration * 0.75))); }; } } #endregion #region Duration & BeginTime /// <summary>BeginTimeSeconds /// 获取或设置动画的执行持续时间。默认为0.5秒。 /// </summary> public static readonly DependencyProperty DurationSecondsProperty = DependencyProperty.RegisterAttached("DurationSeconds", typeof(double), typeof(AnimationHelper), new PropertyMetadata(0.5)); public static double GetDurationSeconds(DependencyObject obj) { return (double)obj.GetValue(DurationSecondsProperty); } public static void SetDurationSeconds(DependencyObject obj, double value) { obj.SetValue(DurationSecondsProperty, value); } /// <summary> /// 获取或设置动画的执行开始时间。默认为0秒。 /// </summary> public static readonly DependencyProperty BeginTimeSecondsProperty = DependencyProperty.RegisterAttached("BeginTimeSeconds", typeof(double), typeof(AnimationHelper), new PropertyMetadata(0.0)); public static double GetBeginTimeSeconds(DependencyObject obj) { return (double)obj.GetValue(BeginTimeSecondsProperty); } public static void SetBeginTimeSeconds(DependencyObject obj, double value) { obj.SetValue(BeginTimeSecondsProperty, value); } #endregion #region Function private static DoubleAnimation GetDoubleAnimation(double to, FrameworkElement element) { return new DoubleAnimation() { To = to, Duration = TimeSpan.FromSeconds(GetDurationSeconds(element)), BeginTime = TimeSpan.FromSeconds(GetBeginTimeSeconds(element)), }; } private static DoubleAnimation GetDoubleAnimation(double to, TimeSpan duration, TimeSpan? beginTime = null) { return new DoubleAnimation() { To = to, Duration = duration, BeginTime = beginTime ?? TimeSpan.FromSeconds(0), }; } private static ColorAnimation GetColorAnimation(Color to, FrameworkElement element) { return new ColorAnimation() { To = to, Duration = TimeSpan.FromSeconds(GetDurationSeconds(element)), BeginTime = TimeSpan.FromSeconds(GetBeginTimeSeconds(element)), }; } private static ColorAnimation GetColorAnimation(Color to, TimeSpan duration, TimeSpan? beginTime = null) { return new ColorAnimation() { To = to, Duration = duration, BeginTime = beginTime ?? TimeSpan.FromSeconds(0), }; } #endregion } }
36.446903
179
0.570535
1e23f7c2c7354f0cb208ec4b726061bd5bc6b9d3
3,389
cs
C#
Vorlesung 2020-05-22/Program.cs
haenno/FOM-BSc-WI-Semster2-ObjektorientierteProgrammierung
1de6e1e0f59229330b347b75a152fdeef9a3ad1d
[ "MIT" ]
null
null
null
Vorlesung 2020-05-22/Program.cs
haenno/FOM-BSc-WI-Semster2-ObjektorientierteProgrammierung
1de6e1e0f59229330b347b75a152fdeef9a3ad1d
[ "MIT" ]
null
null
null
Vorlesung 2020-05-22/Program.cs
haenno/FOM-BSc-WI-Semster2-ObjektorientierteProgrammierung
1de6e1e0f59229330b347b75a152fdeef9a3ad1d
[ "MIT" ]
null
null
null
using System; using System.Collections.Generic; namespace vorl2020_05_22 { /* Aufgabe aus Vorlesung vom 22.05.2020: Watch it all * Ziel ist es, eine Datenbank für Streaming-Angebote zu entwickeln.Dabei möchte der * fiktive Kunde, dass die Kataloge beliebiger Anbieter verwaltet werden können. * Jeder Katalog kann eine beliebige Reihe an Serien und Filmen beinhalten. * Zusätzlich gibt es eine Watch-List, in die Filme aus allen vorhandenen * Katalogen übergreifend eingetragen werden können.1.Bestimmen Sie die Ihrer * Meinung nach notwendigen Klassen.2.Schreiben Sie für jede in 1. gefundene * Klasse eine Code-Datei mit möglichen Attributen. Schreiben Sie noch keine * Methoden!3.Wir vergleichendie Ergebnisse von 1. und2. */ /*Entwurfsteil zu 1: * * Stichwörter / Essenz: * - Datenbank zu Streaming-Angeboten * - Kataloge beliebiger Anbieter * - Jeder Katalog mit beliebiger Reihe an * - Filmen und * - Serien * * - Zusätzlich dazu Watch-List: * - mit Möglichkeit Filmen (und Serien?) aus allen Katalogen übergreifend einzutragen * * * Dazu notwendige Klassen: * - Anbieter * - Filme * - Serien * - Staffeln * - Folgen * - Watch-List * * Details der Klassen: * - Anbieter: * - Anbitername * - Zugeordente Filme * - Zugeordente Serien (Detail: Staffeln später) * - Weitere Details später: Abo Status, Preise, Adressen, nutzbare Abspielgeräte, ... * - Filme * - Filmname * - Film ID * - Weitere Details später: Erscheinungsjahr, Laufzeit in Minuten, Hauptrollen, ... * - Serien * - Serienname * - zugeordente Staffeln (Liste mit Bezug auf eindeutige Staffel ID) * - Staffeln * - Staffel ID * - Staffelnummer * - zugeordnete Folgen (Liste mit Bezug auf eindeutige Folgen ID) * - Folgen * - Folgen ID * - Folgennummer * - Folgenname * - Weitere Details später: Erscheinungsjahr, Laufzeit in Minuten, ... * (TODO später: Anpassung an DB Struktur, 1. / 2. Normalisierung) * * * **UPDATE** * * - Klassen Filme, Serien, Staffeln und Folgen zusammenfassen: * - Neue Klasse "Medium" mit Typ int "1=Film, 2=Serie" * - Optionale Felder bei Typ 2=Serie: int Staffel, int Folge, string Serienname (Serienname ggfls. Normalisieren) * - Watchlist * - ID des Medium <int> * - Datum/Uhrzeit Aufnahme in Watchlist * - Datum/Uhrzeit gesehen * - Weitere Details später: Anzahl gesehen, Stelle Abbruch letztes abspielen, ... * - AnbieterKatalog (und damit MedienID aus Anbeiter nehmen) * - AnbieterID <int> * - MedienID <int> * - MedienAnbieterURL <string> * - Optional: AufnahmeInKatalog <date>, EntfallenAusKatalog <date> * --> Damit sind die Klassen Anbieter und Medium nur noch Datenhaltendene Klassen! * * */ class Program { static void Main(string[] args) { Anbieter testAnbieter = new Anbieter(); testAnbieter.AnbieterName = "Netflix"; Console.WriteLine("Hello World!" + testAnbieter.AnbieterName); } } }
34.938144
121
0.612275
1e248c9cf63933cac42887978aa5ccd836913c4c
2,496
cs
C#
src/Tasks/Microsoft.NET.Build.Tasks/GenerateBundle.cs
mfkl/sdk
af9a57427221065d39361ebe97f0f43cfb9c73b8
[ "MIT" ]
null
null
null
src/Tasks/Microsoft.NET.Build.Tasks/GenerateBundle.cs
mfkl/sdk
af9a57427221065d39361ebe97f0f43cfb9c73b8
[ "MIT" ]
null
null
null
src/Tasks/Microsoft.NET.Build.Tasks/GenerateBundle.cs
mfkl/sdk
af9a57427221065d39361ebe97f0f43cfb9c73b8
[ "MIT" ]
null
null
null
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.Build.Framework; using Microsoft.NET.HostModel.Bundle; using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; namespace Microsoft.NET.Build.Tasks { public class GenerateBundle : TaskBase { [Required] public ITaskItem[] FilesToBundle { get; set; } [Required] public string AppHostName { get; set; } [Required] public bool IncludeSymbols { get; set; } [Required] public string TargetFrameworkVersion { get; set; } [Required] public string RuntimeIdentifier { get; set; } [Required] public string OutputDir { get; set; } [Required] public bool ShowDiagnosticOutput { get; set; } [Output] public ITaskItem[] ExcludedFiles { get; set; } protected override void ExecuteCore() { OSPlatform targetOS = RuntimeIdentifier.StartsWith("win") ? OSPlatform.Windows : RuntimeIdentifier.StartsWith("osx") ? OSPlatform.OSX : OSPlatform.Linux; BundleOptions options = BundleOptions.BundleAllContent; options |= IncludeSymbols ? BundleOptions.BundleSymbolFiles : BundleOptions.None; var bundler = new Bundler(AppHostName, OutputDir, options, targetOS, new Version(TargetFrameworkVersion), ShowDiagnosticOutput); var fileSpec = new List<FileSpec>(FilesToBundle.Length); foreach (var item in FilesToBundle) { fileSpec.Add(new FileSpec(sourcePath: item.ItemSpec, bundleRelativePath:item.GetMetadata(MetadataKeys.RelativePath))); } bundler.GenerateBundle(fileSpec); // Certain files are excluded from the bundle, based on BundleOptions. // For example: // Native files and contents files are excluded by default. // hostfxr and hostpolicy are excluded until singlefilehost is available. // Return the set of excluded files in ExcludedFiles, so that they can be placed in the publish directory. ExcludedFiles = FilesToBundle.Zip(fileSpec, (item, spec) => (spec.Excluded) ? item : null).Where(x => x != null).ToArray(); } } }
39.619048
140
0.640625
1e265f19cdb48ba0ac77f656d2a744098aced9a9
5,632
cs
C#
BugShooting.Output.Outlook/OutputPlugin.cs
BugShooting/Output.Outlook
347ee3a7c30b44b7a7611de0b6d3eaaf4f590471
[ "MIT" ]
1
2018-05-07T04:59:41.000Z
2018-05-07T04:59:41.000Z
BugShooting.Output.Outlook/OutputPlugin.cs
BugShooting/BugShooting.Output.Outlook
347ee3a7c30b44b7a7611de0b6d3eaaf4f590471
[ "MIT" ]
null
null
null
BugShooting.Output.Outlook/OutputPlugin.cs
BugShooting/BugShooting.Output.Outlook
347ee3a7c30b44b7a7611de0b6d3eaaf4f590471
[ "MIT" ]
null
null
null
using System; using System.Drawing; using System.Windows.Forms; using System.Threading.Tasks; using System.IO; using System.Diagnostics; using Microsoft.Win32; using BS.Plugin.V3.Output; using BS.Plugin.V3.Common; using BS.Plugin.V3.Utilities; using System.Linq; namespace BugShooting.Output.Outlook { public class OutputPlugin: OutputPlugin<Output> { protected override string Name { get { return "Microsoft Outlook"; } } protected override Image Image64 { get { return Properties.Resources.logo_64; } } protected override Image Image16 { get { return Properties.Resources.logo_16 ; } } protected override bool Editable { get { return true; } } protected override string Description { get { return "Attach screenshots to your Outlook emails."; } } protected override Output CreateOutput(IWin32Window Owner) { Output output = new Output(Name, "Screenshot", FileHelper.GetFileFormats().First().ID, false); return EditOutput(Owner, output); } protected override Output EditOutput(IWin32Window Owner, Output Output) { Edit edit = new Edit(Output); var ownerHelper = new System.Windows.Interop.WindowInteropHelper(edit); ownerHelper.Owner = Owner.Handle; if (edit.ShowDialog() == true) { return new Output(edit.OutputName, edit.FileName, edit.FileFormatID, edit.EditFileName); } else { return null; } } protected override OutputValues SerializeOutput(Output Output) { OutputValues outputValues = new OutputValues(); outputValues.Add("Name", Output.Name); outputValues.Add("FileName", Output.FileName); outputValues.Add("FileFormatID", Output.FileFormatID.ToString()); outputValues.Add("EditFileName", Output.EditFileName.ToString()); return outputValues; } protected override Output DeserializeOutput(OutputValues OutputValues) { return new Output(OutputValues["Name", this.Name], OutputValues["FileName", "Screenshot"], new Guid(OutputValues["FileFormatID", ""]), Convert.ToBoolean(OutputValues["EditFileName", false.ToString()])); } protected async override Task<SendResult> Send(IWin32Window Owner, Output Output, ImageData ImageData) { try { string applicationPath = string.Empty; // Check 64-bit application using (RegistryKey localMachineKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64)) { using (RegistryKey clsidKey = localMachineKey.OpenSubKey("Software\\Classes\\Outlook.Application\\CLSID", false)) { if (clsidKey != null) { string clsid = Convert.ToString(clsidKey.GetValue(string.Empty, string.Empty)); using (RegistryKey pathKey = localMachineKey.OpenSubKey("Software\\Classes\\CLSID\\" + clsid + "\\LocalServer32", false)) { if (pathKey != null) applicationPath = Convert.ToString(pathKey.GetValue(string.Empty, string.Empty)); } } } } // Check 32-bit application if (string.IsNullOrEmpty(applicationPath)) { using (RegistryKey localMachineKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32)) { using (RegistryKey clsidKey = localMachineKey.OpenSubKey("Software\\Classes\\Outlook.Application\\CLSID", false)) { if (clsidKey != null) { string clsid = Convert.ToString(clsidKey.GetValue(string.Empty, string.Empty)); using (RegistryKey pathKey = localMachineKey.OpenSubKey("Software\\Classes\\CLSID\\" + clsid + "\\LocalServer32", false)) { if (pathKey != null) applicationPath = Convert.ToString(pathKey.GetValue(string.Empty, string.Empty)); } } } } } if (!File.Exists(applicationPath)) { return new SendResult(Result.Failed, "Microsoft Outlook is not installed."); } string fileName = AttributeHelper.ReplaceAttributes(Output.FileName, ImageData); if (Output.EditFileName) { Send send = new Send(fileName); var ownerHelper = new System.Windows.Interop.WindowInteropHelper(send); ownerHelper.Owner = Owner.Handle; if (send.ShowDialog() != true) { return new SendResult(Result.Canceled); } fileName = send.FileName; } string filePath = Path.Combine(Path.GetTempPath(), fileName + "." + FileHelper.GetFileFormat(Output.FileFormatID).FileExtension); Byte[] fileBytes = FileHelper.GetFileBytes(Output.FileFormatID, ImageData); using (FileStream file = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite)) { file.Write(fileBytes, 0, fileBytes.Length); file.Close(); } Process.Start(applicationPath, "/a \"" + filePath + "\""); return new SendResult(Result.Success); } catch (Exception ex) { return new SendResult(Result.Failed, ex.Message); } } } }
28.734694
137
0.596591
1e288a86b127a0225bd87c70e0fda16be90ab064
12,205
cs
C#
src/Extensions/Default/UI/Dialogs/TalkWindowForm.Designer.cs
tquocthuan/acat
f604d0ac95f1a4fa2fdbaaa63eac1c34a8307303
[ "Apache-2.0" ]
2
2019-06-13T15:56:03.000Z
2021-07-07T15:46:38.000Z
src/Extensions/Default/UI/Dialogs/TalkWindowForm.Designer.cs
mehmetkaraca/acat
f604d0ac95f1a4fa2fdbaaa63eac1c34a8307303
[ "Apache-2.0" ]
null
null
null
src/Extensions/Default/UI/Dialogs/TalkWindowForm.Designer.cs
mehmetkaraca/acat
f604d0ac95f1a4fa2fdbaaa63eac1c34a8307303
[ "Apache-2.0" ]
1
2015-08-19T13:00:26.000Z
2015-08-19T13:00:26.000Z
namespace ACAT.Extensions.Default.UI.Dialogs { partial class TalkWindowForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(TalkWindowForm)); this.labelTalk = new System.Windows.Forms.Label(); this.textBox = new System.Windows.Forms.TextBox(); this.labelClose = new System.Windows.Forms.Label(); this.labelClearText = new System.Windows.Forms.Label(); this.labelDateTime = new System.Windows.Forms.Label(); this.lblIntelIcon = new System.Windows.Forms.Label(); this.BorderPanel = new System.Windows.Forms.Panel(); this.labelVolumeLevel = new System.Windows.Forms.Label(); this.labelSpeaker = new System.Windows.Forms.Label(); this.trackBarVolume = new System.Windows.Forms.TrackBar(); this.BorderPanel.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.trackBarVolume)).BeginInit(); this.SuspendLayout(); // // labelTalk // this.labelTalk.AutoSize = true; this.labelTalk.Font = new System.Drawing.Font("Arial", 18F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.labelTalk.ForeColor = System.Drawing.Color.Black; this.labelTalk.Location = new System.Drawing.Point(56, 6); this.labelTalk.Name = "labelTalk"; this.labelTalk.Size = new System.Drawing.Size(59, 29); this.labelTalk.TabIndex = 2; this.labelTalk.Text = "Talk"; // // textBox // this.textBox.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.textBox.BackColor = System.Drawing.Color.Black; this.textBox.BorderStyle = System.Windows.Forms.BorderStyle.None; this.textBox.Font = new System.Drawing.Font("Arial", 18F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox.Location = new System.Drawing.Point(16, 39); this.textBox.Margin = new System.Windows.Forms.Padding(0); this.textBox.Multiline = true; this.textBox.Name = "textBox"; this.textBox.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.textBox.Size = new System.Drawing.Size(924, 281); this.textBox.TabIndex = 0; // // labelClose // this.labelClose.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.labelClose.BackColor = System.Drawing.Color.Transparent; this.labelClose.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.labelClose.Font = new System.Drawing.Font("Arial", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.labelClose.Location = new System.Drawing.Point(900, 2); this.labelClose.Name = "labelClose"; this.labelClose.Size = new System.Drawing.Size(39, 30); this.labelClose.TabIndex = 7; this.labelClose.Text = "X"; this.labelClose.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.labelClose.Click += new System.EventHandler(this.labelClose_Click); // // labelClearText // this.labelClearText.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.labelClearText.BackColor = System.Drawing.Color.Transparent; this.labelClearText.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.labelClearText.Font = new System.Drawing.Font("Microsoft Sans Serif", 15.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.labelClearText.Location = new System.Drawing.Point(862, 2); this.labelClearText.Name = "labelClearText"; this.labelClearText.Size = new System.Drawing.Size(39, 30); this.labelClearText.TabIndex = 8; this.labelClearText.Text = "0"; this.labelClearText.TextAlign = System.Drawing.ContentAlignment.TopCenter; this.labelClearText.Click += new System.EventHandler(this.labelClearText_Click); // // labelDateTime // this.labelDateTime.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.labelDateTime.Font = new System.Drawing.Font("Arial", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.labelDateTime.ForeColor = System.Drawing.Color.Black; this.labelDateTime.Location = new System.Drawing.Point(526, 9); this.labelDateTime.Name = "labelDateTime"; this.labelDateTime.Size = new System.Drawing.Size(326, 23); this.labelDateTime.TabIndex = 10; this.labelDateTime.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // lblIntelIcon // this.lblIntelIcon.BackColor = System.Drawing.Color.Transparent; this.lblIntelIcon.Font = new System.Drawing.Font("Microsoft Sans Serif", 24F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(2))); this.lblIntelIcon.ForeColor = System.Drawing.Color.RoyalBlue; this.lblIntelIcon.Location = new System.Drawing.Point(3, 2); this.lblIntelIcon.Name = "lblIntelIcon"; this.lblIntelIcon.Size = new System.Drawing.Size(40, 34); this.lblIntelIcon.TabIndex = 11; this.lblIntelIcon.TextAlign = System.Drawing.ContentAlignment.TopCenter; this.lblIntelIcon.UseMnemonic = false; // // BorderPanel // this.BorderPanel.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.BorderPanel.Controls.Add(this.labelVolumeLevel); this.BorderPanel.Controls.Add(this.labelSpeaker); this.BorderPanel.Controls.Add(this.trackBarVolume); this.BorderPanel.Controls.Add(this.lblIntelIcon); this.BorderPanel.Dock = System.Windows.Forms.DockStyle.Fill; this.BorderPanel.Location = new System.Drawing.Point(0, 0); this.BorderPanel.Name = "BorderPanel"; this.BorderPanel.Size = new System.Drawing.Size(957, 353); this.BorderPanel.TabIndex = 12; // // labelVolumeLevel // this.labelVolumeLevel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.labelVolumeLevel.BackColor = System.Drawing.Color.Transparent; this.labelVolumeLevel.Font = new System.Drawing.Font("Arial", 18F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.labelVolumeLevel.ForeColor = System.Drawing.Color.Black; this.labelVolumeLevel.Location = new System.Drawing.Point(901, 318); this.labelVolumeLevel.Name = "labelVolumeLevel"; this.labelVolumeLevel.Size = new System.Drawing.Size(33, 30); this.labelVolumeLevel.TabIndex = 14; this.labelVolumeLevel.TextAlign = System.Drawing.ContentAlignment.TopCenter; // // labelSpeaker // this.labelSpeaker.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.labelSpeaker.BackColor = System.Drawing.Color.Transparent; this.labelSpeaker.Font = new System.Drawing.Font("Microsoft Sans Serif", 21.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(2))); this.labelSpeaker.ForeColor = System.Drawing.Color.Black; this.labelSpeaker.Location = new System.Drawing.Point(728, 313); this.labelSpeaker.Name = "labelSpeaker"; this.labelSpeaker.Size = new System.Drawing.Size(33, 30); this.labelSpeaker.TabIndex = 13; this.labelSpeaker.Text = "F"; this.labelSpeaker.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; // // trackBarVolume // this.trackBarVolume.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.trackBarVolume.AutoSize = false; this.trackBarVolume.LargeChange = 3; this.trackBarVolume.Location = new System.Drawing.Point(756, 322); this.trackBarVolume.Maximum = 9; this.trackBarVolume.Name = "trackBarVolume"; this.trackBarVolume.Size = new System.Drawing.Size(148, 26); this.trackBarVolume.TabIndex = 12; this.trackBarVolume.TabStop = false; this.trackBarVolume.TickFrequency = 3; // // TalkWindowForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.Color.White; this.ClientSize = new System.Drawing.Size(957, 353); this.Controls.Add(this.labelDateTime); this.Controls.Add(this.labelClearText); this.Controls.Add(this.labelClose); this.Controls.Add(this.textBox); this.Controls.Add(this.labelTalk); this.Controls.Add(this.BorderPanel); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MaximizeBox = false; this.Name = "TalkWindowForm"; this.RightToLeftLayout = true; this.Text = "ACAT Talk Window"; this.TopMost = true; this.BorderPanel.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.trackBarVolume)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label labelTalk; private System.Windows.Forms.TextBox textBox; private System.Windows.Forms.Label labelClose; private System.Windows.Forms.Label labelClearText; private System.Windows.Forms.Label labelDateTime; private System.Windows.Forms.Label lblIntelIcon; private System.Windows.Forms.Panel BorderPanel; private System.Windows.Forms.TrackBar trackBarVolume; private System.Windows.Forms.Label labelSpeaker; private System.Windows.Forms.Label labelVolumeLevel; } }
56.50463
177
0.638017
1e28f1ee6551c4ec323a82f3005d41b9eecfc157
4,302
cs
C#
src/GuestConfiguration/GuestConfiguration.Test/ScenarioTests/TestController.cs
khannarheams/azure-powershell
d1bbdaed19bd3dd455301902c9033f7ec687f2e6
[ "MIT" ]
1
2019-07-02T14:29:46.000Z
2019-07-02T14:29:46.000Z
src/GuestConfiguration/GuestConfiguration.Test/ScenarioTests/TestController.cs
khannarheams/azure-powershell
d1bbdaed19bd3dd455301902c9033f7ec687f2e6
[ "MIT" ]
15
2015-05-29T10:07:37.000Z
2018-10-17T09:37:56.000Z
src/GuestConfiguration/GuestConfiguration.Test/ScenarioTests/TestController.cs
khannarheams/azure-powershell
d1bbdaed19bd3dd455301902c9033f7ec687f2e6
[ "MIT" ]
2
2015-08-04T08:00:04.000Z
2018-06-26T10:38:46.000Z
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using Microsoft.Azure.Management.Internal.ResourceManager.Version2018_05_01; using Microsoft.Azure.ServiceManagement.Common.Models; namespace Microsoft.Azure.Commands.GuestConfiguration.Test.ScenarioTests { using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using Microsoft.Azure.Commands.Common.Authentication; using Microsoft.Azure.Management.GuestConfiguration; using Microsoft.Azure.Test.HttpRecorder; using Microsoft.Rest.ClientRuntime.Azure.TestFramework; using Microsoft.WindowsAzure.Commands.ScenarioTest; using Microsoft.WindowsAzure.Commands.Test.Utilities.Common; public class TestController : RMTestBase { private readonly EnvironmentSetupHelper _helper; public GuestConfigurationClient GuestConfigurationClient { get; private set; } public PolicyClient PolicyClient { get; private set; } public static TestController NewInstance => new TestController(); protected TestController() { _helper = new EnvironmentSetupHelper(); } public void RunPowerShellTest(XunitTracingInterceptor logger, params string[] scripts) { var sf = new StackTrace().GetFrame(1); var callingClassType = sf.GetMethod().ReflectedType?.ToString(); var mockName = sf.GetMethod().Name; _helper.TracingInterceptor = logger; var providers = new Dictionary<string, string> { { "Microsoft.Resources", null }, { "Microsoft.Authorization", null } }; var providersToIgnore = new Dictionary<string, string>(); HttpMockServer.Matcher = new PermissiveRecordMatcherWithApiExclusion(true, providers, providersToIgnore); HttpMockServer.RecordsDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "SessionRecords"); using (var context = MockContext.Start(callingClassType, mockName)) { SetupManagementClients(context); _helper.SetupEnvironment(AzureModule.AzureResourceManager); var callingClassName = callingClassType?.Split(new[] { "." }, StringSplitOptions.RemoveEmptyEntries).Last(); _helper.SetupModules( AzureModule.AzureResourceManager, _helper.RMProfileModule, _helper.GetRMModulePath(@"Az.GuestConfiguration.psd1"), "ScenarioTests\\Common.ps1", "ScenarioTests\\" + callingClassName + ".ps1"); _helper.RunPowerShellTest(scripts); } } protected void SetupManagementClients(MockContext context) { GuestConfigurationClient = GetGuestConfigurationClient(context); PolicyClient = GetPolicyClient(context); _helper.SetupManagementClients(GuestConfigurationClient, PolicyClient); } private static GuestConfigurationClient GetGuestConfigurationClient(MockContext context) { return context.GetServiceClient<GuestConfigurationClient>(TestEnvironmentFactory.GetTestEnvironment()); } private static PolicyClient GetPolicyClient(MockContext context) { return context.GetServiceClient<PolicyClient>(TestEnvironmentFactory.GetTestEnvironment()); } } }
43.02
125
0.642492
1e2969d21d360bdc0364eb4c7f65f9083e9c1ca0
73,311
cs
C#
sdk/storage/Azure.Storage.Blobs/src/BlockBlobClient.cs
nemakam/azure-sdk-for-net
396d34be904178ad22c82cac05826b6bee4fc13f
[ "MIT" ]
1
2018-08-24T17:52:35.000Z
2018-08-24T17:52:35.000Z
sdk/storage/Azure.Storage.Blobs/src/BlockBlobClient.cs
nemakam/azure-sdk-for-net
396d34be904178ad22c82cac05826b6bee4fc13f
[ "MIT" ]
154
2019-09-27T03:14:59.000Z
2019-10-14T23:22:19.000Z
sdk/storage/Azure.Storage.Blobs/src/BlockBlobClient.cs
nemakam/azure-sdk-for-net
396d34be904178ad22c82cac05826b6bee4fc13f
[ "MIT" ]
3
2019-10-07T23:32:16.000Z
2019-10-08T22:28:40.000Z
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Azure.Core; using Azure.Core.Pipeline; using Azure.Storage.Blobs.Models; using Metadata = System.Collections.Generic.IDictionary<string, string>; #pragma warning disable SA1402 // File may only contain a single type namespace Azure.Storage.Blobs.Specialized { /// <summary> /// The <see cref="BlockBlobClient"/> allows you to manipulate Azure /// Storage block blobs. /// /// Block blobs let you upload large blobs efficiently. Block blobs are /// comprised of blocks, each of which is identified by a block ID. You /// create or modify a block blob by writing a set of blocks and /// committing them by their block IDs. Each block can be a different /// size, up to a maximum of 100 MB (4 MB for requests using REST versions /// before 2016-05-31), and a block blob can include up to 50,000 blocks. /// The maximum size of a block blob is therefore slightly more than 4.75 /// TB (100 MB X 50,000 blocks). If you are writing a block blob that is /// no more than 256 MB in size, you can upload it in its entirety with a /// single write operation; see <see cref="BlockBlobClient.UploadAsync"/>. /// /// When you upload a block to a blob in your storage account, it is /// associated with the specified block blob, but it does not become part /// of the blob until you commit a list of blocks that includes the new /// block's ID. New blocks remain in an uncommitted state until they are /// specifically committed or discarded. Writing a block does not update /// the last modified time of an existing blob. /// /// Block blobs include features that help you manage large files over /// networks. With a block blob, you can upload multiple blocks in /// parallel to decrease upload time. Each block can include an MD5 hash /// to verify the transfer, so you can track upload progress and re-send /// blocks as needed.You can upload blocks in any order, and determine /// their sequence in the final block list commitment step. You can also /// upload a new block to replace an existing uncommitted block of the /// same block ID. You have one week to commit blocks to a blob before /// they are discarded. All uncommitted blocks are also discarded when a /// block list commitment operation occurs but does not include them. /// /// You can modify an existing block blob by inserting, replacing, or /// deleting existing blocks. After uploading the block or blocks that /// have changed, you can commit a new version of the blob by committing /// the new blocks with the existing blocks you want to keep using a /// single commit operation. To insert the same range of bytes in two /// different locations of the committed blob, you can commit the same /// block in two places within the same commit operation.For any commit /// operation, if any block is not found, the entire commitment operation /// fails with an error, and the blob is not modified. Any block commitment /// overwrites the blob’s existing properties and metadata, and discards /// all uncommitted blocks. /// /// Block IDs are strings of equal length within a blob. Block client code /// usually uses base-64 encoding to normalize strings into equal lengths. /// When using base-64 encoding, the pre-encoded string must be 64 bytes /// or less. Block ID values can be duplicated in different blobs. A /// blob can have up to 100,000 uncommitted blocks, but their total size /// cannot exceed 200,000 MB. /// /// If you write a block for a blob that does not exist, a new block blob /// is created, with a length of zero bytes. This blob will appear in /// blob lists that include uncommitted blobs. If you don’t commit any /// block to this blob, it and its uncommitted blocks will be discarded /// one week after the last successful block upload. All uncommitted /// blocks are also discarded when a new blob of the same name is created /// using a single step(rather than the two-step block upload-then-commit /// process). /// </summary> public class BlockBlobClient : BlobBaseClient { /// <summary> /// Gets the maximum number of bytes that can be sent in a call /// to <see cref="UploadAsync"/>. /// </summary> public virtual int BlockBlobMaxUploadBlobBytes => Constants.Blob.Block.MaxUploadBytes; /// <summary> /// Gets the maximum number of bytes that can be sent in a call /// to <see cref="StageBlockAsync"/>. /// </summary> public virtual int BlockBlobMaxStageBlockBytes => Constants.Blob.Block.MaxStageBytes; /// <summary> /// Gets the maximum number of blocks allowed in a block blob. /// </summary> public virtual int BlockBlobMaxBlocks => Constants.Blob.Block.MaxBlocks; #region ctors /// <summary> /// Initializes a new instance of the <see cref="BlockBlobClient"/> /// class for mocking. /// </summary> protected BlockBlobClient() { } /// <summary> /// Initializes a new instance of the <see cref="BlockBlobClient"/> /// class. /// </summary> /// <param name="connectionString"> /// A connection string includes the authentication information /// required for your application to access data in an Azure Storage /// account at runtime. /// /// For more information, <see href="https://docs.microsoft.com/en-us/azure/storage/common/storage-configure-connection-string"/>. /// </param> /// <param name="containerName"> /// The name of the container containing this block blob. /// </param> /// <param name="blobName"> /// The name of this block blob. /// </param> public BlockBlobClient(string connectionString, string containerName, string blobName) : base(connectionString, containerName, blobName) { } /// <summary> /// Initializes a new instance of the <see cref="BlockBlobClient"/> /// class. /// </summary> /// <param name="connectionString"> /// A connection string includes the authentication information /// required for your application to access data in an Azure Storage /// account at runtime. /// /// For more information, <see href="https://docs.microsoft.com/en-us/azure/storage/common/storage-configure-connection-string"/>. /// </param> /// <param name="blobContainerName"> /// The name of the container containing this block blob. /// </param> /// <param name="blobName"> /// The name of this block blob. /// </param> /// <param name="options"> /// Optional client options that define the transport pipeline /// policies for authentication, retries, etc., that are applied to /// every request. /// </param> public BlockBlobClient(string connectionString, string blobContainerName, string blobName, BlobClientOptions options) : base(connectionString, blobContainerName, blobName, options) { } /// <summary> /// Initializes a new instance of the <see cref="BlockBlobClient"/> /// class. /// </summary> /// <param name="blobUri"> /// A <see cref="Uri"/> referencing the block blob that includes the /// name of the account, the name of the container, and the name of /// the blob. /// </param> /// <param name="options"> /// Optional client options that define the transport pipeline /// policies for authentication, retries, etc., that are applied to /// every request. /// </param> public BlockBlobClient(Uri blobUri, BlobClientOptions options = default) : base(blobUri, options) { } /// <summary> /// Initializes a new instance of the <see cref="BlockBlobClient"/> /// class. /// </summary> /// <param name="blobUri"> /// A <see cref="Uri"/> referencing the blob that includes the /// name of the account, the name of the container, and the name of /// the blob. /// </param> /// <param name="credential"> /// The shared key credential used to sign requests. /// </param> /// <param name="options"> /// Optional client options that define the transport pipeline /// policies for authentication, retries, etc., that are applied to /// every request. /// </param> public BlockBlobClient(Uri blobUri, StorageSharedKeyCredential credential, BlobClientOptions options = default) : base(blobUri, credential, options) { } /// <summary> /// Initializes a new instance of the <see cref="BlockBlobClient"/> /// class. /// </summary> /// <param name="blobUri"> /// A <see cref="Uri"/> referencing the blob that includes the /// name of the account, the name of the container, and the name of /// the blob. /// </param> /// <param name="credential"> /// The token credential used to sign requests. /// </param> /// <param name="options"> /// Optional client options that define the transport pipeline /// policies for authentication, retries, etc., that are applied to /// every request. /// </param> public BlockBlobClient(Uri blobUri, TokenCredential credential, BlobClientOptions options = default) : base(blobUri, credential, options) { } /// <summary> /// Initializes a new instance of the <see cref="BlockBlobClient"/> /// class. /// </summary> /// <param name="blobUri"> /// A <see cref="Uri"/> referencing the block blob that includes the /// name of the account, the name of the container, and the name of /// the blob. /// </param> /// <param name="pipeline"> /// The transport pipeline used to send every request. /// </param> /// <param name="version"> /// The version of the service to use when sending requests. /// </param> /// <param name="clientDiagnostics">Client diagnostics.</param> /// <param name="customerProvidedKey">Customer provided key.</param> /// <param name="encryptionScope">Encryption scope.</param> internal BlockBlobClient( Uri blobUri, HttpPipeline pipeline, BlobClientOptions.ServiceVersion version, ClientDiagnostics clientDiagnostics, CustomerProvidedKey? customerProvidedKey, string encryptionScope) : base(blobUri, pipeline, version, clientDiagnostics, customerProvidedKey, encryptionScope) { } /// <summary> /// Initializes a new instance of the <see cref="BlockBlobClient"/> /// class. /// </summary> /// <param name="blobUri"> /// A <see cref="Uri"/> referencing the block blob that includes the /// name of the account, the name of the container, and the name of /// the blob. /// </param> /// <param name="options"> /// Optional client options that define the transport pipeline /// policies for authentication, retries, etc., that are applied to /// every request. /// </param> /// <param name="pipeline"> /// The transport pipeline used to send every request. /// </param> /// <returns> /// New instanc of the <see cref="BlockBlobClient"/> class. /// </returns> protected static BlockBlobClient CreateClient(Uri blobUri, BlobClientOptions options, HttpPipeline pipeline) { return new BlockBlobClient(blobUri, pipeline, options.Version, new ClientDiagnostics(options), null, null); } #endregion ctors /// <summary> /// Initializes a new instance of the <see cref="BlockBlobClient"/> /// class with an identical <see cref="Uri"/> source but the specified /// <paramref name="snapshot"/> timestamp. /// /// For more information, see <see href="https://docs.microsoft.com/en-us/rest/api/storageservices/creating-a-snapshot-of-a-blob" />. /// </summary> /// <param name="snapshot">The snapshot identifier.</param> /// <returns>A new <see cref="BlockBlobClient"/> instance.</returns> /// <remarks> /// Pass null or empty string to remove the snapshot returning a URL /// to the base blob. /// </remarks> public new BlockBlobClient WithSnapshot(string snapshot) => (BlockBlobClient)WithSnapshotCore(snapshot); /// <summary> /// Creates a new instance of the <see cref="BlockBlobClient"/> class /// with an identical <see cref="Uri"/> source but the specified /// <paramref name="snapshot"/> timestamp. /// </summary> /// <param name="snapshot">The snapshot identifier.</param> /// <returns>A new <see cref="BlockBlobClient"/> instance.</returns> protected sealed override BlobBaseClient WithSnapshotCore(string snapshot) { var builder = new BlobUriBuilder(Uri) { Snapshot = snapshot }; return new BlockBlobClient(builder.ToUri(), Pipeline, Version, ClientDiagnostics, CustomerProvidedKey, EncryptionScope); } ///// <summary> ///// Creates a new BlockBlobURL object identical to the source but with the specified version ID. ///// </summary> ///// <remarks> ///// Pass null or empty string to remove the snapshot returning a URL to the base blob. ///// </remarks> ///// <param name="versionId">A string of the version identifier.</param> ///// <returns></returns> //public new BlockBlobClient WithVersionId(string versionId) => (BlockBlobUri)this.WithVersionIdImpl(versionId); //protected sealed override Blobclient WithVersionIdImpl(string versionId) //{ // var builder = new BlobUriBuilder(this.Uri) { VersionId = versionId }; // return new BlockBlobClient(builder.ToUri(), this.Pipeline); //} #region Upload /// <summary> /// The <see cref="Upload"/> operation creates a new block blob, /// or updates the content of an existing block blob. Updating an /// existing block blob overwrites any existing metadata on the blob. /// /// Partial updates are not supported with <see cref="Upload"/>; /// the content of the existing blob is overwritten with the content /// of the new blob. To perform a partial update of the content of a /// block blob, use the <see cref="StageBlock"/> and /// <see cref="CommitBlockList" /> operations. /// /// For more information, see <see href="https://docs.microsoft.com/rest/api/storageservices/put-blob" />. /// </summary> /// <param name="content"> /// A <see cref="Stream"/> containing the content to upload. /// </param> /// <param name="httpHeaders"> /// Optional standard HTTP header properties that can be set for the /// block blob. /// </param> /// <param name="metadata"> /// Optional custom metadata to set for this block blob. /// </param> /// <param name="conditions"> /// Optional <see cref="BlockBlobClient"/> to add /// conditions on the creation of this new block blob. /// </param> /// <param name="accessTier"> /// Optional <see cref="AccessTier"/> /// Indicates the tier to be set on the blob. /// </param> /// <param name="progressHandler"> /// Optional <see cref="IProgress{Long}"/> to provide /// progress updates about data transfers. /// </param> /// <param name="cancellationToken"> /// Optional <see cref="CancellationToken"/> to propagate /// notifications that the operation should be cancelled. /// </param> /// <returns> /// A <see cref="Response{BlobContentInfo}"/> describing the /// state of the updated block blob. /// </returns> /// <remarks> /// A <see cref="RequestFailedException"/> will be thrown if /// a failure occurs. /// </remarks> public virtual Response<BlobContentInfo> Upload( Stream content, BlobHttpHeaders httpHeaders = default, Metadata metadata = default, BlobRequestConditions conditions = default, AccessTier? accessTier = default, IProgress<long> progressHandler = default, CancellationToken cancellationToken = default) { PartitionedUploader uploader = new PartitionedUploader( client: this, transferOptions: default, operationName: $"{nameof(BlockBlobClient)}.{nameof(Upload)}"); return uploader.Upload( content, httpHeaders, metadata, conditions, progressHandler, accessTier, cancellationToken); } /// <summary> /// The <see cref="UploadAsync"/> operation creates a new block blob, /// or updates the content of an existing block blob. Updating an /// existing block blob overwrites any existing metadata on the blob. /// /// Partial updates are not supported with <see cref="UploadAsync"/>; /// the content of the existing blob is overwritten with the content /// of the new blob. To perform a partial update of the content of a /// block blob, use the <see cref="StageBlockAsync"/> and /// <see cref="CommitBlockListAsync" /> operations. /// /// For more information, see <see href="https://docs.microsoft.com/rest/api/storageservices/put-blob" />. /// </summary> /// <param name="content"> /// A <see cref="Stream"/> containing the content to upload. /// </param> /// <param name="httpHeaders"> /// Optional standard HTTP header properties that can be set for the /// block blob. /// </param> /// <param name="metadata"> /// Optional custom metadata to set for this block blob. /// </param> /// <param name="conditions"> /// Optional <see cref="BlobRequestConditions"/> to add /// conditions on the creation of this new block blob. /// </param> /// <param name="accessTier"> /// Optional <see cref="AccessTier"/> /// Indicates the tier to be set on the blob. /// </param> /// <param name="progressHandler"> /// Optional <see cref="IProgress{Long}"/> to provide /// progress updates about data transfers. /// </param> /// <param name="cancellationToken"> /// Optional <see cref="CancellationToken"/> to propagate /// notifications that the operation should be cancelled. /// </param> /// <returns> /// A <see cref="Response{BlobContentInfo}"/> describing the /// state of the updated block blob. /// </returns> /// <remarks> /// A <see cref="RequestFailedException"/> will be thrown if /// a failure occurs. /// </remarks> public virtual async Task<Response<BlobContentInfo>> UploadAsync( Stream content, BlobHttpHeaders httpHeaders = default, Metadata metadata = default, BlobRequestConditions conditions = default, AccessTier? accessTier = default, IProgress<long> progressHandler = default, CancellationToken cancellationToken = default) { PartitionedUploader uploader = new PartitionedUploader( client: this, transferOptions: default, operationName: $"{nameof(BlockBlobClient)}.{nameof(Upload)}"); return await uploader.UploadAsync( content, httpHeaders, metadata, conditions, progressHandler, accessTier, cancellationToken).ConfigureAwait(false); } /// <summary> /// The <see cref="UploadInternal"/> operation creates a new block blob, /// or updates the content of an existing block blob. Updating an /// existing block blob overwrites any existing metadata on the blob. /// /// Partial updates are not supported with <see cref="UploadAsync"/>; /// the content of the existing blob is overwritten with the content /// of the new blob. To perform a partial update of the content of a /// block blob, use the <see cref="StageBlockAsync"/> and /// <see cref="CommitBlockListAsync" /> operations. /// /// For more information, see <see href="https://docs.microsoft.com/rest/api/storageservices/put-blob" />. /// </summary> /// <param name="content"> /// A <see cref="Stream"/> containing the content to upload. /// </param> /// <param name="blobHttpHeaders"> /// Optional standard HTTP header properties that can be set for the /// block blob. /// </param> /// <param name="metadata"> /// Optional custom metadata to set for this block blob. /// </param> /// <param name="conditions"> /// Optional <see cref="BlockBlobClient"/> to add /// conditions on the creation of this new block blob. /// </param> /// <param name="accessTier"> /// Optional <see cref="AccessTier"/> /// Indicates the tier to be set on the blob. /// </param> /// <param name="progressHandler"> /// Optional <see cref="IProgress{Long}"/> to provide /// progress updates about data transfers. /// </param> /// <param name="operationName"> /// The name of the calling operation. /// </param> /// <param name="async"> /// Whether to invoke the operation asynchronously. /// </param> /// <param name="cancellationToken"> /// Optional <see cref="CancellationToken"/> to propagate /// notifications that the operation should be cancelled. /// </param> /// <returns> /// A <see cref="Response{BlobContentInfo}"/> describing the /// state of the updated block blob. /// </returns> /// <remarks> /// A <see cref="RequestFailedException"/> will be thrown if /// a failure occurs. /// </remarks> internal virtual async Task<Response<BlobContentInfo>> UploadInternal( Stream content, BlobHttpHeaders blobHttpHeaders, Metadata metadata, BlobRequestConditions conditions, AccessTier? accessTier, IProgress<long> progressHandler, string operationName, bool async, CancellationToken cancellationToken) { content = content?.WithNoDispose().WithProgress(progressHandler); using (Pipeline.BeginLoggingScope(nameof(BlockBlobClient))) { Pipeline.LogMethodEnter( nameof(BlockBlobClient), message: $"{nameof(Uri)}: {Uri}\n" + $"{nameof(blobHttpHeaders)}: {blobHttpHeaders}\n" + $"{nameof(conditions)}: {conditions}"); try { return await BlobRestClient.BlockBlob.UploadAsync( ClientDiagnostics, Pipeline, Uri, body: content, contentLength: content?.Length ?? 0, version: Version.ToVersionString(), blobContentType: blobHttpHeaders?.ContentType, blobContentEncoding: blobHttpHeaders?.ContentEncoding, blobContentLanguage: blobHttpHeaders?.ContentLanguage, blobContentHash: blobHttpHeaders?.ContentHash, blobCacheControl: blobHttpHeaders?.CacheControl, metadata: metadata, leaseId: conditions?.LeaseId, blobContentDisposition: blobHttpHeaders?.ContentDisposition, encryptionKey: CustomerProvidedKey?.EncryptionKey, encryptionKeySha256: CustomerProvidedKey?.EncryptionKeyHash, encryptionAlgorithm: CustomerProvidedKey?.EncryptionAlgorithm, encryptionScope: EncryptionScope, tier: accessTier, ifModifiedSince: conditions?.IfModifiedSince, ifUnmodifiedSince: conditions?.IfUnmodifiedSince, ifMatch: conditions?.IfMatch, ifNoneMatch: conditions?.IfNoneMatch, async: async, operationName: operationName ?? $"{nameof(BlockBlobClient)}.{nameof(Upload)}", cancellationToken: cancellationToken) .ConfigureAwait(false); } catch (Exception ex) { Pipeline.LogException(ex); throw; } finally { Pipeline.LogMethodExit(nameof(BlockBlobClient)); } } } #endregion Upload #region StageBlock /// <summary> /// The <see cref="StageBlock"/> operation creates a new block as /// part of a block blob's "staging area" to be eventually committed /// via the <see cref="CommitBlockList"/> operation. /// /// For more information, see <see href="https://docs.microsoft.com/en-us/rest/api/storageservices/put-block" />. /// </summary> /// <param name="base64BlockId"> /// A valid Base64 string value that identifies the block. Prior to /// encoding, the string must be less than or equal to 64 bytes in /// size. /// /// For a given blob, the length of the value specified for the /// blockid parameter must be the same size for each block. Note that /// the Base64 string must be URL-encoded. /// </param> /// <param name="content"> /// A <see cref="Stream"/> containing the content to upload. /// </param> /// <param name="transactionalContentHash"> /// An optional MD5 hash of the block <paramref name="content"/>. /// This hash is used to verify the integrity of the block during /// transport. When this value is specified, the storage service /// compares the hash of the content that has arrived with this value. /// Note that this MD5 hash is not stored with the blob. If the two /// hashes do not match, the operation will throw a /// <see cref="RequestFailedException"/>. /// </param> /// <param name="conditions"> /// Optional <see cref="BlobRequestConditions"/> to add /// conditions on the upload of this block. /// </param> /// <param name="progressHandler"> /// Optional <see cref="IProgress{Long}"/> to provide /// progress updates about data transfers. /// </param> /// <param name="cancellationToken"> /// Optional <see cref="CancellationToken"/> to propagate /// notifications that the operation should be cancelled. /// </param> /// <returns> /// A <see cref="Response{BlockInfo}"/> describing the /// state of the updated block. /// </returns> /// <remarks> /// A <see cref="RequestFailedException"/> will be thrown if /// a failure occurs. /// </remarks> public virtual Response<BlockInfo> StageBlock( string base64BlockId, Stream content, byte[] transactionalContentHash = default, BlobRequestConditions conditions = default, IProgress<long> progressHandler = default, CancellationToken cancellationToken = default) => StageBlockInternal( base64BlockId, content, transactionalContentHash, conditions, progressHandler, false, // async cancellationToken) .EnsureCompleted(); /// <summary> /// The <see cref="StageBlockAsync"/> operation creates a new block as /// part of a block blob's "staging area" to be eventually committed /// via the <see cref="CommitBlockListAsync"/> operation. /// /// For more information, see <see href="https://docs.microsoft.com/en-us/rest/api/storageservices/put-block" />. /// </summary> /// <param name="base64BlockId"> /// A valid Base64 string value that identifies the block. Prior to /// encoding, the string must be less than or equal to 64 bytes in /// size. /// /// For a given blob, the length of the value specified for the /// blockid parameter must be the same size for each block. Note that /// the Base64 string must be URL-encoded. /// </param> /// <param name="content"> /// A <see cref="Stream"/> containing the content to upload. /// </param> /// <param name="transactionalContentHash"> /// An optional MD5 hash of the block <paramref name="content"/>. /// This hash is used to verify the integrity of the block during /// transport. When this value is specified, the storage service /// compares the hash of the content that has arrived with this value. /// Note that this MD5 hash is not stored with the blob. If the two /// hashes do not match, the operation will throw a /// <see cref="RequestFailedException"/>. /// </param> /// <param name="conditions"> /// Optional <see cref="BlobRequestConditions"/> to add /// conditions on the upload of this block. /// </param> /// <param name="progressHandler"> /// Optional <see cref="IProgress{Long}"/> to provide /// progress updates about data transfers. /// </param> /// <param name="cancellationToken"> /// Optional <see cref="CancellationToken"/> to propagate /// notifications that the operation should be cancelled. /// </param> /// <returns> /// A <see cref="Response{BlockInfo}"/> describing the /// state of the updated block. /// </returns> /// <remarks> /// A <see cref="RequestFailedException"/> will be thrown if /// a failure occurs. /// </remarks> public virtual async Task<Response<BlockInfo>> StageBlockAsync( string base64BlockId, Stream content, byte[] transactionalContentHash = default, BlobRequestConditions conditions = default, IProgress<long> progressHandler = default, CancellationToken cancellationToken = default) => await StageBlockInternal( base64BlockId, content, transactionalContentHash, conditions, progressHandler, true, // async cancellationToken) .ConfigureAwait(false); /// <summary> /// The <see cref="StageBlockInternal"/> operation creates a new block /// as part of a block blob's "staging area" to be eventually committed /// via the <see cref="CommitBlockListAsync"/> operation. /// /// For more information, see <see href="https://docs.microsoft.com/en-us/rest/api/storageservices/put-block" />. /// </summary> /// <param name="base64BlockId"> /// A valid Base64 string value that identifies the block. Prior to /// encoding, the string must be less than or equal to 64 bytes in /// size. /// /// For a given blob, the length of the value specified for the /// blockid parameter must be the same size for each block. Note that /// the Base64 string must be URL-encoded. /// </param> /// <param name="content"> /// A <see cref="Stream"/> containing the content to upload. /// </param> /// <param name="transactionalContentHash"> /// An optional MD5 hash of the block <paramref name="content"/>. /// This hash is used to verify the integrity of the block during /// transport. When this value is specified, the storage service /// compares the hash of the content that has arrived with this value. /// Note that this MD5 hash is not stored with the blob. If the two /// hashes do not match, the operation will throw a /// <see cref="RequestFailedException"/>. /// </param> /// <param name="conditions"> /// Optional <see cref="BlobRequestConditions"/> to add /// conditions on the upload of this block. /// </param> /// <param name="progressHandler"> /// Optional <see cref="IProgress{Long}"/> to provide /// progress updates about data transfers. /// </param> /// <param name="async"> /// Whether to invoke the operation asynchronously. /// </param> /// <param name="cancellationToken"> /// Optional <see cref="CancellationToken"/> to propagate /// notifications that the operation should be cancelled. /// </param> /// <returns> /// A <see cref="Response{BlockInfo}"/> describing the /// state of the updated block. /// </returns> /// <remarks> /// A <see cref="RequestFailedException"/> will be thrown if /// a failure occurs. /// </remarks> internal async Task<Response<BlockInfo>> StageBlockInternal( string base64BlockId, Stream content, byte[] transactionalContentHash, BlobRequestConditions conditions, IProgress<long> progressHandler, bool async, CancellationToken cancellationToken) { using (Pipeline.BeginLoggingScope(nameof(BlockBlobClient))) { Pipeline.LogMethodEnter( nameof(BlockBlobClient), message: $"{nameof(Uri)}: {Uri}\n" + $"{nameof(base64BlockId)}: {base64BlockId}\n" + $"{nameof(conditions)}: {conditions}"); try { content = content.WithNoDispose().WithProgress(progressHandler); return await BlobRestClient.BlockBlob.StageBlockAsync( ClientDiagnostics, Pipeline, Uri, blockId: base64BlockId, body: content, contentLength: content.Length, version: Version.ToVersionString(), transactionalContentHash: transactionalContentHash, leaseId: conditions?.LeaseId, encryptionKey: CustomerProvidedKey?.EncryptionKey, encryptionKeySha256: CustomerProvidedKey?.EncryptionKeyHash, encryptionAlgorithm: CustomerProvidedKey?.EncryptionAlgorithm, encryptionScope: EncryptionScope, async: async, operationName: $"{nameof(BlockBlobClient)}.{nameof(StageBlock)}", cancellationToken: cancellationToken).ConfigureAwait(false); } catch (Exception ex) { Pipeline.LogException(ex); throw; } finally { Pipeline.LogMethodExit(nameof(BlockBlobClient)); } } } #endregion StageBlock #region StageBlockFromUri /// <summary> /// The <see cref="StageBlockFromUri"/> operation creates a new /// block to be committed as part of a blob where the contents are /// read from the <paramref name="sourceUri" />. /// /// For more information, see <see href="https://docs.microsoft.com/en-us/rest/api/storageservices/put-block-from-url"/>. /// </summary> /// <param name="sourceUri"> /// Specifies the <see cref="Uri"/> of the source blob. The value may /// be a URL of up to 2 KB in length that specifies a blob. The /// source blob must either be public or must be authenticated via a /// shared access signature. If the source blob is public, no /// authentication is required to perform the operation. /// </param> /// <param name="base64BlockId"> /// A valid Base64 string value that identifies the block. Prior to /// encoding, the string must be less than or equal to 64 bytes in /// size. For a given blob, the length of the value specified for /// the <paramref name="base64BlockId"/> parameter must be the same /// size for each block. Note that the Base64 string must be /// URL-encoded. /// </param> /// <param name="sourceRange"> /// Optionally uploads only the bytes of the blob in the /// <paramref name="sourceUri"/> in the specified range. If this is /// not specified, the entire source blob contents are uploaded as a /// single block. /// </param> /// <param name="sourceContentHash"> /// Optional MD5 hash of the block content from the /// <paramref name="sourceUri"/>. This hash is used to verify the /// integrity of the block during transport of the data from the Uri. /// When this hash is specified, the storage service compares the hash /// of the content that has arrived from the <paramref name="sourceUri"/> /// with this value. Note that this md5 hash is not stored with the /// blob. If the two hashes do not match, the operation will fail /// with a <see cref="RequestFailedException"/>. /// </param> /// <param name="sourceConditions"> /// Optional <see cref="RequestConditions"/> to add /// conditions on the copying of data from this source blob. /// </param> /// <param name="conditions"> /// Optional <see cref="BlobRequestConditions"/> to add /// conditions on the staging of this block. /// </param> /// <param name="cancellationToken"> /// Optional <see cref="CancellationToken"/> to propagate /// notifications that the operation should be cancelled. /// </param> /// <returns> /// A <see cref="Response{BlockInfo}"/> describing the /// state of the updated block blob. /// </returns> /// <remarks> /// A <see cref="RequestFailedException"/> will be thrown if /// a failure occurs. /// </remarks> public virtual Response<BlockInfo> StageBlockFromUri( Uri sourceUri, string base64BlockId, HttpRange sourceRange = default, byte[] sourceContentHash = default, RequestConditions sourceConditions = default, BlobRequestConditions conditions = default, CancellationToken cancellationToken = default) => StageBlockFromUriInternal( sourceUri, base64BlockId, sourceRange, sourceContentHash, sourceConditions, conditions, false, // async cancellationToken) .EnsureCompleted(); /// <summary> /// The <see cref="StageBlockFromUriAsync"/> operation creates a new /// block to be committed as part of a blob where the contents are /// read from the <paramref name="sourceUri" />. /// /// For more information, see <see href="https://docs.microsoft.com/en-us/rest/api/storageservices/put-block-from-url"/>. /// </summary> /// <param name="sourceUri"> /// Specifies the <see cref="Uri"/> of the source blob. The value may /// be a URL of up to 2 KB in length that specifies a blob. The /// source blob must either be public or must be authenticated via a /// shared access signature. If the source blob is public, no /// authentication is required to perform the operation. /// </param> /// <param name="base64BlockId"> /// A valid Base64 string value that identifies the block. Prior to /// encoding, the string must be less than or equal to 64 bytes in /// size. For a given blob, the length of the value specified for /// the <paramref name="base64BlockId"/> parameter must be the same /// size for each block. Note that the Base64 string must be /// URL-encoded. /// </param> /// <param name="sourceRange"> /// Optionally uploads only the bytes of the blob in the /// <paramref name="sourceUri"/> in the specified range. If this is /// not specified, the entire source blob contents are uploaded as a /// single block. /// </param> /// <param name="sourceContentHash"> /// Optional MD5 hash of the block content from the /// <paramref name="sourceUri"/>. This hash is used to verify the /// integrity of the block during transport of the data from the Uri. /// When this hash is specified, the storage service compares the hash /// of the content that has arrived from the <paramref name="sourceUri"/> /// with this value. Note that this md5 hash is not stored with the /// blob. If the two hashes do not match, the operation will fail /// with a <see cref="RequestFailedException"/>. /// </param> /// <param name="sourceConditions"> /// Optional <see cref="RequestConditions"/> to add /// conditions on the copying of data from this source blob. /// </param> /// <param name="conditions"> /// Optional <see cref="BlobRequestConditions"/> to add /// conditions on the staging of this block. /// </param> /// <param name="cancellationToken"> /// Optional <see cref="CancellationToken"/> to propagate /// notifications that the operation should be cancelled. /// </param> /// <returns> /// A <see cref="Response{BlockInfo}"/> describing the /// state of the updated block. /// </returns> /// <remarks> /// A <see cref="RequestFailedException"/> will be thrown if /// a failure occurs. /// </remarks> public virtual async Task<Response<BlockInfo>> StageBlockFromUriAsync( Uri sourceUri, string base64BlockId, HttpRange sourceRange = default, byte[] sourceContentHash = default, RequestConditions sourceConditions = default, BlobRequestConditions conditions = default, CancellationToken cancellationToken = default) => await StageBlockFromUriInternal( sourceUri, base64BlockId, sourceRange, sourceContentHash, sourceConditions, conditions, true, // async cancellationToken) .ConfigureAwait(false); /// <summary> /// The <see cref="StageBlockFromUriInternal"/> operation creates a new /// block to be committed as part of a blob where the contents are /// read from the <paramref name="sourceUri" />. /// /// For more information, see <see href="https://docs.microsoft.com/en-us/rest/api/storageservices/put-block-from-url"/>. /// </summary> /// <param name="sourceUri"> /// Specifies the <see cref="Uri"/> of the source blob. The value may /// be a URL of up to 2 KB in length that specifies a blob. The /// source blob must either be public or must be authenticated via a /// shared access signature. If the source blob is public, no /// authentication is required to perform the operation. /// </param> /// <param name="base64BlockId"> /// A valid Base64 string value that identifies the block. Prior to /// encoding, the string must be less than or equal to 64 bytes in /// size. For a given blob, the length of the value specified for /// the <paramref name="base64BlockId"/> parameter must be the same /// size for each block. Note that the Base64 string must be /// URL-encoded. /// </param> /// <param name="sourceRange"> /// Optionally uploads only the bytes of the blob in the /// <paramref name="sourceUri"/> in the specified range. If this is /// not specified, the entire source blob contents are uploaded as a /// single block. /// </param> /// <param name="sourceContentHash"> /// Optional MD5 hash of the block content from the /// <paramref name="sourceUri"/>. This hash is used to verify the /// integrity of the block during transport of the data from the Uri. /// When this hash is specified, the storage service compares the hash /// of the content that has arrived from the <paramref name="sourceUri"/> /// with this value. Note that this md5 hash is not stored with the /// blob. If the two hashes do not match, the operation will fail /// with a <see cref="RequestFailedException"/>. /// </param> /// <param name="sourceConditions"> /// Optional <see cref="RequestConditions"/> to add /// conditions on the copying of data from this source blob. /// </param> /// <param name="conditions"> /// Optional <see cref="BlobRequestConditions"/> to add /// conditions on the staging of this block. /// </param> /// <param name="async"> /// Whether to invoke the operation asynchronously. /// </param> /// <param name="cancellationToken"> /// Optional <see cref="CancellationToken"/> to propagate /// notifications that the operation should be cancelled. /// </param> /// <returns> /// A <see cref="Response{BlockInfo}"/> describing the /// state of the updated block. /// </returns> /// <remarks> /// A <see cref="RequestFailedException"/> will be thrown if /// a failure occurs. /// </remarks> private async Task<Response<BlockInfo>> StageBlockFromUriInternal( Uri sourceUri, string base64BlockId, HttpRange sourceRange, byte[] sourceContentHash, RequestConditions sourceConditions, BlobRequestConditions conditions, bool async, CancellationToken cancellationToken) { using (Pipeline.BeginLoggingScope(nameof(BlockBlobClient))) { Pipeline.LogMethodEnter( nameof(BlockBlobClient), message: $"{nameof(Uri)}: {Uri}\n" + $"{nameof(base64BlockId)}: {base64BlockId}\n" + $"{nameof(sourceUri)}: {sourceUri}\n" + $"{nameof(conditions)}: {conditions}"); try { return await BlobRestClient.BlockBlob.StageBlockFromUriAsync( ClientDiagnostics, Pipeline, Uri, contentLength: default, blockId: base64BlockId, sourceUri: sourceUri, version: Version.ToVersionString(), sourceRange: sourceRange.ToString(), sourceContentHash: sourceContentHash, encryptionKey: CustomerProvidedKey?.EncryptionKey, encryptionKeySha256: CustomerProvidedKey?.EncryptionKeyHash, encryptionAlgorithm: CustomerProvidedKey?.EncryptionAlgorithm, encryptionScope: EncryptionScope, leaseId: conditions?.LeaseId, sourceIfModifiedSince: sourceConditions?.IfModifiedSince, sourceIfUnmodifiedSince: sourceConditions?.IfUnmodifiedSince, sourceIfMatch: sourceConditions?.IfMatch, sourceIfNoneMatch: sourceConditions?.IfNoneMatch, async: async, operationName: $"{nameof(BlockBlobClient)}.{nameof(StageBlockFromUri)}", cancellationToken: cancellationToken) .ConfigureAwait(false); } catch (Exception ex) { Pipeline.LogException(ex); throw; } finally { Pipeline.LogMethodExit(nameof(BlockBlobClient)); } } } #endregion StageBlockFromUri #region CommitBlockList /// <summary> /// The <see cref="CommitBlockList"/> operation writes a blob by /// specifying the list of block IDs that make up the blob. In order /// to be written as part of a blob, a block must have been /// successfully written to the server in a prior <see cref="StageBlock"/> /// operation. You can call <see cref="CommitBlockList"/> to /// update a blob by uploading only those blocks that have changed, /// then committing the new and existing blocks together. You can do /// this by specifying whether to commit a block from the committed /// block list or from the uncommitted block list, or to commit the /// most recently uploaded version of the block, whichever list it /// may belong to. Any blocks not specified in the block list and /// permanently deleted. /// /// For more information, see <see href="https://docs.microsoft.com/rest/api/storageservices/put-block-list"/>. /// </summary> /// <param name="base64BlockIds"> /// Specify the Uncommitted Base64 encoded block IDs to indicate that /// the blob service should search only the uncommitted block list for /// the named blocks. If the block is not found in the uncommitted /// block list, it will not be written as part of the blob, and a /// <see cref="RequestFailedException"/> will be thrown. /// </param> /// <param name="httpHeaders"> /// Optional standard HTTP header properties that can be set for the /// block blob. /// </param> /// <param name="metadata"> /// Optional custom metadata to set for this block blob. /// </param> /// <param name="conditions"> /// Optional <see cref="BlockBlobClient"/> to add /// conditions on committing this block list. /// </param> /// <param name="accessTier"> /// Optional <see cref="AccessTier"/> /// Indicates the tier to be set on the blob. /// </param> /// <param name="cancellationToken"> /// Optional <see cref="CancellationToken"/> to propagate /// notifications that the operation should be cancelled. /// </param> /// <returns> /// A <see cref="Response{BlobAppendInfo}"/> describing the /// state of the updated block blob. /// </returns> /// <remarks> /// A <see cref="RequestFailedException"/> will be thrown if /// a failure occurs. /// </remarks> public virtual Response<BlobContentInfo> CommitBlockList( IEnumerable<string> base64BlockIds, BlobHttpHeaders httpHeaders = default, Metadata metadata = default, BlobRequestConditions conditions = default, AccessTier? accessTier = default, CancellationToken cancellationToken = default) => CommitBlockListInternal( base64BlockIds, httpHeaders, metadata, conditions, accessTier, false, // async cancellationToken) .EnsureCompleted(); /// <summary> /// The <see cref="CommitBlockListAsync"/> operation writes a blob by /// specifying the list of block IDs that make up the blob. In order /// to be written as part of a blob, a block must have been /// successfully written to the server in a prior <see cref="StageBlockAsync"/> /// operation. You can call <see cref="CommitBlockListAsync"/> to /// update a blob by uploading only those blocks that have changed, /// then committing the new and existing blocks together. You can do /// this by specifying whether to commit a block from the committed /// block list or from the uncommitted block list, or to commit the /// most recently uploaded version of the block, whichever list it /// may belong to. Any blocks not specified in the block list and /// permanently deleted. /// /// For more information, see <see href="https://docs.microsoft.com/rest/api/storageservices/put-block-list"/>. /// </summary> /// <param name="base64BlockIds"> /// Specify the Uncommitted Base64 encoded block IDs to indicate that /// the blob service should search only the uncommitted block list for /// the named blocks. If the block is not found in the uncommitted /// block list, it will not be written as part of the blob, and a /// <see cref="RequestFailedException"/> will be thrown. /// </param> /// <param name="httpHeaders"> /// Optional standard HTTP header properties that can be set for the /// block blob. /// </param> /// <param name="metadata"> /// Optional custom metadata to set for this block blob. /// </param> /// <param name="conditions"> /// Optional <see cref="BlockBlobClient"/> to add /// conditions on committing this block list. /// </param> /// <param name="accessTier"> /// Optional <see cref="AccessTier"/> /// Indicates the tier to be set on the blob. /// </param> /// <param name="cancellationToken"> /// Optional <see cref="CancellationToken"/> to propagate /// notifications that the operation should be cancelled. /// </param> /// <returns> /// A <see cref="Response{BlobAppendInfo}"/> describing the /// state of the updated block blob. /// </returns> /// <remarks> /// A <see cref="RequestFailedException"/> will be thrown if /// a failure occurs. /// </remarks> public virtual async Task<Response<BlobContentInfo>> CommitBlockListAsync( IEnumerable<string> base64BlockIds, BlobHttpHeaders httpHeaders = default, Metadata metadata = default, BlobRequestConditions conditions = default, AccessTier? accessTier = default, CancellationToken cancellationToken = default) => await CommitBlockListInternal( base64BlockIds, httpHeaders, metadata, conditions, accessTier, true, // async cancellationToken) .ConfigureAwait(false); /// <summary> /// The <see cref="CommitBlockListInternal"/> operation writes a blob by /// specifying the list of block IDs that make up the blob. In order /// to be written as part of a blob, a block must have been /// successfully written to the server in a prior <see cref="StageBlockAsync"/> /// operation. You can call <see cref="CommitBlockListAsync"/> to /// update a blob by uploading only those blocks that have changed, /// then committing the new and existing blocks together. You can do /// this by specifying whether to commit a block from the committed /// block list or from the uncommitted block list, or to commit the /// most recently uploaded version of the block, whichever list it /// may belong to. Any blocks not specified in the block list and /// permanently deleted. /// /// For more information, see <see href="https://docs.microsoft.com/rest/api/storageservices/put-block-list"/>. /// </summary> /// <param name="base64BlockIds"> /// Specify the Uncommitted Base64 encoded block IDs to indicate that /// the blob service should search only the uncommitted block list for /// the named blocks. If the block is not found in the uncommitted /// block list, it will not be written as part of the blob, and a /// <see cref="RequestFailedException"/> will be thrown. /// </param> /// <param name="blobHttpHeaders"> /// Optional standard HTTP header properties that can be set for the /// block blob. /// </param> /// <param name="metadata"> /// Optional custom metadata to set for this block blob. /// </param> /// <param name="conditions"> /// Optional <see cref="BlockBlobClient"/> to add /// conditions on committing this block list. /// </param> /// <param name="accessTier"> /// Optional <see cref="AccessTier"/> /// Indicates the tier to be set on the blob. /// </param> /// <param name="async"> /// Whether to invoke the operation asynchronously. /// </param> /// <param name="cancellationToken"> /// Optional <see cref="CancellationToken"/> to propagate /// notifications that the operation should be cancelled. /// </param> /// <returns> /// A <see cref="Response{BlobAppendInfo}"/> describing the /// state of the updated block blob. /// </returns> /// <remarks> /// A <see cref="RequestFailedException"/> will be thrown if /// a failure occurs. /// </remarks> internal async Task<Response<BlobContentInfo>> CommitBlockListInternal( IEnumerable<string> base64BlockIds, BlobHttpHeaders blobHttpHeaders, Metadata metadata, BlobRequestConditions conditions, AccessTier? accessTier, bool async, CancellationToken cancellationToken) { using (Pipeline.BeginLoggingScope(nameof(BlockBlobClient))) { Pipeline.LogMethodEnter( nameof(BlockBlobClient), message: $"{nameof(Uri)}: {Uri}\n" + $"{nameof(base64BlockIds)}: {base64BlockIds}\n" + $"{nameof(blobHttpHeaders)}: {blobHttpHeaders}\n" + $"{nameof(conditions)}: {conditions}"); try { var blocks = new BlockLookupList() { Latest = base64BlockIds.ToList() }; return await BlobRestClient.BlockBlob.CommitBlockListAsync( ClientDiagnostics, Pipeline, Uri, blocks, version: Version.ToVersionString(), blobCacheControl: blobHttpHeaders?.CacheControl, blobContentType: blobHttpHeaders?.ContentType, blobContentEncoding: blobHttpHeaders?.ContentEncoding, blobContentLanguage: blobHttpHeaders?.ContentLanguage, blobContentHash: blobHttpHeaders?.ContentHash, metadata: metadata, leaseId: conditions?.LeaseId, blobContentDisposition: blobHttpHeaders?.ContentDisposition, encryptionKey: CustomerProvidedKey?.EncryptionKey, encryptionKeySha256: CustomerProvidedKey?.EncryptionKeyHash, encryptionAlgorithm: CustomerProvidedKey?.EncryptionAlgorithm, encryptionScope: EncryptionScope, tier: accessTier, ifModifiedSince: conditions?.IfModifiedSince, ifUnmodifiedSince: conditions?.IfUnmodifiedSince, ifMatch: conditions?.IfMatch, ifNoneMatch: conditions?.IfNoneMatch, async: async, operationName: $"{nameof(BlockBlobClient)}.{nameof(CommitBlockList)}", cancellationToken: cancellationToken) .ConfigureAwait(false); } catch (Exception ex) { Pipeline.LogException(ex); throw; } finally { Pipeline.LogMethodExit(nameof(BlockBlobClient)); } } } #endregion CommitBlockList #region GetBlockList /// <summary> /// The <see cref="GetBlockList"/> operation operation retrieves /// the list of blocks that have been uploaded as part of a block blob. /// There are two block lists maintained for a blob. The Committed /// Block list has blocks that have been successfully committed to a /// given blob with <see cref="CommitBlockList"/>. The /// Uncommitted Block list has blocks that have been uploaded for a /// blob using <see cref="StageBlock"/>, but that have not yet /// been committed. These blocks are stored in Azure in association /// with a blob, but do not yet form part of the blob. /// </summary> /// <param name="blockListTypes"> /// Specifies whether to return the list of committed blocks, the /// list of uncommitted blocks, or both lists together. If you omit /// this parameter, Get Block List returns the list of committed blocks. /// </param> /// <param name="snapshot"> /// Optionally specifies the blob snapshot to retrieve the block list /// from. For more information on working with blob snapshots, see /// <see href="https://docs.microsoft.com/en-us/rest/api/storageservices/creating-a-snapshot-of-a-blob"/>. /// </param> /// <param name="conditions"> /// Optional <see cref="BlobRequestConditions"/> to add /// conditions on retrieving the block list. /// </param> /// <param name="cancellationToken"> /// Optional <see cref="CancellationToken"/> to propagate /// notifications that the operation should be cancelled. /// </param> /// <returns> /// A <see cref="Response{BlockList}"/> describing requested /// block list. /// </returns> /// <remarks> /// A <see cref="RequestFailedException"/> will be thrown if /// a failure occurs. /// </remarks> public virtual Response<BlockList> GetBlockList( BlockListTypes blockListTypes = BlockListTypes.All, string snapshot = default, BlobRequestConditions conditions = default, CancellationToken cancellationToken = default) => GetBlockListInternal( blockListTypes, snapshot, conditions, false, // async cancellationToken) .EnsureCompleted(); /// <summary> /// The <see cref="GetBlockListAsync"/> operation operation retrieves /// the list of blocks that have been uploaded as part of a block blob. /// There are two block lists maintained for a blob. The Committed /// Block list has blocks that have been successfully committed to a /// given blob with <see cref="CommitBlockListAsync"/>. The /// Uncommitted Block list has blocks that have been uploaded for a /// blob using <see cref="StageBlockAsync"/>, but that have not yet /// been committed. These blocks are stored in Azure in association /// with a blob, but do not yet form part of the blob. /// </summary> /// <param name="blockListTypes"> /// Specifies whether to return the list of committed blocks, the /// list of uncommitted blocks, or both lists together. If you omit /// this parameter, Get Block List returns the list of committed blocks. /// </param> /// <param name="snapshot"> /// Optionally specifies the blob snapshot to retrieve the block list /// from. For more information on working with blob snapshots, see /// <see href="https://docs.microsoft.com/en-us/rest/api/storageservices/creating-a-snapshot-of-a-blob"/>. /// </param> /// <param name="conditions"> /// Optional <see cref="BlobRequestConditions"/> to add /// conditions on retrieving the block list. /// </param> /// <param name="cancellationToken"> /// Optional <see cref="CancellationToken"/> to propagate /// notifications that the operation should be cancelled. /// </param> /// <returns> /// A <see cref="Response{BlockList}"/> describing requested /// block list. /// </returns> /// <remarks> /// A <see cref="RequestFailedException"/> will be thrown if /// a failure occurs. /// </remarks> public virtual async Task<Response<BlockList>> GetBlockListAsync( BlockListTypes blockListTypes = BlockListTypes.All, string snapshot = default, BlobRequestConditions conditions = default, CancellationToken cancellationToken = default) => await GetBlockListInternal( blockListTypes, snapshot, conditions, true, // async cancellationToken) .ConfigureAwait(false); /// <summary> /// The <see cref="GetBlockListInternal"/> operation operation retrieves /// the list of blocks that have been uploaded as part of a block blob. /// There are two block lists maintained for a blob. The Committed /// Block list has blocks that have been successfully committed to a /// given blob with <see cref="CommitBlockListAsync"/>. The /// Uncommitted Block list has blocks that have been uploaded for a /// blob using <see cref="StageBlockAsync"/>, but that have not yet /// been committed. These blocks are stored in Azure in association /// with a blob, but do not yet form part of the blob. /// </summary> /// <param name="blockListTypes"> /// Specifies whether to return the list of committed blocks, the /// list of uncommitted blocks, or both lists together. If you omit /// this parameter, Get Block List returns the list of committed blocks. /// </param> /// <param name="snapshot"> /// Optionally specifies the blob snapshot to retrieve the block list /// from. For more information on working with blob snapshots, see /// <see href="https://docs.microsoft.com/en-us/rest/api/storageservices/creating-a-snapshot-of-a-blob"/>. /// </param> /// <param name="conditions"> /// Optional <see cref="BlobRequestConditions"/> to add /// conditions on retrieving the block list. /// </param> /// <param name="async"> /// Whether to invoke the operation asynchronously. /// </param> /// <param name="cancellationToken"> /// Optional <see cref="CancellationToken"/> to propagate /// notifications that the operation should be cancelled. /// </param> /// <returns> /// A <see cref="Response{BlockList}"/> describing requested /// block list. /// </returns> /// <remarks> /// A <see cref="RequestFailedException"/> will be thrown if /// a failure occurs. /// </remarks> private async Task<Response<BlockList>> GetBlockListInternal( BlockListTypes blockListTypes, string snapshot, BlobRequestConditions conditions, bool async, CancellationToken cancellationToken) { using (Pipeline.BeginLoggingScope(nameof(BlockBlobClient))) { Pipeline.LogMethodEnter( nameof(BlockBlobClient), message: $"{nameof(Uri)}: {Uri}\n" + $"{nameof(blockListTypes)}: {blockListTypes}\n" + $"{nameof(snapshot)}: {snapshot}\n" + $"{nameof(conditions)}: {conditions}"); try { return (await BlobRestClient.BlockBlob.GetBlockListAsync( ClientDiagnostics, Pipeline, Uri, listType: blockListTypes.ToBlockListType(), version: Version.ToVersionString(), snapshot: snapshot, leaseId: conditions?.LeaseId, async: async, operationName: $"{nameof(BlockBlobClient)}.{nameof(GetBlockList)}", cancellationToken: cancellationToken) .ConfigureAwait(false)) .ToBlockList(); } catch (Exception ex) { Pipeline.LogException(ex); throw; } finally { Pipeline.LogMethodExit(nameof(BlockBlobClient)); } } } #endregion GetBlockList } /// <summary> /// Add easy to discover methods to <see cref="BlobContainerClient"/> for /// creating <see cref="BlockBlobClient"/> instances. /// </summary> public static partial class SpecializedBlobExtensions { /// <summary> /// Create a new <see cref="BlockBlobClient"/> object by /// concatenating <paramref name="blobName"/> to /// the end of the <paramref name="client"/>'s /// <see cref="BlobContainerClient.Uri"/>. The new /// <see cref="BlockBlobClient"/> /// uses the same request policy pipeline as the /// <see cref="BlobContainerClient"/>. /// </summary> /// <param name="client">The <see cref="BlobContainerClient"/>.</param> /// <param name="blobName">The name of the block blob.</param> /// <returns>A new <see cref="BlockBlobClient"/> instance.</returns> public static BlockBlobClient GetBlockBlobClient( this BlobContainerClient client, string blobName) => new BlockBlobClient( client.Uri.AppendToPath(blobName), client.Pipeline, client.Version, client.ClientDiagnostics, client.CustomerProvidedKey, client.EncryptionScope); } }
47.145338
141
0.576871
1e2ba2c953ce9bf9e25ef05dfe7f42041f4b434b
3,883
cs
C#
src/Tests/Kephas.Scheduling.Tests/Timers/TimerTriggerTest.cs
snakefoot/kephas
7c52de21c07426cb043605b09a272bb905a604f5
[ "MIT" ]
19
2018-12-24T05:12:26.000Z
2022-02-18T19:58:06.000Z
src/Tests/Kephas.Scheduling.Tests/Timers/TimerTriggerTest.cs
snakefoot/kephas
7c52de21c07426cb043605b09a272bb905a604f5
[ "MIT" ]
9
2018-11-24T14:50:00.000Z
2022-03-02T13:07:17.000Z
src/Tests/Kephas.Scheduling.Tests/Timers/TimerTriggerTest.cs
snakefoot/kephas
7c52de21c07426cb043605b09a272bb905a604f5
[ "MIT" ]
1
2020-11-16T18:18:42.000Z
2020-11-16T18:18:42.000Z
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="TimerTriggerTest.cs" company="Kephas Software SRL"> // Copyright (c) Kephas Software SRL. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // </copyright> // <summary> // Implements the timer trigger test class. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace Kephas.Scheduling.Tests.Timers { using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Kephas.Operations; using Kephas.Scheduling.Triggers; using NUnit.Framework; [TestFixture] public class TimerTriggerTest { [Test] public async Task Fire_respects_Count_StartToStart() { var trigger = new TimerTrigger { Interval = TimeSpan.FromMilliseconds(30), Count = 2, IntervalKind = TimerIntervalKind.StartToStart, }; var fired = 0; var disposed = 0; var fires = new List<long>(); trigger.Fire += (s, e) => { fired++; fires.Add(DateTimeOffset.Now.Ticks); Thread.Sleep(30); }; trigger.Disposed += (s, e) => disposed++; trigger.Initialize(); await Task.Delay(200); Assert.AreEqual(2, fired); Assert.AreEqual(1, disposed); this.AssertInterval(fires, 30); } [Test] public async Task Fire_respects_Count_EndToStart() { var trigger = new TimerTrigger { Interval = TimeSpan.FromMilliseconds(30), Count = 2, IntervalKind = TimerIntervalKind.EndToStart, }; var fired = 0; var disposed = 0; var fires = new List<long>(); trigger.Fire += (s, e) => { fired++; fires.Add(DateTimeOffset.Now.Ticks); var opResult = new OperationResult(Task.Delay(30)); if (e.CompleteCallback != null) { opResult.AsTask().ContinueWith(t => e.CompleteCallback.Invoke(opResult)); } }; trigger.Disposed += (s, e) => disposed++; trigger.Initialize(); await Task.Delay(200); Assert.AreEqual(2, fired); Assert.AreEqual(1, disposed); this.AssertInterval(fires, 60); } [Test] public void ToString_Infinite_3_seconds_interval() { var trigger = new TimerTrigger(144) { Interval = TimeSpan.FromSeconds(3), Count = null, IntervalKind = TimerIntervalKind.EndToStart, }; var triggerString = trigger.ToString(); Assert.AreEqual("TimerTrigger:144 @00:00:03/disabled", triggerString); } private void AssertInterval(IList<long> fires, long milliseconds) { var delta = 10L; // milliseconds var prevtick = fires[0]; for (int i = 1; i < fires.Count; i++) { var diffMillis = (fires[i] - prevtick) / TimeSpan.TicksPerMillisecond; var actualDelta = diffMillis - milliseconds; if (actualDelta > delta || actualDelta < -delta) { Assert.Warn($"Expected an interval of {milliseconds} but got {diffMillis}."); } prevtick = fires[i]; } } } }
32.090909
120
0.486995
1e2c79b82c4ea6fbf8e8803cd237d46eafdddbbc
2,033
cs
C#
hypervisulizer_rendering_server/Assets/Scripts/HyperScripts/Threading/Workers/GeneralThreadWorker.cs
rhedgeco/hyper_visualizer_clientserver
90b2e76c601c2224d362934c55e4c27a9855bb1c
[ "MIT" ]
null
null
null
hypervisulizer_rendering_server/Assets/Scripts/HyperScripts/Threading/Workers/GeneralThreadWorker.cs
rhedgeco/hyper_visualizer_clientserver
90b2e76c601c2224d362934c55e4c27a9855bb1c
[ "MIT" ]
null
null
null
hypervisulizer_rendering_server/Assets/Scripts/HyperScripts/Threading/Workers/GeneralThreadWorker.cs
rhedgeco/hyper_visualizer_clientserver
90b2e76c601c2224d362934c55e4c27a9855bb1c
[ "MIT" ]
null
null
null
using System; using System.Threading; using UnityEngine; namespace HyperScripts.Threading.Workers { public abstract class GeneralThreadWorker { public enum WorkerState { Idle, Running, WaitingClose, CloseError } public WorkerState State { get; private set; } = WorkerState.Idle; protected string StateMessage { get; set; } = ""; protected float StateProgress { get; set; } = 0f; internal abstract void ThreadCallbackStart(); protected abstract void ThreadCallbackUpdate(); protected abstract void ThreadCallbackError(); protected abstract void ThreadCallbackClosed(); protected abstract void ThreadBody(); internal void UpdateWorkerMainState() { switch (State) { case WorkerState.Idle: break; case WorkerState.Running: ThreadCallbackUpdate(); break; case WorkerState.WaitingClose: ThreadCallbackClosed(); HyperThreadDispatcher.DetachWorker(this); break; case WorkerState.CloseError: ThreadCallbackError(); HyperThreadDispatcher.DetachWorker(this); break; default: throw new ArgumentOutOfRangeException(); } } internal void ThreadRunnerWrapper() { try { State = WorkerState.Running; StateProgress = 0f; ThreadBody(); StateProgress = 1f; State = WorkerState.WaitingClose; } catch (Exception e) { Debug.LogError($"Thread {Thread.CurrentThread.Name} closed prematurely, ERROR: {e.Message}"); State = WorkerState.CloseError; } } } }
29.042857
109
0.519429
1e2d6f8ccdf5c9f166f167a523b7c232e29deaad
5,265
cs
C#
src/Configuration/Config.UserSecrets/test/ConfigurationExtensionTest.cs
xrcdev/extensions
f4066026ca06984b07e90e61a6390ac38152ba93
[ "MIT" ]
1
2020-03-15T08:06:12.000Z
2020-03-15T08:06:12.000Z
src/Configuration/Config.UserSecrets/test/ConfigurationExtensionTest.cs
xrcdev/extensions
f4066026ca06984b07e90e61a6390ac38152ba93
[ "MIT" ]
null
null
null
src/Configuration/Config.UserSecrets/test/ConfigurationExtensionTest.cs
xrcdev/extensions
f4066026ca06984b07e90e61a6390ac38152ba93
[ "MIT" ]
2
2020-03-05T17:19:24.000Z
2020-03-05T17:24:43.000Z
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using System.IO; using System.Reflection; using System.Text; using Microsoft.Extensions.Configuration.UserSecrets; using Microsoft.Extensions.Configuration.UserSecrets.Test; using Newtonsoft.Json.Linq; using Xunit; [assembly: UserSecretsId(ConfigurationExtensionTest.TestSecretsId)] namespace Microsoft.Extensions.Configuration.UserSecrets.Test { public class ConfigurationExtensionTest : IDisposable { public const string TestSecretsId = "d6076a6d3ab24c00b2511f10a56c68cc"; private List<string> _tmpDirectories = new List<string>(); private void SetSecret(string id, string key, string value) { var secretsFilePath = PathHelper.GetSecretsPathFromSecretsId(id); var dir = Path.GetDirectoryName(secretsFilePath); Directory.CreateDirectory(dir); _tmpDirectories.Add(dir); var secrets = new ConfigurationBuilder() .AddJsonFile(secretsFilePath, optional: true) .Build() .AsEnumerable() .Where(i => i.Value != null) .ToDictionary(i => i.Key, i => i.Value, StringComparer.OrdinalIgnoreCase); secrets[key] = value; var contents = new JObject(); if (secrets != null) { foreach (var secret in secrets.AsEnumerable()) { contents[secret.Key] = secret.Value; } } File.WriteAllText(secretsFilePath, contents.ToString(), Encoding.UTF8); } [Fact] public void AddUserSecrets_FindsAssemblyAttribute() { var randValue = Guid.NewGuid().ToString(); var configKey = "MyDummySetting"; SetSecret(TestSecretsId, configKey, randValue); var config = new ConfigurationBuilder() .AddUserSecrets(typeof(ConfigurationExtensionTest).GetTypeInfo().Assembly) .Build(); Assert.Equal(randValue, config[configKey]); } [Fact] public void AddUserSecrets_FindsAssemblyAttributeFromType() { var randValue = Guid.NewGuid().ToString(); var configKey = "MyDummySetting"; SetSecret(TestSecretsId, configKey, randValue); var config = new ConfigurationBuilder() .AddUserSecrets<ConfigurationExtensionTest>() .Build(); Assert.Equal(randValue, config[configKey]); } [Fact] public void AddUserSecrets_ThrowsIfAssemblyAttributeFromType() { var ex = Assert.Throws<InvalidOperationException>(() => new ConfigurationBuilder().AddUserSecrets<string>()); Assert.Equal(Resources.FormatError_Missing_UserSecretsIdAttribute(typeof(string).GetTypeInfo().Assembly.GetName().Name), ex.Message); ex = Assert.Throws<InvalidOperationException>(() => new ConfigurationBuilder().AddUserSecrets(typeof(JObject).Assembly)); Assert.Equal(Resources.FormatError_Missing_UserSecretsIdAttribute(typeof(JObject).GetTypeInfo().Assembly.GetName().Name), ex.Message); } [Fact] public void AddUserSecrets_DoesNotThrowsIfOptional() { var config = new ConfigurationBuilder() .AddUserSecrets<string>(optional: true) .AddUserSecrets(typeof(List<>).Assembly, optional: true) .Build(); Assert.Empty(config.AsEnumerable()); } [Fact] public void AddUserSecrets_With_SecretsId_Passed_Explicitly() { var userSecretsId = Guid.NewGuid().ToString(); SetSecret(userSecretsId, "Facebook:AppSecret", "value1"); var builder = new ConfigurationBuilder().AddUserSecrets(userSecretsId); var configuration = builder.Build(); Assert.Equal("value1", configuration["Facebook:AppSecret"]); } [Fact] public void AddUserSecrets_Does_Not_Fail_On_Non_Existing_File() { var userSecretsId = Guid.NewGuid().ToString(); var secretFilePath = PathHelper.GetSecretsPathFromSecretsId(userSecretsId); var builder = new ConfigurationBuilder().AddUserSecrets(userSecretsId); var configuration = builder.Build(); Assert.Null(configuration["Facebook:AppSecret"]); Assert.False(File.Exists(secretFilePath)); } public void Dispose() { foreach (var dir in _tmpDirectories) { try { if (Directory.Exists(dir)) { Directory.Delete(dir, true); } } catch { Console.WriteLine("Failed to delete " + dir); } } } } }
34.638158
133
0.596771
1e2e512298149863138da0cac4d0a0fa479cd29f
5,294
cs
C#
AdventureBot.Cli/Program.cs
bjorg/June2017-AdventureBot
3d3ab8e39cabc4827df77e8286e9de5d3723944c
[ "Apache-2.0" ]
null
null
null
AdventureBot.Cli/Program.cs
bjorg/June2017-AdventureBot
3d3ab8e39cabc4827df77e8286e9de5d3723944c
[ "Apache-2.0" ]
null
null
null
AdventureBot.Cli/Program.cs
bjorg/June2017-AdventureBot
3d3ab8e39cabc4827df77e8286e9de5d3723944c
[ "Apache-2.0" ]
null
null
null
/* * MindTouch λ# * Copyright (C) 2018 MindTouch, Inc. * www.mindtouch.com oss@mindtouch.com * * For community documentation and downloads visit mindtouch.com; * please review the licensing section. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.IO; using System.Linq; using McMaster.Extensions.CommandLineUtils; namespace AdventureBot.Cli { public class Program { //--- Class Methods --- public static void Main(string[] args) { var app = new CommandLineApplication { Name = "AdventureBot.Cli", FullName = "AdventureBot Command Line Interface", Description = "Choose-Your-Adventure CLI" }; app.HelpOption(); var filenameArg = app.Argument("<FILENAME>", "path to adventure file"); app.OnExecute(() => { if(filenameArg.Value == null) { Console.WriteLine(app.GetHelpText()); return; } if(!File.Exists(filenameArg.Value)) { app.ShowRootCommandFullNameAndVersion(); Console.WriteLine("ERROR: could not find file"); return; } // initialize the adventure from the adventure file Adventure adventure; try { adventure = Adventure.LoadFrom(filenameArg.Value); } catch(AdventureException e) { Console.WriteLine($"ERROR: {e.Message}"); return; } catch(Exception e) { Console.WriteLine($"ERROR: unable to load file"); Console.WriteLine(e); return; } // invoke adventure var state = new AdventureState("cli", Adventure.StartPlaceId); var engine = new AdventureEngine(adventure, state); AdventureLoop(engine); }); app.Execute(args); } private static void AdventureLoop(AdventureEngine engine) { // start the adventure loop ProcessResponse(engine.Do(AdventureCommandType.Restart)); try { while(true) { // prompt user input Console.Write("> "); var commandText = Console.ReadLine().Trim().ToLower(); if(!Enum.TryParse(commandText, true, out AdventureCommandType command)) { // TODO (2017-07-21, bjorg): need a way to invoke a 'command not understood' reaction // responses = new[] { new AdventureResponseNotUnderstood() }; continue; } // process user input ProcessResponse(engine.Do(command)); } } catch(Exception e) { Console.Error.WriteLine(e); } // local functions void ProcessResponse(AAdventureResponse response) { switch(response) { case AdventureResponseSay say: TypeLine(say.Text); break; case AdventureResponseDelay delay: System.Threading.Thread.Sleep(delay.Delay); break; case AdventureResponsePlay play: Console.WriteLine($"({play.Name})"); break; case AdventureResponseNotUnderstood _: TypeLine("Sorry, I don't know what that means."); break; case AdventureResponseBye _: TypeLine("Good bye."); System.Environment.Exit(0); break; case AdventureResponseFinished _: break; case AdventureResponseMultiple multiple: foreach(var nestedResponse in multiple.Responses) { ProcessResponse(nestedResponse); } break; default: throw new AdventureException($"Unknown response type: {response?.GetType().FullName}"); } } } private static void TypeLine(string text = "") { // write each character with a random delay to give the text output a typewriter feel var random = new Random(); foreach(var c in text) { System.Threading.Thread.Sleep((int)(random.NextDouble() * 10)); Console.Write(c); } Console.WriteLine(); } } }
37.546099
109
0.526634
1e2f6043a456a42f88011eb8beddaadfd2450950
16,846
cs
C#
src/core/Akka.Streams.Tests/Dsl/FlowPrefixAndTailSpec.cs
uQr/akka.net
bf528b88f7446a1845a56892ed4a93e6a0f31225
[ "Apache-2.0" ]
3
2021-05-03T04:50:00.000Z
2021-05-03T23:15:01.000Z
src/core/Akka.Streams.Tests/Dsl/FlowPrefixAndTailSpec.cs
uQr/akka.net
bf528b88f7446a1845a56892ed4a93e6a0f31225
[ "Apache-2.0" ]
null
null
null
src/core/Akka.Streams.Tests/Dsl/FlowPrefixAndTailSpec.cs
uQr/akka.net
bf528b88f7446a1845a56892ed4a93e6a0f31225
[ "Apache-2.0" ]
null
null
null
//----------------------------------------------------------------------- // <copyright file="FlowPrefixAndTailSpec.cs" company="Akka.NET Project"> // Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Akka.Streams.Dsl; using Akka.Streams.TestKit; using Akka.Streams.TestKit.Tests; using Akka.TestKit; using FluentAssertions; using Xunit; using Xunit.Abstractions; // ReSharper disable InvokeAsExtensionMethod namespace Akka.Streams.Tests.Dsl { public class FlowPrefixAndTailSpec : AkkaSpec { public ActorMaterializer Materializer { get; set; } public FlowPrefixAndTailSpec(ITestOutputHelper helper) : base(helper) { var settings = ActorMaterializerSettings.Create(Sys).WithInputBuffer(2,2); Materializer = ActorMaterializer.Create(Sys, settings); } private static readonly TestException TestException = new TestException("test"); private static Sink<Tuple<IImmutableList<int>, Source<int, NotUsed>>, Task<Tuple<IImmutableList<int>, Source<int, NotUsed>>>> NewHeadSink => Sink.First<Tuple<IImmutableList<int>, Source<int, NotUsed>>>(); [Fact] public void PrefixAndTail_must_work_on_empty_input() { this.AssertAllStagesStopped(() => { var futureSink = NewHeadSink; var fut = Source.Empty<int>().PrefixAndTail(10).RunWith(futureSink, Materializer); fut.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); var tailFlow = fut.Result.Item2; var tailSubscriber = this.CreateManualSubscriberProbe<int>(); tailFlow.To(Sink.FromSubscriber(tailSubscriber)).Run(Materializer); tailSubscriber.ExpectSubscriptionAndComplete(); }, Materializer); } [Fact] public void PrefixAndTail_must_work_on_short_inputs() { this.AssertAllStagesStopped(() => { var futureSink = NewHeadSink; var fut = Source.From(new [] {1,2,3}).PrefixAndTail(10).RunWith(futureSink, Materializer); fut.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); fut.Result.Item1.ShouldAllBeEquivalentTo(new[] {1, 2, 3}); var tailFlow = fut.Result.Item2; var tailSubscriber = this.CreateManualSubscriberProbe<int>(); tailFlow.To(Sink.FromSubscriber(tailSubscriber)).Run(Materializer); tailSubscriber.ExpectSubscriptionAndComplete(); }, Materializer); } [Fact] public void PrefixAndTail_must_work_on_longer_inputs() { this.AssertAllStagesStopped(() => { var futureSink = NewHeadSink; var fut = Source.From(Enumerable.Range(1, 10)).PrefixAndTail(5).RunWith(futureSink, Materializer); fut.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); var takes = fut.Result.Item1; var tail = fut.Result.Item2; takes.Should().Equal(Enumerable.Range(1, 5)); var futureSink2 = Sink.First<IEnumerable<int>>(); var fut2 = tail.Grouped(6).RunWith(futureSink2, Materializer); fut2.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); fut2.Result.ShouldAllBeEquivalentTo(Enumerable.Range(6, 5)); }, Materializer); } [Fact] public void PrefixAndTail_must_handle_zero_take_count() { this.AssertAllStagesStopped(() => { var futureSink = NewHeadSink; var fut = Source.From(Enumerable.Range(1, 10)).PrefixAndTail(0).RunWith(futureSink, Materializer); fut.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); fut.Result.Item1.Should().BeEmpty(); var tail = fut.Result.Item2; var futureSink2 = Sink.First<IEnumerable<int>>(); var fut2 = tail.Grouped(11).RunWith(futureSink2, Materializer); fut2.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); fut2.Result.ShouldAllBeEquivalentTo(Enumerable.Range(1, 10)); }, Materializer); } [Fact] public void PrefixAndTail_must_handle_negative_take_count() { this.AssertAllStagesStopped(() => { var futureSink = NewHeadSink; var fut = Source.From(Enumerable.Range(1, 10)).PrefixAndTail(-1).RunWith(futureSink, Materializer); fut.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); fut.Result.Item1.Should().BeEmpty(); var tail = fut.Result.Item2; var futureSink2 = Sink.First<IEnumerable<int>>(); var fut2 = tail.Grouped(11).RunWith(futureSink2, Materializer); fut2.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); fut2.Result.ShouldAllBeEquivalentTo(Enumerable.Range(1, 10)); }, Materializer); } [Fact] public void PrefixAndTail_must_work_if_size_of_tak_is_equal_to_stream_size() { this.AssertAllStagesStopped(() => { var futureSink = NewHeadSink; var fut = Source.From(Enumerable.Range(1,10)).PrefixAndTail(10).RunWith(futureSink, Materializer); fut.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); fut.Result.Item1.ShouldAllBeEquivalentTo(Enumerable.Range(1, 10)); var tail = fut.Result.Item2; var subscriber = this.CreateManualSubscriberProbe<int>(); tail.To(Sink.FromSubscriber(subscriber)).Run(Materializer); subscriber.ExpectSubscriptionAndComplete(); }, Materializer); } [Fact] public void PrefixAndTail_must_throw_if_tail_is_attempted_to_be_materialized_twice() { this.AssertAllStagesStopped(() => { var futureSink = NewHeadSink; var fut = Source.From(Enumerable.Range(1, 2)).PrefixAndTail(1).RunWith(futureSink, Materializer); fut.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); fut.Result.Item1.ShouldAllBeEquivalentTo(Enumerable.Range(1, 1)); var tail = fut.Result.Item2; var subscriber1 = this.CreateSubscriberProbe<int>(); tail.To(Sink.FromSubscriber(subscriber1)).Run(Materializer); var subscriber2 = this.CreateSubscriberProbe<int>(); tail.To(Sink.FromSubscriber(subscriber2)).Run(Materializer); subscriber2.ExpectSubscriptionAndError() .Message.Should() .Be("Substream Source cannot be materialized more than once"); subscriber1.RequestNext(2).ExpectComplete(); }, Materializer); } [Fact] public void PrefixAndTail_must_signal_error_if_substream_has_been_not_subscribed_in_time() { this.AssertAllStagesStopped(() => { var ms = 300; var settings = ActorMaterializerSettings.Create(Sys) .WithSubscriptionTimeoutSettings( new StreamSubscriptionTimeoutSettings( StreamSubscriptionTimeoutTerminationMode.CancelTermination, TimeSpan.FromMilliseconds(ms))); var tightTimeoutMaterializer = ActorMaterializer.Create(Sys, settings); var futureSink = NewHeadSink; var fut = Source.From(Enumerable.Range(1, 2)).PrefixAndTail(1).RunWith(futureSink, tightTimeoutMaterializer); fut.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); fut.Result.Item1.ShouldAllBeEquivalentTo(Enumerable.Range(1, 1)); var tail = fut.Result.Item2; var subscriber = this.CreateSubscriberProbe<int>(); Thread.Sleep(1000); tail.To(Sink.FromSubscriber(subscriber)).Run(tightTimeoutMaterializer); subscriber.ExpectSubscriptionAndError() .Message.Should() .Be("Substream Source has not been materialized in 00:00:00.3000000"); }, Materializer); } [Fact] public void PrefixAndTail_must_not_fail_the_stream_if_substream_has_not_been_subscribed_in_time_and_configured_subscription_timeout_is_noop() { this.AssertAllStagesStopped(() => { var settings = ActorMaterializerSettings.Create(Sys) .WithSubscriptionTimeoutSettings( new StreamSubscriptionTimeoutSettings( StreamSubscriptionTimeoutTerminationMode.NoopTermination, TimeSpan.FromMilliseconds(1))); var tightTimeoutMaterializer = ActorMaterializer.Create(Sys, settings); var futureSink = NewHeadSink; var fut = Source.From(Enumerable.Range(1, 2)).PrefixAndTail(1).RunWith(futureSink, tightTimeoutMaterializer); fut.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); fut.Result.Item1.ShouldAllBeEquivalentTo(Enumerable.Range(1, 1)); var subscriber = this.CreateSubscriberProbe<int>(); Thread.Sleep(200); fut.Result.Item2.To(Sink.FromSubscriber(subscriber)).Run(tightTimeoutMaterializer); subscriber.ExpectSubscription().Request(2); subscriber.ExpectNext(2).ExpectComplete(); }, Materializer); } [Fact] public void PrefixAndTail_must_shut_down_main_stage_if_substream_is_empty_even_when_not_subscribed() { this.AssertAllStagesStopped(() => { var futureSink = NewHeadSink; var fut = Source.Single(1).PrefixAndTail(1).RunWith(futureSink, Materializer); fut.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); fut.Result.Item1.Should().ContainSingle(i => i == 1); }, Materializer); } [Fact] public void PrefixAndTail_must_handle_OnError_when_no_substream_is_open() { this.AssertAllStagesStopped(() => { var publisher = this.CreateManualPublisherProbe<int>(); var subscriber = this.CreateManualSubscriberProbe<Tuple<IImmutableList<int>, Source<int, NotUsed>>>(); Source.FromPublisher(publisher) .PrefixAndTail(3) .To(Sink.FromSubscriber(subscriber)) .Run(Materializer); var upstream = publisher.ExpectSubscription(); var downstream = subscriber.ExpectSubscription(); downstream.Request(1); upstream.ExpectRequest(); upstream.SendNext(1); upstream.SendError(TestException); subscriber.ExpectError().Should().Be(TestException); }, Materializer); } [Fact] public void PrefixAndTail_must_handle_OnError_when_substream_is_open() { this.AssertAllStagesStopped(() => { var publisher = this.CreateManualPublisherProbe<int>(); var subscriber = this.CreateManualSubscriberProbe<Tuple<IImmutableList<int>, Source<int, NotUsed>>>(); Source.FromPublisher(publisher) .PrefixAndTail(1) .To(Sink.FromSubscriber(subscriber)) .Run(Materializer); var upstream = publisher.ExpectSubscription(); var downstream = subscriber.ExpectSubscription(); downstream.Request(1000); upstream.ExpectRequest(); upstream.SendNext(1); var t = subscriber.ExpectNext(); t.Item1.Should().ContainSingle(i => i == 1); var tail = t.Item2; subscriber.ExpectComplete(); var substreamSubscriber = this.CreateManualSubscriberProbe<int>(); tail.To(Sink.FromSubscriber(substreamSubscriber)).Run(Materializer); substreamSubscriber.ExpectSubscription(); upstream.SendError(TestException); substreamSubscriber.ExpectError().Should().Be(TestException); }, Materializer); } [Fact] public void PrefixAndTail_must_handle_master_stream_cancellation() { this.AssertAllStagesStopped(() => { var publisher = this.CreateManualPublisherProbe<int>(); var subscriber = this.CreateManualSubscriberProbe<Tuple<IImmutableList<int>, Source<int, NotUsed>>>(); Source.FromPublisher(publisher) .PrefixAndTail(3) .To(Sink.FromSubscriber(subscriber)) .Run(Materializer); var upstream = publisher.ExpectSubscription(); var downstream = subscriber.ExpectSubscription(); downstream.Request(1); upstream.ExpectRequest(); upstream.SendNext(1); downstream.Cancel(); upstream.ExpectCancellation(); }, Materializer); } [Fact] public void PrefixAndTail_must_handle_substream_cacellation() { this.AssertAllStagesStopped(() => { var publisher = this.CreateManualPublisherProbe<int>(); var subscriber = this.CreateManualSubscriberProbe<Tuple<IImmutableList<int>, Source<int, NotUsed>>>(); Source.FromPublisher(publisher) .PrefixAndTail(1) .To(Sink.FromSubscriber(subscriber)) .Run(Materializer); var upstream = publisher.ExpectSubscription(); var downstream = subscriber.ExpectSubscription(); downstream.Request(1000); upstream.ExpectRequest(); upstream.SendNext(1); var t = subscriber.ExpectNext(); t.Item1.Should().ContainSingle(i => i == 1); var tail = t.Item2; subscriber.ExpectComplete(); var substreamSubscriber = this.CreateManualSubscriberProbe<int>(); tail.To(Sink.FromSubscriber(substreamSubscriber)).Run(Materializer); substreamSubscriber.ExpectSubscription().Cancel(); upstream.ExpectCancellation(); }, Materializer); } [Fact] public void PrefixAndTail_must_pass_along_early_cancellation() { this.AssertAllStagesStopped(() => { var up = this.CreateManualPublisherProbe<int>(); var down = this.CreateManualSubscriberProbe<Tuple<IImmutableList<int>, Source<int, NotUsed>>>(); var flowSubscriber = Source.AsSubscriber<int>() .PrefixAndTail(1) .To(Sink.FromSubscriber(down)) .Run(Materializer); var downstream = down.ExpectSubscription(); downstream.Cancel(); up.Subscribe(flowSubscriber); var upSub = up.ExpectSubscription(); upSub.ExpectCancellation(); }, Materializer); } [Fact] public void PrefixAndTail_must_work_even_if_tail_subscriber_arrives_after_substream_completion() { var pub = this.CreateManualPublisherProbe<int>(); var sub = this.CreateManualSubscriberProbe<int>(); var f = Source.FromPublisher(pub) .PrefixAndTail(1) .RunWith(Sink.First<Tuple<IImmutableList<int>, Source<int, NotUsed>>>(), Materializer); var s = pub.ExpectSubscription(); s.SendNext(0); f.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); var tail = f.Result.Item2; var tailPub = tail.RunWith(Sink.AsPublisher<int>(false), Materializer); s.SendComplete(); tailPub.Subscribe(sub); sub.ExpectSubscriptionAndComplete(); } } }
42.326633
149
0.580078
1e2f7100a793cfbe21fa3473c987625532e99b3c
44,271
cshtml
C#
Cloud Enter/Epi.Cloud/Views/Survey/Index.Mobile.cshtml
82ndAirborneDiv/Epi-Info-Cloud-Contact-Tracing
580aee0def0bbd03067b63a5ac3784ebbf8abce4
[ "Apache-2.0" ]
1
2020-06-24T03:35:54.000Z
2020-06-24T03:35:54.000Z
Cloud Enter/Epi.Cloud/Views/Survey/Index.Mobile.cshtml
82ndAirborneDiv/Epi-Info-Cloud-Contact-Tracing
580aee0def0bbd03067b63a5ac3784ebbf8abce4
[ "Apache-2.0" ]
null
null
null
Cloud Enter/Epi.Cloud/Views/Survey/Index.Mobile.cshtml
82ndAirborneDiv/Epi-Info-Cloud-Contact-Tracing
580aee0def0bbd03067b63a5ac3784ebbf8abce4
[ "Apache-2.0" ]
4
2016-04-26T13:07:34.000Z
2020-11-13T14:21:01.000Z
@using Epi.Cloud.MVC.Constants @{ ViewBag.Title = "Epi Info™ Cloud Enter - Form"; } <style> .ui-datebox-controls span.ui-btn-inner {padding-bottom: 28px !important; } .ui-datebox-controls a span.ui-btn-inner {padding-bottom: 10px !important; } .ui-datebox-controls div {width:70px !important; margin:0 0.2em !important; </style> <script type="text/javascript"> var redirectTimeout = @FormsAuthentication.Timeout.TotalMilliseconds var redirectTimeoutHandle = setTimeout(function() { window.location.href = '@FormsAuthentication.LoginUrl'; }, redirectTimeout); </script> <script type="text/javascript"> //Check Code Logic start @Html.Raw(Model.Form.FormJavaScript) //Check code logic end </script> <script type="text/javascript"> // $(function () { // $("#savediv button[title]").tooltip(); // }); </script> <script type="text/javascript"> /*Clicking the continue button*/ function Submit(){ $('#myform').submit(); } function AddNewChild(ViewId) { $("#myform")[0].Get_Child_action.value = 'true'; $("#myform")[0].action = window.location.href; $('#myform').submit(); } function DoNotSave() { $("#myform")[0].DontSave.value = 'true'; $("#myform")[0].action = window.location.href; $('#myform').submit(); } function Continue() { //debugger; var presentUrl; var pageNumber; var actionUrlC; presentUrl = '@Url.Action("Index","Survey")'; pageNumber = '@Model.Form.CurrentPage'; actionUrlC = processUrl(presentUrl, 'ContinueUrl', pageNumber); $("#myform")[0].action = actionUrlC; $("#myform").submit(); } /*Clicking the previous button*/ function Previous() { //debugger; var presentUrl; var pageNumber; var actionUrlP; presentUrl = '@Url.Action("Index","Survey")'; pageNumber = '@Model.Form.CurrentPage'; actionUrlP = processUrl(presentUrl, 'PreviousUrl', pageNumber); $("#myform")[0].action = actionUrlP; $("#myform").submit(); } function OpenRelateNavigationDialog() { //$("#RelateNavigation").dialog("open"); } function CloseRelateNavigationDialog() { // $("#RelateNavigation").dialog("close"); } function NavigateToChild(ViewId) { $('#RelateButtonWasClicked_Temp').val(ViewId) $('#RelateButtonWasClicked').val(ViewId); var temp = HasResponse(ViewId); if (temp) { ReadResponse(ViewId); } else { // Save();//Save Current page. AddNewChild(ViewId); // AddChild(ViewId); } } function HasResponse(ViewId) { var signoutUrl = '@Url.Action("HasResponse", "Survey")' + '?SurveyId=' + '@Model.Form.SurveyInfo.SurveyId' + '&ViewId=' + ViewId + '&ResponseId=' + '@Model.Form.ResponseId'; var HasResponse; $.ajax({ url: signoutUrl, type: 'POST', contentType: 'application/json; charset=utf-8', //data: "{}", dataType: "json", //cache: false, async: false, success: successFunc, error: errorFunc }); function successFunc(data) { HasResponse = data } function errorFunc(data) { alert('failed'); } return HasResponse; } function ReadResponse(ViewId) { // var signoutUrl = '@Url.Action("ReadResponseInfo", "Survey")' + '?SurveyId=' + '@Model.Form.SurveyInfo.SurveyId' + '&ViewId=' + ViewId + '&ResponseId=' + '@Model.Form.ResponseId' + '&FormValuesHasChanged=' + $('#FormHasChanged').val() + '&CurrentPage=' + '@Model.Form.CurrentPage'; // // $.ajax({ // url: signoutUrl, // type: 'GET', // contentType: 'application/json; charset=utf-8', // //data: JSON.stringify(model), // async: false, // success: successFunc, // Error: errorFunc // }); // function successFunc(data) { // // $('#RelateNavigation').html(data); // //OpenRelateNavigationDialog(); // } // function errorFunc() { // alert('error'); // } $("#myform")[0].Read_Response_action.value = 'true'; $("#myform")[0].action = window.location.href; $('#myform').submit(); } function AddChild(ViewId) { $('#FormHasChanged').val('True'); var signoutUrl = '@Url.Action("AddChild", "Survey")' + '?SurveyId=' + '@Model.Form.SurveyInfo.SurveyId' + '&ViewId=' + ViewId + '&ResponseId=' + '@Model.Form.ResponseId' + '&FormValuesHasChanged=' + $('#FormHasChanged').val() + '&CurrentPage=' + '@Model.Form.CurrentPage'; $.ajax({ url: signoutUrl, type: 'POST', contentType: 'application/json; charset=utf-8', // data: $('#myform').serialize(), //data:JSON.stringify(model), dataType: "json", //cache: false, async: false, success: successFunc, error: errorFunc }); function successFunc(data) { //$(this).dialog("close"); var tem = 'responseId =' + data; var homePageUrl = '@Url.Action("Index", "Survey",new { responseId= "RId", PageNumber = "1" })'; homePageUrl = homePageUrl.replace("RId", data.toString()); window.location.href = homePageUrl; } function errorFunc(data) { alert('failed'); } } function GoHome() { $('#myform').validationEngine('detach'); $("#myform")[0].Go_Home_action.value = 'true'; $("#myform")[0].action = window.location.href; $('#myform').submit(); } function GoOneLevelUp() { $('#myform').validationEngine('detach'); $("#myform")[0].Go_One_Level_Up_action.value = 'true'; $("#myform")[0].action = window.location.href; $('#myform').submit(); } $(document).ready(function () { // $("#mvcdynamicfield_relatetochild1").bind("click", function (event, ui) { // // alert(); // }); $("#dialog").dialog({ autoOpen: false, show: "blind", hide: "blind", resizable: false, height: 370, modal: true }); $("#VideoDialog").dialog({ autoOpen: false, show: "blind", hide: "blind", resizable: false, height: 410, width: 500, modal: true }); $("#RelateNavigation").dialog({ autoOpen: false, show: "blind", hide: "blind", resizable: false, height: 410, width: 'auto', modal: true }); var responseUrl = GetRedirectionUrl(); $('#url').val(responseUrl); var passcode = '@Model.Form.PassCode'; $('#spPassCode').text(passcode); // if ('@Model.Form.IsSaved' == 'True') { // if ('@Model.Form.StatusId' == '1') { //if clicking the save button for the first time // $('#successContent').show(); // $('#successContent').append('<div class="success"><div class="image"><img src="@Url.Content("~/Content/images/button_check.png")" style="vertical-align:middle; padding-right: 5px; width:24px;" alt=""/></div><div class="message">Your survey has been saved.<p style="text-align:left; margin-top:4px; margin-bottom:2px;"><button id="copy" type="button" name="copy" class="copylink">Get Survey Link & Pass Code</button></p></div><div style="clear:both;"></div></div>') // // //call your jquery modal popup method // $("#dialog").dialog("open"); // // } // else { // // $('#successContent').show(); //in subsequest click we just show that the survey has been saved not the modal popup // $('#successContent').append('<div class="success"><div class="image"><img src="@Url.Content("~/Content/images/button_check.png")" style="vertical-align:middle; padding-right: 5px; width:24px;" alt=""/></div><div class="message">Your survey has been saved.<p style="text-align:left; margin-top:4px; margin-bottom:2px;"><button id="copy" type="button" name="copy" class="copylink">Get Survey Link & Pass Code</button></p></div><div style="clear:both;"></div></div>') // } // return true; // } }); $(document).ready(function () { $('#formdisplay').live("click", function () { CCE_HasFormValuesChanged(); }) jQuery('a').click(function (event) { CCE_HasFormValuesChanged(); }); $('input').change(function () { CCE_HasFormValuesChanged(); }); $('textarea').change(function () { CCE_HasFormValuesChanged(); }); // $('.ui-btn-hidden').removeClass("ui-btn-hidden"); $("#send").click(function () { var emailAddress = $("#email").val(); var confirmemail = $("#confirmemail").val(); var redirectUrl = GetRedirectionUrl(); //var surveyName = $("#_surveyName").val(); var surveyName = '@Model.Form.SurveyInfo.SurveyName'; surveyName = "H"; //ReplaceString(surveyName); var passCode = $('#spPassCode').text(); //url to post for email to be sent var postUrl = '@Url.Action("Notify","Post")'; var EmailSubject = $('#Subject').val(); EmailSubject = "H"; //ReplaceString(EmailSubject); if (ValidateEmail(emailAddress) && ValidateEmail(confirmemail)) { if ($.trim(emailAddress) == $.trim(confirmemail)) { //Call notify function to send notification NotifyByEmail(emailAddress, redirectUrl, surveyName, postUrl, passCode, EmailSubject); //close the modal popup after processing $("#dialog").dialog("close"); } else { alert("The email address did not match."); } } else { // $('#email').after('<span class="error">Enter a valid email address.</span>'); alert('Enter a valid email address!'); } }); /*Open the modal popup on link click*/ $('#copy').click(function () { $("#dialog").dialog("open"); $('#url').val(GetRedirectionUrl()); return false; }); ///////Update Controls State Start/////// CCE_Set_Update_HighlightedControls_State(document.getElementById("HighlightedFieldsList").value); CCE_Set_Update_DisabledControls_State(document.getElementById("DisabledFieldsList").value); ///////Update Controls State end/////// ///////////Adding Red Border for none valid controls start /////////////////// $('.SelectNotValid').find('.ui-btn').css("border-color", "red"); $('.TimePickerNotValid').find('.ui-input-datebox').css("border-color", "red"); $('.DatePickerNotValid').find('.ui-input-datebox').css("border-color", "red"); ///////////Adding Red Border for none valid controls end /////////////////// /////////////////////Save Start/////////////////////// var IsSaved = document.getElementById("HiddenIsSaved").value; var StatusId = document.getElementById("HiddenStatusId").value; var Subject = "Link for Survey: " + '@Model.Form.SurveyInfo.SurveyName'; var passcode1 = '@Model.Form.PassCode'; //if (StatusId == 'false' && '@Model.Form.StatusId' != '2' ) { //if clicking the save button for the first time if ('@Model.Form.IsSaved' == 'True') { if ('@Model.Form.StatusId' == '1') { //if clicking the save button for the first time $('#Savebutton1').simpledialog({ 'mode': 'blank', 'prompt': false, 'forceInput': false, 'useModal': true, 'buttons': { 'OK': { click: function () { $('#dialogoutput').text('OK'); } } }, 'fullHTML': "<div class='success'><div class='image'><img src='../../Content/images/button_check.png' style='vertical-align: middle; padding-right:5px; width:24px;'alt=''/></div><div class='message' style='width:85% !important;'>Your Survey has been saved.</div><div style='clear:both;'></div></div> <p><span style='font-weight:bold;'>Survey Link:</span><br /><textarea " + "value=" + GetRedirectionUrl().toString() + " id='url' cols='65' style=' height:45px; white-space:pre; background:#d6e7f5; border:1px solid #aecfea; padding:4px; margin-top:4px;' readonly='readonly'>" + GetRedirectionUrl().toString() + "</textarea></p><p style='font-weight:bold;'>Pass Code: <span id='spPassCode' style='font-size:12pt; background:#d6e7f5; border:1px solid #aecfea; padding:4px 10px;'>" + passcode1 + "</span></p> <hr/> <p>Enter your email address to have the Survey Link and Pass Code emailed to you.</p><p><span style='font-weight:bold;'>Email Subject:</span><br /><textarea id='Subject' cols='65' style=' height:30px; white-space:pre; border:1px solid #aecfea; padding:4px; margin-top:4px;'>" + Subject + "</textarea></p><p><label for='email' style='font-weight:bold;'>Email:</label> <input id='email' type='email' /></p> <p><label for='confirmemail'style='font-weight:bold;'>Confirm Email:</label> <input id='confirmemail' type='email' /><div align='center'> <a onclick ='SendEmail();' class='login' style='width:50px; padding:8px 15px !important;'>Send Email</a></div></p> <br /> <p style='font-size: 8pt; padding: 5px; background: #ffffa8; margin-top:-5px;'><strong>Note:</strong> Your email address will not be saved and will only be used to send you the survey link.</p>" }) } } // if ('@Model.Form.StatusId' == '2' && document.getElementById("HiddensuccessContent").value == "false") // { // document.getElementById("HiddensuccessContent").value = "true"; // $('#successContent').show(); // $('#successContent').append('<div class="success"><div class="image"><img src="@Url.Content("~/Content/images/button_check.png")" style="vertical-align:middle; padding-right: 5px; width:24px" alt=""/></div><div class="message"> Your survey has been saved.<p style="text-align:left; margin-top:4px; margin-bottom:2px;"><button id="Savebutton2" type="button" class="copylink">Get Survey Link & Pass Code</button></p></div><div style="clear:both;"></div></div>') // } ////////////////////Save End///////////////////////// }); function SendEmail(){ var emailAddress = $("#email").val(); var confirmemail = $("#confirmemail").val(); var redirectUrl = GetRedirectionUrl(); //var surveyName = $("#_surveyName").val(); var surveyName = '@Model.Form.SurveyInfo.SurveyName'; surveyName = ReplaceString(surveyName).toString(); var passCode = $('#spPassCode').text(); var EmailSubject = $('#Subject').val(); EmailSubject = ReplaceString(EmailSubject).toString(); //url to post for email to be sent var postUrl = '@Url.Action("Notify","Post")'; if (ValidateEmail(emailAddress) && ValidateEmail(confirmemail)) { if ($.trim(emailAddress) == $.trim(confirmemail)) { //Call notify function to send notification NotifyByEmail(emailAddress, redirectUrl, surveyName, postUrl, passCode,EmailSubject); //close the modal popup after processing $("#dialog").dialog("close"); } else { alert("The email address did not match."); } } else { // $('#email').after('<span class="error">Enter a valid email address.</span>'); alert('Enter a valid email address!'); } } function updateXml(pName, pValue) { var UpdateUrl = '@Url.Action("UpdateResponseXml","Survey")'; var NList = ""; for (var i = 0; i < NameList.length; i++) { if (NList == ""){ NList = NameList[i] }else{ NList = NList + "," +NameList[i]; } } UpdateResponse(UpdateUrl, NList, pValue, '@Model.Form.ResponseId'); } /*Clicking the save button to save the survey*/ function Save() { var DisabledFieldsList = $('#DisabledFieldsList').val(); if (DisabledFieldsList.length > 0) { CCE_ProcessEnableAllControls(DisabledFieldsList) ; } //SaveSurvey(); //debugger; //set the is_save_action hidden variable value to true to indicate that save button has been clicked $("#myform")[0].is_save_action.value = 'true'; //set the action path of the current form so when it is submitted by clicking the save button it posts to the path $("#myform")[0].action = window.location.href; //detach the validation engine as we don't want to validate data on save button click $('#myform').validationEngine('detach'); //posting the form $('#myform').submit(); // return false; } function SaveSurvey() { var StatusId = document.getElementById("HiddenStatusId").value; if ((StatusId == 'false' || '@Model.Form.StatusId' == '1') && '@Model.Form.StatusId' != '2') { var UpdateUrl = '@Url.Action("SaveSurvey", "Survey")'; SaveAndUpdate(UpdateUrl, "PageNumber", '@Model.Form.CurrentPage', '@Model.Form.ResponseId'); } } // save button dialog $(document).delegate('#Savebutton1', 'click', function() { // var IsSaved = document.getElementById("HiddenIsSaved").value; // var StatusId = document.getElementById("HiddenStatusId").value; // // var Subject ="Link for Survey: " + '@Model.Form.SurveyInfo.SurveyName' ; // var passcode1 = '@Model.Form.PassCode'; // if (StatusId == 'false' && '@Model.Form.StatusId' != '2' ) { //if clicking the save button for the first time // // $('#successContent').show(); // $('#successContent').append('<div class="success"><div class="image"><img src="@Url.Content("~/Content/images/button_check.png")" style="vertical-align:middle; padding-right: 5px; width:24px;" alt=""/></div><div class="message">Your survey has been saved.<p style="text-align:left; margin-top:4px; margin-bottom:2px;"><button id="Savebutton2" type="button" name="copy" class="copylink">Get Survey Link & Pass Code</button></p></div><div style="clear:both;"></div></div>') // $(this).simpledialog({ // 'mode' : 'blank', // 'prompt': false, // 'forceInput': false, // 'useModal':true, // 'buttons' : { // 'OK': { // click: function () { // $('#dialogoutput').text('OK'); // } // } // // }, // 'fullHTML': "<div class='success'><div class='image'><img src='../../Content/images/button_check.png' style='vertical-align: middle; padding-right:5px; width:24px;'alt=''/></div><div class='message' style='width:85% !important;'>Your Survey has been saved.</div><div style='clear:both;'></div></div> <p><span style='font-weight:bold;'>Survey Link:</span><br /><textarea " + "value=" + GetRedirectionUrl().toString() + " id='url' cols='65' style=' height:45px; white-space:pre; background:#d6e7f5; border:1px solid #aecfea; padding:4px; margin-top:4px;' readonly='readonly'>" + GetRedirectionUrl().toString() + "</textarea></p><p style='font-weight:bold;'>Pass Code: <span id='spPassCode' style='font-size:12pt; background:#d6e7f5; border:1px solid #aecfea; padding:4px 10px;'>" + passcode1 + "</span></p> <hr/> <p>Enter your email address to have the Survey Link and Pass Code emailed to you.</p><p><span style='font-weight:bold;'>Email Subject:</span><br /><textarea id='Subject' cols='65' style=' height:30px; white-space:pre; border:1px solid #aecfea; padding:4px; margin-top:4px;'>" + Subject +"</textarea></p><p><label for='email' style='font-weight:bold;'>Email:</label> <input id='email' type='email' /></p> <p><label for='confirmemail'style='font-weight:bold;'>Confirm Email:</label> <input id='confirmemail' type='email' /><div align='center'> <a onclick ='SendEmail();' class='login' style='width:50px; padding:8px 15px !important;'>Send Email</a></div></p> <br /> <p style='font-size: 8pt; padding: 5px; background: #ffffa8; margin-top:-5px;'><strong>Note:</strong> Your email address will not be saved and will only be used to send you the survey link.</p>" // }) // } // if ('@Model.Form.StatusId' == '2' && document.getElementById("HiddensuccessContent").value == "false"){ // document.getElementById("HiddensuccessContent").value = "true"; // $('#successContent').show(); // $('#successContent').append('<div class="success"><div class="image"><img src="@Url.Content("~/Content/images/button_check.png")" style="vertical-align:middle; padding-right: 5px; width:24px" alt=""/></div><div class="message"> Your survey has been saved.<p style="text-align:left; margin-top:4px; margin-bottom:2px;"><button id="Savebutton2" type="button" class="copylink">Get Survey Link & Pass Code</button></p></div><div style="clear:both;"></div></div>') // } }); $(document).delegate('#Savebutton2', 'click', function() { var passcode1 = '@Model.Form.PassCode'; var Subject = "Link for Survey: " + '@Model.Form.SurveyInfo.SurveyName'; $(this).simpledialog({ 'mode' : 'blank', 'prompt': false, 'forceInput': false, 'useModal':true, 'buttons' : { 'OK': { click: function () { $('#dialogoutput').text('OK'); } } }, 'fullHTML': "<div class='success'><div class='image'><img src='../../Content/images/button_check.png' style='vertical-align: middle; padding-right:5px; width:24px;'alt=''/></div><div class='message' style='width:85% !important;'>Your Survey has been saved.</div><div style='clear:both;'></div></div> <p><span style='font-weight:bold;'>Survey Link:</span><br /><textarea " + "value=" + GetRedirectionUrl().toString() + " id='url' cols='65' style=' height:45px; white-space:pre; background:#d6e7f5; border:1px solid #aecfea; padding:4px; margin-top:4px;' readonly='readonly'>" + GetRedirectionUrl().toString() + "</textarea></p><p style='font-weight:bold;'>Pass Code: <span id='spPassCode' style='font-size:12pt; background:#d6e7f5; border:1px solid #aecfea; padding:4px 10px;'>" + passcode1 + "</span></p> <hr/> <p>Enter your email address to have the Survey Link and Pass Code emailed to you.</p><p><span style='font-weight:bold;'>Email Subject:</span><br /><textarea id='Subject' cols='65' style=' height:30px; white-space:pre; border:1px solid #aecfea; padding:4px; margin-top:4px;'>"+ Subject +"</textarea></p><p><label for='email' style='font-weight:bold;'>Email:</label> <input id='email' type='email' /></p> <p><label for='confirmemail' style='font-weight:bold;'>Confirm Email:</label> <input id='confirmemail' type='email' /><div align='center'> <a onclick ='SendEmail();' class='login' style='width:50px; padding:8px 15px !important;'>Send Email</a></div></p> <br /> <p style='font-size: 8pt; padding: 5px; background: #ffffa8; margin-top:-5px;'><strong>Note:</strong> Your email address will not be saved and will only be used to send you the survey link.</p>" }) }); $(document).delegate('#close', 'click', function () { CCE_HasFormValuesChanged(); if ($('#FormHasChanged').val() == 'True') { $(this).simpledialog2({ 'mode': 'blank', // 'prompt': false, 'forceInput': false, 'headerText': 'Exit Record', 'headerClose': true, 'themeDialog': "b", //'useModal': true, //'buttons': { // 'OK': { // click: function () { // $('#dialogoutput').text('OK'); // alert(test); // } // } //}, 'blankContent': "<div id=\"exitdialog\" title=\"Exit Record\" ><p style=\"font-size:1.20em; font-weight:400;\">Do you want to save the record before exiting?</p><p style=\"font-size:1.20em; font-weight:300;\"></p><p><div align='right' id='exitbtns'> <a onclick=\"SaveForm();\" class='login' style='width:50px; padding:4px 5px !important; border: 1px solid #1f3b53 !important; background: #5c53ac !important; color:#fff !important; text-shadow: none !important;'>Save</a> <a class='login' onclick ='ExitSurvey();' style='width:50px; padding:4px 5px !important; border: 1px solid #1f3b53 !important; background: #5c53ac !important; color:#fff !important; text-shadow: none !important;' id='simpleclose' >Don't Save</a> <a class='login' style='width:50px; padding:4px 5px !important; border: 1px solid #1f3b53 !important; background: #5c53ac !important; color:#fff !important; text-shadow: none !important;'rel='close' id='simpleclose' >Cancel</a></div></p>" }) } else { // var homePageUrl = '@Url.Action("Index", "Home")' + '/' + '@Model.Form.SurveyInfo.SurveyId'; // window.location.href = homePageUrl; ExitSurvey(); } }); $(document).delegate('#close1', 'click', function () { CCE_HasFormValuesChanged(); if ($('#FormHasChanged').val() == 'True') { $(this).simpledialog2({ 'mode': 'blank', // 'prompt': false, 'forceInput': false, 'headerText': 'Exit Record', 'headerClose': true, 'themeDialog': "b", //'useModal': true, //'buttons': { // 'OK': { // click: function () { // $('#dialogoutput').text('OK'); // alert(test); // } // } //}, 'blankContent': "<div id=\"exitdialog\" title=\"Exit Record\" ><p style=\"font-size:1.20em; font-weight:400;\">Do you want to update the record before exiting?</p><p style=\"font-size:1.20em; font-weight:300;\"></p><p><div align='right' id='exitbtns'> <a onclick=\"SaveForm();\" class='login' style='width:50px; padding:4px 5px !important; border: 1px solid #1f3b53 !important; background: #5c53ac !important; color:#fff !important; text-shadow: none !important;'>Save</a> <a class='login' onclick ='ExitSurvey();' style='width:50px; padding:4px 5px !important; border: 1px solid #1f3b53 !important; background: #5c53ac !important; color:#fff !important; text-shadow: none !important;'rel='close' id='simpleclose' >Don't Save</a> <a class='login' style='width:50px; padding:4px 5px !important; border: 1px solid #1f3b53 !important; background: #5c53ac !important; color:#fff !important; text-shadow: none !important;'rel='close' id='simpleclose' >Cancel</a></div></p>" }) } else { // var homePageUrl = '@Url.Action("Index", "Home")' + '/' + '@Model.Form.SurveyInfo.SurveyId'; // window.location.href = homePageUrl; ExitSurvey(); } }); function CloseDialog() { $(this).dialog("close"); } /*Exit the survey */ function ExitSurvey() { //Jira EC-543 var signoutUrl = '@Url.Action("Delete", "Survey")'; //var homePageUrl = '@Url.Action("Index", "FormResponse")' + '/' + '@Model.Form.SurveyInfo.SurveyId'; //var homePageUrl = 'FormResponse/Index' + '/' + '@Model.Form.SurveyInfo.SurveyId'; //alert(homePageUrl); $.ajax({ url: signoutUrl, type: 'POST', contentType: 'application/json; charset=utf-8', dataType: "json", async: false, success: successFunc, error: errorFunc }); function successFunc(data) { var homePageUrl = '@Url.Action("Index", "FormResponse")' + '/' + data; window.location.href = homePageUrl; } //DoNotSave(); } function errorFunc(data) { alert('failed'); } $(function() { $('#myform').submit( function() { var DisabledFieldsList = $('#DisabledFieldsList').val(); //alert(" " + DisabledFieldsList); if (DisabledFieldsList.length > 0) { CCE_ProcessEnableAllControls(DisabledFieldsList) ; } return true; }); }); function ReplaceString(string){ return string.replace( /&amp;/g,"&").replace(/&gt;/g ,">").replace( /&lt;/g,"<").replace(/&quot;/g, "\"").replace(/&#39;/g, "'"); } /*Save the survey */ function SaveForm() { var DisabledFieldsList = $('#DisabledFieldsList').val(); if (DisabledFieldsList.length > 0) { CCE_ProcessEnableAllControls(DisabledFieldsList); } //SaveSurvey(); //debugger; //set the is_save_action hidden variable value to true to indicate that save button has been clicked $("#myform")[0].is_save_action.value = 'false'; $("#myform")[0].is_save_action_Mobile.value = 'true'; //set the action path of the current form so when it is submitted by clicking the save button it posts to the path $("#myform")[0].action = window.location.href; //detach the validation engine as we don't want to validate data on save button click $('#myform').validationEngine('detach'); //posting the form $('#myform').submit(); // return false; } </script> <div id="pageHeader"> @*<div id="pageTitle"><h2>@Model.Form.SurveyInfo.SurveyName</h2></div> <div id="userwelcome">Welcome <strong>@Session[UserSession.Key.UserFirstName]&nbsp; @Session[UserSession.Key.UserLastName]</strong>&nbsp; | &nbsp; <a href="#">Log Out</a>*@ @*Html.ActionLink("Log Out", "LogOut", "Survey", null, null) </div> <div style="clear:both;"></div>*@ </div> <div id="content" class="recordcontentdiv" style="margin:20px auto 0;"> @using (Html.BeginForm(null, null, FormMethod.Post, new { id = "myform", @class = "" })) { <div id="formdisplay" class="@Model.Form.IsDraftModeStyleClass.ToString()" style=""> @if (@Model.Form.SurveyInfo.SurveyId != @Session[UserSession.Key.RootFormId].ToString()) { <div id="relatenav" style="padding-bottom:10px;"> @* <button class="" id ="Home" type="button" onclick="GoHome()" name="Home" > Main Record</button> <button class="" id ="LevelUp" type="button" onclick="GoOneLevelUp()" name="Home" > Back</button>*@ <div style="float:left;"><a class="exitsurvey" onclick="GoHome();" style="background: #00B050;" title="Main Record"><img src="../../Content/images/root.png" style="width:16px; vertical-align: text-top;"/> Main Record</a> </div> <div style="float:right;"><a class="exitsurvey" onclick="GoOneLevelUp();" style="background: #00B050;" title="Back"><img src="../../Content/images/uplevel.png" style="width:16px; vertical-align: text-bottom;"/> Back</a> </div> <div style="clear:both;"></div> </div> } <div id="infobox"> <div id="pages" class="pages"> @if (Model.Form.NumberOfPages > 0) { int num = 0; for (int i = 1; Model.Form.NumberOfPages > i - 1; i++) { num = i; if (i == 1 && Model.Form.CurrentPage > 1) { <a onclick="Submit();" style="background-image: url('@Url.Content("~/Content/images/prev.png")'); background-repeat:no-repeat; background-position:center;" href="@Url.RouteUrl(null, new { controller = "Survey", action = "Index", responseid = Model.Form.ResponseId, PageNumber = Model.Form.CurrentPage - 1 })" class="nextprev" title="Previous Page"> &nbsp;&nbsp;&nbsp; </a> @* <a href="@Url.RouteUrl(null, new { controller = "Survey", action = "Index", responseid = Model.ResponseId, PageNumber = Model.CurrentPage - 1 })" onclick="Submit();" data-role="button" data-inline="true" data-theme="e" data-mini="true" data-icon="arrow-l" data-iconpos="notext" > Previous</a>*@ } if (Model.Form.CurrentPage == i) { <span class="current">@num of @Model.Form.NumberOfPages</span> } } if (Model.Form.CurrentPage != Model.Form.NumberOfPages) { <a id="anchorNext" onclick="Submit();" style="background-image: url('@Url.Content("~/Content/images/next.png")'); background-repeat:no-repeat; background-position:center;" href="@Url.RouteUrl(null, new { controller = "Survey", action = "Index", responseid = Model.Form.ResponseId, PageNumber = Model.Form.CurrentPage + 1 })" class="nextprev" title="Go to Next Page"> &nbsp;&nbsp;&nbsp; </a> @* <a id="anchorNext" onclick="Submit();" href="@Url.RouteUrl(null, new { controller = "Survey", action = "Index", responseid = Model.Form.ResponseId, PageNumber = Model.CurrentPage + 1 })" data-role="button" data-inline="true" data-theme="e" data-mini="true" data-icon="arrow-r" data-iconpos="notext"> Next </a>*@ } } </div> <div id="exit" align="right" style="vertical-align:middle;"> @*<button class="MobileExitSurvey" type="submit" id="close">Exit Survey</button>*@ <button data-role="button" data-theme="submit2" data-inline="true" type="submit" name="Submitbutton" value="Submit" > Save & Close </button> @* <a id="close" class="exitsurvey">Delete @*<img src="../../Content/images/close.png" alt="Save & Close" style="border:none; width: 15px; vertical-align:middle; padding-bottom:3px;" /> </a>*@ @* <a id="close" class="exitsurvey" onclick="Submit();" href="@Url.RouteUrl(null, new { controller = "Home", action = "Index", SurveyId = Model.SurveyInfo.SurveyId })">Exit</a>*@ @if (ViewBag.Edit == "Edit") { <a id="close1" class="exitsurvey">Exit</a> } else { <a id="close" class="exitsurvey">Exit</a> } </div> <div style="clear: both;"> </div> </div> @*<div id="content">*@ <div id="successContent"> </div> @if (!string.IsNullOrEmpty(Model.Form.GetErrorSummary())) { <div class="errormsg"> <div class="image"> <img src="@Url.Content("~/Content/images/error.png")" style="vertical-align: middle; padding-right: 5px; width:24px;" alt=""/> </div> <div class="message"> <span style="font-weight: bold; font-size: 10pt;">Please correct the following errors before continuing:</span> <br /> @Html.Raw(Model.Form.GetErrorSummary()) </div> <div style="clear: both;"> </div> </div> } @Html.AntiForgeryToken() @Html.Raw(Model.Form.RenderHtml(true)) <input type="hidden" id="HiddenFieldsList" name="HiddenFieldsList" value="@Model.Form.HiddenFieldsList" /> <input type="hidden" id="HighlightedFieldsList" name="HighlightedFieldsList" value="@Model.Form.HighlightedFieldsList" /> <input type="hidden" id="DisabledFieldsList" name="DisabledFieldsList" value="@Model.Form.DisabledFieldsList" /> <input type="hidden" id="RequiredFieldsList" name="RequiredFieldsList" value="@Model.Form.RequiredFieldsList" /> <input type="hidden" id="AssignList" name="AssignList" value="@Model.Form.AssignList" /> <input type="hidden" name="is_save_action" value="false" /> <input type="hidden" name="is_save_action_Mobile" value="false" /> <input type="hidden" name="is_goto_action" value="false" /> <input type="hidden" name="Get_Child_action" value="false" /> <input type="hidden" name="Read_Response_action" value="false" /> <input type="hidden" name="Go_Home_action" value="false" /> <input type="hidden" name="Go_One_Level_Up_action" value="false" /> <input type="hidden" name="DontSave" value="false" /> <input type="hidden" id="RelateButtonWasClicked" name="Requested_View_Id" value="@HttpContext.Current.Session[UserSession.Key.RequestedViewId]" /> <input type="hidden" id="RelateButtonWasClicked_Temp" name="Requested_View_Id_Temp" value="@HttpContext.Current.Session[UserSession.Key.RequestedViewId]" /> <input type="hidden" name="HiddenStatusId" id="HiddenStatusId" value="false" /> <input type="hidden" name="HiddenIsSaved" id="HiddenIsSaved" value="false" /> <input type="hidden" name="HiddensuccessContent" id="HiddensuccessContent" value="false" /> <input type="hidden" id="FormHasChanged" name="Form_Has_Changed" value="@Model.Form.FormValuesHasChanged" /> <div id="nav"> <div id="pagesbottom"> <div id="prev" align="left">&nbsp; @if (Model.Form.CurrentPage != 1) { <a onclick="Submit();" style="" href="@Url.RouteUrl(null, new { controller = "Survey", action = "Index", responseid = Model.Form.ResponseId, PageNumber = Model.Form.CurrentPage - 1 })" class="prev" title="Previous Page">&nbsp;</a> @* <button class="prev" id="PreviousButton" value="PreviousButton" onclick="Previous();" name="PreviousButton" type="button" > &nbsp; Previous</button>*@ } </div> <div id="savediv" align="center"> @*<a onclick="Save();" style="" class="save" title="Click this button to finish the survey later. Use the survey link and pass code provided to return to the survey at a later time.">&nbsp;</a> *@ @*<button type="button" onclick="Save();" id ="Savebutton1" name="Savebutton" value="save" data-role="button" data-theme="save1" data-inline="true" data-iconpos="notext"></button>*@ @*onclick="Save();"*@ <button data-role="button" data-theme="submit1" data-iconpos="notext" type="submit" name="Submitbutton1" value="Submit"><img src="~/Content/images/saveset.png" alt="Save"/>Save</button> <button data-role="button" data-theme="submit12" data-inline="true" type="submit" name="Submitbutton" value="Submit">Save & Close</button> </div> @if (Model.Form.CurrentPage == Model.Form.NumberOfPages) { <!--<div id="next" align="right" style="margin-top:-8px !important;" > @*<a name="Submitbutton" onclick="Submit();" class="submits" >Submit</a>*@ <button data-role="button" data-theme="submit1" data-inline="true" type="submit" name="Submitbutton" value="Submit" >Submit</button> </div>--> } else { <div id="next" align="right"> <a onclick="Submit();" style="" href="@Url.RouteUrl(null, new { controller = "Survey", action = "Index", responseid = Model.Form.ResponseId, PageNumber = Model.Form.CurrentPage + 1 })" class="next" title="Next Page">&nbsp;</a> @*<button class="next" name="ContinueButton" id="ContinueButton" onclick="Continue();" type="button" >Continue &nbsp; </button>*@ </div> } <div style="clear:both"></div> </div> <div style="height:40px;"> <div id="savediv" align="center" style="margin: 20px auto 0 35%; text-align:center;"> </div> </div> </div> </div> }<!--EndForm--> </div><!--End Conten tDiv--> <div id="RelateNavigation" title="View Related Records" > </div> @* </div>*@ @*<div id="dialog" title="Your Survey has been saved." data-role="popup"> <p>Please copy and save the <span style="font-weight:bold;">Survey Link</span> and <span style="font-weight:bold;">Pass Code</span> in order to return to the survey at a later time.</p> <p><span style="font-weight:bold;">Survey Link:</span><br /><textarea id="url" cols="65" style=" height:30px; white-space:pre; background:#d6e7f5; border:1px solid #aecfea; padding:4px; margin-top:4px;" readonly="readonly"></textarea></p> <p style="font-weight:bold;">Pass Code: <span id="spPassCode" style="font-size:12pt; background:#d6e7f5; border:1px solid #aecfea; padding:4px 10px;"></span></p> <hr/> <p>Optionally enter your email address to have the Survey Link and Pass Code emailed to you.</p> <p><label for="email">Email:</label> <input id="email" type="text" style="width: 200px; margin-left:48px;"/></p> <p><label for="confirmemail">Confirm Email:</label> <input id="confirmemail" type="text" style="width: 200px;"/> <button id="send" type="button" class="login" style="width:50px">Send</button></p> <br /> <p style="font-size: 8pt; padding: 5px; background: #ffffa8; margin-top:-5px;"><strong>Note:</strong> Your email address will not be saved and will only be used to send you the survey link.</p> </div> *@
46.74868
1,706
0.544917
1e3072cb2d9d66efa28e381b47f90a7d67e9887a
4,097
cs
C#
OrganizationUnitSample/src/OrganizationUnitSample.EntityFrameworkCore.DbMigrations/Migrations/20211215084609_Upgrade_To_5.0.0.cs
abennet1314/abp-samples
98fa21d50501fecaa8bd9cb3de6309be3c286277
[ "MIT" ]
1
2022-01-13T19:08:28.000Z
2022-01-13T19:08:28.000Z
OrganizationUnitSample/src/OrganizationUnitSample.EntityFrameworkCore.DbMigrations/Migrations/20211215084609_Upgrade_To_5.0.0.cs
abennet1314/abp-samples
98fa21d50501fecaa8bd9cb3de6309be3c286277
[ "MIT" ]
null
null
null
OrganizationUnitSample/src/OrganizationUnitSample.EntityFrameworkCore.DbMigrations/Migrations/20211215084609_Upgrade_To_5.0.0.cs
abennet1314/abp-samples
98fa21d50501fecaa8bd9cb3de6309be3c286277
[ "MIT" ]
1
2022-03-15T12:24:51.000Z
2022-03-15T12:24:51.000Z
using Microsoft.EntityFrameworkCore.Migrations; #nullable disable namespace OrganizationUnitSample.Migrations { public partial class Upgrade_To_500 : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.DropIndex( name: "IX_AbpSettings_Name_ProviderName_ProviderKey", table: "AbpSettings"); migrationBuilder.DropIndex( name: "IX_AbpPermissionGrants_Name_ProviderName_ProviderKey", table: "AbpPermissionGrants"); migrationBuilder.DropIndex( name: "IX_AbpFeatureValues_Name_ProviderName_ProviderKey", table: "AbpFeatureValues"); migrationBuilder.AddColumn<bool>( name: "IsActive", table: "AbpUsers", type: "bit", nullable: false, defaultValue: false); migrationBuilder.AlterColumn<string>( name: "Exceptions", table: "AbpAuditLogs", type: "nvarchar(max)", nullable: true, oldClrType: typeof(string), oldType: "nvarchar(4000)", oldMaxLength: 4000, oldNullable: true); migrationBuilder.CreateIndex( name: "IX_AbpSettings_Name_ProviderName_ProviderKey", table: "AbpSettings", columns: new[] { "Name", "ProviderName", "ProviderKey" }, unique: true, filter: "[ProviderName] IS NOT NULL AND [ProviderKey] IS NOT NULL"); migrationBuilder.CreateIndex( name: "IX_AbpPermissionGrants_TenantId_Name_ProviderName_ProviderKey", table: "AbpPermissionGrants", columns: new[] { "TenantId", "Name", "ProviderName", "ProviderKey" }, unique: true, filter: "[TenantId] IS NOT NULL"); migrationBuilder.CreateIndex( name: "IX_AbpFeatureValues_Name_ProviderName_ProviderKey", table: "AbpFeatureValues", columns: new[] { "Name", "ProviderName", "ProviderKey" }, unique: true, filter: "[ProviderName] IS NOT NULL AND [ProviderKey] IS NOT NULL"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropIndex( name: "IX_AbpSettings_Name_ProviderName_ProviderKey", table: "AbpSettings"); migrationBuilder.DropIndex( name: "IX_AbpPermissionGrants_TenantId_Name_ProviderName_ProviderKey", table: "AbpPermissionGrants"); migrationBuilder.DropIndex( name: "IX_AbpFeatureValues_Name_ProviderName_ProviderKey", table: "AbpFeatureValues"); migrationBuilder.DropColumn( name: "IsActive", table: "AbpUsers"); migrationBuilder.AlterColumn<string>( name: "Exceptions", table: "AbpAuditLogs", type: "nvarchar(4000)", maxLength: 4000, nullable: true, oldClrType: typeof(string), oldType: "nvarchar(max)", oldNullable: true); migrationBuilder.CreateIndex( name: "IX_AbpSettings_Name_ProviderName_ProviderKey", table: "AbpSettings", columns: new[] { "Name", "ProviderName", "ProviderKey" }); migrationBuilder.CreateIndex( name: "IX_AbpPermissionGrants_Name_ProviderName_ProviderKey", table: "AbpPermissionGrants", columns: new[] { "Name", "ProviderName", "ProviderKey" }); migrationBuilder.CreateIndex( name: "IX_AbpFeatureValues_Name_ProviderName_ProviderKey", table: "AbpFeatureValues", columns: new[] { "Name", "ProviderName", "ProviderKey" }); } } }
38.28972
86
0.561875
1e31a7de97bcba1bc2d0289cbaab9b11f259b06c
2,983
cs
C#
src/WireMock.Net/Settings/SimpleCommandLineParser.cs
leolplex/WireMock.Net
fe265faf33e905cf19cdc2e907aece64b333a691
[ "Apache-2.0" ]
700
2017-06-21T05:35:17.000Z
2022-03-31T12:59:20.000Z
src/WireMock.Net/Settings/SimpleCommandLineParser.cs
leolplex/WireMock.Net
fe265faf33e905cf19cdc2e907aece64b333a691
[ "Apache-2.0" ]
630
2017-06-16T15:21:21.000Z
2022-03-31T08:59:15.000Z
src/WireMock.Net/Settings/SimpleCommandLineParser.cs
leolplex/WireMock.Net
fe265faf33e905cf19cdc2e907aece64b333a691
[ "Apache-2.0" ]
169
2017-06-16T20:20:04.000Z
2022-03-25T08:13:22.000Z
using System; using System.Collections.Generic; using System.Linq; namespace WireMock.Settings { // Based on http://blog.gauffin.org/2014/12/simple-command-line-parser/ internal class SimpleCommandLineParser { private const string Sigil = "--"; private IDictionary<string, string[]> Arguments { get; } = new Dictionary<string, string[]>(StringComparer.OrdinalIgnoreCase); public void Parse(string[] arguments) { string currentName = null; var values = new List<string>(); // Split a single argument on a space character to fix issue (e.g. Azure Service Fabric) when an argument is supplied like "--x abc" or '--x abc' foreach (string arg in arguments.SelectMany(arg => arg.Split(' '))) { if (arg.StartsWith(Sigil)) { if (!string.IsNullOrEmpty(currentName)) { Arguments[currentName] = values.ToArray(); } values.Clear(); currentName = arg.Substring(Sigil.Length); } else if (string.IsNullOrEmpty(currentName)) { Arguments[arg] = new string[0]; } else { values.Add(arg); } } if (!string.IsNullOrEmpty(currentName)) { Arguments[currentName] = values.ToArray(); } } public bool Contains(string name) { return Arguments.ContainsKey(name); } public string[] GetValues(string name, string[] defaultValue = null) { return Contains(name) ? Arguments[name] : defaultValue; } public T GetValue<T>(string name, Func<string[], T> func, T defaultValue = default(T)) { return Contains(name) ? func(Arguments[name]) : defaultValue; } public bool GetBoolValue(string name, bool defaultValue = false) { return GetValue(name, values => { string value = values.FirstOrDefault(); return !string.IsNullOrEmpty(value) ? bool.Parse(value) : defaultValue; }, defaultValue); } public bool GetBoolSwitchValue(string name) { return Contains(name); } public int? GetIntValue(string name, int? defaultValue = null) { return GetValue(name, values => { string value = values.FirstOrDefault(); return !string.IsNullOrEmpty(value) ? int.Parse(value) : defaultValue; }, defaultValue); } public string GetStringValue(string name, string defaultValue = null) { return GetValue(name, values => values.FirstOrDefault() ?? defaultValue, defaultValue); } } }
32.423913
157
0.528998
1e32e573c98f8e9ddef2537084a596050daf1889
3,758
cs
C#
DummyOrm/Dynamix/Impl/GetterSetter.cs
mehmetatas/DummyOrm
d8ccd68044af9ae182e558cab2686801ff5e373b
[ "MIT" ]
null
null
null
DummyOrm/Dynamix/Impl/GetterSetter.cs
mehmetatas/DummyOrm
d8ccd68044af9ae182e558cab2686801ff5e373b
[ "MIT" ]
null
null
null
DummyOrm/Dynamix/Impl/GetterSetter.cs
mehmetatas/DummyOrm
d8ccd68044af9ae182e558cab2686801ff5e373b
[ "MIT" ]
null
null
null
using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Reflection; namespace DummyOrm.Dynamix.Impl { public static class GetterSetter { private static readonly Dictionary<Type, Func<object, object>> TypeConverters = new Dictionary<Type, Func<object, object>>(); public static IGetterSetter Create(PropertyInfo propInf) { var type = propInf.ReflectedType; var propType = propInf.PropertyType; var objParam = Expression.Parameter(type, "obj"); var valueParam = Expression.Parameter(propType, "value"); var propExpression = Expression.Property(objParam, propInf); var getterDelegateType = typeof(Func<,>).MakeGenericType(type, propType); var setterDelegateType = typeof(Action<,>).MakeGenericType(type, propType); var getterLambda = Expression.Lambda(getterDelegateType, propExpression, objParam); var setterLambda = Expression.Lambda(setterDelegateType, Expression.Assign(propExpression, valueParam), objParam, valueParam); var getter = getterLambda.Compile(); var setter = setterLambda.Compile(); var getterSetterType = typeof(GetterSetterImpl<,>).MakeGenericType(type, propType); var getterSetter = Activator.CreateInstance(getterSetterType, new object[] { getter, setter }); return (IGetterSetter)getterSetter; } public static IGetterSetter Create<TObject, TProperty>(Expression<Func<TObject, TProperty>> propExp) { var member = (MemberExpression)propExp.Body; var param = Expression.Parameter(typeof(TProperty), "value"); var lambda = Expression.Lambda<Action<TObject, TProperty>>( Expression.Assign(member, param), propExp.Parameters[0], param); var getter = propExp.Compile(); var setter = lambda.Compile(); return new GetterSetterImpl<TObject, TProperty>(getter, setter); } private static Func<object, object> CreateTypeConverter(Type type) { if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) { type = type.GetGenericArguments()[0]; } if (TypeConverters.ContainsKey(type)) { return TypeConverters[type]; } var converter = type.IsEnum ? (Func<object, object>)(value => Enum.ToObject(type, value)) : (value => Convert.ChangeType(value, type)); TypeConverters.Add(type, converter); return converter; } private class GetterSetterImpl<T, TProp> : IGetterSetter { private readonly Func<T, TProp> _getter; private readonly Action<T, TProp> _setter; private readonly Func<object, object> _typeConverter; public GetterSetterImpl(Func<T, TProp> getter, Action<T, TProp> setter) { _getter = getter; _setter = setter; _typeConverter = CreateTypeConverter(typeof(TProp)); } object IGetter.Get(object obj) { return _getter((T)obj); } void ISetter.Set(object obj, object value) { if (value == null || value is DBNull) { return; } if (value.GetType() != typeof(TProp)) { value = _typeConverter(value); } _setter((T)obj, (TProp)value); } } } }
35.121495
138
0.577169
1e33e41aa672cc0f4743f27d41b01e9cd05f0443
2,048
cs
C#
operators/kubestone/dotnet/Kubernetes/Crds/Operators/Kubestone/Perf/V1Alpha1/Outputs/DrillSpecPodConfigPodSchedulingAffinityPodAffinityRequiredDuringSchedulingIgnoredDuringExecution.cs
pulumi/pulumi-kubernetes-crds
372c4c0182f6b899af82d6edaad521aa14f22150
[ "Apache-2.0" ]
null
null
null
operators/kubestone/dotnet/Kubernetes/Crds/Operators/Kubestone/Perf/V1Alpha1/Outputs/DrillSpecPodConfigPodSchedulingAffinityPodAffinityRequiredDuringSchedulingIgnoredDuringExecution.cs
pulumi/pulumi-kubernetes-crds
372c4c0182f6b899af82d6edaad521aa14f22150
[ "Apache-2.0" ]
2
2020-09-18T17:12:23.000Z
2020-12-30T19:40:56.000Z
operators/kubestone/dotnet/Kubernetes/Crds/Operators/Kubestone/Perf/V1Alpha1/Outputs/DrillSpecPodConfigPodSchedulingAffinityPodAffinityRequiredDuringSchedulingIgnoredDuringExecution.cs
pulumi/pulumi-kubernetes-crds
372c4c0182f6b899af82d6edaad521aa14f22150
[ "Apache-2.0" ]
null
null
null
// *** WARNING: this file was generated by crd2pulumi. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Kubernetes.Types.Outputs.Perf.V1Alpha1 { [OutputType] public sealed class DrillSpecPodConfigPodSchedulingAffinityPodAffinityRequiredDuringSchedulingIgnoredDuringExecution { /// <summary> /// A label query over a set of resources, in this case pods. /// </summary> public readonly Pulumi.Kubernetes.Types.Outputs.Perf.V1Alpha1.DrillSpecPodConfigPodSchedulingAffinityPodAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelector LabelSelector; /// <summary> /// namespaces specifies which namespaces the labelSelector applies to (matches against); null or empty list means "this pod's namespace" /// </summary> public readonly ImmutableArray<string> Namespaces; /// <summary> /// This pod should be co-located (affinity) or not co-located (anti-affinity) with the pods matching the labelSelector in the specified namespaces, where co-located is defined as running on a node whose value of the label with key topologyKey matches that of any node on which any of the selected pods is running. Empty topologyKey is not allowed. /// </summary> public readonly string TopologyKey; [OutputConstructor] private DrillSpecPodConfigPodSchedulingAffinityPodAffinityRequiredDuringSchedulingIgnoredDuringExecution( Pulumi.Kubernetes.Types.Outputs.Perf.V1Alpha1.DrillSpecPodConfigPodSchedulingAffinityPodAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelector labelSelector, ImmutableArray<string> namespaces, string topologyKey) { LabelSelector = labelSelector; Namespaces = namespaces; TopologyKey = topologyKey; } } }
47.627907
356
0.736328
1e3aad941afe0b314f4d2b75088de00b7addd07f
4,494
cs
C#
sdk/dotnet/Time.cs
muhlba91/pulumi-proxmoxve
f17723c42b46c004be43ea0d39ff30ea176dd529
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
sdk/dotnet/Time.cs
muhlba91/pulumi-proxmoxve
f17723c42b46c004be43ea0d39ff30ea176dd529
[ "ECL-2.0", "Apache-2.0" ]
3
2021-11-23T07:11:46.000Z
2022-02-10T09:18:13.000Z
sdk/dotnet/Time.cs
muhlba91/pulumi-proxmoxve
f17723c42b46c004be43ea0d39ff30ea176dd529
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.ProxmoxVE { [ProxmoxVEResourceType("proxmoxve:index/time:Time")] public partial class Time : Pulumi.CustomResource { /// <summary> /// The local timestamp /// </summary> [Output("localTime")] public Output<string> LocalTime { get; private set; } = null!; /// <summary> /// The node name /// </summary> [Output("nodeName")] public Output<string> NodeName { get; private set; } = null!; /// <summary> /// The time zone /// </summary> [Output("timeZone")] public Output<string> TimeZone { get; private set; } = null!; /// <summary> /// The UTC timestamp /// </summary> [Output("utcTime")] public Output<string> UtcTime { get; private set; } = null!; /// <summary> /// Create a Time resource with the given unique name, arguments, and options. /// </summary> /// /// <param name="name">The unique name of the resource</param> /// <param name="args">The arguments used to populate this resource's properties</param> /// <param name="options">A bag of options that control this resource's behavior</param> public Time(string name, TimeArgs args, CustomResourceOptions? options = null) : base("proxmoxve:index/time:Time", name, args ?? new TimeArgs(), MakeResourceOptions(options, "")) { } private Time(string name, Input<string> id, TimeState? state = null, CustomResourceOptions? options = null) : base("proxmoxve:index/time:Time", name, state, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, }; var merged = CustomResourceOptions.Merge(defaultOptions, options); // Override the ID if one was specified for consistency with other language SDKs. merged.Id = id ?? merged.Id; return merged; } /// <summary> /// Get an existing Time resource's state with the given name, ID, and optional extra /// properties used to qualify the lookup. /// </summary> /// /// <param name="name">The unique name of the resulting resource.</param> /// <param name="id">The unique provider ID of the resource to lookup.</param> /// <param name="state">Any extra arguments used during the lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static Time Get(string name, Input<string> id, TimeState? state = null, CustomResourceOptions? options = null) { return new Time(name, id, state, options); } } public sealed class TimeArgs : Pulumi.ResourceArgs { /// <summary> /// The node name /// </summary> [Input("nodeName", required: true)] public Input<string> NodeName { get; set; } = null!; /// <summary> /// The time zone /// </summary> [Input("timeZone", required: true)] public Input<string> TimeZone { get; set; } = null!; public TimeArgs() { } } public sealed class TimeState : Pulumi.ResourceArgs { /// <summary> /// The local timestamp /// </summary> [Input("localTime")] public Input<string>? LocalTime { get; set; } /// <summary> /// The node name /// </summary> [Input("nodeName")] public Input<string>? NodeName { get; set; } /// <summary> /// The time zone /// </summary> [Input("timeZone")] public Input<string>? TimeZone { get; set; } /// <summary> /// The UTC timestamp /// </summary> [Input("utcTime")] public Input<string>? UtcTime { get; set; } public TimeState() { } } }
33.789474
125
0.570093
1e3be1461e14fe49d771207828d22db277c8f7bb
2,972
cshtml
C#
TinyCRM.Web.MVC/Views/LegalPerson/Show.cshtml
tomferreira/TinyCRM
30f3c424688df73844556f6f85383d982c176632
[ "MIT" ]
null
null
null
TinyCRM.Web.MVC/Views/LegalPerson/Show.cshtml
tomferreira/TinyCRM
30f3c424688df73844556f6f85383d982c176632
[ "MIT" ]
null
null
null
TinyCRM.Web.MVC/Views/LegalPerson/Show.cshtml
tomferreira/TinyCRM
30f3c424688df73844556f6f85383d982c176632
[ "MIT" ]
1
2021-03-09T12:46:57.000Z
2021-03-09T12:46:57.000Z
@model TinyCRM.Application.ViewModels.LegalPerson.LegalPersonViewModel @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers @{ ViewData["Title"] = @Model.CompanyName; } <section class="section"> <div class="section-header"> <h1>@ViewData["Title"]</h1> <div class="section-header-breadcrumb"> <div class="breadcrumb-item"><a asp-area="" asp-controller="Home" asp-action="Index">@SharedLocalizer["Home"]</a></div> <div class="breadcrumb-item"><a asp-area="" asp-controller="LegalPerson" asp-action="Index">@SharedLocalizer["LegalPerson"]</a></div> <div class="breadcrumb-item active">@Model.CompanyName</div> </div> </div> <div class="section-body"> <h2 class="section-title">@SharedLocalizer["GeneralSection"]</h2> <div class="card"> <div class="card-body"> <p> <strong><label asp-for="CompanyName"></label></strong> <br /> @Model.CompanyName </p> <p> <strong><label asp-for="TradeName"></label></strong> <br /> @Model.TradeName </p> <p> <strong><label asp-for="IdDocument"></label></strong> <br /> @Model.IdDocument </p> <p> <strong><label asp-for="Country"></label></strong> <br /> @Model.Country </p> <p> <strong><label asp-for="ZipCode"></label></strong> <br /> @Model.ZipCode </p> <p> <strong><label asp-for="City"></label></strong> <br /> @Model.City </p> <p> <strong><label asp-for="State"></label></strong> <br /> @Model.State </p> <p> <strong><label asp-for="AddressLine1"></label></strong> <br /> @Model.AddressLine1 </p> <p> <strong><label asp-for="AddressLine2"></label></strong> <br /> @Model.AddressLine2 </p> </div> <div class="card-footer text-right"> @Html.ActionLink(@SharedLocalizer["EditAction"], "Edit", "LegalPerson", new { id = Model.Id }, new { @class = "btn btn-primary" }) @Html.ActionLink(@SharedLocalizer["DeleteAction"], "Delete", "LegalPerson", new { id = Model.Id }, new { @onclick = $"return confirm('{@SharedLocalizer["DeleteConfirmation"]}')", @class = "btn btn-danger" }) </div> </div> </div> </section>
40.162162
146
0.444145
1e3dda9dca81b61d8e2bbcef23483580161e3b71
5,590
cs
C#
tests/src/CoreMangLib/cti/system/array/arraylastindexof3b.cs
danmosemsft/coreclr
04a3d11e4eecec2a4b7dcc81ab1575a57e30e3e2
[ "MIT" ]
6
2017-09-22T06:55:45.000Z
2021-07-02T07:07:08.000Z
tests/src/CoreMangLib/cti/system/array/arraylastindexof3b.cs
danmosemsft/coreclr
04a3d11e4eecec2a4b7dcc81ab1575a57e30e3e2
[ "MIT" ]
2
2017-09-23T08:21:05.000Z
2017-09-27T03:31:06.000Z
tests/src/CoreMangLib/cti/system/array/arraylastindexof3b.cs
danmosemsft/coreclr
04a3d11e4eecec2a4b7dcc81ab1575a57e30e3e2
[ "MIT" ]
2
2020-01-16T10:14:30.000Z
2020-02-09T08:48:51.000Z
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; public class ArrayLastIndexOf3 { private const int c_MIN_SIZE = 64; private const int c_MAX_SIZE = 1024; private const int c_MIN_STRLEN = 1; private const int c_MAX_STRLEN = 1024; public static int Main() { ArrayLastIndexOf3 ac = new ArrayLastIndexOf3(); TestLibrary.TestFramework.BeginTestCase("Array.LastInexOf(T[] array, T value)"); if (ac.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; retVal = PosTest6() && retVal; retVal = PosTest7() && retVal; retVal = PosTest8() && retVal; retVal = PosTest9() && retVal; retVal = PosTest10() && retVal; TestLibrary.TestFramework.LogInformation(""); TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; return retVal; } public bool PosTest1() { return PosIndexOf<Int64>(1, TestLibrary.Generator.GetInt64(-55), TestLibrary.Generator.GetInt64(-55)); } public bool PosTest2() { return PosIndexOf<Int32>(2, TestLibrary.Generator.GetInt32(-55), TestLibrary.Generator.GetInt32(-55)); } public bool PosTest3() { return PosIndexOf<Int16>(3, TestLibrary.Generator.GetInt16(-55), TestLibrary.Generator.GetInt16(-55)); } public bool PosTest4() { return PosIndexOf<Byte>(4, TestLibrary.Generator.GetByte(-55), TestLibrary.Generator.GetByte(-55)); } public bool PosTest5() { return PosIndexOf<double>(5, TestLibrary.Generator.GetDouble(-55), TestLibrary.Generator.GetDouble(-55)); } public bool PosTest6() { return PosIndexOf<float>(6, TestLibrary.Generator.GetSingle(-55), TestLibrary.Generator.GetSingle(-55)); } public bool PosTest7() { return PosIndexOf<char>(7, TestLibrary.Generator.GetCharLetter(-55), TestLibrary.Generator.GetCharLetter(-55)); } public bool PosTest8() { return PosIndexOf<char>(8, TestLibrary.Generator.GetCharNumber(-55), TestLibrary.Generator.GetCharNumber(-55)); } public bool PosTest9() { return PosIndexOf<char>(9, TestLibrary.Generator.GetChar(-55), TestLibrary.Generator.GetChar(-55)); } public bool PosTest10() { return PosIndexOf<string>(10, TestLibrary.Generator.GetString(-55, false, c_MIN_STRLEN, c_MAX_STRLEN), TestLibrary.Generator.GetString(-55, false, c_MIN_STRLEN, c_MAX_STRLEN)); } public bool NegTest1() { return NegIndexOf<Int32>(1, 1); } public bool PosIndexOf<T>(int id, T element, T otherElem) { bool retVal = true; T[] array; int length; int index; int newIndex; TestLibrary.TestFramework.BeginScenario("PosTest"+id+": Array.LastInexOf(T[] array, T value, int startIndex) (T=="+typeof(T)+") where value is found"); try { // creat the array length = (TestLibrary.Generator.GetInt32(-55) % (c_MAX_SIZE-c_MIN_SIZE)) + c_MIN_SIZE; array = new T[length]; // fill the array for (int i=0; i<array.Length; i++) { array[i] = otherElem; } // set the lucky index index = TestLibrary.Generator.GetInt32(-55) % length; // set the value array.SetValue( element, index); newIndex = Array.LastIndexOf<T>(array, element, array.Length-1); if (index > newIndex) { TestLibrary.TestFramework.LogError("000", "Unexpected index: Expected(" + index + ") Actual(" + newIndex + ")"); retVal = false; } if (!element.Equals(array[newIndex])) { TestLibrary.TestFramework.LogError("001", "Unexpected value: Expected(" + element + ") Actual(" + array[newIndex] + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegIndexOf<T>(int id, T defaultValue) { bool retVal = true; T[] array = null; TestLibrary.TestFramework.BeginScenario("NegTest"+id+": Array.LastInexOf(T[] array, T value, int startIndex) (T == "+typeof(T)+" where array is null"); try { Array.LastIndexOf<T>(array, defaultValue, 0); TestLibrary.TestFramework.LogError("003", "Exepction should have been thrown"); retVal = false; } catch (ArgumentNullException) { // expected } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e); retVal = false; } return retVal; } }
37.266667
208
0.605546
1e3e5f2c3634d06f291734f0c25ee28875d56da4
1,846
cs
C#
Factors.Feature.Phone/Models/PhoneConfiguration.cs
bradmb/factors
22a0e427a209638e4b7f7cb5e78a7d41d4ef23fb
[ "MIT" ]
null
null
null
Factors.Feature.Phone/Models/PhoneConfiguration.cs
bradmb/factors
22a0e427a209638e4b7f7cb5e78a7d41d4ef23fb
[ "MIT" ]
76
2018-09-10T12:13:38.000Z
2020-04-30T12:12:27.000Z
Factors.Feature.Phone/Models/PhoneConfiguration.cs
bradmb/factors
22a0e427a209638e4b7f7cb5e78a7d41d4ef23fb
[ "MIT" ]
2
2018-08-30T18:39:47.000Z
2020-08-01T20:14:25.000Z
using Factors.Feature.Phone.Interfaces; using System; namespace Factors.Feature.Phone.Models { public class PhoneConfiguration { /// <summary> /// If enabled, will allow outbound phone calls with /// verification tokens. This requires your application /// to supply an endpoint that can provide the messaging /// provider with the text to say on the phone call /// </summary> public bool EnablePhoneCallSupport { get; set; } /// <summary> /// This is the URL that will be called by the phone call /// messaging provider when a phone call is connected, which /// will then provide the phone call text that will be read /// to the end user. The token's value will be passed via a "?token=" /// URL parameter, which is appended to the URL automatically. /// </summary> public Uri PhoneCallInboundEndpoint { get; set; } /// <summary> /// The template that is used on outbound text messages. Can include /// "@APPNAME@" to auto-populate the application name. Must include /// "@APPCODE@", as that is what is replaced with the verification token. /// Defaults to: "Your @APPNAME@ verification code is @APPCODE@" /// </summary> public string TextMessageTemplate { get; set; } = "Your @APPNAME@ verification code is: @APPCODE@"; /// <summary> /// The message delivery service you want to use /// for sending out text messages and phone calls /// </summary> public IMessagingProvider MessagingProvider { get; set; } /// <summary> /// The amount of time before an email token /// will expire and become unuseable /// </summary> public TimeSpan TokenExpirationTime { get; set; } } }
40.130435
107
0.621885
1e3f68369662aea22beb9c637e18ac2f3bd26af3
34,428
cs
C#
src/Learners/Core/Metrics.cs
MyIntelligenceAgency/infer
2b3095da50acdf2f5ae6dfb5fd11661ff7800bd1
[ "MIT" ]
1,416
2018-10-05T05:58:50.000Z
2022-03-27T07:18:12.000Z
src/Learners/Core/Metrics.cs
MyIntelligenceAgency/infer
2b3095da50acdf2f5ae6dfb5fd11661ff7800bd1
[ "MIT" ]
162
2018-10-05T09:47:05.000Z
2022-03-21T16:05:30.000Z
src/Learners/Core/Metrics.cs
isabella232/infer-1
85be0de05275ffe139cc83bd3d624c926de0d2f1
[ "MIT" ]
217
2018-10-05T08:11:11.000Z
2022-03-20T22:31:58.000Z
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.ML.Probabilistic.Learners { using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Microsoft.ML.Probabilistic.Collections; using Microsoft.ML.Probabilistic.Distributions; using Microsoft.ML.Probabilistic.Math; /// <summary> /// A diverse set of metrics to evaluate various kinds of predictors. /// </summary> public static class Metrics { /// <summary> /// Linear position discount function. /// </summary> public static readonly Func<int, double> LinearDiscountFunc = i => 1.0 / (i + 1); /// <summary> /// Logarithmic position discount function. /// </summary> public static readonly Func<int, double> LogarithmicDiscountFunc = i => 1.0 / Math.Log(i + 2, 2); /// <summary> /// The tolerance for comparisons of real numbers. /// </summary> private const double Tolerance = 1e-9; #region Pointwise metrics /// <summary> /// Returns 0 if a prediction and the ground truth are the same and 1 otherwise. /// </summary> /// <typeparam name="TLabel">The type of a label.</typeparam> /// <param name="groundTruth">The ground truth.</param> /// <param name="prediction">The prediction.</param> /// <returns>The computed metric value.</returns> public static double ZeroOneError<TLabel>(TLabel groundTruth, TLabel prediction) { if (groundTruth == null) { throw new ArgumentNullException(nameof(groundTruth)); } if (prediction == null) { throw new ArgumentNullException(nameof(prediction)); } return prediction.Equals(groundTruth) ? 0.0 : 1.0; } /// <summary> /// Returns 0 if a prediction and the ground truth are the same and 1 otherwise. /// </summary> /// <param name="groundTruth">The ground truth.</param> /// <param name="prediction">The prediction.</param> /// <returns>The computed metric value.</returns> public static double ZeroOneError(int groundTruth, int prediction) { return prediction == groundTruth ? 0.0 : 1.0; } /// <summary> /// Computes squared difference between a prediction and the ground truth. /// </summary> /// <param name="groundTruth">The ground truth.</param> /// <param name="prediction">The prediction.</param> /// <returns>The computed metric value.</returns> public static double SquaredError(bool groundTruth, bool prediction) { return ZeroOneError(groundTruth, prediction); } /// <summary> /// Computes squared difference between a prediction and the ground truth. /// </summary> /// <param name="groundTruth">The ground truth.</param> /// <param name="prediction">The prediction.</param> /// <returns>The computed metric value.</returns> public static double SquaredError(int groundTruth, int prediction) { return SquaredError((double)groundTruth, (double)prediction); } /// <summary> /// Computes squared difference between a prediction and the ground truth. /// </summary> /// <param name="groundTruth">The ground truth.</param> /// <param name="prediction">The prediction.</param> /// <returns>The computed metric value.</returns> public static double SquaredError(double groundTruth, int prediction) { return SquaredError(groundTruth, (double)prediction); } /// <summary> /// Computes the squared difference between a prediction and the ground truth. /// </summary> /// <param name="groundTruth">The ground truth.</param> /// <param name="prediction">The prediction.</param> /// <returns>The computed metric value.</returns> public static double SquaredError(double groundTruth, double prediction) { double difference = groundTruth - prediction; return difference * difference; } /// <summary> /// Computes the absolute difference between a prediction and the ground truth. /// </summary> /// <param name="groundTruth">The ground truth.</param> /// <param name="prediction">The prediction.</param> /// <returns>The computed metric value.</returns> public static double AbsoluteError(bool groundTruth, bool prediction) { return ZeroOneError(groundTruth, prediction); } /// <summary> /// Computes the absolute difference between a prediction and the ground truth. /// </summary> /// <param name="groundTruth">The ground truth.</param> /// <param name="prediction">The prediction.</param> /// <returns>The computed metric value.</returns> public static double AbsoluteError(int groundTruth, int prediction) { return AbsoluteError((double)groundTruth, (double)prediction); } /// <summary> /// Computes the absolute difference between a prediction and the ground truth. /// </summary> /// <param name="groundTruth">The ground truth.</param> /// <param name="prediction">The prediction.</param> /// <returns>The computed metric value.</returns> public static double AbsoluteError(double groundTruth, int prediction) { return AbsoluteError(groundTruth, (double)prediction); } /// <summary> /// Computes the absolute difference between a prediction and the ground truth. /// </summary> /// <param name="groundTruth">The ground truth.</param> /// <param name="prediction">The prediction.</param> /// <returns>The computed metric value.</returns> public static double AbsoluteError(double groundTruth, double prediction) { return Math.Abs(groundTruth - prediction); } /// <summary> /// Returns the negative natural logarithm of the probability of ground truth for a given predictive distribution. /// </summary> /// <param name="groundTruth">The ground truth.</param> /// <param name="prediction">The prediction as a <see cref="Discrete"/> distribution.</param> /// <returns>The negative natural logarithm of the probability of <paramref name="groundTruth"/>.</returns> public static double NegativeLogProbability(bool groundTruth, Bernoulli prediction) { return -prediction.GetLogProb(groundTruth); } /// <summary> /// Returns the negative natural logarithm of the probability of ground truth for a given predictive distribution. /// </summary> /// <param name="groundTruth">The ground truth.</param> /// <param name="prediction">The prediction as a <see cref="Discrete"/> distribution.</param> /// <returns>The negative natural logarithm of the probability of <paramref name="groundTruth"/>.</returns> public static double NegativeLogProbability(int groundTruth, Discrete prediction) { if (prediction == null) { throw new ArgumentNullException(nameof(prediction)); } return -prediction.GetLogProb(groundTruth); } /// <summary> /// Returns the negative natural logarithm of the probability of ground truth for a given predictive distribution. /// </summary> /// <typeparam name="TLabel">The type of a label.</typeparam> /// <param name="groundTruth">The ground truth.</param> /// <param name="prediction">The prediction as a discrete distribution over labels.</param> /// <returns>The negative natural logarithm of the probability of <paramref name="groundTruth"/>.</returns> public static double NegativeLogProbability<TLabel>(TLabel groundTruth, IDictionary<TLabel, double> prediction) { if (groundTruth == null) { throw new ArgumentNullException(nameof(groundTruth)); } if (prediction == null) { throw new ArgumentNullException(nameof(prediction)); } if (prediction.Count < 2) { throw new ArgumentException("The predicted distribution over labels must contain at least two entries.", nameof(prediction)); } if (Math.Abs(prediction.Values.Sum() - 1) > Tolerance) { throw new ArgumentException("The predicted distribution over labels must sum to 1.", nameof(prediction)); } if (prediction.Values.Any(p => p < 0.0 || p > 1.0)) { throw new ArgumentException("The label probability must be between 0 and 1.", nameof(prediction)); } double probability; if (!prediction.TryGetValue(groundTruth, out probability)) { throw new ArgumentException("The predicted distribution over labels does not contain a probability for the ground truth label '" + groundTruth + "'."); } return -Math.Log(probability); } #endregion #region Listwise metrics /// <summary> /// Computes discounted cumulative gain for the given list of gains. /// </summary> /// <param name="orderedGains">List of gains ordered according to some external criteria.</param> /// <param name="discountFunc">Position discount function.</param> /// <returns>The computed metric value.</returns> /// <exception cref="ArgumentNullException">Thrown if one of the arguments is null.</exception> public static double Dcg(IEnumerable<double> orderedGains, Func<int, double> discountFunc) { if (orderedGains == null) { throw new ArgumentNullException(nameof(orderedGains)); } if (discountFunc == null) { throw new ArgumentNullException(nameof(discountFunc)); } int index = 0; return orderedGains.Sum(gain => gain * discountFunc(index++)); } /// <summary> /// Computes discounted cumulative gain for the given list of gains /// using <see cref="LogarithmicDiscountFunc"/> discount function. /// </summary> /// <param name="orderedGains">List of gains ordered according to some external criteria.</param> /// <returns>The computed metric value.</returns> /// <exception cref="ArgumentNullException">Thrown if one of the arguments is null.</exception> public static double Dcg(IEnumerable<double> orderedGains) { return Dcg(orderedGains, LogarithmicDiscountFunc); } /// <summary> /// Computes discounted cumulative gain for the given list of gains /// using <see cref="LinearDiscountFunc"/> discount function. /// </summary> /// <param name="orderedGains">List of gains ordered according to some external criteria.</param> /// <returns>The computed metric value.</returns> /// <exception cref="ArgumentNullException">Thrown if one of the arguments is null.</exception> public static double LinearDcg(IEnumerable<double> orderedGains) { return Dcg(orderedGains, LinearDiscountFunc); } /// <summary> /// Computes discounted cumulative gain for the given list of gains normalized given another list of gains. /// </summary> /// <param name="orderedGains">List of gains ordered according to some external criteria.</param> /// <param name="bestOrderedGains">List of gains used to compute a normalizer for discounted cumulative gain.</param> /// <param name="discountFunc">Position discount function.</param> /// <returns>The computed metric value.</returns> /// <exception cref="ArgumentNullException">Thrown if one of the arguments is null.</exception> /// <exception cref="ArgumentException"> /// Thrown if <paramref name="orderedGains"/> and <paramref name="bestOrderedGains"/> are of different size. /// </exception> public static double Ndcg(IEnumerable<double> orderedGains, IEnumerable<double> bestOrderedGains, Func<int, double> discountFunc) { if (orderedGains == null) { throw new ArgumentNullException(nameof(orderedGains)); } if (bestOrderedGains == null) { throw new ArgumentNullException(nameof(bestOrderedGains)); } if (discountFunc == null) { throw new ArgumentNullException(nameof(discountFunc)); } List<double> orderedGainList = orderedGains.ToList(); List<double> bestOrderedGainList = bestOrderedGains.ToList(); if (bestOrderedGainList.Count == 0) { throw new ArgumentException("NDCG is not defined for empty gain lists."); } if (orderedGainList.Count != bestOrderedGainList.Count) { throw new ArgumentException("The gain lists must be of the same size in order to compute NDCG."); } double result = Dcg(orderedGainList, discountFunc) / Dcg(bestOrderedGainList, discountFunc); if (double.IsNaN(result) || double.IsInfinity(result)) { throw new ArgumentException("NDCG is not defined for the given pair of gain lists."); } if (result < 0 || result > 1) { throw new ArgumentException("NDCG is out of the [0, 1] range for the given pair of gain lists."); } return result; } /// <summary> /// Computes discounted cumulative gain for the given list of gains normalized given another list of gains using <see cref="LogarithmicDiscountFunc"/>. /// </summary> /// <param name="orderedGains">List of gains ordered according to some external criteria.</param> /// <param name="bestOrderedGains">List of gains used to compute a normalizer for discounted cumulative gain.</param> /// <returns>The computed metric value.</returns> /// <exception cref="ArgumentNullException">Thrown if one of the arguments is null.</exception> /// <exception cref="ArgumentException"> /// Thrown if <paramref name="orderedGains"/> and <paramref name="bestOrderedGains"/> are of different size. /// </exception> public static double Ndcg(IEnumerable<double> orderedGains, IEnumerable<double> bestOrderedGains) { return Ndcg(orderedGains, bestOrderedGains, LogarithmicDiscountFunc); } /// <summary> /// Computes discounted cumulative gain for the given list of gains normalized given another list of gains using <see cref="LinearDiscountFunc"/>. /// </summary> /// <param name="orderedGains">List of gains ordered according to some external criteria.</param> /// <param name="bestOrderedGains">List of gains used to compute a normalizer for discounted cumulative gain.</param> /// <returns>The computed metric value.</returns> /// <exception cref="ArgumentNullException">Thrown if one of the arguments is null.</exception> /// <exception cref="ArgumentException"> /// Thrown if <paramref name="orderedGains"/> and <paramref name="bestOrderedGains"/> are of different size. /// </exception> public static double LinearNdcg(IEnumerable<double> orderedGains, IEnumerable<double> bestOrderedGains) { return Ndcg(orderedGains, bestOrderedGains, LinearDiscountFunc); } /// <summary> /// Computes graded average precision for the given list of relevance values. /// </summary> /// <param name="orderedRelevances">List of relevance values ordered according to some external criteria.</param> /// <returns>The computed metric value.</returns> /// <exception cref="ArgumentNullException">Thrown if one of the arguments is null.</exception> public static double GradedAveragePrecision(IEnumerable<double> orderedRelevances) { if (orderedRelevances == null) { throw new ArgumentNullException(nameof(orderedRelevances)); } int outerIndex = 0; double outerSum = 0; double relevanceSum = 0; List<double> orderedRelevanceList = orderedRelevances.ToList(); foreach (double relevanceOuter in orderedRelevanceList) { relevanceSum += relevanceOuter; int innerIndex = 0; double innerSum = 0; foreach (double relevanceInner in orderedRelevanceList) { if (innerIndex > outerIndex) { break; } innerSum += Math.Min(relevanceOuter, relevanceInner); ++innerIndex; } outerSum += innerSum / (outerIndex + 1); ++outerIndex; } return outerSum / relevanceSum; } /// <summary> /// Computes the precision-recall curve. /// </summary> /// <typeparam name="TInstance">The type of an instance.</typeparam> /// <param name="positiveInstances">The instances with 'positive' ground truth labels.</param> /// <param name="instanceScores"> /// The predicted instance scores. The larger a predicted score, the more likely the instance is /// to belong to the 'positive' class. /// </param> /// <returns>The points on the precision-recall curve, increasing by recall.</returns> /// <remarks> /// All instances not contained in <paramref name="positiveInstances"/> are assumed to belong to the 'negative' class. /// </remarks> public static IEnumerable<PrecisionRecall> PrecisionRecallCurve<TInstance>( IEnumerable<TInstance> positiveInstances, IEnumerable<KeyValuePair<TInstance, double>> instanceScores) { if (positiveInstances == null) { throw new ArgumentNullException(nameof(positiveInstances)); } if (instanceScores == null) { throw new ArgumentNullException(nameof(instanceScores)); } // Compute the number of instances with positive ground truth labels var positiveInstanceSet = new HashSet<TInstance>(positiveInstances); long positivesCount = positiveInstanceSet.Count(); if (positivesCount == 0) { throw new ArgumentException("There must be at least one instance with a 'positive' ground truth label."); } // Sort instances by their scores var sortedInstanceScores = from pair in instanceScores orderby pair.Value descending select pair; // Add (0,1) to PR curve long falsePositivesCount = 0; long truePositivesCount = 0; double recall = 0.0; double precision = 1.0; var precisionRecallCurve = new List<PrecisionRecall> { new PrecisionRecall(precision, recall) }; // Add further points to PR curve foreach (var instance in sortedInstanceScores) { if (positiveInstanceSet.Contains(instance.Key)) { truePositivesCount++; } else { falsePositivesCount++; } recall = truePositivesCount / (double)positivesCount; precision = truePositivesCount / ((double)truePositivesCount + falsePositivesCount); precisionRecallCurve.Add(new PrecisionRecall(precision, recall)); } return precisionRecallCurve; } /// <summary> /// Computes the receiver operating characteristic curve. /// <para> /// The implementation follows Algorithm 2 as described in Fawcett, T. (2004): ROC Graphs: Notes and Practical /// Considerations for Researchers. /// </para> /// </summary> /// <typeparam name="TInstance">The type of an instance.</typeparam> /// <param name="positiveInstances">The instances with 'positive' ground truth labels.</param> /// <param name="instanceScores"> /// The predicted instance scores. The larger a predicted score, the more likely the instance is /// to belong to the 'positive' class. /// </param> /// <returns>The points on the receiver operating characteristic curve, increasing by false positive rate.</returns> /// <remarks> /// All instances not contained in <paramref name="positiveInstances"/> are assumed to belong to the 'negative' class. /// </remarks> public static IEnumerable<FalseAndTruePositiveRate> ReceiverOperatingCharacteristicCurve<TInstance>( IEnumerable<TInstance> positiveInstances, IEnumerable<KeyValuePair<TInstance, double>> instanceScores) { if (positiveInstances == null) { throw new ArgumentNullException(nameof(positiveInstances)); } if (instanceScores == null) { throw new ArgumentNullException(nameof(instanceScores)); } // Compute the number of instances with positive and negative ground truth labels var positiveInstanceSet = new HashSet<TInstance>(positiveInstances); long positivesCount = positiveInstanceSet.Count(); long negativesCount = instanceScores.Count() - positivesCount; if (positivesCount == 0) { throw new ArgumentException("There must be at least one instance with a 'positive' ground truth label."); } if (negativesCount <= 0) { throw new ArgumentException("There must be at least one instance with a 'negative' ground truth label."); } // Sort instances by their scores var sortedInstanceScores = from pair in instanceScores orderby pair.Value descending select pair; long falsePositivesCount = 0; long truePositivesCount = 0; double falsePositiveRate; double truePositiveRate; double previousScore = double.NaN; var rocCurve = new List<FalseAndTruePositiveRate>(); foreach (var instance in sortedInstanceScores) { double score = instance.Value; if (score != previousScore) { falsePositiveRate = falsePositivesCount / (double)negativesCount; truePositiveRate = truePositivesCount / (double)positivesCount; rocCurve.Add(new FalseAndTruePositiveRate(falsePositiveRate, truePositiveRate)); previousScore = score; } if (positiveInstanceSet.Contains(instance.Key)) { truePositivesCount++; } else { falsePositivesCount++; } } // Add point for (1,1) falsePositiveRate = falsePositivesCount / (double)negativesCount; truePositiveRate = truePositivesCount / (double)positivesCount; rocCurve.Add(new FalseAndTruePositiveRate(falsePositiveRate, truePositiveRate)); return rocCurve; } /// <summary> /// Computes the area under the receiver operating characteristic curve. /// <para> /// The implementation follows Algorithm 3 as described in Fawcett, T. (2004): ROC Graphs: Notes and Practical /// Considerations for Researchers. /// </para> /// </summary> /// <typeparam name="TInstance">The type of an instance.</typeparam> /// <param name="positiveInstances">The instances with 'positive' ground truth labels.</param> /// <param name="instanceScores"> /// The predicted instance scores. The larger a predicted score, the more likely the instance is /// to belong to the 'positive' class. /// </param> /// <returns>AUC - the area under the receiver operating characteristic curve.</returns> /// <remarks> /// All instances not contained in <paramref name="positiveInstances"/> are assumed to belong to the 'negative' class. /// </remarks> public static double AreaUnderRocCurve<TInstance>( IEnumerable<TInstance> positiveInstances, IEnumerable<KeyValuePair<TInstance, double>> instanceScores) { if (positiveInstances == null) { throw new ArgumentNullException(nameof(positiveInstances)); } if (instanceScores == null) { throw new ArgumentNullException(nameof(instanceScores)); } // Compute the number of instances with positive and negative ground truth labels var positiveInstanceSet = new HashSet<TInstance>(positiveInstances); long positivesCount = positiveInstanceSet.Count(); long negativesCount = instanceScores.Count() - positivesCount; if (positivesCount == 0) { throw new ArgumentException("There must be at least one instance with a 'positive' ground truth label."); } if (negativesCount <= 0) { throw new ArgumentException("There must be at least one instance with a 'negative' ground truth label."); } // Sort instances by their scores var sortedInstanceScores = from pair in instanceScores orderby pair.Value descending select pair; long falsePositivesCount = 0; long truePositivesCount = 0; long previousFalsePositivesCount = 0; long previousTruePositivesCount = 0; double area = 0.0; double previousScore = double.NaN; foreach (var instance in sortedInstanceScores) { double score = instance.Value; if (score != previousScore) { // Add trapezoid area between current instance and previous instance area += 0.5 * Math.Abs(falsePositivesCount - previousFalsePositivesCount) * (truePositivesCount + previousTruePositivesCount); previousScore = score; previousFalsePositivesCount = falsePositivesCount; previousTruePositivesCount = truePositivesCount; } if (positiveInstanceSet.Contains(instance.Key)) { truePositivesCount++; } else { falsePositivesCount++; } } // Add trapezoid area between last instance and (1, 1) area += 0.5 * Math.Abs(falsePositivesCount - previousFalsePositivesCount) * (truePositivesCount + previousTruePositivesCount); // Scale to unit square return area / (positivesCount * negativesCount); } #endregion #region Correlation measures /// <summary> /// Computes cosine similarity between two given vectors. /// </summary> /// <param name="vector1">The first vector.</param> /// <param name="vector2">The second vector.</param> /// <returns>The computed similarity value.</returns> /// <exception cref="ArgumentNullException">Thrown if one of the arguments is null.</exception> /// <exception cref="ArgumentException"> /// Thrown if the similarity is not defined for the given pair of vectors. /// It can happen if the vectors are of different length or one of them has zero magnitude. /// </exception> public static double CosineSimilarity(Vector vector1, Vector vector2) { CheckVectorPair(vector1, vector2); double result = vector1.Inner(vector2) / Math.Sqrt(vector1.Inner(vector1) * vector2.Inner(vector2)); if (double.IsNaN(result)) { throw new ArgumentException("Similarity is not defined for the given pair of sequences."); } Debug.Assert(result >= -1 && result <= 1, "Similarity should always be in the [-1, 1] range."); return result; } /// <summary> /// Computes Pearson's correlation coefficient for a given pair of vectors. /// </summary> /// <param name="vector1">The first vector.</param> /// <param name="vector2">The second vector.</param> /// <returns>The computed correlation value.</returns> /// <exception cref="ArgumentNullException">Thrown if one of the arguments is null.</exception> /// <exception cref="ArgumentException"> /// Thrown if the correlation is not defined for the given pair of vectors. /// It can happen if the vectors are of different length or one of them has zero variance. /// </exception> public static double PearsonCorrelation(Vector vector1, Vector vector2) { CheckVectorPair(vector1, vector2); double mean1 = vector1.Sum() / vector1.Count; double mean2 = vector2.Sum() / vector2.Count; return CosineSimilarity( vector1 - Vector.Constant(vector1.Count, mean1), vector2 - Vector.Constant(vector2.Count, mean2)); } #endregion #region Distance measures /// <summary> /// Computes the similarity measure for a given pair of vectors based on the Euclidean distance between them. /// The similarity is computed as 1.0 / (1.0 + D(<paramref name="vector1"/>, <paramref name="vector2"/>), /// where D stands for the Euclidean distance divided by the square root of the dimensionality. /// </summary> /// <param name="vector1">The first vector.</param> /// <param name="vector2">The second vector.</param> /// <returns>The computed similarity value.</returns> /// <exception cref="ArgumentNullException">Thrown if one of the arguments is null.</exception> /// <exception cref="ArgumentException"> /// Thrown if the distance is not defined for the given pair of vectors. /// It can happen if the vectors are of different or zero length. /// </exception> public static double NormalizedEuclideanSimilarity(Vector vector1, Vector vector2) { CheckVectorPair(vector1, vector2); Vector diff = vector1 - vector2; double distance = Math.Sqrt(diff.Inner(diff) / diff.Count); return 1.0 / (1.0 + distance); } /// <summary> /// Computes the similarity measure for a given pair of vectors based on Manhattan distance between them. /// The similarity is computed as 1.0 / (1.0 + D(<paramref name="vector1"/>, <paramref name="vector2"/>), /// where D stands for the Manhattan distance divided by the dimensionality. /// </summary> /// <param name="vector1">The first vector.</param> /// <param name="vector2">The second vector.</param> /// <returns>The computed similarity value.</returns> /// <exception cref="ArgumentNullException">Thrown if one of the arguments is null.</exception> /// <exception cref="ArgumentException"> /// Thrown if the distance is not defined for the given pair of vectors. /// It can happen if the vectors are of different or zero length. /// </exception> public static double NormalizedManhattanSimilarity(Vector vector1, Vector vector2) { CheckVectorPair(vector1, vector2); double absoluteDifferenceSum = (vector1 - vector2).Sum(Math.Abs); double distance = absoluteDifferenceSum / vector1.Count; return 1.0 / (1.0 + distance); } #endregion #region Helpers /// <summary> /// Checks if the given pair of vectors is of the same non-zero dimensionality. /// </summary> /// <param name="vector1">The first vector.</param> /// <param name="vector2">The second vector.</param> /// <exception cref="ArgumentNullException">Thrown if one of the arguments is null.</exception> /// <exception cref="ArgumentException">Thrown if arguments are of different or zero length.</exception> private static void CheckVectorPair(Vector vector1, Vector vector2) { if (vector1 == null) { throw new ArgumentNullException(nameof(vector1)); } if (vector2 == null) { throw new ArgumentNullException(nameof(vector2)); } int count1 = vector1.Count; int count2 = vector2.Count; if (count1 == 0) { throw new ArgumentException("The given vectors should have non-zero size."); } if (count1 != count2) { throw new ArgumentException("The given vectors should be of the same size."); } } #endregion } }
44.138462
167
0.600442
1e4118c54f2199ccdc0d014300615948a0597102
2,697
cs
C#
test/Nut.Results.Test/Extensions/Unsafe/T_PassOnErrorTest.cs
Archway-SharedLib/Nut.Results
51cbb155ef145c8083904504d1c91a6e1a386f51
[ "Apache-2.0" ]
null
null
null
test/Nut.Results.Test/Extensions/Unsafe/T_PassOnErrorTest.cs
Archway-SharedLib/Nut.Results
51cbb155ef145c8083904504d1c91a6e1a386f51
[ "Apache-2.0" ]
17
2020-10-30T09:29:05.000Z
2021-12-29T15:42:27.000Z
test/Nut.Results.Test/Extensions/Unsafe/T_PassOnErrorTest.cs
Archway-SharedLib/Nut.Results
51cbb155ef145c8083904504d1c91a6e1a386f51
[ "Apache-2.0" ]
null
null
null
using System; using System.Threading.Tasks; using FluentAssertions; using Xunit; using Nut.Results.FluentAssertions; // ReSharper disable CheckNamespace namespace Nut.Results.Test { public class T_PassOnErrorTest { [Fact] public void TResult_成功の場合は例外が発生する() { Action act = () => Result.Ok(123).PassOnError<int, string>(); act.Should().Throw<InvalidOperationException>(); } [Fact] public void TResult_エラーの値が引き継がれる() { var expect = new Error(); Result.Error<int>(expect).PassOnError<int, string>().Should().BeError().And.Match(a => a == expect); } [Fact] public void TResult_Async_成功の場合は例外が発生する() { Func<Task> act = () => Result.Ok(123).AsTask().PassOnError<int, string>(); act.Should().Throw<InvalidOperationException>(); } [Fact] public async Task TResult_Async_エラーの値が引き継がれる() { var expect = new Error(); var error = await Result.Error<int>(expect).AsTask().PassOnError<int, string>(); error.Should().BeError().And.Match(a => a == expect); } [Fact] public void TResult_Async_引数がnullの場合は例外が発生する() { Func<Task> act = () => ResultUnsafeExtensions.PassOnError<int, string>(null!); act.Should().Throw<ArgumentNullException>(); } [Fact] public void 成功の場合は例外が発生する() { Action act = () => Result.Ok(123).PassOnError(); act.Should().Throw<InvalidOperationException>(); } [Fact] public void エラーの値が引き継がれる() { var expect = new Error(); Result.Error<int>(expect).PassOnError().Should().BeError().And.Match(a => a == expect); } [Fact] public void Async_成功の場合は例外が発生する() { Func<Task> act = () => Result.Ok(123).AsTask().PassOnError(); act.Should().Throw<InvalidOperationException>(); } [Fact] public async Task Async_エラーの値が引き継がれる() { var expect = new Error(); var error = await Result.Error<int>(expect).AsTask().PassOnError(); error.Should().BeError().And.Match(a => a == expect); } [Fact] public void Async_引数がnullの場合は例外が発生する() { Func<Task> act = () => ResultUnsafeExtensions.PassOnError((Task<Result<int>>)null!); act.Should().Throw<ArgumentNullException>(); } } }
31.729412
113
0.525399
1e41c53f0d63dcab43cc98d150c9880a8b2682bf
19,055
cs
C#
DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/DatabaseFolderProviderTests.cs
MaiklT/Dnn.Platform
5c457fc6368e0741516f7394f8b66bcba74634ed
[ "MIT" ]
null
null
null
DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/DatabaseFolderProviderTests.cs
MaiklT/Dnn.Platform
5c457fc6368e0741516f7394f8b66bcba74634ed
[ "MIT" ]
null
null
null
DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/DatabaseFolderProviderTests.cs
MaiklT/Dnn.Platform
5c457fc6368e0741516f7394f8b66bcba74634ed
[ "MIT" ]
null
null
null
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using DotNetNuke.Common.Utilities; using DotNetNuke.Data; using DotNetNuke.Entities.Users; using DotNetNuke.Services.FileSystem; using DotNetNuke.Tests.Utilities; using DotNetNuke.Tests.Utilities.Mocks; using Moq; using NUnit.Framework; using FileInfo = DotNetNuke.Services.FileSystem.FileInfo; namespace DotNetNuke.Tests.Core.Providers.Folder { [TestFixture] public class DatabaseFolderProviderTests { #region Private Variables private DatabaseFolderProvider _dfp; private Mock<DataProvider> _mockData; private Mock<IFolderInfo> _folderInfo; private Mock<IFileInfo> _fileInfo; private Mock<IFolderManager> _folderManager; private Mock<IFileManager> _fileManager; #endregion #region Setup & TearDown [SetUp] public void Setup() { this._dfp = new DatabaseFolderProvider(); this._mockData = MockComponentProvider.CreateDataProvider(); this._folderInfo = new Mock<IFolderInfo>(); this._fileInfo = new Mock<IFileInfo>(); this._folderManager = new Mock<IFolderManager>(); this._fileManager = new Mock<IFileManager>(); FolderManager.RegisterInstance(this._folderManager.Object); FileManager.RegisterInstance(this._fileManager.Object); } [TearDown] public void TearDown() { MockComponentProvider.ResetContainer(); } #endregion #region AddFile [Test] [ExpectedException(typeof(ArgumentNullException))] public void AddFile_Throws_On_Null_Folder() { var stream = new Mock<Stream>(); this._dfp.AddFile(null, Constants.FOLDER_ValidFileName, stream.Object); } [Test] [TestCase(null)] [TestCase("")] [ExpectedException(typeof(ArgumentException))] public void AddFile_Throws_On_NullOrEmpty_FileName(string fileName) { var stream = new Mock<Stream>(); this._dfp.AddFile(this._folderInfo.Object, fileName, stream.Object); } #endregion #region DeleteFile [Test] [ExpectedException(typeof(ArgumentNullException))] public void DeleteFile_Throws_On_Null_File() { this._dfp.DeleteFile(null); } [Test] public void DeleteFile_Calls_DataProvider_ClearFileContent() { this._fileInfo.Setup(fi => fi.FileId).Returns(Constants.FOLDER_ValidFileId); this._dfp.DeleteFile(this._fileInfo.Object); this._mockData.Verify(md => md.ClearFileContent(Constants.FOLDER_ValidFileId), Times.Once()); } #endregion #region FileExists [Test] [ExpectedException(typeof(ArgumentNullException))] public void ExistsFile_Throws_On_Null_Folder() { this._dfp.FileExists(null, Constants.FOLDER_ValidFileName); } [Test] [ExpectedException(typeof(ArgumentNullException))] public void ExistsFile_Throws_On_Null_FileName() { this._dfp.FileExists(this._folderInfo.Object, null); } [Test] public void ExistsFile_Returns_True_When_File_Exists() { this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); this._folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); this._fileManager.Setup(fm => fm.GetFile(this._folderInfo.Object, Constants.FOLDER_ValidFileName, true)).Returns(new FileInfo()); var result = this._dfp.FileExists(this._folderInfo.Object, Constants.FOLDER_ValidFileName); Assert.IsTrue(result); } [Test] public void ExistsFile_Returns_False_When_File_Does_Not_Exist() { this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); this._folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); FileInfo file = null; this._fileManager.Setup(fm => fm.GetFile(this._folderInfo.Object, Constants.FOLDER_ValidFileName)).Returns(file); var result = this._dfp.FileExists(this._folderInfo.Object, Constants.FOLDER_ValidFileName); Assert.IsFalse(result); } #endregion #region FolderExists [Test] [ExpectedException(typeof(ArgumentNullException))] public void ExistsFolder_Throws_On_Null_FolderMapping() { this._dfp.FolderExists(Constants.FOLDER_ValidFolderPath, null); } [Test] [ExpectedException(typeof(ArgumentNullException))] public void ExistsFolder_Throws_On_Null_FolderPath() { var folderMapping = new FolderMappingInfo(); this._dfp.FolderExists(null, folderMapping); } [Test] public void ExistsFolder_Returns_True_When_Folder_Exists() { var folderMapping = new FolderMappingInfo(); folderMapping.PortalID = Constants.CONTENT_ValidPortalId; this._folderManager.Setup(fm => fm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(new FolderInfo()); var result = this._dfp.FolderExists(Constants.FOLDER_ValidFolderRelativePath, folderMapping); Assert.IsTrue(result); } [Test] public void ExistsFolder_Returns_False_When_Folder_Does_Not_Exist() { var folderMapping = new FolderMappingInfo(); folderMapping.PortalID = Constants.CONTENT_ValidPortalId; FolderInfo folder = null; this._folderManager.Setup(fm => fm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(folder); var result = this._dfp.FolderExists(Constants.FOLDER_ValidFolderRelativePath, folderMapping); Assert.IsFalse(result); } #endregion #region GetFileAttributes [Test] public void GetFileAttributes_Returns_Null() { var result = this._dfp.GetFileAttributes(It.IsAny<IFileInfo>()); Assert.IsNull(result); } #endregion #region GetFiles [Test] [ExpectedException(typeof(ArgumentNullException))] public void GetFiles_Throws_On_Null_Folder() { this._dfp.GetFiles(null); } [Test] public void GetFiles_Calls_FolderManager_GetFilesByFolder() { var fileInfos = new List<IFileInfo> { new FileInfo { FileName = "" }, new FileInfo { FileName = "" }, new FileInfo { FileName = "" } }; this._folderManager.Setup(fm => fm.GetFiles(this._folderInfo.Object)).Returns((IList<IFileInfo>)fileInfos); this._dfp.GetFiles(this._folderInfo.Object); this._folderManager.Verify(fm => fm.GetFiles(this._folderInfo.Object), Times.Once()); } [Test] public void GetFiles_Count_Equals_DataProvider_GetFiles_Count() { var expectedFiles = new string[] { "", "", "" }; var fileInfos = new List<IFileInfo> { new FileInfo { FileName = "" }, new FileInfo { FileName = "" }, new FileInfo { FileName = "" } }; this._folderManager.Setup(fm => fm.GetFiles(this._folderInfo.Object)).Returns((IList<IFileInfo>)fileInfos); var files = this._dfp.GetFiles(this._folderInfo.Object); Assert.AreEqual(expectedFiles.Length, files.Length); } [Test] public void GetFiles_Returns_Valid_FileNames_When_Folder_Contains_Files() { var expectedFiles = new string[] { "file1.txt", "file2.txt", "file3.txt" }; var fileInfos = new List<IFileInfo> { new FileInfo { FileName = "file1.txt" }, new FileInfo { FileName = "file2.txt" }, new FileInfo { FileName = "file3.txt" } }; this._folderManager.Setup(fm => fm.GetFiles(this._folderInfo.Object)).Returns((IList<IFileInfo>)fileInfos); var files = this._dfp.GetFiles(this._folderInfo.Object); CollectionAssert.AreEqual(expectedFiles, files); } #endregion #region GetFileContent [Test] [ExpectedException(typeof(ArgumentNullException))] public void GetFileStream_Throws_On_Null_Folder() { this._dfp.GetFileStream(null, Constants.FOLDER_ValidFileName); } [Test] [ExpectedException(typeof(ArgumentException))] public void GetFileStream_Throws_On_NullOrEmpty_FileName() { this._dfp.GetFileStream(this._folderInfo.Object, null); } [Test] public void GetFileStream_Calls_FileManager_GetFile() { this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); this._folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); this._fileManager.Setup(fm => fm.GetFile(this._folderInfo.Object, Constants.FOLDER_ValidFileName)).Returns((IFileInfo)null); this._dfp.GetFileStream(this._folderInfo.Object, Constants.FOLDER_ValidFileName); this._fileManager.Verify(fm => fm.GetFile(this._folderInfo.Object, Constants.FOLDER_ValidFileName, true), Times.Once()); } [Test] public void GetFileStream_Returns_Valid_Stream_When_File_Exists() { var validFileBytes = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); this._folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); var _filesTable = new DataTable("Files"); _filesTable.Columns.Add("Content", typeof(byte[])); _filesTable.Rows.Add(validFileBytes); this._mockData.Setup(md => md.GetFileContent(Constants.FOLDER_ValidFileId)).Returns(_filesTable.CreateDataReader()); this._fileManager.Setup(fm => fm.GetFile(this._folderInfo.Object, Constants.FOLDER_ValidFileName, true)) .Returns(new FileInfo { FileId = Constants.FOLDER_ValidFileId, PortalId = Constants.CONTENT_ValidPortalId }); var result = this._dfp.GetFileStream(this._folderInfo.Object, Constants.FOLDER_ValidFileName); byte[] resultBytes; var buffer = new byte[16 * 1024]; using (var ms = new MemoryStream()) { int read; while ((read = result.Read(buffer, 0, buffer.Length)) > 0) { ms.Write(buffer, 0, read); } resultBytes = ms.ToArray(); } Assert.AreEqual(validFileBytes, resultBytes); } [Test] public void GetFileStream_Returns_Null_When_File_Does_Not_Exist() { this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); this._folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); this._fileManager.Setup(fm => fm.GetFile(this._folderInfo.Object, Constants.FOLDER_ValidFileName, It.IsAny<bool>())) .Returns((IFileInfo)null); var result = this._dfp.GetFileStream(this._folderInfo.Object, Constants.FOLDER_ValidFileName); Assert.IsNull(result); } #endregion #region GetFolderProviderIconPath [Test] public void GetImageUrl_Calls_IconControllerWrapper_IconURL() { var iconControllerWrapper = new Mock<IIconController>(); IconControllerWrapper.RegisterInstance(iconControllerWrapper.Object); this._dfp.GetFolderProviderIconPath(); iconControllerWrapper.Verify(icw => icw.IconURL("FolderDatabase", "32x32"), Times.Once()); } #endregion #region GetLastModificationTime [Test] public void GetLastModificationTime_Returns_Null_Date() { var expectedResult = Null.NullDate; var result = this._dfp.GetLastModificationTime(this._fileInfo.Object); Assert.AreEqual(expectedResult, result); } #endregion #region GetSubFolders [Test] [ExpectedException(typeof(ArgumentNullException))] public void GetSubFolders_Throws_On_Null_FolderMapping() { this._dfp.GetSubFolders(Constants.FOLDER_ValidFolderPath, null).ToList(); } [Test] [ExpectedException(typeof(ArgumentNullException))] public void GetSubFolders_Throws_On_Null_FolderPath() { var folderMappingInfo = new FolderMappingInfo(); this._dfp.GetSubFolders(null, folderMappingInfo).ToList(); } [Test] public void GetSubFolders_Calls_FolderManager_GetFoldersByParentFolder() { var folderMapping = new FolderMappingInfo(); folderMapping.PortalID = Constants.CONTENT_ValidPortalId; this._folderManager.Setup(fm => fm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(this._folderInfo.Object); this._folderManager.Setup(fm => fm.GetFolders(this._folderInfo.Object)).Returns(new List<IFolderInfo>()); this._dfp.GetSubFolders(Constants.FOLDER_ValidFolderRelativePath, folderMapping).ToList(); this._folderManager.Verify(fm => fm.GetFolders(this._folderInfo.Object), Times.Once()); } [Test] public void GetSubFolders_Count_Equals_DataProvider_GetFoldersByParentFolder_Count() { var folderMapping = new FolderMappingInfo(); folderMapping.PortalID = Constants.CONTENT_ValidPortalId; var subFolders = new List<IFolderInfo>() { new FolderInfo { FolderPath = Constants.FOLDER_ValidSubFolderRelativePath }, new FolderInfo { FolderPath = Constants.FOLDER_OtherValidSubFolderRelativePath } }; this._folderManager.Setup(fm => fm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(this._folderInfo.Object); this._folderManager.Setup(fm => fm.GetFolders(this._folderInfo.Object)).Returns(subFolders); var result = this._dfp.GetSubFolders(Constants.FOLDER_ValidFolderRelativePath, folderMapping).ToList(); Assert.AreEqual(subFolders.Count, result.Count); } [Test] public void GetSubFolders_Returns_Valid_SubFolders_When_Folder_Is_Not_Empty() { var expectedResult = new List<string> { Constants.FOLDER_ValidSubFolderRelativePath, Constants.FOLDER_OtherValidSubFolderRelativePath }; var folderMapping = new FolderMappingInfo(); folderMapping.PortalID = Constants.CONTENT_ValidPortalId; var subFolders = new List<IFolderInfo> { new FolderInfo { FolderPath = Constants.FOLDER_ValidSubFolderRelativePath }, new FolderInfo { FolderPath = Constants.FOLDER_OtherValidSubFolderRelativePath } }; this._folderManager.Setup(fm => fm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(this._folderInfo.Object); this._folderManager.Setup(fm => fm.GetFolders(this._folderInfo.Object)).Returns(subFolders); var result = this._dfp.GetSubFolders(Constants.FOLDER_ValidFolderRelativePath, folderMapping).ToList(); CollectionAssert.AreEqual(expectedResult, result); } #endregion #region IsInSync [Test] public void IsInSync_Returns_True() { var result = this._dfp.IsInSync(It.IsAny<IFileInfo>()); Assert.IsTrue(result); } #endregion #region SupportsFileAttributes [Test] public void SupportsFileAttributes_Returns_False() { var result = this._dfp.SupportsFileAttributes(); Assert.IsFalse(result); } #endregion #region UpdateFile [Test] [ExpectedException(typeof(ArgumentNullException))] public void UpdateFile_Throws_On_Null_Folder() { var stream = new Mock<Stream>(); this._dfp.UpdateFile(null, Constants.FOLDER_ValidFileName, stream.Object); } [Test] [TestCase(null)] [TestCase("")] [ExpectedException(typeof(ArgumentException))] public void UpdateFile_Throws_On_NullOrEmpty_FileName(string fileName) { var stream = new Mock<Stream>(); this._dfp.UpdateFile(this._folderInfo.Object, fileName, stream.Object); } [Test] public void UpdateFile_Calls_DataProvider_UpdateFileContent_When_File_Exists() { this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); this._folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); this._fileInfo.Setup(fi => fi.FileId).Returns(Constants.FOLDER_ValidFileId); this._fileManager.Setup(fm => fm.GetFile(this._folderInfo.Object, Constants.FOLDER_ValidFileName, true)).Returns(this._fileInfo.Object); this._dfp.UpdateFile(this._folderInfo.Object, Constants.FOLDER_ValidFileName, new MemoryStream(new byte[16 * 1024])); this._mockData.Verify(md => md.UpdateFileContent(Constants.FOLDER_ValidFileId, It.IsAny<byte[]>()), Times.Once()); } [Test] public void UpdateFile_Does_Not_Call_DataProvider_UpdateFileContent_When_File_Does_Not_Exist() { this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); this._folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); this._fileManager.Setup(fm => fm.GetFile(this._folderInfo.Object, Constants.FOLDER_ValidFileName, It.IsAny<bool>())).Returns((IFileInfo)null); this._dfp.UpdateFile(this._folderInfo.Object, Constants.FOLDER_ValidFileName, null); this._mockData.Verify(md => md.UpdateFileContent(It.IsAny<int>(), It.IsAny<byte[]>()), Times.Never()); } #endregion } }
35.156827
166
0.643296
1e426b52658c90ba778319abbd84895c12e71f7e
12,652
cs
C#
test/EntityFramework.SqlServerCompact.FunctionalTests/CustomConvertersSqlCeTest.cs
divega/EntityFramework.SqlServerCompact
dcf68990fc81d76de9186a31e3147adb777fc4e4
[ "Apache-2.0" ]
2
2018-12-13T12:55:48.000Z
2018-12-13T12:55:50.000Z
test/EntityFramework.SqlServerCompact.FunctionalTests/CustomConvertersSqlCeTest.cs
divega/EntityFramework.SqlServerCompact
dcf68990fc81d76de9186a31e3147adb777fc4e4
[ "Apache-2.0" ]
null
null
null
test/EntityFramework.SqlServerCompact.FunctionalTests/CustomConvertersSqlCeTest.cs
divega/EntityFramework.SqlServerCompact
dcf68990fc81d76de9186a31e3147adb777fc4e4
[ "Apache-2.0" ]
null
null
null
using System; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.TestUtilities; using Microsoft.EntityFrameworkCore.TestUtilities.Xunit; using Xunit; // ReSharper disable InconsistentNaming namespace Microsoft.EntityFrameworkCore { [SqlServerCondition(SqlServerCondition.IsNotSqlAzure)] public class CustomConvertersSqlCeTest : CustomConvertersTestBase<CustomConvertersSqlCeTest.CustomConvertersSqlCeFixture> { public CustomConvertersSqlCeTest(CustomConvertersSqlCeFixture fixture) : base(fixture) { } //System.Data.SqlServerCe.SqlCeException : The data was truncated while converting from one data type to another. [ Name of function(if known) = ] [Fact(Skip = "SQLCE limitation")] public override void Can_insert_and_read_with_max_length_set() { base.Can_insert_and_read_with_max_length_set(); } //System.Data.SqlServerCe.SqlCeException : The data was truncated while converting from one data type to another. [ Name of function(if known) = ] [Fact(Skip = "SQLCE limitation")] public override void Can_perform_query_with_max_length() { base.Can_perform_query_with_max_length(); } [ConditionalFact] public virtual void Columns_have_expected_data_types() { var actual = BuiltInDataTypesSqlCeTest.QueryForColumnTypes(CreateContext()); const string expected = @"BinaryForeignKeyDataType.BinaryKeyDataTypeId ---> [nullable varbinary] [MaxLength = 512] BinaryForeignKeyDataType.Id ---> [int] [Precision = 10] BinaryKeyDataType.Id ---> [varbinary] [MaxLength = 512] BuiltInDataTypes.Enum16 ---> [bigint] [Precision = 19] BuiltInDataTypes.Enum32 ---> [bigint] [Precision = 19] BuiltInDataTypes.Enum64 ---> [bigint] [Precision = 19] BuiltInDataTypes.Enum8 ---> [nvarchar] [MaxLength = 4000] BuiltInDataTypes.EnumS8 ---> [nvarchar] [MaxLength = 24] BuiltInDataTypes.EnumU16 ---> [numeric] [Precision = 20 Scale = 0] BuiltInDataTypes.EnumU32 ---> [numeric] [Precision = 20 Scale = 0] BuiltInDataTypes.EnumU64 ---> [numeric] [Precision = 20 Scale = 0] BuiltInDataTypes.Id ---> [int] [Precision = 10] BuiltInDataTypes.PartitionId ---> [bigint] [Precision = 19] BuiltInDataTypes.TestBoolean ---> [nvarchar] [MaxLength = 4] BuiltInDataTypes.TestByte ---> [int] [Precision = 10] BuiltInDataTypes.TestCharacter ---> [int] [Precision = 10] BuiltInDataTypes.TestDateTime ---> [bigint] [Precision = 19] BuiltInDataTypes.TestDateTimeOffset ---> [bigint] [Precision = 19] BuiltInDataTypes.TestDecimal ---> [varbinary] [MaxLength = 16] BuiltInDataTypes.TestDouble ---> [numeric] [Precision = 26 Scale = 16] BuiltInDataTypes.TestInt16 ---> [bigint] [Precision = 19] BuiltInDataTypes.TestInt32 ---> [bigint] [Precision = 19] BuiltInDataTypes.TestInt64 ---> [bigint] [Precision = 19] BuiltInDataTypes.TestSignedByte ---> [numeric] [Precision = 18 Scale = 2] BuiltInDataTypes.TestSingle ---> [float] [Precision = 53] BuiltInDataTypes.TestTimeSpan ---> [float] [Precision = 53] BuiltInDataTypes.TestUnsignedInt16 ---> [numeric] [Precision = 20 Scale = 0] BuiltInDataTypes.TestUnsignedInt32 ---> [numeric] [Precision = 20 Scale = 0] BuiltInDataTypes.TestUnsignedInt64 ---> [bigint] [Precision = 19] BuiltInDataTypesShadow.Enum16 ---> [bigint] [Precision = 19] BuiltInDataTypesShadow.Enum32 ---> [bigint] [Precision = 19] BuiltInDataTypesShadow.Enum64 ---> [bigint] [Precision = 19] BuiltInDataTypesShadow.Enum8 ---> [nvarchar] [MaxLength = 4000] BuiltInDataTypesShadow.EnumS8 ---> [nvarchar] [MaxLength = 4000] BuiltInDataTypesShadow.EnumU16 ---> [numeric] [Precision = 20 Scale = 0] BuiltInDataTypesShadow.EnumU32 ---> [numeric] [Precision = 20 Scale = 0] BuiltInDataTypesShadow.EnumU64 ---> [numeric] [Precision = 20 Scale = 0] BuiltInDataTypesShadow.Id ---> [int] [Precision = 10] BuiltInDataTypesShadow.PartitionId ---> [bigint] [Precision = 19] BuiltInDataTypesShadow.TestBoolean ---> [nvarchar] [MaxLength = 4000] BuiltInDataTypesShadow.TestByte ---> [int] [Precision = 10] BuiltInDataTypesShadow.TestCharacter ---> [int] [Precision = 10] BuiltInDataTypesShadow.TestDateTime ---> [bigint] [Precision = 19] BuiltInDataTypesShadow.TestDateTimeOffset ---> [bigint] [Precision = 19] BuiltInDataTypesShadow.TestDecimal ---> [varbinary] [MaxLength = 16] BuiltInDataTypesShadow.TestDouble ---> [numeric] [Precision = 26 Scale = 16] BuiltInDataTypesShadow.TestInt16 ---> [bigint] [Precision = 19] BuiltInDataTypesShadow.TestInt32 ---> [bigint] [Precision = 19] BuiltInDataTypesShadow.TestInt64 ---> [bigint] [Precision = 19] BuiltInDataTypesShadow.TestSignedByte ---> [numeric] [Precision = 18 Scale = 2] BuiltInDataTypesShadow.TestSingle ---> [float] [Precision = 53] BuiltInDataTypesShadow.TestTimeSpan ---> [float] [Precision = 53] BuiltInDataTypesShadow.TestUnsignedInt16 ---> [numeric] [Precision = 20 Scale = 0] BuiltInDataTypesShadow.TestUnsignedInt32 ---> [numeric] [Precision = 20 Scale = 0] BuiltInDataTypesShadow.TestUnsignedInt64 ---> [bigint] [Precision = 19] BuiltInNullableDataTypes.Enum16 ---> [nullable bigint] [Precision = 19] BuiltInNullableDataTypes.Enum32 ---> [nullable bigint] [Precision = 19] BuiltInNullableDataTypes.Enum64 ---> [nullable bigint] [Precision = 19] BuiltInNullableDataTypes.Enum8 ---> [nullable nvarchar] [MaxLength = 4000] BuiltInNullableDataTypes.EnumS8 ---> [nullable nvarchar] [MaxLength = 4000] BuiltInNullableDataTypes.EnumU16 ---> [nullable numeric] [Precision = 20 Scale = 0] BuiltInNullableDataTypes.EnumU32 ---> [nullable numeric] [Precision = 20 Scale = 0] BuiltInNullableDataTypes.EnumU64 ---> [nullable numeric] [Precision = 20 Scale = 0] BuiltInNullableDataTypes.Id ---> [int] [Precision = 10] BuiltInNullableDataTypes.PartitionId ---> [bigint] [Precision = 19] BuiltInNullableDataTypes.TestByteArray ---> [nullable image] [MaxLength = 1073741823] BuiltInNullableDataTypes.TestNullableBoolean ---> [nullable nvarchar] [MaxLength = 4000] BuiltInNullableDataTypes.TestNullableByte ---> [nullable int] [Precision = 10] BuiltInNullableDataTypes.TestNullableCharacter ---> [nullable int] [Precision = 10] BuiltInNullableDataTypes.TestNullableDateTime ---> [nullable bigint] [Precision = 19] BuiltInNullableDataTypes.TestNullableDateTimeOffset ---> [nullable bigint] [Precision = 19] BuiltInNullableDataTypes.TestNullableDecimal ---> [nullable varbinary] [MaxLength = 16] BuiltInNullableDataTypes.TestNullableDouble ---> [nullable numeric] [Precision = 26 Scale = 16] BuiltInNullableDataTypes.TestNullableInt16 ---> [nullable bigint] [Precision = 19] BuiltInNullableDataTypes.TestNullableInt32 ---> [nullable bigint] [Precision = 19] BuiltInNullableDataTypes.TestNullableInt64 ---> [nullable bigint] [Precision = 19] BuiltInNullableDataTypes.TestNullableSignedByte ---> [nullable numeric] [Precision = 18 Scale = 2] BuiltInNullableDataTypes.TestNullableSingle ---> [nullable float] [Precision = 53] BuiltInNullableDataTypes.TestNullableTimeSpan ---> [nullable float] [Precision = 53] BuiltInNullableDataTypes.TestNullableUnsignedInt16 ---> [nullable numeric] [Precision = 20 Scale = 0] BuiltInNullableDataTypes.TestNullableUnsignedInt32 ---> [nullable numeric] [Precision = 20 Scale = 0] BuiltInNullableDataTypes.TestNullableUnsignedInt64 ---> [nullable bigint] [Precision = 19] BuiltInNullableDataTypes.TestString ---> [nullable nvarchar] [MaxLength = 4000] BuiltInNullableDataTypesShadow.Enum16 ---> [nullable smallint] [Precision = 5] BuiltInNullableDataTypesShadow.Enum32 ---> [nullable int] [Precision = 10] BuiltInNullableDataTypesShadow.Enum64 ---> [nullable bigint] [Precision = 19] BuiltInNullableDataTypesShadow.Enum8 ---> [nullable tinyint] [Precision = 3] BuiltInNullableDataTypesShadow.EnumS8 ---> [nullable smallint] [Precision = 5] BuiltInNullableDataTypesShadow.EnumU16 ---> [nullable int] [Precision = 10] BuiltInNullableDataTypesShadow.EnumU32 ---> [nullable bigint] [Precision = 19] BuiltInNullableDataTypesShadow.EnumU64 ---> [nullable numeric] [Precision = 20 Scale = 0] BuiltInNullableDataTypesShadow.Id ---> [int] [Precision = 10] BuiltInNullableDataTypesShadow.PartitionId ---> [int] [Precision = 10] BuiltInNullableDataTypesShadow.TestByteArray ---> [nullable image] [MaxLength = 1073741823] BuiltInNullableDataTypesShadow.TestNullableBoolean ---> [nullable bit] [Precision = 1 Scale = 0] BuiltInNullableDataTypesShadow.TestNullableByte ---> [nullable tinyint] [Precision = 3] BuiltInNullableDataTypesShadow.TestNullableCharacter ---> [nullable nvarchar] [MaxLength = 1] BuiltInNullableDataTypesShadow.TestNullableDateTime ---> [nullable datetime] [Precision = 23 Scale = 3] BuiltInNullableDataTypesShadow.TestNullableDateTimeOffset ---> [nullable nvarchar] [MaxLength = 48] BuiltInNullableDataTypesShadow.TestNullableDecimal ---> [nullable numeric] [Precision = 18 Scale = 2] BuiltInNullableDataTypesShadow.TestNullableDouble ---> [nullable float] [Precision = 53] BuiltInNullableDataTypesShadow.TestNullableInt16 ---> [nullable smallint] [Precision = 5] BuiltInNullableDataTypesShadow.TestNullableInt32 ---> [nullable int] [Precision = 10] BuiltInNullableDataTypesShadow.TestNullableInt64 ---> [nullable bigint] [Precision = 19] BuiltInNullableDataTypesShadow.TestNullableSignedByte ---> [nullable smallint] [Precision = 5] BuiltInNullableDataTypesShadow.TestNullableSingle ---> [nullable real] [Precision = 24] BuiltInNullableDataTypesShadow.TestNullableTimeSpan ---> [nullable nvarchar] [MaxLength = 48] BuiltInNullableDataTypesShadow.TestNullableUnsignedInt16 ---> [nullable int] [Precision = 10] BuiltInNullableDataTypesShadow.TestNullableUnsignedInt32 ---> [nullable bigint] [Precision = 19] BuiltInNullableDataTypesShadow.TestNullableUnsignedInt64 ---> [nullable numeric] [Precision = 20 Scale = 0] BuiltInNullableDataTypesShadow.TestString ---> [nullable nvarchar] [MaxLength = 4000] EmailTemplate.Id ---> [uniqueidentifier] EmailTemplate.TemplateType ---> [int] [Precision = 10] Load.Fuel ---> [float] [Precision = 53] Load.LoadId ---> [int] [Precision = 10] MaxLengthDataTypes.ByteArray5 ---> [nullable varbinary] [MaxLength = 7] MaxLengthDataTypes.ByteArray9000 ---> [nullable nvarchar] [MaxLength = 4000] MaxLengthDataTypes.Id ---> [int] [Precision = 10] MaxLengthDataTypes.String3 ---> [nullable nvarchar] [MaxLength = 12] MaxLengthDataTypes.String9000 ---> [nullable varbinary] [MaxLength = 4000] StringForeignKeyDataType.Id ---> [int] [Precision = 10] StringForeignKeyDataType.StringKeyDataTypeId ---> [nullable nvarchar] [MaxLength = 256] StringKeyDataType.Id ---> [nvarchar] [MaxLength = 256] StringListDataType.Id ---> [int] [Precision = 10] StringListDataType.Strings ---> [nullable nvarchar] [MaxLength = 4000] UnicodeDataTypes.Id ---> [int] [Precision = 10] UnicodeDataTypes.StringAnsi ---> [nullable nvarchar] [MaxLength = 4000] UnicodeDataTypes.StringAnsi3 ---> [nullable nvarchar] [MaxLength = 3] UnicodeDataTypes.StringAnsi9000 ---> [nullable nvarchar] [MaxLength = 4000] UnicodeDataTypes.StringDefault ---> [nullable nvarchar] [MaxLength = 4000] UnicodeDataTypes.StringUnicode ---> [nullable nvarchar] [MaxLength = 4000] User.Email ---> [nullable nvarchar] [MaxLength = 4000] User.Id ---> [uniqueidentifier] "; Assert.Equal(expected, actual, ignoreLineEndingDifferences: true); } public class CustomConvertersSqlCeFixture : CustomConvertersFixtureBase { public override bool StrictEquality => true; public override bool SupportsAnsi => false; public override bool SupportsUnicodeToAnsiConversion => false; public override bool SupportsLargeStringComparisons => true; public override int LongStringLength => 4000; protected override ITestStoreFactory TestStoreFactory => SqlCeTestStoreFactory.Instance; public override bool SupportsBinaryKeys => true; public override DateTime DefaultDateTime => new DateTime(1753, 1, 1); public override DbContextOptionsBuilder AddOptions(DbContextOptionsBuilder builder) => base .AddOptions(builder) .ConfigureWarnings( c => c.Log(RelationalEventId.QueryClientEvaluationWarning)); //.Log(SqlServerEventId.DecimalTypeDefaultWarning)); protected override void OnModelCreating(ModelBuilder modelBuilder, DbContext context) { base.OnModelCreating(modelBuilder, context); modelBuilder.Entity<BuiltInDataTypes>().Property(e => e.TestBoolean).IsFixedLength(); } } } }
60.535885
155
0.744309
1e472aa4d5b4bc48ad151c2e54848e51d31a4c18
3,751
cs
C#
src/Jeebs.Auth.Data/AuthDataProvider.cs
bencgreen/jeebs
8e15b051bf09f5cd51e18e9e5de9c923ee80bff9
[ "MIT" ]
3
2020-08-19T17:39:16.000Z
2021-03-17T10:09:31.000Z
src/Jeebs.Auth.Data/AuthDataProvider.cs
bencgreen/jeebs
8e15b051bf09f5cd51e18e9e5de9c923ee80bff9
[ "MIT" ]
null
null
null
src/Jeebs.Auth.Data/AuthDataProvider.cs
bencgreen/jeebs
8e15b051bf09f5cd51e18e9e5de9c923ee80bff9
[ "MIT" ]
1
2021-04-05T11:40:46.000Z
2021-04-05T11:40:46.000Z
// Jeebs Rapid Application Development // Copyright (c) bfren.uk - licensed under https://mit.bfren.uk/2013 using System.Linq; using System.Threading.Tasks; using Jeebs.Auth.Data; using Jeebs.Auth.Data.Entities; using Jeebs.Cryptography; using Jeebs.Linq; using static F.OptionF; namespace Jeebs.Auth { /// <inheritdoc cref="IAuthDataProvider{TUserEntity, TRoleEntity, TUserRoleEntity}"/> public interface IAuthDataProvider : IAuthDataProvider<AuthUserEntity, AuthRoleEntity, AuthUserRoleEntity> { } /// <inheritdoc cref="IAuthDataProvider{TUserEntity, TRoleEntity, TUserRoleEntity}"/> public sealed class AuthDataProvider : IAuthDataProvider { /// <inheritdoc/> public IAuthUserRepository<AuthUserEntity> User { get; private init; } /// <inheritdoc/> public IAuthRoleRepository<AuthRoleEntity> Role { get; private init; } /// <inheritdoc/> public IAuthUserRoleRepository<AuthUserRoleEntity> UserRole { get; private init; } /// <inheritdoc/> public IAuthDbQuery Query { get; private init; } /// <summary> /// Inject dependencies /// </summary> /// <param name="user">IAuthUserRepository</param> /// <param name="role">IAuthRoleRepository</param> /// <param name="userRole">IAuthUserRoleRepository</param> /// <param name="query">IAuthDbQuery</param> public AuthDataProvider( IAuthUserRepository user, IAuthRoleRepository role, IAuthUserRoleRepository userRole, IAuthDbQuery query ) => (User, Role, UserRole, Query) = (user, role, userRole, query); /// <inheritdoc/> public async Task<Option<TModel>> ValidateUserAsync<TModel>(string email, string password) where TModel : IAuthUser { // Check email if (string.IsNullOrEmpty(email)) { return None<TModel, Msg.NullOrEmptyEmailMsg>(); } // Check password if (string.IsNullOrEmpty(password)) { return None<TModel, Msg.InvalidPasswordMsg>(); } // Get user for authentication foreach (var user in await User.RetrieveAsync<AuthUserEntity>(email).ConfigureAwait(false)) { // Verify the user is enabled if (!user.IsEnabled) { return None<TModel>(new Msg.UserNotEnabledMsg(email)); } // Verify the entered password if (!user.PasswordHash.VerifyPassword(password)) { return None<TModel, Msg.InvalidPasswordMsg>(); } // Get user model return await User.RetrieveAsync<TModel>(user.Id).ConfigureAwait(false); } // User not found return None<TModel>(new Msg.UserNotFoundMsg(email)); } /// <inheritdoc/> public Task<Option<TUser>> RetrieveUserWithRolesAsync<TUser, TRole>(AuthUserId id) where TUser : AuthUserWithRoles<TRole> where TRole : IAuthRole => from u in User.RetrieveAsync<TUser>(id) from r in Query.GetRolesForUserAsync<TRole>(u.Id) select u with { Roles = r }; /// <inheritdoc/> public Task<Option<TUser>> RetrieveUserWithRolesAsync<TUser, TRole>(string email) where TUser : AuthUserWithRoles<TRole> where TRole : IAuthRole => from u in User.RetrieveAsync<TUser>(email) from r in Query.GetRolesForUserAsync<TRole>(u.Id) select u with { Roles = r }; /// <summary>Messages</summary> public static class Msg { /// <summary>Invalid password</summary> public sealed record InvalidPasswordMsg : IMsg { } /// <summary>Null or empty email address</summary> public sealed record NullOrEmptyEmailMsg : IMsg { } /// <summary>Null or empty password</summary> public sealed record NullOrEmptyPasswordMsg : IMsg { } /// <summary>User not enabled</summary> public sealed record UserNotEnabledMsg(string Value) : WithValueMsg<string> { } /// <summary>User not found</summary> public sealed record UserNotFoundMsg(string EmailAddress) : NotFoundMsg { } } } }
30.495935
107
0.711277
1e4890754113b7ee6788dbc743bc743cdac4f371
2,054
cs
C#
TabletopTweaks-Base/NewContent/AlternateCapstones/Bloodrager.cs
Vek17/TabletopTweaks-Base
b7f727297c6efa0dbbbb2a39bfb16a8e67625da7
[ "MIT" ]
null
null
null
TabletopTweaks-Base/NewContent/AlternateCapstones/Bloodrager.cs
Vek17/TabletopTweaks-Base
b7f727297c6efa0dbbbb2a39bfb16a8e67625da7
[ "MIT" ]
6
2022-03-27T17:33:46.000Z
2022-03-30T13:23:05.000Z
TabletopTweaks-Base/NewContent/AlternateCapstones/Bloodrager.cs
Vek17/TabletopTweaks-Base
b7f727297c6efa0dbbbb2a39bfb16a8e67625da7
[ "MIT" ]
1
2022-03-30T08:25:57.000Z
2022-03-30T08:25:57.000Z
using Kingmaker.Blueprints.Classes; using Kingmaker.Blueprints.Classes.Selection; using TabletopTweaks.Core.NewComponents.Prerequisites; using TabletopTweaks.Core.Utilities; using static TabletopTweaks.Base.Main; namespace TabletopTweaks.Base.NewContent.AlternateCapstones { internal class Bloodrager { public static BlueprintFeatureSelection BloodragerAlternateCapstone = null; public static void AddAlternateCapstones() { var BloodragerMightyBloodrage = BlueprintTools.GetBlueprint<BlueprintFeature>("a6cd3eca05ee24840ab159ca47b4cd88"); BloodragerAlternateCapstone = Helpers.CreateBlueprint<BlueprintFeatureSelection>(TTTContext, "BloodragerAlternateCapstone", bp => { bp.SetName(TTTContext, "Capstone"); bp.SetDescription(TTTContext, "When a character reaches the 20th level of a class, she gains a powerful class feature or ability, " + "sometimes referred to as a capstone. The following section provides new capstones for characters to select at 20th level. " + "A character can select one of the following capstones in place of the capstone provided by her class. " + "A character can’t select a new capstone if she has previously traded away her class capstone via an archetype. " + "Clerics and wizards can receive a capstone at 20th level, despite not having one to begin with."); bp.IsClassFeature = true; bp.IgnorePrerequisites = true; bp.m_Icon = BloodragerMightyBloodrage.Icon; bp.Ranks = 1; bp.AddPrerequisite<PrerequisiteInPlayerParty>(c => { c.CheckInProgression = true; c.HideInUI = true; }); bp.AddFeatures( BloodragerMightyBloodrage, Generic.PerfectBodyFlawlessMindProgression, Generic.GreatBeastMasterFeature ); }); } } }
55.513514
149
0.654333
1e49a081dd26ed29f0ca7ee571ba6e8fdf1038fa
1,819
cs
C#
src/AdventOfCode/Puzzle.cs
andreibsk/AdventOfCode
d85010456733315c3ae6107b162c80c777935435
[ "MIT" ]
2
2019-12-21T21:38:16.000Z
2020-11-17T12:11:42.000Z
src/AdventOfCode/Puzzle.cs
andreibsk/AdventOfCode
d85010456733315c3ae6107b162c80c777935435
[ "MIT" ]
1
2021-03-02T18:28:09.000Z
2021-03-02T18:28:09.000Z
src/AdventOfCode/Puzzle.cs
andreibsk/AdventOfCode
d85010456733315c3ae6107b162c80c777935435
[ "MIT" ]
1
2019-12-17T17:01:03.000Z
2019-12-17T17:01:03.000Z
using System.Reflection; using System.Runtime.ExceptionServices; namespace AdventOfCode; public abstract class Puzzle { protected Puzzle(string[] input) { Input = input; } public abstract DateTime Date { get; } public IReadOnlyList<string> Input { get; } public string? Solution { get; protected set; } public string? SolutionPartTwo { get; protected set; } public abstract string Title { get; } public static TPuzzle Construct<TPuzzle>(string input) where TPuzzle : Puzzle => Construct<TPuzzle>(new[] { input }); public static TPuzzle Construct<TPuzzle>(string[] input) where TPuzzle : Puzzle => Construct<TPuzzle>(input, config: null); public static TPuzzle Construct<TPuzzle>(string[] input, string? config) where TPuzzle : Puzzle { return (TPuzzle)Construct(typeof(TPuzzle), input, config); } public static Puzzle Construct(Type type, string[] input) => Construct(type, input, config: null); public static Puzzle Construct(Type type, string[] input, string? config) { if (!type.IsSubclassOf(typeof(Puzzle))) throw new ArgumentException(); try { return config == null ? (Puzzle)type.GetConstructor(new[] { typeof(string[]) })!.Invoke(new[] { input }) : (Puzzle)type.GetConstructor(new[] { typeof(string[]), typeof(string) })!.Invoke(new object[] { input, config }); } catch (TargetInvocationException e) { ExceptionDispatchInfo.Capture(e.GetBaseException()).Throw(); throw new InvalidOperationException("Unexpected exception catched."); } } public static Type? GetType(DateTime date) { var type = Type.GetType($"{nameof(AdventOfCode)}.Year{date.Year:00}.Day{date.Day:00}"); return type?.IsSubclassOf(typeof(Puzzle)) == true ? type : null; } public abstract string? CalculateSolution(); public abstract string? CalculateSolutionPartTwo(); }
31.362069
124
0.720176
1e4a438cd2c891f80c93cf7419cce17ea3de8ae1
7,355
cs
C#
ImportData/ImportData/Program.cs
mykebates/Help-SGF
3c3b93b330acda59bbbb56cc9c9a222cb9d1d603
[ "Unlicense" ]
null
null
null
ImportData/ImportData/Program.cs
mykebates/Help-SGF
3c3b93b330acda59bbbb56cc9c9a222cb9d1d603
[ "Unlicense" ]
null
null
null
ImportData/ImportData/Program.cs
mykebates/Help-SGF
3c3b93b330acda59bbbb56cc9c9a222cb9d1d603
[ "Unlicense" ]
null
null
null
using Nest; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Configuration; using System.Text; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace ImportData { public class SearchClient { private string _ES_REPO = ""; private string _ES_SERVER = ""; private ElasticClient _Server; public string ES_REPO { get { return _ES_REPO; } } public string ES_SERVER { get { return _ES_SERVER; } } public ElasticClient Server { get { return _Server; } } public SearchClient() { _ES_REPO = ConfigurationManager.AppSettings["ES_REPO"] ?? "hack4goodsgf"; _ES_SERVER = ConfigurationManager.AppSettings["ES_SERVER"] ?? "http://localhost:9200"; var node = new Uri(_ES_SERVER); _Server = new ElasticClient(new Nest.ConnectionSettings(node).DefaultIndex(_ES_REPO)); } } class Program { protected static int NumSent; static void Main(string[] args) { ImportShelters(); ImportOtherResources(); } private static void ImportShelters() { var client = new SearchClient(); string fileData = System.IO.File.ReadAllText(@"C:\inetpub\domains\Help SGF\Information and Resources\Data\Hack4GoodSGF\real direcoty.json"); IList<ShelterRecordWithTags> resources = JsonConvert.DeserializeObject<IList<ShelterRecordWithTags>>(fileData); var count = 0; foreach (var resource in resources) { count++; resource.Resource.Location = new GeoPoint(); resource.Resource.Location.lat = resource.Resource.Latitude; resource.Resource.Location.lon = resource.Resource.Longitude; if(count % 2 == 0) { resource.Resource.Restriction = resource.Tags; } } var pages = (resources.Count / 250) + (resources.Count % 250 > 0 ? 1 : 0); for (int i = 0; i < pages; i++) { IList<Resource> docsToIndex = new List<Resource>(); foreach (var asset in resources.Skip(250 * i).Take(250).ToList()) { var docToIndex = asset.Resource; docsToIndex.Add(docToIndex); } Interlocked.Exchange(ref NumSent, 0); var tasks = new List<Task>(); var t = client.Server.IndexManyAsync<Resource>(docsToIndex, client.ES_REPO) .ContinueWith(tt => { Interlocked.Add(ref NumSent, 1024); }); tasks.Add(t); Task.WaitAll(tasks.ToArray()); } } private static void ImportOtherResources() { var client = new SearchClient(); string fileData = System.IO.File.ReadAllText(@"C:\inetpub\domains\Help SGF\Information and Resources\Data\wifi_hotspots.json"); IList<OtherResource> resources = JsonConvert.DeserializeObject<IList<OtherResource>>(fileData); foreach (var resource in resources) { resource.location = new GeoPoint(); resource.location.lat = resource.lat; resource.location.lon = resource.lon; } var pages = (resources.Count / 250) + (resources.Count % 250 > 0 ? 1 : 0); for (int i = 0; i < pages; i++) { IList<OtherResource> docsToIndex = new List<OtherResource>(); foreach (var asset in resources.Skip(250 * i).Take(250).ToList()) { var docToIndex = new OtherResource(); docToIndex.resource_type = "wifi"; docToIndex.name = asset.name; docToIndex.lat = asset.lat; docToIndex.lon = asset.lon; docToIndex.location = asset.location; docsToIndex.Add(docToIndex); } Interlocked.Exchange(ref NumSent, 0); var tasks = new List<Task>(); var t = client.Server.IndexManyAsync<OtherResource>(docsToIndex, client.ES_REPO) .ContinueWith(tt => { Interlocked.Add(ref NumSent, 1024); }); tasks.Add(t); Task.WaitAll(tasks.ToArray()); } } } public class ShelterRecordWithTags { public Resource Resource { get; set; } public IList<string> Tags { get; set; } } [ElasticsearchType(Name="shelter")] public class Resource { [String(Name = "id")] public string ID { get; set; } [String(Name = "name")] public string Name { get; set; } [String(Name = "address1")] public string Address1 { get; set; } [String(Name = "address2")] public string Address2 { get; set; } [String(Name = "city")] public string City { get; set; } [String(Name = "state")] public string State { get; set; } [String(Name = "zip")] public string Zip { get; set; } [String(Name = "county")] public string County { get; set; } [String(Name = "phone")] public string Phone { get; set; } [String(Name = "fax")] public string Fax { get; set; } [String(Name = "tty")] public string TTY { get; set; } [String(Name = "tollfree")] public string Tollfree { get; set; } [String(Name = "hotline")] public string Hotline { get; set; } [String(Name = "email")] public string Email { get; set; } [String(Name = "webpage")] public string Webpage { get; set; } [String(Name = "facebookname")] public string FacebookName { get; set; } [String(Name = "facebookurl")] public string FacebookUrl { get; set; } [String(Name = "twitter")] public string Twitter { get; set; } [String(Name = "services")] public string Services { get; set; } [Number(NumberType.Double, Name = "lat")] public double Latitude { get; set; } [Number(NumberType.Double, Name = "lon")] public double Longitude { get; set; } [GeoPoint(Name = "location")] public GeoPoint Location { get; set; } [String(Name = "restriction")] public IList<string> Restriction { get; set; } } [ElasticsearchType(Name = "other_resources")] public class OtherResource { public string name { get; set; } public string resource_type { get; set; } [Number(NumberType.Double, Name = "lat")] public double lat { get; set; } [Number(NumberType.Double, Name = "lon")] public double lon { get; set; } [GeoPoint(Name="location")] public GeoPoint location { get; set; } } public class GeoPoint { [Number(NumberType.Double, Name = "lat")] public double lat { get; set; } [Number(NumberType.Double, Name = "lon")] public double lon { get; set; } } }
32.258772
152
0.541264
1e4dd4e7ee9acbbf6facbfe2c16e3052a198ebb7
2,633
cs
C#
src/Core/Validation.Tests/VariablesAreInputTypesRuleTests.cs
jbray1982/hotchocolate
20ee3361fe432c4825077208f2cbd567b6abda08
[ "MIT" ]
1
2021-08-19T13:27:10.000Z
2021-08-19T13:27:10.000Z
src/Core/Validation.Tests/VariablesAreInputTypesRuleTests.cs
jbray1982/hotchocolate
20ee3361fe432c4825077208f2cbd567b6abda08
[ "MIT" ]
null
null
null
src/Core/Validation.Tests/VariablesAreInputTypesRuleTests.cs
jbray1982/hotchocolate
20ee3361fe432c4825077208f2cbd567b6abda08
[ "MIT" ]
null
null
null
using HotChocolate.Language; using Xunit; namespace HotChocolate.Validation { public class VariablesAreInputTypesRuleTests : ValidationTestBase { public VariablesAreInputTypesRuleTests() : base(new VariablesAreInputTypesRule()) { } [Fact] public void QueriesWithValidVariableTypes() { // arrange Schema schema = ValidationUtils.CreateSchema(); DocumentNode query = Parser.Default.Parse(@" query takesBoolean($atOtherHomes: Boolean) { dog { isHousetrained(atOtherHomes: $atOtherHomes) } } query takesComplexInput($complexInput: ComplexInput) { findDog(complex: $complexInput) { name } } query TakesListOfBooleanBang($booleans: [Boolean!]) { booleanList(booleanListArg: $booleans) } "); // act QueryValidationResult result = Rule.Validate(schema, query); // assert Assert.False(result.HasErrors); } [Fact] public void QueriesWithInvalidVariableTypes() { // arrange Schema schema = ValidationUtils.CreateSchema(); DocumentNode query = Parser.Default.Parse(@" query takesCat($cat: Cat) { # ... } query takesDogBang($dog: Dog!) { # ... } query takesListOfPet($pets: [Pet]) { # ... } query takesCatOrDog($catOrDog: CatOrDog) { # ... } "); // act QueryValidationResult result = Rule.Validate(schema, query); // assert Assert.True(result.HasErrors); Assert.Collection(result.Errors, t => Assert.Equal( "The type of variable `cat` is not an input type.", t.Message), t => Assert.Equal( "The type of variable `dog` is not an input type.", t.Message), t => Assert.Equal( "The type of variable `pets` is not an input type.", t.Message), t => Assert.Equal( "The type of variable `catOrDog` is not an input type.", t.Message)); } } }
29.920455
76
0.456893
1e510b93f5959fe77fc772522ab361d8866a601f
4,011
cs
C#
GPS Listener Parser/DBLogic/GPSdata.cs
ananth7453/FMB920Parser
2d6143088cc0d9f53673091917303e0f7f653a8d
[ "Apache-2.0" ]
4
2019-01-31T09:44:37.000Z
2022-03-14T10:56:24.000Z
GPS Listener Parser/DBLogic/GPSdata.cs
ananth7453/FMB920Parser
2d6143088cc0d9f53673091917303e0f7f653a8d
[ "Apache-2.0" ]
2
2020-07-25T17:46:45.000Z
2020-08-11T05:27:40.000Z
GPS Listener Parser/DBLogic/GPSdata.cs
ananth7453/FMB920Parser
2d6143088cc0d9f53673091917303e0f7f653a8d
[ "Apache-2.0" ]
2
2019-02-04T23:14:04.000Z
2021-01-14T16:13:12.000Z
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace GPSParser.DBLogic { public class GPSdata { private int _ID; public int ID { get { return _ID; } set { _ID = value; } } private string _IMEI; public string IMEI { get { return _IMEI; } set { _IMEI = value; } } private System.Nullable<System.DateTime> _timestamp; public System.Nullable<System.DateTime> Timestamp { get { return _timestamp; } set { _timestamp = value; } } private System.Nullable<byte> _priority; public System.Nullable<byte> Priority { get { return _priority; } set { _priority = value; } } private System.Nullable<double> _long; public System.Nullable<double> Long { get { return _long; } set { _long = value; } } private System.Nullable<double> _lat; public System.Nullable<double> Lat { get { return _lat; } set { _lat = value; } } private System.Nullable<short> _altitude; public System.Nullable<short> Altitude { get { return _altitude; } set { _altitude = value; } } private System.Nullable<short> _direction; public System.Nullable<short> Direction { get { return _direction; } set { _direction = value; } } private System.Nullable<byte> _satellite; public System.Nullable<byte> Satellite { get { return _satellite; } set { _satellite = value; } } private System.Nullable<short> _speed; public System.Nullable<short> Speed { get { return _speed; } set { _speed = value; } } private System.Nullable<short> _localAreaCode; public System.Nullable<short> LocalAreaCode { get { return _localAreaCode; } set { _localAreaCode = value; } } private System.Nullable<short> _cellID; public System.Nullable<short> CellID { get { return _cellID; } set { _cellID = value; } } private System.Nullable<byte> _gsmSignalQuality; public System.Nullable<byte> GsmSignalQuality { get { return _gsmSignalQuality; } set { _gsmSignalQuality = value; } } private System.Nullable<int> _operatorCode; public System.Nullable<int> OperatorCode { get { return _operatorCode; } set { _operatorCode = value; } } private byte event_IO_element_ID; public byte Event_IO_element_ID { get { return event_IO_element_ID; } set { event_IO_element_ID = value; } } private Dictionary<byte, byte> _IO_Elements_1B = new Dictionary<byte,byte>(); public Dictionary<byte, byte> IO_Elements_1B { get { return _IO_Elements_1B; } set { _IO_Elements_1B = value; } } private Dictionary<byte, short> _IO_Elements_2B = new Dictionary<byte,short>(); public Dictionary<byte, short> IO_Elements_2B { get { return _IO_Elements_2B; } set { _IO_Elements_2B = value; } } private Dictionary<byte, int> _IO_Elements_4B = new Dictionary<byte,int>(); public Dictionary<byte, int> IO_Elements_4B { get { return _IO_Elements_4B; } set { _IO_Elements_4B = value; } } private Dictionary<byte, long> _IO_Elements_8B = new Dictionary<byte,long>(); public Dictionary<byte, long> IO_Elements_8B { get { return _IO_Elements_8B; } set { _IO_Elements_8B = value; } } } }
27.662069
87
0.546248
1e5245011f1f7e25b915855217c48702cdca4f60
1,703
cs
C#
src/ResourceManager.DataSource.File/Commands/GetResource/GetResourceFileHandler.cs
Prastiwar/ResourceManager
693c50c4418ae995c1cc696bf96cf040c63949ea
[ "MIT" ]
1
2021-07-06T16:19:53.000Z
2021-07-06T16:19:53.000Z
src/ResourceManager.DataSource.File/Commands/GetResource/GetResourceFileHandler.cs
Prastiwar/ResourceManager
693c50c4418ae995c1cc696bf96cf040c63949ea
[ "MIT" ]
null
null
null
src/ResourceManager.DataSource.File/Commands/GetResource/GetResourceFileHandler.cs
Prastiwar/ResourceManager
693c50c4418ae995c1cc696bf96cf040c63949ea
[ "MIT" ]
null
null
null
using ResourceManager.Commands; using ResourceManager.Data; using ResourceManager.Services; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace ResourceManager.DataSource.File.Commands { public abstract class GetResourceFileHandler<TQuery, TEnumerableQuery> : ResourceRequestHandler<TQuery, TEnumerableQuery> where TQuery : IResourceQuery where TEnumerableQuery : IEnumerableResourceQuery { public GetResourceFileHandler(IResourceDescriptorService descriptorService, IFileClient client, ITextSerializer serializer) { DescriptorService = descriptorService; Client = client; Serializer = serializer; } protected IFileClient Client { get; } protected ITextSerializer Serializer { get; } protected IResourceDescriptorService DescriptorService { get; } protected async Task<IEnumerable<object>> GetResourceByPaths(Type resourceType, IEnumerable<string> paths) { if (paths == null) { return Array.Empty<object>(); } IList<object> presentables = new List<object>(); foreach (string path in paths) { object data = await GetResourceByPath(resourceType, path); presentables.Add(data); } return presentables; } protected async Task<object> GetResourceByPath(Type resourceType, string path) { string content = await Client.ReadFileAsync(path); object resource = Serializer.Deserialize(content, resourceType); return resource; } } }
34.06
131
0.653553
1e553f6dd4b591ccbaa6579ed68bbc4a26dca8fa
1,576
cs
C#
Core/Source/Utilities/StratusAssetsResources.cs
Azurelol/StratusFramework
93b53673415a163338e78de79f8cdc2157c235f2
[ "MIT" ]
16
2016-08-12T00:39:26.000Z
2021-08-19T17:09:26.000Z
Core/Source/Utilities/StratusAssetsResources.cs
Azurelol/StratusFramework
93b53673415a163338e78de79f8cdc2157c235f2
[ "MIT" ]
13
2017-10-15T14:35:47.000Z
2018-08-05T03:33:51.000Z
Core/Source/Utilities/StratusAssetsResources.cs
Azurelol/StratusFramework
93b53673415a163338e78de79f8cdc2157c235f2
[ "MIT" ]
3
2019-11-03T05:52:48.000Z
2020-11-13T01:15:30.000Z
using System.Collections; using System.Collections.Generic; using UnityEngine; using System; using Stratus.Utilities; using System.IO; namespace Stratus { /// <summary> /// Utility class for managing assets at runtime /// </summary> public static partial class StratusAssets { /// <summary> /// Currently loaded resources /// </summary> private static Dictionary<Type, Dictionary<string, UnityEngine.Object>> loadedResources = new Dictionary<Type, Dictionary<string, UnityEngine.Object>>(); public static T LoadResource<T>(string name) where T : UnityEngine.Object { Type type = typeof(T); if (!loadedResources.ContainsKey(type)) AddResourcesOfType<T>(); T resource = (T)loadedResources[type][name]; return resource; } private static void AddResourcesOfType<T>() where T : UnityEngine.Object { Type type = typeof(T); loadedResources.Add(type, new Dictionary<string, UnityEngine.Object>()); T[] resources = Resources.FindObjectsOfTypeAll<T>(); foreach (var resource in resources) { StratusDebug.Log($"Loading {resource.name}"); loadedResources[type].Add(resource.name, resource); } } private static void AddResourcesOfType(Type type) { loadedResources.Add(type, new Dictionary<string, UnityEngine.Object>()); UnityEngine.Object[] resources = Resources.FindObjectsOfTypeAll(type); foreach (var resource in resources) { loadedResources[type].Add(resource.name, resource); } } } }
26.266667
157
0.672589
1e5613d0db28ea5772d4a285aaed4c735ca1f651
8,172
cs
C#
Assets/Scripts/Game/UI/Popups/BuildingGame/BuildingWindow.cs
redmoon-games/SimpleMergeSource
d19a2b9fdc39330a2c807a0ece5692bfdee88d16
[ "MIT" ]
null
null
null
Assets/Scripts/Game/UI/Popups/BuildingGame/BuildingWindow.cs
redmoon-games/SimpleMergeSource
d19a2b9fdc39330a2c807a0ece5692bfdee88d16
[ "MIT" ]
null
null
null
Assets/Scripts/Game/UI/Popups/BuildingGame/BuildingWindow.cs
redmoon-games/SimpleMergeSource
d19a2b9fdc39330a2c807a0ece5692bfdee88d16
[ "MIT" ]
null
null
null
using System; using System.Collections.Generic; using Game.Controllers; using Game.Services; using Game.Signals; using Game.Signals.FromWindow; using Game.UI.BottomBar; using Plugins.WindowsManager; using UnityEngine; using Zenject; namespace Game.UI.Popups.BuildingGame { [Serializable] public class MetaGameData { public List<BuildingData> buildings = new List<BuildingData>(); public List<BuildingTaskData> tasks = new List<BuildingTaskData>(); } public class BuildingWindow : Window<BuildingWindow> { [SerializeField] private TaskListWindow taskListWindow; [SerializeField] private PaymentTypePopup paymentTypePopup; [SerializeField] private List<DeliveryTaskController> taskSlots; [SerializeField] private Transform buildingsRoot; [SerializeField] private BuildingController buildingPrefab; private readonly List<BuildingController> _buildings = new List<BuildingController>(); private WalletService _walletService; private WindowManager _windowManager; private SignalBus _signalBus; private MetaGameData _data; private WorldData _worldData; private MetaGameService _metaGameService; [Inject] public void Construct( WalletService walletService, WindowManager windowManager, MetaGameService metaGameService, SignalBus signalBus ) { _walletService = walletService; _windowManager = windowManager; _metaGameService = metaGameService; _signalBus = signalBus; _signalBus.Subscribe<MetaGameDataNotificationSignal>(OnDataChanged); } public void CloseWindow() { if (ActivatableState != ActivatableState.Inactive) _windowManager.CloseAll(GetType().Name); } public override void Activate(bool immediately = false) { taskListWindow.OnTaskChanged += OnTaskChanged; ActivatableState = ActivatableState.Active; gameObject.SetActive(true); } public override void Deactivate(bool immediately = false) { taskListWindow.OnTaskChanged -= OnTaskChanged; ActivatableState = ActivatableState.Inactive; gameObject.SetActive(false); } public void ShowWindow() { UpdateBuildings(); UpdateTasks(); if (ActivatableState != ActivatableState.Active) { _windowManager.CloseAll(); _signalBus.Fire(new AllClosedSignal()); _windowManager.ShowCreatedWindow(WindowId); _signalBus.Fire(new DownBarShowedSignal(EDownBarButtonType.Map)); } } private void UpdateBuildings() { ResetBuildings(); var buildings = _metaGameService.FilterTopLevelBuildings(_data.buildings); foreach (var buildingDto in buildings) { var building = Instantiate(buildingPrefab, buildingsRoot); building.Init(_metaGameService.GetBuildingInfo(buildingDto.BuildingVo.id)); _buildings.Add(building); } } private void ResetBuildings() { foreach (var building in _buildings) { Destroy(building.gameObject); } _buildings.Clear(); } private void UpdateTasks() { ResetSlots(); var taskCount = 0; foreach (var task in _data.tasks) { var deliveryTime = _metaGameService.GetDeliveryTime(task.building.buildingId); taskSlots[taskCount].OnBuildingDelivered += OnBuildingDelivered; taskSlots[taskCount].OnSpeedupDelivery += OnSpeedupDelivery; taskSlots[taskCount++].Init(_data, task, deliveryTime); } } private void OnSpeedupDelivery(BuildingTaskData task) { paymentTypePopup.OnPaymentSuccess = OnDeliveryPayed; paymentTypePopup.ShowWindow(task, GetAvailablePayments(task)); } private List<Payment> GetAvailablePayments(BuildingTaskData task) { var taskData = _metaGameService.GetTaskData(task.building.buildingId); var result = new List<Payment> { new Payment { Amount = 30, CommodityName = taskData.TaskName, CommoditySprite = taskData.ItemSprite, PaymentSprite = null, Type = PaymentTypes.Video, Enabled = true }, new Payment { Amount = taskData.DeliveryCost, CommodityName = taskData.TaskName, CommoditySprite = taskData.ItemSprite, PaymentSprite = null, Type = PaymentTypes.Crystal, Enabled = _walletService.HasCrystalAmount(taskData.DeliveryCost) }, new Payment { Amount = 1, CommodityName = taskData.TaskName, CommoditySprite = taskData.ItemSprite, PaymentSprite = taskData.UnitSprites?[0], Type = PaymentTypes.Sacrifice, Enabled = HasAllUnits(taskData.UnitIds), UnitIds = taskData.UnitIds } }; return result; } private bool HasAllUnits(IEnumerable<string> unitIds) { foreach (var unitId in unitIds) { if (!HasUnit(unitId)) return false; } return true; } private bool HasUnit(string unitId) { foreach (var room in _worldData.rooms) { foreach (var unit in room.units) { if (unit.data.id == unitId) return true; } } return false; } private void OnDeliveryPayed(BuildingTaskData task, Payment payment) { ApplyPayment(payment); task.state = TaskState.Delivered; _signalBus.Fire(new MetaGameDataChangedSignal()); UpdateTasks(); } private void ApplyPayment(Payment payment) { switch (payment.Type) { case PaymentTypes.Crystal: _walletService.TrySubtractCrystal(payment.Amount); break; case PaymentTypes.Sacrifice: foreach (var unitId in payment.UnitIds) { _signalBus.Fire(new UnitSacrificeSignal(unitId)); } break; } } private void ResetSlots() { foreach (var taskSlot in taskSlots) { taskSlot.ResetTask(); taskSlot.OnBuildingDelivered -= OnBuildingDelivered; } } public void ShowTaskList() { taskListWindow.ShowWindow(_data.tasks); } private void OnTaskChanged(TaskData taskData) { if (taskData.State == TaskState.Delivery) OnSpeedupDelivery(_data.tasks.FindById(taskData.BuildingId)); else UpdateTasks(); } private void OnDataChanged(MetaGameDataNotificationSignal signalData) { _worldData = signalData.data; _data = _worldData.metaGameData; } private void OnBuildingDelivered(BuildingTaskData taskData) { _data.tasks.Remove(taskData); _data.buildings.Add(taskData.building); UpdateTasks(); UpdateBuildings(); _signalBus.Fire(new MetaGameDataChangedSignal()); } } }
32.047059
94
0.555678
1e5718968dc966fd1d85516dd6b45379eb83db1c
3,275
cs
C#
PP/ImageData.cs
Brqqq/PP
394e0af2aadb188b515856e0db01e8a43cd849c2
[ "Apache-2.0" ]
null
null
null
PP/ImageData.cs
Brqqq/PP
394e0af2aadb188b515856e0db01e8a43cd849c2
[ "Apache-2.0" ]
null
null
null
PP/ImageData.cs
Brqqq/PP
394e0af2aadb188b515856e0db01e8a43cd849c2
[ "Apache-2.0" ]
null
null
null
using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PP { class ImageData : IDisposable { public Bitmap SourceBitmap { get; private set; } public Bitmap TargetBitmap { get; private set; } private BitmapData bitmapData; private Dictionary<Color, Color> bestColorMatch; private HashSet<Color> uniqueColors; private List<Color> targetColors; public ImageData(string path, List<string> colors) { SourceBitmap = (Bitmap)Image.FromFile(path); TargetBitmap = new Bitmap(SourceBitmap.Width, SourceBitmap.Height, SourceBitmap.PixelFormat); targetColors = stringColorsToColors(colors); } public void ApplyChanges() { Rectangle rect = new Rectangle(0, 0, SourceBitmap.Width, SourceBitmap.Height); bitmapData = SourceBitmap.LockBits(rect, ImageLockMode.ReadWrite, SourceBitmap.PixelFormat); IntPtr ptr = bitmapData.Scan0; int bytes = Math.Abs(bitmapData.Stride) * bitmapData.Height; byte[] rgbValues = new byte[bytes]; // bitmap -> array System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes); // array -> bitmap // System.Runtime.InteropServices.Marshal.Copy(rgbValues, 0, ptr, bytes); TargetBitmap .UnlockBits(bitmapData); } private void findUniqueColors() { } private void calculateEuclideanDistance() { } private List<Color> stringColorsToColors(List<string> colors) { List<Color> colorList = new List<Color>(); foreach (string stringColor in colors) { colorList.Add(Color.FromArgb(Convert.ToInt32("FF" + stringColor, 16))); } return colorList; } #region IDisposable Support private bool disposedValue = false; // To detect redundant calls protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { // TODO: dispose managed state (managed objects). } // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below. // TODO: set large fields to null. disposedValue = true; } } // TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources. // ~ImageData() { // // Do not change this code. Put cleanup code in Dispose(bool disposing) above. // Dispose(false); // } // This code added to correctly implement the disposable pattern. public void Dispose() { // Do not change this code. Put cleanup code in Dispose(bool disposing) above. Dispose(true); // TODO: uncomment the following line if the finalizer is overridden above. // GC.SuppressFinalize(this); } #endregion } }
32.107843
113
0.588092
1e58e9ec628f2053db7f097b944eb5d23e00b89a
5,360
cs
C#
BlockJump/BlockJump/LevelEditor.Designer.cs
TheRealMichaelWang/BlockJump
18366ef742fac5b11778429e5c894765508a5a25
[ "MIT" ]
null
null
null
BlockJump/BlockJump/LevelEditor.Designer.cs
TheRealMichaelWang/BlockJump
18366ef742fac5b11778429e5c894765508a5a25
[ "MIT" ]
null
null
null
BlockJump/BlockJump/LevelEditor.Designer.cs
TheRealMichaelWang/BlockJump
18366ef742fac5b11778429e5c894765508a5a25
[ "MIT" ]
null
null
null
namespace BlockJump { partial class LevelEditor { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(LevelEditor)); this.LevelDrawer = new System.Windows.Forms.PictureBox(); this.OpenSaveButton = new System.Windows.Forms.Button(); this.textBox = new System.Windows.Forms.TextBox(); this.timer = new System.Windows.Forms.Timer(this.components); this.NewLevelButton = new System.Windows.Forms.Button(); this.openFileDialog = new System.Windows.Forms.OpenFileDialog(); ((System.ComponentModel.ISupportInitialize)(this.LevelDrawer)).BeginInit(); this.SuspendLayout(); // // LevelDrawer // this.LevelDrawer.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.LevelDrawer.Location = new System.Drawing.Point(100, 0); this.LevelDrawer.Name = "LevelDrawer"; this.LevelDrawer.Size = new System.Drawing.Size(800, 75); this.LevelDrawer.TabIndex = 0; this.LevelDrawer.TabStop = false; this.LevelDrawer.SizeChanged += new System.EventHandler(this.LevelDrawer_SizeChanged); // // OpenSaveButton // this.OpenSaveButton.Location = new System.Drawing.Point(12, 0); this.OpenSaveButton.Name = "OpenSaveButton"; this.OpenSaveButton.Size = new System.Drawing.Size(75, 23); this.OpenSaveButton.TabIndex = 1; this.OpenSaveButton.UseVisualStyleBackColor = true; this.OpenSaveButton.Click += new System.EventHandler(this.OpenSaveButton_Click); // // textBox // this.textBox.Font = new System.Drawing.Font("Consolas", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox.Location = new System.Drawing.Point(0, 80); this.textBox.Multiline = true; this.textBox.Name = "textBox"; this.textBox.Size = new System.Drawing.Size(900, 493); this.textBox.TabIndex = 2; this.textBox.TextChanged += new System.EventHandler(this.TextBox_TextChanged); // // timer // this.timer.Enabled = true; this.timer.Tick += new System.EventHandler(this.Timer_Tick); // // NewLevelButton // this.NewLevelButton.Location = new System.Drawing.Point(12, 30); this.NewLevelButton.Name = "NewLevelButton"; this.NewLevelButton.Size = new System.Drawing.Size(75, 23); this.NewLevelButton.TabIndex = 3; this.NewLevelButton.UseVisualStyleBackColor = true; this.NewLevelButton.Click += new System.EventHandler(this.NewLevelButton_Click); // // openFileDialog // this.openFileDialog.Filter = "MW LEVEL FILES|*.lev"; this.openFileDialog.Title = "Open A Level"; // // LevelEditor // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(904, 558); this.Controls.Add(this.NewLevelButton); this.Controls.Add(this.textBox); this.Controls.Add(this.OpenSaveButton); this.Controls.Add(this.LevelDrawer); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Name = "LevelEditor"; this.Text = "LevelEditor"; ((System.ComponentModel.ISupportInitialize)(this.LevelDrawer)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.PictureBox LevelDrawer; private System.Windows.Forms.Button OpenSaveButton; private System.Windows.Forms.TextBox textBox; private System.Windows.Forms.Timer timer; private System.Windows.Forms.Button NewLevelButton; private System.Windows.Forms.OpenFileDialog openFileDialog; } }
45.811966
159
0.588433
1e591a4721de940c9586b1316d445e5322ed3bd6
1,470
cs
C#
VVVCreator/EditMacroDialog.cs
ViViVerse/VVVCreator
9aa6e72c14c6029b3d4cf1c68200558bb71b67ff
[ "MIT" ]
null
null
null
VVVCreator/EditMacroDialog.cs
ViViVerse/VVVCreator
9aa6e72c14c6029b3d4cf1c68200558bb71b67ff
[ "MIT" ]
null
null
null
VVVCreator/EditMacroDialog.cs
ViViVerse/VVVCreator
9aa6e72c14c6029b3d4cf1c68200558bb71b67ff
[ "MIT" ]
null
null
null
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace VVVCreator { public partial class EditMacroDialog : Form { /// <summary> /// The name of the macro. It is displayed in the title of the dialog. /// </summary> private string MacroName; /// <summary> /// The value of the macro. /// </summary> public string MacroValue; /// <summary> /// Constructor. /// </summary> /// <param name="macroName">The name of the macro.</param> /// <param name="macroValue">The value of the macro.</param> public EditMacroDialog(string macroName, string macroValue) { MacroName = macroName; MacroValue = macroValue; InitializeComponent(); textBoxValue.Text = MacroValue; } // EditMacroDialog /// <summary> /// Called when the user clicks the Ok button. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void buttonOk_Click(object sender, EventArgs e) { // Get the macro value. MacroValue = textBoxValue.Text; DialogResult = DialogResult.OK; Close(); } // buttonOk_Click } // class EditMacroDialog } // namespace VVVCreator
27.735849
78
0.57551
1e5ac87336f9279774b99355a03bcd6422d17f5d
10,446
cs
C#
aliyun-net-sdk-schedulerx2/Schedulerx2/Model/V20190430/UpdateJobRequest.cs
pengweiqhca/aliyun-openapi-net-sdk
bfcda305715ead3354098674198854a07eaa470f
[ "Apache-2.0" ]
null
null
null
aliyun-net-sdk-schedulerx2/Schedulerx2/Model/V20190430/UpdateJobRequest.cs
pengweiqhca/aliyun-openapi-net-sdk
bfcda305715ead3354098674198854a07eaa470f
[ "Apache-2.0" ]
null
null
null
aliyun-net-sdk-schedulerx2/Schedulerx2/Model/V20190430/UpdateJobRequest.cs
pengweiqhca/aliyun-openapi-net-sdk
bfcda305715ead3354098674198854a07eaa470f
[ "Apache-2.0" ]
null
null
null
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System.Collections.Generic; using Aliyun.Acs.Core; using Aliyun.Acs.Core.Http; using Aliyun.Acs.Core.Transform; using Aliyun.Acs.Core.Utils; using Aliyun.Acs.schedulerx2; using Aliyun.Acs.schedulerx2.Transform; using Aliyun.Acs.schedulerx2.Transform.V20190430; namespace Aliyun.Acs.schedulerx2.Model.V20190430 { public class UpdateJobRequest : RpcAcsRequest<UpdateJobResponse> { public UpdateJobRequest() : base("schedulerx2", "2019-04-30", "UpdateJob") { if (this.GetType().GetProperty("ProductEndpointMap") != null && this.GetType().GetProperty("ProductEndpointType") != null) { this.GetType().GetProperty("ProductEndpointMap").SetValue(this, Aliyun.Acs.schedulerx2.Endpoint.endpointMap, null); this.GetType().GetProperty("ProductEndpointType").SetValue(this, Aliyun.Acs.schedulerx2.Endpoint.endpointRegionalType, null); } Method = MethodType.POST; } private string namespaceSource; private string description; private int? attemptInterval; private string content; private long? timeout; private bool? timeoutKillEnable; private long? jobId; private int? pageSize; private int? consumerSize; private string jarUrl; private string calendar; private bool? failEnable; private string sendChannel; private int? dataOffset; private string groupId; private int? taskMaxAttempt; private int? maxAttempt; private bool? missWorkerEnable; private int? dispatcherSize; private int? taskAttemptInterval; private string executeMode; private int? queueSize; private string timeExpression; private string className; private bool? timeoutEnable; private List<string> contactInfos = new List<string>(){ }; private string name; private string _namespace; private int? maxConcurrency; private int? timeType; private string parameters; public string NamespaceSource { get { return namespaceSource; } set { namespaceSource = value; DictionaryUtil.Add(BodyParameters, "NamespaceSource", value); } } public string Description { get { return description; } set { description = value; DictionaryUtil.Add(BodyParameters, "Description", value); } } public int? AttemptInterval { get { return attemptInterval; } set { attemptInterval = value; DictionaryUtil.Add(BodyParameters, "AttemptInterval", value.ToString()); } } public string Content { get { return content; } set { content = value; DictionaryUtil.Add(BodyParameters, "Content", value); } } public long? Timeout { get { return timeout; } set { timeout = value; DictionaryUtil.Add(BodyParameters, "Timeout", value.ToString()); } } public bool? TimeoutKillEnable { get { return timeoutKillEnable; } set { timeoutKillEnable = value; DictionaryUtil.Add(BodyParameters, "TimeoutKillEnable", value.ToString()); } } public long? JobId { get { return jobId; } set { jobId = value; DictionaryUtil.Add(BodyParameters, "JobId", value.ToString()); } } public int? PageSize { get { return pageSize; } set { pageSize = value; DictionaryUtil.Add(BodyParameters, "PageSize", value.ToString()); } } public int? ConsumerSize { get { return consumerSize; } set { consumerSize = value; DictionaryUtil.Add(BodyParameters, "ConsumerSize", value.ToString()); } } public string JarUrl { get { return jarUrl; } set { jarUrl = value; DictionaryUtil.Add(BodyParameters, "JarUrl", value); } } public string Calendar { get { return calendar; } set { calendar = value; DictionaryUtil.Add(BodyParameters, "Calendar", value); } } public bool? FailEnable { get { return failEnable; } set { failEnable = value; DictionaryUtil.Add(BodyParameters, "FailEnable", value.ToString()); } } public string SendChannel { get { return sendChannel; } set { sendChannel = value; DictionaryUtil.Add(BodyParameters, "SendChannel", value); } } public int? DataOffset { get { return dataOffset; } set { dataOffset = value; DictionaryUtil.Add(BodyParameters, "DataOffset", value.ToString()); } } public string GroupId { get { return groupId; } set { groupId = value; DictionaryUtil.Add(BodyParameters, "GroupId", value); } } public int? TaskMaxAttempt { get { return taskMaxAttempt; } set { taskMaxAttempt = value; DictionaryUtil.Add(BodyParameters, "TaskMaxAttempt", value.ToString()); } } public int? MaxAttempt { get { return maxAttempt; } set { maxAttempt = value; DictionaryUtil.Add(BodyParameters, "MaxAttempt", value.ToString()); } } public bool? MissWorkerEnable { get { return missWorkerEnable; } set { missWorkerEnable = value; DictionaryUtil.Add(BodyParameters, "MissWorkerEnable", value.ToString()); } } public int? DispatcherSize { get { return dispatcherSize; } set { dispatcherSize = value; DictionaryUtil.Add(BodyParameters, "DispatcherSize", value.ToString()); } } public int? TaskAttemptInterval { get { return taskAttemptInterval; } set { taskAttemptInterval = value; DictionaryUtil.Add(BodyParameters, "TaskAttemptInterval", value.ToString()); } } public string ExecuteMode { get { return executeMode; } set { executeMode = value; DictionaryUtil.Add(BodyParameters, "ExecuteMode", value); } } public int? QueueSize { get { return queueSize; } set { queueSize = value; DictionaryUtil.Add(BodyParameters, "QueueSize", value.ToString()); } } public string TimeExpression { get { return timeExpression; } set { timeExpression = value; DictionaryUtil.Add(BodyParameters, "TimeExpression", value); } } public string ClassName { get { return className; } set { className = value; DictionaryUtil.Add(BodyParameters, "ClassName", value); } } public bool? TimeoutEnable { get { return timeoutEnable; } set { timeoutEnable = value; DictionaryUtil.Add(BodyParameters, "TimeoutEnable", value.ToString()); } } public List<string> ContactInfos { get { return contactInfos; } set { contactInfos = value; if(contactInfos != null) { for (int depth1 = 0; depth1 < contactInfos.Count; depth1++) { DictionaryUtil.Add(BodyParameters,"ContactInfo." + (depth1 + 1), contactInfos[depth1]); DictionaryUtil.Add(BodyParameters,"ContactInfo." + (depth1 + 1), contactInfos[depth1]); DictionaryUtil.Add(BodyParameters,"ContactInfo." + (depth1 + 1), contactInfos[depth1]); DictionaryUtil.Add(BodyParameters,"ContactInfo." + (depth1 + 1), contactInfos[depth1]); } } } } public string Name { get { return name; } set { name = value; DictionaryUtil.Add(BodyParameters, "Name", value); } } public string _Namespace { get { return _namespace; } set { _namespace = value; DictionaryUtil.Add(BodyParameters, "Namespace", value); } } public int? MaxConcurrency { get { return maxConcurrency; } set { maxConcurrency = value; DictionaryUtil.Add(BodyParameters, "MaxConcurrency", value.ToString()); } } public int? TimeType { get { return timeType; } set { timeType = value; DictionaryUtil.Add(BodyParameters, "TimeType", value.ToString()); } } public string Parameters { get { return parameters; } set { parameters = value; DictionaryUtil.Add(BodyParameters, "Parameters", value); } } public class ContactInfo { private string ding; private string userPhone; private string userMail; private string userName; public string Ding { get { return ding; } set { ding = value; } } public string UserPhone { get { return userPhone; } set { userPhone = value; } } public string UserMail { get { return userMail; } set { userMail = value; } } public string UserName { get { return userName; } set { userName = value; } } } public override bool CheckShowJsonItemName() { return false; } public override UpdateJobResponse GetResponse(UnmarshallerContext unmarshallerContext) { return UpdateJobResponseUnmarshaller.Unmarshall(unmarshallerContext); } } }
17.705085
141
0.597071
1e5cc1cacb4ab03b80b252935c65bb4e3a0f939e
1,917
cs
C#
DotNet/Leaf.InsertBigData/BulkCopy/Models/Account.cs
YePiaoRan17/MyWayOnCoding
a3f5aae97dac9ef9333a813f8ecc6483ec110456
[ "MIT" ]
1
2021-02-22T17:06:33.000Z
2021-02-22T17:06:33.000Z
DotNet/Leaf.InsertBigData/BulkCopy/Models/Account.cs
YePiaoRan17/MyWayOnCoding
a3f5aae97dac9ef9333a813f8ecc6483ec110456
[ "MIT" ]
null
null
null
DotNet/Leaf.InsertBigData/BulkCopy/Models/Account.cs
YePiaoRan17/MyWayOnCoding
a3f5aae97dac9ef9333a813f8ecc6483ec110456
[ "MIT" ]
null
null
null
using System; using FreeSql.DataAnnotations; namespace BulkCopy.Models { public class Account { [Column(IsIdentity = true, IsPrimary = true)] public long Id { get; set; } public string Name { get; set; } = string.Empty; public int Age { get; set; } public DateTime CreateTime { get; set; } = DateTime.Now; public string Remark { get; set; } = String.Empty; public string Str01 { get; set; } = String.Empty; public string Str02 { get; set; } = String.Empty; public string Str03 { get; set; } = String.Empty; public string Str04 { get; set; } = String.Empty; public string Str05 { get; set; } = String.Empty; public int Num01 { get; set; } public int Num02 { get; set; } public int Num03 { get; set; } public int Num04 { get; set; } public int Num05 { get; set; } public DateTime Time01 { get; set; } = DateTime.Now; public DateTime Time02 { get; set; } = DateTime.Now; public DateTime Time03 { get; set; } = DateTime.Now; public DateTime Time04 { get; set; } = DateTime.Now; public DateTime Time05 { get; set; } = DateTime.Now; public void Bind() { Random rd = new Random(); Name = "test-" + Guid.NewGuid(); Age = rd.Next(10000, 99999); Remark = "Remark-" + Guid.NewGuid(); Str01 = "Str01-" + Guid.NewGuid(); Str02 = "Str02-" + Guid.NewGuid(); Str03 = "Str03-" + Guid.NewGuid(); Str04 = "Str04-" + Guid.NewGuid(); Str05 = "Str05-" + Guid.NewGuid(); Num01 = rd.Next(10000, 99999); Num02 = rd.Next(10000, 99999); Num03 = rd.Next(10000, 99999); Num04 = rd.Next(10000, 99999); Num05 = rd.Next(10000, 99999); } } }
32.491525
64
0.528951
1e5d40f290d5588e12851c7a1d1b18951f6c2523
6,847
cs
C#
src/NTccTransaction/Persistence/TransactionManager.cs
wzl-bxg/NTcc-TransactionCore
6c58058a86d1fa28ac7d09d579c6215507b146d8
[ "MIT" ]
21
2021-03-17T09:58:47.000Z
2022-03-04T06:14:22.000Z
src/NTccTransaction/Persistence/TransactionManager.cs
wzl-bxg/NTcc-TransactionCore
6c58058a86d1fa28ac7d09d579c6215507b146d8
[ "MIT" ]
null
null
null
src/NTccTransaction/Persistence/TransactionManager.cs
wzl-bxg/NTcc-TransactionCore
6c58058a86d1fa28ac7d09d579c6215507b146d8
[ "MIT" ]
6
2021-03-17T09:58:55.000Z
2021-09-29T03:39:30.000Z
using Microsoft.Extensions.DependencyInjection; using NTccTransaction.Abstractions; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Threading.Tasks; namespace NTccTransaction { public class TransactionManager : ITransactionManager { private readonly IAmbientTransaction _ambientTransaction; private readonly IServiceScopeFactory _serviceScopeFactory; public ITransaction Current => _ambientTransaction.Transaction; public TransactionManager( IAmbientTransaction ambientTransaction, IServiceScopeFactory serviceScopeFactory) { _ambientTransaction = ambientTransaction; _serviceScopeFactory = serviceScopeFactory; } /// <summary> /// /// </summary> /// <returns></returns> public ITransaction Begin() { var transaction = new Transaction(TransactionType.ROOT); using (var scope = _serviceScopeFactory.CreateScope()) { var transactionRepository = scope.ServiceProvider.GetRequiredService<ITransactionRepository>(); transactionRepository.Create(transaction); RegisterTransaction(transaction); return transaction; } } /// <summary> /// /// </summary> /// <param name="uniqueIdentity"></param> /// <returns></returns> public ITransaction Begin(object uniqueIdentity) { var transaction = new Transaction(TransactionType.ROOT); using (var scope = _serviceScopeFactory.CreateScope()) { var transactionRepository = scope.ServiceProvider.GetRequiredService<ITransactionRepository>(); transactionRepository.Create(transaction); RegisterTransaction(transaction); return transaction; } } /// <summary> /// /// </summary> /// <param name="transactionContext"></param> /// <returns></returns> public ITransaction PropagationNewBegin(TransactionContext transactionContext) { var transaction = new Transaction(transactionContext); using (var scope = _serviceScopeFactory.CreateScope()) { var transactionRepository = scope.ServiceProvider.GetRequiredService<ITransactionRepository>(); transactionRepository.Create(transaction); RegisterTransaction(transaction); return transaction; } } /// <summary> /// /// </summary> /// <param name="transactionContext"></param> /// <returns></returns> public ITransaction PropagationExistBegin(TransactionContext transactionContext) { using (var scope = _serviceScopeFactory.CreateScope()) { var transactionRepository = scope.ServiceProvider.GetRequiredService<ITransactionRepository>(); var transaction = transactionRepository.FindByXid(transactionContext.Xid); if (transaction == null) { throw new NoExistedTransactionException(); } transaction.ChangeStatus(transactionContext.Status); RegisterTransaction(transaction); return transaction; } } /// <summary> /// Commit /// </summary> public async Task CommitAsync() { var transaction = this.Current; // When confirm successfully, delete the NTccTransaction from database // The confirm action will be call from the top of stack, so delete the transaction data will not impact the excution under it using (var scope = _serviceScopeFactory.CreateScope()) { var transactionRepository = scope.ServiceProvider.GetRequiredService<ITransactionRepository>(); transaction.ChangeStatus(TransactionStatus.CONFIRMING); transactionRepository.Update(transaction); try { await transaction.CommitAsync(_serviceScopeFactory); transactionRepository.Delete(transaction); } catch (Exception commitException) { throw new ConfirmingException("Confirm failed", commitException); } } } /// <summary> /// Rollback /// </summary> public async Task RollbackAsync() { var transaction = this.Current; using (var scope = _serviceScopeFactory.CreateScope()) { var transactionRepository = scope.ServiceProvider.GetRequiredService<ITransactionRepository>(); transaction.ChangeStatus(TransactionStatus.CANCELLING); transactionRepository.Update(transaction); try { await transaction.RollbackAsync(_serviceScopeFactory); transactionRepository.Delete(transaction); } catch (Exception rollbackException) { throw new CancellingException("Rollback failed", rollbackException); } } } /// <summary> /// /// </summary> /// <param name="participant"></param> public void AddParticipant(IParticipant participant) { var transaction = this.Current; transaction.AddParticipant(participant); using (var scope = _serviceScopeFactory.CreateScope()) { var transactionRepository = scope.ServiceProvider.GetRequiredService<ITransactionRepository>(); transactionRepository.Update(transaction); } } /// <summary> /// /// </summary> /// <returns></returns> public bool IsTransactionActive() { return Current != null; } private void RegisterTransaction(ITransaction transaction) { _ambientTransaction.RegisterTransaction(transaction); } public bool IsDelayCancelException(Exception tryingException, HashSet<Type> allDelayCancelExceptionTypes) { if (null == allDelayCancelExceptionTypes || !allDelayCancelExceptionTypes.Any()) { return false; } var tryingExceptionType = tryingException.GetType(); return allDelayCancelExceptionTypes.Any(t => t.IsAssignableFrom(tryingExceptionType)); } } }
33.89604
138
0.582883
1e5eb7c39e0002b9f62414ff3a5eb5844c2d9f19
35,290
cs
C#
test/Microsoft.AspNetCore.Routing.Tests/Template/TemplateMatcherTests.cs
aneequrrehman/Routing
6fcbf67d901e2337ec3f8e9e9081d4a9d0e22b6b
[ "Apache-2.0" ]
null
null
null
test/Microsoft.AspNetCore.Routing.Tests/Template/TemplateMatcherTests.cs
aneequrrehman/Routing
6fcbf67d901e2337ec3f8e9e9081d4a9d0e22b6b
[ "Apache-2.0" ]
null
null
null
test/Microsoft.AspNetCore.Routing.Tests/Template/TemplateMatcherTests.cs
aneequrrehman/Routing
6fcbf67d901e2337ec3f8e9e9081d4a9d0e22b6b
[ "Apache-2.0" ]
1
2020-12-23T17:33:47.000Z
2020-12-23T17:33:47.000Z
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using Xunit; namespace Microsoft.AspNetCore.Routing.Template.Tests { public class TemplateMatcherTests { private static IInlineConstraintResolver _inlineConstraintResolver = GetInlineConstraintResolver(); [Fact] public void TryMatch_Success() { // Arrange var matcher = CreateMatcher("{controller}/{action}/{id}"); var values = new RouteValueDictionary(); // Act var match = matcher.TryMatch("/Bank/DoAction/123", values); // Assert Assert.True(match); Assert.Equal("Bank", values["controller"]); Assert.Equal("DoAction", values["action"]); Assert.Equal("123", values["id"]); } [Fact] public void TryMatch_Fails() { // Arrange var matcher = CreateMatcher("{controller}/{action}/{id}"); var values = new RouteValueDictionary(); // Act var match = matcher.TryMatch("/Bank/DoAction", values); // Assert Assert.False(match); } [Fact] public void TryMatch_WithDefaults_Success() { // Arrange var matcher = CreateMatcher("{controller}/{action}/{id}", new { id = "default id" }); var values = new RouteValueDictionary(); // Act var match = matcher.TryMatch("/Bank/DoAction", values); // Assert Assert.True(match); Assert.Equal("Bank", values["controller"]); Assert.Equal("DoAction", values["action"]); Assert.Equal("default id", values["id"]); } [Fact] public void TryMatch_WithDefaults_Fails() { // Arrange var matcher = CreateMatcher("{controller}/{action}/{id}", new { id = "default id" }); var values = new RouteValueDictionary(); // Act var match = matcher.TryMatch("/Bank", values); // Assert Assert.False(match); } [Fact] public void TryMatch_WithLiterals_Success() { // Arrange var matcher = CreateMatcher("moo/{p1}/bar/{p2}", new { p2 = "default p2" }); var values = new RouteValueDictionary(); // Act var match = matcher.TryMatch("/moo/111/bar/222", values); // Assert Assert.True(match); Assert.Equal("111", values["p1"]); Assert.Equal("222", values["p2"]); } [Fact] public void TryMatch_RouteWithLiteralsAndDefaults_Success() { // Arrange var matcher = CreateMatcher("moo/{p1}/bar/{p2}", new { p2 = "default p2" }); var values = new RouteValueDictionary(); // Act var match = matcher.TryMatch("/moo/111/bar/", values); // Assert Assert.True(match); Assert.Equal("111", values["p1"]); Assert.Equal("default p2", values["p2"]); } [Theory] [InlineData(@"{p1:regex(^\d{{3}}-\d{{3}}-\d{{4}}$)}", "/123-456-7890")] // ssn [InlineData(@"{p1:regex(^\w+\@\w+\.\w+)}", "/asd@assds.com")] // email [InlineData(@"{p1:regex(([}}])\w+)}", "/}sda")] // Not balanced } [InlineData(@"{p1:regex(([{{)])\w+)}", "/})sda")] // Not balanced { public void TryMatch_RegularExpressionConstraint_Valid( string template, string path) { // Arrange var matcher = CreateMatcher(template); var values = new RouteValueDictionary(); // Act var match = matcher.TryMatch(path, values); // Assert Assert.True(match); } [Theory] [InlineData("moo/{p1}.{p2?}", "/moo/foo.bar", true, "foo", "bar")] [InlineData("moo/{p1?}", "/moo/foo", true, "foo", null)] [InlineData("moo/{p1?}", "/moo", true, null, null)] [InlineData("moo/{p1}.{p2?}", "/moo/foo", true, "foo", null)] [InlineData("moo/{p1}.{p2?}", "/moo/foo..bar", true, "foo.", "bar")] [InlineData("moo/{p1}.{p2?}", "/moo/foo.moo.bar", true, "foo.moo", "bar")] [InlineData("moo/{p1}.{p2}", "/moo/foo.bar", true, "foo", "bar")] [InlineData("moo/foo.{p1}.{p2?}", "/moo/foo.moo.bar", true, "moo", "bar")] [InlineData("moo/foo.{p1}.{p2?}", "/moo/foo.moo", true, "moo", null)] [InlineData("moo/.{p2?}", "/moo/.foo", true, null, "foo")] [InlineData("moo/.{p2?}", "/moo", false, null, null)] [InlineData("moo/{p1}.{p2?}", "/moo/....", true, "..", ".")] [InlineData("moo/{p1}.{p2?}", "/moo/.bar", true, ".bar", null)] public void TryMatch_OptionalParameter_FollowedByPeriod_Valid( string template, string path, bool expectedMatch, string p1, string p2) { // Arrange var matcher = CreateMatcher(template); var values = new RouteValueDictionary(); // Act var match = matcher.TryMatch(path, values); // Assert Assert.Equal(expectedMatch, match); if (p1 != null) { Assert.Equal(p1, values["p1"]); } if (p2 != null) { Assert.Equal(p2, values["p2"]); } } [Theory] [InlineData("moo/{p1}.{p2}.{p3?}", "/moo/foo.moo.bar", "foo", "moo", "bar")] [InlineData("moo/{p1}.{p2}.{p3?}", "/moo/foo.moo", "foo", "moo", null)] [InlineData("moo/{p1}.{p2}.{p3}.{p4?}", "/moo/foo.moo.bar", "foo", "moo", "bar")] [InlineData("{p1}.{p2?}/{p3}", "/foo.moo/bar", "foo", "moo", "bar")] [InlineData("{p1}.{p2?}/{p3}", "/foo/bar", "foo", null, "bar")] [InlineData("{p1}.{p2?}/{p3}", "/.foo/bar", ".foo", null, "bar")] [InlineData("{p1}/{p2}/{p3?}", "/foo/bar/baz", "foo", "bar", "baz")] public void TryMatch_OptionalParameter_FollowedByPeriod_3Parameters_Valid( string template, string path, string p1, string p2, string p3) { // Arrange var matcher = CreateMatcher(template); var values = new RouteValueDictionary(); // Act var match = matcher.TryMatch(path, values); // Assert Assert.True(match); Assert.Equal(p1, values["p1"]); if (p2 != null) { Assert.Equal(p2, values["p2"]); } if (p3 != null) { Assert.Equal(p3, values["p3"]); } } [Theory] [InlineData("moo/{p1}.{p2?}", "/moo/foo.")] [InlineData("moo/{p1}.{p2?}", "/moo/.")] [InlineData("moo/{p1}.{p2}", "/foo.")] [InlineData("moo/{p1}.{p2}", "/foo")] [InlineData("moo/{p1}.{p2}.{p3?}", "/moo/foo.moo.")] [InlineData("moo/foo.{p2}.{p3?}", "/moo/bar.foo.moo")] [InlineData("moo/foo.{p2}.{p3?}", "/moo/kungfoo.moo.bar")] [InlineData("moo/foo.{p2}.{p3?}", "/moo/kungfoo.moo")] [InlineData("moo/{p1}.{p2}.{p3?}", "/moo/foo")] [InlineData("{p1}.{p2?}/{p3}", "/foo./bar")] [InlineData("moo/.{p2?}", "/moo/.")] [InlineData("{p1}.{p2}/{p3}", "/.foo/bar")] public void TryMatch_OptionalParameter_FollowedByPeriod_Invalid(string template, string path) { // Arrange var matcher = CreateMatcher(template); var values = new RouteValueDictionary(); // Act var match = matcher.TryMatch(path, values); // Assert Assert.False(match); } [Fact] public void TryMatch_RouteWithOnlyLiterals_Success() { // Arrange var matcher = CreateMatcher("moo/bar"); var values = new RouteValueDictionary(); // Act var match = matcher.TryMatch("/moo/bar", values); // Assert Assert.True(match); Assert.Empty(values); } [Fact] public void TryMatch_RouteWithOnlyLiterals_Fails() { // Arrange var matcher = CreateMatcher("moo/bars"); var values = new RouteValueDictionary(); // Act var match = matcher.TryMatch("/moo/bar", values); // Assert Assert.False(match); } [Fact] public void TryMatch_RouteWithExtraSeparators_Success() { // Arrange var matcher = CreateMatcher("moo/bar"); var values = new RouteValueDictionary(); // Act var match = matcher.TryMatch("/moo/bar/", values); // Assert Assert.True(match); Assert.Empty(values); } [Fact] public void TryMatch_UrlWithExtraSeparators_Success() { // Arrange var matcher = CreateMatcher("moo/bar/"); var values = new RouteValueDictionary(); // Act var match = matcher.TryMatch("/moo/bar", values); // Assert Assert.True(match); Assert.Empty(values); } [Fact] public void TryMatch_RouteWithParametersAndExtraSeparators_Success() { // Arrange var matcher = CreateMatcher("{p1}/{p2}/"); var values = new RouteValueDictionary(); // Act var match = matcher.TryMatch("/moo/bar", values); // Assert Assert.True(match); Assert.Equal("moo", values["p1"]); Assert.Equal("bar", values["p2"]); } [Fact] public void TryMatch_RouteWithDifferentLiterals_Fails() { // Arrange var matcher = CreateMatcher("{p1}/{p2}/baz"); var values = new RouteValueDictionary(); // Act var match = matcher.TryMatch("/moo/bar/boo", values); // Assert Assert.False(match); } [Fact] public void TryMatch_LongerUrl_Fails() { // Arrange var matcher = CreateMatcher("{p1}"); var values = new RouteValueDictionary(); // Act var match = matcher.TryMatch("/moo/bar", values); // Assert Assert.False(match); } [Fact] public void TryMatch_SimpleFilename_Success() { // Arrange var matcher = CreateMatcher("DEFAULT.ASPX"); var values = new RouteValueDictionary(); // Act var match = matcher.TryMatch("/default.aspx", values); // Assert Assert.True(match); } [Theory] [InlineData("{prefix}x{suffix}", "/xxxxxxxxxx")] [InlineData("{prefix}xyz{suffix}", "/xxxxyzxyzxxxxxxyz")] [InlineData("{prefix}xyz{suffix}", "/abcxxxxyzxyzxxxxxxyzxx")] [InlineData("{prefix}xyz{suffix}", "/xyzxyzxyzxyzxyz")] [InlineData("{prefix}xyz{suffix}", "/xyzxyzxyzxyzxyz1")] [InlineData("{prefix}xyz{suffix}", "/xyzxyzxyz")] [InlineData("{prefix}aa{suffix}", "/aaaaa")] [InlineData("{prefix}aaa{suffix}", "/aaaaa")] public void TryMatch_RouteWithComplexSegment_Success(string template, string path) { var matcher = CreateMatcher(template); var values = new RouteValueDictionary(); // Act var match = matcher.TryMatch(path, values); // Assert Assert.True(match); } [Fact] public void TryMatch_RouteWithExtraDefaultValues_Success() { // Arrange var matcher = CreateMatcher("{p1}/{p2}", new { p2 = (string)null, foo = "bar" }); var values = new RouteValueDictionary(); // Act var match = matcher.TryMatch("/v1", values); // Assert Assert.True(match); Assert.Equal<int>(3, values.Count); Assert.Equal("v1", values["p1"]); Assert.Null(values["p2"]); Assert.Equal("bar", values["foo"]); } [Fact] public void TryMatch_PrettyRouteWithExtraDefaultValues_Success() { // Arrange var matcher = CreateMatcher( "date/{y}/{m}/{d}", new { controller = "blog", action = "showpost", m = (string)null, d = (string)null }); var values = new RouteValueDictionary(); // Act var match = matcher.TryMatch("/date/2007/08", values); // Assert Assert.True(match); Assert.Equal<int>(5, values.Count); Assert.Equal("blog", values["controller"]); Assert.Equal("showpost", values["action"]); Assert.Equal("2007", values["y"]); Assert.Equal("08", values["m"]); Assert.Null(values["d"]); } [Fact] public void TryMatch_WithMultiSegmentParamsOnBothEndsMatches() { RunTest( "language/{lang}-{region}", "/language/en-US", null, new RouteValueDictionary(new { lang = "en", region = "US" })); } [Fact] public void TryMatch_WithMultiSegmentParamsOnLeftEndMatches() { RunTest( "language/{lang}-{region}a", "/language/en-USa", null, new RouteValueDictionary(new { lang = "en", region = "US" })); } [Fact] public void TryMatch_WithMultiSegmentParamsOnRightEndMatches() { RunTest( "language/a{lang}-{region}", "/language/aen-US", null, new RouteValueDictionary(new { lang = "en", region = "US" })); } [Fact] public void TryMatch_WithMultiSegmentParamsOnNeitherEndMatches() { RunTest( "language/a{lang}-{region}a", "/language/aen-USa", null, new RouteValueDictionary(new { lang = "en", region = "US" })); } [Fact] public void TryMatch_WithMultiSegmentParamsOnNeitherEndDoesNotMatch() { RunTest( "language/a{lang}-{region}a", "/language/a-USa", null, null); } [Fact] public void TryMatch_WithMultiSegmentParamsOnNeitherEndDoesNotMatch2() { RunTest( "language/a{lang}-{region}a", "/language/aen-a", null, null); } [Fact] public void TryMatch_WithSimpleMultiSegmentParamsOnBothEndsMatches() { RunTest( "language/{lang}", "/language/en", null, new RouteValueDictionary(new { lang = "en" })); } [Fact] public void TryMatch_WithSimpleMultiSegmentParamsOnBothEndsTrailingSlashDoesNotMatch() { RunTest( "language/{lang}", "/language/", null, null); } [Fact] public void TryMatch_WithSimpleMultiSegmentParamsOnBothEndsDoesNotMatch() { RunTest( "language/{lang}", "/language", null, null); } [Fact] public void TryMatch_WithSimpleMultiSegmentParamsOnLeftEndMatches() { RunTest( "language/{lang}-", "/language/en-", null, new RouteValueDictionary(new { lang = "en" })); } [Fact] public void TryMatch_WithSimpleMultiSegmentParamsOnRightEndMatches() { RunTest( "language/a{lang}", "/language/aen", null, new RouteValueDictionary(new { lang = "en" })); } [Fact] public void TryMatch_WithSimpleMultiSegmentParamsOnNeitherEndMatches() { RunTest( "language/a{lang}a", "/language/aena", null, new RouteValueDictionary(new { lang = "en" })); } [Fact] public void TryMatch_WithMultiSegmentStandamatchMvcRouteMatches() { RunTest( "{controller}.mvc/{action}/{id}", "/home.mvc/index", new RouteValueDictionary(new { action = "Index", id = (string)null }), new RouteValueDictionary(new { controller = "home", action = "index", id = (string)null })); } [Fact] public void TryMatch_WithMultiSegmentParamsOnBothEndsWithDefaultValuesMatches() { RunTest( "language/{lang}-{region}", "/language/-", new RouteValueDictionary(new { lang = "xx", region = "yy" }), null); } [Fact] public void TryMatch_WithUrlWithMultiSegmentWithRepeatedDots() { RunTest( "{Controller}..mvc/{id}/{Param1}", "/Home..mvc/123/p1", null, new RouteValueDictionary(new { Controller = "Home", id = "123", Param1 = "p1" })); } [Fact] public void TryMatch_WithUrlWithTwoRepeatedDots() { RunTest( "{Controller}.mvc/../{action}", "/Home.mvc/../index", null, new RouteValueDictionary(new { Controller = "Home", action = "index" })); } [Fact] public void TryMatch_WithUrlWithThreeRepeatedDots() { RunTest( "{Controller}.mvc/.../{action}", "/Home.mvc/.../index", null, new RouteValueDictionary(new { Controller = "Home", action = "index" })); } [Fact] public void TryMatch_WithUrlWithManyRepeatedDots() { RunTest( "{Controller}.mvc/../../../{action}", "/Home.mvc/../../../index", null, new RouteValueDictionary(new { Controller = "Home", action = "index" })); } [Fact] public void TryMatch_WithUrlWithExclamationPoint() { RunTest( "{Controller}.mvc!/{action}", "/Home.mvc!/index", null, new RouteValueDictionary(new { Controller = "Home", action = "index" })); } [Fact] public void TryMatch_WithUrlWithStartingDotDotSlash() { RunTest( "../{Controller}.mvc", "/../Home.mvc", null, new RouteValueDictionary(new { Controller = "Home" })); } [Fact] public void TryMatch_WithUrlWithStartingBackslash() { RunTest( @"\{Controller}.mvc", @"/\Home.mvc", null, new RouteValueDictionary(new { Controller = "Home" })); } [Fact] public void TryMatch_WithUrlWithBackslashSeparators() { RunTest( @"{Controller}.mvc\{id}\{Param1}", @"/Home.mvc\123\p1", null, new RouteValueDictionary(new { Controller = "Home", id = "123", Param1 = "p1" })); } [Fact] public void TryMatch_WithUrlWithParenthesesLiterals() { RunTest( @"(Controller).mvc", @"/(Controller).mvc", null, new RouteValueDictionary()); } [Fact] public void TryMatch_WithUrlWithTrailingSlashSpace() { RunTest( @"Controller.mvc/ ", @"/Controller.mvc/ ", null, new RouteValueDictionary()); } [Fact] public void TryMatch_WithUrlWithTrailingSpace() { RunTest( @"Controller.mvc ", @"/Controller.mvc ", null, new RouteValueDictionary()); } [Fact] public void TryMatch_WithCatchAllCapturesDots() { // DevDiv Bugs 189892: UrlRouting: Catch all parameter cannot capture url segments that contain the "." RunTest( "Home/ShowPilot/{missionId}/{*name}", "/Home/ShowPilot/777/12345./foobar", new RouteValueDictionary(new { controller = "Home", action = "ShowPilot", missionId = (string)null, name = (string)null }), new RouteValueDictionary(new { controller = "Home", action = "ShowPilot", missionId = "777", name = "12345./foobar" })); } [Fact] public void TryMatch_RouteWithCatchAll_MatchesMultiplePathSegments() { // Arrange var matcher = CreateMatcher("{p1}/{*p2}"); var values = new RouteValueDictionary(); // Act var match = matcher.TryMatch("/v1/v2/v3", values); // Assert Assert.True(match); Assert.Equal<int>(2, values.Count); Assert.Equal("v1", values["p1"]); Assert.Equal("v2/v3", values["p2"]); } [Fact] public void TryMatch_RouteWithCatchAll_MatchesTrailingSlash() { // Arrange var matcher = CreateMatcher("{p1}/{*p2}"); var values = new RouteValueDictionary(); // Act var match = matcher.TryMatch("/v1/", values); // Assert Assert.True(match); Assert.Equal<int>(2, values.Count); Assert.Equal("v1", values["p1"]); Assert.Null(values["p2"]); } [Fact] public void TryMatch_RouteWithCatchAll_MatchesEmptyContent() { // Arrange var matcher = CreateMatcher("{p1}/{*p2}"); var values = new RouteValueDictionary(); // Act var match = matcher.TryMatch("/v1", values); // Assert Assert.True(match); Assert.Equal<int>(2, values.Count); Assert.Equal("v1", values["p1"]); Assert.Null(values["p2"]); } [Fact] public void TryMatch_RouteWithCatchAll_MatchesEmptyContent_DoesNotReplaceExistingRouteValue() { // Arrange var matcher = CreateMatcher("{p1}/{*p2}"); var values = new RouteValueDictionary(new { p2 = "hello" }); // Act var match = matcher.TryMatch("/v1", values); // Assert Assert.True(match); Assert.Equal<int>(2, values.Count); Assert.Equal("v1", values["p1"]); Assert.Equal("hello", values["p2"]); } [Fact] public void TryMatch_RouteWithCatchAll_UsesDefaultValueForEmptyContent() { // Arrange var matcher = CreateMatcher("{p1}/{*p2}", new { p2 = "catchall" }); var values = new RouteValueDictionary(new { p2 = "overridden" }); // Act var match = matcher.TryMatch("/v1", values); // Assert Assert.True(match); Assert.Equal<int>(2, values.Count); Assert.Equal("v1", values["p1"]); Assert.Equal("catchall", values["p2"]); } [Fact] public void TryMatch_RouteWithCatchAll_IgnoresDefaultValueForNonEmptyContent() { // Arrange var matcher = CreateMatcher("{p1}/{*p2}", new { p2 = "catchall" }); var values = new RouteValueDictionary(new { p2 = "overridden" }); // Act var match = matcher.TryMatch("/v1/hello/whatever", values); // Assert Assert.True(match); Assert.Equal<int>(2, values.Count); Assert.Equal("v1", values["p1"]); Assert.Equal("hello/whatever", values["p2"]); } [Fact] public void TryMatch_DoesNotMatchOnlyLeftLiteralMatch() { // DevDiv Bugs 191180: UrlRouting: Wrong template getting matched if a url segment is a substring of the requested url RunTest( "foo", "/fooBAR", null, null); } [Fact] public void TryMatch_DoesNotMatchOnlyRightLiteralMatch() { // DevDiv Bugs 191180: UrlRouting: Wrong template getting matched if a url segment is a substring of the requested url RunTest( "foo", "/BARfoo", null, null); } [Fact] public void TryMatch_DoesNotMatchMiddleLiteralMatch() { // DevDiv Bugs 191180: UrlRouting: Wrong template getting matched if a url segment is a substring of the requested url RunTest( "foo", "/BARfooBAR", null, null); } [Fact] public void TryMatch_DoesMatchesExactLiteralMatch() { // DevDiv Bugs 191180: UrlRouting: Wrong template getting matched if a url segment is a substring of the requested url RunTest( "foo", "/foo", null, new RouteValueDictionary()); } [Fact] public void TryMatch_WithWeimatchParameterNames() { RunTest( "foo/{ }/{.!$%}/{dynamic.data}/{op.tional}", "/foo/space/weimatch/omatcherid", new RouteValueDictionary() { { " ", "not a space" }, { "op.tional", "default value" }, { "ran!dom", "va@lue" } }, new RouteValueDictionary() { { " ", "space" }, { ".!$%", "weimatch" }, { "dynamic.data", "omatcherid" }, { "op.tional", "default value" }, { "ran!dom", "va@lue" } }); } [Fact] public void TryMatch_DoesNotMatchRouteWithLiteralSeparatomatchefaultsButNoValue() { RunTest( "{controller}/{language}-{locale}", "/foo", new RouteValueDictionary(new { language = "en", locale = "US" }), null); } [Fact] public void TryMatch_DoesNotMatchesRouteWithLiteralSeparatomatchefaultsAndLeftValue() { RunTest( "{controller}/{language}-{locale}", "/foo/xx-", new RouteValueDictionary(new { language = "en", locale = "US" }), null); } [Fact] public void TryMatch_DoesNotMatchesRouteWithLiteralSeparatomatchefaultsAndRightValue() { RunTest( "{controller}/{language}-{locale}", "/foo/-yy", new RouteValueDictionary(new { language = "en", locale = "US" }), null); } [Fact] public void TryMatch_MatchesRouteWithLiteralSeparatomatchefaultsAndValue() { RunTest( "{controller}/{language}-{locale}", "/foo/xx-yy", new RouteValueDictionary(new { language = "en", locale = "US" }), new RouteValueDictionary { { "language", "xx" }, { "locale", "yy" }, { "controller", "foo" } }); } [Fact] public void TryMatch_SetsOptionalParameter() { // Arrange var route = CreateMatcher("{controller}/{action?}"); var url = "/Home/Index"; var values = new RouteValueDictionary(); // Act var match = route.TryMatch(url, values); // Assert Assert.True(match); Assert.Equal(2, values.Count); Assert.Equal("Home", values["controller"]); Assert.Equal("Index", values["action"]); } [Fact] public void TryMatch_DoesNotSetOptionalParameter() { // Arrange var route = CreateMatcher("{controller}/{action?}"); var url = "/Home"; var values = new RouteValueDictionary(); // Act var match = route.TryMatch(url, values); // Assert Assert.True(match); Assert.Single(values); Assert.Equal("Home", values["controller"]); Assert.False(values.ContainsKey("action")); } [Fact] public void TryMatch_DoesNotSetOptionalParameter_EmptyString() { // Arrange var route = CreateMatcher("{controller?}"); var url = ""; var values = new RouteValueDictionary(); // Act var match = route.TryMatch(url, values); // Assert Assert.True(match); Assert.Empty(values); Assert.False(values.ContainsKey("controller")); } [Fact] public void TryMatch__EmptyRouteWith_EmptyString() { // Arrange var route = CreateMatcher(""); var url = ""; var values = new RouteValueDictionary(); // Act var match = route.TryMatch(url, values); // Assert Assert.True(match); Assert.Empty(values); } [Fact] public void TryMatch_MultipleOptionalParameters() { // Arrange var route = CreateMatcher("{controller}/{action?}/{id?}"); var url = "/Home/Index"; var values = new RouteValueDictionary(); // Act var match = route.TryMatch(url, values); // Assert Assert.True(match); Assert.Equal(2, values.Count); Assert.Equal("Home", values["controller"]); Assert.Equal("Index", values["action"]); Assert.False(values.ContainsKey("id")); } [Theory] [InlineData("///")] [InlineData("/a//")] [InlineData("/a/b//")] [InlineData("//b//")] [InlineData("///c")] [InlineData("///c/")] public void TryMatch_MultipleOptionalParameters_WithEmptyIntermediateSegmentsDoesNotMatch(string url) { // Arrange var route = CreateMatcher("{controller?}/{action?}/{id?}"); var values = new RouteValueDictionary(); // Act var match = route.TryMatch(url, values); // Assert Assert.False(match); } [Theory] [InlineData("")] [InlineData("/")] [InlineData("/a")] [InlineData("/a/")] [InlineData("/a/b")] [InlineData("/a/b/")] [InlineData("/a/b/c")] [InlineData("/a/b/c/")] public void TryMatch_MultipleOptionalParameters_WithIncrementalOptionalValues(string url) { // Arrange var route = CreateMatcher("{controller?}/{action?}/{id?}"); var values = new RouteValueDictionary(); // Act var match = route.TryMatch(url, values); // Assert Assert.True(match); } [Theory] [InlineData("///")] [InlineData("////")] [InlineData("/a//")] [InlineData("/a///")] [InlineData("//b/")] [InlineData("//b//")] [InlineData("///c")] [InlineData("///c/")] public void TryMatch_MultipleParameters_WithEmptyValues(string url) { // Arrange var route = CreateMatcher("{controller}/{action}/{id}"); var values = new RouteValueDictionary(); // Act var match = route.TryMatch(url, values); // Assert Assert.False(match); } [Theory] [InlineData("/a/b/c//")] [InlineData("/a/b/c/////")] public void TryMatch_CatchAllParameters_WithEmptyValuesAtTheEnd(string url) { // Arrange var route = CreateMatcher("{controller}/{action}/{*id}"); var values = new RouteValueDictionary(); // Act var match = route.TryMatch(url, values); // Assert Assert.True(match); } [Theory] [InlineData("/a/b//")] [InlineData("/a/b///c")] public void TryMatch_CatchAllParameters_WithEmptyValues(string url) { // Arrange var route = CreateMatcher("{controller}/{action}/{*id}"); var values = new RouteValueDictionary(); // Act var match = route.TryMatch(url, values); // Assert Assert.False(match); } private TemplateMatcher CreateMatcher(string template, object defaults = null) { return new TemplateMatcher( TemplateParser.Parse(template), new RouteValueDictionary(defaults)); } private static void RunTest( string template, string path, RouteValueDictionary defaults, IDictionary<string, object> expected) { // Arrange var matcher = new TemplateMatcher( TemplateParser.Parse(template), defaults ?? new RouteValueDictionary()); var values = new RouteValueDictionary(); // Act var match = matcher.TryMatch(new PathString(path), values); // Assert if (expected == null) { Assert.False(match); } else { Assert.True(match); Assert.Equal(expected.Count, values.Count); foreach (string key in values.Keys) { Assert.Equal(expected[key], values[key]); } } } private static IInlineConstraintResolver GetInlineConstraintResolver() { var services = new ServiceCollection().AddOptions(); var serviceProvider = services.BuildServiceProvider(); var accessor = serviceProvider.GetRequiredService<IOptions<RouteOptions>>(); return new DefaultInlineConstraintResolver(accessor); } } }
30.874891
182
0.492888
1e60f1f39da0095da6c6e936c859718de6abad45
1,978
cs
C#
tags/DeepLoad sample v.1.0.0/SelfLoad.Business/ERCLevel/D06Level111.cs
CslaGenFork/CslaGenFork
e3587367897bf54c2c41997fdeb32b3d5523b078
[ "MIT" ]
11
2017-09-13T11:47:08.000Z
2021-07-28T07:59:12.000Z
tags/DeepLoad sample v.1.0.0/SelfLoad.Business/ERCLevel/D06Level111.cs
MarimerLLC/CslaGenFork
e3587367897bf54c2c41997fdeb32b3d5523b078
[ "MIT" ]
58
2017-09-13T19:19:00.000Z
2019-04-14T20:35:43.000Z
tags/DeepLoad sample v.1.0.0/SelfLoad.Business/ERCLevel/D06Level111.cs
MarimerLLC/CslaGenFork
e3587367897bf54c2c41997fdeb32b3d5523b078
[ "MIT" ]
15
2017-09-13T09:57:04.000Z
2021-12-29T11:30:34.000Z
using SelfLoad.Business; namespace SelfLoad.Business.ERCLevel { public partial class D06Level111 { #region Pseudo Event Handlers //partial void OnCreate(DataPortalHookArgs args) //{ // throw new System.Exception("The method or operation is not implemented."); //} //partial void OnDeletePre(DataPortalHookArgs args) //{ // throw new System.Exception("The method or operation is not implemented."); //} //partial void OnDeletePost(DataPortalHookArgs args) //{ // throw new System.Exception("The method or operation is not implemented."); //} //partial void OnFetchPre(DataPortalHookArgs args) //{ // throw new System.Exception("The method or operation is not implemented."); //} //partial void OnFetchPost(DataPortalHookArgs args) //{ // throw new System.Exception("The method or operation is not implemented."); //} //partial void OnFetchRead(DataPortalHookArgs args) //{ // throw new System.Exception("The method or operation is not implemented."); //} //partial void OnUpdatePre(DataPortalHookArgs args) //{ // throw new System.Exception("The method or operation is not implemented."); //} //partial void OnUpdatePost(DataPortalHookArgs args) //{ // throw new System.Exception("The method or operation is not implemented."); //} //partial void OnInsertPre(DataPortalHookArgs args) //{ // throw new System.Exception("The method or operation is not implemented."); //} //partial void OnInsertPost(DataPortalHookArgs args) //{ // throw new System.Exception("The method or operation is not implemented."); //} #endregion } }
30.90625
89
0.579373
1e61b0850810ab6964f228f594dab8d0c86aff9a
1,423
cs
C#
src/AspNetCore3x/MiddlewareWebApp/SampleMiddleware.cs
ichiroku11/Sample
ceb5a7ed6c135434e176306c25ce3f412e36831d
[ "Apache-2.0" ]
null
null
null
src/AspNetCore3x/MiddlewareWebApp/SampleMiddleware.cs
ichiroku11/Sample
ceb5a7ed6c135434e176306c25ce3f412e36831d
[ "Apache-2.0" ]
5
2021-01-28T14:19:07.000Z
2021-03-11T23:24:35.000Z
src/MiddlewareWebApp/SampleMiddleware.cs
ichiroku11/dotnet-sample
269b840ee5d92cda8d13f152f2f95aee69796be3
[ "MIT" ]
null
null
null
using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.Json; using System.Threading.Tasks; namespace MiddlewareWebApp { // 参考 // https://docs.microsoft.com/ja-jp/aspnet/core/fundamentals/middleware/write?view=aspnetcore-3.1 // ミドルウェア // - RequestDelegate型のパラメータを持つパブリックコンストラクタ // - HttpContext型のパラメータを持つInvokeメソッドかInvokeAsyncメソッド // を持つ // サンプルミドルウェア public class SampleMiddleware { private static readonly JsonSerializerOptions _options = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase, }; private readonly RequestDelegate _next; private readonly ILogger _logger; private readonly string _label; public SampleMiddleware(RequestDelegate next, ILogger<SampleMiddleware> logger, string label) { _next = next; _logger = logger; _label = label; } private void Log(HttpContext context, bool beforeRequestDelegate) { var routeValues = context.Request.RouteValues; var json = new { label = _label, beforeRequestDelegate, controller = routeValues["controller"], action = routeValues["action"], }; _logger.LogInformation(JsonSerializer.Serialize(json, _options)); } public async Task InvokeAsync(HttpContext context) { Log(context, true); await _next(context); Log(context, false); } } }
24.964912
98
0.751933
1e61ea0a9f567643a486ea72894a487feeb5824d
1,457
cs
C#
SaintCoinach/Imaging/ImageHeader.cs
shambarick/SaintCoinach-1
60a389a3bb70fb2746e6aa696a2d7b083e92f7f8
[ "WTFPL" ]
266
2015-09-16T20:54:40.000Z
2022-01-04T07:07:27.000Z
SaintCoinach/Imaging/ImageHeader.cs
shambarick/SaintCoinach-1
60a389a3bb70fb2746e6aa696a2d7b083e92f7f8
[ "WTFPL" ]
48
2016-08-24T01:21:03.000Z
2021-05-27T21:26:36.000Z
SaintCoinach/Imaging/ImageHeader.cs
shambarick/SaintCoinach-1
60a389a3bb70fb2746e6aa696a2d7b083e92f7f8
[ "WTFPL" ]
150
2015-11-06T16:43:51.000Z
2022-01-28T20:19:36.000Z
using System; using System.IO; namespace SaintCoinach.Imaging { /// <summary> /// Header of an image file inside SqPack. /// </summary> public class ImageHeader { #region Fields #region Constructor internal byte[] _Buffer; #endregion #endregion #region Properties public int Width { get; private set; } public int Height { get; private set; } public ImageFormat Format { get; private set; } public long EndOfHeader { get; private set; } #endregion #region Constructors #region Constructor public ImageHeader(Stream stream) { const int Length = 0x50; const int FormatOffset = 0x04; const int WidthOffset = 0x08; const int HeightOffset = 0x0A; _Buffer = new byte[Length]; if (stream.Read(_Buffer, 0, Length) != Length) throw new EndOfStreamException(); Width = BitConverter.ToInt16(_Buffer, WidthOffset); Height = BitConverter.ToInt16(_Buffer, HeightOffset); Format = (ImageFormat)BitConverter.ToInt16(_Buffer, FormatOffset); EndOfHeader = stream.Position; } #endregion #endregion public byte[] GetBuffer() { var b = new byte[_Buffer.Length]; Array.Copy(_Buffer, b, b.Length); return b; } } }
24.283333
78
0.566918
1e6213da2718807e9a50aa6a288e2f9a0f4b3ad2
1,670
cs
C#
src/cor64/AssemblyTextSource.cs
bryanperris/cor64
fa5f9d83cefa8136c34ba9cca002114edc926d91
[ "MIT" ]
38
2019-02-16T03:06:19.000Z
2022-03-15T08:39:42.000Z
src/cor64/AssemblyTextSource.cs
bryanperris/cor64
fa5f9d83cefa8136c34ba9cca002114edc926d91
[ "MIT" ]
10
2019-03-11T00:31:33.000Z
2021-01-20T03:33:41.000Z
src/cor64/AssemblyTextSource.cs
bryanperris/cor64
fa5f9d83cefa8136c34ba9cca002114edc926d91
[ "MIT" ]
2
2020-10-19T11:36:22.000Z
2020-11-18T16:31:40.000Z
using cor64.BassSharp; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace cor64 { public class AssemblyTextSource : NamedAssemblySource { StringBuilder m_StringBuilder = new StringBuilder(); List<String> m_AssemblyLines = new List<string>(); private String m_Name; public override String Name => m_Name; public AssemblyTextSource(String name) { m_Name = name; m_StringBuilder.Clear(); m_AssemblyLines.Clear(); } public IList<String> AssemblyLines => m_AssemblyLines; private void Copy() { m_StringBuilder.Clear(); for (int i = 0; i < m_AssemblyLines.Count; i++) { String line = m_AssemblyLines[i] + "\n"; m_StringBuilder.Insert(m_StringBuilder.Length, line); } } public override Stream GetStream() { var s = new MemoryStream(); StreamWriter writer = new StreamWriter(s); Copy(); writer.Write(m_StringBuilder.ToString()); writer.Flush(); return s; } public static AssemblyTextSource operator +(AssemblyTextSource src, String value) { src.AssemblyLines.Add(value); return src; } public static AssemblyTextSource operator -(AssemblyTextSource src, String value) { src.AssemblyLines.Remove(value); return src; } } }
27.377049
90
0.559281
1e632fa276aac22b200a3db663a0cd7f3cad4b82
22,045
cs
C#
vimage/Source/Display/Graphics.cs
Torrunt/vimage
5fa11d2c813ddf06a833cbd55eeccb6a4bc932e2
[ "MIT" ]
57
2015-02-10T11:26:21.000Z
2022-03-31T09:18:15.000Z
vimage/Source/Display/Graphics.cs
Torrunt/vimage
5fa11d2c813ddf06a833cbd55eeccb6a4bc932e2
[ "MIT" ]
26
2015-12-29T09:35:19.000Z
2021-11-06T15:44:14.000Z
vimage/Source/Display/Graphics.cs
Torrunt/vimage
5fa11d2c813ddf06a833cbd55eeccb6a4bc932e2
[ "MIT" ]
11
2016-05-29T14:08:12.000Z
2021-09-22T13:04:36.000Z
using DevIL.Unmanaged; using SFML.Graphics; using SFML.System; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Threading; using Tao.OpenGl; namespace vimage { /// <summary> /// Graphics Manager. /// Loads and stores Textures and AnimatedImageDatas. /// </summary> class Graphics { private static List<Texture> Textures = new List<Texture>(); private static List<string> TextureFileNames = new List<string>(); private static List<AnimatedImageData> AnimatedImageDatas = new List<AnimatedImageData>(); private static List<string> AnimatedImageDataFileNames = new List<string>(); private static List<DisplayObject> SplitTextures = new List<DisplayObject>(); private static List<string> SplitTextureFileNames = new List<string>(); public static uint MAX_TEXTURES = 80; public static uint MAX_ANIMATIONS = 8; public static int TextureMaxSize = (int)Texture.MaximumSize; public static dynamic GetTexture(string fileName) { int index = TextureFileNames.IndexOf(fileName); int splitTextureIndex = SplitTextureFileNames.Count == 0 ? -1 : SplitTextureFileNames.IndexOf(fileName); if (index >= 0) { // Texture Already Exists // move it to the end of the array and return it Texture texture = Textures[index]; string name = TextureFileNames[index]; Textures.RemoveAt(index); TextureFileNames.RemoveAt(index); Textures.Add(texture); TextureFileNames.Add(name); return Textures[Textures.Count - 1]; } else if (splitTextureIndex >= 0) { // Texture Already Exists (as split texture) return SplitTextures[splitTextureIndex]; } else { // New Texture Texture texture = null; DisplayObject textureLarge = null; int imageID = IL.GenerateImage(); IL.BindImage(imageID); IL.Enable(ILEnable.AbsoluteOrigin); IL.SetOriginLocation(DevIL.OriginLocation.UpperLeft); bool loaded = false; using (FileStream fileStream = File.OpenRead(fileName)) loaded = IL.LoadImageFromStream(fileStream); if (loaded) { if (IL.GetImageInfo().Width > TextureMaxSize || IL.GetImageInfo().Height > TextureMaxSize) { // Image is larger than GPU's max texture size - split up textureLarge = GetCutUpTexturesFromBoundImage(TextureMaxSize / 2, fileName); } else { texture = GetTextureFromBoundImage(); if (texture == null) return null; Textures.Add(texture); TextureFileNames.Add(fileName); } // Limit amount of Textures in Memory if (Textures.Count > MAX_TEXTURES) RemoveTexture(); } IL.DeleteImages(new ImageID[] { imageID }); if (texture == null) return textureLarge; else return texture; } } private static Texture GetTextureFromBoundImage() { bool success = IL.ConvertImage(DevIL.DataFormat.RGBA, DevIL.DataType.UnsignedByte); if (!success) return null; int width = IL.GetImageInfo().Width; int height = IL.GetImageInfo().Height; Texture texture = new Texture((uint)width, (uint)height); Texture.Bind(texture); { Gl.glTexImage2D( Gl.GL_TEXTURE_2D, 0, IL.GetInteger(ILIntegerMode.ImageBytesPerPixel), width, height, 0, IL.GetInteger(ILIntegerMode.ImageFormat), ILDefines.IL_UNSIGNED_BYTE, IL.GetData() ); } Texture.Bind(null); return texture; } private static DisplayObject GetCutUpTexturesFromBoundImage(int sectionSize, string fileName = "") { bool success = IL.ConvertImage(DevIL.DataFormat.RGBA, DevIL.DataType.UnsignedByte); if (!success) return null; DisplayObject image = new DisplayObject(); Vector2i size = new Vector2i(IL.GetImageInfo().Width, IL.GetImageInfo().Height); Vector2u amount = new Vector2u((uint)Math.Ceiling(size.X / (float)sectionSize), (uint)Math.Ceiling(size.Y / (float)sectionSize)); Vector2i currentSize = new Vector2i(size.X, size.Y); Vector2i pos = new Vector2i(); for (int iy = 0; iy < amount.Y; iy++) { int h = Math.Min(currentSize.Y, sectionSize); currentSize.Y -= h; currentSize.X = size.X; for (int ix = 0; ix < amount.X; ix++) { int w = Math.Min(currentSize.X, sectionSize); currentSize.X -= w; Texture texture = new Texture((uint)w, (uint)h); IntPtr partPtr = Marshal.AllocHGlobal((w * h) * 4); IL.CopyPixels(pos.X, pos.Y, 0, w, h, 1, DevIL.DataFormat.RGBA, DevIL.DataType.UnsignedByte, partPtr); Texture.Bind(texture); { Gl.glTexImage2D( Gl.GL_TEXTURE_2D, 0, IL.GetInteger(ILIntegerMode.ImageBytesPerPixel), w, h, 0, IL.GetInteger(ILIntegerMode.ImageFormat), ILDefines.IL_UNSIGNED_BYTE, partPtr); } Texture.Bind(null); Marshal.FreeHGlobal(partPtr); Sprite sprite = new Sprite(texture); sprite.Position = new Vector2f(pos.X, pos.Y); image.AddChild(sprite); if (fileName != "") { Textures.Add(texture); TextureFileNames.Add(fileName + "_" + ix.ToString("00") + "_" + iy.ToString("00") + "^"); } pos.X += w; } pos.Y += h; pos.X = 0; } image.Texture.Size = new Vector2u((uint)size.X, (uint)size.Y); SplitTextures.Add(image); SplitTextureFileNames.Add(fileName); return image; } public static Sprite GetSpriteFromIcon(string fileName) { int index = TextureFileNames.IndexOf(fileName); if (index >= 0) { // Texture Already Exists // move it to the end of the array and return it Texture texture = Textures[index]; string name = TextureFileNames[index]; Textures.RemoveAt(index); TextureFileNames.RemoveAt(index); Textures.Add(texture); TextureFileNames.Add(name); return new Sprite(Textures[Textures.Count - 1]); } else { // New Texture (from .ico) try { System.Drawing.Icon icon = new System.Drawing.Icon(fileName, 256, 256); System.Drawing.Bitmap iconImage = ExtractVistaIcon(icon); if (iconImage == null) iconImage = icon.ToBitmap(); Sprite iconSprite; using (MemoryStream iconStream = new MemoryStream()) { iconImage.Save(iconStream, System.Drawing.Imaging.ImageFormat.Png); Texture iconTexture = new Texture(iconStream); Textures.Add(iconTexture); TextureFileNames.Add(fileName); iconSprite = new Sprite(new Texture(iconTexture)); } return iconSprite; } catch (Exception) { } } return null; } // http://stackoverflow.com/questions/220465/using-256-x-256-vista-icon-in-application/1945764#1945764 // Based on: http://www.codeproject.com/KB/cs/IconExtractor.aspx // And a hint from: http://www.codeproject.com/KB/cs/IconLib.aspx public static System.Drawing.Bitmap ExtractVistaIcon(System.Drawing.Icon icoIcon) { System.Drawing.Bitmap bmpPngExtracted = null; try { byte[] srcBuf = null; using (MemoryStream stream = new MemoryStream()) { icoIcon.Save(stream); srcBuf = stream.ToArray(); } const int SizeICONDIR = 6; const int SizeICONDIRENTRY = 16; int iCount = BitConverter.ToInt16(srcBuf, 4); for (int iIndex = 0; iIndex < iCount; iIndex++) { int iWidth = srcBuf[SizeICONDIR + SizeICONDIRENTRY * iIndex]; int iHeight = srcBuf[SizeICONDIR + SizeICONDIRENTRY * iIndex + 1]; int iBitCount = BitConverter.ToInt16(srcBuf, SizeICONDIR + SizeICONDIRENTRY * iIndex + 6); if (iWidth == 0 && iHeight == 0 && iBitCount == 32) { int iImageSize = BitConverter.ToInt32(srcBuf, SizeICONDIR + SizeICONDIRENTRY * iIndex + 8); int iImageOffset = BitConverter.ToInt32(srcBuf, SizeICONDIR + SizeICONDIRENTRY * iIndex + 12); MemoryStream destStream = new MemoryStream(); BinaryWriter writer = new BinaryWriter(destStream); writer.Write(srcBuf, iImageOffset, iImageSize); destStream.Seek(0, SeekOrigin.Begin); bmpPngExtracted = new System.Drawing.Bitmap(destStream); // This is PNG! :) break; } } } catch { return null; } return bmpPngExtracted; } public static Sprite GetSpriteFromSVG(string fileName) { int index = TextureFileNames.IndexOf(fileName); if (index >= 0) { // Texture Already Exists // move it to the end of the array and return it Texture texture = Textures[index]; string name = TextureFileNames[index]; Textures.RemoveAt(index); TextureFileNames.RemoveAt(index); Textures.Add(texture); TextureFileNames.Add(name); return new Sprite(Textures[Textures.Count - 1]); } else { // New Texture (from .svg) try { Svg.SvgDocument svg = Svg.SvgDocument.Open(fileName); System.Drawing.Bitmap bitmap = svg.Draw(); using (MemoryStream stream = new MemoryStream()) { bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Png); Texture texture = new Texture(stream); Textures.Add(texture); TextureFileNames.Add(fileName); return new Sprite(new Texture(texture)); } } catch (Exception) { } } return null; } public static Sprite GetSpriteFromWebP(string fileName) { int index = TextureFileNames.IndexOf(fileName); if (index >= 0) { // Texture Already Exists // move it to the end of the array and return it Texture texture = Textures[index]; string name = TextureFileNames[index]; Textures.RemoveAt(index); TextureFileNames.RemoveAt(index); Textures.Add(texture); TextureFileNames.Add(name); return new Sprite(Textures[Textures.Count - 1]); } else { // New Texture (from .webp) try { var fileBytes = File.ReadAllBytes(fileName); System.Drawing.Bitmap bitmap = new Imazen.WebP.SimpleDecoder().DecodeFromBytes(fileBytes, fileBytes.Length); using (MemoryStream stream = new MemoryStream()) { bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Png); Texture texture = new Texture(stream); Textures.Add(texture); TextureFileNames.Add(fileName); return new Sprite(new Texture(texture)); } } catch (Exception) { } } return null; } /// <param name="filename">Animated Image (ie: animated gif).</param> public static AnimatedImage GetAnimatedImage(string fileName) { return new AnimatedImage(GetAnimatedImageData(fileName)); } /// <param name="filename">Animated Image (ie: animated gif).</param> public static AnimatedImageData GetAnimatedImageData(string fileName) { lock (AnimatedImageDatas) { int index = AnimatedImageDataFileNames.IndexOf(fileName); if (index >= 0) { // AnimatedImageData Already Exists // move it to the end of the array and return it AnimatedImageData data = AnimatedImageDatas[index]; string name = AnimatedImageDataFileNames[index]; AnimatedImageDatas.RemoveAt(index); AnimatedImageDataFileNames.RemoveAt(index); AnimatedImageDatas.Add(data); AnimatedImageDataFileNames.Add(name); return AnimatedImageDatas[AnimatedImageDatas.Count - 1]; } else { // New AnimatedImageData System.Drawing.Image image = System.Drawing.Image.FromFile(fileName); AnimatedImageData data = new AnimatedImageData(); // Store AnimatedImageData AnimatedImageDatas.Add(data); AnimatedImageDataFileNames.Add(fileName); // Limit amount of Animations in Memory if (AnimatedImageDatas.Count > MAX_ANIMATIONS) RemoveAnimatedImage(); // Get Frames LoadingAnimatedImage loadingAnimatedImage = new LoadingAnimatedImage(image, data); Thread loadFramesThread = new Thread(new ThreadStart(loadingAnimatedImage.LoadFrames)) { Name = "AnimationLoadThread - " + fileName, IsBackground = true }; loadFramesThread.Start(); // Wait for at least one frame to be loaded while (data.Frames == null || data.Frames.Length <= 0 || data.Frames[0] == null) { Thread.Sleep(1); } return data; } } } public static void ClearMemory(dynamic image, string file = "") { // Remove all AnimatedImages (except the one that's currently being viewed) int s = image is AnimatedImage ? 1 : 0; int a = 0; while (AnimatedImageDatas.Count > s) { if (s == 1 && (image as AnimatedImage).Data == AnimatedImageDatas[a]) a++; RemoveAnimatedImage(a); } if (image is AnimatedImage) { // Remove all Textures while (TextureFileNames.Count > 0) RemoveTexture(); } else { // Remove all Textures (except ones being used by current image) if (file == "") return; s = 0; a = 0; if (SplitTextureFileNames.Contains(file)) { for (int i = 0; i < TextureFileNames.Count; i++) { if (TextureFileNames[i].IndexOf(file) == 0) s++; else if (s > 0) break; } while (TextureFileNames.Count > s) { if (TextureFileNames[a].IndexOf(file) == 0) a += s; RemoveTexture(a); } } else { while (TextureFileNames.Count > 1) { if (TextureFileNames[a] == file) a++; RemoveTexture(a); } } } } public static void RemoveTexture(int t = 0) { if (TextureFileNames[t].IndexOf('^') == TextureFileNames[t].Length - 1) { // if part of split texture - remove all parts string name = TextureFileNames[t].Substring(0, TextureFileNames[t].Length - 7); int i = t; for (i = t + 1; i < TextureFileNames.Count; i++) { if (TextureFileNames[i].IndexOf(name) != 0) break; } for (int d = t; d < i; d++) { Textures[t]?.Dispose(); Textures.RemoveAt(t); TextureFileNames.RemoveAt(t); } int splitIndex = SplitTextureFileNames.Count == 0 ? -1 : SplitTextureFileNames.IndexOf(name); if (splitIndex != -1) { SplitTextures.RemoveAt(splitIndex); SplitTextureFileNames.RemoveAt(splitIndex); } } else { Textures[t]?.Dispose(); Textures.RemoveAt(t); TextureFileNames.RemoveAt(t); } } public static void RemoveAnimatedImage(int a = 0) { AnimatedImageDatas[a].CancelLoading = true; for (int i = 0; i < AnimatedImageDatas[a].Frames.Length; i++) AnimatedImageDatas[a]?.Frames[i]?.Dispose(); AnimatedImageDatas.RemoveAt(a); AnimatedImageDataFileNames.RemoveAt(a); } } class LoadingAnimatedImage { private System.Drawing.Image Image; private ImageManipulation.OctreeQuantizer Quantizer; private AnimatedImageData Data; public LoadingAnimatedImage(System.Drawing.Image image, AnimatedImageData data) { Image = image; Data = data; } public void LoadFrames() { // Get Frame Count System.Drawing.Imaging.FrameDimension frameDimension = new System.Drawing.Imaging.FrameDimension(Image.FrameDimensionsList[0]); Data.FrameCount = Image.GetFrameCount(frameDimension); Data.Frames = new Texture[Data.FrameCount]; Data.FrameDelays = new int[Data.FrameCount]; // Get Frame Delays byte[] frameDelays = null; try { System.Drawing.Imaging.PropertyItem frameDelaysItem = Image.GetPropertyItem(0x5100); frameDelays = frameDelaysItem.Value; if (frameDelays.Length == 0 || (frameDelays[0] == 0 && frameDelays.All(d => d == 0))) frameDelays = null; } catch { } int defaultFrameDelay = AnimatedImage.DEFAULT_FRAME_DELAY; if (frameDelays != null && frameDelays.Length > 1) defaultFrameDelay = (frameDelays[0] + frameDelays[1] * 256) * 10; for (int i = 0; i < Data.FrameCount; i++) { if (Data.CancelLoading) return; Image.SelectActiveFrame(frameDimension, i); Quantizer = new ImageManipulation.OctreeQuantizer(255, 8); System.Drawing.Bitmap quantized = Quantizer.Quantize(Image); MemoryStream stream = new MemoryStream(); quantized.Save(stream, System.Drawing.Imaging.ImageFormat.Png); Data.Frames[i] = new Texture(stream); stream.Dispose(); if (Data.CancelLoading) return; Data.Frames[i].Smooth = Data.Smooth; Data.Frames[i].Mipmap = Data.Mipmap; var fd = i * 4; if (frameDelays != null && frameDelays.Length > fd) Data.FrameDelays[i] = (frameDelays[fd] + frameDelays[fd + 1] * 256) * 10; else Data.FrameDelays[i] = defaultFrameDelay; } Data.FullyLoaded = true; } } }
38.33913
141
0.493037
1e641e716bbc3da8f5f9742de903c9355cb40f9d
4,827
cs
C#
src/USD.NET/generated/pxr/base/js/JsValue.cs
Secticide/usd-unity-sdk
29bef55be7d580b63fb47efcf946a2cd89051bb2
[ "Apache-2.0" ]
2
2020-12-23T14:05:29.000Z
2021-02-11T21:13:22.000Z
src/USD.NET/generated/pxr/base/js/JsValue.cs
prefrontalcortex/usd-unity-sdk
29bef55be7d580b63fb47efcf946a2cd89051bb2
[ "Apache-2.0" ]
null
null
null
src/USD.NET/generated/pxr/base/js/JsValue.cs
prefrontalcortex/usd-unity-sdk
29bef55be7d580b63fb47efcf946a2cd89051bb2
[ "Apache-2.0" ]
null
null
null
//------------------------------------------------------------------------------ // <auto-generated /> // // This file was automatically generated by SWIG (http://www.swig.org). // Version 3.0.12 // // Do not make changes to this file unless you know what you are doing--modify // the SWIG interface file instead. //------------------------------------------------------------------------------ namespace pxr { public class JsValue : global::System.IDisposable { private global::System.Runtime.InteropServices.HandleRef swigCPtr; protected bool swigCMemOwn; internal JsValue(global::System.IntPtr cPtr, bool cMemoryOwn) { swigCMemOwn = cMemoryOwn; swigCPtr = new global::System.Runtime.InteropServices.HandleRef(this, cPtr); } internal static global::System.Runtime.InteropServices.HandleRef getCPtr(JsValue obj) { return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr; } ~JsValue() { Dispose(); } public virtual void Dispose() { lock(this) { if (swigCPtr.Handle != global::System.IntPtr.Zero) { if (swigCMemOwn) { swigCMemOwn = false; UsdCsPINVOKE.delete_JsValue(swigCPtr); } swigCPtr = new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero); } global::System.GC.SuppressFinalize(this); } } public JsValue() : this(UsdCsPINVOKE.new_JsValue__SWIG_0(), true) { } public JsValue(JsObject value) : this(UsdCsPINVOKE.new_JsValue__SWIG_1(JsObject.getCPtr(value)), true) { if (UsdCsPINVOKE.SWIGPendingException.Pending) throw UsdCsPINVOKE.SWIGPendingException.Retrieve(); } public JsValue(JsObjectVector value) : this(UsdCsPINVOKE.new_JsValue__SWIG_3(JsObjectVector.getCPtr(value)), true) { if (UsdCsPINVOKE.SWIGPendingException.Pending) throw UsdCsPINVOKE.SWIGPendingException.Retrieve(); } public JsValue(string value) : this(UsdCsPINVOKE.new_JsValue__SWIG_5(value), true) { } public JsValue(SWIGTYPE_p_std__string value) : this(UsdCsPINVOKE.new_JsValue__SWIG_7(SWIGTYPE_p_std__string.getCPtr(value)), true) { if (UsdCsPINVOKE.SWIGPendingException.Pending) throw UsdCsPINVOKE.SWIGPendingException.Retrieve(); } public JsValue(bool value) : this(UsdCsPINVOKE.new_JsValue__SWIG_8(value), true) { } public JsValue(int value) : this(UsdCsPINVOKE.new_JsValue__SWIG_9(value), true) { } public JsValue(long value) : this(UsdCsPINVOKE.new_JsValue__SWIG_10(value), true) { } public JsValue(ulong value) : this(UsdCsPINVOKE.new_JsValue__SWIG_11(value), true) { } public JsValue(double value) : this(UsdCsPINVOKE.new_JsValue__SWIG_12(value), true) { } public JsObject GetJsObject() { JsObject ret = new JsObject(UsdCsPINVOKE.JsValue_GetJsObject(swigCPtr), false); return ret; } public JsObjectVector GetJsArray() { JsObjectVector ret = new JsObjectVector(UsdCsPINVOKE.JsValue_GetJsArray(swigCPtr), false); return ret; } public string GetString() { string ret = UsdCsPINVOKE.JsValue_GetString(swigCPtr); return ret; } public bool GetBool() { bool ret = UsdCsPINVOKE.JsValue_GetBool(swigCPtr); return ret; } public int GetInt() { int ret = UsdCsPINVOKE.JsValue_GetInt(swigCPtr); return ret; } public long GetInt64() { long ret = UsdCsPINVOKE.JsValue_GetInt64(swigCPtr); return ret; } public ulong GetUInt64() { ulong ret = UsdCsPINVOKE.JsValue_GetUInt64(swigCPtr); return ret; } public double GetReal() { double ret = UsdCsPINVOKE.JsValue_GetReal(swigCPtr); return ret; } public JsValue.Type GetType() { JsValue.Type ret = (JsValue.Type)UsdCsPINVOKE.JsValue_GetType(swigCPtr); return ret; } public string GetTypeName() { string ret = UsdCsPINVOKE.JsValue_GetTypeName(swigCPtr); return ret; } public bool IsObject() { bool ret = UsdCsPINVOKE.JsValue_IsObject(swigCPtr); return ret; } public bool IsArray() { bool ret = UsdCsPINVOKE.JsValue_IsArray(swigCPtr); return ret; } public bool IsString() { bool ret = UsdCsPINVOKE.JsValue_IsString(swigCPtr); return ret; } public bool IsBool() { bool ret = UsdCsPINVOKE.JsValue_IsBool(swigCPtr); return ret; } public bool IsInt() { bool ret = UsdCsPINVOKE.JsValue_IsInt(swigCPtr); return ret; } public bool IsReal() { bool ret = UsdCsPINVOKE.JsValue_IsReal(swigCPtr); return ret; } public bool IsUInt64() { bool ret = UsdCsPINVOKE.JsValue_IsUInt64(swigCPtr); return ret; } public bool IsNull() { bool ret = UsdCsPINVOKE.JsValue_IsNull(swigCPtr); return ret; } public enum Type { ObjectType, ArrayType, StringType, BoolType, IntType, RealType, NullType } } }
26.96648
134
0.683447
1e6471c7b0094569857c609d3c7e2c733c3d8d43
3,928
cs
C#
ToolRegFB/frm_progress.cs
drakelam/Tool-Register-Facebook
3f5da2222fcf884ff724a362a065385ebac821f7
[ "MIT" ]
1
2022-03-21T10:13:44.000Z
2022-03-21T10:13:44.000Z
ToolRegFB/frm_progress.cs
drakelam/Tool-Register-Facebook
3f5da2222fcf884ff724a362a065385ebac821f7
[ "MIT" ]
null
null
null
ToolRegFB/frm_progress.cs
drakelam/Tool-Register-Facebook
3f5da2222fcf884ff724a362a065385ebac821f7
[ "MIT" ]
null
null
null
using System; using System.ComponentModel; using System.Drawing; using System.IO; using System.IO.Compression; using System.Net; using System.Windows.Forms; using Bunifu.Framework.UI; namespace ToolRegFB { // Token: 0x02000042 RID: 66 public partial class frm_progress : Form { // Token: 0x060002D9 RID: 729 RVA: 0x000365ED File Offset: 0x000347ED public frm_progress() { this.InitializeComponent(); this.lblLoading.Text = "<<< <<< <<< <<< <<< "; } // Token: 0x060002DA RID: 730 RVA: 0x00036616 File Offset: 0x00034816 private void timer1_Tick(object sender, EventArgs e) { this.lblLoading.Text = this.lblLoading.Text.Substring(1) + this.lblLoading.Text.Substring(0, 1); } // Token: 0x060002DB RID: 731 RVA: 0x00036650 File Offset: 0x00034850 private void frm_progress_Load(object sender, EventArgs e) { try { ServicePointManager.Expect100Continue = true; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; string hostname = frmUpdate.hostname; bool flag = InternetConnection.IsConnectedToInternet(); bool flag2 = flag; if (flag2) { WebClient webClient = new WebClient(); webClient.DownloadFileCompleted += this.udcom_file; Uri address = new Uri(hostname + frmUpdate.softname + ".zip"); webClient.DownloadFileAsync(address, "./update/" + frmUpdate.softname + ".zip"); } else { MessageBox.Show("No internet connect.Please check your network!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); Application.Exit(); } } catch (Exception ex) { MessageBox.Show("Error: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Hand); Application.Exit(); } } // Token: 0x060002DC RID: 732 RVA: 0x0003672C File Offset: 0x0003492C public void Copy(string sourceDirectory, string targetDirectory) { DirectoryInfo source = new DirectoryInfo(sourceDirectory); DirectoryInfo target = new DirectoryInfo(targetDirectory); this.CopyAll(source, target); } // Token: 0x060002DD RID: 733 RVA: 0x00036754 File Offset: 0x00034954 public void CopyAll(DirectoryInfo source, DirectoryInfo target) { Directory.CreateDirectory(target.FullName); int num = 1; foreach (FileInfo fileInfo in source.GetFiles()) { Application.DoEvents(); fileInfo.CopyTo(Path.Combine(target.FullName, fileInfo.Name), true); num++; } foreach (DirectoryInfo directoryInfo in source.GetDirectories()) { DirectoryInfo target2 = target.CreateSubdirectory(directoryInfo.Name); this.CopyAll(directoryInfo, target2); } } // Token: 0x060002DE RID: 734 RVA: 0x000367F0 File Offset: 0x000349F0 private void udcom_file(object sender, AsyncCompletedEventArgs e) { try { bool flag = Directory.Exists("./update/" + frmUpdate.softname); bool flag2 = flag; if (flag2) { Directory.Delete("./update/" + frmUpdate.softname, true); } ZipFile.ExtractToDirectory("./update/" + frmUpdate.softname + ".zip", "./update/"); try { string sourceDirectory = "./update/" + frmUpdate.softname + "/"; string startupPath = Application.StartupPath; this.Copy(sourceDirectory, startupPath); } catch (Exception ex) { MessageBox.Show("Update fail:" + ex.Message); return; } bool flag3 = File.Exists("./update/" + frmUpdate.softname + ".zip"); bool flag4 = flag3; if (flag4) { File.Delete("./update/" + frmUpdate.softname + ".zip"); } bool flag5 = Directory.Exists("./update/" + frmUpdate.softname); bool flag6 = flag5; if (flag6) { Directory.Delete("./update/" + frmUpdate.softname, true); } this.timer1.Stop(); } catch (Exception ex2) { MessageBox.Show("Error: " + ex2.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Hand); base.Close(); } finally { base.Close(); } } } }
29.533835
131
0.675916
1e64822414f1f8fc1921fcd99f4e4389d5a35dd2
5,123
cs
C#
src/KubernetesConfiguration/generated/api/Models/Api20220301/ExtensionPropertiesAksAssignedIdentity.cs
jago2136/azure-powershell
acae7332d65828c99d2862a6e819e8876074e14d
[ "MIT" ]
null
null
null
src/KubernetesConfiguration/generated/api/Models/Api20220301/ExtensionPropertiesAksAssignedIdentity.cs
jago2136/azure-powershell
acae7332d65828c99d2862a6e819e8876074e14d
[ "MIT" ]
null
null
null
src/KubernetesConfiguration/generated/api/Models/Api20220301/ExtensionPropertiesAksAssignedIdentity.cs
jago2136/azure-powershell
acae7332d65828c99d2862a6e819e8876074e14d
[ "MIT" ]
null
null
null
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20220301 { using static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Extensions; /// <summary>Identity of the Extension resource in an AKS cluster</summary> public partial class ExtensionPropertiesAksAssignedIdentity : Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20220301.IExtensionPropertiesAksAssignedIdentity, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20220301.IExtensionPropertiesAksAssignedIdentityInternal { /// <summary>Internal Acessors for PrincipalId</summary> string Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20220301.IExtensionPropertiesAksAssignedIdentityInternal.PrincipalId { get => this._principalId; set { {_principalId = value;} } } /// <summary>Internal Acessors for TenantId</summary> string Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20220301.IExtensionPropertiesAksAssignedIdentityInternal.TenantId { get => this._tenantId; set { {_tenantId = value;} } } /// <summary>Backing field for <see cref="PrincipalId" /> property.</summary> private string _principalId; /// <summary>The principal ID of resource identity.</summary> [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Owned)] public string PrincipalId { get => this._principalId; } /// <summary>Backing field for <see cref="TenantId" /> property.</summary> private string _tenantId; /// <summary>The tenant ID of resource.</summary> [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Owned)] public string TenantId { get => this._tenantId; } /// <summary>Backing field for <see cref="Type" /> property.</summary> private Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.AksIdentityType? _type; /// <summary>The identity type.</summary> [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Owned)] public Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.AksIdentityType? Type { get => this._type; set => this._type = value; } /// <summary>Creates an new <see cref="ExtensionPropertiesAksAssignedIdentity" /> instance.</summary> public ExtensionPropertiesAksAssignedIdentity() { } } /// Identity of the Extension resource in an AKS cluster public partial interface IExtensionPropertiesAksAssignedIdentity : Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IJsonSerializable { /// <summary>The principal ID of resource identity.</summary> [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( Required = false, ReadOnly = true, Description = @"The principal ID of resource identity.", SerializedName = @"principalId", PossibleTypes = new [] { typeof(string) })] string PrincipalId { get; } /// <summary>The tenant ID of resource.</summary> [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( Required = false, ReadOnly = true, Description = @"The tenant ID of resource.", SerializedName = @"tenantId", PossibleTypes = new [] { typeof(string) })] string TenantId { get; } /// <summary>The identity type.</summary> [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( Required = false, ReadOnly = false, Description = @"The identity type.", SerializedName = @"type", PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.AksIdentityType) })] Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.AksIdentityType? Type { get; set; } } /// Identity of the Extension resource in an AKS cluster internal partial interface IExtensionPropertiesAksAssignedIdentityInternal { /// <summary>The principal ID of resource identity.</summary> string PrincipalId { get; set; } /// <summary>The tenant ID of resource.</summary> string TenantId { get; set; } /// <summary>The identity type.</summary> Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.AksIdentityType? Type { get; set; } } }
56.296703
215
0.710521
1e65c8c9ed86c8e71b2da7a315eeba6e7ba87923
1,857
cs
C#
src/Tests/Aggregations/Bucket/IpRange/IpRangeAggregationUsageTests.cs
nettsundere/elasticsearch-net
6b7ba8a4d765199161806542dad48cf553275df5
[ "Apache-2.0" ]
null
null
null
src/Tests/Aggregations/Bucket/IpRange/IpRangeAggregationUsageTests.cs
nettsundere/elasticsearch-net
6b7ba8a4d765199161806542dad48cf553275df5
[ "Apache-2.0" ]
null
null
null
src/Tests/Aggregations/Bucket/IpRange/IpRangeAggregationUsageTests.cs
nettsundere/elasticsearch-net
6b7ba8a4d765199161806542dad48cf553275df5
[ "Apache-2.0" ]
null
null
null
using System; using System.Collections.Generic; using FluentAssertions; using Nest; using Tests.Framework; using Tests.Framework.Integration; using Tests.Framework.ManagedElasticsearch.Clusters; using Tests.Framework.MockData; using static Nest.Infer; namespace Tests.Aggregations.Bucket.IpRange { [SkipVersion("5.0.0-alpha2", "broken in this release. error reason: Expected numeric type on field [leadDeveloper.iPAddress], but got [ip]")] public class IpRangeAggregationUsageTests : AggregationUsageTestBase { public IpRangeAggregationUsageTests(ReadOnlyCluster i, EndpointUsage usage) : base(i, usage) { } protected override object AggregationJson => new { ip_ranges = new { ip_range = new { field = "leadDeveloper.ipAddress", ranges = new object[] { new {to = "127.0.0.1"}, new {from = "127.0.0.1"} } } } }; protected override Func<AggregationContainerDescriptor<Project>, IAggregationContainer> FluentAggs => a => a .IpRange("ip_ranges", ip => ip .Field(p => p.LeadDeveloper.IpAddress) .Ranges( r => r.To("127.0.0.1"), r => r.From("127.0.0.1") ) ); protected override AggregationDictionary InitializerAggs => new IpRangeAggregation("ip_ranges") { Field = Field((Project p) => p.LeadDeveloper.IpAddress), Ranges = new List<Nest.IpRange> { new Nest.IpRange {To = "127.0.0.1"}, new Nest.IpRange {From = "127.0.0.1"} } }; protected override void ExpectResponse(ISearchResponse<Project> response) { response.ShouldBeValid(); var ipRanges = response.Aggregations.IpRange("ip_ranges"); ipRanges.Should().NotBeNull(); ipRanges.Buckets.Should().NotBeNull(); ipRanges.Buckets.Count.Should().BeGreaterThan(0); foreach (var range in ipRanges.Buckets) range.DocCount.Should().BeGreaterThan(0); } } }
28.136364
142
0.690361
1e6702e8590940a59bb107e5f9fc1f62745cc1f8
2,886
cs
C#
toolkit/Win32/AcceleratorVirtualKey.cs
fearthecowboy/coapp
32aba5f9636ebaa155bd023a6bc8eef0125c0b5a
[ "Apache-2.0" ]
null
null
null
toolkit/Win32/AcceleratorVirtualKey.cs
fearthecowboy/coapp
32aba5f9636ebaa155bd023a6bc8eef0125c0b5a
[ "Apache-2.0" ]
null
null
null
toolkit/Win32/AcceleratorVirtualKey.cs
fearthecowboy/coapp
32aba5f9636ebaa155bd023a6bc8eef0125c0b5a
[ "Apache-2.0" ]
1
2019-12-06T09:44:43.000Z
2019-12-06T09:44:43.000Z
//----------------------------------------------------------------------- // <copyright company="CoApp Project"> // ResourceLib Original Code from http://resourcelib.codeplex.com // Original Copyright (c) 2008-2009 Vestris Inc. // Changes Copyright (c) 2011 Garrett Serack . All rights reserved. // </copyright> // <license> // MIT License // You may freely use and distribute this software under the terms of the following license agreement. // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated // documentation files (the "Software"), to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and // to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of // the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE // </license> //----------------------------------------------------------------------- namespace CoApp.Toolkit.Win32 { /// <summary> /// Flags, fVirt field of the Accelerator table structure. /// </summary> public enum AcceleratorVirtualKey : uint { /// <summary> /// Virtual key. /// </summary> VIRTKEY = 0x01, /// <summary> /// Specifies that no top-level menu item is highlighted when the accelerator is used. This is useful when defining accelerators for actions such as scrolling that do not correspond to a menu item. If NOINVERT is omitted, a top-level menu item will be highlighted (if possible) when the accelerator is used. /// </summary> NOINVERT = 0x02, /// <summary> /// Causes the accelerator to be activated only if the SHIFT key is down. Applies only to virtual keys. /// </summary> SHIFT = 0x04, /// <summary> /// Causes the accelerator to be activated only if the CONTROL key is down. Applies only to virtual keys. /// </summary> CONTROL = 0x08, /// <summary> /// Causes the accelerator to be activated only if the ALT key is down. Applies only to virtual keys. /// </summary> ALT = 0x10 } }
51.535714
318
0.63964
1e67250ccb0136efc4f71029cebb522b41890d0d
2,375
cs
C#
Samples/XLabs.Sample/ViewModel/BluetoothViewModel.cs
jdluzen/Xamarin-Forms-Labs
78c0a3aa63cd990bee4ac831171cb427b6b1e231
[ "Apache-2.0" ]
null
null
null
Samples/XLabs.Sample/ViewModel/BluetoothViewModel.cs
jdluzen/Xamarin-Forms-Labs
78c0a3aa63cd990bee4ac831171cb427b6b1e231
[ "Apache-2.0" ]
null
null
null
Samples/XLabs.Sample/ViewModel/BluetoothViewModel.cs
jdluzen/Xamarin-Forms-Labs
78c0a3aa63cd990bee4ac831171cb427b6b1e231
[ "Apache-2.0" ]
null
null
null
namespace XLabs.Sample.ViewModel { using System.Collections.Generic; using System.Linq; using System.Windows.Input; using Platform.Device; using XLabs.Data; public class BluetoothViewModel : ObservableObject { private readonly IBluetoothHub hub; private readonly RelayCommand scan; private readonly RelayCommand openSettings; //private readonly RelayCommand findSerialPorts; private IReadOnlyCollection<IBluetoothDevice> devices; private IReadOnlyCollection<string> serialPorts; private bool isBusy; public BluetoothViewModel(IBluetoothHub hub) { this.hub = hub; this.scan = new RelayCommand(async () => this.Devices = await this.hub.GetPairedDevices(), () => this.Enabled && !this.IsBusy); //this.findSerialPorts = new RelayCommand(async () => this.SerialPorts = await this.hub.FindService(BluetoothServiceType.StandardServices.First(a => a.Type == BluetoothServiceType.ServiceType.SerialPort).ServiceId), () => this.Enabled && !this.IsBusy); this.openSettings = new RelayCommand(async () => await this.hub.OpenSettings(), () => this.hub != null && !this.IsBusy); } public bool Enabled { get { return this.hub != null && this.hub.Enabled; } } public bool IsBusy { get { return this.isBusy; } set { if (this.SetProperty(ref this.isBusy, value)) { this.scan.RaiseCanExecuteChanged(); this.openSettings.RaiseCanExecuteChanged(); //this.findSerialPorts.RaiseCanExecuteChanged(); } } } public IReadOnlyCollection<IBluetoothDevice> Devices { get { return this.devices; } private set { this.SetProperty(ref this.devices, value); } } public IReadOnlyCollection<string> SerialPorts { get { return this.serialPorts; } private set { this.SetProperty(ref this.serialPorts, value); } } public ICommand Scan { get { return this.scan; } } public ICommand OpenSettings { get { return this.openSettings; } } //public ICommand FindSerialPorts { get { return this.findSerialPorts; } } } }
37.698413
264
0.607158
1e67a223421e49295f23b2a6cd9242042fd816cf
11,319
cs
C#
main/OpenCover.Console/ServiceEnvironmentManagement.cs
vdubey1989/opencover
50920ae2dd23b44afaeaae7c99d8a3c8d79e3e42
[ "MIT" ]
75
2017-10-13T06:59:23.000Z
2022-01-24T02:25:18.000Z
main/OpenCover.Console/ServiceEnvironmentManagement.cs
vdubey1989/opencover
50920ae2dd23b44afaeaae7c99d8a3c8d79e3e42
[ "MIT" ]
8
2017-11-03T13:32:25.000Z
2020-11-28T02:30:39.000Z
main/OpenCover.Console/ServiceEnvironmentManagement.cs
vdubey1989/opencover
50920ae2dd23b44afaeaae7c99d8a3c8d79e3e42
[ "MIT" ]
23
2018-01-16T16:06:04.000Z
2021-09-28T07:03:22.000Z
/* ==++== * * Copyright (c) Microsoft Corporation. All rights reserved. * * ==--== * * Class: Form1 * * Description: CLR Profiler interface and logic */ /* * The following was taken from CLRProfiler4 MainFrame.cs * and as such I have retained the Microsft copyright * statement. */ using System; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using System.Text; using OpenCover.Framework; namespace OpenCover.Console { class ServiceEnvironmentManagementEx : ServiceEnvironmentManagement { public static bool IsServiceDisabled(string serviceName) { var entry = GetServiceKey(serviceName); return entry != null && (int)entry.GetValue("Start") == 4; } public static bool IsServiceStartAutomatic(string serviceName) { var entry = GetServiceKey(serviceName); return entry != null && (int)entry.GetValue("Start") == 2; } } class ServiceEnvironmentManagement { private string _serviceAccountSid; private string _serviceName; private string[] _profilerEnvironment; public void PrepareServiceEnvironment(string serviceName, ServiceEnvironment envType, string[] profilerEnvironment) { _serviceName = serviceName; _profilerEnvironment = profilerEnvironment; // this is a bit intricate - if the service is running as LocalSystem, we need to set the environment // variables in the registry for the service, otherwise it's better to temporarily set it for the account, // assuming we can find out the account SID // Network Service works better with environments is better on the service too var serviceAccountName = MachineQualifiedServiceAccountName(_serviceName); if (serviceAccountName != "LocalSystem") { _serviceAccountSid = LookupAccountSid(serviceAccountName); } if (_serviceAccountSid != null && envType != ServiceEnvironment.ByName) { SetAccountEnvironment(_serviceAccountSid, _profilerEnvironment); } else { _serviceAccountSid = null; string[] baseEnvironment = GetServicesEnvironment(); string[] combinedEnvironment = CombineEnvironmentVariables(baseEnvironment, _profilerEnvironment); SetEnvironmentVariables(_serviceName, combinedEnvironment); } } public static string MachineQualifiedServiceAccountName(string serviceName) { string serviceAccountName = GetServiceAccountName(serviceName) ?? string.Empty; if (serviceAccountName.StartsWith(@".\")) { serviceAccountName = Environment.MachineName + serviceAccountName.Substring(1); } else if (serviceAccountName.ToLowerInvariant().Contains("localsystem")) { serviceAccountName = "NT Authority\\SYSTEM"; } return serviceAccountName; } public void ResetServiceEnvironment() { if (_serviceAccountSid != null) { ResetAccountEnvironment(_serviceAccountSid, _profilerEnvironment); } else { DeleteEnvironmentVariables(_serviceName); } } [DllImport("Kernel32.dll")] private static extern bool LocalFree(IntPtr ptr); [DllImport("Advapi32.dll")] private static extern bool ConvertSidToStringSidW(byte[] sid, out IntPtr stringSid); [DllImport("Advapi32.dll")] private static extern bool LookupAccountName(string machineName, string accountName, byte[] sid, ref int sidLen, StringBuilder domainName, ref int domainNameLen, out int peUse); [DllImport("Kernel32.dll")] private static extern IntPtr OpenProcess( uint dwDesiredAccess, // access flag bool bInheritHandle, // handle inheritance option int dwProcessId // process identifier ); [DllImport("Advapi32.dll")] private static extern bool OpenProcessToken( IntPtr ProcessHandle, uint DesiredAccess, ref IntPtr TokenHandle ); [DllImport("UserEnv.dll")] private static extern bool CreateEnvironmentBlock( out IntPtr lpEnvironment, IntPtr hToken, bool bInherit); private void SetEnvironmentVariables(string serviceName, string[] environment) { Microsoft.Win32.RegistryKey key = GetServiceKey(serviceName); if (key != null) key.SetValue("Environment", environment); } private static string[] CombineEnvironmentVariables(string[] a, string[] b) { return a.Concat(b).ToArray(); } private string[] GetServicesEnvironment() { Process[] servicesProcesses = Process.GetProcessesByName("services"); if (servicesProcesses == null || servicesProcesses.Length != 1) { servicesProcesses = Process.GetProcessesByName("services.exe"); if (servicesProcesses == null || servicesProcesses.Length != 1) return new string[0]; } Process servicesProcess = servicesProcesses[0]; IntPtr processHandle = OpenProcess(0x20400, false, servicesProcess.Id); if (processHandle == IntPtr.Zero) { // Seems that there will be a problem with anything but windows XP/2003 here // using PROCESS_QUERY_LIMITED_INFORMATION (0x1000) instead //http://msdn.microsoft.com/en-us/library/windows/desktop/ms684880%28v=vs.85%29.aspx processHandle = OpenProcess(0x1000, false, servicesProcess.Id); if (processHandle == IntPtr.Zero) return new string[0]; } IntPtr tokenHandle = IntPtr.Zero; if (!OpenProcessToken(processHandle, 0x20008, ref tokenHandle)) return new string[0]; IntPtr environmentPtr; if (!CreateEnvironmentBlock(out environmentPtr, tokenHandle, false)) return new string[0]; unsafe { string[] envStrings = null; // rather than duplicate the code that walks over the environment, // we have this funny loop where the first iteration just counts the strings, // and the second iteration fills in the strings for (int i = 0; i < 2; i++) { char* env = (char*)environmentPtr.ToPointer(); int count = 0; while (true) { int len = wcslen(env); if (len == 0) break; if (envStrings != null) envStrings[count] = new String(env); count++; env += len + 1; } if (envStrings == null) envStrings = new string[count]; } return envStrings; } } private static unsafe int wcslen(char* s) { char* e; for (e = s; *e != '\0'; e++){/* intentionally do nothing */} return (int)(e - s); } private void SetAccountEnvironment(string serviceAccountSid, string[] profilerEnvironment) { Microsoft.Win32.RegistryKey key = GetAccountEnvironmentKey(serviceAccountSid); if (key != null) { foreach (string envVariable in profilerEnvironment) { key.SetValue(EnvKey(envVariable), EnvValue(envVariable)); } } } private static string GetServiceAccountName(string serviceName) { Microsoft.Win32.RegistryKey key = GetServiceKey(serviceName); if (key != null) return key.GetValue("ObjectName") as string; return null; } private string LookupAccountSid(string accountName) { int sidLen = 0; byte[] sid = new byte[sidLen]; int domainNameLen = 0; int peUse; StringBuilder domainName = new StringBuilder(); LookupAccountName(Environment.MachineName, accountName, sid, ref sidLen, domainName, ref domainNameLen, out peUse); sid = new byte[sidLen]; domainName = new StringBuilder(domainNameLen); string stringSid = null; if (LookupAccountName(Environment.MachineName, accountName, sid, ref sidLen, domainName, ref domainNameLen, out peUse)) { IntPtr stringSidPtr; if (ConvertSidToStringSidW(sid, out stringSidPtr)) { try { stringSid = Marshal.PtrToStringUni(stringSidPtr); } finally { LocalFree(stringSidPtr); } } } return stringSid; } private void ResetAccountEnvironment(string serviceAccountSid, string[] profilerEnvironment) { Microsoft.Win32.RegistryKey key = GetAccountEnvironmentKey(serviceAccountSid); if (key != null) { foreach (string envVariable in profilerEnvironment) { key.DeleteValue(EnvKey(envVariable)); } } } private Microsoft.Win32.RegistryKey GetAccountEnvironmentKey(string serviceAccountSid) { Microsoft.Win32.RegistryKey users = Microsoft.Win32.Registry.Users; return users.OpenSubKey(serviceAccountSid + @"\Environment", true); } private string EnvValue(string envVariable) { int index = envVariable.IndexOf('='); Debug.Assert(index >= 0); return envVariable.Substring(index + 1); } private string EnvKey(string envVariable) { int index = envVariable.IndexOf('='); Debug.Assert(index >= 0); return envVariable.Substring(0, index); } private void DeleteEnvironmentVariables(string serviceName) { Microsoft.Win32.RegistryKey key = GetServiceKey(serviceName); if (key != null) key.DeleteValue("Environment"); } protected static Microsoft.Win32.RegistryKey GetServiceKey(string serviceName) { Microsoft.Win32.RegistryKey localMachine = Microsoft.Win32.Registry.LocalMachine; Microsoft.Win32.RegistryKey key = localMachine.OpenSubKey("SYSTEM\\CurrentControlSet\\Services\\" + serviceName, true); return key; } } }
37.111475
131
0.566835
1e6881ee81e46d1e8a766f1a7cf08c637dd8bcba
2,177
cs
C#
Assets/_PlanetaryInvasion/Scripts/UI/Views/ReportsViewItem.cs
Luchianno/Planet-Invasion
4fa0930b85fbed0d5dcfc123779074b3ff0e4e6c
[ "MIT" ]
null
null
null
Assets/_PlanetaryInvasion/Scripts/UI/Views/ReportsViewItem.cs
Luchianno/Planet-Invasion
4fa0930b85fbed0d5dcfc123779074b3ff0e4e6c
[ "MIT" ]
null
null
null
Assets/_PlanetaryInvasion/Scripts/UI/Views/ReportsViewItem.cs
Luchianno/Planet-Invasion
4fa0930b85fbed0d5dcfc123779074b3ff0e4e6c
[ "MIT" ]
null
null
null
using System.Collections; using System.Collections.Generic; using UnityEngine; using TMPro; using UnityEngine.UI; using System; public class ReportsViewItem : MonoBehaviour { public event Action<StoryLogEntry> OnClicked; public Color CardSuccess; public Color CardFail; public Color CardNeutral; public Color TechColor; public Color StoryColor; public Image Background; public Button Button; public TextMeshProUGUI Description; public TextMeshProUGUI SuccessType; // public TextMeshProUGUI ReportType; StoryLogEntry data; void Start() { this.Button.onClick.AddListener(() => OnClicked(data)); } public void Init(StoryLogEntry log) { data = log; // this.ReportType.text = result.MessageType.ToString(); Button.interactable = false; this.SuccessType.text = ""; if (!log.IsPlayerAction) { this.Description.text = log.Text; this.SuccessType.text = "Planet Action"; Background.color = CardFail; } else { switch (log.Type) { case StoryLogEntryType.CardResult: this.Description.text = log.Text; this.SuccessType.text = log.SuccessType.ToString() + "!"; Background.color = log.SuccessType == ActionResultType.Fail ? CardFail : CardSuccess; break; case StoryLogEntryType.TechResult: this.Description.text = $"\"{log.Card.Name}\" - Research Complete"; // (Click for more info) Button.interactable = true; Background.color = TechColor; break; case StoryLogEntryType.Story: this.Description.text = "Story Entry Unlocked"; // (Click for more info) Button.interactable = true; Background.color = StoryColor; break; case StoryLogEntryType.RandomNews: break; default: break; } } } }
27.2125
112
0.560864
1e6abde6f4dfb8dcd9aae7e5be23a45147325758
1,599
cs
C#
Bridge/System/Threading/Tasks/Promise.cs
cinjguy/Bridge
73a8ce42a4481cabf75dc17ceceb381fa783ee9c
[ "Apache-2.0" ]
14
2019-03-13T22:02:12.000Z
2022-02-15T11:16:52.000Z
Bridge/System/Threading/Tasks/Promise.cs
cinjguy/Bridge
73a8ce42a4481cabf75dc17ceceb381fa783ee9c
[ "Apache-2.0" ]
null
null
null
Bridge/System/Threading/Tasks/Promise.cs
cinjguy/Bridge
73a8ce42a4481cabf75dc17ceceb381fa783ee9c
[ "Apache-2.0" ]
2
2022-01-24T09:49:51.000Z
2022-03-14T11:25:21.000Z
namespace System.Threading.Tasks { /// <summary> /// CommonJS Promise/A interface /// http://wiki.commonjs.org/wiki/Promises/A /// </summary> [Bridge.Convention(Member = Bridge.ConventionMember.Field | Bridge.ConventionMember.Method, Notation = Bridge.Notation.CamelCase)] [Bridge.External] [Bridge.Name("Bridge.IPromise")] [Bridge.Convention(Target = Bridge.ConventionTarget.Member, Member = Bridge.ConventionMember.Method, Notation = Bridge.Notation.CamelCase)] public interface IPromise { /// <summary> /// Adds a fulfilledHandler, errorHandler to be called for completion of a promise. /// </summary> /// <param name="fulfilledHandler">The fulfilledHandler is called when the promise is fulfilled</param> /// <param name="errorHandler">The errorHandler is called when a promise fails.</param> /// <param name="progressHandler"></param> void Then(Delegate fulfilledHandler, Delegate errorHandler = null, Delegate progressHandler = null); } /// <summary> /// /// </summary> [Bridge.Convention(Member = Bridge.ConventionMember.Field | Bridge.ConventionMember.Method, Notation = Bridge.Notation.CamelCase)] [Bridge.External] public static class PromiseExtensions { /// <summary> /// /// </summary> /// <param name="promise"></param> /// <returns></returns> [Bridge.Template("System.Threading.Tasks.Task.fromPromise({promise})")] public static extern TaskAwaiter<object[]> GetAwaiter(this IPromise promise); } }
43.216216
143
0.66479
1e6c2b11512fd5a8cfd4e40dad37062daa9f61f4
2,010
cs
C#
src/Abp/Configuration/Startup/ILocalizationConfiguration.cs
obedurena/aspnetboilerplate
0b40ff91728d67380d56703313141b8bbe127daa
[ "MIT" ]
11,219
2015-01-02T18:17:50.000Z
2022-03-31T11:57:13.000Z
src/Abp/Configuration/Startup/ILocalizationConfiguration.cs
emreerkoca/aspnetboilerplate
a47777c47741ff44483a667afc08f3738babef19
[ "MIT" ]
5,635
2015-01-01T02:04:07.000Z
2022-03-31T13:29:36.000Z
src/Abp/Configuration/Startup/ILocalizationConfiguration.cs
emreerkoca/aspnetboilerplate
a47777c47741ff44483a667afc08f3738babef19
[ "MIT" ]
4,791
2015-01-06T03:34:41.000Z
2022-03-29T13:25:06.000Z
using System.Collections.Generic; using Abp.Localization; namespace Abp.Configuration.Startup { /// <summary> /// Used for localization configurations. /// </summary> public interface ILocalizationConfiguration { /// <summary> /// Used to set languages available for this application. /// </summary> IList<LanguageInfo> Languages { get; } /// <summary> /// List of localization sources. /// </summary> ILocalizationSourceList Sources { get; } /// <summary> /// Used to enable/disable localization system. /// Default: true. /// </summary> bool IsEnabled { get; set; } /// <summary> /// If this is set to true, the given text (name) is returned /// if not found in the localization source. That prevent exceptions if /// given name is not defined in the localization sources. /// Also writes a warning log. /// Default: true. /// </summary> bool ReturnGivenTextIfNotFound { get; set; } /// <summary> /// It returns the given text by wrapping with [ and ] chars /// if not found in the localization source. /// This is considered only if <see cref="ReturnGivenTextIfNotFound"/> is true. /// Default: true. /// </summary> bool WrapGivenTextIfNotFound { get; set; } /// <summary> /// It returns the given text by converting string from 'PascalCase' to a 'Sentense case' /// if not found in the localization source. /// This is considered only if <see cref="ReturnGivenTextIfNotFound"/> is true. /// Default: true. /// </summary> bool HumanizeTextIfNotFound { get; set; } /// <summary> /// Write (or not write) a warning log if given text can not found in the localization source. /// Default: true. /// </summary> bool LogWarnMessageIfNotFound { get; set; } } }
34.067797
102
0.585572
1e6cdef61b0d90f200637f36262a6ea5e4cc4d35
3,914
cs
C#
src/Program.cs
CallumCarmicheal/PySyn
6da12da6fe2873a8c47005033c470cbe774a358e
[ "Unlicense" ]
null
null
null
src/Program.cs
CallumCarmicheal/PySyn
6da12da6fe2873a8c47005033c470cbe774a358e
[ "Unlicense" ]
null
null
null
src/Program.cs
CallumCarmicheal/PySyn
6da12da6fe2873a8c47005033c470cbe774a358e
[ "Unlicense" ]
null
null
null
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; namespace PySynCS { static class Program { static string SubString(string txt, int start, int end) { if (string.IsNullOrWhiteSpace(txt)) return ""; if (txt.Length - 1 <= start) return txt.Substring(start, 1); if (txt.Length - 1 <= end) { int v1 = txt.Length - 1, v2 = v1 - start, v3 = v2 + (start == 0 ? 0 : 1); string ret = txt.Substring(start, v3); return ret; } if (start > end) return ""; if (start == end) return txt.Substring(start, 1); return txt.Substring(start, end - start + 1); } static void PerformSubStringTests() { string str = "0123456789ABCDEF"; Console.WriteLine("Sub String test:\n"); Console.WriteLine("String:"); Console.WriteLine("\t 0123456789"); Console.WriteLine("\t 10 = 9"); Console.WriteLine("\t |11 = 10"); Console.WriteLine("\t ||12 = 11"); Console.WriteLine("\t |||13 = 12"); Console.WriteLine("\t ||||14 = 13"); Console.WriteLine("\t |||||15 = 14"); Console.WriteLine("\t 0123456789ABCDEF"); Console.WriteLine("\t |--| \t 00-03 Test 1"); Console.WriteLine("\t |--| \t 04-07 "); Console.WriteLine("\t |--| \t 08-11 "); Console.WriteLine("\t |--| \t 12-15 "); Console.WriteLine("\t |------| \t 00-07 Test 2"); Console.WriteLine("\t |------| \t 05-13 "); Console.WriteLine("\t |<<<<<<| \t 13-05 "); // Should not work Console.WriteLine("\t |------------| \t 01-14 "); Console.WriteLine("\t |<<| \t 04-01 "); Console.WriteLine("\t |-----------------| \t 00-17 Test 3"); Console.WriteLine("\t |-| \t 14-16 "); // Tests 1 Console.WriteLine("\n\nTest 1:"); Console.WriteLine($"\t 00-03 {SubString(str, 00, 03)}"); Console.WriteLine($"\t 04-07 {SubString(str, 04, 07)}"); Console.WriteLine($"\t 08-11 {SubString(str, 08, 11)}"); Console.WriteLine($"\t 12-15 {SubString(str, 12, 15)}"); //*/ // Tests 2 Console.WriteLine("\nTest 2:"); Console.WriteLine($"\t 00-07 {SubString(str, 00, 07)}"); Console.WriteLine($"\t 05-13 {SubString(str, 05, 13)}"); Console.WriteLine($"\t 13-05 {SubString(str, 13, 05)}"); Console.WriteLine($"\t 01-14 {SubString(str, 01, 14)}"); Console.WriteLine($"\t 04-01 {SubString(str, 04, 01)}"); //*/ // Tests 3 Console.WriteLine("\nTest 3:"); Console.WriteLine($"\t 00-19 {SubString(str, 00, 19)}"); Console.WriteLine($"\t 14-16 {SubString(str, 14, 16)}"); //*/ Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("\nDone"); Console.ReadKey(); } /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new GUI.MainGUI()); //PerformSubStringTests(); } } }
42.086022
95
0.447879
1e6ceb78536b203502454ee9e4a631963163eaef
2,035
cs
C#
src/NuGet.Core/NuGet.Common/ClientVersionUtility.cs
huangqinjin/NuGet.Client
680f9bd4e97db7cd7482584276886764de69d3cb
[ "Apache-2.0" ]
654
2015-03-15T15:53:07.000Z
2022-03-25T18:16:49.000Z
src/NuGet.Core/NuGet.Common/ClientVersionUtility.cs
huangqinjin/NuGet.Client
680f9bd4e97db7cd7482584276886764de69d3cb
[ "Apache-2.0" ]
2,611
2015-09-30T18:03:24.000Z
2022-03-31T23:55:33.000Z
src/NuGet.Core/NuGet.Common/ClientVersionUtility.cs
huangqinjin/NuGet.Client
680f9bd4e97db7cd7482584276886764de69d3cb
[ "Apache-2.0" ]
765
2015-04-06T14:53:51.000Z
2022-03-30T22:36:38.000Z
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Reflection; namespace NuGet.Common { public static class ClientVersionUtility { // Cache the value since it cannot change private static string _clientVersion; /// <summary> /// Find the current NuGet client version from the assembly info as a string. /// If no value can be found an InvalidOperationException will be thrown. /// </summary> /// <remarks>This can contain prerelease labels if AssemblyInformationalVersionAttribute exists.</remarks> public static string GetNuGetAssemblyVersion() { if (_clientVersion == null) { string version = string.Empty; var assembly = typeof(ClientVersionUtility).GetTypeInfo().Assembly; var informationalVersionAttr = assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>(); if (informationalVersionAttr != null) { // Attempt to read the full informational version if it exists version = informationalVersionAttr.InformationalVersion; } else { // Fallback to the .net assembly version var versionAttr = assembly.GetCustomAttribute<AssemblyVersionAttribute>(); if (versionAttr != null) { version = versionAttr.Version.ToString(); } } // Verify a value was found if (string.IsNullOrEmpty(version)) { throw new InvalidOperationException(Strings.UnableToDetemineClientVersion); } _clientVersion = version; } return _clientVersion; } } }
36.339286
116
0.575921
1e6ed30e3ee860372ec47ccb9a3c1a8163209ae9
2,973
cs
C#
backend/src/Squidex.Domain.Apps.Entities/Contents/GraphQL/Types/AllTypes.cs
tapend/tebe-cms
1abd0bcdb044ae84b8e5f11d3ef23c1fdcd7f076
[ "MIT" ]
null
null
null
backend/src/Squidex.Domain.Apps.Entities/Contents/GraphQL/Types/AllTypes.cs
tapend/tebe-cms
1abd0bcdb044ae84b8e5f11d3ef23c1fdcd7f076
[ "MIT" ]
null
null
null
backend/src/Squidex.Domain.Apps.Entities/Contents/GraphQL/Types/AllTypes.cs
tapend/tebe-cms
1abd0bcdb044ae84b8e5f11d3ef23c1fdcd7f076
[ "MIT" ]
null
null
null
// ========================================================================== // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex UG (haftungsbeschraenkt) // All rights reserved. Licensed under the MIT license. // ========================================================================== using System; using GraphQL.Types; using Squidex.Domain.Apps.Core.Assets; using Squidex.Domain.Apps.Entities.Contents.GraphQL.Types.Utils; namespace Squidex.Domain.Apps.Entities.Contents.GraphQL.Types { public static class AllTypes { public const string PathName = "path"; public static readonly Type None = typeof(NoopGraphType); public static readonly Type NonNullTagsType = typeof(NonNullGraphType<ListGraphType<NonNullGraphType<StringGraphType>>>); public static readonly IGraphType Int = new IntGraphType(); public static readonly IGraphType DomainId = new StringGraphType(); public static readonly IGraphType Date = new InstantGraphType(); public static readonly IGraphType Json = new JsonGraphType(); public static readonly IGraphType Float = new FloatGraphType(); public static readonly IGraphType String = new StringGraphType(); public static readonly IGraphType Boolean = new BooleanGraphType(); public static readonly IGraphType AssetType = new EnumerationGraphType<AssetType>(); public static readonly IGraphType NonNullInt = new NonNullGraphType(Int); public static readonly IGraphType NonNullDomainId = new NonNullGraphType(DomainId); public static readonly IGraphType NonNullDate = new NonNullGraphType(Date); public static readonly IGraphType NonNullFloat = new NonNullGraphType(Float); public static readonly IGraphType NonNullString = new NonNullGraphType(String); public static readonly IGraphType NonNullBoolean = new NonNullGraphType(Boolean); public static readonly IGraphType NonNullAssetType = new NonNullGraphType(AssetType); public static readonly IGraphType NoopDate = new NoopGraphType(Date); public static readonly IGraphType NoopJson = new NoopGraphType(Json); public static readonly IGraphType NoopFloat = new NoopGraphType(Float); public static readonly IGraphType NoopString = new NoopGraphType(String); public static readonly IGraphType NoopBoolean = new NoopGraphType(Boolean); public static readonly IGraphType NoopTags = new NoopGraphType("TagsScalar"); public static readonly IGraphType NoopGeolocation = new NoopGraphType("GeolocationScalar"); public static readonly QueryArguments PathArguments = new QueryArguments(new QueryArgument(None) { Name = PathName, Description = "The path to the json value", DefaultValue = null, ResolvedType = String }); } }
39.118421
129
0.671376
1e6f3831dc9c31feb936a76427d75a7800fb89d9
6,259
cs
C#
src/CodegenCS.DbSchema.Templates/SimplePOCOGenerator/SampleOutput/ProductCostHistory.generated.cs
Drizin/codegencs
3c8c905447ff71152a61838e247c8d7feb22ab02
[ "MIT" ]
39
2020-07-14T02:44:35.000Z
2022-02-05T10:02:45.000Z
src/CodegenCS.DbSchema.Templates/SimplePOCOGenerator/SampleOutput/ProductCostHistory.generated.cs
Drizin/codegencs
3c8c905447ff71152a61838e247c8d7feb22ab02
[ "MIT" ]
4
2021-02-19T17:45:29.000Z
2022-03-03T03:49:28.000Z
src/CodegenCS.DbSchema.Templates/SimplePOCOGenerator/SampleOutput/ProductCostHistory.generated.cs
Drizin/codegencs
3c8c905447ff71152a61838e247c8d7feb22ab02
[ "MIT" ]
14
2020-07-14T02:44:37.000Z
2021-12-19T13:16:02.000Z
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using Dapper; using System.ComponentModel; namespace CodegenCS.AdventureWorksPOCOSample { [Table("ProductCostHistory", Schema = "Production")] public partial class ProductCostHistory : INotifyPropertyChanged { #region Members private int _productId; [Key] public int ProductId { get { return _productId; } set { SetField(ref _productId, value, nameof(ProductId)); } } private DateTime _startDate; [Key] public DateTime StartDate { get { return _startDate; } set { SetField(ref _startDate, value, nameof(StartDate)); } } private DateTime? _endDate; public DateTime? EndDate { get { return _endDate; } set { SetField(ref _endDate, value, nameof(EndDate)); } } private DateTime _modifiedDate; public DateTime ModifiedDate { get { return _modifiedDate; } set { SetField(ref _modifiedDate, value, nameof(ModifiedDate)); } } private decimal _standardCost; public decimal StandardCost { get { return _standardCost; } set { SetField(ref _standardCost, value, nameof(StandardCost)); } } #endregion Members #region ActiveRecord public void Save() { if (ProductId == default(int) && StartDate == default(DateTime)) Insert(); else Update(); } public void Insert() { using (var conn = IDbConnectionFactory.CreateConnection()) { string cmd = @" INSERT INTO [Production].[ProductCostHistory] ( [EndDate], [ModifiedDate], [ProductID], [StandardCost], [StartDate] ) VALUES ( @EndDate, @ModifiedDate, @ProductId, @StandardCost, @StartDate )"; conn.Execute(cmd, this); } } public void Update() { using (var conn = IDbConnectionFactory.CreateConnection()) { string cmd = @" UPDATE [Production].[ProductCostHistory] SET [EndDate] = @EndDate, [ModifiedDate] = @ModifiedDate, [ProductID] = @ProductId, [StandardCost] = @StandardCost, [StartDate] = @StartDate WHERE [ProductID] = @ProductId AND [StartDate] = @StartDate"; conn.Execute(cmd, this); } } #endregion ActiveRecord #region Equals/GetHashCode public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) { return false; } if (ReferenceEquals(this, obj)) { return true; } ProductCostHistory other = obj as ProductCostHistory; if (other == null) return false; if (EndDate != other.EndDate) return false; if (ModifiedDate != other.ModifiedDate) return false; if (ProductId != other.ProductId) return false; if (StandardCost != other.StandardCost) return false; if (StartDate != other.StartDate) return false; return true; } public override int GetHashCode() { unchecked { int hash = 17; hash = hash * 23 + (EndDate == null ? 0 : EndDate.GetHashCode()); hash = hash * 23 + (ModifiedDate == default(DateTime) ? 0 : ModifiedDate.GetHashCode()); hash = hash * 23 + (ProductId == default(int) ? 0 : ProductId.GetHashCode()); hash = hash * 23 + (StandardCost == default(decimal) ? 0 : StandardCost.GetHashCode()); hash = hash * 23 + (StartDate == default(DateTime) ? 0 : StartDate.GetHashCode()); return hash; } } public static bool operator ==(ProductCostHistory left, ProductCostHistory right) { return Equals(left, right); } public static bool operator !=(ProductCostHistory left, ProductCostHistory right) { return !Equals(left, right); } #endregion Equals/GetHashCode #region INotifyPropertyChanged/IsDirty public HashSet<string> ChangedProperties = new HashSet<string>(StringComparer.OrdinalIgnoreCase); public void MarkAsClean() { ChangedProperties.Clear(); } public virtual bool IsDirty => ChangedProperties.Any(); public event PropertyChangedEventHandler PropertyChanged; protected void SetField<T>(ref T field, T value, string propertyName) { if (!EqualityComparer<T>.Default.Equals(field, value)) { field = value; ChangedProperties.Add(propertyName); OnPropertyChanged(propertyName); } } protected virtual void OnPropertyChanged(string propertyName) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } #endregion INotifyPropertyChanged/IsDirty } }
34.202186
105
0.507749
1e70111578687d8e6c7d5852a7b3ec9bc4e50360
17,050
cs
C#
commons/Rhino.Commons.Test/ForTesting/DatabaseTestFixtureBaseTests.cs
codechip/rhino-tools
30c66bdc8d750093dde56a482c4ab2b649b70797
[ "BSD-3-Clause" ]
2
2015-08-09T19:01:17.000Z
2016-01-11T21:23:42.000Z
developers-stuff/common-lib/rhino-tools/commons/Rhino.Commons.Test/ForTesting/DatabaseTestFixtureBaseTests.cs
Dreameris/.NET-Common-Library
80266f74fd4ae16945deb9fcdc28aef3d183b008
[ "Unlicense" ]
null
null
null
developers-stuff/common-lib/rhino-tools/commons/Rhino.Commons.Test/ForTesting/DatabaseTestFixtureBaseTests.cs
Dreameris/.NET-Common-Library
80266f74fd4ae16945deb9fcdc28aef3d183b008
[ "Unlicense" ]
4
2016-01-27T07:35:39.000Z
2021-09-10T14:09:20.000Z
#region license // Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of Ayende Rahien nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using Castle.ActiveRecord; using Castle.Windsor; using MbUnit.Framework; using NHibernate; using Rhino.Commons.Facilities; using Rhino.Commons.ForTesting; namespace Rhino.Commons.Test.ForTesting { using Util; public abstract class DatabaseTestFixtureBaseTests : DatabaseTestFixtureBase { [SetUp] public void TestInitialize() { //WARNING: ordinarily you would never dispose of your contexts like this between each test, //as this would seriously degrade performance. //We're only doing it here because we're testing the test framework itself IoC.Reset(); DisposeAndRemoveAllUoWTestContexts(); } [TearDown] public void TestCleanup() { //WARNING: ordinarily you would never dispose of your contexts like this between each test, //as this would seriously degrade performance. //We're only doing it here because we're testing the test framework itself IoC.Reset(); DisposeAndRemoveAllUoWTestContexts(); } [Test] public virtual void CanCreateUnitOfWorkContextFor_MsSqlCe() { VerifyCanCreateUnitOfWorkContextFor(null, DatabaseEngine.MsSqlCe); VerifyCanCreateUseAndDisposeSession(); } [Test] public virtual void CanCreateUnitOfWorkContextFor_MsSqlCe_IoC() { VerifyCanCreateUnitOfWorkContextFor(WindsorFilePath, DatabaseEngine.MsSqlCe); VerifyCanCreateUseAndDisposeSession(); VerifyCanCreateUseAndDisposeUnitOfWork(); } [Test] public virtual void CanCreateUnitOfWorkContextFor_SQLite() { VerifyCanCreateUnitOfWorkContextFor(null, DatabaseEngine.SQLite); VerifyCanCreateUseAndDisposeSession(); } [Test] public virtual void CanCreateUnitOfWorkContextFor_SQLite_IoC() { VerifyCanCreateUnitOfWorkContextFor(WindsorFilePath, DatabaseEngine.SQLite); VerifyCanCreateUseAndDisposeSession(); VerifyCanCreateUseAndDisposeUnitOfWork(); } [Test] public virtual void CanCreateUnitOfWorkContextFor_MsSql2005() { if (UnitOfWorkTestContextDbStrategy.IsSqlServer2005OrAboveInstalled()) { VerifyCanCreateUnitOfWorkContextFor(null, DatabaseEngine.MsSql2005); VerifyCanCreateUseAndDisposeSession(); } } [Test] public virtual void CanCreateUnitOfWorkContextFor_MsSql2005_IoC() { if (UnitOfWorkTestContextDbStrategy.IsSqlServer2005OrAboveInstalled()) { VerifyCanCreateUnitOfWorkContextFor(WindsorFilePath, DatabaseEngine.MsSql2005); VerifyCanCreateUseAndDisposeSession(); VerifyCanCreateUseAndDisposeUnitOfWork(); } } [Test] public virtual void EachUnitOfWorkContextConfigurationWillBeCreatedOnlyOnce() { InitializeNHibernateAndIoC(WindsorFilePath, DatabaseEngine.SQLite, ""); InitializeNHibernateAndIoC(WindsorFilePath, DatabaseEngine.SQLite, ""); Assert.AreEqual(1, Contexts.Count); } [Test] public virtual void NewUnitOfWorkContextCreatedForDifferentDatabaseNames() { if (UnitOfWorkTestContextDbStrategy.IsSqlServer2005OrAboveInstalled()) { VerifyCanCreateUnitOfWorkContextFor(WindsorFilePath, DatabaseEngine.MsSql2005, "TestDb1"); VerifyCanCreateUnitOfWorkContextFor(WindsorFilePath, DatabaseEngine.MsSql2005, "TestDb2"); Assert.AreEqual(2, Contexts.Count); } } [Test] public virtual void NewUnitOfWorkContextCreatedForDifferentWindorConfigFiles() { VerifyCanCreateUnitOfWorkContextFor(WindsorFilePath, DatabaseEngine.SQLite); VerifyCanCreateUnitOfWorkContextFor(AnotherWindsorFilePath, DatabaseEngine.SQLite); Assert.AreEqual(2, Contexts.Count); } [Test] public virtual void SwitchingBetweenExistingContextsHasAcceptablePerformace() { //Creates SQLite context for the first time. Use context to touch all moving parts InitializeNHibernateAndIoC(WindsorFilePath, DatabaseEngine.SQLite, ""); VerifyCanCreateUseAndDisposeUnitOfWork(); //Create another context and ensure all its component parts are used //We're doing this so that the SQLite context created above is no longer current InitializeNHibernateAndIoC(WindsorFilePath, DatabaseEngine.MsSqlCe, ""); VerifyCanCreateUseAndDisposeUnitOfWork(); //Reinstate and use existing SQLite context. double timing = With.PerformanceCounter(delegate { InitializeNHibernateAndIoC(WindsorFilePath, DatabaseEngine.SQLite, ""); VerifyCanCreateUseAndDisposeUnitOfWork(); }); Assert.Less(timing, 0.2, "reinstating then using existing context sufficiently performant"); } [Test] public virtual void CanCreateNestedUnitOfWork() { InitializeNHibernateAndIoC(WindsorFilePath, DatabaseEngine.SQLite, ""); VerifyCanCreateUseAndDisposeNestedUnitOfWork(); } [Test] public virtual void CallingCreateUnitOfWorkMoreThanOnceIsNotAllowed() { InitializeNHibernateAndIoC(WindsorFilePath, DatabaseEngine.SQLite, ""); CurrentContext.CreateUnitOfWork(); try { CurrentContext.CreateUnitOfWork(); Assert.Fail("Exception was expected"); } catch (InvalidOperationException e) { string message = "Cannot create a nested UnitOfWork with this method. Use CreateNestedUnitOfWork() instead"; Assert.AreEqual(message, e.Message); } finally { CurrentContext.DisposeUnitOfWork(); } } [Test] public void CanInitializeWithFluentInterfaceAndContainerInstance() { MappingInfo mappingInfo = MappingInfo.FromAssemblyContaining<AREntity>(); IWindsorContainer container = new WindsorContainer(); container.AddFacility("nh", new NHibernateUnitOfWorkFacility( new NHibernateUnitOfWorkFacilityConfig(Assembly.GetAssembly(typeof (AREntity))))); Initialize(PersistenceFramework.NHibernate, mappingInfo).AndIoC(container); Assert.AreSame(container,CurrentContext.RhinoContainer); } protected void InitializeNHibernateAndIoC(string rhinoContainerPath, DatabaseEngine databaseEngine, string databaseName) { InitializeNHibernateAndIoC(FrameworkToTest, rhinoContainerPath, databaseEngine, databaseName, MappingInfo.FromAssemblyContaining<AREntity>()); } protected void VerifyCanCreateUnitOfWorkContextFor(string rhinoContainerPath, DatabaseEngine databaseEngine) { VerifyCanCreateUnitOfWorkContextFor(FrameworkToTest, rhinoContainerPath, databaseEngine, ""); } protected void VerifyCanCreateUnitOfWorkContextFor(string rhinoContainerPath, DatabaseEngine databaseEngine, string databaseName) { VerifyCanCreateUnitOfWorkContextFor(FrameworkToTest, rhinoContainerPath, databaseEngine, databaseName); } protected void VerifyCanCreateUnitOfWorkContextFor(PersistenceFramework framework, string rhinoContainerPath, DatabaseEngine databaseEngine, string databaseName) { int nextContextPosition = Contexts.Count; //creates the UnitOfWorkContext MappingInfo mappingInfo = MappingInfo.FromAssemblyContaining<AREntity>(); InitializeNHibernateAndIoC(framework, rhinoContainerPath, databaseEngine, databaseName, mappingInfo); UnitOfWorkTestContext context = Contexts[nextContextPosition]; Assert.AreEqual(framework, context.Framework); if (rhinoContainerPath != null) { Assert.AreEqual(rhinoContainerPath, context.RhinoContainerConfigPath); } else { Assert.IsEmpty(context.RhinoContainerConfigPath); } Assert.AreEqual(databaseEngine, context.DatabaseEngine); if (string.IsNullOrEmpty(databaseName)) { Assert.AreEqual( NHibernateInitializer.DeriveDatabaseNameFrom(databaseEngine, mappingInfo.MappingAssemblies[0]), context.DatabaseName); } else { Assert.AreEqual(databaseName, context.DatabaseName); } Assert.AreEqual(CurrentContext, context, "Context just built has been assigned to CurrentContext"); } protected void VerifyCanCreateUseAndDisposeSession() { ISession session = null; try { session = CurrentContext.CreateSession(); Assert.IsNotNull(session); session.Save(new AREntity()); session.Flush(); } finally { CurrentContext.DisposeSession(session); } } protected void VerifyCanCreateUseAndDisposeUnitOfWork() { try { CurrentContext.CreateUnitOfWork(); Console.Write(UnitOfWork.CurrentSession.Connection.ConnectionString); UnitOfWork.CurrentSession.Save(new AREntity()); UnitOfWork.CurrentSession.Flush(); } finally { CurrentContext.DisposeUnitOfWork(); } } protected void VerifyCanCreateUseAndDisposeNestedUnitOfWork() { Assert.AreEqual(-1, CurrentContext.UnitOfWorkNestingLevel, "level before starting UoW = -1"); CurrentContext.CreateUnitOfWork(); Assert.AreEqual(0, CurrentContext.UnitOfWorkNestingLevel, "level after starting UoW = 0"); CurrentContext.CreateNestedUnitOfWork(); Assert.AreEqual(1, CurrentContext.UnitOfWorkNestingLevel, "level after starting nested UoW = 1"); UnitOfWork.CurrentSession.Save(new AREntity()); UnitOfWork.CurrentSession.Flush(); CurrentContext.DisposeUnitOfWork(); //this is happening in the original UoW UnitOfWork.CurrentSession.Save(new AREntity()); UnitOfWork.CurrentSession.Flush(); CurrentContext.DisposeUnitOfWork(); } protected abstract string AnotherWindsorFilePath { get; } protected abstract PersistenceFramework FrameworkToTest { get; } protected abstract string WindsorFilePath { get; } protected static string ActiveRecordWindsorFilePath { get { return Path.GetFullPath( Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"ForTesting\Windsor-AR.config")); } } protected static string NHibernateWindsorFilePath { get { return Path.GetFullPath( Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"ForTesting\Windsor-NH.config")); } } // [Test] // public virtual void CanInitializeWithFluentNHibernate_Simple() // { // MappingInfo mappingInfo = MappingInfo.FromAssemblyContaining<AREntity>(); // NHibernateInitializer initializer=Initialize(PersistenceFramework.NHibernate, mappingInfo).Using(DatabaseEngine.SQLite,":memoir"); // Assert.AreEqual(PersistenceFramework.NHibernate,initializer.PersistenceFramework); // Assert.AreSame(mappingInfo,initializer.MappingInfo); // Assert.AreEqual(DatabaseEngine.SQLite,initializer.DatabaseEngine); // Assert.AreEqual(":memoir",initializer.DatabaseName); // // } // [Test] // public virtual void CanInitializeWithFluentNHibernate_Complete() // { // MappingInfo mappingInfo = MappingInfo.FromAssemblyContaining<AREntity>(); // Initialize(PersistenceFramework.NHibernate, mappingInfo); // // } // [Test] // public virtual void CanInitializeNHibernateWithIoC() // { // MappingInfo mappingInfo = MappingInfo.FromAssemblyContaining<AREntity>(); // string rhinoContainerConfig = "windsor.boo"; // NHibernateInitializer initializer = Initialize(PersistenceFramework.NHibernate, mappingInfo) // .AndIoC().With(rhinoContainerConfig); // // } } [ActiveRecord] public class AREntity { private Guid id = Guid.NewGuid(); private int version = -1; private string name; private int age; [PrimaryKey(PrimaryKeyType.Assigned)] public virtual Guid Id { get { return id; } set { id = value; } } [Version(UnsavedValue = "-1")] public virtual int Version { get { return version; } set { version = value; } } [Property] public virtual int Age { get { return age; } set { age = value; } } [Property] public virtual string Name { get { return name; } set { name = value; } } } }
37.555066
136
0.588446
1e74274ef62d791c0a96aaff3ef1f199129b7161
3,365
cs
C#
Wyrobot/Http/YouTube/YouTubeEventListener.cs
JustAeris/Wyrobot
2a3bc9ea0de8894cdfe32dcf374f3bf4584fdaa5
[ "BSD-4-Clause" ]
null
null
null
Wyrobot/Http/YouTube/YouTubeEventListener.cs
JustAeris/Wyrobot
2a3bc9ea0de8894cdfe32dcf374f3bf4584fdaa5
[ "BSD-4-Clause" ]
null
null
null
Wyrobot/Http/YouTube/YouTubeEventListener.cs
JustAeris/Wyrobot
2a3bc9ea0de8894cdfe32dcf374f3bf4584fdaa5
[ "BSD-4-Clause" ]
null
null
null
using System; using System.Collections.Generic; using System.Threading.Tasks; using YoutubeExplode; using YoutubeExplode.Videos; namespace Wyrobot.Core.Http.YouTube { public class YouTubeEventListener { private YoutubeClient _client; public List<ChannelSubscription> Subscriptions { get; private set; } public event YouTubeEventHandler OnVideoUploaded; private YouTubeEventListener() { Subscriptions = new List<ChannelSubscription>(); } public YouTubeEventListener(YoutubeClient client) : this() { _client = client; } public async Task SubscribeChannels(ulong guildId, ulong channelId, string broadcast, List<string> channels) { if (channels == null) throw new ArgumentNullException(nameof(channels)); foreach (var url in channels) { var uploads = await _client.Channels.GetUploadsAsync(url); Subscriptions.Add(new ChannelSubscription(guildId, channelId, broadcast, url, uploads.Count > 0 ? uploads[0] : null)); } } public async Task SubscribeChannels(ulong guildId, ulong channelId, string broadcast, params string[] channels) { var channelsList = new List<string>(); for (var index = 0; index < channels.Length; ++index) channelsList.Add(channels[index]); await SubscribeChannels(guildId, channelId, broadcast, channelsList); } public void UnsubscribeChannel(ChannelSubscription subscription) { if (!Subscriptions.Contains(subscription)) return; Subscriptions.Remove(subscription); } public async Task PollEvents() { foreach (var subscription in Subscriptions) { var uploads = await _client.Channels.GetUploadsAsync(subscription.Url); var lastVideo = uploads.Count > 0 ? uploads[0] : null; if (lastVideo == null) continue; if (subscription.LastVideo != lastVideo) { if (OnVideoUploaded == null) continue; var channel = await _client.Channels.GetAsync(lastVideo.ChannelId); OnVideoUploaded(this, new YouTubeEventArgs(subscription.GuildId, subscription.ChannelId, subscription.Broadcast, channel, lastVideo )); subscription.LastVideo = lastVideo; } } } public class ChannelSubscription { public ulong GuildId { get; set; } public ulong ChannelId { get; set; } public string Broadcast { get; set; } public string Url { get; set; } public Video LastVideo { get; set; } public ChannelSubscription(ulong guildId, ulong channelId, string broadcast, string url, Video lastVideo = null) { GuildId = guildId; ChannelId = channelId; Broadcast = broadcast; Url = url; LastVideo = lastVideo; } } public delegate void YouTubeEventHandler(object sender, YouTubeEventArgs e); } }
32.355769
155
0.577117
1e74571cc7313710f9777d6155decfc243fe562e
8,682
cs
C#
tradelr.DBML/partials/Contact.cs
seanlinmt/tradelr
0d03cdd10c712ad9592ea7b4e272cc746f984b69
[ "Apache-2.0" ]
2
2018-09-12T11:44:59.000Z
2022-01-16T14:06:32.000Z
tradelr.DBML/partials/Contact.cs
seanlinmt/tradelr
0d03cdd10c712ad9592ea7b4e272cc746f984b69
[ "Apache-2.0" ]
null
null
null
tradelr.DBML/partials/Contact.cs
seanlinmt/tradelr
0d03cdd10c712ad9592ea7b4e272cc746f984b69
[ "Apache-2.0" ]
null
null
null
using System.Collections.Generic; using System.Linq; using tradelr.DBML.Models; using tradelr.Library; using tradelr.Models.contacts; using tradelr.Models.history; using tradelr.Models.users; namespace tradelr.DBML { public partial class TradelrRepository { public IQueryable<user> GetAllContacts(long subdomain) { return db.users.Where(x => x.organisation1.subdomain == subdomain); } public IQueryable<user> GetPrivateContacts(long subdomainid) { // this excludes staff members (admin users on the same domain) // exclude self too since ppl who can get contact lists are admins on the same subdomain return db.users.Where(x => (x.role & (int)UserRole.CREATOR) == 0 && x.organisation1.subdomain == subdomainid); } public IQueryable<user> GetPublicContacts(long requesterSubdomain) { var friend1 = db.friends.Where(x => x.subdomainid == requesterSubdomain) .Select(x => x.MASTERsubdomain1.id); var friend2 = db.friends.Where(x => x.friendsubdomainid == requesterSubdomain) .Select(x => x.MASTERsubdomain.id); var domainids = friend1.Union(friend2).ToList(); return db.users.Where(x => (x.role & (int)UserRole.CREATOR) != 0 && domainids.Contains(x.organisation1.subdomain)); } public IQueryable<user> GetContacts(long subdomain, long requester, string filterList, string sidx, string sord, ContactType? type, string letter) { if (!string.IsNullOrEmpty(filterList)) { var filterid = long.Parse(filterList); var results1 = db.contactGroupMembers.Where( x => x.groupid == filterid && x.contactGroup.subdomainid == requester).Select(x => x.user); if (!string.IsNullOrEmpty(letter)) { results1 = results1.Where(x => x.firstName.StartsWith(letter) || x.firstName.StartsWith(letter.ToLower())); } if (type.HasValue) { switch (type.Value) { case ContactType.PRIVATE: results1 = results1.Where(x => x.organisation1.subdomain == subdomain); break; case ContactType.NETWORK: results1 = results1.Where(x => x.organisation1.subdomain != subdomain); break; } } IOrderedQueryable<user> ordered1 = null; if (!string.IsNullOrEmpty(sord) && !string.IsNullOrEmpty(sidx)) { if (sord == "asc") { ordered1 = results1.OrderBy(sidx); } else if (sord == "desc") { ordered1 = results1.OrderByDescending(sidx); } } return (ordered1 ?? results1); } IQueryable<ContactQueryResult> results = null; var privatecontacts = GetPrivateContacts(subdomain).Select(x => new ContactQueryResult { contact = x, name = x.organisation1.name }); var publiccontacts = GetPublicContacts(subdomain).Select(x => new ContactQueryResult { contact = x, name = x.organisation1.name }); if (type.HasValue) { switch (type.Value) { case ContactType.PRIVATE: results = privatecontacts; break; case ContactType.NETWORK: results = publiccontacts; break; } } else { results = privatecontacts.Union(publiccontacts); } if (!string.IsNullOrEmpty(letter)) { results = results.Where(x => x.contact.firstName.StartsWith(letter) || x.contact.firstName.StartsWith(letter.ToLower())); } IOrderedQueryable<user> ordered = null; if (!string.IsNullOrEmpty(sord) && !string.IsNullOrEmpty(sidx)) { if (sord == "asc") { ordered = results.Select(x => x.contact).OrderBy(sidx); } else if (sord == "desc") { ordered = results.Select(x => x.contact).OrderByDescending(sidx); } } return (ordered ?? results.Select(x => x.contact)); } public IQueryable<user> GetContacts(long subdomain, long requester, List<string> ids, string sidx, string sord) { IQueryable<user> results = db.users.Where(x => ids.Contains(x.id.ToString()) && x.id != requester); IOrderedQueryable<user> ordered = null; if (!string.IsNullOrEmpty(sord) && !string.IsNullOrEmpty(sidx)) { if (sord == "asc") { ordered = results.OrderBy(sidx); } else if (sord == "desc") { ordered = results.OrderByDescending(sidx); } } return (ordered ?? results); } public void AddContactGroupMember(contactGroupMember member) { // check that member doesn't already exist contactGroupMember m = member; var exists = db.contactGroupMembers.Where(x => x.groupid == m.groupid && x.userid == m.userid) .SingleOrDefault(); if (exists == null) { db.contactGroupMembers.InsertOnSubmit(member); db.SubmitChanges(); } else { member = exists; } } private void DeleteChangeHistory(long contextid, ChangeHistoryType type) { var items = db.changeHistoryItems.Where(x => x.changeID == contextid); db.changeHistoryItems.DeleteAllOnSubmit(items); var entry = db.changeHistories.Where(x => x.contextID == contextid && x.historyType == type.ToString()).SingleOrDefault(); if (entry == null) { return; } db.changeHistories.DeleteOnSubmit(entry); } public contactGroup GetContactGroup(long groupid, long subdomainid) { return db.contactGroups.Where(x => x.id == groupid && x.subdomainid == subdomainid).SingleOrDefault(); } public IQueryable<contactGroup> GetContactGroups(long subdomainid) { return db.contactGroups.Where(x => x.subdomainid == subdomainid); } public bool IsContactInUse(long contactid) { // if user is receiver or creator of an order if (db.orders.Where(x => x.owner == contactid || x.receiverUserid == contactid).Count() != 0) { return true; } return false; } public void UpdateContactGroupMembers(long subdomainid, long groupid, string[] userids) { // get existing ones first in filter var result = db.contactGroupMembers .Where(x => x.contactGroup.subdomainid == subdomainid && x.groupid == groupid); db.contactGroupMembers.DeleteAllOnSubmit(result); // add new ones foreach (var userid in userids) { var cf = new contactGroupMember(); cf.userid = long.Parse(userid); cf.groupid = groupid; db.contactGroupMembers.InsertOnSubmit(cf); } db.SubmitChanges(); } public void DeleteContactGroup(long subdomainid, long groupid) { // children set to DELETE CASCADE in db var result = db.contactGroups.Where(x => x.subdomainid == subdomainid && x.id == groupid); db.contactGroups.DeleteAllOnSubmit(result); db.SubmitChanges(); } public user GetContact(long subdomain, long contactid) { return db.users.Where(x => x.organisation1.subdomain == subdomain && x.id == contactid).SingleOrDefault(); } } }
38.078947
145
0.513822
1e7514a5db9a59501a1cd69f663caff074593aaf
1,402
cs
C#
src/Splunk.Client/Properties/AssemblyInfo.cs
glennblock/splunk-sdk-csharp-pcl
777812c035f5adc588c964129b8f3800d763e4c2
[ "Apache-2.0" ]
1
2015-11-08T22:39:38.000Z
2015-11-08T22:39:38.000Z
src/Splunk.Client/Properties/AssemblyInfo.cs
glennblock/splunk-sdk-csharp-pcl
777812c035f5adc588c964129b8f3800d763e4c2
[ "Apache-2.0" ]
null
null
null
src/Splunk.Client/Properties/AssemblyInfo.cs
glennblock/splunk-sdk-csharp-pcl
777812c035f5adc588c964129b8f3800d763e4c2
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2014 Splunk, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"): you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; //// General Information [assembly: AssemblyProduct("splunk-sdk-csharp-pcl")] [assembly: AssemblyTitle("Splunk.Client")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Splunk, Inc.")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("Splunk®")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en-US")] //// Operational information [assembly: ComVisible(false)] [assembly: InternalsVisibleTo("acceptance-tests")] [assembly: InternalsVisibleTo("unit-tests")] //// Version information [assembly: AssemblyVersion("2.0.0.0")] [assembly: AssemblyFileVersion("2.0.0.0")]
31.155556
76
0.749643
1e756bcc8a461052b56d9a03ac92d9a32fc84a9c
6,387
cs
C#
src/graphql-aspnet/Execution/BatchResultProcessor.cs
NET1211/aspnet-archive-tools
c4a3900aee50ef1c64150082647bacb1149910bf
[ "MIT" ]
22
2019-10-24T18:03:57.000Z
2022-03-08T10:24:50.000Z
src/graphql-aspnet/Execution/BatchResultProcessor.cs
NET1211/aspnet-archive-tools
c4a3900aee50ef1c64150082647bacb1149910bf
[ "MIT" ]
31
2019-10-24T21:53:53.000Z
2022-02-27T18:03:46.000Z
src/graphql-aspnet/Execution/BatchResultProcessor.cs
NET1211/aspnet-archive-tools
c4a3900aee50ef1c64150082647bacb1149910bf
[ "MIT" ]
7
2020-02-06T17:01:50.000Z
2022-02-02T05:00:00.000Z
// ************************************************************* // project: graphql-aspnet // -- // repo: https://github.com/graphql-aspnet // docs: https://graphql-aspnet.github.io // -- // License: MIT // ************************************************************* namespace GraphQL.AspNet.Execution { using System; using System.Collections; using System.Collections.Generic; using System.Linq; using GraphQL.AspNet.Common; using GraphQL.AspNet.Common.Source; using GraphQL.AspNet.Controllers; using GraphQL.AspNet.Execution.Exceptions; using GraphQL.AspNet.Execution.FieldResolution; using GraphQL.AspNet.Interfaces.Execution; using GraphQL.AspNet.Interfaces.TypeSystem; using GraphQL.AspNet.Internal; /// <summary> /// A data processor that handles internal batch operations for items being processed through a graph query. /// </summary> public class BatchResultProcessor { private readonly SourceOrigin _origin; private readonly IGraphField _field; private readonly IEnumerable<GraphDataItem> _sourceItems; /// <summary> /// Initializes a new instance of the <see cref="BatchResultProcessor" /> class. /// </summary> /// <param name="field">The field.</param> /// <param name="sourceItems">The source items.</param> /// <param name="origin">The origin.</param> public BatchResultProcessor(IGraphField field, IEnumerable<GraphDataItem> sourceItems, SourceOrigin origin) { _origin = origin; _field = Validation.ThrowIfNullOrReturn(field, nameof(field)); _sourceItems = Validation.ThrowIfNullOrReturn(sourceItems, nameof(sourceItems)); this.Messages = new GraphMessageCollection(); } /// <summary> /// Resolves the specified response splicing it and assigning batch items into the correct source items. This /// method returns an enumerable of those items that were successfully assigned data. /// </summary> /// <param name="data">The data that needs to be resolved.</param> /// <returns>IEnumerable&lt;GraphDataItem&gt;.</returns> public IEnumerable<GraphDataItem> Resolve(object data) { var batch = this.CreateDataBatch(data); if (batch == null) { this.Messages.Critical( $"Unable to process the batch field '{this._field.Name}'. The result of the batch operation was improperly formatted.", Constants.ErrorCodes.INVALID_BATCH_RESULT, _origin, new GraphExecutionException($"Invalid batch operation result for field '{this._field.Name}'. A batch result must be a " + $"'{nameof(IDictionary)}' keyed on the source items provided for the batch. Consider using the action helper methods " + $"of '{nameof(GraphController)}' when applicable to properly generate a batch.")); yield break; } foreach (var item in _sourceItems) { var singleItemResult = batch.RetrieveAssociatedItems(item.SourceData); item.AssignResult(singleItemResult); yield return item; } } /// <summary> /// Creates the data batch. /// </summary> /// <param name="data">The data.</param> /// <returns>FieldDataBatch.</returns> private DataBatch CreateDataBatch(object data) { if (data == null) return new DataBatch(_field.TypeExpression, null); if (!(data is IDictionary dictionary)) return null; return new DataBatch(_field.TypeExpression, dictionary); } /// <summary> /// Gets the messages generated during the processing of a pipeline response. /// </summary> /// <value>The messages.</value> public IGraphMessageCollection Messages { get; } /// <summary> /// Determines whether the provided type to check is IDictionary{ExpectedKey, AnyValue} ensuring that it can be /// used as an input to a batch processor that supplies data to multiple waiting items. /// </summary> /// <param name="typeToCheck">The type being checked.</param> /// <param name="expectedKeyType">The expected key type.</param> /// <param name="batchedItemType">Type of the batched item. if the type to check returns an IEnumerable per /// key this type must represent the individual item of the set. (i.e. the 'T' of IEnumerable{T}).</param> /// <returns><c>true</c> if the type represents a dictionary keyed on the expected key type; otherwise, <c>false</c>.</returns> public static bool IsBatchDictionaryType(Type typeToCheck, Type expectedKeyType, Type batchedItemType) { if (typeToCheck == null || expectedKeyType == null || batchedItemType == null) return false; bool CheckArgs(Type[] argSet) { if (argSet.Length != 2 || argSet[0] != expectedKeyType) return false; // the declared dictionary might have a value of a List<BatchedItemType> // strip the list decorators and test the actual type var actualBatchedItemType = GraphValidation.EliminateWrappersFromCoreType(argSet[1]); return batchedItemType == actualBatchedItemType; } // special case when the typeToCheck IS IDictionary if (typeToCheck.IsGenericType && typeToCheck.GetGenericTypeDefinition() == typeof(IDictionary<,>)) { return CheckArgs(typeToCheck.GetGenericArguments()); } else { var idictionaries = typeToCheck.GetInterfaces().Where(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IDictionary<,>)); foreach (var dic in idictionaries) { if (CheckArgs(dic.GetGenericArguments())) return true; } } return false; } } }
44.048276
168
0.588226
1e77f01338e8334f676d77adc59821dd180bca62
5,678
cs
C#
Freezer/GeckoFX/__Core/Generated/nsIFeedTextConstruct.cs
haga-rak/Freezer
5958540d0d9ab3b7d0cf6a097a40b61fecad01e6
[ "MIT" ]
37
2016-04-21T08:05:11.000Z
2022-03-11T00:05:50.000Z
Freezer/GeckoFX/__Core/Generated/nsIFeedTextConstruct.cs
haga-rak/Freezer
5958540d0d9ab3b7d0cf6a097a40b61fecad01e6
[ "MIT" ]
14
2016-05-05T16:31:45.000Z
2021-12-25T08:25:13.000Z
Freezer/GeckoFX/__Core/Generated/nsIFeedTextConstruct.cs
haga-rak/Freezer
5958540d0d9ab3b7d0cf6a097a40b61fecad01e6
[ "MIT" ]
21
2017-05-25T07:49:34.000Z
2022-03-27T05:23:53.000Z
// -------------------------------------------------------------------------------------------- // Version: MPL 1.1/GPL 2.0/LGPL 2.1 // // The contents of this file are subject to the Mozilla Public License Version // 1.1 (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // http://www.mozilla.org/MPL/ // // Software distributed under the License is distributed on an "AS IS" basis, // WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License // for the specific language governing rights and limitations under the // License. // // <remarks> // Generated by IDLImporter from file nsIFeedTextConstruct.idl // // You should use these interfaces when you access the COM objects defined in the mentioned // IDL/IDH file. // </remarks> // -------------------------------------------------------------------------------------------- namespace Gecko { using System; using System.Runtime.InteropServices; using System.Runtime.InteropServices.ComTypes; using System.Runtime.CompilerServices; /// <summary> /// nsIFeedTextConstructs represent feed text fields that can contain /// one of text, HTML, or XHTML. Some extension elements also have "type" /// parameters, and this interface could be used there as well. /// </summary> [ComImport()] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [Guid("fc97a2a9-d649-4494-931e-db81a156c873")] internal interface nsIFeedTextConstruct { /// <summary> /// If the text construct contains (X)HTML, relative references in /// the content should be resolved against this base URI. /// </summary> [return: MarshalAs(UnmanagedType.Interface)] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] nsIURI GetBaseAttribute(); /// <summary> /// If the text construct contains (X)HTML, relative references in /// the content should be resolved against this base URI. /// </summary> [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void SetBaseAttribute([MarshalAs(UnmanagedType.Interface)] nsIURI aBase); /// <summary> /// The language of the text. For example, "en-US" for US English. /// </summary> [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetLangAttribute([MarshalAs(UnmanagedType.CustomMarshaler, MarshalType = "Gecko.CustomMarshalers.AStringMarshaler")] nsAStringBase aLang); /// <summary> /// The language of the text. For example, "en-US" for US English. /// </summary> [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void SetLangAttribute([MarshalAs(UnmanagedType.CustomMarshaler, MarshalType = "Gecko.CustomMarshalers.AStringMarshaler")] nsAStringBase aLang); /// <summary> /// One of "text", "html", or "xhtml". If the type is (x)html, a '<' /// character represents markup. To display that character, an escape /// such as &lt; must be used. If the type is "text", the '<' /// character represents the character itself, and such text should /// not be embedded in markup without escaping it first. /// </summary> [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetTypeAttribute([MarshalAs(UnmanagedType.CustomMarshaler, MarshalType = "Gecko.CustomMarshalers.AStringMarshaler")] nsAStringBase aType); /// <summary> /// One of "text", "html", or "xhtml". If the type is (x)html, a '<' /// character represents markup. To display that character, an escape /// such as &lt; must be used. If the type is "text", the '<' /// character represents the character itself, and such text should /// not be embedded in markup without escaping it first. /// </summary> [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void SetTypeAttribute([MarshalAs(UnmanagedType.CustomMarshaler, MarshalType = "Gecko.CustomMarshalers.AStringMarshaler")] nsAStringBase aType); /// <summary> /// The content of the text construct. /// </summary> [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetTextAttribute([MarshalAs(UnmanagedType.CustomMarshaler, MarshalType = "Gecko.CustomMarshalers.AStringMarshaler")] nsAStringBase aText); /// <summary> /// The content of the text construct. /// </summary> [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void SetTextAttribute([MarshalAs(UnmanagedType.CustomMarshaler, MarshalType = "Gecko.CustomMarshalers.AStringMarshaler")] nsAStringBase aText); /// <summary> /// Returns the text of the text construct, with all markup stripped /// and all entities decoded. If the type attribute's value is "text", /// this function returns the value of the text attribute unchanged. /// </summary> [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void PlainText([MarshalAs(UnmanagedType.CustomMarshaler, MarshalType = "Gecko.CustomMarshalers.AStringMarshaler")] nsAStringBase retval); /// <summary> /// Return an nsIDocumentFragment containing the text and markup. /// </summary> [return: MarshalAs(UnmanagedType.Interface)] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] nsIDOMDocumentFragment CreateDocumentFragment([MarshalAs(UnmanagedType.Interface)] nsIDOMElement element); } }
49.373913
145
0.697429
1e791beeba15866f979e18abeaa44ea37b0434eb
6,087
cs
C#
DigestingDuck/Pages/Ativos.xaml.cs
JorgeBeserra/DigestingDuck
66949c9dabee6f8e37a3e00ba90c39c7638bdbe8
[ "MIT" ]
2
2021-02-08T17:33:36.000Z
2021-03-08T19:09:39.000Z
DigestingDuck/Pages/Ativos.xaml.cs
JorgeBeserra/DigestingDuck
66949c9dabee6f8e37a3e00ba90c39c7638bdbe8
[ "MIT" ]
55
2021-02-10T05:51:58.000Z
2022-03-31T12:03:50.000Z
DigestingDuck/Pages/Ativos.xaml.cs
JorgeBeserra/DigestingDuck
66949c9dabee6f8e37a3e00ba90c39c7638bdbe8
[ "MIT" ]
null
null
null
using DigestingDuck.models; using Realms.Exceptions; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace DigestingDuck.Pages { /// <summary> /// Lógica interna para Ativos.xaml /// </summary> public partial class Ativos : Page { public Ativos() { InitializeComponent(); } private void PageAtivos_Loaded(object sender, RoutedEventArgs e) { datagridAtivosBinaria.ItemsSource = ((MainWindow)Application.Current.MainWindow).ativosBinaria; datagridAtivosTurbo.ItemsSource = ((MainWindow)Application.Current.MainWindow).ativosTurbo; datagridAtivosDigital.ItemsSource = ((MainWindow)Application.Current.MainWindow).ativosDigital; } private void DatagridAtivosBinaria_MouseDoubleClick(object sender, MouseButtonEventArgs e) { try { if (sender != null) { DataGrid grid = (DataGrid)sender; if (grid != null && grid.SelectedItems != null && grid.SelectedItems.Count == 1) { var value = ((AtivosStatus)grid.SelectedItem); var t = ((MainWindow)Application.Current.MainWindow).ativosBinaria.Where(x => x.Id == value.Id).First(); if (value.Alvo == true) { ((MainWindow)Application.Current.MainWindow).database.realm.Write(() => { t.Alvo = false; }); ((MainWindow)Application.Current.MainWindow).GerarTexto("O ativo " + value.Descricao + " [" + value.Id + "] da categoria BINARIA foi REMOVIDO dos alvo."); } else { ((MainWindow)Application.Current.MainWindow).database.realm.Write(() => { t.Alvo = true; }); ((MainWindow)Application.Current.MainWindow).GerarTexto("O ativo " + value.Descricao + " [" + value.Id + "] da categoria BINARIA foi MARCADO como alvo."); } } } } catch (RealmException ex) { ((MainWindow)Application.Current.MainWindow).clientBug.Notify(ex); MessageBox.Show(ex.Message.ToString()); } } private void DatagridAtivosTurbo_MouseDoubleClick(object sender, MouseButtonEventArgs e) { try { if (sender != null) { DataGrid grid = (DataGrid)sender; if (grid != null && grid.SelectedItems != null && grid.SelectedItems.Count == 1) { var value = ((AtivosStatus)grid.SelectedItem); var t = ((MainWindow)Application.Current.MainWindow).ativosTurbo.Where(x => x.Id == value.Id).First(); if (value.Alvo == true) { ((MainWindow)Application.Current.MainWindow).database.realm.Write(() => { t.Alvo = false; }); ((MainWindow)Application.Current.MainWindow).GerarTexto("O ativo " + value.Descricao + " [" + value.Id + "] da categoria TURBO foi REMOVIDO dos alvo."); } else { ((MainWindow)Application.Current.MainWindow).database.realm.Write(() => { t.Alvo = true; }); ((MainWindow)Application.Current.MainWindow).GerarTexto("O ativo " + value.Descricao + " [" + value.Id + "] da categoria TURBO foi MARCADO como alvo."); } } } } catch (RealmException ex) { ((MainWindow)Application.Current.MainWindow).clientBug.Notify(ex); MessageBox.Show(ex.Message.ToString()); } } private void DatagridAtivosBinaria_SelectionChanged(object sender, SelectionChangedEventArgs e) { } private void DatagridAtivosDigital_MouseDoubleClick(object sender, MouseButtonEventArgs e) { try { if (sender != null) { DataGrid grid = (DataGrid)sender; if (grid != null && grid.SelectedItems != null && grid.SelectedItems.Count == 1) { var value = ((AtivosStatus)grid.SelectedItem); var t = ((MainWindow)Application.Current.MainWindow).ativosDigital.Where(x => x.Id == value.Id).First(); if (value.Alvo == true) { ((MainWindow)Application.Current.MainWindow).database.realm.Write(() => { t.Alvo = false; }); ((MainWindow)Application.Current.MainWindow).GerarTexto("O ativo " + value.Descricao + " [" + value.Id + "] da categoria DIGITAL foi REMOVIDO dos alvo."); } else { ((MainWindow)Application.Current.MainWindow).database.realm.Write(() => { t.Alvo = true; }); ((MainWindow)Application.Current.MainWindow).GerarTexto("O ativo " + value.Descricao + " [" + value.Id + "] da categoria DIGITAL foi MARCADO como alvo."); } } } } catch (RealmException ex) { ((MainWindow)Application.Current.MainWindow).clientBug.Notify(ex); MessageBox.Show(ex.Message.ToString()); } } } }
39.270968
182
0.516511