text
stringlengths
13
6.01M
using TMPro; using UnityEngine; using UnityEngine.UI; namespace CanYouCount { public class MainMenuScreen : BaseScreen { [SerializeField] private Button _playButton = null; [SerializeField] private Button _leaderboardButton = null; [SerializeField] private Button _quitButton = null; [SerializeField] private TMP_InputField _nameInputField = null; public override void InitializeScreen(ApplicationManager appManager) { base.InitializeScreen(appManager); _playButton.onClick.RemoveAllListeners(); _playButton.onClick.AddListener(() => { _applicationManager.AudioManager.PlayUIButtonClick(); _applicationManager.StartNewGame(); }); _leaderboardButton.onClick.RemoveAllListeners(); _leaderboardButton.onClick.AddListener(() => { _applicationManager.AudioManager.PlayUIButtonClick(); _applicationManager.ChangeState(AppStates.Leaderboard); }); _quitButton.onClick.RemoveAllListeners(); _quitButton.onClick.AddListener(() => { #if UNITY_EDITOR UnityEditor.EditorApplication.isPlaying = false; #else Application.Quit(0); #endif }); _nameInputField.onEndEdit.RemoveAllListeners(); _nameInputField.onEndEdit.AddListener((playerNameInput) => { _applicationManager.PlayerName = playerNameInput; UpdatePlayerName(); }); UpdatePlayerName(); } private void UpdatePlayerName() { _nameInputField.text = _applicationManager.PlayerName; } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Threading; using System.IO; using OpenStack.Swift; namespace Rackspace.Cloudfiles.Depricated { [Obsolete] public class Connection { public const string US_AUTH_URL = "https://auth.api.rackspacecloud.com/v1.0"; public const string UK_AUTH_URL = "https://lon.auth.api.rackspacecloud.com/v1.0"; public const string DEFAULT_AUTH_URL = US_AUTH_URL; private readonly ProgressCallback callbacks; private readonly OperationCompleteCallback operation_complete_callback; private string username; private string api_key; private string auth_token; private string auth_url; private string storage_url; private string cdn_management_url; private string user_agent = "CloudFiles-C#/v3.0"; private readonly bool _snet; private readonly Client _client; /* * <summary>This Class is used to connect to Cloud Files</summary> * <param name='user_creds'>Pass a valid UserCredentials <see cref="Rackspace.Cloudfiles.UserCredentials" /> * object to supply connection info</param> */ [Obsolete] public Connection(UserCredentials user_creds) { _client = new CF_Client(); username = user_creds.UserName; api_key = user_creds.ApiKey; auth_token = user_creds.AuthToken; storage_url = user_creds.StorageUrl.ToString(); cdn_management_url = user_creds.CdnMangementUrl.ToString(); auth_url = user_creds.AuthUrl == null ? DEFAULT_AUTH_URL : user_creds.AuthUrl.ToString(); if (auth_token == null || storage_url == null) { Authenticate(); } } [Obsolete] public Connection(UserCredentials user_creds, bool snet) : this(user_creds) { _snet = snet; } [Obsolete] public string UserName { get { return username; } set { username = value; } } [Obsolete] public string ApiKey { get { return api_key; } set { api_key = value; } } [Obsolete] public string AuthToken { get { return auth_token; } set { auth_token = value; } } [Obsolete] public string StorageUrl { get { return storage_url; } set { storage_url = value; } } [Obsolete] public string CdnMangementUrl { get { return cdn_management_url; } set { cdn_management_url = value; } } [Obsolete] public string AuthUrl { get { return auth_url; } set { auth_url = value; } } [Obsolete] public int Timeout { get { return _client.Timeout; } set { _client.Timeout = value; } } [Obsolete] public string UserAgent { get { return user_agent; } set { user_agent = value; } } [Obsolete] public Boolean HasCDN() { return !string.IsNullOrEmpty(CdnMangementUrl); } [Obsolete] public void AddProgessWatcher(ProgressCallback callback) { if (callbacks == null) { _client.Progress = callback; } else { _client.Progress += callback; } } [Obsolete] public void AddOperationCompleteCallback( OperationCompleteCallback callback) { if (operation_complete_callback == null) { _client.OperationComplete = callback; } else { _client.OperationComplete += callback; } } [Obsolete] public void Authenticate() { var headers = new Dictionary<string, string> {{"user-agent", user_agent}}; try { AuthResponse res = _client.GetAuth(auth_url, username, api_key, headers, new Dictionary<string, string>(), _snet); storage_url = res.Headers["x-storage-url"]; auth_token = res.Headers["x-auth-token"]; if (res.Headers.ContainsKey("x-cdn-management-url")) { cdn_management_url = res.Headers["x-cdn-management-url"]; } } catch (ClientException e) { switch (e.Status) { case -1 : throw new TimeoutException(); case 401: throw new AuthenticationFailedException("Bad Username and API key"); default: throw new AuthenticationFailedException("Error: " + e.Status.ToString(CultureInfo.InvariantCulture)); } } } [Obsolete] public AccountInformation GetAccountInformation() { var headers = new Dictionary<string, string> {{"user-agent", user_agent}}; try { return new AccountInformation(_client.HeadAccount(storage_url, auth_token, headers, new Dictionary<string, string>()).Headers); } catch (ClientException e) { switch (e.Status) { case -1: throw new TimeoutException(); case 401: throw new AuthenticationFailedException(); default: throw new CloudFilesException("Error: " + e.Status); } } } [Obsolete] public void CreateContainer(string container_name, Dictionary<string, string> headers) { Common.ValidateContainerName(container_name); headers.Add("user-agent", user_agent); try { _client.PutContainer(storage_url, auth_token, container_name, headers, new Dictionary<string, string>()); } catch (ClientException e) { switch (e.Status) { case -1: throw new TimeoutException(); case 401: throw new AuthenticationFailedException(); default: throw new CloudFilesException("Error: " + e.Status); } } } [Obsolete] public void CreateContainer(string container_name) { var headers = new Dictionary<string, string>(); CreateContainer(container_name, headers); } [Obsolete] public void DeleteContainer(string container_name) { if (string.IsNullOrEmpty(container_name)) { throw new ArgumentNullException(); } Common.ValidateContainerName(container_name); var headers = new Dictionary<string, string> {{"user-agent", user_agent}}; try { _client.DeleteContainer(storage_url,auth_token, container_name, headers, new Dictionary<string, string>()); } catch (ClientException e) { switch (e.Status) { case -1: throw new TimeoutException(); case 401: throw new AuthenticationFailedException(); case 404: throw new ContainerNotFoundException(); case 409: throw new ContainerNotEmptyException(); default: throw new CloudFilesException("Error: " + e.Status); } } } [Obsolete] public void DeleteStorageItem(string container_name, string object_name) { if (string.IsNullOrEmpty(container_name) || string.IsNullOrEmpty(object_name)) { throw new ArgumentNullException(); } Common.ValidateContainerName(container_name); Common.ValidateObjectName(object_name); var headers = new Dictionary<string, string> {{"user-agent", user_agent}}; try { _client.DeleteObject(storage_url,auth_token,container_name,object_name, headers, new Dictionary<string, string>()); } catch (ClientException e) { switch (e.Status) { case -1: throw new TimeoutException(); case 401: throw new AuthenticationFailedException(); case 404: throw new ObjectNotFoundException(); default: throw new CloudFilesException("Error: " + e.Status); } } } [Obsolete] public void PurgePublicObject(string container_name, string object_name, string[] email_addresses) { if (string.IsNullOrEmpty(container_name) || string.IsNullOrEmpty(object_name)) { throw new ArgumentNullException(); } Common.ValidateContainerName(container_name); Common.ValidateObjectName(object_name); var headers = new Dictionary<string, string>(); var emails = ""; var counter = 0; if (email_addresses.Length > 0) { foreach (string str in email_addresses) { counter++; emails = emails + str; if (counter < email_addresses.Length && !string.IsNullOrEmpty(str)) { emails = emails + ","; } } if(emails.Length > 0) { headers.Add("X-Purge-Email", emails); } } try { _client.DeleteObject(cdn_management_url, auth_token, container_name, object_name, headers, new Dictionary<string, string>()); } catch (ClientException e) { switch (e.Status) { case -1: throw new TimeoutException(); case 401: throw new AuthenticationFailedException(); case 404: throw new ObjectNotFoundException(); default: throw new CloudFilesException("Error: " + e.Status); } } } [Obsolete] public void PurgePublicObject(string container_name, string object_name) { var email_addresses = new string[1]; PurgePublicObject(container_name, object_name, email_addresses); } [Obsolete] public List<Dictionary<string, string>> GetContainers(Dictionary<GetContainersListParameters, string> parameters) { var query = new Dictionary<string, string>(); var headers = new Dictionary<string, string> {{"user-agent", user_agent}}; if (parameters.ContainsKey(GetContainersListParameters.Limit)) { query.Add("limit", parameters[GetContainersListParameters.Limit]); } if (parameters.ContainsKey(GetContainersListParameters.Marker)) { query.Add("marker", parameters[GetContainersListParameters.Marker]); } if (parameters.ContainsKey(GetContainersListParameters.Prefix)) { query.Add("prefix", parameters[GetContainersListParameters.Prefix]); } try { return _client.GetAccount(StorageUrl, AuthToken, headers, query, false).Containers; } catch (ClientException e) { switch (e.Status) { case -1: throw new TimeoutException(); case 401: throw new AuthenticationFailedException(); default: throw new CloudFilesException("Error: " + e.Status); } } } [Obsolete] public List<Dictionary<string, string>> GetContainers() { var parameters = new Dictionary<GetContainersListParameters, string>(); return GetContainers(parameters); } [Obsolete] public List<Dictionary<string, string>> GetPublicContainers(Dictionary<GetPublicContainersListParameters,string> parameters) { var query = new Dictionary<string, string>(); var headers = new Dictionary<string, string> {{"user-agent", user_agent}}; if (parameters.ContainsKey(GetPublicContainersListParameters.Limit)) { query.Add("limit", parameters[GetPublicContainersListParameters.Limit]); } if (parameters.ContainsKey(GetPublicContainersListParameters.Marker)) { query.Add("marker", parameters[GetPublicContainersListParameters.Marker]); } if (parameters.ContainsKey(GetPublicContainersListParameters.EnabledOnly)) { query.Add("enabled_only", parameters[GetPublicContainersListParameters.EnabledOnly]); } try { return _client.GetCDNAccount(CdnMangementUrl, AuthToken, headers, query, false).Containers; } catch (ClientException e) { switch (e.Status) { case -1: throw new TimeoutException(); case 401: throw new AuthenticationFailedException(); case 404: throw new ObjectNotFoundException(); default: throw new CloudFilesException("Error: " + e.Status); } } } [Obsolete] public List<Dictionary<string, string>> GetPublicContainers() { var parameters = new Dictionary<GetPublicContainersListParameters,string>(); return GetPublicContainers(parameters); } [Obsolete] public List<Dictionary<string, string>> GetContainerItemList(string container_name, Dictionary<GetItemListParameters,string> parameters) { if (string.IsNullOrEmpty(container_name)) { throw new ArgumentNullException(); } Common.ValidateContainerName(container_name); var query = new Dictionary<string, string>(); var headers = new Dictionary<string, string> {{"user-agent", user_agent}}; if (parameters.ContainsKey(GetItemListParameters.Limit)) { query.Add("limit", parameters[GetItemListParameters.Limit]); } if (parameters.ContainsKey(GetItemListParameters.Prefix)) { query.Add("prefix", parameters[GetItemListParameters.Prefix]); } if (parameters.ContainsKey(GetItemListParameters.Marker)) { query.Add("marker", parameters[GetItemListParameters.Marker]); } if (parameters.ContainsKey(GetItemListParameters.Delimiter)) { query.Add("delimiter", parameters[GetItemListParameters.Delimiter]); } try { return _client.GetContainer(StorageUrl,AuthToken,container_name, headers, query, false).Objects; } catch (ClientException e) { switch (e.Status) { case -1: throw new TimeoutException(); case 401: throw new AuthenticationFailedException(); case 404: throw new ContainerNotFoundException(); default: throw new CloudFilesException("Error: " + e.Status); } } } [Obsolete] public List<Dictionary<string, string>> GetContainerItemList(string container_name) { var parameters = new Dictionary<GetItemListParameters, string>(); return GetContainerItemList(container_name, parameters); } [Obsolete] public Container GetContainerInformation(string container_name) { if (string.IsNullOrEmpty(container_name)) { throw new ArgumentNullException(); } Common.ValidateContainerName(container_name); var headers = new Dictionary<string, string> {{"user-agent", user_agent}}; try { return HasCDN() ? new Container(container_name, _client.HeadContainer(storage_url, auth_token, container_name, headers, new Dictionary<string, string>()),_client.HeadContainer(cdn_management_url, auth_token, container_name, headers, new Dictionary<string, string>())) : new Container(container_name, _client.HeadContainer(storage_url, auth_token, container_name, headers, new Dictionary<string, string>()),new ContainerResponse(new Dictionary<string, string>(), null, -1, new List<Dictionary<string, string>>())); } catch (ClientException e) { switch (e.Status) { case -1: throw new TimeoutException(); case 401: throw new AuthenticationFailedException(); case 404: throw new ContainerNotFoundException(); default: throw new CloudFilesException("Error: " + e.Status); } } } [Obsolete] public void PutStorageItem(string container_name, string local_file_path, Dictionary<string, string> metadata) { var contents = new FileStream(local_file_path, FileMode.Open, FileAccess.Read); var object_name = Path.GetFileName(local_file_path); PutStorageItem(container_name, contents, object_name, metadata); } [Obsolete] public void PutStorageItem(string container_name, string local_file_path) { var metadata = new Dictionary<string, string>(); PutStorageItem(container_name, local_file_path, metadata); } [Obsolete] public void PutStorageItem(string container_name, string local_file_path, string object_name) { var metadata = new Dictionary<string, string>(); PutStorageItem(container_name, local_file_path, object_name, metadata); } [Obsolete] public void PutStorageItem(string container_name, string local_file_path, string object_name, Dictionary<string, string> metadata) { var contents = new FileStream(local_file_path, FileMode.Open, FileAccess.Read); PutStorageItem(container_name, contents, object_name, metadata); } [Obsolete] public void PutStorageItem(string container_name, Stream object_stream, string object_name) { var metadata = new Dictionary<string, string>(); PutStorageItem(container_name, object_stream, object_name, metadata); } [Obsolete] public void PutStorageItem(string container_name, Stream object_stream, string object_name, Dictionary<string, string> metadata) { if (string.IsNullOrEmpty(container_name) || string.IsNullOrEmpty(object_name)) { throw new ArgumentNullException(); } Common.ValidateContainerName(container_name); Common.ValidateObjectName(object_name); metadata.Add("user-agent", user_agent); try { _client.PutObject(storage_url, auth_token, container_name, object_name, object_stream, metadata, new Dictionary<string, string>()); } catch (ClientException e) { switch (e.Status) { case -1: throw new TimeoutException(); case 401: throw new AuthenticationFailedException(); case 404: throw new ContainerNotFoundException(); case 422: throw new InvalidETagException(); default: throw new CloudFilesException("Error: " + e.Status); } } } [Obsolete] public void PutStorageItemAsync(string container_name, string local_file_path, Dictionary<string, string> metadata) { Stream contents = new FileStream(local_file_path, FileMode.Open, FileAccess.Read); string object_name = Path.GetFileName(local_file_path); PutStorageItemAsync(container_name, contents, object_name, metadata); } [Obsolete] public void PutStorageItemAsync(string container_name, string local_file_path) { var metadata = new Dictionary<string, string>(); PutStorageItemAsync(container_name, local_file_path, metadata); } [Obsolete] public void PutStorageItemAsync(string container_name, string local_file_path, string object_name) { var metadata = new Dictionary<string, string>(); PutStorageItemAsync(container_name, local_file_path, object_name, metadata); } [Obsolete] public void PutStorageItemAsync(string container_name, string local_file_path, string object_name, Dictionary<string, string> metadata) { Stream contents = new FileStream(local_file_path, FileMode.Open, FileAccess.Read); PutStorageItemAsync(container_name, contents, object_name, metadata); } [Obsolete] public void PutStorageItemAsync(string container_name, Stream object_stream, string object_name, Dictionary<string, string> metadata) { var thread = new Thread( () => PutStorageItem(container_name, object_stream, object_name, metadata)); thread.Start(); } [Obsolete] public void GetStorageItem(string container_name, string object_name, string path, Dictionary<string, string> headers) { if (path.Equals(null)) { throw new ArgumentNullException(); } var res = GetStorageItem(container_name, object_name, headers); int bytes_written = 0; Stream stream = new FileStream(path, FileMode.OpenOrCreate); var buff = new byte[1048576]; try { while (true) { int read = res.ObjectStream.Read(buff, 0, buff.Length); if (read > 0) { bytes_written += buff.Length; stream.Write(buff, 0, read); if (callbacks != null) { callbacks(bytes_written); } } else { break; } } } finally { stream.Close(); res.ObjectStream.Close(); } if (operation_complete_callback != null) { operation_complete_callback(); } } [Obsolete] public void GetStorageItem(string container_name, string object_name, string path) { var headers = new Dictionary<string, string>(); GetStorageItem(container_name, object_name, path, headers); } [Obsolete] public StorageItem GetStorageItem(string container_name, string object_name) { var headers = new Dictionary<string, string>(); return GetStorageItem(container_name, object_name, headers); } [Obsolete] public StorageItem GetStorageItem(string container_name, string object_name, Dictionary<string, string> headers) { if (container_name == null|| object_name == null || headers == null) { throw new ArgumentNullException(); } Common.ValidateContainerName(container_name); Common.ValidateObjectName(object_name); headers.Add("user-agent", user_agent); try { ObjectResponse res = _client.GetObject(storage_url, auth_token, container_name, object_name, headers, new Dictionary<string, string>()); return new StorageItem(object_name, res.Headers, res.ObjectData); } catch (ClientException e) { switch (e.Status) { case -1: throw new TimeoutException(); case 401: throw new AuthenticationFailedException(); case 404: throw new ContainerNotFoundException(); default: throw new CloudFilesException("Error: " + e.Status); } } } [Obsolete] public void GetStorageItemAsync(string container_name, string object_name, string path,Dictionary<string, string> headers) { var thread = new Thread( () => GetStorageItem(container_name, object_name, path, headers)); thread.Start(); } [Obsolete] public void GetStorageItemAsync(string container_name, string object_name, string path) { var headers = new Dictionary<string, string>(); GetStorageItemAsync(container_name, object_name, path, headers); } [Obsolete] public Dictionary<string, Uri> MarkContainerAsPublic(string container_name, long ttl, bool log_retention) { if (container_name.Equals(null) || ttl.Equals(null) || log_retention.Equals(null)) { throw new ArgumentNullException(); } Common.ValidateContainerName(container_name); if (ttl < 900 || ttl > 1577836800) { throw new TTLLengthException("TTL Too short or too long. Min Value 900 Max Value 1577836800" + " value used: " + ttl.ToString(CultureInfo.InvariantCulture)); } if (!HasCDN()) { throw new CDNNotEnabledException(); } var headers = new Dictionary<string, string> {{"X-Log-Retention", log_retention.ToString(CultureInfo.InvariantCulture)}, {"X-TTL", ttl.ToString(CultureInfo.InvariantCulture)}}; try { var res = _client.PutContainer(cdn_management_url, auth_token, container_name, headers, new Dictionary<string, string>()); var cdn_urls = new Dictionary<string, Uri>(); if (res.Headers.ContainsKey("x-cdn-uri")) { cdn_urls.Add("x-cdn-uri", new Uri(res.Headers["x-cdn-uri"])); } if (res.Headers.ContainsKey("x-cdn-ssl-uri")) { cdn_urls.Add("x-cdn-ssl-uri", new Uri(res.Headers["x-cdn-ssl-uri"])); } if (res.Headers.ContainsKey("x-cdn-streaming-uri")) { cdn_urls.Add("x-cdn-streaming-uri", new Uri(res.Headers["x-cdn-streaming-uri"])); } return cdn_urls; } catch (ClientException e) { switch (e.Status) { case -1: throw new TimeoutException(); case 401: throw new AuthenticationFailedException(); case 404: throw new ContainerNotFoundException(); default: throw new CloudFilesException("Error: " + e.Status); } } } [Obsolete] public Dictionary<string, Uri> MarkContainerAsPublic(string container_name, Int64 ttl) { return MarkContainerAsPublic(container_name, ttl, false); } [Obsolete] public Dictionary<string, Uri> MarkContainerAsPublic(string container_name) { return MarkContainerAsPublic(container_name, 900, false); } [Obsolete] public void MarkContainerAsPrivate(string container_name) { if (container_name == null) { throw new ArgumentNullException(); } Common.ValidateContainerName(container_name); if (!HasCDN()) { throw new CDNNotEnabledException(); } var headers = new Dictionary<string, string> {{"x-cdn-enabled", "false"}}; try { _client.PostContainer(cdn_management_url, auth_token, container_name, headers, new Dictionary<string, string>()); } catch (ClientException e) { switch (e.Status) { case -1: throw new TimeoutException(); case 401: throw new AuthenticationFailedException(); case 404: throw new ContainerNotFoundException(); default: throw new CloudFilesException("Error: " + e.Status); } } } [Obsolete] public void SetDetailsOnPublicContainer(string container_name, Dictionary<string, string> headers) { if (container_name == null) { throw new ArgumentNullException(); } try { _client.PostContainer(cdn_management_url, auth_token, container_name, headers, new Dictionary<string, string>()); } catch (ClientException e) { switch (e.Status) { case -1: throw new TimeoutException(); case 401: throw new AuthenticationFailedException(); case 404: throw new ContainerNotFoundException(); default: throw new CloudFilesException("Error: " + e.Status); } } } [Obsolete] public void SetDetailsOnPublicContainer(string container_name, bool logging_enabled, long ttl) { var headers = new Dictionary<string, string> {{"x-logging-enabled", logging_enabled.ToString(CultureInfo.InvariantCulture)}, {"x-ttl", ttl.ToString(CultureInfo.InvariantCulture)}}; SetDetailsOnPublicContainer(container_name, headers); } [Obsolete] public void SetStorageItemMetaInformation(string container_name, string object_name, Dictionary<string, string> headers) { if (container_name == null || object_name == null || headers == null) { throw new ArgumentNullException(); } Common.ValidateContainerName(container_name); Common.ValidateObjectName(object_name); try { _client.PostObject(storage_url, auth_token, container_name, object_name, headers, new Dictionary<string, string>()); } catch (ClientException e) { switch (e.Status) { case -1: throw new TimeoutException(); case 401: throw new AuthenticationFailedException(); case 404: throw new ObjectNotFoundException(); default: throw new CloudFilesException("Error: " + e.Status); } } } [Obsolete] public void SetContainerMetaInformation(string container_name, Dictionary<string, string> headers) { if (container_name == null || headers == null) { throw new ArgumentNullException(); } Common.ValidateContainerName(container_name); try { _client.PostContainer(storage_url, auth_token, container_name, headers, new Dictionary<string, string>()); } catch (ClientException e) { switch (e.Status) { case -1: throw new TimeoutException(); case 401: throw new AuthenticationFailedException(); case 404: throw new ContainerNotFoundException(); default: throw new CloudFilesException("Error: " + e.Status); } } } [Obsolete] public void SetAccountMetaInformation(Dictionary<string, string> headers) { if (headers == null) { throw new ArgumentNullException(); } try { _client.PostAccount(storage_url, auth_token, headers, new Dictionary<string, string>()); } catch (ClientException e) { switch (e.Status) { case -1: throw new TimeoutException(); case 401: throw new AuthenticationFailedException(); default: throw new CloudFilesException("Error: " + e.Status); } } } } /* * Helper Classes and Functions */ [Obsolete] public class AccountInformation { [Obsolete] public AccountInformation(Dictionary<string, string> headers) { Metadata = new Dictionary<string, string>(); Headers = new Dictionary<string, string>(); foreach (KeyValuePair<string, string> header in headers) { if (header.Key.Contains("x-account-meta")) { Metadata.Add(header.Key.Remove(0, 15), header.Value); } else if (header.Key == "x-account-container-count") { ContainerCount = int.Parse(header.Value); } else if (header.Key == "x-account-bytes-used") { BytesUsed = long.Parse(header.Value); } else { Headers.Add(header.Key, header.Value); } } } [Obsolete] public int ContainerCount { get; set; } [Obsolete] public long BytesUsed { get; set; } [Obsolete] public Dictionary<string, string>Metadata; [Obsolete] public Dictionary<string, string>Headers; } [Obsolete] public class Container { /// <summary> /// Constructor /// </summary> /// <param name="container_name">Name of the container</param> [Obsolete] public Container(string container_name) { Name = container_name; ObjectCount = -1; ByteCount = -1; TTL = -1; CdnUri = null; CdnSslUri = null; CdnStreamingUri = null; CdnEnabled = false; LogRetention = false; Metadata = new Dictionary<string, string>(); } [Obsolete] public Container(string container_name, ContainerResponse resp, ContainerResponse cdn_resp) : this(container_name) { foreach (KeyValuePair<string, string> header in resp.Headers) { if (header.Key.Contains("x-container-meta")) { var key = header.Key.Remove(0, 17); Metadata.Add(key, header.Value); } } if (resp.Headers.ContainsKey("x-container-bytes-used")) { ByteCount = Int64.Parse(resp.Headers["x-container-bytes-used"]); } if (resp.Headers.ContainsKey("x-container-object-count")) { ObjectCount = Int64.Parse(resp.Headers["x-container-object-count"]); } if (cdn_resp.Headers.Count > 0) { TTL = Int64.Parse(cdn_resp.Headers["x-ttl"]); CdnUri = new Uri(cdn_resp.Headers["x-cdn-uri"]); CdnSslUri = new Uri(cdn_resp.Headers["x-cdn-ssl-uri"]); CdnStreamingUri = new Uri(cdn_resp.Headers["x-cdn-streaming-uri"]); LogRetention = Convert.ToBoolean(cdn_resp.Headers["x-log-retention"]); CdnEnabled = Convert.ToBoolean(cdn_resp.Headers["x-cdn-enabled"]); } } [Obsolete] public Dictionary<string, string> Metadata; /// <summary> /// Size of the container /// </summary> [Obsolete] public long ByteCount; /// <summary> /// Number of items in the container /// </summary> [Obsolete] public long ObjectCount; /// <summary> /// Name of the container /// </summary> [Obsolete] public string Name; /// <summary> /// The maximum time (in seconds) content should be kept alive on the CDN before it checks for freshness. /// </summary> [Obsolete] public long TTL; /// <summary> /// The URI one can use to access objects in this container via the CDN. No time based URL stuff will be included with this URI /// </summary> [Obsolete] public Uri CdnUri; /// <summary> /// The SSL URI one can use to access objects in this container via the CDN. /// </summary> [Obsolete] public Uri CdnSslUri; /// <summary> /// The Streaming URI one can use to access objects in this container via the CDN. /// </summary> [Obsolete] public Uri CdnStreamingUri; /// <summary> /// Boolean is CDN is enabled or not /// </summary> [Obsolete] public bool CdnEnabled; /// <summary> /// Boolean is CDN Log Retention Enabled /// </summary> [Obsolete] public bool LogRetention; } [Obsolete] public class StorageItem { [Obsolete] public string Name; [Obsolete] public Dictionary<string, string> Metadata; [Obsolete] public Dictionary<string, string> Headers; [Obsolete] public string ContentType; [Obsolete] public Stream ObjectStream; [Obsolete] public long ContentLength; [Obsolete] public DateTime LastModified; [Obsolete] public StorageItem(string object_name) { Name = object_name; ContentType = null; ObjectStream = null; ContentLength = -1; LastModified = new DateTime(); Metadata = new Dictionary<string, string>(); Headers = new Dictionary<string, string>(); } [Obsolete] public StorageItem(string object_name, Dictionary<string, string> headers, Stream object_stream) : this(object_name) { ObjectStream = object_stream; foreach (var header in headers) { if(header.Key.Contains("x-object-meta")) { string key = header.Key.Remove(0, 14); Metadata.Add(key, header.Value); } else if (header.Key.Equals("content-length")) { ContentLength = Int64.Parse(header.Value); } else if (header.Key.Equals("content-type")) { ContentType = header.Value.ToString(CultureInfo.InvariantCulture); } else if (header.Key.Equals("last-modified")) { LastModified = DateTime.Parse(header.Value); } else { Headers.Add(header.Key, header.Value); } } } } [Obsolete] public enum GetItemListParameters { Limit, Marker, Prefix, Path, Delimiter } [Obsolete] public enum GetContainersListParameters { Limit, Marker, Prefix } [Obsolete] public enum GetPublicContainersListParameters { Limit, Marker, EnabledOnly } }
namespace Cogito.Kademlia { public class KNodePingResponse : KNodeResponse { /// <summary> /// Initializes a new instance. /// </summary> /// <param name="status"></param> public KNodePingResponse(KNodeResponseStatus status) : base(status) { } } }
using System; using System.Collections.Generic; using System.Linq; using Android.Support.V7.Widget; using Android.Views; namespace DartsTracker { public class MainRecViewAdapter : RecyclerView.Adapter { public List<string> ItemList { get; set; } public event EventHandler<string> ItemClick; public event EventHandler<string> ItemLongClick; private bool showPopupMenu; public MainRecViewAdapter(List<string> itemList, bool showPopupMenu) { this.showPopupMenu = showPopupMenu; ItemList = itemList; } public override int ItemCount => ItemList.Count(); public override void OnBindViewHolder(RecyclerView.ViewHolder holder, int position) { MainRecViewHolder vh = holder as MainRecViewHolder; vh.TxtView.Text = ItemList[position]; } public override RecyclerView.ViewHolder OnCreateViewHolder(ViewGroup parent, int viewType) { View itemView = LayoutInflater.From(parent.Context) .Inflate(Resource.Layout.main_rec_item, parent, false); return new MainRecViewHolder(itemView, onClick, onLongClick, showPopupMenu); } void onClick(string name) { ItemClick?.Invoke(this, name); } void onLongClick(string name) { ItemLongClick?.Invoke(this, name); } } }
using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace mokiniu_sistema.Models { public class MokiniuContext : DbContext { public DbSet<Mokykla> Mokyklos { get; set; } public DbSet<Rajonas> Rajonai { get; set; } public DbSet<Tevas> Tevai { get; set; } public DbSet<Vaikas> Vaikai { get; set; } public MokiniuContext(DbContextOptions<MokiniuContext> options) : base(options) { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel; using Binding; using DomainModel.BusinessObjects; namespace SimpleBinding { [Serializable] public class AddressViewModel : INotifyPropertyChanged { #region Properties private string id; public string ID { get { return id; } set { if (id != value) { id = value; OnPropertyChanged("ID"); } } } private string userName; public string UserName {get { return userName;} set { if (userName != value) { userName = value; OnPropertyChanged("UserName"); } } } private NotifyPropertyCollection<Address> availableAddresses; public NotifyPropertyCollection<Address> AvailableAddresses { get { return availableAddresses; } set { if (availableAddresses != value) { availableAddresses = value; availableAddresses.PropertyChanged += new PropertyChangedEventHandler(OnPropertyChanged); } } } private Address selectedAddress; public Address SelectedAddress { get { return selectedAddress; } set { if (selectedAddress != value) { selectedAddress = value; selectedAddress.PropertyChanged += new PropertyChangedEventHandler(OnPropertyChanged); } } } #endregion #region INotifyPropertyChanged Members [field: NonSerialized] public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged(string propertyName) { OnPropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } protected virtual void OnPropertyChanged(object sender, PropertyChangedEventArgs e) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) { handler(sender, e); } } #endregion } }
using Castle.Core.Internal; namespace Athena.Import.Extractors { public class StoragePlaceCommentExtractor { public static string Extract(string text) { if (text.IsNullOrEmpty()) { return null; } return text.Trim(); } } }
using SGA.Models; using System.Data.Entity.ModelConfiguration; namespace SGA.EntitiesConfig { public class EmentaConfig : EntityTypeConfiguration<Ementa> { public EmentaConfig() { HasKey(t => t.EmentaId); Property(t => t.Descricao).HasMaxLength(500); Property(t => t.Descricao).HasMaxLength(800); } } }
using System; using System.Collections.Generic; /*Write a program that finds the maximal sequence of equal elements in an array. Example: input | result 2, 1, 1, 2, 3, 3, 2, 2, 2, 1 | 2, 2, 2*/ class Program { static void Main() { Console.WriteLine("Enter how much members have your sequence."); int N = int.Parse(Console.ReadLine()); int[] numbers = new int[N]; for (int i = 0; i < N; i++) { numbers[i] = int.Parse(Console.ReadLine()); } int br = 0; int maxElement = numbers[0]; int maxSequence = 0; int num = numbers[0]; for (int i = 0; i < N; i++) { if (num == numbers[i]) { br++; } else { if (maxSequence < br) { maxSequence = br; maxElement = numbers[i-1]; } else { br = 0; } } } Console.WriteLine(new string(char.Parse(maxElement.ToString()), maxSequence)); } }
using System; using System.Collections.Generic; //using Microsoft.Commerce.Tools.Test.BizOpsTools.Common.BatchTool; //using Microsoft.Commerce.Tools.Test.BizOpsTools.Common.Helper; //using Microsoft.Commerce.Tools.Test.BizOpsTools.TestDataGenerator.Transports; using Microsoft.Subscriptions.Schema; using MintBilling = Microsoft.Online.Commerce.Mint.Billing; namespace PICaller.MintAPI { class MintDataLib { /// <summary> /// Create account /// </summary> public static MintBilling.AccountInfoOutput CreateAccount(string countryCode, string currency, string locale, string identityValue) { string companyName = string.Format("Company_{0}", Randomizer.RandomFixedString(4)); string email = string.Format("{0}@{1}.com", Randomizer.RandomFixedString(4), Randomizer.RandomFixedNumericString(3)); string firstName = string.Format("FirstName_{0}", Randomizer.RandomFixedString(4)); string friendlyName = string.Format("FriendlyName_{0}", Randomizer.RandomFixedString(4)); string lastName = string.Format("LastName_{0}", Randomizer.RandomFixedString(4)); var request = new MintBilling.CreateAccountRequest { TrackingGuid = Guid.NewGuid(), AccountInfoInput = new MintBilling.AccountInfoInput { CustomerType = MintBilling.CustomerType.Personal, Currency = currency, CompanyName = companyName, CountryCode = countryCode, Email = email, FirstName = firstName, FriendlyName = friendlyName, LastName = lastName, Locale = locale, AddressSet = new MintBilling.Address[] { CreateAddress(firstName, friendlyName, lastName, countryCode, "Seattle", "WA", "98101") }, CustomProperties = new MintBilling.Property[] { new MintBilling.Property() { Name ="Name", Namespace = "Namespace", Value = "Value" } }, HCI = "NO", PhoneSet = new MintBilling.Phone[] { CreatePhone("5551212", countryCode) }, }, Requester = new MintBilling.Identity { IdentityEmail = "test@microsoft.com", IdentityType = "PUID", IdentityValue = identityValue, } }; return MintApiClient.CreateAccount(request); } /// <summary> /// Create mint account /// </summary> public static MintBilling.AccountInfoOutput GetAccount(string accountId, string identityValue) { var request = new MintBilling.GetAccountRequest { AccountId = accountId, CorrelationId = Guid.NewGuid(), AccountInfoDetailLevel = MintBilling.AccountInfoDetailLevel.CustomProperties, Requester = new MintBilling.Identity { IdentityEmail = "test@microsoft.com", IdentityType = "PUID", IdentityValue = identityValue, } }; return MintApiClient.GetAccount(request); } /// <summary> /// Create address /// </summary> private static MintBilling.Address CreateAddress(string firstName, string friendlyName, string lastName, string countryCode, string city, string state, string postalCode) { return new MintBilling.Address { FirstName = firstName, FriendlyName = friendlyName, LastName = lastName, Street1 = "Zi XING ROAD", Street2 = string.Empty, Street3 = string.Empty, City = city, District = state, State = state, CountryCode = countryCode, PostalCode = postalCode, }; } /// <summary> /// Create PhoneNumber /// </summary> private static MintBilling.Phone CreatePhone(string phoneNumber, string countryCode) { return new MintBilling.Phone { PhoneType = MintBilling.PhoneType.Primary, PhonePrefix = "425", PhoneNumber = phoneNumber, CountryCode = countryCode }; } /// <summary> /// Add PI /// </summary> public static MintBilling.AddPaymentInstrumentResponse AddPaymentInstrument(string accountId, MintBilling.PaymentInstrument paymentInstrument, string identityValue) { var request = new MintBilling.AddPaymentInstrumentRequest { AccountId = accountId, PaymentInstrument = paymentInstrument, TrackingGuid = Guid.NewGuid(), Requester = new MintBilling.Identity { IdentityEmail = "test@microsoft.com", IdentityType = "PUID", IdentityValue = identityValue, } }; return MintApiClient.AddPaymentInstrument(request); } /// <summary> /// Add CC PI /// </summary> /// <param name="createAccountRequest"></param> /// <returns></returns> public static MintBilling.AddPaymentInstrumentResponse AddCCPaymentInstrument(string accountId, string identityValue) { var accountInfoOutput = GetAccount(accountId, identityValue); string creditCardNumber = MintApiClient.GetRandomCreditCard(4, 16); //VISA var paymentInstrument = new MintBilling.CreditCardPaymentInstrument() { AccountHolderName = string.Format("Name_{0}", Randomizer.RandomFixedString(4)), CardType = "VISA", AddressInfo = CreateAddress(accountInfoOutput.FirstName, accountInfoOutput.FriendlyName, accountInfoOutput.LastName, accountInfoOutput.CountryCode, accountInfoOutput.AddressSet[0].City, accountInfoOutput.AddressSet[0].State, accountInfoOutput.AddressSet[0].PostalCode), Phone = CreatePhone("5551212", accountInfoOutput.CountryCode), FriendlyName = "PaymentInstrument", Status = MintBilling.PaymentInstrumentStatus.Good, EncryptedAccountNumber = MintPaymentEncryptionHelper.EncryptToByteArray(creditCardNumber, MintApiClient.GetMintPublicKey()), EncryptedCVMCode = null, ExpirationDate = "122099", }; return AddPaymentInstrument(accountId, paymentInstrument, identityValue); } /// <summary> /// Purchase subs /// </summary> public static MintBilling.PurchaseSubscriptionResponse PurchaseSubscription(string accountId, string identityValue, string paymentMethodId, Guid offeringGuid) { var accountInfoOutput = GetAccount(accountId, identityValue); Guid guid = Guid.NewGuid(); Console.WriteLine(guid); var request = new MintBilling.PurchaseSubscriptionRequest { TrackingGuid = guid, PurchaseContext = new MintBilling.PurchaseContext() { ComputeOnly = false, ProductGuid = new Guid("00000000-0000-0000-0000-000000000000"), Timestamp = DateTime.Now.AddYears(1), }, PurchaseSubscriptionInput = new MintBilling.PurchaseSubscriptionInput() { InstanceCount = 1, OfferingGuid = offeringGuid, InvoiceGroupId = "5630C9FD-D667-4476-8D07-1C97F220F48F", SalesModel = MintBilling.SalesModelType.Reseller, PONumber = "O324001", SubscriptionFriendlyName = "Subs friendly name", }, BillingInfo = new MintBilling.BillingInfo() { BillingMode = MintBilling.BillingMode.None, PaymentMethod = new MintBilling.RegisteredPaymentMethod { PaymentMethodId = paymentMethodId, }, PaymentOption = new MintBilling.PaymentOption() { EnableDefaultPaymentInstrument = false, EnableStoredValue = false, }, }, AccountContext = new MintBilling.AccountContext() { CustomerType = MintBilling.CustomerType.Personal, }, AccountId = accountId, Requester = new MintBilling.Identity { IdentityEmail = "test@microsoft.com", IdentityType = "PUID", IdentityValue = identityValue, } }; return MintApiClient.PurchaseSubscription(request); } /// <summary> /// Get Subs /// </summary> public static MintBilling.GetSubscriptionsResponse GetSubscriptions(string accountId, string subscriptionId, string identityValue) { var request = new MintBilling.GetSubscriptionsRequest { GetSubscriptionsOfAllPartners = true, AccountId = accountId, SubscriptionId = subscriptionId, Requester = new MintBilling.Identity { IdentityEmail = "test@microsoft.com", IdentityType = "PUID", IdentityValue = identityValue, } }; return MintApiClient.GetSubscriptions(request); } /// <summary> /// Cancel Subs /// </summary> /// <param name="cancelSubscriptionRequest"></param> /// <returns></returns> public static MintBilling.CancelSubscriptionResponse CancelSubscription(string accountId, string subscriptionId, string identityValue) { var request = new MintBilling.CancelSubscriptionRequest { TrackingGuid = Guid.NewGuid(), AccountId = accountId, SubscriptionId = subscriptionId, CommentInfo = new MintBilling.CommentInfo() { CommentCode = MintBilling.CommentCode.CancelSubscription, CommentText = "Test_CancelSubscription", }, CancelMode=MintBilling.CancelMode.ImmediateCancel, Requester = new MintBilling.Identity { IdentityEmail = "test@microsoft.com", IdentityType = "PUID", IdentityValue = identityValue, } }; return MintApiClient.CancelSubscription(request); } #region Privates //public static List<string> CreateContent(string apiName, List<List<string>> records) //{ // List<string> fileHeader = FileHeaders[apiName]; // List<string> content = new List<string>(); // StringBuilder header = new StringBuilder(); // for (int i = 0; i <= fileHeader.Count - 1; i++) // { // string headerValue = fileHeader[i]; // header.Append(headerValue); // if (i != fileHeader.Count - 1) // header.Append("\t"); // } // content.Add(header.ToString()); // string line = string.Empty; // foreach (List<string> record in records) // { // line = string.Empty; // for (int i = 0; i < record.Count; i++) // { // line = line + record[i]; // if (i != record.Count - 1) // line = line + "\t"; // } // content.Add(line); // } // return content; //} #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LunarTrader.Enums { public enum LogLevel { Off, Trace, Debug, Info, Warn, Error, Fatal } public enum LogType { Console, LogFile, Both } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using BLL_DAL; namespace QLNHAHANG { public partial class Form1 : Form { Login_BLL_DAL login = new Login_BLL_DAL(); public Form1() { InitializeComponent(); txtPassword.PasswordChar = '\u2022'; CenterToScreen(); btnHidePass.Image = Image.FromFile("../../img/icon/hidden.png"); } private void Form1_Load(object sender, EventArgs e) { } private void btnLogIn_Click(object sender, EventArgs e) { if (txtUsername.TextLength <= 0) { MessageBox.Show(grbTenDangNhap.Text + " không được bỏ trống!"); txtUsername.Focus(); } else if (txtPassword.TextLength <= 0) { MessageBox.Show(grbMatKhau.Text + " không được bỏ trống!"); txtPassword.Focus(); } else { string user = txtUsername.Text.Trim(); string pass = txtPassword.Text.Trim(); int kt = login.ktKH(user, pass); if (kt == -1) { MessageBox.Show("Tài khoản không tồn tại"); return; } else if (kt == 0) { MessageBox.Show("Mật khẩu không chính xác"); return; } else { DialogResult result; result = MessageBox.Show("Đăng nhập thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1); if (result == DialogResult.OK) { KHACHHANG nd = login.layKH(user); this.Visible = false; } } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace ws_seta.Models { public class CondicaoPagamento { public string codigo { get; set; } public string descricao { get; set; } public int parcelas { get; set; } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace Payroll.Models { public class Department : Basic { [Display(ResourceType = typeof(Resource), Name = "Company")] public Guid CompanyId { get; set; } [ForeignKey("CompanyId")] public virtual Company Company { get; set; } [Display(ResourceType = typeof(Resource), Name = "Description")] [Required(ErrorMessageResourceType = typeof(Resource), ErrorMessageResourceName = "RequiredField")] public string Description { get; set; } [Display(ResourceType = typeof(Resource), Name = "IsManagerDepartment")] public bool IsManagerDepartment { get; set; } [Display(ResourceType = typeof(Resource), Name = "IsOperationalDepartment")] public bool IsOperationalDepartment { get; set; } [Display(ResourceType = typeof(Resource), Name = "IsDirectionDepartment")] public bool IsDirectionDepartment { get; set; } public virtual IEnumerable<Employee> Employees { get; set; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using MySql.Data.MySqlClient; namespace POS_SYSTEM { public partial class UpdateSupplier : Form { public UpdateSupplier(string pfn, string databaseString) { InitializeComponent(); databaseConnectionStringTextBox.Text = databaseString; viewSupplier(); updatepfsession.Text = pfn; //session variable searchSupplierName(); showSupplierData(); } DialogResult dialog; DataTable dataTable; //filter database public void filterDatabase() { DataView dv = new DataView(dataTable); dv.RowFilter = string.Format("name LIKE '%{0}%'", searchSupplier.Text); updateSupplierDataGridView.DataSource = dv; } //search supplier from suppliers public void searchSupplierName() { searchSupplier.AutoCompleteMode = AutoCompleteMode.SuggestAppend; searchSupplier.AutoCompleteSource = AutoCompleteSource.CustomSource; AutoCompleteStringCollection collection = new AutoCompleteStringCollection(); try { string db = databaseConnectionStringTextBox.Text; MySqlConnection con = new MySqlConnection(db); con.Open(); MySqlCommand c = new MySqlCommand("select * from supplier", con); MySqlDataReader r = c.ExecuteReader(); while (r.Read()) { String l = r.GetString("name"); collection.Add(l); } con.Close(); } catch (Exception ex) { MessageBox.Show("Error has occured!" + ex.Message); } searchSupplier.AutoCompleteCustomSource = collection; } //fill data in fields public void showSupplierData() { try { string db = databaseConnectionStringTextBox.Text; MySqlConnection con = new MySqlConnection(db); con.Open(); MySqlCommand c = new MySqlCommand("select * from supplier WHERE name='" + this.searchSupplier.Text + "'", con); MySqlDataReader r = c.ExecuteReader(); while (r.Read()) { String ids = r.GetInt32("id").ToString(); String nm = r.GetString("name"); String ph = r.GetString("phone"); String ad = r.GetString("address"); String loc = r.GetString("location"); String status = r.GetString("status"); updateSupplierName.Text = nm; updateSupplierPhone.Text = ph; updateSupplierAdress.Text = ad; updateSupplierLocation.Text = loc; updateSupplierId.Text = ids; supplierStatusComboBox.Text = status; } con.Close(); } catch (Exception ex) { MessageBox.Show("Error has occured!" + ex.Message); } } //view supplier public void viewSupplier() { try { string db = databaseConnectionStringTextBox.Text; MySqlConnection con = new MySqlConnection(db); con.Open(); MySqlCommand com = new MySqlCommand("SELECT `supplier`.`name` AS 'Supplier Name',`supplier`.`phone` AS 'Supplier Phone',`supplier`.`address` AS 'Supplier Adress',`supplier`.`location` AS 'Supplier Location',`supplier`.`pfno` AS 'Registered By',`supplier`.`registered_date` AS 'Registered Date',`supplier`.`status` AS 'Status' FROM supplier ORDER BY name ASC", con); MySqlDataAdapter a = new MySqlDataAdapter(); a.SelectCommand = com; dataTable = new DataTable(); // Add autoincrement column. dataTable.Columns.Add("#", typeof(int)); dataTable.PrimaryKey = new DataColumn[] { dataTable.Columns["#"] }; dataTable.Columns["#"].AutoIncrement = true; dataTable.Columns["#"].AutoIncrementSeed = 1; dataTable.Columns["#"].ReadOnly = true; // End adding AI column. // Format titles. dataTable.Columns.Add("Supplier Name"); dataTable.Columns.Add("Supplier Phone"); dataTable.Columns.Add("Supplier Adress"); dataTable.Columns.Add("Supplier Location"); dataTable.Columns.Add("Registered By"); dataTable.Columns.Add("Registered Date", typeof(string)); dataTable.Columns.Add("Status"); // End formating titles. a.Fill(dataTable); BindingSource bs = new BindingSource(); bs.DataSource = dataTable; updateSupplierDataGridView.DataSource = bs; a.Update(dataTable); // Count number of rows to return records. Int64 count = Convert.ToInt64(updateSupplierDataGridView.Rows.Count) - 1; rowCountLabel.Text = count.ToString() + " Records"; } catch (Exception ex) { MessageBox.Show(ex.Message); } } //update supplier public void updateSupplier() { string db = databaseConnectionStringTextBox.Text; if (updateSupplierId.Text == string.Empty || updateSupplierName.Text == string.Empty || updateSupplierPhone.Text == string.Empty || updateSupplierAdress.Text == string.Empty || updateSupplierLocation.Text == string.Empty || searchSupplier.Text == string.Empty) { MessageBox.Show("Please fill all the required fields...............!", "SUPPLIER UPDATE", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } else { try { DateTime dt = DateTime.Now; string date = dt.ToString("yyyy-MM-dd"); dialog = MessageBox.Show("Are you sure you want to update the supplier?", "SUPPLIER UPDATE", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (dialog == DialogResult.Yes) { MySqlConnection con = new MySqlConnection(db); con.Open(); int did = Convert.ToInt32(updateSupplierId.Text); // int pf = Convert.ToInt32(updatepfsession.Text); MySqlCommand c = new MySqlCommand("UPDATE supplier SET pfno='" + this.updatepfsession.Text + "',name='" + this.updateSupplierName.Text + "',phone='" + this.updateSupplierPhone.Text + "',address='" + this.updateSupplierAdress.Text + "',location='" + this.updateSupplierLocation.Text + "',status='" + this.supplierStatusComboBox.Text + "' WHERE id='" + did + "'", con); c.ExecuteNonQuery(); MessageBox.Show("Supplier updated successfully...............!", "SUPPLIER UPDATE ", MessageBoxButtons.OK, MessageBoxIcon.Information); con.Close(); } } catch (Exception) { MessageBox.Show("Error has occured while updating supplier............!", "SUPPLIER UPDATE", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Error); } viewSupplier(); } } private void UpdateSupplier_Load(object sender, EventArgs e) { } private void searchSupplier_TextChanged(object sender, EventArgs e) { showSupplierData(); } private void updateSupplierButton_Click(object sender, EventArgs e) { updateSupplier(); } } }
using Npgsql; using System; using System.Collections.Generic; using System.Linq; using System.Web; using ws_seta.Models; using ws_seta.Util; namespace ws_seta.Eao { public class PedidoEao { const string sql_insert_cliente = "insert into pessoas(codigo, nome, apelido, pessoa, cep, endereco, " + "bairro, cidade, uf, telefone1, cpfcnpj, rgie, email, sexo, obs, cliente, status, contribuinte, codcidade, complemento) " + "values (newid('PESSOAS'::bpchar, 6), @nome, @apelido, @pessoa, @cep, @endereco, @bairro, @cidade, @uf, @telefone1, @cpfcnpj, '', " + "@email, @sexo, @obs, 'true', 'A','1', @codcidade, @complemento) RETURNING codigo "; const string sql_insert_movimento = " insert into movimento(codigo, auxiliar, operacao, movimento, data, empresa, produto, " +"quantidade, unitario, total, custo, base, desconto, ipi, icms, estoque, presente, conferido) " +"values (newid('MOVIMENTO'::bpchar, 8) , @auxiliar , 'VE', 'S', now(), @empresa, @produto, @quantidade, " +" @unitario, @total, @custo, @base, 0, 0, 0, 'true', 'false', 'false')"; const string sql_cliente_existe = "select codigo from pessoas where replace(replace(replace(cpfcnpj,'.',''),'-',''),'/','') = @cpf"; const string sql_insert_venda = "insert into vendas(codigo, empresa, tipo, cliente, vendedor, condicoes, impresso, " +"status, data, hora, itens, subtotal, frete, total, aprazo, obs, ecommerce, avista, ajustex, ajuste, percentual, vmanual) " +"values ( newid('VENDAS'::bpchar, 8) , @empresa, '01', @cliente, @vendedor, @condicoes, 1 , 'P', now(), " + "@hora, @itens, @subtotal, @frete, @total, @aprazo, @obs, 'true', @avista, 'D', @desconto, @percentual, @vmanual) RETURNING codigo "; const string sql_insert_financeiro = "insert into financeiro_titulos(pessoa, item, tipo, rp, valor, documento, auxiliar, descricao, previsao, " + " pendencia, scpc, cartorio, registrado, conferido, empresa, status, lancamento, conta, comprovante, parcela, vencimento, complemento, instituicao, ajustes) " + " values (@cliente, '001', '1', 'R', @valor, @codumento, @auxiliar, 'VENDA DE PRODUTOS', 'false', " + " 'false', 'false', 'false', 'false', 'false', @empresa, 'P', now(), @conta, @comprovante, @parcela, @vencimento, @complemento, @instituicao, @ajustes) "; const string sql_taxa_cartao = "SELECT replace(g_1.arr1[g_1.i], ',', '.')::numeric(18,2) as taxa, g_1.taxad, g_1.codigo, g_1.i as parcela, fo.retorno, g_1.debito, g_1.credito " + "from " + " (select generate_series(1, array_upper(g_2.arr1, 1)) as i, g_2.arr1, codigo, taxad, operadora, debito, credito from " + " (select prazod as debito, prazo as credito, operadora, codigo, taxad, string_to_array(taxasparcelas::text, '/'::text) AS arr1 " + "from financeiro_operadoras where not desativar) as g_2) as g_1 " + "inner join operadoras_cartoes as fo on fo.codigo = g_1.operadora " + " where fo.retorno = @retorno "; const string sql_insert_web_log_venda = "insert into web_log_venda(venda_seta, venda_ecommerce, xml_retorno, datahora, tipo_frete, status_pagamento, correios_rastreamento) " + " values (@venda_seta, @venda_ecommerce, @xml_retorno, now(), @tipo_frete, @status_pagamento, @correios_rastreamento) "; const string sql_buscar_pedido_id = "select v.codigo as idvenda, " + "wv.venda_ecommerce, " + "v.status, " + "to_char(v.data,'DD/MM/YYYY') as datavenda, " + "v.hora, " + "v.subtotal, " + "v.total, " + "v.ajuste as desconto, " + "v.vendedor, " + "v.obs, " + "v.empresa, " + "case when v.aprazo > 0 then 'N' else 'S' end as avista, " + "pc.codigo as idcliente, " + "pc.sexo, " + "pc.cpfcnpj, " + "pc.obs as idclienteecommerce, " + "pc.nome, " + "pc.apelido, " + "pc.email, " + "pc.telefone1, " + "pc.cep, " + "pc.endereco, " + "pc.complemento, " + "pc.cidade, " + "pc.bairro, " + "pc.uf, " + "co.codigo as idcondicao, " + "co.descricao, " + "co.vezes, " + "v.autorizador, " + "'' as bandeira, " + "m.produto, " + "m.quantidade, " + "m.unitario, " + "m.total as totalitem, " + "wv.tipo_frete, " + "v.frete, " + "wv.correios_rastreamento " + "from vendas as v " + "inner join web_log_venda as wv on wv.venda_seta = v.codigo " + "inner join pessoas as pc on pc.codigo = v.cliente " + "inner join condicoes as co on co.codigo = v.condicoes " + "inner join financeiro_titulos as ft on ft.auxiliar = 'VE' || v.codigo " + "inner join movimento as m on m.auxiliar = 'VE' || v.codigo " + " where wv.venda_ecommerce = @id "; public Pedido salvar(Pedido pedido, string token) { NpgsqlConnection conexao = Conexao.getConexaoCliente(token); conexao.Open(); string codigoCliente = inserirCliente(pedido.cliente, conexao); pedido.cliente.codigoSeta = codigoCliente; string codigoVenda = inserirVenda(pedido, conexao); pedido.codigoSeta = codigoVenda; inserirFinanceiro(pedido, conexao); inserirWebLogVenda(pedido, conexao); conexao.Close(); conexao.Dispose(); conexao = null; return pedido; } private void inserirWebLogVenda(Pedido pedido, NpgsqlConnection conexao) { NpgsqlCommand cmdInsert = new NpgsqlCommand(sql_insert_web_log_venda, conexao); criarParametro(pedido.codigoSeta, "venda_seta", ref cmdInsert); criarParametro(pedido.codigoEcommerce, "venda_ecommerce", ref cmdInsert); criarParametro(Util.UtilValidator.Serialize(pedido), "xml_retorno", ref cmdInsert); criarParametro(pedido.frete.descricao.Trim().ToUpper(), "tipo_frete", ref cmdInsert); criarParametro(pedido.status, "status_pagamento", ref cmdInsert); criarParametro(pedido.frete.codigoRastreio, "correios_rastreamento", ref cmdInsert); cmdInsert.ExecuteNonQuery(); } private void inserirFinanceiro(Pedido pedido, NpgsqlConnection conexao) { List<TaxaCartao> cartoes = obterTaxaCartao(pedido.financeiro.bandeira, conexao); bool isDebito = false; int parcela = pedido.financeiro.quantidadeVezes; if (pedido.aVista == "S") { isDebito = true; parcela = 1; } for (int x = 1; x <= parcela; x++) { double taxa = 0; double ajuste = 0; double ajusteDebito = 0; if (isDebito) { if (cartoes.Count > 0) { taxa = cartoes[0].taxaDebito; } } else { taxa = cartoes.First(t => t.parcela == x).taxaCredito; } ajuste = (pedido.total * (taxa / 100)); NpgsqlCommand cmdInsert = new NpgsqlCommand(sql_insert_financeiro, conexao); criarParametro(pedido.cliente.codigoSeta.Trim(), "cliente", ref cmdInsert); criarParametro(pedido.total, "valor", ref cmdInsert); criarParametro("", "codumento", ref cmdInsert); criarParametro("VE" + pedido.codigoSeta.Trim(), "auxiliar", ref cmdInsert); criarParametro(pedido.empresaFaturamento, "empresa", ref cmdInsert); criarParametro("001", "conta", ref cmdInsert); criarParametro(pedido.financeiro.autorizacao, "comprovante", ref cmdInsert); if (isDebito) { criarParametro("AV", "parcela", ref cmdInsert); } else { criarParametro((x + "").PadLeft(2, '0'), "parcela", ref cmdInsert); } criarParametro(DateTime.Now.AddDays(x * cartoes[0].credito), "vencimento", ref cmdInsert); criarParametro("PAR " + x.ToString().PadLeft(2, '0') + "/" + pedido.financeiro.quantidadeVezes.ToString().PadLeft(2, '0'), "complemento", ref cmdInsert); criarParametro(cartoes[0].codigo, "instituicao", ref cmdInsert); if (isDebito) { ajusteDebito = ajuste; criarParametro(0, "ajustes", ref cmdInsert); } else { criarParametro(ajuste, "ajustes", ref cmdInsert); } cmdInsert.ExecuteNonQuery(); } } public Pedido obterPedidoPorId(string token, string idPedido) { Pedido p = new Pedido(); NpgsqlConnection conexao = Conexao.getConexaoCliente(token); conexao.Open(); NpgsqlCommand cmdPedido = new NpgsqlCommand(sql_buscar_pedido_id, conexao); criarParametro(idPedido, "id", ref cmdPedido); NpgsqlDataReader reader = cmdPedido.ExecuteReader(); while (reader.Read()) { p.codigoSeta = Convert.ToString(reader["idvenda"]).Trim(); p.aVista = Convert.ToString(reader["avista"]).Trim(); p.codigoEcommerce = Convert.ToString(reader["venda_ecommerce"]).Trim(); p.data = Convert.ToString(reader["datavenda"]).Trim(); p.hora = Convert.ToString(reader["hora"]).Trim(); p.observacao = Convert.ToString(reader["obs"]).Trim(); p.subtotal = Convert.ToDouble(reader["subtotal"]); p.total = Convert.ToDouble(reader["total"]); p.desconto = Convert.ToDouble(reader["desconto"]); p.vendedor = Convert.ToString(reader["vendedor"]).Trim(); p.empresaFaturamento = Convert.ToString(reader["empresa"]).Trim(); p.status = Convert.ToString(reader["status"]).Trim(); Cliente c = new Cliente(); c.codigoSeta = Convert.ToString(reader["idcliente"]); c.apelido = UtilValidator.aNull(Convert.ToString(reader["apelido"])); c.cpf = UtilValidator.aNull(Convert.ToString(reader["cpfcnpj"])); c.codigoEcommerce = UtilValidator.aNull(Convert.ToString(reader["idclienteecommerce"])); c.email = UtilValidator.aNull(Convert.ToString(reader["email"])); c.nome = UtilValidator.aNull(Convert.ToString(reader["nome"])); c.telefone = UtilValidator.aNull(Convert.ToString(reader["telefone1"])); c.sexo = UtilValidator.aNull(Convert.ToString(reader["sexo"])); Endereco end = new Endereco(); end.bairro = UtilValidator.aNull(Convert.ToString(reader["bairro"])); end.cep = UtilValidator.aNull(Convert.ToString(reader["cep"])); end.cidade = UtilValidator.aNull(Convert.ToString(reader["cidade"])); end.uf = UtilValidator.aNull(Convert.ToString(reader["uf"]).Trim()); end.endereco = UtilValidator.aNull(Convert.ToString(reader["endereco"]).Trim()); end.complemento = UtilValidator.aNull(Convert.ToString(reader["complemento"])); end.numero = 0; if (end.endereco != null) { try { string numero = end.endereco.Substring(end.endereco.IndexOf(",") + 1).Trim(); end.numero = Convert.ToInt32(numero); } catch { } } c.endereco = end; p.cliente = c; Financeiro f = new Financeiro(); f.autorizacao = UtilValidator.aNull(Convert.ToString(reader["autorizador"])); f.bandeira = ""; f.condicaoVenda = UtilValidator.aNull(Convert.ToString(reader["idcondicao"])); f.descricaoCondicao = UtilValidator.aNull(Convert.ToString(reader["descricao"])); f.quantidadeVezes = Convert.ToInt32(reader["vezes"]); p.financeiro = f; Item it = new Item(); it.codigoVariacao = Convert.ToString(reader["produto"]); it.quantidade = Convert.ToInt32(reader["quantidade"]); it.valorTotal = Convert.ToDouble(reader["totalitem"]); it.valorUnitario = Convert.ToDouble(reader["unitario"]); p.itens.Add(it); Frete fr = new Frete(); fr.codigoRastreio = UtilValidator.aNull(Convert.ToString(reader["correios_rastreamento"])); fr.descricao = UtilValidator.aNull(Convert.ToString(reader["tipo_frete"])); fr.valor = Convert.ToDouble(reader["frete"]); p.frete = fr; } reader.Close(); conexao.Close(); conexao.Dispose(); conexao = null; return p; } public void cancelarPedido(string idPedido, string token) { NpgsqlConnection conexao = Conexao.getConexaoCliente(token); conexao.Open(); NpgsqlCommand cmdRemoveVenda = new NpgsqlCommand("Update Vendas Set Status='C' Where Codigo in ( select venda_seta from web_log_venda where venda_ecommerce = @id ) ", conexao); criarParametro(idPedido, "id", ref cmdRemoveVenda); cmdRemoveVenda.ExecuteNonQuery(); NpgsqlCommand cmdRemoveVendaItem = new NpgsqlCommand("Update Movimento Set Estoque='false', Obs='VENDA CANCELADA' Where Auxiliar in ( select 'VE'||venda_seta from web_log_venda where venda_ecommerce = @id )", conexao); criarParametro(idPedido, "id", ref cmdRemoveVendaItem); cmdRemoveVendaItem.ExecuteNonQuery(); NpgsqlCommand cmdRemoveVendaFinanceiro = new NpgsqlCommand("Update financeiro_titulos Set status='C', instrucoes='VENDA CANCELADA' Where Auxiliar in ( select 'VE'||venda_seta from web_log_venda where venda_ecommerce = @id ) ", conexao); criarParametro(idPedido, "id", ref cmdRemoveVendaFinanceiro); cmdRemoveVendaFinanceiro.ExecuteNonQuery(); conexao.Close(); conexao.Dispose(); conexao = null; } public void atualizarStatus(string status, string idPedido, string token) { NpgsqlConnection conexao = Conexao.getConexaoCliente(token); conexao.Open(); NpgsqlCommand cmdInsert = new NpgsqlCommand("update web_log_venda set status_pagamento = 'P' where venda_ecommerce = @id ", conexao); criarParametro(idPedido, "id", ref cmdInsert); cmdInsert.ExecuteNonQuery(); conexao.Close(); conexao.Dispose(); conexao = null; } private string inserirVenda(Pedido pedido, NpgsqlConnection conexao) { string codigo = ""; NpgsqlCommand cmdInsert = new NpgsqlCommand(sql_insert_venda, conexao); criarParametro(pedido.empresaFaturamento.Trim(), "empresa", ref cmdInsert); criarParametro(pedido.cliente.codigoSeta.Trim(), "cliente", ref cmdInsert); criarParametro(pedido.vendedor.Trim(), "vendedor", ref cmdInsert); criarParametro(pedido.financeiro.condicaoVenda.Trim(), "condicoes", ref cmdInsert); criarParametro(pedido.hora.Trim(), "hora", ref cmdInsert); criarParametro(pedido.itens.Count(), "itens", ref cmdInsert); criarParametro(pedido.subtotal, "subtotal", ref cmdInsert); criarParametro(pedido.frete.valor, "frete", ref cmdInsert); criarParametro(pedido.total, "total", ref cmdInsert); if (pedido.aVista == "S") { criarParametro(pedido.total, "avista", ref cmdInsert); criarParametro(0, "aprazo", ref cmdInsert); } else { criarParametro(0, "avista", ref cmdInsert); criarParametro(pedido.total, "aprazo", ref cmdInsert); } criarParametro(pedido.observacao, "obs", ref cmdInsert); criarParametro(pedido.desconto, "desconto", ref cmdInsert); criarParametro((pedido.desconto * 100) / pedido.subtotal, "percentual", ref cmdInsert); criarParametro(pedido.desconto * (-1) , "vmanual", ref cmdInsert); NpgsqlDataReader reader = cmdInsert.ExecuteReader(); if (reader.Read()) { codigo = Convert.ToString(reader["codigo"]); } reader.Close(); foreach (Item it in pedido.itens) { double custo = 0; NpgsqlCommand cmdInsertMovimento = new NpgsqlCommand(sql_insert_movimento, conexao); criarParametro("VE" + codigo, "auxiliar", ref cmdInsertMovimento); criarParametro(pedido.empresaFaturamento, "empresa", ref cmdInsertMovimento); criarParametro(it.codigoVariacao.Trim(), "produto", ref cmdInsertMovimento); criarParametro(it.quantidade, "quantidade", ref cmdInsertMovimento); criarParametro(it.valorUnitario, "unitario", ref cmdInsertMovimento); criarParametro(it.valorTotal, "total", ref cmdInsertMovimento); NpgsqlCommand cmdBuscarCusto = new NpgsqlCommand("select custo from produtos where codigo = @codigo", conexao); criarParametro(it.codigoVariacao.Trim().Substring(0, 6), "codigo", ref cmdBuscarCusto); NpgsqlDataReader readerCusto = cmdBuscarCusto.ExecuteReader(); if (readerCusto.Read()) { custo = Convert.ToDouble(readerCusto["custo"]); } readerCusto.Close(); criarParametro(custo, "custo", ref cmdInsertMovimento); criarParametro(it.valorTotal, "base", ref cmdInsertMovimento); cmdInsertMovimento.ExecuteNonQuery(); } return codigo; } private string inserirCliente(Cliente cliente, NpgsqlConnection conexao) { try { string codigo = ""; NpgsqlCommand cmd = new NpgsqlCommand(sql_cliente_existe, conexao); criarParametro(cliente.cpf.Replace(".", "").Replace("-", "").Trim(), "cpf", ref cmd); NpgsqlDataReader reader = cmd.ExecuteReader(); if (reader.Read()) { codigo = Convert.ToString(reader["codigo"]); }else { reader.Close(); NpgsqlCommand cmdInsert = new NpgsqlCommand(sql_insert_cliente, conexao); criarParametro(UtilValidator.ajustarTamanho(cliente.nome, 50).ToUpper(), "nome", ref cmdInsert); criarParametro(UtilValidator.ajustarTamanho(cliente.apelido, 30).ToUpper(), "apelido", ref cmdInsert); criarParametro(1, "pessoa", ref cmdInsert); criarParametro(UtilValidator.ajustarTamanho(cliente.endereco.cep, 10).ToUpper(), "cep", ref cmdInsert); string endereco = cliente.endereco.endereco + ", " + cliente.endereco.numero; criarParametro(UtilValidator.ajustarTamanho(endereco, 50).ToUpper(), "endereco", ref cmdInsert); criarParametro(UtilValidator.ajustarTamanho(cliente.endereco.complemento, 30).ToUpper(), "complemento", ref cmdInsert); criarParametro(UtilValidator.ajustarTamanho(cliente.endereco.bairro, 30).ToUpper(), "bairro", ref cmdInsert); criarParametro(UtilValidator.ajustarTamanho(cliente.telefone, 20).ToUpper(), "telefone1", ref cmdInsert); criarParametro(UtilValidator.ajustarTamanho(cliente.cpf, 18).ToUpper(), "cpfcnpj", ref cmdInsert); criarParametro(UtilValidator.ajustarTamanho(cliente.email, 50).ToUpper(), "email", ref cmdInsert); criarParametro(UtilValidator.ajustarTamanho(cliente.sexo, 2).ToUpper(), "sexo", ref cmdInsert); criarParametro(UtilValidator.ajustarTamanho(cliente.codigoEcommerce , 50).ToUpper(), "obs", ref cmdInsert); string[] dadosEntrega = obterDadosEntregaPorCep(cliente.endereco.cep.Trim(), conexao); criarParametro(UtilValidator.ajustarTamanho(dadosEntrega[0].Trim(), 30).ToUpper(), "cidade", ref cmdInsert); criarParametro(UtilValidator.ajustarTamanho(dadosEntrega[1].Trim(), 2).ToUpper(), "uf", ref cmdInsert); criarParametro(UtilValidator.ajustarTamanho(dadosEntrega[2].Trim(), 7).ToUpper(), "codcidade", ref cmdInsert); NpgsqlDataReader readerInsert = cmdInsert.ExecuteReader(); if (readerInsert.Read()) { codigo = Convert.ToString(readerInsert["codigo"]); } readerInsert.Close(); } reader.Close(); return codigo; } catch(Exception ex) { throw new Exception("Não foi possível inserir a venda " + ex.Message); } } private string[] obterDadosEntregaPorCep(string cep, NpgsqlConnection conexao) { string[] dados = new string[3]; NpgsqlCommand cmd = new NpgsqlCommand("select codigo, descricao, uf from cepcidades where replace(replace(cep,'.',''),'-','') = @cep", conexao); criarParametro(cep.Replace(".","").Replace("-",""), "cep", ref cmd); NpgsqlDataReader reader = cmd.ExecuteReader(); if (reader.Read()) { dados[0] = Convert.ToString(reader["descricao"]); dados[1] = Convert.ToString(reader["uf"]); dados[2] = Convert.ToString(reader["codigo"]); } reader.Close(); return dados; } private void criarParametro(object valor, string parametro, ref NpgsqlCommand cmd) { NpgsqlParameter parametroCmd = cmd.CreateParameter(); parametroCmd.ParameterName = parametro; parametroCmd.Value = valor; cmd.Parameters.Add(parametroCmd); } private List<TaxaCartao> obterTaxaCartao(string rede, NpgsqlConnection conexao) { NpgsqlCommand cmdTaxa = new NpgsqlCommand(sql_taxa_cartao, conexao); criarParametro(rede, "retorno", ref cmdTaxa); List<TaxaCartao> taxaCartoes = new List<TaxaCartao>(); NpgsqlDataReader reader = cmdTaxa.ExecuteReader(); try { while (reader.Read()) { TaxaCartao t = new TaxaCartao(); t.codigo = Convert.ToString(reader["codigo"]).Trim(); t.parcela = Convert.ToInt32(reader["parcela"]); t.taxaCredito = Convert.ToDouble(reader["taxa"]); t.taxaDebito = Convert.ToDouble(reader["taxad"]); t.credito = Convert.ToDouble(reader["credito"]); t.debito = Convert.ToDouble(reader["debito"]); taxaCartoes.Add(t); } reader.Close(); return taxaCartoes; } catch (Exception) { return taxaCartoes; } } public List<CondicaoPagamento> obterCondicoes(string token) { List<CondicaoPagamento> condicoes = new List<CondicaoPagamento>(); NpgsqlConnection conexao = Conexao.getConexaoCliente(token); conexao.Open(); NpgsqlCommand cmd = new NpgsqlCommand("select codigo, descricao, vezes from condicoes", conexao); NpgsqlDataReader reader = cmd.ExecuteReader(); try { while (reader.Read()) { CondicaoPagamento c = new CondicaoPagamento(); c.codigo = Convert.ToString(reader["codigo"]).Trim(); c.descricao = Convert.ToString(reader["descricao"]).Trim(); c.parcelas = Convert.ToInt32(reader["vezes"]); condicoes.Add(c); } } catch { } finally { reader.Close(); conexao.Close(); } return condicoes; } } }
using BPiaoBao.Common.Enums; using BPiaoBao.DomesticTicket.Platform.Plugin; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace BPiaoBao.DomesticTicket.Domain.Models.Orders.Behaviors { /// <summary> /// 接口平台取消出票 通知 /// </summary> [Behavior("PlatformCancelTicketNotify")] public class PlatformCancelTicketNotifyBehavior : BaseOrderBehavior { public override object Execute() { string remark = getParame("remark").ToString(); string operatorName = getParame("operatorName").ToString(); order.ChangeStatus(EnumOrderStatus.WaitReimburseWithPlatformRepelIssue); order.WriteLog(new OrderLog() { OperationContent = "平台取消出票,订单号" + order.OrderId + ",备注:" + remark, OperationDatetime = System.DateTime.Now, OperationPerson = string.IsNullOrEmpty(operatorName) ? "系统" : operatorName , IsShowLog = false }); return null; } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="AuditInfo.cs" company="CGI"> // Copyright (c) CGI. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace CGI.Reflex.Core.Entities { public class AuditInfo : BaseEntity { private ICollection<AuditInfoProperty> _properties; public AuditInfo() { _properties = new List<AuditInfoProperty>(); } [Required] [StringLength(255)] [Display(ResourceType = typeof(CoreResources), Name = "EntityType")] public virtual string EntityType { get; set; } [Required] [Display(ResourceType = typeof(CoreResources), Name = "EntityId")] public virtual int EntityId { get; set; } public virtual int? ConcurrencyVersion { get; set; } [Required] [Display(ResourceType = typeof(CoreResources), Name = "Timestamp")] public virtual DateTime Timestamp { get; set; } [Required] [Display(ResourceType = typeof(CoreResources), Name = "Action")] public virtual AuditInfoAction Action { get; set; } [Display(ResourceType = typeof(CoreResources), Name = "User")] public virtual User User { get; set; } [Display(ResourceType = typeof(CoreResources), Name = "DisplayName")] public virtual string DisplayName { get; set; } [Display(ResourceType = typeof(CoreResources), Name = "Properties")] public virtual IEnumerable<AuditInfoProperty> Properties { get { return _properties; } } public virtual void Add(AuditInfoProperty property) { _properties.Add(property); } public override string ToString() { return string.Format("{0} {1} {2}", Action, EntityType, EntityId); } } }
using JoveZhao.Framework.DDD; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace BPiaoBao.DomesticTicket.Domain.Models.Orders { /// <summary> /// 订单日志 /// </summary> public class OrderLog : EntityBase { /// <summary> /// 编号 /// </summary> public int Id { get; set; } /// <summary> /// 订单操作日期 /// </summary> public DateTime OperationDatetime { get; set; } /// <summary> /// 操作内容 /// </summary> public string OperationContent { get; set; } /// <summary> /// 操作人 /// </summary> public string OperationPerson { get; set; } /// <summary> /// 备注 /// </summary> public string Remark { get; set; } /// <summary> /// 是否可见日志 /// </summary> public bool IsShowLog { get; set; } protected override string GetIdentity() { return Id.ToString(); } } }
using System.IO; using System.Runtime.Serialization.Json; namespace Semon.Yahtzee.Rules.Partials { public static class PartialRuleExtensions { public static string Serialize(this IPartialRule rule) { var serializer = new DataContractJsonSerializer(rule.GetType()); var stream = new MemoryStream(); serializer.WriteObject(stream, rule); stream.Position = 0; var reader = new StreamReader(stream); return reader.ReadToEnd(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace WebMarket.Models.Response { public class Response { public int Code { get; set; } public string Message { get; set; } public Response() { Code = 0; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.Entity; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace FittSoft { public partial class FormWorkoutSession : Form { UserControlPreWorkout ucPreWorkout; UserControlExercise ucExercise; List<WorkoutPlanItem> currentPlanList; DWEntities context = new DWEntities(); bool isCompleted = false; int curExNumber = 0; WorkoutSession currentSession; public FormWorkoutSession() { InitializeComponent(); // Edzés tervezési nézet megjelenítése ucPreWorkout = new UserControlPreWorkout(); panel_main.Controls.Clear(); panel_main.Controls.Add(ucPreWorkout); btn_delete.Visible = false; btn_save.Visible = false; btn_next.Visible = false; } private void btn_startWorkout_Click(object sender, EventArgs e) { // Új edzés session létrehozása currentSession = new WorkoutSession(); currentSession.startTime = DateTime.Now; currentPlanList = new List<WorkoutPlanItem>(); // Edzéstervben lévő gyakorlatok listába töltése foreach (DataGridViewRow curRow in ucPreWorkout.dgw_workoutPlan.Rows) { WorkoutPlanItem curItem = new WorkoutPlanItem(); curItem.Megnevezés = curRow.Cells[0].Value.ToString(); curItem.Ismétlés = int.Parse(curRow.Cells[1].Value.ToString()); curItem.Időtartam = decimal.Parse(curRow.Cells[2].Value.ToString()); curItem.Súly = decimal.Parse(curRow.Cells[3].Value.ToString()); curItem.Leírás = curRow.Cells[4].Value.ToString(); currentPlanList.Add(curItem); } // Pre Workout nézet elrejtése, új nézet megjelenítése ucExercise = new UserControlExercise(); panel_main.Controls.Clear(); panel_main.Controls.Add(ucExercise); btn_next.Visible = true; btn_startWorkout.Visible = false; // Első gyakorlat betöltése TryNextExercise(); } private void TryNextExercise() { // Ellenőrzés, nehogy tovább menjünk mint ahány gyakorlatunk van if (curExNumber >= currentPlanList.Count) isCompleted = true; if(!isCompleted) { // Aktuális gyakorlat adatainak tárolása string name = currentPlanList[curExNumber].Megnevezés; string desc = currentPlanList[curExNumber].Leírás; int reps = currentPlanList[curExNumber].Ismétlés; decimal duration = currentPlanList[curExNumber].Időtartam; decimal weight = currentPlanList[curExNumber].Súly; // UI frissítés RefreshExercisePanel(name, desc, reps, duration, weight); // Következő gyakorlat curExNumber++; } else { // Ha végeztünk az edzéssel string name = "KÉSZ"; string desc = "KÉSZ"; int reps = 0; decimal duration = 0; decimal weight = 0; RefreshExercisePanel(name, desc, reps, duration, weight); btn_save.Visible = true; btn_delete.Visible = true; btn_next.Visible = false; // Osztály hiányzó tulajdonságainak beállítása currentSession.endTime = DateTime.Now; currentSession.duration = Decimal.Parse((currentSession.endTime - currentSession.startTime).TotalMinutes.ToString()); } } private void RefreshExercisePanel(string name, string desc, int reps, decimal duration, decimal weight) { // Aktuális gyakorlat adatainak megjelenítése ucExercise.label_var_exerciseName.Text = name; ucExercise.label_var_desc.Text = desc; ucExercise.label_var_reps.Text = reps.ToString(); ucExercise.label_var_duration.Text = duration.ToString(); ucExercise.label_var_weight.Text = weight.ToString(); } private void btn_next_Click(object sender, EventArgs e) { TryNextExercise(); } private void btn_save_Click(object sender, EventArgs e) { // Mentés az adatbázisba context.F_EDZES.Load(); context.F_EDZES_GYAKORLAT.Load(); fEDZESBindingSource.DataSource = context.F_EDZES.Local; fEDZES_GYAKORLATBindingSource.DataSource = context.F_EDZES_GYAKORLAT.Local; // Edzés hozzáadása F_EDZES newWorkout = new F_EDZES(); newWorkout.KEZD_IDOPONT = currentSession.startTime; newWorkout.BEF_IDOPONT = currentSession.endTime; newWorkout.IDOTARTAM = currentSession.duration; fEDZESBindingSource.Add(newWorkout); context.SaveChanges(); // Gyakorlatok hozzáadása a létrehozott edzéshez var prevAddedWorkout = (from x in context.F_EDZES where x.KEZD_IDOPONT == newWorkout.KEZD_IDOPONT select x).First(); int prevAddedSK = prevAddedWorkout.EDZES_SK; foreach (WorkoutPlanItem curItem in currentPlanList) { var curEx = (from x in context.D_GYAKORLAT where x.MEGNEVEZES == curItem.Megnevezés select x).First(); int exerciseSK = curEx.GYAKORLAT_SK; F_EDZES_GYAKORLAT newExercise = new F_EDZES_GYAKORLAT(); newExercise.EDZES_ID = prevAddedSK; newExercise.GYAKORLAT_ID = exerciseSK; newExercise.ISMETLES = curItem.Ismétlés; newExercise.IDOTARTAM = curItem.Időtartam; newExercise.SULY = curItem.Súly; fEDZES_GYAKORLATBindingSource.Add(newExercise); context.SaveChanges(); this.Close(); } } private void btn_delete_Click(object sender, EventArgs e) { // Form bezárása mentés nélkül this.Close(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using PayRoll.BLL; using NUnit.Framework; namespace PayRoll.UnitTest.BLL { [TestFixture] public class ChangeNameTransactionTest:SetUpInmemoryDb { [Test] public void ExecuteTest() { //目的:检查改名字 int empId = 18; string newName = "Busu"; //添加雇员 AddHourlyEmployee addHourlyEmp = new AddHourlyEmployee(empId, "Mana", "duva", 12.3, database); addHourlyEmp.Execute(); //改名字 ChangeEmployeeTransaction changeNameTrans = new ChangeNameTransaction(empId, newName, database); changeNameTrans.Execute(); //获取雇员 Employee emp = database.GetEmployee(empId); Assert.IsNotNull(emp); //检查名字 Assert.AreEqual(emp.Name, newName); } } }
using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; using System.IO; using System.Web; using System.Web.Hosting; namespace Ws2008.WEB.tools { /// <summary> /// upload 的摘要说明 /// </summary> public class upload : IHttpHandler { public void ProcessRequest(HttpContext context) { HttpPostedFile upfile = context.Request.Files["Filedata"]; string filename = upfile.FileName; string staticFolder = "upload"; string fileFolder = DateTime.Now.ToString("yyyy/MM/dd/"); //string path = string.Concat(staticFolder,"/",fileFolder); string path = context.Server.MapPath(string.Concat("~/",staticFolder, "/", fileFolder)); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } string fileType = upfile.ContentType.Substring(0, 5); if (fileType == "image") { string imgExtension = Path.GetExtension(path + filename).ToLower(); } upfile.SaveAs(path + filename); context.Response.Write("上传成功"); } public bool IsReusable { get { return false; } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class EnemyAttack : MonoBehaviour { public float startTimeBtwAttack; public float attackRange; public LayerMask whatIsPlayer; private float timeBtwAttack; private GameObject player; private EnemyBehavior enemy; private Rigidbody2D body; private PlayerController pc; private Animator anim; //private Collider2D attackTrigger; private void Start() { enemy = GetComponentInParent<EnemyBehavior>(); player = GameObject.FindGameObjectWithTag("Player"); pc = player.GetComponent<PlayerController>(); body = GetComponentInParent<Rigidbody2D>(); anim = GetComponentInParent<Animator>(); } private void Update() { if (enemy.attackReady) { if (timeBtwAttack <= 0) { Collider2D[] playerToDamage = Physics2D.OverlapCircleAll(player.transform.position, attackRange, whatIsPlayer); for (int i = 0; i < playerToDamage.Length; i++) { playerToDamage[i].GetComponent<PlayerResources>().TakeDamage(this.gameObject); } enemy.attackReady = false; FindObjectOfType<AudioManager>().LasherAttackSound(); timeBtwAttack = startTimeBtwAttack; } else { timeBtwAttack -= Time.deltaTime; } } } private void OnCollisionEnter2D(Collision2D collision) { if (collision.gameObject.CompareTag("Player")) { Vector2 dir = collision.GetContact(0).point; dir = -dir.normalized; pc.TakeDamage(this.gameObject); player.GetComponent<Rigidbody2D>().AddForce(dir * 600); } } }
namespace Students { using System; using System.Text; class Student { public Student(string fName, string lName, int age) { this.FirstName = fName; this.LastName = lName; this.Age = age; } public int Age { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public override string ToString() { var sb = new StringBuilder(); sb.Append(string.Format("Name: {0,-18} | ", this.FirstName + " " + this.LastName)); sb.Append(string.Format("Age: {0,-3} | ", this.Age)); return sb.ToString(); } } }
using FluentAssertions; using NUnit.Framework; namespace Example.Tests { public class BuildingMetricsValidatorTests { protected IBuildingMetricsValidator SystemUnderTest { get; set; } [SetUp] public void Setup() { SystemUnderTest = new BuildingMetricsValidator(); } [Test] public void ItShouldValidateRequest() { var request = new JsonOptions(); var result = SystemUnderTest.Validate(request); result.Should().BeTrue(); } } }
using LuaInterface; using SLua; using System; using UnityEngine; public class Lua_UIDragDropContainer : LuaObject { [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_reparentTarget(IntPtr l) { int result; try { UIDragDropContainer uIDragDropContainer = (UIDragDropContainer)LuaObject.checkSelf(l); LuaObject.pushValue(l, true); LuaObject.pushValue(l, uIDragDropContainer.reparentTarget); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_reparentTarget(IntPtr l) { int result; try { UIDragDropContainer uIDragDropContainer = (UIDragDropContainer)LuaObject.checkSelf(l); Transform reparentTarget; LuaObject.checkType<Transform>(l, 2, out reparentTarget); uIDragDropContainer.reparentTarget = reparentTarget; LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } public static void reg(IntPtr l) { LuaObject.getTypeTable(l, "UIDragDropContainer"); LuaObject.addMember(l, "reparentTarget", new LuaCSFunction(Lua_UIDragDropContainer.get_reparentTarget), new LuaCSFunction(Lua_UIDragDropContainer.set_reparentTarget), true); LuaObject.createTypeMetatable(l, null, typeof(UIDragDropContainer), typeof(MonoBehaviour)); } }
using System.Collections; using UnityEngine; using UnityEngine.UI; public class Attack_NumbersPop : MonoBehaviour { //=======================| Variables |==================================== const float duration = 1.0f; const float maxX = 20.0f; const float maxY = 60.0f; [SerializeField] Transform parent; [SerializeField] GameObject popNumbersObj; public static Attack_NumbersPop Instance; //=======================| Awake() |=============================== private void Awake() { Instance = this; } //=======================| IEnumerator - PopNumbers() |=============================== public IEnumerator PopNumbers (float amount, bool critB) { RectTransform numObj = Instantiate(popNumbersObj, parent).GetComponent<RectTransform>(); string crit = critB ? " - VIBE CRITICAL" : ""; numObj.gameObject.GetComponent<Text>().text = string.Format("{0} Damage{1}", Mathf.RoundToInt(amount), crit); numObj.localPosition = Vector3.zero; Vector3 translation = new Vector3(Random.Range(-maxX, maxX), Random.Range(maxY / 2, maxY), 0); float t = 0; while (t < 1) { float increment = Time.deltaTime / duration; t += increment; numObj.localPosition += translation * increment; yield return null; } Destroy(numObj.gameObject); } }
using System; using Alpaca.Markets; using Microsoft.Extensions.DependencyInjection; using LunarTrader.Attributes; using LunarTrader.Interfaces; namespace LunarTrader.Services { public class AccountService : IAccountService { public AccountService(ILoggerService logger, IAlpacaTradingClient tradingClient) { Logger = logger; TradingClient = tradingClient; Logger.LogInfo("Fetching Account Data"); Account = TradingClient.GetAccountAsync().Result; if (Account != null) Logger.LogInfo("Account Data Fetched"); else throw new Exception("Could not fetch account data"); } public IAlpacaTradingClient TradingClient { get; } public IAccount Account { get; } public ILoggerService Logger { get; } [Command("getAccountDetails", "Gets various details about the trading account")] private static void getAccountDetails() { var account = Core.ServiceProvider.GetService<IAlpacaTradingClient>().GetAccountAsync().Result; var result = $"\n" + $"Account Details: \n" + $"Account Number: {account.AccountNumber} \n" + $"Buying Power: {account.BuyingPower} \n" + $"Day Trade Buying Power: {account.DayTradingBuyingPower}\n" + $"Day Trade Count: {account.DayTradeCount}\n" + $"Is Day Trader: {account.IsDayPatternTrader} \n" + $"Equity: {account.Equity} \n"; Core.Logger.LogInfo(result); } } }
using System; using System.Collections.Generic; using System.Linq; using QUnit; using System.Text.RegularExpressions; namespace Linq.TestScript { [TestFixture] public class ConvertTests { [Test] public void ToArrayWorksFromLinqJSEnumerable() { Assert.AreEqual(new[] { 1, 2, 3 }.Select(i => i * i).ToArray(), new[] { 1, 4, 9 }); } [Test] public void ToArrayWorksFromSatarelleEnumerable() { var enumerable = new TestEnumerable(1, 3); Assert.AreEqual(enumerable.ToArray(), new[] { 1, 2, 3 }, "Result should be correct"); Assert.IsTrue(enumerable.EnumeratorDisposed, "Enumerator should be disposed"); } [Test] public void ToListWorksFromLinqJSEnumerable() { Assert.AreEqual(new[] { 1, 2, 3 }.Select(i => i * i).ToList(), new[] { 1, 4, 9 }); } [Test] public void ToListWorksFromSatarelleEnumerable() { var enumerable = new TestEnumerable(1, 3); Assert.AreEqual(enumerable.ToList(), new[] { 1, 2, 3 }, "Result should be correct"); Assert.IsTrue(enumerable.EnumeratorDisposed, "Enumerator should be disposed"); } [Test] public void CanForeachOverLinqJSEnumerable() { var enumerable = new TestEnumerable(1, 3); var result = new List<int>(); foreach (var i in enumerable.Select(i => i * i)) { result.Add(i); } Assert.AreEqual(result, new[] { 1, 4, 9 }, "Result should be correct"); Assert.IsTrue(enumerable.EnumeratorDisposed, "Enumerator should be disposed"); } [Test] public void ToLookupWithOnlyKeySelectorWorksForArray() { var lu = new[] { "temp.xls", "temp.pdf", "temp.jpg", "temp2.pdf" }.ToLookup(s => s.Match(new Regex("\\.(.+$)"))[1]); Assert.AreEqual(lu.Count, 3); Assert.AreEqual(lu["xls"].ToArray(), new[] { "temp.xls" }); Assert.AreEqual(lu["pdf"].ToArray(), new[] { "temp.pdf", "temp2.pdf" }); Assert.AreEqual(lu["jpg"].ToArray(), new[] { "temp.jpg" }); var lu2 = new[] { new { s = "1", i = 100 }, new { s = "3", i = 101 }, new { s = "1", i = 102 }, new { s = "2", i = 103 }, new { s = "3", i = 104 } }.ToLookup(x => new C(x.s)); Assert.AreEqual(lu2.Select(x => x.Key.S).ToArray(), new[] { "1", "3", "2" }); Assert.AreEqual(lu2[new C("1")].Select(x => x.i).ToArray(), new[] { 100, 102 }); Assert.AreEqual(lu2[new C("2")].Select(x => x.i).ToArray(), new[] { 103 }); Assert.AreEqual(lu2[new C("3")].Select(x => x.i).ToArray(), new[] { 101, 104 }); } [Test] public void ToLookupWithOnlyKeySelectorWorksForSaltarelleEnumerable() { var lu = new[] { "temp.xls", "temp.pdf", "temp.jpg", "temp2.pdf" }.Wrap().ToLookup(s => s.Match(new Regex("\\.(.+$)"))[1]); Assert.AreEqual(lu.Count, 3); Assert.AreEqual(lu["xls"].ToArray(), new[] { "temp.xls" }); Assert.AreEqual(lu["pdf"].ToArray(), new[] { "temp.pdf", "temp2.pdf" }); Assert.AreEqual(lu["jpg"].ToArray(), new[] { "temp.jpg" }); var lu2 = new[] { new { s = "1", i = 100 }, new { s = "3", i = 101 }, new { s = "1", i = 102 }, new { s = "2", i = 103 }, new { s = "3", i = 104 } }.Wrap().ToLookup(x => new C(x.s)); Assert.AreEqual(lu2.Select(x => x.Key.S).ToArray(), new[] { "1", "3", "2" }); Assert.AreEqual(lu2[new C("1")].Select(x => x.i).ToArray(), new[] { 100, 102 }); Assert.AreEqual(lu2[new C("2")].Select(x => x.i).ToArray(), new[] { 103 }); Assert.AreEqual(lu2[new C("3")].Select(x => x.i).ToArray(), new[] { 101, 104 }); } [Test] public void ToLookupWithOnlyKeySelectorWorksForLinqJSEnumerable() { var lu = Enumerable.From(new[] { "temp.xls", "temp.pdf", "temp.jpg", "temp2.pdf" }).ToLookup(s => s.Match(new Regex("\\.(.+$)"))[1]); Assert.AreEqual(lu.Count, 3); Assert.AreEqual(lu["xls"].ToArray(), new[] { "temp.xls" }); Assert.AreEqual(lu["pdf"].ToArray(), new[] { "temp.pdf", "temp2.pdf" }); Assert.AreEqual(lu["jpg"].ToArray(), new[] { "temp.jpg" }); var lu2 = Enumerable.From(new[] { new { s = "1", i = 100 }, new { s = "3", i = 101 }, new { s = "1", i = 102 }, new { s = "2", i = 103 }, new { s = "3", i = 104 } }).ToLookup(x => new C(x.s)); Assert.AreEqual(lu2.Select(x => x.Key.S).ToArray(), new[] { "1", "3", "2" }); Assert.AreEqual(lu2[new C("1")].Select(x => x.i).ToArray(), new[] { 100, 102 }); Assert.AreEqual(lu2[new C("2")].Select(x => x.i).ToArray(), new[] { 103 }); Assert.AreEqual(lu2[new C("3")].Select(x => x.i).ToArray(), new[] { 101, 104 }); } [Test] public void ToLookupWithKeySelectorAndComparerWorksForArray() { var lu2 = new[] { new { s = "11", i = 100 }, new { s = "31", i = 101 }, new { s = "12", i = 102 }, new { s = "22", i = 103 }, new { s = "32", i = 104 } }.ToLookup(x => new C(x.s), new FirstLetterComparer()); Assert.AreEqual(lu2.Select(x => x.Key.S).ToArray(), new[] { "11", "31", "22" }); Assert.AreEqual(lu2[new C("1")].Select(x => x.i).ToArray(), new[] { 100, 102 }); Assert.AreEqual(lu2[new C("2")].Select(x => x.i).ToArray(), new[] { 103 }); Assert.AreEqual(lu2[new C("3")].Select(x => x.i).ToArray(), new[] { 101, 104 }); } [Test] public void ToLookupWithKeySelectorAndComparerWorksForSaltarelleEnumerable() { var lu2 = new[] { new { s = "11", i = 100 }, new { s = "31", i = 101 }, new { s = "12", i = 102 }, new { s = "22", i = 103 }, new { s = "32", i = 104 } }.Wrap().ToLookup(x => new C(x.s), new FirstLetterComparer()); Assert.AreEqual(lu2.Select(x => x.Key.S).ToArray(), new[] { "11", "31", "22" }); Assert.AreEqual(lu2[new C("1")].Select(x => x.i).ToArray(), new[] { 100, 102 }); Assert.AreEqual(lu2[new C("2")].Select(x => x.i).ToArray(), new[] { 103 }); Assert.AreEqual(lu2[new C("3")].Select(x => x.i).ToArray(), new[] { 101, 104 }); } [Test] public void ToLookupWithKeySelectorAndComparerWorksForLinqJSEnumerable() { var lu2 = Enumerable.From(new[] { new { s = "11", i = 100 }, new { s = "31", i = 101 }, new { s = "12", i = 102 }, new { s = "22", i = 103 }, new { s = "32", i = 104 } }).ToLookup(x => new C(x.s), new FirstLetterComparer()); Assert.AreEqual(lu2.Select(x => x.Key.S).ToArray(), new[] { "11", "31", "22" }); Assert.AreEqual(lu2[new C("1")].Select(x => x.i).ToArray(), new[] { 100, 102 }); Assert.AreEqual(lu2[new C("2")].Select(x => x.i).ToArray(), new[] { 103 }); Assert.AreEqual(lu2[new C("3")].Select(x => x.i).ToArray(), new[] { 101, 104 }); } [Test] public void ToLookupWithKeyAndValueSelectorsWorksForArray() { var lu = new[] { "temp1.xls", "temp2.pdf", "temp3.jpg", "temp4.pdf" }.ToLookup(s => s.Match(new Regex("\\.(.+$)"))[1], s => s.Match(new Regex("^(.+)\\."))[1]); Assert.AreEqual(lu.Count, 3); Assert.AreEqual(lu["xls"].ToArray(), new[] { "temp1" }); Assert.AreEqual(lu["pdf"].ToArray(), new[] { "temp2", "temp4" }); Assert.AreEqual(lu["jpg"].ToArray(), new[] { "temp3" }); var lu2 = new[] { new { s = "1", i = 100 }, new { s = "3", i = 101 }, new { s = "1", i = 102 }, new { s = "2", i = 103 }, new { s = "3", i = 104 } }.ToLookup(x => new C(x.s), x => x.i); Assert.AreEqual(lu2.Select(x => x.Key.S).ToArray(), new[] { "1", "3", "2" }); Assert.AreEqual(lu2[new C("1")].ToArray(), new[] { 100, 102 }); Assert.AreEqual(lu2[new C("2")].ToArray(), new[] { 103 }); Assert.AreEqual(lu2[new C("3")].ToArray(), new[] { 101, 104 }); } [Test] public void ToLookupWithKeyAndValueSelectorsWorksForSaltarelleEnumerable() { var lu = new[] { "temp1.xls", "temp2.pdf", "temp3.jpg", "temp4.pdf" }.Wrap().ToLookup(s => s.Match(new Regex("\\.(.+$)"))[1], s => s.Match(new Regex("^(.+)\\."))[1]); Assert.AreEqual(lu.Count, 3); Assert.AreEqual(lu["xls"].ToArray(), new[] { "temp1" }); Assert.AreEqual(lu["pdf"].ToArray(), new[] { "temp2", "temp4" }); Assert.AreEqual(lu["jpg"].ToArray(), new[] { "temp3" }); var lu2 = new[] { new { s = "1", i = 100 }, new { s = "3", i = 101 }, new { s = "1", i = 102 }, new { s = "2", i = 103 }, new { s = "3", i = 104 } }.Wrap().ToLookup(x => new C(x.s), x => x.i); Assert.AreEqual(lu2.Select(x => x.Key.S).ToArray(), new[] { "1", "3", "2" }); Assert.AreEqual(lu2[new C("1")].ToArray(), new[] { 100, 102 }); Assert.AreEqual(lu2[new C("2")].ToArray(), new[] { 103 }); Assert.AreEqual(lu2[new C("3")].ToArray(), new[] { 101, 104 }); } [Test] public void ToLookupWithKeyAndValueSelectorsWorksForLinqJSEnumerable() { var lu = Enumerable.From(new[] { "temp1.xls", "temp2.pdf", "temp3.jpg", "temp4.pdf" }).ToLookup(s => s.Match(new Regex("\\.(.+$)"))[1], s => s.Match(new Regex("^(.+)\\."))[1]); Assert.AreEqual(lu.Count, 3); Assert.AreEqual(lu["xls"].ToArray(), new[] { "temp1" }); Assert.AreEqual(lu["pdf"].ToArray(), new[] { "temp2", "temp4" }); Assert.AreEqual(lu["jpg"].ToArray(), new[] { "temp3" }); var lu2 = Enumerable.From(new[] { new { s = "1", i = 100 }, new { s = "3", i = 101 }, new { s = "1", i = 102 }, new { s = "2", i = 103 }, new { s = "3", i = 104 } }).ToLookup(x => new C(x.s), x => x.i); Assert.AreEqual(lu2.Select(x => x.Key.S).ToArray(), new[] { "1", "3", "2" }); Assert.AreEqual(lu2[new C("1")].ToArray(), new[] { 100, 102 }); Assert.AreEqual(lu2[new C("2")].ToArray(), new[] { 103 }); Assert.AreEqual(lu2[new C("3")].ToArray(), new[] { 101, 104 }); } [Test] public void ToLookupWithKeyAndValueSelectorsAndComparerWorksForArray() { var lu = new[] { new { s = "11", i = 100 }, new { s = "31", i = 101 }, new { s = "12", i = 102 }, new { s = "22", i = 103 }, new { s = "32", i = 104 } }.ToLookup(x => new C(x.s), x => x.i, new FirstLetterComparer()); Assert.AreEqual(lu.Select(x => x.Key.S).ToArray(), new[] { "11", "31", "22" }); Assert.AreEqual(lu[new C("11")].ToArray(), new[] { 100, 102 }); Assert.AreEqual(lu[new C("22")].ToArray(), new[] { 103 }); Assert.AreEqual(lu[new C("31")].ToArray(), new[] { 101, 104 }); } [Test] public void ToLookupWithKeyAndValueSelectorsAndComparerWorksForSaltarelleEnumerable() { var lu = new[] { new { s = "11", i = 100 }, new { s = "31", i = 101 }, new { s = "12", i = 102 }, new { s = "22", i = 103 }, new { s = "32", i = 104 } }.Wrap().ToLookup(x => new C(x.s), x => x.i, new FirstLetterComparer()); Assert.AreEqual(lu.Select(x => x.Key.S).ToArray(), new[] { "11", "31", "22" }); Assert.AreEqual(lu[new C("12")].ToArray(), new[] { 100, 102 }); Assert.AreEqual(lu[new C("22")].ToArray(), new[] { 103 }); Assert.AreEqual(lu[new C("31")].ToArray(), new[] { 101, 104 }); } [Test] public void ToLookupWithKeyAndValueSelectorsAndComparerWorksForLinqJSEnumerable() { var lu = Enumerable.From(new[] { new { s = "11", i = 100 }, new { s = "31", i = 101 }, new { s = "12", i = 102 }, new { s = "22", i = 103 }, new { s = "32", i = 104 } }).ToLookup(x => new C(x.s), x => x.i, new FirstLetterComparer()); Assert.AreEqual(lu.Select(x => x.Key.S).ToArray(), new[] { "11", "31", "22" }); Assert.AreEqual(lu[new C("11")].ToArray(), new[] { 100, 102 }); Assert.AreEqual(lu[new C("22")].ToArray(), new[] { 103 }); Assert.AreEqual(lu[new C("31")].ToArray(), new[] { 101, 104 }); } [Test] public void ToObjectWorksForArray() { Assert.AreEqual(Enumerable.Range(1, 5).Select((value, index) => new {id = "id_" + index, value}).ToArray().ToObject(item => item.id, item => item.value), new { id_0 = 1, id_1 = 2, id_2 = 3, id_3 = 4, id_4 = 5 }); } [Test] public void ToObjectWorksForLinqJSEnumerable() { Assert.AreEqual(Enumerable.Range(1, 5).Select((value, index) => new {id = "id_" + index, value}).ToObject(item => item.id, item => item.value), new { id_0 = 1, id_1 = 2, id_2 = 3, id_3 = 4, id_4 = 5 }); } [Test] public void ToDictionaryWithOnlyKeySelectorWorksForArray() { var d = Enumerable.Range(1, 5).Select((value, index) => new { id = "id_" + index, value }).ToArray().ToDictionary(item => item.id); Assert.AreEqual(d.Count, 5); Assert.AreEqual(d["id_0"], new { id = "id_0", value = 1 }); Assert.AreEqual(d["id_1"], new { id = "id_1", value = 2 }); Assert.AreEqual(d["id_2"], new { id = "id_2", value = 3 }); Assert.AreEqual(d["id_3"], new { id = "id_3", value = 4 }); Assert.AreEqual(d["id_4"], new { id = "id_4", value = 5 }); var d2 = Enumerable.Range(1, 5).Select((value, index) => new { id = new C(index.ToString()), value }).ToArray().ToDictionary(item => item.id); Assert.AreEqual(d2.Count, 5); Assert.AreEqual(d2[new C("0")].value, 1); Assert.AreEqual(d2[new C("1")].value, 2); Assert.AreEqual(d2[new C("2")].value, 3); Assert.AreEqual(d2[new C("3")].value, 4); Assert.AreEqual(d2[new C("4")].value, 5); } [Test] public void ToDictionaryWithOnlyKeySelectorWorksForSaltarelleEnumerable() { var d = Enumerable.Range(1, 5).Select((value, index) => new { id = "id_" + index, value }).Wrap().ToDictionary(item => item.id); Assert.AreEqual(d.Count, 5); Assert.AreEqual(d["id_0"], new { id = "id_0", value = 1 }); Assert.AreEqual(d["id_1"], new { id = "id_1", value = 2 }); Assert.AreEqual(d["id_2"], new { id = "id_2", value = 3 }); Assert.AreEqual(d["id_3"], new { id = "id_3", value = 4 }); Assert.AreEqual(d["id_4"], new { id = "id_4", value = 5 }); var d2 = Enumerable.Range(1, 5).Select((value, index) => new { id = new C(index.ToString()), index, value }).Wrap().ToDictionary(item => item.id); Assert.AreEqual(d2.Count, 5); Assert.AreEqual(d2[new C("0")].value, 1); Assert.AreEqual(d2[new C("1")].value, 2); Assert.AreEqual(d2[new C("2")].value, 3); Assert.AreEqual(d2[new C("3")].value, 4); Assert.AreEqual(d2[new C("4")].value, 5); } [Test] public void ToDictionaryWithOnlyKeySelectorWorksForLinqJSEnumerable() { var d = Enumerable.Range(1, 5).Select((value, index) => new { id = "id_" + index, value }).ToDictionary(item => item.id); Assert.AreEqual(d.Count, 5); Assert.AreEqual(d["id_0"], new { id = "id_0", value = 1 }); Assert.AreEqual(d["id_1"], new { id = "id_1", value = 2 }); Assert.AreEqual(d["id_2"], new { id = "id_2", value = 3 }); Assert.AreEqual(d["id_3"], new { id = "id_3", value = 4 }); Assert.AreEqual(d["id_4"], new { id = "id_4", value = 5 }); var d2 = Enumerable.Range(1, 5).Select((value, index) => new { id = new C(index.ToString()), index, value }).ToDictionary(item => item.id); Assert.AreEqual(d2.Count, 5); Assert.AreEqual(d2[new C("0")].value, 1); Assert.AreEqual(d2[new C("1")].value, 2); Assert.AreEqual(d2[new C("2")].value, 3); Assert.AreEqual(d2[new C("3")].value, 4); Assert.AreEqual(d2[new C("4")].value, 5); } [Test] public void ToDictionaryWithKeySelectorAndComparerWorksForArray() { var d2 = Enumerable.Range(1, 5).Select((value, index) => new { id = new C(index.ToString()), value }).ToArray().ToDictionary(item => item.id, new FirstLetterComparer()); Assert.AreEqual(d2.Count, 5); Assert.AreEqual(d2[new C("02")].value, 1); Assert.AreEqual(d2[new C("12")].value, 2); Assert.AreEqual(d2[new C("22")].value, 3); Assert.AreEqual(d2[new C("32")].value, 4); Assert.AreEqual(d2[new C("42")].value, 5); } [Test] public void ToDictionaryWithKeySelectorAndComparerWorksForSaltarelleEnumerable() { var d2 = Enumerable.Range(1, 5).Select((value, index) => new { id = new C(index.ToString()), value }).Wrap().ToDictionary(item => item.id, new FirstLetterComparer()); Assert.AreEqual(d2.Count, 5); Assert.AreEqual(d2[new C("02")].value, 1); Assert.AreEqual(d2[new C("12")].value, 2); Assert.AreEqual(d2[new C("22")].value, 3); Assert.AreEqual(d2[new C("32")].value, 4); Assert.AreEqual(d2[new C("42")].value, 5); } [Test] public void ToDictionaryWithKeySelectorAndComparerWorksForLinqJSEnumerable() { var d2 = Enumerable.Range(1, 5).Select((value, index) => new { id = new C(index.ToString()), value }).ToDictionary(item => item.id, new FirstLetterComparer()); Assert.AreEqual(d2.Count, 5); Assert.AreEqual(d2[new C("02")].value, 1); Assert.AreEqual(d2[new C("12")].value, 2); Assert.AreEqual(d2[new C("22")].value, 3); Assert.AreEqual(d2[new C("32")].value, 4); Assert.AreEqual(d2[new C("42")].value, 5); } [Test] public void ToDictionaryWithKeyAndValueSelectorsWorksForArray() { var d = Enumerable.Range(1, 5).Select((value, index) => new { id = "id_" + index, value }).ToArray().ToDictionary(item => item.id, item => item.value); Assert.AreEqual(d.Count, 5); Assert.AreEqual(d["id_0"], 1); Assert.AreEqual(d["id_1"], 2); Assert.AreEqual(d["id_2"], 3); Assert.AreEqual(d["id_3"], 4); Assert.AreEqual(d["id_4"], 5); var d2 = Enumerable.Range(1, 5).Select((value, index) => new { id = new C(index.ToString()), value }).ToArray().ToDictionary(item => item.id, item => item.value); Assert.AreEqual(d2.Count, 5); Assert.AreEqual(d2[new C("0")], 1); Assert.AreEqual(d2[new C("1")], 2); Assert.AreEqual(d2[new C("2")], 3); Assert.AreEqual(d2[new C("3")], 4); Assert.AreEqual(d2[new C("4")], 5); } [Test] public void ToDictionaryWithKeyAndValueSelectorsWorksForSaltarelleEnumerable() { var d = Enumerable.Range(1, 5).Select((value, index) => new { id = "id_" + index, value }).Wrap().ToDictionary(item => item.id, item => item.value); Assert.AreEqual(d.Count, 5); Assert.AreEqual(d["id_0"], 1); Assert.AreEqual(d["id_1"], 2); Assert.AreEqual(d["id_2"], 3); Assert.AreEqual(d["id_3"], 4); Assert.AreEqual(d["id_4"], 5); var d2 = Enumerable.Range(1, 5).Select((value, index) => new { id = new C(index.ToString()), value }).Wrap().ToDictionary(item => item.id, item => item.value); Assert.AreEqual(d2.Count, 5); Assert.AreEqual(d2[new C("0")], 1); Assert.AreEqual(d2[new C("1")], 2); Assert.AreEqual(d2[new C("2")], 3); Assert.AreEqual(d2[new C("3")], 4); Assert.AreEqual(d2[new C("4")], 5); } [Test] public void ToDictionaryWithKeyAndValueSelectorsWorksForLinqJSEnumerable() { var d = Enumerable.Range(1, 5).Select((value, index) => new { id = "id_" + index, value }).ToDictionary(item => item.id, item => item.value); Assert.AreEqual(d.Count, 5); Assert.AreEqual(d["id_0"], 1); Assert.AreEqual(d["id_1"], 2); Assert.AreEqual(d["id_2"], 3); Assert.AreEqual(d["id_3"], 4); Assert.AreEqual(d["id_4"], 5); var d2 = Enumerable.Range(1, 5).Select((value, index) => new { id = new C(index.ToString()), value }).ToDictionary(item => item.id, item => item.value); Assert.AreEqual(d2.Count, 5); Assert.AreEqual(d2[new C("0")], 1); Assert.AreEqual(d2[new C("1")], 2); Assert.AreEqual(d2[new C("2")], 3); Assert.AreEqual(d2[new C("3")], 4); Assert.AreEqual(d2[new C("4")], 5); } [Test] public void ToDictionaryWithKeyAndValueSelectorsAndComparerWorksForArray() { var d2 = Enumerable.Range(1, 5).Select((value, index) => new { id = new C(index.ToString()), value }).ToArray().ToDictionary(item => item.id, item => item.value, new FirstLetterComparer()); Assert.AreEqual(d2.Count, 5); Assert.AreEqual(d2[new C("02")], 1); Assert.AreEqual(d2[new C("12")], 2); Assert.AreEqual(d2[new C("22")], 3); Assert.AreEqual(d2[new C("32")], 4); Assert.AreEqual(d2[new C("42")], 5); } [Test] public void ToDictionaryWithKeyAndValueSelectorsAndComparerWorksForSaltarelleEnumerable() { var d2 = Enumerable.Range(1, 5).Select((value, index) => new { id = new C(index.ToString()), value }).Wrap().ToDictionary(item => item.id, item => item.value, new FirstLetterComparer()); Assert.AreEqual(d2.Count, 5); Assert.AreEqual(d2[new C("02")], 1); Assert.AreEqual(d2[new C("12")], 2); Assert.AreEqual(d2[new C("22")], 3); Assert.AreEqual(d2[new C("32")], 4); Assert.AreEqual(d2[new C("42")], 5); } [Test] public void ToDictionaryWithKeyAndValueSelectorsAndComparerWorksForLinqJSEnumerable() { var d2 = Enumerable.Range(1, 5).Select((value, index) => new { id = new C(index.ToString()), value }).ToDictionary(item => item.id, item => item.value, new FirstLetterComparer()); Assert.AreEqual(d2.Count, 5); Assert.AreEqual(d2[new C("02")], 1); Assert.AreEqual(d2[new C("12")], 2); Assert.AreEqual(d2[new C("22")], 3); Assert.AreEqual(d2[new C("32")], 4); Assert.AreEqual(d2[new C("42")], 5); } [Test] public void ToJoinedStringWithoutArgumentsWorksForArray() { Assert.AreEqual(new[] { 1, 2, 3, 4, 5 }.ToJoinedString(), "12345"); } [Test] public void ToJoinedStringWithSeparatorWorksForArray() { Assert.AreEqual(new[] { 1, 2, 3, 4, 5 }.ToJoinedString(","), "1,2,3,4,5"); } [Test] public void ToJoinedStringWithSelectorAndSeparatorWorksForArray() { Assert.AreEqual(new[] { 1, 2, 3, 4, 5 }.ToJoinedString(",", i => (i + 1).ToString()), "2,3,4,5,6"); } [Test] public void ToJoinedStringWithoutArgumentsWorksForLinqJSEnumerable() { Assert.AreEqual(Enumerable.Range(1, 5).ToJoinedString(), "12345"); } [Test] public void ToJoinedStringWithSeparatorWorksForLinqJSEnumerable() { Assert.AreEqual(Enumerable.Range(1, 5).ToJoinedString(","), "1,2,3,4,5"); } [Test] public void ToJoinedStringWithSelectorAndSeparatorWorksForLinqJSEnumerable() { Assert.AreEqual(Enumerable.Range(1, 5).ToJoinedString(",", i => (i + 1).ToString()), "2,3,4,5,6"); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Net; using System.Net.Sockets; namespace control_panel { public partial class control_panel : Form { int message_fold = 1; string[] url = { "", "", "", "", "", "" }; IPEndPoint ipe = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9090); Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); public control_panel() { InitializeComponent(); message_splitContainer.Panel2Collapsed = !message_splitContainer.Panel2Collapsed; try { sock.Connect(ipe); } catch { Console.WriteLine("连接失败"); } } private void Fill_button_Click(object sender, EventArgs e) { if (windows_checkedListBox.CheckedItems.Count == 0) { message_textBox.Text = "没有选择要放大的窗口!"; if (message_fold == 1) { message_splitContainer.Panel1Collapsed = !message_splitContainer.Panel1Collapsed; message_fold = 0; } } else if (windows_checkedListBox.CheckedItems.Count > 1) { message_textBox.Text = "请不要勾选1个以上选项!"; if (message_fold == 1) { message_splitContainer.Panel1Collapsed = !message_splitContainer.Panel1Collapsed; message_fold = 0; } for (int i = 0; i < windows_checkedListBox.Items.Count; i++) { if (windows_checkedListBox.GetItemChecked(i)) { windows_checkedListBox.SetItemChecked(i, false); } } } else { for (int i = 0; i < windows_checkedListBox.Items.Count; i++) { if (windows_checkedListBox.GetItemChecked(i)) { string msg = "*"+"fill_window'"+i.ToString()+"'#"; byte[] send_data = Encoding.ASCII.GetBytes(msg); sock.Send(send_data, send_data.Length, 0); } } } } private void Add_window_button_Click(object sender, EventArgs e) { /* 添加视频窗口,最多同时展示6路视频窗口 */ int i = windows_checkedListBox.Items.Count; if (i < 6) { int k = i + 1; windows_checkedListBox.Items.Add(k.ToString() + "窗"); string msg = "*" + "add_window''#"; byte[] send_data = Encoding.ASCII.GetBytes(msg); sock.Send(send_data, send_data.Length, 0); } } private void Remove_window_button_Click(object sender, EventArgs e) { /* 删除视频窗口,最少必须有4个视频窗口 */ if (windows_checkedListBox.Items.Count > 4) { windows_checkedListBox.Items.RemoveAt(windows_checkedListBox.Items.Count - 1); string msg = "*" + "remove_window''#"; byte[] send_data = Encoding.ASCII.GetBytes(msg); sock.Send(send_data, send_data.Length, 0); } } private void Video_play_button_Click(object sender, EventArgs e) { if (windows_checkedListBox.CheckedItems.Count < 1) { message_textBox.Text = "没有选择窗口!"; if (message_fold == 1) { message_splitContainer.Panel1Collapsed = !message_splitContainer.Panel1Collapsed; message_fold = 0; } } else { // 视频播放窗口列表 for (int i = 0; i < windows_checkedListBox.Items.Count; i++) { if (windows_checkedListBox.GetItemChecked(i)) { url[i] = address_textBox.Text; string msg = "*" + "video_play'"+url[i]+','+i.ToString()+"'#"; byte[] send_data = Encoding.ASCII.GetBytes(msg); sock.Send(send_data, send_data.Length, 0); windows_checkedListBox.SetItemChecked(i, false); } } } } private void Video_stop_button_Click(object sender, EventArgs e) { if (windows_checkedListBox.CheckedItems.Count < 1) { message_textBox.Text = "没有选择窗口!"; if (message_fold == 1) { message_splitContainer.Panel1Collapsed = !message_splitContainer.Panel1Collapsed; message_fold = 0; } } else { // 视频播放窗口列表 for (int i = 0; i < windows_checkedListBox.Items.Count; i++) { if (windows_checkedListBox.GetItemChecked(i)) { string msg = "*" + "video_stop'"+i.ToString()+"'#"; byte[] send_data = Encoding.ASCII.GetBytes(msg); sock.Send(send_data, send_data.Length, 0); windows_checkedListBox.SetItemChecked(i, false); } } } } private void Message_confirm_button_Click(object sender, EventArgs e) { message_splitContainer.Panel2Collapsed = !message_splitContainer.Panel2Collapsed; message_fold = 1; } } }
using UnityEngine; using System.Collections; public class Villager : MonoBehaviour { GameState state; EventReceiver eventReceiver; // Use this for initialization void Start () { state = GameObject.FindObjectOfType<GameState>(); eventReceiver = GameObject.FindObjectOfType<EventReceiver>(); } // Update is called once per frame void Update () { } void OnMouseDown() { eventReceiver.OnVillagerDown(this); } }
using System; using System.Collections.Generic; using JetBrains.Annotations; namespace alone { internal class SaveGameEditor3 : SaveGameEditor2 { public SaveGameEditor3([NotNull] Dictionary<Option, string> options) : base(options) { offsets = new [] { new KeyValuePair<Option, long>(Option.HEALTH, 0xAD64), new KeyValuePair<Option, long>(Option.HEALTH2, 0xAF9C), new KeyValuePair<Option, long>(Option.WINCHESTER, 0xAFC6), new KeyValuePair<Option, long>(Option.REVOLVER, 0xAFCE), new KeyValuePair<Option, long>(Option.GATLING, 0xB0C0), }; } } }
using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Micro.Net.Abstractions; using Micro.Net.Dispatch; namespace Micro.Net.Transport.Generic { public abstract class GenericDispatcherBase : IDispatcher, IStartable, IStoppable { /// <summary> /// Advertises features this dispatcher supports. /// </summary> public abstract ISet<DispatcherFeature> Features { get; } /// <summary> /// Advertises message types this dispatcher is capable of handling. /// </summary> public abstract IEnumerable<(Type, Type)> Available { get; } /// <summary> /// Called by upstream core components when a message is ready to be dispatched. /// </summary> /// <typeparam name="TRequest">Type of message to be dispatched.</typeparam> /// <typeparam name="TResponse">Type of response expected. When no response is expected, <see cref="ValueTuple"/> is used to indicate no value is expected.</typeparam> /// <param name="messageContext">Message context to be dispatched. Value for dispatching is <see> /// <cref>messageContext.Request.Payload</cref> /// </see>, response should be added to <see><crf>messageContext.Response.Payload</crf></see> /// </param> /// <returns></returns> public abstract Task Handle<TRequest, TResponse>(IDispatchContext<TRequest,TResponse> messageContext) where TRequest : IContract<TResponse>; public virtual async Task Start(CancellationToken cancellationToken) { } public virtual async Task Stop(CancellationToken cancellationToken) { } } }
using System.Collections; using UnityEngine; public class UFOControl : MonoBehaviour { // Use this for class variables. public GameObject theLargeUFO; public GameObject theSmallUFO; public int wave; private GameObject spawnedUFO; private float spawnTimer; private float spawnWait; public bool isSpawnedUFO; public int spawnCounter; public float spawnPercent; public float spawnSeed; // Use this for initialization when scene loads. private void Awake() { spawnWait = 25.15f; spawnSeed = 0.985f; isSpawnedUFO = false; } // Use this for initialization when game starts. private void Start() { ResetTimer(); } // Update is called once per frame. private void Update() { if (Time.time > spawnTimer && !isSpawnedUFO) { SpawnUFO(); ResetTimer(); } } // Update is called by physics. private void FixedUpdate() { } // When Collider is triggered by other. private void OnTriggerEnter(Collider other) { } // When object other leaves Collider. private void OnTriggerExit(Collider other) { } private void ResetTimer() { spawnTimer = Time.time + Random.Range(Mathf.Clamp((spawnWait - (wave * 0.25f)), 5.75f, 15.15f), Mathf.Clamp((spawnWait - (wave * 0.25f)), 15.75f, 25.15f)); } private void SpawnUFO() { spawnPercent = Mathf.Pow(spawnSeed, (spawnCounter * 15) / (wave + 1)); if (Random.Range(1, 100) < spawnPercent * 100) { SpawnLarge(); } else { SpawnSmall(); } } private void SpawnLarge() { spawnedUFO = Instantiate(theLargeUFO); Debug.Log("Large UFO spawned."); } private void SpawnSmall() { spawnedUFO = Instantiate(theSmallUFO); spawnedUFO.GetComponentInChildren<AimedUFOShooter>().wave = wave; spawnedUFO.GetComponentInChildren<UFO>().points = 1000; spawnedUFO.GetComponentInChildren<UFO>().vectorWait = 2.5f; spawnedUFO.GetComponentInChildren<UFO>().speed = 1.0f; spawnedUFO.GetComponentInChildren<RandomUFOShooter>().aimed = true; Debug.Log("Small UFO spawned."); } public void UFOSpawned() { spawnCounter++; isSpawnedUFO = true; } public void UFOHit() { ResetTimer(); isSpawnedUFO = false; } }
using System; using System.Collections.Generic; using System.IO; using Newtonsoft.Json; using QuantConnect; using QuantConnect.Configuration; using QuantConnect.Interfaces; using QuantConnect.Logging; using QuantConnect.Packets; using QuantConnect.Python; using QuantConnect.Queues; namespace LeanBatchLauncher.Launcher { public class Queue : IJobQueueHandler { /// <summary> /// The shadow queue object - we don't want to reimplement everything so we use it instead. /// </summary> private readonly JobQueue _shadow; private readonly bool _liveMode = Config.GetBool("live-mode"); private static readonly string AccessToken = Config.Get("api-access-token"); private static readonly int UserId = Config.GetInt("job-user-id", 0); private static readonly int ProjectId = Config.GetInt("job-project-id", 0); private readonly string AlgorithmTypeName = Config.Get("algorithm-type-name"); private readonly Language Language = (Language)Enum.Parse(typeof(Language), Config.Get("algorithm-language"), ignoreCase: true); private readonly string BacktestId = Config.Get("BacktestId"); /// <summary> /// Creates the queue and a parent queue. /// </summary> public Queue() { _shadow = new JobQueue(); } /// <summary> /// Physical location of Algorithm DLL. /// </summary> private string AlgorithmLocation { get { // we expect this dll to be copied into the output directory return Config.Get("algorithm-location", "Algorithm.dll"); } } /// <summary> /// Desktop/Local acknowledge the task processed. Nothing to do. /// </summary> /// <param name="job"></param> public void AcknowledgeJob(AlgorithmNodePacket job) { // We don't want to wait for a key press // Console.Read(); Console.WriteLine("Engine.Main(): Analysis Complete."); } /// <summary> /// Facade for the parent's NextJob() function. /// We're exposing this in order to change the BacktestId. /// </summary> /// <param name="location"></param> /// <returns></returns> public AlgorithmNodePacket NextJob(out string location) { location = GetAlgorithmLocation(); Log.Trace("JobQueue.NextJob(): Selected " + location); // check for parameters in the config var parameters = new Dictionary<string, string>(); var parametersConfigString = Config.Get("parameters"); if (parametersConfigString != string.Empty) { parameters = JsonConvert.DeserializeObject<Dictionary<string, string>>(parametersConfigString); } var controls = new Controls() { MinuteLimit = Config.GetInt("symbol-minute-limit", 10000), SecondLimit = Config.GetInt("symbol-second-limit", 10000), TickLimit = Config.GetInt("symbol-tick-limit", 10000), RamAllocation = int.MaxValue, MaximumDataPointsPerChartSeries = Config.GetInt("maximum-data-points-per-chart-series", 4000) }; if ((Language)Enum.Parse(typeof(Language), Config.Get("algorithm-language")) == Language.Python) { // Set the python path for loading python algorithms ("algorithm-location" config parameter) var pythonFile = new FileInfo(location); // PythonInitializer automatically adds the current working directory for us //PythonInitializer.SetPythonPathEnvironmentVariable(new string[] { pythonFile.Directory.FullName }); PythonInitializer.Initialize(); } // We currently offer no live job functionality //Default run a backtesting job. var backtestJob = new BacktestNodePacket(0, 0, "", new byte[] { }, "local") { Type = PacketType.BacktestNode, Algorithm = File.ReadAllBytes(location), HistoryProvider = Config.Get("history-provider", "SubscriptionDataReaderHistoryProvider"), Channel = AccessToken, UserId = UserId, ProjectId = ProjectId, Version = Globals.Version, BacktestId = BacktestId, //AlgorithmTypeName + "-" + Guid.NewGuid(), Language = (Language)Enum.Parse(typeof(Language), Config.Get("algorithm-language")), Parameters = parameters, Controls = controls, }; return backtestJob; } /// <summary> /// Get the algorithm location for client side backtests. /// </summary> /// <returns></returns> private string GetAlgorithmLocation() { if (Language == Language.Python) { if (!File.Exists(AlgorithmLocation)) { throw new FileNotFoundException($"JobQueue.TryCreatePythonAlgorithm(): Unable to find py file: {AlgorithmLocation}"); } // Add this directory to our Python Path so it may be imported properly var pythonFile = new FileInfo(AlgorithmLocation); PythonInitializer.AddPythonPaths(new string[] { pythonFile.Directory.FullName }); } return AlgorithmLocation; } #region Shadow methods public void Initialize(IApi api) { } #endregion } }
using SnakeGameConsole.Services; using SnakeGameConsole.Interfaces; using Microsoft.Extensions.DependencyInjection; namespace SnakeGameConsole { public class DependencyInjection { public static ServiceProvider Setup() => new ServiceCollection() .AddSingleton<IGameService, GameService>() .AddSingleton<ISnakeService, SnakeService>() .AddSingleton<IBoardService, BoardService>() .AddSingleton<IMainMenuService, MainMenuService>() .BuildServiceProvider(); } }
using System; using System.Collections.Generic; namespace Tavisca.Bootcamp.LanguageBasics.Exercise1 { public static class Program { static void Main(string[] args) { Test(new[] {"12:12:12"}, new [] { "few seconds ago" }, "12:12:12"); Test(new[] { "23:23:23", "23:23:23" }, new[] { "59 minutes ago", "59 minutes ago" }, "00:22:23"); Test(new[] { "00:10:10", "00:10:10" }, new[] { "59 minutes ago", "1 hours ago" }, "impossible"); Test(new[] { "11:59:13", "11:13:23", "12:25:15" }, new[] { "few seconds ago", "46 minutes ago", "23 hours ago" }, "11:59:23"); Console.ReadKey(true); } private static void Test(string[] postTimes, string[] showTimes, string expected) { var result = GetCurrentTime(postTimes, showTimes).Equals(expected) ? "PASS" : "FAIL"; var postTimesCsv = string.Join(", ", postTimes); var showTimesCsv = string.Join(", ", showTimes); Console.WriteLine($"[{postTimesCsv}], [{showTimesCsv}] => {result}"); } public static string GetCurrentTime(string[] exactPostTime, string[] showPostTime) { var length = exactPostTime.Length; var array = new List<string>(); for(var i=0;i<length;i++) { // Check whether for same exactPostTime we have different showPostTime if(i!=length-1) { if(exactPostTime[i]==exactPostTime[i+1] && showPostTime[i]!=showPostTime[i+1]) return "impossible"; } var postTime = TimeSpan.Parse(exactPostTime[i]); // add seconds in exactPostTime if(showPostTime[i].Contains("seconds")) { array.Add(new TimeSpan(postTime.Hours,postTime.Minutes,postTime.Seconds).ToString()); } // add minutes in exactPostTime else if(showPostTime[i].Contains("minutes")) { var minutes = showPostTime[i].Split(" ")[0]; postTime = postTime.Add(TimeSpan.FromMinutes(Double.Parse(minutes))); array.Add(new TimeSpan(postTime.Hours,postTime.Minutes,postTime.Seconds).ToString()); } // add hours in exactPostTime else if(showPostTime[i].Contains("hours")) { var hours = showPostTime[i].Split(" ")[0]; postTime = postTime.Add(TimeSpan.FromHours(Double.Parse(hours))); array.Add(new TimeSpan(postTime.Hours,postTime.Minutes,postTime.Seconds).ToString()); } else { return "impossible"; } } // Sort array and return the largest one array.Sort(); return array[array.Count-1]; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using PaintingCost.Entities; namespace PaintingCost.SeedDb { public interface ISeedDb { ProjectType[] GetProjectTypes(); Sector[] GetSectors(); Product[] GetProducts(); ProjectTypeSector[] GetProjectTypeSectors(); SectorProduct[] GetProductSectors(); } }
using OmniSharp.Extensions.JsonRpc.Generation; namespace OmniSharp.Extensions.DebugAdapter.Protocol.Models { [StringEnum] public readonly partial struct PathFormat { public static PathFormat Path { get; } = new PathFormat("path"); public static PathFormat Uri { get; } = new PathFormat("uri"); } }
namespace Bomberman.Api { public struct MoveProbability { public double KeepDirection { get; set; } public double TurnLeft { get; set; } public double TurnRight { get; set; } public double Stop { get; set; } public double Reverse { get; set; } public MoveProbability Normalize(bool keepDirectionAllowed, bool turnLeftAllowed, bool turnRightAllowed) { var sum = KeepDirection * (keepDirectionAllowed ? 1 : 0) + TurnLeft * turnLeftAllowed.AsInt() + TurnRight * turnRightAllowed.AsInt() + Stop + Reverse; var res = new MoveProbability { KeepDirection = KeepDirection * keepDirectionAllowed.AsInt() / sum, TurnLeft = TurnLeft * turnLeftAllowed.AsInt() / sum, TurnRight = TurnRight * turnRightAllowed.AsInt() / sum, Stop = Stop / sum, Reverse = Reverse / sum }; return res; } } }
using System; using System.Data; using System.Collections.Generic; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; using System.Configuration; using System.Web.Security; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Data.SqlClient; /// <summary> /// changepass 的摘要说明 /// </summary> public class changepass { SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["classConnectionString"].ConnectionString); public changepass() { // // TODO: 在此处添加构造函数逻辑 // } public bool Schangepass(string np, string id) { String sql = "update Student set stuPwd='" + np + "'where stuID='" + id + "'"; SqlCommand cmd = new SqlCommand(sql, con); try { con.Open(); SqlDataReader da = cmd.ExecuteReader(); if (da.Read()) { return true; } else { return false; } } catch (Exception ex) { throw (ex); } finally { con.Close(); } } public bool Achangepass(string np, string id) { String sql = "update Admin set adPwd='" + np + "'where adID='" + id + "'"; SqlCommand cmd = new SqlCommand(sql, con); try { con.Open(); SqlDataReader da = cmd.ExecuteReader(); if (da.Read()) { return true; } else { return false; } } catch (Exception ex) { throw (ex); } finally { con.Close(); } } }
/** *┌──────────────────────────────────────────────────────────────┐ *│ 描 述: *│ 作 者:zhujun *│ 版 本:1.0 模板代码自动生成 *│ 创建时间:2019-05-23 16:43:42 *└──────────────────────────────────────────────────────────────┘ *┌──────────────────────────────────────────────────────────────┐ *│ 命名空间: EWF.Services *│ 接口名称: ISYS_LOGINSUCCESSRepository *└──────────────────────────────────────────────────────────────┘ */ using EWF.Entity; using EWF.Util; using System; using System.Collections.Generic; using System.Data; using System.Text; namespace EWF.IServices { public interface ISYS_LOGINSUCCESSService: IDependency { /// <summary> /// 往表里插记录 /// </summary> /// <param name="entity">实体</param> /// <returns></returns> string Insert(SYS_LOGINSUCCESS entity); /// <summary> /// 删除登录成功的记录 /// </summary> /// <param name="userip">ip</param> /// <param name="username">用户名</param> /// <param name="tm">时间</param> /// <returns></returns> bool DeleteLoginSuccess(string userip, string username, DateTime tm); /// <summary> /// 检查登录次数 /// </summary> /// <param name="userip">ip</param> /// <param name="username">用户名</param> /// <param name="tm">时间</param> /// <returns></returns> DataTable GetLoginSuccessCount(string userip, string username, DateTime tm); } }
using System; using System.Collections.Generic; using System.Linq; public class Program { public static void Main() { var inputList = Console.ReadLine().Split().Select(int.Parse).ToList(); while (true) { var command = Console.ReadLine().Split().ToList(); if (command[0] == "add") { Add(inputList, command); } else if (command[0] == "addMany") { AddMany(inputList, command); } else if (command[0] == "contains") { Contains(inputList, command); } else if (command[0] == "remove") { Remove(inputList, command); } else if (command[0] == "shift") { Shift(inputList, command); } else if (command[0] == "sumPairs") { SumPairs(inputList); } else if (command[0] == "print") { Console.WriteLine("[" + string.Join(", ", inputList) + "]"); break; } } } public static void Add(List<int> inputList, List<string> command) { var index = int.Parse(command[1]); var number = int.Parse(command[2]); inputList.Insert(index, number); } public static void AddMany(List<int> inputList, List<string> command) { var index = int.Parse(command[1]); for (int i = command.Count - 1; i > 1; i--) { var number = int.Parse(command[i]); inputList.Insert(index, number); } } public static void Contains(List<int> inputList, List<string> command) { var number = int.Parse(command[1]); var index = 0; bool contains = false; for (int i = 0; i < inputList.Count; i++) { if (inputList[i] == number) { contains = true; index = i; break; } } Console.WriteLine("{0}", contains ? index : -1); } public static void Remove(List<int> inputList, List<string> command) { var number = int.Parse(command[1]); inputList.RemoveAt(number); } public static void Shift(List<int> inputList, List<string> command) { var numberOfShifts = int.Parse(command[1]); for (int i = 0; i < numberOfShifts; i++) { var oldFirstNumber = inputList.First(); for (int j = 0; j < inputList.Count; j++) { if (j + 1 < inputList.Count) { inputList[j] = inputList[j + 1]; } } inputList[inputList.Count - 1] = oldFirstNumber; } } public static void SumPairs(List<int> inputList) { for (int i = 0; i < inputList.Count; i++) { if (i + 1 < inputList.Count) { inputList[i] += inputList[i + 1]; inputList.RemoveAt(i + 1); } } } }
using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Domen { public interface IEntity { string TableName { get; } string InsertValues { get; set; } string SelectWhere { get; set; } string JoinTable { get; } string JoinCondition { get; } string AliasName { get; } string Id { get; } string UpdateValue { get; set; } List<IEntity> ReturnReaderResult(SqlDataReader reader); } }
using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Kers.Models.Contexts; using Kers.Models.Entities.KERScore; using Kers.Models.Repositories; using Kers.Models.ViewModels; using Microsoft.Extensions.Caching.Distributed; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.DependencyInjection; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace Kers.Tasks { public class ActivityPerMajorProgramTask : TaskBase, IScheduledTask { IServiceProvider serviceProvider; public ActivityPerMajorProgramTask( IServiceProvider serviceProvider ){ this.serviceProvider = serviceProvider; } public string Schedule => "18 23 * * *"; public async Task ExecuteAsync(CancellationToken cancellationToken) { var serviceScopeFactory = this.serviceProvider.GetRequiredService<IServiceScopeFactory>(); using (var scope = serviceScopeFactory.CreateScope()) { var context = scope.ServiceProvider.GetService<KERScoreContext>(); var progressLog = ""; try{ var cache = scope.ServiceProvider.GetService<IDistributedCache>(); var memoryCache = scope.ServiceProvider.GetService<IMemoryCache>(); var fiscalYearRepo = new FiscalYearRepository( context ); var repo = new ContactRepository(cache, context, memoryCache); var startTime = DateTime.Now; progressLog += startTime.ToString() + ": ActivityPerMajorProgramTask Started\n"; Random rnd = new Random(); int RndInt = rnd.Next(1, 53); var tables = new List<TableViewModel>(); progressLog += DateTime.Now.ToString() + ": Random Number = "+ RndInt.ToString() + "\n"; // Districts var districts = context.District; foreach( var district in districts){ progressLog += DateTime.Now.ToString() + ": " + district.Name + " Data for current fiscal year started.\n"; var tbl = await repo.DataByMajorProgram(fiscalYearRepo.currentFiscalYear(FiscalYearType.ServiceLog),0, district.Id, true); progressLog += DateTime.Now.ToString() + ": " + district.Name + " Data for current fiscal year finished.\n"; if(RndInt == 1){ progressLog += DateTime.Now.ToString() + ": " + district.Name + " Data for previous fiscal year started.\n"; tbl = await repo.DataByMajorProgram(fiscalYearRepo.previoiusFiscalYear(FiscalYearType.ServiceLog),0, district.Id, true); progressLog += DateTime.Now.ToString() + ": " + district.Name + " Data for previous fiscal year finished.\n"; } tables.Add(tbl); } // Planning Units var units = context.PlanningUnit; foreach( var unit in units){ progressLog += DateTime.Now.ToString() + ": " + unit.Name + " Data for current fiscal year started.\n"; var tbl = await repo.DataByMajorProgram(fiscalYearRepo.currentFiscalYear(FiscalYearType.ServiceLog),1, unit.Id, true); progressLog += DateTime.Now.ToString() + ": " + unit.Name + " Data for current fiscal year finished.\n"; if(RndInt == 2){ progressLog += DateTime.Now.ToString() + ": " + unit.Name + " Data for previous fiscal year started.\n"; tbl = await repo.DataByMajorProgram(fiscalYearRepo.previoiusFiscalYear(FiscalYearType.ServiceLog),1, unit.Id, true); progressLog += DateTime.Now.ToString() + ": " + unit.Name + " Data for previous fiscal year finished.\n"; } tables.Add(tbl); } // KSU if( startTime.DayOfWeek == DayOfWeek.Friday){ progressLog += DateTime.Now.ToString() + ": KSU Data for current fiscal year started.\n"; var tblKSU = await repo.DataByMajorProgram(fiscalYearRepo.currentFiscalYear(FiscalYearType.ServiceLog),2, 0, true, 20); progressLog += DateTime.Now.ToString() + ": KSU Data for current fiscal year finished.\n"; if( RndInt == 3 ){ progressLog += DateTime.Now.ToString() + ": KSU Data for previous fiscal year started.\n"; tblKSU = await repo.DataByMajorProgram(fiscalYearRepo.previoiusFiscalYear(FiscalYearType.ServiceLog),2, 0, true); progressLog += DateTime.Now.ToString() + ": KSU Data for previous fiscal year finished.\n"; } tables.Add(tblKSU); } // UK if( startTime.DayOfWeek == DayOfWeek.Saturday){ progressLog += DateTime.Now.ToString() + ": UK Data for current fiscal year started.\n"; var tblUK = await repo.DataByMajorProgram(fiscalYearRepo.currentFiscalYear(FiscalYearType.ServiceLog),3, 0, true, 20); progressLog += DateTime.Now.ToString() + ": UK Data for current fiscal year finished.\n"; if( RndInt == 4 ){ progressLog += DateTime.Now.ToString() + ": UK Data for previous fiscal year started.\n"; tblUK = await repo.DataByMajorProgram(fiscalYearRepo.previoiusFiscalYear(FiscalYearType.ServiceLog),3, 0, true); progressLog += DateTime.Now.ToString() + ": UK Data for previous fiscal year finished.\n"; } tables.Add(tblUK); } // ALL if( startTime.DayOfWeek == DayOfWeek.Sunday){ progressLog += DateTime.Now.ToString() + ": ALL Data for current fiscal year started.\n"; var tblAll = await repo.DataByMajorProgram(fiscalYearRepo.currentFiscalYear(FiscalYearType.ServiceLog),4, 0, true, 20); progressLog += DateTime.Now.ToString() + ": ALL Data for current fiscal year finished.\n"; if( RndInt == 5 ){ progressLog += DateTime.Now.ToString() + ": All Data for previous fiscal year started.\n"; tblAll = await repo.DataByMajorProgram(fiscalYearRepo.previoiusFiscalYear(FiscalYearType.ServiceLog),4, 0, true); progressLog += DateTime.Now.ToString() + ": All Data for previous fiscal year finished.\n"; } tables.Add(tblAll); } var endTime = DateTime.Now; await LogComplete(context, "ActivityPerMajorProgramTask", tables, "Activity Per Major Program Task executed for " + (endTime - startTime).TotalSeconds + " seconds", progressLog ); }catch( Exception e){ await LogError(context, "ActivityPerMajorProgramTask", e, "Activity Per Major Program Task failed", progressLog ); } } } } }
using System; using System.Collections.Generic; using System.Text; namespace RecuperacionParcial { public abstract class LineaAbstracta<T> : ILinea<T> { public abstract T[] Punto { get; } public double Longitud() { double longitud = 0; // si no hay ningun punto en el arreglo if (Punto.Length == 0 || Punto.Length == 1) { return 0; } for (int i = 0; i < Punto.Length; i++) { if (i == Punto.Length) { break; } longitud += Distancia(Punto[i], Punto[i + 1]); } return longitud; } public T PuntoMasCercano(T punto) { T PuntoMasCercano = Punto[0]; for (int i = 0; i < Punto.Length; i++) { if (Distancia(punto, Punto[i]) < Distancia(punto, PuntoMasCercano)) { PuntoMasCercano = Punto[i]; } } return PuntoMasCercano; } public abstract double Distancia(T puntoA,T puntoB); } }
// <copyright file="DoublyLinkedListNodeTTest.cs"></copyright> using System; using Dsa.DataStructures; using Microsoft.Pex.Framework; using Microsoft.Pex.Framework.Validation; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Dsa.DataStructures { [PexClass(typeof(DoublyLinkedListNode<>))] //[PexAllowedExceptionFromTypeUnderTest(typeof(InvalidOperationException))] //[PexAllowedExceptionFromTypeUnderTest(typeof(ArgumentException), AcceptExceptionSubtypes = true)] [TestClass] public partial class DoublyLinkedListNodeTTest { [PexGenericArguments(typeof(int))] [PexMethod] public DoublyLinkedListNode<T> Constructor<T>(T value) { DoublyLinkedListNode<T> target = new DoublyLinkedListNode<T>(value); return target; } } }
using SQLite; namespace DartsTracker.Models { public class Throw { [PrimaryKey, AutoIncrement] public int Id { get; set; } public int PlayerId { get; set;} public int GameId { get; set; } public byte First { get; set; } public byte Second { get; set; } public byte Third { get; set; } public Throw() {} public Throw(int playerId, int gameId, byte first, byte second, byte third) { PlayerId = playerId; GameId = gameId; First = first; Second = second; Third = third; } } }
using EmployeeConsoleApp.Repository; using System; namespace EmployeeConsoleApp { class Program { static void Main(string[] args) { EmployeeRepository employeeRepository = new EmployeeRepository(); employeeRepository.AddEmployee(); } } }
// ---------------------------------------------------------------------------------------------------------------------------------------- // <copyright file="TimeSpanSurrogate.cs" company="David Eiwen"> // Copyright © 2016 by David Eiwen // </copyright> // <author>David Eiwen</author> // <summary> // This file contains the TimeSpanSurrogate class. // </summary> // ---------------------------------------------------------------------------------------------------------------------------------------- namespace IndiePortable.Formatter.MscorlibSurrogates { using System; /// <summary> /// Provides serialization and de-serialization logic for the <see cref="TimeSpan" /> type. /// </summary> /// <seealso cref="ISurrogate" /> internal sealed class TimeSpanSurrogate : ISurrogate { /// <summary> /// Gets the target type for the <see cref="TimeSpanSurrogate" />. /// </summary> /// <value> /// Contains the target type for the <see cref="TimeSpanSurrogate" />. /// </value> /// <remarks> /// <para>Implements <see cref="ISurrogate.TargetType" /> implicitly.</para> /// </remarks> public Type TargetType { get { return typeof(TimeSpan); } } /// <summary> /// Populates an <see cref="ObjectDataCollection" /> instance with data from a <see cref="TimeSpan" /> value. /// </summary> /// <param name="value"> /// The source <see cref="TimeSpan" /> providing the data. /// </param> /// <param name="data"> /// The <see cref="ObjectDataCollection" /> that shall be populated with data. /// </param> /// <exception cref="ArgumentNullException"> /// <para>Thrown if <paramref name="data" /> is <c>null</c>.</para> /// </exception> /// <exception cref="ArgumentException"> /// <para>Thrown if <paramref name="value" /> is not of type <see cref="TimeSpan" />.</para> /// </exception> public void GetData(object value, ObjectDataCollection data) { if (object.ReferenceEquals(data, null)) { throw new ArgumentNullException(nameof(data)); } if (!(value is TimeSpan)) { throw new ArgumentException( "The value must be of type System.TimeSpan in order to be used with the TimeSpanSurrogate.", nameof(value)); } var time = (TimeSpan)value; data.AddValue(nameof(TimeSpan.Ticks), time.Ticks); } /// <summary> /// Populates a <see cref="TimeSpan" /> value with data from an <see cref="ObjectDataCollection" /> instance. /// </summary> /// <param name="value"> /// The object that shall be populated with data. This parameter is to be passed by reference. /// </param> /// <param name="data"> /// The <see cref="ObjectDataCollection" /> providing the data. /// </param> /// <exception cref="ArgumentNullException"> /// <para>Thrown if <paramref name="data" /> is <c>null</c>.</para> /// </exception> /// <exception cref="ArgumentException"> /// <para>Thrown if <paramref name="value" /> is not of type <see cref="TimeSpan" />.</para> /// <para>or</para> /// <para><paramref name="data" /> does not contain the <see cref="TimeSpan.Ticks" /> property.</para> /// </exception> public void SetData(ref object value, ObjectDataCollection data) { if (object.ReferenceEquals(data, null)) { throw new ArgumentNullException(nameof(data)); } if (!(value is TimeSpan)) { throw new ArgumentException( "The value must be of type System.TimeSpan in order to be used with the TimeSpanSurrogate.", nameof(value)); } long ticks; if (!data.TryGetValue(nameof(TimeSpan.Ticks), out ticks)) { throw new ArgumentException("The data collection must contain the ticks of the desired TimeSpan value.", nameof(data)); } value = new TimeSpan(ticks); } } }
using System; using System.Collections; namespace Aut.Lab.Lab11 { public class Powtwo { private int newnum = 0; Stack mystack = new Stack(); public Powtwo(int num) { newnum = num; if(newnum == 0) { mystack.Push(0); } } public int Count() { int count = mystack.Count; return(count); } public void Binarynumeral() { while(newnum > 0) { if(newnum % 2 == 0) { mystack.Push(0); } else if(newnum % 2 == 1) { mystack.Push(1); } int sumdivide = newnum / 2; newnum = sumdivide; } foreach(int num in mystack) { Console.Write(num); } Console.WriteLine(); } } }
using System; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Input; using System.Windows.Media; using HandyControl.Data; namespace HandyControl.Controls { [TemplatePart(Name = PreviewContentKey, Type = typeof(ContentControl))] [TemplatePart(Name = TracKKey, Type = typeof(Track))] public class PreviewSlider : Slider { private const string PreviewContentKey = "PART_ContentBorder"; private const string TracKKey = "PART_Track"; private ContentControl _previewContent; private TranslateTransform _transform; private Track _track; /// <summary> /// 预览内容 /// </summary> public static readonly DependencyProperty PreviewContentProperty = DependencyProperty.Register( "PreviewContent", typeof(object), typeof(PreviewSlider), new PropertyMetadata(default(object))); /// <summary> /// 预览内容 /// </summary> public object PreviewContent { get => GetValue(PreviewContentProperty); set => SetValue(PreviewContentProperty, value); } public static readonly DependencyProperty PreviewPositionProperty = DependencyProperty.Register( "PreviewPosition", typeof(double), typeof(PreviewSlider), new PropertyMetadata(ValueBoxes.Double0Box)); public double PreviewPosition { get => (double) GetValue(PreviewPositionProperty); set => SetValue(PreviewPositionProperty, value); } /// <summary> /// 值改变事件 /// </summary> public static readonly RoutedEvent PreviewPositionChangedEvent = EventManager.RegisterRoutedEvent("PreviewPositionChanged", RoutingStrategy.Bubble, typeof(EventHandler<FunctionEventArgs<double>>), typeof(PreviewSlider)); /// <summary> /// 值改变事件 /// </summary> public event EventHandler<FunctionEventArgs<double>> PreviewPositionChanged { add => AddHandler(PreviewPositionChangedEvent, value); remove => RemoveHandler(PreviewPositionChangedEvent, value); } protected override void OnMouseMove(MouseEventArgs e) { base.OnMouseMove(e); var p = e.GetPosition(_track); _transform.X = p.X - _previewContent.ActualWidth/2; PreviewPosition = p.X / _track.ActualWidth * Maximum; RaiseEvent(new FunctionEventArgs<double>(PreviewPositionChangedEvent, this) { Info = PreviewPosition }); } public override void OnApplyTemplate() { base.OnApplyTemplate(); _previewContent = Template.FindName(PreviewContentKey, this) as ContentControl; _track = Template.FindName(TracKKey, this) as Track; if (_previewContent != null) { _transform = new TranslateTransform(); _previewContent.RenderTransform = _transform; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using AgentStoryComponents.core; namespace AgentStoryComponents.commands { public class cmdDisplayGameController : ICommand { public MacroEnvelope execute(Macro macro) { string targetDiv = MacroUtils.getParameterString("targetDiv", macro); //string tx_id64 = MacroUtils.getParameterString("tx_id64", macro); //string tx_id = TheUtils.ute.decode64(tx_id64); int storyID = MacroUtils.getParameterInt("storyID", macro); Dictionary<string,int> listGates = new Dictionary<string,int>(); Story currStory = new Story(config.conn, storyID, macro.RunningMe); int stateCursor = currStory.StateCursor; int i = 0; foreach (Page pg in currStory.Pages) { listGates.Add(pg.Name, i); i++; } string html = this.getHTML(listGates, stateCursor); MacroEnvelope me = new MacroEnvelope(); Macro proc = new Macro("DisplayDiv", 2); proc.addParameter("html64", TheUtils.ute.encode64(html)); proc.addParameter("targetDiv", targetDiv); me.addMacro(proc); return me; } private string getHTML(Dictionary<string, int> listGates,int stateCursor) { System.Text.StringBuilder sbHTML = new StringBuilder(); sbHTML.Append("<select class='clsGameController' ondblclick='setGate(this.options[this.selectedIndex].value);' onchange='setGate(this.options[this.selectedIndex].value);' title='double click to re-send gate command'>"); // sbHTML.Append("<option value='-1'> -- select stage gate --</option>"); string selstring = string.Empty; int i = 0; foreach (KeyValuePair<string, int> kvp in listGates) { if (i == stateCursor) selstring = "SELECTED='true'"; else selstring = string.Empty; sbHTML.AppendFormat("<option value='{1}' {2}>{0}</option>", TheUtils.ute.decode64(kvp.Key), kvp.Value,selstring); i++; } sbHTML.Append("</select>"); return sbHTML.ToString(); } } }
// TestScope.cs // Author: // Stephen Shaw <sshaw@decriptor.com> // Copyright (c) 2012 sshaw using System; using Compiler.Parser; using NUnit.Framework; namespace CompilerTests { [TestFixture] public class TestOf_ScopeManagerTests { ScopeManager sm; [Test] public void ScopeManagerDefaultValuesTest () { sm = new ScopeManager (); Assert.IsTrue (sm.CurrentScope() == "g"); } [Test] public void ScopeManagerPushOneScopeLevel () { sm = new ScopeManager (); sm.Push ("Cat"); Assert.IsTrue (sm.CurrentScope () == "g.Cat"); } [Test] public void ScopeManagerPushTwoScopeLevels () { sm = new ScopeManager (); sm.Push ("Cat"); sm.Push ("Dog"); Assert.IsTrue (sm.CurrentScope () == "g.Cat.Dog"); } [Test] [ExpectedException(typeof(Exception))] public void ScopeManagerPopTwoScopeLevelException () { sm = new ScopeManager (); sm.Push ("Cat"); sm.Pop (); sm.Pop (); } [Test] public void ScopeManagerPopOneLevel () { sm = new ScopeManager (); sm.Push ("Cat"); sm.Pop (); Assert.IsTrue (sm.CurrentScope () == "g"); } [Test] public void ScopeManagerPopTwoLevel () { sm = new ScopeManager (); sm.Push ("Cat"); sm.Push ("Dog"); sm.Pop (); sm.Pop (); Assert.IsTrue (sm.CurrentScope () == "g"); } } }
// Author(s): Aaron Holloway // Fall 2018 // Last Modified: 11/18/2018 using System.Collections; using System.Collections.Generic; using UnityEngine; // Monitors Keyboard Events and resulting behavior. public class KeyboardInputManager : MonoBehaviour { public DirectRCControl_TCP rc; void Update () { // As Up is Pressed if (Input.GetKeyDown(KeyCode.UpArrow)) { if (Input.GetKey(KeyCode.LeftArrow) && !(Input.GetKey(KeyCode.RightArrow) || Input.GetKey(KeyCode.DownArrow))) { rc.forwardLeftAction(); } else if (Input.GetKey(KeyCode.RightArrow) && !(Input.GetKey(KeyCode.LeftArrow) || Input.GetKey(KeyCode.DownArrow))) { rc.forwardRightAction(); } else if (!(Input.GetKey(KeyCode.LeftArrow) || Input.GetKey(KeyCode.RightArrow) || Input.GetKey(KeyCode.DownArrow))) { rc.forwardAction(); } else { rc.stopAction(); } } // As Up is Released if (Input.GetKeyUp(KeyCode.UpArrow)) { if ((Input.GetKey(KeyCode.LeftArrow) && (Input.GetKey(KeyCode.DownArrow))) && !Input.GetKey(KeyCode.RightArrow)) { rc.backLeftAction(); } else if (Input.GetKey(KeyCode.LeftArrow) && !(Input.GetKey(KeyCode.RightArrow) || Input.GetKey(KeyCode.DownArrow))) { rc.leftAction(); } else if ((Input.GetKey(KeyCode.RightArrow) && (Input.GetKey(KeyCode.DownArrow))) && !Input.GetKey(KeyCode.LeftArrow)) { rc.backRightAction(); } else if (Input.GetKey(KeyCode.RightArrow) && !(Input.GetKey(KeyCode.LeftArrow) || Input.GetKey(KeyCode.DownArrow))) { rc.rightAction(); } else if (Input.GetKey(KeyCode.DownArrow) && !(Input.GetKey(KeyCode.LeftArrow) || Input.GetKey(KeyCode.RightArrow))) { rc.backAction(); } else { rc.stopAction(); } } // As Down is Pressed if (Input.GetKeyDown(KeyCode.DownArrow)) { if (Input.GetKey(KeyCode.LeftArrow) && !(Input.GetKey(KeyCode.RightArrow) || Input.GetKey(KeyCode.UpArrow))) { rc.backLeftAction(); } else if (Input.GetKey(KeyCode.RightArrow) && !(Input.GetKey(KeyCode.LeftArrow) || Input.GetKey(KeyCode.UpArrow))) { rc.backRightAction(); } else if (!(Input.GetKey(KeyCode.LeftArrow) || Input.GetKey(KeyCode.RightArrow) || Input.GetKey(KeyCode.UpArrow))) { rc.backAction(); } else { rc.stopAction(); } } // As Down is Released if (Input.GetKeyUp(KeyCode.DownArrow)) { if ((Input.GetKey(KeyCode.LeftArrow) && (Input.GetKey(KeyCode.UpArrow))) && !Input.GetKey(KeyCode.RightArrow)) { rc.forwardLeftAction(); } else if (Input.GetKey(KeyCode.LeftArrow) && !(Input.GetKey(KeyCode.RightArrow) || Input.GetKey(KeyCode.UpArrow))) { rc.leftAction(); } else if ((Input.GetKey(KeyCode.RightArrow) && (Input.GetKey(KeyCode.UpArrow))) && !Input.GetKey(KeyCode.LeftArrow)) { rc.forwardRightAction(); } else if (Input.GetKey(KeyCode.RightArrow) && !(Input.GetKey(KeyCode.LeftArrow) || Input.GetKey(KeyCode.UpArrow))) { rc.rightAction(); } else if (Input.GetKey(KeyCode.UpArrow) && !(Input.GetKey(KeyCode.LeftArrow) || Input.GetKey(KeyCode.RightArrow))) { rc.forwardAction(); } else { rc.stopAction(); } } // As Left is Pressed if (Input.GetKeyDown(KeyCode.LeftArrow)) { if (Input.GetKey(KeyCode.UpArrow) && !(Input.GetKey(KeyCode.DownArrow) || Input.GetKey(KeyCode.RightArrow))) { rc.forwardLeftAction(); } else if (Input.GetKey(KeyCode.DownArrow) && !(Input.GetKey(KeyCode.UpArrow) || Input.GetKey(KeyCode.RightArrow))) { rc.backLeftAction(); } else if (!(Input.GetKey(KeyCode.UpArrow) || Input.GetKey(KeyCode.DownArrow) || Input.GetKey(KeyCode.RightArrow))) { rc.leftAction(); } else { rc.stopAction(); } } // As Left is Released if (Input.GetKeyUp(KeyCode.LeftArrow)) { if ((Input.GetKey(KeyCode.UpArrow) && (Input.GetKey(KeyCode.RightArrow))) && !Input.GetKey(KeyCode.DownArrow)) { rc.forwardRightAction(); } else if (Input.GetKey(KeyCode.UpArrow) && !(Input.GetKey(KeyCode.DownArrow) || Input.GetKey(KeyCode.RightArrow))) { rc.forwardAction(); } else if ((Input.GetKey(KeyCode.DownArrow) && (Input.GetKey(KeyCode.RightArrow))) && !Input.GetKey(KeyCode.UpArrow)) { rc.backRightAction(); } else if (Input.GetKey(KeyCode.DownArrow) && !(Input.GetKey(KeyCode.UpArrow) || Input.GetKey(KeyCode.RightArrow))) { rc.backAction(); } else if (Input.GetKey(KeyCode.RightArrow) && !(Input.GetKey(KeyCode.UpArrow) || Input.GetKey(KeyCode.DownArrow))) { rc.rightAction(); } else { rc.stopAction(); } } // As Right is Pressed if (Input.GetKeyDown(KeyCode.RightArrow)) { if (Input.GetKey(KeyCode.UpArrow) && !(Input.GetKey(KeyCode.DownArrow) || Input.GetKey(KeyCode.LeftArrow))) { rc.forwardRightAction(); } else if (Input.GetKey(KeyCode.DownArrow) && !(Input.GetKey(KeyCode.UpArrow) || Input.GetKey(KeyCode.LeftArrow))) { rc.backRightAction(); } else if (!(Input.GetKey(KeyCode.UpArrow) || Input.GetKey(KeyCode.DownArrow) || Input.GetKey(KeyCode.LeftArrow))) { rc.rightAction(); } else { rc.stopAction(); } } // As Right is Released if (Input.GetKeyUp(KeyCode.RightArrow)) { if ((Input.GetKey(KeyCode.UpArrow) && (Input.GetKey(KeyCode.LeftArrow))) && !Input.GetKey(KeyCode.DownArrow)) { rc.forwardLeftAction(); } else if (Input.GetKey(KeyCode.UpArrow) && !(Input.GetKey(KeyCode.DownArrow) || Input.GetKey(KeyCode.LeftArrow))) { rc.forwardAction(); } else if ((Input.GetKey(KeyCode.DownArrow) && (Input.GetKey(KeyCode.LeftArrow))) && !Input.GetKey(KeyCode.UpArrow)) { rc.backLeftAction(); } else if (Input.GetKey(KeyCode.DownArrow) && !(Input.GetKey(KeyCode.UpArrow) || Input.GetKey(KeyCode.LeftArrow))) { rc.backAction(); } else if (Input.GetKey(KeyCode.LeftArrow) && !(Input.GetKey(KeyCode.UpArrow) || Input.GetKey(KeyCode.DownArrow))) { rc.leftAction(); } else { rc.stopAction(); } } // As Shift is Pressed if (Input.GetKeyDown(KeyCode.LeftShift)) { rc.setHighGear(); } // As Shift is Released if (Input.GetKeyUp(KeyCode.LeftShift)) { rc.unsetHighGear(); } // As E is Pressed if (Input.GetKeyDown(KeyCode.E)) { rc.exitAction(); } } }
using Discovery.Core.Model; using Prism.Mvvm; using System; using System.Collections.Generic; using System.Text; namespace Discovery.Core.Models { public class PostComment : BindableBase { /// <summary> /// 评论 ID /// </summary> private int _id; public int ID { get => _id; set => SetProperty(ref _id, value); } /// <summary> /// 帖子ID /// </summary> private int _postID; public int PostID { get => _postID; set => SetProperty(ref _postID, value); } /// <summary> /// 评论内容 /// </summary> private string _comment; public string Comment { get => _comment; set => SetProperty(ref _comment, value); } /// <summary> /// 评论者 /// </summary> private Discoverer _author; public Discoverer Author { get => _author; set => SetProperty(ref _author, value); } /// <summary> /// 评论时间 /// </summary> private DateTime _creationTime; public DateTime CreationTime { get => _creationTime; set => SetProperty(ref _creationTime, value); } } }
using filter.framework.utility.XPort; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace filter.data.model { public class ExportShopsModel { [ExcelColumnName(ColumnName = "店铺名")] public string Name { get; set; } [ExcelColumnName(ColumnName = "联系人")] public string Contact { get; set; } [ExcelColumnName(ColumnName = "联系方式")] public string Mobile { get; set; } [ExcelColumnName(ColumnName = "业务员")] public string SalemanName { get; set; } } }
using System; namespace IMDB.Api.Models.ResponseDto { public class User : BaseModel { public string FirstName { get; set; } public string LastName { get; set; } public string Email { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; using static Conditions; public class ItemHover : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler { public Item item; public int id; public bool condition1; public bool condition2; void Start() { Conditions.conditions[id] = 1; if (item) { if (!item.alt1) item.alt1 = condition1; if (!item.alt2) item.alt2 = condition2; } } public void OnPointerEnter(PointerEventData eventData) { transform.GetChild(0).gameObject.SetActive(true); } public void OnPointerExit(PointerEventData eventData) { transform.GetChild(0).gameObject.SetActive(false); } }
using System; using System.Collections.Generic; using System.Linq; using System.IO; using X360.STFS; using System.Text.RegularExpressions; using RocksmithToolkitLib.Extensions; using RocksmithToolkitLib.DLCPackage.Manifest.Tone; using RocksmithToolkitLib.DLCPackage.Manifest; using RocksmithToolkitLib.PSARC; using System.Xml.Serialization; using RocksmithToolkitLib.DLCPackage.AggregateGraph; using RocksmithToolkitLib.Ogg; namespace RocksmithToolkitLib.DLCPackage { public class DLCPackageData : IDisposable { public GameVersion GameVersion; public bool Pc { get; set; } public bool Mac { get; set; } public bool XBox360 { get; set; } public bool PS3 { get; set; } public double? SongLength { get; set; } public string AppId { get; set; } public string Name { get; set; } public SongInfo SongInfo { get; set; } public bool IsOgg { get; set; } public Stream Audio { get { if (_Audio == null) ParseAudioFiles(); return _Audio; } set { _Audio = value; } } public Stream AudioPreview{ get { if (_Audio == null) ParseAudioFiles(); return _Audio; } set { _Audio = value; } } public float Volume { get; set; } public int AverageTempo { get; set; } public PackageMagic SignatureType { get; set; } public string PackageVersion { get; set; } public List<Manifest.ChordTemplate> Chords { get; set; } public Platform Platform { get; set;} public AggregateGraph2014 AggregateGraph { get; set; } private List<XBox360License> xbox360Licenses = null; public List<XBox360License> XBox360Licenses { get { if (xbox360Licenses == null) { xbox360Licenses = new List<XBox360License>(); return xbox360Licenses; } else return xbox360Licenses; } set { xbox360Licenses = value; } } #region RS1 only public List<Tone.Tone> Tones { get; set; } #endregion #region RS2014 only public float? PreviewVolume { get; set; } private PSARC.PSARC Archive; private Dictionary<object, Entry> _entries = new Dictionary<object, Entry>(); private List<Arrangement> _Arrangements; private List<AlbumArt> _AlbumArt; private Stream _Audio; private Stream _AudioPreview; public DLCPackageData() { } public DLCPackageData(string filename, Platform targetPlatform = null) { this.BasePath = filename; this.Archive = new PSARC.PSARC(); using (var fs = File.OpenRead(this.BasePath)) this.Archive.Read(fs); this.SignatureType = PackageMagic.CON; this.Platform = targetPlatform ?? Packer.TryGetPlatformByEndName(filename); var aggregate = this.Archive.Entries.Single(e => e.Name.EndsWith("aggregategraph.nt")); this.AggregateGraph = AggregateGraph2014.LoadFromFile(aggregate.Data); _entries[this.AggregateGraph] = aggregate; var appid = this.Archive.Entries.Single(e => e.Name.Equals("/appid.appid")); using (var r = new StreamReader(appid.Data)) this.AppId = r.ReadToEnd(); _entries[this.AppId] = appid; ParseBaseData(); } public List<Arrangement> Arrangements { get { if (this._Arrangements == null) { this._Arrangements = new List<Arrangement>(); foreach (var json in this.AggregateGraph.JsonDB) { var jsonEntry = Archive.Entries.Single(e => e.Name.Equals(json.RelPath)); var attr = Manifest2014<Attributes2014>.LoadFromFile(jsonEntry.Data).Entries.ToArray()[0].Value.ToArray()[0].Value; var sngFile = AggregateGraph.MusicgameSong.Where(s => s.Name.Equals(json.Name)) .Concat(AggregateGraph.SongXml.Where(x => x.Name.Equals(json.Name))) .First(); var sngEntry = Archive.Entries.Single(e => e.Name.Equals(sngFile.RelPath)); var arr = Arrangement.Read(attr, Platform, sngFile.LLID, sngEntry.Name, sngEntry.Data); this._entries[arr] = jsonEntry; this._entries[arr.Sng2014] = sngEntry; this._Arrangements.Add(arr); } } return this._Arrangements; } } public List<Tone2014> TonesRS2014 { get { return this.Arrangements.SelectMany(a => a.Tones).Distinct(new PropertyComparer<Tone2014>("Key")).ToList(); } } public List<AlbumArt> AlbumArt { get { if (_AlbumArt == null) { _AlbumArt = AggregateGraph.ImageArt.Select(ia => new AlbumArt(ia.getEntry(Archive).Data)).ToList(); } return _AlbumArt; } } private string _AudioFile; public string TempAudioFile { get { if (_AudioFile == null) { _AudioFile = GeneralExtensions.GetTempFileName(".ogg"); using (var fs = File.OpenWrite(_AudioFile)) Audio.CopyTo(fs); } return _AudioFile; } } private void ParseAudioFiles() { var oggFiles = Archive.Entries.Where(e => e.Name.EndsWith(".ogg")).OrderByDescending(e => e.Data.Length); if (oggFiles.Count() > 0) { Audio = oggFiles.First().Data; if (oggFiles.Count() > 1) _AudioPreview = oggFiles.Last().Data; return; } var wemFiles = Archive.Entries.Where(e => e.Name.EndsWith(".wem")).OrderByDescending(e => e.Data.Length); if (oggFiles.Count() > 0) { _Audio = OggFile.ConvertOgg(oggFiles.First().Data); if (oggFiles.Count() > 1) _AudioPreview = OggFile.ConvertOgg(oggFiles.Last().Data); return; } throw new InvalidDataException("Audio files not found."); } private void ParseBaseData () { var attr = AggregateGraph.JsonDB.Select(j => j.getManifest(Archive)).First(m => m.SongName != null); this.Name = attr.DLCKey; this.SongInfo = new SongInfo (); this.SongInfo.SongDisplayName = attr.SongName; this.SongInfo.SongDisplayNameSort = attr.SongNameSort; this.SongInfo.Album = attr.AlbumName; this.SongInfo.AlbumSort = attr.AlbumNameSort; this.SongInfo.SongYear = attr.SongYear ?? 0; this.SongInfo.Artist = attr.ArtistName; this.SongInfo.ArtistSort = attr.ArtistNameSort; this.SongInfo.AverageTempo = (int)attr.SongAverageTempo; // FIXME these should aggregate this.Volume = attr.SongVolume; this.PreviewVolume = (attr.PreviewVolume != null) ? (float)attr.PreviewVolume : this.Volume; this.Difficulty = attr.SongDifficulty; this.Chords = attr.ChordTemplates; this.SongLength = attr.SongLength ?? 0; } public IDictionary<string, Entry> OtherEntries { get { return Archive.Entries.ToDictionary(e => e.Name, e => e); } } // TODO -- filter to unrecognized ones #endregion #region RS2014 Inlay only [XmlIgnore] public InlayData Inlay { get; set; } #endregion // needs to be called after all packages for platforms are created public void CleanCache() { if (Arrangements != null) foreach (var a in Arrangements) a.CleanCache(); if (_AudioFile != null) { File.Delete(_AudioFile); _AudioFile = null; } } public void Dispose() { CleanCache(); } public static string DoLikeProject(string unpackedDir) { //Get name for new folder name string outdir = ""; string EOF = "EOF"; string KIT = "Toolkit"; string SongName = "SongName"; var jsonFiles = Directory.GetFiles(unpackedDir, "*.json", SearchOption.AllDirectories); var attr = Manifest2014<Attributes2014>.LoadFromFile(jsonFiles[0]).Entries.ToArray()[0].Value.ToArray()[0].Value; //Create dir sruct SongName = attr.FullName.Split('_')[0]; outdir = Path.Combine(Path.GetDirectoryName(unpackedDir), String.Format("{0}_{1}", attr.ArtistNameSort.GetValidName(false), attr.SongNameSort.GetValidName(false))); if (Directory.Exists(outdir)) outdir += "_" + DateTime.Now.ToString("yyyy-MM-dd"); Directory.CreateDirectory(outdir); Directory.CreateDirectory(Path.Combine(outdir, EOF)); Directory.CreateDirectory(Path.Combine(outdir, KIT)); foreach (var json in jsonFiles) { var atr = Manifest2014<Attributes2014>.LoadFromFile(json).Entries.ToArray()[0].Value.ToArray()[0].Value; var Name = atr.SongXml.Split(':')[3]; var xmlFile = Directory.GetFiles(unpackedDir, Name + ".xml", SearchOption.AllDirectories)[0]; //Move all pair JSON\XML File.Move(json, Path.Combine(outdir, KIT, Name + ".json")); File.Move(xmlFile, Path.Combine(outdir, EOF, Name + ".xml")); } //Move art_256.dds to KIT folder var ArtFile = Directory.GetFiles(unpackedDir, "*_256.dds", SearchOption.AllDirectories); if (ArtFile.Length > 0) File.Move(ArtFile[0], Path.Combine(outdir, KIT, Path.GetFileName(ArtFile[0]))); //Move ogg to EOF folder + rename var OggFiles = Directory.GetFiles(unpackedDir, "*_fixed.ogg", SearchOption.AllDirectories); if(OggFiles.Count() <= 0) throw new InvalidDataException("Audio files not found."); var a0 = new FileInfo(OggFiles[0]); FileInfo b0 = null; if (OggFiles.Count() == 2){ b0 = new FileInfo(OggFiles[1]); if (a0.Length > b0.Length) { File.Move(a0.FullName, Path.Combine(outdir, EOF, SongName + ".ogg")); File.Move(b0.FullName, Path.Combine(outdir, EOF, SongName + "_preview.ogg")); } else { File.Move(b0.FullName, Path.Combine(outdir, EOF, SongName + ".ogg")); File.Move(a0.FullName, Path.Combine(outdir, EOF, SongName + "_preview.ogg")); } } else File.Move(a0.FullName, Path.Combine(outdir, EOF, SongName + ".ogg")); //Move wem to KIT folder + rename var WemFiles = Directory.GetFiles(unpackedDir, "*.wem", SearchOption.AllDirectories); if(WemFiles.Count() <= 0) throw new InvalidDataException("Audio files not found."); var a1 = new FileInfo(WemFiles[0]); FileInfo b1 = null; if (WemFiles.Count() == 2){ b1 = new FileInfo(WemFiles[1]); if (a1.Length > b1.Length) { File.Move(a1.FullName, Path.Combine(outdir, KIT, SongName + ".wem")); File.Move(b1.FullName, Path.Combine(outdir, KIT, SongName + "_preview.wem")); } else { File.Move(b1.FullName, Path.Combine(outdir, KIT, SongName + ".wem")); File.Move(a1.FullName, Path.Combine(outdir, KIT, SongName + "_preview.wem")); } } else File.Move(a1.FullName, Path.Combine(outdir, KIT, SongName + ".wem")); //Move Appid for correct template generation. var appidFile = Directory.GetFiles(unpackedDir, "*.appid", SearchOption.AllDirectories); if (appidFile.Length > 0) File.Move(appidFile[0], Path.Combine(outdir, KIT, Path.GetFileName(appidFile[0]))); //Remove old folder DirectoryExtension.SafeDelete(unpackedDir); return outdir; } public double? Difficulty { get; set; } public Stream Showlights { get { var showlights = this.Archive.Entries.SingleOrDefault(e => e.Name.Equals(AggregateGraph.ShowlightXml.RelPath)); if (showlights == null) return null; _entries[showlights.Data] = showlights; return showlights.Data; } } public Stream LyricsTex { get { var lyrics = this.Archive.Entries.SingleOrDefault(e => e.Name.Equals(AggregateGraph.LyricsTex.RelPath)); if (lyrics == null) return null; _entries[lyrics.Data] = lyrics; return lyrics.Data; } } public string BasePath { get; private set; } public string Digest { get { return Archive.Digest; } } } public class DDSConvertedFile { public int sizeX { get; set; } public int sizeY { get; set; } public string sourceFile { get; set; } public string destinationFile { get; set; } } public class InlayData { public string DLCSixName { get; set; } public string InlayPath { get; set; } public string IconPath { get; set; } public Guid Id { get; set; } public bool Frets24 { get; set; } public bool Colored { get; set; } public InlayData() { Id = IdGenerator.Guid(); } } public static class HelperExtensions { public static Entry getEntry(this GraphItem gi, PSARC.PSARC archive) { return archive.Entries.Single(e => e.Name.Equals(gi.RelPath)); } public static Attributes2014 getManifest(this GraphItem jsonItem, PSARC.PSARC archive) { return Manifest2014<Attributes2014>.LoadFromFile(jsonItem.getEntry(archive).Data).Entries.ToArray()[0].Value.ToArray()[0].Value; } } }
using System; using System.Collections.Generic; using System.Net.Http; using System.Text; using System.Threading.Tasks; using Degree.Models; using Degree.Services.Social.Twitter.TweetAuth; using Degree.Services.Utils; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.Linq; namespace Degree.Services.Social.Twitter { public class TwitterRest { public static async Task DownloadWCFTweets() { var auth = await TwitterAuthorize.AccessToken(); await GetTweets(auth, WCFTweetRequest); } private static async Task GetTweets(TokenAuth auth, TweetRequest tweetRequest) { try { using (var handler = new HttpClientHandler()) { handler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return true; }; using (var httpClient = new HttpClient(handler)) using (var client = new HttpClient(handler)) { string baseAddress = "https://api.twitter.com/1.1/tweets/search/30day/analysis.json"; client.DefaultRequestHeaders.Add("Authorization", $"Bearer {auth.AccessToken}"); int index = 1; do { Console.WriteLine($"Page: {index++}"); var json = JsonConvert.SerializeObject(tweetRequest); var stringContent = new StringContent(json); var request = client.PostAsync(baseAddress, stringContent).Result; var content = await request.Content.ReadAsStringAsync(); await FileHelper.WriteFile($"wcf-{index}.json", content); var result = JsonConvert.DeserializeObject<TweetResult> ( content, new IsoDateTimeConverter { DateTimeFormat = "ddd MMM dd HH:mm:ss K yyyy", Culture = new System.Globalization.CultureInfo("en-US") } ); Console.WriteLine($"Found: {result.Results.Count}"); tweetRequest.Next = result.Next; result.Results.ForEach(x => { // Normalize ID, for store. if (x.QuotedStatusId == 0) x.QuotedStatusId = null; if (x.RetweetedStatusId == 0) x.RetweetedStatusId = null; if (x.ExtendedTweet != null) x.ExtendedTweet.TweetRawId = x.Id; }); } while (!string.IsNullOrEmpty(tweetRequest.Next)); } } } catch (Exception ex) { var message = ex.Message; } } private static TweetRequest WCFTweetRequest { get { var tweetRequest = new TweetRequest(); tweetRequest.MaxResults = 500; tweetRequest.AddFromDate(new DateTime(2019, 3, 29, 0, 0, 0)); tweetRequest.AddToDate(new DateTime(2019, 3, 31, 23, 59, 59)); tweetRequest.Query = TweetRequest .QueryBuilder .InitQuery() .Hashtag("#Adozionigay") .Or() .Hashtag("#Prolgbt") .Or() .Hashtag("#Famigliatradizionale") .Or() .Hashtag("#cirinnà") .Or() .Hashtag("famigliaarcobaleno") .Or() .Hashtag("#Congressodellefamiglie") .Or() .Hashtag("#Congressomondialedellefamiglie") .Or() .Hashtag("#WCFVerona") .Or() .Hashtag("#NoWCFVerona") .Or() .Hashtag("#No194") .Or() .Hashtag("#noeutonasia") .Or() .Hashtag("#uteroinaffitto") .Or() .Hashtag("#NoDDLPillon") .Or() .Hashtag("#Pillon") .Or() .Hashtag("#Pilloff") .Or() .Hashtag("#Spadafora") .Or() .Hashtag("#Affidocondiviso") .Or() .Hashtag("#Affidoparitario") .Build(); return tweetRequest; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using WF.SDK.Fax; using WF.SDK.Models; namespace WF.SDK.Fax { public static class FaxInterface { //Pass through the value on the Raw Interface public static string RestUrlTemplate { get { return Internal.FaxInterfaceRaw.RestUrlTemplate; } set { Internal.FaxInterfaceRaw.RestUrlTemplate = value; } } static FaxInterface() { //You can configure this statically here and compile, or set the URL template above from another source such as confguration //FaxInterface.RestUrlTemplate = System.Configuration.ConfigurationManager.AppSettings["APIEncoding"]; //From config? //FaxInterface.RestUrlTemplate = "https://api2.westfax.com/REST/{0}/json"; //Statically? //Encoding can be json, json2, xml. } #region Ping public static ApiResult<string> Ping(string pingStr = "") { var rstr = Internal.FaxInterfaceRaw.Ping(pingStr); var ret = WF.SDK.Common.JSONSerializerHelper.Deserialize<ApiResult<string>>(rstr); return ret; } #endregion #region Authenticate public static ApiResult<string> Authenticate(string username, string password, Guid? productId = null) { var rstr = Internal.FaxInterfaceRaw.Authenticate(username, password, productId); var ret = WF.SDK.Common.JSONSerializerHelper.Deserialize<ApiResult<string>>(rstr); return ret; } #endregion #region GetProductList /// <summary> /// ProductType can be FaxForward, BroadcastFax, FaxRelay /// </summary> public static ApiResult<List<Product>> GetProductList(string username, string password) { var rstr = Internal.FaxInterfaceRaw.GetProductList(username, password); var result = WF.SDK.Common.JSONSerializerHelper.Deserialize<ApiResult<List<Models.Internal.ProductItem>>>(rstr); var ret = new ApiResult<List<Product>>(); if (result.Success) { ret.Success = true; ret.ErrorString = ""; ret.Result = result.Result.Select(i => new Product(i)).ToList(); } else { ret.Success = false; ret.ErrorString = result.ErrorString; ret.Result = new List<Product>(); } return ret; } #endregion #region GetF2EProductList /// /// <summary> /// ProductType can be FaxForward only /// </summary> public static ApiResult<List<Product>> GetF2EProductList(string username, string password) { var rstr = Internal.FaxInterfaceRaw.GetF2EProductList(username, password); var result = WF.SDK.Common.JSONSerializerHelper.Deserialize<ApiResult<List<Models.Internal.F2EProductItem>>>(rstr); var ret = new ApiResult<List<Product>>(); if (result.Success) { ret.Success = true; ret.ErrorString = ""; ret.Result = result.Result.Select(i => new Product(i)).ToList(); } else { ret.Success = false; ret.ErrorString = result.ErrorString; ret.Result = new List<Product>(); } return ret; } #endregion #region GetF2EProductDetail /// <summary> /// ProductType can be FaxForward only /// </summary> public static ApiResult<Product> GetF2EProductDetail(string username, string password, Guid productId) { var rstr = Internal.FaxInterfaceRaw.GetF2EProductDetail(username, password, productId); var result = WF.SDK.Common.JSONSerializerHelper.Deserialize<ApiResult<Models.Internal.F2EProductItem>>(rstr); var ret = new ApiResult<Product>(); if (result.Success) { ret.Success = true; ret.ErrorString = ""; ret.Result = new Product(result.Result); } else { ret.Success = false; ret.ErrorString = result.ErrorString; ret.Result = null; } return ret; } #endregion #region GetAccountInfo /// <summary> /// ProductType can be FaxForward, BroadcastFax, FaxRelay. /// </summary> public static ApiResult<AccountInfo> GetAccountInfo(string username, string password, Guid? productId = null) { var rstr = Internal.FaxInterfaceRaw.GetAccountInfo(username, password, productId); var result = WF.SDK.Common.JSONSerializerHelper.Deserialize<ApiResult<Models.Internal.AccountItem>>(rstr); var ret = new ApiResult<AccountInfo>(); if (result.Success) { ret.Success = true; ret.ErrorString = ""; ret.Result = AccountInfoExtensions.ToAccountInfo(result.Result); } else { ret.Success = false; ret.ErrorString = result.ErrorString; ret.Result = null; } return ret; } #endregion #region GetUserProfile /// <summary> /// ProductType can be FaxForward, BroadcastFax, FaxRelay /// </summary> public static ApiResult<User> GetUserProfile(string username, string password, Guid? productId = null) { var rstr = Internal.FaxInterfaceRaw.GetUserProfile(username, password, productId); var result = WF.SDK.Common.JSONSerializerHelper.Deserialize<ApiResult<Models.Internal.UserItem>>(rstr); var ret = new ApiResult<User>(); if (result.Success) { ret.Success = true; ret.ErrorString = ""; ret.Result = new User(result.Result); } else { ret.Success = false; ret.ErrorString = result.ErrorString; ret.Result = null; } return ret; } #endregion #region GetLoginInfo public static ApiResult<LoginInfo> GetLoginInfo(string username, string password) { var rstr = Internal.FaxInterfaceRaw.GetLoginInfo(username, password); var result = WF.SDK.Common.JSONSerializerHelper.Deserialize<ApiResult<Models.Internal.LoginInfoItem>>(rstr); var ret = new ApiResult<LoginInfo>(); if (result.Success) { ret.Success = true; ret.ErrorString = ""; ret.Result = new LoginInfo(result.Result); } else { ret.Success = false; ret.ErrorString = result.ErrorString; ret.Result = null; } return ret; } #endregion #region GetContactList /// <summary> /// Retrieves a list of the contacts that are available to the user, based on user role. /// Contacts appropriate for the product will be filtered if the ProductId is given. /// </summary> public static ApiResult<List<Models.Contact>> GetContactList(string username, string password, Guid? productId = null) { var rstr = Internal.FaxInterfaceRaw.GetContactList(username, password, productId); var result = WF.SDK.Common.JSONSerializerHelper.Deserialize<ApiResult<List<Models.Internal.ContactItem>>>(rstr); var ret = new ApiResult<List<Models.Contact>>(); if (result.Success) { ret.Success = true; ret.ErrorString = ""; ret.Result = result.Result.Select(i => new Models.Contact(i)).ToList(); } else { ret.Success = false; ret.ErrorString = result.ErrorString; ret.Result = new List<Models.Contact>(); } return ret; } #endregion #region GetFaxIds (Inbound and Outbound) /// <summary> /// Gets all the faxes. /// </summary> public static ApiResult<List<IFaxId>> GetFaxIds(string username, string password, Guid productId) { var rstr = Internal.FaxInterfaceRaw.GetFaxIds(username, password, productId); var result = WF.SDK.Common.JSONSerializerHelper.Deserialize<ApiResult<List<Models.Internal.FaxIdItem>>>(rstr); var ret = new ApiResult<List<IFaxId>>(); if (result.Success) { ret.Success = true; ret.ErrorString = ""; ret.Result = result.Result.Select(i => (IFaxId)(new FaxDesc(i))).ToList(); } else { ret.Success = false; ret.ErrorString = result.ErrorString; ret.Result = new List<IFaxId>(); } return ret; } /// <summary> /// Get The inbound Faxes. /// </summary> public static ApiResult<List<IFaxId>> GetInboundFaxIds(string username, string password, Guid productId) { var rstr = Internal.FaxInterfaceRaw.GetInboundFaxIds(username, password, productId); var result = WF.SDK.Common.JSONSerializerHelper.Deserialize<ApiResult<List<Models.Internal.FaxIdItem>>>(rstr); var ret = new ApiResult<List<IFaxId>>(); if (result.Success) { ret.Success = true; ret.ErrorString = ""; ret.Result = result.Result.Select(i => (IFaxId)(new FaxDesc(i))).ToList(); } else { ret.Success = false; ret.ErrorString = result.ErrorString; ret.Result = new List<IFaxId>(); } return ret; } /// <summary> /// Get The outbound Faxes. /// </summary> public static ApiResult<List<IFaxId>> GetOutboundFaxIds(string username, string password, Guid productId) { var rstr = Internal.FaxInterfaceRaw.GetOutboundFaxIds(username, password, productId); var result = WF.SDK.Common.JSONSerializerHelper.Deserialize<ApiResult<List<Models.Internal.FaxIdItem>>>(rstr); var ret = new ApiResult<List<IFaxId>>(); if (result.Success) { ret.Success = true; ret.ErrorString = ""; ret.Result = result.Result.Select(i => (IFaxId)(new FaxDesc(i))).ToList(); } else { ret.Success = false; ret.ErrorString = result.ErrorString; ret.Result = new List<IFaxId>(); } return ret; } #endregion #region GetFaxDescriptions (Inbound and outbound) /// <summary> /// Get The inbound Faxes /// </summary> public static ApiResult<List<IFaxId>> GetInboundFaxDescriptions(string username, string password, Guid productId) { var rstr = Internal.FaxInterfaceRaw.GetInboundFaxDescriptions(username, password, productId); var result = WF.SDK.Common.JSONSerializerHelper.Deserialize<ApiResult<List<Models.Internal.FaxDescItem>>>(rstr); var ret = new ApiResult<List<IFaxId>>(); if (result.Success) { ret.Success = true; ret.ErrorString = ""; ret.Result = result.Result.Select(i => (IFaxId)(new FaxDesc(i))).ToList(); } else { ret.Success = false; ret.ErrorString = result.ErrorString; ret.Result = new List<IFaxId>(); } return ret; } /// <summary> /// Get The outbound Faxes /// </summary> public static ApiResult<List<IFaxId>> GetOutboundFaxDescriptions(string username, string password, Guid productId) { var rstr = Internal.FaxInterfaceRaw.GetOutboundFaxDescriptions(username, password, productId); var result = WF.SDK.Common.JSONSerializerHelper.Deserialize<ApiResult<List<Models.Internal.FaxDescItem>>>(rstr); var ret = new ApiResult<List<IFaxId>>(); if (result.Success) { ret.Success = true; ret.ErrorString = ""; ret.Result = result.Result.Select(i => (IFaxId)(new FaxDesc(i))).ToList(); } else { ret.Success = false; ret.ErrorString = result.ErrorString; ret.Result = new List<IFaxId>(); } return ret; } /// <summary> /// Get the requested Faxes /// </summary> public static ApiResult<List<IFaxId>> GetFaxDescriptions(string username, string password, Guid productId, List<IFaxId> items) { var rstr = Internal.FaxInterfaceRaw.GetFaxDescriptions(username, password, productId, FaxDesc.ToFaxIdItemList(items)); var result = WF.SDK.Common.JSONSerializerHelper.Deserialize<ApiResult<List<Models.Internal.FaxDescItem>>>(rstr); var ret = new ApiResult<List<IFaxId>>(); if (result.Success) { ret.Success = true; ret.ErrorString = ""; try { ret.Result = result.Result.Select(i => (IFaxId)(new FaxDesc(i))).ToList(); } catch { ret.Result = new List<IFaxId>(); } } else { ret.Success = false; ret.ErrorString = result.ErrorString; ret.Result = new List<IFaxId>(); } return ret; } #endregion #region GetFaxDocuments /// <summary> /// Get the requested Faxes /// </summary> public static ApiResult<List<IFaxId>> GetFaxDocuments(string username, string password, Guid productId, List<IFaxId> items, FileFormat format = FileFormat.Pdf) { var rstr = Internal.FaxInterfaceRaw.GetFaxDocuments(username, password, productId, FaxDesc.ToFaxIdItemList(items), format.ToString().ToLower()); var result = WF.SDK.Common.JSONSerializerHelper.Deserialize<ApiResult<List<Models.Internal.FaxFileItem>>>(rstr); var ret = new ApiResult<List<IFaxId>>(); if (result.Success) { ret.Success = true; ret.ErrorString = ""; ret.Result = result.Result.Select(i => (IFaxId)(new FaxDesc(i))).ToList(); } else { ret.Success = false; ret.ErrorString = result.ErrorString; ret.Result = new List<IFaxId>(); } return ret; } #endregion #region GetProductsWithInboundFaxes /// <summary> /// Get the products that have faxes matching the given filter. Usually used to /// determine if there are faxes waiting for download, and what products may have them. /// </summary> public static ApiResult<List<Product>> GetProductsWithInboundFaxes(string username, string password, string filter = "None") { var rstr = Internal.FaxInterfaceRaw.GetProductsWithInboundFaxes(username, password, filter); var result = WF.SDK.Common.JSONSerializerHelper.Deserialize<ApiResult<List<Models.Internal.ProductItem>>>(rstr); var ret = new ApiResult<List<Product>>(); if (result.Success) { ret.Success = true; ret.ErrorString = result.ErrorString; ret.InfoString = result.InfoString; ret.Result = result.Result.Select(i => new Product(i)).ToList(); } else { ret.Success = false; ret.ErrorString = result.ErrorString; ret.InfoString = result.InfoString; ret.Result = new List<Product>(); } return ret; } #endregion #region SendFax /// <summary> /// Send a Fax now. /// Fax quality is Fine or Normal. /// </summary> public static ApiResult<string> SendFax(string username, string password, Guid productId, List<string> numbers, HttpFileCollection files, string csid, string ani, DateTime? startDate = null, string faxQuality = "Fine", string jobname = "", string header = "", string billingCode = "", string feedbackEmail = null, string callbackUrl = null, List<string> custKeys1 = null) { var rstr = Internal.FaxInterfaceRaw.SendFax(username, password, productId, numbers, files, csid, ani, startDate, faxQuality, jobname, header, billingCode, feedbackEmail, callbackUrl, custKeys1); var ret = WF.SDK.Common.JSONSerializerHelper.Deserialize<ApiResult<string>>(rstr); return ret; } /// <summary> /// Send a Fax now. /// Fax quality is Fine or Normal. /// </summary> public static ApiResult<string> SendFax(string username, string password, Guid productId, List<string> numbers, FileDetail file, string csid, string ani, DateTime? startDate = null, string faxQuality = "Fine", string jobname = "", string header = "", string billingCode = "", string feedbackEmail = null, string callbackUrl = null, List<string> custKeys1 = null) { var rstr = Internal.FaxInterfaceRaw.SendFax(username, password, productId, numbers, file.FileContents, file.Filename, csid, ani, startDate, faxQuality, jobname, header, billingCode, feedbackEmail, callbackUrl, custKeys1); var ret = WF.SDK.Common.JSONSerializerHelper.Deserialize<ApiResult<string>>(rstr); return ret; } /// <summary> /// Send a Fax now. /// Fax quality is Fine or Normal. /// </summary> public static ApiResult<string> SendFax(string username, string password, Guid productId, List<string> numbers, List<string> filePaths, string csid, string ani, DateTime? startDate = null, string faxQuality = "Fine", string jobname = "", string header = "", string billingCode = "", string feedbackEmail = null, string callbackUrl = null, List<string> custKeys1 = null) { var rstr = Internal.FaxInterfaceRaw.SendFax(username, password, productId, numbers, filePaths, csid, ani, startDate, faxQuality, jobname, header, billingCode, feedbackEmail, callbackUrl, custKeys1); var ret = WF.SDK.Common.JSONSerializerHelper.Deserialize<ApiResult<string>>(rstr); return ret; } #endregion #region MarkAsRead /// <summary> /// ProductType can be FaxForward, BroadcastFax, FaxRelay /// Must have a contact object defined. /// </summary> public static ApiResult<bool> MarkAsRead(string username, string password, Guid productId, List<IFaxId> items) { var rstr = Internal.FaxInterfaceRaw.ChangeFaxFilterValue(username, password, productId, FaxDesc.ToFaxIdItemList(items), "Retrieved"); var ret = WF.SDK.Common.JSONSerializerHelper.Deserialize<ApiResult<bool>>(rstr); return ret; } #endregion #region MarkAsUnRead /// <summary> /// ProductType can be FaxForward, BroadcastFax, FaxRelay /// Must have a contact object defined. /// </summary> public static ApiResult<bool> MarkAsUnRead(string username, string password, Guid productId, List<IFaxId> items) { var rstr = Internal.FaxInterfaceRaw.ChangeFaxFilterValue(username, password, productId, FaxDesc.ToFaxIdItemList(items), "None"); var ret = WF.SDK.Common.JSONSerializerHelper.Deserialize<ApiResult<bool>>(rstr); return ret; } #endregion #region MarkAsDeleted /// <summary> /// ProductType can be FaxForward, BroadcastFax, FaxRelay /// Must have a contact object defined. /// </summary> public static ApiResult<bool> MarkAsDeleted(string username, string password, Guid productId, List<IFaxId> items) { var rstr = Internal.FaxInterfaceRaw.ChangeFaxFilterValue(username, password, productId, FaxDesc.ToFaxIdItemList(items), "Removed"); var ret = WF.SDK.Common.JSONSerializerHelper.Deserialize<ApiResult<bool>>(rstr); return ret; } #endregion #region SendFaxAsEmail /// <summary> /// Send the fax as an email. Works on inbound and outbound. /// </summary> public static ApiResult<bool> SendFaxAsEmail(string username, string password, Guid productId, IFaxId item, string emailAddress) { var rstr = Internal.FaxInterfaceRaw.SendFaxAsEmail(username, password, productId, FaxDesc.ToFaxIdItem(item), emailAddress); var ret = WF.SDK.Common.JSONSerializerHelper.Deserialize<ApiResult<bool>>(rstr); return ret; } #endregion #region ResendFaxNotification /// <summary> /// Send the fax as an email. Works on inbound only. /// </summary> public static ApiResult<bool> ResendFaxNotification(string username, string password, Guid productId, IFaxId item) { var rstr = Internal.FaxInterfaceRaw.ResendFaxNotification(username, password, productId, FaxDesc.ToFaxIdItem(item)); var ret = WF.SDK.Common.JSONSerializerHelper.Deserialize<ApiResult<bool>>(rstr); return ret; } #endregion #region ConvertToFaxDocument /// <summary> /// Converts files to Fax files. /// </summary> public static ApiResult<FaxFileInfo> ConvertToFaxDocument(string username, string password, HttpFileCollection files, string faxQuality = "Fine", Models.FileFormat format = FileFormat.Tiff) { var rstr = Internal.FaxInterfaceRaw.ConvertToFaxDocument(username, password, files, faxQuality, format.ToString()); var result = WF.SDK.Common.JSONSerializerHelper.Deserialize<ApiResult<Models.Internal.FaxFileItem>>(rstr); var ret = new ApiResult<FaxFileInfo>(); if (result.Success) { ret.Success = true; ret.ErrorString = ""; ret.Result = new FaxFileInfo(result.Result); } else { ret.Success = false; ret.ErrorString = result.ErrorString; ret.Result = null; } return ret; } /// <summary> /// Send a Fax now. /// Fax quality is Fine or Normal. /// </summary> public static ApiResult<FaxFileInfo> ConvertToFaxDocument(string username, string password, FileDetail file, string faxQuality = "Fine", Models.FileFormat format = FileFormat.Tiff) { var rstr = Internal.FaxInterfaceRaw.ConvertToFaxDocument(username, password, file.FileContents, file.Filename, faxQuality, format.ToString()); var result = WF.SDK.Common.JSONSerializerHelper.Deserialize<ApiResult<Models.Internal.FaxFileItem>>(rstr); var ret = new ApiResult<FaxFileInfo>(); if (result.Success) { ret.Success = true; ret.ErrorString = ""; ret.Result = new FaxFileInfo(result.Result); } else { ret.Success = false; ret.ErrorString = result.ErrorString; ret.Result = null; } return ret; } #endregion } }
using System.Windows.Forms; using ObjetoTransferencia; namespace Apresentacao { public partial class FrmCadastrar : Form { private void HablilitarEdicao(AcaoNaTela acaoNaTela) { this.textBoxNome.ReadOnly = (acaoNaTela == AcaoNaTela.Consultar); this.textBoxNome.TabStop = (acaoNaTela != AcaoNaTela.Consultar); this.textBoxLimiteCompra.ReadOnly = (acaoNaTela == AcaoNaTela.Consultar); this.textBoxLimiteCompra.TabStop = (acaoNaTela != AcaoNaTela.Consultar); this.dateNascimento.Enabled = !(acaoNaTela == AcaoNaTela.Consultar); this.dateNascimento.TabStop = (acaoNaTela != AcaoNaTela.Consultar); this.radioSexoFeminino.Enabled = !(acaoNaTela == AcaoNaTela.Consultar); this.radioSexoFeminino.TabStop = (acaoNaTela != AcaoNaTela.Consultar); this.radioSexoMasculino.Enabled = !(acaoNaTela == AcaoNaTela.Consultar); this.radioSexoMasculino.TabStop = (acaoNaTela != AcaoNaTela.Consultar); this.buttonSalvar.Visible = !(acaoNaTela == AcaoNaTela.Consultar); if (acaoNaTela == AcaoNaTela.Consultar) { this.buttonCancelar.Text = "&Fechar"; this.buttonCancelar.Focus(); } else this.buttonCancelar.Text = "&Cancelar"; } private void CarregarTela(Cliente cliente) { this.Text = "Alterar Cliente"; this.textBoxCodigo.Text = cliente.idCliente.ToString(); this.textBoxNome.Text = cliente.Nome; this.textBoxLimiteCompra.Text = cliente.LimiteCompra.ToString("#,##0.00"); this.dateNascimento.Value = cliente.DataNascimento; if (cliente.Sexo == false) { this.radioSexoFeminino.Checked = true; } else { this.radioSexoMasculino.Checked = true; } } //Construtor public FrmCadastrar( AcaoNaTela acaoNaTela, Cliente cliente ) { InitializeComponent(); if (acaoNaTela == AcaoNaTela.Inserir) { this.Text = "Inserir Cliente"; HablilitarEdicao(acaoNaTela); } else if (acaoNaTela == AcaoNaTela.Alterar) { CarregarTela(cliente); HablilitarEdicao(acaoNaTela); //this.Text = "Alterar Cliente"; //this.textBoxCodigo.Text = cliente.idCliente.ToString(); //this.textBoxNome.Text = cliente.Nome; //this.textBoxLimiteCompra.Text = cliente.LimiteCompra.ToString("#,##0.00"); //this.dateNascimento.Value = cliente.DataNascimento; //if (cliente.Sexo == false) //{ // this.radioSexoFeminino.Checked = true; //} //else //{ // this.radioSexoMasculino.Checked = true; //} } else if (acaoNaTela == AcaoNaTela.Consultar) { this.Text = "Consultar Cliente"; CarregarTela(cliente); HablilitarEdicao(acaoNaTela); } } private void buttonCancelar_Click(object sender, System.EventArgs e) { this.Close(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace T1 { class Program { static void Main(string[] args) { Elevator elevator = new Elevator(); do { Console.WriteLine("Elevator is in room: " + elevator.Height); Console.Write("Give floor number (1-5): "); elevator.Height = int.Parse(Console.ReadLine()); } while (true); } } }
using Microsoft.Practices.Unity; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using bringpro.Web.Domain; using bringpro.Web.Enums; using bringpro.Web.Models.Requests; using bringpro.Web.Models.Requests.Users; using bringpro.Web.Models.Responses; using bringpro.Web.Services; using bringpro.Web.Services.Interfaces; using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Http; using System.Web; using System.Web.Http; namespace bringpro.Web.Controllers.Api { [System.Web.Http.RoutePrefix("api/webhooks")] public class WebHookApiController : ApiController { private object jObj; [Dependency] public IActivityLogService _ActivityLogService { get; set; } [Dependency] public IUserCreditsService _CreditsService { get; set; } [Dependency] public IUserProfileService _UserProfileService { get; set; } [Dependency] public IBrainTreeService _BrainTreeService { get; set; } [Route("{id:int}")] [HttpPost] public HttpResponseMessage Insert(JobStatus id) { string json = String.Empty; ActivityLogAddRequest add = new ActivityLogAddRequest(); Job job = new Job(); Dictionary<string, object> values = new Dictionary<string, object>(); SuccessResponse response = new SuccessResponse(); if (HttpContext.Current.Request.InputStream.Length > 0) { HttpContext.Current.Request.InputStream.Position = 0; using (var inputStream = new StreamReader(HttpContext.Current.Request.InputStream)) { json = inputStream.ReadToEnd(); } jObj = JObject.Parse(json); values = JsonConvert.DeserializeObject<Dictionary<string, object>>(json); int externalJobId = Convert.ToInt32(values["id"]); job = JobsService.GetByExternalJobId(externalJobId); add.JobId = job.Id; add.TargetValue = (int)id; add.RawResponse = Newtonsoft.Json.JsonConvert.SerializeObject(jObj); add.ActivityType = ActivityTypeId.BringgTaskStatusUpdated; //Need an if to check if the userId is null or not - If it is null, then use the Phone Nunber if (job.UserId != null) { _ActivityLogService.Insert(job.UserId, add); } else { job.UserId = job.Phone; _ActivityLogService.Insert(job.UserId, add); } JobsService.UpdateJobStatus(id, externalJobId); } //Will call the CompleteTrancsaction function once delivery is done if (id == JobStatus.BringgDone) { _BrainTreeService.CompleteTransaction(job, add); } return Request.CreateResponse(HttpStatusCode.OK, response); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Configuration; namespace solution1 { public partial class FormPortique : Form { string connectionString = ConfigurationManager.ConnectionStrings["connectString1"].ConnectionString; public string idSite = "1"; String requete; DataSet dataSet = null; public FormPortique() { InitializeComponent(); } struct structSite { string idSite; string Site; public structSite(String idSite, string Site) { this.idSite = idSite; this.Site = Site; } public string idsite { get { return idSite; } } public string site { get { return Site; } } } private void groupBox2_Enter(object sender, EventArgs e) { } private void FormPortique_Load(object sender, EventArgs e) { chargementSites(); chargerPortique(); } private void chargementSites() { DataSet dsite = MaConnexion.ExecuteSelect(connectionString, "select * from site"); foreach (DataRow row in dsite.Tables[0].Rows) { structSite str = new structSite(row[0].ToString(), row[1].ToString()); comboBoxSite.Items.Add(str); } try //selection du premier site { comboBoxSite.Text = dsite.Tables[0].Rows[0][1].ToString(); tVEmplacement.SelectedNode = tVEmplacement.Nodes[0]; } catch (Exception) { } //pas de site dans la base de donnée } private void comboBoxSite_SelectedIndexChanged(object sender, EventArgs e) { chargementEmplacements(); } private void chargementEmplacements() { idSite = ((structSite)comboBoxSite.SelectedItem).idsite; tVEmplacement.Nodes.Clear(); try { requete = "select * from emplacement where idSitePere is null and idEmplaPere is null and idsite=" + ((structSite)comboBoxSite.SelectedItem).idsite; dataSet = MaConnexion.ExecuteSelect(connectionString, requete); if (dataSet.Tables[0].Rows.Count > 0) { foreach (DataRow dRRacine in dataSet.Tables[0].Rows) { TreeNode racine = new TreeNode(dRRacine[4].ToString(), 0, 1); //on stocke l'identifant de l'emplacement (idSite_idEmpla) racine.Name = dRRacine[0].ToString() + "_" + dRRacine[1].ToString(); requete = "select * from emplacement where idSitePere = " + dRRacine[0].ToString() + " and idEmplaPere = " + dRRacine[1].ToString() + ";"; DataSet sousDataTable = MaConnexion.ExecuteSelect(connectionString, requete); foreach (DataRow dRCourant in sousDataTable.Tables[0].Rows) { TreeNode tNCourant = new TreeNode(dRCourant[4].ToString(), 0, 1); //on stocke l'identifant de l'emplacement (idSite_idEmpla) tNCourant.Name = dRCourant[0].ToString() + "_" + dRCourant[1].ToString(); racine.Nodes.Add(approfondir(tNCourant, dRCourant[0].ToString(), dRCourant[1].ToString())); } tVEmplacement.Nodes.Add(racine); } tVEmplacement.SelectedNode = tVEmplacement.Nodes[0]; } } catch (Exception ex) { this.BackColor = Color.Red; } } public TreeNode approfondir(TreeNode node, String idSite, String idEmpla) { String requete = "select * from emplacement where idSitePere = " + idSite + " and idEmplaPere = " + idEmpla + ";"; DataSet dataTable = MaConnexion.ExecuteSelect(connectionString, requete); if (dataTable.Tables[0].Rows.Count == 0) { return node; } else { foreach (DataRow dRCourant in dataTable.Tables[0].Rows) { TreeNode subNode = new TreeNode(dRCourant[4].ToString(), 0, 1); //on stocke l'identifant de l'emplacement (idSite_idEmpla) subNode.Name = dRCourant[0].ToString() + "_" + dRCourant[1].ToString(); String sousRequete = "select * from emplacement where idSitePere = " + dRCourant[0].ToString() + " and idEmplaPere = " + dRCourant[1].ToString() + ";"; DataSet sousDataTable = MaConnexion.ExecuteSelect(connectionString, sousRequete); if (sousDataTable.Tables[0].Rows.Count != 0) { node.Nodes.Add(approfondir(subNode, dRCourant[0].ToString(), dRCourant[1].ToString())); } else { node.Nodes.Add(subNode); } } return node; } } private void chargerPortique() { tVPortiques.Nodes.Clear(); requete = "select * from portique"; dataSet = MaConnexion.ExecuteSelect(connectionString, requete); foreach (DataRow row in dataSet.Tables[0].Rows) { TreeNode node = new TreeNode(row[1].ToString(), 2, 3); tVPortiques.Nodes.Add(node); node.Name = row[0].ToString(); //ajout des noeuds emplacement associé a ce portique requete = "select idSite,emplacement.idEmpla, emplacement.desigEmpla from emplacement, associer where emplacement.idEmpla = associer.idEmpla " + "and idPortique = " + row[0].ToString(); DataSet dS = MaConnexion.ExecuteSelect(connectionString, requete); if (dS != null) { foreach (DataRow ligne in dS.Tables[0].Rows) { TreeNode subNode = new TreeNode(ligne[2].ToString(), 0, 1); subNode.Name = ligne[0].ToString() + "_" + ligne[1].ToString(); node.Nodes.Add(subNode); } } } } private void button1_Click(object sender, EventArgs e) { if (tVEmplacement.SelectedNode != null && tVPortiques.SelectedNode != null) { if (tVPortiques.SelectedNode.Parent != null) tVPortiques.SelectedNode = tVPortiques.SelectedNode.Parent; string[] tabId = tVEmplacement.SelectedNode.Name.Split(new char[] { '_' }); string idEmpla = tabId[1]; string idPortique = tVPortiques.SelectedNode.Name; if (tVPortiques.SelectedNode.Nodes.Count < 2) { requete = "select * from associer where idPortique = " + idPortique + " and idEmpla = " + idEmpla; if (MaConnexion.ExecuteSelect(connectionString, requete).Tables[0].Rows.Count == 0) { requete = "insert into associer(idPortique, idEmpla) values (" + idPortique + ", " + idEmpla + ");"; if (MaConnexion.ExecuteUpdate(connectionString, requete) == 1) { TreeNode node = new TreeNode(tVEmplacement.SelectedNode.Text, 0, 1); node.Name = tVEmplacement.SelectedNode.Name; tVPortiques.SelectedNode.Nodes.Add(node); tVPortiques.SelectedNode = node; } else { MessageBox.Show("Echec lors de l'association de l'emplacement '" + tVEmplacement.SelectedNode.Text + "' au portique '" + tVPortiques.SelectedNode.Text + "'", "Erreur d'insertion", MessageBoxButtons.OK , MessageBoxIcon.Exclamation); } } else { MessageBox.Show("L'emplacement '" + tVEmplacement.SelectedNode.Text + "' est déja associé au portique '" + tVPortiques.SelectedNode.Text + "'", "", MessageBoxButtons.OK, MessageBoxIcon.Information); } }else { MessageBox.Show("Un portique ne peut être partagé que par 2 emplacement au plus", "Plus de 2 emplacements", MessageBoxButtons.OK, MessageBoxIcon.Information); } } else { MessageBox.Show("Sélectionnez d'abord un emplacement et un portique RFID", "Sélection", MessageBoxButtons.OK, MessageBoxIcon.Information); } } private void bNouveauPortique_Click(object sender, EventArgs e) { requete = "insert into portique values ('Nouveau portique')"; if (MaConnexion.ExecuteUpdate(connectionString, requete) == 1) { TreeNode node = new TreeNode("Nouveau Portique", 2, 3); tVPortiques.Nodes.Add(node); try //recupération de l'identifiant du portique inséré { requete = "select max(idPortique) from portique"; dataSet = MaConnexion.ExecuteSelect(connectionString, requete); node.Name = dataSet.Tables[0].Rows[0][0].ToString(); } catch (Exception) { chargerPortique(); } node.BeginEdit(); } else { MessageBox.Show("Renommer d'abord le portique 'Nouveau portique' ", "Nom du portique", MessageBoxButtons.OK, MessageBoxIcon.Information); } } private void tVPortiques_AfterLabelEdit(object sender, NodeLabelEditEventArgs e) { if (e.Node.Parent == null) //la modification ne concerne que les portiques (et non leurs fils qui sont des emplacements) { TreeNode node = e.Node; string newName = null; if (e.Label != null) newName = e.Label; else newName = node.Text; requete = "update portique set libelléPortique = '" + newName + "' where idPortique = " + node.Name; if (MaConnexion.ExecuteUpdate(connectionString, requete) != 1) { MessageBox.Show("Le portique '" + e.Label + "' existe dajà, choisissez un autre nom", "Nom du portique", MessageBoxButtons.OK, MessageBoxIcon.Information); chargerPortique(); } } } private void bSupprimer_Click(object sender, EventArgs e) { if (tVPortiques.SelectedNode != null) { if (tVPortiques.SelectedNode.Parent != null) //c'est un emplacement qui est sélectionné et non un portique tVPortiques.SelectedNode = tVPortiques.SelectedNode.Parent; if (MessageBox.Show("Voulez vous vraiment supprimer le portique '" + tVPortiques.SelectedNode.Text + "' ?", "Supprimer un portique", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes) { requete = "delete from portique where idPortique = " + tVPortiques.SelectedNode.Name ; if (MaConnexion.ExecuteUpdate(connectionString, requete) == 1) { tVPortiques.Nodes.Remove(tVPortiques.SelectedNode); } else { MessageBox.Show("Echec de la suppression du portique '" + tVPortiques.SelectedNode.Text + "'", "Erreur de Suppression", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } } else { MessageBox.Show("Sélectionnez d'abord le portique à supprimer", "Portque non sélectionné", MessageBoxButtons.OK, MessageBoxIcon.Information); } } private void groupBox3_Enter(object sender, EventArgs e) { } private void button2_Click(object sender, EventArgs e) { if (tVPortiques.SelectedNode != null) { if (tVPortiques.SelectedNode.Parent != null) { string[] tabId = tVPortiques.SelectedNode.Name.Split(new char[] { '_' }); string idEmpla = tabId[1]; requete = "delete from associer where idPortique = " + tVPortiques.SelectedNode.Parent.Name + " and idEmpla = " + idEmpla; if (MaConnexion.ExecuteUpdate(connectionString, requete) != 1) { MessageBox.Show("Echec de la suppression de l'emplacement '" + tVPortiques.SelectedNode.Text + "' pour le portique '" + tVPortiques.SelectedNode.Parent.Text + "'", "Erreur de suppression", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } else { tVPortiques.SelectedNode.Remove(); } } else MessageBox.Show("Vous devez sélectionner un emplacement et non un portique", "Sélection", MessageBoxButtons.OK, MessageBoxIcon.Information); } else MessageBox.Show("Sélectionnez d'abord un emplacement", "Sélection", MessageBoxButtons.OK, MessageBoxIcon.Information); } private void tVPortiques_BeforeLabelEdit(object sender, NodeLabelEditEventArgs e) { } // } } }
using System; using System.Collections.Generic; using System.Text; namespace Incubator { class CBot { public const int MAX_DNA_SIZE = 64; public BotType Type; public List<DnaCommands> DNA; public int CurrentCommand; public int XCoord; public int YCoord; public int Health; public int Minerals; public int CRed; public int CGreen; public int CBlue; public BotDirect Direct; public CBot() { this.Type = BotType.LV_ALIVE; this.DNA = new List<DnaCommands>(); this.Direct = BotDirect.Right; for(int i=0; i < MAX_DNA_SIZE; i++) { DNA.Add(DnaCommands.Photosynthesis); } } public void EatSun(Seasons currentSeason) { var t = 0; if (Minerals < 100) { t = 0; } else { if (Minerals < 400) t = 1; else t = 2; } int hlt = (int)currentSeason - ((YCoord - 1) / 6) + t; if (hlt > 0) { Health += hlt; goGreen(Minerals); } } public void MineraltoEnergy() { if (Minerals > 100) { Minerals = Minerals - 100; Minerals = Health + 400; goBlue(); } else { goBlue(); Health = Health + 4 * Minerals; Minerals = 0; } } public void NextCommand() { if (CurrentCommand == MAX_DNA_SIZE - 1) { CurrentCommand = 0; return; } CurrentCommand++; } public void ExecuteCommnad() { switch (DNA[CurrentCommand]) { case DnaCommands.Photosynthesis: break; case DnaCommands.ChangeDirectRel: break; case DnaCommands.ChangeDirectAbs: break; case DnaCommands.StepDirectRel: break; case DnaCommands.StepDirectAbs: break; case DnaCommands.EatDirectRel: break; case DnaCommands.EatDirectAbs: break; case DnaCommands.LookDirectRel: break; case DnaCommands.LookDirectAbs: break; case DnaCommands.DivDirectRel: break; case DnaCommands.DivDirectAbs: break; case DnaCommands.AligDirectRel: break; case DnaCommands.AligDirectAbs: break; case DnaCommands.QLevel: break; case DnaCommands.QHealth: break; case DnaCommands.QMinerals: break; case DnaCommands.Div: break; case DnaCommands.QSurrounded: break; case DnaCommands.QAddEnergy: break; case DnaCommands.QAddMinerals: break; case DnaCommands.MineralsToE: break; case DnaCommands.Mutation: break; case DnaCommands.DnaAttac: break; } } public int xFromVektorR(int n,CWorld World) { int xt = XCoord; n = n + Direct; if (n >= 8) { n = n - 8; } if (n == 0 || n == 6 || n == 7) { xt = xt - 1; if (xt == -1) { xt = World.WorldWidth - 1; } } else if (n == 2 || n == 3 || n == 4) { xt = xt + 1; if (xt == World.WorldWidth) { xt = 0; } } return xt; } //жжжжжжжжжжжжжжжжжжжхжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжж // -- получение Х-координаты рядом --------- // с био по абсолютному направлению ---------- // in - номер био, направление -------------- // out - X - координата -------------- public int xFromVektorA(Bot bot, int n) { int xt = bot.x; if (n == 0 || n == 6 || n == 7) { xt = xt - 1; if (xt == -1) { xt = World.simulation.width - 1; } } else if (n == 2 || n == 3 || n == 4) { xt = xt + 1; if (xt == World.simulation.width) { xt = 0; } } return xt; } //жжжжжжжжжжжжхжжжжжхжжжжжжхжхжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжж // ------ получение Y-координаты рядом --------- // ---- Y координата по относительному направлению ---------- // --- in - номер бота, направление ------------ // --- out - Y - координата ------------- public int yFromVektorR(Bot bot, int n) { int yt = bot.y; n = n + bot.direction; if (n >= 8) { n = n - 8; } if (n == 0 || n == 1 || n == 2) { yt = yt - 1; } else if (n == 4 || n == 5 || n == 6) { yt = yt + 1; } return yt; } //жжжжжжжжжжжжхжжжжжхжжжжжжхжхжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжж // ------ получение Y-координаты рядом --------- // ---- Y координата по абсолютному направлению ---------- // --- in - номер бота, направление ------------ // --- out - Y - координата ------------- public int yFromVektorA(Bot bot, int n) { int yt = bot.y; if (n == 0 || n == 1 || n == 2) { yt = yt - 1; } else if (n == 4 || n == 5 || n == 6) { yt = yt + 1; } return yt; } public int botEat(int direction, int ra) { // на входе ссылка на бота, направлелие и флажок(относительное или абсолютное направление) // на выходе пусто - 2 стена - 3 органик - 4 бот - 5 Health = Health - 4; // бот теряет на этом 4 энергии в независимости от результата int xt; int yt; if (ra == 0) { // вычисляем координату клетки, с которой хочет скушать бот (относительное направление) xt = xFromVektorR(bot, direction); yt = yFromVektorR(bot, direction); } else { // вычисляем координату клетки, с которой хочет скушать бот (абсолютное направление) xt = xFromVektorA(bot, direction); yt = yFromVektorA(bot, direction); } if ((yt < 0) || (yt >= World.simulation.height)) { // если там стена возвращаем 3 return 3; } if (World.simulation.matrix[xt][yt] == null) { // если клетка пустая возвращаем 2 return 2; } // осталось 2 варианта: ограника или бот else if (World.simulation.matrix[xt][yt].alive <= LV_ORGANIC_SINK) { // если там оказалась органика deleteBot(World.simulation.matrix[xt][yt]); // то удаляем её из списков bot.health = bot.health + 100; //здоровье увеличилось на 100 goRed(this, 100); // бот покраснел return 4; // возвращаем 4 } //--------- дошли до сюда, значит впереди живой бот ------------------- int min0 = bot.mineral; // определим количество минералов у бота int min1 = World.simulation.matrix[xt][yt].mineral; // определим количество минералов у потенциального обеда int hl = World.simulation.matrix[xt][yt].health; // определим энергию у потенциального обеда // если у бота минералов больше if (min0 >= min1) { bot.mineral = min0 - min1; // количество минералов у бота уменьшается на количество минералов у жертвы // типа, стесал свои зубы о панцирь жертвы deleteBot(World.simulation.matrix[xt][yt]); // удаляем жертву из списков int cl = 100 + (hl / 2); // количество энергии у бота прибавляется на 100+(половина от энергии жертвы) bot.health = bot.health + cl; goRed(this, cl); // бот краснеет return 5; // возвращаем 5 } //если у жертвы минералов больше ---------------------- bot.mineral = 0; // то бот израсходовал все свои минералы на преодоление защиты min1 = min1 - min0; // у жертвы количество минералов тоже уменьшилось World.simulation.matrix[xt][yt].mineral = min1 - min0; // перезаписали минералы жертве =========================ЗАПЛАТКА!!!!!!!!!!!! //------ если здоровья в 2 раза больше, чем минералов у жертвы ------ //------ то здоровьем проламываем минералы --------------------------- if (bot.health >= 2 * min1) { deleteBot(World.simulation.matrix[xt][yt]); // удаляем жертву из списков int cl = 100 + (hl / 2) - 2 * min1; // вычисляем, сколько энергии смог получить бот bot.health = bot.health + cl; if (cl < 0) { cl = 0; } //========================================================================================ЗАПЛАТКА!!!!!!!!!!! - энергия не должна быть отрицательной goRed(this, cl); // бот краснеет return 5; // возвращаем 5 } //--- если здоровья меньше, чем (минералов у жертвы)*2, то бот погибает от жертвы World.simulation.matrix[xt][yt].mineral = min1 - (bot.health / 2); // у жертвы минералы истраченны bot.health = 0; // здоровье уходит в ноль return 5; // возвращаем 5 } public void deleteBot() { Bot pbot = bot.mprev; Bot nbot = bot.mnext; if (pbot != null) { pbot.mnext = null; } // удаление бота из многоклеточной цепочки if (nbot != null) { nbot.mprev = null; } bot.mprev = null; bot.mnext = null; World.simulation.matrix[bot.x][bot.y] = null; // удаление бота с карты } public void goBlue(int num)//Функция посоинения { CBlue = CBlue + num; if (CBlue >255) { CBlue = 255; } int nm = num / 2; CGreen = CGreen - nm; if(CGreen < 0) { CRed = CRed + CGreen; } CRed = CRed - nm; if (CRed < 0) { CGreen = CGreen + CRed; } if (CRed < 0) { CRed = 0; } if (CGreen < 0) { CGreen = 0; } } public void goGreen(int num)//Функция позеленения { CGreen = CGreen + num; if (CGreen > 255) { CGreen = 255; } int nm = num / 2; CRed = CRed - nm; if (CRed < 0) { CBlue = CBlue + CRed; } CBlue = CBlue - nm; if (CBlue < 0) { CRed = CRed + CBlue; } if (CRed < 0) { CRed = 0; } if (CBlue < 0) { CBlue = 0; } } public void goRed(int num)//Функция покраснения { CRed = CRed + num; if (CRed > 255) { CRed = 255; } int nm = num / 2; CGreen = CGreen - nm; if (CGreen < 0) { CBlue = CBlue + CGreen; } CBlue = CBlue - nm; if (CBlue < 0) { CGreen = CGreen + CBlue; } if (CBlue < 0) { CBlue = 0; } if (CGreen < 0) { CGreen = 0; } } } }
using System; using System.Collections.Generic; using System.Linq; using Users.DB; using Microsoft.EntityFrameworkCore; namespace Users.Core { public class UsersServices : IUsersServices { public UsersServices(AppDbContext context) { _context = context; } private AppDbContext _context; public List<User> GetUsers() { return _context.Users.Include(p=>p.Items).ToList(); } //public User GetUser(int id) //{ // return _context.Users.Include(p=>p.Items).First(e => e.Id == id); //} public User GetUser(string username) { return _context.Users.Include(p => p.Items).FirstOrDefault(e => e.Username == username); } public User CreateUser(User user) { User find = _context.Users.Include(p => p.Items).FirstOrDefault(e => e.Username == user.Username); if (find != null) return find; _context.Add(user); Random r = new Random(); user.Money = Math.Round(100.0 + r.NextDouble() * 1000,2); user.Items = new List<Item>(); _context.SaveChanges(); return user; } public string AddItem(User user1) { var user = _context.Users.Include(p => p.Items).First(e => e.Username == user1.Username); if (user1.Items[0].Price > user.Money) return "Not enough money"; _context.Items.Add(user1.Items[0]); user.Items.Add(user1.Items[0]); user.Money = Math.Round(user.Money - user1.Items[0].Price,2); _context.SaveChanges(); return "Item was added succesfully"; } //public string AddItem(int ShopId, bool isUnique, int userId) //{ // Item item = new Item(); // item.IsUnique = isUnique; // item.StoreId = ShopId; // _context.Users.Include(p => p.Items).First(e => e.Id == userId).Items.Add(item); // _context.SaveChanges(); // return "added"; //} } }
using System; using System.Collections.Generic; namespace UnitOfWorkRuleSpecificationRepository.Models { public class RuleSpecification { public int RuleSpecificationId { get; set; } public string RuleSpecificationName { get; set; } public string DefaultValue { get; set; } public string Domain { get; set; } //Navigation public virtual ICollection<Specification> Specifications { get; set; } = new List<Specification>(); } }
using Microsoft.Xna.Framework.Content.Pipeline; using MonoGame.Extended.Content.Pipeline.Json; namespace MonoGame.Extended.Content.Pipeline.SpriteFactory { [ContentImporter(".sf", DefaultProcessor = nameof(SpriteFactoryContentProcessor), DisplayName = "Sprite Factory Importer - MonoGame.Extended")] public class SpriteFactoryContentImporter : JsonContentImporter { } }
namespace SIPCA.CLASES.Migrations { using System; using System.Data.Entity.Migrations; public partial class prodEnDetallePedido : DbMigration { public override void Up() { AddColumn("dbo.DetallePedido", "ProductoId", c => c.Int(nullable: false)); CreateIndex("dbo.DetallePedido", "ProductoId"); AddForeignKey("dbo.DetallePedido", "ProductoId", "dbo.Producto", "IdProducto"); } public override void Down() { DropForeignKey("dbo.DetallePedido", "ProductoId", "dbo.Producto"); DropIndex("dbo.DetallePedido", new[] { "ProductoId" }); DropColumn("dbo.DetallePedido", "ProductoId"); } } }
using System; using System.Collections.Generic; using DryRunTempBackend.API.Proxies; using Microsoft.AspNetCore.Mvc; namespace DryRunTempBackend.API.Controllers { [Route("api/Questions")] public class QuestionsController : Controller { [HttpGet] public ObjectResult Get() { var result = new ListModel<Question> { Total = 4, Items = new List<Question> { new Question{ Id = Guid.NewGuid(), Title = "Are you agree A ?" }, new Question{ Id = Guid.NewGuid(), Title = "Are you agree A ?" }, new Question{ Id = Guid.NewGuid(), Title = "Are you agree A ?" }, new Question{ Id = Guid.NewGuid(), Title = "Are you agree A ?" } } }; return Ok(result); } [HttpPost] [Route("api/Questions/Answers")] public ObjectResult AnswerQuestions([FromBody] QuestionsAnswer model) { return Ok(""); } } }
namespace Triton.Game.Mapping { using ns25; using ns26; using System; using System.Collections.Generic; [Attribute38("WeaponSocketDecoration")] public class WeaponSocketDecoration : MonoBehaviour { public WeaponSocketDecoration(IntPtr address) : this(address, "WeaponSocketDecoration") { } public WeaponSocketDecoration(IntPtr address, string className) : base(address, className) { } public bool AreVisibilityRequirementsMet() { return base.method_11<bool>("AreVisibilityRequirementsMet", Array.Empty<object>()); } public void Hide() { base.method_8("Hide", Array.Empty<object>()); } public bool IsShown() { return base.method_11<bool>("IsShown", Array.Empty<object>()); } public void Show() { base.method_8("Show", Array.Empty<object>()); } public void UpdateVisibility() { base.method_8("UpdateVisibility", Array.Empty<object>()); } public List<WeaponSocketRequirement> m_VisibilityRequirements { get { Class267<WeaponSocketRequirement> class2 = base.method_3<Class267<WeaponSocketRequirement>>("m_VisibilityRequirements"); if (class2 != null) { return class2.method_25(); } return null; } } } }
using UnityEngine; public class CameraManager : MonoBehaviour { private EnemyManager _enemyManager = null; private void Start () { _enemyManager = GameObject.Find ("EnemyManager").GetComponent <EnemyManager> (); } public void GoToUp () { transform.position += new Vector3(0f, 750f, 0f); _enemyManager.GenerateEnemy(); } public void GoToDown () { transform.position += new Vector3(0f, -750f, 0f); _enemyManager.GenerateEnemy(); } public void GoToLeft () { //Reset and level up transform.position = new Vector3(-2133f, 375f, 0f); _enemyManager.GenerateEnemy(); } public void GoToStraight () { //Reset and level up transform.position = new Vector3(667f, 375f, 0f); _enemyManager.GenerateEnemy(); } public void GoToRight () { //Reset and level up transform.position = new Vector3(3467f, 375f, 0f); _enemyManager.GenerateEnemy(); } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace TreeNodeAndWebbrowser { public partial class Form2 : Form { Person _p; public Form2(Person p) { _p = p; InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { _p.Name = textBox1.Text; _p.Tel = textBox2.Text; _p.Desc = textBox3.Text; this.DialogResult = DialogResult.OK; } private void Form2_Load(object sender, EventArgs e) { textBox1.Text = _p.Name; textBox2.Text = _p.Tel; textBox3.Text = _p.Desc; } private void button2_Click(object sender, EventArgs e) { this.DialogResult = DialogResult.Cancel; } } }
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using System; //JaJuan Webster //Professor Cascioli //Spaceship! namespace Webster_HW_Project1_Spaceship { class Background { public void DrawBackground(SpriteBatch spriteBatch, Texture2D texture, Vector2 vector, Color color) { spriteBatch.Draw(texture, vector, color); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PDV.DAO.Entidades { public class Recibo { public string Pessoa { get; set; } public string PessoaEndereco { get; set; } public string Referente { get; set; } public decimal Valor { get; set; } public string Importancia { get; set; } public string Emitente { get; set; } public string EmitenteEndereco { get; set; } public string EmitenteDocumento { get; set; } public string Data { get; set; } } }
using System; using System.Collections.Generic; using System.Text; namespace HackerRank_HomeCode { public class AppendDelete { public void IsPossible() { //first string string s = Console.ReadLine(); //second string string t = Console.ReadLine(); //no of operation in which s must be made same as t int k = Convert.ToInt32(Console.ReadLine()); string result = "ERROR"; //aba aba k =6 if (s.Equals(t)) { result = (k >= s.Length * 2 || k % 2 == 0) ? "YES" : "NO"; } else { int matchingCharacters = 0; for (int i = 0; i < Math.Min(s.Length, t.Length); i++) { if (s[i] != t[i]) { break; } matchingCharacters++; } int nms = s.Length - matchingCharacters; int nmt = t.Length - matchingCharacters; bool condA = nms + nmt == k; //aaaaaaaaaa = 10 //aaaaa = 5 bool condB = (nms + nmt < k && (nms + nmt - k) % 2 == 0); bool condC = s.Length + t.Length <= k; result = (condA || condB || condC) ? "YES" : "NO"; } Console.WriteLine(result); } } }
using System; namespace Rinsen.IdentityProvider.ExternalApplications { public class ExternalSession { public int Id { get; set; } public Guid CorrelationId { get; set; } public Guid IdentityId { get; set; } public Guid ExternalApplicationId { get; set; } public DateTimeOffset Created { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class SweetCounter : MonoBehaviour { [SerializeField] private AudioSource SweetSound; [SerializeField] private SoundManager theSoundManager; [SerializeField] private Text _sweetText; private int _sweetsOnCounter; private int _sweetsQueue; private float _lastAddedSweetTime; [SerializeField] private float _sweetCooldown; [SerializeField] private Animator _sweetCounterAnimator; // Use this for initialization void Start () { _sweetText = GetComponentInChildren<Text>(); _sweetsOnCounter = 0; } // Update is called once per frame void FixedUpdate () { if (_sweetsQueue > 0 && Time.time - _lastAddedSweetTime > _sweetCooldown) { _sweetsQueue--; _lastAddedSweetTime = Time.time; AddSweet(); } } private void AddSweet() { theSoundManager.PlaySweetSound(); _sweetCounterAnimator.SetTrigger("SweetPickup"); _sweetsOnCounter++; _sweetText.text = " " + _sweetsOnCounter; } public void AddSweetsToQueue(int ammount) { _sweetsQueue += ammount; } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace E_Learning.Models { public class Odgovor { [Key] public int Id { get; set; } public bool JeLiTacno { get; set; } public int PitanjeId { get; set; } public Pitanje Pitanje { get; set; } public int KvizId { get; set; } public Kviz Kviz { get; set; } } }
using System; using System.Collections.Generic; using Fluid; namespace FlipLeaf.Core.Text.FluidLiquid { internal class IgnoreCaseMemberAccessStrategy : IMemberAccessStrategy { private Dictionary<string, IMemberAccessor> _map = new Dictionary<string, IMemberAccessor>(StringComparer.OrdinalIgnoreCase); public IMemberAccessor GetAccessor(object obj, string name) { // Look for specific property map if (_map.TryGetValue(Key(obj.GetType(), name), out var getter)) { return getter; } // Look for a catch-all getter if (_map.TryGetValue(Key(obj.GetType(), "*"), out getter)) { return getter; } return null; } public void Register(Type type, string name, IMemberAccessor getter) { _map[Key(type, name)] = getter; } private string Key(Type type, string name) => $"{type.Name}.{name}"; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class HoldingObjects : MonoBehaviour { public string inputFieldPlayerString; public string playerTwoName; private void Update() { DontDestroyOnLoad(this.gameObject); } }
using System; namespace PiPlateRelay { public class PiRelayException : Exception { public PiRelayException(string message) : base(message) { } } }
using DDDSouthWest.IdentityServer.Framework; using IdentityServer4.Services; using IdentityServer4.Validation; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpOverrides; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; namespace DDDSouthWest.IdentityServer { public class Startup { public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", false, true) .AddJsonFile($"appsettings.{env.EnvironmentName.ToLower()}.json", true) .AddEnvironmentVariables(); Configuration = builder.Build(); } public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddAuthServerAppSettingsOptions(Configuration); var websiteUrl = Configuration["DDDSouthWestIdentityServer:WebsiteUrl"]; services.AddIdentityServer() .AddTemporarySigningCredential() .AddInMemoryIdentityResources(Config.GetIdentityResources()) .AddInMemoryApiResources(Config.GetApiResources()) // only used for API .AddInMemoryClients(Config.GetClients(websiteUrl)) .AddProfileService<CustomProfileService>(); services.AddTransient<IUserStore, CustomUserStore>(); services.AddTransient<IProfileService, CustomProfileService>(); services.AddTransient<IResourceOwnerPasswordValidator, CustomValidator>(); } public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { var forwardedHeadersOptions = new ForwardedHeadersOptions { ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto }; forwardedHeadersOptions.KnownProxies.Clear(); forwardedHeadersOptions.KnownNetworks.Clear(); app.UseForwardedHeaders(forwardedHeadersOptions); if (env.IsDevelopment()) { loggerFactory.AddConsole(LogLevel.Debug); app.UseDeveloperExceptionPage(); } app.UseIdentityServer(); app.UseStaticFiles(); app.UseMvcWithDefaultRoute(); } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using TestingExample.Models; using System; using System.Collections.Generic; using System.Text; namespace TestingExample.Models.Tests { [TestClass()] public class SimpleGameTests { [TestMethod()] [DataRow(0)] [DataRow(300)] [DataRow(150)] public void SetGame1_ValidScore_SetsValue(int initialScore) { SimpleGame g = new SimpleGame(); g.Game1 = initialScore; Assert.AreEqual(initialScore, g.Game1); } [TestMethod] [DataRow(301)] [DataRow(-1)] [DataRow(null)] public void SetGame1_InvalidScore_ThrowsArgumentOutOfRangeException(int? score) { var g = new SimpleGame(); Assert.ThrowsException<ArgumentOutOfRangeException> ( () => g.Game1 = score ); } [TestMethod] public void TotalScore_ReturnsSumOfAllGames() { var g = new SimpleGame(); Assert.AreEqual(0, g.TotalScore); g.Game1 = 250; g.Game2 = 125; Assert.AreEqual(375, g.TotalScore); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Networking; public class MyNetworkManager : NetworkManager { public void MyStartHost(){ Debug.Log ("Starting Host at " + Time.timeSinceLevelLoad); StartHost (); } public override void OnStartHost(){ base.OnStartHost (); Debug.Log ("Host Started at " + Time.timeSinceLevelLoad); } public void MyStartClient(){ Debug.Log ("starting Host at " + Time.timeSinceLevelLoad); StartClient (); } public override void OnStartClient(NetworkClient myClient){ base.OnStartClient (myClient); Debug.Log ("Client start requested at " + Time.timeSinceLevelLoad); InvokeRepeating ("PrintDots", 0f, 1f); } public override void OnClientConnect(NetworkConnection con){ base.OnClientConnect (con); Debug.Log ("Client is connected to " + con.address + " at " + Time.timeSinceLevelLoad); CancelInvoke (); } void PrintDots(){ Debug.Log ("."); } }
using System; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using Tff.Panzer.Models.Geography; namespace Tff.Panzer.Models { public class Turn { public int TurnId { get; set; } public DateTime TurnDate { get; set; } public Weather CurrentWeather { get; set; } public TerrainCondition CurrentTerrainCondition { get; set; } public Weather ForcastedWeather { get; set; } public TerrainCondition ForcastedTerrainCondition { get; set; } public int CurrentAxisPrestige { get; set; } public int CurrentAlliedPrestige { get; set; } public Boolean ActiveTurn { get; set; } public SideEnum CurrentSide { get; set; } public int TurnNumber { get { return TurnId + 1; } } } }
// Copyright 2021 Google Inc. All Rights Reserved. // // 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 NtApiDotNet; using System.Collections; using System.Collections.Generic; using System.Management.Automation; namespace NtObjectManager.Cmdlets.Object { /// <summary> /// <para type="synopsis">Compare two security descriptors against each other.</para> /// <para type="description">This cmdlet compares two security descriptors against each other. Returns a boolean result.</para> /// </summary> /// <example> /// <code>Compare-NtSecurityDescriptor $sd1 $sd2</code> /// <para>Checks both security descriptors are equal.</para> /// </example> /// <example> /// <code>Compare-NtSecurityDescriptor $sd1 $sd2 -Report</code> /// <para>Checks both security descriptors are equal and report the differences.</para> /// </example> [Cmdlet(VerbsData.Compare, "NtSecurityDescriptor")] [OutputType(typeof(bool))] public class CompareNtSecurityDescriptorCmdlet : PSCmdlet { /// <summary> /// <para type="description">Specify the left security descriptor to compare.</para> /// </summary> [Parameter(Position = 0, Mandatory = true)] public SecurityDescriptor Left { get; set; } /// <summary> /// <para type="description">Specify the right security descriptor to compare.</para> /// </summary> [Parameter(Position = 1, Mandatory = true)] public SecurityDescriptor Right { get; set; } /// <summary> /// <para type="description">Specify to print what differs between the two security descriptors if they do not match.</para> /// </summary> [Parameter] public SwitchParameter Report { get; set; } /// <summary> /// Process record. /// </summary> protected override void ProcessRecord() { WriteObject(CheckSd()); } private void CompareSid(string sid_name, Sid left, Sid right) { if (left is null && right is null) return; if (left is null) { WriteWarning($"{sid_name} left not present."); return; } if (right is null) { WriteWarning($"{sid_name} right not present."); return; } if (!left.Equals(right)) { WriteWarning($"{sid_name} SIDs mismatch, left {left} right {right}."); } } private void CompareAcls(string acl_name, Acl left, Acl right) { if (left is null && right is null) return; if (left is null) { WriteWarning($"{acl_name} left not present."); return; } if (right is null) { WriteWarning($"{acl_name} right not present."); return; } if (left.Count != right.Count) { WriteWarning($"{acl_name} ACE count mismatch, left {left.Count} right {right.Count}"); return; } for (int i = 0; i < left.Count; ++i) { if (!left[i].Equals(right[i])) { WriteWarning($"{acl_name} ACE {i} mismatch."); WriteWarning($"Left : {left[i]}"); WriteWarning($"Right: {right[i]}"); } } } private bool CheckSd() { IStructuralEquatable left = Left.ToByteArray(); if (left.Equals(Right.ToByteArray(), EqualityComparer<byte>.Default)) return true; if (!Report) return false; if (Left.Control != Right.Control) { WriteWarning($"Control mismatch, left {Left.Control} right {Right.Control}"); } if (Left.RmControl != Right.RmControl) { WriteWarning($"RmControl mismatch, left {Left.RmControl} right {Right.RmControl}"); } CompareSid("Owner", Left.Owner?.Sid, Right.Owner?.Sid); CompareSid("Group", Left.Group?.Sid, Right.Group?.Sid); CompareAcls("DACL", Left.Dacl, Right.Dacl); CompareAcls("SACL", Left.Sacl, Right.Sacl); return false; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Pitstop { public class OutlineCrystal : MonoBehaviour { //My Components Renderer myRenderer; //Serializable [SerializeField] Color color = default; [SerializeField] ScannableObjectBehaviour scannableObjectBehaviour = default; void Start() { myRenderer = GetComponent<Renderer>(); } private void OnMouseOver() { if (scannableObjectBehaviour.isScannable) { SetOutline(255); } } private void OnMouseExit() { SetOutline(0); } void SetOutline(int alphaAmount) { color = myRenderer.material.GetColor("_ColorOutline"); color.a = alphaAmount; myRenderer.material.SetColor("_ColorOutline", color); } } }
using UnityEngine; public class GameAchivementData { public GameAchivementData(Json_GameData data) { gameData = data; } Json_GameData gameData; public int MonsterKill { get => gameData.monsterKill; set { gameData.monsterKill = value; } } public int RefillCount { get => gameData.refillCount; set { gameData.refillCount = value; } } public int GottenItemCount { get => gameData.gottenItemCount; set { gameData.gottenItemCount = value; } } public int GoldMonsterKill { get => gameData.goldMonsterKill; set { gameData.goldMonsterKill = value; } } public int ClearCount { get => gameData.clearCount; set { gameData.clearCount = value; if (gameData.clearCount == 1) AchievementManager.CanGoHeaven(); } } public int GameOverCount { get => gameData.gameOverCount; set { gameData.gameOverCount = value; if (gameData.gameOverCount <= 100) AchievementManager.Achivement_3(gameData.gameOverCount); } } public int AchivementClear { get => gameData.achivementClear; set { gameData.achivementClear = value; if (gameData.achivementClear == 12) AchievementManager.CanMasterHEAVEN(); } } public void SumDatas(StageAchivementData data) { gameData.shortestTime = gameData.shortestTime > data.timer.TimerTime ? data.timer.TimerTime : gameData.shortestTime; MonsterKill += data.MonsterKill; GoldMonsterKill += data.GoldMonsterKill; GottenItemCount += data.GottenItemCount; RefillCount += data.RefillCount; JsonManager.Save(gameData); } } public struct Json_GameData { public double shortestTime; public int monsterKill; public int refillCount; public int gottenItemCount; public int goldMonsterKill; public int clearCount; public int gameOverCount; public int achivementClear; }
using System.Collections.Generic; namespace SprintFour.Triggers { public static class LevelTriggers { public static List<ITrigger> TriggerList; static LevelTriggers() { TriggerList = new List<ITrigger>(); } public static void Update() { foreach (ITrigger trigger in TriggerList) trigger.Update(); } public static void Reset() { TriggerList.Clear(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; [CreateAssetMenu(menuName = "Enemy Wave Config")] public class WaveConfig : ScriptableObject { [SerializeField] GameObject enemyPrefab; [SerializeField] GameObject pathPrefab; [SerializeField] float timeBetweenSpawns = 0.5f; [SerializeField] float spawnRandomFactor = 0.3f; [SerializeField] int numberOfEnemies = 5; [SerializeField] float moveSpeed = 2f; [SerializeField] bool enableBackAndForthPattern = false; [SerializeField] List<Transform> waypointList; public GameObject GetEnemyPrefab() { return enemyPrefab; } public void ResetWaypoints() { waypointList.Clear(); } public List<Transform> GetWaypoints() { if (waypointList.Count < pathPrefab.transform.childCount) { Transform[] waveWaypoints = pathPrefab.GetComponentsInChildren<Transform>(); foreach (Transform child in pathPrefab.transform) { waypointList.Add(child); } } return waypointList; } public float GetTimeBetweenSpawns() { return timeBetweenSpawns; } public float GetSpawnRandomFactor() { return spawnRandomFactor; } public int GetNumberOfEnemies() { return numberOfEnemies; } public float GetMoveSpeed() { return moveSpeed; } public bool GetEnableBackAndForthPattern() { return enableBackAndForthPattern; } }
using Events.Web.Helpers; using Events.Web.Mappers; using Events.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Threading.Tasks; namespace Events.Web.Controllers { public class EventsController : BaseController { // // GET: /Events/ async public Task<ActionResult> Index() { var user = (await this._eventsAppService.ActiveDirectoryUsersAsync()).Where(u => u.ActiveDirectoryId == System.Web.HttpContext.Current.User.Identity.Name).FirstOrDefault(); if (string.IsNullOrWhiteSpace(user.ImageUrl)) { user.ImageUrl = Url.Content("~/Images/user-placeholder.png"); } ViewBag.CurrentUser = user; return View(); } async public Task<ActionResult> AddEvent() { EventViewModel viewModel = new EventViewModel(); viewModel.Owner = System.Web.HttpContext.Current.User.Identity.Name; viewModel.OwnerId = viewModel.Owner; ViewBag.Users = await this.GetActiveUsers(); ViewBag.CurrentView = MenuEnabledView.AddEvent; ViewBag.EventViewModel = viewModel; return View(viewModel); } [HttpPost] async public Task<ActionResult> AddEvent(EventViewModel addedEvent) { try { if (ModelState.IsValid) { var eventData = addedEvent.MapToModel(); eventData = this._eventsAppService.CreateEvent(eventData); if (eventData != null) { return RedirectToAction("SubmitSuccess", "Events", new { id = eventData.Id }); } } ViewBag.CurrentView = MenuEnabledView.AddEvent; ViewBag.Users = await this.GetActiveUsers(); ViewBag.CurrentView = MenuEnabledView.AddEvent; ViewBag.DateRangeError = true; return View(addedEvent); } catch (Exception) { ViewBag.Users = await this.GetActiveUsers(); ViewBag.CurrentView = MenuEnabledView.AddEvent; ModelState.AddModelError("Error", "Error Occured"); return View(); } } public ActionResult MyEvents() { ViewBag.CurrentView = MenuEnabledView.MyEvents; var events = this._eventsAppService.GetUserEvents(System.Web.HttpContext.Current.User.Identity.Name); return View(events.MapToViewModelCollection()); } public ActionResult SubmitSuccess(int id) { string registerLink = this.Request.Url.AbsoluteUri.Replace(this.Request.Url.AbsolutePath, "/Events/Register/" + id.ToString()); @ViewBag.EventRegistrationLink = registerLink; return View(); } async public Task<ActionResult> Register(int id) { if (id > 0) { var eventData = this._eventsAppService.GetEvent(id); if (eventData == null) { return RedirectToAction("Index", "Home"); } ViewBag.Users = await this.GetActiveUsers(); var viewModel = eventData.MapToViewModel(); viewModel.Owner = System.Web.HttpContext.Current.User.Identity.Name; viewModel.OwnerId = viewModel.Owner; ViewBag.CurrentView = MenuEnabledView.Default; return View(viewModel); } return RedirectToAction("Index", "Home"); } [HttpPost] public ActionResult RegisterSuccess(string AttendeeId, int EventId) { var userEvents = this._eventsAppService.GetUserEvents(AttendeeId); if (!userEvents.Any(ue => ue.Id == EventId)) this._eventsAppService.RegisterUser(AttendeeId, EventId); return View(); } async private Task<IEnumerable<ActiveDirectoryUser>> GetActiveUsers() { return await this._eventsAppService.ActiveDirectoryUsersAsync(); } } }
using System; using Microsoft.Practices.Prism; using Microsoft.Practices.Prism.ViewModel; namespace Torshify.Radio.Framework { public class SearchBar : NotificationObject { #region Fields public const string IsFromSearchBarParameter = "IsFromSearchBar"; public const string ValueParameter = "Value"; #endregion Fields #region Constructors public SearchBar(Uri navigationUri, UriQuery parameters, SearchBarData data) { NavigationUri = navigationUri; Data = data; Parameters = parameters; } #endregion Constructors #region Properties public SearchBarData Data { get; private set; } public Uri NavigationUri { get; private set; } public UriQuery Parameters { get; private set; } #endregion Properties } }
using AutoMapper; using L7.Domain; namespace L7.Business { public class ShoppingCartMapping : Profile { public ShoppingCartMapping() { CreateMap<ShoppingCart, ShoppingCartModel>(); } } }
namespace DownloadExtractLib.Interfaces { public interface IDownload { void FetchHtml(string downloadUrl, string fileName = null); } }
using System; using UnityEngine; using UnityEngine.Events; using Valve.VR.InteractionSystem; namespace codepa { [RequireComponent(typeof(Interactable))] public class VRJoystick : MonoBehaviour { [Serializable] class ValueEvent : UnityEvent<Vector2> { } [SerializeField] Transform pivotPoint; [Space] [SerializeField, Range(0, 90)] float maxXAngles; [SerializeField, Range(0, 90)] float maxYAngles; [Space] [SerializeField] ValueEvent OnValueChage; private Interactable interactable; private Vector3 originalPosition; private Vector2 joystickValue; public Vector2 Value { get { return joystickValue; } private set { joystickValue = value; OnValueChage?.Invoke(joystickValue); } } void Awake() { interactable = this.GetComponent<Interactable>(); // Save our position/rotation so that we can restore it when we detach originalPosition = pivotPoint.transform.localPosition; } protected virtual void HandHoverUpdate(Hand hand) { GrabTypes startingGrabType = hand.GetGrabStarting(); if (interactable.attachedToHand == null && startingGrabType != GrabTypes.None) { hand.AttachObject(gameObject, startingGrabType, Hand.AttachmentFlags.DetachOthers); } } protected virtual void HandAttachedUpdate(Hand hand) { // Ensure hand stay in place. pivotPoint.transform.localPosition = originalPosition; pivotPoint.transform.rotation = hand.transform.rotation; // Correct hand rotation pivotPoint.transform.Rotate(Vector3.right, 90); // Errase vertical rotation and set it to the correct orientation. pivotPoint.transform.localEulerAngles = new Vector3( ClampDegrees(pivotPoint.transform.localEulerAngles.x, maxXAngles), 0, ClampDegrees(pivotPoint.transform.localEulerAngles.z, maxYAngles)); // Update Joystick value Value = new Vector2(DegreePrecentage(pivotPoint.transform.localEulerAngles.z, -maxYAngles), DegreePrecentage(pivotPoint.transform.localEulerAngles.x, maxXAngles)); // Apply local offset to the pivot point pivotPoint.transform.localEulerAngles += -transform.localEulerAngles; // Check if trigger is released if (hand.IsGrabEnding(this.gameObject)) { hand.DetachObject(gameObject); } } /// <summary> /// Utilite method to clamp the rotation of the stick. /// </summary> /// <param name="value"></param> /// <param name="degree"></param> /// <returns></returns> private float ClampDegrees(float value, float degree) { if (value > 180) return Mathf.Clamp(value, 360 - degree, 360); else return Mathf.Clamp(value, 0, degree); } /// <summary> /// Utilitie method to check the joystick movement percentage. /// </summary> /// <param name="value"></param> /// <param name="degree"></param> /// <returns></returns> private float DegreePrecentage(float value, float degree) { if (value > 180) value = value - 360; return value / degree; } /// <summary> /// Helpful Gizmos /// </summary> private void OnDrawGizmos() { Gizmos.color = Color.blue; Gizmos.DrawWireSphere(pivotPoint.position, 0.01f); DrawGizmosArrow(transform.position, transform.forward * 0.1f, 0.025f, 30); void DrawGizmosArrow(in Vector3 pos, in Vector3 direction, float arrowHeadLength = 0.25f, float arrowHeadAngle = 20.0f) { Gizmos.DrawRay(pos, direction); Gizmos.DrawRay(pos + direction, Quaternion.LookRotation(direction) * Quaternion.Euler(0, arrowHeadAngle, 0) * Vector3.back * arrowHeadLength); Gizmos.DrawRay(pos + direction, Quaternion.LookRotation(direction) * Quaternion.Euler(0, -arrowHeadAngle, 0) * Vector3.back * arrowHeadLength); } } } }