text
stringlengths
3
1.02M
//----------------------------------------------------------------------- // <copyright file="XmlObjectExtension.cs" company="NJsonSchema"> // Copyright (c) Rico Suter. All rights reserved. // </copyright> // <license>https://github.com/rsuter/NJsonSchema/blob/master/LICENSE.md</license> // <author>Rico Suter, [email protected]</author> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace NJsonSchema.Infrastructure { /// <summary>Extension methods to help out generating XMLObject structure to schema.</summary> public static class XmlObjectExtension { /// <summary>Generate XML object for a JSON Schema definition.</summary> /// <param name="schema">The JSON Schema.</param> /// <param name="type">The type of the JSON Schema.</param> public static void GenerateXmlObjectForType(this JsonSchema4 schema, Type type) { var attributes = type.GetTypeInfo().GetCustomAttributes().ToList(); if (attributes.Any()) { dynamic xmlTypeAttribute = attributes.TryGetIfAssignableTo("System.Xml.Serialization.XmlTypeAttribute"); if (xmlTypeAttribute != null) GenerateXmlObject(xmlTypeAttribute.TypeName, xmlTypeAttribute.Namespace, false, false, schema); } } /// <summary>Generates an XML object for a JSON Schema definition.</summary> /// <param name="schema">The JSON Schema</param> /// <param name="type">The array type</param> public static void GenerateXmlObjectForArrayType(this JsonSchema4 schema, Type type) { if (schema.IsArray && schema.ParentSchema == null) { GenerateXmlObject($@"ArrayOf{schema.Item.Xml.Name}", null, true, false, schema); } } /// <summary>Generates XMLObject structure for an array with primitive types</summary> /// <param name="schema">The JSON Schema of the item.</param> /// <param name="type">The item type.</param> public static void GenerateXmlObjectForItemType(this JsonSchema4 schema, Type type) { // Is done all the time for XML to be able to get type name as the element name if not there was an attribute defined since earlier var attributes = type.GetTypeInfo().GetCustomAttributes().ToList(); dynamic xmlTypeAttribute = attributes.TryGetIfAssignableTo("System.Xml.Serialization.XmlTypeAttribute"); var itemName = GetXmlItemName(type); if (xmlTypeAttribute != null) itemName = xmlTypeAttribute.TypeName; GenerateXmlObject(itemName, null, false, false, schema); } /// <summary>Generates XMLObject structure for a property.</summary> /// <param name="propertySchema">The JSON Schema for the property</param> /// <param name="type">The type.</param> /// <param name="propertyName">The property name.</param> /// <param name="attributes">The attributes that exists for the property.</param> public static void GenerateXmlObjectForProperty(this JsonProperty propertySchema, Type type, string propertyName, IEnumerable<Attribute> attributes) { string xmlName = null; string xmlNamespace = null; bool xmlWrapped = false; if (propertySchema.IsArray) { dynamic xmlArrayAttribute = attributes.TryGetIfAssignableTo("System.Xml.Serialization.XmlArrayAttribute"); if (xmlArrayAttribute != null) { xmlName = xmlArrayAttribute.ElementName; xmlNamespace = xmlArrayAttribute.Namespace; } dynamic xmlArrayItemsAttribute = attributes.TryGetIfAssignableTo("System.Xml.Serialization.XmlArrayItemAttribute"); if (xmlArrayItemsAttribute != null) { var xmlItemName = xmlArrayItemsAttribute.ElementName; var xmlItemNamespace = xmlArrayItemsAttribute.Namespace; GenerateXmlObject(xmlItemName, xmlItemNamespace, true, false, propertySchema.Item); } xmlWrapped = true; } dynamic xmlElementAttribute = attributes.TryGetIfAssignableTo("System.Xml.Serialization.XmlElementAttribute"); if (xmlElementAttribute != null) { xmlName = xmlElementAttribute.ElementName; xmlNamespace = xmlElementAttribute.Namespace; } dynamic xmlAttribute = attributes.TryGetIfAssignableTo("System.Xml.Serialization.XmlAttributeAttribute"); if (xmlAttribute != null) { if (!string.IsNullOrEmpty(xmlAttribute.AttributeName)) xmlName = xmlAttribute.AttributeName; if (!string.IsNullOrEmpty(xmlAttribute.Namespace)) xmlNamespace = xmlAttribute.Namespace; } // Due to that the JSON Reference is used, the xml name from the referenced type will be copied to the property. // We need to ensure that the property name is preserved if (string.IsNullOrEmpty(xmlName) && propertySchema.Type == JsonObjectType.None) { var referencedTypeAttributes = type.GetTypeInfo().GetCustomAttributes(); dynamic xmlReferenceTypeAttribute = referencedTypeAttributes.TryGetIfAssignableTo("System.Xml.Serialization.XmlTypeAttribute"); if (xmlReferenceTypeAttribute != null) { xmlName = propertyName; } } if (!string.IsNullOrEmpty(xmlName) || xmlWrapped) GenerateXmlObject(xmlName, xmlNamespace, xmlWrapped, xmlAttribute != null ? true : false, propertySchema); } private static void GenerateXmlObject(string name, string @namespace, bool wrapped, bool isAttribute, JsonSchema4 schema) { schema.Xml = new JsonXmlObject { Name = name, Wrapped = wrapped, Namespace = @namespace, ParentSchema = schema, Attribute = isAttribute }; } /// <summary>type.Name is used int will return Int32, string will return String etc. /// These are not valid with how the XMLSerializer performs.</summary> private static string GetXmlItemName(Type type) { if (type == typeof(int)) return "int"; else if (type == typeof(string)) return "string"; else if (type == typeof(double)) return "double"; else if (type == typeof(decimal)) return "decimal"; else return type.Name; } } }
using System; using System.Collections.Generic; using System.Text; using System.Net; using System.Net.Sockets; using System.ComponentModel; using System.IO; using System.Text.RegularExpressions; namespace GRebind { public class HttpData { public WebHeaderCollection Headers; public string Html; } public class WebReq { public Uri URI; private Socket socket; private Random rnd = new Random(); public ReqState State = ReqState.Ready; public WebHeaderCollection Headers = new WebHeaderCollection(); private WebHeaderCollection outHeaders = new WebHeaderCollection(); private string Filename = ""; private string Postdata = ""; private string ConMode = "GET"; private string tmpPath = ""; private bool ReturnStr = false; public bool isReady = true; public string ResponseCode = ""; public string Response = ""; public string SentPacket = ""; public int cSize = 1024; private int iTimeout = -1; private long cLength; public double Progress; public double dSpeed; private double[] daSpeed = new double[2]; private long lSpdLastTick; private long lSpdPacketCnt; public enum ReqState { Ready, Connecting, Requesting, Downloading, Completed, Failed }; public void Request(Uri Url, WebHeaderCollection cHeaders, string sPostdata, string sFilename, bool bReturnStr) { isReady = false; State = ReqState.Connecting; URI = Url; Filename = sFilename; ReturnStr = bReturnStr; Headers = new WebHeaderCollection(); outHeaders["Host"] = URI.Host; outHeaders["Keep-Alive"] = "close"; for (int a = 0; a < cHeaders.Count; a++) { outHeaders.Add(cHeaders.GetKey(a) + ": " + cHeaders.Get(a)); } if (sPostdata != "") { ConMode = "POST"; Postdata = sPostdata; outHeaders.Add("Content-Length: " + Postdata.Length); } BackgroundWorker bw = new BackgroundWorker(); bw.DoWork += new DoWorkEventHandler(bw_DoWork); bw.RunWorkerAsync(); } private void bw_DoWork(object sender, DoWorkEventArgs e) { try { // ~~~ Create socket, set timeout ~~~ \\ socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPEndPoint RHost = new IPEndPoint(Dns.GetHostEntry(URI.Host).AddressList[0], URI.Port); if (iTimeout != -1) { socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, iTimeout); socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, iTimeout); BackgroundWorker bwTimeout = new BackgroundWorker(); bwTimeout.DoWork += new DoWorkEventHandler(bwTimeout_DoWork); bwTimeout.RunWorkerAsync(); } // ~~~ Create request, send request ~~~ \\ State = ReqState.Connecting; try { socket.Connect(RHost); } catch { throw new Exception("#02-0002"); } State = ReqState.Requesting; if (ConMode == "POST") outHeaders.Add("Content-Type: application/x-www-form-urlencoded"); string ReqStr = ConMode + " " + URI.PathAndQuery + " HTTP/1.0\r\n" + outHeaders; if (ConMode == "POST") ReqStr += Postdata; SentPacket = ReqStr + "\r\n\r\n>"; byte[] bPck = System.Text.Encoding.ASCII.GetBytes(ReqStr); foreach (byte btPck in bPck) SentPacket += btPck + " "; socket.Send(System.Text.Encoding.ASCII.GetBytes(ReqStr)); if (!ParseHeader()) { if (ResponseCode != "") throw new Exception("#02-0004_" + ResponseCode); throw new Exception("#02-0003"); } // ~~~ Find filename ~~~ \\ string tFName = ""; do tFName = tmpPath + "wanr_" + RandomChars(12) + ".tmp"; while (File.Exists(tFName)); // ~~~ Download file ~~~ \\ lSpdLastTick = Tick(); FileStream streamOut = File.Open(tFName, FileMode.Create, FileAccess.Write, FileShare.ReadWrite); BinaryWriter writer = new BinaryWriter(streamOut); byte[] RecvBuffer = new byte[cSize]; int nBytes, nTotalBytes = 0; while ((nBytes = socket.Receive(RecvBuffer, 0, cSize, SocketFlags.None)) > 0) { nTotalBytes += nBytes; State = ReqState.Downloading; lSpdPacketCnt++; cSpeed(); Progress = Math.Round(((double)100 - ((double)cLength - (double)nTotalBytes) * (double)100 / (double)cLength), 1); writer.Write(RecvBuffer, 0, nBytes); if (ReturnStr) Response += Encoding.ASCII.GetString(RecvBuffer, 0, nBytes); } streamOut.Flush(); streamOut.Close(); streamOut.Dispose(); socket.Close(); // ~~~ Verify download, return text ~~~ \\ long tStart = Tick(); if (!File.Exists(tFName)) wrErrlog("Poll1 false"); while (!File.Exists(tFName)) { System.Threading.Thread.Sleep(10); if (Tick() > tStart + 2000) break; } if (!File.Exists(tFName)) wrErrlog("Poll2 false"); if (File.Exists(tFName)) { if (ReturnStr) { System.IO.StreamReader strmIn = new System.IO.StreamReader(tFName, Encoding.GetEncoding("iso-8859-1")); Response = strmIn.ReadToEnd(); strmIn.Close(); strmIn.Dispose(); } if (Filename != "") { File.Delete(Filename); File.Move(tFName, Filename); } else File.Delete(tFName); } else { throw new Exception("#02-0001"); } State = ReqState.Completed; Progress = 100; isReady = true; } catch (Exception ex) { wrExThrow(ex.Message, ex.StackTrace); } } public void Request(String sURL, WebHeaderCollection cHeaders, string sPostdata, string sFilename, bool bReturnStr) { if (!sURL.ToLower().StartsWith("http://")) sURL = "http://" + sURL; Request(new Uri(sURL), cHeaders, sPostdata, sFilename, bReturnStr); } public void Request(String sURL, string sPostdata, string sFilename, bool bReturnStr) { Request(sURL, new WebHeaderCollection(), sPostdata, sFilename, bReturnStr); } public void Request(String sURL, string sFilename, bool bReturnStr) { Request(sURL, new WebHeaderCollection(), "", sFilename, bReturnStr); } public void Request(String sURL) { Request(sURL, new WebHeaderCollection(), "", "", true); } private bool ParseHeader() { try { byte[] bytes = new byte[10]; string Header = ""; while (socket.Receive(bytes, 0, 1, SocketFlags.None) > 0) { Header += Encoding.ASCII.GetString(bytes, 0, 1); if (bytes[0] == '\n' && Header.EndsWith("\r\n\r\n")) break; } MatchCollection matches = new Regex("[^\r\n]+").Matches(Header.TrimEnd('\r', '\n')); for (int n = 1; n < matches.Count; n++) { string[] strItem = matches[n].Value.Split(new char[] { ':' }, 2); if (strItem.Length > 0) Headers[strItem[0].Trim()] = strItem[1].Trim(); } if (matches.Count > 0) { if (matches[0].Value.Contains(" 404 ")) ResponseCode = "404"; } if (Headers["Content-Length"] != null) cLength = int.Parse(Headers["Content-Length"]); if (ResponseCode != "") return false; return true; } catch { //wrExThrow("Header parse error"); return false; } } public void SetTimeout(int Timeout) { iTimeout = Timeout; } private void bwTimeout_DoWork(object sender, DoWorkEventArgs e) { System.Threading.Thread.Sleep(iTimeout); if (State != ReqState.Connecting) return; wrExThrow("#02-0005"); } public long Tick() { return System.DateTime.Now.Ticks / 10000; } private void cSpeed() { long ltDiff = Tick() - lSpdLastTick; if (ltDiff > 500) { lSpdLastTick = Tick(); for (int a = daSpeed.Length - 2; a > 0; a--) { daSpeed[a + 1] = daSpeed[a]; } daSpeed[0] = ((double)lSpdPacketCnt / ((double)ltDiff/1000)) * ((double)cSize / 1024); lSpdPacketCnt = 0; double dcSpeed = 0; int iLogCnt = 0; for (int a = 0; a < daSpeed.Length; a++) { if (daSpeed[a] != 0) { iLogCnt++; dcSpeed += daSpeed[a]; } } dSpeed = dcSpeed / (double)iLogCnt; } } private string RandomChars(int Count) { string ret = ""; for (int a = 0; a < Count; a++) { int ThisRnd = rnd.Next(1, 63); if (ThisRnd >= 1 && ThisRnd <= 26) ThisRnd += 64; else if (ThisRnd >= 27 && ThisRnd <= 52) ThisRnd += 97 - 27; else if (ThisRnd >= 53 && ThisRnd <= 62) ThisRnd += 48 - 53; ret += (char)ThisRnd; } return ret; } private static String Byte2Str(byte[] Value) { int len = 0; for (len = Value.Length; len > 0; len--) if (Value[len - 1] != 0) break; string ret = ""; for (int a = 0; a < len; a++) ret += (char)Value[a]; //byte[] buf = new byte[a]; for (a = 0; a < buf.Length; a++) buf[a] = Value[a]; return ret; //System.Text.Encoding.ASCII.GetString(buf); } private void wrErrlog(string msg) { //string errMessage = System.DateTime.Now.ToShortDateString() + " - " + // System.DateTime.Now.ToLongTimeString() + "\r\n" + // msg + "\r\n\r\n"; //FileStream fs = new FileStream("errors_browser.txt", FileMode.Append); //fs.Write(System.Text.Encoding.ASCII.GetBytes(errMessage), 0, errMessage.Length); //fs.Close(); fs.Dispose(); } private void wrExThrow(string msg, string trace) { string exMessage = msg; Response = "<WebReq_Error>" + msg + "</WebReq_Error>"; //if (Filename != "") //{ // FileStream fs = new FileStream(Filename, FileMode.Create); // fs.Write(System.Text.Encoding.ASCII.GetBytes(Response), 0, Response.Length); // fs.Flush(); fs.Close(); fs.Dispose(); //} if (trace.Contains(":line ")) trace = trace.Substring(trace.IndexOf(":line ") + 6); else trace = ""; if (trace != "") exMessage += "\r\nSTACK TRACING --> " + trace; wrErrlog(exMessage); socket.Close(); State = ReqState.Failed; Progress = 0; isReady = true; } private void wrExThrow(string msg) { wrExThrow(msg, ""); } } }
using System; using System.Collections.Generic; using System.Linq; namespace _01.CountCharsInAString { class Program { static void Main(string[] args) { string[] text = Console.ReadLine() .Split(" ",StringSplitOptions.RemoveEmptyEntries) .ToArray(); Dictionary<string, int> count = new Dictionary<string, int>(); for (int i = 0; i < text.Length; i++) { string word = text[i]; for (int j = 0; j < text[i].Length; j++) { if (count.ContainsKey(word[j].ToString())) { count[word[j].ToString()]++; } else { count.Add(word[j].ToString(), 1); } } } foreach (var item in count) { Console.WriteLine($"{item.Key} -> {item.Value}"); } } } }
using System; using NetOffice; namespace NetOffice.MSHTMLApi.Enums { /// <summary> /// SupportByVersion MSHTML 4 /// </summary> [SupportByVersionAttribute("MSHTML", 4)] [EntityTypeAttribute(EntityType.IsEnum)] public enum _htmlZOrder { /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <remarks>0</remarks> [SupportByVersionAttribute("MSHTML", 4)] htmlZOrderFront = 0, /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <remarks>1</remarks> [SupportByVersionAttribute("MSHTML", 4)] htmlZOrderBack = 1, /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <remarks>2147483647</remarks> [SupportByVersionAttribute("MSHTML", 4)] htmlZOrder_Max = 2147483647 } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System.Collections.Generic; using Aliyun.Acs.Core; using Aliyun.Acs.Core.Http; using Aliyun.Acs.Core.Transform; using Aliyun.Acs.Core.Utils; using Aliyun.Acs.rtc.Transform; using Aliyun.Acs.rtc.Transform.V20180111; namespace Aliyun.Acs.rtc.Model.V20180111 { public class DescribeMAURuleRequest : RpcAcsRequest<DescribeMAURuleResponse> { public DescribeMAURuleRequest() : base("rtc", "2018-01-11", "DescribeMAURule", "rtc", "openAPI") { if (this.GetType().GetProperty("ProductEndpointMap") != null && this.GetType().GetProperty("ProductEndpointType") != null) { this.GetType().GetProperty("ProductEndpointMap").SetValue(this, Endpoint.endpointMap, null); this.GetType().GetProperty("ProductEndpointType").SetValue(this, Endpoint.endpointRegionalType, null); } } private long? ownerId; private string appId; public long? OwnerId { get { return ownerId; } set { ownerId = value; DictionaryUtil.Add(QueryParameters, "OwnerId", value.ToString()); } } public string AppId { get { return appId; } set { appId = value; DictionaryUtil.Add(QueryParameters, "AppId", value); } } public override bool CheckShowJsonItemName() { return false; } public override DescribeMAURuleResponse GetResponse(UnmarshallerContext unmarshallerContext) { return DescribeMAURuleResponseUnmarshaller.Unmarshall(unmarshallerContext); } } }
using Rakor.Blazor.ECharts.Option.Enum; namespace Rakor.Blazor.ECharts.Option { public class LineStyle : AreaStyle { /// <summary> /// 线宽。 /// </summary> public double? Width { set; get; } /// <summary> /// 线的类型。 /// </summary> public LineStyleType? Type { set; get; } } }
//------------------- // Copyright 2019 // Reachable Games, LLC //------------------- using System; using System.Collections; using UnityEngine; using UnityEngine.Networking; using UnityEditor; namespace ReachableGames { namespace SmoothTrails { public class AssetsPopup : EditorWindow { static string kNextCheckTime = "ReachableGames_AssetPopup_NextCheckTime"; static string kHashOfWebPage = "ReachableGames_AssetPopup_Hash"; static string kAssetsURL = "https://reachablegames.com/unity-asset-updates/"; static private AssetsPopup _instance = null; [MenuItem("Tools/ReachableGames/Check for Updates")] static void CheckForUpdatesMenu() { EditorPrefs.SetString(kHashOfWebPage, ""); // someone asked for the window, give it to them WaitForWebRequest(CheckContent()); } static void Init() { if (_instance==null) _instance = EditorWindow.CreateInstance<AssetsPopup>(); _instance.ShowUtility(); } [InitializeOnLoadMethod] static void CheckForUpdates() { long nextCheckTime = long.Parse(EditorPrefs.GetString(kNextCheckTime, "0")); if (DateTime.UtcNow.Ticks > nextCheckTime) { // Do a daily check for updated web page, unless we're told not to check for 3 months. long nextCheck = DateTime.UtcNow.Ticks + TimeSpan.FromDays(1.0).Ticks; EditorPrefs.SetString(kNextCheckTime, nextCheck.ToString()); WaitForWebRequest(CheckContent()); } } static private string ComputeHash(string text) { #if UNITY_2018_1_OR_NEWER return Hash128.Compute(text).ToString(); #else // Unity 2017 didn't have a compute function, so we fall back to a crappier hash that is quick to write. long value = 0; for (int i=0; i<text.Length; i++) { char c = text[i]; value += (((long)c) << (i % 5)) + (((long)c) << (i % 11)); } return value.ToString(); #endif } static private IEnumerator CheckContent() { using (UnityWebRequest w = UnityWebRequest.Get(kAssetsURL)) { yield return w.SendWebRequest(); while (!w.isDone) yield return null; if (!w.isNetworkError && !w.isHttpError && w.downloadProgress==1.0f) { string hashOfWebPage = ComputeHash(w.downloadHandler.text); if (EditorPrefs.GetString(kHashOfWebPage, "")!=hashOfWebPage) { EditorPrefs.SetString(kHashOfWebPage, hashOfWebPage); Init(); // pop up the window, something's new } } } } static private void WaitForWebRequest(IEnumerator update) { EditorApplication.CallbackFunction cb = null; cb = () => { try { if (!update.MoveNext()) EditorApplication.update -= cb; } catch (Exception ex) { Debug.LogException(ex); EditorApplication.update -= cb; } }; EditorApplication.update += cb; } //------------------- private WebViewHook _webHook = null; void OnEnable() { if (_webHook==null) _webHook = CreateInstance<WebViewHook>(); _webHook.AllowRightClickMenu(false); minSize = new Vector2(840, 800); titleContent = new GUIContent("Check for Updates"); } void OnDestroy() { if (_webHook!=null) { DestroyImmediate(_webHook); } } Rect bottomBarRect; void OnGUI() { // Put web block here if (_webHook.Hook(this)) { _webHook.LoadURL(kAssetsURL); } if (Event.current.type==EventType.Repaint) _webHook.OnGUI(new Rect(0, 0, position.width, bottomBarRect.height)); GUILayout.FlexibleSpace(); if (Event.current.type==EventType.Repaint) bottomBarRect = GUILayoutUtility.GetLastRect(); var bigTextArea = new GUIStyle(GUI.skin.textArea); bigTextArea.fontSize = 15; EditorGUILayout.TextArea("Thank you for using our assets. We sincerely hope they are making dev life better for you. If so, please help us keep working on them by giving each a great 5* review and recommend them to your friends. It really does make a difference!", bigTextArea); using (new EditorGUILayout.HorizontalScope()) { if (GUILayout.Button(new GUIContent("Check for updates in 3 months", "You can always check manually at Tools->ReachableGames."), GUILayout.Width(200))) { long nextCheck = DateTime.UtcNow.Ticks + TimeSpan.FromDays(90.0).Ticks; EditorPrefs.SetString(kNextCheckTime, nextCheck.ToString()); } GUILayout.FlexibleSpace(); GUIStyle blueLabel = new GUIStyle(EditorStyles.whiteMiniLabel); blueLabel.normal.textColor = EditorGUIUtility.isProSkin ? Color.white : Color.blue; blueLabel.fontSize = 12; if (GUILayout.Button("[email protected]", blueLabel)) { Application.OpenURL("mailto:[email protected]?Subject=Support Request"); } GUILayout.FlexibleSpace(); var blueTextButton = new GUIStyle(GUI.skin.button); blueTextButton.normal.textColor = EditorGUIUtility.isProSkin ? Color.white : Color.blue; if (GUILayout.Button(new GUIContent("Check for updates regularly", "As a service, this will let you know as soon as bugs are fixed or features are added to one of our assets. Generally this is not more than once a month."), blueTextButton, GUILayout.Width(200))) { long nextCheck = DateTime.UtcNow.Ticks + TimeSpan.FromDays(1.0).Ticks; EditorPrefs.SetString(kNextCheckTime, nextCheck.ToString()); } } } } } }
/* This file is part of the iText (R) project. Copyright (c) 1998-2022 iText Group NV Authors: iText Software. This program is offered under a commercial and under the AGPL license. For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. AGPL licensing: This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ using System; using System.Collections.Generic; using iText.Commons.Actions.Processors; using iText.Commons.Actions.Sequence; namespace iText.Commons.Actions { /// <summary>Abstract class which represents system configuration events.</summary> /// <remarks>Abstract class which represents system configuration events. Only for internal usage.</remarks> public abstract class AbstractITextConfigurationEvent : AbstractITextEvent { /// <summary> /// Adds a new /// <see cref="iText.Commons.Actions.Processors.ITextProductEventProcessor"/> /// for a product. /// </summary> /// <param name="processor">is a new processor</param> /// <returns>a replaced processor for the product</returns> protected internal virtual ITextProductEventProcessor AddProcessor(ITextProductEventProcessor processor) { return ProductEventHandler.INSTANCE.AddProcessor(processor); } /// <summary>Removes a processor registered for a product.</summary> /// <param name="productName">is a product for which processor is removed</param> /// <returns>removed processor</returns> protected internal virtual ITextProductEventProcessor RemoveProcessor(String productName) { return ProductEventHandler.INSTANCE.RemoveProcessor(productName); } /// <summary>Gets a processor registered for a product.</summary> /// <remarks> /// Gets a processor registered for a product. /// <para /> /// If processor isn't registered and product supports AGPL mode /// <see cref="iText.Commons.Actions.Processors.DefaultITextProductEventProcessor"/> /// will be obtained otherwise null will be returned. /// </remarks> /// <param name="productName">is a product for which processor is obtained</param> /// <returns>processor for the product</returns> protected internal virtual ITextProductEventProcessor GetActiveProcessor(String productName) { return ProductEventHandler.INSTANCE.GetActiveProcessor(productName); } /// <summary>Gets an unmodifiable map of registered processors.</summary> /// <returns>all processors</returns> protected internal virtual IDictionary<String, ITextProductEventProcessor> GetProcessors() { return ProductEventHandler.INSTANCE.GetProcessors(); } /// <summary>Gets events registered for provided identifier.</summary> /// <param name="id">is the identifier</param> /// <returns>the list of event for identifier</returns> protected internal virtual IList<AbstractProductProcessITextEvent> GetEvents(SequenceId id) { return ProductEventHandler.INSTANCE.GetEvents(id); } /// <summary>Registers a new event for provided identifier.</summary> /// <param name="id">is the identifier</param> /// <param name="event">is the event to register</param> protected internal virtual void AddEvent(SequenceId id, AbstractProductProcessITextEvent @event) { ProductEventHandler.INSTANCE.AddEvent(id, @event); } /// <summary>Registers internal namespace.</summary> /// <param name="namespace">is the namespace to register</param> protected internal virtual void RegisterInternalNamespace(String @namespace) { AbstractITextEvent.RegisterNamespace(@namespace); } /// <summary>Method defines the logic of action processing.</summary> protected internal abstract void DoAction(); } }
using UnityEngine; using UnityEngine.UI; public class MoleculeText : MonoBehaviour { public int option; public Image line; private void OnEnable() { ContentAdaptationManager.NextMolecule += SetText; } private void OnDisable() { ContentAdaptationManager.NextMolecule -= SetText; } public void Start() { SetText(); } private void SetText() //sets the text for the molecule name and enables the line if constructed or named. { //stands for the naming quiz if (option == 1 && GameManager.currentLevel == GameManager.Levels.moleculeNaming) { if (GameManager.instance.IsMoleculeNamed(GameManager.chosenMolecule.Name)) { line.enabled = true; } else{ line.enabled = false; } gameObject.GetComponent<Text>().text = GameManager.chosenMolecule.Name; } else if(option == 1 && GameManager.currentLevel == GameManager.Levels.moleculeConstruction) { if (GameManager.instance.IsMoleculeConstructed(GameManager.chosenMolecule.Name)) { line.enabled = true; } else { line.enabled = false; } gameObject.GetComponent<Text>().text = GameManager.chosenMolecule.Name; } else // for the formula in construction scene. { gameObject.GetComponent<Text>().text = GameManager.chosenMolecule.Formula; } } }
@using Syncfusion.EJ2.PivotView @section Meta{ <meta name="description" content="This demo for Essential JS2 ASP.NET MVC Pivot Table control demonstrate the cell selection feature" /> } @section ControlsSection{ <div class="col-lg-8 control-section" style="overflow:auto"> <div class="content-wrapper"> @Html.EJS().PivotView("pivotview").Width("100%").Height("300").DataSource(dataSource => dataSource.Data((IEnumerable<object> )ViewBag.Data).ExpandAll(true).EnableSorting(true) .Rows(rows => { rows.Name("Country").Add(); rows.Name("Products").Add(); }) .Columns(columns => { columns.Name("Year").Add(); columns.Name("Order_Source").Caption("Order Source").Add(); }) .Values(values => { values.Name("Sold").Caption("Units Sold").Add(); values.Name("Amount").Caption("Sold Amount").Add(); }) .FormatSettings(formatsettings => { formatsettings.Name("Amount").Format("C0").MaximumSignificantDigits(10).MinimumSignificantDigits(1).UseGrouping(true).Add(); }) .Filters(filters => { filters.Name("Product_Categories").Caption("Product Categories").Add(); })).GridSettings(new PivotViewGridSettings { ColumnWidth = 120, AllowSelection = true}).Load("onLoad").CellSelected("onCellSelected").Render() </div> </div> <div class="col-lg-4 property-section pivotgrid-property-section"> <table id="property" title="Properties" style="width: 100%"> <tbody> <tr style="height: 50px"> <td> <div> Selection Modes: </div> </td> <td> <div> <select id="mode" name="ddl-view-mode"> <option value='Cell' selected>Cell</option> <option value='Row'>Row Only</option> <option value='Column'>Column Only</option> <option value='Both'>Both</option> </select> </div> </td> </tr> <tr style="height: 50px"> <td> <div> Selection Types: </div> </td> <td> <div> <select id="type" name="ddl-view-mode"> <option value='Single'>Single</option> <option value='Multiple' selected>Multiple</option> </select> </div> </td> </tr> <tr> <td colspan="2"> <div> <b> <hr>Event Trace: </b> </div> </td> </tr> <tr> <td colspan="2"> <div class="eventarea" style="height: 230px;overflow: auto"> <span class="EventLog" id="selection-EventLog" style="word-break: normal;"></span> </div> </td> </tr> </tbody> </table> </div> <style> .pivotgrid-property-section hr { margin: 1px 10px 0px 0px; border-top: 1px solid #eee; } </style> <script> function onLoad(args) { var pivotGridObj = document.getElementById('pivotview').ej2_instances[0]; pivotGridObj.gridSettings.selectionSettings = { mode: 'Cell', type: 'Multiple', cellSelectionMode: 'Box' }; } function onCellSelected(args) { document.getElementById('selection-EventLog').innerHTML = ''; if (args.selectedCellsInfo.length > 0) { for (var cnt = 0; cnt < args.selectedCellsInfo.length; cnt++) { var cell = args.selectedCellsInfo[cnt]; var summMeasure = this.engineModule.fieldList[cell.measure] ? this.engineModule.fieldList[cell.measure].aggregateType + ' of ' + this.engineModule.fieldList[cell.measure].caption : ''; appendElement( (cell.columnHeaders == '' ? '' : 'Column Headers: ' + '<b>' + cell.columnHeaders.split('.').join(' - ') + '</b></br>') + (cell.rowHeaders == '' ? '' : 'Row Headers: ' + '<b>' + cell.rowHeaders.split('.').join(' - ') + '</b></br>') + (summMeasure == '' ? '' : 'Measure: ' + '<b>' + summMeasure + '</b></br>') + 'Value: ' + '<b>' + cell.currentCell.formattedText + '</b><hr></br>'); } } } function appendElement(html) { var span = document.createElement('span'); span.innerHTML = html; var log = document.getElementById('selection-EventLog'); log.appendChild(span); } var modeddl = new ej.dropdowns.DropDownList({ floatLabelType: 'Auto', width: 150, change: function (args) { var pivotGridObj = document.getElementById('pivotview').ej2_instances[0]; pivotGridObj.gridSettings.selectionSettings.mode = args.value; pivotGridObj.renderModule.updateGridSettings(); } }); modeddl.appendTo('#mode'); var typeddl = new ej.dropdowns.DropDownList({ floatLabelType: 'Auto', width: 150, change: function (args) { var pivotGridObj = document.getElementById('pivotview').ej2_instances[0]; pivotGridObj.gridSettings.selectionSettings.type = args.value; pivotGridObj.renderModule.updateGridSettings(); } }); typeddl.appendTo('#type'); </script> } @section PreScripts { <script> ej.base.enableRipple(false); </script> } @section ActionDescription{ <div id="action-description"> <p> This sample demonstrates different types of grid cell selection options and an event to get complete information about the same. </p> </div> } @section Description{ <div id="description"> <p> This feature provides interactive support to highlight rows, columns, values, and summary cells that you select. Selection can be done through either mouse or keyboard interaction. To enable selection, set <code> allowSelection </code> as true. </p> <p> PivotGrid supports two types of selection that can be set using <code>selectionSettings.type</code> property. They are, </p> <ul> <li> <code>Single</code> - Enabled by default. Allows user to select a single row, column, or cell at a time. </li> <li><code>Multiple</code> - Allows the user to select more than one row, column, or cell at the same time.</li> </ul> <p> Also, there are three modes of selection that can be set using <code>selectionSettings.mode</code> property. They are, </p> <ul> <li><code>Row</code> - Enabled by default. Enables the complete row selection in a pivot grid.</li> <li><code>Column</code> - Enables the complete column selection in a pivot grid.</li> <li><code>Cell</code> - Enables only value and summary cell selection in a pivot grid.</li> <li><code>Both</code> - Enables both row and column selection in a pivot grid.</li> </ul> <p> To perform multiselection, hold the <strong>CTRL</strong> key and click the desired cells. To select a range of cells, hold the <strong>SHIFT</strong> key and click the cells. </p> <p> While using Pivot Grid in a touch device, double-tap over a row, column, or other cells. This results in a pop-up with a multiselect icon. Now tap the icon to proceed with multiselection. </p> <p> In this demo, pick the selection type and selection mode from the properties panel in order to perform the desired selection process. The selected cell information can be seen in the Event Trace part with the help of the <code>cellSelected</code> event. </p> </div> }
using System; using System.Collections.Generic; using System.Text; using FlubuCore.Context; using FlubuCore.Tasks; using FlubuCore.Tasks.Process; namespace FlubuCore.Azure.Tasks.Sf { public partial class AzureSfClusterClientCertificateTask : ExternalProcessTaskBase<AzureSfClusterClientCertificateTask> { /// <summary> /// Manage the client certificate of a cluster. /// </summary> public AzureSfClusterClientCertificateTask() { WithArguments("az sf cluster client-certificate"); } protected override string Description { get; set; } } }
namespace _07.RawData { public class Car { public string Model { get; set; } public Engine Engine { get; private set; } public Cargo Cargo { get; private set; } public Tire[] Tires { get; private set; } public Car(string model, Engine engine, Cargo cargo, Tire[] tires) { this.Model = model; this.Engine = engine; this.Cargo = cargo; this.Tires = tires; } } }
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.RecoveryServices.V20210301.Inputs { /// <summary> /// HyperV Replica Blue policy input. /// </summary> public sealed class HyperVReplicaBluePolicyInputArgs : Pulumi.ResourceArgs { /// <summary> /// A value indicating the authentication type. /// </summary> [Input("allowedAuthenticationType")] public Input<int>? AllowedAuthenticationType { get; set; } /// <summary> /// A value indicating the application consistent frequency. /// </summary> [Input("applicationConsistentSnapshotFrequencyInHours")] public Input<int>? ApplicationConsistentSnapshotFrequencyInHours { get; set; } /// <summary> /// A value indicating whether compression has to be enabled. /// </summary> [Input("compression")] public Input<string>? Compression { get; set; } /// <summary> /// A value indicating whether IR is online. /// </summary> [Input("initialReplicationMethod")] public Input<string>? InitialReplicationMethod { get; set; } /// <summary> /// The class type. /// Expected value is 'HyperVReplica2012R2'. /// </summary> [Input("instanceType")] public Input<string>? InstanceType { get; set; } /// <summary> /// A value indicating the offline IR export path. /// </summary> [Input("offlineReplicationExportPath")] public Input<string>? OfflineReplicationExportPath { get; set; } /// <summary> /// A value indicating the offline IR import path. /// </summary> [Input("offlineReplicationImportPath")] public Input<string>? OfflineReplicationImportPath { get; set; } /// <summary> /// A value indicating the online IR start time. /// </summary> [Input("onlineReplicationStartTime")] public Input<string>? OnlineReplicationStartTime { get; set; } /// <summary> /// A value indicating the number of recovery points. /// </summary> [Input("recoveryPoints")] public Input<int>? RecoveryPoints { get; set; } /// <summary> /// A value indicating whether the VM has to be auto deleted. /// </summary> [Input("replicaDeletion")] public Input<string>? ReplicaDeletion { get; set; } /// <summary> /// A value indicating the replication interval. /// </summary> [Input("replicationFrequencyInSeconds")] public Input<int>? ReplicationFrequencyInSeconds { get; set; } /// <summary> /// A value indicating the recovery HTTPS port. /// </summary> [Input("replicationPort")] public Input<int>? ReplicationPort { get; set; } public HyperVReplicaBluePolicyInputArgs() { } } }
using System; using System.IO; using System.Net; using System.Net.Security; using System.Net.Sockets; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; using System.Threading; using System.Threading.Tasks; namespace Myrtille.Fleck { public class SocketWrapper : ISocket { private readonly Socket _socket; private Stream _stream; private CancellationTokenSource _tokenSource; private TaskFactory _taskFactory; public string RemoteIpAddress { get { var endpoint = _socket.RemoteEndPoint as IPEndPoint; return endpoint != null ? endpoint.Address.ToString() : null; } } public int RemotePort { get { var endpoint = _socket.RemoteEndPoint as IPEndPoint; return endpoint != null ? endpoint.Port : -1; } } public SocketWrapper(Socket socket) { _tokenSource = new CancellationTokenSource(); _taskFactory = new TaskFactory(_tokenSource.Token); _socket = socket; if (_socket.Connected) _stream = new NetworkStream(_socket); } public Task Authenticate(X509Certificate2 certificate, SslProtocols enabledSslProtocols, Action callback, Action<Exception> error) { var ssl = new SslStream(_stream, false); _stream = new QueuedStream(ssl); Func<AsyncCallback, object, IAsyncResult> begin = (cb, s) => ssl.BeginAuthenticateAsServer(certificate, false, enabledSslProtocols, false, cb, s); Task task = Task.Factory.FromAsync(begin, ssl.EndAuthenticateAsServer, null); task.ContinueWith(t => callback(), TaskContinuationOptions.NotOnFaulted) .ContinueWith(t => error(t.Exception), TaskContinuationOptions.OnlyOnFaulted); task.ContinueWith(t => error(t.Exception), TaskContinuationOptions.OnlyOnFaulted); return task; } public void Listen(int backlog) { _socket.Listen(backlog); } public void Bind(EndPoint endPoint) { _socket.Bind(endPoint); } public bool Connected { get { return _socket.Connected; } } public Stream Stream { get { return _stream; } } public bool NoDelay { get { return _socket.NoDelay; } set { _socket.NoDelay = value; } } public EndPoint LocalEndPoint { get { return _socket.LocalEndPoint; } } public Task<int> Receive(byte[] buffer, Action<int> callback, Action<Exception> error, int offset) { try { Func<AsyncCallback, object, IAsyncResult> begin = (cb, s) => _stream.BeginRead(buffer, offset, buffer.Length, cb, s); Task<int> task = Task.Factory.FromAsync<int>(begin, _stream.EndRead, null); task.ContinueWith(t => callback(t.Result), TaskContinuationOptions.NotOnFaulted) .ContinueWith(t => error(t.Exception), TaskContinuationOptions.OnlyOnFaulted); task.ContinueWith(t => error(t.Exception), TaskContinuationOptions.OnlyOnFaulted); return task; } catch (Exception e) { error(e); return null; } } public Task<ISocket> Accept(Action<ISocket> callback, Action<Exception> error) { Func<IAsyncResult, ISocket> end = r => _tokenSource.Token.IsCancellationRequested ? null : new SocketWrapper(_socket.EndAccept(r)); var task = _taskFactory.FromAsync(_socket.BeginAccept, end, null); task.ContinueWith(t => callback(t.Result), TaskContinuationOptions.OnlyOnRanToCompletion) .ContinueWith(t => error(t.Exception), TaskContinuationOptions.OnlyOnFaulted); task.ContinueWith(t => error(t.Exception), TaskContinuationOptions.OnlyOnFaulted); return task; } public void Dispose() { _tokenSource.Cancel(); if (_stream != null) _stream.Dispose(); if (_socket != null) _socket.Dispose(); } public void Close() { _tokenSource.Cancel(); if (_stream != null) _stream.Close(); if (_socket != null) _socket.Close(); } public int EndSend(IAsyncResult asyncResult) { _stream.EndWrite(asyncResult); return 0; } public Task Send(byte[] buffer, Action callback, Action<Exception> error) { if (_tokenSource.IsCancellationRequested) return null; try { Func<AsyncCallback, object, IAsyncResult> begin = (cb, s) => _stream.BeginWrite(buffer, 0, buffer.Length, cb, s); Task task = Task.Factory.FromAsync(begin, _stream.EndWrite, null); task.ContinueWith(t => callback(), TaskContinuationOptions.NotOnFaulted) .ContinueWith(t => error(t.Exception), TaskContinuationOptions.OnlyOnFaulted); task.ContinueWith(t => error(t.Exception), TaskContinuationOptions.OnlyOnFaulted); return task; } catch (Exception e) { error(e); return null; } } } }
// Copyright 2015-2018 The NATS Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Threading; using System.Diagnostics; #if NET45 using System.Reflection; #endif using NATS.Client; using System.IO; namespace STAN.Client.UnitTests { class RunnableServer : IDisposable { Process p; string executablePath; public void init(string exeName, string args) { UnitTestUtilities.CleanupExistingServers(exeName); executablePath = exeName + ".exe"; ProcessStartInfo psInfo = createProcessStartInfo(args); try { p = Process.Start(psInfo); for (int i = 1; i <= 20; i++) { Thread.Sleep(100 * i); if (IsRunning()) break; } if (p.HasExited) { throw new Exception("Unable to start process."); } Thread.Sleep(1000); } catch (Exception ex) { p = null; throw new Exception(string.Format("{0} {1} failure with error: {2}", psInfo.FileName, psInfo.Arguments, ex.Message)); } } public RunnableServer(string exeName) { init(exeName, null); } public RunnableServer(string exeName, string args) { init(exeName, args); } private ProcessStartInfo createProcessStartInfo(string args) { ProcessStartInfo ps = new ProcessStartInfo(executablePath); ps.Arguments = args; ps.WorkingDirectory = UnitTestUtilities.GetConfigDir(); #if NET45 ps.WindowStyle = ProcessWindowStyle.Hidden; #else ps.CreateNoWindow = false; ps.RedirectStandardError = true; #endif return ps; } public bool IsRunning() { try { new ConnectionFactory().CreateConnection().Close(); return true; } catch (Exception) { return false; } } public void Shutdown() { if (p == null) return; try { p.Kill(); p.WaitForExit(60000); } catch (Exception) { } p = null; } void IDisposable.Dispose() { Shutdown(); } } class NatsServer : RunnableServer { public NatsServer() : base("gnatsd") { } public NatsServer(string args) : base("gnatsd", args) { } } class NatsStreamingServer : RunnableServer { public NatsStreamingServer() : base("nats-streaming-server") { } public NatsStreamingServer(string args) : base("nats-streaming-server", args) { } } class UnitTestUtilities { object mu = new object(); static internal string GetConfigDir() { #if NET45 string baseDir = Assembly.GetExecutingAssembly().CodeBase; return baseDir + "\\NATSUnitTests\\config"; #else return AppContext.BaseDirectory + string.Format("{0}..{0}..{0}..{0}", Path.DirectorySeparatorChar); #endif } internal static void CleanupExistingServers(string procname) { bool hadProc = false; try { Process[] procs = Process.GetProcessesByName(procname); foreach (Process proc in procs) { proc.Kill(); } } catch (Exception) { } // ignore if (hadProc) Thread.Sleep(500); } } }
namespace HuaweiMobileServices.IAP { public class OrderStatusCode { public const int ORDER_STATE_SUCCESS = 0; public const int ORDER_STATE_FAILED = -1; public const int ORDER_STATE_CANCEL = 60000; public const int ORDER_STATE_PARAM_ERROR = 60001; public const int ORDER_STATE_NET_ERROR = 60005; public const int ORDER_VR_UNINSTALL_ERROR = 60020; public const int ORDER_HWID_NOT_LOGIN = 60050; public const int ORDER_PRODUCT_OWNED = 60051; public const int ORDER_PRODUCT_NOT_OWNED = 60052; public const int ORDER_PRODUCT_CONSUMED = 60053; public const int ORDER_ACCOUNT_AREA_NOT_SUPPORTED = 60054; public const int ORDER_NOT_ACCEPT_AGREEMENT = 60055; } }
using System; using System.IO; using System.Linq; namespace AdventOfCode { class Program { static void Main (string[] args) { string[] dimensions = File.ReadLines(@"input.txt").ToArray(); ulong lengthOfRibbon = 0; foreach (var dim in dimensions) { lengthOfRibbon += calculateTotalLength(dim); } Console.WriteLine(lengthOfRibbon); } private static ulong calculateTotalLength(string dim) { ulong[] dims = dim.Split('x').Select(ulong.Parse).ToArray(); ulong len = calculateLength(dims); return len + (dims[0] * dims[1] * dims[2]); } private static ulong calculateLength(ulong[] dims) { return 2 * dims[0] + 2 * dims[1] + 2 * dims[2] - 2 * Math.Max(Math.Max(dims[0], dims[1]), dims[2]); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Antlr.Runtime; using Compiler.SemanticStructures; using Compiler.Errors; using Compiler.CodeGenerators; using System.Reflection; using System.Reflection.Emit; namespace Compiler.AST { public class RecordDotAccessNode : AccessNode { public RecordDotAccessNode(IToken token) : base(token) { } /// <summary> /// Expresion a la que se le hace punto /// </summary> public ExpressionNode DotedExpression { get { return GetChild(0) as ExpressionNode; } } /// <summary> /// Representa el id que se usa para acceder a un campo del record. /// </summary> public string ID { get { return GetChild(1).Text; } } public string RecordName { get; set; } public override void CheckSemantic(SymbolTable symbolTable, List<CompileError> errors) { //se manda a chequear semanticamente la expresion a la que se le hizo punto DotedExpression.CheckSemantic(symbolTable, errors); //si DotedExpression evalua de error este tambien evalua de error if (Object.Equals(DotedExpression.NodeInfo, SemanticInfo.SemanticError)) { ///el nodo evalúa de error NodeInfo = SemanticInfo.SemanticError; return; } //la expresion tiene que ser compatible con record if (!DotedExpression.NodeInfo.BuiltInType.IsCompatibleWith(BuiltInType.Record)) { errors.Add(new CompileError { Line = GetChild(1).Line, Column = GetChild(1).CharPositionInLine, ErrorMessage = "Dot notation can only be applied to 'record' types", Kind = ErrorKind.Semantic }); ///el nodo evalúa de error NodeInfo = SemanticInfo.SemanticError; } ///si este nodo evaluó de error if (Object.Equals(NodeInfo, SemanticInfo.SemanticError)) { ///terminamos de chequear la semántica de este nodo return; } //verificamos que el record tenga un campo con el nombre ID bool existField = false; foreach (var field in DotedExpression.NodeInfo.Fields) { if (field.Key.Equals(ID)) { existField = true; NodeInfo.Type = field.Value.Type; NodeInfo.BuiltInType = field.Value.BuiltInType; NodeInfo.ElementsType = field.Value.ElementsType; NodeInfo.Fields = field.Value.Fields; break; } } if (!existField) { errors.Add(new CompileError { Line = GetChild(1).Line, Column = GetChild(1).CharPositionInLine, ErrorMessage = string.Format("Type '{0}' does not contain a definition for '{1}'", DotedExpression.NodeInfo.Type.Name, ID), Kind = ErrorKind.Semantic }); ///el nodo evalúa de error NodeInfo = SemanticInfo.SemanticError; } RecordName = DotedExpression.NodeInfo.Type.Name; } public override void GenerateCode(ILCodeGenerator cg) { DotedExpression.GenerateCode(cg); if (LoadVariableInTheStack) { ILElementInfo ile = cg.ILContextTable.GetDefinedType(RecordName); FieldInfo fi = ile.TypeBuilder.GetField(ID); cg.ILGenerator.Emit(OpCodes.Ldfld, fi); } } } }
/* *************************************************************************** * This file is part of SharpNEAT - Evolution of Neural Networks. * * Copyright 2004-2016 Colin Green ([email protected]) * * SharpNEAT is free software; you can redistribute it and/or modify * it under the terms of The MIT License (MIT). * * You should have received a copy of the MIT License * along with SharpNEAT; if not, see https://opensource.org/licenses/MIT. */ using System.Diagnostics; namespace SharpNeat.Domains.FunctionRegression { /// <summary> /// Parameter sampling info. Describes the value range to sample, the number of samples within /// that range and the increment between samples. /// </summary> public struct ParamSamplingInfo { /// <summary>Sample range minimum.</summary> public readonly double _min; /// <summary>Sample range maximum.</summary> public readonly double _max; /// <summary>Intra sample increment.</summary> public readonly double _incr; /// <summary>Sample count.</summary> public readonly int _sampleCount; /// <summary>X positions of the sample points.</summary> public readonly double[] _xArr; /// <summary>X positions of the sample points in the neural net input space (i.e. scaled from 0 to 1)</summary> public readonly double[] _xArrNetwork; /// <summary> /// Construct with the provided parameter info. /// </summary> public ParamSamplingInfo(double min, double max, int sampleCount) { Debug.Assert(sampleCount>=3, "Sample count must be >= 3"); _min = min; _max = max; _incr = (max-min) / (sampleCount-1); _sampleCount = sampleCount; double incrNet = 1.0 / (sampleCount-1); double x = min; double xNet = 0; _xArr = new double[sampleCount]; _xArrNetwork = new double[sampleCount]; for(int i=0; i<sampleCount; i++, x += _incr, xNet += incrNet) { _xArr[i] = x; _xArrNetwork[i] = xNet; } } } }

No dataset card yet

New: Create and edit this dataset card directly on the website!

Contribute a Dataset Card
Downloads last month
2
Add dataset card