repo_id
stringlengths
6
101
size
int64
367
5.14M
file_path
stringlengths
2
269
content
stringlengths
367
5.14M
2881099/dotnetGen_postgresql
5,499
GenPg/Lib/JSDecoder.cs
using System; using System.Text; using System.Text.RegularExpressions; public class JSDecoder { private const byte STATE_COPY_INPUT = 100; private const byte STATE_READLEN = 101; private const byte STATE_DECODE = 102; private const byte STATE_UNESCAPE = 103; private static byte[] _pickEncoding; private static byte[] _rawData; private static byte[] _digits = new byte[123]; private static byte[][] _transformed = new byte[3][]; static JSDecoder() { InitArrayData(); } private static void InitArrayData() { _pickEncoding = new byte[] { 1, 2, 0, 1, 2, 0, 2, 0, 0, 2, 0, 2, 1, 0, 2, 0, 1, 0, 2, 0, 1, 1, 2, 0, 0, 2, 1, 0, 2, 0, 0, 2, 1, 1, 0, 2, 0, 2, 0, 1, 0, 1, 1, 2, 0, 1, 0, 2, 1, 0, 2, 0, 1, 1, 2, 0, 0, 1, 1, 2, 0, 1, 0, 2 }; _rawData = new byte[] { 0x64,0x37,0x69, 0x50,0x7E,0x2C, 0x22,0x5A,0x65, 0x4A,0x45,0x72, 0x61,0x3A,0x5B, 0x5E,0x79,0x66, 0x5D,0x59,0x75, 0x5B,0x27,0x4C, 0x42,0x76,0x45, 0x60,0x63,0x76, 0x23,0x62,0x2A, 0x65,0x4D,0x43, 0x5F,0x51,0x33, 0x7E,0x53,0x42, 0x4F,0x52,0x20, 0x52,0x20,0x63, 0x7A,0x26,0x4A, 0x21,0x54,0x5A, 0x46,0x71,0x38, 0x20,0x2B,0x79, 0x26,0x66,0x32, 0x63,0x2A,0x57, 0x2A,0x58,0x6C, 0x76,0x7F,0x2B, 0x47,0x7B,0x46, 0x25,0x30,0x52, 0x2C,0x31,0x4F, 0x29,0x6C,0x3D, 0x69,0x49,0x70, 0x3F,0x3F,0x3F, 0x27,0x78,0x7B, 0x3F,0x3F,0x3F, 0x67,0x5F,0x51, 0x3F,0x3F,0x3F, 0x62,0x29,0x7A, 0x41,0x24,0x7E, 0x5A,0x2F,0x3B, 0x66,0x39,0x47, 0x32,0x33,0x41, 0x73,0x6F,0x77, 0x4D,0x21,0x56, 0x43,0x75,0x5F, 0x71,0x28,0x26, 0x39,0x42,0x78, 0x7C,0x46,0x6E, 0x53,0x4A,0x64, 0x48,0x5C,0x74, 0x31,0x48,0x67, 0x72,0x36,0x7D, 0x6E,0x4B,0x68, 0x70,0x7D,0x35, 0x49,0x5D,0x22, 0x3F,0x6A,0x55, 0x4B,0x50,0x3A, 0x6A,0x69,0x60, 0x2E,0x23,0x6A, 0x7F,0x09,0x71, 0x28,0x70,0x6F, 0x35,0x65,0x49, 0x7D,0x74,0x5C, 0x24,0x2C,0x5D, 0x2D,0x77,0x27, 0x54,0x44,0x59, 0x37,0x3F,0x25, 0x7B,0x6D,0x7C, 0x3D,0x7C,0x23, 0x6C,0x43,0x6D, 0x34,0x38,0x28, 0x6D,0x5E,0x31, 0x4E,0x5B,0x39, 0x2B,0x6E,0x7F, 0x30,0x57,0x36, 0x6F,0x4C,0x54, 0x74,0x34,0x34, 0x6B,0x72,0x62, 0x4C,0x25,0x4E, 0x33,0x56,0x30, 0x56,0x73,0x5E, 0x3A,0x68,0x73, 0x78,0x55,0x09, 0x57,0x47,0x4B, 0x77,0x32,0x61, 0x3B,0x35,0x24, 0x44,0x2E,0x4D, 0x2F,0x64,0x6B, 0x59,0x4F,0x44, 0x45,0x3B,0x21, 0x5C,0x2D,0x37, 0x68,0x41,0x53, 0x36,0x61,0x58, 0x58,0x7A,0x48, 0x79,0x22,0x2E, 0x09,0x60,0x50, 0x75,0x6B,0x2D, 0x38,0x4E,0x29, 0x55,0x3D,0x3F }; for (byte i = 0; i < 3; i++) _transformed[i] = new byte[288]; for (byte i = 31; i < 127; i++) for (byte j = 0; j < 3; j++) _transformed[j][_rawData[(i - 31) * 3 + j]] = i == 31 ? (byte)9 : i; for (byte i = 0; i < 26; i++) { _digits[65 + i] = i; _digits[97 + i] = (byte)(i + 26); } for (byte i = 0; i < 10; i++) _digits[48 + i] = (byte)(i + 52); _digits[43] = 62; _digits[47] = 63; } private static string UnEscape(string s) { string escapes = "#&!*$"; string escaped = "\r\n<>@"; if ((int)s.ToCharArray()[0] > 126) return s; if (escapes.IndexOf(s) != -1) return escaped.Substring(escapes.IndexOf(s), 1); return "?"; } private static int DecodeBase64(string s) { int val = 0; byte[] bs = Encoding.UTF8.GetBytes(s); val += ((int)_digits[bs[0]] << 2); val += (_digits[bs[1]] >> 4); val += (_digits[bs[1]] & 0xf) << 12; val += ((_digits[bs[2]] >> 2) << 8); val += ((_digits[bs[2]] & 0x3) << 22); val += (_digits[bs[3]] << 16); return val; } public static string Decode(string encodingString) { string marker = "#@~^"; int stringIndex = 0; int scriptIndex = -1; int unEncodingIndex = 0; string strChar = ""; string getCodeString = ""; int unEncodinglength = 0; int state = STATE_COPY_INPUT; string unEncodingString = ""; try { while (state != 0) { switch (state) { case STATE_COPY_INPUT: scriptIndex = encodingString.IndexOf(marker, stringIndex); if (scriptIndex != -1) { unEncodingString += encodingString.Substring(stringIndex, scriptIndex); scriptIndex += marker.Length; state = STATE_READLEN; } else { stringIndex = stringIndex == 0 ? 0 : stringIndex; unEncodingString += encodingString.Substring(stringIndex); state = 0; } break; case STATE_READLEN: getCodeString = encodingString.Substring(scriptIndex, 6); unEncodinglength = DecodeBase64(getCodeString); scriptIndex += 8; state = STATE_DECODE; break; case STATE_DECODE: if (unEncodinglength == 0) { stringIndex = scriptIndex + "DQgAAA==^#~@".Length; unEncodingIndex = 0; state = STATE_COPY_INPUT; } else { strChar = encodingString.Substring(scriptIndex, 1); if (strChar == "@") state = STATE_UNESCAPE; else { int b = (int)strChar.ToCharArray()[0]; if (b < 0xFF) { unEncodingString += (char)_transformed[_pickEncoding[unEncodingIndex % 64]][b]; unEncodingIndex++; } else { unEncodingString += strChar; } scriptIndex++; unEncodinglength--; } } break; case STATE_UNESCAPE: unEncodingString += UnEscape(encodingString.Substring(++scriptIndex, 1)); scriptIndex++; unEncodinglength -= 2; unEncodingIndex++; state = STATE_DECODE; break; } } } catch { } string Pattern; Pattern = "(JScript|VBscript).encode"; unEncodingString = Regex.Replace(unEncodingString, Pattern, "", RegexOptions.IgnoreCase); return unEncodingString; } }
27182812/ChatGLM-LLaMA-chinese-insturct
10,508
src/transformers/models/codegen/tokenization_codegen_fast.py
# coding=utf-8 # Copyright 2022 The Salesforce authors, The Open AI Team Authors and The HuggingFace Inc. team. # # 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. """Tokenization classes for OpenAI GPT.""" import json import re from typing import TYPE_CHECKING, List, Optional, Tuple, Union import numpy as np from ...utils import is_tf_available, is_torch_available, logging if TYPE_CHECKING: if is_torch_available(): import torch if is_tf_available(): import tensorflow as tf from tokenizers import pre_tokenizers from ...tokenization_utils_base import BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from .tokenization_codegen import CodeGenTokenizer logger = logging.get_logger(__name__) VOCAB_FILES_NAMES = {"vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_file": "tokenizer.json"} PRETRAINED_VOCAB_FILES_MAP = { "vocab_file": { "Salesforce/codegen-350M-mono": "https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/vocab.json", }, "merges_file": { "Salesforce/codegen-350M-mono": "https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/merges.txt", }, "tokenizer_file": { "Salesforce/codegen-350M-mono": ( "https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/tokenizer.json" ), }, } PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = { "Salesforce/codegen-350M-mono": 2048, } class CodeGenTokenizerFast(PreTrainedTokenizerFast): """ Construct a "fast" CodeGen tokenizer (backed by HuggingFace's *tokenizers* library). Based on byte-level Byte-Pair-Encoding. This tokenizer has been trained to treat spaces like parts of the tokens (a bit like sentencepiece) so a word will be encoded differently whether it is at the beginning of the sentence (without space) or not: ``` >>> from transformers import CodeGenTokenizerFast >>> tokenizer = CodeGenTokenizerFast.from_pretrained("Salesforce/codegen-350M-mono") >>> tokenizer("Hello world")['input_ids'] [15496, 995] >>> tokenizer(" Hello world")['input_ids'] [18435, 995] ``` You can get around that behavior by passing `add_prefix_space=True` when instantiating this tokenizer, but since the model was not pretrained this way, it might yield a decrease in performance. <Tip> When used with `is_split_into_words=True`, this tokenizer needs to be instantiated with `add_prefix_space=True`. </Tip> This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should refer to this superclass for more information regarding those methods. Args: vocab_file (`str`): Path to the vocabulary file. merges_file (`str`): Path to the merges file. errors (`str`, *optional*, defaults to `"replace"`): Paradigm to follow when decoding bytes to UTF-8. See [bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information. unk_token (`str`, *optional*, defaults to `<|endoftext|>`): The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this token instead. bos_token (`str`, *optional*, defaults to `<|endoftext|>`): The beginning of sequence token. eos_token (`str`, *optional*, defaults to `<|endoftext|>`): The end of sequence token. add_prefix_space (`bool`, *optional*, defaults to `False`): Whether or not to add an initial space to the input. This allows to treat the leading word just as any other word. (CodeGen tokenizer detect beginning of words by the preceding space). trim_offsets (`bool`, *optional*, defaults to `True`): Whether or not the post-processing step should trim offsets to avoid including whitespaces. """ vocab_files_names = VOCAB_FILES_NAMES pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES model_input_names = ["input_ids", "attention_mask"] slow_tokenizer_class = CodeGenTokenizer def __init__( self, vocab_file=None, merges_file=None, tokenizer_file=None, unk_token="<|endoftext|>", bos_token="<|endoftext|>", eos_token="<|endoftext|>", add_prefix_space=False, **kwargs, ): super().__init__( vocab_file, merges_file, tokenizer_file=tokenizer_file, unk_token=unk_token, bos_token=bos_token, eos_token=eos_token, add_prefix_space=add_prefix_space, **kwargs, ) if kwargs.pop("add_bos_token", False): model_id = kwargs.pop("name_or_path", "") raise ValueError( "Currenty GPT2's fast tokenizer does NOT support adding a BOS token." "Instead you should use GPT2's slow tokenizer class `CodeGenTokenizer` as follows: \n" f"`CodeGenTokenizer.from_pretrained('{model_id}')`\nor\n" f"`AutoTokenizer.from_pretrained('{model_id}', use_fast=False)`\n" "This issue will be fixed soon, see: https://github.com/huggingface/tokenizers/pull/1005." " so that the fast tokenizer works correctly." ) pre_tok_state = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__()) if pre_tok_state.get("add_prefix_space", add_prefix_space) != add_prefix_space: pre_tok_class = getattr(pre_tokenizers, pre_tok_state.pop("type")) pre_tok_state["add_prefix_space"] = add_prefix_space self.backend_tokenizer.pre_tokenizer = pre_tok_class(**pre_tok_state) self.add_prefix_space = add_prefix_space def _batch_encode_plus(self, *args, **kwargs) -> BatchEncoding: is_split_into_words = kwargs.get("is_split_into_words", False) assert self.add_prefix_space or not is_split_into_words, ( f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True " "to use it with pretokenized inputs." ) return super()._batch_encode_plus(*args, **kwargs) def _encode_plus(self, *args, **kwargs) -> BatchEncoding: is_split_into_words = kwargs.get("is_split_into_words", False) assert self.add_prefix_space or not is_split_into_words, ( f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True " "to use it with pretokenized inputs." ) return super()._encode_plus(*args, **kwargs) def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]: files = self._tokenizer.model.save(save_directory, name=filename_prefix) return tuple(files) def decode( self, token_ids: Union[int, List[int], "np.ndarray", "torch.Tensor", "tf.Tensor"], skip_special_tokens: bool = False, clean_up_tokenization_spaces: bool = True, truncate_before_pattern: Optional[List[str]] = None, **kwargs, ) -> str: """ Converts a sequence of ids in a string, using the tokenizer and vocabulary with options to remove special tokens and clean up tokenization spaces. Similar to doing `self.convert_tokens_to_string(self.convert_ids_to_tokens(token_ids))`. Args: token_ids (`Union[int, List[int], np.ndarray, torch.Tensor, tf.Tensor]`): List of tokenized input ids. Can be obtained using the `__call__` method. skip_special_tokens (`bool`, *optional*, defaults to `False`): Whether or not to remove special tokens in the decoding. clean_up_tokenization_spaces (`bool`, *optional*, defaults to `True`): Whether or not to clean up the tokenization spaces. truncate_before_pattern (`List[str]`, *optional*, defaults to `None`): A list of regular expression strings that will be used to truncate the returned string. This can be used to remove extra pieces of code (e.g. truncate if observing a comment symbol "#" at the beginning of a new line). An example pattern could be `["^#", re.escape("<|endoftext|>"), "^'''", "\n\n\n"]`. kwargs (additional keyword arguments, *optional*): Will be passed to the underlying model specific decode method. Returns: `str`: The decoded sentence. """ decoded_text = super().decode( token_ids=token_ids, skip_special_tokens=skip_special_tokens, clean_up_tokenization_spaces=clean_up_tokenization_spaces, **kwargs, ) if truncate_before_pattern is not None and len(truncate_before_pattern) > 0: decoded_text = self.truncate(decoded_text, truncate_before_pattern) return decoded_text def truncate(self, completion, truncate_before_pattern): def find_re(string, pattern, start_pos): m = pattern.search(string, start_pos) return m.start() if m else -1 terminals = [re.compile(pattern, re.MULTILINE) for pattern in truncate_before_pattern] prints = list(re.finditer("^print", completion, re.MULTILINE)) if len(prints) > 1: completion = completion[: prints[1].start()] defs = list(re.finditer("^def", completion, re.MULTILINE)) if len(defs) > 1: completion = completion[: defs[1].start()] start_pos = 0 terminals_pos = [ pos for pos in [find_re(completion, terminal, start_pos) for terminal in terminals] if pos != -1 ] if len(terminals_pos) > 0: return completion[: min(terminals_pos)] else: return completion
2881099/dotnetGen_postgresql
7,555
GenPg/Lib/Lib.cs
using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Text; using System.Net; using System.Threading; using System.Runtime.Serialization.Json; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using PList; using System.Runtime.Serialization.Formatters.Binary; public delegate void AnonymousHandler(); /// <summary> /// 常用函数库 /// </summary> public class Lib { /// <summary> /// 当前程序类型是否为 Web Application /// </summary> public static string HtmlEncode(object input) { return WebUtility.HtmlEncode(string.Concat(input)); } public static string HtmlDecode(object input) { return WebUtility.HtmlDecode(string.Concat(input)); } public static string UrlEncode(object input) { return WebUtility.UrlEncode(string.Concat(input)); } public static string UrlDecode(object input) { return WebUtility.UrlDecode(string.Concat(input)); } public static string JSDecode(string input) { return JSDecoder.Decode(input); } #region 弥补 String.PadRight 和 String.PadLeft 对中文的 Bug public static string PadRight(object text, int length) { return PadRightLeft(text, length, ' ', true); } public static string PadRight(object text, char paddingChar, int length) { return PadRightLeft(text, length, paddingChar, true); } public static string PadLeft(object text, int length) { return PadRightLeft(text, length, ' ', false); } public static string PadLeft(object text, char paddingChar, int length) { return PadRightLeft(text, length, paddingChar, false); } static string PadRightLeft(object text, int length, char paddingChar, bool isRight) { string str = string.Concat(text); int len2 = Encoding.UTF8.GetBytes(str).Length; for (int a = 0; a < length - len2; a++) if (isRight) str += paddingChar; else str = paddingChar + str; return str; } #endregion #region 序列化/反序列化(二进制) public static byte[] Serialize(object obj) { var formatter = new BinaryFormatter(); MemoryStream ms = new MemoryStream(); formatter.Serialize(ms, obj); byte[] data = ms.ToArray(); ms.Close(); return data; //using (MemoryStream ms = new MemoryStream()) { // DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(object)); // js.WriteObject(ms, obj); // return ms.ToArray(); //} } public static object Deserialize(byte[] stream) { var formatter = new BinaryFormatter(); MemoryStream ms = new MemoryStream(stream); object obj = formatter.Deserialize(ms); ms.Close(); return obj; //using (MemoryStream ms = new MemoryStream(stream)) { // DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(object)); // return js.ReadObject(ms); //} } #endregion /// <summary> /// 将 plist 格式的 xml 内容,解析成 Newtowsoft.Json JObject 对象来访问 /// </summary> /// <param name="plist">plist 格式的 xml 内容</param> /// <returns>JObject</returns> public static JObject ParsePListToJson(string plist) { NSObject obj = XmlPropertyListParser.Parse(Encoding.UTF8.GetBytes(plist)); string json = JsonConvert.SerializeObject(obj.ToObject()); return JsonConvert.DeserializeObject<JObject>(json); } /// <summary> /// 重试某过程 maxError 次,直到成功或失败 /// </summary> /// <param name="handler">托管函数</param> /// <param name="maxError">允许失败的次数</param> /// <returns>如果执行成功,则返回 null, 否则返回该错误对象</returns> public static Exception Trys(AnonymousHandler handler, int maxError) { if (handler != null) { Exception ex = null; for (int a = 0; a < maxError; a++) { try { handler(); return null; } catch (Exception e) { ex = e; } } return ex; } return null; } /// <summary> /// 延迟 milliSecond 毫秒后执行 handler,与 javascript 里的 setTimeout 相似 /// </summary> /// <param name="handler">托管函数</param> /// <param name="milliSecond">毫秒</param> public static void SetTimeout(AnonymousHandler handler, int milliSecond) { new Timer((a) => { try { handler(); } catch { } }, null, milliSecond, milliSecond); } /// <summary> /// 将服务器端数据转换成安全的JS字符串 /// </summary> /// <param name="input">一个服务器端变量或字符串</param> /// <returns>安全的JS字符串</returns> public static string GetJsString(object input) { if (input == null) return string.Empty; return string.Concat(input).Replace("\\", "\\\\").Replace("\r", "\\r").Replace("\n", "\\n").Replace("'", "\\'"); } static Dictionary<string, Type> _InvokeMethod_cache_type = new Dictionary<string, Type>(); static object _InvokeMethod_cache_type_lock = new object(); public static object InvokeMethod(string typeName, string method, params object[] parms) { Type type; if (!_InvokeMethod_cache_type.TryGetValue(typeName, out type)) { type = System.Type.GetType(typeName); lock (_InvokeMethod_cache_type_lock) { if (!_InvokeMethod_cache_type.TryGetValue(typeName, out type)) _InvokeMethod_cache_type.Add(typeName, type); } } return type.GetMethod(method).Invoke(null, parms); } /// <summary> /// 获取对象属性 /// </summary> /// <param name="obj">对象</param> /// <param name="property">属性,此属性可为多级属性,如:newsInfo.newsClassInfo...</param> /// <returns>对象的(子)属性</returns> public static object EvaluateValue(object obj, string property) { if (obj == null) return null; string prop = property; object ret = string.Empty; if (property.Contains(".")) { prop = property.Substring(0, property.IndexOf(".")); PropertyInfo propa = EvaluateValue_GetProperty(obj, prop); if (propa != null) { object obja = propa.GetValue(obj, null); ret = EvaluateValue(obja, property.Substring(property.IndexOf(".") + 1)); } } else { PropertyInfo propa = EvaluateValue_GetProperty(obj, prop); if (propa != null) { ret = propa.GetValue(obj, null); } } return ret; } private static PropertyInfo EvaluateValue_GetProperty(object obj, string property) { if (obj == null) return null; Type type = obj.GetType(); PropertyInfo ret = type.GetProperty(property); if (ret == null) { PropertyInfo[] pis = type.GetProperties(); foreach (PropertyInfo pi in pis) { if (string.Compare(pi.Name, property, true) == 0) { ret = pi; break; } } } return ret; } /// <summary> /// (安全转换)对象/值转换类型 /// </summary> /// <typeparam name="T">转换后的类型</typeparam> /// <param name="input">转换的对象</param> /// <returns>转换后的对象/值</returns> public static T ConvertTo<T>(object input) { return ConvertTo<T>(input, default(T)); } public static T ConvertTo<T>(object input, T defaultValue) { if (input == null) return defaultValue; object obj = null; if (defaultValue is System.Byte || defaultValue is System.Decimal || defaultValue is System.Int16 || defaultValue is System.Int32 || defaultValue is System.Int64 || defaultValue is System.SByte || defaultValue is System.Single || defaultValue is System.UInt16 || defaultValue is System.UInt32 || defaultValue is System.UInt64) { decimal trydec = 0; if (decimal.TryParse(string.Concat(input), out trydec)) obj = trydec; } else { if (defaultValue is System.DateTime) { DateTime trydt = DateTime.Now; if (DateTime.TryParse(string.Concat(input), out trydt)) obj = trydt; } else { if (defaultValue is System.Boolean) { bool trybool = false; if (bool.TryParse(string.Concat(input), out trybool)) obj = trybool; } else { if (defaultValue is System.Double) { double trydb = 0; if (double.TryParse(string.Concat(input), out trydb)) obj = trydb; } else { obj = input; } } } } try { if (obj != null) return (T)Convert.ChangeType(obj, typeof(T)); } catch { } return defaultValue; } }
2881099/dotnetGen_sqlserver
898
Server/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 有关程序集的常规信息通过下列属性集 // 控制。更改这些属性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("Server")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Server")] [assembly: AssemblyCopyright("版权所有 (C) 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 将 ComVisible 设置为 false 使此程序集中的类型 // 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型, // 则将该类型上的 ComVisible 属性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID [assembly: Guid("1963fe13-0957-46b8-b20c-593eb34a5897")] // 程序集的版本信息由下面四个值组成: // // 主版本 // 次版本 // 内部版本号 // 修订号 // // 可以指定所有这些值,也可以使用“修订号”和“内部版本号”的默认值, // 方法是按如下所示使用“*”: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
27182812/ChatGLM-LLaMA-chinese-insturct
7,895
src/transformers/models/transfo_xl/configuration_transfo_xl.py
# coding=utf-8 # Copyright 2018 Google AI, Google Brain and Carnegie Mellon University Authors and the HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. 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. """ Transformer XL configuration""" from ...configuration_utils import PretrainedConfig from ...utils import logging logger = logging.get_logger(__name__) TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP = { "transfo-xl-wt103": "https://huggingface.co/transfo-xl-wt103/resolve/main/config.json", } class TransfoXLConfig(PretrainedConfig): """ This is the configuration class to store the configuration of a [`TransfoXLModel`] or a [`TFTransfoXLModel`]. It is used to instantiate a Transformer-XL model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the TransfoXL [transfo-xl-wt103](https://huggingface.co/transfo-xl-wt103) architecture. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the documentation from [`PretrainedConfig`] for more information. Args: vocab_size (`int`, *optional*, defaults to 267735): Vocabulary size of the BERT model. Defines the number of different tokens that can be represented by the `inputs_ids` passed when calling [`TransfoXLModel`] or [`TFTransfoXLModel`]. cutoffs (`List[int]`, *optional*, defaults to `[20000, 40000, 200000]`): Cutoffs for the adaptive softmax. d_model (`int`, *optional*, defaults to 1024): Dimensionality of the model's hidden states. d_embed (`int`, *optional*, defaults to 1024): Dimensionality of the embeddings n_head (`int`, *optional*, defaults to 16): Number of attention heads for each attention layer in the Transformer encoder. d_head (`int`, *optional*, defaults to 64): Dimensionality of the model's heads. d_inner (`int`, *optional*, defaults to 4096): Inner dimension in FF div_val (`int`, *optional*, defaults to 4): Divident value for adapative input and softmax pre_lnorm (`boolean`, *optional*, defaults to `False`): Whether or not to apply LayerNorm to the input instead of the output in the blocks. n_layer (`int`, *optional*, defaults to 18): Number of hidden layers in the Transformer encoder. mem_len (`int`, *optional*, defaults to 1600): Length of the retained previous heads. clamp_len (`int`, *optional*, defaults to 1000): Use the same pos embeddings after clamp_len. same_length (`boolean`, *optional*, defaults to `True`): Whether or not to use the same attn length for all tokens proj_share_all_but_first (`boolean`, *optional*, defaults to `True`): True to share all but first projs, False not to share. attn_type (`int`, *optional*, defaults to 0): Attention type. 0 for Transformer-XL, 1 for Shaw et al, 2 for Vaswani et al, 3 for Al Rfou et al. sample_softmax (`int`, *optional*, defaults to -1): Number of samples in the sampled softmax. adaptive (`boolean`, *optional*, defaults to `True`): Whether or not to use adaptive softmax. dropout (`float`, *optional*, defaults to 0.1): The dropout probability for all fully connected layers in the embeddings, encoder, and pooler. dropatt (`float`, *optional*, defaults to 0): The dropout ratio for the attention probabilities. untie_r (`boolean`, *optional*, defaults to `True`): Whether ot not to untie relative position biases. init (`str`, *optional*, defaults to `"normal"`): Parameter initializer to use. init_range (`float`, *optional*, defaults to 0.01): Parameters initialized by U(-init_range, init_range). proj_init_std (`float`, *optional*, defaults to 0.01): Parameters initialized by N(0, init_std) init_std (`float`, *optional*, defaults to 0.02): Parameters initialized by N(0, init_std) layer_norm_epsilon (`float`, *optional*, defaults to 1e-5): The epsilon to use in the layer normalization layers Examples: ```python >>> from transformers import TransfoXLConfig, TransfoXLModel >>> # Initializing a Transformer XL configuration >>> configuration = TransfoXLConfig() >>> # Initializing a model (with random weights) from the configuration >>> model = TransfoXLModel(configuration) >>> # Accessing the model configuration >>> configuration = model.config ```""" model_type = "transfo-xl" keys_to_ignore_at_inference = ["mems"] attribute_map = { "n_token": "vocab_size", "hidden_size": "d_model", "num_attention_heads": "n_head", "num_hidden_layers": "n_layer", } def __init__( self, vocab_size=267735, cutoffs=[20000, 40000, 200000], d_model=1024, d_embed=1024, n_head=16, d_head=64, d_inner=4096, div_val=4, pre_lnorm=False, n_layer=18, mem_len=1600, clamp_len=1000, same_length=True, proj_share_all_but_first=True, attn_type=0, sample_softmax=-1, adaptive=True, dropout=0.1, dropatt=0.0, untie_r=True, init="normal", init_range=0.01, proj_init_std=0.01, init_std=0.02, layer_norm_epsilon=1e-5, eos_token_id=0, **kwargs, ): self.vocab_size = vocab_size self.cutoffs = [] self.cutoffs.extend(cutoffs) if proj_share_all_but_first: self.tie_projs = [False] + [True] * len(self.cutoffs) else: self.tie_projs = [False] + [False] * len(self.cutoffs) self.d_model = d_model self.d_embed = d_embed self.d_head = d_head self.d_inner = d_inner self.div_val = div_val self.pre_lnorm = pre_lnorm self.n_layer = n_layer self.n_head = n_head self.mem_len = mem_len self.same_length = same_length self.attn_type = attn_type self.clamp_len = clamp_len self.sample_softmax = sample_softmax self.adaptive = adaptive self.dropout = dropout self.dropatt = dropatt self.untie_r = untie_r self.init = init self.init_range = init_range self.proj_init_std = proj_init_std self.init_std = init_std self.layer_norm_epsilon = layer_norm_epsilon super().__init__(eos_token_id=eos_token_id, **kwargs) @property def max_position_embeddings(self): # Message copied from Transformer-XL documentation logger.info(f"The model {self.model_type} is one of the few models that has no sequence length limit.") return -1 @max_position_embeddings.setter def max_position_embeddings(self, value): # Message copied from Transformer-XL documentation raise NotImplementedError( f"The model {self.model_type} is one of the few models that has no sequence length limit." )
2881099/dotnetGen_postgresql
3,888
GenPg/Lib/IniHelper.cs
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.IO; public class IniHelper { private static Dictionary<string, object> _cache = new Dictionary<string, object>(); private static Dictionary<string, FileSystemWatcher> _watcher = new Dictionary<string, FileSystemWatcher>(); private static object _lock = new object(); private static object loadAndCache(string path) { path = TranslateUrl(path); object ret = null; if (!_cache.TryGetValue(path, out ret)) { object value2 = LoadIniNotCache(path); string dir = Path.GetDirectoryName(path); string name = Path.GetFileName(path); FileSystemWatcher fsw = new FileSystemWatcher(dir, name); fsw.IncludeSubdirectories = false; fsw.Changed += watcher_handler; fsw.Renamed += watcher_handler; fsw.EnableRaisingEvents = false; lock (_lock) { if (!_cache.TryGetValue(path, out ret)) { _cache.Add(path, ret = value2); _watcher.Add(path, fsw); fsw.EnableRaisingEvents = true; } else { fsw.Dispose(); } } } return ret; } private static void watcher_handler(object sender, FileSystemEventArgs e) { lock (_lock) { _cache.Remove(e.FullPath); FileSystemWatcher fsw = null; if (_watcher.TryGetValue(e.FullPath, out fsw)) { fsw.EnableRaisingEvents = false; fsw.Dispose(); } } } public static Dictionary<string, NameValueCollection> LoadIni(string path) { return loadAndCache(path) as Dictionary<string, NameValueCollection>; } public static Dictionary<string, NameValueCollection> LoadIniNotCache(string path) { Dictionary<string, NameValueCollection> ret = new Dictionary<string, NameValueCollection>(); string[] lines = ReadTextFile(path).Split(new string[] { "\n" }, StringSplitOptions.None); string key = ""; foreach (string line2 in lines) { string line = line2.Trim(); if (string.IsNullOrEmpty(line) || line.StartsWith("#") || line.StartsWith(";")) continue; Match m = Regex.Match(line, @"^\[([^\]]+)\]$"); if (m.Success) { key = m.Groups[1].Value; continue; } if (!ret.ContainsKey(key)) ret.Add(key, new NameValueCollection()); string[] kv = line.Split(new char[] { '=' }, 2); if (!string.IsNullOrEmpty(kv[0])) { ret[key][kv[0]] = kv.Length > 1 ? kv[1] : null; } } return ret; } public static string ReadTextFile(string path) { byte[] bytes = ReadFile(path); return Encoding.UTF8.GetString(bytes).TrimStart((char)65279); } public static byte[] ReadFile(string path) { if (File.Exists(path)) { string destFileName = Path.GetTempFileName(); File.Copy(path, destFileName, true); int read = 0; byte[] data = new byte[1024]; using (MemoryStream ms = new MemoryStream()) { using (FileStream fs = new FileStream(destFileName, FileMode.OpenOrCreate, FileAccess.Read)) { do { read = fs.Read(data, 0, data.Length); if (read <= 0) break; ms.Write(data, 0, read); } while (true); } File.Delete(destFileName); data = ms.ToArray(); } return data; } return new byte[] { }; } public static string TranslateUrl(string url) { return TranslateUrl(url, null); } public static string TranslateUrl(string url, string baseDir) { if (string.IsNullOrEmpty(baseDir)) baseDir = AppContext.BaseDirectory + "/"; if (string.IsNullOrEmpty(url)) return Path.GetDirectoryName(baseDir); if (url.StartsWith("~/")) url = url.Substring(1); if (url.StartsWith("/")) return Path.GetFullPath(Path.Combine(Path.GetDirectoryName(baseDir), url.TrimStart('/'))); if (url.StartsWith("\\")) return Path.GetFullPath(Path.Combine(Path.GetDirectoryName(baseDir), url.TrimStart('\\'))); if (url.IndexOf(":\\") != -1) return url; return Path.GetFullPath(Path.Combine(Path.GetDirectoryName(baseDir), url)); } }
2881099/dotnetGen_sqlserver
14,099
Server/Properties/Resources.Designer.cs
//------------------------------------------------------------------------------ // <auto-generated> // 此代码由工具生成。 // 运行时版本:4.0.30319.42000 // // 对此文件的更改可能会导致不正确的行为,并且如果 // 重新生成代码,这些更改将会丢失。 // </auto-generated> //------------------------------------------------------------------------------ namespace Server.Properties { using System; /// <summary> /// 一个强类型的资源类,用于查找本地化的字符串等。 /// </summary> // 此类是由 StronglyTypedResourceBuilder // 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。 // 若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen // (以 /str 作为命令选项),或重新生成 VS 项目。 [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// 返回此类使用的缓存的 ResourceManager 实例。 /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Server.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// 使用此强类型资源类,为所有资源查找 /// 重写当前线程的 CurrentUICulture 属性。 /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// 查找类似 ///rem dotnet restore /// ///rem cd src/Module/Admin &amp;&amp; dotnet build &amp;&amp; cd ../../../ ///rem cd src/Module/Order &amp;&amp; dotnet build &amp;&amp; cd ../../../ ///rem cd src/Module/Search &amp;&amp; dotnet build &amp;&amp; cd ../../../ /// ///dotnet build /// ///rem cd src/WebHost &amp;&amp; npm install &amp;&amp; npm install --global gulp-cli &amp;&amp; gulp copy-module ///cd src/WebHost &amp;&amp; gulp copy-module &amp;&amp; cd ../../ /// ///echo &quot;Then type &apos;dotnet run&apos; in src/WebHost to start the app.&quot; /// ///pause 的本地化字符串。 /// </summary> internal static string _build_bat { get { return ResourceManager.GetString("_build_bat", resourceCulture); } } /// <summary> /// 查找类似 ############################################################################### ///# Set default behavior to automatically normalize line endings. ///############################################################################### ///* text=auto /// ///############################################################################### ///# Set default behavior for command prompt diff. ///# ///# This is need for earlier builds of msysgit that does not have it on by ///# default for csharp files. ///# Note: This is only used by comma [字符串的其余部分被截断]&quot;; 的本地化字符串。 /// </summary> internal static string _gitattributes { get { return ResourceManager.GetString("_gitattributes", resourceCulture); } } /// <summary> /// 查找类似 ## Ignore Visual Studio temporary files, build results, and ///## files generated by popular Visual Studio add-ons. /// ///# User-specific files ///*.suo ///*.user ///*.userosscache ///*.sln.docstates /// ///# User-specific files (MonoDevelop/Xamarin Studio) ///*.userprefs /// ///# Build results ///[Dd]ebug/ ///[Dd]ebugPublic/ ///[Rr]elease/ ///[Rr]eleases/ ///[Xx]64/ ///[Xx]86/ ///[Bb]uild/ ///bld/ ///[Bb]in/ ///[Oo]bj/ /// ///# Visual Studio 2015 cache/options directory ///.vs/ ///# Uncomment if you have tasks that create the project&apos;s static files in wwwr [字符串的其余部分被截断]&quot;; 的本地化字符串。 /// </summary> internal static string _gitignore { get { return ResourceManager.GetString("_gitignore", resourceCulture); } } /// <summary> /// 查找 System.Byte[] 类型的本地化资源。 /// </summary> internal static byte[] htm_zip { get { object obj = ResourceManager.GetObject("htm_zip", resourceCulture); return ((byte[])(obj)); } } /// <summary> /// 查找类似 using Microsoft.AspNetCore.Cors; ///using Microsoft.AspNetCore.Http; ///using Microsoft.AspNetCore.Mvc; ///using Microsoft.AspNetCore.Mvc.Filters; ///using Microsoft.Extensions.Configuration; ///using Microsoft.Extensions.Logging; ///using Newtonsoft.Json; ///using System; ///using System.Collections; ///using System.Linq; ///using System.Threading.Tasks; /// ///[ServiceFilter(typeof(CustomExceptionFilter)), EnableCors(&quot;cors_all&quot;)] ///public partial class BaseController : Controller { /// public ILogger _logger; /// public ISession Sess [字符串的其余部分被截断]&quot;; 的本地化字符串。 /// </summary> internal static string Infrastructure_Controllers_BaseController_cs { get { return ResourceManager.GetString("Infrastructure_Controllers_BaseController_cs", resourceCulture); } } /// <summary> /// 查找类似 using Microsoft.AspNetCore.Hosting; ///using Microsoft.AspNetCore.Http; ///using Microsoft.AspNetCore.Mvc; ///using Microsoft.AspNetCore.Mvc.Filters; ///using Microsoft.Extensions.Configuration; ///using Microsoft.Extensions.Logging; ///using System; ///using System.Collections.Generic; ///using System.Security.Cryptography; ///using System.Text; ///using System.Threading.Tasks; /// ///public class CustomExceptionFilter : Attribute, IExceptionFilter { /// private ILogger _logger = null; /// private IConfiguration _cfg = null; /// privat [字符串的其余部分被截断]&quot;; 的本地化字符串。 /// </summary> internal static string Infrastructure_Controllers_CustomExceptionFilter_cs { get { return ResourceManager.GetString("Infrastructure_Controllers_CustomExceptionFilter_cs", resourceCulture); } } /// <summary> /// 查找类似 using Newtonsoft.Json; ///using System; ///using System.Text.RegularExpressions; /// ///public static class GlobalExtensions { /// public static object Json(this Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper html, object obj) { /// string str = JsonConvert.SerializeObject(obj); /// if (!string.IsNullOrEmpty(str)) str = Regex.Replace(str, @&quot;&lt;(/?script[\s&gt;])&quot;, &quot;&lt;\&quot;+\&quot;$1&quot;, RegexOptions.IgnoreCase); /// if (html == null) return str; /// return html.Raw(str); /// } /// /// /// &lt;summary&gt; /// /// 转格林时间,并以ISO8601格式化字符串 /// /// &lt;/summary&gt; [字符串的其余部分被截断]&quot;; 的本地化字符串。 /// </summary> internal static string Infrastructure_Extensions_GlobalExtensions_cs { get { return ResourceManager.GetString("Infrastructure_Extensions_GlobalExtensions_cs", resourceCulture); } } /// <summary> /// 查找类似 using Microsoft.AspNetCore.Builder; ///using Microsoft.Extensions.DependencyInjection; /// ///public interface IModuleInitializer { /// void Init(IApplicationBuilder services); ///} 的本地化字符串。 /// </summary> internal static string Infrastructure_ModuleBasic_IModuleInitializer_cs { get { return ResourceManager.GetString("Infrastructure_ModuleBasic_IModuleInitializer_cs", resourceCulture); } } /// <summary> /// 查找类似 using System.Linq; ///using System.Reflection; /// ///public class ModuleInfo { /// public string Name { get; set; } /// /// public Assembly Assembly { get; set; } /// /// public string ShortName { /// get { /// return Name.Split(&apos;.&apos;).Last(); /// } /// } /// /// public string Path { get; set; } ///} 的本地化字符串。 /// </summary> internal static string Infrastructure_ModuleBasic_ModuleInfo_cs { get { return ResourceManager.GetString("Infrastructure_ModuleBasic_ModuleInfo_cs", resourceCulture); } } /// <summary> /// 查找类似 using Microsoft.AspNetCore.Mvc.Razor; ///using System.Collections.Generic; ///using System.Linq; /// ///public class ModuleViewLocationExpander : IViewLocationExpander { /// private const string _moduleKey = &quot;module&quot;; /// /// public IEnumerable&lt;string&gt; ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable&lt;string&gt; viewLocations) { /// if (context.Values.ContainsKey(_moduleKey)) { /// var module = context.Values[_moduleKey]; /// if (!string.IsNullOrWhiteSpace(module)) { /// var moduleViewLocations = new stri [字符串的其余部分被截断]&quot;; 的本地化字符串。 /// </summary> internal static string Infrastructure_ModuleBasic_ModuleViewLocationExpander_cs { get { return ResourceManager.GetString("Infrastructure_ModuleBasic_ModuleViewLocationExpander_cs", resourceCulture); } } /// <summary> /// 查找类似 [Mm]odule/ ///wwwroot/[Mm]odule/ 的本地化字符串。 /// </summary> internal static string WebHost_gitignore { get { return ResourceManager.GetString("WebHost_gitignore", resourceCulture); } } /// <summary> /// 查找类似 &quot;use strict&quot;; /// ///var gulp = require(&apos;gulp&apos;), /// clean = require(&apos;gulp-clean&apos;), /// glob = require(&quot;glob&quot;); /// ///var paths = { /// devModule: &quot;../Module/&quot;, /// hostModule: &quot;./Module/&quot;, /// hostWwwrootModules: &quot;./wwwroot/module/&quot; ///}; /// ///var modules = loadModules(); /// ///gulp.task(&apos;clean-module&apos;, function () { /// return gulp.src([paths.hostModule + &apos;*&apos;, paths.hostWwwrootModules + &apos;*&apos;], { read: false }) /// .pipe(clean()); ///}); /// ///gulp.task(&apos;copy-module&apos;, [&apos;clean-module&apos;], function () { /// modules.forEach(f [字符串的其余部分被截断]&quot;; 的本地化字符串。 /// </summary> internal static string WebHost_gulpfile_js { get { return ResourceManager.GetString("WebHost_gulpfile_js", resourceCulture); } } /// <summary> /// 查找类似 { /// &quot;version&quot;: &quot;1.0.0&quot;, /// &quot;name&quot;: &quot;aaa&quot;, /// &quot;private&quot;: true, /// &quot;devDependencies&quot;: { /// &quot;gulp&quot;: &quot;3.9.1&quot;, /// &quot;gulp-clean&quot;: &quot;0.3.2&quot;, /// &quot;glob&quot;: &quot;7.1.1&quot; /// } ///} 的本地化字符串。 /// </summary> internal static string WebHost_package_json { get { return ResourceManager.GetString("WebHost_package_json", resourceCulture); } } /// <summary> /// 查找类似 &lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt; ///&lt;configuration&gt; /// /// &lt;!-- /// Configure your application settings in appsettings.json. Learn more at http://go.microsoft.com/fwlink/?LinkId=786380 /// --&gt; /// /// &lt;system.webServer&gt; /// &lt;handlers&gt; /// &lt;add name=&quot;aspNetCore&quot; path=&quot;*&quot; verb=&quot;*&quot; modules=&quot;AspNetCoreModule&quot; resourceType=&quot;Unspecified&quot;/&gt; /// &lt;/handlers&gt; /// &lt;aspNetCore processPath=&quot;%LAUNCHER_PATH%&quot; arguments=&quot;%LAUNCHER_ARGS%&quot; stdoutLogEnabled=&quot;false&quot; stdoutLogFile=&quot;.\logs\stdout&quot; forwardWindowsAuthToken=&quot;f [字符串的其余部分被截断]&quot;; 的本地化字符串。 /// </summary> internal static string WebHost_web_config { get { return ResourceManager.GetString("WebHost_web_config", resourceCulture); } } } }
2881099/dotnetGen_postgresql
3,815
GenPg/WinFormClass/WorkQueue.cs
using System; using System.Collections.Generic; using System.Text; using System.Threading; public class WorkQueue : WorkQueue<AnonymousHandler> { public WorkQueue() : this(16, -1) { } public WorkQueue(int thread) : this(thread, -1) { } public WorkQueue(int thread, int capacity) { base.Thread = thread; base.Capacity = capacity; base.Process += delegate(AnonymousHandler ah) { ah(); }; } } public class WorkQueue<T> : IDisposable { public delegate void WorkQueueProcessHandler(T item); public event WorkQueueProcessHandler Process; private int _thread = 16; private int _capacity = -1; private int _work_index = 0; private Dictionary<int, WorkInfo> _works = new Dictionary<int, WorkInfo>(); private object _works_lock = new object(); private Queue<T> _queue = new Queue<T>(); private object _queue_lock = new object(); public WorkQueue() : this(16, -1) { } public WorkQueue(int thread) : this(thread, -1) { } public WorkQueue(int thread, int capacity) { _thread = thread; _capacity = capacity; } public void Enqueue(T item) { lock (_queue_lock) { if (_capacity > 0 && _queue.Count >= _capacity) return; _queue.Enqueue(item); } lock (_works_lock) { foreach (WorkInfo w in _works.Values) { if (w.IsWaiting) { w.Set(); return; } } } if (_works.Count < _thread) { if (_queue.Count > 0) { int index = 0; lock (_works_lock) { index = _work_index++; _works.Add(index, new WorkInfo()); } new Thread(delegate() { WorkInfo work = _works[index]; while (true) { List<T> de = new List<T>(); if (_queue.Count > 0) { lock (_queue_lock) { if (_queue.Count > 0) { de.Add(_queue.Dequeue()); } } } if (de.Count > 0) { try { this.OnProcess(de[0]); } catch { } } if (_queue.Count == 0) { work.WaitOne(TimeSpan.FromSeconds(20)); if (_queue.Count == 0) { break; } } } lock (_works_lock) { _works.Remove(index); } work.Dispose(); }).Start(); } } } protected virtual void OnProcess(T item) { if (Process != null) { Process(item); } } #region IDisposable 成员 public void Dispose() { lock (_queue_lock) { _queue.Clear(); } lock (_works_lock) { foreach (WorkInfo w in _works.Values) { w.Dispose(); } } } #endregion public int Thread { get { return _thread; } set { if (_thread != value) { _thread = value; } } } public int Capacity { get { return _capacity; } set { if (_capacity != value) { _capacity = value; } } } public int UsedThread { get { return _works.Count; } } public int Queue { get { return _queue.Count; } } public string Statistics { get { string value = string.Format(@"线程:{0}/{1} 队列:{2} ", _works.Count, _thread, _queue.Count); int[] keys = new int[_works.Count]; try { _works.Keys.CopyTo(keys, 0); } catch { lock (_works_lock) { keys = new int[_works.Count]; _works.Keys.CopyTo(keys, 0); } } foreach (int k in keys) { WorkInfo w = null; if (_works.TryGetValue(k, out w)) { value += string.Format(@"线程{0}:{1} ", k, w.IsWaiting); } } return value; } } class WorkInfo : IDisposable { private ManualResetEvent _reset = new ManualResetEvent(false); private bool _isWaiting = false; public void WaitOne(TimeSpan timeout) { try { _reset.Reset(); _isWaiting = true; _reset.WaitOne(timeout); } catch { } } public void Set() { try { _isWaiting = false; _reset.Set(); } catch { } } public bool IsWaiting { get { return _isWaiting; } } #region IDisposable 成员 public void Dispose() { this.Set(); } #endregion } }
27182812/ChatGLM-LLaMA-chinese-insturct
47,147
src/transformers/models/transfo_xl/modeling_tf_transfo_xl.py
# coding=utf-8 # Copyright 2018 Google AI, Google Brain and Carnegie Mellon University Authors and the HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. 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. """ TF 2.0 Transformer XL model. """ from dataclasses import dataclass from typing import List, Optional, Tuple, Union import numpy as np import tensorflow as tf from ...modeling_tf_utils import ( TFModelInputType, TFPreTrainedModel, TFSequenceClassificationLoss, get_initializer, keras_serializable, unpack_inputs, ) from ...tf_utils import shape_list, stable_softmax from ...utils import ( ModelOutput, add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging, ) from .configuration_transfo_xl import TransfoXLConfig from .modeling_tf_transfo_xl_utilities import TFAdaptiveSoftmaxMask logger = logging.get_logger(__name__) _CHECKPOINT_FOR_DOC = "transfo-xl-wt103" _CONFIG_FOR_DOC = "TransfoXLConfig" TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST = [ "transfo-xl-wt103", # See all Transformer XL models at https://huggingface.co/models?filter=transfo-xl ] class TFPositionalEmbedding(tf.keras.layers.Layer): def __init__(self, demb, **kwargs): super().__init__(**kwargs) self.inv_freq = 1 / (10000 ** (tf.range(0, demb, 2.0) / demb)) def call(self, pos_seq, bsz=None): self.inv_freq = tf.cast(self.inv_freq, dtype=pos_seq.dtype) sinusoid_inp = tf.einsum("i,j->ij", pos_seq, self.inv_freq) pos_emb = tf.concat([tf.sin(sinusoid_inp), tf.cos(sinusoid_inp)], -1) if bsz is not None: return tf.tile(pos_emb[:, None, :], [1, bsz, 1]) else: return pos_emb[:, None, :] class TFPositionwiseFF(tf.keras.layers.Layer): def __init__(self, d_model, d_inner, dropout, pre_lnorm=False, layer_norm_epsilon=1e-5, init_std=0.02, **kwargs): super().__init__(**kwargs) self.d_model = d_model self.d_inner = d_inner self.dropout = dropout self.layer_1 = tf.keras.layers.Dense( d_inner, kernel_initializer=get_initializer(init_std), activation=tf.nn.relu, name="CoreNet_._0" ) self.drop_1 = tf.keras.layers.Dropout(dropout) self.layer_2 = tf.keras.layers.Dense(d_model, kernel_initializer=get_initializer(init_std), name="CoreNet_._3") self.drop_2 = tf.keras.layers.Dropout(dropout) self.layer_norm = tf.keras.layers.LayerNormalization(epsilon=layer_norm_epsilon, name="layer_norm") self.pre_lnorm = pre_lnorm def call(self, inp, training=False): if self.pre_lnorm: # layer normalization + positionwise feed-forward core_out = self.layer_norm(inp) core_out = self.layer_1(core_out) core_out = self.drop_1(core_out, training=training) core_out = self.layer_2(core_out) core_out = self.drop_2(core_out, training=training) # residual connection output = core_out + inp else: # positionwise feed-forward core_out = self.layer_1(inp) core_out = self.drop_1(core_out, training=training) core_out = self.layer_2(core_out) core_out = self.drop_2(core_out, training=training) # residual connection + layer normalization output = self.layer_norm(inp + core_out) return output class TFRelPartialLearnableMultiHeadAttn(tf.keras.layers.Layer): def __init__( self, n_head, d_model, d_head, dropout, dropatt=0.0, pre_lnorm=False, r_r_bias=None, r_w_bias=None, layer_norm_epsilon=1e-5, init_std=0.02, output_attentions=False, **kwargs, ): super().__init__(**kwargs) self.n_head = n_head self.d_model = d_model self.d_head = d_head self.dropout = dropout self.output_attentions = output_attentions self.qkv_net = tf.keras.layers.Dense( 3 * n_head * d_head, kernel_initializer=get_initializer(init_std), use_bias=False, name="qkv_net" ) self.drop = tf.keras.layers.Dropout(dropout) self.dropatt = tf.keras.layers.Dropout(dropatt) self.o_net = tf.keras.layers.Dense( d_model, kernel_initializer=get_initializer(init_std), use_bias=False, name="o_net" ) self.layer_norm = tf.keras.layers.LayerNormalization(epsilon=layer_norm_epsilon, name="layer_norm") self.scale = 1 / (d_head**0.5) self.pre_lnorm = pre_lnorm if r_r_bias is not None and r_w_bias is not None: # Biases are shared self.r_r_bias = r_r_bias self.r_w_bias = r_w_bias else: self.r_r_bias = None self.r_w_bias = None self.r_net = tf.keras.layers.Dense( self.n_head * self.d_head, kernel_initializer=get_initializer(init_std), use_bias=False, name="r_net" ) def build(self, input_shape): if self.r_r_bias is None or self.r_w_bias is None: # Biases are not shared self.r_r_bias = self.add_weight( shape=(self.n_head, self.d_head), initializer="zeros", trainable=True, name="r_r_bias" ) self.r_w_bias = self.add_weight( shape=(self.n_head, self.d_head), initializer="zeros", trainable=True, name="r_w_bias" ) super().build(input_shape) def _rel_shift(self, x): x_size = shape_list(x) x = tf.pad(x, [[0, 0], [1, 0], [0, 0], [0, 0]]) x = tf.reshape(x, [x_size[1] + 1, x_size[0], x_size[2], x_size[3]]) x = tf.slice(x, [1, 0, 0, 0], [-1, -1, -1, -1]) x = tf.reshape(x, x_size) return x def call(self, w, r, attn_mask, mems, head_mask, output_attentions, training=False): qlen, rlen, bsz = shape_list(w)[0], shape_list(r)[0], shape_list(w)[1] if mems is not None: mems = tf.cast(mems, dtype=w.dtype) cat = tf.concat([mems, w], 0) if self.pre_lnorm: w_heads = self.qkv_net(self.layer_norm(cat)) else: w_heads = self.qkv_net(cat) r_head_k = self.r_net(r) w_head_q, w_head_k, w_head_v = tf.split(w_heads, 3, axis=-1) w_head_q = w_head_q[-qlen:] else: if self.pre_lnorm: w_heads = self.qkv_net(self.layer_norm(w)) else: w_heads = self.qkv_net(w) r_head_k = self.r_net(r) w_head_q, w_head_k, w_head_v = tf.split(w_heads, 3, axis=-1) klen = shape_list(w_head_k)[0] w_head_q = tf.reshape(w_head_q, (qlen, bsz, self.n_head, self.d_head)) # qlen x bsz x n_head x d_head w_head_k = tf.reshape(w_head_k, (klen, bsz, self.n_head, self.d_head)) # qlen x bsz x n_head x d_head w_head_v = tf.reshape(w_head_v, (klen, bsz, self.n_head, self.d_head)) # qlen x bsz x n_head x d_head r_head_k = tf.reshape(r_head_k, (rlen, self.n_head, self.d_head)) # qlen x n_head x d_head # compute attention score rw_head_q = w_head_q + self.r_w_bias # qlen x bsz x n_head x d_head AC = tf.einsum("ibnd,jbnd->ijbn", rw_head_q, w_head_k) # qlen x klen x bsz x n_head rr_head_q = w_head_q + self.r_r_bias BD = tf.einsum("ibnd,jnd->ijbn", rr_head_q, r_head_k) # qlen x klen x bsz x n_head BD = self._rel_shift(BD) # [qlen x klen x bsz x n_head] attn_score = AC + BD attn_score = attn_score * self.scale # compute attention probability if attn_mask is not None: attn_mask_t = attn_mask[:, :, None, None] attn_mask_t = tf.cast(attn_mask_t, dtype=attn_score.dtype) attn_score = attn_score * (1.0 - attn_mask_t) - 1e30 * attn_mask_t # [qlen x klen x bsz x n_head] attn_prob = stable_softmax(attn_score, axis=1) attn_prob = self.dropatt(attn_prob, training=training) # Mask heads if we want to if head_mask is not None: attn_prob = attn_prob * head_mask # compute attention vector attn_vec = tf.einsum("ijbn,jbnd->ibnd", attn_prob, w_head_v) # [qlen x bsz x n_head x d_head] attn_vec_sizes = shape_list(attn_vec) attn_vec = tf.reshape(attn_vec, (attn_vec_sizes[0], attn_vec_sizes[1], self.n_head * self.d_head)) # linear projection attn_out = self.o_net(attn_vec) attn_out = self.drop(attn_out, training=training) if self.pre_lnorm: # residual connection outputs = [w + attn_out] else: # residual connection + layer normalization outputs = [self.layer_norm(w + attn_out)] if output_attentions: outputs.append(attn_prob) return outputs class TFRelPartialLearnableDecoderLayer(tf.keras.layers.Layer): def __init__( self, n_head, d_model, d_head, d_inner, dropout, dropatt=0.0, pre_lnorm=False, r_w_bias=None, r_r_bias=None, layer_norm_epsilon=1e-5, init_std=0.02, output_attentions=False, **kwargs, ): super().__init__(**kwargs) self.dec_attn = TFRelPartialLearnableMultiHeadAttn( n_head, d_model, d_head, dropout, dropatt=dropatt, pre_lnorm=pre_lnorm, r_w_bias=r_w_bias, r_r_bias=r_r_bias, init_std=init_std, layer_norm_epsilon=layer_norm_epsilon, output_attentions=output_attentions, name="dec_attn", ) self.pos_ff = TFPositionwiseFF( d_model, d_inner, dropout, pre_lnorm=pre_lnorm, init_std=init_std, layer_norm_epsilon=layer_norm_epsilon, name="pos_ff", ) def call(self, dec_inp, r, dec_attn_mask, mems, head_mask, output_attentions, training=False): attn_outputs = self.dec_attn(dec_inp, r, dec_attn_mask, mems, head_mask, output_attentions, training=training) ff_output = self.pos_ff(attn_outputs[0], training=training) outputs = [ff_output] + attn_outputs[1:] return outputs class TFTransfoEmbeddings(tf.keras.layers.Layer): def __init__(self, vocab_size, emb_size, init_std, **kwargs): super().__init__(**kwargs) self.vocab_size = vocab_size self.emb_size = emb_size self.init_std = init_std def build(self, input_shape): self.weight = self.add_weight( shape=(self.vocab_size, self.emb_size), initializer=get_initializer(self.init_std), name="embeddings", ) super().build(input_shape) def call(self, inputs): return tf.gather(self.weight, inputs) class TFAdaptiveEmbedding(tf.keras.layers.Layer): def __init__(self, n_token, d_embed, d_proj, cutoffs, div_val=1, init_std=0.02, sample_softmax=False, **kwargs): super().__init__(**kwargs) self.n_token = n_token self.d_embed = d_embed self.init_std = init_std self.cutoffs = cutoffs + [n_token] self.div_val = div_val self.d_proj = d_proj self.emb_scale = d_proj**0.5 self.cutoff_ends = [0] + self.cutoffs self.emb_layers = [] self.emb_projs = [] if div_val == 1: raise NotImplementedError # Removed these to avoid maintaining dead code - They are not used in our pretrained checkpoint else: for i in range(len(self.cutoffs)): l_idx, r_idx = self.cutoff_ends[i], self.cutoff_ends[i + 1] d_emb_i = d_embed // (div_val**i) self.emb_layers.append( TFTransfoEmbeddings( r_idx - l_idx, d_emb_i, init_std, name=f"emb_layers_._{i}", ) ) def build(self, input_shape): for i in range(len(self.cutoffs)): d_emb_i = self.d_embed // (self.div_val**i) self.emb_projs.append( self.add_weight( shape=(d_emb_i, self.d_proj), initializer=get_initializer(self.init_std), trainable=True, name=f"emb_projs_._{i}", ) ) super().build(input_shape) def call(self, inp): if self.div_val == 1: raise NotImplementedError # Removed these to avoid maintaining dead code - They are not used in our pretrained checkpoint else: inp_flat = tf.reshape(inp, (-1,)) emb_flat = tf.zeros([shape_list(inp_flat)[0], self.d_proj]) for i in range(len(self.cutoffs)): l_idx, r_idx = self.cutoff_ends[i], self.cutoff_ends[i + 1] mask_i = (inp_flat >= l_idx) & (inp_flat < r_idx) inp_i = tf.boolean_mask(inp_flat, mask_i) - l_idx emb_i = self.emb_layers[i](inp_i) emb_i = tf.einsum("id,de->ie", emb_i, self.emb_projs[i]) mask_idx = tf.where(mask_i) scatter = tf.scatter_nd(mask_idx, emb_i, shape_list(emb_flat)) emb_flat = tf.cast(emb_flat, dtype=scatter.dtype) emb_flat += scatter embed_shape = shape_list(inp) + [self.d_proj] embed = tf.reshape(emb_flat, embed_shape) embed *= self.emb_scale return embed @keras_serializable class TFTransfoXLMainLayer(tf.keras.layers.Layer): config_class = TransfoXLConfig def __init__(self, config, **kwargs): super().__init__(**kwargs) self.config = config self.output_hidden_states = config.output_hidden_states self.output_attentions = config.output_attentions self.return_dict = config.use_return_dict self.n_token = config.vocab_size self.d_embed = config.d_embed self.d_model = config.d_model self.n_head = config.n_head self.d_head = config.d_head self.untie_r = config.untie_r self.word_emb = TFAdaptiveEmbedding( config.vocab_size, config.d_embed, config.d_model, config.cutoffs, div_val=config.div_val, init_std=config.init_std, name="word_emb", ) self.drop = tf.keras.layers.Dropout(config.dropout) self.n_layer = config.n_layer self.mem_len = config.mem_len self.attn_type = config.attn_type self.layers = [] if config.attn_type == 0: # the default attention for i in range(config.n_layer): self.layers.append( TFRelPartialLearnableDecoderLayer( config.n_head, config.d_model, config.d_head, config.d_inner, config.dropout, dropatt=config.dropatt, pre_lnorm=config.pre_lnorm, r_w_bias=None if self.untie_r else self.r_w_bias, r_r_bias=None if self.untie_r else self.r_r_bias, layer_norm_epsilon=config.layer_norm_epsilon, init_std=config.init_std, output_attentions=self.output_attentions, name=f"layers_._{i}", ) ) else: # learnable embeddings and absolute embeddings raise NotImplementedError # Removed these to avoid maintaining dead code - They are not used in our pretrained checkpoint self.same_length = config.same_length self.clamp_len = config.clamp_len if self.attn_type == 0: # default attention self.pos_emb = TFPositionalEmbedding(self.d_model, name="pos_emb") else: # learnable embeddings and absolute embeddings raise NotImplementedError # Removed these to avoid maintaining dead code - They are not used in our pretrained checkpoint def build(self, input_shape): if not self.untie_r: self.r_w_bias = self.add_weight( shape=(self.n_head, self.d_head), initializer="zeros", trainable=True, name="r_w_bias" ) self.r_r_bias = self.add_weight( shape=(self.n_head, self.d_head), initializer="zeros", trainable=True, name="r_r_bias" ) super().build(input_shape) def get_input_embeddings(self): return self.word_emb def set_input_embeddings(self, value): raise NotImplementedError def backward_compatible(self): self.sample_softmax = -1 def reset_memory_length(self, mem_len): self.mem_len = mem_len def _prune_heads(self, heads): raise NotImplementedError def init_mems(self, bsz): if self.mem_len > 0: mems = [] for i in range(self.n_layer): empty = tf.zeros([self.mem_len, bsz, self.d_model]) mems.append(empty) return mems else: return None def _update_mems(self, hids, mems, mlen, qlen): # does not deal with None if mems is None: return None # mems is not None assert len(hids) == len(mems), "len(hids) != len(mems)" # There are `mlen + qlen` steps that can be cached into mems new_mems = [] end_idx = mlen + tf.math.maximum(0, qlen) beg_idx = tf.math.maximum(0, end_idx - tf.convert_to_tensor(self.mem_len)) for i in range(len(hids)): mems[i] = tf.cast(mems[i], dtype=hids[i].dtype) cat = tf.concat([mems[i], hids[i]], axis=0) tf.stop_gradient(cat) new_mems.append(cat[beg_idx:end_idx]) return new_mems @unpack_inputs def call( self, input_ids: Optional[TFModelInputType] = None, mems: Optional[List[tf.Tensor]] = None, head_mask: Optional[Union[np.ndarray, tf.Tensor]] = None, inputs_embeds: Optional[Union[np.ndarray, tf.Tensor]] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, labels: Optional[Union[np.ndarray, tf.Tensor]] = None, training: bool = False, ): # the original code for Transformer-XL used shapes [len, bsz] but we want a unified interface in the library # so we transpose here from shape [bsz, len] to shape [len, bsz] if input_ids is not None and inputs_embeds is not None: raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time") elif input_ids is not None: input_ids = tf.transpose(input_ids, perm=(1, 0)) qlen, bsz = shape_list(input_ids) elif inputs_embeds is not None: inputs_embeds = tf.transpose(inputs_embeds, perm=(1, 0, 2)) qlen, bsz = shape_list(inputs_embeds)[:2] else: raise ValueError("You have to specify either input_ids or inputs_embeds") if mems is None: mems = self.init_mems(bsz) # Prepare head mask if needed # 1.0 in head_mask indicate we keep the head # attention_probs has shape bsz x n_heads x N x N # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads] (a head_mask for each layer) # and head_mask is converted to shape [num_hidden_layers x qlen x klen x bsz x n_head] if head_mask is not None: raise NotImplementedError else: head_mask = [None] * self.n_layer if inputs_embeds is not None: word_emb = inputs_embeds else: word_emb = self.word_emb(input_ids) mlen = shape_list(mems[0])[0] if mems is not None else 0 klen = mlen + qlen # Compute decoder attention mask # ::: PyTorch masking code for reference ::: # if self.same_length: # all_ones = word_emb.new_ones((qlen, klen), dtype=torch.uint8) # mask_len = klen - self.mem_len # if mask_len > 0: # mask_shift_len = qlen - mask_len # else: # mask_shift_len = qlen # dec_attn_mask = (torch.triu(all_ones, 1+mlen) # + torch.tril(all_ones, -mask_shift_len))[:, :, None] # -1 # else: # dec_attn_mask = torch.triu( # word_emb.new_ones((qlen, klen), dtype=torch.uint8), diagonal=1+mlen)[:,:,None] # TensorFlow version dec_attn_mask = 1 - tf.linalg.band_part( tf.ones([qlen, klen], dtype=tf.int32), -1, mlen ) # (q, q): diagonal with 1's if self.same_length: mask_len = klen - self.mem_len if mask_len > 0: mask_shift_len = qlen - mask_len else: mask_shift_len = qlen if mask_shift_len >= 1: dec_attn_mask += 1 - tf.linalg.band_part(tf.ones([qlen, klen], dtype=tf.int32), mask_shift_len - 1, -1) else: dec_attn_mask += tf.linalg.band_part(tf.ones([qlen, klen], dtype=tf.int32), -1, -mask_shift_len) hids = [] attentions = [] if output_attentions else None if self.attn_type == 0: # default pos_seq = tf.range(klen - 1, -1, -1.0) if self.clamp_len > 0: pos_seq = tf.minimum(pos_seq, self.clamp_len) pos_emb = self.pos_emb(pos_seq) core_out = self.drop(word_emb, training=training) pos_emb = self.drop(pos_emb, training=training) for i, layer in enumerate(self.layers): hids.append(core_out) mems_i = None if mems is None else mems[i] layer_outputs = layer( core_out, pos_emb, dec_attn_mask, mems_i, head_mask[i], output_attentions, training=training, ) core_out = layer_outputs[0] if output_attentions: attentions.append(layer_outputs[1]) else: # learnable embeddings and absolute embeddings raise NotImplementedError # Removed these to avoid maintaining dead code - They are not used in our pretrained checkpoint core_out = self.drop(core_out, training=training) new_mems = self._update_mems(hids, mems, mlen, qlen) # We transpose back here to shape [bsz, len, hidden_dim] core_out = tf.transpose(core_out, perm=(1, 0, 2)) if output_hidden_states: # Transpose to library standard shape [bsz, len, hidden_dim] and add last layer hids = tuple(tf.transpose(t, perm=(1, 0, 2)) for t in hids) hids = hids + (core_out,) else: hids = None if output_attentions: # Transpose to library standard shape [bsz, n_heads, query_seq_len, key_seq_len] attentions = tuple(tf.transpose(t, perm=(2, 3, 0, 1)) for t in attentions) if not return_dict: return tuple(v for v in [core_out, new_mems, hids, attentions] if v is not None) return TFTransfoXLModelOutput( last_hidden_state=core_out, mems=new_mems, hidden_states=hids, attentions=attentions, ) class TFTransfoXLPreTrainedModel(TFPreTrainedModel): """ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models. """ config_class = TransfoXLConfig base_model_prefix = "transformer" @tf.function( input_signature=[ { "input_ids": tf.TensorSpec((None, None), tf.int32, name="input_ids"), } ] ) def serving(self, inputs): output = self.call(inputs) return self.serving_output(output) @dataclass class TFTransfoXLModelOutput(ModelOutput): """ Base class for model's outputs that may also contain a past key/values (to speed up sequential decoding). Args: last_hidden_state (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`): Sequence of hidden-states at the output of the last layer of the model. mems (`List[tf.Tensor]` of length `config.n_layers`): Contains pre-computed hidden-states (key and values in the attention blocks). Can be used (see `mems` input) to speed up sequential decoding. The token ids which have their past given to this model should not be passed as input ids as they have already been computed. hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): Tuple of `tf.Tensor` (one for the output of the embeddings + one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer plus the initial embedding outputs. attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. """ last_hidden_state: tf.Tensor = None mems: List[tf.Tensor] = None hidden_states: Optional[Tuple[tf.Tensor]] = None attentions: Optional[Tuple[tf.Tensor]] = None @dataclass class TFTransfoXLLMHeadModelOutput(ModelOutput): """ Base class for model's outputs that may also contain a past key/values (to speed up sequential decoding). Args: losses (`tf.Tensor` of shape *(batch_size, sequence_length-1)*, *optional*, returned when `labels` is provided): Language modeling losses (not reduced). prediction_scores (`tf.Tensor` of shape `(batch_size, sequence_length, config.vocab_size)`): Prediction scores of the language modeling head (scores for each vocabulary token after SoftMax). mems (`List[tf.Tensor]` of length `config.n_layers`): Contains pre-computed hidden-states (key and values in the attention blocks). Can be used (see `mems` input) to speed up sequential decoding. The token ids which have their past given to this model should not be passed as input ids as they have already been computed. hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): Tuple of `tf.Tensor` (one for the output of the embeddings + one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer plus the initial embedding outputs. attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. """ prediction_scores: tf.Tensor = None mems: List[tf.Tensor] = None hidden_states: Optional[Tuple[tf.Tensor]] = None attentions: Optional[Tuple[tf.Tensor]] = None @dataclass class TFTransfoXLSequenceClassifierOutputWithPast(ModelOutput): """ Base class for outputs of sentence classification models. Args: loss (`tf.Tensor` of shape `(1,)`, *optional*, returned when `labels` is provided): Classification (or regression if config.num_labels==1) loss. logits (`tf.Tensor` of shape `(batch_size, config.num_labels)`): Classification (or regression if config.num_labels==1) scores (before SoftMax). mems (`List[tf.Tensor]` of length `config.n_layers`): Contains pre-computed hidden-states (key and values in the attention blocks). Can be used (see `mems` input) to speed up sequential decoding. The token ids which have their past given to this model should not be passed as input ids as they have already been computed. hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): Tuple of `tf.Tensor` (one for the output of the embeddings + one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer plus the initial embedding outputs. attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. """ loss: Optional[tf.Tensor] = None logits: tf.Tensor = None mems: List[tf.Tensor] = None hidden_states: Optional[Tuple[tf.Tensor]] = None attentions: Optional[Tuple[tf.Tensor]] = None TRANSFO_XL_START_DOCSTRING = r""" This model inherits from [`TFPreTrainedModel`]. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.) This model is also a [tf.keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model) subclass. Use it as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and behavior. <Tip> TensorFlow models and layers in `transformers` accept two formats as input: - having all inputs as keyword arguments (like PyTorch models), or - having all inputs as a list, tuple or dict in the first positional argument. The reason the second format is supported is that Keras methods prefer this format when passing inputs to models and layers. Because of this support, when using methods like `model.fit()` things should "just work" for you - just pass your inputs and labels in any format that `model.fit()` supports! If, however, you want to use the second format outside of Keras methods like `fit()` and `predict()`, such as when creating your own layers or models with the Keras `Functional` API, there are three possibilities you can use to gather all the input Tensors in the first positional argument: - a single Tensor with `input_ids` only and nothing else: `model(input_ids)` - a list of varying length with one or several input Tensors IN THE ORDER given in the docstring: `model([input_ids, attention_mask])` or `model([input_ids, attention_mask, token_type_ids])` - a dictionary with one or several input Tensors associated to the input names given in the docstring: `model({"input_ids": input_ids, "token_type_ids": token_type_ids})` Note that when creating models and layers with [subclassing](https://keras.io/guides/making_new_layers_and_models_via_subclassing/) then you don't need to worry about any of this, as you can just pass inputs like you would to any other Python function! </Tip> Parameters: config ([`TransfoXLConfig`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights. """ TRANSFO_XL_INPUTS_DOCSTRING = r""" Args: input_ids (`tf.Tensor` or `Numpy array` of shape `(batch_size, sequence_length)`): Indices of input sequence tokens in the vocabulary. Indices can be obtained using [`BertTokenizer`]. See [`PreTrainedTokenizer.__call__`] and [`PreTrainedTokenizer.encode`] for details. [What are input IDs?](../glossary#input-ids) mems (`List[tf.Tensor]` of length `config.n_layers`): Contains pre-computed hidden-states (key and values in the attention blocks) as computed by the model (see `mems` output below). Can be used to speed up sequential decoding. The token ids which have their mems given to this model should not be passed as `input_ids` as they have already been computed. head_mask (`tf.Tensor` or `Numpy array` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*): Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`: - 1 indicates the head is **not masked**, - 0 indicates the head is **masked**. inputs_embeds (`tf.Tensor` or `Numpy array` of shape `(batch_size, sequence_length, hidden_size)`, *optional*): Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert `input_ids` indices into associated vectors than the model's internal embedding lookup matrix. output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail. This argument can be used only in eager mode, in graph mode the value in the config will be used instead. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. This argument can be used only in eager mode, in graph mode the value in the config will be used instead. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. This argument can be used in eager mode, in graph mode the value will always be set to True. training (`bool`, *optional*, defaults to `False`): Whether or not to use the model in training mode (some modules like dropout modules have different behaviors between training and evaluation). """ @add_start_docstrings( "The bare Bert Model transformer outputting raw hidden-states without any specific head on top.", TRANSFO_XL_START_DOCSTRING, ) class TFTransfoXLModel(TFTransfoXLPreTrainedModel): def __init__(self, config, *inputs, **kwargs): super().__init__(config, *inputs, **kwargs) self.transformer = TFTransfoXLMainLayer(config, name="transformer") @unpack_inputs @add_start_docstrings_to_model_forward(TRANSFO_XL_INPUTS_DOCSTRING) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC, output_type=TFTransfoXLModelOutput, config_class=_CONFIG_FOR_DOC, ) def call( self, input_ids: Optional[TFModelInputType] = None, mems: Optional[List[tf.Tensor]] = None, head_mask: Optional[Union[np.ndarray, tf.Tensor]] = None, inputs_embeds: Optional[Union[np.ndarray, tf.Tensor]] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, training: bool = False, ): outputs = self.transformer( input_ids=input_ids, mems=mems, head_mask=head_mask, inputs_embeds=inputs_embeds, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, training=training, ) return outputs def serving_output(self, output): hs = tf.convert_to_tensor(output.hidden_states) if self.config.output_hidden_states else None attns = tf.convert_to_tensor(output.attentions) if self.config.output_attentions else None return TFTransfoXLModelOutput( last_hidden_state=output.last_hidden_state, mems=tf.convert_to_tensor(output.mems), hidden_states=hs, attentions=attns, ) @add_start_docstrings( """ The Transformer-XL Model with a language modeling head on top (adaptive softmax with weights tied to the adaptive input embeddings) """, TRANSFO_XL_START_DOCSTRING, ) class TFTransfoXLLMHeadModel(TFTransfoXLPreTrainedModel): def __init__(self, config): super().__init__(config) self.transformer = TFTransfoXLMainLayer(config, name="transformer") self.sample_softmax = config.sample_softmax assert self.sample_softmax <= 0, ( "Sampling from the softmax is not implemented yet. Please look at issue: #3310:" " https://github.com/huggingface/transformers/issues/3310" ) self.crit = TFAdaptiveSoftmaxMask( config.vocab_size, config.d_embed, config.d_model, config.cutoffs, div_val=config.div_val, name="crit" ) def _resize_token_embeddings(self, new_num_tokens): raise NotImplementedError() def get_output_embeddings(self): """Double-check if you are using adaptive softmax.""" if len(self.crit.out_layers) > 0: return self.crit.out_layers[-1] return None def reset_memory_length(self, mem_len): self.transformer.reset_memory_length(mem_len) def init_mems(self, bsz): return self.transformer.init_mems(bsz) @unpack_inputs @add_start_docstrings_to_model_forward(TRANSFO_XL_INPUTS_DOCSTRING) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC, output_type=TFTransfoXLLMHeadModelOutput, config_class=_CONFIG_FOR_DOC, ) def call( self, input_ids: Optional[TFModelInputType] = None, mems: Optional[List[tf.Tensor]] = None, head_mask: Optional[Union[np.ndarray, tf.Tensor]] = None, inputs_embeds: Optional[Union[np.ndarray, tf.Tensor]] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, labels: Optional[Union[np.ndarray, tf.Tensor]] = None, training: bool = False, ): if input_ids is not None: bsz, tgt_len = shape_list(input_ids)[:2] else: bsz, tgt_len = shape_list(inputs_embeds)[:2] transformer_outputs = self.transformer( input_ids, mems, head_mask, inputs_embeds, output_attentions, output_hidden_states, return_dict, training=training, ) last_hidden = transformer_outputs[0] pred_hid = last_hidden[:, -tgt_len:] softmax_output = self.crit(pred_hid, labels, training=training) prediction_scores = softmax_output if labels is None else () if not return_dict: return (prediction_scores,) + transformer_outputs[1:] return TFTransfoXLLMHeadModelOutput( prediction_scores=prediction_scores, mems=transformer_outputs.mems, hidden_states=transformer_outputs.hidden_states, attentions=transformer_outputs.attentions, ) def serving_output(self, output): hs = tf.convert_to_tensor(output.hidden_states) if self.config.output_hidden_states else None attns = tf.convert_to_tensor(output.attentions) if self.config.output_attentions else None return TFTransfoXLLMHeadModelOutput( prediction_scores=output.prediction_scores, mems=tf.convert_to_tensor(output.mems), hidden_states=hs, attentions=attns, ) def prepare_inputs_for_generation(self, input_ids, past_key_values=None, **model_kwargs): inputs = {} # if past is defined in model kwargs then use it for faster decoding if past_key_values: input_ids = tf.expand_dims(input_ids[:, -1], axis=-1) else: input_ids = input_ids return inputs @add_start_docstrings( """ The Transfo XL Model transformer with a sequence classification head on top (linear layer). [`TFTransfoXLForSequenceClassification`] uses the last token in order to do the classification, as other causal models (e.g. GPT-1,GPT-2) do. Since it does classification on the last token, it requires to know the position of the last token. If a `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in each row of the batch). """, TRANSFO_XL_START_DOCSTRING, ) class TFTransfoXLForSequenceClassification(TFTransfoXLPreTrainedModel, TFSequenceClassificationLoss): def __init__(self, config, *inputs, **kwargs): super().__init__(config, *inputs, **kwargs) self.num_labels = config.num_labels self.score = tf.keras.layers.Dense( config.num_labels, kernel_initializer=get_initializer(config.init_range), name="score", use_bias=False, ) self.transformer = TFTransfoXLMainLayer(config, name="transformer") def get_output_embeddings(self): return self.transformer.word_emb @unpack_inputs @add_start_docstrings_to_model_forward(TRANSFO_XL_INPUTS_DOCSTRING) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC, output_type=TFTransfoXLSequenceClassifierOutputWithPast, config_class=_CONFIG_FOR_DOC, ) def call( self, input_ids: Optional[TFModelInputType] = None, mems: Optional[List[tf.Tensor]] = None, head_mask: Optional[Union[np.ndarray, tf.Tensor]] = None, inputs_embeds: Optional[Union[np.ndarray, tf.Tensor]] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, labels: Optional[Union[np.ndarray, tf.Tensor]] = None, training: Optional[bool] = False, ) -> Union[Tuple, TFTransfoXLSequenceClassifierOutputWithPast]: r""" labels (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*): Labels for computing the cross entropy classification loss. Indices should be in `[0, ..., config.vocab_size - 1]`. """ transformer_outputs = self.transformer( input_ids=input_ids, mems=mems, head_mask=head_mask, inputs_embeds=inputs_embeds, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, training=training, ) hidden_states = transformer_outputs[0] logits = self.score(hidden_states) in_logits = None if self.config.pad_token_id is None: sequence_lengths = -1 else: if input_ids is not None: sequence_lengths = ( tf.reduce_sum( tf.cast( tf.math.not_equal(input_ids, self.config.pad_token_id), dtype=input_ids.dtype, ), -1, keepdims=False, ) - 1 ) in_logits = tf.gather(logits, sequence_lengths, batch_dims=1, axis=1) else: sequence_lengths = -1 logger.warning( f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be " "unexpected if using padding tokens in conjunction with `inputs_embeds.`" ) loss = None if labels is not None: if input_ids is not None: batch_size, sequence_length = shape_list(input_ids)[:2] else: batch_size, sequence_length = shape_list(inputs_embeds)[:2] assert ( self.config.pad_token_id is not None or batch_size == 1 ), "Cannot handle batch sizes > 1 if no padding token is defined." if not tf.is_tensor(sequence_lengths): in_logits = logits[0:batch_size, sequence_lengths] loss = self.hf_compute_loss(tf.reshape(labels, [-1, 1]), tf.reshape(in_logits, [-1, self.num_labels])) pooled_logits = in_logits if in_logits is not None else logits if not return_dict: output = (pooled_logits,) + transformer_outputs[1:] return ((loss,) + output) if loss is not None else output return TFTransfoXLSequenceClassifierOutputWithPast( loss=loss, logits=pooled_logits, mems=transformer_outputs.mems, hidden_states=transformer_outputs.hidden_states, attentions=transformer_outputs.attentions, ) def serving_output(self, output): hs = tf.convert_to_tensor(output.hidden_states) if self.config.output_hidden_states else None attns = tf.convert_to_tensor(output.attentions) if self.config.output_attentions else None return TFTransfoXLSequenceClassifierOutputWithPast( logits=output.logits, mems=tf.convert_to_tensor(output.mems), hidden_states=hs, attentions=attns )
2881099/dotnetGen_sqlserver
2,201
Server/Resources/WebHost/gulpfile.js
"use strict"; var gulp = require('gulp'), clean = require('gulp-clean'), glob = require("glob"); var paths = { devModule: "../Module/", hostModule: "./Module/", hostWwwrootModules: "./wwwroot/module/" }; var modules = loadModules(); gulp.task('clean-module', function () { return gulp.src([paths.hostModule + '*', paths.hostWwwrootModules + '*'], { read: false }) .pipe(clean()); }); gulp.task('copy-module', ['clean-module'], function () { modules.forEach(function (module) { console.log(paths.devModule + module.fullName + '/Views/**/*.*'); gulp.src([paths.devModule + module.fullName + '/Views/**/*.*'], { base: module.fullName }) .pipe(gulp.dest(paths.hostModule + module.fullName)); gulp.src(paths.devModule + module.fullName + '/bin/Debug/netstandard2.0/**/' + module.fullName + '.*') .pipe(gulp.dest(paths.hostModule + module.fullName)); gulp.src(paths.devModule + module.fullName + '/appsettings.json') .pipe(gulp.dest(paths.hostModule + module.fullName)); gulp.src(paths.devModule + module.fullName + '/wwwroot/**/*.*') .pipe(gulp.dest(paths.hostWwwrootModules + module.name)); }); }); gulp.task('copy-static', function () { modules.forEach(function (module) { gulp.src([paths.devModule + module.fullName + '/Views/**/*.*'], { base: module.fullName }) .pipe(gulp.dest(paths.hostModule + module.fullName)); gulp.src(paths.devModule + module.fullName + '/wwwroot/**/*.*') .pipe(gulp.dest(paths.hostWwwrootModules + module.name)); }); }); function loadModules() { var moduleManifestPaths, modules = []; moduleManifestPaths = glob.sync(paths.devModule + '*/*.csproj', {}); moduleManifestPaths.forEach(function (moduleManifestPath) { var reg = /\/([^\/]+)\/\1\.csproj/.exec(moduleManifestPath); var moduleManifest = { name: reg[1], fullName: reg[1], version: "1.0.0" } //var exec = require('child_process').exec; //var child = exec('echo hello ' + name, function (err, stdout, stderr) { // if (err) throw err; // console.log(stdout); //}); modules.push(moduleManifest); }); return modules; }
27182812/ChatGLM-LLaMA-chinese-insturct
3,182
src/transformers/models/transfo_xl/__init__.py
# Copyright 2020 The HuggingFace Team. 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. from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available _import_structure = { "configuration_transfo_xl": ["TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP", "TransfoXLConfig"], "tokenization_transfo_xl": ["TransfoXLCorpus", "TransfoXLTokenizer"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _import_structure["modeling_transfo_xl"] = [ "TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST", "AdaptiveEmbedding", "TransfoXLForSequenceClassification", "TransfoXLLMHeadModel", "TransfoXLModel", "TransfoXLPreTrainedModel", "load_tf_weights_in_transfo_xl", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _import_structure["modeling_tf_transfo_xl"] = [ "TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST", "TFAdaptiveEmbedding", "TFTransfoXLForSequenceClassification", "TFTransfoXLLMHeadModel", "TFTransfoXLMainLayer", "TFTransfoXLModel", "TFTransfoXLPreTrainedModel", ] if TYPE_CHECKING: from .configuration_transfo_xl import TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, TransfoXLConfig from .tokenization_transfo_xl import TransfoXLCorpus, TransfoXLTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_transfo_xl import ( TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST, AdaptiveEmbedding, TransfoXLForSequenceClassification, TransfoXLLMHeadModel, TransfoXLModel, TransfoXLPreTrainedModel, load_tf_weights_in_transfo_xl, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_transfo_xl import ( TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST, TFAdaptiveEmbedding, TFTransfoXLForSequenceClassification, TFTransfoXLLMHeadModel, TFTransfoXLMainLayer, TFTransfoXLModel, TFTransfoXLPreTrainedModel, ) else: import sys sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
2881099/dotnetGen_postgresql
11,008
GenPg/WinFormClass/Robot.cs
using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Threading; /// <summary> /// 作业调度器,一般运行在控制台 /// </summary> public class Robot : IDisposable { private string _def_path; private List<RobotDef> _robots; private Dictionary<string, RobotDef> _dic_robots = new Dictionary<string, RobotDef>(); private object _robots_lock = new object(); private FileSystemWatcher _defWatcher; public event RobotErrorHandler Error; public event RobotRunHandler Run; public Robot() : this(Path.Combine(AppContext.BaseDirectory, @"robot.txt")) { } public Robot(string path) { _def_path = path; } public void Start() { lock (_robots_lock) { _dic_robots.Clear(); if (_robots != null) { for (int a = 0; a < _robots.Count; a++) _dic_robots.Add(_robots[a].Name, _robots[a]); _robots.Clear(); } } if (!File.Exists(_def_path)) return; lock (_robots_lock) { _robots = LoadDef(); foreach (RobotDef bot in _robots) if (bot._timer == null) bot.RunNow(); } if (_defWatcher == null) { _defWatcher = new FileSystemWatcher(Path.GetDirectoryName(_def_path), Path.GetFileName(_def_path)); _defWatcher.Changed += delegate(object sender, FileSystemEventArgs e) { _defWatcher.EnableRaisingEvents = false; if (_robots.Count > 0) { Start(); } _defWatcher.EnableRaisingEvents = true; }; _defWatcher.EnableRaisingEvents = true; } } public void Stop() { lock (_robots_lock) { if (_robots != null) { for (int a = 0; a < _robots.Count; a++) _robots[a].Dispose(); _robots.Clear(); } } } #region IDisposable 成员 public void Dispose() { if (_defWatcher != null) _defWatcher.Dispose(); Stop(); } #endregion public List<RobotDef> LoadDef() { string defDoc = Encoding.UTF8.GetString(readFile(_def_path)); return LoadDef(defDoc); } public List<RobotDef> LoadDef(string defDoc) { Dictionary<string, RobotDef> dic = new Dictionary<string, RobotDef>(); string[] defs = defDoc.Split(new string[] { "\n" }, StringSplitOptions.None); int row = 1; foreach (string def in defs) { string loc1 = def.Trim().Trim('\r'); if (string.IsNullOrEmpty(loc1) || loc1[0] == 65279 || loc1[0] == ';' || loc1[0] == '#') continue; string pattern = @"([^\s]+)\s+(NONE|SEC|MIN|HOUR|DAY|RunOnDay|RunOnWeek|RunOnMonth)\s+([^\s]+)\s+([^\s]+)"; Match m = Regex.Match(loc1, pattern, RegexOptions.IgnoreCase); if (!m.Success) { onError(new Exception("Robot配置错误“" + loc1 + "”, 第" + row + "行")); continue; } string name = m.Groups[1].Value.Trim('\t', ' '); RobotRunMode mode = getMode(m.Groups[2].Value.Trim('\t', ' ')); string param = m.Groups[3].Value.Trim('\t', ' '); string runParam = m.Groups[4].Value.Trim('\t', ' '); if (dic.ContainsKey(name)) { onError(new Exception("Robot配置存在重复的名字“" + name + "”, 第" + row + "行")); continue; } if (mode == RobotRunMode.NONE) continue; RobotDef rd = null; if (_dic_robots.ContainsKey(name)) { rd = _dic_robots[name]; rd.Update(mode, param, runParam); _dic_robots.Remove(name); } else rd = new RobotDef(this, name, mode, param, runParam); if (rd.Interval < 0) { onError(new Exception("Robot配置参数错误“" + def + "”, 第" + row + "行")); continue; } dic.Add(rd.Name, rd); row++; } List<RobotDef> rds = new List<RobotDef>(); foreach (RobotDef rd in dic.Values) rds.Add(rd); foreach (RobotDef stopBot in _dic_robots.Values) stopBot.Dispose(); return rds; } private void onError(Exception ex) { onError(ex, null); } internal void onError(Exception ex, RobotDef def) { if (Error != null) Error(this, new RobotErrorEventArgs(ex, def)); } internal void onRun(RobotDef def) { if (Run != null) Run(this, def); } private byte[] readFile(string path) { if (File.Exists(path)) { string destFileName = Path.GetTempFileName(); File.Copy(path, destFileName, true); int read = 0; byte[] data = new byte[1024]; using (MemoryStream ms = new MemoryStream()) { using (FileStream fs = new FileStream(destFileName, FileMode.OpenOrCreate, FileAccess.Read)) { do { read = fs.Read(data, 0, data.Length); if (read <= 0) break; ms.Write(data, 0, read); } while (true); } File.Delete(destFileName); data = ms.ToArray(); } return data; } return new byte[] { }; } private RobotRunMode getMode(string mode) { mode = string.Concat(mode).ToUpper(); switch (mode) { case "SEC": return RobotRunMode.SEC; case "MIN": return RobotRunMode.MIN; case "HOUR": return RobotRunMode.HOUR; case "DAY": return RobotRunMode.DAY; case "RUNONDAY": return RobotRunMode.RunOnDay; case "RUNONWEEK": return RobotRunMode.RunOnWeek; case "RUNONMONTH": return RobotRunMode.RunOnMonth; default: return RobotRunMode.NONE; } } } public class RobotDef : IDisposable { private string _name; private RobotRunMode _mode = RobotRunMode.NONE; private string _param; private string _runParam; private int _runTimes = 0; private int _errTimes = 0; private Robot _onwer; internal Timer _timer; private bool _timerIntervalOverflow = false; public RobotDef(Robot onwer, string name, RobotRunMode mode, string param, string runParam) { _onwer = onwer; _name = name; _mode = mode; _param = param; _runParam = runParam; } public void Update(RobotRunMode mode, string param, string runParam) { if (_mode != mode || _param != param || _runParam != runParam) { _mode = mode; _param = param; _runParam = runParam; if (_timer != null) { _timer.Dispose(); _timer = null; } RunNow(); } } public void RunNow() { double tmp = this.Interval; _timerIntervalOverflow = tmp > int.MaxValue; int interval = _timerIntervalOverflow ? int.MaxValue : (int)tmp; if (interval <= 0) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(" {0} Interval <= 0", _name); Console.ResetColor(); return; } //Console.WriteLine(interval); if (_timer == null) { _timer = new Timer(a => { if (_timerIntervalOverflow) { RunNow(); return; } _runTimes++; string logObj = this.ToString(); try { _onwer.onRun(this); } catch (Exception ex) { _errTimes++; _onwer.onError(ex, this); } RunNow(); }, null, interval, -1); } else { _timer.Change(interval, -1); } if (tmp > 1000 * 9) { DateTime nextTime = DateTime.Now.AddMilliseconds(tmp); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine(" {0} 下次触发时间:{1:yyyy-MM-dd HH:mm:ss}", _name, nextTime); Console.ResetColor(); } } public override string ToString() { return Name + ", " + Mode + ", " + Param + ", " + RunParam; } #region IDisposable 成员 public void Dispose() { if (_timer != null) { _timer.Dispose(); _timer = null; } } #endregion public string Name { get { return _name; } } public RobotRunMode Mode { get { return _mode; } } public string Param { get { return _param; } } public string RunParam { get { return _runParam; } } public int RunTimes { get { return _runTimes; } } public int ErrTimes { get { return _errTimes; } } public double Interval { get { DateTime now = DateTime.Now; DateTime curt = DateTime.MinValue; TimeSpan ts = TimeSpan.Zero; uint ww = 0, dd = 0, hh = 0, mm = 0, ss = 0; double interval = -1; switch (_mode) { case RobotRunMode.SEC: double.TryParse(_param, out interval); interval *= 1000; break; case RobotRunMode.MIN: double.TryParse(_param, out interval); interval *= 60 * 1000; break; case RobotRunMode.HOUR: double.TryParse(_param, out interval); interval *= 60 * 60 * 1000; break; case RobotRunMode.DAY: double.TryParse(_param, out interval); interval *= 24 * 60 * 60 * 1000; break; case RobotRunMode.RunOnDay: List<string> hhmmss = new List<string>(string.Concat(_param).Split(':')); if (hhmmss.Count == 3) if (uint.TryParse(hhmmss[0], out hh) && hh < 24 && uint.TryParse(hhmmss[1], out mm) && mm < 60 && uint.TryParse(hhmmss[2], out ss) && ss < 60) { curt = now.Date.AddHours(hh).AddMinutes(mm).AddSeconds(ss); ts = curt.Subtract(now); while (!(ts.TotalMilliseconds > 0)) { curt = curt.AddDays(1); ts = curt.Subtract(now); } interval = ts.TotalMilliseconds; } break; case RobotRunMode.RunOnWeek: string[] wwhhmmss = string.Concat(_param).Split(':'); if (wwhhmmss.Length == 4) if (uint.TryParse(wwhhmmss[0], out ww) && ww < 7 && uint.TryParse(wwhhmmss[1], out hh) && hh < 24 && uint.TryParse(wwhhmmss[2], out mm) && mm < 60 && uint.TryParse(wwhhmmss[3], out ss) && ss < 60) { curt = now.Date.AddHours(hh).AddMinutes(mm).AddSeconds(ss); ts = curt.Subtract(now); while(!(ts.TotalMilliseconds > 0 && (int)curt.DayOfWeek == ww)) { curt = curt.AddDays(1); ts = curt.Subtract(now); } interval = ts.TotalMilliseconds; } break; case RobotRunMode.RunOnMonth: string[] ddhhmmss = string.Concat(_param).Split(':'); if (ddhhmmss.Length == 4) if (uint.TryParse(ddhhmmss[0], out dd) && dd > 0 && dd < 32 && uint.TryParse(ddhhmmss[1], out hh) && hh < 24 && uint.TryParse(ddhhmmss[2], out mm) && mm < 60 && uint.TryParse(ddhhmmss[3], out ss) && ss < 60) { curt = new DateTime(now.Year, now.Month, (int)dd).AddHours(hh).AddMinutes(mm).AddSeconds(ss); ts = curt.Subtract(now); while (!(ts.TotalMilliseconds > 0)) { curt = curt.AddMonths(1); ts = curt.Subtract(now); } interval = ts.TotalMilliseconds; } break; } if (interval == 0) interval = 1; return interval; } } } /* ; 和 # 匀为行注释 ;SEC: 按秒触发 ;MIN: 按分触发 ;HOUR: 按时触发 ;DAY: 按天触发 ;RunOnDay: 每天 什么时间 触发 ;RunOnWeek: 星期几 什么时间 触发 ;RunOnMonth: 每月 第几天 什么时间 触发 ;Name1 SEC 2 /schedule/test002.aspx ;Name2 MIN 2 /schedule/test002.aspx ;Name3 HOUR 1 /schedule/test002.aspx ;Name4 DAY 2 /schedule/test002.aspx ;Name5 RunOnDay 15:55:59 /schedule/test002.aspx ;每天15点55分59秒 ;Name6 RunOnWeek 1:15:55:59 /schedule/test002.aspx ;每星期一15点55分59秒 ;Name7 RunOnMonth 1:15:55:59 /schedule/test002.aspx ;每月1号15点55分59秒 */ public enum RobotRunMode { NONE = 0, SEC = 1, MIN = 2, HOUR = 3, DAY = 4, RunOnDay = 11, RunOnWeek = 12, RunOnMonth = 13 } public delegate void RobotErrorHandler(object sender, RobotErrorEventArgs e); public delegate void RobotRunHandler(object sender, RobotDef e); public class RobotErrorEventArgs : EventArgs { private Exception _exception; private RobotDef _def; public RobotErrorEventArgs(Exception exception, RobotDef def) { _exception = exception; _def = def; } public Exception Exception { get { return _exception; } } public RobotDef Def { get { return _def; } } }
2881099/dotnetGen_sqlserver
1,264
Server/Resources/Infrastructure/Extensions/GlobalExtensions.cs
using Newtonsoft.Json; using System; using System.Text.RegularExpressions; public static class GlobalExtensions { public static object Json(this Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper html, object obj) { string str = JsonConvert.SerializeObject(obj); if (!string.IsNullOrEmpty(str)) str = Regex.Replace(str, @"<(/?script[\s>])", "<\"+\"$1", RegexOptions.IgnoreCase); if (html == null) return str; return html.Raw(str); } /// <summary> /// 转格林时间,并以ISO8601格式化字符串 /// </summary> /// <param name="time"></param> /// <returns></returns> public static string ToGmtISO8601(this DateTime time) { return time.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ"); } /// <summary> /// 获取时间戳,按1970-1-1 /// </summary> /// <param name="time"></param> /// <returns></returns> public static long GetTime(this DateTime time) { return (long)time.ToUniversalTime().Subtract(new DateTime(1970, 1, 1)).TotalSeconds; } static DateTime dt19700101 = new DateTime(1970, 1, 1); /// <summary> /// 获取时间戳毫秒数,按1970-1-1 /// </summary> /// <param name="time"></param> /// <returns></returns> public static long GetTimeMilliseconds(this DateTime time) { return (long)time.ToUniversalTime().Subtract(new DateTime(1970, 1, 1)).TotalMilliseconds; } }
2881099/dotnetGen_sqlserver
1,194
Server/Resources/Infrastructure/Controllers/CustomExceptionFilter.cs
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; public class CustomExceptionFilter : Attribute, IExceptionFilter { private ILogger _logger = null; private IConfiguration _cfg = null; private IHostingEnvironment _env = null; public CustomExceptionFilter (ILogger<CustomExceptionFilter> logger, IConfiguration cfg, IHostingEnvironment env) { _logger = logger; _cfg = cfg; _env = env; } public void OnException(ExceptionContext context) { //在这里记录错误日志,context.Exception 为异常对象 context.Result = APIReturn.失败.SetMessage(context.Exception.Message); //返回给调用方 var innerLog = context.Exception.InnerException != null ? $" \r\n{context.Exception.InnerException.Message} \r\n{ context.Exception.InnerException.StackTrace}" : ""; _logger.LogError($"=============错误:{context.Exception.Message} \r\n{context.Exception.StackTrace}{innerLog}"); context.ExceptionHandled = true; } }
2881099/dotnetGen_sqlserver
5,159
Server/Resources/Infrastructure/Controllers/BaseController.cs
using Microsoft.AspNetCore.Cors; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using System; using System.Collections; using System.Linq; using System.Threading.Tasks; [ServiceFilter(typeof(CustomExceptionFilter)), EnableCors("cors_all")] public partial class BaseController : Controller { public ILogger _logger; public ISession Session { get { return HttpContext.Session; } } public HttpRequest Req { get { return Request; } } public HttpResponse Res { get { return Response; } } public string Ip => this.Request.Headers["X-Real-IP"].FirstOrDefault() ?? this.Request.HttpContext.Connection.RemoteIpAddress.ToString(); public IConfiguration Configuration => (IConfiguration) HttpContext.RequestServices.GetService(typeof(IConfiguration)); //public SysuserInfo LoginUser { get; private set; } public BaseController(ILogger logger) { _logger = logger; } public override void OnActionExecuting(ActionExecutingContext context) { #region 参数验证 if (context.ModelState.IsValid == false) foreach (var value in context.ModelState.Values) if (value.Errors.Any()) { context.Result = APIReturn.参数格式不正确.SetMessage($"参数格式不正确:{value.Errors.First().ErrorMessage}"); return; } #endregion #region 初始化当前登陆账号 //string username = Session.GetString("login.username"); //if (!string.IsNullOrEmpty(username)) LoginUser = Sysuser.GetItemByUsername(username); //var method = (context.ActionDescriptor as ControllerActionDescriptor).MethodInfo; //if (method.GetCustomAttribute<需要登陆Attribute>() != null && LoginUser == null) // context.Result = new RedirectResult("/signin"); //else if (method.GetCustomAttribute<匿名访问Attribute>() == null && LoginUser == null) // context.Result = new RedirectResult("/signin"); //ViewBag.user = LoginUser; #endregion base.OnActionExecuting(context); } public override void OnActionExecuted(ActionExecutedContext context) { base.OnActionExecuted(context); } #region 角色权限验证 //public bool sysrole_check(string url) { // url = url.ToLower(); // //Response.Write(url + "<br>"); // if (url == "/" || url.IndexOf("/default.aspx") == 0) return true; // foreach(var role in this.LoginUser.Obj_sysroles) { // //Response.Write(role.ToString()); // foreach(var dir in role.Obj_sysdirs) { // //Response.Write("-----------------" + dir.ToString() + "<br>"); // string tmp = dir.Url; // if (tmp.EndsWith("/")) tmp += "default.aspx"; // if (url.IndexOf(tmp) == 0) return true; // } // } // return false; //} #endregion } #region 需要登陆、匿名访问 public partial class 需要登陆Attribute : Attribute { } public partial class 匿名访问Attribute : Attribute { } #endregion #region APIReturn [JsonObject(MemberSerialization.OptIn)] public partial class APIReturn : ContentResult { [JsonProperty("code")] public int Code { get; protected set; } [JsonProperty("message")] public string Message { get; protected set; } [JsonProperty("data")] public Hashtable Data { get; protected set; } = new Hashtable(); [JsonProperty("success")] public bool Success { get { return this.Code == 0; } } public APIReturn() { } public APIReturn(int code) { this.SetCode(code); } public APIReturn(string message) { this.SetMessage(message); } public APIReturn(int code, string message, params object[] data) { this.SetCode(code).SetMessage(message).AppendData(data); } public APIReturn SetCode(int value) { this.Code = value; return this; } public APIReturn SetMessage(string value) { this.Message = value; return this; } public APIReturn SetData(params object[] value) { this.Data.Clear(); return this.AppendData(value); } public APIReturn AppendData(params object[] value) { if (value == null || value.Length < 2 || value[0] == null) return this; for (int a = 0; a < value.Length; a += 2) { if (value[a] == null) continue; this.Data[value[a]] = a + 1 < value.Length ? value[a + 1] : null; } return this; } #region form 表单 target=iframe 提交回调处理 private void Jsonp(ActionContext context) { string __callback = context.HttpContext.Request.HasFormContentType ? context.HttpContext.Request.Form["__callback"].ToString() : null; if (string.IsNullOrEmpty(__callback)) { this.ContentType = "text/json;charset=utf-8;"; this.Content = JsonConvert.SerializeObject(this); }else { this.ContentType = "text/html;charset=utf-8"; this.Content = $"<script>top.{__callback}({GlobalExtensions.Json(null, this)});</script>"; } } public override void ExecuteResult(ActionContext context) { Jsonp(context); base.ExecuteResult(context); } public override Task ExecuteResultAsync(ActionContext context) { Jsonp(context); return base.ExecuteResultAsync(context); } #endregion public static APIReturn 成功 { get { return new APIReturn(0, "成功"); } } public static APIReturn 失败 { get { return new APIReturn(99, "失败"); } } public static APIReturn 记录不存在_或者没有权限 { get { return new APIReturn(98, "记录不存在,或者没有权限"); } } public static APIReturn 参数格式不正确 { get { return new APIReturn(97, "参数格式不正确"); } } } #endregion
27182812/ChatGLM-LLaMA-chinese-insturct
55,820
src/transformers/models/transfo_xl/modeling_transfo_xl.py
# coding=utf-8 # Copyright 2018 Google AI, Google Brain and Carnegie Mellon University Authors and the HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. 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. """ PyTorch Transformer XL model. Adapted from https://github.com/kimiyoung/transformer-xl. In particular https://github.com/kimiyoung/transformer-xl/blob/master/pytorch/mem_transformer.py """ import warnings from dataclasses import dataclass from typing import List, Optional, Tuple, Union import torch from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...modeling_utils import PreTrainedModel from ...utils import ( ModelOutput, add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging, ) from .configuration_transfo_xl import TransfoXLConfig from .modeling_transfo_xl_utilities import ProjectedAdaptiveLogSoftmax logger = logging.get_logger(__name__) _CHECKPOINT_FOR_DOC = "transfo-xl-wt103" _CONFIG_FOR_DOC = "TransfoXLConfig" TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST = [ "transfo-xl-wt103", # See all Transformer XL models at https://huggingface.co/models?filter=transfo-xl ] def build_tf_to_pytorch_map(model, config): """ A map of modules from TF to PyTorch. This time I use a map to keep the PyTorch model as identical to the original PyTorch model as possible. """ tf_to_pt_map = {} if hasattr(model, "transformer"): # We are loading in a TransfoXLLMHeadModel => we will load also the Adaptive Softmax tf_to_pt_map.update( { "transformer/adaptive_softmax/cutoff_0/cluster_W": model.crit.cluster_weight, "transformer/adaptive_softmax/cutoff_0/cluster_b": model.crit.cluster_bias, } ) for i, (out_l, proj_l, tie_proj) in enumerate( zip(model.crit.out_layers, model.crit.out_projs, config.tie_projs) ): layer_str = f"transformer/adaptive_softmax/cutoff_{i}/" if config.tie_word_embeddings: tf_to_pt_map.update({layer_str + "b": out_l.bias}) else: raise NotImplementedError # I don't think this is implemented in the TF code tf_to_pt_map.update({layer_str + "lookup_table": out_l.weight, layer_str + "b": out_l.bias}) if not tie_proj: tf_to_pt_map.update({layer_str + "proj": proj_l}) # Now load the rest of the transformer model = model.transformer # Embeddings for i, (embed_l, proj_l) in enumerate(zip(model.word_emb.emb_layers, model.word_emb.emb_projs)): layer_str = f"transformer/adaptive_embed/cutoff_{i}/" tf_to_pt_map.update({layer_str + "lookup_table": embed_l.weight, layer_str + "proj_W": proj_l}) # Transformer blocks for i, b in enumerate(model.layers): layer_str = f"transformer/layer_{i}/" tf_to_pt_map.update( { layer_str + "rel_attn/LayerNorm/gamma": b.dec_attn.layer_norm.weight, layer_str + "rel_attn/LayerNorm/beta": b.dec_attn.layer_norm.bias, layer_str + "rel_attn/o/kernel": b.dec_attn.o_net.weight, layer_str + "rel_attn/qkv/kernel": b.dec_attn.qkv_net.weight, layer_str + "rel_attn/r/kernel": b.dec_attn.r_net.weight, layer_str + "ff/LayerNorm/gamma": b.pos_ff.layer_norm.weight, layer_str + "ff/LayerNorm/beta": b.pos_ff.layer_norm.bias, layer_str + "ff/layer_1/kernel": b.pos_ff.CoreNet[0].weight, layer_str + "ff/layer_1/bias": b.pos_ff.CoreNet[0].bias, layer_str + "ff/layer_2/kernel": b.pos_ff.CoreNet[3].weight, layer_str + "ff/layer_2/bias": b.pos_ff.CoreNet[3].bias, } ) # Relative positioning biases if config.untie_r: r_r_list = [] r_w_list = [] for b in model.layers: r_r_list.append(b.dec_attn.r_r_bias) r_w_list.append(b.dec_attn.r_w_bias) else: r_r_list = [model.r_r_bias] r_w_list = [model.r_w_bias] tf_to_pt_map.update({"transformer/r_r_bias": r_r_list, "transformer/r_w_bias": r_w_list}) return tf_to_pt_map def load_tf_weights_in_transfo_xl(model, config, tf_path): """Load tf checkpoints in a pytorch model""" try: import numpy as np import tensorflow as tf except ImportError: logger.error( "Loading a TensorFlow models in PyTorch, requires TensorFlow to be installed. Please see " "https://www.tensorflow.org/install/ for installation instructions." ) raise # Build TF to PyTorch weights loading map tf_to_pt_map = build_tf_to_pytorch_map(model, config) # Load weights from TF model init_vars = tf.train.list_variables(tf_path) tf_weights = {} for name, shape in init_vars: logger.info(f"Loading TF weight {name} with shape {shape}") array = tf.train.load_variable(tf_path, name) tf_weights[name] = array for name, pointer in tf_to_pt_map.items(): assert name in tf_weights array = tf_weights[name] # adam_v and adam_m are variables used in AdamWeightDecayOptimizer to calculated m and v # which are not required for using pretrained model if "kernel" in name or "proj" in name: array = np.transpose(array) if ("r_r_bias" in name or "r_w_bias" in name) and len(pointer) > 1: # Here we will split the TF weights assert len(pointer) == array.shape[0] for i, p_i in enumerate(pointer): arr_i = array[i, ...] try: assert p_i.shape == arr_i.shape except AssertionError as e: e.args += (p_i.shape, arr_i.shape) raise logger.info(f"Initialize PyTorch weight {name} for layer {i}") p_i.data = torch.from_numpy(arr_i) else: try: assert ( pointer.shape == array.shape ), f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched" except AssertionError as e: e.args += (pointer.shape, array.shape) raise logger.info(f"Initialize PyTorch weight {name}") pointer.data = torch.from_numpy(array) tf_weights.pop(name, None) tf_weights.pop(name + "/Adam", None) tf_weights.pop(name + "/Adam_1", None) logger.info(f"Weights not copied to PyTorch model: {', '.join(tf_weights.keys())}") return model class PositionalEmbedding(nn.Module): def __init__(self, demb): super().__init__() self.demb = demb inv_freq = 1 / (10000 ** (torch.arange(0.0, demb, 2.0) / demb)) self.register_buffer("inv_freq", inv_freq) def forward(self, pos_seq, bsz=None): sinusoid_inp = torch.ger(pos_seq, self.inv_freq) pos_emb = torch.cat([sinusoid_inp.sin(), sinusoid_inp.cos()], dim=-1) if bsz is not None: return pos_emb[:, None, :].expand(-1, bsz, -1) else: return pos_emb[:, None, :] class PositionwiseFF(nn.Module): def __init__(self, d_model, d_inner, dropout, pre_lnorm=False, layer_norm_epsilon=1e-5): super().__init__() self.d_model = d_model self.d_inner = d_inner self.dropout = dropout self.CoreNet = nn.Sequential( nn.Linear(d_model, d_inner), nn.ReLU(inplace=True), nn.Dropout(dropout), nn.Linear(d_inner, d_model), nn.Dropout(dropout), ) self.layer_norm = nn.LayerNorm(d_model, eps=layer_norm_epsilon) self.pre_lnorm = pre_lnorm def forward(self, inp): if self.pre_lnorm: # layer normalization + positionwise feed-forward core_out = self.CoreNet(self.layer_norm(inp)) # residual connection output = core_out + inp else: # positionwise feed-forward core_out = self.CoreNet(inp) # residual connection + layer normalization output = self.layer_norm(inp + core_out) return output class RelPartialLearnableMultiHeadAttn(nn.Module): def __init__( self, n_head, d_model, d_head, dropout, dropatt=0, pre_lnorm=False, r_r_bias=None, r_w_bias=None, layer_norm_epsilon=1e-5, ): super().__init__() self.n_head = n_head self.d_model = d_model self.d_head = d_head self.dropout = dropout self.qkv_net = nn.Linear(d_model, 3 * n_head * d_head, bias=False) self.drop = nn.Dropout(dropout) self.dropatt = nn.Dropout(dropatt) self.o_net = nn.Linear(n_head * d_head, d_model, bias=False) self.layer_norm = nn.LayerNorm(d_model, eps=layer_norm_epsilon) self.scale = 1 / (d_head**0.5) self.pre_lnorm = pre_lnorm if r_r_bias is None or r_w_bias is None: # Biases are not shared self.r_r_bias = nn.Parameter(torch.FloatTensor(self.n_head, self.d_head)) self.r_w_bias = nn.Parameter(torch.FloatTensor(self.n_head, self.d_head)) else: self.r_r_bias = r_r_bias self.r_w_bias = r_w_bias self.r_net = nn.Linear(self.d_model, self.n_head * self.d_head, bias=False) def _rel_shift(self, x): zero_pad_shape = (x.size(0), 1) + x.size()[2:] zero_pad = torch.zeros(zero_pad_shape, device=x.device, dtype=x.dtype) x_padded = torch.cat([zero_pad, x], dim=1) x_padded_shape = (x.size(1) + 1, x.size(0)) + x.size()[2:] x_padded = x_padded.view(*x_padded_shape) x = x_padded[1:].view_as(x) return x def forward(self, w, r, attn_mask=None, mems=None, head_mask=None, output_attentions=False): qlen, rlen, bsz = w.size(0), r.size(0), w.size(1) if mems is not None: cat = torch.cat([mems, w], 0) if self.pre_lnorm: w_heads = self.qkv_net(self.layer_norm(cat)) else: w_heads = self.qkv_net(cat) r_head_k = self.r_net(r) w_head_q, w_head_k, w_head_v = torch.chunk(w_heads, 3, dim=-1) w_head_q = w_head_q[-qlen:] else: if self.pre_lnorm: w_heads = self.qkv_net(self.layer_norm(w)) else: w_heads = self.qkv_net(w) r_head_k = self.r_net(r) w_head_q, w_head_k, w_head_v = torch.chunk(w_heads, 3, dim=-1) klen = w_head_k.size(0) w_head_q = w_head_q.view(qlen, bsz, self.n_head, self.d_head) # qlen x bsz x n_head x d_head w_head_k = w_head_k.view(klen, bsz, self.n_head, self.d_head) # qlen x bsz x n_head x d_head w_head_v = w_head_v.view(klen, bsz, self.n_head, self.d_head) # qlen x bsz x n_head x d_head r_head_k = r_head_k.view(rlen, self.n_head, self.d_head) # qlen x n_head x d_head # compute attention score rw_head_q = w_head_q + self.r_w_bias # qlen x bsz x n_head x d_head AC = torch.einsum("ibnd,jbnd->ijbn", (rw_head_q, w_head_k)) # qlen x klen x bsz x n_head rr_head_q = w_head_q + self.r_r_bias BD = torch.einsum("ibnd,jnd->ijbn", (rr_head_q, r_head_k)) # qlen x klen x bsz x n_head BD = self._rel_shift(BD) # [qlen x klen x bsz x n_head] attn_score = AC + BD attn_score.mul_(self.scale) mask_value = torch.finfo(attn_score.dtype).min # compute attention probability if attn_mask is not None and torch.sum(attn_mask).item(): attn_mask = attn_mask == 1 # Switch to bool if attn_mask.dim() == 2: attn_score = ( attn_score.float().masked_fill(attn_mask[None, :, :, None], mask_value).type_as(attn_score) ) elif attn_mask.dim() == 3: attn_score = attn_score.float().masked_fill(attn_mask[:, :, :, None], mask_value).type_as(attn_score) # [qlen x klen x bsz x n_head] attn_prob = nn.functional.softmax(attn_score, dim=1) attn_prob = self.dropatt(attn_prob) # Mask heads if we want to if head_mask is not None: attn_prob = attn_prob * head_mask # compute attention vector attn_vec = torch.einsum("ijbn,jbnd->ibnd", (attn_prob, w_head_v)) # [qlen x bsz x n_head x d_head] attn_vec = attn_vec.contiguous().view(attn_vec.size(0), attn_vec.size(1), self.n_head * self.d_head) # linear projection attn_out = self.o_net(attn_vec) attn_out = self.drop(attn_out) if self.pre_lnorm: # residual connection outputs = [w + attn_out] else: # residual connection + layer normalization outputs = [self.layer_norm(w + attn_out)] if output_attentions: outputs.append(attn_prob) return outputs class RelPartialLearnableDecoderLayer(nn.Module): def __init__(self, n_head, d_model, d_head, d_inner, dropout, layer_norm_epsilon=1e-5, **kwargs): super().__init__() self.dec_attn = RelPartialLearnableMultiHeadAttn( n_head, d_model, d_head, dropout, layer_norm_epsilon=layer_norm_epsilon, **kwargs ) self.pos_ff = PositionwiseFF( d_model, d_inner, dropout, pre_lnorm=kwargs.get("pre_lnorm"), layer_norm_epsilon=layer_norm_epsilon ) def forward(self, dec_inp, r, dec_attn_mask=None, mems=None, head_mask=None, output_attentions=False): attn_outputs = self.dec_attn( dec_inp, r, attn_mask=dec_attn_mask, mems=mems, head_mask=head_mask, output_attentions=output_attentions, ) ff_output = self.pos_ff(attn_outputs[0]) outputs = [ff_output] + attn_outputs[1:] return outputs class AdaptiveEmbedding(nn.Module): def __init__(self, n_token, d_embed, d_proj, cutoffs, div_val=1, sample_softmax=False): super().__init__() self.n_token = n_token self.d_embed = d_embed self.cutoffs = cutoffs + [n_token] self.div_val = div_val self.d_proj = d_proj self.emb_scale = d_proj**0.5 self.cutoff_ends = [0] + self.cutoffs self.emb_layers = nn.ModuleList() self.emb_projs = nn.ParameterList() if div_val == 1: self.emb_layers.append(nn.Embedding(n_token, d_embed, sparse=sample_softmax > 0)) if d_proj != d_embed: self.emb_projs.append(nn.Parameter(torch.FloatTensor(d_proj, d_embed))) else: for i in range(len(self.cutoffs)): l_idx, r_idx = self.cutoff_ends[i], self.cutoff_ends[i + 1] d_emb_i = d_embed // (div_val**i) self.emb_layers.append(nn.Embedding(r_idx - l_idx, d_emb_i)) self.emb_projs.append(nn.Parameter(torch.FloatTensor(d_proj, d_emb_i))) def forward(self, inp): if self.div_val == 1: embed = self.emb_layers[0](inp) if self.d_proj != self.d_embed: embed = nn.functional.linear(embed, self.emb_projs[0]) else: param = next(self.parameters()) inp_flat = inp.view(-1) emb_flat = torch.zeros([inp_flat.size(0), self.d_proj], dtype=param.dtype, device=param.device) for i in range(len(self.cutoffs)): l_idx, r_idx = self.cutoff_ends[i], self.cutoff_ends[i + 1] mask_i = (inp_flat >= l_idx) & (inp_flat < r_idx) indices_i = mask_i.nonzero().squeeze() if indices_i.numel() == 0: continue inp_i = inp_flat.index_select(0, indices_i) - l_idx emb_i = self.emb_layers[i](inp_i) emb_i = nn.functional.linear(emb_i, self.emb_projs[i]) emb_flat.index_copy_(0, indices_i, emb_i) embed_shape = inp.size() + (self.d_proj,) embed = emb_flat.view(embed_shape) embed.mul_(self.emb_scale) return embed class TransfoXLPreTrainedModel(PreTrainedModel): """ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models. """ config_class = TransfoXLConfig load_tf_weights = load_tf_weights_in_transfo_xl base_model_prefix = "transformer" def _init_weight(self, weight): if self.config.init == "uniform": nn.init.uniform_(weight, -self.config.init_range, self.config.init_range) elif self.config.init == "normal": nn.init.normal_(weight, 0.0, self.config.init_std) def _init_bias(self, bias): nn.init.constant_(bias, 0.0) def _init_weights(self, m): """Initialize the weights.""" classname = m.__class__.__name__ if classname.find("Linear") != -1: if hasattr(m, "weight") and m.weight is not None: self._init_weight(m.weight) if hasattr(m, "bias") and m.bias is not None: self._init_bias(m.bias) elif classname.find("AdaptiveEmbedding") != -1: if hasattr(m, "emb_projs"): for i in range(len(m.emb_projs)): if m.emb_projs[i] is not None: nn.init.normal_(m.emb_projs[i], 0.0, self.config.proj_init_std) elif classname.find("Embedding") != -1: if hasattr(m, "weight"): self._init_weight(m.weight) elif classname.find("ProjectedAdaptiveLogSoftmax") != -1: if hasattr(m, "cluster_weight") and m.cluster_weight is not None: self._init_weight(m.cluster_weight) if hasattr(m, "cluster_bias") and m.cluster_bias is not None: self._init_bias(m.cluster_bias) if hasattr(m, "out_projs"): for i in range(len(m.out_projs)): if m.out_projs[i] is not None: nn.init.normal_(m.out_projs[i], 0.0, self.config.proj_init_std) elif classname.find("LayerNorm") != -1: if hasattr(m, "weight"): nn.init.normal_(m.weight, 1.0, self.config.init_std) if hasattr(m, "bias") and m.bias is not None: self._init_bias(m.bias) else: if hasattr(m, "r_emb"): self._init_weight(m.r_emb) if hasattr(m, "r_w_bias"): self._init_weight(m.r_w_bias) if hasattr(m, "r_r_bias"): self._init_weight(m.r_r_bias) if hasattr(m, "r_bias"): self._init_bias(m.r_bias) def resize_token_embeddings(self, new_num_tokens: Optional[int] = None, layer: Optional[int] = -1): """ Resize input token embeddings matrix of the model if new_num_tokens != config.vocab_size. Take care of tying weights embeddings afterwards if the model class has a *tie_weights()* method. Arguments: new_num_tokens: (*optional*) int: New number of tokens in the embedding matrix. Increasing the size will add newly initialized vectors at the end. Reducing the size will remove vectors from the end. If not provided or None: does nothing and just returns a pointer to the input tokens `torch.nn.Embeddings` Module of the model. layer: (*optional*) int: Layer of the *AdaptiveEmbedding* where the resizing should be done. Per default the last layer will be resized. Be aware that when resizing other than the last layer, you have to ensure that the new token(s) in the tokenizer are at the corresponding position. Return: `torch.nn.Embeddings` Pointer to the input tokens Embeddings Module of the model """ base_model = getattr(self, self.base_model_prefix, self) # get the base model if needed if new_num_tokens is None: return self.get_input_embeddings() new_num_tokens_layer, layer = self._get_new_num_tokens_layer(new_num_tokens, layer) assert new_num_tokens_layer > 0, "The size of the new embedding layer cannot be 0 or less" model_embeds = base_model._resize_token_embeddings(new_num_tokens_layer, layer) # Update base model and current model config self.config.vocab_size = new_num_tokens base_model.vocab_size = new_num_tokens base_model.n_token = new_num_tokens new_embedding_shapes = self._get_embedding_shapes() self._resize_cutoffs(new_num_tokens, new_num_tokens_layer, new_embedding_shapes, layer) # Tie weights again if needed self.tie_weights() return model_embeds def _get_new_num_tokens_layer(self, new_num_tokens, layer): embeddings = self.get_input_embeddings() if layer == -1: layer = len(embeddings.emb_layers) - 1 assert 0 <= layer <= len(embeddings.emb_layers) - 1 new_num_tokens_layer = ( new_num_tokens - sum([emb.weight.shape[0] for emb in embeddings.emb_layers[:layer]]) - sum([emb.weight.shape[0] for emb in embeddings.emb_layers[layer + 1 :]]) ) return new_num_tokens_layer, layer def _get_embedding_shapes(self): embeddings = self.get_input_embeddings() return [emb.weight.shape[0] for emb in embeddings.emb_layers] def _resize_token_embeddings(self, new_num_tokens, layer=-1): embeddings = self.get_input_embeddings() if new_num_tokens is None: return embeddings new_embeddings_layer = self._get_resized_embeddings(embeddings.emb_layers[layer], new_num_tokens) embeddings.emb_layers[layer] = new_embeddings_layer self.set_input_embeddings(embeddings) return self.get_input_embeddings() def _resize_cutoffs(self, new_num_tokens, new_emb_size, new_embedding_shapes, layer): embeddings = self.get_input_embeddings() for i in range(layer, len(embeddings.cutoffs)): embeddings.cutoffs[i] = sum(new_embedding_shapes[: i + 1]) embeddings.cutoff_ends = [0] + embeddings.cutoffs embeddings.n_token = new_num_tokens self.config.cutoffs = embeddings.cutoffs[:-1] return embeddings.cutoffs @dataclass class TransfoXLModelOutput(ModelOutput): """ Base class for model's outputs that may also contain a past key/values (to speed up sequential decoding). Args: last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`): Sequence of hidden-states at the output of the last layer of the model. mems (`List[torch.FloatTensor]` of length `config.n_layers`): Contains pre-computed hidden-states (key and values in the attention blocks). Can be used (see `mems` input) to speed up sequential decoding. The token ids which have their past given to this model should not be passed as input ids as they have already been computed. hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer plus the initial embedding outputs. attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. """ last_hidden_state: torch.FloatTensor mems: List[torch.FloatTensor] = None hidden_states: Optional[Tuple[torch.FloatTensor]] = None attentions: Optional[Tuple[torch.FloatTensor]] = None @dataclass class TransfoXLSequenceClassifierOutputWithPast(ModelOutput): """ Base class for outputs of sentence classification models. Args: loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided): Classification (or regression if config.num_labels==1) loss. logits (`torch.FloatTensor` of shape `(batch_size, config.num_labels)`): Classification (or regression if config.num_labels==1) scores (before SoftMax). mems (`List[torch.FloatTensor]` of length `config.n_layers`): Contains pre-computed hidden-states (key and values in the attention blocks). Can be used (see `mems` input) to speed up sequential decoding. The token ids which have their past given to this model should not be passed as input ids as they have already been computed. hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer plus the initial embedding outputs. attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. """ loss: Optional[torch.FloatTensor] = None logits: torch.FloatTensor = None mems: List[torch.FloatTensor] = None hidden_states: Optional[Tuple[torch.FloatTensor]] = None attentions: Optional[Tuple[torch.FloatTensor]] = None @dataclass class TransfoXLLMHeadModelOutput(ModelOutput): """ Base class for model's outputs that may also contain a past key/values (to speed up sequential decoding). Args: losses (`torch.FloatTensor` of shape *(batch_size, sequence_length-1)*, *optional*, returned when `labels` is provided): Language modeling losses (not reduced). prediction_scores (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`): Prediction scores of the language modeling head (scores for each vocabulary token after SoftMax). mems (`List[torch.FloatTensor]` of length `config.n_layers`): Contains pre-computed hidden-states (key and values in the attention blocks). Can be used (see `mems` input) to speed up sequential decoding. The token ids which have their past given to this model should not be passed as input ids as they have already been computed. hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer plus the initial embedding outputs. attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. loss (`torch.FloatTensor` of shape `()`, *optional*, returned when `labels` is provided) Reduced language modeling loss. """ losses: Optional[torch.FloatTensor] = None prediction_scores: torch.FloatTensor = None mems: List[torch.FloatTensor] = None hidden_states: Optional[Tuple[torch.FloatTensor]] = None attentions: Optional[Tuple[torch.FloatTensor]] = None loss: Optional[torch.FloatTensor] = None @property def logits(self): # prediction scores are the output of the adaptive softmax, see # the file `modeling_transfo_xl_utilities`. Since the adaptive # softmax returns the log softmax value, `self.prediction_scores` # are strictly speaking not exactly `logits`, but behave the same # way logits do. return self.prediction_scores TRANSFO_XL_START_DOCSTRING = r""" This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.) This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior. Parameters: config ([`TransfoXLConfig`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights. """ TRANSFO_XL_INPUTS_DOCSTRING = r""" Args: input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): Indices of input sequence tokens in the vocabulary. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input IDs?](../glossary#input-ids) mems (`List[torch.FloatTensor]` of length `config.n_layers`): Contains pre-computed hidden-states (key and values in the attention blocks) as computed by the model (see `mems` output below). Can be used to speed up sequential decoding. The token ids which have their mems given to this model should not be passed as `input_ids` as they have already been computed. head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*): Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`: - 1 indicates the head is **not masked**, - 0 indicates the head is **masked**. inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*): Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert `input_ids` indices into associated vectors than the model's internal embedding lookup matrix. output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. """ @add_start_docstrings( "The bare Bert Model transformer outputting raw hidden-states without any specific head on top.", TRANSFO_XL_START_DOCSTRING, ) class TransfoXLModel(TransfoXLPreTrainedModel): def __init__(self, config): super().__init__(config) self.n_token = config.vocab_size self.d_embed = config.d_embed self.d_model = config.d_model self.n_head = config.n_head self.d_head = config.d_head self.word_emb = AdaptiveEmbedding( config.vocab_size, config.d_embed, config.d_model, config.cutoffs, div_val=config.div_val ) self.drop = nn.Dropout(config.dropout) self.n_layer = config.n_layer self.mem_len = config.mem_len self.attn_type = config.attn_type if not config.untie_r: self.r_w_bias = nn.Parameter(torch.FloatTensor(self.n_head, self.d_head)) self.r_r_bias = nn.Parameter(torch.FloatTensor(self.n_head, self.d_head)) self.layers = nn.ModuleList() if config.attn_type == 0: # the default attention for i in range(config.n_layer): self.layers.append( RelPartialLearnableDecoderLayer( config.n_head, config.d_model, config.d_head, config.d_inner, config.dropout, dropatt=config.dropatt, pre_lnorm=config.pre_lnorm, r_w_bias=None if config.untie_r else self.r_w_bias, r_r_bias=None if config.untie_r else self.r_r_bias, layer_norm_epsilon=config.layer_norm_epsilon, ) ) else: # learnable embeddings and absolute embeddings are not used in our pretrained checkpoints raise NotImplementedError # Removed them to avoid maintaining dead code self.same_length = config.same_length self.clamp_len = config.clamp_len if self.attn_type == 0: # default attention self.pos_emb = PositionalEmbedding(self.d_model) else: # learnable embeddings and absolute embeddings raise NotImplementedError # Removed these to avoid maintaining dead code - They are not used in our pretrained checkpoint # Initialize weights and apply final processing self.post_init() def get_input_embeddings(self): return self.word_emb def set_input_embeddings(self, new_embeddings): self.word_emb = new_embeddings def backward_compatible(self): self.sample_softmax = -1 def reset_memory_length(self, mem_len): self.mem_len = mem_len def _prune_heads(self, heads): logger.info("Head pruning is not implemented for Transformer-XL model") pass def init_mems(self, bsz): if self.mem_len > 0: mems = [] param = next(self.parameters()) for i in range(self.n_layer): empty = torch.zeros(self.mem_len, bsz, self.config.d_model, dtype=param.dtype, device=param.device) mems.append(empty) return mems else: return None def _update_mems(self, hids, mems, mlen, qlen): # does not deal with None if mems is None: return None # mems is not None assert len(hids) == len(mems), "len(hids) != len(mems)" # There are `mlen + qlen` steps that can be cached into mems with torch.no_grad(): new_mems = [] end_idx = mlen + max(0, qlen) beg_idx = max(0, end_idx - self.mem_len) for i in range(len(hids)): cat = torch.cat([mems[i], hids[i]], dim=0) new_mems.append(cat[beg_idx:end_idx].detach()) return new_mems @add_start_docstrings_to_model_forward(TRANSFO_XL_INPUTS_DOCSTRING) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC, output_type=TransfoXLModelOutput, config_class=_CONFIG_FOR_DOC, ) def forward( self, input_ids: Optional[torch.LongTensor] = None, mems: Optional[List[torch.FloatTensor]] = None, head_mask: Optional[torch.FloatTensor] = None, inputs_embeds: Optional[torch.FloatTensor] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, ) -> Union[Tuple, TransfoXLModelOutput]: output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) return_dict = return_dict if return_dict is not None else self.config.use_return_dict # the original code for Transformer-XL used shapes [len, bsz] but we want a unified interface in the library # so we transpose here from shape [bsz, len] to shape [len, bsz] if input_ids is not None and inputs_embeds is not None: raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time") elif input_ids is not None: input_ids = input_ids.transpose(0, 1).contiguous() qlen, bsz = input_ids.size() elif inputs_embeds is not None: inputs_embeds = inputs_embeds.transpose(0, 1).contiguous() qlen, bsz = inputs_embeds.shape[0], inputs_embeds.shape[1] else: raise ValueError("You have to specify either input_ids or inputs_embeds") if mems is None: mems = self.init_mems(bsz) # Prepare head mask if needed # 1.0 in head_mask indicate we keep the head # attention_probs has shape bsz x n_heads x N x N # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads] (a head_mask for each layer) # and head_mask is converted to shape [num_hidden_layers x qlen x klen x bsz x n_head] if head_mask is not None: if head_mask.dim() == 1: head_mask = head_mask.unsqueeze(0).unsqueeze(0).unsqueeze(0).unsqueeze(0) head_mask = head_mask.expand(self.n_layer, -1, -1, -1, -1) elif head_mask.dim() == 2: head_mask = head_mask.unsqueeze(1).unsqueeze(1).unsqueeze(1) head_mask = head_mask.to( dtype=next(self.parameters()).dtype ) # switch to float if need + fp16 compatibility else: head_mask = [None] * self.n_layer if inputs_embeds is not None: word_emb = inputs_embeds else: word_emb = self.word_emb(input_ids) mlen = mems[0].size(0) if mems is not None else 0 klen = mlen + qlen if self.same_length: all_ones = word_emb.new_ones((qlen, klen), dtype=torch.bool) mask_len = klen - self.mem_len if mask_len > 0: mask_shift_len = qlen - mask_len else: mask_shift_len = qlen dec_attn_mask = (torch.triu(all_ones, 1 + mlen) + torch.tril(all_ones, -mask_shift_len))[:, :, None] # -1 else: dec_attn_mask = torch.triu(word_emb.new_ones((qlen, klen), dtype=torch.bool), diagonal=1 + mlen)[ :, :, None ] hids = [] attentions = [] if output_attentions else None if self.attn_type == 0: # default pos_seq = torch.arange(klen - 1, -1, -1.0, device=word_emb.device, dtype=word_emb.dtype) if self.clamp_len > 0: pos_seq.clamp_(max=self.clamp_len) pos_emb = self.pos_emb(pos_seq) core_out = self.drop(word_emb) pos_emb = self.drop(pos_emb) for i, layer in enumerate(self.layers): hids.append(core_out) mems_i = None if mems is None else mems[i] layer_outputs = layer( core_out, pos_emb, dec_attn_mask=dec_attn_mask, mems=mems_i, head_mask=head_mask[i], output_attentions=output_attentions, ) core_out = layer_outputs[0] if output_attentions: attentions.append(layer_outputs[1]) else: # learnable embeddings and absolute embeddings raise NotImplementedError # Removed these to avoid maintaining dead code - They are not used in our pretrained checkpoint core_out = self.drop(core_out) new_mems = self._update_mems(hids, mems, mlen, qlen) if output_hidden_states: # Add last layer and transpose to library standard shape [bsz, len, hidden_dim] hids.append(core_out) hids = tuple(t.transpose(0, 1).contiguous() for t in hids) else: hids = None if output_attentions: # Transpose to library standard shape [bsz, n_heads, query_seq_len, key_seq_len] attentions = tuple(t.permute(2, 3, 0, 1).contiguous() for t in attentions) # We transpose back here to shape [bsz, len, hidden_dim] core_out = core_out.transpose(0, 1).contiguous() if not return_dict: return tuple(v for v in [core_out, new_mems, hids, attentions] if v is not None) return TransfoXLModelOutput( last_hidden_state=core_out, mems=new_mems, hidden_states=hids, attentions=attentions, ) @add_start_docstrings( """ The Transformer-XL Model with a language modeling head on top (adaptive softmax with weights tied to the adaptive input embeddings) """, TRANSFO_XL_START_DOCSTRING, ) class TransfoXLLMHeadModel(TransfoXLPreTrainedModel): _keys_to_ignore_on_load_missing = [r"crit\.out_projs\.\d+", r"crit\.out_layers\.\d+\.weight"] def __init__(self, config): super().__init__(config) self.transformer = TransfoXLModel(config) self.sample_softmax = config.sample_softmax self.trainer_compatible = getattr(config, "trainer_compatible", False) if not self.trainer_compatible: warnings.warn( "The output of TransfoXL will be updated in v5 to support a single loss as first argument. In order" "to use that updated output, please specify `trainer_compatible=True` as your configuration" " attribute.", DeprecationWarning, ) assert self.sample_softmax <= 0, ( "Sampling from the softmax is not implemented yet. Please look at issue: #3310:" " https://github.com/huggingface/transformers/issues/3310" ) self.crit = ProjectedAdaptiveLogSoftmax( config.vocab_size, config.d_embed, config.d_model, config.cutoffs, div_val=config.div_val ) # Initialize weights and apply final processing self.post_init() def tie_weights(self): """ Run this to be sure output and input (adaptive) softmax weights are tied """ if self.config.tie_word_embeddings: for i in range(len(self.crit.out_layers)): self._tie_or_clone_weights(self.crit.out_layers[i], self.transformer.word_emb.emb_layers[i]) if self.config.tie_projs: for i, tie_proj in enumerate(self.config.tie_projs): if tie_proj and self.config.div_val == 1 and self.config.d_model != self.config.d_embed: if self.config.torchscript: self.crit.out_projs[i] = nn.Parameter(self.transformer.word_emb.emb_projs[0].clone()) else: self.crit.out_projs[i] = self.transformer.word_emb.emb_projs[0] elif tie_proj and self.config.div_val != 1: if self.config.torchscript: self.crit.out_projs[i] = nn.Parameter(self.transformer.word_emb.emb_projs[i].clone()) else: self.crit.out_projs[i] = self.transformer.word_emb.emb_projs[i] def reset_memory_length(self, mem_len): self.transformer.reset_memory_length(mem_len) def init_mems(self, bsz): return self.transformer.init_mems(bsz) @add_start_docstrings_to_model_forward(TRANSFO_XL_INPUTS_DOCSTRING) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC, output_type=TransfoXLLMHeadModelOutput, config_class=_CONFIG_FOR_DOC, ) def forward( self, input_ids: Optional[torch.LongTensor] = None, mems: Optional[List[torch.FloatTensor]] = None, head_mask: Optional[torch.FloatTensor] = None, inputs_embeds: Optional[torch.FloatTensor] = None, labels: Optional[torch.LongTensor] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, ) -> Union[Tuple, TransfoXLLMHeadModelOutput]: r""" labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100` are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]` """ return_dict = return_dict if return_dict is not None else self.config.use_return_dict if input_ids is not None: bsz, tgt_len = input_ids.size(0), input_ids.size(1) elif inputs_embeds is not None: bsz, tgt_len = inputs_embeds.size(0), inputs_embeds.size(1) else: raise ValueError("You have to specify either input_ids or inputs_embeds") transformer_outputs = self.transformer( input_ids, mems=mems, head_mask=head_mask, inputs_embeds=inputs_embeds, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) last_hidden = transformer_outputs[0] pred_hid = last_hidden[:, -tgt_len:] if labels is not None: # Prevents all labels being -100 and throwing an error # when backwarding the loss miss_valid_label = labels[0, 1:].sum() == (labels.size(1) - 1) * -100 if miss_valid_label: # Sets an <EOS> token, just to prevent loss from being NaN labels[0, 1] = self.config.eos_token_id softmax_output = self.crit(pred_hid, labels) prediction_scores = softmax_output.view(bsz, tgt_len, -1) if labels is None else () if labels is not None: losses = softmax_output.view(bsz, tgt_len - 1) # Avoids from incorporating padding (-100) tokens into loss value loss = losses[losses != 0].mean() else: losses, loss = None, None if not return_dict: if self.trainer_compatible: output = (prediction_scores, losses) if losses is not None else (prediction_scores,) output += transformer_outputs[1:] return ((loss,) + output) if loss is not None else output else: output = (prediction_scores, *transformer_outputs[1:]) output = ((losses,) + output) if losses is not None else output return (output + (loss,)) if loss is not None else output return TransfoXLLMHeadModelOutput( loss=loss, prediction_scores=prediction_scores, losses=losses, mems=transformer_outputs.mems, hidden_states=transformer_outputs.hidden_states, attentions=transformer_outputs.attentions, ) def get_output_embeddings(self): """Double-check if you are using adaptive softmax.""" if self.sample_softmax > 0: return self.out_layer else: return self.crit.out_layers[-1] def prepare_inputs_for_generation(self, input_ids, past_key_values=None, **model_kwargs): inputs = {} # if past is defined in model kwargs then use it for faster decoding if past_key_values: inputs["mems"] = past_key_values inputs["input_ids"] = input_ids[:, -1].unsqueeze(-1) else: inputs["input_ids"] = input_ids return inputs def _resize_cutoffs(self, new_num_tokens, new_emb_size, new_embedding_shapes, layer): new_cutoffs = super()._resize_cutoffs(new_num_tokens, new_emb_size, new_embedding_shapes, layer) self.crit.cutoffs = new_cutoffs self.crit.cutoff_ends = [0] + new_cutoffs self.crit.n_token = new_num_tokens @staticmethod def _reorder_cache(mems: List[torch.Tensor], beam_idx: torch.Tensor) -> List[torch.Tensor]: """ This function is used to re-order the `mems` cache if [`~PreTrainedModel.beam_search`] or [`~PreTrainedModel.beam_sample`] is called. This is required to match `mems` with the correct beam_idx at every generation step. """ return [layer_past.index_select(1, beam_idx.to(layer_past.device)) for layer_past in mems] @add_start_docstrings( """ The Transformer-XL Model transformer with a sequence classification head on top (linear layer). [`TransfoXLForSequenceClassification`] uses the last token in order to do the classification, as other causal models (e.g. GPT-1) do. Since it does classification on the last token, it requires to know the position of the last token. If a `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in each row of the batch). """, TRANSFO_XL_START_DOCSTRING, ) class TransfoXLForSequenceClassification(TransfoXLPreTrainedModel): _keys_to_ignore_on_load_missing = [r"h\.\d+\.attn\.masked_bias", r"lm_head.weight"] def __init__(self, config): super().__init__(config) self.num_labels = config.num_labels self.transformer = TransfoXLModel(config) self.score = nn.Linear(config.d_embed, self.num_labels, bias=False) # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(TRANSFO_XL_INPUTS_DOCSTRING) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC, output_type=TransfoXLSequenceClassifierOutputWithPast, config_class=_CONFIG_FOR_DOC, ) def forward( self, input_ids: Optional[torch.LongTensor] = None, mems: Optional[List[torch.FloatTensor]] = None, head_mask: Optional[torch.FloatTensor] = None, inputs_embeds: Optional[torch.FloatTensor] = None, labels: Optional[torch.LongTensor] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, ) -> Union[Tuple, TransfoXLSequenceClassifierOutputWithPast]: r""" labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*): Labels for computing the sequence classification/regression loss. Indices should be in `[0, ..., config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If `config.num_labels > 1` a classification loss is computed (Cross-Entropy). """ return_dict = return_dict if return_dict is not None else self.config.use_return_dict transformer_outputs = self.transformer( input_ids, mems=mems, head_mask=head_mask, inputs_embeds=inputs_embeds, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) hidden_states = transformer_outputs[0] logits = self.score(hidden_states) if input_ids is not None: batch_size, sequence_length = input_ids.shape[:2] else: batch_size, sequence_length = inputs_embeds.shape[:2] assert ( self.config.pad_token_id is not None or batch_size == 1 ), "Cannot handle batch sizes > 1 if no padding token is defined." if self.config.pad_token_id is None: sequence_lengths = -1 else: if input_ids is not None: sequence_lengths = torch.ne(input_ids, self.config.pad_token_id).sum(-1) - 1 else: sequence_lengths = -1 logger.warning( f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be " "unexpected if using padding tokens in conjunction with `inputs_embeds.`" ) pooled_logits = logits[range(batch_size), sequence_lengths] loss = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: self.config.problem_type = "regression" elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): self.config.problem_type = "single_label_classification" else: self.config.problem_type = "multi_label_classification" if self.config.problem_type == "regression": loss_fct = MSELoss() if self.num_labels == 1: loss = loss_fct(pooled_logits.squeeze(), labels.squeeze()) else: loss = loss_fct(pooled_logits, labels) elif self.config.problem_type == "single_label_classification": loss_fct = CrossEntropyLoss() loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1)) elif self.config.problem_type == "multi_label_classification": loss_fct = BCEWithLogitsLoss() loss = loss_fct(pooled_logits, labels) if not return_dict: output = (pooled_logits,) + transformer_outputs[1:] return ((loss,) + output) if loss is not None else output return TransfoXLSequenceClassifierOutputWithPast( loss=loss, logits=pooled_logits, mems=transformer_outputs.mems, hidden_states=transformer_outputs.hidden_states, attentions=transformer_outputs.attentions, )
2881099/dotnetGen_postgresql
36,291
GenPg/NPinyin/PyHash.cs
using System; using System.Collections.Generic; using System.Text; namespace NPinyin { internal class PyHash { internal static short[][] hashes = new short[][] { new short[]{23, 70, 96, 128, 154, 165, 172, 195}, new short[]{25, 35, 87, 108, 120, 128, 132, 137, 168, 180, 325, 334, 336, 353, 361, 380}, new short[]{23, 34, 46, 81, 82, 87, 134, 237, 255, 288, 317, 322, 354, 359}, new short[]{7, 11, 37, 49, 53, 56, 131, 132, 146, 176, 315, 372}, new short[]{11, 69, 73, 87, 96, 103, 159, 175, 195, 296, 298, 359, 361}, new short[]{57, 87, 115, 126, 149, 244, 282, 298, 308, 345, 355}, new short[]{19, 37, 117, 118, 141, 154, 196, 216, 267, 301, 327, 333, 337, 347}, new short[]{4, 11, 59, 61, 62, 87, 119, 169, 183, 198, 262, 334, 362, 380}, new short[]{37, 135, 167, 170, 246, 250, 334, 341, 351, 354, 386, 390, 398}, new short[]{5, 6, 52, 55, 76, 146, 165, 244, 256, 266, 300, 318, 331}, new short[]{6, 71, 94, 129, 137, 141, 169, 179, 225, 226, 235, 248, 289, 290, 333, 345, 391}, new short[]{0, 33, 37, 62, 90, 131, 205, 246, 268, 343, 349, 380}, new short[]{31, 62, 85, 115, 117, 150, 159, 167, 171, 204, 215, 252, 343}, new short[]{69, 81, 98, 140, 165, 195, 239, 240, 259, 265, 329, 368, 375, 392, 393}, new short[]{13, 81, 82, 123, 132, 144, 154, 165, 334, 336, 345, 348, 349, 355, 367, 377, 383}, new short[]{31, 32, 44, 57, 76, 83, 87, 129, 151, 172, 176, 183, 184, 193, 221, 235, 285, 288, 305}, new short[]{10, 14, 60, 76, 85, 97, 115, 125, 128, 130, 286, 288, 301, 313, 382}, new short[]{62, 128, 136, 175, 211, 240, 254, 273, 274, 317, 330, 344, 349, 360, 380}, new short[]{29, 47, 52, 116, 126, 127, 130, 133, 191, 284, 288, 306, 353, 361, 383}, new short[]{1, 15, 25, 67, 83, 90, 117, 121, 150, 228, 308, 324, 336, 351, 386}, new short[]{34, 37, 67, 101, 103, 117, 127, 165, 168, 254, 267, 272, 274, 288, 305, 310, 323, 329, 333, 358, 378}, new short[]{5, 74, 103, 135, 163, 165, 171, 244, 262, 266, 334, 352, 390, 397}, new short[]{4, 17, 95, 125, 165, 186, 203, 221, 252, 282, 317, 333, 339, 348, 351, 353}, new short[]{74, 79, 81, 84, 92, 110, 116, 117, 131, 132, 154, 199, 241, 251, 300, 306, 349, 359, 383, 387}, new short[]{40, 83, 127, 144, 161, 188, 249, 288, 344, 382, 388}, new short[]{8, 55, 61, 76, 85, 98, 111, 127, 186, 230, 241, 247, 267, 287, 327, 341, 344, 347, 359, 364}, new short[]{20, 59, 69, 80, 117, 129, 176, 186, 191, 237, 275, 289, 309, 338, 375, 380}, new short[]{5, 15, 25, 35, 40, 129, 174, 236, 274, 337, 347}, new short[]{14, 22, 47, 56, 87, 120, 129, 144, 155, 160, 237, 283, 284, 309, 327, 337, 365, 372}, new short[]{1, 14, 47, 132, 198, 254, 255, 300, 310, 335, 336, 372}, new short[]{2, 36, 64, 96, 125, 176, 184, 190, 211, 271, 308, 315, 367}, new short[]{20, 76, 79, 81, 110, 117, 120, 129, 182, 192, 235, 353, 378}, new short[]{37, 83, 88, 92, 111, 127, 243, 303, 324, 325, 348, 353, 359, 371, 377}, new short[]{5, 87, 90, 124, 127, 180, 259, 288, 290, 302, 312, 313, 324, 332}, new short[]{55, 62, 89, 98, 108, 132, 168, 240, 248, 322, 325, 327, 347, 353, 391, 396}, new short[]{4, 8, 13, 35, 37, 39, 41, 64, 111, 174, 212, 245, 248, 251, 263, 288, 335, 373, 375}, new short[]{10, 39, 93, 110, 168, 227, 228, 254, 288, 336, 378, 381}, new short[]{75, 92, 122, 176, 198, 211, 214, 283, 334, 353, 359, 379, 386}, new short[]{5, 8, 13, 19, 57, 87, 104, 125, 130, 176, 202, 249, 252, 290, 309, 391}, new short[]{88, 132, 173, 176, 235, 247, 253, 292, 324, 328, 339, 359}, new short[]{19, 32, 61, 84, 87, 118, 120, 125, 129, 132, 181, 190, 288, 290, 331, 355, 359, 366}, new short[]{13, 25, 46, 126, 140, 157, 165, 225, 226, 252, 288, 304, 327, 353, 378}, new short[]{12, 14, 26, 56, 72, 95, 131, 132, 134, 142, 253, 298, 337, 361, 391}, new short[]{4, 18, 37, 49, 87, 93, 196, 225, 226, 246, 248, 250, 255, 310, 354, 358}, new short[]{64, 87, 110, 111, 128, 135, 151, 165, 177, 188, 191, 268, 312, 334, 352, 354, 357, 371}, new short[]{10, 17, 19, 30, 40, 48, 81, 97, 125, 129, 130, 182, 234, 305, 328, 393}, new short[]{13, 69, 80, 114, 192, 200, 235, 343, 345, 353, 354, 360, 374, 378, 383}, new short[]{83, 87, 94, 105, 107, 124, 144, 153, 219, 290, 298, 324, 349, 358, 367}, new short[]{10, 36, 142, 169, 221, 232, 241, 246, 346, 347, 375, 383, 390}, new short[]{26, 104, 126, 143, 176, 186, 241, 247, 250, 318, 320, 333, 360}, new short[]{66, 92, 116, 148, 191, 215, 254, 333, 334, 335, 336, 351, 353, 358, 380}, new short[]{9, 37, 55, 56, 76, 79, 90, 111, 122, 124, 161, 192, 247, 313, 353, 359, 374}, new short[]{17, 30, 34, 56, 64, 68, 90, 125, 151, 168, 176, 188, 286, 333, 338, 360}, new short[]{26, 143, 173, 182, 190, 194, 246, 284, 286, 328, 333, 355, 357, 360, 362, 363, 377, 380}, new short[]{1, 13, 87, 122, 168, 171, 186, 201, 297, 328, 349, 352, 380}, new short[]{18, 39, 61, 88, 98, 123, 129, 131, 148, 162, 165, 243, 285, 314, 340, 349, 360, 377, 378}, new short[]{67, 98, 117, 118, 122, 128, 156, 174, 184, 207, 244, 250, 330, 335, 342, 372, 375}, new short[]{13, 38, 63, 160, 180, 185, 189, 190, 219, 248, 253, 275, 297, 318, 355}, new short[]{1, 44, 47, 93, 107, 172, 235, 276, 281, 287, 290, 306, 333, 334, 337, 347, 353, 376}, new short[]{13, 15, 32, 125, 127, 157, 165, 176, 236, 344, 350, 381}, new short[]{47, 65, 93, 134, 159, 174, 218, 282, 318, 336, 358, 373, 379}, new short[]{7, 17, 40, 66, 102, 141, 154, 159, 165, 172, 174, 177, 328, 329, 334, 348, 379, 382}, new short[]{4, 34, 36, 76, 79, 122, 127, 138, 176, 241, 267, 309, 334, 367, 382}, new short[]{9, 17, 33, 46, 90, 103, 125, 138, 144, 157, 185, 198, 224, 250, 260, 291, 326, 343, 349, 377, 381}, new short[]{29, 31, 53, 58, 134, 138, 193, 287, 305, 308, 333, 334}, new short[]{13, 64, 83, 93, 129, 192, 227, 244, 397}, new short[]{7, 8, 14, 78, 85, 103, 138, 175, 176, 200, 203, 234, 301, 313, 361}, new short[]{13, 75, 87, 111, 244, 253, 288, 321, 339, 341, 357, 395}, new short[]{4, 14, 42, 64, 69, 108, 110, 117, 122, 131, 159, 163, 188, 198, 200, 206, 244, 292, 300, 354, 390}, new short[]{14, 37, 73, 87, 129, 135, 144, 176, 182, 300, 346, 352, 380, 383}, new short[]{23, 50, 87, 143, 171, 186, 191, 223, 290, 333, 334, 364, 378, 380, 388, 391, 393}, new short[]{5, 14, 23, 36, 62, 71, 76, 95, 99, 128, 176, 211, 229, 357}, new short[]{12, 33, 47, 70, 81, 90, 97, 119, 122, 131, 189, 190, 191, 235, 244, 253, 320, 350, 359}, new short[]{10, 13, 23, 93, 110, 120, 135, 171, 195, 250, 293, 298, 329, 344, 354}, new short[]{13, 29, 37, 163, 169, 200, 211, 214, 217, 236, 246, 249, 282, 327, 349, 353, 362, 372}, new short[]{5, 13, 23, 41, 57, 62, 76, 89, 111, 135, 195, 234, 248, 314, 334, 341, 349, 380}, new short[]{17, 35, 57, 117, 121, 206, 235, 243, 265, 329, 358, 374}, new short[]{13, 28, 41, 55, 69, 101, 103, 126, 138, 198, 267, 276, 288, 313, 334, 335, 339, 354, 376, 383, 394}, new short[]{11, 13, 19, 36, 38, 58, 75, 124, 232, 235, 265, 286, 298, 330, 333, 359}, new short[]{4, 19, 25, 43, 110, 125, 165, 331, 334, 341, 349, 355, 372}, new short[]{40, 55, 64, 70, 117, 126, 127, 135, 160, 172, 173, 186, 270, 318, 338, 344, 378}, new short[]{122, 176, 198, 238, 246, 284, 286, 290, 318, 329, 337, 381, 394}, new short[]{23, 36, 37, 44, 117, 124, 198, 204, 233, 248, 282, 288, 297, 314, 332, 336, 388}, new short[]{15, 33, 54, 64, 75, 85, 115, 127, 165, 196, 229, 237, 254, 307, 327, 335, 349, 383}, new short[]{22, 87, 121, 127, 161, 180, 248, 250, 276, 313, 324, 347, 349, 355, 357, 359}, new short[]{14, 48, 67, 88, 130, 131, 172, 188, 195, 203, 267, 282, 333, 339, 350, 392}, new short[]{22, 31, 37, 98, 118, 132, 135, 137, 142, 151, 243, 244, 282, 305, 333, 349, 350, 351, 353, 358, 374}, new short[]{15, 42, 67, 75, 125, 134, 189, 255, 261, 309, 334, 350, 380, 382}, new short[]{10, 39, 87, 97, 105, 109, 125, 137, 225, 226, 253, 329, 341, 354, 363, 372}, new short[]{5, 17, 42, 64, 80, 111, 120, 169, 175, 206, 237, 267, 288, 290, 324, 351, 364, 390}, new short[]{3, 33, 55, 75, 91, 97, 103, 132, 187, 220, 232, 234, 240, 288, 301, 330, 336, 337, 338, 340, 359, 374, 380, 382}, new short[]{13, 87, 98, 125, 126, 127, 128, 250, 330, 341, 353, 360, 374, 382, 391}, new short[]{59, 66, 75, 125, 135, 172, 192, 230, 231, 255, 256, 276, 300, 306, 339, 349, 353, 390}, new short[]{25, 36, 56, 90, 107, 125, 127, 142, 165, 195, 244, 246, 319, 347, 355, 375, 380}, new short[]{2, 33, 35, 36, 72, 74, 87, 92, 111, 131, 145, 176, 244, 248, 282, 333, 355, 359}, new short[]{5, 39, 127, 134, 137, 200, 240, 283, 284, 343, 344, 372}, new short[]{9, 32, 37, 80, 96, 104, 110, 117, 154, 176, 244, 297, 298, 339, 353, 374, 381}, new short[]{38, 51, 64, 76, 80, 93, 96, 134, 150, 173, 275, 290, 340, 347, 359, 363, 380}, new short[]{55, 89, 111, 126, 157, 159, 162, 182, 188, 244, 253, 280, 334, 359, 384, 398}, new short[]{59, 64, 75, 81, 97, 105, 115, 125, 155, 198, 248, 262, 319, 323, 376}, new short[]{13, 41, 76, 125, 127, 130, 134, 135, 159, 167, 183, 229, 230, 240, 246, 308, 319, 329, 333, 334, 340, 344, 363, 382}, new short[]{8, 13, 19, 31, 70, 76, 79, 96, 127, 153, 163, 165, 184, 227, 230, 247, 255, 336, 337, 348, 353, 357, 361, 362}, new short[]{71, 87, 111, 121, 130, 142, 150, 160, 175, 224, 248, 314, 336, 353, 357, 359}, new short[]{67, 84, 101, 130, 287, 288, 332, 333, 359, 361, 377}, new short[]{34, 52, 90, 100, 125, 135, 165, 173, 320, 341, 352, 359, 382, 392}, new short[]{13, 18, 39, 55, 62, 87, 248, 255, 290, 327, 349, 353, 355, 360, 383}, new short[]{1, 9, 12, 29, 32, 36, 82, 139, 140, 149, 153, 165, 167, 180, 185, 231, 241, 244, 274, 299, 309, 329, 355, 362}, new short[]{48, 66, 98, 107, 120, 122, 125, 135, 190, 195, 198, 215, 253, 256, 280, 282, 307, 320, 334, 349, 353, 355}, new short[]{1, 7, 13, 25, 64, 98, 139, 144, 166, 176, 206, 236, 262, 330, 362}, new short[]{37, 55, 116, 123, 125, 131, 165, 234, 266, 276, 328, 329, 342, 349, 353, 359, 391}, new short[]{126, 137, 191, 215, 239, 288, 290, 321, 324, 333, 334, 338, 349, 353, 362, 379}, new short[]{50, 57, 87, 93, 98, 115, 134, 148, 174, 229, 251, 260, 285, 298, 313, 348, 349, 350}, new short[]{5, 13, 31, 45, 69, 81, 108, 122, 127, 160, 165, 176, 179, 237, 244, 301, 316, 352, 360}, new short[]{5, 87, 95, 98, 101, 132, 135, 159, 167, 190, 203, 217, 234, 235, 247, 289, 333, 341, 343, 352}, new short[]{22, 56, 66, 85, 87, 93, 126, 127, 163, 230, 243, 248, 254, 280, 301, 305, 334, 357}, new short[]{13, 19, 53, 59, 76, 91, 117, 122, 195, 298, 303, 309, 337, 345, 398}, new short[]{9, 54, 84, 107, 125, 127, 135, 144, 156, 173, 176, 202, 215, 231, 234, 246, 266, 282, 335, 336, 347, 351, 374}, new short[]{11, 15, 30, 31, 40, 57, 58, 87, 88, 113, 186, 244, 245, 256, 308, 334, 377}, new short[]{62, 111, 176, 196, 228, 231, 288, 294, 302, 306, 350, 353, 375, 378, 392}, new short[]{119, 131, 133, 154, 161, 179, 198, 232, 234, 265, 301, 314, 344, 353, 378}, new short[]{67, 84, 123, 172, 175, 176, 182, 229, 290, 359, 360, 375, 383, 393}, new short[]{33, 36, 39, 102, 116, 136, 137, 208, 234, 256, 307, 329, 341, 347, 376, 380}, new short[]{13, 27, 32, 80, 95, 108, 131, 165, 167, 180, 190, 200, 235, 241, 244, 323, 330, 339, 372}, new short[]{1, 18, 37, 62, 67, 82, 85, 118, 125, 147, 159, 169, 174, 243, 284, 307, 313, 318, 355, 391, 396}, new short[]{10, 87, 91, 135, 169, 176, 215, 246, 267, 282, 295, 320, 345, 353, 380}, new short[]{2, 11, 13, 29, 90, 124, 131, 132, 170, 174, 176, 229, 246, 258, 298, 336, 344, 349}, new short[]{14, 37, 42, 71, 128, 152, 185, 218, 288, 304, 315, 353, 362, 380, 391}, new short[]{17, 20, 36, 73, 93, 128, 163, 194, 211, 217, 282, 290, 320, 354, 383}, new short[]{9, 26, 32, 101, 127, 169, 178, 183, 191, 236, 244, 310, 330, 336, 345, 353, 360, 372, 380, 394}, new short[]{7, 13, 64, 78, 81, 90, 115, 133, 164, 169, 244, 246, 269, 278, 290, 292, 310, 320, 353, 360, 364, 366, 380}, new short[]{8, 65, 81, 84, 91, 126, 129, 158, 183, 184, 194, 254, 262, 333, 334, 339, 351, 363, 382}, new short[]{44, 87, 96, 97, 125, 161, 173, 177, 183, 188, 189, 209, 235, 288, 315, 334, 351}, new short[]{50, 56, 60, 62, 67, 71, 105, 149, 154, 158, 164, 167, 185, 221, 285, 288, 308, 337, 344, 353}, new short[]{6, 10, 37, 62, 74, 79, 81, 128, 139, 154, 167, 198, 228, 244, 267, 290, 302, 368, 394}, new short[]{6, 30, 35, 36, 62, 65, 71, 112, 153, 163, 167, 180, 186, 195, 249, 286, 303, 329, 334}, new short[]{158, 241, 282, 324, 332, 334, 351, 353, 363, 365}, new short[]{17, 89, 117, 144, 165, 180, 185, 198, 229, 244, 290, 334, 335, 380}, new short[]{20, 32, 45, 57, 64, 66, 120, 135, 144, 176, 192, 244, 297, 301, 354, 381}, new short[]{1, 7, 35, 62, 74, 122, 159, 170, 172, 238, 239, 307, 308, 338, 349, 350, 359, 366, 368, 375, 382, 383}, new short[]{7, 9, 23, 66, 92, 103, 111, 135, 182, 203, 246, 247, 265, 285, 288, 303, 317, 329, 348}, new short[]{13, 39, 74, 87, 127, 135, 144, 193, 212, 243, 270, 290, 303, 315, 375, 376}, new short[]{33, 36, 40, 59, 101, 120, 127, 244, 285, 287, 309, 339, 391}, new short[]{4, 10, 39, 195, 268, 284, 336, 354, 359, 375, 381}, new short[]{39, 42, 62, 79, 83, 84, 101, 109, 132, 138, 202, 215, 277, 353, 358, 359}, new short[]{10, 39, 46, 73, 84, 87, 132, 170, 192, 219, 232, 246, 288, 320, 337}, new short[]{10, 12, 56, 87, 91, 101, 132, 227, 254, 301, 303, 333, 343, 347, 351}, new short[]{7, 8, 15, 18, 82, 105, 130, 232, 250, 290, 316, 332, 348, 350}, new short[]{36, 109, 110, 125, 154, 191, 193, 246, 265, 348, 349, 350, 378, 383}, new short[]{12, 16, 45, 57, 87, 92, 101, 105, 129, 130, 155, 167, 218, 292, 293, 327, 349, 354, 361}, new short[]{30, 59, 64, 121, 125, 149, 163, 188, 212, 250, 348, 350, 351, 352, 353, 378, 380}, new short[]{1, 69, 130, 138, 194, 200, 239, 260, 264, 357, 380, 381, 382, 396}, new short[]{7, 10, 19, 40, 57, 61, 125, 137, 141, 212, 239, 251, 310, 333, 347, 359, 380, 383}, new short[]{20, 28, 50, 97, 109, 134, 157, 162, 184, 199, 244, 246, 286, 352, 353, 360, 373, 380}, new short[]{35, 62, 87, 96, 122, 127, 136, 142, 148, 155, 165, 186, 196, 227, 354, 380, 388}, new short[]{81, 82, 101, 115, 125, 200, 243, 313, 351, 359, 367}, new short[]{7, 19, 40, 61, 107, 108, 124, 154, 161, 244, 309, 329, 345, 379, 394}, new short[]{10, 27, 48, 66, 75, 103, 116, 122, 128, 221, 228, 319, 322, 350, 377, 398}, new short[]{2, 64, 74, 117, 130, 165, 172, 180, 191, 218, 221, 288, 299, 325, 347, 353, 355, 360}, new short[]{5, 76, 79, 87, 106, 111, 137, 168, 180, 235, 243, 288, 315, 321, 338, 344, 348, 378, 382, 383}, new short[]{0, 29, 31, 37, 40, 50, 88, 100, 129, 134, 137, 144, 174, 186, 203, 254, 310, 313, 329, 341, 359, 364}, new short[]{69, 70, 71, 96, 115, 121, 130, 157, 159, 200, 230, 246, 250, 299, 318, 324, 353, 359, 380, 391}, new short[]{7, 90, 95, 116, 127, 128, 135, 137, 141, 154, 161, 254, 330, 359, 379, 388}, new short[]{10, 14, 56, 91, 108, 125, 130, 167, 211, 228, 246, 258, 280, 306, 324, 333, 336, 338, 379}, new short[]{4, 5, 14, 57, 85, 98, 125, 135, 136, 176, 254, 334, 336, 337, 351, 358, 362, 379, 383}, new short[]{1, 4, 13, 18, 19, 32, 50, 60, 62, 87, 117, 176, 211, 251, 329, 343, 359}, new short[]{38, 56, 94, 103, 117, 125, 129, 144, 159, 176, 244, 251, 253, 324, 345, 353, 386, 390}, new short[]{4, 22, 38, 47, 59, 64, 82, 97, 110, 135, 153, 176, 235, 236, 241, 287, 288, 303, 333, 347, 358, 359, 361}, new short[]{2, 5, 20, 52, 97, 125, 127, 132, 135, 137, 174, 188, 191, 243, 288, 310, 334, 346, 348, 349, 362, 372, 378}, new short[]{19, 35, 55, 98, 125, 131, 134, 147, 153, 246, 255, 390}, new short[]{5, 59, 62, 129, 136, 153, 198, 225, 235, 239, 254, 295, 334, 338, 341, 359, 361}, new short[]{8, 13, 51, 94, 121, 122, 125, 126, 129, 240, 272, 290, 297, 323, 352, 358, 376, 391, 395}, new short[]{6, 111, 116, 122, 125, 131, 135, 164, 175, 200, 212, 221, 267, 287, 319, 328, 334, 344, 378}, new short[]{83, 108, 143, 172, 176, 192, 198, 246, 262, 286, 287, 308, 338, 340, 343, 348, 353, 367, 380, 383}, new short[]{39, 82, 92, 118, 126, 128, 144, 171, 211, 234, 244, 253, 328, 333, 339, 357, 359, 380}, new short[]{37, 62, 64, 81, 97, 122, 125, 127, 137, 211, 246, 344, 360}, new short[]{7, 29, 62, 67, 69, 81, 87, 107, 132, 151, 160, 229, 244, 284, 285, 317, 358, 387, 390}, new short[]{13, 75, 76, 83, 87, 154, 165, 190, 212, 258, 285, 308, 309, 316, 320, 332, 336, 340, 352, 353, 354, 358, 383}, new short[]{9, 19, 29, 46, 122, 125, 127, 130, 170, 171, 174, 180, 182, 232, 282, 290, 359, 362, 367}, new short[]{13, 40, 71, 98, 101, 116, 125, 127, 169, 172, 175, 283, 288, 309, 311, 313, 323, 334, 353, 391}, new short[]{3, 9, 70, 104, 118, 173, 200, 219, 246, 262, 288, 297, 309, 328, 329, 334, 341, 353}, new short[]{32, 89, 93, 131, 132, 142, 199, 200, 214, 246, 287, 298, 307, 339, 348, 349, 357, 358, 368, 372, 391}, new short[]{103, 134, 159, 176, 186, 235, 261, 276, 282, 290, 301, 317, 329, 345, 356}, new short[]{10, 59, 125, 129, 130, 192, 217, 283, 318, 343, 345, 349, 353, 380, 383, 392}, new short[]{19, 76, 79, 102, 107, 126, 155, 161, 180, 253, 288, 289, 290, 314, 329, 333, 334, 360, 368, 378, 394}, new short[]{12, 92, 98, 105, 137, 149, 172, 196, 198, 244, 260, 262, 282, 298, 329, 345, 353, 368, 390}, new short[]{31, 39, 79, 83, 121, 125, 167, 171, 186, 198, 288, 303, 306, 334, 337, 376}, new short[]{13, 20, 36, 57, 98, 108, 114, 165, 171, 225, 226, 262, 269, 305, 309, 351, 377, 389}, new short[]{13, 51, 71, 93, 110, 129, 130, 156, 165, 170, 173, 183, 191, 200, 211, 212, 255, 266, 299, 301, 329, 336, 348}, new short[]{31, 56, 97, 122, 125, 129, 160, 188, 202, 204, 206, 225, 235, 247, 254, 255, 288, 334, 350, 362, 365, 367}, new short[]{9, 32, 37, 70, 75, 87, 88, 96, 125, 130, 162, 163, 168, 169, 257, 285, 308, 310, 337, 373, 392}, new short[]{18, 40, 42, 47, 73, 76, 85, 105, 108, 125, 130, 132, 134, 167, 191, 284, 310, 311, 344, 358, 361, 374, 378, 379}, new short[]{5, 19, 29, 31, 48, 65, 98, 129, 131, 143, 165, 171, 172, 196, 198, 277, 296, 311, 317, 327, 351, 380}, new short[]{51, 69, 96, 98, 117, 123, 130, 131, 148, 161, 168, 172, 176, 184, 202, 324, 332, 336, 348, 392}, new short[]{1, 20, 37, 57, 70, 76, 79, 87, 165, 176, 234, 251, 333, 388}, new short[]{8, 13, 134, 135, 153, 165, 169, 193, 195, 255, 273, 337, 348, 359, 360, 382, 391}, new short[]{2, 14, 53, 71, 83, 127, 136, 144, 149, 208, 234, 235, 293, 301, 347, 352}, new short[]{20, 40, 42, 95, 135, 141, 165, 199, 250, 290, 299, 308, 337, 338, 350, 353, 354, 355, 358, 380}, new short[]{13, 19, 33, 35, 36, 49, 85, 121, 122, 127, 137, 158, 165, 282, 303, 320, 328, 334, 365, 367, 374}, new short[]{17, 37, 123, 126, 127, 139, 140, 143, 167, 185, 192, 235, 254, 275, 315, 340, 349, 353, 362}, new short[]{57, 72, 127, 159, 163, 165, 176, 199, 215, 218, 238, 254, 284, 288, 336, 339, 347, 352, 380, 395}, new short[]{54, 69, 81, 101, 114, 121, 165, 206, 236, 313, 332, 338, 349, 358, 360, 362, 377}, new short[]{29, 37, 43, 120, 127, 176, 193, 244, 246, 254, 284, 288, 336, 339, 372}, new short[]{36, 56, 85, 122, 125, 126, 154, 232, 282, 308, 314, 315, 324, 336, 353, 359, 382}, new short[]{7, 99, 104, 117, 124, 125, 143, 176, 239, 298, 318, 383}, new short[]{13, 20, 71, 90, 108, 122, 176, 186, 214, 231, 247, 262, 267, 280, 286, 300, 332, 358, 377, 380, 385, 390, 393}, new short[]{31, 65, 75, 79, 85, 91, 109, 110, 120, 159, 229, 235, 288, 298, 347, 355, 359, 379, 381}, new short[]{38, 75, 82, 90, 99, 202, 248, 265, 324, 329, 350, 354, 355, 365}, new short[]{7, 15, 72, 90, 117, 125, 140, 144, 171, 198, 269, 271, 282, 305, 325, 338, 343, 353}, new short[]{13, 14, 20, 29, 37, 42, 45, 47, 165, 184, 244, 329, 341, 347, 372}, new short[]{31, 36, 82, 99, 149, 154, 173, 182, 185, 200, 217, 251, 298, 329, 332, 333, 349, 353, 354, 355, 377, 383}, new short[]{32, 44, 45, 52, 93, 97, 108, 114, 120, 144, 155, 172, 236, 240, 267, 272, 282, 288, 329, 333, 334, 343, 381}, new short[]{35, 55, 57, 62, 95, 96, 98, 127, 131, 177, 262, 317, 318, 357, 359, 380, 388}, new short[]{22, 24, 68, 103, 115, 119, 120, 125, 128, 156, 162, 184, 186, 235, 244, 327, 353, 358, 378, 380, 393}, new short[]{29, 37, 62, 67, 81, 83, 93, 104, 110, 129, 132, 142, 172, 274, 298, 354, 380}, new short[]{19, 45, 66, 87, 104, 108, 118, 155, 170, 176, 234, 286, 310, 313, 327, 329, 333, 347, 358, 368, 380, 383, 386}, new short[]{10, 14, 32, 83, 96, 131, 165, 180, 205, 211, 249, 255, 286, 288, 292, 299, 312, 336, 338, 349, 368, 375}, new short[]{2, 13, 48, 75, 85, 98, 116, 125, 126, 128, 135, 136, 151, 188, 195, 243, 280, 289, 333, 339, 349, 378, 382}, new short[]{9, 19, 39, 45, 87, 106, 117, 125, 126, 127, 154, 165, 202, 211, 256, 309, 360, 397, 398}, new short[]{14, 21, 65, 76, 87, 93, 97, 105, 131, 177, 212, 254, 294, 336, 349, 359, 381}, new short[]{36, 55, 65, 70, 87, 93, 96, 98, 108, 127, 254, 337, 352, 359, 375, 380}, new short[]{22, 42, 62, 82, 131, 132, 136, 158, 168, 196, 267, 305, 336}, new short[]{45, 69, 74, 75, 81, 120, 123, 126, 127, 130, 150, 171, 191, 194, 313, 339, 368, 378, 379, 389, 398}, new short[]{35, 43, 85, 98, 122, 131, 135, 176, 189, 250, 259, 277, 288, 303, 333, 336, 345, 376, 381, 387}, new short[]{1, 6, 34, 87, 115, 129, 131, 202, 235, 252, 256, 263, 317, 328, 349, 372, 391}, new short[]{3, 18, 42, 48, 84, 90, 92, 138, 193, 227, 288, 310, 315, 353, 375}, new short[]{2, 10, 31, 66, 124, 145, 240, 314, 334}, new short[]{32, 38, 84, 141, 165, 188, 193, 212, 346, 359, 379, 380}, new short[]{10, 75, 81, 96, 111, 140, 179, 298, 309, 353, 357, 359, 380, 396}, new short[]{2, 34, 121, 127, 132, 134, 184, 234, 244, 251, 262, 290, 308, 359, 380}, new short[]{17, 24, 93, 172, 186, 198, 218, 234, 239, 250, 252, 255, 307, 309, 325, 334, 354, 359}, new short[]{14, 18, 45, 50, 131, 174, 211, 237, 252, 267, 309, 334, 348, 351, 377, 391}, new short[]{32, 61, 87, 97, 125, 126, 132, 184, 249, 252, 273, 284, 288, 339, 383, 398}, new short[]{76, 81, 87, 127, 147, 161, 163, 199, 206, 306, 329, 340, 349, 353, 360, 383}, new short[]{14, 16, 76, 87, 101, 169, 188, 243, 246, 251, 253, 269, 298, 355, 375, 380}, new short[]{32, 79, 87, 103, 117, 125, 127, 177, 244, 301, 305, 317, 333, 338, 340, 342, 391}, new short[]{4, 67, 76, 121, 127, 130, 140, 158, 165, 186, 193, 251, 301, 303, 330, 336}, new short[]{11, 76, 83, 84, 87, 214, 248, 276, 299, 311, 320, 329, 332, 335, 371}, new short[]{2, 4, 19, 40, 42, 71, 98, 119, 121, 137, 167, 262, 288, 295, 306, 339, 350, 382}, new short[]{14, 40, 54, 90, 125, 129, 132, 146, 147, 165, 169, 176, 190, 253, 284, 303, 307, 316, 339, 342, 359, 389}, new short[]{47, 59, 71, 103, 125, 126, 129, 130, 200, 206, 240, 254, 276, 282, 299, 303, 307, 318, 320, 336, 338, 357, 362, 380, 387, 392}, new short[]{4, 22, 58, 102, 113, 115, 153, 167, 188, 212, 262, 286, 305, 333, 348, 354, 360, 371, 379, 386}, new short[]{5, 6, 56, 61, 108, 128, 129, 164, 165, 177, 182, 225, 226, 235, 244, 246, 249, 310, 333, 348, 349, 381, 391}, new short[]{18, 32, 33, 53, 56, 176, 186, 199, 200, 244, 246, 248, 259, 285, 289, 306, 358, 371, 373, 375, 379}, new short[]{40, 43, 70, 76, 83, 84, 90, 93, 101, 125, 159, 204, 276, 282, 304, 320, 339, 351, 353, 367, 391}, new short[]{14, 19, 59, 71, 76, 87, 93, 97, 105, 111, 120, 121, 122, 154, 171, 211, 231, 244, 286, 288, 341, 351}, new short[]{10, 56, 65, 72, 92, 108, 123, 129, 212, 258, 329, 353, 359}, new short[]{5, 76, 124, 127, 161, 172, 188, 244, 250, 266, 290, 318, 347, 351, 369, 382, 391, 395}, new short[]{1, 33, 86, 120, 121, 130, 154, 162, 173, 192, 241, 244, 262, 338, 339, 343, 353, 380, 390}, new short[]{1, 15, 22, 54, 57, 85, 126, 127, 176, 188, 248, 305, 332, 347, 349, 358, 367}, new short[]{91, 111, 122, 125, 130, 178, 190, 224, 225, 226, 235, 286, 308, 329, 334, 345, 346, 349, 358, 362, 367}, new short[]{16, 26, 51, 54, 84, 85, 98, 120, 272, 319, 349, 359, 360, 362, 377, 391, 398}, new short[]{73, 85, 102, 109, 128, 153, 171, 184, 248, 249, 256, 298, 300, 335, 338, 340, 355, 370}, new short[]{9, 108, 122, 131, 164, 168, 173, 176, 195, 218, 235, 286, 341, 350, 353, 358, 375, 377}, new short[]{25, 62, 125, 140, 165, 173, 200, 225, 226, 243, 283, 286, 329, 343, 357, 366, 377}, new short[]{10, 35, 58, 64, 98, 103, 125, 127, 129, 135, 141, 165, 169, 175, 189, 244, 258, 259, 306, 331, 333, 378, 380, 391}, new short[]{54, 87, 89, 99, 116, 125, 129, 221, 246, 269, 324, 335, 348, 351}, new short[]{85, 90, 103, 115, 131, 134, 165, 207, 282, 307, 313, 328, 346, 349, 380, 383, 387, 398}, new short[]{10, 40, 74, 84, 160, 239, 253, 272, 282, 333, 344, 351, 359, 360, 379}, new short[]{32, 38, 54, 74, 76, 117, 163, 171, 176, 217, 227, 250, 251, 280, 329, 330, 350, 378}, new short[]{13, 20, 40, 107, 129, 135, 154, 158, 161, 163, 179, 206, 281, 315, 325, 351, 355, 359, 397}, new short[]{0, 4, 37, 49, 62, 98, 117, 129, 177, 244, 285, 289, 306, 338, 360, 381}, new short[]{36, 38, 43, 61, 71, 87, 120, 128, 172, 200, 235, 247, 251, 282, 299, 329, 341, 352, 355}, new short[]{43, 71, 83, 85, 108, 117, 118, 121, 133, 138, 165, 206, 231, 254, 290, 291, 335, 336, 359, 362, 377}, new short[]{29, 32, 71, 103, 122, 125, 198, 224, 244, 285, 303, 333, 335, 337}, new short[]{54, 55, 82, 87, 101, 108, 127, 229, 230, 269, 290, 306, 349, 353}, new short[]{9, 117, 126, 137, 154, 165, 167, 186, 192, 229, 277, 283, 301, 317, 365, 367, 372, 378}, new short[]{4, 11, 19, 47, 51, 92, 110, 132, 137, 140, 290, 298, 361, 377, 379}, new short[]{23, 83, 98, 134, 165, 170, 186, 190, 253, 269, 308, 322, 327, 332, 335, 344, 398}, new short[]{60, 83, 111, 129, 173, 176, 186, 232, 306, 327, 329, 349, 355}, new short[]{25, 31, 40, 56, 72, 95, 126, 144, 149, 161, 173, 240, 262, 332, 333, 356, 368, 391, 394}, new short[]{91, 127, 134, 144, 155, 158, 161, 232, 251, 280, 287, 353, 380, 394}, new short[]{37, 43, 57, 84, 87, 149, 175, 288, 330, 380}, new short[]{8, 9, 83, 97, 120, 128, 158, 171, 193, 232, 287, 308, 309, 334, 355}, new short[]{39, 40, 62, 82, 94, 98, 101, 144, 147, 205, 290, 333, 339, 353, 372, 397}, new short[]{10, 20, 38, 125, 135, 138, 168, 180, 191, 203, 231, 250, 280, 301, 328, 345, 388}, new short[]{44, 54, 64, 87, 117, 122, 127, 154, 234, 239, 244, 298, 329, 378, 383}, new short[]{13, 62, 70, 97, 121, 176, 244, 267, 282, 318, 324, 334, 341, 353, 386, 388}, new short[]{40, 89, 91, 117, 125, 131, 155, 173, 193, 244, 273, 277, 328, 333, 360, 382}, new short[]{30, 47, 95, 108, 127, 165, 188, 211, 273, 349, 354, 368, 391}, new short[]{19, 52, 87, 98, 100, 122, 125, 157, 159, 215, 217, 235, 254, 309, 336, 344, 349, 382}, new short[]{19, 85, 87, 136, 144, 180, 190, 229, 310, 345, 365, 376, 390}, new short[]{35, 52, 87, 113, 124, 135, 145, 167, 174, 225, 226, 244, 247, 300, 359}, new short[]{10, 35, 69, 103, 129, 144, 165, 180, 230, 232, 329, 335, 353, 359, 371, 390}, new short[]{5, 13, 80, 83, 135, 139, 142, 176, 179, 190, 205, 217, 282, 298, 308, 334, 353, 359}, new short[]{24, 52, 67, 108, 135, 138, 153, 176, 231, 249, 283, 304, 337, 351, 353, 355}, new short[]{90, 93, 127, 132, 136, 163, 165, 196, 284, 306, 353, 383}, new short[]{20, 37, 103, 126, 135, 184, 204, 215, 221, 288, 300, 329, 339, 358, 383}, new short[]{16, 36, 52, 99, 117, 136, 171, 190, 243, 244, 303, 315, 333, 349, 373, 382}, new short[]{0, 57, 69, 98, 125, 129, 132, 158, 165, 190, 191, 193, 198, 254, 256, 285, 288, 303, 339, 346, 351, 391}, new short[]{1, 13, 21, 87, 125, 132, 150, 204, 240, 249, 253, 265, 288, 334, 343, 348, 349, 359}, new short[]{29, 40, 71, 80, 91, 99, 122, 203, 289, 290, 298, 329, 353, 380, 390}, new short[]{2, 5, 36, 57, 93, 102, 135, 140, 314, 343, 398}, new short[]{20, 59, 107, 193, 204, 246, 247, 336, 341, 342, 354, 359, 360, 383}, new short[]{47, 71, 93, 111, 116, 120, 122, 130, 251, 286, 298, 299, 348}, new short[]{21, 52, 56, 69, 76, 118, 120, 125, 137, 274, 280, 324, 327, 335, 339, 340}, new short[]{23, 29, 57, 75, 98, 132, 149, 157, 160, 235, 244, 288, 327, 340, 354, 372, 377}, new short[]{4, 22, 97, 103, 111, 129, 131, 151, 158, 176, 204, 248, 265, 309, 359, 391, 392}, new short[]{15, 17, 73, 105, 115, 170, 186, 228, 255, 317, 321, 339, 349, 379, 380, 381}, new short[]{17, 52, 72, 103, 188, 329, 342, 353, 358, 359, 374, 376, 380, 393}, new short[]{40, 48, 74, 124, 135, 191, 225, 226, 237, 291, 300, 304, 310, 347, 359, 380, 396}, new short[]{2, 36, 47, 57, 122, 125, 174, 188, 203, 224, 255, 325, 353, 359, 387}, new short[]{13, 58, 69, 83, 115, 120, 134, 161, 165, 174, 175, 191, 246, 255, 280, 353, 357, 358, 359, 379}, new short[]{1, 29, 47, 87, 89, 135, 176, 190, 209, 236, 304, 344, 348, 358, 359, 378}, new short[]{8, 13, 40, 52, 58, 61, 71, 125, 144, 168, 189, 210, 260, 337, 338, 340, 347, 376, 380}, new short[]{29, 90, 126, 127, 129, 136, 145, 159, 165, 188, 274, 284, 288, 316, 329, 358, 380}, new short[]{2, 19, 103, 120, 123, 159, 165, 175, 177, 180, 238, 244, 251, 294, 329, 342, 345, 349, 357, 376, 392}, new short[]{41, 42, 59, 71, 81, 98, 101, 117, 159, 171, 180, 240, 285, 290, 299, 344, 353}, new short[]{83, 103, 108, 142, 175, 248, 290, 300, 321, 354, 365, 374, 382}, new short[]{12, 67, 105, 130, 140, 171, 188, 192, 244, 276, 290, 302, 348, 349, 357, 360, 380}, new short[]{4, 13, 36, 65, 75, 160, 165, 185, 198, 235, 293, 324, 327, 333, 345, 347, 375, 383}, new short[]{37, 61, 80, 125, 234, 283, 290, 353, 359, 378, 383}, new short[]{9, 32, 83, 110, 155, 248, 252, 288, 313}, new short[]{37, 48, 52, 93, 167, 170, 179, 244, 267, 288, 296, 333, 335, 355, 374}, new short[]{35, 92, 98, 153, 165, 184, 215, 233, 242, 290, 339, 355}, new short[]{9, 38, 83, 121, 127, 165, 176, 235, 253, 305, 330, 337, 355, 358, 359}, new short[]{35, 117, 122, 125, 132, 136, 183, 235, 254, 280, 285, 286, 329, 334, 338, 353, 372}, new short[]{6, 87, 117, 125, 141, 144, 153, 157, 179, 215, 267, 272, 289, 329, 336, 359}, new short[]{7, 14, 37, 82, 135, 147, 154, 202, 244, 290, 297, 298, 345, 355, 368, 383}, new short[]{105, 135, 173, 244, 255, 280, 288, 299, 304, 307, 337, 338, 341, 344}, new short[]{19, 31, 33, 77, 92, 99, 114, 151, 173, 202, 253, 318, 329, 333, 358, 371}, new short[]{1, 8, 14, 30, 39, 120, 157, 172, 227, 229, 251, 257, 272, 339, 380}, new short[]{19, 98, 171, 191, 213, 246, 289, 353, 357, 366, 374, 383}, new short[]{8, 98, 125, 126, 144, 152, 244, 277, 282, 290, 322, 393}, new short[]{17, 206, 211, 224, 336, 338, 386}, new short[]{52, 55, 71, 99, 105, 191, 211, 215, 224, 246, 290, 300, 336, 339, 361}, new short[]{15, 16, 44, 66, 96, 121, 127, 162, 167, 202, 219, 243, 244, 254, 282, 320, 345, 390}, new short[]{7, 83, 92, 121, 130, 160, 177, 280, 308, 309, 339, 350, 352, 358, 380, 390}, new short[]{67, 122, 144, 148, 170, 173, 184, 222, 280, 374}, new short[]{2, 4, 15, 19, 115, 130, 136, 148, 172, 180, 243, 251, 313, 329, 333, 359, 364}, new short[]{90, 98, 108, 124, 167, 176, 202, 254, 286, 351, 359}, new short[]{80, 126, 135, 167, 212, 242, 243, 256, 283, 286, 295, 327, 337, 340, 346, 357, 358, 364}, new short[]{19, 108, 125, 132, 149, 172, 180, 186, 200, 254, 286, 296, 339, 344, 350, 359, 391}, new short[]{62, 65, 67, 105, 127, 129, 132, 250, 298, 307, 334, 344, 359, 383}, new short[]{31, 59, 87, 107, 121, 131, 132, 160, 244, 246, 247, 253, 344, 360, 394}, new short[]{4, 39, 76, 125, 130, 148, 168, 170, 191, 196, 298, 306, 327, 338, 345, 349, 360, 375}, new short[]{13, 14, 32, 84, 98, 122, 126, 156, 188, 235, 255, 330, 336, 338, 375, 380, 389}, new short[]{5, 18, 31, 54, 71, 74, 76, 81, 87, 93, 126, 129, 182, 303, 327, 353, 359, 373, 391}, new short[]{13, 37, 64, 137, 138, 180, 244, 247, 251, 253, 269, 284, 308, 344, 374, 376}, new short[]{5, 7, 10, 23, 35, 125, 168, 169, 187, 191, 192, 313, 337, 340, 342, 365}, new short[]{62, 67, 122, 125, 165, 190, 217, 243, 254, 256, 265, 299, 318, 353, 394}, new short[]{4, 24, 62, 92, 109, 118, 134, 143, 144, 176, 190, 199, 221, 299, 349, 380}, new short[]{22, 35, 64, 74, 92, 113, 161, 172, 193, 282, 287, 307, 359, 393}, new short[]{37, 50, 66, 75, 76, 78, 82, 87, 139, 159, 172, 176, 188, 231, 352, 371}, new short[]{19, 31, 75, 121, 144, 152, 163, 171, 172, 198, 243, 246, 285, 288, 289, 333, 344, 347, 357, 398}, new short[]{1, 15, 17, 51, 57, 65, 69, 127, 241, 244, 254, 259, 329, 336, 358}, new short[]{9, 95, 117, 121, 125, 137, 204, 242, 247, 301, 309, 314, 334, 339, 350, 354, 358}, new short[]{9, 61, 96, 111, 130, 163, 180, 211, 225, 226, 241, 253, 282, 283, 346, 355, 359, 380, 383}, new short[]{94, 117, 121, 124, 126, 130, 135, 172, 199, 232, 286, 325, 336, 352, 362, 375}, new short[]{110, 125, 163, 250, 265, 303, 329, 334, 391}, new short[]{47, 72, 76, 111, 125, 157, 169, 245, 254, 285, 287, 297, 298, 336, 353, 359, 383}, new short[]{62, 93, 115, 125, 127, 130, 174, 231, 308, 310, 329, 333, 355, 359, 390}, new short[]{44, 116, 163, 167, 180, 191, 200, 245, 254, 329, 343, 345, 354, 364}, new short[]{31, 62, 105, 108, 144, 145, 162, 173, 177, 191, 198, 247, 249, 344, 345, 348, 353}, new short[]{29, 65, 66, 74, 83, 87, 125, 148, 165, 228, 334, 353, 359, 380, 383, 391}, new short[]{2, 15, 125, 130, 239, 290, 312, 336, 337, 341, 398}, new short[]{40, 76, 87, 114, 119, 120, 165, 229, 265, 313, 324, 349, 358, 383}, new short[]{48, 62, 87, 91, 103, 186, 195, 212, 214, 315, 322, 327, 330, 338, 339}, new short[]{9, 32, 85, 108, 135, 191, 224, 237, 257, 288, 307, 310, 313, 318, 329, 337, 352, 395}, new short[]{87, 93, 102, 112, 129, 154, 171, 236, 317, 320, 349, 350, 359, 380}, new short[]{1, 14, 92, 111, 137, 140, 186, 290, 329, 336, 354, 355, 378, 379, 383}, new short[]{7, 26, 37, 47, 84, 101, 144, 153, 175, 180, 198, 232, 243, 305, 333, 353, 357, 383}, new short[]{20, 58, 76, 93, 99, 127, 134, 154, 188, 206, 246, 312, 313, 324}, new short[]{2, 12, 117, 125, 160, 167, 188, 206, 279, 285, 287, 301, 329, 332, 333, 336, 344, 362}, new short[]{2, 76, 126, 127, 137, 165, 244, 288, 290, 339, 346, 351, 359, 365, 383}, new short[]{66, 108, 136, 151, 174, 265, 344, 351, 353, 357, 378, 386}, new short[]{8, 76, 87, 90, 111, 116, 124, 176, 198, 334, 337, 349, 359, 379, 394}, new short[]{32, 36, 42, 76, 81, 125, 127, 205, 227, 262, 280, 288, 326, 336, 390, 398}, new short[]{9, 32, 65, 83, 89, 93, 97, 122, 129, 178, 180, 215, 241, 246, 323, 332, 353, 362, 364, 380}, new short[]{5, 24, 56, 127, 130, 155, 184, 191, 217, 235, 245, 339, 344, 358, 359, 362, 380}, new short[]{14, 40, 64, 71, 93, 108, 131, 165, 188, 204, 217, 235, 237, 241, 248, 308, 309, 318, 380, 387}, new short[]{17, 29, 34, 74, 125, 175, 184, 196, 211, 275, 301, 318, 327, 334, 349, 355, 358, 368}, new short[]{15, 45, 110, 111, 116, 129, 132, 211, 247, 275, 286, 317, 333, 334, 377, 383}, new short[]{4, 5, 59, 87, 103, 124, 125, 127, 130, 165, 241, 265, 299, 353, 360}, new short[]{31, 120, 124, 135, 154, 197, 235, 243, 247, 248, 258, 309, 320, 335, 357}, new short[]{50, 125, 127, 130, 137, 147, 171, 172, 267, 289, 301, 308, 325, 334, 337, 353, 360, 374, 391}, new short[]{62, 64, 69, 87, 111, 118, 129, 134, 212, 239, 244, 246, 250, 254, 307, 322, 329, 370, 372}, new short[]{54, 92, 128, 160, 198, 244, 248, 255, 284, 314, 335, 349, 358, 360, 376, 380}, new short[]{9, 13, 29, 54, 72, 89, 110, 122, 126, 139, 158, 159, 163, 230, 304, 306, 313}, new short[]{1, 9, 54, 95, 108, 132, 176, 193, 243, 251, 339, 378}, new short[]{0, 96, 99, 135, 137, 184, 212, 232, 251, 315, 334}, new short[]{140, 157, 165, 182, 235, 294, 314, 349, 354, 365}, new short[]{14, 18, 31, 56, 117, 125, 138, 227, 246, 283, 334, 345, 352, 357, 361}, new short[]{0, 71, 82, 130, 131, 144, 161, 235, 247, 301, 333, 335, 345, 353, 355, 359, 360, 374}, new short[]{6, 23, 35, 117, 125, 141, 169, 200, 244, 288, 298, 338, 353, 379}, new short[]{10, 98, 125, 127, 138, 153, 219, 244, 307, 350, 353, 366, 367}, new short[]{9, 32, 40, 122, 126, 127, 170, 176, 300, 334, 350, 391}, new short[]{6, 13, 31, 87, 89, 97, 125, 165, 171, 173, 176, 244, 331, 348, 373}, new short[]{10, 61, 87, 105, 123, 125, 127, 195, 260, 265, 323, 361, 362}, new short[]{2, 20, 90, 124, 353, 354, 378, 382}, new short[]{5, 48, 58, 83, 98, 117, 125, 126, 196, 198}, new short[]{13, 37, 50, 64, 66, 79, 99, 132, 135, 244, 247, 380}, new short[]{57, 165, 235, 238, 248, 272, 287, 299, 327, 329, 334, 350, 353, 380}, new short[]{55, 66, 118, 125, 130, 169, 250, 255, 271, 314, 324, 338, 353}, new short[]{7, 31, 62, 84, 103, 105, 111, 126, 132, 149, 154, 191, 250, 334, 372, 375}, new short[]{56, 81, 114, 117, 120, 124, 127, 128, 154, 254, 290, 317, 345, 354}, new short[]{4, 13, 86, 101, 153, 191, 193, 231, 243, 258, 283, 288, 308, 353, 387, 392}, new short[]{5, 37, 58, 62, 67, 84, 87, 176, 237, 267, 333, 334, 347}, new short[]{1, 7, 74, 110, 165, 168, 182, 233, 288, 305, 309, 315, 347, 351, 353, 358, 360, 375}, new short[]{57, 84, 129, 138, 165, 243, 244, 259, 280, 282, 290, 380, 383} }; } }
2881099/dotnetGen_postgresql
5,396
GenPg/NPinyin/Pinyin.cs
/** * NPinyin包含一个公开类Pinyin,该类实现了取汉字文本首字母、文本对应拼音、以及 * 获取和拼音对应的汉字列表等方法。由于汉字字库大,且多音字较多,因此本组中实现的 * 拼音转换不一定和词语中的字的正确读音完全吻合。但绝大部分是正确的。 * * 最后感谢百度网友韦祎提供的常用汉字拼音对照表。见下载地址: * http://wenku.baidu.com/view/d725f4335a8102d276a22f46.html * * 最后,我想简要地说明一下我的设计思路: * 首先,我将汉字按拼音分组后建立一个字符串数组(见PyCode.codes),然后使用程序 * 将PyCode.codes中每一个汉字通过其编码值使用散列函数: * * f(x) = x % PyCode.codes.Length * { * g(f(x)) = pos(x) * * 其中, pos(x)为字符x所属字符串所在的PyCode.codes的数组下标, 然后散列到同 * PyCode.codes长度相同长度的一个散列表中PyHash.hashes)。 * 当检索一个汉字的拼音时,首先从PyHash.hashes中获取和 * 对应的PyCode.codes中数组下标,然后从对应字符串查找,当到要查找的字符时,字符 * 串的前6个字符即包含了该字的拼音。 * * 此种方法的好处一是节约了存储空间,二是兼顾了查询效率。 * * 如有意见,请与我联系反馈。我的邮箱是:qzyzwsy@gmail.com * * 汪思言 2011年1月3日凌晨 * */ /* * v0.2.x的变化 * ================================================================= * 1、增加对不同编码格式文本的支持,同时增加编码转换方法Pinyin.ConvertEncoding * 2、重构单字符拼音的获取,未找到拼音时返回字符本身. * * 汪思言 2012年7月23日晚 * */ using System; using System.Collections.Generic; using System.Text; namespace NPinyin { public static class Pinyin { /// <summary> /// 取中文文本的拼音首字母 /// </summary> /// <param name="text">编码为UTF8的文本</param> /// <returns>返回中文对应的拼音首字母</returns> public static string GetInitials(string text) { text = text.Trim(); StringBuilder chars = new StringBuilder(); for (var i = 0; i < text.Length; ++i) { string py = GetPinyin(text[i]); if (py != "") chars.Append(py[0]); } return chars.ToString().ToUpper(); } /// <summary> /// 取中文文本的拼音首字母 /// </summary> /// <param name="text">文本</param> /// <param name="encoding">源文本的编码</param> /// <returns>返回encoding编码类型中文对应的拼音首字母</returns> public static string GetInitials(string text, Encoding encoding) { string temp = ConvertEncoding(text, encoding, Encoding.UTF8); return ConvertEncoding(GetInitials(temp), Encoding.UTF8, encoding); } /// <summary> /// 取中文文本的拼音 /// </summary> /// <param name="text">编码为UTF8的文本</param> /// <returns>返回中文文本的拼音</returns> public static string GetPinyin(string text) { StringBuilder sbPinyin = new StringBuilder(); for (var i = 0; i < text.Length; ++i) { string py = GetPinyin(text[i]); if (py != "") sbPinyin.Append(py); sbPinyin.Append(" "); } return sbPinyin.ToString().Trim(); } /// <summary> /// 取中文文本的拼音 /// </summary> /// <param name="text">编码为UTF8的文本</param> /// <param name="encoding">源文本的编码</param> /// <returns>返回encoding编码类型的中文文本的拼音</returns> public static string GetPinyin(string text, Encoding encoding) { string temp = ConvertEncoding(text.Trim(), encoding, Encoding.UTF8); return ConvertEncoding(GetPinyin(temp), Encoding.UTF8, encoding); } /// <summary> /// 取和拼音相同的汉字列表 /// </summary> /// <param name="Pinyin">编码为UTF8的拼音</param> /// <returns>取拼音相同的汉字列表,如拼音“ai”将会返回“唉爱……”等</returns> public static string GetChineseText(string pinyin) { string key = pinyin.Trim().ToLower(); foreach (string str in PyCode.codes) { if (str.StartsWith(key + " ") || str.StartsWith(key + ":")) return str.Substring(7); } return ""; } /// <summary> /// 取和拼音相同的汉字列表,编码同参数encoding /// </summary> /// <param name="Pinyin">编码为encoding的拼音</param> /// <param name="encoding">编码</param> /// <returns>返回编码为encoding的拼音为pinyin的汉字列表,如拼音“ai”将会返回“唉爱……”等</returns> public static string GetChineseText(string pinyin, Encoding encoding) { string text = ConvertEncoding(pinyin, encoding, Encoding.UTF8); return ConvertEncoding(GetChineseText(text), Encoding.UTF8, encoding); } /// <summary> /// 返回单个字符的汉字拼音 /// </summary> /// <param name="ch">编码为UTF8的中文字符</param> /// <returns>ch对应的拼音</returns> public static string GetPinyin(char ch) { short hash = GetHashIndex(ch); for (var i = 0; i < PyHash.hashes[hash].Length; ++i) { short index = PyHash.hashes[hash][i]; var pos = PyCode.codes[index].IndexOf(ch, 7); if (pos != -1) return PyCode.codes[index].Substring(0, 6).Trim(); } return ch.ToString(); } /// <summary> /// 返回单个字符的汉字拼音 /// </summary> /// <param name="ch">编码为encoding的中文字符</param> /// <returns>编码为encoding的ch对应的拼音</returns> public static string GetPinyin(char ch, Encoding encoding) { ch = ConvertEncoding(ch.ToString(), encoding, Encoding.UTF8)[0]; return ConvertEncoding(GetPinyin(ch), Encoding.UTF8, encoding); } /// <summary> /// 转换编码 /// </summary> /// <param name="text">文本</param> /// <param name="srcEncoding">源编码</param> /// <param name="dstEncoding">目标编码</param> /// <returns>目标编码文本</returns> public static string ConvertEncoding(string text, Encoding srcEncoding, Encoding dstEncoding) { byte[] srcBytes = srcEncoding.GetBytes(text); byte[] dstBytes = Encoding.Convert(srcEncoding, dstEncoding, srcBytes); return dstEncoding.GetString(dstBytes); } /// <summary> /// 取文本索引值 /// </summary> /// <param name="ch">字符</param> /// <returns>文本索引值</returns> private static short GetHashIndex(char ch) { return (short)((uint)ch % PyCode.codes.Length); } } }
2881099/dotnetGen_postgresql
11,323
GenPg/NPinyin/PyCode.cs
using System; using System.Collections.Generic; using System.Text; namespace NPinyin { internal class PyCode { internal static string[] codes = new string[]{ "a :阿啊吖嗄腌锕", "ai :爱埃碍矮挨唉哎哀皑癌蔼艾隘捱嗳嗌嫒瑷暧砹锿霭", "an :安按暗岸案俺氨胺鞍谙埯揞犴庵桉铵鹌黯", "ang :昂肮盎", "ao :凹奥敖熬翱袄傲懊澳坳拗嗷岙廒遨媪骜獒聱螯鏊鳌鏖", "ba :把八吧巴拔霸罢爸坝芭捌扒叭笆疤跋靶耙茇菝岜灞钯粑鲅魃", "bai :百白败摆柏佰拜稗捭掰", "ban :办半板班般版拌搬斑扳伴颁扮瓣绊阪坂钣瘢癍舨", "bang :帮棒邦榜梆膀绑磅蚌镑傍谤蒡浜", "bao :报保包剥薄胞暴宝饱抱爆堡苞褒雹豹鲍葆孢煲鸨褓趵龅", "bei :北被倍备背辈贝杯卑悲碑钡狈惫焙孛陂邶埤萆蓓呗悖碚鹎褙鐾鞴", "ben :本奔苯笨畚坌贲锛", "beng :泵崩绷甭蹦迸嘣甏", "bi :比必避闭辟笔壁臂毕彼逼币鼻蔽鄙碧蓖毙毖庇痹敝弊陛匕俾荜荸薜吡哔狴庳愎滗濞弼妣婢嬖璧畀铋秕裨筚箅篦舭襞跸髀", "bian :变边便编遍辩扁辨鞭贬卞辫匾弁苄忭汴缏飚煸砭碥窆褊蝙笾鳊", "biao :表标彪膘婊骠杓飑飙镖镳瘭裱鳔髟", "bie :别鳖憋瘪蹩", "bin :宾彬斌濒滨摈傧豳缤玢槟殡膑镔髌鬓", "bing :并病兵柄冰丙饼秉炳禀邴摒", "bo :波播伯拨博勃驳玻泊菠钵搏铂箔帛舶脖膊渤亳啵饽檗擘礴钹鹁簸跛踣", "bu :不部步布补捕卜哺埠簿怖卟逋瓿晡钚钸醭", "ca :擦嚓礤", "cai :采才材菜财裁彩猜睬踩蔡", "can :参残蚕灿餐惭惨孱骖璨粲黪", "cang :藏仓苍舱沧", "cao :草槽操糙曹嘈漕螬艚", "ce :测策侧册厕恻", "cen :岑涔", "ceng :层蹭", "cha :查差插察茶叉茬碴搽岔诧猹馇汊姹杈楂槎檫锸镲衩", "chai :柴拆豺侪钗瘥虿", "chan :产铲阐搀掺蝉馋谗缠颤冁谄蒇廛忏潺澶羼婵骣觇禅镡蟾躔", "chang :长常场厂唱肠昌倡偿畅猖尝敞伥鬯苌菖徜怅惝阊娼嫦昶氅鲳", "chao :朝超潮巢抄钞嘲吵炒怊晁耖", "che :车彻撤扯掣澈坼砗", "chen :陈沉称衬尘臣晨郴辰忱趁伧谌谶抻嗔宸琛榇碜龀", "cheng :成程称城承乘呈撑诚橙惩澄逞骋秤丞埕噌枨柽塍瞠铖铛裎蛏酲", "chi :持尺齿吃赤池迟翅斥耻痴匙弛驰侈炽傺坻墀茌叱哧啻嗤彳饬媸敕眵鸱瘛褫蚩螭笞篪豉踟魑", "chong :虫充冲崇宠茺忡憧铳舂艟", "chou :抽仇臭酬畴踌稠愁筹绸瞅丑俦帱惆瘳雠", "chu :出处除初础触楚锄储橱厨躇雏滁矗搐亍刍怵憷绌杵楮樗褚蜍蹰黜", "chuai :揣搋啜膪踹", "chuan :传船穿串川椽喘舛遄巛氚钏舡", "chuang:床创窗闯疮幢怆", "chui :吹垂锤炊捶陲棰槌", "chun :春纯醇椿唇淳蠢莼鹑蝽", "chuo :戳绰辍踔龊", "ci :此次刺磁雌词茨疵辞慈瓷赐茈呲祠鹚糍", "cong :从丛聪葱囱匆苁淙骢琮璁", "cou :凑楱辏腠", "cu :粗促醋簇蔟徂猝殂酢蹙蹴", "cuan :篡蹿窜汆撺爨镩", "cui :催脆淬粹摧崔瘁翠萃啐悴璀榱毳隹", "cun :存村寸忖皴", "cuo :错措撮磋搓挫厝嵯脞锉矬痤鹾蹉", "da :大打达答搭瘩耷哒嗒怛妲疸褡笪靼鞑", "dai :代带待袋戴呆歹傣殆贷逮怠埭甙呔岱迨骀绐玳黛", "dan :单但弹担蛋淡胆氮丹旦耽郸掸惮诞儋萏啖殚赕眈疸瘅聃箪", "dang :党当档挡荡谠凼菪宕砀裆", "dao :到道导刀倒稻岛捣盗蹈祷悼叨忉氘纛", "de :的得德锝", "deng :等灯登邓蹬瞪凳噔嶝戥磴镫簦", "di :地第低敌底帝抵滴弟递堤迪笛狄涤翟嫡蒂缔氐籴诋谛邸荻嘀娣绨柢棣觌砥碲睇镝羝骶", "dia :嗲", "dian :电点垫典店颠淀掂滇碘靛佃甸惦奠殿阽坫巅玷钿癜癫簟踮", "diao :调掉吊碉叼雕凋刁钓铞铫貂鲷", "die :迭跌爹碟蝶谍叠垤堞揲喋牒瓞耋蹀鲽", "ding :定顶钉丁订盯叮鼎锭仃啶玎腚碇町疔耵酊", "diu :丢铥", "dong :动东冬懂洞冻董栋侗恫垌咚岽峒氡胨胴硐鸫", "dou :斗豆兜抖陡逗痘蔸窦蚪篼", "du :度都毒独读渡杜堵镀顿督犊睹赌肚妒芏嘟渎椟牍蠹笃髑黩", "duan :断端段短锻缎椴煅簖", "dui :对队堆兑怼憝碓", "dun :盾吨顿蹲敦墩囤钝遁沌炖砘礅盹镦趸", "duo :多夺朵掇哆垛躲跺舵剁惰堕咄哚沲缍柁铎裰踱", "e :而二尔儿恶额恩俄耳饵蛾饿峨鹅讹娥厄扼遏鄂噩谔垩苊莪萼呃愕屙婀轭腭锇锷鹗颚鳄", "ei :诶", "en :恩蒽摁", "er :而二尔儿耳饵洱贰佴迩珥铒鸸鲕", "fa :发法阀乏伐罚筏珐垡砝", "fan :反翻范犯饭繁泛番凡烦返藩帆樊矾钒贩蕃蘩幡梵燔畈蹯", "fang :方放防访房纺仿妨芳肪坊邡枋钫舫鲂", "fei :非肥飞费废肺沸菲匪啡诽吠芾狒悱淝妃绯榧腓斐扉镄痱蜚篚翡霏鲱", "fen :分粉奋份粪纷芬愤酚吩氛坟焚汾忿偾瀵棼鲼鼢", "feng :风封蜂丰缝峰锋疯奉枫烽逢冯讽凤俸酆葑唪沣砜", "fou :否缶", "fu :复服副府夫负富附福伏符幅腐浮辅付腹妇孵覆扶辐傅佛缚父弗甫肤氟敷拂俘涪袱抚俯釜斧脯腑赴赋阜讣咐匐凫郛芙苻茯莩菔拊呋幞怫滏艴孚驸绂绋桴赙祓砩黻黼罘稃馥蚨蜉蝠蝮麸趺跗鲋鳆", "ga :噶嘎尬尕尜旮钆", "gai :改该盖概钙溉丐陔垓戤赅", "gan :干杆感敢赶甘肝秆柑竿赣坩苷尴擀泔淦澉绀橄旰矸疳酐", "gang :刚钢缸纲岗港杠冈肛戆罡筻", "gao :高搞告稿膏篙皋羔糕镐睾诰郜藁缟槔槁杲锆", "ge :个各革格割歌隔哥铬阁戈葛搁鸽胳疙蛤鬲仡哿圪塥嗝搿膈硌镉袼虼舸骼", "gen :根跟亘茛哏艮", "geng :更耕颈庚羹埂耿梗哽赓绠鲠", "gong :工公共供功攻巩贡汞宫恭龚躬弓拱珙肱蚣觥", "gou :够构沟狗钩勾购苟垢佝诟岣遘媾缑枸觏彀笱篝鞲", "gu :鼓固古骨故顾股谷估雇孤姑辜菇咕箍沽蛊嘏诂菰崮汩梏轱牯牿臌毂瞽罟钴锢鸪痼蛄酤觚鲴鹘", "gua :挂刮瓜剐寡褂卦诖呱栝胍鸹", "guai :怪乖拐", "guan :关管观官灌贯惯冠馆罐棺倌莞掼涫盥鹳矜鳏", "guang :光广逛咣犷桄胱", "gui :规贵归硅鬼轨龟桂瑰圭闺诡癸柜跪刽匦刿庋宄妫桧炅晷皈簋鲑鳜", "gun :滚辊棍衮绲磙鲧", "guo :国过果锅郭裹馘埚掴呙帼崞猓椁虢聒蜾蝈", "ha :哈铪", "hai :还海害孩骸氦亥骇嗨胲醢", "han :含焊旱喊汉寒汗函韩酣憨邯涵罕翰撼捍憾悍邗菡撖阚瀚晗焓顸颔蚶鼾", "hang :航夯杭沆绗珩颃", "hao :好号毫耗豪郝浩壕嚎蒿薅嗥嚆濠灏昊皓颢蚝", "he :和合河何核赫荷褐喝贺呵禾盒菏貉阂涸鹤诃劾壑嗬阖纥曷盍颌蚵翮", "hei :黑嘿", "hen :很狠痕恨", "heng :横衡恒哼亨蘅桁", "hong :红洪轰烘哄虹鸿宏弘黉訇讧荭蕻薨闳泓", "hou :后候厚侯喉猴吼堠後逅瘊篌糇鲎骺", "hu :护互湖呼户弧乎胡糊虎忽瑚壶葫蝴狐唬沪冱唿囫岵猢怙惚浒滹琥槲轷觳烀煳戽扈祜瓠鹄鹕鹱笏醐斛", "hua :化花话划滑华画哗猾骅桦砉铧", "huai :坏怀淮槐徊踝", "huan :环换欢缓患幻焕桓唤痪豢涣宦郇奂萑擐圜獾洹浣漶寰逭缳锾鲩鬟", "huang :黄簧荒皇慌蝗磺凰惶煌晃幌恍谎隍徨湟潢遑璜肓癀蟥篁鳇", "hui :会回灰挥辉汇毁慧恢绘惠徽蛔悔卉晦贿秽烩讳诲诙茴荟蕙咴哕喙隳洄浍彗缋珲晖恚虺蟪麾", "hun :混浑荤昏婚魂诨馄阍溷", "huo :活或火货获伙霍豁惑祸劐藿攉嚯夥钬锪镬耠蠖", "ji :级及机极几积给基记己计集即际季激济技击继急剂既纪寄挤鸡迹绩吉脊辑籍疾肌棘畸圾稽箕饥讥姬缉汲嫉蓟冀伎祭悸寂忌妓藉丌亟乩剞佶偈诘墼芨芰荠蒺蕺掎叽咭哜唧岌嵴洎屐骥畿玑楫殛戟戢赍觊犄齑矶羁嵇稷瘠虮笈笄暨跻跽霁鲚鲫髻麂", "jia :加家架价甲夹假钾贾稼驾嘉枷佳荚颊嫁伽郏葭岬浃迦珈戛胛恝铗镓痂瘕袷蛱笳袈跏", "jian :间件见建坚减检践尖简碱剪艰渐肩键健柬鉴剑歼监兼奸箭茧舰俭笺煎缄硷拣捡荐槛贱饯溅涧僭谏谫菅蒹搛湔蹇謇缣枧楗戋戬牮犍毽腱睑锏鹣裥笕翦趼踺鲣鞯", "jiang :将降讲江浆蒋奖疆僵姜桨匠酱茳洚绛缰犟礓耩糨豇", "jiao :较教交角叫脚胶浇焦搅酵郊铰窖椒礁骄娇嚼矫侥狡饺缴绞剿轿佼僬艽茭挢噍峤徼姣敫皎鹪蛟醮跤鲛", "jie :结阶解接节界截介借届街揭洁杰竭皆秸劫桔捷睫姐戒藉芥疥诫讦拮喈嗟婕孑桀碣疖颉蚧羯鲒骱", "jin :进金近紧斤今尽仅劲浸禁津筋锦晋巾襟谨靳烬卺荩堇噤馑廑妗缙瑾槿赆觐衿", "jing :经精京径井静竟晶净境镜景警茎敬惊睛竞荆兢鲸粳痉靖刭儆阱菁獍憬泾迳弪婧肼胫腈旌", "jiong :炯窘迥扃", "jiu :就九旧究久救酒纠揪玖韭灸厩臼舅咎疚僦啾阄柩桕鸠鹫赳鬏", "ju :具据局举句聚距巨居锯剧矩拒鞠拘狙疽驹菊咀沮踞俱惧炬倨讵苣苴莒掬遽屦琚椐榘榉橘犋飓钜锔窭裾趄醵踽龃雎鞫", "juan :卷捐鹃娟倦眷绢鄄狷涓桊蠲锩镌隽", "jue :决觉绝掘撅攫抉倔爵诀厥劂谲矍蕨噘噱崛獗孓珏桷橛爝镢蹶觖", "jun :军均菌君钧峻俊竣浚郡骏捃皲筠麇", "ka :卡喀咖咯佧咔胩", "kai :开凯揩楷慨剀垲蒈忾恺铠锎锴", "kan :看刊坎堪勘砍侃莰戡龛瞰", "kang :抗康炕慷糠扛亢伉闶钪", "kao :考靠拷烤尻栲犒铐", "ke :可克科刻客壳颗棵柯坷苛磕咳渴课嗑岢恪溘骒缂珂轲氪瞌钶锞稞疴窠颏蝌髁", "ken :肯啃垦恳裉", "keng :坑吭铿", "kong :孔空控恐倥崆箜", "kou :口扣抠寇芤蔻叩眍筘", "ku :苦库枯酷哭窟裤刳堀喾绔骷", "kua :跨夸垮挎胯侉", "kuai :快块筷侩蒯郐哙狯脍", "kuan :宽款髋", "kuang :况矿狂框匡筐眶旷诓诳邝圹夼哐纩贶", "kui :奎溃馈亏盔岿窥葵魁傀愧馗匮夔隗蒉揆喹喟悝愦逵暌睽聩蝰篑跬", "kun :困昆坤捆悃阃琨锟醌鲲髡", "kuo :扩括阔廓蛞", "la :拉啦蜡腊蓝垃喇辣剌邋旯砬瘌", "lai :来赖莱崃徕涞濑赉睐铼癞籁", "lan :兰烂蓝览栏婪拦篮阑澜谰揽懒缆滥岚漤榄斓罱镧褴", "lang :浪朗郎狼琅榔廊莨蒗啷阆锒稂螂", "lao :老劳牢涝捞佬姥酪烙唠崂栳铑铹痨耢醪", "le :了乐勒肋仂叻泐鳓", "lei :类雷累垒泪镭蕾磊儡擂肋羸诔嘞嫘缧檑耒酹", "leng :冷棱楞塄愣", "li :理里利力立离例历粒厘礼李隶黎璃励犁梨丽厉篱狸漓鲤莉荔吏栗砾傈俐痢沥哩俪俚郦坜苈莅蓠藜呖唳喱猁溧澧逦娌嫠骊缡枥栎轹戾砺詈罹锂鹂疠疬蛎蜊蠡笠篥粝醴跞雳鲡鳢黧", "lia :俩", "lian :连联练炼脸链莲镰廉怜涟帘敛恋蔹奁潋濂琏楝殓臁裢裣蠊鲢", "liang :量两粮良亮梁凉辆粱晾谅墚椋踉靓魉", "liao :料疗辽僚撩聊燎寥潦撂镣廖蓼尥嘹獠寮缭钌鹩", "lie :列裂烈劣猎冽埒捩咧洌趔躐鬣", "lin :林磷临邻淋麟琳霖鳞凛赁吝蔺啉嶙廪懔遴檩辚膦瞵粼躏", "ling :领另零令灵岭铃龄凌陵拎玲菱伶羚酃苓呤囹泠绫柃棂瓴聆蛉翎鲮", "liu :流六留刘硫柳馏瘤溜琉榴浏遛骝绺旒熘锍镏鹨鎏", "long :龙垄笼隆聋咙窿拢陇垅茏泷珑栊胧砻癃", "lou :漏楼娄搂篓陋偻蒌喽嵝镂瘘耧蝼髅", "lu :路率露绿炉律虑滤陆氯鲁铝录旅卢吕芦颅庐掳卤虏麓碌赂鹿潞禄戮驴侣履屡缕垆撸噜闾泸渌漉逯璐栌榈橹轳辂辘氇胪膂镥稆鸬鹭褛簏舻鲈", "luan :卵乱峦挛孪滦脔娈栾鸾銮", "lue :略掠锊", "lun :论轮伦抡仑沦纶囵", "luo :落罗螺洛络逻萝锣箩骡裸骆倮蠃荦捋摞猡泺漯珞椤脶镙瘰雒", "m :呒", "ma :马麻吗妈骂嘛码玛蚂唛犸嬷杩蟆", "mai :麦脉卖买埋迈劢荬霾", "man :满慢曼漫蔓瞒馒蛮谩墁幔缦熳镘颟螨鳗鞔", "mang :忙芒盲茫氓莽邙漭硭蟒", "mao :毛矛冒貌贸帽猫茅锚铆卯茂袤茆峁泖瑁昴牦耄旄懋瞀蟊髦", "me :么麽", "mei :没每美煤霉酶梅妹眉玫枚媒镁昧寐媚莓嵋猸浼湄楣镅鹛袂魅", "men :们门闷扪焖懑钔", "meng :孟猛蒙盟梦萌锰檬勐甍瞢懵朦礞虻蜢蠓艋艨", "mi :米密迷蜜秘眯醚靡糜谜弥觅泌幂芈谧蘼咪嘧猕汨宓弭脒祢敉糸縻麋", "mian :面棉免绵眠冕勉娩缅沔渑湎腼眄", "miao :苗秒描庙妙瞄藐渺喵邈缈缪杪淼眇鹋", "mie :灭蔑咩蠛篾", "min :民敏抿皿悯闽苠岷闵泯缗玟珉愍黾鳘", "ming :命明名鸣螟铭冥茗溟暝瞑酩", "miu :谬", "mo :磨末模膜摸墨摩莫抹默摹蘑魔沫漠寞陌谟茉蓦馍嫫殁镆秣瘼耱貊貘", "mou :某谋牟侔哞眸蛑蝥鍪", "mu :亩目木母墓幕牧姆穆拇牡暮募慕睦仫坶苜沐毪钼", "n :嗯", "na :那南哪拿纳钠呐娜捺肭镎衲", "nai :耐奶乃氖奈鼐艿萘柰", "nan :南难男喃囝囡楠腩蝻赧", "nang :囊攮囔馕曩", "nao :脑闹挠恼淖孬垴呶猱瑙硇铙蛲", "ne :呢讷", "nei :内馁", "nen :嫩恁", "neng :能", "ni :你泥尼逆拟尿妮霓倪匿腻溺伲坭猊怩昵旎慝睨铌鲵", "nian :年念粘蔫拈碾撵捻酿廿埝辇黏鲇鲶", "niang :娘", "niao :尿鸟茑嬲脲袅", "nie :镍啮涅捏聂孽镊乜陧蘖嗫颞臬蹑", "nin :您", "ning :宁凝拧柠狞泞佞苎咛甯聍", "niu :牛扭钮纽狃忸妞", "nong :农弄浓脓侬哝", "nou :耨", "nu :女奴努怒弩胬孥驽恧钕衄", "nuan :暖", "nue :虐", "nuo :诺挪懦糯傩搦喏锘", "o :欧偶哦鸥殴藕呕沤讴噢怄瓯耦", "ou :欧偶鸥殴藕呕沤讴怄瓯耦", "pa :怕派爬帕啪趴琶葩杷筢", "pai :派排拍牌哌徘湃俳蒎", "pan :判盘叛潘攀磐盼畔胖爿泮袢襻蟠蹒", "pang :旁乓庞耪胖彷滂逄螃", "pao :跑炮刨抛泡咆袍匏狍庖脬疱", "pei :配培陪胚呸裴赔佩沛辔帔旆锫醅霈", "pen :喷盆湓", "peng :碰棚蓬朋捧膨砰抨烹澎彭硼篷鹏堋嘭怦蟛", "pi :批皮坯脾疲砒霹披劈琵毗啤匹痞僻屁譬丕仳陴邳郫圮鼙芘擗噼庀淠媲纰枇甓睥罴铍癖疋蚍蜱貔", "pian :片偏篇骗谝骈犏胼翩蹁", "piao :票漂飘瓢剽嘌嫖缥殍瞟螵", "pie :撇瞥丿苤氕", "pin :品贫频拼苹聘拚姘嫔榀牝颦", "ping :平评瓶凭苹乒坪萍屏俜娉枰鲆", "po :破迫坡泼颇婆魄粕叵鄱珀攴钋钷皤笸", "pou :剖裒掊", "pu :普谱扑埔铺葡朴蒲仆莆菩圃浦曝瀑匍噗溥濮璞氆镤镨蹼", "qi :起其气期七器齐奇汽企漆欺旗畦启弃歧栖戚妻凄柒沏棋崎脐祈祁骑岂乞契砌迄泣讫亓俟圻芑芪萁萋葺蕲嘁屺岐汔淇骐绮琪琦杞桤槭耆欹祺憩碛颀蛴蜞綦綮蹊鳍麒", "qia :恰掐洽葜髂", "qian :前千钱浅签迁铅潜牵钳谴扦钎仟谦乾黔遣堑嵌欠歉倩佥阡芊芡茜荨掮岍悭慊骞搴褰缱椠肷愆钤虔箬箝", "qiang :强枪抢墙腔呛羌蔷戕嫱樯戗炝锖锵镪襁蜣羟跄", "qiao :桥瞧巧敲乔蕉橇锹悄侨鞘撬翘峭俏窍劁诮谯荞愀憔樵硗跷鞒", "qie :切且茄怯窃郄惬妾挈锲箧", "qin :亲侵勤秦钦琴芹擒禽寝沁芩揿吣嗪噙溱檎锓覃螓衾", "qing :情清青轻倾请庆氢晴卿擎氰顷苘圊檠磬蜻罄箐謦鲭黥", "qiong :穷琼邛茕穹蛩筇跫銎", "qiu :求球秋丘邱囚酋泅俅巯犰湫逑遒楸赇虬蚯蝤裘糗鳅鼽", "qu :去区取曲渠屈趋驱趣蛆躯娶龋诎劬蕖蘧岖衢阒璩觑氍朐祛磲鸲癯蛐蠼麴瞿黢", "quan :全权圈劝泉醛颧痊拳犬券诠荃悛绻辁畎铨蜷筌鬈", "que :确却缺炔瘸鹊榷雀阕阙悫", "qun :群裙逡", "ran :然燃染冉苒蚺髯", "rang :让壤嚷瓤攘禳穰", "rao :绕扰饶荛娆桡", "re :热惹", "ren :人认任仁刃忍壬韧妊纫仞荏葚饪轫稔衽", "reng :仍扔", "ri :日", "rong :容溶荣熔融绒戎茸蓉冗嵘狨榕肜蝾", "rou :肉揉柔糅蹂鞣", "ru :如入儒乳茹蠕孺辱汝褥蓐薷嚅洳溽濡缛铷襦颥", "ruan :软阮朊", "rui :瑞锐蕊芮蕤枘睿蚋", "run :润闰", "ruo :弱若偌", "sa :撒萨洒卅仨挲脎飒", "sai :塞赛腮鳃噻", "san :三散叁伞馓毵糁", "sang :桑丧嗓搡磉颡", "sao :扫搔骚嫂埽缫缲臊瘙鳋", "se :色瑟涩啬铯穑", "sen :森", "seng :僧", "sha :沙杀砂啥纱莎刹傻煞杉唼歃铩痧裟霎鲨", "shai :筛晒", "shan :山闪善珊扇陕苫杉删煽衫擅赡膳汕缮剡讪鄯埏芟潸姗嬗骟膻钐疝蟮舢跚鳝", "shang :上商伤尚墒赏晌裳垧绱殇熵觞", "shao :少烧稍绍哨梢捎芍勺韶邵劭苕潲蛸筲艄", "she :社设射摄舌涉舍蛇奢赊赦慑厍佘猞滠歙畲麝", "shen :深身神伸甚渗沈肾审申慎砷呻娠绅婶诜谂莘哂渖椹胂矧蜃", "sheng :生胜声省升盛绳剩圣牲甥嵊晟眚笙", "shi :是时十使事实式识世试石什示市史师始施士势湿适食失视室氏蚀诗释拾饰驶狮尸虱矢屎柿拭誓逝嗜噬仕侍恃谥埘莳蓍弑轼贳炻铈螫舐筮酾豕鲥鲺", "shou :手受收首守授寿兽售瘦狩绶艏", "shu :数书树属术输述熟束鼠疏殊舒蔬薯叔署枢梳抒淑赎孰暑曙蜀黍戍竖墅庶漱恕丨倏塾菽摅沭澍姝纾毹腧殳秫", "shua :刷耍唰", "shuai :衰帅摔甩蟀", "shuan :栓拴闩涮", "shuang:双霜爽孀", "shui :水谁睡税", "shun :顺吮瞬舜", "shuo :说硕朔烁蒴搠妁槊铄", "si :四思死斯丝似司饲私撕嘶肆寺嗣伺巳厮兕厶咝汜泗澌姒驷缌祀锶鸶耜蛳笥", "song :松送宋颂耸怂讼诵凇菘崧嵩忪悚淞竦", "sou :搜艘擞嗽叟薮嗖嗾馊溲飕瞍锼螋", "su :素速苏塑缩俗诉宿肃酥粟僳溯夙谡蔌嗉愫涑簌觫稣", "suan :算酸蒜狻", "sui :随穗碎虽岁隋绥髓遂隧祟谇荽濉邃燧眭睢", "sun :损孙笋荪狲飧榫隼", "suo :所缩锁索蓑梭唆琐唢嗦嗍娑桫睃羧", "ta :他它她塔踏塌獭挞蹋闼溻遢榻沓铊趿鳎", "tai :台太态胎抬泰苔酞汰邰薹肽炱钛跆鲐", "tan :谈碳探炭坦贪滩坍摊瘫坛檀痰潭谭毯袒叹郯澹昙忐钽锬", "tang :堂糖唐塘汤搪棠膛倘躺淌趟烫傥帑溏瑭樘铴镗耥螗螳羰醣", "tao :套讨逃陶萄桃掏涛滔绦淘鼗啕洮韬焘饕", "te :特忒忑铽", "teng :腾疼藤誊滕", "ti :提题体替梯惕剔踢锑蹄啼嚏涕剃屉倜悌逖缇鹈裼醍", "tian :天田添填甜恬舔腆掭忝阗殄畋", "tiao :条跳挑迢眺佻祧窕蜩笤粜龆鲦髫", "tie :铁贴帖萜餮", "ting :听停庭挺廷厅烃汀亭艇莛葶婷梃铤蜓霆", "tong :同通统铜痛筒童桶桐酮瞳彤捅佟仝茼嗵恸潼砼", "tou :头投透偷钭骰", "tu :图土突途徒凸涂吐兔屠秃堍荼菟钍酴", "tuan :团湍抟彖疃", "tui :推退腿颓蜕褪煺", "tun :吞屯臀氽饨暾豚", "tuo :脱拖托妥椭鸵陀驮驼拓唾乇佗坨庹沱柝橐砣箨酡跎鼍", "wa :瓦挖哇蛙洼娃袜佤娲腽", "wai :外歪", "wan :完万晚弯碗顽湾挽玩豌丸烷皖惋宛婉腕剜芄菀纨绾琬脘畹蜿", "wang :往王望网忘妄亡旺汪枉罔尢惘辋魍", "wei :为位委围维唯卫微伟未威危尾谓喂味胃魏伪违韦畏纬巍桅惟潍苇萎蔚渭尉慰偎诿隈葳薇囗帏帷崴嵬猥猬闱沩洧涠逶娓玮韪軎炜煨痿艉鲔", "wen :问温文稳纹闻蚊瘟吻紊刎阌汶璺雯", "weng :嗡翁瓮蓊蕹", "wo :我握窝蜗涡沃挝卧斡倭莴喔幄渥肟硪龌", "wu :无五物武务误伍舞污悟雾午屋乌吴诬钨巫呜芜梧吾毋捂侮坞戊晤勿兀仵阢邬圬芴唔庑怃忤浯寤迕妩婺骛杌牾焐鹉鹜痦蜈鋈鼯", "xi :系席西习细吸析喜洗铣稀戏隙希息袭锡烯牺悉惜溪昔熙硒矽晰嘻膝夕熄汐犀檄媳僖兮隰郗菥葸蓰奚唏徙饩阋浠淅屣嬉玺樨曦觋欷熹禊禧皙穸蜥螅蟋舄舾羲粞翕醯鼷", "xia :下夏吓狭霞瞎虾匣辖暇峡侠厦呷狎遐瑕柙硖罅黠", "xian :线现先县限显鲜献险陷宪纤掀弦腺锨仙咸贤衔舷闲涎嫌馅羡冼苋莶藓岘猃暹娴氙燹祆鹇痫蚬筅籼酰跣跹霰", "xiang :想向相象响项箱乡香像详橡享湘厢镶襄翔祥巷芗葙饷庠骧缃蟓鲞飨", "xiao :小消削效笑校销硝萧肖孝霄哮嚣宵淆晓啸哓崤潇逍骁绡枭枵筱箫魈", "xie :些写斜谢协械卸屑鞋歇邪胁蟹泄泻楔蝎挟携谐懈偕亵勰燮薤撷獬廨渫瀣邂绁缬榭榍躞", "xin :新心信锌芯辛欣薪忻衅囟馨昕歆鑫", "xing :行性形型星兴醒姓幸腥猩惺刑邢杏陉荇荥擤饧悻硎", "xiong :雄胸兄凶熊匈汹芎", "xiu :修锈休袖秀朽羞嗅绣咻岫馐庥溴鸺貅髹", "xu :续许须需序虚絮畜叙蓄绪徐墟戌嘘酗旭恤婿诩勖圩蓿洫溆顼栩煦盱胥糈醑", "xuan :选旋宣悬玄轩喧癣眩绚儇谖萱揎泫渲漩璇楦暄炫煊碹铉镟痃", "xue :学血雪穴靴薛谑泶踅鳕", "xun :训旬迅讯寻循巡勋熏询驯殉汛逊巽埙荀蕈薰峋徇獯恂洵浔曛醺鲟", "ya :压亚呀牙芽雅蚜鸭押鸦丫崖衙涯哑讶伢垭揠岈迓娅琊桠氩砑睚痖", "yan :验研严眼言盐演岩沿烟延掩宴炎颜燕衍焉咽阉淹蜒阎奄艳堰厌砚雁唁彦焰谚厣赝俨偃兖谳郾鄢菸崦恹闫阏湮滟妍嫣琰檐晏胭焱罨筵酽魇餍鼹", "yang :样养氧扬洋阳羊秧央杨仰殃鸯佯疡痒漾徉怏泱炀烊恙蛘鞅", "yao :要药摇腰咬邀耀疟妖瑶尧遥窑谣姚舀夭爻吆崾徭幺珧杳轺曜肴鹞窈繇鳐", "ye :也业页叶液夜野爷冶椰噎耶掖曳腋靥谒邺揶晔烨铘", "yi :一以义意已移医议依易乙艺益异宜仪亿遗伊役衣疑亦谊翼译抑忆疫壹揖铱颐夷胰沂姨彝椅蚁倚矣邑屹臆逸肄裔毅溢诣翌绎刈劓佚佾诒圯埸懿苡荑薏弈奕挹弋呓咦咿噫峄嶷猗饴怿怡悒漪迤驿缢殪轶贻旖熠眙钇镒镱痍瘗癔翊蜴舣羿翳酏黟", "yin :因引阴印音银隐饮荫茵殷姻吟淫寅尹胤鄞垠堙茚吲喑狺夤洇氤铟瘾窨蚓霪龈", "ying :应影硬营英映迎樱婴鹰缨莹萤荧蝇赢盈颖嬴郢茔莺萦蓥撄嘤膺滢潆瀛瑛璎楹媵鹦瘿颍罂", "yo :哟唷", "yong :用勇永拥涌蛹庸佣臃痈雍踊咏泳恿俑壅墉喁慵邕镛甬鳙饔", "you :有由又油右友优幼游尤诱犹幽悠忧邮铀酉佑釉卣攸侑莠莜莸呦囿宥柚猷牖铕疣蚰蚴蝣鱿黝鼬", "yu :于与育鱼雨玉余遇预域语愈渔予羽愚御欲宇迂淤盂榆虞舆俞逾愉渝隅娱屿禹芋郁吁喻峪狱誉浴寓裕豫驭禺毓伛俣谀谕萸蓣揄圄圉嵛狳饫馀庾阈鬻妪妤纡瑜昱觎腴欤於煜熨燠聿钰鹆鹬瘐瘀窬窳蜮蝓竽臾舁雩龉", "yuan :员原圆源元远愿院缘援园怨鸳渊冤垣袁辕猿苑垸塬芫掾沅媛瑗橼爰眢鸢螈箢鼋", "yue :月越约跃曰阅钥岳粤悦龠瀹樾刖钺", "yun :运云匀允孕耘郧陨蕴酝晕韵郓芸狁恽愠纭韫殒昀氲熨", "za :杂咱匝砸咋咂", "zai :在再载栽灾哉宰崽甾", "zan :赞咱暂攒拶瓒昝簪糌趱錾", "zang :脏葬赃奘驵臧", "zao :造早遭燥凿糟枣皂藻澡蚤躁噪灶唣", "ze :则择责泽仄赜啧帻迮昃笮箦舴", "zei :贼", "zen :怎谮", "zeng :增曾憎赠缯甑罾锃", "zha :扎炸闸铡轧渣喳札眨栅榨乍诈揸吒咤哳砟痄蚱齄", "zhai :寨摘窄斋宅债砦瘵", "zhan :战展站占瞻毡詹沾盏斩辗崭蘸栈湛绽谵搌旃", "zhang :张章掌仗障胀涨账樟彰漳杖丈帐瘴仉鄣幛嶂獐嫜璋蟑", "zhao :照找招召赵爪罩沼兆昭肇诏棹钊笊", "zhe :这着者折哲浙遮蛰辙锗蔗谪摺柘辄磔鹧褶蜇赭", "zhen :真针阵镇振震珍诊斟甄砧臻贞侦枕疹圳蓁浈缜桢榛轸赈胗朕祯畛稹鸩箴", "zheng :争正政整证征蒸症郑挣睁狰怔拯帧诤峥徵钲铮筝", "zhi :之制治只质指直支织止至置志值知执职植纸致枝殖脂智肢秩址滞汁芝吱蜘侄趾旨挚掷帜峙稚炙痔窒卮陟郅埴芷摭帙忮彘咫骘栉枳栀桎轵轾贽胝膣祉祗黹雉鸷痣蛭絷酯跖踬踯豸觯", "zhong :中种重众钟终忠肿仲盅衷冢锺螽舯踵", "zhou :轴周洲州皱骤舟诌粥肘帚咒宙昼荮啁妯纣绉胄碡籀酎", "zhu :主注著住助猪铸株筑柱驻逐祝竹贮珠朱诸蛛诛烛煮拄瞩嘱蛀伫侏邾茱洙渚潴杼槠橥炷铢疰瘃竺箸舳翥躅麈", "zhua :抓", "zhuai :拽", "zhuan :转专砖撰赚篆啭馔颛", "zhuang:装状壮庄撞桩妆僮", "zhui :追锥椎赘坠缀惴骓缒", "zhun :准谆肫窀", "zhuo :捉桌拙卓琢茁酌啄灼浊倬诼擢浞涿濯焯禚斫镯", "zi :子自资字紫仔籽姿兹咨滋淄孜滓渍谘嵫姊孳缁梓辎赀恣眦锱秭耔笫粢趑觜訾龇鲻髭", "zong :总纵宗综棕鬃踪偬枞腙粽", "zou :走邹奏揍诹陬鄹驺鲰", "zu :组族足阻祖租卒诅俎菹镞", "zuan :钻纂攥缵躜", "zui :最罪嘴醉蕞", "zun :尊遵撙樽鳟", "zuo :作做左座坐昨佐柞阼唑嘬怍胙祚"}; } }
2881099/dotnetGen_postgresql
12,117
GenPg/plist-cil/NSSet.cs
// plist-cil - An open source library to parse and generate property lists for .NET // Copyright (C) 2015 Natalia Portillo // // This code is based on: // plist - An open source library to parse and generate property lists // Copyright (C) 2014 Daniel Dreibrodt // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. using System; using System.Collections.Generic; using System.Collections; using System.Text; namespace PList { /// <summary> /// <para> /// A set is an interface to an unordered collection of objects. /// </para><para> /// This implementation uses a <see cref="List{NSObject}"/>as the underlying /// data structure. /// </para> /// </summary> /// @author Daniel Dreibrodt /// @author Natalia Portillo public class NSSet : NSObject, IEnumerable { readonly List<NSObject> set; bool ordered; /// <summary> /// Creates an empty unordered set. /// </summary> public NSSet() { set = new List<NSObject>(); } /// <summary> /// Creates an empty set. /// </summary> /// <param name="ordered">Should the set be ordered on operations?</param> public NSSet(bool ordered) { this.ordered = ordered; set = new List<NSObject>(); } /// <summary> /// Creates a set and fill it with the given objects. /// </summary> /// <param name="objects">The objects to populate the set.</param> public NSSet(params NSObject[] objects) { set = new List<NSObject>(objects); } /// <summary> /// Creates a set and fill it with the given objects. /// </summary> /// <param name="objects">The objects to populate the set.</param> /// <param name="ordered">Should the set be ordered on operations?</param> public NSSet(bool ordered, params NSObject[] objects) { this.ordered = ordered; set = new List<NSObject>(objects); if (ordered) set.Sort(); } /// <summary> /// Adds an object to the set. /// </summary> /// <param name="obj">The object to add.</param> public void AddObject(NSObject obj) { lock (set) { set.Add(obj); if (ordered) set.Sort(); } } /// <summary> /// Removes an object from the set. /// </summary> /// <param name="obj">The object to remove.</param> public void RemoveObject(NSObject obj) { lock (set) { set.Remove(obj); if (ordered) set.Sort(); } } /// <summary> /// Returns all objects contained in the set. /// </summary> /// <returns>An array of all objects in the set.</returns> public NSObject[] AllObjects() { lock (set) { return set.ToArray(); } } /// <summary> /// Returns one of the objects in the set, or <c>null</c> /// if the set contains no objects. /// </summary> /// <returns>The first object in the set, or <c>null</c> if the set is empty.</returns> public NSObject AnyObject() { lock (set) { return set.Count == 0 ? null : set[0]; } } /// <summary> /// Finds out whether a given object is contained in the set. /// </summary> /// <returns><c>true</c>, when the object was found, <c>false</c> otherwise.</returns> /// <param name="obj">The object to look for.</param> public bool ContainsObject(NSObject obj) { return set.Contains(obj); } /// <summary> /// Determines whether the set contains an object equal to a given object /// and returns that object if it is present. /// </summary> /// <param name="obj">The object to look for.</param> /// <returns>The object if it is present, <c>null</c> otherwise.</returns> public NSObject Member(NSObject obj) { lock (set) { foreach (NSObject o in set) { if (o.Equals(obj)) return o; } return null; } } /// <summary> /// Finds out whether at least one object is present in both sets. /// </summary> /// <returns><c>true</c> if the intersection of both sets is empty, <c>false</c> otherwise.</returns> /// <param name="otherSet">The other set.</param> public bool IntersectsSet(NSSet otherSet) { lock (set) { foreach (NSObject o in set) { if (otherSet.ContainsObject(o)) return true; } return false; } } /// <summary> /// Finds out if this set is a subset of the given set. /// </summary> /// <returns><c>true</c> if all elements in this set are also present in the other set, <c>false</c>otherwise.</returns> /// <param name="otherSet">The other set.</param> public bool IsSubsetOfSet(NSSet otherSet) { lock (set) { foreach (NSObject o in set) { if (!otherSet.ContainsObject(o)) return false; } return true; } } /// <summary> /// Returns an enumerator object that lets you iterate over all elements of the set. /// This is the equivalent to <c>objectEnumerator</c> in the Cocoa implementation /// of NSSet. /// </summary> /// <returns>The iterator for the set.</returns> public IEnumerator GetEnumerator() { lock (set) { return set.GetEnumerator(); } } /// <summary> /// Gets the underlying data structure in which this NSSets stores its content. /// </summary> /// <returns>A Set object.</returns> internal List<NSObject> GetSet() { return set; } /// <summary> /// Serves as a hash function for a <see cref="PList.NSSet"/> object. /// </summary> /// <returns>A hash code for this instance that is suitable for use in hashing algorithms and data structures such as a /// hash table.</returns> public override int GetHashCode() { int hash = 7; hash = 29 * hash + (set != null ? set.GetHashCode() : 0); return hash; } /// <summary> /// Determines whether the specified <see cref="System.Object"/> is equal to the current <see cref="PList.NSSet"/>. /// </summary> /// <param name="obj">The <see cref="System.Object"/> to compare with the current <see cref="PList.NSSet"/>.</param> /// <returns><c>true</c> if the specified <see cref="System.Object"/> is equal to the current /// <see cref="PList.NSSet"/>; otherwise, <c>false</c>.</returns> public override bool Equals(Object obj) { if (obj == null) { return false; } if (GetType() != obj.GetType()) { return false; } NSSet other = (NSSet)obj; return !(set != other.set && (set == null || !set.Equals(other.set))); } /// <summary> /// Gets the number of elements in the set. /// </summary> /// <value>The number of elements in the set.</value> public int Count { get { lock (set) { return set.Count; } } } /// <summary> /// Returns the XML representantion for this set. /// There is no official XML representation specified for sets. /// In this implementation it is represented by an array. /// </summary> /// <param name="xml">The XML StringBuilder</param> /// <param name="level">The indentation level</param> internal override void ToXml(StringBuilder xml, int level) { Indent(xml, level); xml.Append("<array>"); xml.Append(NSObject.NEWLINE); if (ordered) set.Sort(); foreach (NSObject o in set) { o.ToXml(xml, level + 1); xml.Append(NSObject.NEWLINE); } Indent(xml, level); xml.Append("</array>"); } internal override void AssignIDs(BinaryPropertyListWriter outPlist) { base.AssignIDs(outPlist); foreach (NSObject obj in set) { obj.AssignIDs(outPlist); } } internal override void ToBinary(BinaryPropertyListWriter outPlist) { if (ordered) { set.Sort(); outPlist.WriteIntHeader(0xB, set.Count); } else { outPlist.WriteIntHeader(0xC, set.Count); } foreach (NSObject obj in set) { outPlist.WriteID(outPlist.GetID(obj)); } } /// <summary> /// Returns the ASCII representation of this set. /// There is no official ASCII representation for sets. /// In this implementation sets are represented as arrays. /// </summary> /// <param name="ascii">The ASCII file string builder</param> /// <param name="level">The indentation level</param> internal override void ToASCII(StringBuilder ascii, int level) { Indent(ascii, level); if (ordered) set.Sort(); NSObject[] array = AllObjects(); ascii.Append(ASCIIPropertyListParser.ARRAY_BEGIN_TOKEN); int indexOfLastNewLine = ascii.ToString().LastIndexOf(NEWLINE, StringComparison.Ordinal); for (int i = 0; i < array.Length; i++) { Type objClass = array[i].GetType(); if ((objClass.Equals(typeof(NSDictionary)) || objClass.Equals(typeof(NSArray)) || objClass.Equals(typeof(NSData))) && indexOfLastNewLine != ascii.Length) { ascii.Append(NEWLINE); indexOfLastNewLine = ascii.Length; array[i].ToASCII(ascii, level + 1); } else { if (i != 0) ascii.Append(" "); array[i].ToASCII(ascii, 0); } if (i != array.Length - 1) ascii.Append(ASCIIPropertyListParser.ARRAY_ITEM_DELIMITER_TOKEN); if (ascii.Length - indexOfLastNewLine > ASCII_LINE_LENGTH) { ascii.Append(NEWLINE); indexOfLastNewLine = ascii.Length; } } ascii.Append(ASCIIPropertyListParser.ARRAY_END_TOKEN); } /// <summary> /// Returns the ASCII representation of this set according to the GnuStep format. /// There is no official ASCII representation for sets. /// In this implementation sets are represented as arrays. /// </summary> /// <param name="ascii">The ASCII file string builder</param> /// <param name="level">The indentation level</param> internal override void ToASCIIGnuStep(StringBuilder ascii, int level) { Indent(ascii, level); if (ordered) set.Sort(); NSObject[] array = AllObjects(); ascii.Append(ASCIIPropertyListParser.ARRAY_BEGIN_TOKEN); int indexOfLastNewLine = ascii.ToString().LastIndexOf(NEWLINE, StringComparison.Ordinal); for (int i = 0; i < array.Length; i++) { Type objClass = array[i].GetType(); if ((objClass.Equals(typeof(NSDictionary)) || objClass.Equals(typeof(NSArray)) || objClass.Equals(typeof(NSData))) && indexOfLastNewLine != ascii.Length) { ascii.Append(NEWLINE); indexOfLastNewLine = ascii.Length; array[i].ToASCIIGnuStep(ascii, level + 1); } else { if (i != 0) ascii.Append(" "); array[i].ToASCIIGnuStep(ascii, 0); } if (i != array.Length - 1) ascii.Append(ASCIIPropertyListParser.ARRAY_ITEM_DELIMITER_TOKEN); if (ascii.Length - indexOfLastNewLine > ASCII_LINE_LENGTH) { ascii.Append(NEWLINE); indexOfLastNewLine = ascii.Length; } } ascii.Append(ASCIIPropertyListParser.ARRAY_END_TOKEN); } /// <summary> /// Determines whether the specified <see cref="PList.NSObject"/> is equal to the current <see cref="PList.NSSet"/>. /// </summary> /// <param name="obj">The <see cref="PList.NSObject"/> to compare with the current <see cref="PList.NSSet"/>.</param> /// <returns><c>true</c> if the specified <see cref="PList.NSObject"/> is equal to the current /// <see cref="PList.NSSet"/>; otherwise, <c>false</c>.</returns> public override bool Equals(NSObject obj) { if (!(obj is NSSet)) return false; if (set.Count != ((NSSet)obj).Count) return false; foreach (NSObject objS in (NSSet)obj) if (!set.Contains(objS)) return false; return true; } } }
2881099/dotnetGen_postgresql
14,727
GenPg/plist-cil/NSNumber.cs
// plist-cil - An open source library to parse and generate property lists for .NET // Copyright (C) 2015 Natalia Portillo // // This code is based on: // plist - An open source library to parse and generate property lists // Copyright (C) 2014 Daniel Dreibrodt // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. using System; using System.Text; using System.Globalization; namespace PList { /// <summary> /// A number whose value is either an integer, a real number or bool. /// </summary> /// @author Daniel Dreibrodt /// @author Natalia Portillo public class NSNumber : NSObject, IComparable { /// <summary> /// Indicates that the number's value is an integer. /// The number is stored as a .NET <see cref="long"/>. /// Its original value could have been char, short, int, long or even long long. /// </summary> public const int INTEGER = 0; /// <summary> /// Indicates that the number's value is a real number. /// The number is stored as a .NET <see cref="double"/>. /// Its original value could have been float or double. /// </summary> public const int REAL = 1; /// <summary> /// Indicates that the number's value is bool. /// </summary> public const int BOOLEAN = 2; //Holds the current type of this number readonly int type; readonly long longValue; readonly double doubleValue; readonly bool boolValue; /// <summary> /// Parses integers and real numbers from their binary representation. /// <i>Note: real numbers are not yet supported.</i> /// </summary> /// <param name="bytes">The binary representation</param> /// <param name="type">The type of number</param> /// <seealso cref="INTEGER"/> /// <seealso cref="REAL"/> public NSNumber(byte[] bytes, int type) { switch (type) { case INTEGER: doubleValue = longValue = BinaryPropertyListParser.ParseLong(bytes); break; case REAL: doubleValue = BinaryPropertyListParser.ParseDouble(bytes); longValue = (long)Math.Round(doubleValue); break; default: throw new ArgumentException("Type argument is not valid."); } this.type = type; } public NSNumber(string text, int type) { switch (type) { case INTEGER: { doubleValue = longValue = long.Parse(text, CultureInfo.InvariantCulture); break; } case REAL: { doubleValue = double.Parse(text, CultureInfo.InvariantCulture); longValue = (long)Math.Round(doubleValue); break; } default: { throw new ArgumentException("Type argument is not valid."); } } this.type = type; } /// <summary> /// Creates a number from its textual representation. /// </summary> /// <param name="text">The textual representation of the number.</param> /// <seealso cref="bool.Parse(string)"/> /// <seealso cref="long.Parse(string)"/> /// <seealso cref="double.Parse(string, IFormatProvider)"/> public NSNumber(string text) { if (text == null) throw new ArgumentException("The given string is null and cannot be parsed as number."); long l; double d; if (long.TryParse(text, NumberStyles.Number, CultureInfo.InvariantCulture, out l)) { doubleValue = longValue = l; type = INTEGER; } else if (double.TryParse(text, NumberStyles.Number, CultureInfo.InvariantCulture, out d)) { doubleValue = d; longValue = (long)Math.Round(doubleValue); type = REAL; } else { bool isTrue = string.Equals(text, "true", StringComparison.CurrentCultureIgnoreCase) || string.Equals(text, "yes", StringComparison.CurrentCultureIgnoreCase); bool isFalse = string.Equals(text, "false", StringComparison.CurrentCultureIgnoreCase) || string.Equals(text, "no", StringComparison.CurrentCultureIgnoreCase); if (isTrue || isFalse) { type = BOOLEAN; doubleValue = longValue = boolValue ? 1 : 0; } else { throw new ArgumentException("The given string neither represents a double, an int nor a bool value."); } } } /// <summary> /// Creates an integer number. /// </summary> /// <param name="i">The integer value.</param> public NSNumber(int i) { doubleValue = longValue = i; type = INTEGER; } /// <summary> /// Creates an integer number. /// </summary> /// <param name="l">The long integer value.</param> public NSNumber(long l) { doubleValue = longValue = l; type = INTEGER; } /// <summary> /// Creates a real number. /// </summary> /// <param name="d">The real value.</param> public NSNumber(double d) { longValue = (long)(doubleValue = d); type = REAL; } /// <summary> /// Creates a bool number. /// </summary> /// <param name="b">The bool value.</param> public NSNumber(bool b) { boolValue = b; doubleValue = longValue = b ? 1 : 0; type = BOOLEAN; } /// <summary> /// Gets the type of this number's value. /// </summary> /// <returns>The type flag.</returns> /// <seealso cref="BOOLEAN"/> /// <seealso cref="INTEGER"/> /// <seealso cref="REAL"/> public int GetNSNumberType() { return type; } /// <summary> /// Checks whether the value of this NSNumber is a bool. /// </summary> /// <returns>Whether the number's value is a bool.</returns> public bool isBoolean() { return type == BOOLEAN; } /// <summary> /// Checks whether the value of this NSNumber is an integer. /// </summary> /// <returns>Whether the number's value is an integer.</returns> public bool isInteger() { return type == INTEGER; } /// <summary> /// Checks whether the value of this NSNumber is a real number. /// </summary> /// <returns>Whether the number's value is a real number.</returns> public bool isReal() { return type == REAL; } /// <summary> /// The number's bool value. /// </summary> /// <returns><c>true</c> if the value is true or non-zero, <c>false</c> otherwise.</returns> public bool ToBool() { if (type == BOOLEAN) return boolValue; return longValue != 0; } /// <summary> /// The number's long value. /// </summary> /// <returns>The value of the number as long</returns> public long ToLong() { return longValue; } /// <summary> /// The number's int value. /// <i>Note: Even though the number's type might be INTEGER it can be larger than a Java int. /// Use intValue() only if you are certain that it contains a number from the int range. /// Otherwise the value might be innaccurate.</i> /// </summary> /// <returns>The value of the number as int.</returns> public int ToInt() { return (int)longValue; } /// <summary> /// The number's double value. /// </summary> /// <returns>The value of the number as double.</returns> public double ToDouble() { return doubleValue; } /// <summary> /// The number's float value. /// WARNING: Possible loss of precision if the value is outside the float range. /// </summary> /// <returns>The value of the number as float.</returns> public float floatValue() { return (float)doubleValue; } /// <summary> /// Checks whether the other object is a NSNumber of the same value. /// </summary> /// <param name="obj">The object to compare to.</param> /// <returns>Whether the objects are equal in terms of numeric value and type.</returns> public override bool Equals(Object obj) { if (!(obj is NSNumber)) return false; NSNumber n = (NSNumber)obj; return type == n.type && longValue == n.longValue && doubleValue == n.doubleValue && boolValue == n.boolValue; } /// <summary> /// Serves as a hash function for a <see cref="PList.NSNumber"/> object. /// </summary> /// <returns>A hash code for this instance that is suitable for use in hashing algorithms and data structures such as a /// hash table.</returns> public override int GetHashCode() { int hash = type; hash = 37 * hash + (int)(longValue ^ ((uint)longValue >> 32)); hash = 37 * hash + (int)(BitConverter.DoubleToInt64Bits(doubleValue) ^ ((uint)(BitConverter.DoubleToInt64Bits(doubleValue) >> 32))); hash = 37 * hash + (ToBool() ? 1 : 0); return hash; } /// <summary> /// Returns a <see cref="System.String"/> that represents the current <see cref="PList.NSNumber"/>. /// </summary> /// <returns>A <see cref="System.String"/> that represents the current <see cref="PList.NSNumber"/>.</returns> public override string ToString() { switch (type) { case INTEGER: { return ToLong().ToString(); } case REAL: { return ToDouble().ToString(CultureInfo.InvariantCulture); } case BOOLEAN: { return ToBool().ToString(); } default: { return base.ToString(); } } } internal override void ToXml(StringBuilder xml, int level) { Indent(xml, level); switch (type) { case INTEGER: { xml.Append("<integer>"); xml.Append(ToLong()); xml.Append("</integer>"); break; } case REAL: { xml.Append("<real>"); if (doubleValue == 0) { // 0 values appear to always roundtrip as 0.0, // but non-zero values do not include decimals if // not required (e.g. 10 -> "10") xml.Append("0.0"); } else { xml.Append(ToDouble().ToString(CultureInfo.InvariantCulture)); } xml.Append("</real>"); break; } case BOOLEAN: { if (ToBool()) xml.Append("<true/>"); else xml.Append("<false/>"); break; } } } internal override void ToBinary(BinaryPropertyListWriter outPlist) { switch (GetNSNumberType()) { case INTEGER: { if (ToLong() < 0) { outPlist.Write(0x13); outPlist.WriteBytes(ToLong(), 8); } else if (ToLong() <= 0xff) { outPlist.Write(0x10); outPlist.WriteBytes(ToLong(), 1); } else if (ToLong() <= 0xffff) { outPlist.Write(0x11); outPlist.WriteBytes(ToLong(), 2); } else if (ToLong() <= 0xffffffffL) { outPlist.Write(0x12); outPlist.WriteBytes(ToLong(), 4); } else { outPlist.Write(0x13); outPlist.WriteBytes(ToLong(), 8); } break; } case REAL: { outPlist.Write(0x23); outPlist.WriteDouble(ToDouble()); break; } case BOOLEAN: { outPlist.Write(ToBool() ? 0x09 : 0x08); break; } } } internal override void ToASCII(StringBuilder ascii, int level) { Indent(ascii, level); if (type == BOOLEAN) { ascii.Append(boolValue ? "YES" : "NO"); } else { ascii.Append(ToString()); } } internal override void ToASCIIGnuStep(StringBuilder ascii, int level) { Indent(ascii, level); switch (type) { case INTEGER: { ascii.Append("<*I"); ascii.Append(ToString()); ascii.Append(">"); break; } case REAL: { ascii.Append("<*R"); ascii.Append(ToString()); ascii.Append(">"); break; } case BOOLEAN: { if (boolValue) { ascii.Append("<*BY>"); } else { ascii.Append("<*BN>"); } break; } } } /// <summary> /// Compares the current <see cref="PList.NSNumber"/> to the specified object. /// </summary> /// <returns>0 if the numbers are equal, 1 if the current <see cref="PList.NSNumber"/> is greater /// than the argument and -1 if it is less, or the argument is not a number.</returns> /// <param name="o">Object to compare to the current <see cref="PList.NSNumber"/>.</param> public int CompareTo(Object o) { double x = ToDouble(); double y; if (o is NSNumber) { NSNumber num = (NSNumber)o; y = num.ToDouble(); return (x < y) ? -1 : ((x == y) ? 0 : 1); } if (IsNumber(o)) { y = GetDoubleFromObject(o); return (x < y) ? -1 : ((x == y) ? 0 : 1); } return -1; } /// <summary> /// Determines if an object is a number. /// Substitutes .NET's Number class comparison /// </summary> /// <returns><c>true</c> if it is a number.</returns> /// <param name="o">Object.</param> static bool IsNumber(Object o) { return o is sbyte || o is byte || o is short || o is ushort || o is int || o is uint || o is long || o is ulong || o is float || o is double || o is decimal; } static double GetDoubleFromObject(Object o) { if (o is sbyte) return (double)((sbyte)o); if (o is byte) return (double)((byte)o); if (o is short) return (double)((short)o); if (o is ushort) return (double)((ushort)o); if (o is int) return (double)((int)o); if (o is uint) return (double)((uint)o); if (o is long) return (double)((long)o); if (o is ulong) return (double)((ulong)o); if (o is float) return (double)((float)o); if (o is double) return (double)o; if (o is decimal) return (double)((decimal)o); return (double)0; } /// <summary> /// Determines whether the specified <see cref="PList.NSObject"/> is equal to the current <see cref="PList.NSNumber"/>. /// </summary> /// <param name="obj">The <see cref="PList.NSObject"/> to compare with the current <see cref="PList.NSNumber"/>.</param> /// <returns><c>true</c> if the specified <see cref="PList.NSObject"/> is equal to the current /// <see cref="PList.NSNumber"/>; otherwise, <c>false</c>.</returns> public override bool Equals(NSObject obj) { if (!(obj is NSNumber)) return false; if (((NSNumber)obj).GetNSNumberType() != type) return false; switch (type) { case INTEGER: return (longValue == ((NSNumber)obj).ToLong()); case REAL: return (doubleValue == ((NSNumber)obj).ToDouble()); case BOOLEAN: return (boolValue == ((NSNumber)obj).ToBool()); default: return false; } } } }
2881099/dotnetGen_postgresql
7,116
GenPg/plist-cil/NSDate.cs
// plist-cil - An open source library to parse and generate property lists for .NET // Copyright (C) 2015 Natalia Portillo // // This code is based on: // plist - An open source library to parse and generate property lists // Copyright (C) 2014 Daniel Dreibrodt // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. using System; using System.Text; namespace PList { /// <summary> /// Represents a date /// </summary> /// @author Daniel Dreibrodt /// @author Natalia Portillo public class NSDate : NSObject { readonly DateTime date; static readonly DateTime EPOCH = new DateTime(2001, 1, 1, 0, 0, 0, DateTimeKind.Utc); // The datetime ends with 'Z', which indicates UTC time. To make sure .NET // understands the 'Z' character as a timezone, specify the 'K' format string. static readonly string sdfDefault = "yyyy-MM-dd'T'HH:mm:ssK"; static readonly string sdfGnuStep = "yyyy-MM-dd HH:mm:ss zzz"; static readonly System.Globalization.CultureInfo provider = System.Globalization.CultureInfo.InvariantCulture; /// <summary> /// Parses the XML date string and creates a .NET DateTime object from it. /// </summary> /// <returns>The parsed Date</returns> /// <param name="textRepresentation">The date string as found in the XML property list</param> /// <exception cref="FormatException">Given string cannot be parsed</exception> static DateTime ParseDateString(string textRepresentation) { try { return DateTime.ParseExact(textRepresentation, sdfDefault, provider); } catch (FormatException) { return DateTime.ParseExact(textRepresentation, sdfGnuStep, provider); } } /// <summary> /// Generates a String representation of a .NET DateTime object. The string /// is formatted according to the specification for XML property list dates. /// </summary> /// <param name="date">The date which should be represented.</param> /// <returns>The string representation of the date.</returns> public static string MakeDateString(DateTime date) { return date.ToUniversalTime().ToString(sdfDefault); } /// <summary> /// Generates a String representation of a .NET DateTime object. The string /// is formatted according to the specification for GnuStep ASCII property /// list dates. /// </summary> /// <param name="date">The date which should be represented.</param> /// <returns>The string representation of the date.</returns> static string MakeDateStringGnuStep(DateTime date) { return date.ToString(sdfGnuStep); } /// <summary> /// Creates a date from its binary representation. /// </summary> /// <param name="bytes">bytes The date bytes</param> public NSDate(byte[] bytes) { //dates are 8 byte big-endian double, seconds since the epoch date = EPOCH.AddSeconds(BinaryPropertyListParser.ParseDouble(bytes)); } /// <summary> /// Parses a date from its textual representation. /// That representation has the following pattern: <code>yyyy-MM-dd'T'HH:mm:ss'Z'</code> /// </summary> /// <param name="textRepresentation">The textual representation of the date (ISO 8601 format)</param> /// <exception cref="FormatException">When the date could not be parsed, i.e. it does not match the expected pattern.</exception> public NSDate(String textRepresentation) { date = ParseDateString(textRepresentation); } /// <summary> /// Creates a NSDate from a .NET DateTime /// </summary> /// <param name="d">The date</param> public NSDate(DateTime d) { date = d; } /// <summary> /// Gets the date. /// </summary> /// <returns>The date.</returns> public DateTime Date { get { return date; } } /// <summary> /// Determines whether the specified <see cref="System.Object"/> is equal to the current <see cref="PList.NSDate"/>. /// </summary> /// <param name="obj">The <see cref="System.Object"/> to compare with the current <see cref="PList.NSDate"/>.</param> /// <returns><c>true</c> if the specified <see cref="System.Object"/> is equal to the current /// <see cref="PList.NSDate"/>; otherwise, <c>false</c>.</returns> public override bool Equals(Object obj) { return obj.GetType().Equals(GetType()) && date.Equals(((NSDate)obj).Date); } /// <summary> /// Serves as a hash function for a <see cref="PList.NSDate"/> object. /// </summary> /// <returns>A hash code for this instance that is suitable for use in hashing algorithms and data structures such as a /// hash table.</returns> public override int GetHashCode() { return date.GetHashCode(); } internal override void ToXml(StringBuilder xml, int level) { Indent(xml, level); xml.Append("<date>"); xml.Append(MakeDateString(date)); xml.Append("</date>"); } internal override void ToBinary(BinaryPropertyListWriter outPlist) { outPlist.Write(0x33); outPlist.WriteDouble((date - EPOCH).TotalSeconds); } /// <summary> /// Generates a string representation of the date. /// </summary> /// <returns>A string representation of the date.</returns> public override String ToString() { return date.ToString(); } internal override void ToASCII(StringBuilder ascii, int level) { Indent(ascii, level); ascii.Append("\""); ascii.Append(MakeDateString(date)); ascii.Append("\""); } internal override void ToASCIIGnuStep(StringBuilder ascii, int level) { Indent(ascii, level); ascii.Append("<*D"); ascii.Append(MakeDateStringGnuStep(date)); ascii.Append(">"); } /// <summary> /// Determines whether the specified <see cref="PList.NSObject"/> is equal to the current <see cref="PList.NSDate"/>. /// </summary> /// <param name="obj">The <see cref="PList.NSObject"/> to compare with the current <see cref="PList.NSDate"/>.</param> /// <returns><c>true</c> if the specified <see cref="PList.NSObject"/> is equal to the current /// <see cref="PList.NSDate"/>; otherwise, <c>false</c>.</returns> public override bool Equals(NSObject obj) { if (!(obj is NSDate)) return false; int equality = DateTime.Compare(date, ((NSDate)obj).Date); return equality == 0; } } }
2881099/dotnetGen_postgresql
1,967
GenPg/plist-cil/PropertyListFormatException.cs
// plist-cil - An open source library to parse and generate property lists for .NET // Copyright (C) 2015 Natalia Portillo // // This code is based on: // plist - An open source library to parse and generate property lists // Copyright (C) 2014 Daniel Dreibrodt // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. using System; namespace PList { /// <summary> /// A PropertyListFormatException is thrown by the various property list format parsers /// when an error in the format of the given property list is encountered. /// </summary> /// @author Daniel Dreibrodt /// @author Natalia Portillo public class PropertyListFormatException : PropertyListException { /// <summary> /// Creates a new exception with the given message. /// </summary> /// <param name="message">A message containing information about the nature of the exception.</param> public PropertyListFormatException(string message) : base(message) { } } }
2881099/dotnetGen_sqlserver
1,815
Common/Model/ForeignKeyInfo.cs
using System; using System.Text; using System.Collections.Generic; namespace Model { [Serializable] public class ForeignKeyInfo { private TableInfo _table; private List<ColumnInfo> _columns = new List<ColumnInfo>(); private TableInfo _referencedTable; private List<ColumnInfo> _referencedColumns = new List<ColumnInfo>(); private string _referencedDBName; private string _referencedTableName; private List<string> _referencedColumnNames = new List<string>(); private bool _referencedIsPrimaryKey; public ForeignKeyInfo(TableInfo table, TableInfo referencedTable) { _table = table; _referencedTable = referencedTable; } public ForeignKeyInfo(string referencedSln, string referencedTableName, bool referencedIsPK) { _referencedDBName = referencedSln; _referencedTableName = referencedTableName; _referencedIsPrimaryKey = referencedIsPK; } public TableInfo Table { get { return _table; } set { _table = value; } } public List<ColumnInfo> Columns { get { return _columns; } set { _columns = value; } } public TableInfo ReferencedTable { get { return _referencedTable; } set { _referencedTable = value; } } public List<ColumnInfo> ReferencedColumns { get { return _referencedColumns; } set { _referencedColumns = value; } } public string ReferencedDBName { get { return _referencedDBName; } set { _referencedDBName = value; } } public string ReferencedTableName { get { return _referencedTableName; } set { _referencedTableName = value; } } public List<string> ReferencedColumnNames { get { return _referencedColumnNames; } set { _referencedColumnNames = value; } } public bool ReferencedIsPrimaryKey { get { return _referencedIsPrimaryKey; } set { _referencedIsPrimaryKey = value; } } } }
27182812/ChatGLM-LLaMA-chinese-insturct
10,675
src/transformers/models/transfo_xl/modeling_transfo_xl_utilities.py
# coding=utf-8 # Copyright 2018 Google AI, Google Brain and Carnegie Mellon University Authors and the HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. 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. """ Utilities for PyTorch Transformer XL model. Directly adapted from https://github.com/kimiyoung/transformer-xl. """ import torch from torch import nn # CUDA_MAJOR = int(torch.version.cuda.split('.')[0]) # CUDA_MINOR = int(torch.version.cuda.split('.')[1]) class ProjectedAdaptiveLogSoftmax(nn.Module): def __init__(self, n_token, d_embed, d_proj, cutoffs, div_val=1, keep_order=False): super().__init__() self.n_token = n_token self.d_embed = d_embed self.d_proj = d_proj self.cutoffs = cutoffs + [n_token] self.cutoff_ends = [0] + self.cutoffs self.div_val = div_val self.shortlist_size = self.cutoffs[0] self.n_clusters = len(self.cutoffs) - 1 self.head_size = self.shortlist_size + self.n_clusters if self.n_clusters > 0: self.cluster_weight = nn.Parameter(torch.zeros(self.n_clusters, self.d_embed)) self.cluster_bias = nn.Parameter(torch.zeros(self.n_clusters)) self.out_layers = nn.ModuleList() self.out_projs = nn.ParameterList() if div_val == 1: for i in range(len(self.cutoffs)): if d_proj != d_embed: self.out_projs.append(nn.Parameter(torch.FloatTensor(d_proj, d_embed))) else: self.out_projs.append(None) self.out_layers.append(nn.Linear(d_embed, n_token)) else: for i in range(len(self.cutoffs)): l_idx, r_idx = self.cutoff_ends[i], self.cutoff_ends[i + 1] d_emb_i = d_embed // (div_val**i) self.out_projs.append(nn.Parameter(torch.FloatTensor(d_proj, d_emb_i))) self.out_layers.append(nn.Linear(d_emb_i, r_idx - l_idx)) self.keep_order = keep_order def _compute_logit(self, hidden, weight, bias, proj): if proj is None: logit = nn.functional.linear(hidden, weight, bias=bias) else: # if CUDA_MAJOR <= 9 and CUDA_MINOR <= 1: proj_hid = nn.functional.linear(hidden, proj.t().contiguous()) logit = nn.functional.linear(proj_hid, weight, bias=bias) # else: # logit = torch.einsum('bd,de,ev->bv', (hidden, proj, weight.t())) # if bias is not None: # logit = logit + bias return logit def forward(self, hidden, labels=None, keep_order=False): """ Params: hidden :: [len*bsz x d_proj] labels :: [len*bsz Return: if labels is None: out :: [len*bsz x n_tokens] log probabilities of tokens over the vocabulary else: out :: [(len-1)*bsz] Negative log likelihood. We could replace this implementation by the native PyTorch one if theirs had an option to set bias on all clusters in the native one. here: https://github.com/pytorch/pytorch/blob/dbe6a7a9ff1a364a8706bf5df58a1ca96d2fd9da/torch/nn/modules/adaptive.py#L138 """ if labels is not None: # Shift so that tokens < n predict n hidden = hidden[..., :-1, :].contiguous() labels = labels[..., 1:].contiguous() hidden = hidden.view(-1, hidden.size(-1)) labels = labels.view(-1) if hidden.size(0) != labels.size(0): raise RuntimeError("Input and labels should have the same size in the batch dimension.") else: hidden = hidden.view(-1, hidden.size(-1)) if self.n_clusters == 0: logit = self._compute_logit(hidden, self.out_layers[0].weight, self.out_layers[0].bias, self.out_projs[0]) if labels is not None: out = -nn.functional.log_softmax(logit, dim=-1).gather(1, labels.unsqueeze(1)).squeeze(1) else: out = nn.functional.log_softmax(logit, dim=-1) else: # construct weights and biases weights, biases = [], [] for i in range(len(self.cutoffs)): if self.div_val == 1: l_idx, r_idx = self.cutoff_ends[i], self.cutoff_ends[i + 1] weight_i = self.out_layers[0].weight[l_idx:r_idx] bias_i = self.out_layers[0].bias[l_idx:r_idx] else: weight_i = self.out_layers[i].weight bias_i = self.out_layers[i].bias if i == 0: weight_i = torch.cat([weight_i, self.cluster_weight], dim=0) bias_i = torch.cat([bias_i, self.cluster_bias], dim=0) weights.append(weight_i) biases.append(bias_i) head_weight, head_bias, head_proj = weights[0], biases[0], self.out_projs[0] head_logit = self._compute_logit(hidden, head_weight, head_bias, head_proj) head_logprob = nn.functional.log_softmax(head_logit, dim=1) if labels is None: out = hidden.new_empty((head_logit.size(0), self.n_token)) else: out = torch.zeros_like(labels, dtype=hidden.dtype, device=hidden.device) offset = 0 cutoff_values = [0] + self.cutoffs for i in range(len(cutoff_values) - 1): l_idx, r_idx = cutoff_values[i], cutoff_values[i + 1] if labels is not None: mask_i = (labels >= l_idx) & (labels < r_idx) indices_i = mask_i.nonzero().squeeze() if indices_i.numel() == 0: continue target_i = labels.index_select(0, indices_i) - l_idx head_logprob_i = head_logprob.index_select(0, indices_i) hidden_i = hidden.index_select(0, indices_i) else: hidden_i = hidden if i == 0: if labels is not None: logprob_i = head_logprob_i.gather(1, target_i[:, None]).squeeze(1) else: out[:, : self.cutoffs[0]] = head_logprob[:, : self.cutoffs[0]] else: weight_i, bias_i, proj_i = weights[i], biases[i], self.out_projs[i] tail_logit_i = self._compute_logit(hidden_i, weight_i, bias_i, proj_i) tail_logprob_i = nn.functional.log_softmax(tail_logit_i, dim=1) cluster_prob_idx = self.cutoffs[0] + i - 1 # No probability for the head cluster if labels is not None: logprob_i = head_logprob_i[:, cluster_prob_idx] + tail_logprob_i.gather( 1, target_i[:, None] ).squeeze(1) else: logprob_i = head_logprob[:, cluster_prob_idx, None] + tail_logprob_i out[:, l_idx:r_idx] = logprob_i if labels is not None: if (hasattr(self, "keep_order") and self.keep_order) or keep_order: out.index_copy_(0, indices_i, -logprob_i) else: out[offset : offset + logprob_i.size(0)].copy_(-logprob_i) offset += logprob_i.size(0) return out def log_prob(self, hidden): r""" Computes log probabilities for all \\(n\_classes\\) From: https://github.com/pytorch/pytorch/blob/master/torch/nn/modules/adaptive.p Args: hidden (Tensor): a minibatch of example Returns: log-probabilities of for each class \\(c\\) in range \\(0 <= c <= n\_classes\\), where \\(n\_classes\\) is a parameter passed to `AdaptiveLogSoftmaxWithLoss` constructor. Shape: - Input: \\((N, in\_features)\\) - Output: \\((N, n\_classes)\\) """ if self.n_clusters == 0: logit = self._compute_logit(hidden, self.out_layers[0].weight, self.out_layers[0].bias, self.out_projs[0]) return nn.functional.log_softmax(logit, dim=-1) else: # construct weights and biases weights, biases = [], [] for i in range(len(self.cutoffs)): if self.div_val == 1: l_idx, r_idx = self.cutoff_ends[i], self.cutoff_ends[i + 1] weight_i = self.out_layers[0].weight[l_idx:r_idx] bias_i = self.out_layers[0].bias[l_idx:r_idx] else: weight_i = self.out_layers[i].weight bias_i = self.out_layers[i].bias if i == 0: weight_i = torch.cat([weight_i, self.cluster_weight], dim=0) bias_i = torch.cat([bias_i, self.cluster_bias], dim=0) weights.append(weight_i) biases.append(bias_i) head_weight, head_bias, head_proj = weights[0], biases[0], self.out_projs[0] head_logit = self._compute_logit(hidden, head_weight, head_bias, head_proj) out = hidden.new_empty((head_logit.size(0), self.n_token)) head_logprob = nn.functional.log_softmax(head_logit, dim=1) cutoff_values = [0] + self.cutoffs for i in range(len(cutoff_values) - 1): start_idx, stop_idx = cutoff_values[i], cutoff_values[i + 1] if i == 0: out[:, : self.cutoffs[0]] = head_logprob[:, : self.cutoffs[0]] else: weight_i, bias_i, proj_i = weights[i], biases[i], self.out_projs[i] tail_logit_i = self._compute_logit(hidden, weight_i, bias_i, proj_i) tail_logprob_i = nn.functional.log_softmax(tail_logit_i, dim=1) logprob_i = head_logprob[:, -i] + tail_logprob_i out[:, start_idx, stop_idx] = logprob_i return out
2881099/dotnetGen_sqlserver
1,624
Common/Model/ColumnInfo.cs
using System; using System.Collections.Generic; using System.Data; using System.Text; namespace Model { [Serializable] public class ColumnInfo { private string _name; private SqlDbType _type; private int _length; private string _sqlType; private DataSort _orderby; private bool _isNullable; private bool _isIdentity; private bool _isClustered; private bool _isPrimaryKey; public ColumnInfo() { } public ColumnInfo(string name, SqlDbType type, int length, string sqlType, DataSort orderby, bool isNullable, bool isIdentity, bool isClustered, bool isPrimaryKey) { _name = name; _type = type; _length = length; _sqlType = sqlType; _orderby = orderby; _isNullable = isNullable; _isIdentity = isIdentity; _isClustered = isClustered; _isPrimaryKey = isPrimaryKey; } public string Name { get { return _name; } set { _name = value; } } public SqlDbType Type { get { return _type; } set { _type = value; } } public int Length { get { return _length; } set { _length = value; } } public string SqlType { get { return _sqlType; } set { _sqlType = value; } } public DataSort Orderby { get { return _orderby; } set { _orderby = value; } } public bool IsNullable { get { return _isNullable; } set { _isNullable = value; } } public bool IsIdentity { get { return _isIdentity; } set { _isIdentity = value; } } public bool IsClustered { get { return _isClustered; } set { _isClustered = value; } } public bool IsPrimaryKey { get { return _isPrimaryKey; } set { _isPrimaryKey = value; } } } }
2881099/dotnetGen_postgresql
12,138
GenPg/plist-cil/NSArray.cs
// plist-cil - An open source library to parse and generate property lists for .NET // Copyright (C) 2015 Natalia Portillo // // This code is based on: // plist - An open source library to parse and generate property lists // Copyright (C) 2014 Daniel Dreibrodt // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Text; namespace PList { /// <summary> /// Represents an Array. /// </summary> /// @author Daniel Dreibrodt /// @author Natalia Portillo public partial class NSArray : NSObject { List<NSObject> array; /// <summary> /// Creates an empty array of the given length. /// </summary> /// <param name="length">The number of elements this array will be able to hold.</param> public NSArray(int length) { array = new List<NSObject>(length); } /// <summary> /// Creates a array from an existing one /// </summary> /// <param name="a">The array which should be wrapped by the NSArray.</param> public NSArray(params NSObject[] a) { array = new List<NSObject>(a); } /// <summary> /// Returns the object stored at the given index. /// </summary> /// <returns>The object at the given index.</returns> /// <param name="i">The index of the object.</param> public NSObject ObjectAtIndex(int i) { return array[i]; } /// <summary> /// Remove the i-th element from the array. /// The array will be resized. /// </summary> /// <param name="i">The index of the object</param> public void Remove(int i) { this.array.RemoveAt(i); } /// <summary> /// Stores an object at the specified index. /// If there was another object stored at that index it will be replaced. /// </summary> /// <param name="key">The index where to store the object.</param> /// <param name="value">The object.</param> public void SetValue(int key, Object value) { if (value == null) throw new ArgumentNullException("value", "Cannot add null values to an NSArray!"); array[key] = NSObject.Wrap(value); } /// <summary> /// Returns the array of NSObjects represented by this NSArray. /// Any changes to the values of this array will also affect the NSArray. /// </summary> /// <returns>The actual array represented by this NSArray.</returns> public NSObject[] GetArray() { return array.ToArray(); } /// <summary> /// Returns the size of the array. /// </summary> /// <value>The number of elements that this array can store.</value> public int Count { get { return array.Count; } } /// <summary> /// Checks whether an object is present in the array or whether it is equal /// to any of the objects in the array. /// </summary> /// <returns><c>true</c>, when the object could be found. <c>false</c> otherwise.</returns> /// <param name="obj">The object to look for.</param> public bool ContainsObject(Object obj) { NSObject nso = NSObject.Wrap(obj); foreach (NSObject elem in array) { if (elem.Equals(nso)) { return true; } } return false; } /// <summary> /// Searches for an object in the array. If it is found its index will be /// returned. This method also returns an index if the object is not the same /// as the one stored in the array but has equal contents. /// </summary> /// <returns>The index of the object, if it was found. -1 otherwise.</returns> /// <param name="obj">The object to look for.</param> public int IndexOfObject(Object obj) { NSObject nso = NSObject.Wrap(obj); for (int i = 0; i < array.Count; i++) { if (array[i].Equals(nso)) { return i; } } return -1; } /// <summary> /// Searches for an object in the array. If it is found its index will be /// returned. This method only returns the index of an object that is /// <b>identical</b> to the given one. Thus objects that might contain the /// same value as the given one will not be considered. /// </summary> /// <returns>The index of the object, if it was found. -1 otherwise.</returns> /// <param name="obj">The object to look for.</param> public int IndexOfIdenticalObject(Object obj) { NSObject nso = NSObject.Wrap(obj); for (int i = 0; i < array.Count; i++) { if (array[i] == nso) { return i; } } return -1; } /// <summary> /// Returns the last object contained in this array. /// </summary> /// <returns>The value of the highest index in the array.</returns> public NSObject LastObject() { return array[array.Count - 1]; } /// <summary> /// Returns a new array containing only the values stored at the given /// indices. The values are sorted by their index. /// </summary> /// <returns>The new array containing the objects stored at the given indices.</returns> /// <param name="indexes">The indices of the objects.</param> public NSObject[] ObjectsAtIndexes(params int[] indexes) { NSObject[] result = new NSObject[indexes.Length]; Array.Sort(indexes); for (int i = 0; i < indexes.Length; i++) result[i] = array[indexes[i]]; return result; } /// <summary> /// Determines whether the specified <see cref="System.Object"/> is equal to the current <see cref="PList.NSArray"/>. /// </summary> /// <param name="obj">The <see cref="System.Object"/> to compare with the current <see cref="PList.NSArray"/>.</param> /// <returns><c>true</c> if the specified <see cref="System.Object"/> is equal to the current /// <see cref="PList.NSArray"/>; otherwise, <c>false</c>.</returns> public override bool Equals(Object obj) { if (obj.GetType().Equals(typeof(NSArray))) { return ArrayEquals(((NSArray)obj).GetArray(), this.GetArray()); } else { NSObject nso = NSObject.Wrap(obj); if (nso.GetType().Equals(typeof(NSArray))) { return ArrayEquals(((NSArray)nso).GetArray(), this.GetArray()); } } return false; } /// <summary> /// Serves as a hash function for a <see cref="PList.NSArray"/> object. /// </summary> /// <returns>A hash code for this instance that is suitable for use in hashing algorithms and data structures such as a /// hash table.</returns> public override int GetHashCode() { int hash = 7; hash = 89 * hash + array.GetHashCode(); return hash; } internal override void ToXml(StringBuilder xml, int level) { Indent(xml, level); xml.Append("<array>"); xml.Append(NSObject.NEWLINE); foreach (NSObject o in array) { o.ToXml(xml, level + 1); xml.Append(NSObject.NEWLINE); } Indent(xml, level); xml.Append("</array>"); } internal override void AssignIDs(BinaryPropertyListWriter outPlist) { base.AssignIDs(outPlist); foreach (NSObject obj in array) { obj.AssignIDs(outPlist); } } internal override void ToBinary(BinaryPropertyListWriter outPlist) { outPlist.WriteIntHeader(0xA, array.Count); foreach (NSObject obj in array) { outPlist.WriteID(outPlist.GetID(obj)); } } /// <summary> /// <para> /// Generates a valid ASCII property list which has this NSArray as its /// root object. /// </para><para> /// The generated property list complies with the format as /// described in https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/PropertyLists/OldStylePlists/OldStylePLists.html /// Property List Programming Guide - Old-Style ASCII Property Lists. /// </para> /// </summary> /// <returns>ASCII representation of this object.</returns> public string ToASCIIPropertyList() { StringBuilder ascii = new StringBuilder(); ToASCII(ascii, 0); ascii.Append(NEWLINE); return ascii.ToString(); } /// <summary> /// <para> /// Generates a valid ASCII property list in GnuStep format which has this /// NSArray as its root object. /// </para><para> /// The generated property list complies with /// the format as described in http://www.gnustep.org/resources/documentation/Developer/Base/Reference/NSPropertyList.html /// GnuStep - NSPropertyListSerialization class documentation. /// </para> /// </summary> /// <returns>GnuStep ASCII representation of this object.</returns> public string ToGnuStepASCIIPropertyList() { StringBuilder ascii = new StringBuilder(); ToASCIIGnuStep(ascii, 0); ascii.Append(NEWLINE); return ascii.ToString(); } internal override void ToASCII(StringBuilder ascii, int level) { Indent(ascii, level); ascii.Append(ASCIIPropertyListParser.ARRAY_BEGIN_TOKEN); int indexOfLastNewLine = ascii.ToString().LastIndexOf(NEWLINE, StringComparison.Ordinal); for (int i = 0; i < array.Count; i++) { Type objClass = array[i].GetType(); if ((objClass.Equals(typeof(NSDictionary)) || objClass.Equals(typeof(NSArray)) || objClass.Equals(typeof(NSData))) && indexOfLastNewLine != ascii.Length) { ascii.Append(NEWLINE); indexOfLastNewLine = ascii.Length; array[i].ToASCII(ascii, level + 1); } else { if (i != 0) ascii.Append(" "); array[i].ToASCII(ascii, 0); } if (i != array.Count - 1) ascii.Append(ASCIIPropertyListParser.ARRAY_ITEM_DELIMITER_TOKEN); if (ascii.Length - indexOfLastNewLine > ASCII_LINE_LENGTH) { ascii.Append(NEWLINE); indexOfLastNewLine = ascii.Length; } } ascii.Append(ASCIIPropertyListParser.ARRAY_END_TOKEN); } internal override void ToASCIIGnuStep(StringBuilder ascii, int level) { Indent(ascii, level); ascii.Append(ASCIIPropertyListParser.ARRAY_BEGIN_TOKEN); int indexOfLastNewLine = ascii.ToString().LastIndexOf(NEWLINE, StringComparison.Ordinal); for (int i = 0; i < array.Count; i++) { Type objClass = array[i].GetType(); if ((objClass.Equals(typeof(NSDictionary)) || objClass.Equals(typeof(NSArray)) || objClass.Equals(typeof(NSData))) && indexOfLastNewLine != ascii.Length) { ascii.Append(NEWLINE); indexOfLastNewLine = ascii.Length; array[i].ToASCIIGnuStep(ascii, level + 1); } else { if (i != 0) ascii.Append(" "); array[i].ToASCIIGnuStep(ascii, 0); } if (i != array.Count - 1) ascii.Append(ASCIIPropertyListParser.ARRAY_ITEM_DELIMITER_TOKEN); if (ascii.Length - indexOfLastNewLine > ASCII_LINE_LENGTH) { ascii.Append(NEWLINE); indexOfLastNewLine = ascii.Length; } } ascii.Append(ASCIIPropertyListParser.ARRAY_END_TOKEN); } /// <summary> /// Determines whether the specified <see cref="PList.NSObject"/> is equal to the current <see cref="PList.NSArray"/>. /// </summary> /// <param name="obj">The <see cref="PList.NSObject"/> to compare with the current <see cref="PList.NSArray"/>.</param> /// <returns><c>true</c> if the specified <see cref="PList.NSObject"/> is equal to the current /// <see cref="PList.NSArray"/>; otherwise, <c>false</c>.</returns> public override bool Equals(NSObject obj) { if (!(obj is NSArray)) return false; if (array.Count != ((NSArray)obj).array.Count) return false; for (int i = 0; i < array.Count; i++) if (!array[i].Equals(((NSArray)obj).ObjectAtIndex(i))) return false; return true; } } }
2881099/dotnetGen_postgresql
7,396
GenPg/plist-cil/XmlPropertyListParser.cs
// plist-cil - An open source library to parse and generate property lists for .NET // Copyright (C) 2015 Natalia Portillo // // This code is based on: // plist - An open source library to parse and generate property lists // Copyright (C) 2014 Daniel Dreibrodt // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. using System.Xml; using System.Collections.Generic; using System.IO; using System.Linq; namespace PList { /// <summary> /// Parses XML property lists. /// </summary> /// @author Daniel Dreibrodt /// @author Natalia Portillo public static class XmlPropertyListParser { /// <summary> /// Parses a XML property list file. /// </summary> /// <param name="f">The XML property list file.</param> /// <returns>The root object of the property list. This is usually a NSDictionary but can also be a NSArray.</returns> public static NSObject Parse(FileInfo f) { XmlDocument doc = new XmlDocument(); using (Stream stream = f.OpenRead()) { doc.Load(stream); } return ParseDocument(doc); } /// <summary> /// Parses a XML property list from a byte array. /// </summary> /// <param name="bytes">The byte array containing the property list's data.</param> /// <returns>The root object of the property list. This is usually a NSDictionary but can also be a NSArray.</returns> public static NSObject Parse(byte[] bytes) { MemoryStream bis = new MemoryStream(bytes); return Parse(bis); } /// <summary> /// Parses a XML property list from an input stream. /// </summary> /// <param name="str">The input stream pointing to the property list's data.</param> /// <returns>The root object of the property list. This is usually a NSDictionary but can also be a NSArray.</returns> public static NSObject Parse(Stream str) { XmlDocument doc = new XmlDocument(); XmlReaderSettings settings = new XmlReaderSettings(); settings.DtdProcessing = DtdProcessing.Ignore; using (XmlReader reader = XmlReader.Create(str, settings)) { doc.Load(reader); } return ParseDocument(doc); } /// <summary> /// Parses the XML document by generating the appropriate NSObjects for each XML node. /// </summary> /// <returns>The root NSObject of the property list contained in the XML document.</returns> /// <param name="doc">The XML document.</param> static NSObject ParseDocument(XmlDocument doc) { var docType = doc.ChildNodes .OfType<XmlNode>() .SingleOrDefault(n => n.NodeType == XmlNodeType.DocumentType); if (docType == null) { if (!doc.DocumentElement.Name.Equals("plist")) { throw new XmlException("The given XML document is not a property list."); } } else if (!docType.Name.Equals("plist")) { throw new XmlException("The given XML document is not a property list."); } XmlNode rootNode; if (doc.DocumentElement.Name.Equals("plist")) { //Root element wrapped in plist tag List<XmlNode> rootNodes = FilterElementNodes(doc.DocumentElement.ChildNodes); if (rootNodes.Count == 0) throw new PropertyListFormatException("The given XML property list has no root element!"); if (rootNodes.Count == 1) rootNode = rootNodes[0]; else throw new PropertyListFormatException("The given XML property list has more than one root element!"); } else //Root NSObject not wrapped in plist-tag rootNode = doc.DocumentElement; return ParseObject(rootNode); } /// <summary> /// Parses a node in the XML structure and returns the corresponding NSObject /// </summary> /// <returns>The corresponding NSObject.</returns> /// <param name="n">The XML node.</param> static NSObject ParseObject(XmlNode n) { if (n.Name.Equals("dict")) { NSDictionary dict = new NSDictionary(); List<XmlNode> children = FilterElementNodes(n.ChildNodes); for (int i = 0; i < children.Count; i += 2) { XmlNode key = children[i]; XmlNode val = children[i + 1]; string keyString = GetNodeTextContents(key); dict.Add(keyString, ParseObject(val)); } return dict; } if (n.Name.Equals("array")) { List<XmlNode> children = FilterElementNodes(n.ChildNodes); NSArray array = new NSArray(children.Count); for (int i = 0; i < children.Count; i++) { array.Add(ParseObject(children[i])); } return array; } if (n.Name.Equals("true")) return new NSNumber(true); if (n.Name.Equals("false")) return new NSNumber(false); if (n.Name.Equals("integer")) return new NSNumber(GetNodeTextContents(n), NSNumber.INTEGER); if (n.Name.Equals("real")) return new NSNumber(GetNodeTextContents(n), NSNumber.REAL); if (n.Name.Equals("string")) return new NSString(GetNodeTextContents(n)); if (n.Name.Equals("data")) return new NSData(GetNodeTextContents(n)); return n.Name.Equals("date") ? new NSDate(GetNodeTextContents(n)) : null; } /// <summary> /// Returns all element nodes that are contained in a list of nodes. /// </summary> /// <returns>The sublist containing only nodes representing actual elements.</returns> /// <param name="list">The list of nodes to search.</param> static List<XmlNode> FilterElementNodes(XmlNodeList list) { List<XmlNode> result = new List<XmlNode>(); foreach (XmlNode child in list) if (child.NodeType == XmlNodeType.Element) result.Add(child); return result; } /// <summary> /// Returns a node's text content. /// This method will return the text value represented by the node's direct children. /// If the given node is a TEXT or CDATA node, then its value is returned. /// </summary> /// <returns>The node's text content.</returns> /// <param name="n">The node.</param> static string GetNodeTextContents(XmlNode n) { if (n.NodeType == XmlNodeType.Text || n.NodeType == XmlNodeType.CDATA) { string content = n.Value; //This concatenates any adjacent text/cdata/entity nodes return content ?? ""; } if (n.HasChildNodes) { XmlNodeList children = n.ChildNodes; foreach (XmlNode child in children) { //Skip any non-text nodes, like comments or entities if (child.NodeType == XmlNodeType.Text || child.NodeType == XmlNodeType.CDATA) { string content = child.Value; //This concatenates any adjacent text/cdata/entity nodes return content ?? ""; } } return ""; } return ""; } } }
27182812/ChatGLM-LLaMA-chinese-insturct
7,597
src/transformers/models/transfo_xl/modeling_tf_transfo_xl_utilities.py
# coding=utf-8 # Copyright 2018 Google AI, Google Brain and Carnegie Mellon University Authors and the HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. 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. """ A TF 2.0 Adaptive Softmax for Transformer XL model. """ import tensorflow as tf from ...tf_utils import shape_list class TFAdaptiveSoftmaxMask(tf.keras.layers.Layer): def __init__(self, vocab_size, d_embed, d_proj, cutoffs, div_val=1, keep_order=False, **kwargs): super().__init__(**kwargs) self.vocab_size = vocab_size self.d_embed = d_embed self.d_proj = d_proj self.cutoffs = cutoffs + [vocab_size] self.cutoff_ends = [0] + self.cutoffs self.div_val = div_val self.shortlist_size = self.cutoffs[0] self.n_clusters = len(self.cutoffs) - 1 self.head_size = self.shortlist_size + self.n_clusters self.keep_order = keep_order self.out_layers = [] self.out_projs = [] def build(self, input_shape): if self.n_clusters > 0: self.cluster_weight = self.add_weight( shape=(self.n_clusters, self.d_embed), initializer="zeros", trainable=True, name="cluster_weight" ) self.cluster_bias = self.add_weight( shape=(self.n_clusters,), initializer="zeros", trainable=True, name="cluster_bias" ) if self.div_val == 1: for i in range(len(self.cutoffs)): if self.d_proj != self.d_embed: weight = self.add_weight( shape=(self.d_embed, self.d_proj), initializer="zeros", trainable=True, name=f"out_projs_._{i}", ) self.out_projs.append(weight) else: self.out_projs.append(None) weight = self.add_weight( shape=(self.vocab_size, self.d_embed), initializer="zeros", trainable=True, name=f"out_layers_._{i}_._weight", ) bias = self.add_weight( shape=(self.vocab_size,), initializer="zeros", trainable=True, name=f"out_layers_._{i}_._bias", ) self.out_layers.append((weight, bias)) else: for i in range(len(self.cutoffs)): l_idx, r_idx = self.cutoff_ends[i], self.cutoff_ends[i + 1] d_emb_i = self.d_embed // (self.div_val**i) weight = self.add_weight( shape=(d_emb_i, self.d_proj), initializer="zeros", trainable=True, name=f"out_projs_._{i}" ) self.out_projs.append(weight) weight = self.add_weight( shape=(r_idx - l_idx, d_emb_i), initializer="zeros", trainable=True, name=f"out_layers_._{i}_._weight", ) bias = self.add_weight( shape=(r_idx - l_idx,), initializer="zeros", trainable=True, name=f"out_layers_._{i}_._bias", ) self.out_layers.append((weight, bias)) super().build(input_shape) @staticmethod def _logit(x, W, b, proj=None): y = x if proj is not None: y = tf.einsum("ibd,ed->ibe", y, proj) return tf.einsum("ibd,nd->ibn", y, W) + b @staticmethod def _gather_logprob(logprob, target): lp_size = shape_list(logprob) r = tf.range(lp_size[0], dtype=target.dtype) idx = tf.stack([r, target], 1) return tf.gather_nd(logprob, idx) def call(self, hidden, target, return_mean=True, training=False): head_logprob = 0 if self.n_clusters == 0: output = self._logit(hidden, self.out_layers[0][0], self.out_layers[0][1], self.out_projs[0]) if target is not None: loss = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=target, logits=output) out = tf.nn.log_softmax(output, axis=-1) else: hidden_sizes = shape_list(hidden) out = [] loss = tf.zeros(hidden_sizes[:2]) for i in range(len(self.cutoffs)): l_idx, r_idx = self.cutoff_ends[i], self.cutoff_ends[i + 1] if target is not None: mask = (target >= l_idx) & (target < r_idx) mask_idx = tf.where(mask) cur_target = tf.boolean_mask(target, mask) - l_idx if self.div_val == 1: cur_W = self.out_layers[0][0][l_idx:r_idx] cur_b = self.out_layers[0][1][l_idx:r_idx] else: cur_W = self.out_layers[i][0] cur_b = self.out_layers[i][1] if i == 0: cur_W = tf.concat([cur_W, self.cluster_weight], 0) cur_b = tf.concat([cur_b, self.cluster_bias], 0) head_logit = self._logit(hidden, cur_W, cur_b, self.out_projs[0]) head_logprob = tf.nn.log_softmax(head_logit) out.append(head_logprob[..., : self.cutoffs[0]]) if target is not None: cur_head_logprob = tf.boolean_mask(head_logprob, mask) cur_logprob = self._gather_logprob(cur_head_logprob, cur_target) else: tail_logit = self._logit(hidden, cur_W, cur_b, self.out_projs[i]) tail_logprob = tf.nn.log_softmax(tail_logit) cluster_prob_idx = self.cutoffs[0] + i - 1 # No probability for the head cluster logprob_i = head_logprob[..., cluster_prob_idx, None] + tail_logprob out.append(logprob_i) if target is not None: cur_head_logprob = tf.boolean_mask(head_logprob, mask) cur_tail_logprob = tf.boolean_mask(tail_logprob, mask) cur_logprob = self._gather_logprob(cur_tail_logprob, cur_target) cur_logprob += cur_head_logprob[:, self.cutoff_ends[1] + i - 1] if target is not None: loss += tf.scatter_nd(mask_idx, -cur_logprob, shape_list(loss)) out = tf.concat(out, axis=-1) if target is not None: if return_mean: loss = tf.reduce_mean(loss) # Add the training-time loss value to the layer using `self.add_loss()`. self.add_loss(loss) # Log the loss as a metric (we could log arbitrary metrics, # including different metrics for training and inference. self.add_metric(loss, name=self.name, aggregation="mean" if return_mean else "") return out
2881099/dotnetGen_sqlserver
2,625
Common/Model/TableInfo.cs
using System; using System.Text; using System.Text.RegularExpressions; using System.Collections.Generic; namespace Model { [Serializable] public class TableInfo { private int _id; private string _owner; private string _name; private List<ColumnInfo> _columns = new List<ColumnInfo>(); private List<List<ColumnInfo>> _uniques = new List<List<ColumnInfo>>(); private List<List<ColumnInfo>> _indexes = new List<List<ColumnInfo>>(); private List<ForeignKeyInfo> _foreignKeys = new List<ForeignKeyInfo>(); private List<ColumnInfo> _identitys = new List<ColumnInfo>(); private List<ColumnInfo> _clustereds = new List<ColumnInfo>(); private List<ColumnInfo> _primaryKeys = new List<ColumnInfo>(); private string _Type; private bool _IsOutput; public TableInfo(int id, string owner, string name, string type) { _id = id; _owner = owner; _name = name; _Type = type; } public static string GetClassName(string name) { int rr = 0; string n = name.StartsWith("dbo.") ? name.Substring(4) : Regex.Replace(name, @"\.", delegate(Match m) { if (rr++ > 0) return m.Groups[0].Value; return "_"; }); return char.IsLetter(n, 0) ? n : string.Concat("_", n); } public static string GetEntryName(string name) { int idx = name.IndexOf('.'); return idx == -1 ? name : name.Substring(idx + 1); } public int Id { get { return _id; } } public string Owner { get { return _owner; } } public string Name { get { return _name; } } public string ClassName { get { return GetClassName(_owner.ToLower() + "." + _name); } } public string FullName { get { return string.Format("{0}.{1}", _owner, _name); } } public string Type { get { return _Type; } } public List<ColumnInfo> Columns { get { return _columns; } } public List<List<ColumnInfo>> Uniques { get { if (_uniques == null) { } return _uniques; } } public List<List<ColumnInfo>> Indexes { get { if (_indexes == null) { } return _indexes; } } public List<ForeignKeyInfo> ForeignKeys { get { if (_foreignKeys == null) { } return _foreignKeys; } } public List<ColumnInfo> PrimaryKeys { get { if (_primaryKeys == null) { } return _primaryKeys; } } public List<ColumnInfo> Clustereds { get { if (_clustereds == null) { } return _clustereds; } } public List<ColumnInfo> Identitys { get { if (_identitys == null) { } return _identitys; } } public bool IsOutput { get { return _IsOutput; } set { _IsOutput = value; } } } }
2881099/dotnetGen_sqlserver
898
Common/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 有关程序集的常规信息通过下列属性集 // 控制。更改这些属性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("Common")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Common")] [assembly: AssemblyCopyright("版权所有 (C) 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 将 ComVisible 设置为 false 使此程序集中的类型 // 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型, // 则将该类型上的 ComVisible 属性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID [assembly: Guid("b3e3991f-30e6-4edf-ad0b-8a24b747de76")] // 程序集的版本信息由下面四个值组成: // // 主版本 // 次版本 // 内部版本号 // 修订号 // // 可以指定所有这些值,也可以使用“修订号”和“内部版本号”的默认值, // 方法是按如下所示使用“*”: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
2881099/dotnetGen_sqlserver
1,815
GenMs/Model/ForeignKeyInfo.cs
using System; using System.Text; using System.Collections.Generic; namespace Model { [Serializable] public class ForeignKeyInfo { private TableInfo _table; private List<ColumnInfo> _columns = new List<ColumnInfo>(); private TableInfo _referencedTable; private List<ColumnInfo> _referencedColumns = new List<ColumnInfo>(); private string _referencedDBName; private string _referencedTableName; private List<string> _referencedColumnNames = new List<string>(); private bool _referencedIsPrimaryKey; public ForeignKeyInfo(TableInfo table, TableInfo referencedTable) { _table = table; _referencedTable = referencedTable; } public ForeignKeyInfo(string referencedSln, string referencedTableName, bool referencedIsPK) { _referencedDBName = referencedSln; _referencedTableName = referencedTableName; _referencedIsPrimaryKey = referencedIsPK; } public TableInfo Table { get { return _table; } set { _table = value; } } public List<ColumnInfo> Columns { get { return _columns; } set { _columns = value; } } public TableInfo ReferencedTable { get { return _referencedTable; } set { _referencedTable = value; } } public List<ColumnInfo> ReferencedColumns { get { return _referencedColumns; } set { _referencedColumns = value; } } public string ReferencedDBName { get { return _referencedDBName; } set { _referencedDBName = value; } } public string ReferencedTableName { get { return _referencedTableName; } set { _referencedTableName = value; } } public List<string> ReferencedColumnNames { get { return _referencedColumnNames; } set { _referencedColumnNames = value; } } public bool ReferencedIsPrimaryKey { get { return _referencedIsPrimaryKey; } set { _referencedIsPrimaryKey = value; } } } }
2881099/dotnetGen_sqlserver
1,624
GenMs/Model/ColumnInfo.cs
using System; using System.Collections.Generic; using System.Data; using System.Text; namespace Model { [Serializable] public class ColumnInfo { private string _name; private SqlDbType _type; private int _length; private string _sqlType; private DataSort _orderby; private bool _isNullable; private bool _isIdentity; private bool _isClustered; private bool _isPrimaryKey; public ColumnInfo() { } public ColumnInfo(string name, SqlDbType type, int length, string sqlType, DataSort orderby, bool isNullable, bool isIdentity, bool isClustered, bool isPrimaryKey) { _name = name; _type = type; _length = length; _sqlType = sqlType; _orderby = orderby; _isNullable = isNullable; _isIdentity = isIdentity; _isClustered = isClustered; _isPrimaryKey = isPrimaryKey; } public string Name { get { return _name; } set { _name = value; } } public SqlDbType Type { get { return _type; } set { _type = value; } } public int Length { get { return _length; } set { _length = value; } } public string SqlType { get { return _sqlType; } set { _sqlType = value; } } public DataSort Orderby { get { return _orderby; } set { _orderby = value; } } public bool IsNullable { get { return _isNullable; } set { _isNullable = value; } } public bool IsIdentity { get { return _isIdentity; } set { _isIdentity = value; } } public bool IsClustered { get { return _isClustered; } set { _isClustered = value; } } public bool IsPrimaryKey { get { return _isPrimaryKey; } set { _isPrimaryKey = value; } } } }
2881099/dotnetGen_postgresql
2,575
GenPg/plist-cil/PropertyListException.cs
// plist-cil - An open source library to parse and generate property lists for .NET // Copyright (C) 2015 Natalia Portillo // Copyright (C) 2016 Quamotion // // This code is based on: // plist - An open source library to parse and generate property lists // Copyright (C) 2014 Daniel Dreibrodt // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. using System; using System.Runtime.Serialization; namespace PList { /// <summary> /// The exception that is thrown when an property list file could not be processed correctly. /// </summary> public class PropertyListException : Exception { /// <summary> /// Initializes a new instance of the <see cref="PropertyListException"/> class. /// </summary> public PropertyListException() { } /// <summary> /// Initializes a new instance of the <see cref="PropertyListException"/> class. /// </summary> /// <param name="message"> /// The error message that explains the reason for the exception. /// </param> public PropertyListException(string message) : base(message) { } /// <summary> /// Initializes a new instance of the <see cref="PropertyListException"/> class. /// </summary> /// <param name="message"> /// The error message that explains the reason for the exception. /// </param> /// <param name="inner"> /// The exception that is the cause of the current exception, or <see langword="null"/> /// if no inner exception is specified. /// </param> public PropertyListException(string message, Exception inner) : base(message, inner) { } } }
2881099/dotnetGen_postgresql
3,798
GenPg/plist-cil/UID.cs
// plist-cil - An open source library to parse and generate property lists for .NET // Copyright (C) 2015 Natalia Portillo // // This code is based on: // plist - An open source library to parse and generate property lists // Copyright (C) 2014 Daniel Dreibrodt // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. using System; using System.Text; namespace PList { /// <summary> /// An UID. Only found in binary property lists that are keyed archives. /// </summary> /// @author Daniel Dreibrodt /// @author Natalia Portillo public class UID : NSObject { readonly byte[] bytes; readonly string name; /// <summary> /// Initializes a new instance of the <see cref="PList.UID"/> class. /// </summary> /// <param name="name">Name.</param> /// <param name="bytes">Bytes.</param> public UID(String name, byte[] bytes) { this.name = name; this.bytes = bytes; } /// <summary> /// Gets the bytes. /// </summary> /// <value>The bytes.</value> public byte[] Bytes { get { return bytes; } } /// <summary> /// Gets the name. /// </summary> /// <value>The name.</value> public string Name { get { return name; } } /// <summary> /// There is no XML representation specified for UIDs. /// In this implementation UIDs are represented as strings in the XML output. /// </summary> /// <param name="xml">The xml StringBuilder</param> /// <param name="level">The indentation level</param> internal override void ToXml(StringBuilder xml, int level) { Indent(xml, level); xml.Append("<string>"); foreach (byte b in bytes) xml.Append(String.Format("{0:x2}", b)); xml.Append("</string>"); } internal override void ToBinary(BinaryPropertyListWriter outPlist) { outPlist.Write(0x80 + bytes.Length - 1); outPlist.Write(bytes); } internal override void ToASCII(StringBuilder ascii, int level) { Indent(ascii, level); ascii.Append("\""); foreach (byte b in bytes) ascii.Append(String.Format("{0:x2}", b)); ascii.Append("\""); } internal override void ToASCIIGnuStep(StringBuilder ascii, int level) { ToASCII(ascii, level); } /// <summary> /// Determines whether the specified <see cref="PList.NSObject"/> is equal to the current <see cref="PList.UID"/>. /// </summary> /// <param name="obj">The <see cref="PList.NSObject"/> to compare with the current <see cref="PList.UID"/>.</param> /// <returns><c>true</c> if the specified <see cref="PList.NSObject"/> is equal to the current /// <see cref="PList.UID"/>; otherwise, <c>false</c>.</returns> public override bool Equals(NSObject obj) { if (!(obj is UID)) return false; if (((UID)obj).Name != name) return false; return ArrayEquals(((UID)obj).Bytes, bytes); } } }
2881099/dotnetGen_sqlserver
2,625
GenMs/Model/TableInfo.cs
using System; using System.Text; using System.Text.RegularExpressions; using System.Collections.Generic; namespace Model { [Serializable] public class TableInfo { private int _id; private string _owner; private string _name; private List<ColumnInfo> _columns = new List<ColumnInfo>(); private List<List<ColumnInfo>> _uniques = new List<List<ColumnInfo>>(); private List<List<ColumnInfo>> _indexes = new List<List<ColumnInfo>>(); private List<ForeignKeyInfo> _foreignKeys = new List<ForeignKeyInfo>(); private List<ColumnInfo> _identitys = new List<ColumnInfo>(); private List<ColumnInfo> _clustereds = new List<ColumnInfo>(); private List<ColumnInfo> _primaryKeys = new List<ColumnInfo>(); private string _Type; private bool _IsOutput; public TableInfo(int id, string owner, string name, string type) { _id = id; _owner = owner; _name = name; _Type = type; } public static string GetClassName(string name) { int rr = 0; string n = name.StartsWith("dbo.") ? name.Substring(4) : Regex.Replace(name, @"\.", delegate(Match m) { if (rr++ > 0) return m.Groups[0].Value; return "_"; }); return char.IsLetter(n, 0) ? n : string.Concat("_", n); } public static string GetEntryName(string name) { int idx = name.IndexOf('.'); return idx == -1 ? name : name.Substring(idx + 1); } public int Id { get { return _id; } } public string Owner { get { return _owner; } } public string Name { get { return _name; } } public string ClassName { get { return GetClassName(_owner.ToLower() + "." + _name); } } public string FullName { get { return string.Format("{0}.{1}", _owner, _name); } } public string Type { get { return _Type; } } public List<ColumnInfo> Columns { get { return _columns; } } public List<List<ColumnInfo>> Uniques { get { if (_uniques == null) { } return _uniques; } } public List<List<ColumnInfo>> Indexes { get { if (_indexes == null) { } return _indexes; } } public List<ForeignKeyInfo> ForeignKeys { get { if (_foreignKeys == null) { } return _foreignKeys; } } public List<ColumnInfo> PrimaryKeys { get { if (_primaryKeys == null) { } return _primaryKeys; } } public List<ColumnInfo> Clustereds { get { if (_clustereds == null) { } return _clustereds; } } public List<ColumnInfo> Identitys { get { if (_identitys == null) { } return _identitys; } } public bool IsOutput { get { return _IsOutput; } set { _IsOutput = value; } } } }
2881099/dotnetGen_sqlserver
5,499
GenMs/Lib/JSDecoder.cs
using System; using System.Text; using System.Text.RegularExpressions; public class JSDecoder { private const byte STATE_COPY_INPUT = 100; private const byte STATE_READLEN = 101; private const byte STATE_DECODE = 102; private const byte STATE_UNESCAPE = 103; private static byte[] _pickEncoding; private static byte[] _rawData; private static byte[] _digits = new byte[123]; private static byte[][] _transformed = new byte[3][]; static JSDecoder() { InitArrayData(); } private static void InitArrayData() { _pickEncoding = new byte[] { 1, 2, 0, 1, 2, 0, 2, 0, 0, 2, 0, 2, 1, 0, 2, 0, 1, 0, 2, 0, 1, 1, 2, 0, 0, 2, 1, 0, 2, 0, 0, 2, 1, 1, 0, 2, 0, 2, 0, 1, 0, 1, 1, 2, 0, 1, 0, 2, 1, 0, 2, 0, 1, 1, 2, 0, 0, 1, 1, 2, 0, 1, 0, 2 }; _rawData = new byte[] { 0x64,0x37,0x69, 0x50,0x7E,0x2C, 0x22,0x5A,0x65, 0x4A,0x45,0x72, 0x61,0x3A,0x5B, 0x5E,0x79,0x66, 0x5D,0x59,0x75, 0x5B,0x27,0x4C, 0x42,0x76,0x45, 0x60,0x63,0x76, 0x23,0x62,0x2A, 0x65,0x4D,0x43, 0x5F,0x51,0x33, 0x7E,0x53,0x42, 0x4F,0x52,0x20, 0x52,0x20,0x63, 0x7A,0x26,0x4A, 0x21,0x54,0x5A, 0x46,0x71,0x38, 0x20,0x2B,0x79, 0x26,0x66,0x32, 0x63,0x2A,0x57, 0x2A,0x58,0x6C, 0x76,0x7F,0x2B, 0x47,0x7B,0x46, 0x25,0x30,0x52, 0x2C,0x31,0x4F, 0x29,0x6C,0x3D, 0x69,0x49,0x70, 0x3F,0x3F,0x3F, 0x27,0x78,0x7B, 0x3F,0x3F,0x3F, 0x67,0x5F,0x51, 0x3F,0x3F,0x3F, 0x62,0x29,0x7A, 0x41,0x24,0x7E, 0x5A,0x2F,0x3B, 0x66,0x39,0x47, 0x32,0x33,0x41, 0x73,0x6F,0x77, 0x4D,0x21,0x56, 0x43,0x75,0x5F, 0x71,0x28,0x26, 0x39,0x42,0x78, 0x7C,0x46,0x6E, 0x53,0x4A,0x64, 0x48,0x5C,0x74, 0x31,0x48,0x67, 0x72,0x36,0x7D, 0x6E,0x4B,0x68, 0x70,0x7D,0x35, 0x49,0x5D,0x22, 0x3F,0x6A,0x55, 0x4B,0x50,0x3A, 0x6A,0x69,0x60, 0x2E,0x23,0x6A, 0x7F,0x09,0x71, 0x28,0x70,0x6F, 0x35,0x65,0x49, 0x7D,0x74,0x5C, 0x24,0x2C,0x5D, 0x2D,0x77,0x27, 0x54,0x44,0x59, 0x37,0x3F,0x25, 0x7B,0x6D,0x7C, 0x3D,0x7C,0x23, 0x6C,0x43,0x6D, 0x34,0x38,0x28, 0x6D,0x5E,0x31, 0x4E,0x5B,0x39, 0x2B,0x6E,0x7F, 0x30,0x57,0x36, 0x6F,0x4C,0x54, 0x74,0x34,0x34, 0x6B,0x72,0x62, 0x4C,0x25,0x4E, 0x33,0x56,0x30, 0x56,0x73,0x5E, 0x3A,0x68,0x73, 0x78,0x55,0x09, 0x57,0x47,0x4B, 0x77,0x32,0x61, 0x3B,0x35,0x24, 0x44,0x2E,0x4D, 0x2F,0x64,0x6B, 0x59,0x4F,0x44, 0x45,0x3B,0x21, 0x5C,0x2D,0x37, 0x68,0x41,0x53, 0x36,0x61,0x58, 0x58,0x7A,0x48, 0x79,0x22,0x2E, 0x09,0x60,0x50, 0x75,0x6B,0x2D, 0x38,0x4E,0x29, 0x55,0x3D,0x3F }; for (byte i = 0; i < 3; i++) _transformed[i] = new byte[288]; for (byte i = 31; i < 127; i++) for (byte j = 0; j < 3; j++) _transformed[j][_rawData[(i - 31) * 3 + j]] = i == 31 ? (byte)9 : i; for (byte i = 0; i < 26; i++) { _digits[65 + i] = i; _digits[97 + i] = (byte)(i + 26); } for (byte i = 0; i < 10; i++) _digits[48 + i] = (byte)(i + 52); _digits[43] = 62; _digits[47] = 63; } private static string UnEscape(string s) { string escapes = "#&!*$"; string escaped = "\r\n<>@"; if ((int)s.ToCharArray()[0] > 126) return s; if (escapes.IndexOf(s) != -1) return escaped.Substring(escapes.IndexOf(s), 1); return "?"; } private static int DecodeBase64(string s) { int val = 0; byte[] bs = Encoding.UTF8.GetBytes(s); val += ((int)_digits[bs[0]] << 2); val += (_digits[bs[1]] >> 4); val += (_digits[bs[1]] & 0xf) << 12; val += ((_digits[bs[2]] >> 2) << 8); val += ((_digits[bs[2]] & 0x3) << 22); val += (_digits[bs[3]] << 16); return val; } public static string Decode(string encodingString) { string marker = "#@~^"; int stringIndex = 0; int scriptIndex = -1; int unEncodingIndex = 0; string strChar = ""; string getCodeString = ""; int unEncodinglength = 0; int state = STATE_COPY_INPUT; string unEncodingString = ""; try { while (state != 0) { switch (state) { case STATE_COPY_INPUT: scriptIndex = encodingString.IndexOf(marker, stringIndex); if (scriptIndex != -1) { unEncodingString += encodingString.Substring(stringIndex, scriptIndex); scriptIndex += marker.Length; state = STATE_READLEN; } else { stringIndex = stringIndex == 0 ? 0 : stringIndex; unEncodingString += encodingString.Substring(stringIndex); state = 0; } break; case STATE_READLEN: getCodeString = encodingString.Substring(scriptIndex, 6); unEncodinglength = DecodeBase64(getCodeString); scriptIndex += 8; state = STATE_DECODE; break; case STATE_DECODE: if (unEncodinglength == 0) { stringIndex = scriptIndex + "DQgAAA==^#~@".Length; unEncodingIndex = 0; state = STATE_COPY_INPUT; } else { strChar = encodingString.Substring(scriptIndex, 1); if (strChar == "@") state = STATE_UNESCAPE; else { int b = (int)strChar.ToCharArray()[0]; if (b < 0xFF) { unEncodingString += (char)_transformed[_pickEncoding[unEncodingIndex % 64]][b]; unEncodingIndex++; } else { unEncodingString += strChar; } scriptIndex++; unEncodinglength--; } } break; case STATE_UNESCAPE: unEncodingString += UnEscape(encodingString.Substring(++scriptIndex, 1)); scriptIndex++; unEncodinglength -= 2; unEncodingIndex++; state = STATE_DECODE; break; } } } catch { } string Pattern; Pattern = "(JScript|VBscript).encode"; unEncodingString = Regex.Replace(unEncodingString, Pattern, "", RegexOptions.IgnoreCase); return unEncodingString; } }
2881099/dotnetGen_postgresql
21,071
GenPg/plist-cil/BinaryPropertyListParser.cs
// plist-cil - An open source library to parse and generate property lists for .NET // Copyright (C) 2015 Natalia Portillo // // This code is based on: // plist - An open source library to parse and generate property lists // Copyright (C) 2014 Daniel Dreibrodt // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. using System; using System.Text; using System.IO; namespace PList { /// <summary> /// <para> /// Parses property lists that are in Apple's binary format. /// Use this class when you are sure about the format of the property list. /// Otherwise use the PropertyListParser class. /// </para><para> /// Parsing is done by calling the static <see cref="Parse(byte[])"/>, /// <see cref="Parse(FileInfo)"/> and <see cref="Parse(Stream)"/> methods. /// </para> /// </summary> /// @author Daniel Dreibrodt /// @author Natalia Portillo public class BinaryPropertyListParser { /// <summary> /// Major version of the property list format /// </summary> int majorVersion; /// <summary> /// Minor version of the property list format /// </summary> int minorVersion; /// <summary> /// Property list in bytes /// </summary> byte[] bytes; /// <summary> /// Length of an object reference in bytes /// </summary> int objectRefSize; /// <summary> /// The table holding the information at which offset each object is found /// </summary> int[] offsetTable; /// <summary> /// Protected constructor so that instantiation is fully controlled by the /// static parse methods. /// </summary> /// <see cref="Parse(byte[])"/> protected BinaryPropertyListParser() { } /// <summary> /// Parses a binary property list from a byte array. /// </summary> /// <param name="data">The binary property list's data.</param> /// <returns>The root object of the property list. This is usually a NSDictionary but can also be a NSArray.</returns> /// <exception cref="PropertyListFormatException">When the property list's format could not be parsed.</exception> public static NSObject Parse(byte[] data) { BinaryPropertyListParser parser = new BinaryPropertyListParser(); return parser.DoParse(data); } /// <summary> /// Parses a binary property list from a byte array. /// </summary> /// <returns>The root object of the property list. This is usually a NSDictionary but can also be a NSArray.</returns> /// <param name="data">The binary property list's data.</param> /// <exception cref="PropertyListFormatException">When the property list's format could not be parsed.</exception> NSObject DoParse(byte[] data) { bytes = data; string magic = Encoding.ASCII.GetString(CopyOfRange(bytes, 0, 8)); if (!magic.StartsWith("bplist", StringComparison.Ordinal)) { throw new PropertyListFormatException("The given data is no binary property list. Wrong magic bytes: " + magic); } majorVersion = magic[6] - 0x30; //ASCII number minorVersion = magic[7] - 0x30; //ASCII number // 0.0 - OS X Tiger and earlier // 0.1 - Leopard // 0.? - Snow Leopard // 1.5 - Lion // 2.0 - Snow Lion if (majorVersion > 0) { // Version 1.0+ is not even supported by OS X's own parser throw new PropertyListFormatException("Unsupported binary property list format: v" + majorVersion + "." + minorVersion + ". " + "Version 1.0 and later are not yet supported."); } /* * Handle trailer, last 32 bytes of the file */ byte[] trailer = CopyOfRange(bytes, bytes.Length - 32, bytes.Length); //6 null bytes (index 0 to 5) int offsetSize = (int)ParseUnsignedInt(trailer, 6, 7); objectRefSize = (int)ParseUnsignedInt(trailer, 7, 8); int numObjects = (int)ParseUnsignedInt(trailer, 8, 16); int topObject = (int)ParseUnsignedInt(trailer, 16, 24); int offsetTableOffset = (int)ParseUnsignedInt(trailer, 24, 32); /* * Handle offset table */ offsetTable = new int[numObjects]; for (int i = 0; i < numObjects; i++) { byte[] offsetBytes = CopyOfRange(bytes, offsetTableOffset + i * offsetSize, offsetTableOffset + (i + 1) * offsetSize); offsetTable[i] = (int)ParseUnsignedInt(offsetBytes); } return ParseObject(topObject); } /// <summary> /// Parses a binary property list from an input stream. /// </summary> /// <param name="fs">The input stream that points to the property list's data.</param> /// <returns>The root object of the property list. This is usually a NSDictionary but can also be a NSArray.</returns> /// <exception cref="PropertyListFormatException">When the property list's format could not be parsed.</exception> public static NSObject Parse(Stream fs) { //Read all bytes into a list byte[] buf = PropertyListParser.ReadAll(fs); // Don't close the stream - that would be the responisibility of code that class // Parse return Parse(buf); } /// <summary> /// Parses a binary property list file. /// </summary> /// <param name="f">The binary property list file</param> /// <returns>The root object of the property list. This is usually a NSDictionary but can also be a NSArray.</returns> /// <exception cref="PropertyListFormatException">When the property list's format could not be parsed.</exception> public static NSObject Parse(FileInfo f) { return Parse(f.OpenRead()); } /// <summary> /// Parses an object inside the currently parsed binary property list. /// For the format specification check /// <a href="http://www.opensource.apple.com/source/CF/CF-855.17/CFBinaryPList.c"> /// Apple's binary property list parser implementation</a>. /// </summary> /// <returns>The parsed object.</returns> /// <param name="obj">The object ID.</param> /// <exception cref="PropertyListFormatException">When the property list's format could not be parsed.</exception> NSObject ParseObject(int obj) { int offset = offsetTable[obj]; byte type = bytes[offset]; int objType = (type & 0xF0) >> 4; //First 4 bits int objInfo = (type & 0x0F); //Second 4 bits switch (objType) { case 0x0: { //Simple switch (objInfo) { case 0x0: { //null object (v1.0 and later) return null; } case 0x8: { //false return new NSNumber(false); } case 0x9: { //true return new NSNumber(true); } case 0xC: { //URL with no base URL (v1.0 and later) //TODO Implement binary URL parsing (not yet even implemented in Core Foundation as of revision 855.17) break; } case 0xD: { //URL with base URL (v1.0 and later) //TODO Implement binary URL parsing (not yet even implemented in Core Foundation as of revision 855.17) break; } case 0xE: { //16-byte UUID (v1.0 and later) //TODO Implement binary UUID parsing (not yet even implemented in Core Foundation as of revision 855.17) break; } case 0xF: { //filler byte return null; } } break; } case 0x1: { //integer int length = (int)Math.Pow(2, objInfo); return new NSNumber(CopyOfRange(bytes, offset + 1, offset + 1 + length), NSNumber.INTEGER); } case 0x2: { //real int length = (int)Math.Pow(2, objInfo); return new NSNumber(CopyOfRange(bytes, offset + 1, offset + 1 + length), NSNumber.REAL); } case 0x3: { //Date if (objInfo != 0x3) { throw new PropertyListFormatException("The given binary property list contains a date object of an unknown type (" + objInfo + ")"); } return new NSDate(CopyOfRange(bytes, offset + 1, offset + 9)); } case 0x4: { //Data int[] lengthAndOffset = ReadLengthAndOffset(objInfo, offset); int length = lengthAndOffset[0]; int dataoffset = lengthAndOffset[1]; return new NSData(CopyOfRange(bytes, offset + dataoffset, offset + dataoffset + length)); } case 0x5: { //ASCII String int[] lengthAndOffset = ReadLengthAndOffset(objInfo, offset); int length = lengthAndOffset[0]; //Each character is 1 byte int stroffset = lengthAndOffset[1]; return new NSString(CopyOfRange(bytes, offset + stroffset, offset + stroffset + length), "ASCII"); } case 0x6: { //UTF-16-BE String int[] lengthAndOffset = ReadLengthAndOffset(objInfo, offset); int length = lengthAndOffset[0]; int stroffset = lengthAndOffset[1]; //UTF-16 characters can have variable length, but the Core Foundation reference implementation //assumes 2 byte characters, thus only covering the Basic Multilingual Plane length *= 2; return new NSString(CopyOfRange(bytes, offset + stroffset, offset + stroffset + length), "UTF-16BE"); } case 0x7: { //UTF-8 string (v1.0 and later) int[] lengthAndOffset = ReadLengthAndOffset(objInfo, offset); int strOffset = lengthAndOffset[1]; int characters = lengthAndOffset[0]; //UTF-8 characters can have variable length, so we need to calculate the byte length dynamically //by reading the UTF-8 characters one by one int length = CalculateUtf8StringLength(bytes, offset + strOffset, characters); return new NSString(CopyOfRange(bytes, offset + strOffset, offset + strOffset + length), "UTF-8"); } case 0x8: { //UID (v1.0 and later) int length = objInfo + 1; return new UID(obj.ToString(), CopyOfRange(bytes, offset + 1, offset + 1 + length)); } case 0xA: { //Array int[] lengthAndOffset = ReadLengthAndOffset(objInfo, offset); int length = lengthAndOffset[0]; int arrayOffset = lengthAndOffset[1]; NSArray array = new NSArray(length); for (int i = 0; i < length; i++) { int objRef = (int)ParseUnsignedInt(CopyOfRange(bytes, offset + arrayOffset + i * objectRefSize, offset + arrayOffset + (i + 1) * objectRefSize)); array.Add(ParseObject(objRef)); } return array; } case 0xB: { //Ordered set (v1.0 and later) int[] lengthAndOffset = ReadLengthAndOffset(objInfo, offset); int length = lengthAndOffset[0]; int contentOffset = lengthAndOffset[1]; NSSet set = new NSSet(true); for (int i = 0; i < length; i++) { int objRef = (int)ParseUnsignedInt(CopyOfRange(bytes, offset + contentOffset + i * objectRefSize, offset + contentOffset + (i + 1) * objectRefSize)); set.AddObject(ParseObject(objRef)); } return set; } case 0xC: { //Set (v1.0 and later) int[] lengthAndOffset = ReadLengthAndOffset(objInfo, offset); int length = lengthAndOffset[0]; int contentOffset = lengthAndOffset[1]; NSSet set = new NSSet(); for (int i = 0; i < length; i++) { int objRef = (int)ParseUnsignedInt(CopyOfRange(bytes, offset + contentOffset + i * objectRefSize, offset + contentOffset + (i + 1) * objectRefSize)); set.AddObject(ParseObject(objRef)); } return set; } case 0xD: { //Dictionary int[] lengthAndOffset = ReadLengthAndOffset(objInfo, offset); int length = lengthAndOffset[0]; int contentOffset = lengthAndOffset[1]; //System.out.println("Parsing dictionary #"+obj); NSDictionary dict = new NSDictionary(); for (int i = 0; i < length; i++) { int keyRef = (int)ParseUnsignedInt(CopyOfRange(bytes, offset + contentOffset + i * objectRefSize, offset + contentOffset + (i + 1) * objectRefSize)); int valRef = (int)ParseUnsignedInt(CopyOfRange(bytes, offset + contentOffset + (length * objectRefSize) + i * objectRefSize, offset + contentOffset + (length * objectRefSize) + (i + 1) * objectRefSize)); NSObject key = ParseObject(keyRef); NSObject val = ParseObject(valRef); dict.Add(key.ToString(), val); } return dict; } default: { Console.WriteLine("WARNING: The given binary property list contains an object of unknown type (" + objType + ")"); break; } } return null; } /// <summary> /// Reads the length for arrays, sets and dictionaries. /// </summary> /// <returns>An array with the length two. First entry is the length, second entry the offset at which the content starts.</returns> /// <param name="objInfo">Object information byte.</param> /// <param name="offset">Offset in the byte array at which the object is located.</param> int[] ReadLengthAndOffset(int objInfo, int offset) { int lengthValue = objInfo; int offsetValue = 1; if (objInfo == 0xF) { int int_type = bytes[offset + 1]; int intType = (int_type & 0xF0) >> 4; if (intType != 0x1) { Console.WriteLine("BinaryPropertyListParser: Length integer has an unexpected type" + intType + ". Attempting to parse anyway..."); } int intInfo = int_type & 0x0F; int intLength = (int)Math.Pow(2, intInfo); offsetValue = 2 + intLength; if (intLength < 3) { lengthValue = (int)ParseUnsignedInt(CopyOfRange(bytes, offset + 2, offset + 2 + intLength)); } else { // BigInteger is Little-Endian in .NET, swap the thing. // Also BigInteger is of .NET 4.0, maybe there's a better way to do it. byte[] bigEBigInteger = CopyOfRange(bytes, offset + 2, offset + 2 + intLength); byte[] litEBigInteger = new byte[bigEBigInteger.Length + 1]; for (int i = 0, j = bigEBigInteger.Length - 1; i < bigEBigInteger.Length && j >= 0; i++, j--) litEBigInteger[i] = bigEBigInteger[j]; litEBigInteger[litEBigInteger.Length - 1] = (byte)0x00; // Be sure to get unsigned BigInteger lengthValue = (int)new System.Numerics.BigInteger(litEBigInteger); } } return new[] { lengthValue, offsetValue }; } /// <summary> /// Calculates the length in bytes of the UTF-8 string. /// </summary> /// <returns>The UTF-8 string length.</returns> /// <param name="bytes">Array containing the UTF-8 string.</param> /// <param name="offset">Offset in the array where the UTF-8 string resides.</param> /// <param name="numCharacters">How many UTF-8 characters are in the string.</param> int CalculateUtf8StringLength(byte[] bytes, int offset, int numCharacters) { int length = 0; for (int i = 0; i < numCharacters; i++) { int tempOffset = offset + length; if (bytes.Length <= tempOffset) { //WARNING: Invalid UTF-8 string, fall back to length = number of characters return numCharacters; } if (bytes[tempOffset] < 0x80) { length++; } if (bytes[tempOffset] < 0xC2) { //Invalid value (marks continuation byte), fall back to length = number of characters return numCharacters; } else if (bytes[tempOffset] < 0xE0) { if ((bytes[tempOffset + 1] & 0xC0) != 0x80) { //Invalid continuation byte, fall back to length = number of characters return numCharacters; } length += 2; } else if (bytes[tempOffset] < 0xF0) { if ((bytes[tempOffset + 1] & 0xC0) != 0x80 || (bytes[tempOffset + 2] & 0xC0) != 0x80) { //Invalid continuation byte, fall back to length = number of characters return numCharacters; } length += 3; } else if (bytes[tempOffset] < 0xF5) { if ((bytes[tempOffset + 1] & 0xC0) != 0x80 || (bytes[tempOffset + 2] & 0xC0) != 0x80 || (bytes[tempOffset + 3] & 0xC0) != 0x80) { //Invalid continuation byte, fall back to length = number of characters return numCharacters; } length += 4; } } return length; } /// <summary> /// Parses an unsigned integers from a byte array. /// </summary> /// <returns>The byte array containing the unsigned integer.</returns> /// <param name="bytes">The unsigned integer represented by the given bytes.</param> public static long ParseUnsignedInt(byte[] bytes) { long l = 0; foreach (byte b in bytes) { l <<= 8; #pragma warning disable 675 l |= b & 0xFF; #pragma warning restore 675 } l &= 0xFFFFFFFFL; return l; } /// <summary> /// Parses an unsigned integer from a byte array. /// </summary> /// <returns>The unsigned integer represented by the given bytes.</returns> /// <param name="bytes">The byte array containing the unsigned integer.</param> /// <param name="startIndex">Beginning of the unsigned int in the byte array.</param> /// <param name="endIndex">End of the unsigned int in the byte array.</param> public static long ParseUnsignedInt(byte[] bytes, int startIndex, int endIndex) { long l = 0; for (int i = startIndex; i < endIndex; i++) { l <<= 8; #pragma warning disable 675 l |= bytes[i] & 0xFF; #pragma warning restore 675 } l &= 0xFFFFFFFFL; return l; } /// <summary> /// Parses a long from a (big-endian) byte array. /// </summary> /// <returns>The long integer represented by the given bytes.</returns> /// <param name="bytes">The bytes representing the long integer.</param> public static long ParseLong(byte[] bytes) { long l = 0; foreach (byte b in bytes) { l <<= 8; #pragma warning disable 675 l |= b & 0xFF; #pragma warning restore 675 } return l; } /// <summary> /// Parses a long from a (big-endian) byte array. /// </summary> /// <returns>The long integer represented by the given bytes.</returns> /// <param name="bytes">The bytes representing the long integer.</param> /// <param name="startIndex">Beginning of the long in the byte array.</param> /// <param name="endIndex">End of the long in the byte array.</param> public static long ParseLong(byte[] bytes, int startIndex, int endIndex) { long l = 0; for (int i = startIndex; i < endIndex; i++) { l <<= 8; #pragma warning disable 675 l |= bytes[i] & 0xFF; #pragma warning restore 675 } return l; } /// <summary> /// Parses a double from a (big-endian) byte array. /// </summary> /// <returns>The double represented by the given bytes.</returns> /// <param name="bytes">The bytes representing the double.</param> public static double ParseDouble(byte[] bytes) { if (bytes.Length == 8) return BitConverter.Int64BitsToDouble(ParseLong(bytes)); if (bytes.Length == 4) return BitConverter.ToSingle(BitConverter.GetBytes(ParseLong(bytes)), 0); throw new ArgumentException("bad byte array length " + bytes.Length); } /// <summary> /// Parses a double from a (big-endian) byte array. /// </summary> /// <returns>The double represented by the given bytes.</returns> /// <param name="bytes">The bytes representing the double.</param> /// <param name="startIndex">Beginning of the double in the byte array.</param> /// <param name="endIndex">End of the double in the byte array.</param> public static double ParseDouble(byte[] bytes, int startIndex, int endIndex) { if (endIndex - startIndex == 8) return BitConverter.Int64BitsToDouble(ParseLong(bytes, startIndex, endIndex)); if (endIndex - startIndex == 4) return BitConverter.ToSingle(BitConverter.GetBytes(ParseLong(bytes, startIndex, endIndex)), 0); throw new ArgumentException("endIndex (" + endIndex + ") - startIndex (" + startIndex + ") != 4 or 8"); } /// <summary> /// Copies a part of a byte array into a new array. /// </summary> /// <returns>The copied array.</returns> /// <param name="src">The source array.</param> /// <param name="startIndex">The index from which to start copying.</param> /// <param name="endIndex">The index until which to copy.</param> public static byte[] CopyOfRange(byte[] src, int startIndex, int endIndex) { int length = endIndex - startIndex; if (length < 0) { throw new ArgumentOutOfRangeException("startIndex (" + startIndex + ")" + " > endIndex (" + endIndex + ")"); } byte[] dest = new byte[length]; Array.Copy(src, startIndex, dest, 0, length); return dest; } } }
2881099/dotnetGen_sqlserver
7,555
GenMs/Lib/Lib.cs
using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Text; using System.Net; using System.Threading; using System.Runtime.Serialization.Json; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using PList; using System.Runtime.Serialization.Formatters.Binary; public delegate void AnonymousHandler(); /// <summary> /// 常用函数库 /// </summary> public class Lib { /// <summary> /// 当前程序类型是否为 Web Application /// </summary> public static string HtmlEncode(object input) { return WebUtility.HtmlEncode(string.Concat(input)); } public static string HtmlDecode(object input) { return WebUtility.HtmlDecode(string.Concat(input)); } public static string UrlEncode(object input) { return WebUtility.UrlEncode(string.Concat(input)); } public static string UrlDecode(object input) { return WebUtility.UrlDecode(string.Concat(input)); } public static string JSDecode(string input) { return JSDecoder.Decode(input); } #region 弥补 String.PadRight 和 String.PadLeft 对中文的 Bug public static string PadRight(object text, int length) { return PadRightLeft(text, length, ' ', true); } public static string PadRight(object text, char paddingChar, int length) { return PadRightLeft(text, length, paddingChar, true); } public static string PadLeft(object text, int length) { return PadRightLeft(text, length, ' ', false); } public static string PadLeft(object text, char paddingChar, int length) { return PadRightLeft(text, length, paddingChar, false); } static string PadRightLeft(object text, int length, char paddingChar, bool isRight) { string str = string.Concat(text); int len2 = Encoding.UTF8.GetBytes(str).Length; for (int a = 0; a < length - len2; a++) if (isRight) str += paddingChar; else str = paddingChar + str; return str; } #endregion #region 序列化/反序列化(二进制) public static byte[] Serialize(object obj) { var formatter = new BinaryFormatter(); MemoryStream ms = new MemoryStream(); formatter.Serialize(ms, obj); byte[] data = ms.ToArray(); ms.Close(); return data; //using (MemoryStream ms = new MemoryStream()) { // DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(object)); // js.WriteObject(ms, obj); // return ms.ToArray(); //} } public static object Deserialize(byte[] stream) { var formatter = new BinaryFormatter(); MemoryStream ms = new MemoryStream(stream); object obj = formatter.Deserialize(ms); ms.Close(); return obj; //using (MemoryStream ms = new MemoryStream(stream)) { // DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(object)); // return js.ReadObject(ms); //} } #endregion /// <summary> /// 将 plist 格式的 xml 内容,解析成 Newtowsoft.Json JObject 对象来访问 /// </summary> /// <param name="plist">plist 格式的 xml 内容</param> /// <returns>JObject</returns> public static JObject ParsePListToJson(string plist) { NSObject obj = XmlPropertyListParser.Parse(Encoding.UTF8.GetBytes(plist)); string json = JsonConvert.SerializeObject(obj.ToObject()); return JsonConvert.DeserializeObject<JObject>(json); } /// <summary> /// 重试某过程 maxError 次,直到成功或失败 /// </summary> /// <param name="handler">托管函数</param> /// <param name="maxError">允许失败的次数</param> /// <returns>如果执行成功,则返回 null, 否则返回该错误对象</returns> public static Exception Trys(AnonymousHandler handler, int maxError) { if (handler != null) { Exception ex = null; for (int a = 0; a < maxError; a++) { try { handler(); return null; } catch (Exception e) { ex = e; } } return ex; } return null; } /// <summary> /// 延迟 milliSecond 毫秒后执行 handler,与 javascript 里的 setTimeout 相似 /// </summary> /// <param name="handler">托管函数</param> /// <param name="milliSecond">毫秒</param> public static void SetTimeout(AnonymousHandler handler, int milliSecond) { new Timer((a) => { try { handler(); } catch { } }, null, milliSecond, milliSecond); } /// <summary> /// 将服务器端数据转换成安全的JS字符串 /// </summary> /// <param name="input">一个服务器端变量或字符串</param> /// <returns>安全的JS字符串</returns> public static string GetJsString(object input) { if (input == null) return string.Empty; return string.Concat(input).Replace("\\", "\\\\").Replace("\r", "\\r").Replace("\n", "\\n").Replace("'", "\\'"); } static Dictionary<string, Type> _InvokeMethod_cache_type = new Dictionary<string, Type>(); static object _InvokeMethod_cache_type_lock = new object(); public static object InvokeMethod(string typeName, string method, params object[] parms) { Type type; if (!_InvokeMethod_cache_type.TryGetValue(typeName, out type)) { type = System.Type.GetType(typeName); lock (_InvokeMethod_cache_type_lock) { if (!_InvokeMethod_cache_type.TryGetValue(typeName, out type)) _InvokeMethod_cache_type.Add(typeName, type); } } return type.GetMethod(method).Invoke(null, parms); } /// <summary> /// 获取对象属性 /// </summary> /// <param name="obj">对象</param> /// <param name="property">属性,此属性可为多级属性,如:newsInfo.newsClassInfo...</param> /// <returns>对象的(子)属性</returns> public static object EvaluateValue(object obj, string property) { if (obj == null) return null; string prop = property; object ret = string.Empty; if (property.Contains(".")) { prop = property.Substring(0, property.IndexOf(".")); PropertyInfo propa = EvaluateValue_GetProperty(obj, prop); if (propa != null) { object obja = propa.GetValue(obj, null); ret = EvaluateValue(obja, property.Substring(property.IndexOf(".") + 1)); } } else { PropertyInfo propa = EvaluateValue_GetProperty(obj, prop); if (propa != null) { ret = propa.GetValue(obj, null); } } return ret; } private static PropertyInfo EvaluateValue_GetProperty(object obj, string property) { if (obj == null) return null; Type type = obj.GetType(); PropertyInfo ret = type.GetProperty(property); if (ret == null) { PropertyInfo[] pis = type.GetProperties(); foreach (PropertyInfo pi in pis) { if (string.Compare(pi.Name, property, true) == 0) { ret = pi; break; } } } return ret; } /// <summary> /// (安全转换)对象/值转换类型 /// </summary> /// <typeparam name="T">转换后的类型</typeparam> /// <param name="input">转换的对象</param> /// <returns>转换后的对象/值</returns> public static T ConvertTo<T>(object input) { return ConvertTo<T>(input, default(T)); } public static T ConvertTo<T>(object input, T defaultValue) { if (input == null) return defaultValue; object obj = null; if (defaultValue is System.Byte || defaultValue is System.Decimal || defaultValue is System.Int16 || defaultValue is System.Int32 || defaultValue is System.Int64 || defaultValue is System.SByte || defaultValue is System.Single || defaultValue is System.UInt16 || defaultValue is System.UInt32 || defaultValue is System.UInt64) { decimal trydec = 0; if (decimal.TryParse(string.Concat(input), out trydec)) obj = trydec; } else { if (defaultValue is System.DateTime) { DateTime trydt = DateTime.Now; if (DateTime.TryParse(string.Concat(input), out trydt)) obj = trydt; } else { if (defaultValue is System.Boolean) { bool trybool = false; if (bool.TryParse(string.Concat(input), out trybool)) obj = trybool; } else { if (defaultValue is System.Double) { double trydb = 0; if (double.TryParse(string.Concat(input), out trydb)) obj = trydb; } else { obj = input; } } } } try { if (obj != null) return (T)Convert.ChangeType(obj, typeof(T)); } catch { } return defaultValue; } }
2881099/dotnetGen_sqlserver
3,888
GenMs/Lib/IniHelper.cs
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.IO; public class IniHelper { private static Dictionary<string, object> _cache = new Dictionary<string, object>(); private static Dictionary<string, FileSystemWatcher> _watcher = new Dictionary<string, FileSystemWatcher>(); private static object _lock = new object(); private static object loadAndCache(string path) { path = TranslateUrl(path); object ret = null; if (!_cache.TryGetValue(path, out ret)) { object value2 = LoadIniNotCache(path); string dir = Path.GetDirectoryName(path); string name = Path.GetFileName(path); FileSystemWatcher fsw = new FileSystemWatcher(dir, name); fsw.IncludeSubdirectories = false; fsw.Changed += watcher_handler; fsw.Renamed += watcher_handler; fsw.EnableRaisingEvents = false; lock (_lock) { if (!_cache.TryGetValue(path, out ret)) { _cache.Add(path, ret = value2); _watcher.Add(path, fsw); fsw.EnableRaisingEvents = true; } else { fsw.Dispose(); } } } return ret; } private static void watcher_handler(object sender, FileSystemEventArgs e) { lock (_lock) { _cache.Remove(e.FullPath); FileSystemWatcher fsw = null; if (_watcher.TryGetValue(e.FullPath, out fsw)) { fsw.EnableRaisingEvents = false; fsw.Dispose(); } } } public static Dictionary<string, NameValueCollection> LoadIni(string path) { return loadAndCache(path) as Dictionary<string, NameValueCollection>; } public static Dictionary<string, NameValueCollection> LoadIniNotCache(string path) { Dictionary<string, NameValueCollection> ret = new Dictionary<string, NameValueCollection>(); string[] lines = ReadTextFile(path).Split(new string[] { "\n" }, StringSplitOptions.None); string key = ""; foreach (string line2 in lines) { string line = line2.Trim(); if (string.IsNullOrEmpty(line) || line.StartsWith("#") || line.StartsWith(";")) continue; Match m = Regex.Match(line, @"^\[([^\]]+)\]$"); if (m.Success) { key = m.Groups[1].Value; continue; } if (!ret.ContainsKey(key)) ret.Add(key, new NameValueCollection()); string[] kv = line.Split(new char[] { '=' }, 2); if (!string.IsNullOrEmpty(kv[0])) { ret[key][kv[0]] = kv.Length > 1 ? kv[1] : null; } } return ret; } public static string ReadTextFile(string path) { byte[] bytes = ReadFile(path); return Encoding.UTF8.GetString(bytes).TrimStart((char)65279); } public static byte[] ReadFile(string path) { if (File.Exists(path)) { string destFileName = Path.GetTempFileName(); File.Copy(path, destFileName, true); int read = 0; byte[] data = new byte[1024]; using (MemoryStream ms = new MemoryStream()) { using (FileStream fs = new FileStream(destFileName, FileMode.OpenOrCreate, FileAccess.Read)) { do { read = fs.Read(data, 0, data.Length); if (read <= 0) break; ms.Write(data, 0, read); } while (true); } File.Delete(destFileName); data = ms.ToArray(); } return data; } return new byte[] { }; } public static string TranslateUrl(string url) { return TranslateUrl(url, null); } public static string TranslateUrl(string url, string baseDir) { if (string.IsNullOrEmpty(baseDir)) baseDir = AppContext.BaseDirectory + "/"; if (string.IsNullOrEmpty(url)) return Path.GetDirectoryName(baseDir); if (url.StartsWith("~/")) url = url.Substring(1); if (url.StartsWith("/")) return Path.GetFullPath(Path.Combine(Path.GetDirectoryName(baseDir), url.TrimStart('/'))); if (url.StartsWith("\\")) return Path.GetFullPath(Path.Combine(Path.GetDirectoryName(baseDir), url.TrimStart('\\'))); if (url.IndexOf(":\\") != -1) return url; return Path.GetFullPath(Path.Combine(Path.GetDirectoryName(baseDir), url)); } }
2881099/dotnetGen_sqlserver
3,815
GenMs/WinFormClass/WorkQueue.cs
using System; using System.Collections.Generic; using System.Text; using System.Threading; public class WorkQueue : WorkQueue<AnonymousHandler> { public WorkQueue() : this(16, -1) { } public WorkQueue(int thread) : this(thread, -1) { } public WorkQueue(int thread, int capacity) { base.Thread = thread; base.Capacity = capacity; base.Process += delegate(AnonymousHandler ah) { ah(); }; } } public class WorkQueue<T> : IDisposable { public delegate void WorkQueueProcessHandler(T item); public event WorkQueueProcessHandler Process; private int _thread = 16; private int _capacity = -1; private int _work_index = 0; private Dictionary<int, WorkInfo> _works = new Dictionary<int, WorkInfo>(); private object _works_lock = new object(); private Queue<T> _queue = new Queue<T>(); private object _queue_lock = new object(); public WorkQueue() : this(16, -1) { } public WorkQueue(int thread) : this(thread, -1) { } public WorkQueue(int thread, int capacity) { _thread = thread; _capacity = capacity; } public void Enqueue(T item) { lock (_queue_lock) { if (_capacity > 0 && _queue.Count >= _capacity) return; _queue.Enqueue(item); } lock (_works_lock) { foreach (WorkInfo w in _works.Values) { if (w.IsWaiting) { w.Set(); return; } } } if (_works.Count < _thread) { if (_queue.Count > 0) { int index = 0; lock (_works_lock) { index = _work_index++; _works.Add(index, new WorkInfo()); } new Thread(delegate() { WorkInfo work = _works[index]; while (true) { List<T> de = new List<T>(); if (_queue.Count > 0) { lock (_queue_lock) { if (_queue.Count > 0) { de.Add(_queue.Dequeue()); } } } if (de.Count > 0) { try { this.OnProcess(de[0]); } catch { } } if (_queue.Count == 0) { work.WaitOne(TimeSpan.FromSeconds(20)); if (_queue.Count == 0) { break; } } } lock (_works_lock) { _works.Remove(index); } work.Dispose(); }).Start(); } } } protected virtual void OnProcess(T item) { if (Process != null) { Process(item); } } #region IDisposable 成员 public void Dispose() { lock (_queue_lock) { _queue.Clear(); } lock (_works_lock) { foreach (WorkInfo w in _works.Values) { w.Dispose(); } } } #endregion public int Thread { get { return _thread; } set { if (_thread != value) { _thread = value; } } } public int Capacity { get { return _capacity; } set { if (_capacity != value) { _capacity = value; } } } public int UsedThread { get { return _works.Count; } } public int Queue { get { return _queue.Count; } } public string Statistics { get { string value = string.Format(@"线程:{0}/{1} 队列:{2} ", _works.Count, _thread, _queue.Count); int[] keys = new int[_works.Count]; try { _works.Keys.CopyTo(keys, 0); } catch { lock (_works_lock) { keys = new int[_works.Count]; _works.Keys.CopyTo(keys, 0); } } foreach (int k in keys) { WorkInfo w = null; if (_works.TryGetValue(k, out w)) { value += string.Format(@"线程{0}:{1} ", k, w.IsWaiting); } } return value; } } class WorkInfo : IDisposable { private ManualResetEvent _reset = new ManualResetEvent(false); private bool _isWaiting = false; public void WaitOne(TimeSpan timeout) { try { _reset.Reset(); _isWaiting = true; _reset.WaitOne(timeout); } catch { } } public void Set() { try { _isWaiting = false; _reset.Set(); } catch { } } public bool IsWaiting { get { return _isWaiting; } } #region IDisposable 成员 public void Dispose() { this.Set(); } #endregion } }
2881099/dotnetGen_postgresql
9,398
GenPg/plist-cil/NSString.cs
// plist-cil - An open source library to parse and generate property lists for .NET // Copyright (C) 2015 Natalia Portillo // // This code is based on: // plist - An open source library to parse and generate property lists // Copyright (C) 2014 Daniel Dreibrodt // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. using System; using System.Text; namespace PList { /// <summary> /// A NSString contains a string. /// </summary> /// @author Daniel Dreibrodt /// @author Natalia Portillo public class NSString : NSObject, IComparable { string content; /// <summary> /// Creates a NSString from its binary representation. /// </summary> /// <param name="bytes">The binary representation.</param> /// <param name="encoding">The encoding of the binary representation, the name of a supported charset.</param> /// <exception cref="ArgumentException">The encoding charset is invalid or not supported by the underlying platform.</exception> public NSString(byte[] bytes, String encoding) { Encoding enc = Encoding.GetEncoding(encoding); content = enc.GetString(bytes); } /// <summary> /// Creates a NSString from a string. /// </summary> /// <param name="text">The string that will be contained in the NSString.</param> public NSString(string text) { content = text; } /// <summary> /// Gets this strings content. /// </summary> /// <returns>This NSString as .NET string object.</returns> public string GetContent() { return content; } /// <summary> /// Sets the contents of this string. /// </summary> /// <param name="c">The new content of this string object.</param> public void SetContent(string c) { content = c; } /// <summary> /// Appends a string to this string. /// </summary> /// <param name="s">The string to append.</param> public void Append(NSString s) { Append(s.GetContent()); } /// <summary> /// Appends a string to this string. /// </summary> /// <param name="s">The string to append.</param> public void Append(string s) { content += s; } /// <summary> /// Prepends a string to this string. /// </summary> /// <param name="s">The string to prepend.</param> public void Prepend(string s) { content = s + content; } /// <summary> /// Prepends a string to this string. /// </summary> /// <param name="s">The string to prepend.</param> public void Prepend(NSString s) { Prepend(s.GetContent()); } /// <summary> /// Determines whether the specified <see cref="System.Object"/> is equal to the current <see cref="PList.NSString"/>. /// </summary> /// <param name="obj">The <see cref="System.Object"/> to compare with the current <see cref="PList.NSString"/>.</param> /// <returns><c>true</c> if the specified <see cref="System.Object"/> is equal to the current /// <see cref="PList.NSString"/>; otherwise, <c>false</c>.</returns> public override bool Equals(Object obj) { if (!(obj is NSString)) return false; return content.Equals(((NSString)obj).content); } /// <summary> /// Serves as a hash function for a <see cref="PList.NSString"/> object. /// </summary> /// <returns>A hash code for this instance that is suitable for use in hashing algorithms and data structures such as a /// hash table.</returns> public override int GetHashCode() { return content.GetHashCode(); } /// <summary> /// The textual representation of this NSString. /// </summary> /// <returns>The NSString's contents.</returns> public override string ToString() { return content; } static Encoding asciiEncoder, utf16beEncoder, utf8Encoder; internal override void ToXml(StringBuilder xml, int level) { Indent(xml, level); xml.Append("<string>"); //Make sure that the string is encoded in UTF-8 for the XML output lock (typeof(NSString)) { if (utf8Encoder == null) utf8Encoder = Encoding.GetEncoding("UTF-8"); try { byte[] bytes = utf8Encoder.GetBytes(content); content = utf8Encoder.GetString(bytes); } catch (Exception ex) { throw new PropertyListException("Could not encode the NSString into UTF-8: " + ex.Message); } } //According to http://www.w3.org/TR/REC-xml/#syntax node values must not //contain the characters < or &. Also the > character should be escaped. if (content.Contains("&") || content.Contains("<") || content.Contains(">")) { xml.Append("<![CDATA["); xml.Append(content.Replace("]]>", "]]]]><![CDATA[>")); xml.Append("]]>"); } else { xml.Append(content); } xml.Append("</string>"); } internal override void ToBinary(BinaryPropertyListWriter outPlist) { int kind; byte[] byteBuf; lock (typeof(NSString)) { if (asciiEncoder == null) // Not much use, because some characters do not fallback to exception, even if not ASCII asciiEncoder = Encoding.GetEncoding("ascii", EncoderFallback.ExceptionFallback, DecoderFallback.ExceptionFallback); if (IsASCIIEncodable(content)) { kind = 0x5; // standard ASCII byteBuf = asciiEncoder.GetBytes(content); } else { if (utf16beEncoder == null) utf16beEncoder = Encoding.BigEndianUnicode; kind = 0x6; // UTF-16-BE byteBuf = utf16beEncoder.GetBytes(content); } } outPlist.WriteIntHeader(kind, content.Length); outPlist.Write(byteBuf); } internal override void ToASCII(StringBuilder ascii, int level) { Indent(ascii, level); ascii.Append("\""); //According to https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/PropertyLists/OldStylePlists/OldStylePLists.html //non-ASCII characters are not escaped but simply written into the //file, thus actually violating the ASCII plain text format. //We will escape the string anyway because current Xcode project files (ASCII property lists) also escape their strings. ascii.Append(EscapeStringForASCII(content)); ascii.Append("\""); } internal override void ToASCIIGnuStep(StringBuilder ascii, int level) { Indent(ascii, level); ascii.Append("\""); ascii.Append(EscapeStringForASCII(content)); ascii.Append("\""); } /// <summary> /// Escapes a string for use in ASCII property lists. /// </summary> /// <returns>The unescaped string.</returns> /// <param name="s">S.</param> internal static string EscapeStringForASCII(string s) { string outString = ""; char[] cArray = s.ToCharArray(); foreach (char c in cArray) { if (c > 127) { //non-ASCII Unicode outString += "\\U"; string hex = String.Format("{0:x}", c); while (hex.Length < 4) hex = "0" + hex; outString += hex; } else if (c == '\\') { outString += "\\\\"; } else if (c == '\"') { outString += "\\\""; } else if (c == '\b') { outString += "\\b"; } else if (c == '\n') { outString += "\\n"; } else if (c == '\r') { outString += "\\r"; } else if (c == '\t') { outString += "\\t"; } else { outString += c; } } return outString; } /// <summary> /// Compares the current <see cref="PList.NSString"/> to the specified object. /// </summary> /// <returns>A 32-bit signed integer that indicates the lexical relationship between the two comparands.</returns> /// <param name="o">Object to compare to the current <see cref="PList.NSString"/>.</param> public int CompareTo(Object o) { if (o is NSString) return string.Compare(GetContent(), ((NSString)o).GetContent(), StringComparison.Ordinal); if (o is String) return string.Compare(GetContent(), ((String)o), StringComparison.Ordinal); return -1; } /// <summary> /// Determines whether the specified <see cref="PList.NSObject"/> is equal to the current <see cref="PList.NSString"/>. /// </summary> /// <param name="obj">The <see cref="PList.NSObject"/> to compare with the current <see cref="PList.NSString"/>.</param> /// <returns><c>true</c> if the specified <see cref="PList.NSObject"/> is equal to the current /// <see cref="PList.NSString"/>; otherwise, <c>false</c>.</returns> public override bool Equals(NSObject obj) { if (!(obj is NSString)) return false; return content == ((NSString)obj).content; } internal static bool IsASCIIEncodable(string text) { foreach (char c in text) if ((int)c > 0x7F) return false; return true; } } }
2881099/dotnetGen_postgresql
7,077
GenPg/plist-cil/NSData.cs
// plist-cil - An open source library to parse and generate property lists for .NET // Copyright (C) 2015 Natalia Portillo // // This code is based on: // plist - An open source library to parse and generate property lists // Copyright (C) 2014 Daniel Dreibrodt // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. using System; using System.IO; using System.Text; namespace PList { /// <summary> /// NSData objects are wrappers for byte buffers /// </summary> /// @author Daniel Dreibrodt /// @author Natalia Portillo public class NSData : NSObject { readonly byte[] bytes; /// <summary> /// Creates the NSData object from the binary representation of it. /// </summary> /// <param name="bytes">The raw data contained in the NSData object.</param> public NSData(byte[] bytes) { this.bytes = bytes; } /// <summary> /// Creates a NSData object from its textual representation, which is a Base64 encoded amount of bytes. /// </summary> /// <param name="base64">The Base64 encoded contents of the NSData object.</param> /// <exception cref="FormatException">When the given string is not a proper Base64 formatted string.</exception> public NSData(string base64) { bytes = Convert.FromBase64String(base64); } /// <summary> /// Creates a NSData object from a file. Using the files contents as the contents of this NSData object. /// </summary> /// <param name="file">The file containing the data.</param> /// <exception cref="FileNotFoundException">If the file could not be found.</exception> /// <exception cref="IOException">If the file could not be read.</exception> public NSData(FileInfo file) { bytes = new byte[(int)file.Length]; using (FileStream raf = file.OpenRead()) { raf.Read(bytes, 0, (int)file.Length); } } /// <summary> /// The bytes contained in this NSData object. /// </summary> /// <value>The data as bytes</value> public byte[] Bytes { get { return bytes; } } /// <summary> /// Gets the amount of data stored in this object. /// </summary> /// <value>The number of bytes contained in this object.</value> public int Length { get { return bytes.Length; } } /// <summary> /// Loads the bytes from this NSData object into a byte buffer. /// </summary> /// <param name="buf">The byte buffer which will contain the data</param> /// <param name="length">The amount of data to copy</param> public void GetBytes(MemoryStream buf, int length) { buf.Write(bytes, 0, Math.Min(bytes.Length, length)); } /// <summary> /// Loads the bytes from this NSData object into a byte buffer. /// </summary> /// <param name="buf">The byte buffer which will contain the data</param> /// <param name="rangeStart">The start index.</param> /// <param name="rangeStop">The stop index.</param> public void GetBytes(MemoryStream buf, int rangeStart, int rangeStop) { buf.Write(bytes, rangeStart, Math.Min(bytes.Length, rangeStop)); } /// <summary> /// Gets the Base64 encoded data contained in this NSData object. /// </summary> /// <returns>The Base64 encoded data as a <c>string</c>.</returns> public string GetBase64EncodedData() { return Convert.ToBase64String(bytes); } /// <summary> /// Determines whether the specified <see cref="System.Object"/> is equal to the current <see cref="PList.NSData"/>. /// </summary> /// <param name="obj">The <see cref="System.Object"/> to compare with the current <see cref="PList.NSData"/>.</param> /// <returns><c>true</c> if the specified <see cref="System.Object"/> is equal to the current /// <see cref="PList.NSData"/>; otherwise, <c>false</c>.</returns> public override bool Equals(Object obj) { return obj.GetType().Equals(GetType()) && ArrayEquals(((NSData)obj).bytes, bytes); } /// <summary> /// Serves as a hash function for a <see cref="PList.NSData"/> object. /// </summary> /// <returns>A hash code for this instance that is suitable for use in hashing algorithms and data structures such as a /// hash table.</returns> public override int GetHashCode() { int hash = 5; hash = 67 * hash + bytes.GetHashCode(); return hash; } internal override void ToXml(StringBuilder xml, int level) { Indent(xml, level); xml.Append("<data>"); xml.Append(NSObject.NEWLINE); string base64 = GetBase64EncodedData(); foreach (string line in base64.Split('\n')) { Indent(xml, level); xml.Append(line); xml.Append(NSObject.NEWLINE); } Indent(xml, level); xml.Append("</data>"); } internal override void ToBinary(BinaryPropertyListWriter outPlist) { outPlist.WriteIntHeader(0x4, bytes.Length); outPlist.Write(bytes); } internal override void ToASCII(StringBuilder ascii, int level) { Indent(ascii, level); ascii.Append(ASCIIPropertyListParser.DATA_BEGIN_TOKEN); int indexOfLastNewLine = ascii.ToString().LastIndexOf(NEWLINE, StringComparison.Ordinal); for (int i = 0; i < bytes.Length; i++) { int b = bytes[i] & 0xFF; ascii.Append(String.Format("{0:x2}", b)); if (ascii.Length - indexOfLastNewLine > ASCII_LINE_LENGTH) { ascii.Append(NEWLINE); indexOfLastNewLine = ascii.Length; } else if ((i + 1) % 2 == 0 && i != bytes.Length - 1) { ascii.Append(" "); } } ascii.Append(ASCIIPropertyListParser.DATA_END_TOKEN); } internal override void ToASCIIGnuStep(StringBuilder ascii, int level) { ToASCII(ascii, level); } /// <summary> /// Determines whether the specified <see cref="PList.NSObject"/> is equal to the current <see cref="PList.NSData"/>. /// </summary> /// <param name="obj">The <see cref="PList.NSObject"/> to compare with the current <see cref="PList.NSData"/>.</param> /// <returns><c>true</c> if the specified <see cref="PList.NSObject"/> is equal to the current /// <see cref="PList.NSData"/>; otherwise, <c>false</c>.</returns> public override bool Equals(NSObject obj) { if (!(obj is NSData)) return false; return ArrayEquals(bytes, ((NSData)obj).Bytes); } } }
27182812/ChatGLM-LLaMA-chinese-insturct
30,487
src/transformers/models/transfo_xl/tokenization_transfo_xl.py
# coding=utf-8 # Copyright 2018 Google AI, Google Brain and Carnegie Mellon University Authors and the HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. 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. """ Tokenization classes for Transformer XL model. Adapted from https://github.com/kimiyoung/transformer-xl. """ import glob import os import pickle import re from collections import Counter, OrderedDict from typing import List, Optional, Tuple import numpy as np from ...tokenization_utils import PreTrainedTokenizer from ...utils import ( cached_file, is_sacremoses_available, is_torch_available, logging, requires_backends, torch_only_method, ) if is_sacremoses_available(): import sacremoses as sm if is_torch_available(): import torch logger = logging.get_logger(__name__) VOCAB_FILES_NAMES = { "pretrained_vocab_file": "vocab.pkl", "pretrained_vocab_file_torch": "vocab.bin", "vocab_file": "vocab.txt", } PRETRAINED_VOCAB_FILES_MAP = { "pretrained_vocab_file": { "transfo-xl-wt103": "https://huggingface.co/transfo-xl-wt103/resolve/main/vocab.pkl", } } PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = { "transfo-xl-wt103": None, } PRETRAINED_CORPUS_ARCHIVE_MAP = { "transfo-xl-wt103": "https://huggingface.co/transfo-xl-wt103/resolve/main/corpus.bin", } CORPUS_NAME = "corpus.bin" MATCH_NUMBERS = r"(?<=\d)[,.](?=\d)", r" @\g<0>@ " DETOKENIZE_NUMBERS = [(r" @\,@ ", r","), (r" @\.@ ", r".")] def tokenize_numbers(text_array: List[str]) -> List[str]: """ Splits large comma-separated numbers and floating point values. This is done by replacing commas with ' @,@ ' and dots with ' @.@ '. Args: text_array: An already tokenized text as list. Returns: A list of strings with tokenized numbers. Example: ```python >>> tokenize_numbers(["$", "5,000", "1.73", "m"]) ["$", "5", "@,@", "000", "1", "@.@", "73", "m"] ```""" tokenized = [] for i in range(len(text_array)): reg, sub = MATCH_NUMBERS replaced = re.sub(reg, sub, text_array[i]).split() tokenized.extend(replaced) return tokenized def detokenize_numbers(text: str) -> str: """ Inverts the operation of *tokenize_numbers*. This is replacing ' @,@ ' and ' @.@' by ',' and '.'. Args: text: A string where the number should be detokenized. Returns: A detokenized string. Example: ```python >>> detokenize_numbers("$ 5 @,@ 000 1 @.@ 73 m") "$ 5,000 1.73 m" ```""" for reg, sub in DETOKENIZE_NUMBERS: text = re.sub(reg, sub, text) return text class TransfoXLTokenizer(PreTrainedTokenizer): """ Construct a Transformer-XL tokenizer adapted from Vocab class in [the original code](https://github.com/kimiyoung/transformer-xl). The Transformer-XL tokenizer is a word-level tokenizer (no sub-word tokenization). This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to this superclass for more information regarding those methods. Args: special (`List[str]`, *optional*): A list of special tokens (to be treated by the original implementation of this tokenizer). min_freq (`int`, *optional*, defaults to 0): The minimum number of times a token has to be present in order to be kept in the vocabulary (otherwise it will be mapped to `unk_token`). max_size (`int`, *optional*): The maximum size of the vocabulary. If left unset, it will default to the size of the vocabulary found after excluding the tokens according to the `min_freq` rule. lower_case (`bool`, *optional*, defaults to `False`): Whether or not to lowercase the input when tokenizing. delimiter (`str`, *optional*): The delimiter used between tokens. vocab_file (`str`, *optional*): File containing the vocabulary (from the original implementation). pretrained_vocab_file (`str`, *optional*): File containing the vocabulary as saved with the `save_pretrained()` method. never_split (`List[str]`, *optional*): List of tokens that should never be split. If no list is specified, will simply use the existing special tokens. unk_token (`str`, *optional*, defaults to `"<unk>"`): The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this token instead. eos_token (`str`, *optional*, defaults to `"<eos>"`): The end of sequence token. additional_special_tokens (`List[str]`, *optional*, defaults to `["<formula>"]`): A list of additional special tokens (for the HuggingFace functionality). language (`str`, *optional*, defaults to `"en"`): The language of this tokenizer (used for mose preprocessing). """ vocab_files_names = VOCAB_FILES_NAMES pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES model_input_names = ["input_ids"] def __init__( self, special=None, min_freq=0, max_size=None, lower_case=False, delimiter=None, vocab_file=None, pretrained_vocab_file: str = None, never_split=None, unk_token="<unk>", eos_token="<eos>", additional_special_tokens=["<formula>"], language="en", **kwargs, ): super().__init__( special=special, min_freq=min_freq, max_size=max_size, lower_case=lower_case, delimiter=delimiter, vocab_file=vocab_file, pretrained_vocab_file=pretrained_vocab_file, never_split=never_split, unk_token=unk_token, eos_token=eos_token, additional_special_tokens=additional_special_tokens, language=language, **kwargs, ) requires_backends(self, "sacremoses") if never_split is None: never_split = self.all_special_tokens if special is None: special = [] self.counter = Counter() self.special = special self.min_freq = min_freq self.max_size = max_size self.lower_case = lower_case self.delimiter = delimiter self.vocab_file = vocab_file self.never_split = never_split self.punctuation_symbols = '!"#$%&()*+,-./\\:;<=>?@[\\]^_`{|}~' self.punction_without_space_before_pattern = re.compile(rf"[^\s][{self.punctuation_symbols}]") self.punctuation_with_space_around_pattern = self._compile_space_around_punctuation_pattern() self.language = language self.moses_punct_normalizer = sm.MosesPunctNormalizer(language) self.moses_tokenizer = sm.MosesTokenizer(language) self.moses_detokenizer = sm.MosesDetokenizer(language) # This try... catch... is not beautiful but honestly this tokenizer was not made to be used # in a library like ours, at all. try: vocab_dict = None if pretrained_vocab_file is not None: # Priority on pickle files (support PyTorch and TF) with open(pretrained_vocab_file, "rb") as f: vocab_dict = pickle.load(f) # Loading a torch-saved transfo-xl vocab dict with pickle results in an integer # Entering this if statement means that we tried to load a torch-saved file with pickle, and we failed. # We therefore load it with torch, if it's available. if type(vocab_dict) == int: if not is_torch_available(): raise ImportError( "Not trying to load dict with PyTorch as you need to install pytorch to load " "from a PyTorch pretrained vocabulary, " "or activate it with environment variables USE_TORCH=1 and USE_TF=0." ) vocab_dict = torch.load(pretrained_vocab_file) if vocab_dict is not None: for key, value in vocab_dict.items(): if key not in self.__dict__: self.__dict__[key] = value elif vocab_file is not None: self.build_vocab() except Exception as e: raise ValueError( f"Unable to parse file {pretrained_vocab_file}. Unknown format. " "If you tried to load a model saved through TransfoXLTokenizerFast, " "please note they are not compatible." ) from e if vocab_file is not None: self.build_vocab() @property def do_lower_case(self): return self.lower_case def _compile_space_around_punctuation_pattern(self): look_ahead_for_special_token = f"(?=[{self.punctuation_symbols}])" look_ahead_to_match_all_except_space = r"(?=[^\s])" return re.compile(r"" + look_ahead_for_special_token + look_ahead_to_match_all_except_space) def count_file(self, path, verbose=False, add_eos=False): if verbose: logger.info(f"counting file {path} ...") assert os.path.exists(path), f"Input file {path} not found" sents = [] with open(path, "r", encoding="utf-8") as f: for idx, line in enumerate(f): if verbose and idx > 0 and idx % 500000 == 0: logger.info(f" line {idx}") symbols = self.tokenize(line, add_eos=add_eos) self.counter.update(symbols) sents.append(symbols) return sents def count_sents(self, sents, verbose=False): """ sents : a list of sentences, each a list of tokenized symbols """ if verbose: logger.info(f"counting {len(sents)} sents ...") for idx, symbols in enumerate(sents): if verbose and idx > 0 and idx % 500000 == 0: logger.info(f" line {idx}") self.counter.update(symbols) def _build_from_file(self, vocab_file): self.idx2sym = [] self.sym2idx = OrderedDict() with open(vocab_file, "r", encoding="utf-8") as f: for line in f: symb = line.strip().split()[0] self.add_symbol(symb) if "<UNK>" in self.sym2idx: self.unk_idx = self.sym2idx["<UNK>"] elif "<unk>" in self.sym2idx: self.unk_idx = self.sym2idx["<unk>"] else: raise ValueError("No <unknown> token in vocabulary") def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]: if os.path.isdir(save_directory): vocab_file = os.path.join( save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["pretrained_vocab_file"], ) else: vocab_file = (filename_prefix + "-" if filename_prefix else "") + save_directory with open(vocab_file, "wb") as f: pickle.dump(self.__dict__, f) return (vocab_file,) def build_vocab(self): if self.vocab_file: logger.info(f"building vocab from {self.vocab_file}") self._build_from_file(self.vocab_file) logger.info(f"final vocab size {len(self)}") else: logger.info(f"building vocab with min_freq={self.min_freq}, max_size={self.max_size}") self.idx2sym = [] self.sym2idx = OrderedDict() for sym in self.special: self.add_special(sym) for sym, cnt in self.counter.most_common(self.max_size): if cnt < self.min_freq: break self.add_symbol(sym) logger.info(f"final vocab size {len(self)} from {len(self.counter)} unique tokens") @torch_only_method def encode_file(self, path, ordered=False, verbose=False, add_eos=True, add_double_eos=False): if verbose: logger.info(f"encoding file {path} ...") assert os.path.exists(path), f"Output file {path} not found" encoded = [] with open(path, "r", encoding="utf-8") as f: for idx, line in enumerate(f): if verbose and idx > 0 and idx % 500000 == 0: logger.info(f" line {idx}") symbols = self.tokenize(line, add_eos=add_eos, add_double_eos=add_double_eos) encoded.append(self.convert_to_tensor(symbols)) if ordered: encoded = torch.cat(encoded) return encoded @torch_only_method def encode_sents(self, sents, ordered=False, verbose=False): if verbose: logger.info(f"encoding {len(sents)} sents ...") encoded = [] for idx, symbols in enumerate(sents): if verbose and idx > 0 and idx % 500000 == 0: logger.info(f" line {idx}") encoded.append(self.convert_to_tensor(symbols)) if ordered: encoded = torch.cat(encoded) return encoded def add_special(self, sym): if sym not in self.sym2idx: self.idx2sym.append(sym) self.sym2idx[sym] = len(self.idx2sym) - 1 setattr(self, f"{sym.strip('<>')}_idx", self.sym2idx[sym]) def add_symbol(self, sym): if sym not in self.sym2idx: self.idx2sym.append(sym) self.sym2idx[sym] = len(self.idx2sym) - 1 def move_added_token(self, token: str, target_idx: int): """ Moves an added token to a specific position in the vocab. This method should be used when resizing an embedding layer other than the last one in the `AdaptiveEmbedding` in order to move the token in the tokenizer from the default position (at the very end) to the desired one. Args: token: The token to move to a specific position in the vocab. target_idx: The position where the token should be moved to. """ assert token in self.added_tokens_encoder, "Token which should be moved has to be an added token" assert token not in self.idx2sym, "Token which should be moved is already in vocab" # Insert sym into vocab self.idx2sym.insert(target_idx, token) self.sym2idx[token] = target_idx # Shift following indices in sym2idx for idx in range(target_idx + 1, len(self.idx2sym)): current_sym = self.idx2sym[idx] self.sym2idx[current_sym] = idx # Delete token from added_tokens old_index = self.added_tokens_encoder[token] del self.added_tokens_decoder[old_index] del self.added_tokens_encoder[token] def moses_punct_norm(self, text): return self.moses_punct_normalizer.normalize(text) def moses_tokenize(self, text): return self.moses_tokenizer.tokenize( text, aggressive_dash_splits=True, return_str=False, escape=False, protected_patterns=self.never_split ) def moses_pipeline(self, text: str) -> List[str]: """ Does basic tokenization using [`sacremoses.MosesPunctNormalizer`] and [`sacremoses.MosesTokenizer`] with *aggressive_dash_splits=True* (see [`sacremoses.tokenize.MosesTokenizer.tokenize`]). Additionally, large comma-separated numbers and floating point values are split. E.g. "23,000 people are 1.80m tall" -> "23 @,@ 000 people are 1 @.@ 80m tall" Args: text: Text to be tokenize Returns: A list of tokenized string Example: ```python >>> tokenizer = TransfoXLTokenizer.from_pretrained("transfo-xl-wt103") >>> tokenizer.moses_pipeline("23,000 people are 1.80 m tall") ['23', '@,@', '000', 'people', 'are', '1', '@.@', '80', 'm', 'tall'] ```""" text = self.moses_punct_norm(text) text = self.moses_tokenize(text) text = tokenize_numbers(text) return text def _convert_id_to_token(self, idx): """Converts an id in a token (BPE) using the vocab.""" assert 0 <= idx < len(self), f"Index {idx} out of vocabulary range" return self.idx2sym[idx] def _convert_token_to_id(self, sym): """Converts a token (str) in an id using the vocab.""" if sym in self.sym2idx: return self.sym2idx[sym] else: # logger.info(f'encounter unk {sym}') # assert '<eos>' not in sym if hasattr(self, "unk_idx"): return self.sym2idx.get(sym, self.unk_idx) # Backward compatibility with pre-trained models elif "<unk>" in self.sym2idx: return self.sym2idx["<unk>"] elif "<UNK>" in self.sym2idx: return self.sym2idx["<UNK>"] else: raise ValueError("Token not in vocabulary and no <unk> token in vocabulary for replacement") def convert_tokens_to_string(self, tokens): """ Converts a sequence of tokens (string) in a single string. Additionally, the split numbers are converted back into it's original form. """ out_string = self.moses_detokenizer.detokenize(tokens) return detokenize_numbers(out_string).strip() @torch_only_method def convert_to_tensor(self, symbols): return torch.LongTensor(self.convert_tokens_to_ids(symbols)) @property def vocab_size(self): return len(self.idx2sym) def get_vocab(self): return dict(self.sym2idx, **self.added_tokens_encoder) def _tokenize(self, line, add_eos=False, add_double_eos=False): line = line.strip() # convert to lower case if self.lower_case: line = line.lower() # empty delimiter '' will evaluate False if self.delimiter == "": symbols = line else: symbols = self.moses_pipeline(line) if add_double_eos: # lm1b return ["<S>"] + symbols + ["<S>"] elif add_eos: return symbols + ["<eos>"] else: return symbols class LMOrderedIterator(object): def __init__(self, data, bsz, bptt, device="cpu", ext_len=None): """ data -- LongTensor -- the LongTensor is strictly ordered """ self.bsz = bsz self.bptt = bptt self.ext_len = ext_len if ext_len is not None else 0 self.device = device # Work out how cleanly we can divide the dataset into bsz parts. self.n_step = data.size(0) // bsz # Trim off any extra elements that wouldn't cleanly fit (remainders). data = data.narrow(0, 0, self.n_step * bsz) # Evenly divide the data across the bsz batches. self.data = data.view(bsz, -1).t().contiguous().to(device) # Number of mini-batches self.n_batch = (self.n_step + self.bptt - 1) // self.bptt def get_batch(self, i, bptt=None): if bptt is None: bptt = self.bptt seq_len = min(bptt, self.data.size(0) - 1 - i) end_idx = i + seq_len beg_idx = max(0, i - self.ext_len) data = self.data[beg_idx:end_idx] target = self.data[i + 1 : i + 1 + seq_len] data_out = data.transpose(0, 1).contiguous().to(self.device) target_out = target.transpose(0, 1).contiguous().to(self.device) return data_out, target_out, seq_len def get_fixlen_iter(self, start=0): for i in range(start, self.data.size(0) - 1, self.bptt): yield self.get_batch(i) def get_varlen_iter(self, start=0, std=5, min_len=5, max_deviation=3): max_len = self.bptt + max_deviation * std i = start while True: bptt = self.bptt if np.random.random() < 0.95 else self.bptt / 2.0 bptt = min(max_len, max(min_len, int(np.random.normal(bptt, std)))) data, target, seq_len = self.get_batch(i, bptt) i += seq_len yield data, target, seq_len if i >= self.data.size(0) - 2: break def __iter__(self): return self.get_fixlen_iter() class LMShuffledIterator(object): def __init__(self, data, bsz, bptt, device="cpu", ext_len=None, shuffle=False): """ data -- list[LongTensor] -- there is no order among the LongTensors """ self.data = data self.bsz = bsz self.bptt = bptt self.ext_len = ext_len if ext_len is not None else 0 self.device = device self.shuffle = shuffle def get_sent_stream(self): # index iterator epoch_indices = np.random.permutation(len(self.data)) if self.shuffle else np.array(range(len(self.data))) # sentence iterator for idx in epoch_indices: yield self.data[idx] @torch_only_method def stream_iterator(self, sent_stream): # streams for each data in the batch streams = [None] * self.bsz data = torch.LongTensor(self.bptt, self.bsz) target = torch.LongTensor(self.bptt, self.bsz) n_retain = 0 while True: # data : [n_retain+bptt x bsz] # target : [bptt x bsz] data[n_retain:].fill_(-1) target.fill_(-1) valid_batch = True for i in range(self.bsz): n_filled = 0 try: while n_filled < self.bptt: if streams[i] is None or len(streams[i]) <= 1: streams[i] = next(sent_stream) # number of new tokens to fill in n_new = min(len(streams[i]) - 1, self.bptt - n_filled) # first n_retain tokens are retained from last batch data[n_retain + n_filled : n_retain + n_filled + n_new, i] = streams[i][:n_new] target[n_filled : n_filled + n_new, i] = streams[i][1 : n_new + 1] streams[i] = streams[i][n_new:] n_filled += n_new except StopIteration: valid_batch = False break if not valid_batch: return data_out = data.transpose(0, 1).contiguous().to(self.device) target_out = target.transpose(0, 1).contiguous().to(self.device) yield data_out, target_out, self.bptt n_retain = min(data.size(0), self.ext_len) if n_retain > 0: data[:n_retain] = data[-n_retain:] data.resize_(n_retain + self.bptt, data.size(1)) def __iter__(self): # sent_stream is an iterator sent_stream = self.get_sent_stream() for batch in self.stream_iterator(sent_stream): yield batch class LMMultiFileIterator(LMShuffledIterator): def __init__(self, paths, vocab, bsz, bptt, device="cpu", ext_len=None, shuffle=False): self.paths = paths self.vocab = vocab self.bsz = bsz self.bptt = bptt self.ext_len = ext_len if ext_len is not None else 0 self.device = device self.shuffle = shuffle def get_sent_stream(self, path): sents = self.vocab.encode_file(path, add_double_eos=True) if self.shuffle: np.random.shuffle(sents) sent_stream = iter(sents) return sent_stream def __iter__(self): if self.shuffle: np.random.shuffle(self.paths) for path in self.paths: # sent_stream is an iterator sent_stream = self.get_sent_stream(path) for batch in self.stream_iterator(sent_stream): yield batch class TransfoXLCorpus(object): @classmethod @torch_only_method def from_pretrained(cls, pretrained_model_name_or_path, cache_dir=None, *inputs, **kwargs): """ Instantiate a pre-processed corpus. """ vocab = TransfoXLTokenizer.from_pretrained(pretrained_model_name_or_path, *inputs, **kwargs) is_local = os.path.isdir(pretrained_model_name_or_path) # redirect to the cache, if necessary try: resolved_corpus_file = cached_file(pretrained_model_name_or_path, CORPUS_NAME, cache_dir=cache_dir) except EnvironmentError: logger.error( f"Corpus '{pretrained_model_name_or_path}' was not found in corpus list" f" ({', '.join(PRETRAINED_CORPUS_ARCHIVE_MAP.keys())}. We assumed '{pretrained_model_name_or_path}'" f" was a path or url but couldn't find files {CORPUS_NAME} at this path or url." ) return None if is_local: logger.info(f"loading corpus file {resolved_corpus_file}") else: logger.info(f"loading corpus file {CORPUS_NAME} from cache at {resolved_corpus_file}") # Instantiate tokenizer. corpus = cls(*inputs, **kwargs) corpus_dict = torch.load(resolved_corpus_file) for key, value in corpus_dict.items(): corpus.__dict__[key] = value corpus.vocab = vocab if corpus.train is not None: corpus.train = torch.tensor(corpus.train, dtype=torch.long) if corpus.valid is not None: corpus.valid = torch.tensor(corpus.valid, dtype=torch.long) if corpus.test is not None: corpus.test = torch.tensor(corpus.test, dtype=torch.long) return corpus def __init__(self, *args, **kwargs): self.vocab = TransfoXLTokenizer(*args, **kwargs) self.dataset = None self.train = None self.valid = None self.test = None def build_corpus(self, path, dataset): self.dataset = dataset if self.dataset in ["ptb", "wt2", "enwik8", "text8"]: self.vocab.count_file(os.path.join(path, "train.txt")) self.vocab.count_file(os.path.join(path, "valid.txt")) self.vocab.count_file(os.path.join(path, "test.txt")) elif self.dataset == "wt103": self.vocab.count_file(os.path.join(path, "train.txt")) elif self.dataset == "lm1b": train_path_pattern = os.path.join( path, "1-billion-word-language-modeling-benchmark-r13output", "training-monolingual.tokenized.shuffled", "news.en-*", ) train_paths = glob.glob(train_path_pattern) # the vocab will load from file when build_vocab() is called self.vocab.build_vocab() if self.dataset in ["ptb", "wt2", "wt103"]: self.train = self.vocab.encode_file(os.path.join(path, "train.txt"), ordered=True) self.valid = self.vocab.encode_file(os.path.join(path, "valid.txt"), ordered=True) self.test = self.vocab.encode_file(os.path.join(path, "test.txt"), ordered=True) elif self.dataset in ["enwik8", "text8"]: self.train = self.vocab.encode_file(os.path.join(path, "train.txt"), ordered=True, add_eos=False) self.valid = self.vocab.encode_file(os.path.join(path, "valid.txt"), ordered=True, add_eos=False) self.test = self.vocab.encode_file(os.path.join(path, "test.txt"), ordered=True, add_eos=False) elif self.dataset == "lm1b": self.train = train_paths self.valid = self.vocab.encode_file(os.path.join(path, "valid.txt"), ordered=False, add_double_eos=True) self.test = self.vocab.encode_file(os.path.join(path, "test.txt"), ordered=False, add_double_eos=True) def get_iterator(self, split, *args, **kwargs): if split == "train": if self.dataset in ["ptb", "wt2", "wt103", "enwik8", "text8"]: data_iter = LMOrderedIterator(self.train, *args, **kwargs) elif self.dataset == "lm1b": kwargs["shuffle"] = True data_iter = LMMultiFileIterator(self.train, self.vocab, *args, **kwargs) elif split in ["valid", "test"]: data = self.valid if split == "valid" else self.test if self.dataset in ["ptb", "wt2", "wt103", "enwik8", "text8"]: data_iter = LMOrderedIterator(data, *args, **kwargs) elif self.dataset == "lm1b": data_iter = LMShuffledIterator(data, *args, **kwargs) else: data_iter = None raise ValueError(f"Split not recognized: {split}") return data_iter @torch_only_method def get_lm_corpus(datadir, dataset): fn = os.path.join(datadir, "cache.pt") fn_pickle = os.path.join(datadir, "cache.pkl") if os.path.exists(fn): logger.info("Loading cached dataset...") corpus = torch.load(fn_pickle) elif os.path.exists(fn): logger.info("Loading cached dataset from pickle...") with open(fn, "rb") as fp: corpus = pickle.load(fp) else: logger.info(f"Producing dataset {dataset}...") kwargs = {} if dataset in ["wt103", "wt2"]: kwargs["special"] = ["<eos>"] kwargs["lower_case"] = False elif dataset == "ptb": kwargs["special"] = ["<eos>"] kwargs["lower_case"] = True elif dataset == "lm1b": kwargs["special"] = [] kwargs["lower_case"] = False kwargs["vocab_file"] = os.path.join(datadir, "1b_word_vocab.txt") elif dataset in ["enwik8", "text8"]: pass corpus = TransfoXLCorpus(datadir, dataset, **kwargs) torch.save(corpus, fn) return corpus
2881099/dotnetGen_sqlserver
11,008
GenMs/WinFormClass/Robot.cs
using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Threading; /// <summary> /// 作业调度器,一般运行在控制台 /// </summary> public class Robot : IDisposable { private string _def_path; private List<RobotDef> _robots; private Dictionary<string, RobotDef> _dic_robots = new Dictionary<string, RobotDef>(); private object _robots_lock = new object(); private FileSystemWatcher _defWatcher; public event RobotErrorHandler Error; public event RobotRunHandler Run; public Robot() : this(Path.Combine(AppContext.BaseDirectory, @"robot.txt")) { } public Robot(string path) { _def_path = path; } public void Start() { lock (_robots_lock) { _dic_robots.Clear(); if (_robots != null) { for (int a = 0; a < _robots.Count; a++) _dic_robots.Add(_robots[a].Name, _robots[a]); _robots.Clear(); } } if (!File.Exists(_def_path)) return; lock (_robots_lock) { _robots = LoadDef(); foreach (RobotDef bot in _robots) if (bot._timer == null) bot.RunNow(); } if (_defWatcher == null) { _defWatcher = new FileSystemWatcher(Path.GetDirectoryName(_def_path), Path.GetFileName(_def_path)); _defWatcher.Changed += delegate(object sender, FileSystemEventArgs e) { _defWatcher.EnableRaisingEvents = false; if (_robots.Count > 0) { Start(); } _defWatcher.EnableRaisingEvents = true; }; _defWatcher.EnableRaisingEvents = true; } } public void Stop() { lock (_robots_lock) { if (_robots != null) { for (int a = 0; a < _robots.Count; a++) _robots[a].Dispose(); _robots.Clear(); } } } #region IDisposable 成员 public void Dispose() { if (_defWatcher != null) _defWatcher.Dispose(); Stop(); } #endregion public List<RobotDef> LoadDef() { string defDoc = Encoding.UTF8.GetString(readFile(_def_path)); return LoadDef(defDoc); } public List<RobotDef> LoadDef(string defDoc) { Dictionary<string, RobotDef> dic = new Dictionary<string, RobotDef>(); string[] defs = defDoc.Split(new string[] { "\n" }, StringSplitOptions.None); int row = 1; foreach (string def in defs) { string loc1 = def.Trim().Trim('\r'); if (string.IsNullOrEmpty(loc1) || loc1[0] == 65279 || loc1[0] == ';' || loc1[0] == '#') continue; string pattern = @"([^\s]+)\s+(NONE|SEC|MIN|HOUR|DAY|RunOnDay|RunOnWeek|RunOnMonth)\s+([^\s]+)\s+([^\s]+)"; Match m = Regex.Match(loc1, pattern, RegexOptions.IgnoreCase); if (!m.Success) { onError(new Exception("Robot配置错误“" + loc1 + "”, 第" + row + "行")); continue; } string name = m.Groups[1].Value.Trim('\t', ' '); RobotRunMode mode = getMode(m.Groups[2].Value.Trim('\t', ' ')); string param = m.Groups[3].Value.Trim('\t', ' '); string runParam = m.Groups[4].Value.Trim('\t', ' '); if (dic.ContainsKey(name)) { onError(new Exception("Robot配置存在重复的名字“" + name + "”, 第" + row + "行")); continue; } if (mode == RobotRunMode.NONE) continue; RobotDef rd = null; if (_dic_robots.ContainsKey(name)) { rd = _dic_robots[name]; rd.Update(mode, param, runParam); _dic_robots.Remove(name); } else rd = new RobotDef(this, name, mode, param, runParam); if (rd.Interval < 0) { onError(new Exception("Robot配置参数错误“" + def + "”, 第" + row + "行")); continue; } dic.Add(rd.Name, rd); row++; } List<RobotDef> rds = new List<RobotDef>(); foreach (RobotDef rd in dic.Values) rds.Add(rd); foreach (RobotDef stopBot in _dic_robots.Values) stopBot.Dispose(); return rds; } private void onError(Exception ex) { onError(ex, null); } internal void onError(Exception ex, RobotDef def) { if (Error != null) Error(this, new RobotErrorEventArgs(ex, def)); } internal void onRun(RobotDef def) { if (Run != null) Run(this, def); } private byte[] readFile(string path) { if (File.Exists(path)) { string destFileName = Path.GetTempFileName(); File.Copy(path, destFileName, true); int read = 0; byte[] data = new byte[1024]; using (MemoryStream ms = new MemoryStream()) { using (FileStream fs = new FileStream(destFileName, FileMode.OpenOrCreate, FileAccess.Read)) { do { read = fs.Read(data, 0, data.Length); if (read <= 0) break; ms.Write(data, 0, read); } while (true); } File.Delete(destFileName); data = ms.ToArray(); } return data; } return new byte[] { }; } private RobotRunMode getMode(string mode) { mode = string.Concat(mode).ToUpper(); switch (mode) { case "SEC": return RobotRunMode.SEC; case "MIN": return RobotRunMode.MIN; case "HOUR": return RobotRunMode.HOUR; case "DAY": return RobotRunMode.DAY; case "RUNONDAY": return RobotRunMode.RunOnDay; case "RUNONWEEK": return RobotRunMode.RunOnWeek; case "RUNONMONTH": return RobotRunMode.RunOnMonth; default: return RobotRunMode.NONE; } } } public class RobotDef : IDisposable { private string _name; private RobotRunMode _mode = RobotRunMode.NONE; private string _param; private string _runParam; private int _runTimes = 0; private int _errTimes = 0; private Robot _onwer; internal Timer _timer; private bool _timerIntervalOverflow = false; public RobotDef(Robot onwer, string name, RobotRunMode mode, string param, string runParam) { _onwer = onwer; _name = name; _mode = mode; _param = param; _runParam = runParam; } public void Update(RobotRunMode mode, string param, string runParam) { if (_mode != mode || _param != param || _runParam != runParam) { _mode = mode; _param = param; _runParam = runParam; if (_timer != null) { _timer.Dispose(); _timer = null; } RunNow(); } } public void RunNow() { double tmp = this.Interval; _timerIntervalOverflow = tmp > int.MaxValue; int interval = _timerIntervalOverflow ? int.MaxValue : (int)tmp; if (interval <= 0) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(" {0} Interval <= 0", _name); Console.ResetColor(); return; } //Console.WriteLine(interval); if (_timer == null) { _timer = new Timer(a => { if (_timerIntervalOverflow) { RunNow(); return; } _runTimes++; string logObj = this.ToString(); try { _onwer.onRun(this); } catch (Exception ex) { _errTimes++; _onwer.onError(ex, this); } RunNow(); }, null, interval, -1); } else { _timer.Change(interval, -1); } if (tmp > 1000 * 9) { DateTime nextTime = DateTime.Now.AddMilliseconds(tmp); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine(" {0} 下次触发时间:{1:yyyy-MM-dd HH:mm:ss}", _name, nextTime); Console.ResetColor(); } } public override string ToString() { return Name + ", " + Mode + ", " + Param + ", " + RunParam; } #region IDisposable 成员 public void Dispose() { if (_timer != null) { _timer.Dispose(); _timer = null; } } #endregion public string Name { get { return _name; } } public RobotRunMode Mode { get { return _mode; } } public string Param { get { return _param; } } public string RunParam { get { return _runParam; } } public int RunTimes { get { return _runTimes; } } public int ErrTimes { get { return _errTimes; } } public double Interval { get { DateTime now = DateTime.Now; DateTime curt = DateTime.MinValue; TimeSpan ts = TimeSpan.Zero; uint ww = 0, dd = 0, hh = 0, mm = 0, ss = 0; double interval = -1; switch (_mode) { case RobotRunMode.SEC: double.TryParse(_param, out interval); interval *= 1000; break; case RobotRunMode.MIN: double.TryParse(_param, out interval); interval *= 60 * 1000; break; case RobotRunMode.HOUR: double.TryParse(_param, out interval); interval *= 60 * 60 * 1000; break; case RobotRunMode.DAY: double.TryParse(_param, out interval); interval *= 24 * 60 * 60 * 1000; break; case RobotRunMode.RunOnDay: List<string> hhmmss = new List<string>(string.Concat(_param).Split(':')); if (hhmmss.Count == 3) if (uint.TryParse(hhmmss[0], out hh) && hh < 24 && uint.TryParse(hhmmss[1], out mm) && mm < 60 && uint.TryParse(hhmmss[2], out ss) && ss < 60) { curt = now.Date.AddHours(hh).AddMinutes(mm).AddSeconds(ss); ts = curt.Subtract(now); while (!(ts.TotalMilliseconds > 0)) { curt = curt.AddDays(1); ts = curt.Subtract(now); } interval = ts.TotalMilliseconds; } break; case RobotRunMode.RunOnWeek: string[] wwhhmmss = string.Concat(_param).Split(':'); if (wwhhmmss.Length == 4) if (uint.TryParse(wwhhmmss[0], out ww) && ww < 7 && uint.TryParse(wwhhmmss[1], out hh) && hh < 24 && uint.TryParse(wwhhmmss[2], out mm) && mm < 60 && uint.TryParse(wwhhmmss[3], out ss) && ss < 60) { curt = now.Date.AddHours(hh).AddMinutes(mm).AddSeconds(ss); ts = curt.Subtract(now); while(!(ts.TotalMilliseconds > 0 && (int)curt.DayOfWeek == ww)) { curt = curt.AddDays(1); ts = curt.Subtract(now); } interval = ts.TotalMilliseconds; } break; case RobotRunMode.RunOnMonth: string[] ddhhmmss = string.Concat(_param).Split(':'); if (ddhhmmss.Length == 4) if (uint.TryParse(ddhhmmss[0], out dd) && dd > 0 && dd < 32 && uint.TryParse(ddhhmmss[1], out hh) && hh < 24 && uint.TryParse(ddhhmmss[2], out mm) && mm < 60 && uint.TryParse(ddhhmmss[3], out ss) && ss < 60) { curt = new DateTime(now.Year, now.Month, (int)dd).AddHours(hh).AddMinutes(mm).AddSeconds(ss); ts = curt.Subtract(now); while (!(ts.TotalMilliseconds > 0)) { curt = curt.AddMonths(1); ts = curt.Subtract(now); } interval = ts.TotalMilliseconds; } break; } if (interval == 0) interval = 1; return interval; } } } /* ; 和 # 匀为行注释 ;SEC: 按秒触发 ;MIN: 按分触发 ;HOUR: 按时触发 ;DAY: 按天触发 ;RunOnDay: 每天 什么时间 触发 ;RunOnWeek: 星期几 什么时间 触发 ;RunOnMonth: 每月 第几天 什么时间 触发 ;Name1 SEC 2 /schedule/test002.aspx ;Name2 MIN 2 /schedule/test002.aspx ;Name3 HOUR 1 /schedule/test002.aspx ;Name4 DAY 2 /schedule/test002.aspx ;Name5 RunOnDay 15:55:59 /schedule/test002.aspx ;每天15点55分59秒 ;Name6 RunOnWeek 1:15:55:59 /schedule/test002.aspx ;每星期一15点55分59秒 ;Name7 RunOnMonth 1:15:55:59 /schedule/test002.aspx ;每月1号15点55分59秒 */ public enum RobotRunMode { NONE = 0, SEC = 1, MIN = 2, HOUR = 3, DAY = 4, RunOnDay = 11, RunOnWeek = 12, RunOnMonth = 13 } public delegate void RobotErrorHandler(object sender, RobotErrorEventArgs e); public delegate void RobotRunHandler(object sender, RobotDef e); public class RobotErrorEventArgs : EventArgs { private Exception _exception; private RobotDef _def; public RobotErrorEventArgs(Exception exception, RobotDef def) { _exception = exception; _def = def; } public Exception Exception { get { return _exception; } } public RobotDef Def { get { return _def; } } }
2881099/dotnetGen_postgresql
19,629
GenPg/plist-cil/NSDictionary.cs
// plist-cil - An open source library to parse and generate property lists for .NET // Copyright (C) 2015 Natalia Portillo // // This code is based on: // plist - An open source library to parse and generate property lists // Copyright (C) 2014 Daniel Dreibrodt // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. using System; using System.Collections.Generic; using System.Text; namespace PList { /// <summary> /// <para> /// A NSDictionary is a collection of keys and values, essentially a Dictionary. /// The keys are simple Strings whereas the values can be any kind of NSObject. /// </para><para> /// You can access the keys through the function <see cref="Keys"/>. /// </para><para> /// Access to the objects stored for each key is given through the function /// <see cref="ObjectForKey"/>. /// </para> /// </summary> /// @author Daniel Dreibrodt /// @author Natalia Portillo public class NSDictionary : NSObject, IDictionary<string, NSObject> { readonly Dictionary<string, NSObject> dict; /// <summary> /// Creates a new empty NSDictionary. /// </summary> public NSDictionary() { dict = new Dictionary<string, NSObject>(); } /// <summary> /// Gets the hashmap which stores the keys and values of this dictionary. /// Changes to the hashmap's contents are directly reflected in this /// dictionary. /// </summary> /// <returns>The hashmap which is used by this dictionary to store its contents.</returns> public Dictionary<string, NSObject> GetDictionary() { return dict; } /// <summary> /// Gets the NSObject stored for the given key. /// </summary> /// <returns>The object.</returns> /// <param name="key">The key.</param> public NSObject ObjectForKey(string key) { NSObject nso; return dict.TryGetValue(key, out nso) ? nso : null; } /// <summary> /// Gets a value indicating whether this instance is empty. /// </summary> /// <value><c>true</c> if this instance is empty; otherwise, <c>false</c>.</value> public bool IsEmpty { get { return dict.Count == 0; } } /// <summary> /// Checks if the specified object key is contained in the current instance. /// </summary> /// <returns><c>true</c>, if key is contained, <c>false</c> otherwise.</returns> /// <param name="key">Key.</param> public bool ContainsKey(Object key) { return key is string && dict.ContainsKey((string)key); } /// <summary> /// Removes the item corresponding to the specified key from the current instance, if found. /// </summary> /// <param name="key">Key.</param> /// <returns><c>true</c>, if removed, <c>false</c> otherwise.</returns> public bool Remove(Object key) { return key is string && dict.Remove((string)key); } /// <summary> /// Gets the <see cref="NSObject"/> corresponding to the specified key from the current instance. /// </summary> /// <param name="key">Key.</param> /// <returns>The object corresponding to the specified key, null if not found in the current instance.</returns> public NSObject Get(Object key) { if (key is string) return ObjectForKey((string)key); return null; } /// <summary> /// Checks if the current instance contains the object corresponding to the specified key. /// </summary> /// <returns><c>true</c>, if value is contained, <c>false</c> otherwise.</returns> /// <param name="value">Object to search up in the current instance.</param> public bool ContainsValue(Object value) { if (value == null) return false; NSObject wrap = NSObject.Wrap(value); return dict.ContainsValue(wrap); } /// <summary> /// Puts a new key-value pair into this dictionary. /// If the value is null, no operation will be performed on the dictionary. /// </summary> /// <param name="key">The key.</param> /// <param name="obj">The value. Supported object types are numbers, byte-arrays, dates, strings and arrays or sets of those.</param> public void Add(String key, Object obj) { if (obj == null) return; Add(key, NSObject.Wrap(obj)); } /// <summary> /// Puts a new key-value pair into this dictionary. /// </summary> /// <param name="key">The key.</param> /// <param name="obj">The value.</param> public void Add(string key, long obj) { Add(key, new NSNumber(obj)); } /// <summary> /// Puts a new key-value pair into this dictionary. /// </summary> /// <param name="key">The key.</param> /// <param name="obj">The value.</param> public void Add(string key, double obj) { Add(key, new NSNumber(obj)); } /// <summary> /// Puts a new key-value pair into this dictionary. /// </summary> /// <param name="key">The key.</param> /// <param name="obj">The value.</param> public void Add(string key, bool obj) { Add(key, new NSNumber(obj)); } /// <summary> /// Checks whether a given value is contained in this dictionary. /// </summary> /// <param name="val">The value that will be searched for.</param> /// <returns>Whether the key is contained in this dictionary.</returns> public bool ContainsValue(string val) { foreach (NSObject o in dict.Values) { if (o.GetType().Equals(typeof(NSString))) { NSString str = (NSString)o; if (str.GetContent().Equals(val)) return true; } } return false; } /// <summary> /// Checks whether a given value is contained in this dictionary. /// </summary> /// <param name="val">The value that will be searched for.</param> /// <returns>Whether the key is contained in this dictionary.</returns> public bool ContainsValue(long val) { foreach (NSObject o in dict.Values) { if (o.GetType().Equals(typeof(NSNumber))) { NSNumber num = (NSNumber)o; if (num.isInteger() && num.ToInt() == val) return true; } } return false; } /// <summary> /// Checks whether a given value is contained in this dictionary. /// </summary> /// <param name="val">The value that will be searched for.</param> /// <returns>Whether the key is contained in this dictionary.</returns> public bool ContainsValue(double val) { foreach (NSObject o in dict.Values) { if (o.GetType().Equals(typeof(NSNumber))) { NSNumber num = (NSNumber)o; if (num.isReal() && num.ToDouble() == val) return true; } } return false; } /// <summary> /// Checks whether a given value is contained in this dictionary. /// </summary> /// <param name="val">The value that will be searched for.</param> /// <returns>Whether the key is contained in this dictionary.</returns> public bool ContainsValue(bool val) { foreach (NSObject o in dict.Values) { if (o.GetType().Equals(typeof(NSNumber))) { NSNumber num = (NSNumber)o; if (num.isBoolean() && num.ToBool() == val) return true; } } return false; } /// <summary> /// Checks whether a given value is contained in this dictionary. /// </summary> /// <param name="val">The value that will be searched for.</param> /// <returns>Whether the key is contained in this dictionary.</returns> public bool ContainsValue(DateTime val) { foreach (NSObject o in dict.Values) { if (o.GetType().Equals(typeof(NSDate))) { NSDate dat = (NSDate)o; if (dat.Date.Equals(val)) return true; } } return false; } /// <summary> /// Checks whether a given value is contained in this dictionary. /// </summary> /// <param name="val">The value that will be searched for.</param> /// <returns>Whether the key is contained in this dictionary.</returns> public bool ContainsValue(byte[] val) { foreach (NSObject o in dict.Values) { if (o.GetType().Equals(typeof(NSData))) { NSData dat = (NSData)o; if (ArrayEquals(dat.Bytes, val)) return true; } } return false; } /// <summary> /// Determines whether the specified <see cref="PList.NSObject"/> is equal to the current <see cref="PList.NSDictionary"/>. /// </summary> /// <param name="obj">The <see cref="PList.NSObject"/> to compare with the current <see cref="PList.NSDictionary"/>.</param> /// <returns><c>true</c> if the specified <see cref="PList.NSObject"/> is equal to the current /// <see cref="PList.NSDictionary"/>; otherwise, <c>false</c>.</returns> public override bool Equals(NSObject obj) { if (!(obj is NSDictionary)) return false; if (((NSDictionary)obj).dict.Count != dict.Count) return false; bool found; foreach (KeyValuePair<string, NSObject> kvp in dict) { NSObject nsoB; found = ((NSDictionary)obj).dict.TryGetValue(kvp.Key, out nsoB); if (!found) return false; if (!kvp.Value.Equals(nsoB)) return false; } return true; } /// <summary> /// Serves as a hash function for a <see cref="PList.NSDictionary"/> object. /// </summary> /// <returns>A hash code for this instance that is suitable for use in hashing algorithms and data structures such as a /// hash table.</returns> public override int GetHashCode() { int hash = 7; hash = 83 * hash + (dict != null ? dict.GetHashCode() : 0); return hash; } internal override void ToXml(StringBuilder xml, int level) { Indent(xml, level); xml.Append("<dict>"); xml.Append(NSObject.NEWLINE); foreach (KeyValuePair<string, NSObject> kvp in dict) { Indent(xml, level + 1); xml.Append("<key>"); //According to http://www.w3.org/TR/REC-xml/#syntax node values must not //contain the characters < or &. Also the > character should be escaped. if (kvp.Key.Contains("&") || kvp.Key.Contains("<") || kvp.Key.Contains(">")) { xml.Append("<![CDATA["); xml.Append(kvp.Key.Replace("]]>", "]]]]><![CDATA[>")); xml.Append("]]>"); } else { xml.Append(kvp.Key); } xml.Append("</key>"); xml.Append(NSObject.NEWLINE); kvp.Value.ToXml(xml, level + 1); xml.Append(NSObject.NEWLINE); } Indent(xml, level); xml.Append("</dict>"); } internal override void AssignIDs(BinaryPropertyListWriter outPlist) { base.AssignIDs(outPlist); foreach (KeyValuePair<string, NSObject> entry in dict) { new NSString(entry.Key).AssignIDs(outPlist); } foreach (KeyValuePair<string, NSObject> entry in dict) { entry.Value.AssignIDs(outPlist); } } internal override void ToBinary(BinaryPropertyListWriter outPlist) { outPlist.WriteIntHeader(0xD, dict.Count); foreach (KeyValuePair<String, NSObject> entry in dict) { outPlist.WriteID(outPlist.GetID(new NSString(entry.Key))); } foreach (KeyValuePair<String, NSObject> entry in dict) { outPlist.WriteID(outPlist.GetID(entry.Value)); } } /// <summary> /// Generates a valid ASCII property list which has this NSDictionary as its /// root object. The generated property list complies with the format as /// described in https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/PropertyLists/OldStylePlists/OldStylePLists.html /// Property List Programming Guide - Old-Style ASCII Property Lists. /// </summary> /// <returns>ASCII representation of this object.</returns> public string ToASCIIPropertyList() { StringBuilder ascii = new StringBuilder(); ToASCII(ascii, 0); ascii.Append(NEWLINE); return ascii.ToString(); } /// <summary> /// Generates a valid ASCII property list in GnuStep format which has this /// NSDictionary as its root object. The generated property list complies with /// the format as described in http://www.gnustep.org/resources/documentation/Developer/Base/Reference/NSPropertyList.html /// GnuStep - NSPropertyListSerialization class documentation. /// </summary> /// <returns>GnuStep ASCII representation of this object.</returns> public string ToGnuStepASCIIPropertyList() { StringBuilder ascii = new StringBuilder(); ToASCIIGnuStep(ascii, 0); ascii.Append(NEWLINE); return ascii.ToString(); } internal override void ToASCII(StringBuilder ascii, int level) { Indent(ascii, level); ascii.Append(ASCIIPropertyListParser.DICTIONARY_BEGIN_TOKEN); ascii.Append(NEWLINE); foreach (string key in Keys) { NSObject val = ObjectForKey(key); Indent(ascii, level + 1); ascii.Append("\""); ascii.Append(NSString.EscapeStringForASCII(key)); ascii.Append("\" ="); Type objClass = val.GetType(); if (objClass.Equals(typeof(NSDictionary)) || objClass.Equals(typeof(NSArray)) || objClass.Equals(typeof(NSData))) { ascii.Append(NEWLINE); val.ToASCII(ascii, level + 2); } else { ascii.Append(" "); val.ToASCII(ascii, 0); } ascii.Append(ASCIIPropertyListParser.DICTIONARY_ITEM_DELIMITER_TOKEN); ascii.Append(NEWLINE); } Indent(ascii, level); ascii.Append(ASCIIPropertyListParser.DICTIONARY_END_TOKEN); } internal override void ToASCIIGnuStep(StringBuilder ascii, int level) { Indent(ascii, level); ascii.Append(ASCIIPropertyListParser.DICTIONARY_BEGIN_TOKEN); ascii.Append(NEWLINE); foreach (string key in Keys) { NSObject val = ObjectForKey(key); Indent(ascii, level + 1); ascii.Append("\""); ascii.Append(NSString.EscapeStringForASCII(key)); ascii.Append("\" ="); Type objClass = val.GetType(); if (objClass.Equals(typeof(NSDictionary)) || objClass.Equals(typeof(NSArray)) || objClass.Equals(typeof(NSData))) { ascii.Append(NEWLINE); val.ToASCIIGnuStep(ascii, level + 2); } else { ascii.Append(" "); val.ToASCIIGnuStep(ascii, 0); } ascii.Append(ASCIIPropertyListParser.DICTIONARY_ITEM_DELIMITER_TOKEN); ascii.Append(NEWLINE); } Indent(ascii, level); ascii.Append(ASCIIPropertyListParser.DICTIONARY_END_TOKEN); } #region IDictionary implementation /// <summary> /// Add the specified key and value. /// </summary> /// <param name="key">Key.</param> /// <param name="value">Value.</param> public void Add(string key, NSObject value) { dict.Add(key, value); } /// <summary> /// Checks if there is any item contained in the current instance corresponding with the specified key. /// </summary> /// <returns><c>true</c>, if key was contained, <c>false</c> otherwise.</returns> /// <param name="key">Key.</param> public bool ContainsKey(string key) { return dict.ContainsKey(key); } /// <summary> /// Checks if there is any item contained in the current instance corresponding with the specified value. /// </summary> /// <returns><c>true</c>, if value is contained, <c>false</c> otherwise.</returns> /// <param name="value">Key.</param> public bool ContainsValue(NSObject value) { return dict.ContainsValue(value); } /// <summary> /// Removes the item belonging to the specified key. /// </summary> /// <param name="key">Key.</param> public bool Remove(string key) { return dict.Remove(key); } /// <summary> /// Tries to get the item corresponding to the specified key /// </summary> /// <returns><c>true</c>, if get value was successfully found and retrieved, <c>false</c> otherwise.</returns> /// <param name="key">Key.</param> /// <param name="value">Where to store the value.</param> public bool TryGetValue(string key, out NSObject value) { return dict.TryGetValue(key, out value); } /// <summary> /// Gets or sets the <see cref="PList.NSObject"/> at the specified index. /// </summary> /// <param name="index">Index.</param> public NSObject this[string index] { get { return dict[index]; } set { dict[index] = value; } } /// <summary> /// Gets an array with all the keys contained in the current instance. /// </summary> /// <value>The keys.</value> public ICollection<string> Keys { get { return dict.Keys; } } /// <summary> /// Gets an array with all the objects contained in the current instance. /// </summary> /// <value>The objects.</value> public ICollection<NSObject> Values { get { return dict.Values; } } #endregion #region ICollection implementation /// <summary> /// Adds the specified item. /// </summary> /// <param name="item">Item.</param> public void Add(KeyValuePair<string, NSObject> item) { dict.Add(item.Key, item.Value); } /// <summary> /// Clears this instance. /// </summary> public void Clear() { dict.Clear(); } /// <summary> /// Checks if the current instance contains the specified item. /// </summary> /// <param name="item">Item.</param> /// <returns><c>true</c> if it is found, <c>false</c> otherwise.</returns> public bool Contains(KeyValuePair<string, NSObject> item) { return dict.ContainsKey(item.Key); } /// <summary> /// Copies the <see cref="Dictionary{TKey, TValue}.ValueCollection"/> elements to an existing one-dimensional <see cref="Array"/>, starting at the specified array index. /// </summary> /// <param name="array">The one-dimensional <see cref="Array"/> that is the destination of the elements copied from <see cref="Dictionary{TKey, TValue}.ValueCollection"/>. The <see cref="Array"/> must have zero-based indexing.</param> /// <param name="arrayIndex">The zero-based index in array at which copying begins.</param> public void CopyTo(KeyValuePair<string, NSObject>[] array, int arrayIndex) { ICollection<KeyValuePair<string, NSObject>> coll = dict; coll.CopyTo(array, arrayIndex); } /// <summary> /// Removes the specified item. /// </summary> /// <param name="item">Item to remove.</param> /// <returns><c>true</c> if successfully removed, <c>false</c> if not, or if item is not in current instance.</returns> public bool Remove(KeyValuePair<string, NSObject> item) { return dict.Remove(item.Key); } /// <summary> /// Gets the count of items in the current instance. /// </summary> /// <value>How many items are contained in the current instance.</value> public int Count { get { return dict.Count; } } /// <summary> /// Gets a value indicating whether this instance is read only. /// </summary> /// <value><c>true</c> if this instance is read only; otherwise, <c>false</c>.</value> public bool IsReadOnly { get { return false; } } #endregion #region IEnumerable implementation /// <summary> /// Gets the enumerator. /// </summary> /// <returns>The enumerator.</returns> public IEnumerator<KeyValuePair<string, NSObject>> GetEnumerator() { return dict.GetEnumerator(); } #endregion #region IEnumerable implementation System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return dict.GetEnumerator(); } #endregion } }
2881099/dotnetGen_postgresql
14,735
GenPg/plist-cil/PropertyListParser.cs
// plist-cil - An open source library to parse and generate property lists for .NET // Copyright (C) 2015 Natalia Portillo // // This code is based on: // plist - An open source library to parse and generate property lists // Copyright (C) 2014 Daniel Dreibrodt // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. using System; using System.Text; using System.IO; namespace PList { /// <summary> /// This class provides methods to parse property lists. It can handle files, /// input streams and byte arrays. All known property list formats are supported. /// /// This class also provides methods to save and convert property lists. /// </summary> /// @author Daniel Dreibrodt /// @author Natalia Portillo public static class PropertyListParser { const int TYPE_XML = 0; const int TYPE_BINARY = 1; const int TYPE_ASCII = 2; const int TYPE_ERROR_BLANK = 10; const int TYPE_ERROR_UNKNOWN = 11; /// <summary> /// Determines the type of a property list by means of the first bytes of its data /// </summary> /// <returns>The type of the property list</returns> /// <param name="dataBeginning">The very first bytes of data of the property list (minus any whitespace) as a string</param> static int DetermineType(string dataBeginning) { dataBeginning = dataBeginning.Trim(); if (dataBeginning.Length == 0) { return TYPE_ERROR_BLANK; } if (dataBeginning.StartsWith("bplist")) { return TYPE_BINARY; } if (dataBeginning.StartsWith("(") || dataBeginning.StartsWith("{") || dataBeginning.StartsWith("/")) { return TYPE_ASCII; } return dataBeginning.StartsWith("<") ? TYPE_XML : TYPE_ERROR_UNKNOWN; } /// <summary> /// Determines the type of a property list by means of the first bytes of its data /// </summary> /// <returns>The very first bytes of data of the property list (minus any whitespace)</returns> /// <param name="bytes">The type of the property list</param> static int DetermineType(byte[] bytes) { //Skip any possible whitespace at the beginning of the file int offset = 0; if (bytes.Length >= 3 && (bytes[0] & 0xFF) == 0xEF && (bytes[1] & 0xFF) == 0xBB && (bytes[2] & 0xFF) == 0xBF) { //Skip Unicode byte order mark (BOM) offset += 3; } while (offset < bytes.Length && (bytes[offset] == ' ' || bytes[offset] == '\t' || bytes[offset] == '\r' || bytes[offset] == '\n' || bytes[offset] == '\f')) { offset++; } return DetermineType(Encoding.ASCII.GetString(bytes, offset, Math.Min(8, bytes.Length - offset))); } /// <summary> /// Determines the type of a property list by means of the first bytes of its data /// </summary> /// <returns>The type of the property list</returns> /// <param name="fs">An input stream pointing to the beginning of the property list data. /// The stream will be reset to the beginning of the property /// list data after the type has been determined.</param> static int DetermineType(Stream fs) { //Skip any possible whitespace at the beginning of the file byte[] magicBytes = new byte[8]; int b; long index = -1; bool bom = false; long mark; do { mark = fs.Position; b = fs.ReadByte(); index++; //Check if we are reading the Unicode byte order mark (BOM) and skip it bom = index < 3 && ((index == 0 && b == 0xEF) || (bom && ((index == 1 && b == 0xBB) || (index == 2 && b == 0xBF)))); } while (b != -1 && b == ' ' || b == '\t' || b == '\r' || b == '\n' || b == '\f' || bom); magicBytes[0] = (byte)b; int read = fs.Read(magicBytes, 1, 7); int type = DetermineType(Encoding.ASCII.GetString(magicBytes, 0, read)); fs.Seek(mark, SeekOrigin.Begin); //if(fs.markSupported()) // fs.reset(); return type; } /// <summary> /// Reads all bytes from an Stream and stores them in an array, up to /// a maximum count. /// </summary> /// <param name="fs">The Stream pointing to the data that should be stored in the array.</param> internal static byte[] ReadAll(Stream fs) { using (MemoryStream outputStream = new MemoryStream()) { fs.CopyTo(outputStream); return outputStream.ToArray(); } } /// <summary> /// Parses a property list from a file. /// </summary> /// <param name="filePath">Path to the property list file.</param> /// <returns>The root object in the property list. This is usually a NSDictionary but can also be a NSArray.</returns> public static NSObject Parse(string filePath) { return Parse(new FileInfo(filePath)); } /// <summary> /// Parses a property list from a file. /// </summary> /// <param name="f">The property list file.</param> /// <returns>The root object in the property list. This is usually a NSDictionary but can also be a NSArray.</returns> public static NSObject Parse(FileInfo f) { int type; using (FileStream fis = f.OpenRead()) { type = DetermineType(fis); } switch (type) { case TYPE_BINARY: return BinaryPropertyListParser.Parse(f); case TYPE_XML: return XmlPropertyListParser.Parse(f); case TYPE_ASCII: return ASCIIPropertyListParser.Parse(f); default: throw new PropertyListFormatException("The given file is not a property list of a supported format."); } } /// <summary> /// Parses a property list from a byte array. /// </summary> /// <param name="bytes">The property list data as a byte array.</param> /// <returns>The root object in the property list. This is usually a NSDictionary but can also be a NSArray.</returns> public static NSObject Parse(byte[] bytes) { switch (DetermineType(bytes)) { case TYPE_BINARY: return BinaryPropertyListParser.Parse(bytes); case TYPE_XML: return XmlPropertyListParser.Parse(bytes); case TYPE_ASCII: return ASCIIPropertyListParser.Parse(bytes); default: throw new PropertyListFormatException("The given data is not a property list of a supported format."); } } /// <summary> /// Parses a property list from an Stream. /// </summary> /// <param name="fs">The Stream delivering the property list data.</param> /// <returns>The root object of the property list. This is usually a NSDictionary but can also be a NSArray.</returns> public static NSObject Parse(Stream fs) { return Parse(ReadAll(fs)); } /// <summary> /// Saves a property list with the given object as root into a XML file. /// </summary> /// <param name="root">The root object.</param> /// <param name="outFile">The output file.</param> /// <exception cref="IOException">When an error occurs during the writing process.</exception> public static void SaveAsXml(NSObject root, FileInfo outFile) { string parent = outFile.DirectoryName; if (!Directory.Exists(parent)) Directory.CreateDirectory(parent); // Use Create here -- to make sure that when the updated file is shorter than // the original file, no "obsolete" data is left at the end. using (Stream fous = outFile.Open(FileMode.Create, FileAccess.ReadWrite)) { SaveAsXml(root, fous); } } /// <summary> /// Saves a property list with the given object as root in XML format into an output stream. /// </summary> /// <param name="root">The root object.</param> /// <param name="outStream">The output stream.</param> /// <exception cref="IOException">When an error occurs during the writing process.</exception> public static void SaveAsXml(NSObject root, Stream outStream) { #if NET40 // The StreamWriter constructor which takes a "leaveOpen" parameter is // not available on .NET 4.0 StreamWriter w = new StreamWriter(outStream, Encoding.UTF8); w.Write(root.ToXmlPropertyList()); w.Close(); #else using (StreamWriter w = new StreamWriter(outStream, Encoding.UTF8, bufferSize: 1024, leaveOpen: true)) { w.Write(root.ToXmlPropertyList()); } #endif } /// <summary> /// Converts a given property list file into the OS X and iOS XML format. /// </summary> /// <param name="inFile">The source file.</param> /// <param name="outFile">The target file.</param> public static void ConvertToXml(FileInfo inFile, FileInfo outFile) { NSObject root = Parse(inFile); SaveAsXml(root, outFile); } /// <summary> /// Saves a property list with the given object as root into a binary file. /// </summary> /// <param name="root">The root object.</param> /// <param name="outFile">The output file.</param> /// <exception cref="IOException">When an error occurs during the writing process.</exception> public static void SaveAsBinary(NSObject root, FileInfo outFile) { string parent = outFile.DirectoryName; if (!Directory.Exists(parent)) Directory.CreateDirectory(parent); BinaryPropertyListWriter.Write(outFile, root); } /// <summary> /// Saves a property list with the given object as root in binary format into an output stream. /// </summary> /// <param name="root">The root object.</param> /// <param name="outStream">The output stream.</param> /// <exception cref="IOException">When an error occurs during the writing process.</exception> public static void SaveAsBinary(NSObject root, Stream outStream) { BinaryPropertyListWriter.Write(outStream, root); } /// <summary> /// Converts a given property list file into the OS X and iOS binary format. /// </summary> /// <param name="inFile">The source file.</param> /// <param name="outFile">The target file.</param> public static void ConvertToBinary(FileInfo inFile, FileInfo outFile) { NSObject root = Parse(inFile); SaveAsBinary(root, outFile); } /// <summary> /// Saves a property list with the given object as root into a ASCII file. /// </summary> /// <param name="root">The root object.</param> /// <param name="outFile">The output file.</param> /// <exception cref="IOException">When an error occurs during the writing process.</exception> public static void SaveAsASCII(NSDictionary root, FileInfo outFile) { string parent = outFile.DirectoryName; if (!Directory.Exists(parent)) Directory.CreateDirectory(parent); using (Stream fous = outFile.Open(FileMode.OpenOrCreate, FileAccess.ReadWrite)) using (StreamWriter w = new StreamWriter(fous, Encoding.ASCII)) { w.Write(root.ToASCIIPropertyList()); } } /// <summary> /// Saves a property list with the given object as root into a ASCII file. /// </summary> /// <param name="root">The root object.</param> /// <param name="outFile">The output file.</param> /// <exception cref="IOException">When an error occurs during the writing process.</exception> public static void SaveAsASCII(NSArray root, FileInfo outFile) { string parent = outFile.DirectoryName; if (!Directory.Exists(parent)) Directory.CreateDirectory(parent); using (Stream fous = outFile.Open(FileMode.OpenOrCreate, FileAccess.ReadWrite)) using (StreamWriter w = new StreamWriter(fous, Encoding.ASCII)) { w.Write(root.ToASCIIPropertyList()); } } /// <summary> /// Converts a given property list file into ASCII format. /// </summary> /// <param name="inFile">The source file.</param> /// <param name="outFile">The target file.</param> public static void ConvertToASCII(FileInfo inFile, FileInfo outFile) { NSObject root = Parse(inFile); if (root is NSDictionary) { SaveAsASCII((NSDictionary)root, outFile); } else if (root is NSArray) { SaveAsASCII((NSArray)root, outFile); } else { throw new PropertyListFormatException("The root of the given input property list " + "is neither a Dictionary nor an Array!"); } } /// <summary> /// Saves a property list with the given object as root into a GnuStep ASCII file. /// </summary> /// <param name="root">The root object.</param> /// <param name="outFile">The output file.</param> /// <exception cref="IOException">When an error occurs during the writing process.</exception> public static void SaveAsGnuStepASCII(NSDictionary root, FileInfo outFile) { string parent = outFile.DirectoryName; if (!Directory.Exists(parent)) Directory.CreateDirectory(parent); using (Stream fous = outFile.Open(FileMode.OpenOrCreate, FileAccess.ReadWrite)) using (StreamWriter w = new StreamWriter(fous, Encoding.ASCII)) { w.Write(root.ToGnuStepASCIIPropertyList()); } } /// <summary> /// Saves a property list with the given object as root into a GnuStep ASCII file. /// </summary> /// <param name="root">The root object.</param> /// <param name="outFile">The output file.</param> /// <exception cref="IOException">When an error occurs during the writing process.</exception> public static void SaveAsGnuStepASCII(NSArray root, FileInfo outFile) { string parent = outFile.DirectoryName; if (!Directory.Exists(parent)) Directory.CreateDirectory(parent); using (Stream fous = outFile.Open(FileMode.OpenOrCreate, FileAccess.ReadWrite)) using (StreamWriter w = new StreamWriter(fous, Encoding.ASCII)) { w.Write(root.ToGnuStepASCIIPropertyList()); } } /// <summary> /// Converts a given property list file into GnuStep ASCII format. /// </summary> /// <param name="inFile">The source file.</param> /// <param name="outFile">The target file.</param> public static void ConvertToGnuStepASCII(FileInfo inFile, FileInfo outFile) { NSObject root = Parse(inFile); if (root is NSDictionary) { SaveAsGnuStepASCII((NSDictionary)root, outFile); } else if (root is NSArray) { SaveAsGnuStepASCII((NSArray)root, outFile); } else { throw new PropertyListFormatException("The root of the given input property list " + "is neither a Dictionary nor an Array!"); } } } }
2881099/dotnetGen_postgresql
3,038
GenPg/plist-cil/NSArray.IList.cs
// plist-cil - An open source library to parse and generate property lists for .NET // Copyright (C) 2016 Quamotion // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; namespace PList { partial class NSArray : IList<NSObject> { /// <inheritdoc/> public NSObject this[int index] { get { return this.array[index]; } set { this.array[index] = value; } } /// <inheritdoc/> public bool IsReadOnly { get { return false; } } public void Add(object item) { this.Add(NSObject.Wrap(item)); } /// <inheritdoc/> public void Add(NSObject item) { this.array.Add(item); } /// <inheritdoc/> public void Clear() { this.array.Clear(); } public bool Contains(object item) { return this.Contains(NSObject.Wrap(item)); } /// <inheritdoc/> public bool Contains(NSObject item) { return this.array.Contains(item); } /// <inheritdoc/> public void CopyTo(NSObject[] array, int arrayIndex) { this.array.CopyTo(array, arrayIndex); } /// <inheritdoc/> public IEnumerator<NSObject> GetEnumerator() { return this.array.GetEnumerator(); } public int IndexOf(object item) { return this.array.IndexOf(NSObject.Wrap(item)); } /// <inheritdoc/> public int IndexOf(NSObject item) { return this.array.IndexOf(item); } public void Insert(int index, object item) { this.Insert(index, NSObject.Wrap(item)); } /// <inheritdoc/> public void Insert(int index, NSObject item) { this.array.Insert(index, item); } public bool Remove(object item) { return this.Remove(NSObject.Wrap(item)); } /// <inheritdoc/> public bool Remove(NSObject item) { return this.array.Remove(item); } /// <inheritdoc/> public void RemoveAt(int index) { this.array.RemoveAt(index); } /// <inheritdoc/> IEnumerator IEnumerable.GetEnumerator() { return this.array.GetEnumerator(); } } }
2881099/dotnetGen_sqlserver
36,291
GenMs/NPinyin/PyHash.cs
using System; using System.Collections.Generic; using System.Text; namespace NPinyin { internal class PyHash { internal static short[][] hashes = new short[][] { new short[]{23, 70, 96, 128, 154, 165, 172, 195}, new short[]{25, 35, 87, 108, 120, 128, 132, 137, 168, 180, 325, 334, 336, 353, 361, 380}, new short[]{23, 34, 46, 81, 82, 87, 134, 237, 255, 288, 317, 322, 354, 359}, new short[]{7, 11, 37, 49, 53, 56, 131, 132, 146, 176, 315, 372}, new short[]{11, 69, 73, 87, 96, 103, 159, 175, 195, 296, 298, 359, 361}, new short[]{57, 87, 115, 126, 149, 244, 282, 298, 308, 345, 355}, new short[]{19, 37, 117, 118, 141, 154, 196, 216, 267, 301, 327, 333, 337, 347}, new short[]{4, 11, 59, 61, 62, 87, 119, 169, 183, 198, 262, 334, 362, 380}, new short[]{37, 135, 167, 170, 246, 250, 334, 341, 351, 354, 386, 390, 398}, new short[]{5, 6, 52, 55, 76, 146, 165, 244, 256, 266, 300, 318, 331}, new short[]{6, 71, 94, 129, 137, 141, 169, 179, 225, 226, 235, 248, 289, 290, 333, 345, 391}, new short[]{0, 33, 37, 62, 90, 131, 205, 246, 268, 343, 349, 380}, new short[]{31, 62, 85, 115, 117, 150, 159, 167, 171, 204, 215, 252, 343}, new short[]{69, 81, 98, 140, 165, 195, 239, 240, 259, 265, 329, 368, 375, 392, 393}, new short[]{13, 81, 82, 123, 132, 144, 154, 165, 334, 336, 345, 348, 349, 355, 367, 377, 383}, new short[]{31, 32, 44, 57, 76, 83, 87, 129, 151, 172, 176, 183, 184, 193, 221, 235, 285, 288, 305}, new short[]{10, 14, 60, 76, 85, 97, 115, 125, 128, 130, 286, 288, 301, 313, 382}, new short[]{62, 128, 136, 175, 211, 240, 254, 273, 274, 317, 330, 344, 349, 360, 380}, new short[]{29, 47, 52, 116, 126, 127, 130, 133, 191, 284, 288, 306, 353, 361, 383}, new short[]{1, 15, 25, 67, 83, 90, 117, 121, 150, 228, 308, 324, 336, 351, 386}, new short[]{34, 37, 67, 101, 103, 117, 127, 165, 168, 254, 267, 272, 274, 288, 305, 310, 323, 329, 333, 358, 378}, new short[]{5, 74, 103, 135, 163, 165, 171, 244, 262, 266, 334, 352, 390, 397}, new short[]{4, 17, 95, 125, 165, 186, 203, 221, 252, 282, 317, 333, 339, 348, 351, 353}, new short[]{74, 79, 81, 84, 92, 110, 116, 117, 131, 132, 154, 199, 241, 251, 300, 306, 349, 359, 383, 387}, new short[]{40, 83, 127, 144, 161, 188, 249, 288, 344, 382, 388}, new short[]{8, 55, 61, 76, 85, 98, 111, 127, 186, 230, 241, 247, 267, 287, 327, 341, 344, 347, 359, 364}, new short[]{20, 59, 69, 80, 117, 129, 176, 186, 191, 237, 275, 289, 309, 338, 375, 380}, new short[]{5, 15, 25, 35, 40, 129, 174, 236, 274, 337, 347}, new short[]{14, 22, 47, 56, 87, 120, 129, 144, 155, 160, 237, 283, 284, 309, 327, 337, 365, 372}, new short[]{1, 14, 47, 132, 198, 254, 255, 300, 310, 335, 336, 372}, new short[]{2, 36, 64, 96, 125, 176, 184, 190, 211, 271, 308, 315, 367}, new short[]{20, 76, 79, 81, 110, 117, 120, 129, 182, 192, 235, 353, 378}, new short[]{37, 83, 88, 92, 111, 127, 243, 303, 324, 325, 348, 353, 359, 371, 377}, new short[]{5, 87, 90, 124, 127, 180, 259, 288, 290, 302, 312, 313, 324, 332}, new short[]{55, 62, 89, 98, 108, 132, 168, 240, 248, 322, 325, 327, 347, 353, 391, 396}, new short[]{4, 8, 13, 35, 37, 39, 41, 64, 111, 174, 212, 245, 248, 251, 263, 288, 335, 373, 375}, new short[]{10, 39, 93, 110, 168, 227, 228, 254, 288, 336, 378, 381}, new short[]{75, 92, 122, 176, 198, 211, 214, 283, 334, 353, 359, 379, 386}, new short[]{5, 8, 13, 19, 57, 87, 104, 125, 130, 176, 202, 249, 252, 290, 309, 391}, new short[]{88, 132, 173, 176, 235, 247, 253, 292, 324, 328, 339, 359}, new short[]{19, 32, 61, 84, 87, 118, 120, 125, 129, 132, 181, 190, 288, 290, 331, 355, 359, 366}, new short[]{13, 25, 46, 126, 140, 157, 165, 225, 226, 252, 288, 304, 327, 353, 378}, new short[]{12, 14, 26, 56, 72, 95, 131, 132, 134, 142, 253, 298, 337, 361, 391}, new short[]{4, 18, 37, 49, 87, 93, 196, 225, 226, 246, 248, 250, 255, 310, 354, 358}, new short[]{64, 87, 110, 111, 128, 135, 151, 165, 177, 188, 191, 268, 312, 334, 352, 354, 357, 371}, new short[]{10, 17, 19, 30, 40, 48, 81, 97, 125, 129, 130, 182, 234, 305, 328, 393}, new short[]{13, 69, 80, 114, 192, 200, 235, 343, 345, 353, 354, 360, 374, 378, 383}, new short[]{83, 87, 94, 105, 107, 124, 144, 153, 219, 290, 298, 324, 349, 358, 367}, new short[]{10, 36, 142, 169, 221, 232, 241, 246, 346, 347, 375, 383, 390}, new short[]{26, 104, 126, 143, 176, 186, 241, 247, 250, 318, 320, 333, 360}, new short[]{66, 92, 116, 148, 191, 215, 254, 333, 334, 335, 336, 351, 353, 358, 380}, new short[]{9, 37, 55, 56, 76, 79, 90, 111, 122, 124, 161, 192, 247, 313, 353, 359, 374}, new short[]{17, 30, 34, 56, 64, 68, 90, 125, 151, 168, 176, 188, 286, 333, 338, 360}, new short[]{26, 143, 173, 182, 190, 194, 246, 284, 286, 328, 333, 355, 357, 360, 362, 363, 377, 380}, new short[]{1, 13, 87, 122, 168, 171, 186, 201, 297, 328, 349, 352, 380}, new short[]{18, 39, 61, 88, 98, 123, 129, 131, 148, 162, 165, 243, 285, 314, 340, 349, 360, 377, 378}, new short[]{67, 98, 117, 118, 122, 128, 156, 174, 184, 207, 244, 250, 330, 335, 342, 372, 375}, new short[]{13, 38, 63, 160, 180, 185, 189, 190, 219, 248, 253, 275, 297, 318, 355}, new short[]{1, 44, 47, 93, 107, 172, 235, 276, 281, 287, 290, 306, 333, 334, 337, 347, 353, 376}, new short[]{13, 15, 32, 125, 127, 157, 165, 176, 236, 344, 350, 381}, new short[]{47, 65, 93, 134, 159, 174, 218, 282, 318, 336, 358, 373, 379}, new short[]{7, 17, 40, 66, 102, 141, 154, 159, 165, 172, 174, 177, 328, 329, 334, 348, 379, 382}, new short[]{4, 34, 36, 76, 79, 122, 127, 138, 176, 241, 267, 309, 334, 367, 382}, new short[]{9, 17, 33, 46, 90, 103, 125, 138, 144, 157, 185, 198, 224, 250, 260, 291, 326, 343, 349, 377, 381}, new short[]{29, 31, 53, 58, 134, 138, 193, 287, 305, 308, 333, 334}, new short[]{13, 64, 83, 93, 129, 192, 227, 244, 397}, new short[]{7, 8, 14, 78, 85, 103, 138, 175, 176, 200, 203, 234, 301, 313, 361}, new short[]{13, 75, 87, 111, 244, 253, 288, 321, 339, 341, 357, 395}, new short[]{4, 14, 42, 64, 69, 108, 110, 117, 122, 131, 159, 163, 188, 198, 200, 206, 244, 292, 300, 354, 390}, new short[]{14, 37, 73, 87, 129, 135, 144, 176, 182, 300, 346, 352, 380, 383}, new short[]{23, 50, 87, 143, 171, 186, 191, 223, 290, 333, 334, 364, 378, 380, 388, 391, 393}, new short[]{5, 14, 23, 36, 62, 71, 76, 95, 99, 128, 176, 211, 229, 357}, new short[]{12, 33, 47, 70, 81, 90, 97, 119, 122, 131, 189, 190, 191, 235, 244, 253, 320, 350, 359}, new short[]{10, 13, 23, 93, 110, 120, 135, 171, 195, 250, 293, 298, 329, 344, 354}, new short[]{13, 29, 37, 163, 169, 200, 211, 214, 217, 236, 246, 249, 282, 327, 349, 353, 362, 372}, new short[]{5, 13, 23, 41, 57, 62, 76, 89, 111, 135, 195, 234, 248, 314, 334, 341, 349, 380}, new short[]{17, 35, 57, 117, 121, 206, 235, 243, 265, 329, 358, 374}, new short[]{13, 28, 41, 55, 69, 101, 103, 126, 138, 198, 267, 276, 288, 313, 334, 335, 339, 354, 376, 383, 394}, new short[]{11, 13, 19, 36, 38, 58, 75, 124, 232, 235, 265, 286, 298, 330, 333, 359}, new short[]{4, 19, 25, 43, 110, 125, 165, 331, 334, 341, 349, 355, 372}, new short[]{40, 55, 64, 70, 117, 126, 127, 135, 160, 172, 173, 186, 270, 318, 338, 344, 378}, new short[]{122, 176, 198, 238, 246, 284, 286, 290, 318, 329, 337, 381, 394}, new short[]{23, 36, 37, 44, 117, 124, 198, 204, 233, 248, 282, 288, 297, 314, 332, 336, 388}, new short[]{15, 33, 54, 64, 75, 85, 115, 127, 165, 196, 229, 237, 254, 307, 327, 335, 349, 383}, new short[]{22, 87, 121, 127, 161, 180, 248, 250, 276, 313, 324, 347, 349, 355, 357, 359}, new short[]{14, 48, 67, 88, 130, 131, 172, 188, 195, 203, 267, 282, 333, 339, 350, 392}, new short[]{22, 31, 37, 98, 118, 132, 135, 137, 142, 151, 243, 244, 282, 305, 333, 349, 350, 351, 353, 358, 374}, new short[]{15, 42, 67, 75, 125, 134, 189, 255, 261, 309, 334, 350, 380, 382}, new short[]{10, 39, 87, 97, 105, 109, 125, 137, 225, 226, 253, 329, 341, 354, 363, 372}, new short[]{5, 17, 42, 64, 80, 111, 120, 169, 175, 206, 237, 267, 288, 290, 324, 351, 364, 390}, new short[]{3, 33, 55, 75, 91, 97, 103, 132, 187, 220, 232, 234, 240, 288, 301, 330, 336, 337, 338, 340, 359, 374, 380, 382}, new short[]{13, 87, 98, 125, 126, 127, 128, 250, 330, 341, 353, 360, 374, 382, 391}, new short[]{59, 66, 75, 125, 135, 172, 192, 230, 231, 255, 256, 276, 300, 306, 339, 349, 353, 390}, new short[]{25, 36, 56, 90, 107, 125, 127, 142, 165, 195, 244, 246, 319, 347, 355, 375, 380}, new short[]{2, 33, 35, 36, 72, 74, 87, 92, 111, 131, 145, 176, 244, 248, 282, 333, 355, 359}, new short[]{5, 39, 127, 134, 137, 200, 240, 283, 284, 343, 344, 372}, new short[]{9, 32, 37, 80, 96, 104, 110, 117, 154, 176, 244, 297, 298, 339, 353, 374, 381}, new short[]{38, 51, 64, 76, 80, 93, 96, 134, 150, 173, 275, 290, 340, 347, 359, 363, 380}, new short[]{55, 89, 111, 126, 157, 159, 162, 182, 188, 244, 253, 280, 334, 359, 384, 398}, new short[]{59, 64, 75, 81, 97, 105, 115, 125, 155, 198, 248, 262, 319, 323, 376}, new short[]{13, 41, 76, 125, 127, 130, 134, 135, 159, 167, 183, 229, 230, 240, 246, 308, 319, 329, 333, 334, 340, 344, 363, 382}, new short[]{8, 13, 19, 31, 70, 76, 79, 96, 127, 153, 163, 165, 184, 227, 230, 247, 255, 336, 337, 348, 353, 357, 361, 362}, new short[]{71, 87, 111, 121, 130, 142, 150, 160, 175, 224, 248, 314, 336, 353, 357, 359}, new short[]{67, 84, 101, 130, 287, 288, 332, 333, 359, 361, 377}, new short[]{34, 52, 90, 100, 125, 135, 165, 173, 320, 341, 352, 359, 382, 392}, new short[]{13, 18, 39, 55, 62, 87, 248, 255, 290, 327, 349, 353, 355, 360, 383}, new short[]{1, 9, 12, 29, 32, 36, 82, 139, 140, 149, 153, 165, 167, 180, 185, 231, 241, 244, 274, 299, 309, 329, 355, 362}, new short[]{48, 66, 98, 107, 120, 122, 125, 135, 190, 195, 198, 215, 253, 256, 280, 282, 307, 320, 334, 349, 353, 355}, new short[]{1, 7, 13, 25, 64, 98, 139, 144, 166, 176, 206, 236, 262, 330, 362}, new short[]{37, 55, 116, 123, 125, 131, 165, 234, 266, 276, 328, 329, 342, 349, 353, 359, 391}, new short[]{126, 137, 191, 215, 239, 288, 290, 321, 324, 333, 334, 338, 349, 353, 362, 379}, new short[]{50, 57, 87, 93, 98, 115, 134, 148, 174, 229, 251, 260, 285, 298, 313, 348, 349, 350}, new short[]{5, 13, 31, 45, 69, 81, 108, 122, 127, 160, 165, 176, 179, 237, 244, 301, 316, 352, 360}, new short[]{5, 87, 95, 98, 101, 132, 135, 159, 167, 190, 203, 217, 234, 235, 247, 289, 333, 341, 343, 352}, new short[]{22, 56, 66, 85, 87, 93, 126, 127, 163, 230, 243, 248, 254, 280, 301, 305, 334, 357}, new short[]{13, 19, 53, 59, 76, 91, 117, 122, 195, 298, 303, 309, 337, 345, 398}, new short[]{9, 54, 84, 107, 125, 127, 135, 144, 156, 173, 176, 202, 215, 231, 234, 246, 266, 282, 335, 336, 347, 351, 374}, new short[]{11, 15, 30, 31, 40, 57, 58, 87, 88, 113, 186, 244, 245, 256, 308, 334, 377}, new short[]{62, 111, 176, 196, 228, 231, 288, 294, 302, 306, 350, 353, 375, 378, 392}, new short[]{119, 131, 133, 154, 161, 179, 198, 232, 234, 265, 301, 314, 344, 353, 378}, new short[]{67, 84, 123, 172, 175, 176, 182, 229, 290, 359, 360, 375, 383, 393}, new short[]{33, 36, 39, 102, 116, 136, 137, 208, 234, 256, 307, 329, 341, 347, 376, 380}, new short[]{13, 27, 32, 80, 95, 108, 131, 165, 167, 180, 190, 200, 235, 241, 244, 323, 330, 339, 372}, new short[]{1, 18, 37, 62, 67, 82, 85, 118, 125, 147, 159, 169, 174, 243, 284, 307, 313, 318, 355, 391, 396}, new short[]{10, 87, 91, 135, 169, 176, 215, 246, 267, 282, 295, 320, 345, 353, 380}, new short[]{2, 11, 13, 29, 90, 124, 131, 132, 170, 174, 176, 229, 246, 258, 298, 336, 344, 349}, new short[]{14, 37, 42, 71, 128, 152, 185, 218, 288, 304, 315, 353, 362, 380, 391}, new short[]{17, 20, 36, 73, 93, 128, 163, 194, 211, 217, 282, 290, 320, 354, 383}, new short[]{9, 26, 32, 101, 127, 169, 178, 183, 191, 236, 244, 310, 330, 336, 345, 353, 360, 372, 380, 394}, new short[]{7, 13, 64, 78, 81, 90, 115, 133, 164, 169, 244, 246, 269, 278, 290, 292, 310, 320, 353, 360, 364, 366, 380}, new short[]{8, 65, 81, 84, 91, 126, 129, 158, 183, 184, 194, 254, 262, 333, 334, 339, 351, 363, 382}, new short[]{44, 87, 96, 97, 125, 161, 173, 177, 183, 188, 189, 209, 235, 288, 315, 334, 351}, new short[]{50, 56, 60, 62, 67, 71, 105, 149, 154, 158, 164, 167, 185, 221, 285, 288, 308, 337, 344, 353}, new short[]{6, 10, 37, 62, 74, 79, 81, 128, 139, 154, 167, 198, 228, 244, 267, 290, 302, 368, 394}, new short[]{6, 30, 35, 36, 62, 65, 71, 112, 153, 163, 167, 180, 186, 195, 249, 286, 303, 329, 334}, new short[]{158, 241, 282, 324, 332, 334, 351, 353, 363, 365}, new short[]{17, 89, 117, 144, 165, 180, 185, 198, 229, 244, 290, 334, 335, 380}, new short[]{20, 32, 45, 57, 64, 66, 120, 135, 144, 176, 192, 244, 297, 301, 354, 381}, new short[]{1, 7, 35, 62, 74, 122, 159, 170, 172, 238, 239, 307, 308, 338, 349, 350, 359, 366, 368, 375, 382, 383}, new short[]{7, 9, 23, 66, 92, 103, 111, 135, 182, 203, 246, 247, 265, 285, 288, 303, 317, 329, 348}, new short[]{13, 39, 74, 87, 127, 135, 144, 193, 212, 243, 270, 290, 303, 315, 375, 376}, new short[]{33, 36, 40, 59, 101, 120, 127, 244, 285, 287, 309, 339, 391}, new short[]{4, 10, 39, 195, 268, 284, 336, 354, 359, 375, 381}, new short[]{39, 42, 62, 79, 83, 84, 101, 109, 132, 138, 202, 215, 277, 353, 358, 359}, new short[]{10, 39, 46, 73, 84, 87, 132, 170, 192, 219, 232, 246, 288, 320, 337}, new short[]{10, 12, 56, 87, 91, 101, 132, 227, 254, 301, 303, 333, 343, 347, 351}, new short[]{7, 8, 15, 18, 82, 105, 130, 232, 250, 290, 316, 332, 348, 350}, new short[]{36, 109, 110, 125, 154, 191, 193, 246, 265, 348, 349, 350, 378, 383}, new short[]{12, 16, 45, 57, 87, 92, 101, 105, 129, 130, 155, 167, 218, 292, 293, 327, 349, 354, 361}, new short[]{30, 59, 64, 121, 125, 149, 163, 188, 212, 250, 348, 350, 351, 352, 353, 378, 380}, new short[]{1, 69, 130, 138, 194, 200, 239, 260, 264, 357, 380, 381, 382, 396}, new short[]{7, 10, 19, 40, 57, 61, 125, 137, 141, 212, 239, 251, 310, 333, 347, 359, 380, 383}, new short[]{20, 28, 50, 97, 109, 134, 157, 162, 184, 199, 244, 246, 286, 352, 353, 360, 373, 380}, new short[]{35, 62, 87, 96, 122, 127, 136, 142, 148, 155, 165, 186, 196, 227, 354, 380, 388}, new short[]{81, 82, 101, 115, 125, 200, 243, 313, 351, 359, 367}, new short[]{7, 19, 40, 61, 107, 108, 124, 154, 161, 244, 309, 329, 345, 379, 394}, new short[]{10, 27, 48, 66, 75, 103, 116, 122, 128, 221, 228, 319, 322, 350, 377, 398}, new short[]{2, 64, 74, 117, 130, 165, 172, 180, 191, 218, 221, 288, 299, 325, 347, 353, 355, 360}, new short[]{5, 76, 79, 87, 106, 111, 137, 168, 180, 235, 243, 288, 315, 321, 338, 344, 348, 378, 382, 383}, new short[]{0, 29, 31, 37, 40, 50, 88, 100, 129, 134, 137, 144, 174, 186, 203, 254, 310, 313, 329, 341, 359, 364}, new short[]{69, 70, 71, 96, 115, 121, 130, 157, 159, 200, 230, 246, 250, 299, 318, 324, 353, 359, 380, 391}, new short[]{7, 90, 95, 116, 127, 128, 135, 137, 141, 154, 161, 254, 330, 359, 379, 388}, new short[]{10, 14, 56, 91, 108, 125, 130, 167, 211, 228, 246, 258, 280, 306, 324, 333, 336, 338, 379}, new short[]{4, 5, 14, 57, 85, 98, 125, 135, 136, 176, 254, 334, 336, 337, 351, 358, 362, 379, 383}, new short[]{1, 4, 13, 18, 19, 32, 50, 60, 62, 87, 117, 176, 211, 251, 329, 343, 359}, new short[]{38, 56, 94, 103, 117, 125, 129, 144, 159, 176, 244, 251, 253, 324, 345, 353, 386, 390}, new short[]{4, 22, 38, 47, 59, 64, 82, 97, 110, 135, 153, 176, 235, 236, 241, 287, 288, 303, 333, 347, 358, 359, 361}, new short[]{2, 5, 20, 52, 97, 125, 127, 132, 135, 137, 174, 188, 191, 243, 288, 310, 334, 346, 348, 349, 362, 372, 378}, new short[]{19, 35, 55, 98, 125, 131, 134, 147, 153, 246, 255, 390}, new short[]{5, 59, 62, 129, 136, 153, 198, 225, 235, 239, 254, 295, 334, 338, 341, 359, 361}, new short[]{8, 13, 51, 94, 121, 122, 125, 126, 129, 240, 272, 290, 297, 323, 352, 358, 376, 391, 395}, new short[]{6, 111, 116, 122, 125, 131, 135, 164, 175, 200, 212, 221, 267, 287, 319, 328, 334, 344, 378}, new short[]{83, 108, 143, 172, 176, 192, 198, 246, 262, 286, 287, 308, 338, 340, 343, 348, 353, 367, 380, 383}, new short[]{39, 82, 92, 118, 126, 128, 144, 171, 211, 234, 244, 253, 328, 333, 339, 357, 359, 380}, new short[]{37, 62, 64, 81, 97, 122, 125, 127, 137, 211, 246, 344, 360}, new short[]{7, 29, 62, 67, 69, 81, 87, 107, 132, 151, 160, 229, 244, 284, 285, 317, 358, 387, 390}, new short[]{13, 75, 76, 83, 87, 154, 165, 190, 212, 258, 285, 308, 309, 316, 320, 332, 336, 340, 352, 353, 354, 358, 383}, new short[]{9, 19, 29, 46, 122, 125, 127, 130, 170, 171, 174, 180, 182, 232, 282, 290, 359, 362, 367}, new short[]{13, 40, 71, 98, 101, 116, 125, 127, 169, 172, 175, 283, 288, 309, 311, 313, 323, 334, 353, 391}, new short[]{3, 9, 70, 104, 118, 173, 200, 219, 246, 262, 288, 297, 309, 328, 329, 334, 341, 353}, new short[]{32, 89, 93, 131, 132, 142, 199, 200, 214, 246, 287, 298, 307, 339, 348, 349, 357, 358, 368, 372, 391}, new short[]{103, 134, 159, 176, 186, 235, 261, 276, 282, 290, 301, 317, 329, 345, 356}, new short[]{10, 59, 125, 129, 130, 192, 217, 283, 318, 343, 345, 349, 353, 380, 383, 392}, new short[]{19, 76, 79, 102, 107, 126, 155, 161, 180, 253, 288, 289, 290, 314, 329, 333, 334, 360, 368, 378, 394}, new short[]{12, 92, 98, 105, 137, 149, 172, 196, 198, 244, 260, 262, 282, 298, 329, 345, 353, 368, 390}, new short[]{31, 39, 79, 83, 121, 125, 167, 171, 186, 198, 288, 303, 306, 334, 337, 376}, new short[]{13, 20, 36, 57, 98, 108, 114, 165, 171, 225, 226, 262, 269, 305, 309, 351, 377, 389}, new short[]{13, 51, 71, 93, 110, 129, 130, 156, 165, 170, 173, 183, 191, 200, 211, 212, 255, 266, 299, 301, 329, 336, 348}, new short[]{31, 56, 97, 122, 125, 129, 160, 188, 202, 204, 206, 225, 235, 247, 254, 255, 288, 334, 350, 362, 365, 367}, new short[]{9, 32, 37, 70, 75, 87, 88, 96, 125, 130, 162, 163, 168, 169, 257, 285, 308, 310, 337, 373, 392}, new short[]{18, 40, 42, 47, 73, 76, 85, 105, 108, 125, 130, 132, 134, 167, 191, 284, 310, 311, 344, 358, 361, 374, 378, 379}, new short[]{5, 19, 29, 31, 48, 65, 98, 129, 131, 143, 165, 171, 172, 196, 198, 277, 296, 311, 317, 327, 351, 380}, new short[]{51, 69, 96, 98, 117, 123, 130, 131, 148, 161, 168, 172, 176, 184, 202, 324, 332, 336, 348, 392}, new short[]{1, 20, 37, 57, 70, 76, 79, 87, 165, 176, 234, 251, 333, 388}, new short[]{8, 13, 134, 135, 153, 165, 169, 193, 195, 255, 273, 337, 348, 359, 360, 382, 391}, new short[]{2, 14, 53, 71, 83, 127, 136, 144, 149, 208, 234, 235, 293, 301, 347, 352}, new short[]{20, 40, 42, 95, 135, 141, 165, 199, 250, 290, 299, 308, 337, 338, 350, 353, 354, 355, 358, 380}, new short[]{13, 19, 33, 35, 36, 49, 85, 121, 122, 127, 137, 158, 165, 282, 303, 320, 328, 334, 365, 367, 374}, new short[]{17, 37, 123, 126, 127, 139, 140, 143, 167, 185, 192, 235, 254, 275, 315, 340, 349, 353, 362}, new short[]{57, 72, 127, 159, 163, 165, 176, 199, 215, 218, 238, 254, 284, 288, 336, 339, 347, 352, 380, 395}, new short[]{54, 69, 81, 101, 114, 121, 165, 206, 236, 313, 332, 338, 349, 358, 360, 362, 377}, new short[]{29, 37, 43, 120, 127, 176, 193, 244, 246, 254, 284, 288, 336, 339, 372}, new short[]{36, 56, 85, 122, 125, 126, 154, 232, 282, 308, 314, 315, 324, 336, 353, 359, 382}, new short[]{7, 99, 104, 117, 124, 125, 143, 176, 239, 298, 318, 383}, new short[]{13, 20, 71, 90, 108, 122, 176, 186, 214, 231, 247, 262, 267, 280, 286, 300, 332, 358, 377, 380, 385, 390, 393}, new short[]{31, 65, 75, 79, 85, 91, 109, 110, 120, 159, 229, 235, 288, 298, 347, 355, 359, 379, 381}, new short[]{38, 75, 82, 90, 99, 202, 248, 265, 324, 329, 350, 354, 355, 365}, new short[]{7, 15, 72, 90, 117, 125, 140, 144, 171, 198, 269, 271, 282, 305, 325, 338, 343, 353}, new short[]{13, 14, 20, 29, 37, 42, 45, 47, 165, 184, 244, 329, 341, 347, 372}, new short[]{31, 36, 82, 99, 149, 154, 173, 182, 185, 200, 217, 251, 298, 329, 332, 333, 349, 353, 354, 355, 377, 383}, new short[]{32, 44, 45, 52, 93, 97, 108, 114, 120, 144, 155, 172, 236, 240, 267, 272, 282, 288, 329, 333, 334, 343, 381}, new short[]{35, 55, 57, 62, 95, 96, 98, 127, 131, 177, 262, 317, 318, 357, 359, 380, 388}, new short[]{22, 24, 68, 103, 115, 119, 120, 125, 128, 156, 162, 184, 186, 235, 244, 327, 353, 358, 378, 380, 393}, new short[]{29, 37, 62, 67, 81, 83, 93, 104, 110, 129, 132, 142, 172, 274, 298, 354, 380}, new short[]{19, 45, 66, 87, 104, 108, 118, 155, 170, 176, 234, 286, 310, 313, 327, 329, 333, 347, 358, 368, 380, 383, 386}, new short[]{10, 14, 32, 83, 96, 131, 165, 180, 205, 211, 249, 255, 286, 288, 292, 299, 312, 336, 338, 349, 368, 375}, new short[]{2, 13, 48, 75, 85, 98, 116, 125, 126, 128, 135, 136, 151, 188, 195, 243, 280, 289, 333, 339, 349, 378, 382}, new short[]{9, 19, 39, 45, 87, 106, 117, 125, 126, 127, 154, 165, 202, 211, 256, 309, 360, 397, 398}, new short[]{14, 21, 65, 76, 87, 93, 97, 105, 131, 177, 212, 254, 294, 336, 349, 359, 381}, new short[]{36, 55, 65, 70, 87, 93, 96, 98, 108, 127, 254, 337, 352, 359, 375, 380}, new short[]{22, 42, 62, 82, 131, 132, 136, 158, 168, 196, 267, 305, 336}, new short[]{45, 69, 74, 75, 81, 120, 123, 126, 127, 130, 150, 171, 191, 194, 313, 339, 368, 378, 379, 389, 398}, new short[]{35, 43, 85, 98, 122, 131, 135, 176, 189, 250, 259, 277, 288, 303, 333, 336, 345, 376, 381, 387}, new short[]{1, 6, 34, 87, 115, 129, 131, 202, 235, 252, 256, 263, 317, 328, 349, 372, 391}, new short[]{3, 18, 42, 48, 84, 90, 92, 138, 193, 227, 288, 310, 315, 353, 375}, new short[]{2, 10, 31, 66, 124, 145, 240, 314, 334}, new short[]{32, 38, 84, 141, 165, 188, 193, 212, 346, 359, 379, 380}, new short[]{10, 75, 81, 96, 111, 140, 179, 298, 309, 353, 357, 359, 380, 396}, new short[]{2, 34, 121, 127, 132, 134, 184, 234, 244, 251, 262, 290, 308, 359, 380}, new short[]{17, 24, 93, 172, 186, 198, 218, 234, 239, 250, 252, 255, 307, 309, 325, 334, 354, 359}, new short[]{14, 18, 45, 50, 131, 174, 211, 237, 252, 267, 309, 334, 348, 351, 377, 391}, new short[]{32, 61, 87, 97, 125, 126, 132, 184, 249, 252, 273, 284, 288, 339, 383, 398}, new short[]{76, 81, 87, 127, 147, 161, 163, 199, 206, 306, 329, 340, 349, 353, 360, 383}, new short[]{14, 16, 76, 87, 101, 169, 188, 243, 246, 251, 253, 269, 298, 355, 375, 380}, new short[]{32, 79, 87, 103, 117, 125, 127, 177, 244, 301, 305, 317, 333, 338, 340, 342, 391}, new short[]{4, 67, 76, 121, 127, 130, 140, 158, 165, 186, 193, 251, 301, 303, 330, 336}, new short[]{11, 76, 83, 84, 87, 214, 248, 276, 299, 311, 320, 329, 332, 335, 371}, new short[]{2, 4, 19, 40, 42, 71, 98, 119, 121, 137, 167, 262, 288, 295, 306, 339, 350, 382}, new short[]{14, 40, 54, 90, 125, 129, 132, 146, 147, 165, 169, 176, 190, 253, 284, 303, 307, 316, 339, 342, 359, 389}, new short[]{47, 59, 71, 103, 125, 126, 129, 130, 200, 206, 240, 254, 276, 282, 299, 303, 307, 318, 320, 336, 338, 357, 362, 380, 387, 392}, new short[]{4, 22, 58, 102, 113, 115, 153, 167, 188, 212, 262, 286, 305, 333, 348, 354, 360, 371, 379, 386}, new short[]{5, 6, 56, 61, 108, 128, 129, 164, 165, 177, 182, 225, 226, 235, 244, 246, 249, 310, 333, 348, 349, 381, 391}, new short[]{18, 32, 33, 53, 56, 176, 186, 199, 200, 244, 246, 248, 259, 285, 289, 306, 358, 371, 373, 375, 379}, new short[]{40, 43, 70, 76, 83, 84, 90, 93, 101, 125, 159, 204, 276, 282, 304, 320, 339, 351, 353, 367, 391}, new short[]{14, 19, 59, 71, 76, 87, 93, 97, 105, 111, 120, 121, 122, 154, 171, 211, 231, 244, 286, 288, 341, 351}, new short[]{10, 56, 65, 72, 92, 108, 123, 129, 212, 258, 329, 353, 359}, new short[]{5, 76, 124, 127, 161, 172, 188, 244, 250, 266, 290, 318, 347, 351, 369, 382, 391, 395}, new short[]{1, 33, 86, 120, 121, 130, 154, 162, 173, 192, 241, 244, 262, 338, 339, 343, 353, 380, 390}, new short[]{1, 15, 22, 54, 57, 85, 126, 127, 176, 188, 248, 305, 332, 347, 349, 358, 367}, new short[]{91, 111, 122, 125, 130, 178, 190, 224, 225, 226, 235, 286, 308, 329, 334, 345, 346, 349, 358, 362, 367}, new short[]{16, 26, 51, 54, 84, 85, 98, 120, 272, 319, 349, 359, 360, 362, 377, 391, 398}, new short[]{73, 85, 102, 109, 128, 153, 171, 184, 248, 249, 256, 298, 300, 335, 338, 340, 355, 370}, new short[]{9, 108, 122, 131, 164, 168, 173, 176, 195, 218, 235, 286, 341, 350, 353, 358, 375, 377}, new short[]{25, 62, 125, 140, 165, 173, 200, 225, 226, 243, 283, 286, 329, 343, 357, 366, 377}, new short[]{10, 35, 58, 64, 98, 103, 125, 127, 129, 135, 141, 165, 169, 175, 189, 244, 258, 259, 306, 331, 333, 378, 380, 391}, new short[]{54, 87, 89, 99, 116, 125, 129, 221, 246, 269, 324, 335, 348, 351}, new short[]{85, 90, 103, 115, 131, 134, 165, 207, 282, 307, 313, 328, 346, 349, 380, 383, 387, 398}, new short[]{10, 40, 74, 84, 160, 239, 253, 272, 282, 333, 344, 351, 359, 360, 379}, new short[]{32, 38, 54, 74, 76, 117, 163, 171, 176, 217, 227, 250, 251, 280, 329, 330, 350, 378}, new short[]{13, 20, 40, 107, 129, 135, 154, 158, 161, 163, 179, 206, 281, 315, 325, 351, 355, 359, 397}, new short[]{0, 4, 37, 49, 62, 98, 117, 129, 177, 244, 285, 289, 306, 338, 360, 381}, new short[]{36, 38, 43, 61, 71, 87, 120, 128, 172, 200, 235, 247, 251, 282, 299, 329, 341, 352, 355}, new short[]{43, 71, 83, 85, 108, 117, 118, 121, 133, 138, 165, 206, 231, 254, 290, 291, 335, 336, 359, 362, 377}, new short[]{29, 32, 71, 103, 122, 125, 198, 224, 244, 285, 303, 333, 335, 337}, new short[]{54, 55, 82, 87, 101, 108, 127, 229, 230, 269, 290, 306, 349, 353}, new short[]{9, 117, 126, 137, 154, 165, 167, 186, 192, 229, 277, 283, 301, 317, 365, 367, 372, 378}, new short[]{4, 11, 19, 47, 51, 92, 110, 132, 137, 140, 290, 298, 361, 377, 379}, new short[]{23, 83, 98, 134, 165, 170, 186, 190, 253, 269, 308, 322, 327, 332, 335, 344, 398}, new short[]{60, 83, 111, 129, 173, 176, 186, 232, 306, 327, 329, 349, 355}, new short[]{25, 31, 40, 56, 72, 95, 126, 144, 149, 161, 173, 240, 262, 332, 333, 356, 368, 391, 394}, new short[]{91, 127, 134, 144, 155, 158, 161, 232, 251, 280, 287, 353, 380, 394}, new short[]{37, 43, 57, 84, 87, 149, 175, 288, 330, 380}, new short[]{8, 9, 83, 97, 120, 128, 158, 171, 193, 232, 287, 308, 309, 334, 355}, new short[]{39, 40, 62, 82, 94, 98, 101, 144, 147, 205, 290, 333, 339, 353, 372, 397}, new short[]{10, 20, 38, 125, 135, 138, 168, 180, 191, 203, 231, 250, 280, 301, 328, 345, 388}, new short[]{44, 54, 64, 87, 117, 122, 127, 154, 234, 239, 244, 298, 329, 378, 383}, new short[]{13, 62, 70, 97, 121, 176, 244, 267, 282, 318, 324, 334, 341, 353, 386, 388}, new short[]{40, 89, 91, 117, 125, 131, 155, 173, 193, 244, 273, 277, 328, 333, 360, 382}, new short[]{30, 47, 95, 108, 127, 165, 188, 211, 273, 349, 354, 368, 391}, new short[]{19, 52, 87, 98, 100, 122, 125, 157, 159, 215, 217, 235, 254, 309, 336, 344, 349, 382}, new short[]{19, 85, 87, 136, 144, 180, 190, 229, 310, 345, 365, 376, 390}, new short[]{35, 52, 87, 113, 124, 135, 145, 167, 174, 225, 226, 244, 247, 300, 359}, new short[]{10, 35, 69, 103, 129, 144, 165, 180, 230, 232, 329, 335, 353, 359, 371, 390}, new short[]{5, 13, 80, 83, 135, 139, 142, 176, 179, 190, 205, 217, 282, 298, 308, 334, 353, 359}, new short[]{24, 52, 67, 108, 135, 138, 153, 176, 231, 249, 283, 304, 337, 351, 353, 355}, new short[]{90, 93, 127, 132, 136, 163, 165, 196, 284, 306, 353, 383}, new short[]{20, 37, 103, 126, 135, 184, 204, 215, 221, 288, 300, 329, 339, 358, 383}, new short[]{16, 36, 52, 99, 117, 136, 171, 190, 243, 244, 303, 315, 333, 349, 373, 382}, new short[]{0, 57, 69, 98, 125, 129, 132, 158, 165, 190, 191, 193, 198, 254, 256, 285, 288, 303, 339, 346, 351, 391}, new short[]{1, 13, 21, 87, 125, 132, 150, 204, 240, 249, 253, 265, 288, 334, 343, 348, 349, 359}, new short[]{29, 40, 71, 80, 91, 99, 122, 203, 289, 290, 298, 329, 353, 380, 390}, new short[]{2, 5, 36, 57, 93, 102, 135, 140, 314, 343, 398}, new short[]{20, 59, 107, 193, 204, 246, 247, 336, 341, 342, 354, 359, 360, 383}, new short[]{47, 71, 93, 111, 116, 120, 122, 130, 251, 286, 298, 299, 348}, new short[]{21, 52, 56, 69, 76, 118, 120, 125, 137, 274, 280, 324, 327, 335, 339, 340}, new short[]{23, 29, 57, 75, 98, 132, 149, 157, 160, 235, 244, 288, 327, 340, 354, 372, 377}, new short[]{4, 22, 97, 103, 111, 129, 131, 151, 158, 176, 204, 248, 265, 309, 359, 391, 392}, new short[]{15, 17, 73, 105, 115, 170, 186, 228, 255, 317, 321, 339, 349, 379, 380, 381}, new short[]{17, 52, 72, 103, 188, 329, 342, 353, 358, 359, 374, 376, 380, 393}, new short[]{40, 48, 74, 124, 135, 191, 225, 226, 237, 291, 300, 304, 310, 347, 359, 380, 396}, new short[]{2, 36, 47, 57, 122, 125, 174, 188, 203, 224, 255, 325, 353, 359, 387}, new short[]{13, 58, 69, 83, 115, 120, 134, 161, 165, 174, 175, 191, 246, 255, 280, 353, 357, 358, 359, 379}, new short[]{1, 29, 47, 87, 89, 135, 176, 190, 209, 236, 304, 344, 348, 358, 359, 378}, new short[]{8, 13, 40, 52, 58, 61, 71, 125, 144, 168, 189, 210, 260, 337, 338, 340, 347, 376, 380}, new short[]{29, 90, 126, 127, 129, 136, 145, 159, 165, 188, 274, 284, 288, 316, 329, 358, 380}, new short[]{2, 19, 103, 120, 123, 159, 165, 175, 177, 180, 238, 244, 251, 294, 329, 342, 345, 349, 357, 376, 392}, new short[]{41, 42, 59, 71, 81, 98, 101, 117, 159, 171, 180, 240, 285, 290, 299, 344, 353}, new short[]{83, 103, 108, 142, 175, 248, 290, 300, 321, 354, 365, 374, 382}, new short[]{12, 67, 105, 130, 140, 171, 188, 192, 244, 276, 290, 302, 348, 349, 357, 360, 380}, new short[]{4, 13, 36, 65, 75, 160, 165, 185, 198, 235, 293, 324, 327, 333, 345, 347, 375, 383}, new short[]{37, 61, 80, 125, 234, 283, 290, 353, 359, 378, 383}, new short[]{9, 32, 83, 110, 155, 248, 252, 288, 313}, new short[]{37, 48, 52, 93, 167, 170, 179, 244, 267, 288, 296, 333, 335, 355, 374}, new short[]{35, 92, 98, 153, 165, 184, 215, 233, 242, 290, 339, 355}, new short[]{9, 38, 83, 121, 127, 165, 176, 235, 253, 305, 330, 337, 355, 358, 359}, new short[]{35, 117, 122, 125, 132, 136, 183, 235, 254, 280, 285, 286, 329, 334, 338, 353, 372}, new short[]{6, 87, 117, 125, 141, 144, 153, 157, 179, 215, 267, 272, 289, 329, 336, 359}, new short[]{7, 14, 37, 82, 135, 147, 154, 202, 244, 290, 297, 298, 345, 355, 368, 383}, new short[]{105, 135, 173, 244, 255, 280, 288, 299, 304, 307, 337, 338, 341, 344}, new short[]{19, 31, 33, 77, 92, 99, 114, 151, 173, 202, 253, 318, 329, 333, 358, 371}, new short[]{1, 8, 14, 30, 39, 120, 157, 172, 227, 229, 251, 257, 272, 339, 380}, new short[]{19, 98, 171, 191, 213, 246, 289, 353, 357, 366, 374, 383}, new short[]{8, 98, 125, 126, 144, 152, 244, 277, 282, 290, 322, 393}, new short[]{17, 206, 211, 224, 336, 338, 386}, new short[]{52, 55, 71, 99, 105, 191, 211, 215, 224, 246, 290, 300, 336, 339, 361}, new short[]{15, 16, 44, 66, 96, 121, 127, 162, 167, 202, 219, 243, 244, 254, 282, 320, 345, 390}, new short[]{7, 83, 92, 121, 130, 160, 177, 280, 308, 309, 339, 350, 352, 358, 380, 390}, new short[]{67, 122, 144, 148, 170, 173, 184, 222, 280, 374}, new short[]{2, 4, 15, 19, 115, 130, 136, 148, 172, 180, 243, 251, 313, 329, 333, 359, 364}, new short[]{90, 98, 108, 124, 167, 176, 202, 254, 286, 351, 359}, new short[]{80, 126, 135, 167, 212, 242, 243, 256, 283, 286, 295, 327, 337, 340, 346, 357, 358, 364}, new short[]{19, 108, 125, 132, 149, 172, 180, 186, 200, 254, 286, 296, 339, 344, 350, 359, 391}, new short[]{62, 65, 67, 105, 127, 129, 132, 250, 298, 307, 334, 344, 359, 383}, new short[]{31, 59, 87, 107, 121, 131, 132, 160, 244, 246, 247, 253, 344, 360, 394}, new short[]{4, 39, 76, 125, 130, 148, 168, 170, 191, 196, 298, 306, 327, 338, 345, 349, 360, 375}, new short[]{13, 14, 32, 84, 98, 122, 126, 156, 188, 235, 255, 330, 336, 338, 375, 380, 389}, new short[]{5, 18, 31, 54, 71, 74, 76, 81, 87, 93, 126, 129, 182, 303, 327, 353, 359, 373, 391}, new short[]{13, 37, 64, 137, 138, 180, 244, 247, 251, 253, 269, 284, 308, 344, 374, 376}, new short[]{5, 7, 10, 23, 35, 125, 168, 169, 187, 191, 192, 313, 337, 340, 342, 365}, new short[]{62, 67, 122, 125, 165, 190, 217, 243, 254, 256, 265, 299, 318, 353, 394}, new short[]{4, 24, 62, 92, 109, 118, 134, 143, 144, 176, 190, 199, 221, 299, 349, 380}, new short[]{22, 35, 64, 74, 92, 113, 161, 172, 193, 282, 287, 307, 359, 393}, new short[]{37, 50, 66, 75, 76, 78, 82, 87, 139, 159, 172, 176, 188, 231, 352, 371}, new short[]{19, 31, 75, 121, 144, 152, 163, 171, 172, 198, 243, 246, 285, 288, 289, 333, 344, 347, 357, 398}, new short[]{1, 15, 17, 51, 57, 65, 69, 127, 241, 244, 254, 259, 329, 336, 358}, new short[]{9, 95, 117, 121, 125, 137, 204, 242, 247, 301, 309, 314, 334, 339, 350, 354, 358}, new short[]{9, 61, 96, 111, 130, 163, 180, 211, 225, 226, 241, 253, 282, 283, 346, 355, 359, 380, 383}, new short[]{94, 117, 121, 124, 126, 130, 135, 172, 199, 232, 286, 325, 336, 352, 362, 375}, new short[]{110, 125, 163, 250, 265, 303, 329, 334, 391}, new short[]{47, 72, 76, 111, 125, 157, 169, 245, 254, 285, 287, 297, 298, 336, 353, 359, 383}, new short[]{62, 93, 115, 125, 127, 130, 174, 231, 308, 310, 329, 333, 355, 359, 390}, new short[]{44, 116, 163, 167, 180, 191, 200, 245, 254, 329, 343, 345, 354, 364}, new short[]{31, 62, 105, 108, 144, 145, 162, 173, 177, 191, 198, 247, 249, 344, 345, 348, 353}, new short[]{29, 65, 66, 74, 83, 87, 125, 148, 165, 228, 334, 353, 359, 380, 383, 391}, new short[]{2, 15, 125, 130, 239, 290, 312, 336, 337, 341, 398}, new short[]{40, 76, 87, 114, 119, 120, 165, 229, 265, 313, 324, 349, 358, 383}, new short[]{48, 62, 87, 91, 103, 186, 195, 212, 214, 315, 322, 327, 330, 338, 339}, new short[]{9, 32, 85, 108, 135, 191, 224, 237, 257, 288, 307, 310, 313, 318, 329, 337, 352, 395}, new short[]{87, 93, 102, 112, 129, 154, 171, 236, 317, 320, 349, 350, 359, 380}, new short[]{1, 14, 92, 111, 137, 140, 186, 290, 329, 336, 354, 355, 378, 379, 383}, new short[]{7, 26, 37, 47, 84, 101, 144, 153, 175, 180, 198, 232, 243, 305, 333, 353, 357, 383}, new short[]{20, 58, 76, 93, 99, 127, 134, 154, 188, 206, 246, 312, 313, 324}, new short[]{2, 12, 117, 125, 160, 167, 188, 206, 279, 285, 287, 301, 329, 332, 333, 336, 344, 362}, new short[]{2, 76, 126, 127, 137, 165, 244, 288, 290, 339, 346, 351, 359, 365, 383}, new short[]{66, 108, 136, 151, 174, 265, 344, 351, 353, 357, 378, 386}, new short[]{8, 76, 87, 90, 111, 116, 124, 176, 198, 334, 337, 349, 359, 379, 394}, new short[]{32, 36, 42, 76, 81, 125, 127, 205, 227, 262, 280, 288, 326, 336, 390, 398}, new short[]{9, 32, 65, 83, 89, 93, 97, 122, 129, 178, 180, 215, 241, 246, 323, 332, 353, 362, 364, 380}, new short[]{5, 24, 56, 127, 130, 155, 184, 191, 217, 235, 245, 339, 344, 358, 359, 362, 380}, new short[]{14, 40, 64, 71, 93, 108, 131, 165, 188, 204, 217, 235, 237, 241, 248, 308, 309, 318, 380, 387}, new short[]{17, 29, 34, 74, 125, 175, 184, 196, 211, 275, 301, 318, 327, 334, 349, 355, 358, 368}, new short[]{15, 45, 110, 111, 116, 129, 132, 211, 247, 275, 286, 317, 333, 334, 377, 383}, new short[]{4, 5, 59, 87, 103, 124, 125, 127, 130, 165, 241, 265, 299, 353, 360}, new short[]{31, 120, 124, 135, 154, 197, 235, 243, 247, 248, 258, 309, 320, 335, 357}, new short[]{50, 125, 127, 130, 137, 147, 171, 172, 267, 289, 301, 308, 325, 334, 337, 353, 360, 374, 391}, new short[]{62, 64, 69, 87, 111, 118, 129, 134, 212, 239, 244, 246, 250, 254, 307, 322, 329, 370, 372}, new short[]{54, 92, 128, 160, 198, 244, 248, 255, 284, 314, 335, 349, 358, 360, 376, 380}, new short[]{9, 13, 29, 54, 72, 89, 110, 122, 126, 139, 158, 159, 163, 230, 304, 306, 313}, new short[]{1, 9, 54, 95, 108, 132, 176, 193, 243, 251, 339, 378}, new short[]{0, 96, 99, 135, 137, 184, 212, 232, 251, 315, 334}, new short[]{140, 157, 165, 182, 235, 294, 314, 349, 354, 365}, new short[]{14, 18, 31, 56, 117, 125, 138, 227, 246, 283, 334, 345, 352, 357, 361}, new short[]{0, 71, 82, 130, 131, 144, 161, 235, 247, 301, 333, 335, 345, 353, 355, 359, 360, 374}, new short[]{6, 23, 35, 117, 125, 141, 169, 200, 244, 288, 298, 338, 353, 379}, new short[]{10, 98, 125, 127, 138, 153, 219, 244, 307, 350, 353, 366, 367}, new short[]{9, 32, 40, 122, 126, 127, 170, 176, 300, 334, 350, 391}, new short[]{6, 13, 31, 87, 89, 97, 125, 165, 171, 173, 176, 244, 331, 348, 373}, new short[]{10, 61, 87, 105, 123, 125, 127, 195, 260, 265, 323, 361, 362}, new short[]{2, 20, 90, 124, 353, 354, 378, 382}, new short[]{5, 48, 58, 83, 98, 117, 125, 126, 196, 198}, new short[]{13, 37, 50, 64, 66, 79, 99, 132, 135, 244, 247, 380}, new short[]{57, 165, 235, 238, 248, 272, 287, 299, 327, 329, 334, 350, 353, 380}, new short[]{55, 66, 118, 125, 130, 169, 250, 255, 271, 314, 324, 338, 353}, new short[]{7, 31, 62, 84, 103, 105, 111, 126, 132, 149, 154, 191, 250, 334, 372, 375}, new short[]{56, 81, 114, 117, 120, 124, 127, 128, 154, 254, 290, 317, 345, 354}, new short[]{4, 13, 86, 101, 153, 191, 193, 231, 243, 258, 283, 288, 308, 353, 387, 392}, new short[]{5, 37, 58, 62, 67, 84, 87, 176, 237, 267, 333, 334, 347}, new short[]{1, 7, 74, 110, 165, 168, 182, 233, 288, 305, 309, 315, 347, 351, 353, 358, 360, 375}, new short[]{57, 84, 129, 138, 165, 243, 244, 259, 280, 282, 290, 380, 383} }; } }
2881099/dotnetGen_sqlserver
5,396
GenMs/NPinyin/Pinyin.cs
/** * NPinyin包含一个公开类Pinyin,该类实现了取汉字文本首字母、文本对应拼音、以及 * 获取和拼音对应的汉字列表等方法。由于汉字字库大,且多音字较多,因此本组中实现的 * 拼音转换不一定和词语中的字的正确读音完全吻合。但绝大部分是正确的。 * * 最后感谢百度网友韦祎提供的常用汉字拼音对照表。见下载地址: * http://wenku.baidu.com/view/d725f4335a8102d276a22f46.html * * 最后,我想简要地说明一下我的设计思路: * 首先,我将汉字按拼音分组后建立一个字符串数组(见PyCode.codes),然后使用程序 * 将PyCode.codes中每一个汉字通过其编码值使用散列函数: * * f(x) = x % PyCode.codes.Length * { * g(f(x)) = pos(x) * * 其中, pos(x)为字符x所属字符串所在的PyCode.codes的数组下标, 然后散列到同 * PyCode.codes长度相同长度的一个散列表中PyHash.hashes)。 * 当检索一个汉字的拼音时,首先从PyHash.hashes中获取和 * 对应的PyCode.codes中数组下标,然后从对应字符串查找,当到要查找的字符时,字符 * 串的前6个字符即包含了该字的拼音。 * * 此种方法的好处一是节约了存储空间,二是兼顾了查询效率。 * * 如有意见,请与我联系反馈。我的邮箱是:qzyzwsy@gmail.com * * 汪思言 2011年1月3日凌晨 * */ /* * v0.2.x的变化 * ================================================================= * 1、增加对不同编码格式文本的支持,同时增加编码转换方法Pinyin.ConvertEncoding * 2、重构单字符拼音的获取,未找到拼音时返回字符本身. * * 汪思言 2012年7月23日晚 * */ using System; using System.Collections.Generic; using System.Text; namespace NPinyin { public static class Pinyin { /// <summary> /// 取中文文本的拼音首字母 /// </summary> /// <param name="text">编码为UTF8的文本</param> /// <returns>返回中文对应的拼音首字母</returns> public static string GetInitials(string text) { text = text.Trim(); StringBuilder chars = new StringBuilder(); for (var i = 0; i < text.Length; ++i) { string py = GetPinyin(text[i]); if (py != "") chars.Append(py[0]); } return chars.ToString().ToUpper(); } /// <summary> /// 取中文文本的拼音首字母 /// </summary> /// <param name="text">文本</param> /// <param name="encoding">源文本的编码</param> /// <returns>返回encoding编码类型中文对应的拼音首字母</returns> public static string GetInitials(string text, Encoding encoding) { string temp = ConvertEncoding(text, encoding, Encoding.UTF8); return ConvertEncoding(GetInitials(temp), Encoding.UTF8, encoding); } /// <summary> /// 取中文文本的拼音 /// </summary> /// <param name="text">编码为UTF8的文本</param> /// <returns>返回中文文本的拼音</returns> public static string GetPinyin(string text) { StringBuilder sbPinyin = new StringBuilder(); for (var i = 0; i < text.Length; ++i) { string py = GetPinyin(text[i]); if (py != "") sbPinyin.Append(py); sbPinyin.Append(" "); } return sbPinyin.ToString().Trim(); } /// <summary> /// 取中文文本的拼音 /// </summary> /// <param name="text">编码为UTF8的文本</param> /// <param name="encoding">源文本的编码</param> /// <returns>返回encoding编码类型的中文文本的拼音</returns> public static string GetPinyin(string text, Encoding encoding) { string temp = ConvertEncoding(text.Trim(), encoding, Encoding.UTF8); return ConvertEncoding(GetPinyin(temp), Encoding.UTF8, encoding); } /// <summary> /// 取和拼音相同的汉字列表 /// </summary> /// <param name="Pinyin">编码为UTF8的拼音</param> /// <returns>取拼音相同的汉字列表,如拼音“ai”将会返回“唉爱……”等</returns> public static string GetChineseText(string pinyin) { string key = pinyin.Trim().ToLower(); foreach (string str in PyCode.codes) { if (str.StartsWith(key + " ") || str.StartsWith(key + ":")) return str.Substring(7); } return ""; } /// <summary> /// 取和拼音相同的汉字列表,编码同参数encoding /// </summary> /// <param name="Pinyin">编码为encoding的拼音</param> /// <param name="encoding">编码</param> /// <returns>返回编码为encoding的拼音为pinyin的汉字列表,如拼音“ai”将会返回“唉爱……”等</returns> public static string GetChineseText(string pinyin, Encoding encoding) { string text = ConvertEncoding(pinyin, encoding, Encoding.UTF8); return ConvertEncoding(GetChineseText(text), Encoding.UTF8, encoding); } /// <summary> /// 返回单个字符的汉字拼音 /// </summary> /// <param name="ch">编码为UTF8的中文字符</param> /// <returns>ch对应的拼音</returns> public static string GetPinyin(char ch) { short hash = GetHashIndex(ch); for (var i = 0; i < PyHash.hashes[hash].Length; ++i) { short index = PyHash.hashes[hash][i]; var pos = PyCode.codes[index].IndexOf(ch, 7); if (pos != -1) return PyCode.codes[index].Substring(0, 6).Trim(); } return ch.ToString(); } /// <summary> /// 返回单个字符的汉字拼音 /// </summary> /// <param name="ch">编码为encoding的中文字符</param> /// <returns>编码为encoding的ch对应的拼音</returns> public static string GetPinyin(char ch, Encoding encoding) { ch = ConvertEncoding(ch.ToString(), encoding, Encoding.UTF8)[0]; return ConvertEncoding(GetPinyin(ch), Encoding.UTF8, encoding); } /// <summary> /// 转换编码 /// </summary> /// <param name="text">文本</param> /// <param name="srcEncoding">源编码</param> /// <param name="dstEncoding">目标编码</param> /// <returns>目标编码文本</returns> public static string ConvertEncoding(string text, Encoding srcEncoding, Encoding dstEncoding) { byte[] srcBytes = srcEncoding.GetBytes(text); byte[] dstBytes = Encoding.Convert(srcEncoding, dstEncoding, srcBytes); return dstEncoding.GetString(dstBytes); } /// <summary> /// 取文本索引值 /// </summary> /// <param name="ch">字符</param> /// <returns>文本索引值</returns> private static short GetHashIndex(char ch) { return (short)((uint)ch % PyCode.codes.Length); } } }
2881099/dotnetGen_sqlserver
11,323
GenMs/NPinyin/PyCode.cs
using System; using System.Collections.Generic; using System.Text; namespace NPinyin { internal class PyCode { internal static string[] codes = new string[]{ "a :阿啊吖嗄腌锕", "ai :爱埃碍矮挨唉哎哀皑癌蔼艾隘捱嗳嗌嫒瑷暧砹锿霭", "an :安按暗岸案俺氨胺鞍谙埯揞犴庵桉铵鹌黯", "ang :昂肮盎", "ao :凹奥敖熬翱袄傲懊澳坳拗嗷岙廒遨媪骜獒聱螯鏊鳌鏖", "ba :把八吧巴拔霸罢爸坝芭捌扒叭笆疤跋靶耙茇菝岜灞钯粑鲅魃", "bai :百白败摆柏佰拜稗捭掰", "ban :办半板班般版拌搬斑扳伴颁扮瓣绊阪坂钣瘢癍舨", "bang :帮棒邦榜梆膀绑磅蚌镑傍谤蒡浜", "bao :报保包剥薄胞暴宝饱抱爆堡苞褒雹豹鲍葆孢煲鸨褓趵龅", "bei :北被倍备背辈贝杯卑悲碑钡狈惫焙孛陂邶埤萆蓓呗悖碚鹎褙鐾鞴", "ben :本奔苯笨畚坌贲锛", "beng :泵崩绷甭蹦迸嘣甏", "bi :比必避闭辟笔壁臂毕彼逼币鼻蔽鄙碧蓖毙毖庇痹敝弊陛匕俾荜荸薜吡哔狴庳愎滗濞弼妣婢嬖璧畀铋秕裨筚箅篦舭襞跸髀", "bian :变边便编遍辩扁辨鞭贬卞辫匾弁苄忭汴缏飚煸砭碥窆褊蝙笾鳊", "biao :表标彪膘婊骠杓飑飙镖镳瘭裱鳔髟", "bie :别鳖憋瘪蹩", "bin :宾彬斌濒滨摈傧豳缤玢槟殡膑镔髌鬓", "bing :并病兵柄冰丙饼秉炳禀邴摒", "bo :波播伯拨博勃驳玻泊菠钵搏铂箔帛舶脖膊渤亳啵饽檗擘礴钹鹁簸跛踣", "bu :不部步布补捕卜哺埠簿怖卟逋瓿晡钚钸醭", "ca :擦嚓礤", "cai :采才材菜财裁彩猜睬踩蔡", "can :参残蚕灿餐惭惨孱骖璨粲黪", "cang :藏仓苍舱沧", "cao :草槽操糙曹嘈漕螬艚", "ce :测策侧册厕恻", "cen :岑涔", "ceng :层蹭", "cha :查差插察茶叉茬碴搽岔诧猹馇汊姹杈楂槎檫锸镲衩", "chai :柴拆豺侪钗瘥虿", "chan :产铲阐搀掺蝉馋谗缠颤冁谄蒇廛忏潺澶羼婵骣觇禅镡蟾躔", "chang :长常场厂唱肠昌倡偿畅猖尝敞伥鬯苌菖徜怅惝阊娼嫦昶氅鲳", "chao :朝超潮巢抄钞嘲吵炒怊晁耖", "che :车彻撤扯掣澈坼砗", "chen :陈沉称衬尘臣晨郴辰忱趁伧谌谶抻嗔宸琛榇碜龀", "cheng :成程称城承乘呈撑诚橙惩澄逞骋秤丞埕噌枨柽塍瞠铖铛裎蛏酲", "chi :持尺齿吃赤池迟翅斥耻痴匙弛驰侈炽傺坻墀茌叱哧啻嗤彳饬媸敕眵鸱瘛褫蚩螭笞篪豉踟魑", "chong :虫充冲崇宠茺忡憧铳舂艟", "chou :抽仇臭酬畴踌稠愁筹绸瞅丑俦帱惆瘳雠", "chu :出处除初础触楚锄储橱厨躇雏滁矗搐亍刍怵憷绌杵楮樗褚蜍蹰黜", "chuai :揣搋啜膪踹", "chuan :传船穿串川椽喘舛遄巛氚钏舡", "chuang:床创窗闯疮幢怆", "chui :吹垂锤炊捶陲棰槌", "chun :春纯醇椿唇淳蠢莼鹑蝽", "chuo :戳绰辍踔龊", "ci :此次刺磁雌词茨疵辞慈瓷赐茈呲祠鹚糍", "cong :从丛聪葱囱匆苁淙骢琮璁", "cou :凑楱辏腠", "cu :粗促醋簇蔟徂猝殂酢蹙蹴", "cuan :篡蹿窜汆撺爨镩", "cui :催脆淬粹摧崔瘁翠萃啐悴璀榱毳隹", "cun :存村寸忖皴", "cuo :错措撮磋搓挫厝嵯脞锉矬痤鹾蹉", "da :大打达答搭瘩耷哒嗒怛妲疸褡笪靼鞑", "dai :代带待袋戴呆歹傣殆贷逮怠埭甙呔岱迨骀绐玳黛", "dan :单但弹担蛋淡胆氮丹旦耽郸掸惮诞儋萏啖殚赕眈疸瘅聃箪", "dang :党当档挡荡谠凼菪宕砀裆", "dao :到道导刀倒稻岛捣盗蹈祷悼叨忉氘纛", "de :的得德锝", "deng :等灯登邓蹬瞪凳噔嶝戥磴镫簦", "di :地第低敌底帝抵滴弟递堤迪笛狄涤翟嫡蒂缔氐籴诋谛邸荻嘀娣绨柢棣觌砥碲睇镝羝骶", "dia :嗲", "dian :电点垫典店颠淀掂滇碘靛佃甸惦奠殿阽坫巅玷钿癜癫簟踮", "diao :调掉吊碉叼雕凋刁钓铞铫貂鲷", "die :迭跌爹碟蝶谍叠垤堞揲喋牒瓞耋蹀鲽", "ding :定顶钉丁订盯叮鼎锭仃啶玎腚碇町疔耵酊", "diu :丢铥", "dong :动东冬懂洞冻董栋侗恫垌咚岽峒氡胨胴硐鸫", "dou :斗豆兜抖陡逗痘蔸窦蚪篼", "du :度都毒独读渡杜堵镀顿督犊睹赌肚妒芏嘟渎椟牍蠹笃髑黩", "duan :断端段短锻缎椴煅簖", "dui :对队堆兑怼憝碓", "dun :盾吨顿蹲敦墩囤钝遁沌炖砘礅盹镦趸", "duo :多夺朵掇哆垛躲跺舵剁惰堕咄哚沲缍柁铎裰踱", "e :而二尔儿恶额恩俄耳饵蛾饿峨鹅讹娥厄扼遏鄂噩谔垩苊莪萼呃愕屙婀轭腭锇锷鹗颚鳄", "ei :诶", "en :恩蒽摁", "er :而二尔儿耳饵洱贰佴迩珥铒鸸鲕", "fa :发法阀乏伐罚筏珐垡砝", "fan :反翻范犯饭繁泛番凡烦返藩帆樊矾钒贩蕃蘩幡梵燔畈蹯", "fang :方放防访房纺仿妨芳肪坊邡枋钫舫鲂", "fei :非肥飞费废肺沸菲匪啡诽吠芾狒悱淝妃绯榧腓斐扉镄痱蜚篚翡霏鲱", "fen :分粉奋份粪纷芬愤酚吩氛坟焚汾忿偾瀵棼鲼鼢", "feng :风封蜂丰缝峰锋疯奉枫烽逢冯讽凤俸酆葑唪沣砜", "fou :否缶", "fu :复服副府夫负富附福伏符幅腐浮辅付腹妇孵覆扶辐傅佛缚父弗甫肤氟敷拂俘涪袱抚俯釜斧脯腑赴赋阜讣咐匐凫郛芙苻茯莩菔拊呋幞怫滏艴孚驸绂绋桴赙祓砩黻黼罘稃馥蚨蜉蝠蝮麸趺跗鲋鳆", "ga :噶嘎尬尕尜旮钆", "gai :改该盖概钙溉丐陔垓戤赅", "gan :干杆感敢赶甘肝秆柑竿赣坩苷尴擀泔淦澉绀橄旰矸疳酐", "gang :刚钢缸纲岗港杠冈肛戆罡筻", "gao :高搞告稿膏篙皋羔糕镐睾诰郜藁缟槔槁杲锆", "ge :个各革格割歌隔哥铬阁戈葛搁鸽胳疙蛤鬲仡哿圪塥嗝搿膈硌镉袼虼舸骼", "gen :根跟亘茛哏艮", "geng :更耕颈庚羹埂耿梗哽赓绠鲠", "gong :工公共供功攻巩贡汞宫恭龚躬弓拱珙肱蚣觥", "gou :够构沟狗钩勾购苟垢佝诟岣遘媾缑枸觏彀笱篝鞲", "gu :鼓固古骨故顾股谷估雇孤姑辜菇咕箍沽蛊嘏诂菰崮汩梏轱牯牿臌毂瞽罟钴锢鸪痼蛄酤觚鲴鹘", "gua :挂刮瓜剐寡褂卦诖呱栝胍鸹", "guai :怪乖拐", "guan :关管观官灌贯惯冠馆罐棺倌莞掼涫盥鹳矜鳏", "guang :光广逛咣犷桄胱", "gui :规贵归硅鬼轨龟桂瑰圭闺诡癸柜跪刽匦刿庋宄妫桧炅晷皈簋鲑鳜", "gun :滚辊棍衮绲磙鲧", "guo :国过果锅郭裹馘埚掴呙帼崞猓椁虢聒蜾蝈", "ha :哈铪", "hai :还海害孩骸氦亥骇嗨胲醢", "han :含焊旱喊汉寒汗函韩酣憨邯涵罕翰撼捍憾悍邗菡撖阚瀚晗焓顸颔蚶鼾", "hang :航夯杭沆绗珩颃", "hao :好号毫耗豪郝浩壕嚎蒿薅嗥嚆濠灏昊皓颢蚝", "he :和合河何核赫荷褐喝贺呵禾盒菏貉阂涸鹤诃劾壑嗬阖纥曷盍颌蚵翮", "hei :黑嘿", "hen :很狠痕恨", "heng :横衡恒哼亨蘅桁", "hong :红洪轰烘哄虹鸿宏弘黉訇讧荭蕻薨闳泓", "hou :后候厚侯喉猴吼堠後逅瘊篌糇鲎骺", "hu :护互湖呼户弧乎胡糊虎忽瑚壶葫蝴狐唬沪冱唿囫岵猢怙惚浒滹琥槲轷觳烀煳戽扈祜瓠鹄鹕鹱笏醐斛", "hua :化花话划滑华画哗猾骅桦砉铧", "huai :坏怀淮槐徊踝", "huan :环换欢缓患幻焕桓唤痪豢涣宦郇奂萑擐圜獾洹浣漶寰逭缳锾鲩鬟", "huang :黄簧荒皇慌蝗磺凰惶煌晃幌恍谎隍徨湟潢遑璜肓癀蟥篁鳇", "hui :会回灰挥辉汇毁慧恢绘惠徽蛔悔卉晦贿秽烩讳诲诙茴荟蕙咴哕喙隳洄浍彗缋珲晖恚虺蟪麾", "hun :混浑荤昏婚魂诨馄阍溷", "huo :活或火货获伙霍豁惑祸劐藿攉嚯夥钬锪镬耠蠖", "ji :级及机极几积给基记己计集即际季激济技击继急剂既纪寄挤鸡迹绩吉脊辑籍疾肌棘畸圾稽箕饥讥姬缉汲嫉蓟冀伎祭悸寂忌妓藉丌亟乩剞佶偈诘墼芨芰荠蒺蕺掎叽咭哜唧岌嵴洎屐骥畿玑楫殛戟戢赍觊犄齑矶羁嵇稷瘠虮笈笄暨跻跽霁鲚鲫髻麂", "jia :加家架价甲夹假钾贾稼驾嘉枷佳荚颊嫁伽郏葭岬浃迦珈戛胛恝铗镓痂瘕袷蛱笳袈跏", "jian :间件见建坚减检践尖简碱剪艰渐肩键健柬鉴剑歼监兼奸箭茧舰俭笺煎缄硷拣捡荐槛贱饯溅涧僭谏谫菅蒹搛湔蹇謇缣枧楗戋戬牮犍毽腱睑锏鹣裥笕翦趼踺鲣鞯", "jiang :将降讲江浆蒋奖疆僵姜桨匠酱茳洚绛缰犟礓耩糨豇", "jiao :较教交角叫脚胶浇焦搅酵郊铰窖椒礁骄娇嚼矫侥狡饺缴绞剿轿佼僬艽茭挢噍峤徼姣敫皎鹪蛟醮跤鲛", "jie :结阶解接节界截介借届街揭洁杰竭皆秸劫桔捷睫姐戒藉芥疥诫讦拮喈嗟婕孑桀碣疖颉蚧羯鲒骱", "jin :进金近紧斤今尽仅劲浸禁津筋锦晋巾襟谨靳烬卺荩堇噤馑廑妗缙瑾槿赆觐衿", "jing :经精京径井静竟晶净境镜景警茎敬惊睛竞荆兢鲸粳痉靖刭儆阱菁獍憬泾迳弪婧肼胫腈旌", "jiong :炯窘迥扃", "jiu :就九旧究久救酒纠揪玖韭灸厩臼舅咎疚僦啾阄柩桕鸠鹫赳鬏", "ju :具据局举句聚距巨居锯剧矩拒鞠拘狙疽驹菊咀沮踞俱惧炬倨讵苣苴莒掬遽屦琚椐榘榉橘犋飓钜锔窭裾趄醵踽龃雎鞫", "juan :卷捐鹃娟倦眷绢鄄狷涓桊蠲锩镌隽", "jue :决觉绝掘撅攫抉倔爵诀厥劂谲矍蕨噘噱崛獗孓珏桷橛爝镢蹶觖", "jun :军均菌君钧峻俊竣浚郡骏捃皲筠麇", "ka :卡喀咖咯佧咔胩", "kai :开凯揩楷慨剀垲蒈忾恺铠锎锴", "kan :看刊坎堪勘砍侃莰戡龛瞰", "kang :抗康炕慷糠扛亢伉闶钪", "kao :考靠拷烤尻栲犒铐", "ke :可克科刻客壳颗棵柯坷苛磕咳渴课嗑岢恪溘骒缂珂轲氪瞌钶锞稞疴窠颏蝌髁", "ken :肯啃垦恳裉", "keng :坑吭铿", "kong :孔空控恐倥崆箜", "kou :口扣抠寇芤蔻叩眍筘", "ku :苦库枯酷哭窟裤刳堀喾绔骷", "kua :跨夸垮挎胯侉", "kuai :快块筷侩蒯郐哙狯脍", "kuan :宽款髋", "kuang :况矿狂框匡筐眶旷诓诳邝圹夼哐纩贶", "kui :奎溃馈亏盔岿窥葵魁傀愧馗匮夔隗蒉揆喹喟悝愦逵暌睽聩蝰篑跬", "kun :困昆坤捆悃阃琨锟醌鲲髡", "kuo :扩括阔廓蛞", "la :拉啦蜡腊蓝垃喇辣剌邋旯砬瘌", "lai :来赖莱崃徕涞濑赉睐铼癞籁", "lan :兰烂蓝览栏婪拦篮阑澜谰揽懒缆滥岚漤榄斓罱镧褴", "lang :浪朗郎狼琅榔廊莨蒗啷阆锒稂螂", "lao :老劳牢涝捞佬姥酪烙唠崂栳铑铹痨耢醪", "le :了乐勒肋仂叻泐鳓", "lei :类雷累垒泪镭蕾磊儡擂肋羸诔嘞嫘缧檑耒酹", "leng :冷棱楞塄愣", "li :理里利力立离例历粒厘礼李隶黎璃励犁梨丽厉篱狸漓鲤莉荔吏栗砾傈俐痢沥哩俪俚郦坜苈莅蓠藜呖唳喱猁溧澧逦娌嫠骊缡枥栎轹戾砺詈罹锂鹂疠疬蛎蜊蠡笠篥粝醴跞雳鲡鳢黧", "lia :俩", "lian :连联练炼脸链莲镰廉怜涟帘敛恋蔹奁潋濂琏楝殓臁裢裣蠊鲢", "liang :量两粮良亮梁凉辆粱晾谅墚椋踉靓魉", "liao :料疗辽僚撩聊燎寥潦撂镣廖蓼尥嘹獠寮缭钌鹩", "lie :列裂烈劣猎冽埒捩咧洌趔躐鬣", "lin :林磷临邻淋麟琳霖鳞凛赁吝蔺啉嶙廪懔遴檩辚膦瞵粼躏", "ling :领另零令灵岭铃龄凌陵拎玲菱伶羚酃苓呤囹泠绫柃棂瓴聆蛉翎鲮", "liu :流六留刘硫柳馏瘤溜琉榴浏遛骝绺旒熘锍镏鹨鎏", "long :龙垄笼隆聋咙窿拢陇垅茏泷珑栊胧砻癃", "lou :漏楼娄搂篓陋偻蒌喽嵝镂瘘耧蝼髅", "lu :路率露绿炉律虑滤陆氯鲁铝录旅卢吕芦颅庐掳卤虏麓碌赂鹿潞禄戮驴侣履屡缕垆撸噜闾泸渌漉逯璐栌榈橹轳辂辘氇胪膂镥稆鸬鹭褛簏舻鲈", "luan :卵乱峦挛孪滦脔娈栾鸾銮", "lue :略掠锊", "lun :论轮伦抡仑沦纶囵", "luo :落罗螺洛络逻萝锣箩骡裸骆倮蠃荦捋摞猡泺漯珞椤脶镙瘰雒", "m :呒", "ma :马麻吗妈骂嘛码玛蚂唛犸嬷杩蟆", "mai :麦脉卖买埋迈劢荬霾", "man :满慢曼漫蔓瞒馒蛮谩墁幔缦熳镘颟螨鳗鞔", "mang :忙芒盲茫氓莽邙漭硭蟒", "mao :毛矛冒貌贸帽猫茅锚铆卯茂袤茆峁泖瑁昴牦耄旄懋瞀蟊髦", "me :么麽", "mei :没每美煤霉酶梅妹眉玫枚媒镁昧寐媚莓嵋猸浼湄楣镅鹛袂魅", "men :们门闷扪焖懑钔", "meng :孟猛蒙盟梦萌锰檬勐甍瞢懵朦礞虻蜢蠓艋艨", "mi :米密迷蜜秘眯醚靡糜谜弥觅泌幂芈谧蘼咪嘧猕汨宓弭脒祢敉糸縻麋", "mian :面棉免绵眠冕勉娩缅沔渑湎腼眄", "miao :苗秒描庙妙瞄藐渺喵邈缈缪杪淼眇鹋", "mie :灭蔑咩蠛篾", "min :民敏抿皿悯闽苠岷闵泯缗玟珉愍黾鳘", "ming :命明名鸣螟铭冥茗溟暝瞑酩", "miu :谬", "mo :磨末模膜摸墨摩莫抹默摹蘑魔沫漠寞陌谟茉蓦馍嫫殁镆秣瘼耱貊貘", "mou :某谋牟侔哞眸蛑蝥鍪", "mu :亩目木母墓幕牧姆穆拇牡暮募慕睦仫坶苜沐毪钼", "n :嗯", "na :那南哪拿纳钠呐娜捺肭镎衲", "nai :耐奶乃氖奈鼐艿萘柰", "nan :南难男喃囝囡楠腩蝻赧", "nang :囊攮囔馕曩", "nao :脑闹挠恼淖孬垴呶猱瑙硇铙蛲", "ne :呢讷", "nei :内馁", "nen :嫩恁", "neng :能", "ni :你泥尼逆拟尿妮霓倪匿腻溺伲坭猊怩昵旎慝睨铌鲵", "nian :年念粘蔫拈碾撵捻酿廿埝辇黏鲇鲶", "niang :娘", "niao :尿鸟茑嬲脲袅", "nie :镍啮涅捏聂孽镊乜陧蘖嗫颞臬蹑", "nin :您", "ning :宁凝拧柠狞泞佞苎咛甯聍", "niu :牛扭钮纽狃忸妞", "nong :农弄浓脓侬哝", "nou :耨", "nu :女奴努怒弩胬孥驽恧钕衄", "nuan :暖", "nue :虐", "nuo :诺挪懦糯傩搦喏锘", "o :欧偶哦鸥殴藕呕沤讴噢怄瓯耦", "ou :欧偶鸥殴藕呕沤讴怄瓯耦", "pa :怕派爬帕啪趴琶葩杷筢", "pai :派排拍牌哌徘湃俳蒎", "pan :判盘叛潘攀磐盼畔胖爿泮袢襻蟠蹒", "pang :旁乓庞耪胖彷滂逄螃", "pao :跑炮刨抛泡咆袍匏狍庖脬疱", "pei :配培陪胚呸裴赔佩沛辔帔旆锫醅霈", "pen :喷盆湓", "peng :碰棚蓬朋捧膨砰抨烹澎彭硼篷鹏堋嘭怦蟛", "pi :批皮坯脾疲砒霹披劈琵毗啤匹痞僻屁譬丕仳陴邳郫圮鼙芘擗噼庀淠媲纰枇甓睥罴铍癖疋蚍蜱貔", "pian :片偏篇骗谝骈犏胼翩蹁", "piao :票漂飘瓢剽嘌嫖缥殍瞟螵", "pie :撇瞥丿苤氕", "pin :品贫频拼苹聘拚姘嫔榀牝颦", "ping :平评瓶凭苹乒坪萍屏俜娉枰鲆", "po :破迫坡泼颇婆魄粕叵鄱珀攴钋钷皤笸", "pou :剖裒掊", "pu :普谱扑埔铺葡朴蒲仆莆菩圃浦曝瀑匍噗溥濮璞氆镤镨蹼", "qi :起其气期七器齐奇汽企漆欺旗畦启弃歧栖戚妻凄柒沏棋崎脐祈祁骑岂乞契砌迄泣讫亓俟圻芑芪萁萋葺蕲嘁屺岐汔淇骐绮琪琦杞桤槭耆欹祺憩碛颀蛴蜞綦綮蹊鳍麒", "qia :恰掐洽葜髂", "qian :前千钱浅签迁铅潜牵钳谴扦钎仟谦乾黔遣堑嵌欠歉倩佥阡芊芡茜荨掮岍悭慊骞搴褰缱椠肷愆钤虔箬箝", "qiang :强枪抢墙腔呛羌蔷戕嫱樯戗炝锖锵镪襁蜣羟跄", "qiao :桥瞧巧敲乔蕉橇锹悄侨鞘撬翘峭俏窍劁诮谯荞愀憔樵硗跷鞒", "qie :切且茄怯窃郄惬妾挈锲箧", "qin :亲侵勤秦钦琴芹擒禽寝沁芩揿吣嗪噙溱檎锓覃螓衾", "qing :情清青轻倾请庆氢晴卿擎氰顷苘圊檠磬蜻罄箐謦鲭黥", "qiong :穷琼邛茕穹蛩筇跫銎", "qiu :求球秋丘邱囚酋泅俅巯犰湫逑遒楸赇虬蚯蝤裘糗鳅鼽", "qu :去区取曲渠屈趋驱趣蛆躯娶龋诎劬蕖蘧岖衢阒璩觑氍朐祛磲鸲癯蛐蠼麴瞿黢", "quan :全权圈劝泉醛颧痊拳犬券诠荃悛绻辁畎铨蜷筌鬈", "que :确却缺炔瘸鹊榷雀阕阙悫", "qun :群裙逡", "ran :然燃染冉苒蚺髯", "rang :让壤嚷瓤攘禳穰", "rao :绕扰饶荛娆桡", "re :热惹", "ren :人认任仁刃忍壬韧妊纫仞荏葚饪轫稔衽", "reng :仍扔", "ri :日", "rong :容溶荣熔融绒戎茸蓉冗嵘狨榕肜蝾", "rou :肉揉柔糅蹂鞣", "ru :如入儒乳茹蠕孺辱汝褥蓐薷嚅洳溽濡缛铷襦颥", "ruan :软阮朊", "rui :瑞锐蕊芮蕤枘睿蚋", "run :润闰", "ruo :弱若偌", "sa :撒萨洒卅仨挲脎飒", "sai :塞赛腮鳃噻", "san :三散叁伞馓毵糁", "sang :桑丧嗓搡磉颡", "sao :扫搔骚嫂埽缫缲臊瘙鳋", "se :色瑟涩啬铯穑", "sen :森", "seng :僧", "sha :沙杀砂啥纱莎刹傻煞杉唼歃铩痧裟霎鲨", "shai :筛晒", "shan :山闪善珊扇陕苫杉删煽衫擅赡膳汕缮剡讪鄯埏芟潸姗嬗骟膻钐疝蟮舢跚鳝", "shang :上商伤尚墒赏晌裳垧绱殇熵觞", "shao :少烧稍绍哨梢捎芍勺韶邵劭苕潲蛸筲艄", "she :社设射摄舌涉舍蛇奢赊赦慑厍佘猞滠歙畲麝", "shen :深身神伸甚渗沈肾审申慎砷呻娠绅婶诜谂莘哂渖椹胂矧蜃", "sheng :生胜声省升盛绳剩圣牲甥嵊晟眚笙", "shi :是时十使事实式识世试石什示市史师始施士势湿适食失视室氏蚀诗释拾饰驶狮尸虱矢屎柿拭誓逝嗜噬仕侍恃谥埘莳蓍弑轼贳炻铈螫舐筮酾豕鲥鲺", "shou :手受收首守授寿兽售瘦狩绶艏", "shu :数书树属术输述熟束鼠疏殊舒蔬薯叔署枢梳抒淑赎孰暑曙蜀黍戍竖墅庶漱恕丨倏塾菽摅沭澍姝纾毹腧殳秫", "shua :刷耍唰", "shuai :衰帅摔甩蟀", "shuan :栓拴闩涮", "shuang:双霜爽孀", "shui :水谁睡税", "shun :顺吮瞬舜", "shuo :说硕朔烁蒴搠妁槊铄", "si :四思死斯丝似司饲私撕嘶肆寺嗣伺巳厮兕厶咝汜泗澌姒驷缌祀锶鸶耜蛳笥", "song :松送宋颂耸怂讼诵凇菘崧嵩忪悚淞竦", "sou :搜艘擞嗽叟薮嗖嗾馊溲飕瞍锼螋", "su :素速苏塑缩俗诉宿肃酥粟僳溯夙谡蔌嗉愫涑簌觫稣", "suan :算酸蒜狻", "sui :随穗碎虽岁隋绥髓遂隧祟谇荽濉邃燧眭睢", "sun :损孙笋荪狲飧榫隼", "suo :所缩锁索蓑梭唆琐唢嗦嗍娑桫睃羧", "ta :他它她塔踏塌獭挞蹋闼溻遢榻沓铊趿鳎", "tai :台太态胎抬泰苔酞汰邰薹肽炱钛跆鲐", "tan :谈碳探炭坦贪滩坍摊瘫坛檀痰潭谭毯袒叹郯澹昙忐钽锬", "tang :堂糖唐塘汤搪棠膛倘躺淌趟烫傥帑溏瑭樘铴镗耥螗螳羰醣", "tao :套讨逃陶萄桃掏涛滔绦淘鼗啕洮韬焘饕", "te :特忒忑铽", "teng :腾疼藤誊滕", "ti :提题体替梯惕剔踢锑蹄啼嚏涕剃屉倜悌逖缇鹈裼醍", "tian :天田添填甜恬舔腆掭忝阗殄畋", "tiao :条跳挑迢眺佻祧窕蜩笤粜龆鲦髫", "tie :铁贴帖萜餮", "ting :听停庭挺廷厅烃汀亭艇莛葶婷梃铤蜓霆", "tong :同通统铜痛筒童桶桐酮瞳彤捅佟仝茼嗵恸潼砼", "tou :头投透偷钭骰", "tu :图土突途徒凸涂吐兔屠秃堍荼菟钍酴", "tuan :团湍抟彖疃", "tui :推退腿颓蜕褪煺", "tun :吞屯臀氽饨暾豚", "tuo :脱拖托妥椭鸵陀驮驼拓唾乇佗坨庹沱柝橐砣箨酡跎鼍", "wa :瓦挖哇蛙洼娃袜佤娲腽", "wai :外歪", "wan :完万晚弯碗顽湾挽玩豌丸烷皖惋宛婉腕剜芄菀纨绾琬脘畹蜿", "wang :往王望网忘妄亡旺汪枉罔尢惘辋魍", "wei :为位委围维唯卫微伟未威危尾谓喂味胃魏伪违韦畏纬巍桅惟潍苇萎蔚渭尉慰偎诿隈葳薇囗帏帷崴嵬猥猬闱沩洧涠逶娓玮韪軎炜煨痿艉鲔", "wen :问温文稳纹闻蚊瘟吻紊刎阌汶璺雯", "weng :嗡翁瓮蓊蕹", "wo :我握窝蜗涡沃挝卧斡倭莴喔幄渥肟硪龌", "wu :无五物武务误伍舞污悟雾午屋乌吴诬钨巫呜芜梧吾毋捂侮坞戊晤勿兀仵阢邬圬芴唔庑怃忤浯寤迕妩婺骛杌牾焐鹉鹜痦蜈鋈鼯", "xi :系席西习细吸析喜洗铣稀戏隙希息袭锡烯牺悉惜溪昔熙硒矽晰嘻膝夕熄汐犀檄媳僖兮隰郗菥葸蓰奚唏徙饩阋浠淅屣嬉玺樨曦觋欷熹禊禧皙穸蜥螅蟋舄舾羲粞翕醯鼷", "xia :下夏吓狭霞瞎虾匣辖暇峡侠厦呷狎遐瑕柙硖罅黠", "xian :线现先县限显鲜献险陷宪纤掀弦腺锨仙咸贤衔舷闲涎嫌馅羡冼苋莶藓岘猃暹娴氙燹祆鹇痫蚬筅籼酰跣跹霰", "xiang :想向相象响项箱乡香像详橡享湘厢镶襄翔祥巷芗葙饷庠骧缃蟓鲞飨", "xiao :小消削效笑校销硝萧肖孝霄哮嚣宵淆晓啸哓崤潇逍骁绡枭枵筱箫魈", "xie :些写斜谢协械卸屑鞋歇邪胁蟹泄泻楔蝎挟携谐懈偕亵勰燮薤撷獬廨渫瀣邂绁缬榭榍躞", "xin :新心信锌芯辛欣薪忻衅囟馨昕歆鑫", "xing :行性形型星兴醒姓幸腥猩惺刑邢杏陉荇荥擤饧悻硎", "xiong :雄胸兄凶熊匈汹芎", "xiu :修锈休袖秀朽羞嗅绣咻岫馐庥溴鸺貅髹", "xu :续许须需序虚絮畜叙蓄绪徐墟戌嘘酗旭恤婿诩勖圩蓿洫溆顼栩煦盱胥糈醑", "xuan :选旋宣悬玄轩喧癣眩绚儇谖萱揎泫渲漩璇楦暄炫煊碹铉镟痃", "xue :学血雪穴靴薛谑泶踅鳕", "xun :训旬迅讯寻循巡勋熏询驯殉汛逊巽埙荀蕈薰峋徇獯恂洵浔曛醺鲟", "ya :压亚呀牙芽雅蚜鸭押鸦丫崖衙涯哑讶伢垭揠岈迓娅琊桠氩砑睚痖", "yan :验研严眼言盐演岩沿烟延掩宴炎颜燕衍焉咽阉淹蜒阎奄艳堰厌砚雁唁彦焰谚厣赝俨偃兖谳郾鄢菸崦恹闫阏湮滟妍嫣琰檐晏胭焱罨筵酽魇餍鼹", "yang :样养氧扬洋阳羊秧央杨仰殃鸯佯疡痒漾徉怏泱炀烊恙蛘鞅", "yao :要药摇腰咬邀耀疟妖瑶尧遥窑谣姚舀夭爻吆崾徭幺珧杳轺曜肴鹞窈繇鳐", "ye :也业页叶液夜野爷冶椰噎耶掖曳腋靥谒邺揶晔烨铘", "yi :一以义意已移医议依易乙艺益异宜仪亿遗伊役衣疑亦谊翼译抑忆疫壹揖铱颐夷胰沂姨彝椅蚁倚矣邑屹臆逸肄裔毅溢诣翌绎刈劓佚佾诒圯埸懿苡荑薏弈奕挹弋呓咦咿噫峄嶷猗饴怿怡悒漪迤驿缢殪轶贻旖熠眙钇镒镱痍瘗癔翊蜴舣羿翳酏黟", "yin :因引阴印音银隐饮荫茵殷姻吟淫寅尹胤鄞垠堙茚吲喑狺夤洇氤铟瘾窨蚓霪龈", "ying :应影硬营英映迎樱婴鹰缨莹萤荧蝇赢盈颖嬴郢茔莺萦蓥撄嘤膺滢潆瀛瑛璎楹媵鹦瘿颍罂", "yo :哟唷", "yong :用勇永拥涌蛹庸佣臃痈雍踊咏泳恿俑壅墉喁慵邕镛甬鳙饔", "you :有由又油右友优幼游尤诱犹幽悠忧邮铀酉佑釉卣攸侑莠莜莸呦囿宥柚猷牖铕疣蚰蚴蝣鱿黝鼬", "yu :于与育鱼雨玉余遇预域语愈渔予羽愚御欲宇迂淤盂榆虞舆俞逾愉渝隅娱屿禹芋郁吁喻峪狱誉浴寓裕豫驭禺毓伛俣谀谕萸蓣揄圄圉嵛狳饫馀庾阈鬻妪妤纡瑜昱觎腴欤於煜熨燠聿钰鹆鹬瘐瘀窬窳蜮蝓竽臾舁雩龉", "yuan :员原圆源元远愿院缘援园怨鸳渊冤垣袁辕猿苑垸塬芫掾沅媛瑗橼爰眢鸢螈箢鼋", "yue :月越约跃曰阅钥岳粤悦龠瀹樾刖钺", "yun :运云匀允孕耘郧陨蕴酝晕韵郓芸狁恽愠纭韫殒昀氲熨", "za :杂咱匝砸咋咂", "zai :在再载栽灾哉宰崽甾", "zan :赞咱暂攒拶瓒昝簪糌趱錾", "zang :脏葬赃奘驵臧", "zao :造早遭燥凿糟枣皂藻澡蚤躁噪灶唣", "ze :则择责泽仄赜啧帻迮昃笮箦舴", "zei :贼", "zen :怎谮", "zeng :增曾憎赠缯甑罾锃", "zha :扎炸闸铡轧渣喳札眨栅榨乍诈揸吒咤哳砟痄蚱齄", "zhai :寨摘窄斋宅债砦瘵", "zhan :战展站占瞻毡詹沾盏斩辗崭蘸栈湛绽谵搌旃", "zhang :张章掌仗障胀涨账樟彰漳杖丈帐瘴仉鄣幛嶂獐嫜璋蟑", "zhao :照找招召赵爪罩沼兆昭肇诏棹钊笊", "zhe :这着者折哲浙遮蛰辙锗蔗谪摺柘辄磔鹧褶蜇赭", "zhen :真针阵镇振震珍诊斟甄砧臻贞侦枕疹圳蓁浈缜桢榛轸赈胗朕祯畛稹鸩箴", "zheng :争正政整证征蒸症郑挣睁狰怔拯帧诤峥徵钲铮筝", "zhi :之制治只质指直支织止至置志值知执职植纸致枝殖脂智肢秩址滞汁芝吱蜘侄趾旨挚掷帜峙稚炙痔窒卮陟郅埴芷摭帙忮彘咫骘栉枳栀桎轵轾贽胝膣祉祗黹雉鸷痣蛭絷酯跖踬踯豸觯", "zhong :中种重众钟终忠肿仲盅衷冢锺螽舯踵", "zhou :轴周洲州皱骤舟诌粥肘帚咒宙昼荮啁妯纣绉胄碡籀酎", "zhu :主注著住助猪铸株筑柱驻逐祝竹贮珠朱诸蛛诛烛煮拄瞩嘱蛀伫侏邾茱洙渚潴杼槠橥炷铢疰瘃竺箸舳翥躅麈", "zhua :抓", "zhuai :拽", "zhuan :转专砖撰赚篆啭馔颛", "zhuang:装状壮庄撞桩妆僮", "zhui :追锥椎赘坠缀惴骓缒", "zhun :准谆肫窀", "zhuo :捉桌拙卓琢茁酌啄灼浊倬诼擢浞涿濯焯禚斫镯", "zi :子自资字紫仔籽姿兹咨滋淄孜滓渍谘嵫姊孳缁梓辎赀恣眦锱秭耔笫粢趑觜訾龇鲻髭", "zong :总纵宗综棕鬃踪偬枞腙粽", "zou :走邹奏揍诹陬鄹驺鲰", "zu :组族足阻祖租卒诅俎菹镞", "zuan :钻纂攥缵躜", "zui :最罪嘴醉蕞", "zun :尊遵撙樽鳟", "zuo :作做左座坐昨佐柞阼唑嘬怍胙祚"}; } }
27182812/ChatGLM-LLaMA-chinese-insturct
4,916
src/transformers/models/transfo_xl/convert_transfo_xl_original_tf_checkpoint_to_pytorch.py
# coding=utf-8 # Copyright 2018 The HuggingFace Inc. team. # # 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. """Convert Transformer XL checkpoint and datasets.""" import argparse import os import pickle import sys import torch from transformers import TransfoXLConfig, TransfoXLLMHeadModel, load_tf_weights_in_transfo_xl from transformers.models.transfo_xl import tokenization_transfo_xl as data_utils from transformers.models.transfo_xl.tokenization_transfo_xl import CORPUS_NAME, VOCAB_FILES_NAMES from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() # We do this to be able to load python 2 datasets pickles # See e.g. https://stackoverflow.com/questions/2121874/python-pickling-after-changing-a-modules-directory/2121918#2121918 data_utils.Vocab = data_utils.TransfoXLTokenizer data_utils.Corpus = data_utils.TransfoXLCorpus sys.modules["data_utils"] = data_utils sys.modules["vocabulary"] = data_utils def convert_transfo_xl_checkpoint_to_pytorch( tf_checkpoint_path, transfo_xl_config_file, pytorch_dump_folder_path, transfo_xl_dataset_file ): if transfo_xl_dataset_file: # Convert a pre-processed corpus (see original TensorFlow repo) with open(transfo_xl_dataset_file, "rb") as fp: corpus = pickle.load(fp, encoding="latin1") # Save vocabulary and dataset cache as Dictionaries (should be better than pickles for the long-term) pytorch_vocab_dump_path = pytorch_dump_folder_path + "/" + VOCAB_FILES_NAMES["pretrained_vocab_file"] print(f"Save vocabulary to {pytorch_vocab_dump_path}") corpus_vocab_dict = corpus.vocab.__dict__ torch.save(corpus_vocab_dict, pytorch_vocab_dump_path) corpus_dict_no_vocab = corpus.__dict__ corpus_dict_no_vocab.pop("vocab", None) pytorch_dataset_dump_path = pytorch_dump_folder_path + "/" + CORPUS_NAME print(f"Save dataset to {pytorch_dataset_dump_path}") torch.save(corpus_dict_no_vocab, pytorch_dataset_dump_path) if tf_checkpoint_path: # Convert a pre-trained TensorFlow model config_path = os.path.abspath(transfo_xl_config_file) tf_path = os.path.abspath(tf_checkpoint_path) print(f"Converting Transformer XL checkpoint from {tf_path} with config at {config_path}.") # Initialise PyTorch model if transfo_xl_config_file == "": config = TransfoXLConfig() else: config = TransfoXLConfig.from_json_file(transfo_xl_config_file) print(f"Building PyTorch model from configuration: {config}") model = TransfoXLLMHeadModel(config) model = load_tf_weights_in_transfo_xl(model, config, tf_path) # Save pytorch-model pytorch_weights_dump_path = os.path.join(pytorch_dump_folder_path, WEIGHTS_NAME) pytorch_config_dump_path = os.path.join(pytorch_dump_folder_path, CONFIG_NAME) print(f"Save PyTorch model to {os.path.abspath(pytorch_weights_dump_path)}") torch.save(model.state_dict(), pytorch_weights_dump_path) print(f"Save configuration file to {os.path.abspath(pytorch_config_dump_path)}") with open(pytorch_config_dump_path, "w", encoding="utf-8") as f: f.write(config.to_json_string()) if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the folder to store the PyTorch model or dataset/vocab.", ) parser.add_argument( "--tf_checkpoint_path", default="", type=str, help="An optional path to a TensorFlow checkpoint path to be converted.", ) parser.add_argument( "--transfo_xl_config_file", default="", type=str, help=( "An optional config json file corresponding to the pre-trained BERT model. \n" "This specifies the model architecture." ), ) parser.add_argument( "--transfo_xl_dataset_file", default="", type=str, help="An optional dataset file to be converted in a vocabulary.", ) args = parser.parse_args() convert_transfo_xl_checkpoint_to_pytorch( args.tf_checkpoint_path, args.transfo_xl_config_file, args.pytorch_dump_folder_path, args.transfo_xl_dataset_file, )
2881099/dotnetGen_sqlserver
12,117
GenMs/plist-cil/NSSet.cs
// plist-cil - An open source library to parse and generate property lists for .NET // Copyright (C) 2015 Natalia Portillo // // This code is based on: // plist - An open source library to parse and generate property lists // Copyright (C) 2014 Daniel Dreibrodt // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. using System; using System.Collections.Generic; using System.Collections; using System.Text; namespace PList { /// <summary> /// <para> /// A set is an interface to an unordered collection of objects. /// </para><para> /// This implementation uses a <see cref="List{NSObject}"/>as the underlying /// data structure. /// </para> /// </summary> /// @author Daniel Dreibrodt /// @author Natalia Portillo public class NSSet : NSObject, IEnumerable { readonly List<NSObject> set; bool ordered; /// <summary> /// Creates an empty unordered set. /// </summary> public NSSet() { set = new List<NSObject>(); } /// <summary> /// Creates an empty set. /// </summary> /// <param name="ordered">Should the set be ordered on operations?</param> public NSSet(bool ordered) { this.ordered = ordered; set = new List<NSObject>(); } /// <summary> /// Creates a set and fill it with the given objects. /// </summary> /// <param name="objects">The objects to populate the set.</param> public NSSet(params NSObject[] objects) { set = new List<NSObject>(objects); } /// <summary> /// Creates a set and fill it with the given objects. /// </summary> /// <param name="objects">The objects to populate the set.</param> /// <param name="ordered">Should the set be ordered on operations?</param> public NSSet(bool ordered, params NSObject[] objects) { this.ordered = ordered; set = new List<NSObject>(objects); if (ordered) set.Sort(); } /// <summary> /// Adds an object to the set. /// </summary> /// <param name="obj">The object to add.</param> public void AddObject(NSObject obj) { lock (set) { set.Add(obj); if (ordered) set.Sort(); } } /// <summary> /// Removes an object from the set. /// </summary> /// <param name="obj">The object to remove.</param> public void RemoveObject(NSObject obj) { lock (set) { set.Remove(obj); if (ordered) set.Sort(); } } /// <summary> /// Returns all objects contained in the set. /// </summary> /// <returns>An array of all objects in the set.</returns> public NSObject[] AllObjects() { lock (set) { return set.ToArray(); } } /// <summary> /// Returns one of the objects in the set, or <c>null</c> /// if the set contains no objects. /// </summary> /// <returns>The first object in the set, or <c>null</c> if the set is empty.</returns> public NSObject AnyObject() { lock (set) { return set.Count == 0 ? null : set[0]; } } /// <summary> /// Finds out whether a given object is contained in the set. /// </summary> /// <returns><c>true</c>, when the object was found, <c>false</c> otherwise.</returns> /// <param name="obj">The object to look for.</param> public bool ContainsObject(NSObject obj) { return set.Contains(obj); } /// <summary> /// Determines whether the set contains an object equal to a given object /// and returns that object if it is present. /// </summary> /// <param name="obj">The object to look for.</param> /// <returns>The object if it is present, <c>null</c> otherwise.</returns> public NSObject Member(NSObject obj) { lock (set) { foreach (NSObject o in set) { if (o.Equals(obj)) return o; } return null; } } /// <summary> /// Finds out whether at least one object is present in both sets. /// </summary> /// <returns><c>true</c> if the intersection of both sets is empty, <c>false</c> otherwise.</returns> /// <param name="otherSet">The other set.</param> public bool IntersectsSet(NSSet otherSet) { lock (set) { foreach (NSObject o in set) { if (otherSet.ContainsObject(o)) return true; } return false; } } /// <summary> /// Finds out if this set is a subset of the given set. /// </summary> /// <returns><c>true</c> if all elements in this set are also present in the other set, <c>false</c>otherwise.</returns> /// <param name="otherSet">The other set.</param> public bool IsSubsetOfSet(NSSet otherSet) { lock (set) { foreach (NSObject o in set) { if (!otherSet.ContainsObject(o)) return false; } return true; } } /// <summary> /// Returns an enumerator object that lets you iterate over all elements of the set. /// This is the equivalent to <c>objectEnumerator</c> in the Cocoa implementation /// of NSSet. /// </summary> /// <returns>The iterator for the set.</returns> public IEnumerator GetEnumerator() { lock (set) { return set.GetEnumerator(); } } /// <summary> /// Gets the underlying data structure in which this NSSets stores its content. /// </summary> /// <returns>A Set object.</returns> internal List<NSObject> GetSet() { return set; } /// <summary> /// Serves as a hash function for a <see cref="PList.NSSet"/> object. /// </summary> /// <returns>A hash code for this instance that is suitable for use in hashing algorithms and data structures such as a /// hash table.</returns> public override int GetHashCode() { int hash = 7; hash = 29 * hash + (set != null ? set.GetHashCode() : 0); return hash; } /// <summary> /// Determines whether the specified <see cref="System.Object"/> is equal to the current <see cref="PList.NSSet"/>. /// </summary> /// <param name="obj">The <see cref="System.Object"/> to compare with the current <see cref="PList.NSSet"/>.</param> /// <returns><c>true</c> if the specified <see cref="System.Object"/> is equal to the current /// <see cref="PList.NSSet"/>; otherwise, <c>false</c>.</returns> public override bool Equals(Object obj) { if (obj == null) { return false; } if (GetType() != obj.GetType()) { return false; } NSSet other = (NSSet)obj; return !(set != other.set && (set == null || !set.Equals(other.set))); } /// <summary> /// Gets the number of elements in the set. /// </summary> /// <value>The number of elements in the set.</value> public int Count { get { lock (set) { return set.Count; } } } /// <summary> /// Returns the XML representantion for this set. /// There is no official XML representation specified for sets. /// In this implementation it is represented by an array. /// </summary> /// <param name="xml">The XML StringBuilder</param> /// <param name="level">The indentation level</param> internal override void ToXml(StringBuilder xml, int level) { Indent(xml, level); xml.Append("<array>"); xml.Append(NSObject.NEWLINE); if (ordered) set.Sort(); foreach (NSObject o in set) { o.ToXml(xml, level + 1); xml.Append(NSObject.NEWLINE); } Indent(xml, level); xml.Append("</array>"); } internal override void AssignIDs(BinaryPropertyListWriter outPlist) { base.AssignIDs(outPlist); foreach (NSObject obj in set) { obj.AssignIDs(outPlist); } } internal override void ToBinary(BinaryPropertyListWriter outPlist) { if (ordered) { set.Sort(); outPlist.WriteIntHeader(0xB, set.Count); } else { outPlist.WriteIntHeader(0xC, set.Count); } foreach (NSObject obj in set) { outPlist.WriteID(outPlist.GetID(obj)); } } /// <summary> /// Returns the ASCII representation of this set. /// There is no official ASCII representation for sets. /// In this implementation sets are represented as arrays. /// </summary> /// <param name="ascii">The ASCII file string builder</param> /// <param name="level">The indentation level</param> internal override void ToASCII(StringBuilder ascii, int level) { Indent(ascii, level); if (ordered) set.Sort(); NSObject[] array = AllObjects(); ascii.Append(ASCIIPropertyListParser.ARRAY_BEGIN_TOKEN); int indexOfLastNewLine = ascii.ToString().LastIndexOf(NEWLINE, StringComparison.Ordinal); for (int i = 0; i < array.Length; i++) { Type objClass = array[i].GetType(); if ((objClass.Equals(typeof(NSDictionary)) || objClass.Equals(typeof(NSArray)) || objClass.Equals(typeof(NSData))) && indexOfLastNewLine != ascii.Length) { ascii.Append(NEWLINE); indexOfLastNewLine = ascii.Length; array[i].ToASCII(ascii, level + 1); } else { if (i != 0) ascii.Append(" "); array[i].ToASCII(ascii, 0); } if (i != array.Length - 1) ascii.Append(ASCIIPropertyListParser.ARRAY_ITEM_DELIMITER_TOKEN); if (ascii.Length - indexOfLastNewLine > ASCII_LINE_LENGTH) { ascii.Append(NEWLINE); indexOfLastNewLine = ascii.Length; } } ascii.Append(ASCIIPropertyListParser.ARRAY_END_TOKEN); } /// <summary> /// Returns the ASCII representation of this set according to the GnuStep format. /// There is no official ASCII representation for sets. /// In this implementation sets are represented as arrays. /// </summary> /// <param name="ascii">The ASCII file string builder</param> /// <param name="level">The indentation level</param> internal override void ToASCIIGnuStep(StringBuilder ascii, int level) { Indent(ascii, level); if (ordered) set.Sort(); NSObject[] array = AllObjects(); ascii.Append(ASCIIPropertyListParser.ARRAY_BEGIN_TOKEN); int indexOfLastNewLine = ascii.ToString().LastIndexOf(NEWLINE, StringComparison.Ordinal); for (int i = 0; i < array.Length; i++) { Type objClass = array[i].GetType(); if ((objClass.Equals(typeof(NSDictionary)) || objClass.Equals(typeof(NSArray)) || objClass.Equals(typeof(NSData))) && indexOfLastNewLine != ascii.Length) { ascii.Append(NEWLINE); indexOfLastNewLine = ascii.Length; array[i].ToASCIIGnuStep(ascii, level + 1); } else { if (i != 0) ascii.Append(" "); array[i].ToASCIIGnuStep(ascii, 0); } if (i != array.Length - 1) ascii.Append(ASCIIPropertyListParser.ARRAY_ITEM_DELIMITER_TOKEN); if (ascii.Length - indexOfLastNewLine > ASCII_LINE_LENGTH) { ascii.Append(NEWLINE); indexOfLastNewLine = ascii.Length; } } ascii.Append(ASCIIPropertyListParser.ARRAY_END_TOKEN); } /// <summary> /// Determines whether the specified <see cref="PList.NSObject"/> is equal to the current <see cref="PList.NSSet"/>. /// </summary> /// <param name="obj">The <see cref="PList.NSObject"/> to compare with the current <see cref="PList.NSSet"/>.</param> /// <returns><c>true</c> if the specified <see cref="PList.NSObject"/> is equal to the current /// <see cref="PList.NSSet"/>; otherwise, <c>false</c>.</returns> public override bool Equals(NSObject obj) { if (!(obj is NSSet)) return false; if (set.Count != ((NSSet)obj).Count) return false; foreach (NSObject objS in (NSSet)obj) if (!set.Contains(objS)) return false; return true; } } }
2881099/dotnetGen_sqlserver
14,727
GenMs/plist-cil/NSNumber.cs
// plist-cil - An open source library to parse and generate property lists for .NET // Copyright (C) 2015 Natalia Portillo // // This code is based on: // plist - An open source library to parse and generate property lists // Copyright (C) 2014 Daniel Dreibrodt // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. using System; using System.Text; using System.Globalization; namespace PList { /// <summary> /// A number whose value is either an integer, a real number or bool. /// </summary> /// @author Daniel Dreibrodt /// @author Natalia Portillo public class NSNumber : NSObject, IComparable { /// <summary> /// Indicates that the number's value is an integer. /// The number is stored as a .NET <see cref="long"/>. /// Its original value could have been char, short, int, long or even long long. /// </summary> public const int INTEGER = 0; /// <summary> /// Indicates that the number's value is a real number. /// The number is stored as a .NET <see cref="double"/>. /// Its original value could have been float or double. /// </summary> public const int REAL = 1; /// <summary> /// Indicates that the number's value is bool. /// </summary> public const int BOOLEAN = 2; //Holds the current type of this number readonly int type; readonly long longValue; readonly double doubleValue; readonly bool boolValue; /// <summary> /// Parses integers and real numbers from their binary representation. /// <i>Note: real numbers are not yet supported.</i> /// </summary> /// <param name="bytes">The binary representation</param> /// <param name="type">The type of number</param> /// <seealso cref="INTEGER"/> /// <seealso cref="REAL"/> public NSNumber(byte[] bytes, int type) { switch (type) { case INTEGER: doubleValue = longValue = BinaryPropertyListParser.ParseLong(bytes); break; case REAL: doubleValue = BinaryPropertyListParser.ParseDouble(bytes); longValue = (long)Math.Round(doubleValue); break; default: throw new ArgumentException("Type argument is not valid."); } this.type = type; } public NSNumber(string text, int type) { switch (type) { case INTEGER: { doubleValue = longValue = long.Parse(text, CultureInfo.InvariantCulture); break; } case REAL: { doubleValue = double.Parse(text, CultureInfo.InvariantCulture); longValue = (long)Math.Round(doubleValue); break; } default: { throw new ArgumentException("Type argument is not valid."); } } this.type = type; } /// <summary> /// Creates a number from its textual representation. /// </summary> /// <param name="text">The textual representation of the number.</param> /// <seealso cref="bool.Parse(string)"/> /// <seealso cref="long.Parse(string)"/> /// <seealso cref="double.Parse(string, IFormatProvider)"/> public NSNumber(string text) { if (text == null) throw new ArgumentException("The given string is null and cannot be parsed as number."); long l; double d; if (long.TryParse(text, NumberStyles.Number, CultureInfo.InvariantCulture, out l)) { doubleValue = longValue = l; type = INTEGER; } else if (double.TryParse(text, NumberStyles.Number, CultureInfo.InvariantCulture, out d)) { doubleValue = d; longValue = (long)Math.Round(doubleValue); type = REAL; } else { bool isTrue = string.Equals(text, "true", StringComparison.CurrentCultureIgnoreCase) || string.Equals(text, "yes", StringComparison.CurrentCultureIgnoreCase); bool isFalse = string.Equals(text, "false", StringComparison.CurrentCultureIgnoreCase) || string.Equals(text, "no", StringComparison.CurrentCultureIgnoreCase); if (isTrue || isFalse) { type = BOOLEAN; doubleValue = longValue = boolValue ? 1 : 0; } else { throw new ArgumentException("The given string neither represents a double, an int nor a bool value."); } } } /// <summary> /// Creates an integer number. /// </summary> /// <param name="i">The integer value.</param> public NSNumber(int i) { doubleValue = longValue = i; type = INTEGER; } /// <summary> /// Creates an integer number. /// </summary> /// <param name="l">The long integer value.</param> public NSNumber(long l) { doubleValue = longValue = l; type = INTEGER; } /// <summary> /// Creates a real number. /// </summary> /// <param name="d">The real value.</param> public NSNumber(double d) { longValue = (long)(doubleValue = d); type = REAL; } /// <summary> /// Creates a bool number. /// </summary> /// <param name="b">The bool value.</param> public NSNumber(bool b) { boolValue = b; doubleValue = longValue = b ? 1 : 0; type = BOOLEAN; } /// <summary> /// Gets the type of this number's value. /// </summary> /// <returns>The type flag.</returns> /// <seealso cref="BOOLEAN"/> /// <seealso cref="INTEGER"/> /// <seealso cref="REAL"/> public int GetNSNumberType() { return type; } /// <summary> /// Checks whether the value of this NSNumber is a bool. /// </summary> /// <returns>Whether the number's value is a bool.</returns> public bool isBoolean() { return type == BOOLEAN; } /// <summary> /// Checks whether the value of this NSNumber is an integer. /// </summary> /// <returns>Whether the number's value is an integer.</returns> public bool isInteger() { return type == INTEGER; } /// <summary> /// Checks whether the value of this NSNumber is a real number. /// </summary> /// <returns>Whether the number's value is a real number.</returns> public bool isReal() { return type == REAL; } /// <summary> /// The number's bool value. /// </summary> /// <returns><c>true</c> if the value is true or non-zero, <c>false</c> otherwise.</returns> public bool ToBool() { if (type == BOOLEAN) return boolValue; return longValue != 0; } /// <summary> /// The number's long value. /// </summary> /// <returns>The value of the number as long</returns> public long ToLong() { return longValue; } /// <summary> /// The number's int value. /// <i>Note: Even though the number's type might be INTEGER it can be larger than a Java int. /// Use intValue() only if you are certain that it contains a number from the int range. /// Otherwise the value might be innaccurate.</i> /// </summary> /// <returns>The value of the number as int.</returns> public int ToInt() { return (int)longValue; } /// <summary> /// The number's double value. /// </summary> /// <returns>The value of the number as double.</returns> public double ToDouble() { return doubleValue; } /// <summary> /// The number's float value. /// WARNING: Possible loss of precision if the value is outside the float range. /// </summary> /// <returns>The value of the number as float.</returns> public float floatValue() { return (float)doubleValue; } /// <summary> /// Checks whether the other object is a NSNumber of the same value. /// </summary> /// <param name="obj">The object to compare to.</param> /// <returns>Whether the objects are equal in terms of numeric value and type.</returns> public override bool Equals(Object obj) { if (!(obj is NSNumber)) return false; NSNumber n = (NSNumber)obj; return type == n.type && longValue == n.longValue && doubleValue == n.doubleValue && boolValue == n.boolValue; } /// <summary> /// Serves as a hash function for a <see cref="PList.NSNumber"/> object. /// </summary> /// <returns>A hash code for this instance that is suitable for use in hashing algorithms and data structures such as a /// hash table.</returns> public override int GetHashCode() { int hash = type; hash = 37 * hash + (int)(longValue ^ ((uint)longValue >> 32)); hash = 37 * hash + (int)(BitConverter.DoubleToInt64Bits(doubleValue) ^ ((uint)(BitConverter.DoubleToInt64Bits(doubleValue) >> 32))); hash = 37 * hash + (ToBool() ? 1 : 0); return hash; } /// <summary> /// Returns a <see cref="System.String"/> that represents the current <see cref="PList.NSNumber"/>. /// </summary> /// <returns>A <see cref="System.String"/> that represents the current <see cref="PList.NSNumber"/>.</returns> public override string ToString() { switch (type) { case INTEGER: { return ToLong().ToString(); } case REAL: { return ToDouble().ToString(CultureInfo.InvariantCulture); } case BOOLEAN: { return ToBool().ToString(); } default: { return base.ToString(); } } } internal override void ToXml(StringBuilder xml, int level) { Indent(xml, level); switch (type) { case INTEGER: { xml.Append("<integer>"); xml.Append(ToLong()); xml.Append("</integer>"); break; } case REAL: { xml.Append("<real>"); if (doubleValue == 0) { // 0 values appear to always roundtrip as 0.0, // but non-zero values do not include decimals if // not required (e.g. 10 -> "10") xml.Append("0.0"); } else { xml.Append(ToDouble().ToString(CultureInfo.InvariantCulture)); } xml.Append("</real>"); break; } case BOOLEAN: { if (ToBool()) xml.Append("<true/>"); else xml.Append("<false/>"); break; } } } internal override void ToBinary(BinaryPropertyListWriter outPlist) { switch (GetNSNumberType()) { case INTEGER: { if (ToLong() < 0) { outPlist.Write(0x13); outPlist.WriteBytes(ToLong(), 8); } else if (ToLong() <= 0xff) { outPlist.Write(0x10); outPlist.WriteBytes(ToLong(), 1); } else if (ToLong() <= 0xffff) { outPlist.Write(0x11); outPlist.WriteBytes(ToLong(), 2); } else if (ToLong() <= 0xffffffffL) { outPlist.Write(0x12); outPlist.WriteBytes(ToLong(), 4); } else { outPlist.Write(0x13); outPlist.WriteBytes(ToLong(), 8); } break; } case REAL: { outPlist.Write(0x23); outPlist.WriteDouble(ToDouble()); break; } case BOOLEAN: { outPlist.Write(ToBool() ? 0x09 : 0x08); break; } } } internal override void ToASCII(StringBuilder ascii, int level) { Indent(ascii, level); if (type == BOOLEAN) { ascii.Append(boolValue ? "YES" : "NO"); } else { ascii.Append(ToString()); } } internal override void ToASCIIGnuStep(StringBuilder ascii, int level) { Indent(ascii, level); switch (type) { case INTEGER: { ascii.Append("<*I"); ascii.Append(ToString()); ascii.Append(">"); break; } case REAL: { ascii.Append("<*R"); ascii.Append(ToString()); ascii.Append(">"); break; } case BOOLEAN: { if (boolValue) { ascii.Append("<*BY>"); } else { ascii.Append("<*BN>"); } break; } } } /// <summary> /// Compares the current <see cref="PList.NSNumber"/> to the specified object. /// </summary> /// <returns>0 if the numbers are equal, 1 if the current <see cref="PList.NSNumber"/> is greater /// than the argument and -1 if it is less, or the argument is not a number.</returns> /// <param name="o">Object to compare to the current <see cref="PList.NSNumber"/>.</param> public int CompareTo(Object o) { double x = ToDouble(); double y; if (o is NSNumber) { NSNumber num = (NSNumber)o; y = num.ToDouble(); return (x < y) ? -1 : ((x == y) ? 0 : 1); } if (IsNumber(o)) { y = GetDoubleFromObject(o); return (x < y) ? -1 : ((x == y) ? 0 : 1); } return -1; } /// <summary> /// Determines if an object is a number. /// Substitutes .NET's Number class comparison /// </summary> /// <returns><c>true</c> if it is a number.</returns> /// <param name="o">Object.</param> static bool IsNumber(Object o) { return o is sbyte || o is byte || o is short || o is ushort || o is int || o is uint || o is long || o is ulong || o is float || o is double || o is decimal; } static double GetDoubleFromObject(Object o) { if (o is sbyte) return (double)((sbyte)o); if (o is byte) return (double)((byte)o); if (o is short) return (double)((short)o); if (o is ushort) return (double)((ushort)o); if (o is int) return (double)((int)o); if (o is uint) return (double)((uint)o); if (o is long) return (double)((long)o); if (o is ulong) return (double)((ulong)o); if (o is float) return (double)((float)o); if (o is double) return (double)o; if (o is decimal) return (double)((decimal)o); return (double)0; } /// <summary> /// Determines whether the specified <see cref="PList.NSObject"/> is equal to the current <see cref="PList.NSNumber"/>. /// </summary> /// <param name="obj">The <see cref="PList.NSObject"/> to compare with the current <see cref="PList.NSNumber"/>.</param> /// <returns><c>true</c> if the specified <see cref="PList.NSObject"/> is equal to the current /// <see cref="PList.NSNumber"/>; otherwise, <c>false</c>.</returns> public override bool Equals(NSObject obj) { if (!(obj is NSNumber)) return false; if (((NSNumber)obj).GetNSNumberType() != type) return false; switch (type) { case INTEGER: return (longValue == ((NSNumber)obj).ToLong()); case REAL: return (doubleValue == ((NSNumber)obj).ToDouble()); case BOOLEAN: return (boolValue == ((NSNumber)obj).ToBool()); default: return false; } } } }
27182812/ChatGLM-LLaMA-chinese-insturct
2,670
src/transformers/models/efficientnet/__init__.py
# flake8: noqa # There's no way to ignore "F401 '...' imported but unused" warnings in this # module, but to preserve other warnings. So, don't check this module at all. # Copyright 2023 The HuggingFace Team. 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. from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available _import_structure = { "configuration_efficientnet": [ "EFFICIENTNET_PRETRAINED_CONFIG_ARCHIVE_MAP", "EfficientNetConfig", "EfficientNetOnnxConfig", ] } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _import_structure["image_processing_efficientnet"] = ["EfficientNetImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _import_structure["modeling_efficientnet"] = [ "EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST", "EfficientNetForImageClassification", "EfficientNetModel", "EfficientNetPreTrainedModel", ] if TYPE_CHECKING: from .configuration_efficientnet import ( EFFICIENTNET_PRETRAINED_CONFIG_ARCHIVE_MAP, EfficientNetConfig, EfficientNetOnnxConfig, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_efficientnet import EfficientNetImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_efficientnet import ( EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST, EfficientNetForImageClassification, EfficientNetModel, EfficientNetPreTrainedModel, ) else: import sys sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure)
2881099/dotnetGen_postgresql
9,777
GenPg/plist-cil/BinaryPropertyListWriter.cs
// plist-cil - An open source library to parse and generate property lists for .NET // Copyright (C) 2015 Natalia Portillo // // This code is based on: // plist - An open source library to parse and generate property lists // Copyright (C) 2014 Daniel Dreibrodt // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. using System; using System.IO; using System.Linq; using System.Collections.Generic; using System.Collections.ObjectModel; namespace PList { /// <summary> /// <para> /// A BinaryPropertyListWriter is a helper class for writing out /// binary property list files. /// </para><para> /// It contains an output stream and various structures for keeping track /// of which NSObjects have already been serialized, and where they were /// put in the file. /// </para> /// </summary> /// @author Keith Randall /// @author Natalia Portillo public class BinaryPropertyListWriter { /// <summary> /// Binary property list version 0.0 /// </summary> public const int VERSION_00 = 0; /// <summary> /// Binary property list version 1.0 /// </summary> public const int VERSION_10 = 10; /// <summary> /// Binary property list version 1.5 /// </summary> public const int VERSION_15 = 15; /// <summary> /// Binary property list version 2.0 /// </summary> public const int VERSION_20 = 20; /// <summary> /// Finds out the minimum binary property list format version that /// can be used to save the given NSObject tree. /// </summary> /// <returns>Version code</returns> /// <param name="root">Object root.</param> static int GetMinimumRequiredVersion(NSObject root) { int minVersion = VERSION_00; if (root == null) { minVersion = VERSION_10; } if (root is NSDictionary) { NSDictionary dict = (NSDictionary)root; foreach (NSObject o in dict.GetDictionary().Values) { int v = GetMinimumRequiredVersion(o); if (v > minVersion) minVersion = v; } } else if (root is NSArray) { NSArray array = (NSArray)root; foreach (NSObject o in array.GetArray()) { int v = GetMinimumRequiredVersion(o); if (v > minVersion) minVersion = v; } } else if (root is NSSet) { //Sets are only allowed in property lists v1+ minVersion = VERSION_10; NSSet set = (NSSet)root; foreach (NSObject o in set.AllObjects()) { int v = GetMinimumRequiredVersion(o); if (v > minVersion) minVersion = v; } } return minVersion; } /// <summary> /// Writes a binary plist file with the given object as the root. /// </summary> /// <param name="file">the file to write to</param> /// <param name="root">the source of the data to write to the file</param> /// <exception cref="IOException"></exception> public static void Write(FileInfo file, NSObject root) { using (FileStream fous = file.OpenWrite()) { Write(fous, root); } } /// <summary> /// Writes a binary plist serialization of the given object as the root. /// </summary> /// <param name="outStream">the stream to write to</param> /// <param name="root">the source of the data to write to the stream</param> /// <exception cref="IOException"></exception> public static void Write(Stream outStream, NSObject root) { int minVersion = GetMinimumRequiredVersion(root); if (minVersion > VERSION_00) { string versionString = ((minVersion == VERSION_10) ? "v1.0" : ((minVersion == VERSION_15) ? "v1.5" : ((minVersion == VERSION_20) ? "v2.0" : "v0.0"))); throw new IOException("The given property list structure cannot be saved. " + "The required version of the binary format (" + versionString + ") is not yet supported."); } BinaryPropertyListWriter w = new BinaryPropertyListWriter(outStream, minVersion); w.Write(root); } /// <summary> /// Writes a binary plist serialization of the given object as the root /// into a byte array. /// </summary> /// <returns>The byte array containing the serialized property list</returns> /// <param name="root">The root object of the property list</param> /// <exception cref="IOException"></exception> public static byte[] WriteToArray(NSObject root) { MemoryStream bout = new MemoryStream(); Write(bout, root); return bout.ToArray(); } int version = VERSION_00; // raw output stream to result file Stream outStream; // # of bytes written so far long count; // map from object to its ID Collection<NSObject> idMap = new Collection<NSObject>(); //(new IdentityEqualityComparer<NSObject>()); int idSizeInBytes; /// <summary> /// Creates a new binary property list writer /// </summary> /// <param name="outStr">The output stream into which the binary property list will be written</param> /// <exception cref="IOException">If an error occured while writing to the stream</exception> BinaryPropertyListWriter(Stream outStr) { outStream = outStr; } BinaryPropertyListWriter(Stream outStr, int version) { this.version = version; outStream = outStr; } void Write(NSObject root) { // magic bytes Write(new[] { (byte)'b', (byte)'p', (byte)'l', (byte)'i', (byte)'s', (byte)'t' }); //version switch (version) { case VERSION_00: { Write(new[] { (byte)'0', (byte)'0' }); break; } case VERSION_10: { Write(new[] { (byte)'1', (byte)'0' }); break; } case VERSION_15: { Write(new[] { (byte)'1', (byte)'5' }); break; } case VERSION_20: { Write(new[] { (byte)'2', (byte)'0' }); break; } } // assign IDs to all the objects. root.AssignIDs(this); idSizeInBytes = ComputeIdSizeInBytes(idMap.Count); // offsets of each object, indexed by ID long[] offsets = new long[idMap.Count]; // write each object, save offset for (int i = 0; i < idMap.Count; i++) { NSObject obj = idMap[i]; int id = i; offsets[id] = count; if (obj == null) { Write(0x00); } else { obj.ToBinary(this); } } // write offset table long offsetTableOffset = count; int offsetSizeInBytes = ComputeOffsetSizeInBytes(count); foreach (long offset in offsets) { WriteBytes(offset, offsetSizeInBytes); } if (version != VERSION_15) { // write trailer // 6 null bytes Write(new byte[6]); // size of an offset Write(offsetSizeInBytes); // size of a ref Write(idSizeInBytes); // number of objects WriteLong(idMap.Count); // top object int rootID = idMap.IndexOf(root); WriteLong(rootID); // offset table offset WriteLong(offsetTableOffset); } outStream.Flush(); } internal void AssignID(NSObject obj) { if (obj is UID || obj is NSArray) { idMap.Add(obj); } else if (!idMap.Contains(obj)) { idMap.Add(obj); } } internal int GetID(NSObject obj) { if (obj is UID) { var uid = obj as UID; var first = idMap.OfType<UID>().First(v => NSObject.ArrayEquals(v.Bytes, uid.Bytes)); return idMap.IndexOf(first); } else if (obj is NSArray) { int index = 0; for (int i = 0; i < idMap.Count; i++) { if (idMap[i] == obj) { index = i; break; } } return index; } else { return idMap.IndexOf(obj); } } static int ComputeIdSizeInBytes(int numberOfIds) { if (numberOfIds < 256) return 1; return numberOfIds < 65536 ? 2 : 4; } static int ComputeOffsetSizeInBytes(long maxOffset) { if (maxOffset < 256) return 1; if (maxOffset < 65536) return 2; return maxOffset < 4294967296L ? 4 : 8; } internal void WriteIntHeader(int kind, int value) { if (value < 0) throw new ArgumentException("value must be greater than or equal to 0", "value"); if (value < 15) { Write((kind << 4) + value); } else if (value < 256) { Write((kind << 4) + 15); Write(0x10); WriteBytes(value, 1); } else if (value < 65536) { Write((kind << 4) + 15); Write(0x11); WriteBytes(value, 2); } else { Write((kind << 4) + 15); Write(0x12); WriteBytes(value, 4); } } internal void Write(int b) { byte[] bBytes = new byte[1]; bBytes[0] = (byte)b; outStream.Write(bBytes, 0, 1); count++; } internal void Write(byte[] bytes) { outStream.Write(bytes, 0, bytes.Length); count += bytes.Length; } internal void WriteBytes(long value, int bytes) { // write low-order bytes big-endian style for (int i = bytes - 1; i >= 0; i--) { Write((int)(value >> (8 * i))); } } internal void WriteID(int id) { WriteBytes(id, idSizeInBytes); } internal void WriteLong(long value) { WriteBytes(value, 8); } internal void WriteDouble(double value) { WriteLong(BitConverter.DoubleToInt64Bits(value)); } } }
2881099/dotnetGen_postgresql
25,173
GenPg/plist-cil/ASCIIPropertyListParser.cs
// plist-cil - An open source library to parse and generate property lists for .NET // Copyright (C) 2015 Natalia Portillo // // This code is based on: // plist - An open source library to parse and generate property lists // Copyright (C) 2014 Daniel Dreibrodt // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. using System; using System.IO; using System.Collections.Generic; using System.Text.RegularExpressions; using System.Text; using System.Runtime.CompilerServices; namespace PList { /// <summary> /// <para> /// Parser for ASCII property lists. Supports Apple OS X/iOS and GnuStep/NeXTSTEP format. /// This parser is based on the recursive descent paradigm, but the underlying grammar /// is not explicitely defined. /// </para> /// <para> /// Resources on ASCII property list format: /// </para> /// <para> /// https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/PropertyLists/OldStylePlists/OldStylePLists.html /// </para> /// <para> /// Property List Programming Guide - Old-Style ASCII Property Lists /// </para> /// <para> /// http://www.gnustep.org/resources/documentation/Developer/Base/Reference/NSPropertyList.html /// </para> /// <para> /// GnuStep - NSPropertyListSerialization class documentation /// </para> /// </summary> /// @author Daniel Dreibrodt /// @author Natalia Portillo public class ASCIIPropertyListParser { /// <summary> /// Parses an ASCII property list file. /// </summary> /// <param name="f">The ASCII property list file..</param> /// <returns>The root object of the property list. This is usually a NSDictionary but can also be a NSArray.</returns> /// <exception cref="FormatException">When an error occurs during parsing.</exception> /// <exception cref="IOException">When an error occured while reading from the input stream.</exception> public static NSObject Parse(FileInfo f) { return Parse(f.OpenRead()); } /// <summary> /// Parses an ASCII property list from an input stream. /// </summary> /// <param name="fs">The input stream that points to the property list's data.</param> /// <returns>The root object of the property list. This is usually a NSDictionary but can also be a NSArray.</returns> /// <exception cref="FormatException">When an error occurs during parsing.</exception> /// <exception cref="IOException"></exception> public static NSObject Parse(Stream fs) { byte[] buf = PropertyListParser.ReadAll(fs); // Don't close the stream - that would be the responisibility of code that class // Parse return Parse(buf); } /// <summary> /// Parses an ASCII property list from a byte array. /// </summary> /// <param name="bytes">The ASCII property list data.</param> /// <returns>The root object of the property list. This is usually a NSDictionary but can also be a NSArray.</returns> /// <exception cref="FormatException">When an error occurs during parsing.</exception> public static NSObject Parse(byte[] bytes) { ASCIIPropertyListParser parser = new ASCIIPropertyListParser(bytes); return parser.Parse(); } /// <summary> /// A space /// </summary> public const char WHITESPACE_SPACE = ' '; /// <summary> /// A tabulator /// </summary> public const char WHITESPACE_TAB = '\t'; /// <summary> /// A newline /// </summary> public const char WHITESPACE_NEWLINE = '\n'; /// <summary> /// A carriage return /// </summary> public const char WHITESPACE_CARRIAGE_RETURN = '\r'; /// <summary> /// Token of NSArray start /// </summary> public const char ARRAY_BEGIN_TOKEN = '('; /// <summary> /// Token of NSArray end /// </summary> public const char ARRAY_END_TOKEN = ')'; /// <summary> /// Token of NSArray item delimiter /// </summary> public const char ARRAY_ITEM_DELIMITER_TOKEN = ','; /// <summary> /// Token of NSDictionary start /// </summary> public const char DICTIONARY_BEGIN_TOKEN = '{'; /// <summary> /// Token of NSDictionary end /// </summary> public const char DICTIONARY_END_TOKEN = '}'; /// <summary> /// Token of NSDictionary assignment /// </summary> public const char DICTIONARY_ASSIGN_TOKEN = '='; /// <summary> /// Token of NSDictionary item delimiter /// </summary> public const char DICTIONARY_ITEM_DELIMITER_TOKEN = ';'; /// <summary> /// Token of quoted NSString start /// </summary> public const char QUOTEDSTRING_BEGIN_TOKEN = '"'; /// <summary> /// Token of quoted NSString end /// </summary> public const char QUOTEDSTRING_END_TOKEN = '"'; /// <summary> /// Token of quoted NSString escaped character /// </summary> public const char QUOTEDSTRING_ESCAPE_TOKEN = '\\'; /// <summary> /// Token of NSData start /// </summary> public const char DATA_BEGIN_TOKEN = '<'; /// <summary> /// Token of NSData end /// </summary> public const char DATA_END_TOKEN = '>'; /// <summary> /// Token of GSObject start /// </summary> public const char DATA_GSOBJECT_BEGIN_TOKEN = '*'; /// <summary> /// Token of GSDate start /// </summary> public const char DATA_GSDATE_BEGIN_TOKEN = 'D'; /// <summary> /// Token of GSBoolean start /// </summary> public const char DATA_GSBOOL_BEGIN_TOKEN = 'B'; /// <summary> /// Token for GSBoolen's <c>true</c> /// </summary> public const char DATA_GSBOOL_TRUE_TOKEN = 'Y'; /// <summary> /// Token for GSBoolen's <c>false</c> /// </summary> public const char DATA_GSBOOL_FALSE_TOKEN = 'N'; /// <summary> /// Token for GSInteger /// </summary> public const char DATA_GSINT_BEGIN_TOKEN = 'I'; /// <summary> /// Token for GSReal /// </summary> public const char DATA_GSREAL_BEGIN_TOKEN = 'R'; /// <summary> /// Token for NSDate date field delimited /// </summary> public const char DATE_DATE_FIELD_DELIMITER = '-'; /// <summary> /// Token for NSDate time field delimiter /// </summary> public const char DATE_TIME_FIELD_DELIMITER = ':'; /// <summary> /// Token for GSDate date and time delimiter /// </summary> public const char DATE_GS_DATE_TIME_DELIMITER = ' '; /// <summary> /// Token for NSDate date and time delimiter /// </summary> public const char DATE_APPLE_DATE_TIME_DELIMITER = 'T'; /// <summary> /// Token for NSDate end /// </summary> public const char DATE_APPLE_END_TOKEN = 'Z'; /// <summary> /// Token for comment start /// </summary> public const char COMMENT_BEGIN_TOKEN = '/'; /// <summary> /// Second token for multiline comment /// </summary> public const char MULTILINE_COMMENT_SECOND_TOKEN = '*'; /// <summary> /// Second token for singleline comment /// </summary> public const char SINGLELINE_COMMENT_SECOND_TOKEN = '/'; /// <summary> /// End token for multiline comment /// </summary> public const char MULTILINE_COMMENT_END_TOKEN = '/'; /** * Property list source data */ byte[] data; /** * Current parsing index */ int index; /** * Only allow subclasses to change instantiation. */ protected ASCIIPropertyListParser() { } /// <summary> /// Creates a new parser for the given property list content. /// </summary> /// <param name="propertyListContent">The content of the property list that is to be parsed.</param> ASCIIPropertyListParser(byte[] propertyListContent) { data = propertyListContent; } /// <summary> /// Checks whether the given sequence of symbols can be accepted. /// </summary> /// <returns>Whether the given tokens occur at the current parsing position.</returns> /// <param name="sequence">The sequence of tokens to look for.</param> bool AcceptSequence(params char[] sequence) { for (int i = 0; i < sequence.Length; i++) { if (data[index + i] != sequence[i]) return false; } return true; } /// <summary> /// Checks whether the given symbols can be accepted, that is, if one /// of the given symbols is found at the current parsing position. /// </summary> /// <param name="acceptableSymbols">The symbols to check.</param> /// <returns>Whether one of the symbols can be accepted or not.</returns> bool Accept(params char[] acceptableSymbols) { bool symbolPresent = false; foreach (char c in acceptableSymbols) symbolPresent |= data[index] == c; return symbolPresent; } /// <summary> /// Checks whether the given symbol can be accepted, that is, if /// the given symbols is found at the current parsing position. /// </summary> /// <param name="acceptableSymbol">The symbol to check.</param> /// <returns>Whether the symbol can be accepted or not.</returns> bool Accept(char acceptableSymbol) { return data[index] == acceptableSymbol; } /// <summary> /// Expects the input to have one of the given symbols at the current parsing position. /// </summary> /// <param name="expectedSymbols">The expected symbols.</param> /// <exception cref="FormatException">If none of the expected symbols could be found.</exception> void Expect(params char[] expectedSymbols) { if (!Accept(expectedSymbols)) { String excString = "Expected '" + expectedSymbols[0] + "'"; for (int i = 1; i < expectedSymbols.Length; i++) excString += " or '" + expectedSymbols[i] + "'"; excString += " but found '" + (char)data[index] + "'"; throw new FormatException(String.Format("{0} at {1}", excString, index)); } } /// <summary> /// Expects the input to have the given symbol at the current parsing position. /// </summary> /// <param name="expectedSymbol">The expected symbol.</param> /// <exception cref="FormatException">If the expected symbol could be found.</exception> void Expect(char expectedSymbol) { if (!Accept(expectedSymbol)) throw new FormatException(String.Format("Expected '{0}' but found '{1}' at {2}", expectedSymbol, data[index], index)); } /// <summary> /// Reads an expected symbol. /// </summary> /// <param name="symbol">The symbol to read.</param> /// <exception cref="FormatException">If the expected symbol could not be read.</exception> void Read(char symbol) { Expect(symbol); index++; } /** * Skips the current symbol. */ void Skip() { index++; } /// <summary> /// Skips several symbols /// </summary> /// <param name="numSymbols">The amount of symbols to skip.</param> void Skip(int numSymbols) { index += numSymbols; } /** * Skips all whitespaces and comments from the current parsing position onward. */ void SkipWhitespacesAndComments() { bool commentSkipped; do { commentSkipped = false; //Skip whitespaces while (Accept(WHITESPACE_CARRIAGE_RETURN, WHITESPACE_NEWLINE, WHITESPACE_SPACE, WHITESPACE_TAB)) { Skip(); } //Skip single line comments "//..." if (AcceptSequence(COMMENT_BEGIN_TOKEN, SINGLELINE_COMMENT_SECOND_TOKEN)) { Skip(2); ReadInputUntil(WHITESPACE_CARRIAGE_RETURN, WHITESPACE_NEWLINE); commentSkipped = true; } //Skip multi line comments "/* ... */" else if (AcceptSequence(COMMENT_BEGIN_TOKEN, MULTILINE_COMMENT_SECOND_TOKEN)) { Skip(2); while (true) { if (AcceptSequence(MULTILINE_COMMENT_SECOND_TOKEN, MULTILINE_COMMENT_END_TOKEN)) { Skip(2); break; } Skip(); } commentSkipped = true; } } while (commentSkipped); //if a comment was skipped more whitespace or another comment can follow, so skip again } /// <summary> /// Reads input until one of the given symbols is found. /// </summary> /// <returns>The input until one the given symbols.</returns> /// <param name="symbols">The symbols that can occur after the string to read.</param> string ReadInputUntil(params char[] symbols) { string s = ""; while (!Accept(symbols)) { s += (char)data[index]; Skip(); } return s; } /// <summary> /// Reads input until the given symbol is found. /// </summary> /// <returns>The input until the given symbol.</returns> /// <param name="symbol">The symbol that can occur after the string to read.</param> string ReadInputUntil(char symbol) { String s = ""; while (!Accept(symbol)) { s += (char)data[index]; Skip(); } return s; } /// <summary> /// Parses the property list from the beginning and returns the root object /// of the property list. /// </summary> /// <returns>The root object of the property list. This can either be a NSDictionary or a NSArray.</returns> /// <exception cref="FormatException">When an error occured during parsing</exception> public NSObject Parse() { index = 0; //Skip Unicode byte order mark (BOM) if (data.Length >= 3 && (data[0] & 0xFF) == 0xEF && (data[1] & 0xFF) == 0xBB && (data[2] & 0xFF) == 0xBF) Skip(3); SkipWhitespacesAndComments(); Expect(DICTIONARY_BEGIN_TOKEN, ARRAY_BEGIN_TOKEN, COMMENT_BEGIN_TOKEN); try { return ParseObject(); } catch (IndexOutOfRangeException) { throw new FormatException(String.Format("Reached end of input unexpectedly at {0}.", index)); } } /// <summary> /// Parses the NSObject found at the current position in the property list /// data stream. /// </summary> /// <returns>The parsed NSObject.</returns> /// <seealso cref="ASCIIPropertyListParser.index"/> NSObject ParseObject() { switch (data[index]) { case (byte)ARRAY_BEGIN_TOKEN: { return ParseArray(); } case (byte)DICTIONARY_BEGIN_TOKEN: { return ParseDictionary(); } case (byte)DATA_BEGIN_TOKEN: { return ParseData(); } case (byte)QUOTEDSTRING_BEGIN_TOKEN: { string quotedString = ParseQuotedString(); //apple dates are quoted strings of length 20 and after the 4 year digits a dash is found if (quotedString.Length == 20 && quotedString[4] == DATE_DATE_FIELD_DELIMITER) { try { return new NSDate(quotedString); } catch (Exception) { //not a date? --> return string return new NSString(quotedString); } } return new NSString(quotedString); } default: { //0-9 if (data[index] > 0x2F && data[index] < 0x3A) { //could be a date or just a string return ParseDateString(); } else { //non-numerical -> string or boolean string parsedString = ParseString(); return new NSString(parsedString); } } } } /// <summary> /// Parses an array from the current parsing position. /// The prerequisite for calling this method is, that an array begin token has been read. /// </summary> /// <returns>The array found at the parsing position.</returns> NSArray ParseArray() { //Skip begin token Skip(); SkipWhitespacesAndComments(); List<NSObject> objects = new List<NSObject>(); while (!Accept(ARRAY_END_TOKEN)) { objects.Add(ParseObject()); SkipWhitespacesAndComments(); if (Accept(ARRAY_ITEM_DELIMITER_TOKEN)) { Skip(); } else { break; //must have reached end of array } SkipWhitespacesAndComments(); } //parse end token Read(ARRAY_END_TOKEN); return new NSArray(objects.ToArray()); } /// <summary> /// Parses a dictionary from the current parsing position. /// The prerequisite for calling this method is, that a dictionary begin token has been read. /// </summary> /// <returns>The dictionary found at the parsing position.</returns> NSDictionary ParseDictionary() { //Skip begin token Skip(); SkipWhitespacesAndComments(); NSDictionary dict = new NSDictionary(); while (!Accept(DICTIONARY_END_TOKEN)) { //Parse key string keyString; if (Accept(QUOTEDSTRING_BEGIN_TOKEN)) keyString = ParseQuotedString(); else keyString = ParseString(); SkipWhitespacesAndComments(); //Parse assign token Read(DICTIONARY_ASSIGN_TOKEN); SkipWhitespacesAndComments(); NSObject nso = ParseObject(); dict.Add(keyString, nso); SkipWhitespacesAndComments(); Read(DICTIONARY_ITEM_DELIMITER_TOKEN); SkipWhitespacesAndComments(); } //skip end token Skip(); return dict; } /// <summary> /// Parses a data object from the current parsing position. /// This can either be a NSData object or a GnuStep NSNumber or NSDate. /// The prerequisite for calling this method is, that a data begin token has been read. /// </summary> /// <returns>The data object found at the parsing position.</returns> NSObject ParseData() { NSObject obj = null; //Skip begin token Skip(); if (Accept(DATA_GSOBJECT_BEGIN_TOKEN)) { Skip(); Expect(DATA_GSBOOL_BEGIN_TOKEN, DATA_GSDATE_BEGIN_TOKEN, DATA_GSINT_BEGIN_TOKEN, DATA_GSREAL_BEGIN_TOKEN); if (Accept(DATA_GSBOOL_BEGIN_TOKEN)) { //Boolean Skip(); Expect(DATA_GSBOOL_TRUE_TOKEN, DATA_GSBOOL_FALSE_TOKEN); if (Accept(DATA_GSBOOL_TRUE_TOKEN)) obj = new NSNumber(true); else obj = new NSNumber(false); //Skip the parsed boolean token Skip(); } else if (Accept(DATA_GSDATE_BEGIN_TOKEN)) { //Date Skip(); string dateString = ReadInputUntil(DATA_END_TOKEN); obj = new NSDate(dateString); } else if (Accept(DATA_GSINT_BEGIN_TOKEN, DATA_GSREAL_BEGIN_TOKEN)) { //Number Skip(); string numberString = ReadInputUntil(DATA_END_TOKEN); obj = new NSNumber(numberString); } //parse data end token Read(DATA_END_TOKEN); } else { string dataString = ReadInputUntil(DATA_END_TOKEN); dataString = Regex.Replace(dataString, "\\s+", ""); int numBytes = dataString.Length / 2; byte[] bytes = new byte[numBytes]; for (int i = 0; i < bytes.Length; i++) { string byteString = dataString.Substring(i * 2, 2); int byteValue = Convert.ToInt32(byteString, 16); bytes[i] = (byte)byteValue; } obj = new NSData(bytes); //skip end token Skip(); } return obj; } /// <summary> /// Attempts to parse a plain string as a date if possible. /// </summary> /// <returns>A NSDate if the string represents such an object. Otherwise a NSString is returned.</returns> NSObject ParseDateString() { string numericalString = ParseString(); if (numericalString.Length > 4 && numericalString[4] == DATE_DATE_FIELD_DELIMITER) { try { return new NSDate(numericalString); } catch (Exception) { //An exception occurs if the string is not a date but just a string } } return new NSString(numericalString); } /// <summary> /// Parses a plain string from the current parsing position. /// The string is made up of all characters to the next whitespace, delimiter token or assignment token. /// </summary> /// <returns>The string found at the current parsing position.</returns> string ParseString() { return ReadInputUntil(WHITESPACE_SPACE, WHITESPACE_TAB, WHITESPACE_NEWLINE, WHITESPACE_CARRIAGE_RETURN, ARRAY_ITEM_DELIMITER_TOKEN, DICTIONARY_ITEM_DELIMITER_TOKEN, DICTIONARY_ASSIGN_TOKEN, ARRAY_END_TOKEN); } /// <summary> /// Parses a quoted string from the current parsing position. /// The prerequisite for calling this method is, that a quoted string begin token has been read. /// </summary> /// <returns>The quoted string found at the parsing method with all special characters unescaped.</returns> /// <exception cref="FormatException">If an error occured during parsing.</exception> string ParseQuotedString() { //Skip begin token Skip(); string quotedString = ""; bool unescapedBackslash = true; //Read from opening quotation marks to closing quotation marks and skip escaped quotation marks while (data[index] != QUOTEDSTRING_END_TOKEN || (data[index - 1] == QUOTEDSTRING_ESCAPE_TOKEN && unescapedBackslash)) { quotedString += (char)data[index]; if (Accept(QUOTEDSTRING_ESCAPE_TOKEN)) { unescapedBackslash = !(data[index - 1] == QUOTEDSTRING_ESCAPE_TOKEN && unescapedBackslash); } Skip(); } string unescapedString; try { unescapedString = ParseQuotedString(quotedString); } catch (Exception) { throw new FormatException(String.Format("The quoted string could not be parsed at {0}.", index)); } //skip end token Skip(); return unescapedString; } /// <summary> /// Parses a string according to the format specified for ASCII property lists. /// Such strings can contain escape sequences which are unescaped in this method. /// </summary> /// <returns>The unescaped string in UTF-8 or ASCII format, depending on the contained characters.</returns> /// <param name="s">The escaped string according to the ASCII property list format, without leading and trailing quotation marks.</param> /// <exception cref="ArgumentException">If the en-/decoder for the UTF-8 or ASCII encoding could not be loaded</exception> /// <exception cref="EncoderFallbackException">If the string is encoded neither in ASCII nor in UTF-8</exception> public static string ParseQuotedString(string s) { List<byte> strBytes = new List<byte>(); var characters = (IEnumerable<char>)s.ToCharArray(); var c = characters.GetEnumerator(); while (c.MoveNext()) { switch (c.Current) { case '\\': { //An escaped sequence is following byte[] bts = Encoding.UTF8.GetBytes(ParseEscapedSequence(c)); foreach (byte b in bts) strBytes.Add(b); break; } default: { //a normal ASCII char strBytes.Add((byte)0); strBytes.Add((byte)c.Current); break; } } } byte[] bytArr = new byte[strBytes.Count]; int i = 0; foreach (byte b in strBytes) { bytArr[i] = b; i++; } //Build string string result = Encoding.BigEndianUnicode.GetString(bytArr); //If the string can be represented in the ASCII codepage // --> use ASCII encoding if (IsASCIIEncodable(result)) return Encoding.ASCII.GetString(Encoding.Convert(Encoding.BigEndianUnicode, Encoding.ASCII, bytArr)); //The string contains characters outside the ASCII codepage // --> use the UTF-8 encoded string return result; } /// <summary> /// Unescapes an escaped character sequence, e.g. \\u00FC. /// </summary> /// <returns>The unescaped character as a string.</returns> /// <param name="iterator">The string character iterator pointing to the first character after the backslash</param> /// <exception cref="EncoderFallbackException">If an invalid Unicode or ASCII escape sequence is found.</exception> private static string ParseEscapedSequence(IEnumerator<char> iterator) { iterator.MoveNext(); char c = iterator.Current; if (c == '\\') { return Encoding.UTF8.GetString(new byte[] { 0, (byte)'\\' }); } else if (c == '"') { return Encoding.UTF8.GetString(new byte[] { 0, (byte)'\"' }); } else if (c == 'b') { return Encoding.UTF8.GetString(new byte[] { 0, (byte)'\b' }); } else if (c == 'n') { return Encoding.UTF8.GetString(new byte[] { 0, (byte)'\n' }); } else if (c == 'r') { return Encoding.UTF8.GetString(new byte[] { 0, (byte)'\r' }); } else if (c == 't') { return Encoding.UTF8.GetString(new byte[] { 0, (byte)'\t' }); } else if (c == 'U' || c == 'u') { //4 digit hex Unicode value string byte1 = ""; iterator.MoveNext(); byte1 += iterator.Current; iterator.MoveNext(); byte1 += iterator.Current; string byte2 = ""; iterator.MoveNext(); byte2 += iterator.Current; iterator.MoveNext(); byte2 += iterator.Current; byte[] stringBytes = { (byte)Convert.ToInt32(byte1, 16), (byte)Convert.ToInt32(byte2, 16) }; return Encoding.UTF8.GetString(stringBytes); } else { //3 digit octal ASCII value string num = ""; num += c; iterator.MoveNext(); num += iterator.Current; iterator.MoveNext(); num += iterator.Current; int asciiCode = Convert.ToInt32(num, 8); byte[] stringBytes = { 0, (byte)asciiCode }; return Encoding.UTF8.GetString(stringBytes); } } internal static bool IsASCIIEncodable(string text) { foreach (char c in text) if ((int)c > 0x7F) return false; return true; } } }
2881099/dotnetGen_postgresql
16,113
GenPg/plist-cil/NSObject.cs
// plist-cil - An open source library to parse and generate property lists for .NET // Copyright (C) 2015 Natalia Portillo // // This code is based on: // plist - An open source library to parse and generate property lists // Copyright (C) 2014 Daniel Dreibrodt // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. using System; using System.Text; using System.Collections.Generic; using System.IO; using System.Reflection; namespace PList { /// <summary> /// <para> /// Abstract interface for any object contained in a property list. /// </para><para> /// The names and functions of the various objects orient themselves /// towards Apple's Cocoa API. /// </para> /// </summary> /// @author Daniel Dreibrodt /// @author Natalia Portillo public abstract class NSObject { /// <summary> /// The newline character used for generating the XML output. /// To maintain compatibility with the Apple format, only a newline character /// is used (as opposed to cr+lf which is normally used on Windows). /// </summary> readonly internal static string NEWLINE = "\n"; /// <summary> /// The identation character used for generating the XML output. This is the /// tabulator character. /// </summary> readonly static string INDENT = "\t"; /// <summary> /// The maximum length of the text lines to be used when generating /// ASCII property lists. But this number is only a guideline it is not /// guaranteed that it will not be overstepped. /// </summary> internal readonly static int ASCII_LINE_LENGTH = 80; /// <summary> /// Generates the XML representation of the object (without XML headers or enclosing plist-tags). /// </summary> /// <param name="xml">The StringBuilder onto which the XML representation is appended.</param> /// <param name="level">The indentation level of the object.</param> internal abstract void ToXml(StringBuilder xml, int level); /// <summary> /// Assigns IDs to all the objects in this NSObject subtree. /// </summary> /// <param name="outPlist">The writer object that handles the binary serialization.</param> internal virtual void AssignIDs(BinaryPropertyListWriter outPlist) { outPlist.AssignID(this); } /// <summary> /// Generates the binary representation of the object. /// </summary> /// <param name="outPlist">The output stream to serialize the object to.</param> internal abstract void ToBinary(BinaryPropertyListWriter outPlist); /// <summary> /// Generates a valid XML property list including headers using this object as root. /// </summary> /// <returns>The XML representation of the property list including XML header and doctype information.</returns> public string ToXmlPropertyList() { StringBuilder xml = new StringBuilder("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); xml.Append(NSObject.NEWLINE); xml.Append("<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">"); xml.Append(NSObject.NEWLINE); xml.Append("<plist version=\"1.0\">"); xml.Append(NSObject.NEWLINE); ToXml(xml, 0); xml.Append(NSObject.NEWLINE); xml.Append("</plist>"); xml.Append(NSObject.NEWLINE); return xml.ToString(); } /// <summary> /// Generates the ASCII representation of this object. /// The generated ASCII representation does not end with a newline. /// Complies with https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/PropertyLists/OldStylePlists/OldStylePLists.html /// </summary> /// <param name="ascii">The StringBuilder onto which the ASCII representation is appended.</param> /// <param name="level">The indentation level of the object.</param> internal abstract void ToASCII(StringBuilder ascii, int level); /// <summary> /// Generates the ASCII representation of this object in the GnuStep format. /// The generated ASCII representation does not end with a newline. /// </summary> /// <param name="ascii">The StringBuilder onto which the ASCII representation is appended.</param> /// <param name="level">The indentation level of the object.</param> internal abstract void ToASCIIGnuStep(StringBuilder ascii, int level); /// <summary> /// Helper method that adds correct identation to the xml output. /// Calling this method will add <c>level</c> number of tab characters /// to the <c>xml</c> string. /// </summary> /// <param name="xml">The string builder for the XML document.</param> /// <param name="level">The level of identation.</param> internal static void Indent(StringBuilder xml, int level) { for (int i = 0; i < level; i++) xml.Append(INDENT); } /// <summary> /// Wraps the given value inside a NSObject. /// </summary> /// <param name="value">The value to represent as a NSObject.</param> /// <returns>A NSObject representing the given value.</returns> public static NSNumber Wrap(long value) { return new NSNumber(value); } /// <summary> /// Wraps the given value inside a NSObject. /// </summary> /// <param name="value">The value to represent as a NSObject.</param> /// <returns>A NSObject representing the given value.</returns> public static NSNumber Wrap(double value) { return new NSNumber(value); } /// <summary> /// Wraps the given value inside a NSObject. /// </summary> /// <param name="value">The value to represent as a NSObject.</param> /// <returns>A NSObject representing the given value.</returns> public static NSNumber Wrap(bool value) { return new NSNumber(value); } /// <summary> /// Wraps the given value inside a NSObject. /// </summary> /// <param name="value">The value to represent as a NSObject.</param> /// <returns>A NSObject representing the given value.</returns> public static NSData Wrap(byte[] value) { return new NSData(value); } /// <summary> /// Creates a NSArray with the contents of the given array. /// </summary> /// <param name="value">The value to represent as a NSObject.</param> /// <returns>A NSObject representing the given value.</returns> /// <exception cref="SystemException">When one of the objects contained in the array cannot be represented by a NSObject.</exception> public static NSArray Wrap(Object[] value) { NSArray arr = new NSArray(value.Length); for (int i = 0; i < value.Length; i++) { arr.Add(Wrap(value[i])); } return arr; } /// <summary> /// Creates a NSDictionary with the contents of the given map. /// </summary> /// <param name="value">The value to represent as a NSObject.</param> /// <returns>A NSObject representing the given value.</returns> /// <exception cref="SystemException">When one of the values contained in the map cannot be represented by a NSObject.</exception> public static NSDictionary Wrap(Dictionary<string, Object> value) { NSDictionary dict = new NSDictionary(); foreach (KeyValuePair<string, Object> kvp in value) dict.Add(kvp.Key, Wrap(kvp.Value)); return dict; } /// <summary> /// Creates a NSSet with the contents of this set. /// </summary> /// <param name="value">The value to represent as a NSObject.</param> /// <returns>A NSObject representing the given value.</returns> /// <exception cref="SystemException">When one of the values contained in the map cannot be represented by a NSObject.</exception> public static NSSet Wrap(List<Object> value) { NSSet set = new NSSet(); foreach (Object o in value) set.AddObject(Wrap(o)); return set; } /// <summary> /// <para> /// Creates a NSObject representing the given .NET Object. /// </para><para> /// Numerics of type <see cref="bool"/>, <see cref="int"/>, <see cref="long"/>, <see cref="short"/>, <see cref="byte"/>, <see cref="float"/> or <see cref="double"/> are wrapped as NSNumber objects. /// </para><para> /// Strings are wrapped as <see cref="NSString"/> objects and byte arrays as <see cref="NSData"/> objects. /// </para><para> /// DateTime objects are wrapped as <see cref="NSDate"/> objects. /// </para><para> /// Serializable classes are serialized and their data is stored in <see cref="NSData"/> objects. /// </para><para> /// Arrays and Collection objects are converted to <see cref="NSArray"/> where each array member is wrapped into a <see cref="NSObject"/>. /// </para><para> /// Dictionaries are converted to <see cref="NSDictionary"/>. Each key is converted to a string and each value wrapped into a <see cref="NSObject"/>. /// </para> /// </summary> /// <param name="o">The object to represent.</param> ///<returns>A NSObject equivalent to the given object.</returns> public static NSObject Wrap(Object o) { if (o == null) throw new NullReferenceException("A null object cannot be wrapped as a NSObject"); if (o is NSObject) return (NSObject)o; Type c = o.GetType(); if (typeof(bool).Equals(c)) { return Wrap((bool)o); } if (typeof(Byte).Equals(c)) { return Wrap((int)(Byte)o); } if (typeof(short).Equals(c)) { return Wrap((int)(short)o); } if (typeof(int).Equals(c)) { return Wrap((int)(int)o); } if (typeof(long).IsAssignableFrom(c)) { return Wrap((long)o); } if (typeof(float).Equals(c)) { return Wrap((double)(float)o); } if (typeof(double).IsAssignableFrom(c)) { return Wrap((double)o); } if (typeof(string).Equals(c)) { return new NSString((string)o); } if (typeof(DateTime).Equals(c)) { return new NSDate((DateTime)o); } if (c.IsArray) { Type cc = c.GetElementType(); if (cc.Equals(typeof(byte))) { return Wrap((byte[])o); } if (cc.Equals(typeof(bool))) { bool[] array = (bool[])o; NSArray nsa = new NSArray(array.Length); for (int i = 0; i < array.Length; i++) nsa.Add(Wrap(array[i])); return nsa; } if (cc.Equals(typeof(float))) { float[] array = (float[])o; NSArray nsa = new NSArray(array.Length); for (int i = 0; i < array.Length; i++) nsa.Add(Wrap(array[i])); return nsa; } if (cc.Equals(typeof(double))) { double[] array = (double[])o; NSArray nsa = new NSArray(array.Length); for (int i = 0; i < array.Length; i++) nsa.Add(Wrap(array[i])); return nsa; } if (cc.Equals(typeof(short))) { short[] array = (short[])o; NSArray nsa = new NSArray(array.Length); for (int i = 0; i < array.Length; i++) nsa.Add(Wrap(array[i])); return nsa; } if (cc.Equals(typeof(int))) { int[] array = (int[])o; NSArray nsa = new NSArray(array.Length); for (int i = 0; i < array.Length; i++) nsa.Add(Wrap(array[i])); return nsa; } if (cc.Equals(typeof(long))) { long[] array = (long[])o; NSArray nsa = new NSArray(array.Length); for (int i = 0; i < array.Length; i++) nsa.Add(Wrap(array[i])); return nsa; } return Wrap((Object[])o); } if (typeof(Dictionary<string, Object>).IsAssignableFrom(c)) { Dictionary<string, Object> netDict = (Dictionary<string, Object>)o; NSDictionary dict = new NSDictionary(); foreach (KeyValuePair<string, Object> kvp in netDict) { dict.Add(kvp.Key, Wrap(kvp.Value)); } return dict; } if (typeof(List<Object>).IsAssignableFrom(c)) return Wrap(((List<Object>)o).ToArray()); throw new PropertyListException(string.Format("Cannot wrap an object of type {0}.", o.GetType().Name)); } /// <summary> /// Converts this NSObject into an equivalent object /// of the .NET Runtime Environment. /// <para><see cref="NSArray"/> objects are converted to arrays.</para> /// <para><see cref="NSDictionary"/> objects are converted to objects extending the <see cref="Dictionary{TKey, TValue}"/> class.</para> /// <para><see cref="NSSet"/> objects are converted to objects extending the <see cref="List{NSObject}"/> class.</para> /// <para><see cref="NSNumber"/> objects are converted to primitive number values (<see cref="int"/>, <see cref="long"/>, <see cref="double"/> or <see cref="bool"/>).</para> /// <para><see cref="NSString"/> objects are converted to <see cref="string"/> objects.</para> /// <para><see cref="NSData"/> objects are converted to <see cref="byte"/> arrays.</para> /// <para><see cref="NSDate"/> objects are converted to <see cref="System.DateTime"/> objects.</para> /// <para><see cref="UID"/> objects are converted to <see cref="byte"/> arrays.</para> /// </summary> /// <returns>A native .NET object representing this NSObject's value.</returns> public Object ToObject() { if (this is NSArray) { NSObject[] arrayA = ((NSArray)this).GetArray(); Object[] arrayB = new Object[arrayA.Length]; for (int i = 0; i < arrayA.Length; i++) { arrayB[i] = arrayA[i].ToObject(); } return arrayB; } if (this is NSDictionary) { Dictionary<string, NSObject> dictA = ((NSDictionary)this).GetDictionary(); Dictionary<string, Object> dictB = new Dictionary<string, Object>(dictA.Count); foreach (KeyValuePair<string, NSObject> kvp in dictA) { dictB.Add(kvp.Key, kvp.Value.ToObject()); } return dictB; } if (this is NSSet) { List<NSObject> setA = ((NSSet)this).GetSet(); List<Object> setB = new List<Object>(); foreach (NSObject o in setA) { setB.Add(o.ToObject()); } return setB; } if (this is NSNumber) { NSNumber num = (NSNumber)this; switch (num.GetNSNumberType()) { case NSNumber.INTEGER: { long longVal = num.ToLong(); if (longVal > int.MaxValue || longVal < int.MinValue) return longVal; return num.ToInt(); } case NSNumber.REAL: return num.ToDouble(); case NSNumber.BOOLEAN: return num.ToBool(); default: return num.ToDouble(); } } if (this is NSString) { return ((NSString)this).GetContent(); } if (this is NSData) { return ((NSData)this).Bytes; } if (this is NSDate) { return ((NSDate)this).Date; } if (this is UID) { return ((UID)this).Bytes; } return this; } internal static bool ArrayEquals(byte[] arrayA, byte[] arrayB) { if (arrayA.Length == arrayB.Length) { for (int i = 0; i < arrayA.Length; i++) if (arrayA[i] != arrayB[i]) return false; return true; } return false; } internal static bool ArrayEquals(NSObject[] arrayA, NSObject[] arrayB) { if (arrayA.Length == arrayB.Length) { for (int i = 0; i < arrayA.Length; i++) { if (arrayA[i] != arrayB[i]) { return false; } } return true; } return false; } /// <summary> /// Determines if the specific NSObject is the same as the NSObject overriding this method. /// </summary> /// <param name="obj">The <see cref="PList.NSObject"/> to compare with the current <see cref="PList.NSObject"/>.</param> /// <returns><c>true</c> if the specified <see cref="PList.NSObject"/> is equal to the current /// <see cref="PList.NSObject"/>; otherwise, <c>false</c>.</returns> public abstract bool Equals(NSObject obj); } }
27182812/ChatGLM-LLaMA-chinese-insturct
16,724
src/transformers/models/efficientnet/image_processing_efficientnet.py
# coding=utf-8 # Copyright 2023 The HuggingFace Inc. team. 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. """Image processor class for EfficientNet.""" from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import center_crop, normalize, rescale, resize, to_channel_dimension_format from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL logger = logging.get_logger(__name__) class EfficientNetImageProcessor(BaseImageProcessor): r""" Constructs a EfficientNet image processor. Args: do_resize (`bool`, *optional*, defaults to `True`): Whether to resize the image's (height, width) dimensions to the specified `size`. Can be overridden by `do_resize` in `preprocess`. size (`Dict[str, int]` *optional*, defaults to `{"height": 346, "width": 346}`): Size of the image after `resize`. Can be overridden by `size` in `preprocess`. resample (`PILImageResampling` filter, *optional*, defaults to `PILImageResampling.NEAREST`): Resampling filter to use if resizing the image. Can be overridden by `resample` in `preprocess`. do_center_crop (`bool`, *optional*, defaults to `False`): Whether to center crop the image. If the input size is smaller than `crop_size` along any edge, the image is padded with 0's and then center cropped. Can be overridden by `do_center_crop` in `preprocess`. crop_size (`Dict[str, int]`, *optional*, defaults to `{"height": 289, "width": 289}`): Desired output size when applying center-cropping. Can be overridden by `crop_size` in `preprocess`. do_rescale (`bool`, *optional*, defaults to `True`): Whether to rescale the image by the specified scale `rescale_factor`. Can be overridden by the `do_rescale` parameter in the `preprocess` method. rescale_factor (`int` or `float`, *optional*, defaults to `1/255`): Scale factor to use if rescaling the image. Can be overridden by the `rescale_factor` parameter in the `preprocess` method. rescale_offset (`bool`, *optional*, defaults to `False`): Whether to rescale the image between [-scale_range, scale_range] instead of [0, scale_range]. Can be overridden by the `rescale_factor` parameter in the `preprocess` method. do_normalize (`bool`, *optional*, defaults to `True`): Whether to normalize the image. Can be overridden by the `do_normalize` parameter in the `preprocess` method. image_mean (`float` or `List[float]`, *optional*, defaults to `IMAGENET_STANDARD_MEAN`): Mean to use if normalizing the image. This is a float or list of floats the length of the number of channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method. image_std (`float` or `List[float]`, *optional*, defaults to `IMAGENET_STANDARD_STD`): Standard deviation to use if normalizing the image. This is a float or list of floats the length of the number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method. include_top (`bool`, *optional*, defaults to `True`): Whether to rescale the image again. Should be set to True if the inputs are used for image classification. """ model_input_names = ["pixel_values"] def __init__( self, do_resize: bool = True, size: Dict[str, int] = None, resample: PILImageResampling = PIL.Image.NEAREST, do_center_crop: bool = False, crop_size: Dict[str, int] = None, rescale_factor: Union[int, float] = 1 / 255, rescale_offset: bool = False, do_rescale: bool = True, do_normalize: bool = True, image_mean: Optional[Union[float, List[float]]] = None, image_std: Optional[Union[float, List[float]]] = None, include_top: bool = True, **kwargs, ) -> None: super().__init__(**kwargs) size = size if size is not None else {"height": 346, "width": 346} size = get_size_dict(size) crop_size = crop_size if crop_size is not None else {"height": 289, "width": 289} crop_size = get_size_dict(crop_size, param_name="crop_size") self.do_resize = do_resize self.size = size self.resample = resample self.do_center_crop = do_center_crop self.crop_size = crop_size self.do_rescale = do_rescale self.rescale_factor = rescale_factor self.rescale_offset = rescale_offset self.do_normalize = do_normalize self.image_mean = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN self.image_std = image_std if image_std is not None else IMAGENET_STANDARD_STD self.include_top = include_top def resize( self, image: np.ndarray, size: Dict[str, int], resample: PILImageResampling = PIL.Image.NEAREST, data_format: Optional[Union[str, ChannelDimension]] = None, **kwargs, ) -> np.ndarray: """ Resize an image to `(size["height"], size["width"])` using the specified resampling filter. Args: image (`np.ndarray`): Image to resize. size (`Dict[str, int]`): Size of the output image. resample (`PILImageResampling` filter, *optional*, defaults to `PILImageResampling.NEAREST`): Resampling filter to use when resizing the image. data_format (`str` or `ChannelDimension`, *optional*): The channel dimension format of the image. If not provided, it will be the same as the input image. """ size = get_size_dict(size) if "height" not in size or "width" not in size: raise ValueError(f"The size dictionary must have keys 'height' and 'width'. Got {size.keys()}") return resize( image, size=(size["height"], size["width"]), resample=resample, data_format=data_format, **kwargs ) def center_crop( self, image: np.ndarray, size: Dict[str, int], data_format: Optional[Union[str, ChannelDimension]] = None, **kwargs, ) -> np.ndarray: """ Center crop an image to `(crop_size["height"], crop_size["width"])`. If the input size is smaller than `crop_size` along any edge, the image is padded with 0's and then center cropped. Args: image (`np.ndarray`): Image to center crop. size (`Dict[str, int]`): Size of the output image. data_format (`str` or `ChannelDimension`, *optional*): The channel dimension format of the image. If not provided, it will be the same as the input image. """ size = get_size_dict(size) if "height" not in size or "width" not in size: raise ValueError(f"The size dictionary must have keys 'height' and 'width'. Got {size.keys()}") return center_crop(image, size=(size["height"], size["width"]), data_format=data_format, **kwargs) def rescale( self, image: np.ndarray, scale: Union[int, float], offset: bool = True, data_format: Optional[Union[str, ChannelDimension]] = None, **kwargs, ): """ Rescale an image by a scale factor. image = image * scale. Args: image (`np.ndarray`): Image to rescale. scale (`int` or `float`): Scale to apply to the image. offset (`bool`, *optional*): Whether to scale the image in both negative and positive directions. data_format (`str` or `ChannelDimension`, *optional*): The channel dimension format of the image. If not provided, it will be the same as the input image. """ if offset: rescaled_image = (image - 127.5) * scale if data_format is not None: rescaled_image = to_channel_dimension_format(rescaled_image, data_format) rescaled_image = rescaled_image.astype(np.float32) else: rescaled_image = rescale(image, scale=scale, data_format=data_format, **kwargs) return rescaled_image def normalize( self, image: np.ndarray, mean: Union[float, List[float]], std: Union[float, List[float]], data_format: Optional[Union[str, ChannelDimension]] = None, **kwargs, ) -> np.ndarray: """ Normalize an image. image = (image - image_mean) / image_std. Args: image (`np.ndarray`): Image to normalize. image_mean (`float` or `List[float]`): Image mean. image_std (`float` or `List[float]`): Image standard deviation. data_format (`str` or `ChannelDimension`, *optional*): The channel dimension format of the image. If not provided, it will be the same as the input image. """ return normalize(image, mean=mean, std=std, data_format=data_format, **kwargs) def preprocess( self, images: ImageInput, do_resize: bool = None, size: Dict[str, int] = None, resample=None, do_center_crop: bool = None, crop_size: Dict[str, int] = None, do_rescale: bool = None, rescale_factor: float = None, rescale_offset: bool = None, do_normalize: bool = None, image_mean: Optional[Union[float, List[float]]] = None, image_std: Optional[Union[float, List[float]]] = None, include_top: bool = None, return_tensors: Optional[Union[str, TensorType]] = None, data_format: ChannelDimension = ChannelDimension.FIRST, **kwargs, ) -> PIL.Image.Image: """ Preprocess an image or batch of images. Args: images (`ImageInput`): Image to preprocess. do_resize (`bool`, *optional*, defaults to `self.do_resize`): Whether to resize the image. size (`Dict[str, int]`, *optional*, defaults to `self.size`): Size of the image after `resize`. resample (`PILImageResampling`, *optional*, defaults to `self.resample`): PILImageResampling filter to use if resizing the image Only has an effect if `do_resize` is set to `True`. do_center_crop (`bool`, *optional*, defaults to `self.do_center_crop`): Whether to center crop the image. crop_size (`Dict[str, int]`, *optional*, defaults to `self.crop_size`): Size of the image after center crop. If one edge the image is smaller than `crop_size`, it will be padded with zeros and then cropped do_rescale (`bool`, *optional*, defaults to `self.do_rescale`): Whether to rescale the image values between [0 - 1]. rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`): Rescale factor to rescale the image by if `do_rescale` is set to `True`. rescale_offset (`bool`, *optional*, defaults to `self.rescale_offset`): Whether to rescale the image between [-scale_range, scale_range] instead of [0, scale_range]. do_normalize (`bool`, *optional*, defaults to `self.do_normalize`): Whether to normalize the image. image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`): Image mean. image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`): Image standard deviation. include_top (`bool`, *optional*, defaults to `self.include_top`): Rescales the image again for image classification if set to True. return_tensors (`str` or `TensorType`, *optional*): The type of tensors to return. Can be one of: - `None`: Return a list of `np.ndarray`. - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`. - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`. - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`. - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`. data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`): The channel dimension format for the output image. Can be one of: - `ChannelDimension.FIRST`: image in (num_channels, height, width) format. - `ChannelDimension.LAST`: image in (height, width, num_channels) format. """ do_resize = do_resize if do_resize is not None else self.do_resize resample = resample if resample is not None else self.resample do_center_crop = do_center_crop if do_center_crop is not None else self.do_center_crop do_rescale = do_rescale if do_rescale is not None else self.do_rescale rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor rescale_offset = rescale_offset if rescale_offset is not None else self.rescale_offset do_normalize = do_normalize if do_normalize is not None else self.do_normalize image_mean = image_mean if image_mean is not None else self.image_mean image_std = image_std if image_std is not None else self.image_std include_top = include_top if include_top is not None else self.include_top size = size if size is not None else self.size size = get_size_dict(size) crop_size = crop_size if crop_size is not None else self.crop_size crop_size = get_size_dict(crop_size, param_name="crop_size") images = make_list_of_images(images) if not valid_images(images): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) if do_resize and size is None or resample is None: raise ValueError("Size and resample must be specified if do_resize is True.") if do_center_crop and crop_size is None: raise ValueError("Crop size must be specified if do_center_crop is True.") if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True.") if do_normalize and (image_mean is None or image_std is None): raise ValueError("Image mean and std must be specified if do_normalize is True.") # All transformations expect numpy arrays. images = [to_numpy_array(image) for image in images] if do_resize: images = [self.resize(image=image, size=size, resample=resample) for image in images] if do_center_crop: images = [self.center_crop(image=image, size=crop_size) for image in images] if do_rescale: images = [self.rescale(image=image, scale=rescale_factor, offset=rescale_offset) for image in images] if do_normalize: images = [self.normalize(image=image, mean=image_mean, std=image_std) for image in images] if include_top: images = [self.normalize(image=image, mean=[0, 0, 0], std=image_std) for image in images] images = [to_channel_dimension_format(image, data_format) for image in images] data = {"pixel_values": images} return BatchFeature(data=data, tensor_type=return_tensors)
2881099/dotnetGen_sqlserver
7,116
GenMs/plist-cil/NSDate.cs
// plist-cil - An open source library to parse and generate property lists for .NET // Copyright (C) 2015 Natalia Portillo // // This code is based on: // plist - An open source library to parse and generate property lists // Copyright (C) 2014 Daniel Dreibrodt // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. using System; using System.Text; namespace PList { /// <summary> /// Represents a date /// </summary> /// @author Daniel Dreibrodt /// @author Natalia Portillo public class NSDate : NSObject { readonly DateTime date; static readonly DateTime EPOCH = new DateTime(2001, 1, 1, 0, 0, 0, DateTimeKind.Utc); // The datetime ends with 'Z', which indicates UTC time. To make sure .NET // understands the 'Z' character as a timezone, specify the 'K' format string. static readonly string sdfDefault = "yyyy-MM-dd'T'HH:mm:ssK"; static readonly string sdfGnuStep = "yyyy-MM-dd HH:mm:ss zzz"; static readonly System.Globalization.CultureInfo provider = System.Globalization.CultureInfo.InvariantCulture; /// <summary> /// Parses the XML date string and creates a .NET DateTime object from it. /// </summary> /// <returns>The parsed Date</returns> /// <param name="textRepresentation">The date string as found in the XML property list</param> /// <exception cref="FormatException">Given string cannot be parsed</exception> static DateTime ParseDateString(string textRepresentation) { try { return DateTime.ParseExact(textRepresentation, sdfDefault, provider); } catch (FormatException) { return DateTime.ParseExact(textRepresentation, sdfGnuStep, provider); } } /// <summary> /// Generates a String representation of a .NET DateTime object. The string /// is formatted according to the specification for XML property list dates. /// </summary> /// <param name="date">The date which should be represented.</param> /// <returns>The string representation of the date.</returns> public static string MakeDateString(DateTime date) { return date.ToUniversalTime().ToString(sdfDefault); } /// <summary> /// Generates a String representation of a .NET DateTime object. The string /// is formatted according to the specification for GnuStep ASCII property /// list dates. /// </summary> /// <param name="date">The date which should be represented.</param> /// <returns>The string representation of the date.</returns> static string MakeDateStringGnuStep(DateTime date) { return date.ToString(sdfGnuStep); } /// <summary> /// Creates a date from its binary representation. /// </summary> /// <param name="bytes">bytes The date bytes</param> public NSDate(byte[] bytes) { //dates are 8 byte big-endian double, seconds since the epoch date = EPOCH.AddSeconds(BinaryPropertyListParser.ParseDouble(bytes)); } /// <summary> /// Parses a date from its textual representation. /// That representation has the following pattern: <code>yyyy-MM-dd'T'HH:mm:ss'Z'</code> /// </summary> /// <param name="textRepresentation">The textual representation of the date (ISO 8601 format)</param> /// <exception cref="FormatException">When the date could not be parsed, i.e. it does not match the expected pattern.</exception> public NSDate(String textRepresentation) { date = ParseDateString(textRepresentation); } /// <summary> /// Creates a NSDate from a .NET DateTime /// </summary> /// <param name="d">The date</param> public NSDate(DateTime d) { date = d; } /// <summary> /// Gets the date. /// </summary> /// <returns>The date.</returns> public DateTime Date { get { return date; } } /// <summary> /// Determines whether the specified <see cref="System.Object"/> is equal to the current <see cref="PList.NSDate"/>. /// </summary> /// <param name="obj">The <see cref="System.Object"/> to compare with the current <see cref="PList.NSDate"/>.</param> /// <returns><c>true</c> if the specified <see cref="System.Object"/> is equal to the current /// <see cref="PList.NSDate"/>; otherwise, <c>false</c>.</returns> public override bool Equals(Object obj) { return obj.GetType().Equals(GetType()) && date.Equals(((NSDate)obj).Date); } /// <summary> /// Serves as a hash function for a <see cref="PList.NSDate"/> object. /// </summary> /// <returns>A hash code for this instance that is suitable for use in hashing algorithms and data structures such as a /// hash table.</returns> public override int GetHashCode() { return date.GetHashCode(); } internal override void ToXml(StringBuilder xml, int level) { Indent(xml, level); xml.Append("<date>"); xml.Append(MakeDateString(date)); xml.Append("</date>"); } internal override void ToBinary(BinaryPropertyListWriter outPlist) { outPlist.Write(0x33); outPlist.WriteDouble((date - EPOCH).TotalSeconds); } /// <summary> /// Generates a string representation of the date. /// </summary> /// <returns>A string representation of the date.</returns> public override String ToString() { return date.ToString(); } internal override void ToASCII(StringBuilder ascii, int level) { Indent(ascii, level); ascii.Append("\""); ascii.Append(MakeDateString(date)); ascii.Append("\""); } internal override void ToASCIIGnuStep(StringBuilder ascii, int level) { Indent(ascii, level); ascii.Append("<*D"); ascii.Append(MakeDateStringGnuStep(date)); ascii.Append(">"); } /// <summary> /// Determines whether the specified <see cref="PList.NSObject"/> is equal to the current <see cref="PList.NSDate"/>. /// </summary> /// <param name="obj">The <see cref="PList.NSObject"/> to compare with the current <see cref="PList.NSDate"/>.</param> /// <returns><c>true</c> if the specified <see cref="PList.NSObject"/> is equal to the current /// <see cref="PList.NSDate"/>; otherwise, <c>false</c>.</returns> public override bool Equals(NSObject obj) { if (!(obj is NSDate)) return false; int equality = DateTime.Compare(date, ((NSDate)obj).Date); return equality == 0; } } }
2881099/dotnetGen_postgresql
5,877
GenPg/FastExcel/FastExcel.Write.cs
using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; namespace FastExcel { public partial class FastExcel { /// <summary> /// Write data to a sheet /// </summary> /// <param name="worksheet">A dataset</param> public void Write(Worksheet worksheet) { this.Write(worksheet, null, null); } /// <summary> /// Write data to a sheet /// </summary> /// <param name="worksheet">A dataset</param> /// <param name="sheetNumber">The number of the sheet starting at 1</param> /// <param name="existingHeadingRows">How many rows in the template sheet you would like to keep</param> public void Write(Worksheet worksheet, int sheetNumber, int existingHeadingRows = 0) { this.Write(worksheet, sheetNumber, null, existingHeadingRows); } /// <summary> /// Write data to a sheet /// </summary> /// <param name="worksheet">A dataset</param> /// <param name="sheetName">The display name of the sheet</param> /// <param name="existingHeadingRows">How many rows in the template sheet you would like to keep</param> public void Write(Worksheet worksheet, string sheetName, int existingHeadingRows = 0) { this.Write(worksheet, null, sheetName, existingHeadingRows); } /// <summary> /// Write a list of objects to a sheet /// </summary> /// <typeparam name="T">Row Object</typeparam> /// <param name="rows">IEnumerable list of objects</param> /// <param name="sheetNumber">The number of the sheet starting at 1</param> /// <param name="existingHeadingRows">How many rows in the template sheet you would like to keep</param> public void Write<T>(IEnumerable<T> rows, int sheetNumber, int existingHeadingRows = 0) { Worksheet data = new Worksheet(); data.PopulateRows<T>(rows); this.Write(data, sheetNumber, null, existingHeadingRows); } /// <summary> /// Write a list of objects to a sheet /// </summary> /// <typeparam name="T">Row Object</typeparam> /// <param name="rows">IEnumerable list of objects</param> /// <param name="sheetName">The display name of the sheet</param> /// <param name="existingHeadingRows">How many rows in the template sheet you would like to keep</param> public void Write<T>(IEnumerable<T> rows, string sheetName, int existingHeadingRows = 0) { Worksheet data = new Worksheet(); data.PopulateRows<T>(rows, existingHeadingRows); this.Write(data, null, sheetName, existingHeadingRows); } /// <summary> /// Write a list of objects to a sheet /// </summary> /// <typeparam name="T">Row Object</typeparam> /// <param name="objectList">IEnumerable list of objects</param> /// <param name="sheetNumber">The number of the sheet starting at 1</param> /// <param name="usePropertiesAsHeadings">Use property names from object list as headings</param> public void Write<T>(IEnumerable<T> objectList, int sheetNumber, bool usePropertiesAsHeadings) { Worksheet data = new Worksheet(); data.PopulateRows<T>(objectList, 0, usePropertiesAsHeadings); this.Write(data, sheetNumber, null, 0); } /// <summary> /// Write a list of objects to a sheet /// </summary> /// <typeparam name="T">Row Object</typeparam> /// <param name="rows">IEnumerable list of objects</param> /// <param name="sheetName">The display name of the sheet</param> /// <param name="usePropertiesAsHeadings">Use property names from object list as headings</param> public void Write<T>(IEnumerable<T> rows, string sheetName, bool usePropertiesAsHeadings) { Worksheet data = new Worksheet(); data.PopulateRows<T>(rows, 0, usePropertiesAsHeadings); this.Write(data, null, sheetName, 0); } private void Write(Worksheet worksheet, int? sheetNumber = null, string sheetName = null, int existingHeadingRows = 0) { CheckFiles(); try { if (!this.UpdateExisting) { File.Copy(this.TemplateFile.FullName, this.ExcelFile.FullName); } } catch (Exception ex) { throw new Exception("Could not copy template to output file path", ex); } PrepareArchive(); // Open worksheet worksheet.GetWorksheetProperties(this, sheetNumber, sheetName); worksheet.ExistingHeadingRows = existingHeadingRows; if (this.Archive.Mode != ZipArchiveMode.Update) { throw new Exception("FastExcel is in ReadOnly mode so cannot perform a write"); } // Check if ExistingHeadingRows will be overridden by the dataset if (worksheet.ExistingHeadingRows != 0 && worksheet.Rows.Where(r => r.RowNumber <= worksheet.ExistingHeadingRows).Any()) { throw new Exception("Existing Heading Rows was specified but some or all will be overridden by data rows. Check DataSet.Row.RowNumber against ExistingHeadingRows"); } using (Stream stream = this.Archive.GetEntry(worksheet.FileName).Open()) { // Open worksheet and read the data at the top and bottom of the sheet StreamReader streamReader = new StreamReader(stream); worksheet.ReadHeadersAndFooters(streamReader, ref worksheet); //Set the stream to the start stream.Position = 0; // Open the stream so we can override all content of the sheet StreamWriter streamWriter = new StreamWriter(stream); // TODO instead of saving the headers then writing them back get position where the headers finish then write from there streamWriter.Write(worksheet.Headers); if (!worksheet.Template) { worksheet.Headers = null; } this.SharedStrings.ReadWriteMode = true; // Add Rows foreach (Row row in worksheet.Rows) { streamWriter.Write(row.ToXmlString(this.SharedStrings)); } this.SharedStrings.ReadWriteMode = false; //Add Footers streamWriter.Write(worksheet.Footers); if (!worksheet.Template) { worksheet.Footers = null; } streamWriter.Flush(); } } } }
2881099/dotnetGen_postgresql
3,559
GenPg/FastExcel/Row.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; namespace FastExcel { /// <summary> /// Row that contains the Cells /// </summary> public class Row { /// <summary> /// The Row Number (Row numbers start at 1) /// </summary> public int RowNumber { get; set; } /// <summary> /// The collection of cells for this row /// </summary> public IEnumerable<Cell> Cells { get; set; } /// <summary> /// Create a new Row /// </summary> /// <param name="rowNumber">Row number starting with 1</param> /// <param name="cells">Cells on this row</param> public Row(int rowNumber, IEnumerable<Cell> cells) { if (rowNumber <= 0) { throw new Exception("Row numbers starting at 1"); } this.RowNumber = rowNumber; this.Cells = cells; } public Row(XElement rowElement, SharedStrings sharedStrings) { try { this.RowNumber = (from a in rowElement.Attributes("r") select int.Parse(a.Value)).First(); } catch (Exception ex) { throw new Exception("Row Number not found", ex); } if (rowElement.HasElements) { this.Cells = GetCells(rowElement, sharedStrings); } } private IEnumerable<Cell> GetCells(XElement rowElement, SharedStrings sharedStrings) { foreach (XElement cellElement in rowElement.Elements()) { Cell cell = new Cell(cellElement, sharedStrings); if (cell.Value != null) { yield return cell; } } } internal StringBuilder ToXmlString(SharedStrings sharedStrings) { StringBuilder row = new StringBuilder(); if (this.Cells != null && Cells.Any()) { row.AppendFormat("<row r=\"{0}\">", this.RowNumber); try { foreach (Cell cell in this.Cells) { row.Append(cell.ToXmlString(sharedStrings, this.RowNumber)); } } finally { row.Append("</row>"); } } return row; } /// <summary> /// Merge this row and the passed one togeather /// </summary> /// <param name="row">Row to be merged into this one</param> internal void Merge(Row row) { // Merge cells List<Cell> outputList = new List<Cell>(); foreach (var cell in this.Cells.Union(row.Cells).GroupBy(c => c.ColumnNumber)) { int count = cell.Count(); if (count == 1) { outputList.Add(cell.First()); } else { cell.First().Merge(cell.Skip(1).First()); outputList.Add(cell.First()); } } // Sort this.Cells = (from c in outputList orderby c.ColumnNumber select c); } } }
2881099/dotnetGen_sqlserver
1,967
GenMs/plist-cil/PropertyListFormatException.cs
// plist-cil - An open source library to parse and generate property lists for .NET // Copyright (C) 2015 Natalia Portillo // // This code is based on: // plist - An open source library to parse and generate property lists // Copyright (C) 2014 Daniel Dreibrodt // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. using System; namespace PList { /// <summary> /// A PropertyListFormatException is thrown by the various property list format parsers /// when an error in the format of the given property list is encountered. /// </summary> /// @author Daniel Dreibrodt /// @author Natalia Portillo public class PropertyListFormatException : PropertyListException { /// <summary> /// Creates a new exception with the given message. /// </summary> /// <param name="message">A message containing information about the nature of the exception.</param> public PropertyListFormatException(string message) : base(message) { } } }
27182812/ChatGLM-LLaMA-chinese-insturct
7,751
src/transformers/models/efficientnet/configuration_efficientnet.py
# coding=utf-8 # Copyright 2023 Google Research, Inc. and The HuggingFace Inc. team. 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. """ EfficientNet model configuration""" from collections import OrderedDict from typing import List, Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging logger = logging.get_logger(__name__) EFFICIENTNET_PRETRAINED_CONFIG_ARCHIVE_MAP = { "google/efficientnet-b7": "https://huggingface.co/google/efficientnet-b7/resolve/main/config.json", } class EfficientNetConfig(PretrainedConfig): r""" This is the configuration class to store the configuration of a [`EfficientNetModel`]. It is used to instantiate an EfficientNet model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the EfficientNet [google/efficientnet-b7](https://huggingface.co/google/efficientnet-b7) architecture. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the documentation from [`PretrainedConfig`] for more information. Args: num_channels (`int`, *optional*, defaults to 3): The number of input channels. image_size (`int`, *optional*, defaults to 600): The input image size. width_coefficient (`float`, *optional*, defaults to 2.0): Scaling coefficient for network width at each stage. depth_coefficient (`float`, *optional*, defaults to 3.1): Scaling coefficient for network depth at each stage. depth_divisor `int`, *optional*, defaults to 8): A unit of network width. kernel_sizes (`List[int]`, *optional*, defaults to `[3, 3, 5, 3, 5, 5, 3]`): List of kernel sizes to be used in each block. in_channels (`List[int]`, *optional*, defaults to `[32, 16, 24, 40, 80, 112, 192]`): List of input channel sizes to be used in each block for convolutional layers. out_channels (`List[int]`, *optional*, defaults to `[16, 24, 40, 80, 112, 192, 320]`): List of output channel sizes to be used in each block for convolutional layers. depthwise_padding (`List[int]`, *optional*, defaults to `[]`): List of block indices with square padding. strides: (`List[int]`, *optional*, defaults to `[1, 2, 2, 2, 1, 2, 1]`): List of stride sizes to be used in each block for convolutional layers. num_block_repeats (`List[int]`, *optional*, defaults to `[1, 2, 2, 3, 3, 4, 1]`): List of the number of times each block is to repeated. expand_ratios (`List[int]`, *optional*, defaults to `[1, 6, 6, 6, 6, 6, 6]`): List of scaling coefficient of each block. squeeze_expansion_ratio (`float`, *optional*, defaults to 0.25): Squeeze expansion ratio. hidden_act (`str` or `function`, *optional*, defaults to `"silu"`): The non-linear activation function (function or string) in each block. If string, `"gelu"`, `"relu"`, `"selu", `"gelu_new"`, `"silu"` and `"mish"` are supported. hiddem_dim (`int`, *optional*, defaults to 1280): The hidden dimension of the layer before the classification head. pooling_type (`str` or `function`, *optional*, defaults to `"mean"`): Type of final pooling to be applied before the dense classification head. Available options are [`"mean"`, `"max"`] initializer_range (`float`, *optional*, defaults to 0.02): The standard deviation of the truncated_normal_initializer for initializing all weight matrices. batch_norm_eps (`float`, *optional*, defaults to 1e-3): The epsilon used by the batch normalization layers. batch_norm_momentum (`float`, *optional*, defaults to 0.99): The momentum used by the batch normalization layers. dropout_rate (`float`, *optional*, defaults to 0.5): The dropout rate to be applied before final classifier layer. drop_connect_rate (`float`, *optional*, defaults to 0.2): The drop rate for skip connections. Example: ```python >>> from transformers import EfficientNetConfig, EfficientNetModel >>> # Initializing a EfficientNet efficientnet-b7 style configuration >>> configuration = EfficientNetConfig() >>> # Initializing a model (with random weights) from the efficientnet-b7 style configuration >>> model = EfficientNetModel(configuration) >>> # Accessing the model configuration >>> configuration = model.config ```""" model_type = "efficientnet" def __init__( self, num_channels: int = 3, image_size: int = 600, width_coefficient: float = 2.0, depth_coefficient: float = 3.1, depth_divisor: int = 8, kernel_sizes: List[int] = [3, 3, 5, 3, 5, 5, 3], in_channels: List[int] = [32, 16, 24, 40, 80, 112, 192], out_channels: List[int] = [16, 24, 40, 80, 112, 192, 320], depthwise_padding: List[int] = [], strides: List[int] = [1, 2, 2, 2, 1, 2, 1], num_block_repeats: List[int] = [1, 2, 2, 3, 3, 4, 1], expand_ratios: List[int] = [1, 6, 6, 6, 6, 6, 6], squeeze_expansion_ratio: float = 0.25, hidden_act: str = "swish", hidden_dim: int = 2560, pooling_type: str = "mean", initializer_range: float = 0.02, batch_norm_eps: float = 0.001, batch_norm_momentum: float = 0.99, dropout_rate: float = 0.5, drop_connect_rate: float = 0.2, **kwargs, ): super().__init__(**kwargs) self.num_channels = num_channels self.image_size = image_size self.width_coefficient = width_coefficient self.depth_coefficient = depth_coefficient self.depth_divisor = depth_divisor self.kernel_sizes = kernel_sizes self.in_channels = in_channels self.out_channels = out_channels self.depthwise_padding = depthwise_padding self.strides = strides self.num_block_repeats = num_block_repeats self.expand_ratios = expand_ratios self.squeeze_expansion_ratio = squeeze_expansion_ratio self.hidden_act = hidden_act self.hidden_dim = hidden_dim self.pooling_type = pooling_type self.initializer_range = initializer_range self.batch_norm_eps = batch_norm_eps self.batch_norm_momentum = batch_norm_momentum self.dropout_rate = dropout_rate self.drop_connect_rate = drop_connect_rate self.num_hidden_layers = sum(num_block_repeats) * 4 class EfficientNetOnnxConfig(OnnxConfig): torch_onnx_minimum_version = version.parse("1.11") @property def inputs(self) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}), ] ) @property def atol_for_validation(self) -> float: return 1e-5
2881099/dotnetGen_postgresql
21,409
GenPg/FastExcel/Worksheet.cs
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.IO.Compression; using System.IO; using System.Xml.Linq; namespace FastExcel { public class Worksheet { /// <summary> /// Collection of rows in this worksheet /// </summary> public IEnumerable<Row> Rows { get; set; } public IEnumerable<string> Headings { get; set; } public int Index { get; internal set; } public string Name { get; set; } public int ExistingHeadingRows { get; set; } private int? InsertAfterIndex { get; set; } public bool Template { get; set; } internal string Headers { get; set; } internal string Footers { get; set; } public FastExcel FastExcel { get; private set; } internal string FileName { get { return Worksheet.GetFileName(this.Index); } } public static string GetFileName(int index) { return string.Format("xl/worksheets/sheet{0}.xml", index); } private const string DEFAULT_HEADERS = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?><worksheet xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\"><sheetData>"; private const string DEFAULT_FOOTERS = "</sheetData></worksheet>"; public Worksheet() { } public Worksheet(FastExcel fastExcel) { FastExcel = fastExcel; } public void PopulateRows<T>(IEnumerable<T> rows, int existingHeadingRows = 0, bool usePropertiesAsHeadings = false) { if ((rows.FirstOrDefault() as IEnumerable<object>) == null) { PopulateRowsFromObjects(rows, existingHeadingRows, usePropertiesAsHeadings); } else { PopulateRowsFromIEnumerable(rows as IEnumerable<IEnumerable<object>>, existingHeadingRows); } } private string GetHeaderName(PropertyInfo propertyInfo) { var descriptionAttribute = propertyInfo.GetCustomAttribute(typeof (DescriptionAttribute)) as DescriptionAttribute; if (descriptionAttribute != null && !string.IsNullOrWhiteSpace(descriptionAttribute.Description)) { return descriptionAttribute.Description; } return propertyInfo.Name; } private void PopulateRowsFromObjects<T>(IEnumerable<T> rows, int existingHeadingRows = 0, bool usePropertiesAsHeadings = false) { int rowNumber = existingHeadingRows + 1; // Get all properties PropertyInfo[] properties = typeof(T).GetTypeInfo().GetProperties(); List<Row> newRows = new List<Row>(); if (usePropertiesAsHeadings) { this.Headings = properties.Select(GetHeaderName); int headingColumnNumber = 1; IEnumerable<Cell> headingCells = (from h in this.Headings select new Cell(headingColumnNumber++, h)).ToArray(); Row headingRow = new Row(rowNumber++, headingCells); newRows.Add(headingRow); } foreach (T rowObject in rows) { List<Cell> cells = new List<Cell>(); int columnNumber = 1; // Get value from each property foreach (PropertyInfo propertyInfo in properties) { object value = propertyInfo.GetValue(rowObject, null); if(value != null) { Cell cell = new Cell(columnNumber, value); cells.Add(cell); } columnNumber++; } Row row = new Row(rowNumber++, cells); newRows.Add(row); } this.Rows = newRows; } private void PopulateRowsFromIEnumerable(IEnumerable<IEnumerable<object>> rows, int existingHeadingRows = 0) { int rowNumber = existingHeadingRows + 1; List<Row> newRows = new List<Row>(); foreach (IEnumerable<object> rowOfObjects in rows) { List<Cell> cells = new List<Cell>(); int columnNumber = 1; foreach (object value in rowOfObjects) { if (value != null) { Cell cell = new Cell(columnNumber, value); cells.Add(cell); } columnNumber++; } Row row = new Row(rowNumber++, cells); newRows.Add(row); } this.Rows = newRows; } /// <summary> /// Add a row using a collection of value objects /// </summary> /// <param name="cellValues">Collection of objects</param> public void AddRow(params object[] cellValues) { if (this.Rows == null) { this.Rows = new List<Row>(); } List<Cell> cells = new List<Cell>(); int columnNumber = 1; foreach (object value in cellValues) { if (value != null) { Cell cell = new Cell(columnNumber++, value); cells.Add(cell); } else { columnNumber++; } } Row row = new Row(this.Rows.Count() + 1, cells); (this.Rows as List<Row>).Add(row); } /// <summary> /// Note: This method is slow /// </summary> public void AddValue(int rowNumber, int columnNumber, object value) { if (this.Rows == null) { this.Rows = new List<Row>(); } Row row = (from r in this.Rows where r.RowNumber == rowNumber select r).FirstOrDefault(); Cell cell = null; if (row == null) { cell = new Cell(columnNumber, value); row = new Row(rowNumber, new List<Cell>{ cell }); (this.Rows as List<Row>).Add(row); } if (cell == null) { cell = (from c in row.Cells where c.ColumnNumber == columnNumber select c).FirstOrDefault(); if (cell == null) { cell = new Cell(columnNumber, value); (row.Cells as List<Cell>).Add(cell); } } } /// <summary> /// Merges the parameter into the current DatSet object, the parameter takes precedence /// </summary> /// <param name="data">A DataSet to merge</param> public void Merge(Worksheet data) { // Merge headings if (this.Headings == null || !this.Headings.Any()) { this.Headings = data.Headings; } // Merge rows data.Rows = MergeRows(data.Rows); } private IEnumerable<Row> MergeRows(IEnumerable<Row> rows) { foreach (var row in this.Rows.Union(rows).GroupBy(r => r.RowNumber)) { int count = row.Count(); if (count == 1) { yield return row.First(); } else { row.First().Merge(row.Skip(1).First()); yield return row.First(); } } } public bool Exists { get { return !string.IsNullOrEmpty(this.FileName); } } internal void Read(int? sheetNumber = null, string sheetName = null, int existingHeadingRows = 0) { GetWorksheetProperties(FastExcel, sheetNumber, sheetName); Read(existingHeadingRows); } public void Read(int existingHeadingRows = 0) { FastExcel.CheckFiles(); FastExcel.PrepareArchive(); ExistingHeadingRows = existingHeadingRows; IEnumerable<Row> rows = null; List<string> headings = new List<string>(); using (Stream stream = FastExcel.Archive.GetEntry(FileName).Open()) { XDocument document = XDocument.Load(stream); int skipRows = 0; Row possibleHeadingRow = new Row(document.Descendants().Where(d => d.Name.LocalName == "row").FirstOrDefault(), FastExcel.SharedStrings); if (ExistingHeadingRows == 1 && possibleHeadingRow.RowNumber == 1) { foreach (Cell headerCell in possibleHeadingRow.Cells) { headings.Add(headerCell.Value.ToString()); } } rows = GetRows(document.Descendants().Where(d => d.Name.LocalName == "row").Skip(skipRows)); } Headings = headings; Rows = rows; } private IEnumerable<Row> GetRows(IEnumerable<XElement> rowElements) { foreach (var rowElement in rowElements) { yield return new Row(rowElement, FastExcel.SharedStrings); } } /// <summary> /// Read the existing sheet and copy some of the existing content /// </summary> /// <param name="stream">Worksheet stream</param> /// <param name="worksheet">Saves the header and footer to the worksheet</param> internal void ReadHeadersAndFooters(StreamReader stream, ref Worksheet worksheet) { StringBuilder headers = new StringBuilder(); StringBuilder footers = new StringBuilder(); bool headersComplete = false; bool rowsComplete = false; int existingHeadingRows = worksheet.ExistingHeadingRows; while (stream.Peek() >= 0) { string line = stream.ReadLine(); int currentLineIndex = 0; if (!headersComplete) { if (line.Contains("<sheetData/>")) { currentLineIndex = line.IndexOf("<sheetData/>"); headers.Append(line.Substring(0, currentLineIndex)); //remove the read section from line line = line.Substring(currentLineIndex, line.Length - currentLineIndex); headers.Append("<sheetData>"); // Headers complete now skip any content and start footer headersComplete = true; footers = new StringBuilder(); footers.Append("</sheetData>"); //There is no rows rowsComplete = true; } else if (line.Contains("<sheetData>")) { currentLineIndex = line.IndexOf("<sheetData>"); headers.Append(line.Substring(0, currentLineIndex)); //remove the read section from line line = line.Substring(currentLineIndex, line.Length - currentLineIndex); headers.Append("<sheetData>"); // Headers complete now skip any content and start footer headersComplete = true; footers = new StringBuilder(); footers.Append("</sheetData>"); } else { headers.Append(line); } } if (headersComplete && !rowsComplete) { if (existingHeadingRows == 0) { rowsComplete = true; } if (!rowsComplete) { while (!string.IsNullOrEmpty(line) && existingHeadingRows != 0) { if (line.Contains("<row")) { if (line.Contains("</row>")) { int index = line.IndexOf("<row"); currentLineIndex = line.IndexOf("</row>") + "</row>".Length; headers.Append(line.Substring(index, currentLineIndex - index)); //remove the read section from line line = line.Substring(currentLineIndex, line.Length - currentLineIndex); existingHeadingRows--; } else { int index = line.IndexOf("<row"); headers.Append(line.Substring(index, line.Length - index)); line = string.Empty; } } else if (line.Contains("</row>")) { currentLineIndex = line.IndexOf("</row>") + "</row>".Length; headers.Append(line.Substring(0, currentLineIndex)); //remove the read section from line line = line.Substring(currentLineIndex, line.Length - currentLineIndex); existingHeadingRows--; } } } if (existingHeadingRows == 0) { rowsComplete = true; } } if (rowsComplete) { if (line.Contains("</sheetData>")) { int index = line.IndexOf("</sheetData>") + "</sheetData>".Length; footers.Append(line.Substring(index, line.Length - index)); } else if (line.Contains("<sheetData/>")) { int index = line.IndexOf("<sheetData/>") + "<sheetData/>".Length; footers.Append(line.Substring(index, line.Length - index)); } else { footers.Append(line); } } } worksheet.Headers = headers.ToString(); worksheet.Footers = footers.ToString(); } /// <summary> /// Get worksheet file name from xl/workbook.xml /// </summary> internal void GetWorksheetProperties(FastExcel fastExcel, int? sheetNumber = null, string sheetName = null) { GetWorksheetPropertiesAndValidateNewName(fastExcel, sheetNumber, sheetName); } private bool GetWorksheetPropertiesAndValidateNewName(FastExcel fastExcel, int? sheetNumber = null, string sheetName = null, string newSheetName = null) { FastExcel = fastExcel; bool newSheetNameExists = false; FastExcel.CheckFiles(); FastExcel.PrepareArchive(); //If index has already been loaded then we can skip this function if (this.Index != 0) { return true; } if (!sheetNumber.HasValue && string.IsNullOrEmpty(sheetName)) { throw new Exception("No worksheet name or number was specified"); } using (Stream stream = FastExcel.Archive.GetEntry("xl/workbook.xml").Open()) { XDocument document = XDocument.Load(stream); if (document == null) { throw new Exception("Unable to load workbook.xml"); } List<XElement> sheetsElements = document.Descendants().Where(d => d.Name.LocalName == "sheet").ToList(); XElement sheetElement = null; if (sheetNumber.HasValue) { if (sheetNumber.Value <= sheetsElements.Count) { sheetElement = sheetsElements[sheetNumber.Value - 1]; } else { throw new Exception(string.Format("There is no sheet at index '{0}'", sheetNumber)); } } else if (!string.IsNullOrEmpty(sheetName)) { sheetElement = (from sheet in sheetsElements from attribute in sheet.Attributes() where attribute.Name == "name" && attribute.Value.Equals(sheetName, StringComparison.CurrentCultureIgnoreCase) select sheet).FirstOrDefault(); if (sheetElement == null) { throw new Exception(string.Format("There is no sheet named '{0}'", sheetName)); } if (!string.IsNullOrEmpty(newSheetName)) { newSheetNameExists = (from sheet in sheetsElements from attribute in sheet.Attributes() where attribute.Name == "name" && attribute.Value.Equals(newSheetName, StringComparison.CurrentCultureIgnoreCase) select sheet).Any(); if (FastExcel.MaxSheetNumber == 0) { FastExcel.MaxSheetNumber = (from sheet in sheetsElements from attribute in sheet.Attributes() where attribute.Name == "sheetId" select int.Parse(attribute.Value)).Max(); } } } this.Index = sheetsElements.IndexOf(sheetElement)+1; this.Name = (from attribute in sheetElement.Attributes() where attribute.Name == "name" select attribute.Value).FirstOrDefault(); } if (!this.Exists) { throw new Exception("No worksheet was found with the name or number was specified"); } if (string.IsNullOrEmpty(newSheetName)) { return false; } else { return !newSheetNameExists; } } internal void ValidateNewWorksheet(FastExcel fastExcel, int? insertAfterSheetNumber = null, string insertAfterSheetName = null) { if (string.IsNullOrEmpty(this.Name)) { // TODO possibly could calulcate a new worksheet name throw new Exception("Name for new worksheet is not specified"); } // Get worksheet details Worksheet previousWorksheet = new Worksheet(fastExcel); bool isNameValid = previousWorksheet.GetWorksheetPropertiesAndValidateNewName(fastExcel, insertAfterSheetNumber, insertAfterSheetName, this.Name); this.InsertAfterIndex = previousWorksheet.Index; if (!isNameValid) { throw new Exception(string.Format("Worksheet name '{0}' already exists", this.Name)); } fastExcel.MaxSheetNumber += 1; this.Index = fastExcel.MaxSheetNumber; if (string.IsNullOrEmpty(this.Headers)) { this.Headers = DEFAULT_HEADERS; } if (string.IsNullOrEmpty(this.Footers)) { this.Footers = DEFAULT_FOOTERS; } } internal WorksheetAddSettings AddSettings { get { if (this.InsertAfterIndex.HasValue) { return new WorksheetAddSettings() { Name = this.Name, SheetId = this.Index, InsertAfterSheetId = this.InsertAfterIndex.Value }; } else { return null; } } } } }
2881099/dotnetGen_sqlserver
12,138
GenMs/plist-cil/NSArray.cs
// plist-cil - An open source library to parse and generate property lists for .NET // Copyright (C) 2015 Natalia Portillo // // This code is based on: // plist - An open source library to parse and generate property lists // Copyright (C) 2014 Daniel Dreibrodt // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Text; namespace PList { /// <summary> /// Represents an Array. /// </summary> /// @author Daniel Dreibrodt /// @author Natalia Portillo public partial class NSArray : NSObject { List<NSObject> array; /// <summary> /// Creates an empty array of the given length. /// </summary> /// <param name="length">The number of elements this array will be able to hold.</param> public NSArray(int length) { array = new List<NSObject>(length); } /// <summary> /// Creates a array from an existing one /// </summary> /// <param name="a">The array which should be wrapped by the NSArray.</param> public NSArray(params NSObject[] a) { array = new List<NSObject>(a); } /// <summary> /// Returns the object stored at the given index. /// </summary> /// <returns>The object at the given index.</returns> /// <param name="i">The index of the object.</param> public NSObject ObjectAtIndex(int i) { return array[i]; } /// <summary> /// Remove the i-th element from the array. /// The array will be resized. /// </summary> /// <param name="i">The index of the object</param> public void Remove(int i) { this.array.RemoveAt(i); } /// <summary> /// Stores an object at the specified index. /// If there was another object stored at that index it will be replaced. /// </summary> /// <param name="key">The index where to store the object.</param> /// <param name="value">The object.</param> public void SetValue(int key, Object value) { if (value == null) throw new ArgumentNullException("value", "Cannot add null values to an NSArray!"); array[key] = NSObject.Wrap(value); } /// <summary> /// Returns the array of NSObjects represented by this NSArray. /// Any changes to the values of this array will also affect the NSArray. /// </summary> /// <returns>The actual array represented by this NSArray.</returns> public NSObject[] GetArray() { return array.ToArray(); } /// <summary> /// Returns the size of the array. /// </summary> /// <value>The number of elements that this array can store.</value> public int Count { get { return array.Count; } } /// <summary> /// Checks whether an object is present in the array or whether it is equal /// to any of the objects in the array. /// </summary> /// <returns><c>true</c>, when the object could be found. <c>false</c> otherwise.</returns> /// <param name="obj">The object to look for.</param> public bool ContainsObject(Object obj) { NSObject nso = NSObject.Wrap(obj); foreach (NSObject elem in array) { if (elem.Equals(nso)) { return true; } } return false; } /// <summary> /// Searches for an object in the array. If it is found its index will be /// returned. This method also returns an index if the object is not the same /// as the one stored in the array but has equal contents. /// </summary> /// <returns>The index of the object, if it was found. -1 otherwise.</returns> /// <param name="obj">The object to look for.</param> public int IndexOfObject(Object obj) { NSObject nso = NSObject.Wrap(obj); for (int i = 0; i < array.Count; i++) { if (array[i].Equals(nso)) { return i; } } return -1; } /// <summary> /// Searches for an object in the array. If it is found its index will be /// returned. This method only returns the index of an object that is /// <b>identical</b> to the given one. Thus objects that might contain the /// same value as the given one will not be considered. /// </summary> /// <returns>The index of the object, if it was found. -1 otherwise.</returns> /// <param name="obj">The object to look for.</param> public int IndexOfIdenticalObject(Object obj) { NSObject nso = NSObject.Wrap(obj); for (int i = 0; i < array.Count; i++) { if (array[i] == nso) { return i; } } return -1; } /// <summary> /// Returns the last object contained in this array. /// </summary> /// <returns>The value of the highest index in the array.</returns> public NSObject LastObject() { return array[array.Count - 1]; } /// <summary> /// Returns a new array containing only the values stored at the given /// indices. The values are sorted by their index. /// </summary> /// <returns>The new array containing the objects stored at the given indices.</returns> /// <param name="indexes">The indices of the objects.</param> public NSObject[] ObjectsAtIndexes(params int[] indexes) { NSObject[] result = new NSObject[indexes.Length]; Array.Sort(indexes); for (int i = 0; i < indexes.Length; i++) result[i] = array[indexes[i]]; return result; } /// <summary> /// Determines whether the specified <see cref="System.Object"/> is equal to the current <see cref="PList.NSArray"/>. /// </summary> /// <param name="obj">The <see cref="System.Object"/> to compare with the current <see cref="PList.NSArray"/>.</param> /// <returns><c>true</c> if the specified <see cref="System.Object"/> is equal to the current /// <see cref="PList.NSArray"/>; otherwise, <c>false</c>.</returns> public override bool Equals(Object obj) { if (obj.GetType().Equals(typeof(NSArray))) { return ArrayEquals(((NSArray)obj).GetArray(), this.GetArray()); } else { NSObject nso = NSObject.Wrap(obj); if (nso.GetType().Equals(typeof(NSArray))) { return ArrayEquals(((NSArray)nso).GetArray(), this.GetArray()); } } return false; } /// <summary> /// Serves as a hash function for a <see cref="PList.NSArray"/> object. /// </summary> /// <returns>A hash code for this instance that is suitable for use in hashing algorithms and data structures such as a /// hash table.</returns> public override int GetHashCode() { int hash = 7; hash = 89 * hash + array.GetHashCode(); return hash; } internal override void ToXml(StringBuilder xml, int level) { Indent(xml, level); xml.Append("<array>"); xml.Append(NSObject.NEWLINE); foreach (NSObject o in array) { o.ToXml(xml, level + 1); xml.Append(NSObject.NEWLINE); } Indent(xml, level); xml.Append("</array>"); } internal override void AssignIDs(BinaryPropertyListWriter outPlist) { base.AssignIDs(outPlist); foreach (NSObject obj in array) { obj.AssignIDs(outPlist); } } internal override void ToBinary(BinaryPropertyListWriter outPlist) { outPlist.WriteIntHeader(0xA, array.Count); foreach (NSObject obj in array) { outPlist.WriteID(outPlist.GetID(obj)); } } /// <summary> /// <para> /// Generates a valid ASCII property list which has this NSArray as its /// root object. /// </para><para> /// The generated property list complies with the format as /// described in https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/PropertyLists/OldStylePlists/OldStylePLists.html /// Property List Programming Guide - Old-Style ASCII Property Lists. /// </para> /// </summary> /// <returns>ASCII representation of this object.</returns> public string ToASCIIPropertyList() { StringBuilder ascii = new StringBuilder(); ToASCII(ascii, 0); ascii.Append(NEWLINE); return ascii.ToString(); } /// <summary> /// <para> /// Generates a valid ASCII property list in GnuStep format which has this /// NSArray as its root object. /// </para><para> /// The generated property list complies with /// the format as described in http://www.gnustep.org/resources/documentation/Developer/Base/Reference/NSPropertyList.html /// GnuStep - NSPropertyListSerialization class documentation. /// </para> /// </summary> /// <returns>GnuStep ASCII representation of this object.</returns> public string ToGnuStepASCIIPropertyList() { StringBuilder ascii = new StringBuilder(); ToASCIIGnuStep(ascii, 0); ascii.Append(NEWLINE); return ascii.ToString(); } internal override void ToASCII(StringBuilder ascii, int level) { Indent(ascii, level); ascii.Append(ASCIIPropertyListParser.ARRAY_BEGIN_TOKEN); int indexOfLastNewLine = ascii.ToString().LastIndexOf(NEWLINE, StringComparison.Ordinal); for (int i = 0; i < array.Count; i++) { Type objClass = array[i].GetType(); if ((objClass.Equals(typeof(NSDictionary)) || objClass.Equals(typeof(NSArray)) || objClass.Equals(typeof(NSData))) && indexOfLastNewLine != ascii.Length) { ascii.Append(NEWLINE); indexOfLastNewLine = ascii.Length; array[i].ToASCII(ascii, level + 1); } else { if (i != 0) ascii.Append(" "); array[i].ToASCII(ascii, 0); } if (i != array.Count - 1) ascii.Append(ASCIIPropertyListParser.ARRAY_ITEM_DELIMITER_TOKEN); if (ascii.Length - indexOfLastNewLine > ASCII_LINE_LENGTH) { ascii.Append(NEWLINE); indexOfLastNewLine = ascii.Length; } } ascii.Append(ASCIIPropertyListParser.ARRAY_END_TOKEN); } internal override void ToASCIIGnuStep(StringBuilder ascii, int level) { Indent(ascii, level); ascii.Append(ASCIIPropertyListParser.ARRAY_BEGIN_TOKEN); int indexOfLastNewLine = ascii.ToString().LastIndexOf(NEWLINE, StringComparison.Ordinal); for (int i = 0; i < array.Count; i++) { Type objClass = array[i].GetType(); if ((objClass.Equals(typeof(NSDictionary)) || objClass.Equals(typeof(NSArray)) || objClass.Equals(typeof(NSData))) && indexOfLastNewLine != ascii.Length) { ascii.Append(NEWLINE); indexOfLastNewLine = ascii.Length; array[i].ToASCIIGnuStep(ascii, level + 1); } else { if (i != 0) ascii.Append(" "); array[i].ToASCIIGnuStep(ascii, 0); } if (i != array.Count - 1) ascii.Append(ASCIIPropertyListParser.ARRAY_ITEM_DELIMITER_TOKEN); if (ascii.Length - indexOfLastNewLine > ASCII_LINE_LENGTH) { ascii.Append(NEWLINE); indexOfLastNewLine = ascii.Length; } } ascii.Append(ASCIIPropertyListParser.ARRAY_END_TOKEN); } /// <summary> /// Determines whether the specified <see cref="PList.NSObject"/> is equal to the current <see cref="PList.NSArray"/>. /// </summary> /// <param name="obj">The <see cref="PList.NSObject"/> to compare with the current <see cref="PList.NSArray"/>.</param> /// <returns><c>true</c> if the specified <see cref="PList.NSObject"/> is equal to the current /// <see cref="PList.NSArray"/>; otherwise, <c>false</c>.</returns> public override bool Equals(NSObject obj) { if (!(obj is NSArray)) return false; if (array.Count != ((NSArray)obj).array.Count) return false; for (int i = 0; i < array.Count; i++) if (!array[i].Equals(((NSArray)obj).ObjectAtIndex(i))) return false; return true; } } }
2881099/dotnetGen_sqlserver
7,396
GenMs/plist-cil/XmlPropertyListParser.cs
// plist-cil - An open source library to parse and generate property lists for .NET // Copyright (C) 2015 Natalia Portillo // // This code is based on: // plist - An open source library to parse and generate property lists // Copyright (C) 2014 Daniel Dreibrodt // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. using System.Xml; using System.Collections.Generic; using System.IO; using System.Linq; namespace PList { /// <summary> /// Parses XML property lists. /// </summary> /// @author Daniel Dreibrodt /// @author Natalia Portillo public static class XmlPropertyListParser { /// <summary> /// Parses a XML property list file. /// </summary> /// <param name="f">The XML property list file.</param> /// <returns>The root object of the property list. This is usually a NSDictionary but can also be a NSArray.</returns> public static NSObject Parse(FileInfo f) { XmlDocument doc = new XmlDocument(); using (Stream stream = f.OpenRead()) { doc.Load(stream); } return ParseDocument(doc); } /// <summary> /// Parses a XML property list from a byte array. /// </summary> /// <param name="bytes">The byte array containing the property list's data.</param> /// <returns>The root object of the property list. This is usually a NSDictionary but can also be a NSArray.</returns> public static NSObject Parse(byte[] bytes) { MemoryStream bis = new MemoryStream(bytes); return Parse(bis); } /// <summary> /// Parses a XML property list from an input stream. /// </summary> /// <param name="str">The input stream pointing to the property list's data.</param> /// <returns>The root object of the property list. This is usually a NSDictionary but can also be a NSArray.</returns> public static NSObject Parse(Stream str) { XmlDocument doc = new XmlDocument(); XmlReaderSettings settings = new XmlReaderSettings(); settings.DtdProcessing = DtdProcessing.Ignore; using (XmlReader reader = XmlReader.Create(str, settings)) { doc.Load(reader); } return ParseDocument(doc); } /// <summary> /// Parses the XML document by generating the appropriate NSObjects for each XML node. /// </summary> /// <returns>The root NSObject of the property list contained in the XML document.</returns> /// <param name="doc">The XML document.</param> static NSObject ParseDocument(XmlDocument doc) { var docType = doc.ChildNodes .OfType<XmlNode>() .SingleOrDefault(n => n.NodeType == XmlNodeType.DocumentType); if (docType == null) { if (!doc.DocumentElement.Name.Equals("plist")) { throw new XmlException("The given XML document is not a property list."); } } else if (!docType.Name.Equals("plist")) { throw new XmlException("The given XML document is not a property list."); } XmlNode rootNode; if (doc.DocumentElement.Name.Equals("plist")) { //Root element wrapped in plist tag List<XmlNode> rootNodes = FilterElementNodes(doc.DocumentElement.ChildNodes); if (rootNodes.Count == 0) throw new PropertyListFormatException("The given XML property list has no root element!"); if (rootNodes.Count == 1) rootNode = rootNodes[0]; else throw new PropertyListFormatException("The given XML property list has more than one root element!"); } else //Root NSObject not wrapped in plist-tag rootNode = doc.DocumentElement; return ParseObject(rootNode); } /// <summary> /// Parses a node in the XML structure and returns the corresponding NSObject /// </summary> /// <returns>The corresponding NSObject.</returns> /// <param name="n">The XML node.</param> static NSObject ParseObject(XmlNode n) { if (n.Name.Equals("dict")) { NSDictionary dict = new NSDictionary(); List<XmlNode> children = FilterElementNodes(n.ChildNodes); for (int i = 0; i < children.Count; i += 2) { XmlNode key = children[i]; XmlNode val = children[i + 1]; string keyString = GetNodeTextContents(key); dict.Add(keyString, ParseObject(val)); } return dict; } if (n.Name.Equals("array")) { List<XmlNode> children = FilterElementNodes(n.ChildNodes); NSArray array = new NSArray(children.Count); for (int i = 0; i < children.Count; i++) { array.Add(ParseObject(children[i])); } return array; } if (n.Name.Equals("true")) return new NSNumber(true); if (n.Name.Equals("false")) return new NSNumber(false); if (n.Name.Equals("integer")) return new NSNumber(GetNodeTextContents(n), NSNumber.INTEGER); if (n.Name.Equals("real")) return new NSNumber(GetNodeTextContents(n), NSNumber.REAL); if (n.Name.Equals("string")) return new NSString(GetNodeTextContents(n)); if (n.Name.Equals("data")) return new NSData(GetNodeTextContents(n)); return n.Name.Equals("date") ? new NSDate(GetNodeTextContents(n)) : null; } /// <summary> /// Returns all element nodes that are contained in a list of nodes. /// </summary> /// <returns>The sublist containing only nodes representing actual elements.</returns> /// <param name="list">The list of nodes to search.</param> static List<XmlNode> FilterElementNodes(XmlNodeList list) { List<XmlNode> result = new List<XmlNode>(); foreach (XmlNode child in list) if (child.NodeType == XmlNodeType.Element) result.Add(child); return result; } /// <summary> /// Returns a node's text content. /// This method will return the text value represented by the node's direct children. /// If the given node is a TEXT or CDATA node, then its value is returned. /// </summary> /// <returns>The node's text content.</returns> /// <param name="n">The node.</param> static string GetNodeTextContents(XmlNode n) { if (n.NodeType == XmlNodeType.Text || n.NodeType == XmlNodeType.CDATA) { string content = n.Value; //This concatenates any adjacent text/cdata/entity nodes return content ?? ""; } if (n.HasChildNodes) { XmlNodeList children = n.ChildNodes; foreach (XmlNode child in children) { //Skip any non-text nodes, like comments or entities if (child.NodeType == XmlNodeType.Text || child.NodeType == XmlNodeType.CDATA) { string content = child.Value; //This concatenates any adjacent text/cdata/entity nodes return content ?? ""; } } return ""; } return ""; } } }
2881099/dotnetGen_postgresql
16,482
GenPg/FastExcel/FastExcel.cs
using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Linq; using System.Text; using System.Xml.Linq; namespace FastExcel { public partial class FastExcel : IDisposable { public FileInfo ExcelFile { get; private set; } public FileInfo TemplateFile { get; private set; } public bool ReadOnly { get; private set; } internal SharedStrings SharedStrings { get; set; } internal ZipArchive Archive { get; set; } private bool UpdateExisting { get; set; } private bool _filesChecked; /// <summary> /// Maximum sheet number, obtained when a sheet is added /// </summary> internal int MaxSheetNumber { get; set; } /// <summary> /// A list of worksheet indexs to delete /// </summary> private List<int> DeleteWorksheets { get; set; } /// <summary> /// A list of worksheet indexs to insert /// </summary> private List<WorksheetAddSettings> AddWorksheets { get; set; } /// <summary> /// Update an existing excel file /// </summary> /// <param name="excelFile">location of an existing excel file</param> public FastExcel(FileInfo excelFile, bool readOnly = false) : this(null, excelFile, true, readOnly) { } /// <summary> /// Create a new excel file from a template /// </summary> /// <param name="templateFile">template location</param> /// <param name="excelFile">location of where a new excel file will be saved to</param> public FastExcel(FileInfo templateFile, FileInfo excelFile) : this(templateFile, excelFile, false, false) { } private FastExcel(FileInfo templateFile, FileInfo excelFile, bool updateExisting, bool readOnly = false) { this.TemplateFile = templateFile; this.ExcelFile = excelFile; this.UpdateExisting = updateExisting; this.ReadOnly = readOnly; CheckFiles(); } internal void PrepareArchive(bool openSharedStrings = true) { if (this.Archive == null) { if (this.ReadOnly) { Archive = ZipFile.Open(this.ExcelFile.FullName, ZipArchiveMode.Read); } else { Archive = ZipFile.Open(this.ExcelFile.FullName, ZipArchiveMode.Update); } } // Get Strings file if (this.SharedStrings == null && openSharedStrings) { this.SharedStrings = new SharedStrings(this.Archive); } } /// <summary> /// Ensure files are ready for use /// </summary> internal void CheckFiles() { if (_filesChecked) { return; } if (this.UpdateExisting) { if (this.ExcelFile == null) { throw new Exception("No input file name was supplied"); } else if (!this.ExcelFile.Exists) { throw new Exception(string.Format("Input file '{0}' does not exist", this.ExcelFile.FullName)); } } else { if (this.TemplateFile == null) { throw new Exception("No Template file was supplied"); } else if (!this.TemplateFile.Exists) { throw new FileNotFoundException(string.Format("Template file '{0}' was not found", this.TemplateFile.FullName)); } if (this.ExcelFile == null) { throw new Exception("No Ouput file name was supplied"); } else if (this.ExcelFile.Exists) { throw new Exception(string.Format("Output file '{0}' already exists", this.ExcelFile.FullName)); } } _filesChecked = true; } /// <summary> /// Update xl/_rels/workbook.xml.rels file /// </summary> private void UpdateRelations(bool ensureStrings) { if (!(ensureStrings || (this.DeleteWorksheets != null && this.DeleteWorksheets.Any()) || (this.AddWorksheets != null && this.AddWorksheets.Any()))) { // Nothing to update return; } using (Stream stream = this.Archive.GetEntry("xl/_rels/workbook.xml.rels").Open()) { XDocument document = XDocument.Load(stream); if (document == null) { //TODO error } bool update = false; List<XElement> relationshipElements = document.Descendants().Where(d => d.Name.LocalName == "Relationship").ToList(); int id = relationshipElements.Count; if (ensureStrings) { //Ensure SharedStrings XElement relationshipElement = (from element in relationshipElements from attribute in element.Attributes() where attribute.Name == "Target" && attribute.Value.Equals("sharedStrings.xml", StringComparison.CurrentCultureIgnoreCase) select element).FirstOrDefault(); if (relationshipElement == null) { relationshipElement = new XElement(document.Root.GetDefaultNamespace() + "Relationship"); relationshipElement.Add(new XAttribute("Target", "sharedStrings.xml")); relationshipElement.Add(new XAttribute("Type", "http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings")); relationshipElement.Add(new XAttribute("Id", string.Format("rId{0}", ++id))); document.Root.Add(relationshipElement); update = true; } } // Remove all references to sheets from this file as they are not requried if ((this.DeleteWorksheets != null && this.DeleteWorksheets.Any()) || (this.AddWorksheets != null && this.AddWorksheets.Any())) { XElement[] worksheetElements = (from element in relationshipElements from attribute in element.Attributes() where attribute.Name == "Type" && attribute.Value == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" select element).ToArray(); for (int i = worksheetElements.Length - 1; i > 0; i--) { worksheetElements[i].Remove(); update = true; } } if (update) { // Set the stream to the start stream.Position = 0; // Clear the stream stream.SetLength(0); // Open the stream so we can override all content of the sheet StreamWriter streamWriter = new StreamWriter(stream, Encoding.UTF8); document.Save(streamWriter); streamWriter.Flush(); } } } /// <summary> /// Update xl/workbook.xml file /// </summary> private string[] UpdateWorkbook() { if (!(this.DeleteWorksheets != null && this.DeleteWorksheets.Any() || (this.AddWorksheets != null && this.AddWorksheets.Any()))) { // Nothing to update return null; } List<string> sheetNames = new List<string>(); using (Stream stream = this.Archive.GetEntry("xl/workbook.xml").Open()) { XDocument document = XDocument.Load(stream); if (document == null) { throw new Exception("Unable to load workbook.xml"); } bool update = false; RenameAndRebildWorksheetProperties((from sheet in document.Descendants() where sheet.Name.LocalName == "sheet" select sheet).ToArray()); if (update) { // Re number sheet ids XNamespace r = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"; int id = 1; foreach (XElement sheetElement in (from sheet in document.Descendants() where sheet.Name.LocalName == "sheet" select sheet)) { sheetElement.SetAttributeValue(r + "id", string.Format("rId{0}", id++)); sheetNames.Add(sheetElement.Attribute("name").Value); } //Set the stream to the start stream.Position = 0; // Clear the stream stream.SetLength(0); // Open the stream so we can override all content of the sheet StreamWriter streamWriter = new StreamWriter(stream); document.Save(streamWriter); streamWriter.Flush(); } } return sheetNames.ToArray(); } /// <summary> /// If sheets have been added or deleted, sheets need to be renamed /// </summary> private void RenameAndRebildWorksheetProperties(XElement[] sheets) { if (!((this.DeleteWorksheets != null && this.DeleteWorksheets.Any()) || (this.AddWorksheets != null && this.AddWorksheets.Any()))) { // Nothing to update return; } XNamespace r = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"; List<WorksheetProperties> sheetProperties = (from sheet in sheets select new WorksheetProperties () { SheetId = int.Parse(sheet.Attribute("sheetId").Value), Name = sheet.Attribute("name").Value, CurrentIndex = int.Parse(sheet.Attribute(r + "id").Value) }).ToList(); // Remove deleted worksheets to sheetProperties if (this.DeleteWorksheets != null && this.DeleteWorksheets.Any()) { foreach (var item in this.DeleteWorksheets) { WorksheetProperties sheetToDelete = (from sp in sheetProperties where sp.SheetId == item select sp).FirstOrDefault(); if (sheetToDelete != null) { sheetProperties.Remove(sheetToDelete); } } } // Add new worksheets to sheetProperties if (this.AddWorksheets != null && this.AddWorksheets.Any()) { // Add the sheets in reverse, this will add them correctly with less work foreach (var item in this.AddWorksheets.Reverse<WorksheetAddSettings>()) { WorksheetProperties previousSheet = (from sp in sheetProperties where sp.SheetId == item.InsertAfterSheetId select sp).FirstOrDefault(); if (previousSheet == null) { throw new Exception(string.Format("Sheet name {0} cannot be added because the insertAfterSheetNumber or insertAfterSheetName is now invalid", item.Name)); } WorksheetProperties newWorksheet = new WorksheetProperties(); newWorksheet.SheetId = item.SheetId; newWorksheet.Name = item.Name; newWorksheet.CurrentIndex = 0;// TODO Something?? sheetProperties.Insert(sheetProperties.IndexOf(previousSheet), newWorksheet); } } int index = 1; foreach (WorksheetProperties worksheet in sheetProperties) { if (worksheet.CurrentIndex != index) { ZipArchiveEntry entry = this.Archive.GetEntry(Worksheet.GetFileName(worksheet.CurrentIndex)); if (entry == null) { // TODO better message throw new Exception("Worksheets could not be rebuilt"); } } index++; } } public class WorksheetProperties { public int CurrentIndex { get; set; } public int SheetId { get; set; } public string Name { get; set; } } /// <summary> /// Update [Content_Types].xml file /// </summary> private void UpdateContentTypes(bool ensureStrings) { if (!(ensureStrings || (this.DeleteWorksheets != null && this.DeleteWorksheets.Any()) || (this.AddWorksheets != null && this.AddWorksheets.Any()))) { // Nothing to update return; } using (Stream stream = this.Archive.GetEntry("[Content_Types].xml").Open()) { XDocument document = XDocument.Load(stream); if (document == null) { //TODO error } bool update = false; List<XElement> overrideElements = document.Descendants().Where(d => d.Name.LocalName == "Override").ToList(); //Ensure SharedStrings if (ensureStrings) { XElement overrideElement = (from element in overrideElements from attribute in element.Attributes() where attribute.Name == "PartName" && attribute.Value.Equals("/xl/sharedStrings.xml", StringComparison.CurrentCultureIgnoreCase) select element).FirstOrDefault(); if (overrideElement == null) { overrideElement = new XElement(document.Root.GetDefaultNamespace() + "Override"); overrideElement.Add(new XAttribute("ContentType", "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml")); overrideElement.Add(new XAttribute("PartName", "/xl/sharedStrings.xml")); document.Root.Add(overrideElement); update = true; } } if (this.DeleteWorksheets != null && this.DeleteWorksheets.Any()) { foreach (var item in this.DeleteWorksheets) { // the file name is different for each xml file string fileName = string.Format("/xl/worksheets/sheet{0}.xml", item); XElement overrideElement = (from element in overrideElements from attribute in element.Attributes() where attribute.Name == "PartName" && attribute.Value == fileName select element).FirstOrDefault(); if (overrideElement != null) { overrideElement.Remove(); update = true; } } } if (this.AddWorksheets != null && this.AddWorksheets.Any()) { foreach (var item in this.AddWorksheets) { // the file name is different for each xml file string fileName = string.Format("/xl/worksheets/sheet{0}.xml", item.SheetId); XElement overrideElement = new XElement(document.Root.GetDefaultNamespace() + "Override"); overrideElement.Add(new XAttribute("ContentType", "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml")); overrideElement.Add(new XAttribute("PartName", fileName)); document.Root.Add(overrideElement); update = true; } } if (update) { // Set the stream to the start stream.Position = 0; // Clear the stream stream.SetLength(0); // Open the stream so we can override all content of the sheet StreamWriter streamWriter = new StreamWriter(stream, Encoding.UTF8); document.Save(streamWriter); streamWriter.Flush(); } } } /// <summary> /// Update docProps/app.xml file /// </summary> private void UpdateDocPropsApp(string[] sheetNames) { /* if (sheetNames == null || !sheetNames.Any()) { // Nothing to update return; } using (Stream stream = this.Archive.GetEntry("docProps/app.xml ").Open()) { XDocument document = XDocument.Load(stream); if (document == null) { throw new Exception("Unable to load app.xml"); } // Update TilesOfParts // Update HeadingPairs if (this.AddWorksheets != null && this.AddWorksheets.Any()) { // Add the sheets in reverse, this will add them correctly with less work foreach (var item in this.AddWorksheets.Reverse<WorksheetAddSettings>()) { XElement previousSheetElement = (from sheet in document.Descendants() where sheet.Name.LocalName == "sheet" from attribute in sheet.Attributes() where attribute.Name == "sheetId" && attribute.Value == item.InsertAfterIndex.ToString() select sheet).FirstOrDefault(); if (previousSheetElement == null) { throw new Exception(string.Format("Sheet name {0} cannot be added because the insertAfterSheetNumber or insertAfterSheetName is now invalid", item.Name)); } XElement newSheetElement = new XElement(document.Root.GetDefaultNamespace() + "sheet"); newSheetElement.Add(new XAttribute("name", item.Name)); newSheetElement.Add(new XAttribute("sheetId", item.Index)); previousSheetElement.AddAfterSelf(newSheetElement); update = true; } } if (update) { // Re number sheet ids XNamespace r = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"; int id = 1; foreach (XElement sheetElement in (from sheet in document.Descendants() where sheet.Name.LocalName == "sheet" select sheet)) { sheetElement.SetAttributeValue(r + "id", string.Format("rId{0}", id++)); } //Set the stream to the start stream.Position = 0; // Clear the stream stream.SetLength(0); // Open the stream so we can override all content of the sheet StreamWriter streamWriter = new StreamWriter(stream); document.Save(streamWriter); streamWriter.Flush(); } }*/ } /// <summary> /// Saves any pending changes to the Excel stream and adds/updates associated files if needed /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (this.Archive == null) { return; } if (this.Archive.Mode != ZipArchiveMode.Read) { bool ensureSharedStrings = false; // Update or create xl/sharedStrings.xml file if (this.SharedStrings != null) { ensureSharedStrings = this.SharedStrings.PendingChanges; this.SharedStrings.Write(); } // Update xl/_rels/workbook.xml.rels file UpdateRelations(ensureSharedStrings); // Update xl/workbook.xml file string[] sheetNames = UpdateWorkbook(); // Update [Content_Types].xml file UpdateContentTypes(ensureSharedStrings); // Update docProps/app.xml file UpdateDocPropsApp(sheetNames); } this.Archive.Dispose(); } } }
2881099/dotnetGen_sqlserver
2,575
GenMs/plist-cil/PropertyListException.cs
// plist-cil - An open source library to parse and generate property lists for .NET // Copyright (C) 2015 Natalia Portillo // Copyright (C) 2016 Quamotion // // This code is based on: // plist - An open source library to parse and generate property lists // Copyright (C) 2014 Daniel Dreibrodt // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. using System; using System.Runtime.Serialization; namespace PList { /// <summary> /// The exception that is thrown when an property list file could not be processed correctly. /// </summary> public class PropertyListException : Exception { /// <summary> /// Initializes a new instance of the <see cref="PropertyListException"/> class. /// </summary> public PropertyListException() { } /// <summary> /// Initializes a new instance of the <see cref="PropertyListException"/> class. /// </summary> /// <param name="message"> /// The error message that explains the reason for the exception. /// </param> public PropertyListException(string message) : base(message) { } /// <summary> /// Initializes a new instance of the <see cref="PropertyListException"/> class. /// </summary> /// <param name="message"> /// The error message that explains the reason for the exception. /// </param> /// <param name="inner"> /// The exception that is the cause of the current exception, or <see langword="null"/> /// if no inner exception is specified. /// </param> public PropertyListException(string message, Exception inner) : base(message, inner) { } } }
27182812/ChatGLM-LLaMA-chinese-insturct
12,762
src/transformers/models/efficientnet/convert_efficientnet_to_pytorch.py
# coding=utf-8 # Copyright 2023 The HuggingFace Inc. team. # # 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. """Convert EfficientNet checkpoints from the original repository. URL: https://github.com/keras-team/keras/blob/v2.11.0/keras/applications/efficientnet.py""" import argparse import json import os import numpy as np import PIL import requests import tensorflow.keras.applications.efficientnet as efficientnet import torch from huggingface_hub import hf_hub_download from PIL import Image from tensorflow.keras.preprocessing import image from transformers import ( EfficientNetConfig, EfficientNetForImageClassification, EfficientNetImageProcessor, ) from transformers.utils import logging logging.set_verbosity_info() logger = logging.get_logger(__name__) model_classes = { "b0": efficientnet.EfficientNetB0, "b1": efficientnet.EfficientNetB1, "b2": efficientnet.EfficientNetB2, "b3": efficientnet.EfficientNetB3, "b4": efficientnet.EfficientNetB4, "b5": efficientnet.EfficientNetB5, "b6": efficientnet.EfficientNetB6, "b7": efficientnet.EfficientNetB7, } CONFIG_MAP = { "b0": { "hidden_dim": 1280, "width_coef": 1.0, "depth_coef": 1.0, "image_size": 224, "dropout_rate": 0.2, "dw_padding": [], }, "b1": { "hidden_dim": 1280, "width_coef": 1.0, "depth_coef": 1.1, "image_size": 240, "dropout_rate": 0.2, "dw_padding": [16], }, "b2": { "hidden_dim": 1408, "width_coef": 1.1, "depth_coef": 1.2, "image_size": 260, "dropout_rate": 0.3, "dw_padding": [5, 8, 16], }, "b3": { "hidden_dim": 1536, "width_coef": 1.2, "depth_coef": 1.4, "image_size": 300, "dropout_rate": 0.3, "dw_padding": [5, 18], }, "b4": { "hidden_dim": 1792, "width_coef": 1.4, "depth_coef": 1.8, "image_size": 380, "dropout_rate": 0.4, "dw_padding": [6], }, "b5": { "hidden_dim": 2048, "width_coef": 1.6, "depth_coef": 2.2, "image_size": 456, "dropout_rate": 0.4, "dw_padding": [13, 27], }, "b6": { "hidden_dim": 2304, "width_coef": 1.8, "depth_coef": 2.6, "image_size": 528, "dropout_rate": 0.5, "dw_padding": [31], }, "b7": { "hidden_dim": 2560, "width_coef": 2.0, "depth_coef": 3.1, "image_size": 600, "dropout_rate": 0.5, "dw_padding": [18], }, } def get_efficientnet_config(model_name): config = EfficientNetConfig() config.hidden_dim = CONFIG_MAP[model_name]["hidden_dim"] config.width_coefficient = CONFIG_MAP[model_name]["width_coef"] config.depth_coefficient = CONFIG_MAP[model_name]["depth_coef"] config.image_size = CONFIG_MAP[model_name]["image_size"] config.dropout_rate = CONFIG_MAP[model_name]["dropout_rate"] config.depthwise_padding = CONFIG_MAP[model_name]["dw_padding"] repo_id = "huggingface/label-files" filename = "imagenet-1k-id2label.json" config.num_labels = 1000 id2label = json.load(open(hf_hub_download(repo_id, filename, repo_type="dataset"), "r")) id2label = {int(k): v for k, v in id2label.items()} config.id2label = id2label config.label2id = {v: k for k, v in id2label.items()} return config # We will verify our results on an image of cute cats def prepare_img(): url = "http://images.cocodataset.org/val2017/000000039769.jpg" im = Image.open(requests.get(url, stream=True).raw) return im def convert_image_processor(model_name): size = CONFIG_MAP[model_name]["image_size"] preprocessor = EfficientNetImageProcessor( size={"height": size, "width": size}, image_mean=[0.485, 0.456, 0.406], image_std=[0.47853944, 0.4732864, 0.47434163], do_center_crop=False, ) return preprocessor # here we list all keys to be renamed (original name on the left, our name on the right) def rename_keys(original_param_names): block_names = [v.split("_")[0].split("block")[1] for v in original_param_names if v.startswith("block")] block_names = sorted(set(block_names)) num_blocks = len(block_names) block_name_mapping = {b: str(i) for b, i in zip(block_names, range(num_blocks))} rename_keys = [] rename_keys.append(("stem_conv/kernel:0", "embeddings.convolution.weight")) rename_keys.append(("stem_bn/gamma:0", "embeddings.batchnorm.weight")) rename_keys.append(("stem_bn/beta:0", "embeddings.batchnorm.bias")) rename_keys.append(("stem_bn/moving_mean:0", "embeddings.batchnorm.running_mean")) rename_keys.append(("stem_bn/moving_variance:0", "embeddings.batchnorm.running_var")) for b in block_names: hf_b = block_name_mapping[b] rename_keys.append((f"block{b}_expand_conv/kernel:0", f"encoder.blocks.{hf_b}.expansion.expand_conv.weight")) rename_keys.append((f"block{b}_expand_bn/gamma:0", f"encoder.blocks.{hf_b}.expansion.expand_bn.weight")) rename_keys.append((f"block{b}_expand_bn/beta:0", f"encoder.blocks.{hf_b}.expansion.expand_bn.bias")) rename_keys.append( (f"block{b}_expand_bn/moving_mean:0", f"encoder.blocks.{hf_b}.expansion.expand_bn.running_mean") ) rename_keys.append( (f"block{b}_expand_bn/moving_variance:0", f"encoder.blocks.{hf_b}.expansion.expand_bn.running_var") ) rename_keys.append( (f"block{b}_dwconv/depthwise_kernel:0", f"encoder.blocks.{hf_b}.depthwise_conv.depthwise_conv.weight") ) rename_keys.append((f"block{b}_bn/gamma:0", f"encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.weight")) rename_keys.append((f"block{b}_bn/beta:0", f"encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.bias")) rename_keys.append( (f"block{b}_bn/moving_mean:0", f"encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.running_mean") ) rename_keys.append( (f"block{b}_bn/moving_variance:0", f"encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.running_var") ) rename_keys.append((f"block{b}_se_reduce/kernel:0", f"encoder.blocks.{hf_b}.squeeze_excite.reduce.weight")) rename_keys.append((f"block{b}_se_reduce/bias:0", f"encoder.blocks.{hf_b}.squeeze_excite.reduce.bias")) rename_keys.append((f"block{b}_se_expand/kernel:0", f"encoder.blocks.{hf_b}.squeeze_excite.expand.weight")) rename_keys.append((f"block{b}_se_expand/bias:0", f"encoder.blocks.{hf_b}.squeeze_excite.expand.bias")) rename_keys.append( (f"block{b}_project_conv/kernel:0", f"encoder.blocks.{hf_b}.projection.project_conv.weight") ) rename_keys.append((f"block{b}_project_bn/gamma:0", f"encoder.blocks.{hf_b}.projection.project_bn.weight")) rename_keys.append((f"block{b}_project_bn/beta:0", f"encoder.blocks.{hf_b}.projection.project_bn.bias")) rename_keys.append( (f"block{b}_project_bn/moving_mean:0", f"encoder.blocks.{hf_b}.projection.project_bn.running_mean") ) rename_keys.append( (f"block{b}_project_bn/moving_variance:0", f"encoder.blocks.{hf_b}.projection.project_bn.running_var") ) rename_keys.append(("top_conv/kernel:0", "encoder.top_conv.weight")) rename_keys.append(("top_bn/gamma:0", "encoder.top_bn.weight")) rename_keys.append(("top_bn/beta:0", "encoder.top_bn.bias")) rename_keys.append(("top_bn/moving_mean:0", "encoder.top_bn.running_mean")) rename_keys.append(("top_bn/moving_variance:0", "encoder.top_bn.running_var")) key_mapping = {} for item in rename_keys: if item[0] in original_param_names: key_mapping[item[0]] = "efficientnet." + item[1] key_mapping["predictions/kernel:0"] = "classifier.weight" key_mapping["predictions/bias:0"] = "classifier.bias" return key_mapping def replace_params(hf_params, tf_params, key_mapping): for key, value in tf_params.items(): if "normalization" in key: continue hf_key = key_mapping[key] if "_conv" in key and "kernel" in key: new_hf_value = torch.from_numpy(value).permute(3, 2, 0, 1) elif "depthwise_kernel" in key: new_hf_value = torch.from_numpy(value).permute(2, 3, 0, 1) elif "kernel" in key: new_hf_value = torch.from_numpy(np.transpose(value)) else: new_hf_value = torch.from_numpy(value) # Replace HF parameters with original TF model parameters assert hf_params[hf_key].shape == new_hf_value.shape hf_params[hf_key].copy_(new_hf_value) @torch.no_grad() def convert_efficientnet_checkpoint(model_name, pytorch_dump_folder_path, save_model, push_to_hub): """ Copy/paste/tweak model's weights to our EfficientNet structure. """ # Load original model original_model = model_classes[model_name]( include_top=True, weights="imagenet", input_tensor=None, input_shape=None, pooling=None, classes=1000, classifier_activation="softmax", ) tf_params = original_model.trainable_variables tf_non_train_params = original_model.non_trainable_variables tf_params = {param.name: param.numpy() for param in tf_params} for param in tf_non_train_params: tf_params[param.name] = param.numpy() tf_param_names = list(tf_params.keys()) # Load HuggingFace model config = get_efficientnet_config(model_name) hf_model = EfficientNetForImageClassification(config).eval() hf_params = hf_model.state_dict() # Create src-to-dst parameter name mapping dictionary print("Converting parameters...") key_mapping = rename_keys(tf_param_names) replace_params(hf_params, tf_params, key_mapping) # Initialize preprocessor and preprocess input image preprocessor = convert_image_processor(model_name) inputs = preprocessor(images=prepare_img(), return_tensors="pt") # HF model inference hf_model.eval() with torch.no_grad(): outputs = hf_model(**inputs) hf_logits = outputs.logits.detach().numpy() # Original model inference original_model.trainable = False image_size = CONFIG_MAP[model_name]["image_size"] img = prepare_img().resize((image_size, image_size), resample=PIL.Image.NEAREST) x = image.img_to_array(img) x = np.expand_dims(x, axis=0) original_logits = original_model.predict(x) # Check whether original and HF model outputs match -> np.allclose assert np.allclose(original_logits, hf_logits, atol=1e-3), "The predicted logits are not the same." print("Model outputs match!") if save_model: # Create folder to save model if not os.path.isdir(pytorch_dump_folder_path): os.mkdir(pytorch_dump_folder_path) # Save converted model and feature extractor hf_model.save_pretrained(pytorch_dump_folder_path) preprocessor.save_pretrained(pytorch_dump_folder_path) if push_to_hub: # Push model and feature extractor to hub print(f"Pushing converted {model_name} to the hub...") model_name = f"efficientnet-{model_name}" preprocessor.push_to_hub(model_name) hf_model.push_to_hub(model_name) if __name__ == "__main__": parser = argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default="b0", type=str, help="Version name of the EfficientNet model you want to convert, select from [b0, b1, b2, b3, b4, b5, b6, b7].", ) parser.add_argument( "--pytorch_dump_folder_path", default="hf_model", type=str, help="Path to the output PyTorch model directory.", ) parser.add_argument("--save_model", action="store_true", help="Save model to local") parser.add_argument("--push_to_hub", action="store_true", help="Push model and feature extractor to the hub") args = parser.parse_args() convert_efficientnet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.save_model, args.push_to_hub)
2881099/dotnetGen_postgresql
4,088
GenPg/FastExcel/Cell.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Xml.Linq; namespace FastExcel { /// <summary> /// Contains the actual value /// </summary> public class Cell { /// <summary> /// Column Numnber (Starts at 1) /// </summary> public int ColumnNumber { get; set; } /// <summary> /// The value that is stored /// </summary> public object Value { get; set; } /// <summary> /// Create a new Cell /// </summary> /// <param name="columnNumber">Column number starting at 1</param> /// <param name="value">Cell Value</param> public Cell(int columnNumber, object value) { if (columnNumber <= 0) { throw new Exception("Column numbers starting at 1"); } this.ColumnNumber = columnNumber; this.Value = value; } /// <summary> /// Create a new Cell /// </summary> /// <param name="cellElement">Cell</param> /// <param name="sharedStrings">The collection of shared strings used by this document</param> public Cell(XElement cellElement, SharedStrings sharedStrings) { bool isTextRow = (from a in cellElement.Attributes("t") where a.Value == "s" select a).Any(); string columnName = (from a in cellElement.Attributes("r") select a.Value).FirstOrDefault(); this.ColumnNumber = GetExcelColumnNumber(columnName); if (isTextRow) { this.Value = sharedStrings.GetString(cellElement.Value); } else { this.Value = cellElement.Value; } } internal StringBuilder ToXmlString(SharedStrings sharedStrings, int rowNumber) { StringBuilder cell = new StringBuilder(); if (this.Value != null) { bool isString = false; object value = this.Value; if (this.Value is int) { isString = false; } else if (this.Value is double) { isString = false; } else if (this.Value is string) { isString = true; } if (isString) { value = sharedStrings.AddString(value.ToString()); } cell.AppendFormat("<c r=\"{0}{1}\"{2}>", GetExcelColumnName(this.ColumnNumber), rowNumber, (isString ? " t=\"s\"" : string.Empty)); cell.AppendFormat("<v>{0}</v>", value); cell.Append("</c>"); } return cell; } //http://stackoverflow.com/questions/181596/how-to-convert-a-column-number-eg-127-into-an-excel-column-eg-aa /// <summary> /// Convert Column Number into Column Name - Character(s) eg 1-A, 2-B /// </summary> /// <param name="columnNumber">Column Number</param> /// <returns>Column Name - Character(s)</returns> public static string GetExcelColumnName(int columnNumber) { int dividend = columnNumber; string columnName = String.Empty; int modulo; while (dividend > 0) { modulo = (dividend - 1) % 26; columnName = string.Concat(Convert.ToChar(65 + modulo), columnName); dividend = (int)((dividend - modulo) / 26); } return columnName; } //http://stackoverflow.com/questions/181596/how-to-convert-a-column-number-eg-127-into-an-excel-column-eg-aa /// <summary> /// Covert Column Name - Character(s) into a Column Number eg A-1, B-2, A1 - 1, B9 - 2 /// </summary> /// <param name="columnName">Column Name - Character(s) optinally with the Row Number</param> /// <param name="includesRowNumber">Specify if the row number is included</param> /// <returns>Column Number</returns> public static int GetExcelColumnNumber(string columnName, bool includesRowNumber = true) { if (includesRowNumber) { columnName = Regex.Replace(columnName, @"\d", ""); } int[] digits = new int[columnName.Length]; for (int i = 0; i < columnName.Length; ++i) { digits[i] = Convert.ToInt32(columnName[i]) - 64; } int mul = 1; int res = 0; for (int pos = digits.Length - 1; pos >= 0; --pos) { res += digits[pos] * mul; mul *= 26; } return res; } /// <summary> /// Merge the parameter cell into this cell /// </summary> /// <param name="cell">Cell to merge</param> public void Merge(Cell cell) { this.Value = cell.Value; } } }
2881099/dotnetGen_postgresql
2,198
GenPg/FastExcel/FastExcel.Add.cs
using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; namespace FastExcel { public partial class FastExcel { /// <summary> /// Append new worksheet /// </summary> /// <param name="worksheet">New worksheet</param> public void Add(Worksheet worksheet) { this.Add(worksheet, null, null); } public void Add(Worksheet worksheet, int insertAfterSheetNumber) { this.Add(worksheet, insertAfterSheetNumber, null); } public void Add(Worksheet worksheet, string insertAfterSheetName) { this.Add(worksheet, null, insertAfterSheetName); } private void Add(Worksheet worksheet, int? insertAfterSheetNumber = null, string insertAfterSheetName = null) { CheckFiles(); PrepareArchive(true); worksheet.ValidateNewWorksheet(this, insertAfterSheetNumber, insertAfterSheetName); if (this.AddWorksheets == null) { this.AddWorksheets = new List<WorksheetAddSettings>(); } this.AddWorksheets.Add(worksheet.AddSettings); if (!this.ReadOnly) { throw new Exception("FastExcel is in ReadOnly mode so cannot perform a write"); } // Check if ExistingHeadingRows will be overridden by the dataset if (worksheet.ExistingHeadingRows != 0 && worksheet.Rows.Where(r => r.RowNumber <= worksheet.ExistingHeadingRows).Any()) { throw new Exception("Existing Heading Rows was specified but some or all will be overridden by data rows. Check DataSet.Row.RowNumber against ExistingHeadingRows"); } using (StreamWriter streamWriter = null)//new StreamWriter(this.Archive.CreateEntry(worksheet.FileName).Open())) { streamWriter.Write(worksheet.Headers); if (!worksheet.Template) { worksheet.Headers = null; } this.SharedStrings.ReadWriteMode = true; // Add Rows foreach (Row row in worksheet.Rows) { streamWriter.Write(row.ToXmlString(this.SharedStrings)); } this.SharedStrings.ReadWriteMode = false; //Add Footers streamWriter.Write(worksheet.Footers); if (!worksheet.Template) { worksheet.Footers = null; } streamWriter.Flush(); } } } }
2881099/dotnetGen_postgresql
1,413
GenPg/FastExcel/FastExcel.Worksheets.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; namespace FastExcel { public partial class FastExcel { private Worksheet[] _worksheets; /// <summary> /// List of worksheets, loaded on first access of property /// </summary> public Worksheet[] Worksheets { get { if (_worksheets != null) { return _worksheets; } else { _worksheets = GetWorksheetProperties(); return _worksheets; } } } private Worksheet[] GetWorksheetProperties() { CheckFiles(); PrepareArchive(false); var worksheets = new List<Worksheet>(); using (Stream stream = this.Archive.GetEntry("xl/workbook.xml").Open()) { XDocument document = XDocument.Load(stream); if (document == null) { throw new Exception("Unable to load workbook.xml"); } List<XElement> sheetsElements = document.Descendants().Where(d => d.Name.LocalName == "sheet").ToList(); foreach (var sheetElement in sheetsElements) { var worksheet = new Worksheet(this); worksheet.Index = sheetsElements.IndexOf(sheetElement) + 1; worksheet.Name = (from attribute in sheetElement.Attributes() where attribute.Name == "name" select attribute.Value).FirstOrDefault(); worksheets.Add(worksheet); } } return worksheets.ToArray(); } } }
27182812/ChatGLM-LLaMA-chinese-insturct
24,389
src/transformers/models/efficientnet/modeling_efficientnet.py
# coding=utf-8 # Copyright 2023 Google Research, Inc. and The HuggingFace Inc. team. 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. """ PyTorch EfficientNet model.""" import math from typing import Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACT2FN from ...modeling_outputs import ( BaseModelOutputWithNoAttention, BaseModelOutputWithPoolingAndNoAttention, ImageClassifierOutputWithNoAttention, ) from ...modeling_utils import PreTrainedModel from ...utils import ( add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging, ) from .configuration_efficientnet import EfficientNetConfig logger = logging.get_logger(__name__) # General docstring _CONFIG_FOR_DOC = "EfficientNetConfig" # Base docstring _CHECKPOINT_FOR_DOC = "google/efficientnet-b7" _EXPECTED_OUTPUT_SHAPE = [1, 768, 7, 7] # Image classification docstring _IMAGE_CLASS_CHECKPOINT = "google/efficientnet-b7" _IMAGE_CLASS_EXPECTED_OUTPUT = "tabby, tabby cat" EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST = [ "google/efficientnet-b7", # See all EfficientNet models at https://huggingface.co/models?filter=efficientnet ] EFFICIENTNET_START_DOCSTRING = r""" This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior. Parameters: config ([`EfficientNetConfig`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights. """ EFFICIENTNET_INPUTS_DOCSTRING = r""" Args: pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`): Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`AutoImageProcessor.__call__`] for details. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. """ def round_filters(config: EfficientNetConfig, num_channels: int): r""" Round number of filters based on depth multiplier. """ divisor = config.depth_divisor num_channels *= config.width_coefficient new_dim = max(divisor, int(num_channels + divisor / 2) // divisor * divisor) # Make sure that round down does not go down by more than 10%. if new_dim < 0.9 * num_channels: new_dim += divisor return int(new_dim) def correct_pad(kernel_size: Union[int, Tuple], adjust: bool = True): r""" Utility function to get the tuple padding value for the depthwise convolution. Args: kernel_size (`int` or `tuple`): Kernel size of the convolution layers. adjust (`bool`, *optional*, defaults to `True`): Adjusts padding value to apply to right and bottom sides of the input. """ if isinstance(kernel_size, int): kernel_size = (kernel_size, kernel_size) correct = (kernel_size[0] // 2, kernel_size[1] // 2) if adjust: return (correct[1] - 1, correct[1], correct[0] - 1, correct[0]) else: return (correct[1], correct[1], correct[0], correct[0]) class EfficientNetEmbeddings(nn.Module): r""" A module that corresponds to the stem module of the original work. """ def __init__(self, config: EfficientNetConfig): super().__init__() self.out_dim = round_filters(config, 32) self.padding = nn.ZeroPad2d(padding=(0, 1, 0, 1)) self.convolution = nn.Conv2d( config.num_channels, self.out_dim, kernel_size=3, stride=2, padding="valid", bias=False ) self.batchnorm = nn.BatchNorm2d(self.out_dim, eps=config.batch_norm_eps, momentum=config.batch_norm_momentum) self.activation = ACT2FN[config.hidden_act] def forward(self, pixel_values: torch.Tensor) -> torch.Tensor: features = self.padding(pixel_values) features = self.convolution(features) features = self.batchnorm(features) features = self.activation(features) return features class EfficientNetDepthwiseConv2d(nn.Conv2d): def __init__( self, in_channels, depth_multiplier=1, kernel_size=3, stride=1, padding=0, dilation=1, bias=True, padding_mode="zeros", ): out_channels = in_channels * depth_multiplier super().__init__( in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, stride=stride, padding=padding, dilation=dilation, groups=in_channels, bias=bias, padding_mode=padding_mode, ) class EfficientNetExpansionLayer(nn.Module): r""" This corresponds to the expansion phase of each block in the original implementation. """ def __init__(self, config: EfficientNetConfig, in_dim: int, out_dim: int, stride: int): super().__init__() self.expand_conv = nn.Conv2d( in_channels=in_dim, out_channels=out_dim, kernel_size=1, padding="same", bias=False, ) self.expand_bn = nn.BatchNorm2d(num_features=out_dim, eps=config.batch_norm_eps) self.expand_act = ACT2FN[config.hidden_act] def forward(self, hidden_states: torch.FloatTensor) -> torch.Tensor: # Expand phase hidden_states = self.expand_conv(hidden_states) hidden_states = self.expand_bn(hidden_states) hidden_states = self.expand_act(hidden_states) return hidden_states class EfficientNetDepthwiseLayer(nn.Module): r""" This corresponds to the depthwise convolution phase of each block in the original implementation. """ def __init__( self, config: EfficientNetConfig, in_dim: int, stride: int, kernel_size: int, adjust_padding: bool, ): super().__init__() self.stride = stride conv_pad = "valid" if self.stride == 2 else "same" padding = correct_pad(kernel_size, adjust=adjust_padding) self.depthwise_conv_pad = nn.ZeroPad2d(padding=padding) self.depthwise_conv = EfficientNetDepthwiseConv2d( in_dim, kernel_size=kernel_size, stride=stride, padding=conv_pad, bias=False ) self.depthwise_norm = nn.BatchNorm2d( num_features=in_dim, eps=config.batch_norm_eps, momentum=config.batch_norm_momentum ) self.depthwise_act = ACT2FN[config.hidden_act] def forward(self, hidden_states: torch.FloatTensor) -> torch.Tensor: # Depthwise convolution if self.stride == 2: hidden_states = self.depthwise_conv_pad(hidden_states) hidden_states = self.depthwise_conv(hidden_states) hidden_states = self.depthwise_norm(hidden_states) hidden_states = self.depthwise_act(hidden_states) return hidden_states class EfficientNetSqueezeExciteLayer(nn.Module): r""" This corresponds to the Squeeze and Excitement phase of each block in the original implementation. """ def __init__(self, config: EfficientNetConfig, in_dim: int, expand_dim: int, expand: bool = False): super().__init__() self.dim = expand_dim if expand else in_dim self.dim_se = max(1, int(in_dim * config.squeeze_expansion_ratio)) self.squeeze = nn.AdaptiveAvgPool2d(output_size=1) self.reduce = nn.Conv2d( in_channels=self.dim, out_channels=self.dim_se, kernel_size=1, padding="same", ) self.expand = nn.Conv2d( in_channels=self.dim_se, out_channels=self.dim, kernel_size=1, padding="same", ) self.act_reduce = ACT2FN[config.hidden_act] self.act_expand = nn.Sigmoid() def forward(self, hidden_states: torch.FloatTensor) -> torch.Tensor: inputs = hidden_states hidden_states = self.squeeze(hidden_states) hidden_states = self.reduce(hidden_states) hidden_states = self.act_reduce(hidden_states) hidden_states = self.expand(hidden_states) hidden_states = self.act_expand(hidden_states) hidden_states = torch.mul(inputs, hidden_states) return hidden_states class EfficientNetFinalBlockLayer(nn.Module): r""" This corresponds to the final phase of each block in the original implementation. """ def __init__( self, config: EfficientNetConfig, in_dim: int, out_dim: int, stride: int, drop_rate: float, id_skip: bool ): super().__init__() self.apply_dropout = stride == 1 and not id_skip self.project_conv = nn.Conv2d( in_channels=in_dim, out_channels=out_dim, kernel_size=1, padding="same", bias=False, ) self.project_bn = nn.BatchNorm2d( num_features=out_dim, eps=config.batch_norm_eps, momentum=config.batch_norm_momentum ) self.dropout = nn.Dropout(p=drop_rate) def forward(self, embeddings: torch.FloatTensor, hidden_states: torch.FloatTensor) -> torch.Tensor: hidden_states = self.project_conv(hidden_states) hidden_states = self.project_bn(hidden_states) if self.apply_dropout: hidden_states = self.dropout(hidden_states) hidden_states = hidden_states + embeddings return hidden_states class EfficientNetBlock(nn.Module): r""" This corresponds to the expansion and depthwise convolution phase of each block in the original implementation. Args: config ([`EfficientNetConfig`]): Model configuration class. in_dim (`int`): Number of input channels. out_dim (`int`): Number of output channels. stride (`int`): Stride size to be used in convolution layers. expand_ratio (`int`): Expand ratio to set the output dimensions for the expansion and squeeze-excite layers. kernel_size (`int`): Kernel size for the depthwise convolution layer. drop_rate (`float`): Dropout rate to be used in the final phase of each block. id_skip (`bool`): Whether to apply dropout and sum the final hidden states with the input embeddings during the final phase of each block. Set to `True` for the first block of each stage. adjust_padding (`bool`): Whether to apply padding to only right and bottom side of the input kernel before the depthwise convolution operation, set to `True` for inputs with odd input sizes. """ def __init__( self, config: EfficientNetConfig, in_dim: int, out_dim: int, stride: int, expand_ratio: int, kernel_size: int, drop_rate: float, id_skip: bool, adjust_padding: bool, ): super().__init__() self.expand_ratio = expand_ratio self.expand = True if self.expand_ratio != 1 else False expand_in_dim = in_dim * expand_ratio if self.expand: self.expansion = EfficientNetExpansionLayer( config=config, in_dim=in_dim, out_dim=expand_in_dim, stride=stride ) self.depthwise_conv = EfficientNetDepthwiseLayer( config=config, in_dim=expand_in_dim if self.expand else in_dim, stride=stride, kernel_size=kernel_size, adjust_padding=adjust_padding, ) self.squeeze_excite = EfficientNetSqueezeExciteLayer( config=config, in_dim=in_dim, expand_dim=expand_in_dim, expand=self.expand ) self.projection = EfficientNetFinalBlockLayer( config=config, in_dim=expand_in_dim if self.expand else in_dim, out_dim=out_dim, stride=stride, drop_rate=drop_rate, id_skip=id_skip, ) def forward(self, hidden_states: torch.FloatTensor) -> torch.Tensor: embeddings = hidden_states # Expansion and depthwise convolution phase if self.expand_ratio != 1: hidden_states = self.expansion(hidden_states) hidden_states = self.depthwise_conv(hidden_states) # Squeeze and excite phase hidden_states = self.squeeze_excite(hidden_states) hidden_states = self.projection(embeddings, hidden_states) return hidden_states class EfficientNetEncoder(nn.Module): r""" Forward propogates the embeddings through each EfficientNet block. Args: config ([`EfficientNetConfig`]): Model configuration class. """ def __init__(self, config: EfficientNetConfig): super().__init__() self.config = config self.depth_coefficient = config.depth_coefficient def round_repeats(repeats): # Round number of block repeats based on depth multiplier. return int(math.ceil(self.depth_coefficient * repeats)) num_base_blocks = len(config.in_channels) num_blocks = sum(round_repeats(n) for n in config.num_block_repeats) curr_block_num = 0 blocks = [] for i in range(num_base_blocks): in_dim = round_filters(config, config.in_channels[i]) out_dim = round_filters(config, config.out_channels[i]) stride = config.strides[i] kernel_size = config.kernel_sizes[i] expand_ratio = config.expand_ratios[i] for j in range(round_repeats(config.num_block_repeats[i])): id_skip = True if j == 0 else False stride = 1 if j > 0 else stride in_dim = out_dim if j > 0 else in_dim adjust_padding = False if curr_block_num in config.depthwise_padding else True drop_rate = config.drop_connect_rate * curr_block_num / num_blocks block = EfficientNetBlock( config=config, in_dim=in_dim, out_dim=out_dim, stride=stride, kernel_size=kernel_size, expand_ratio=expand_ratio, drop_rate=drop_rate, id_skip=id_skip, adjust_padding=adjust_padding, ) blocks.append(block) curr_block_num += 1 self.blocks = nn.ModuleList(blocks) self.top_conv = nn.Conv2d( in_channels=out_dim, out_channels=round_filters(config, 1280), kernel_size=1, padding="same", bias=False, ) self.top_bn = nn.BatchNorm2d( num_features=config.hidden_dim, eps=config.batch_norm_eps, momentum=config.batch_norm_momentum ) self.top_activation = ACT2FN[config.hidden_act] def forward( self, hidden_states: torch.FloatTensor, output_hidden_states: Optional[bool] = False, return_dict: Optional[bool] = True, ) -> BaseModelOutputWithNoAttention: all_hidden_states = (hidden_states,) if output_hidden_states else None for block in self.blocks: hidden_states = block(hidden_states) if output_hidden_states: all_hidden_states += (hidden_states,) hidden_states = self.top_conv(hidden_states) hidden_states = self.top_bn(hidden_states) hidden_states = self.top_activation(hidden_states) if not return_dict: return tuple(v for v in [hidden_states, all_hidden_states] if v is not None) return BaseModelOutputWithNoAttention( last_hidden_state=hidden_states, hidden_states=all_hidden_states, ) class EfficientNetPreTrainedModel(PreTrainedModel): """ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models. """ config_class = EfficientNetConfig base_model_prefix = "efficientnet" main_input_name = "pixel_values" supports_gradient_checkpointing = True def _init_weights(self, module): """Initialize the weights""" if isinstance(module, (nn.Linear, nn.Conv2d)): # Slightly different from the TF version which uses truncated_normal for initialization # cf https://github.com/pytorch/pytorch/pull/5617 module.weight.data.normal_(mean=0.0, std=self.config.initializer_range) if module.bias is not None: module.bias.data.zero_() elif isinstance(module, nn.LayerNorm): module.bias.data.zero_() module.weight.data.fill_(1.0) def _set_gradient_checkpointing(self, module, value=False): if isinstance(module, EfficientNetBlock): module.gradient_checkpointing = value @add_start_docstrings( "The bare EfficientNet model outputting raw features without any specific head on top.", EFFICIENTNET_START_DOCSTRING, ) class EfficientNetModel(EfficientNetPreTrainedModel): def __init__(self, config: EfficientNetConfig): super().__init__(config) self.config = config self.embeddings = EfficientNetEmbeddings(config) self.encoder = EfficientNetEncoder(config) # Final pooling layer if config.pooling_type == "mean": self.pooler = nn.AvgPool2d(config.hidden_dim, ceil_mode=True) elif config.pooling_type == "max": self.pooler = nn.MaxPool2d(config.hidden_dim, ceil_mode=True) else: raise ValueError(f"config.pooling must be one of ['mean', 'max'] got {config.pooling}") # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(EFFICIENTNET_INPUTS_DOCSTRING) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC, output_type=BaseModelOutputWithPoolingAndNoAttention, config_class=_CONFIG_FOR_DOC, modality="vision", expected_output=_EXPECTED_OUTPUT_SHAPE, ) def forward( self, pixel_values: torch.FloatTensor = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, ) -> Union[Tuple, BaseModelOutputWithPoolingAndNoAttention]: output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) return_dict = return_dict if return_dict is not None else self.config.use_return_dict if pixel_values is None: raise ValueError("You have to specify pixel_values") embedding_output = self.embeddings(pixel_values) encoder_outputs = self.encoder( embedding_output, output_hidden_states=output_hidden_states, return_dict=return_dict, ) # Apply pooling last_hidden_state = encoder_outputs[0] pooled_output = self.pooler(last_hidden_state) # Reshape (batch_size, 1280, 1 , 1) -> (batch_size, 1280) pooled_output = pooled_output.reshape(pooled_output.shape[:2]) if not return_dict: return (last_hidden_state, pooled_output) + encoder_outputs[1:] return BaseModelOutputWithPoolingAndNoAttention( last_hidden_state=last_hidden_state, pooler_output=pooled_output, hidden_states=encoder_outputs.hidden_states, ) @add_start_docstrings( """ EfficientNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for ImageNet. """, EFFICIENTNET_START_DOCSTRING, ) class EfficientNetForImageClassification(EfficientNetPreTrainedModel): def __init__(self, config): super().__init__(config) self.num_labels = config.num_labels self.config = config self.efficientnet = EfficientNetModel(config) # Classifier head self.dropout = nn.Dropout(p=config.dropout_rate) self.classifier = nn.Linear(config.hidden_dim, self.num_labels) if self.num_labels > 0 else nn.Identity() self.classifier_act = nn.Softmax(dim=1) # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(EFFICIENTNET_INPUTS_DOCSTRING) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT, output_type=ImageClassifierOutputWithNoAttention, config_class=_CONFIG_FOR_DOC, expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT, ) def forward( self, pixel_values: torch.FloatTensor = None, labels: Optional[torch.LongTensor] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, ) -> Union[Tuple, ImageClassifierOutputWithNoAttention]: r""" labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*): Labels for computing the image classification/regression loss. Indices should be in `[0, ..., config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If `config.num_labels > 1` a classification loss is computed (Cross-Entropy). """ return_dict = return_dict if return_dict is not None else self.config.use_return_dict outputs = self.efficientnet(pixel_values, output_hidden_states=output_hidden_states, return_dict=return_dict) pooled_output = outputs.pooler_output if return_dict else outputs[1] pooled_output = self.dropout(pooled_output) logits = self.classifier(pooled_output) logits = self.classifier_act(logits) loss = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: self.config.problem_type = "regression" elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): self.config.problem_type = "single_label_classification" else: self.config.problem_type = "multi_label_classification" if self.config.problem_type == "regression": loss_fct = MSELoss() if self.num_labels == 1: loss = loss_fct(logits.squeeze(), labels.squeeze()) else: loss = loss_fct(logits, labels) elif self.config.problem_type == "single_label_classification": loss_fct = CrossEntropyLoss() loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1)) elif self.config.problem_type == "multi_label_classification": loss_fct = BCEWithLogitsLoss() loss = loss_fct(logits, labels) if not return_dict: output = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return ImageClassifierOutputWithNoAttention( loss=loss, logits=logits, hidden_states=outputs.hidden_states, )
2881099/dotnetGen_postgresql
1,325
GenPg/FastExcel/FastExcel.Delete.cs
using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; namespace FastExcel { public partial class FastExcel { /// <summary> /// Deletes the selected sheet Note:delete happens on Dispose /// </summary> /// <param name="sheetNumber">sheet number, starts at 1</param> public void Delete(int sheetNumber) { this.Delete(sheetNumber, null); } /// <summary> /// Deletes the selected sheet Note:delete happens on Dispose /// </summary> /// <param name="sheetName">Worksheet name</param> public void Delete(string sheetName) { this.Update(null, sheetName); } private void Delete(int? sheetNumber = null, string sheetName = null) { CheckFiles(); PrepareArchive(false); // Get worksheet details Worksheet worksheet = new Worksheet(); worksheet.GetWorksheetProperties(this, sheetNumber, sheetName); // Delete the file if (!string.IsNullOrEmpty(worksheet.FileName)) { ZipArchiveEntry entry = this.Archive.GetEntry(worksheet.FileName); if (entry != null) { entry.Delete(); } if (this.DeleteWorksheets == null) { this.DeleteWorksheets = new List<int>(); } this.DeleteWorksheets.Add(worksheet.Index); } } } }
2881099/dotnetGen_sqlserver
3,798
GenMs/plist-cil/UID.cs
// plist-cil - An open source library to parse and generate property lists for .NET // Copyright (C) 2015 Natalia Portillo // // This code is based on: // plist - An open source library to parse and generate property lists // Copyright (C) 2014 Daniel Dreibrodt // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. using System; using System.Text; namespace PList { /// <summary> /// An UID. Only found in binary property lists that are keyed archives. /// </summary> /// @author Daniel Dreibrodt /// @author Natalia Portillo public class UID : NSObject { readonly byte[] bytes; readonly string name; /// <summary> /// Initializes a new instance of the <see cref="PList.UID"/> class. /// </summary> /// <param name="name">Name.</param> /// <param name="bytes">Bytes.</param> public UID(String name, byte[] bytes) { this.name = name; this.bytes = bytes; } /// <summary> /// Gets the bytes. /// </summary> /// <value>The bytes.</value> public byte[] Bytes { get { return bytes; } } /// <summary> /// Gets the name. /// </summary> /// <value>The name.</value> public string Name { get { return name; } } /// <summary> /// There is no XML representation specified for UIDs. /// In this implementation UIDs are represented as strings in the XML output. /// </summary> /// <param name="xml">The xml StringBuilder</param> /// <param name="level">The indentation level</param> internal override void ToXml(StringBuilder xml, int level) { Indent(xml, level); xml.Append("<string>"); foreach (byte b in bytes) xml.Append(String.Format("{0:x2}", b)); xml.Append("</string>"); } internal override void ToBinary(BinaryPropertyListWriter outPlist) { outPlist.Write(0x80 + bytes.Length - 1); outPlist.Write(bytes); } internal override void ToASCII(StringBuilder ascii, int level) { Indent(ascii, level); ascii.Append("\""); foreach (byte b in bytes) ascii.Append(String.Format("{0:x2}", b)); ascii.Append("\""); } internal override void ToASCIIGnuStep(StringBuilder ascii, int level) { ToASCII(ascii, level); } /// <summary> /// Determines whether the specified <see cref="PList.NSObject"/> is equal to the current <see cref="PList.UID"/>. /// </summary> /// <param name="obj">The <see cref="PList.NSObject"/> to compare with the current <see cref="PList.UID"/>.</param> /// <returns><c>true</c> if the specified <see cref="PList.NSObject"/> is equal to the current /// <see cref="PList.UID"/>; otherwise, <c>false</c>.</returns> public override bool Equals(NSObject obj) { if (!(obj is UID)) return false; if (((UID)obj).Name != name) return false; return ArrayEquals(((UID)obj).Bytes, bytes); } } }
2881099/dotnetGen_sqlserver
21,071
GenMs/plist-cil/BinaryPropertyListParser.cs
// plist-cil - An open source library to parse and generate property lists for .NET // Copyright (C) 2015 Natalia Portillo // // This code is based on: // plist - An open source library to parse and generate property lists // Copyright (C) 2014 Daniel Dreibrodt // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. using System; using System.Text; using System.IO; namespace PList { /// <summary> /// <para> /// Parses property lists that are in Apple's binary format. /// Use this class when you are sure about the format of the property list. /// Otherwise use the PropertyListParser class. /// </para><para> /// Parsing is done by calling the static <see cref="Parse(byte[])"/>, /// <see cref="Parse(FileInfo)"/> and <see cref="Parse(Stream)"/> methods. /// </para> /// </summary> /// @author Daniel Dreibrodt /// @author Natalia Portillo public class BinaryPropertyListParser { /// <summary> /// Major version of the property list format /// </summary> int majorVersion; /// <summary> /// Minor version of the property list format /// </summary> int minorVersion; /// <summary> /// Property list in bytes /// </summary> byte[] bytes; /// <summary> /// Length of an object reference in bytes /// </summary> int objectRefSize; /// <summary> /// The table holding the information at which offset each object is found /// </summary> int[] offsetTable; /// <summary> /// Protected constructor so that instantiation is fully controlled by the /// static parse methods. /// </summary> /// <see cref="Parse(byte[])"/> protected BinaryPropertyListParser() { } /// <summary> /// Parses a binary property list from a byte array. /// </summary> /// <param name="data">The binary property list's data.</param> /// <returns>The root object of the property list. This is usually a NSDictionary but can also be a NSArray.</returns> /// <exception cref="PropertyListFormatException">When the property list's format could not be parsed.</exception> public static NSObject Parse(byte[] data) { BinaryPropertyListParser parser = new BinaryPropertyListParser(); return parser.DoParse(data); } /// <summary> /// Parses a binary property list from a byte array. /// </summary> /// <returns>The root object of the property list. This is usually a NSDictionary but can also be a NSArray.</returns> /// <param name="data">The binary property list's data.</param> /// <exception cref="PropertyListFormatException">When the property list's format could not be parsed.</exception> NSObject DoParse(byte[] data) { bytes = data; string magic = Encoding.ASCII.GetString(CopyOfRange(bytes, 0, 8)); if (!magic.StartsWith("bplist", StringComparison.Ordinal)) { throw new PropertyListFormatException("The given data is no binary property list. Wrong magic bytes: " + magic); } majorVersion = magic[6] - 0x30; //ASCII number minorVersion = magic[7] - 0x30; //ASCII number // 0.0 - OS X Tiger and earlier // 0.1 - Leopard // 0.? - Snow Leopard // 1.5 - Lion // 2.0 - Snow Lion if (majorVersion > 0) { // Version 1.0+ is not even supported by OS X's own parser throw new PropertyListFormatException("Unsupported binary property list format: v" + majorVersion + "." + minorVersion + ". " + "Version 1.0 and later are not yet supported."); } /* * Handle trailer, last 32 bytes of the file */ byte[] trailer = CopyOfRange(bytes, bytes.Length - 32, bytes.Length); //6 null bytes (index 0 to 5) int offsetSize = (int)ParseUnsignedInt(trailer, 6, 7); objectRefSize = (int)ParseUnsignedInt(trailer, 7, 8); int numObjects = (int)ParseUnsignedInt(trailer, 8, 16); int topObject = (int)ParseUnsignedInt(trailer, 16, 24); int offsetTableOffset = (int)ParseUnsignedInt(trailer, 24, 32); /* * Handle offset table */ offsetTable = new int[numObjects]; for (int i = 0; i < numObjects; i++) { byte[] offsetBytes = CopyOfRange(bytes, offsetTableOffset + i * offsetSize, offsetTableOffset + (i + 1) * offsetSize); offsetTable[i] = (int)ParseUnsignedInt(offsetBytes); } return ParseObject(topObject); } /// <summary> /// Parses a binary property list from an input stream. /// </summary> /// <param name="fs">The input stream that points to the property list's data.</param> /// <returns>The root object of the property list. This is usually a NSDictionary but can also be a NSArray.</returns> /// <exception cref="PropertyListFormatException">When the property list's format could not be parsed.</exception> public static NSObject Parse(Stream fs) { //Read all bytes into a list byte[] buf = PropertyListParser.ReadAll(fs); // Don't close the stream - that would be the responisibility of code that class // Parse return Parse(buf); } /// <summary> /// Parses a binary property list file. /// </summary> /// <param name="f">The binary property list file</param> /// <returns>The root object of the property list. This is usually a NSDictionary but can also be a NSArray.</returns> /// <exception cref="PropertyListFormatException">When the property list's format could not be parsed.</exception> public static NSObject Parse(FileInfo f) { return Parse(f.OpenRead()); } /// <summary> /// Parses an object inside the currently parsed binary property list. /// For the format specification check /// <a href="http://www.opensource.apple.com/source/CF/CF-855.17/CFBinaryPList.c"> /// Apple's binary property list parser implementation</a>. /// </summary> /// <returns>The parsed object.</returns> /// <param name="obj">The object ID.</param> /// <exception cref="PropertyListFormatException">When the property list's format could not be parsed.</exception> NSObject ParseObject(int obj) { int offset = offsetTable[obj]; byte type = bytes[offset]; int objType = (type & 0xF0) >> 4; //First 4 bits int objInfo = (type & 0x0F); //Second 4 bits switch (objType) { case 0x0: { //Simple switch (objInfo) { case 0x0: { //null object (v1.0 and later) return null; } case 0x8: { //false return new NSNumber(false); } case 0x9: { //true return new NSNumber(true); } case 0xC: { //URL with no base URL (v1.0 and later) //TODO Implement binary URL parsing (not yet even implemented in Core Foundation as of revision 855.17) break; } case 0xD: { //URL with base URL (v1.0 and later) //TODO Implement binary URL parsing (not yet even implemented in Core Foundation as of revision 855.17) break; } case 0xE: { //16-byte UUID (v1.0 and later) //TODO Implement binary UUID parsing (not yet even implemented in Core Foundation as of revision 855.17) break; } case 0xF: { //filler byte return null; } } break; } case 0x1: { //integer int length = (int)Math.Pow(2, objInfo); return new NSNumber(CopyOfRange(bytes, offset + 1, offset + 1 + length), NSNumber.INTEGER); } case 0x2: { //real int length = (int)Math.Pow(2, objInfo); return new NSNumber(CopyOfRange(bytes, offset + 1, offset + 1 + length), NSNumber.REAL); } case 0x3: { //Date if (objInfo != 0x3) { throw new PropertyListFormatException("The given binary property list contains a date object of an unknown type (" + objInfo + ")"); } return new NSDate(CopyOfRange(bytes, offset + 1, offset + 9)); } case 0x4: { //Data int[] lengthAndOffset = ReadLengthAndOffset(objInfo, offset); int length = lengthAndOffset[0]; int dataoffset = lengthAndOffset[1]; return new NSData(CopyOfRange(bytes, offset + dataoffset, offset + dataoffset + length)); } case 0x5: { //ASCII String int[] lengthAndOffset = ReadLengthAndOffset(objInfo, offset); int length = lengthAndOffset[0]; //Each character is 1 byte int stroffset = lengthAndOffset[1]; return new NSString(CopyOfRange(bytes, offset + stroffset, offset + stroffset + length), "ASCII"); } case 0x6: { //UTF-16-BE String int[] lengthAndOffset = ReadLengthAndOffset(objInfo, offset); int length = lengthAndOffset[0]; int stroffset = lengthAndOffset[1]; //UTF-16 characters can have variable length, but the Core Foundation reference implementation //assumes 2 byte characters, thus only covering the Basic Multilingual Plane length *= 2; return new NSString(CopyOfRange(bytes, offset + stroffset, offset + stroffset + length), "UTF-16BE"); } case 0x7: { //UTF-8 string (v1.0 and later) int[] lengthAndOffset = ReadLengthAndOffset(objInfo, offset); int strOffset = lengthAndOffset[1]; int characters = lengthAndOffset[0]; //UTF-8 characters can have variable length, so we need to calculate the byte length dynamically //by reading the UTF-8 characters one by one int length = CalculateUtf8StringLength(bytes, offset + strOffset, characters); return new NSString(CopyOfRange(bytes, offset + strOffset, offset + strOffset + length), "UTF-8"); } case 0x8: { //UID (v1.0 and later) int length = objInfo + 1; return new UID(obj.ToString(), CopyOfRange(bytes, offset + 1, offset + 1 + length)); } case 0xA: { //Array int[] lengthAndOffset = ReadLengthAndOffset(objInfo, offset); int length = lengthAndOffset[0]; int arrayOffset = lengthAndOffset[1]; NSArray array = new NSArray(length); for (int i = 0; i < length; i++) { int objRef = (int)ParseUnsignedInt(CopyOfRange(bytes, offset + arrayOffset + i * objectRefSize, offset + arrayOffset + (i + 1) * objectRefSize)); array.Add(ParseObject(objRef)); } return array; } case 0xB: { //Ordered set (v1.0 and later) int[] lengthAndOffset = ReadLengthAndOffset(objInfo, offset); int length = lengthAndOffset[0]; int contentOffset = lengthAndOffset[1]; NSSet set = new NSSet(true); for (int i = 0; i < length; i++) { int objRef = (int)ParseUnsignedInt(CopyOfRange(bytes, offset + contentOffset + i * objectRefSize, offset + contentOffset + (i + 1) * objectRefSize)); set.AddObject(ParseObject(objRef)); } return set; } case 0xC: { //Set (v1.0 and later) int[] lengthAndOffset = ReadLengthAndOffset(objInfo, offset); int length = lengthAndOffset[0]; int contentOffset = lengthAndOffset[1]; NSSet set = new NSSet(); for (int i = 0; i < length; i++) { int objRef = (int)ParseUnsignedInt(CopyOfRange(bytes, offset + contentOffset + i * objectRefSize, offset + contentOffset + (i + 1) * objectRefSize)); set.AddObject(ParseObject(objRef)); } return set; } case 0xD: { //Dictionary int[] lengthAndOffset = ReadLengthAndOffset(objInfo, offset); int length = lengthAndOffset[0]; int contentOffset = lengthAndOffset[1]; //System.out.println("Parsing dictionary #"+obj); NSDictionary dict = new NSDictionary(); for (int i = 0; i < length; i++) { int keyRef = (int)ParseUnsignedInt(CopyOfRange(bytes, offset + contentOffset + i * objectRefSize, offset + contentOffset + (i + 1) * objectRefSize)); int valRef = (int)ParseUnsignedInt(CopyOfRange(bytes, offset + contentOffset + (length * objectRefSize) + i * objectRefSize, offset + contentOffset + (length * objectRefSize) + (i + 1) * objectRefSize)); NSObject key = ParseObject(keyRef); NSObject val = ParseObject(valRef); dict.Add(key.ToString(), val); } return dict; } default: { Console.WriteLine("WARNING: The given binary property list contains an object of unknown type (" + objType + ")"); break; } } return null; } /// <summary> /// Reads the length for arrays, sets and dictionaries. /// </summary> /// <returns>An array with the length two. First entry is the length, second entry the offset at which the content starts.</returns> /// <param name="objInfo">Object information byte.</param> /// <param name="offset">Offset in the byte array at which the object is located.</param> int[] ReadLengthAndOffset(int objInfo, int offset) { int lengthValue = objInfo; int offsetValue = 1; if (objInfo == 0xF) { int int_type = bytes[offset + 1]; int intType = (int_type & 0xF0) >> 4; if (intType != 0x1) { Console.WriteLine("BinaryPropertyListParser: Length integer has an unexpected type" + intType + ". Attempting to parse anyway..."); } int intInfo = int_type & 0x0F; int intLength = (int)Math.Pow(2, intInfo); offsetValue = 2 + intLength; if (intLength < 3) { lengthValue = (int)ParseUnsignedInt(CopyOfRange(bytes, offset + 2, offset + 2 + intLength)); } else { // BigInteger is Little-Endian in .NET, swap the thing. // Also BigInteger is of .NET 4.0, maybe there's a better way to do it. byte[] bigEBigInteger = CopyOfRange(bytes, offset + 2, offset + 2 + intLength); byte[] litEBigInteger = new byte[bigEBigInteger.Length + 1]; for (int i = 0, j = bigEBigInteger.Length - 1; i < bigEBigInteger.Length && j >= 0; i++, j--) litEBigInteger[i] = bigEBigInteger[j]; litEBigInteger[litEBigInteger.Length - 1] = (byte)0x00; // Be sure to get unsigned BigInteger lengthValue = (int)new System.Numerics.BigInteger(litEBigInteger); } } return new[] { lengthValue, offsetValue }; } /// <summary> /// Calculates the length in bytes of the UTF-8 string. /// </summary> /// <returns>The UTF-8 string length.</returns> /// <param name="bytes">Array containing the UTF-8 string.</param> /// <param name="offset">Offset in the array where the UTF-8 string resides.</param> /// <param name="numCharacters">How many UTF-8 characters are in the string.</param> int CalculateUtf8StringLength(byte[] bytes, int offset, int numCharacters) { int length = 0; for (int i = 0; i < numCharacters; i++) { int tempOffset = offset + length; if (bytes.Length <= tempOffset) { //WARNING: Invalid UTF-8 string, fall back to length = number of characters return numCharacters; } if (bytes[tempOffset] < 0x80) { length++; } if (bytes[tempOffset] < 0xC2) { //Invalid value (marks continuation byte), fall back to length = number of characters return numCharacters; } else if (bytes[tempOffset] < 0xE0) { if ((bytes[tempOffset + 1] & 0xC0) != 0x80) { //Invalid continuation byte, fall back to length = number of characters return numCharacters; } length += 2; } else if (bytes[tempOffset] < 0xF0) { if ((bytes[tempOffset + 1] & 0xC0) != 0x80 || (bytes[tempOffset + 2] & 0xC0) != 0x80) { //Invalid continuation byte, fall back to length = number of characters return numCharacters; } length += 3; } else if (bytes[tempOffset] < 0xF5) { if ((bytes[tempOffset + 1] & 0xC0) != 0x80 || (bytes[tempOffset + 2] & 0xC0) != 0x80 || (bytes[tempOffset + 3] & 0xC0) != 0x80) { //Invalid continuation byte, fall back to length = number of characters return numCharacters; } length += 4; } } return length; } /// <summary> /// Parses an unsigned integers from a byte array. /// </summary> /// <returns>The byte array containing the unsigned integer.</returns> /// <param name="bytes">The unsigned integer represented by the given bytes.</param> public static long ParseUnsignedInt(byte[] bytes) { long l = 0; foreach (byte b in bytes) { l <<= 8; #pragma warning disable 675 l |= b & 0xFF; #pragma warning restore 675 } l &= 0xFFFFFFFFL; return l; } /// <summary> /// Parses an unsigned integer from a byte array. /// </summary> /// <returns>The unsigned integer represented by the given bytes.</returns> /// <param name="bytes">The byte array containing the unsigned integer.</param> /// <param name="startIndex">Beginning of the unsigned int in the byte array.</param> /// <param name="endIndex">End of the unsigned int in the byte array.</param> public static long ParseUnsignedInt(byte[] bytes, int startIndex, int endIndex) { long l = 0; for (int i = startIndex; i < endIndex; i++) { l <<= 8; #pragma warning disable 675 l |= bytes[i] & 0xFF; #pragma warning restore 675 } l &= 0xFFFFFFFFL; return l; } /// <summary> /// Parses a long from a (big-endian) byte array. /// </summary> /// <returns>The long integer represented by the given bytes.</returns> /// <param name="bytes">The bytes representing the long integer.</param> public static long ParseLong(byte[] bytes) { long l = 0; foreach (byte b in bytes) { l <<= 8; #pragma warning disable 675 l |= b & 0xFF; #pragma warning restore 675 } return l; } /// <summary> /// Parses a long from a (big-endian) byte array. /// </summary> /// <returns>The long integer represented by the given bytes.</returns> /// <param name="bytes">The bytes representing the long integer.</param> /// <param name="startIndex">Beginning of the long in the byte array.</param> /// <param name="endIndex">End of the long in the byte array.</param> public static long ParseLong(byte[] bytes, int startIndex, int endIndex) { long l = 0; for (int i = startIndex; i < endIndex; i++) { l <<= 8; #pragma warning disable 675 l |= bytes[i] & 0xFF; #pragma warning restore 675 } return l; } /// <summary> /// Parses a double from a (big-endian) byte array. /// </summary> /// <returns>The double represented by the given bytes.</returns> /// <param name="bytes">The bytes representing the double.</param> public static double ParseDouble(byte[] bytes) { if (bytes.Length == 8) return BitConverter.Int64BitsToDouble(ParseLong(bytes)); if (bytes.Length == 4) return BitConverter.ToSingle(BitConverter.GetBytes(ParseLong(bytes)), 0); throw new ArgumentException("bad byte array length " + bytes.Length); } /// <summary> /// Parses a double from a (big-endian) byte array. /// </summary> /// <returns>The double represented by the given bytes.</returns> /// <param name="bytes">The bytes representing the double.</param> /// <param name="startIndex">Beginning of the double in the byte array.</param> /// <param name="endIndex">End of the double in the byte array.</param> public static double ParseDouble(byte[] bytes, int startIndex, int endIndex) { if (endIndex - startIndex == 8) return BitConverter.Int64BitsToDouble(ParseLong(bytes, startIndex, endIndex)); if (endIndex - startIndex == 4) return BitConverter.ToSingle(BitConverter.GetBytes(ParseLong(bytes, startIndex, endIndex)), 0); throw new ArgumentException("endIndex (" + endIndex + ") - startIndex (" + startIndex + ") != 4 or 8"); } /// <summary> /// Copies a part of a byte array into a new array. /// </summary> /// <returns>The copied array.</returns> /// <param name="src">The source array.</param> /// <param name="startIndex">The index from which to start copying.</param> /// <param name="endIndex">The index until which to copy.</param> public static byte[] CopyOfRange(byte[] src, int startIndex, int endIndex) { int length = endIndex - startIndex; if (length < 0) { throw new ArgumentOutOfRangeException("startIndex (" + startIndex + ")" + " > endIndex (" + endIndex + ")"); } byte[] dest = new byte[length]; Array.Copy(src, startIndex, dest, 0, length); return dest; } } }
2881099/dotnetGen_postgresql
1,022
GenPg/FastExcel/FastExcel.Update.cs
using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; namespace FastExcel { public partial class FastExcel { /// <summary> /// Update the worksheet /// </summary> /// <param name="data">The worksheet</param> /// <param name="sheetNumber">eg 1,2,4</param> public void Update(Worksheet data, int sheetNumber) { this.Update(data, sheetNumber, null); } /// <summary> /// Update the worksheet /// </summary> /// <param name="data">The worksheet</param> /// <param name="sheetName">eg. Sheet1, Sheet2</param> public void Update(Worksheet data, string sheetName) { this.Update(data, null, sheetName); } private void Update(Worksheet data, int? sheetNumber = null, string sheetName = null) { CheckFiles(); PrepareArchive(); Worksheet currentData = this.Read(sheetNumber, sheetName); currentData.Merge(data); this.Write(currentData); } } }
2881099/dotnetGen_postgresql
5,412
GenPg/FastExcel/SharedStrings.cs
using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; namespace FastExcel { /// <summary> /// Read and update xl/sharedStrings.xml file /// </summary> public class SharedStrings { //A dictionary is a lot faster than a list private Dictionary<string, int> StringDictionary { get; set; } private Dictionary<int, string> StringArray { get; set; } private bool SharedStringsExists { get; set; } private ZipArchive ZipArchive { get; set; } public bool PendingChanges { get; private set; } public bool ReadWriteMode { get; set; } internal SharedStrings(ZipArchive archive) { this.ZipArchive = archive; this.SharedStringsExists = true; if (!this.ZipArchive.Entries.Where(entry => entry.FullName == "xl/sharedStrings.xml").Any()) { this.StringDictionary = new Dictionary<string, int>(); this.SharedStringsExists = false; return; } using (Stream stream = this.ZipArchive.GetEntry("xl/sharedStrings.xml").Open()) { if (stream == null) { this.StringDictionary = new Dictionary<string, int>(); this.SharedStringsExists = false; return; } XDocument document = XDocument.Load(stream); if (document == null) { this.StringDictionary = new Dictionary<string, int>(); this.SharedStringsExists = false; return; } int i = 0; this.StringDictionary = document.Descendants().Where(d => d.Name.LocalName == "t").Select(e => e.Value).ToDictionary(k=> k,v => i++); } } internal int AddString(string stringValue) { if (this.StringDictionary.ContainsKey(stringValue)) { return this.StringDictionary[stringValue]; } else { this.PendingChanges = true; this.StringDictionary.Add(stringValue, this.StringDictionary.Count); // Clear String Array used for retrieval if (this.ReadWriteMode && this.StringArray != null) { this.StringArray.Add(this.StringDictionary.Count - 1, stringValue); } else { this.StringArray = null; } return this.StringDictionary.Count - 1; } } internal void Write() { // Only update if changes were made if (!this.PendingChanges) { return; } StreamWriter streamWriter = null; try { if (this.SharedStringsExists) { streamWriter = new StreamWriter(this.ZipArchive.GetEntry("xl/sharedStrings.xml").Open()); } else { streamWriter = new StreamWriter(this.ZipArchive.CreateEntry("xl/sharedStrings.xml").Open()); } // TODO instead of saving the headers then writing them back get position where the headers finish then write from there /* Note: the count attribute value is wrong, it is the number of times strings are used thoughout the workbook it is different to the unique count * but because this library is about speed and Excel does not seem to care I am not going to fix it because I would need to read the whole workbook */ streamWriter.Write(string.Format("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>" + "<sst uniqueCount=\"{0}\" count=\"{0}\" xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\">", this.StringDictionary.Count)); // Add Rows foreach (var stringValue in this.StringDictionary) { streamWriter.Write(string.Format("<si><t>{0}</t></si>", stringValue.Key)); } //Add Footers streamWriter.Write("</sst>"); streamWriter.Flush(); } finally { streamWriter.Dispose(); this.PendingChanges = false; } } internal string GetString(string position) { int pos = 0; if (int.TryParse(position, out pos)) { return GetString(pos + 1); } else { // TODO: should I throw an error? this is a corrupted excel document return string.Empty; } } internal string GetString(int position) { if (this.StringArray == null) { this.StringArray = this.StringDictionary.ToDictionary(kv => kv.Value, kv => kv.Key); } return this.StringArray[position - 1]; } } }
2881099/dotnetGen_sqlserver
9,398
GenMs/plist-cil/NSString.cs
// plist-cil - An open source library to parse and generate property lists for .NET // Copyright (C) 2015 Natalia Portillo // // This code is based on: // plist - An open source library to parse and generate property lists // Copyright (C) 2014 Daniel Dreibrodt // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. using System; using System.Text; namespace PList { /// <summary> /// A NSString contains a string. /// </summary> /// @author Daniel Dreibrodt /// @author Natalia Portillo public class NSString : NSObject, IComparable { string content; /// <summary> /// Creates a NSString from its binary representation. /// </summary> /// <param name="bytes">The binary representation.</param> /// <param name="encoding">The encoding of the binary representation, the name of a supported charset.</param> /// <exception cref="ArgumentException">The encoding charset is invalid or not supported by the underlying platform.</exception> public NSString(byte[] bytes, String encoding) { Encoding enc = Encoding.GetEncoding(encoding); content = enc.GetString(bytes); } /// <summary> /// Creates a NSString from a string. /// </summary> /// <param name="text">The string that will be contained in the NSString.</param> public NSString(string text) { content = text; } /// <summary> /// Gets this strings content. /// </summary> /// <returns>This NSString as .NET string object.</returns> public string GetContent() { return content; } /// <summary> /// Sets the contents of this string. /// </summary> /// <param name="c">The new content of this string object.</param> public void SetContent(string c) { content = c; } /// <summary> /// Appends a string to this string. /// </summary> /// <param name="s">The string to append.</param> public void Append(NSString s) { Append(s.GetContent()); } /// <summary> /// Appends a string to this string. /// </summary> /// <param name="s">The string to append.</param> public void Append(string s) { content += s; } /// <summary> /// Prepends a string to this string. /// </summary> /// <param name="s">The string to prepend.</param> public void Prepend(string s) { content = s + content; } /// <summary> /// Prepends a string to this string. /// </summary> /// <param name="s">The string to prepend.</param> public void Prepend(NSString s) { Prepend(s.GetContent()); } /// <summary> /// Determines whether the specified <see cref="System.Object"/> is equal to the current <see cref="PList.NSString"/>. /// </summary> /// <param name="obj">The <see cref="System.Object"/> to compare with the current <see cref="PList.NSString"/>.</param> /// <returns><c>true</c> if the specified <see cref="System.Object"/> is equal to the current /// <see cref="PList.NSString"/>; otherwise, <c>false</c>.</returns> public override bool Equals(Object obj) { if (!(obj is NSString)) return false; return content.Equals(((NSString)obj).content); } /// <summary> /// Serves as a hash function for a <see cref="PList.NSString"/> object. /// </summary> /// <returns>A hash code for this instance that is suitable for use in hashing algorithms and data structures such as a /// hash table.</returns> public override int GetHashCode() { return content.GetHashCode(); } /// <summary> /// The textual representation of this NSString. /// </summary> /// <returns>The NSString's contents.</returns> public override string ToString() { return content; } static Encoding asciiEncoder, utf16beEncoder, utf8Encoder; internal override void ToXml(StringBuilder xml, int level) { Indent(xml, level); xml.Append("<string>"); //Make sure that the string is encoded in UTF-8 for the XML output lock (typeof(NSString)) { if (utf8Encoder == null) utf8Encoder = Encoding.GetEncoding("UTF-8"); try { byte[] bytes = utf8Encoder.GetBytes(content); content = utf8Encoder.GetString(bytes); } catch (Exception ex) { throw new PropertyListException("Could not encode the NSString into UTF-8: " + ex.Message); } } //According to http://www.w3.org/TR/REC-xml/#syntax node values must not //contain the characters < or &. Also the > character should be escaped. if (content.Contains("&") || content.Contains("<") || content.Contains(">")) { xml.Append("<![CDATA["); xml.Append(content.Replace("]]>", "]]]]><![CDATA[>")); xml.Append("]]>"); } else { xml.Append(content); } xml.Append("</string>"); } internal override void ToBinary(BinaryPropertyListWriter outPlist) { int kind; byte[] byteBuf; lock (typeof(NSString)) { if (asciiEncoder == null) // Not much use, because some characters do not fallback to exception, even if not ASCII asciiEncoder = Encoding.GetEncoding("ascii", EncoderFallback.ExceptionFallback, DecoderFallback.ExceptionFallback); if (IsASCIIEncodable(content)) { kind = 0x5; // standard ASCII byteBuf = asciiEncoder.GetBytes(content); } else { if (utf16beEncoder == null) utf16beEncoder = Encoding.BigEndianUnicode; kind = 0x6; // UTF-16-BE byteBuf = utf16beEncoder.GetBytes(content); } } outPlist.WriteIntHeader(kind, content.Length); outPlist.Write(byteBuf); } internal override void ToASCII(StringBuilder ascii, int level) { Indent(ascii, level); ascii.Append("\""); //According to https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/PropertyLists/OldStylePlists/OldStylePLists.html //non-ASCII characters are not escaped but simply written into the //file, thus actually violating the ASCII plain text format. //We will escape the string anyway because current Xcode project files (ASCII property lists) also escape their strings. ascii.Append(EscapeStringForASCII(content)); ascii.Append("\""); } internal override void ToASCIIGnuStep(StringBuilder ascii, int level) { Indent(ascii, level); ascii.Append("\""); ascii.Append(EscapeStringForASCII(content)); ascii.Append("\""); } /// <summary> /// Escapes a string for use in ASCII property lists. /// </summary> /// <returns>The unescaped string.</returns> /// <param name="s">S.</param> internal static string EscapeStringForASCII(string s) { string outString = ""; char[] cArray = s.ToCharArray(); foreach (char c in cArray) { if (c > 127) { //non-ASCII Unicode outString += "\\U"; string hex = String.Format("{0:x}", c); while (hex.Length < 4) hex = "0" + hex; outString += hex; } else if (c == '\\') { outString += "\\\\"; } else if (c == '\"') { outString += "\\\""; } else if (c == '\b') { outString += "\\b"; } else if (c == '\n') { outString += "\\n"; } else if (c == '\r') { outString += "\\r"; } else if (c == '\t') { outString += "\\t"; } else { outString += c; } } return outString; } /// <summary> /// Compares the current <see cref="PList.NSString"/> to the specified object. /// </summary> /// <returns>A 32-bit signed integer that indicates the lexical relationship between the two comparands.</returns> /// <param name="o">Object to compare to the current <see cref="PList.NSString"/>.</param> public int CompareTo(Object o) { if (o is NSString) return string.Compare(GetContent(), ((NSString)o).GetContent(), StringComparison.Ordinal); if (o is String) return string.Compare(GetContent(), ((String)o), StringComparison.Ordinal); return -1; } /// <summary> /// Determines whether the specified <see cref="PList.NSObject"/> is equal to the current <see cref="PList.NSString"/>. /// </summary> /// <param name="obj">The <see cref="PList.NSObject"/> to compare with the current <see cref="PList.NSString"/>.</param> /// <returns><c>true</c> if the specified <see cref="PList.NSObject"/> is equal to the current /// <see cref="PList.NSString"/>; otherwise, <c>false</c>.</returns> public override bool Equals(NSObject obj) { if (!(obj is NSString)) return false; return content == ((NSString)obj).content; } internal static bool IsASCIIEncodable(string text) { foreach (char c in text) if ((int)c > 0x7F) return false; return true; } } }
2881099/dotnetGen_sqlserver
7,077
GenMs/plist-cil/NSData.cs
// plist-cil - An open source library to parse and generate property lists for .NET // Copyright (C) 2015 Natalia Portillo // // This code is based on: // plist - An open source library to parse and generate property lists // Copyright (C) 2014 Daniel Dreibrodt // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. using System; using System.IO; using System.Text; namespace PList { /// <summary> /// NSData objects are wrappers for byte buffers /// </summary> /// @author Daniel Dreibrodt /// @author Natalia Portillo public class NSData : NSObject { readonly byte[] bytes; /// <summary> /// Creates the NSData object from the binary representation of it. /// </summary> /// <param name="bytes">The raw data contained in the NSData object.</param> public NSData(byte[] bytes) { this.bytes = bytes; } /// <summary> /// Creates a NSData object from its textual representation, which is a Base64 encoded amount of bytes. /// </summary> /// <param name="base64">The Base64 encoded contents of the NSData object.</param> /// <exception cref="FormatException">When the given string is not a proper Base64 formatted string.</exception> public NSData(string base64) { bytes = Convert.FromBase64String(base64); } /// <summary> /// Creates a NSData object from a file. Using the files contents as the contents of this NSData object. /// </summary> /// <param name="file">The file containing the data.</param> /// <exception cref="FileNotFoundException">If the file could not be found.</exception> /// <exception cref="IOException">If the file could not be read.</exception> public NSData(FileInfo file) { bytes = new byte[(int)file.Length]; using (FileStream raf = file.OpenRead()) { raf.Read(bytes, 0, (int)file.Length); } } /// <summary> /// The bytes contained in this NSData object. /// </summary> /// <value>The data as bytes</value> public byte[] Bytes { get { return bytes; } } /// <summary> /// Gets the amount of data stored in this object. /// </summary> /// <value>The number of bytes contained in this object.</value> public int Length { get { return bytes.Length; } } /// <summary> /// Loads the bytes from this NSData object into a byte buffer. /// </summary> /// <param name="buf">The byte buffer which will contain the data</param> /// <param name="length">The amount of data to copy</param> public void GetBytes(MemoryStream buf, int length) { buf.Write(bytes, 0, Math.Min(bytes.Length, length)); } /// <summary> /// Loads the bytes from this NSData object into a byte buffer. /// </summary> /// <param name="buf">The byte buffer which will contain the data</param> /// <param name="rangeStart">The start index.</param> /// <param name="rangeStop">The stop index.</param> public void GetBytes(MemoryStream buf, int rangeStart, int rangeStop) { buf.Write(bytes, rangeStart, Math.Min(bytes.Length, rangeStop)); } /// <summary> /// Gets the Base64 encoded data contained in this NSData object. /// </summary> /// <returns>The Base64 encoded data as a <c>string</c>.</returns> public string GetBase64EncodedData() { return Convert.ToBase64String(bytes); } /// <summary> /// Determines whether the specified <see cref="System.Object"/> is equal to the current <see cref="PList.NSData"/>. /// </summary> /// <param name="obj">The <see cref="System.Object"/> to compare with the current <see cref="PList.NSData"/>.</param> /// <returns><c>true</c> if the specified <see cref="System.Object"/> is equal to the current /// <see cref="PList.NSData"/>; otherwise, <c>false</c>.</returns> public override bool Equals(Object obj) { return obj.GetType().Equals(GetType()) && ArrayEquals(((NSData)obj).bytes, bytes); } /// <summary> /// Serves as a hash function for a <see cref="PList.NSData"/> object. /// </summary> /// <returns>A hash code for this instance that is suitable for use in hashing algorithms and data structures such as a /// hash table.</returns> public override int GetHashCode() { int hash = 5; hash = 67 * hash + bytes.GetHashCode(); return hash; } internal override void ToXml(StringBuilder xml, int level) { Indent(xml, level); xml.Append("<data>"); xml.Append(NSObject.NEWLINE); string base64 = GetBase64EncodedData(); foreach (string line in base64.Split('\n')) { Indent(xml, level); xml.Append(line); xml.Append(NSObject.NEWLINE); } Indent(xml, level); xml.Append("</data>"); } internal override void ToBinary(BinaryPropertyListWriter outPlist) { outPlist.WriteIntHeader(0x4, bytes.Length); outPlist.Write(bytes); } internal override void ToASCII(StringBuilder ascii, int level) { Indent(ascii, level); ascii.Append(ASCIIPropertyListParser.DATA_BEGIN_TOKEN); int indexOfLastNewLine = ascii.ToString().LastIndexOf(NEWLINE, StringComparison.Ordinal); for (int i = 0; i < bytes.Length; i++) { int b = bytes[i] & 0xFF; ascii.Append(String.Format("{0:x2}", b)); if (ascii.Length - indexOfLastNewLine > ASCII_LINE_LENGTH) { ascii.Append(NEWLINE); indexOfLastNewLine = ascii.Length; } else if ((i + 1) % 2 == 0 && i != bytes.Length - 1) { ascii.Append(" "); } } ascii.Append(ASCIIPropertyListParser.DATA_END_TOKEN); } internal override void ToASCIIGnuStep(StringBuilder ascii, int level) { ToASCII(ascii, level); } /// <summary> /// Determines whether the specified <see cref="PList.NSObject"/> is equal to the current <see cref="PList.NSData"/>. /// </summary> /// <param name="obj">The <see cref="PList.NSObject"/> to compare with the current <see cref="PList.NSData"/>.</param> /// <returns><c>true</c> if the specified <see cref="PList.NSObject"/> is equal to the current /// <see cref="PList.NSData"/>; otherwise, <c>false</c>.</returns> public override bool Equals(NSObject obj) { if (!(obj is NSData)) return false; return ArrayEquals(bytes, ((NSData)obj).Bytes); } } }
2881099/dotnetGen_postgresql
13,345
GenPg/WinFormClass/Socket/ServerSocket.cs
using System; using System.Collections.Generic; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; public class ServerSocket : IDisposable { private TcpListener _tcpListener; private Thread _tcpListenerThread; private Dictionary<int, AcceptSocket> _clients = new Dictionary<int, AcceptSocket>(); private object _clients_lock = new object(); private int _id = 1; private int _port; private bool _running; private ManualResetEvent _stopWait; public event ServerSocketAcceptedEventHandler Accepted; public event ServerSocketClosedEventHandler Closed; public event ServerSocketReceiveEventHandler Receive; public event ServerSocketErrorEventHandler Error; private WorkQueue _acceptWQ; internal WorkQueue _receiveWQ; internal WorkQueue _receiveSyncWQ; private WorkQueue _writeWQ; public ServerSocket(int port) { this._port = port; } public void Start() { if (this._running == false) { this._running = true; try { this._tcpListener = new TcpListener(IPAddress.Any, this._port); this._tcpListener.Start(); this._acceptWQ = new WorkQueue(); this._receiveWQ = new WorkQueue(); this._receiveSyncWQ = new WorkQueue(); this._writeWQ = new WorkQueue(); } catch (Exception ex) { this._running = false; this.OnError(ex); return; } this._tcpListenerThread = new Thread(delegate() { while (this._running) { try { TcpClient tcpClient = this._tcpListener.AcceptTcpClientAsync().Result; this._acceptWQ.Enqueue(delegate() { try { AcceptSocket acceptSocket = new AcceptSocket(this, tcpClient, this._id); this.OnAccepted(acceptSocket); } catch (Exception ex) { this.OnError(ex); } }); } catch (Exception ex) { this.OnError(ex); } } int[] keys = new int[this._clients.Count]; try { this._clients.Keys.CopyTo(keys, 0); } catch { lock (this._clients_lock) { keys = new int[this._clients.Count]; this._clients.Keys.CopyTo(keys, 0); } } foreach (int key in keys) { AcceptSocket client = null; if (this._clients.TryGetValue(key, out client)) { client.Close(); } } if (this._acceptWQ != null) { this._acceptWQ.Dispose(); } if (this._receiveWQ != null) { this._receiveWQ.Dispose(); } if (this._receiveSyncWQ != null) { this._receiveSyncWQ.Dispose(); } if (this._writeWQ != null) { this._writeWQ.Dispose(); } this._clients.Clear(); this._stopWait.Set(); }); this._tcpListenerThread.Start(); } } public void Stop() { if (this._tcpListener != null) { this._tcpListener.Stop(); } if (this._running == true) { this._stopWait = new ManualResetEvent(false); this._stopWait.Reset(); this._running = false; this._stopWait.WaitOne(); } } internal void AccessDenied(AcceptSocket client) { client.Write(SocketMessager.SYS_ACCESS_DENIED, delegate(object sender2, ServerSocketReceiveEventArgs e2) { }, TimeSpan.FromSeconds(1)); client.Close(); } public void Write(SocketMessager messager) { int[] keys = new int[this._clients.Count]; try { this._clients.Keys.CopyTo(keys, 0); } catch { lock (this._clients_lock) { keys = new int[this._clients.Count]; this._clients.Keys.CopyTo(keys, 0); } } foreach (int key in keys) { AcceptSocket client = null; if (this._clients.TryGetValue(key, out client)) { this._writeWQ.Enqueue(delegate() { client.Write(messager); }); } } } public AcceptSocket GetAcceptSocket(int id) { AcceptSocket socket = null; this._clients.TryGetValue(id, out socket); return socket; } internal void CloseClient(AcceptSocket client) { this._clients.Remove(client.Id); } protected virtual void OnAccepted(ServerSocketAcceptedEventArgs e) { SocketMessager helloMessager = new SocketMessager(SocketMessager.SYS_HELLO_WELCOME.Action); e.AcceptSocket.Write(helloMessager, delegate(object sender2, ServerSocketReceiveEventArgs e2) { if (e2.Messager.Id == helloMessager.Id && string.Compare(e2.Messager.Action, helloMessager.Action) == 0) { e.AcceptSocket._accepted = true; } }, TimeSpan.FromSeconds(2)); if (e.AcceptSocket._accepted) { if (this.Accepted != null) { try { this.Accepted(this, e); } catch (Exception ex) { this.OnError(ex); } } } else { e.AcceptSocket.AccessDenied(); } } private void OnAccepted(AcceptSocket client) { lock (_clients_lock) { _clients.Add(this._id++, client); } ServerSocketAcceptedEventArgs e = new ServerSocketAcceptedEventArgs(this._clients.Count, client); this.OnAccepted(e); } protected virtual void OnClosed(ServerSocketClosedEventArgs e) { if (this.Closed != null) { this.Closed(this, e); } } internal void OnClosed(AcceptSocket client) { ServerSocketClosedEventArgs e = new ServerSocketClosedEventArgs(this._clients.Count, client.Id); this.OnClosed(e); } protected virtual void OnReceive(ServerSocketReceiveEventArgs e) { if (this.Receive != null) { this.Receive(this, e); } } internal void OnReceive2(ServerSocketReceiveEventArgs e) { this.OnReceive(e); } protected virtual void OnError(ServerSocketErrorEventArgs e) { if (this.Error != null) { this.Error(this, e); } } protected void OnError(Exception ex) { ServerSocketErrorEventArgs e = new ServerSocketErrorEventArgs(-1, ex, null); this.OnError(e); } internal void OnError2(ServerSocketErrorEventArgs e) { this.OnError(e); } #region IDisposable 成员 public void Dispose() { this.Stop(); } #endregion } public class AcceptSocket : BaseSocket, IDisposable { private ServerSocket _server; private TcpClient _tcpClient; private Thread _thread; private bool _running; private int _id; private int _receives; private int _errors; private object _errors_lock = new object(); private object _write_lock = new object(); private Dictionary<int, SyncReceive> _receiveHandlers = new Dictionary<int, SyncReceive>(); private object _receiveHandlers_lock = new object(); private DateTime _lastActive; internal bool _accepted; public AcceptSocket(ServerSocket server, TcpClient tcpClient, int id) { this._running = true; this._id = id; this._server = server; this._tcpClient = tcpClient; this._lastActive = DateTime.Now; this._thread = new Thread(delegate() { while (this._running) { try { NetworkStream ns = this._tcpClient.GetStream(); ns.ReadTimeout = 1000 * 20; if (ns.DataAvailable) { SocketMessager messager = base.Read(ns); if (string.Compare(messager.Action, SocketMessager.SYS_TEST_LINK.Action) != 0) { ServerSocketReceiveEventArgs e = new ServerSocketReceiveEventArgs(this._receives++, messager, this); SyncReceive receive = null; if (this._receiveHandlers.TryGetValue(messager.Id, out receive)) { this._server._receiveSyncWQ.Enqueue(delegate() { try { receive.ReceiveHandler(this, e); } catch (Exception ex) { this.OnError(ex); } finally { receive.Wait.Set(); } }); } else { this._server._receiveWQ.Enqueue(delegate() { this.OnReceive(e); }); } } this._lastActive = DateTime.Now; } else if (_accepted) { TimeSpan ts = DateTime.Now - _lastActive; if (ts.TotalSeconds > 5) { this.Write(SocketMessager.SYS_TEST_LINK); } } if (!ns.DataAvailable) Thread.CurrentThread.Join(1); } catch (Exception ex) { this._running = false; this.OnError(ex); } } this.Close(); this.OnClosed(); }); this._thread.Start(); } public void Close() { this._running = false; if (this._tcpClient != null) { this._tcpClient.Dispose(); this._tcpClient = null; } this._server.CloseClient(this); int[] keys = new int[this._receiveHandlers.Count]; try { this._receiveHandlers.Keys.CopyTo(keys, 0); } catch { lock (this._receiveHandlers_lock) { keys = new int[this._receiveHandlers.Count]; this._receiveHandlers.Keys.CopyTo(keys, 0); } } foreach (int key in keys) { SyncReceive receiveHandler = null; if (this._receiveHandlers.TryGetValue(key, out receiveHandler)) { receiveHandler.Wait.Set(); } } lock (this._receiveHandlers_lock) { this._receiveHandlers.Clear(); } } public void Write(SocketMessager messager) { this.Write(messager, null, TimeSpan.Zero); } public void Write(SocketMessager messager, ServerSocketReceiveEventHandler receiveHandler) { this.Write(messager, receiveHandler, TimeSpan.FromSeconds(20)); } public void Write(SocketMessager messager, ServerSocketReceiveEventHandler receiveHandler, TimeSpan timeout) { SyncReceive syncReceive = null; try { if (receiveHandler != null) { syncReceive = new SyncReceive(receiveHandler); lock (this._receiveHandlers_lock) { if (!this._receiveHandlers.ContainsKey(messager.Id)) { this._receiveHandlers.Add(messager.Id, syncReceive); } else { this._receiveHandlers[messager.Id] = syncReceive; } } } lock (_write_lock) { NetworkStream ns = this._tcpClient.GetStream(); base.Write(ns, messager); } this._lastActive = DateTime.Now; if (syncReceive != null) { syncReceive.Wait.Reset(); syncReceive.Wait.WaitOne(timeout); syncReceive.Wait.Set(); lock (this._receiveHandlers_lock) { this._receiveHandlers.Remove(messager.Id); } } } catch (Exception ex) { this._running = false; this.OnError(ex); if (syncReceive != null) { syncReceive.Wait.Set(); lock (this._receiveHandlers_lock) { this._receiveHandlers.Remove(messager.Id); } } } } /// <summary> /// 拒绝访问,并关闭连接 /// </summary> public void AccessDenied() { this._server.AccessDenied(this); } protected virtual void OnClosed() { try { this._server.OnClosed(this); } catch (Exception ex) { this.OnError(ex); } } protected virtual void OnReceive(ServerSocketReceiveEventArgs e) { try { this._server.OnReceive2(e); } catch (Exception ex) { this.OnError(ex); } } protected virtual void OnError(Exception ex) { int errors = 0; lock (this._errors_lock) { errors = ++this._errors; } ServerSocketErrorEventArgs e = new ServerSocketErrorEventArgs(errors, ex, this); this._server.OnError2(e); } public int Id { get { return _id; } } class SyncReceive : IDisposable { private ServerSocketReceiveEventHandler _receiveHandler; private ManualResetEvent _wait; public SyncReceive(ServerSocketReceiveEventHandler onReceive) { this._receiveHandler = onReceive; this._wait = new ManualResetEvent(false); } public ManualResetEvent Wait { get { return _wait; } } public ServerSocketReceiveEventHandler ReceiveHandler { get { return _receiveHandler; } } #region IDisposable 成员 public void Dispose() { this._wait.Set(); } #endregion } #region IDisposable 成员 void IDisposable.Dispose() { this.Close(); } #endregion } public delegate void ServerSocketClosedEventHandler(object sender, ServerSocketClosedEventArgs e); public delegate void ServerSocketAcceptedEventHandler(object sender, ServerSocketAcceptedEventArgs e); public delegate void ServerSocketErrorEventHandler(object sender, ServerSocketErrorEventArgs e); public delegate void ServerSocketReceiveEventHandler(object sender, ServerSocketReceiveEventArgs e); public class ServerSocketClosedEventArgs : EventArgs { private int _accepts; private int _acceptSocketId; public ServerSocketClosedEventArgs(int accepts, int acceptSocketId) { this._accepts = accepts; this._acceptSocketId = acceptSocketId; } public int Accepts { get { return _accepts; } } public int AcceptSocketId { get { return _acceptSocketId; } } } public class ServerSocketAcceptedEventArgs : EventArgs { private int _accepts; private AcceptSocket _acceptSocket; public ServerSocketAcceptedEventArgs(int accepts, AcceptSocket acceptSocket) { this._accepts = accepts; this._acceptSocket = acceptSocket; } public int Accepts { get { return _accepts; } } public AcceptSocket AcceptSocket { get { return _acceptSocket; } } } public class ServerSocketErrorEventArgs : EventArgs { private int _errors; private Exception _exception; private AcceptSocket _acceptSocket; public ServerSocketErrorEventArgs(int errors, Exception exception, AcceptSocket acceptSocket) { this._errors = errors; this._exception = exception; this._acceptSocket = acceptSocket; } public int Errors { get { return _errors; } } public Exception Exception { get { return _exception; } } public AcceptSocket AcceptSocket { get { return _acceptSocket; } } } public class ServerSocketReceiveEventArgs : EventArgs { private int _receives; private SocketMessager _messager; private AcceptSocket _acceptSocket; public ServerSocketReceiveEventArgs(int receives, SocketMessager messager, AcceptSocket acceptSocket) { this._receives = receives; this._messager = messager; this._acceptSocket = acceptSocket; } public int Receives { get { return _receives; } } public SocketMessager Messager { get { return _messager; } } public AcceptSocket AcceptSocket { get { return _acceptSocket; } } }
2881099/dotnetGen_sqlserver
19,629
GenMs/plist-cil/NSDictionary.cs
// plist-cil - An open source library to parse and generate property lists for .NET // Copyright (C) 2015 Natalia Portillo // // This code is based on: // plist - An open source library to parse and generate property lists // Copyright (C) 2014 Daniel Dreibrodt // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. using System; using System.Collections.Generic; using System.Text; namespace PList { /// <summary> /// <para> /// A NSDictionary is a collection of keys and values, essentially a Dictionary. /// The keys are simple Strings whereas the values can be any kind of NSObject. /// </para><para> /// You can access the keys through the function <see cref="Keys"/>. /// </para><para> /// Access to the objects stored for each key is given through the function /// <see cref="ObjectForKey"/>. /// </para> /// </summary> /// @author Daniel Dreibrodt /// @author Natalia Portillo public class NSDictionary : NSObject, IDictionary<string, NSObject> { readonly Dictionary<string, NSObject> dict; /// <summary> /// Creates a new empty NSDictionary. /// </summary> public NSDictionary() { dict = new Dictionary<string, NSObject>(); } /// <summary> /// Gets the hashmap which stores the keys and values of this dictionary. /// Changes to the hashmap's contents are directly reflected in this /// dictionary. /// </summary> /// <returns>The hashmap which is used by this dictionary to store its contents.</returns> public Dictionary<string, NSObject> GetDictionary() { return dict; } /// <summary> /// Gets the NSObject stored for the given key. /// </summary> /// <returns>The object.</returns> /// <param name="key">The key.</param> public NSObject ObjectForKey(string key) { NSObject nso; return dict.TryGetValue(key, out nso) ? nso : null; } /// <summary> /// Gets a value indicating whether this instance is empty. /// </summary> /// <value><c>true</c> if this instance is empty; otherwise, <c>false</c>.</value> public bool IsEmpty { get { return dict.Count == 0; } } /// <summary> /// Checks if the specified object key is contained in the current instance. /// </summary> /// <returns><c>true</c>, if key is contained, <c>false</c> otherwise.</returns> /// <param name="key">Key.</param> public bool ContainsKey(Object key) { return key is string && dict.ContainsKey((string)key); } /// <summary> /// Removes the item corresponding to the specified key from the current instance, if found. /// </summary> /// <param name="key">Key.</param> /// <returns><c>true</c>, if removed, <c>false</c> otherwise.</returns> public bool Remove(Object key) { return key is string && dict.Remove((string)key); } /// <summary> /// Gets the <see cref="NSObject"/> corresponding to the specified key from the current instance. /// </summary> /// <param name="key">Key.</param> /// <returns>The object corresponding to the specified key, null if not found in the current instance.</returns> public NSObject Get(Object key) { if (key is string) return ObjectForKey((string)key); return null; } /// <summary> /// Checks if the current instance contains the object corresponding to the specified key. /// </summary> /// <returns><c>true</c>, if value is contained, <c>false</c> otherwise.</returns> /// <param name="value">Object to search up in the current instance.</param> public bool ContainsValue(Object value) { if (value == null) return false; NSObject wrap = NSObject.Wrap(value); return dict.ContainsValue(wrap); } /// <summary> /// Puts a new key-value pair into this dictionary. /// If the value is null, no operation will be performed on the dictionary. /// </summary> /// <param name="key">The key.</param> /// <param name="obj">The value. Supported object types are numbers, byte-arrays, dates, strings and arrays or sets of those.</param> public void Add(String key, Object obj) { if (obj == null) return; Add(key, NSObject.Wrap(obj)); } /// <summary> /// Puts a new key-value pair into this dictionary. /// </summary> /// <param name="key">The key.</param> /// <param name="obj">The value.</param> public void Add(string key, long obj) { Add(key, new NSNumber(obj)); } /// <summary> /// Puts a new key-value pair into this dictionary. /// </summary> /// <param name="key">The key.</param> /// <param name="obj">The value.</param> public void Add(string key, double obj) { Add(key, new NSNumber(obj)); } /// <summary> /// Puts a new key-value pair into this dictionary. /// </summary> /// <param name="key">The key.</param> /// <param name="obj">The value.</param> public void Add(string key, bool obj) { Add(key, new NSNumber(obj)); } /// <summary> /// Checks whether a given value is contained in this dictionary. /// </summary> /// <param name="val">The value that will be searched for.</param> /// <returns>Whether the key is contained in this dictionary.</returns> public bool ContainsValue(string val) { foreach (NSObject o in dict.Values) { if (o.GetType().Equals(typeof(NSString))) { NSString str = (NSString)o; if (str.GetContent().Equals(val)) return true; } } return false; } /// <summary> /// Checks whether a given value is contained in this dictionary. /// </summary> /// <param name="val">The value that will be searched for.</param> /// <returns>Whether the key is contained in this dictionary.</returns> public bool ContainsValue(long val) { foreach (NSObject o in dict.Values) { if (o.GetType().Equals(typeof(NSNumber))) { NSNumber num = (NSNumber)o; if (num.isInteger() && num.ToInt() == val) return true; } } return false; } /// <summary> /// Checks whether a given value is contained in this dictionary. /// </summary> /// <param name="val">The value that will be searched for.</param> /// <returns>Whether the key is contained in this dictionary.</returns> public bool ContainsValue(double val) { foreach (NSObject o in dict.Values) { if (o.GetType().Equals(typeof(NSNumber))) { NSNumber num = (NSNumber)o; if (num.isReal() && num.ToDouble() == val) return true; } } return false; } /// <summary> /// Checks whether a given value is contained in this dictionary. /// </summary> /// <param name="val">The value that will be searched for.</param> /// <returns>Whether the key is contained in this dictionary.</returns> public bool ContainsValue(bool val) { foreach (NSObject o in dict.Values) { if (o.GetType().Equals(typeof(NSNumber))) { NSNumber num = (NSNumber)o; if (num.isBoolean() && num.ToBool() == val) return true; } } return false; } /// <summary> /// Checks whether a given value is contained in this dictionary. /// </summary> /// <param name="val">The value that will be searched for.</param> /// <returns>Whether the key is contained in this dictionary.</returns> public bool ContainsValue(DateTime val) { foreach (NSObject o in dict.Values) { if (o.GetType().Equals(typeof(NSDate))) { NSDate dat = (NSDate)o; if (dat.Date.Equals(val)) return true; } } return false; } /// <summary> /// Checks whether a given value is contained in this dictionary. /// </summary> /// <param name="val">The value that will be searched for.</param> /// <returns>Whether the key is contained in this dictionary.</returns> public bool ContainsValue(byte[] val) { foreach (NSObject o in dict.Values) { if (o.GetType().Equals(typeof(NSData))) { NSData dat = (NSData)o; if (ArrayEquals(dat.Bytes, val)) return true; } } return false; } /// <summary> /// Determines whether the specified <see cref="PList.NSObject"/> is equal to the current <see cref="PList.NSDictionary"/>. /// </summary> /// <param name="obj">The <see cref="PList.NSObject"/> to compare with the current <see cref="PList.NSDictionary"/>.</param> /// <returns><c>true</c> if the specified <see cref="PList.NSObject"/> is equal to the current /// <see cref="PList.NSDictionary"/>; otherwise, <c>false</c>.</returns> public override bool Equals(NSObject obj) { if (!(obj is NSDictionary)) return false; if (((NSDictionary)obj).dict.Count != dict.Count) return false; bool found; foreach (KeyValuePair<string, NSObject> kvp in dict) { NSObject nsoB; found = ((NSDictionary)obj).dict.TryGetValue(kvp.Key, out nsoB); if (!found) return false; if (!kvp.Value.Equals(nsoB)) return false; } return true; } /// <summary> /// Serves as a hash function for a <see cref="PList.NSDictionary"/> object. /// </summary> /// <returns>A hash code for this instance that is suitable for use in hashing algorithms and data structures such as a /// hash table.</returns> public override int GetHashCode() { int hash = 7; hash = 83 * hash + (dict != null ? dict.GetHashCode() : 0); return hash; } internal override void ToXml(StringBuilder xml, int level) { Indent(xml, level); xml.Append("<dict>"); xml.Append(NSObject.NEWLINE); foreach (KeyValuePair<string, NSObject> kvp in dict) { Indent(xml, level + 1); xml.Append("<key>"); //According to http://www.w3.org/TR/REC-xml/#syntax node values must not //contain the characters < or &. Also the > character should be escaped. if (kvp.Key.Contains("&") || kvp.Key.Contains("<") || kvp.Key.Contains(">")) { xml.Append("<![CDATA["); xml.Append(kvp.Key.Replace("]]>", "]]]]><![CDATA[>")); xml.Append("]]>"); } else { xml.Append(kvp.Key); } xml.Append("</key>"); xml.Append(NSObject.NEWLINE); kvp.Value.ToXml(xml, level + 1); xml.Append(NSObject.NEWLINE); } Indent(xml, level); xml.Append("</dict>"); } internal override void AssignIDs(BinaryPropertyListWriter outPlist) { base.AssignIDs(outPlist); foreach (KeyValuePair<string, NSObject> entry in dict) { new NSString(entry.Key).AssignIDs(outPlist); } foreach (KeyValuePair<string, NSObject> entry in dict) { entry.Value.AssignIDs(outPlist); } } internal override void ToBinary(BinaryPropertyListWriter outPlist) { outPlist.WriteIntHeader(0xD, dict.Count); foreach (KeyValuePair<String, NSObject> entry in dict) { outPlist.WriteID(outPlist.GetID(new NSString(entry.Key))); } foreach (KeyValuePair<String, NSObject> entry in dict) { outPlist.WriteID(outPlist.GetID(entry.Value)); } } /// <summary> /// Generates a valid ASCII property list which has this NSDictionary as its /// root object. The generated property list complies with the format as /// described in https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/PropertyLists/OldStylePlists/OldStylePLists.html /// Property List Programming Guide - Old-Style ASCII Property Lists. /// </summary> /// <returns>ASCII representation of this object.</returns> public string ToASCIIPropertyList() { StringBuilder ascii = new StringBuilder(); ToASCII(ascii, 0); ascii.Append(NEWLINE); return ascii.ToString(); } /// <summary> /// Generates a valid ASCII property list in GnuStep format which has this /// NSDictionary as its root object. The generated property list complies with /// the format as described in http://www.gnustep.org/resources/documentation/Developer/Base/Reference/NSPropertyList.html /// GnuStep - NSPropertyListSerialization class documentation. /// </summary> /// <returns>GnuStep ASCII representation of this object.</returns> public string ToGnuStepASCIIPropertyList() { StringBuilder ascii = new StringBuilder(); ToASCIIGnuStep(ascii, 0); ascii.Append(NEWLINE); return ascii.ToString(); } internal override void ToASCII(StringBuilder ascii, int level) { Indent(ascii, level); ascii.Append(ASCIIPropertyListParser.DICTIONARY_BEGIN_TOKEN); ascii.Append(NEWLINE); foreach (string key in Keys) { NSObject val = ObjectForKey(key); Indent(ascii, level + 1); ascii.Append("\""); ascii.Append(NSString.EscapeStringForASCII(key)); ascii.Append("\" ="); Type objClass = val.GetType(); if (objClass.Equals(typeof(NSDictionary)) || objClass.Equals(typeof(NSArray)) || objClass.Equals(typeof(NSData))) { ascii.Append(NEWLINE); val.ToASCII(ascii, level + 2); } else { ascii.Append(" "); val.ToASCII(ascii, 0); } ascii.Append(ASCIIPropertyListParser.DICTIONARY_ITEM_DELIMITER_TOKEN); ascii.Append(NEWLINE); } Indent(ascii, level); ascii.Append(ASCIIPropertyListParser.DICTIONARY_END_TOKEN); } internal override void ToASCIIGnuStep(StringBuilder ascii, int level) { Indent(ascii, level); ascii.Append(ASCIIPropertyListParser.DICTIONARY_BEGIN_TOKEN); ascii.Append(NEWLINE); foreach (string key in Keys) { NSObject val = ObjectForKey(key); Indent(ascii, level + 1); ascii.Append("\""); ascii.Append(NSString.EscapeStringForASCII(key)); ascii.Append("\" ="); Type objClass = val.GetType(); if (objClass.Equals(typeof(NSDictionary)) || objClass.Equals(typeof(NSArray)) || objClass.Equals(typeof(NSData))) { ascii.Append(NEWLINE); val.ToASCIIGnuStep(ascii, level + 2); } else { ascii.Append(" "); val.ToASCIIGnuStep(ascii, 0); } ascii.Append(ASCIIPropertyListParser.DICTIONARY_ITEM_DELIMITER_TOKEN); ascii.Append(NEWLINE); } Indent(ascii, level); ascii.Append(ASCIIPropertyListParser.DICTIONARY_END_TOKEN); } #region IDictionary implementation /// <summary> /// Add the specified key and value. /// </summary> /// <param name="key">Key.</param> /// <param name="value">Value.</param> public void Add(string key, NSObject value) { dict.Add(key, value); } /// <summary> /// Checks if there is any item contained in the current instance corresponding with the specified key. /// </summary> /// <returns><c>true</c>, if key was contained, <c>false</c> otherwise.</returns> /// <param name="key">Key.</param> public bool ContainsKey(string key) { return dict.ContainsKey(key); } /// <summary> /// Checks if there is any item contained in the current instance corresponding with the specified value. /// </summary> /// <returns><c>true</c>, if value is contained, <c>false</c> otherwise.</returns> /// <param name="value">Key.</param> public bool ContainsValue(NSObject value) { return dict.ContainsValue(value); } /// <summary> /// Removes the item belonging to the specified key. /// </summary> /// <param name="key">Key.</param> public bool Remove(string key) { return dict.Remove(key); } /// <summary> /// Tries to get the item corresponding to the specified key /// </summary> /// <returns><c>true</c>, if get value was successfully found and retrieved, <c>false</c> otherwise.</returns> /// <param name="key">Key.</param> /// <param name="value">Where to store the value.</param> public bool TryGetValue(string key, out NSObject value) { return dict.TryGetValue(key, out value); } /// <summary> /// Gets or sets the <see cref="PList.NSObject"/> at the specified index. /// </summary> /// <param name="index">Index.</param> public NSObject this[string index] { get { return dict[index]; } set { dict[index] = value; } } /// <summary> /// Gets an array with all the keys contained in the current instance. /// </summary> /// <value>The keys.</value> public ICollection<string> Keys { get { return dict.Keys; } } /// <summary> /// Gets an array with all the objects contained in the current instance. /// </summary> /// <value>The objects.</value> public ICollection<NSObject> Values { get { return dict.Values; } } #endregion #region ICollection implementation /// <summary> /// Adds the specified item. /// </summary> /// <param name="item">Item.</param> public void Add(KeyValuePair<string, NSObject> item) { dict.Add(item.Key, item.Value); } /// <summary> /// Clears this instance. /// </summary> public void Clear() { dict.Clear(); } /// <summary> /// Checks if the current instance contains the specified item. /// </summary> /// <param name="item">Item.</param> /// <returns><c>true</c> if it is found, <c>false</c> otherwise.</returns> public bool Contains(KeyValuePair<string, NSObject> item) { return dict.ContainsKey(item.Key); } /// <summary> /// Copies the <see cref="Dictionary{TKey, TValue}.ValueCollection"/> elements to an existing one-dimensional <see cref="Array"/>, starting at the specified array index. /// </summary> /// <param name="array">The one-dimensional <see cref="Array"/> that is the destination of the elements copied from <see cref="Dictionary{TKey, TValue}.ValueCollection"/>. The <see cref="Array"/> must have zero-based indexing.</param> /// <param name="arrayIndex">The zero-based index in array at which copying begins.</param> public void CopyTo(KeyValuePair<string, NSObject>[] array, int arrayIndex) { ICollection<KeyValuePair<string, NSObject>> coll = dict; coll.CopyTo(array, arrayIndex); } /// <summary> /// Removes the specified item. /// </summary> /// <param name="item">Item to remove.</param> /// <returns><c>true</c> if successfully removed, <c>false</c> if not, or if item is not in current instance.</returns> public bool Remove(KeyValuePair<string, NSObject> item) { return dict.Remove(item.Key); } /// <summary> /// Gets the count of items in the current instance. /// </summary> /// <value>How many items are contained in the current instance.</value> public int Count { get { return dict.Count; } } /// <summary> /// Gets a value indicating whether this instance is read only. /// </summary> /// <value><c>true</c> if this instance is read only; otherwise, <c>false</c>.</value> public bool IsReadOnly { get { return false; } } #endregion #region IEnumerable implementation /// <summary> /// Gets the enumerator. /// </summary> /// <returns>The enumerator.</returns> public IEnumerator<KeyValuePair<string, NSObject>> GetEnumerator() { return dict.GetEnumerator(); } #endregion #region IEnumerable implementation System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return dict.GetEnumerator(); } #endregion } }
2881099/dotnetGen_sqlserver
14,735
GenMs/plist-cil/PropertyListParser.cs
// plist-cil - An open source library to parse and generate property lists for .NET // Copyright (C) 2015 Natalia Portillo // // This code is based on: // plist - An open source library to parse and generate property lists // Copyright (C) 2014 Daniel Dreibrodt // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. using System; using System.Text; using System.IO; namespace PList { /// <summary> /// This class provides methods to parse property lists. It can handle files, /// input streams and byte arrays. All known property list formats are supported. /// /// This class also provides methods to save and convert property lists. /// </summary> /// @author Daniel Dreibrodt /// @author Natalia Portillo public static class PropertyListParser { const int TYPE_XML = 0; const int TYPE_BINARY = 1; const int TYPE_ASCII = 2; const int TYPE_ERROR_BLANK = 10; const int TYPE_ERROR_UNKNOWN = 11; /// <summary> /// Determines the type of a property list by means of the first bytes of its data /// </summary> /// <returns>The type of the property list</returns> /// <param name="dataBeginning">The very first bytes of data of the property list (minus any whitespace) as a string</param> static int DetermineType(string dataBeginning) { dataBeginning = dataBeginning.Trim(); if (dataBeginning.Length == 0) { return TYPE_ERROR_BLANK; } if (dataBeginning.StartsWith("bplist")) { return TYPE_BINARY; } if (dataBeginning.StartsWith("(") || dataBeginning.StartsWith("{") || dataBeginning.StartsWith("/")) { return TYPE_ASCII; } return dataBeginning.StartsWith("<") ? TYPE_XML : TYPE_ERROR_UNKNOWN; } /// <summary> /// Determines the type of a property list by means of the first bytes of its data /// </summary> /// <returns>The very first bytes of data of the property list (minus any whitespace)</returns> /// <param name="bytes">The type of the property list</param> static int DetermineType(byte[] bytes) { //Skip any possible whitespace at the beginning of the file int offset = 0; if (bytes.Length >= 3 && (bytes[0] & 0xFF) == 0xEF && (bytes[1] & 0xFF) == 0xBB && (bytes[2] & 0xFF) == 0xBF) { //Skip Unicode byte order mark (BOM) offset += 3; } while (offset < bytes.Length && (bytes[offset] == ' ' || bytes[offset] == '\t' || bytes[offset] == '\r' || bytes[offset] == '\n' || bytes[offset] == '\f')) { offset++; } return DetermineType(Encoding.ASCII.GetString(bytes, offset, Math.Min(8, bytes.Length - offset))); } /// <summary> /// Determines the type of a property list by means of the first bytes of its data /// </summary> /// <returns>The type of the property list</returns> /// <param name="fs">An input stream pointing to the beginning of the property list data. /// The stream will be reset to the beginning of the property /// list data after the type has been determined.</param> static int DetermineType(Stream fs) { //Skip any possible whitespace at the beginning of the file byte[] magicBytes = new byte[8]; int b; long index = -1; bool bom = false; long mark; do { mark = fs.Position; b = fs.ReadByte(); index++; //Check if we are reading the Unicode byte order mark (BOM) and skip it bom = index < 3 && ((index == 0 && b == 0xEF) || (bom && ((index == 1 && b == 0xBB) || (index == 2 && b == 0xBF)))); } while (b != -1 && b == ' ' || b == '\t' || b == '\r' || b == '\n' || b == '\f' || bom); magicBytes[0] = (byte)b; int read = fs.Read(magicBytes, 1, 7); int type = DetermineType(Encoding.ASCII.GetString(magicBytes, 0, read)); fs.Seek(mark, SeekOrigin.Begin); //if(fs.markSupported()) // fs.reset(); return type; } /// <summary> /// Reads all bytes from an Stream and stores them in an array, up to /// a maximum count. /// </summary> /// <param name="fs">The Stream pointing to the data that should be stored in the array.</param> internal static byte[] ReadAll(Stream fs) { using (MemoryStream outputStream = new MemoryStream()) { fs.CopyTo(outputStream); return outputStream.ToArray(); } } /// <summary> /// Parses a property list from a file. /// </summary> /// <param name="filePath">Path to the property list file.</param> /// <returns>The root object in the property list. This is usually a NSDictionary but can also be a NSArray.</returns> public static NSObject Parse(string filePath) { return Parse(new FileInfo(filePath)); } /// <summary> /// Parses a property list from a file. /// </summary> /// <param name="f">The property list file.</param> /// <returns>The root object in the property list. This is usually a NSDictionary but can also be a NSArray.</returns> public static NSObject Parse(FileInfo f) { int type; using (FileStream fis = f.OpenRead()) { type = DetermineType(fis); } switch (type) { case TYPE_BINARY: return BinaryPropertyListParser.Parse(f); case TYPE_XML: return XmlPropertyListParser.Parse(f); case TYPE_ASCII: return ASCIIPropertyListParser.Parse(f); default: throw new PropertyListFormatException("The given file is not a property list of a supported format."); } } /// <summary> /// Parses a property list from a byte array. /// </summary> /// <param name="bytes">The property list data as a byte array.</param> /// <returns>The root object in the property list. This is usually a NSDictionary but can also be a NSArray.</returns> public static NSObject Parse(byte[] bytes) { switch (DetermineType(bytes)) { case TYPE_BINARY: return BinaryPropertyListParser.Parse(bytes); case TYPE_XML: return XmlPropertyListParser.Parse(bytes); case TYPE_ASCII: return ASCIIPropertyListParser.Parse(bytes); default: throw new PropertyListFormatException("The given data is not a property list of a supported format."); } } /// <summary> /// Parses a property list from an Stream. /// </summary> /// <param name="fs">The Stream delivering the property list data.</param> /// <returns>The root object of the property list. This is usually a NSDictionary but can also be a NSArray.</returns> public static NSObject Parse(Stream fs) { return Parse(ReadAll(fs)); } /// <summary> /// Saves a property list with the given object as root into a XML file. /// </summary> /// <param name="root">The root object.</param> /// <param name="outFile">The output file.</param> /// <exception cref="IOException">When an error occurs during the writing process.</exception> public static void SaveAsXml(NSObject root, FileInfo outFile) { string parent = outFile.DirectoryName; if (!Directory.Exists(parent)) Directory.CreateDirectory(parent); // Use Create here -- to make sure that when the updated file is shorter than // the original file, no "obsolete" data is left at the end. using (Stream fous = outFile.Open(FileMode.Create, FileAccess.ReadWrite)) { SaveAsXml(root, fous); } } /// <summary> /// Saves a property list with the given object as root in XML format into an output stream. /// </summary> /// <param name="root">The root object.</param> /// <param name="outStream">The output stream.</param> /// <exception cref="IOException">When an error occurs during the writing process.</exception> public static void SaveAsXml(NSObject root, Stream outStream) { #if NET40 // The StreamWriter constructor which takes a "leaveOpen" parameter is // not available on .NET 4.0 StreamWriter w = new StreamWriter(outStream, Encoding.UTF8); w.Write(root.ToXmlPropertyList()); w.Close(); #else using (StreamWriter w = new StreamWriter(outStream, Encoding.UTF8, bufferSize: 1024, leaveOpen: true)) { w.Write(root.ToXmlPropertyList()); } #endif } /// <summary> /// Converts a given property list file into the OS X and iOS XML format. /// </summary> /// <param name="inFile">The source file.</param> /// <param name="outFile">The target file.</param> public static void ConvertToXml(FileInfo inFile, FileInfo outFile) { NSObject root = Parse(inFile); SaveAsXml(root, outFile); } /// <summary> /// Saves a property list with the given object as root into a binary file. /// </summary> /// <param name="root">The root object.</param> /// <param name="outFile">The output file.</param> /// <exception cref="IOException">When an error occurs during the writing process.</exception> public static void SaveAsBinary(NSObject root, FileInfo outFile) { string parent = outFile.DirectoryName; if (!Directory.Exists(parent)) Directory.CreateDirectory(parent); BinaryPropertyListWriter.Write(outFile, root); } /// <summary> /// Saves a property list with the given object as root in binary format into an output stream. /// </summary> /// <param name="root">The root object.</param> /// <param name="outStream">The output stream.</param> /// <exception cref="IOException">When an error occurs during the writing process.</exception> public static void SaveAsBinary(NSObject root, Stream outStream) { BinaryPropertyListWriter.Write(outStream, root); } /// <summary> /// Converts a given property list file into the OS X and iOS binary format. /// </summary> /// <param name="inFile">The source file.</param> /// <param name="outFile">The target file.</param> public static void ConvertToBinary(FileInfo inFile, FileInfo outFile) { NSObject root = Parse(inFile); SaveAsBinary(root, outFile); } /// <summary> /// Saves a property list with the given object as root into a ASCII file. /// </summary> /// <param name="root">The root object.</param> /// <param name="outFile">The output file.</param> /// <exception cref="IOException">When an error occurs during the writing process.</exception> public static void SaveAsASCII(NSDictionary root, FileInfo outFile) { string parent = outFile.DirectoryName; if (!Directory.Exists(parent)) Directory.CreateDirectory(parent); using (Stream fous = outFile.Open(FileMode.OpenOrCreate, FileAccess.ReadWrite)) using (StreamWriter w = new StreamWriter(fous, Encoding.ASCII)) { w.Write(root.ToASCIIPropertyList()); } } /// <summary> /// Saves a property list with the given object as root into a ASCII file. /// </summary> /// <param name="root">The root object.</param> /// <param name="outFile">The output file.</param> /// <exception cref="IOException">When an error occurs during the writing process.</exception> public static void SaveAsASCII(NSArray root, FileInfo outFile) { string parent = outFile.DirectoryName; if (!Directory.Exists(parent)) Directory.CreateDirectory(parent); using (Stream fous = outFile.Open(FileMode.OpenOrCreate, FileAccess.ReadWrite)) using (StreamWriter w = new StreamWriter(fous, Encoding.ASCII)) { w.Write(root.ToASCIIPropertyList()); } } /// <summary> /// Converts a given property list file into ASCII format. /// </summary> /// <param name="inFile">The source file.</param> /// <param name="outFile">The target file.</param> public static void ConvertToASCII(FileInfo inFile, FileInfo outFile) { NSObject root = Parse(inFile); if (root is NSDictionary) { SaveAsASCII((NSDictionary)root, outFile); } else if (root is NSArray) { SaveAsASCII((NSArray)root, outFile); } else { throw new PropertyListFormatException("The root of the given input property list " + "is neither a Dictionary nor an Array!"); } } /// <summary> /// Saves a property list with the given object as root into a GnuStep ASCII file. /// </summary> /// <param name="root">The root object.</param> /// <param name="outFile">The output file.</param> /// <exception cref="IOException">When an error occurs during the writing process.</exception> public static void SaveAsGnuStepASCII(NSDictionary root, FileInfo outFile) { string parent = outFile.DirectoryName; if (!Directory.Exists(parent)) Directory.CreateDirectory(parent); using (Stream fous = outFile.Open(FileMode.OpenOrCreate, FileAccess.ReadWrite)) using (StreamWriter w = new StreamWriter(fous, Encoding.ASCII)) { w.Write(root.ToGnuStepASCIIPropertyList()); } } /// <summary> /// Saves a property list with the given object as root into a GnuStep ASCII file. /// </summary> /// <param name="root">The root object.</param> /// <param name="outFile">The output file.</param> /// <exception cref="IOException">When an error occurs during the writing process.</exception> public static void SaveAsGnuStepASCII(NSArray root, FileInfo outFile) { string parent = outFile.DirectoryName; if (!Directory.Exists(parent)) Directory.CreateDirectory(parent); using (Stream fous = outFile.Open(FileMode.OpenOrCreate, FileAccess.ReadWrite)) using (StreamWriter w = new StreamWriter(fous, Encoding.ASCII)) { w.Write(root.ToGnuStepASCIIPropertyList()); } } /// <summary> /// Converts a given property list file into GnuStep ASCII format. /// </summary> /// <param name="inFile">The source file.</param> /// <param name="outFile">The target file.</param> public static void ConvertToGnuStepASCII(FileInfo inFile, FileInfo outFile) { NSObject root = Parse(inFile); if (root is NSDictionary) { SaveAsGnuStepASCII((NSDictionary)root, outFile); } else if (root is NSArray) { SaveAsGnuStepASCII((NSArray)root, outFile); } else { throw new PropertyListFormatException("The root of the given input property list " + "is neither a Dictionary nor an Array!"); } } } }
2881099/dotnetGen_postgresql
7,283
GenPg/WinFormClass/Socket/BaseSocket.cs
/********************************************************************************** * * 此文件代码由 NicPetShop.exe 自动生成,您没有必要修改它或删除它 * NicPetShop.exe 能将数据库的关系映射到 c#,让您使用更方便,您无需要担心它的性能 * NicPetShop.exe 将永久免费给大家使用 * * Author: Nic * QQ: 2881099 * Email: kellynic@163.com * 帮助: http://www.kellynic.com/default.asp?tag=NicPetShop * **********************************************************************************/ using System; using System.IO; using System.Collections.Generic; using System.Globalization; using System.Net.Sockets; using System.Text; using System.Threading; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using System.Reflection; public class BaseSocket { protected void Write(Stream stream, SocketMessager messager) { MemoryStream ms = new MemoryStream(); byte[] buff = Encoding.UTF8.GetBytes(messager.GetCanParseString()); ms.Write(buff, 0, buff.Length); if (messager.Arg != null) { buff = Deflate.Compress(BaseSocket.Serialize(messager.Arg)); ms.Write(buff, 0, buff.Length); } this.Write(stream, ms.ToArray()); ms.Close(); } private void Write(Stream stream, byte[] data) { MemoryStream ms = new MemoryStream(); byte[] buff = Encoding.UTF8.GetBytes(Convert.ToString(data.Length + 8, 16).PadRight(8)); ms.Write(buff, 0, buff.Length); ms.Write(data, 0, data.Length); buff = ms.ToArray(); ms.Close(); stream.Write(buff, 0, buff.Length); } protected SocketMessager Read(Stream stream) { byte[] data = new byte[8]; int bytes = 0; int overs = data.Length; string size = string.Empty; while (overs > 0) { bytes = stream.Read(data, 0, overs); overs -= bytes; size += Encoding.UTF8.GetString(data, 0, bytes); } if (int.TryParse(size, NumberStyles.HexNumber, null, out overs) == false) { return null; } overs -= data.Length; MemoryStream ms = new MemoryStream(); data = new Byte[1024]; while (overs > 0) { bytes = stream.Read(data, 0, overs < data.Length ? overs : data.Length); overs -= bytes; ms.Write(data, 0, bytes); } data = ms.ToArray(); ms.Close(); return SocketMessager.Parse(data); } public static int findBytes(byte[] source, byte[] find, int startIndex) { if (find == null) return -1; if (find.Length == 0) return -1; if (source == null) return -1; if (source.Length == 0) return -1; if (startIndex < 0) startIndex = 0; int idx = -1, idx2 = startIndex - 1; do { idx2 = idx = Array.FindIndex<byte>(source, Math.Min(idx2 + 1, source.Length), delegate (byte b) { return b == find[0]; }); if (idx2 != -1) { for (int a = 1; a < find.Length; a++) { if (++idx2 >= source.Length || source[idx2] != find[a]) { idx = -1; break; } } if (idx != -1) break; } } while (idx2 != -1); return idx; } public static byte[] Serialize(object obj) { IFormatter formatter = new BinaryFormatter(); MemoryStream ms = new MemoryStream(); formatter.Serialize(ms, obj); byte[] data = ms.ToArray(); ms.Close(); return data; } public static object Deserialize(byte[] stream) { IFormatter formatter = new BinaryFormatter(); formatter.Binder = new TransmissionBinder(); MemoryStream ms = new MemoryStream(stream); object obj = formatter.Deserialize(ms); ms.Close(); return obj; } } internal class TransmissionBinder : SerializationBinder { public override Type BindToType(string assemblyName, string typeName) { //var ass = AppDomain.CurrentDomain.GetAssemblies(); //foreach (var a in ass) if (a.FullName == assemblyName) return a.GetType(typeName); //foreach (var a in ass) if (a.GetName().Name == "Common") return a.GetType(typeName); return Type.GetType(typeName.Replace("Common, ", "GenPg, ")); } } public class SocketMessager { private static int _identity; public static readonly SocketMessager SYS_TEST_LINK = new SocketMessager("\0"); public static readonly SocketMessager SYS_HELLO_WELCOME = new SocketMessager("Hello, Welcome!"); public static readonly SocketMessager SYS_ACCESS_DENIED = new SocketMessager("Access Denied."); private int _id; public bool _isChangeId; private string _action; private string _permission; private DateTime _remoteTime; private object _arg; private Exception _exception; public SocketMessager(string action) : this(action, null, null) { } public SocketMessager(string action, object arg) : this(action, null, arg) { } public SocketMessager(string action, string permission, object arg) { this._id = Interlocked.Increment(ref _identity); this._action = action == null ? string.Empty : action; this._permission = permission == null ? string.Empty : permission; this._arg = arg; this._remoteTime = DateTime.Now; } public override string ToString() { return this._remoteTime.ToString("yyyy-MM-dd HH:mm:ss") + "\t" + this._id + "\t" + this._action.Replace("\t", "\\t") + "\t" + this._permission.Replace("\t", "\\t") + "\t" + this._arg; } public string GetCanParseString() { if (string.Compare(this._action, SocketMessager.SYS_TEST_LINK.Action) == 0) { return this.Action; } else if ( string.Compare(this._action, SocketMessager.SYS_HELLO_WELCOME.Action) == 0 || string.Compare(this._action, SocketMessager.SYS_ACCESS_DENIED.Action) == 0) { return this._id + "\t" + this.Action + "\r\n"; } else { return this._id + "\t" + this._action.Replace("\\", "\\\\").Replace("\t", "\\t").Replace("\r\n", "\\n") + "\t" + this._permission.Replace("\\", "\\\\").Replace("\t", "\\t").Replace("\r\n", "\\n") + "\t" + this._remoteTime.ToString("yyyy-MM-dd HH:mm:ss") + "\r\n"; } } public static SocketMessager Parse(byte[] data) { if (data == null) return new SocketMessager("NULL"); if (data.Length == 1 && data[0] == 0) return SocketMessager.SYS_TEST_LINK; int idx = BaseSocket.findBytes(data, new byte[] { 13, 10 }, 0); string text = Encoding.UTF8.GetString(data, 0, idx); string[] loc1 = text.Split(new string[] { "\t" }, 4, StringSplitOptions.None); string loc2 = loc1[0]; string loc3 = loc1.Length > 1 ? loc1[1].Replace("\\\\", "\\").Replace("\\t", "\t").Replace("\\n", "\r\n") : null; string loc4 = loc1.Length > 2 ? loc1[2].Replace("\\\\", "\\").Replace("\\t", "\t").Replace("\\n", "\r\n") : null; string loc5 = loc1.Length > 3 ? loc1[3] : null; MemoryStream ms = new MemoryStream(); ms.Write(data, idx + 2, data.Length - idx - 2); SocketMessager messager = new SocketMessager(loc3, loc4, ms.Length > 0 ? BaseSocket.Deserialize(Deflate.Decompress(ms.ToArray())) : null); if (int.TryParse(loc2, out idx)) messager._id = idx; if (!string.IsNullOrEmpty(loc5)) DateTime.TryParse(loc5, out messager._remoteTime); if (messager._arg is Exception) messager._exception = messager._arg as Exception; return messager; } /// <summary> /// 服务端为 -,客户端为 + /// </summary> public int Id { get { return _id; } set { if (_id != value) { _isChangeId = true; } _id = value; } } public string Action { get { return _action; } } public string Permission { get { return _permission; } } public DateTime RemoteTime { get { return _remoteTime; } } public object Arg { get { return _arg; } } public Exception Exception { get { return _exception; } } }
2881099/dotnetGen_sqlserver
3,038
GenMs/plist-cil/NSArray.IList.cs
// plist-cil - An open source library to parse and generate property lists for .NET // Copyright (C) 2016 Quamotion // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; namespace PList { partial class NSArray : IList<NSObject> { /// <inheritdoc/> public NSObject this[int index] { get { return this.array[index]; } set { this.array[index] = value; } } /// <inheritdoc/> public bool IsReadOnly { get { return false; } } public void Add(object item) { this.Add(NSObject.Wrap(item)); } /// <inheritdoc/> public void Add(NSObject item) { this.array.Add(item); } /// <inheritdoc/> public void Clear() { this.array.Clear(); } public bool Contains(object item) { return this.Contains(NSObject.Wrap(item)); } /// <inheritdoc/> public bool Contains(NSObject item) { return this.array.Contains(item); } /// <inheritdoc/> public void CopyTo(NSObject[] array, int arrayIndex) { this.array.CopyTo(array, arrayIndex); } /// <inheritdoc/> public IEnumerator<NSObject> GetEnumerator() { return this.array.GetEnumerator(); } public int IndexOf(object item) { return this.array.IndexOf(NSObject.Wrap(item)); } /// <inheritdoc/> public int IndexOf(NSObject item) { return this.array.IndexOf(item); } public void Insert(int index, object item) { this.Insert(index, NSObject.Wrap(item)); } /// <inheritdoc/> public void Insert(int index, NSObject item) { this.array.Insert(index, item); } public bool Remove(object item) { return this.Remove(NSObject.Wrap(item)); } /// <inheritdoc/> public bool Remove(NSObject item) { return this.array.Remove(item); } /// <inheritdoc/> public void RemoveAt(int index) { this.array.RemoveAt(index); } /// <inheritdoc/> IEnumerator IEnumerable.GetEnumerator() { return this.array.GetEnumerator(); } } }
2881099/dotnetGen_sqlserver
9,777
GenMs/plist-cil/BinaryPropertyListWriter.cs
// plist-cil - An open source library to parse and generate property lists for .NET // Copyright (C) 2015 Natalia Portillo // // This code is based on: // plist - An open source library to parse and generate property lists // Copyright (C) 2014 Daniel Dreibrodt // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. using System; using System.IO; using System.Linq; using System.Collections.Generic; using System.Collections.ObjectModel; namespace PList { /// <summary> /// <para> /// A BinaryPropertyListWriter is a helper class for writing out /// binary property list files. /// </para><para> /// It contains an output stream and various structures for keeping track /// of which NSObjects have already been serialized, and where they were /// put in the file. /// </para> /// </summary> /// @author Keith Randall /// @author Natalia Portillo public class BinaryPropertyListWriter { /// <summary> /// Binary property list version 0.0 /// </summary> public const int VERSION_00 = 0; /// <summary> /// Binary property list version 1.0 /// </summary> public const int VERSION_10 = 10; /// <summary> /// Binary property list version 1.5 /// </summary> public const int VERSION_15 = 15; /// <summary> /// Binary property list version 2.0 /// </summary> public const int VERSION_20 = 20; /// <summary> /// Finds out the minimum binary property list format version that /// can be used to save the given NSObject tree. /// </summary> /// <returns>Version code</returns> /// <param name="root">Object root.</param> static int GetMinimumRequiredVersion(NSObject root) { int minVersion = VERSION_00; if (root == null) { minVersion = VERSION_10; } if (root is NSDictionary) { NSDictionary dict = (NSDictionary)root; foreach (NSObject o in dict.GetDictionary().Values) { int v = GetMinimumRequiredVersion(o); if (v > minVersion) minVersion = v; } } else if (root is NSArray) { NSArray array = (NSArray)root; foreach (NSObject o in array.GetArray()) { int v = GetMinimumRequiredVersion(o); if (v > minVersion) minVersion = v; } } else if (root is NSSet) { //Sets are only allowed in property lists v1+ minVersion = VERSION_10; NSSet set = (NSSet)root; foreach (NSObject o in set.AllObjects()) { int v = GetMinimumRequiredVersion(o); if (v > minVersion) minVersion = v; } } return minVersion; } /// <summary> /// Writes a binary plist file with the given object as the root. /// </summary> /// <param name="file">the file to write to</param> /// <param name="root">the source of the data to write to the file</param> /// <exception cref="IOException"></exception> public static void Write(FileInfo file, NSObject root) { using (FileStream fous = file.OpenWrite()) { Write(fous, root); } } /// <summary> /// Writes a binary plist serialization of the given object as the root. /// </summary> /// <param name="outStream">the stream to write to</param> /// <param name="root">the source of the data to write to the stream</param> /// <exception cref="IOException"></exception> public static void Write(Stream outStream, NSObject root) { int minVersion = GetMinimumRequiredVersion(root); if (minVersion > VERSION_00) { string versionString = ((minVersion == VERSION_10) ? "v1.0" : ((minVersion == VERSION_15) ? "v1.5" : ((minVersion == VERSION_20) ? "v2.0" : "v0.0"))); throw new IOException("The given property list structure cannot be saved. " + "The required version of the binary format (" + versionString + ") is not yet supported."); } BinaryPropertyListWriter w = new BinaryPropertyListWriter(outStream, minVersion); w.Write(root); } /// <summary> /// Writes a binary plist serialization of the given object as the root /// into a byte array. /// </summary> /// <returns>The byte array containing the serialized property list</returns> /// <param name="root">The root object of the property list</param> /// <exception cref="IOException"></exception> public static byte[] WriteToArray(NSObject root) { MemoryStream bout = new MemoryStream(); Write(bout, root); return bout.ToArray(); } int version = VERSION_00; // raw output stream to result file Stream outStream; // # of bytes written so far long count; // map from object to its ID Collection<NSObject> idMap = new Collection<NSObject>(); //(new IdentityEqualityComparer<NSObject>()); int idSizeInBytes; /// <summary> /// Creates a new binary property list writer /// </summary> /// <param name="outStr">The output stream into which the binary property list will be written</param> /// <exception cref="IOException">If an error occured while writing to the stream</exception> BinaryPropertyListWriter(Stream outStr) { outStream = outStr; } BinaryPropertyListWriter(Stream outStr, int version) { this.version = version; outStream = outStr; } void Write(NSObject root) { // magic bytes Write(new[] { (byte)'b', (byte)'p', (byte)'l', (byte)'i', (byte)'s', (byte)'t' }); //version switch (version) { case VERSION_00: { Write(new[] { (byte)'0', (byte)'0' }); break; } case VERSION_10: { Write(new[] { (byte)'1', (byte)'0' }); break; } case VERSION_15: { Write(new[] { (byte)'1', (byte)'5' }); break; } case VERSION_20: { Write(new[] { (byte)'2', (byte)'0' }); break; } } // assign IDs to all the objects. root.AssignIDs(this); idSizeInBytes = ComputeIdSizeInBytes(idMap.Count); // offsets of each object, indexed by ID long[] offsets = new long[idMap.Count]; // write each object, save offset for (int i = 0; i < idMap.Count; i++) { NSObject obj = idMap[i]; int id = i; offsets[id] = count; if (obj == null) { Write(0x00); } else { obj.ToBinary(this); } } // write offset table long offsetTableOffset = count; int offsetSizeInBytes = ComputeOffsetSizeInBytes(count); foreach (long offset in offsets) { WriteBytes(offset, offsetSizeInBytes); } if (version != VERSION_15) { // write trailer // 6 null bytes Write(new byte[6]); // size of an offset Write(offsetSizeInBytes); // size of a ref Write(idSizeInBytes); // number of objects WriteLong(idMap.Count); // top object int rootID = idMap.IndexOf(root); WriteLong(rootID); // offset table offset WriteLong(offsetTableOffset); } outStream.Flush(); } internal void AssignID(NSObject obj) { if (obj is UID || obj is NSArray) { idMap.Add(obj); } else if (!idMap.Contains(obj)) { idMap.Add(obj); } } internal int GetID(NSObject obj) { if (obj is UID) { var uid = obj as UID; var first = idMap.OfType<UID>().First(v => NSObject.ArrayEquals(v.Bytes, uid.Bytes)); return idMap.IndexOf(first); } else if (obj is NSArray) { int index = 0; for (int i = 0; i < idMap.Count; i++) { if (idMap[i] == obj) { index = i; break; } } return index; } else { return idMap.IndexOf(obj); } } static int ComputeIdSizeInBytes(int numberOfIds) { if (numberOfIds < 256) return 1; return numberOfIds < 65536 ? 2 : 4; } static int ComputeOffsetSizeInBytes(long maxOffset) { if (maxOffset < 256) return 1; if (maxOffset < 65536) return 2; return maxOffset < 4294967296L ? 4 : 8; } internal void WriteIntHeader(int kind, int value) { if (value < 0) throw new ArgumentException("value must be greater than or equal to 0", "value"); if (value < 15) { Write((kind << 4) + value); } else if (value < 256) { Write((kind << 4) + 15); Write(0x10); WriteBytes(value, 1); } else if (value < 65536) { Write((kind << 4) + 15); Write(0x11); WriteBytes(value, 2); } else { Write((kind << 4) + 15); Write(0x12); WriteBytes(value, 4); } } internal void Write(int b) { byte[] bBytes = new byte[1]; bBytes[0] = (byte)b; outStream.Write(bBytes, 0, 1); count++; } internal void Write(byte[] bytes) { outStream.Write(bytes, 0, bytes.Length); count += bytes.Length; } internal void WriteBytes(long value, int bytes) { // write low-order bytes big-endian style for (int i = bytes - 1; i >= 0; i--) { Write((int)(value >> (8 * i))); } } internal void WriteID(int id) { WriteBytes(id, idSizeInBytes); } internal void WriteLong(long value) { WriteBytes(value, 8); } internal void WriteDouble(double value) { WriteLong(BitConverter.DoubleToInt64Bits(value)); } } }
2881099/dotnetGen_postgresql
7,753
GenPg/WinFormClass/Socket/ClientSocket.cs
using System; using System.IO; using System.Collections.Generic; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; public class ClientSocket : BaseSocket, IDisposable { private bool _isDisposed; private IPEndPoint _remotePoint; private TcpClient _tcpClient; private Thread _thread; private bool _running; private int _receives; private int _errors; private object _errors_lock = new object(); private object _write_lock = new object(); private Dictionary<int, SyncReceive> _receiveHandlers = new Dictionary<int, SyncReceive>(); private object _receiveHandlers_lock = new object(); private DateTime _lastActive; public event ClientSocketClosedEventHandler Closed; public event ClientSocketReceiveEventHandler Receive; public event ClientSocketErrorEventHandler Error; public void Connect(string hostname, int port) { if (this._isDisposed == false && this._running == false) { this._running = true; try { IPAddress[] ips = Dns.GetHostAddresses(hostname); if (ips.Length == 0) throw new Exception("无法解析“" + hostname + "”"); this._remotePoint = new IPEndPoint(ips[0], port); this._tcpClient = new TcpClient(); this._tcpClient.Connect(this._remotePoint); } catch (Exception ex) { this._running = false; this.OnError(ex); this.OnClosed(); return; } this._receives = 0; this._errors = 0; this._lastActive = DateTime.Now; this._thread = new Thread(delegate() { while (this._running) { try { NetworkStream ns = this._tcpClient.GetStream(); ns.ReadTimeout = 1000 * 20; if (ns.DataAvailable) { SocketMessager messager = base.Read(ns); if (string.Compare(messager.Action, SocketMessager.SYS_TEST_LINK.Action) == 0) { } else if (this._receives == 0 && string.Compare(messager.Action, SocketMessager.SYS_HELLO_WELCOME.Action) == 0) { this._receives++; this.Write(messager); } else if (string.Compare(messager.Action, SocketMessager.SYS_ACCESS_DENIED.Action) == 0) { throw new Exception(SocketMessager.SYS_ACCESS_DENIED.Action); } else { ClientSocketReceiveEventArgs e = new ClientSocketReceiveEventArgs(this._receives++, messager); SyncReceive receive = null; if (this._receiveHandlers.TryGetValue(messager.Id, out receive)) { new Thread(delegate() { try { receive.ReceiveHandler(this, e); } catch (Exception ex) { this.OnError(ex); } finally { receive.Wait.Set(); } }).Start(); } else if (this.Receive != null) { new Thread(delegate() { this.OnReceive(e); }).Start(); } } this._lastActive = DateTime.Now; } else { TimeSpan ts = DateTime.Now - _lastActive; if (ts.TotalSeconds > 3) { this.Write(SocketMessager.SYS_TEST_LINK); } } if (!ns.DataAvailable) Thread.CurrentThread.Join(1); } catch (Exception ex) { this._running = false; this.OnError(ex); } } this.Close(); this.OnClosed(); }); this._thread.Start(); } } public void Close() { this._running = false; if (this._tcpClient != null) { this._tcpClient.Close(); } int[] keys = new int[this._receiveHandlers.Count]; try { this._receiveHandlers.Keys.CopyTo(keys, 0); } catch { lock (this._receiveHandlers_lock) { keys = new int[this._receiveHandlers.Count]; this._receiveHandlers.Keys.CopyTo(keys, 0); } } foreach (int key in keys) { SyncReceive receiveHandler = null; if (this._receiveHandlers.TryGetValue(key, out receiveHandler)) { receiveHandler.Wait.Set(); } } lock (this._receiveHandlers_lock) { this._receiveHandlers.Clear(); } } public void Write(SocketMessager messager) { this.Write(messager, null, TimeSpan.Zero); } public void Write(SocketMessager messager, ClientSocketReceiveEventHandler receiveHandler) { this.Write(messager, receiveHandler, TimeSpan.FromSeconds(20)); } public void Write(SocketMessager messager, ClientSocketReceiveEventHandler receiveHandler, TimeSpan timeout) { SyncReceive syncReceive = null; try { if (receiveHandler != null) { syncReceive = new SyncReceive(receiveHandler); lock (this._receiveHandlers_lock) { if (!this._receiveHandlers.ContainsKey(messager.Id)) { this._receiveHandlers.Add(messager.Id, syncReceive); } else { this._receiveHandlers[messager.Id] = syncReceive; } } } lock (_write_lock) { NetworkStream ns = this._tcpClient.GetStream(); base.Write(ns, messager); } this._lastActive = DateTime.Now; if (syncReceive != null) { syncReceive.Wait.Reset(); syncReceive.Wait.WaitOne(timeout, false); syncReceive.Wait.Set(); lock (this._receiveHandlers_lock) { this._receiveHandlers.Remove(messager.Id); } } } catch (Exception ex) { this._running = false; this.OnError(ex); if (syncReceive != null) { syncReceive.Wait.Set(); lock (this._receiveHandlers_lock) { this._receiveHandlers.Remove(messager.Id); } } } } protected virtual void OnClosed(EventArgs e) { if (this.Closed != null) { new Thread(delegate() { try { this.Closed(this, e); } catch (Exception ex) { this.OnError(ex); } }).Start(); } } protected void OnClosed() { this.OnClosed(new EventArgs()); } protected virtual void OnReceive(ClientSocketReceiveEventArgs e) { if (this.Receive != null) { try { this.Receive(this, e); } catch (Exception ex) { this.OnError(ex); } } } protected virtual void OnError(ClientSocketErrorEventArgs e) { if (this.Error != null) { this.Error(this, e); } } protected void OnError(Exception ex) { int errors = 0; lock (this._errors_lock) { errors = ++this._errors; } ClientSocketErrorEventArgs e = new ClientSocketErrorEventArgs(ex, errors); this.OnError(e); } public bool Running { get { return this._running; } } class SyncReceive : IDisposable { private ClientSocketReceiveEventHandler _receiveHandler; private ManualResetEvent _wait; public SyncReceive(ClientSocketReceiveEventHandler receiveHandler) { this._receiveHandler = receiveHandler; this._wait = new ManualResetEvent(false); } public ClientSocketReceiveEventHandler ReceiveHandler { get { return _receiveHandler; } } public ManualResetEvent Wait { get { return _wait; } } #region IDisposable 成员 public void Dispose() { this._wait.Set(); this._wait.Close(); } #endregion } #region IDisposable 成员 public void Dispose() { this._isDisposed = true; this.Close(); } #endregion } public delegate void ClientSocketClosedEventHandler(object sender, EventArgs e); public delegate void ClientSocketErrorEventHandler(object sender, ClientSocketErrorEventArgs e); public delegate void ClientSocketReceiveEventHandler(object sender, ClientSocketReceiveEventArgs e); public class ClientSocketErrorEventArgs : EventArgs { private int _errors; private Exception _exception; public ClientSocketErrorEventArgs(Exception exception, int errors) { this._exception = exception; this._errors = errors; } public int Errors { get { return _errors; } } public Exception Exception { get { return _exception; } } } public class ClientSocketReceiveEventArgs : EventArgs { private int _receives; private SocketMessager _messager; public ClientSocketReceiveEventArgs(int receives, SocketMessager messager) { this._receives = receives; this._messager = messager; } public int Receives { get { return _receives; } } public SocketMessager Messager { get { return _messager; } } }
2881099/dotnetGen_postgresql
857
ServerWinForm/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 有关程序集的常规信息通过下列属性集 // 控制。更改这些属性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("ServerWinForm")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ServerWinForm")] [assembly: AssemblyCopyright("版权所有 (C) 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 将 ComVisible 设置为 false 使此程序集中的类型 // 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型, // 则将该类型上的 ComVisible 属性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID [assembly: Guid("919d7765-864f-4c8c-9d5c-c18c7bd11e38")] // 程序集的版本信息由下面四个值组成: // // 主版本 // 次版本 // 内部版本号 // 修订号 // [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
2881099/dotnetGen_postgresql
979
ServerWinForm/Properties/Settings.Designer.cs
//------------------------------------------------------------------------------ // <auto-generated> // 此代码由工具生成。 // 运行时版本:4.0.30319.42000 // // 对此文件的更改可能会导致不正确的行为,并且如果 // 重新生成代码,这些更改将会丢失。 // </auto-generated> //------------------------------------------------------------------------------ namespace ServerWinForm.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "14.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
2881099/dotnetGen_postgresql
2,453
ServerWinForm/Properties/Resources.Designer.cs
//------------------------------------------------------------------------------ // <auto-generated> // 此代码由工具生成。 // 运行时版本:4.0.30319.42000 // // 对此文件的更改可能会导致不正确的行为,并且如果 // 重新生成代码,这些更改将会丢失。 // </auto-generated> //------------------------------------------------------------------------------ namespace ServerWinForm.Properties { using System; /// <summary> /// 一个强类型的资源类,用于查找本地化的字符串等。 /// </summary> // 此类是由 StronglyTypedResourceBuilder // 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。 // 若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen // (以 /str 作为命令选项),或重新生成 VS 项目。 [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// 返回此类使用的缓存的 ResourceManager 实例。 /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("ServerWinForm.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// 使用此强类型资源类,为所有资源查找 /// 重写当前线程的 CurrentUICulture 属性。 /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
2881099/dotnetGen_sqlserver
25,173
GenMs/plist-cil/ASCIIPropertyListParser.cs
// plist-cil - An open source library to parse and generate property lists for .NET // Copyright (C) 2015 Natalia Portillo // // This code is based on: // plist - An open source library to parse and generate property lists // Copyright (C) 2014 Daniel Dreibrodt // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. using System; using System.IO; using System.Collections.Generic; using System.Text.RegularExpressions; using System.Text; using System.Runtime.CompilerServices; namespace PList { /// <summary> /// <para> /// Parser for ASCII property lists. Supports Apple OS X/iOS and GnuStep/NeXTSTEP format. /// This parser is based on the recursive descent paradigm, but the underlying grammar /// is not explicitely defined. /// </para> /// <para> /// Resources on ASCII property list format: /// </para> /// <para> /// https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/PropertyLists/OldStylePlists/OldStylePLists.html /// </para> /// <para> /// Property List Programming Guide - Old-Style ASCII Property Lists /// </para> /// <para> /// http://www.gnustep.org/resources/documentation/Developer/Base/Reference/NSPropertyList.html /// </para> /// <para> /// GnuStep - NSPropertyListSerialization class documentation /// </para> /// </summary> /// @author Daniel Dreibrodt /// @author Natalia Portillo public class ASCIIPropertyListParser { /// <summary> /// Parses an ASCII property list file. /// </summary> /// <param name="f">The ASCII property list file..</param> /// <returns>The root object of the property list. This is usually a NSDictionary but can also be a NSArray.</returns> /// <exception cref="FormatException">When an error occurs during parsing.</exception> /// <exception cref="IOException">When an error occured while reading from the input stream.</exception> public static NSObject Parse(FileInfo f) { return Parse(f.OpenRead()); } /// <summary> /// Parses an ASCII property list from an input stream. /// </summary> /// <param name="fs">The input stream that points to the property list's data.</param> /// <returns>The root object of the property list. This is usually a NSDictionary but can also be a NSArray.</returns> /// <exception cref="FormatException">When an error occurs during parsing.</exception> /// <exception cref="IOException"></exception> public static NSObject Parse(Stream fs) { byte[] buf = PropertyListParser.ReadAll(fs); // Don't close the stream - that would be the responisibility of code that class // Parse return Parse(buf); } /// <summary> /// Parses an ASCII property list from a byte array. /// </summary> /// <param name="bytes">The ASCII property list data.</param> /// <returns>The root object of the property list. This is usually a NSDictionary but can also be a NSArray.</returns> /// <exception cref="FormatException">When an error occurs during parsing.</exception> public static NSObject Parse(byte[] bytes) { ASCIIPropertyListParser parser = new ASCIIPropertyListParser(bytes); return parser.Parse(); } /// <summary> /// A space /// </summary> public const char WHITESPACE_SPACE = ' '; /// <summary> /// A tabulator /// </summary> public const char WHITESPACE_TAB = '\t'; /// <summary> /// A newline /// </summary> public const char WHITESPACE_NEWLINE = '\n'; /// <summary> /// A carriage return /// </summary> public const char WHITESPACE_CARRIAGE_RETURN = '\r'; /// <summary> /// Token of NSArray start /// </summary> public const char ARRAY_BEGIN_TOKEN = '('; /// <summary> /// Token of NSArray end /// </summary> public const char ARRAY_END_TOKEN = ')'; /// <summary> /// Token of NSArray item delimiter /// </summary> public const char ARRAY_ITEM_DELIMITER_TOKEN = ','; /// <summary> /// Token of NSDictionary start /// </summary> public const char DICTIONARY_BEGIN_TOKEN = '{'; /// <summary> /// Token of NSDictionary end /// </summary> public const char DICTIONARY_END_TOKEN = '}'; /// <summary> /// Token of NSDictionary assignment /// </summary> public const char DICTIONARY_ASSIGN_TOKEN = '='; /// <summary> /// Token of NSDictionary item delimiter /// </summary> public const char DICTIONARY_ITEM_DELIMITER_TOKEN = ';'; /// <summary> /// Token of quoted NSString start /// </summary> public const char QUOTEDSTRING_BEGIN_TOKEN = '"'; /// <summary> /// Token of quoted NSString end /// </summary> public const char QUOTEDSTRING_END_TOKEN = '"'; /// <summary> /// Token of quoted NSString escaped character /// </summary> public const char QUOTEDSTRING_ESCAPE_TOKEN = '\\'; /// <summary> /// Token of NSData start /// </summary> public const char DATA_BEGIN_TOKEN = '<'; /// <summary> /// Token of NSData end /// </summary> public const char DATA_END_TOKEN = '>'; /// <summary> /// Token of GSObject start /// </summary> public const char DATA_GSOBJECT_BEGIN_TOKEN = '*'; /// <summary> /// Token of GSDate start /// </summary> public const char DATA_GSDATE_BEGIN_TOKEN = 'D'; /// <summary> /// Token of GSBoolean start /// </summary> public const char DATA_GSBOOL_BEGIN_TOKEN = 'B'; /// <summary> /// Token for GSBoolen's <c>true</c> /// </summary> public const char DATA_GSBOOL_TRUE_TOKEN = 'Y'; /// <summary> /// Token for GSBoolen's <c>false</c> /// </summary> public const char DATA_GSBOOL_FALSE_TOKEN = 'N'; /// <summary> /// Token for GSInteger /// </summary> public const char DATA_GSINT_BEGIN_TOKEN = 'I'; /// <summary> /// Token for GSReal /// </summary> public const char DATA_GSREAL_BEGIN_TOKEN = 'R'; /// <summary> /// Token for NSDate date field delimited /// </summary> public const char DATE_DATE_FIELD_DELIMITER = '-'; /// <summary> /// Token for NSDate time field delimiter /// </summary> public const char DATE_TIME_FIELD_DELIMITER = ':'; /// <summary> /// Token for GSDate date and time delimiter /// </summary> public const char DATE_GS_DATE_TIME_DELIMITER = ' '; /// <summary> /// Token for NSDate date and time delimiter /// </summary> public const char DATE_APPLE_DATE_TIME_DELIMITER = 'T'; /// <summary> /// Token for NSDate end /// </summary> public const char DATE_APPLE_END_TOKEN = 'Z'; /// <summary> /// Token for comment start /// </summary> public const char COMMENT_BEGIN_TOKEN = '/'; /// <summary> /// Second token for multiline comment /// </summary> public const char MULTILINE_COMMENT_SECOND_TOKEN = '*'; /// <summary> /// Second token for singleline comment /// </summary> public const char SINGLELINE_COMMENT_SECOND_TOKEN = '/'; /// <summary> /// End token for multiline comment /// </summary> public const char MULTILINE_COMMENT_END_TOKEN = '/'; /** * Property list source data */ byte[] data; /** * Current parsing index */ int index; /** * Only allow subclasses to change instantiation. */ protected ASCIIPropertyListParser() { } /// <summary> /// Creates a new parser for the given property list content. /// </summary> /// <param name="propertyListContent">The content of the property list that is to be parsed.</param> ASCIIPropertyListParser(byte[] propertyListContent) { data = propertyListContent; } /// <summary> /// Checks whether the given sequence of symbols can be accepted. /// </summary> /// <returns>Whether the given tokens occur at the current parsing position.</returns> /// <param name="sequence">The sequence of tokens to look for.</param> bool AcceptSequence(params char[] sequence) { for (int i = 0; i < sequence.Length; i++) { if (data[index + i] != sequence[i]) return false; } return true; } /// <summary> /// Checks whether the given symbols can be accepted, that is, if one /// of the given symbols is found at the current parsing position. /// </summary> /// <param name="acceptableSymbols">The symbols to check.</param> /// <returns>Whether one of the symbols can be accepted or not.</returns> bool Accept(params char[] acceptableSymbols) { bool symbolPresent = false; foreach (char c in acceptableSymbols) symbolPresent |= data[index] == c; return symbolPresent; } /// <summary> /// Checks whether the given symbol can be accepted, that is, if /// the given symbols is found at the current parsing position. /// </summary> /// <param name="acceptableSymbol">The symbol to check.</param> /// <returns>Whether the symbol can be accepted or not.</returns> bool Accept(char acceptableSymbol) { return data[index] == acceptableSymbol; } /// <summary> /// Expects the input to have one of the given symbols at the current parsing position. /// </summary> /// <param name="expectedSymbols">The expected symbols.</param> /// <exception cref="FormatException">If none of the expected symbols could be found.</exception> void Expect(params char[] expectedSymbols) { if (!Accept(expectedSymbols)) { String excString = "Expected '" + expectedSymbols[0] + "'"; for (int i = 1; i < expectedSymbols.Length; i++) excString += " or '" + expectedSymbols[i] + "'"; excString += " but found '" + (char)data[index] + "'"; throw new FormatException(String.Format("{0} at {1}", excString, index)); } } /// <summary> /// Expects the input to have the given symbol at the current parsing position. /// </summary> /// <param name="expectedSymbol">The expected symbol.</param> /// <exception cref="FormatException">If the expected symbol could be found.</exception> void Expect(char expectedSymbol) { if (!Accept(expectedSymbol)) throw new FormatException(String.Format("Expected '{0}' but found '{1}' at {2}", expectedSymbol, data[index], index)); } /// <summary> /// Reads an expected symbol. /// </summary> /// <param name="symbol">The symbol to read.</param> /// <exception cref="FormatException">If the expected symbol could not be read.</exception> void Read(char symbol) { Expect(symbol); index++; } /** * Skips the current symbol. */ void Skip() { index++; } /// <summary> /// Skips several symbols /// </summary> /// <param name="numSymbols">The amount of symbols to skip.</param> void Skip(int numSymbols) { index += numSymbols; } /** * Skips all whitespaces and comments from the current parsing position onward. */ void SkipWhitespacesAndComments() { bool commentSkipped; do { commentSkipped = false; //Skip whitespaces while (Accept(WHITESPACE_CARRIAGE_RETURN, WHITESPACE_NEWLINE, WHITESPACE_SPACE, WHITESPACE_TAB)) { Skip(); } //Skip single line comments "//..." if (AcceptSequence(COMMENT_BEGIN_TOKEN, SINGLELINE_COMMENT_SECOND_TOKEN)) { Skip(2); ReadInputUntil(WHITESPACE_CARRIAGE_RETURN, WHITESPACE_NEWLINE); commentSkipped = true; } //Skip multi line comments "/* ... */" else if (AcceptSequence(COMMENT_BEGIN_TOKEN, MULTILINE_COMMENT_SECOND_TOKEN)) { Skip(2); while (true) { if (AcceptSequence(MULTILINE_COMMENT_SECOND_TOKEN, MULTILINE_COMMENT_END_TOKEN)) { Skip(2); break; } Skip(); } commentSkipped = true; } } while (commentSkipped); //if a comment was skipped more whitespace or another comment can follow, so skip again } /// <summary> /// Reads input until one of the given symbols is found. /// </summary> /// <returns>The input until one the given symbols.</returns> /// <param name="symbols">The symbols that can occur after the string to read.</param> string ReadInputUntil(params char[] symbols) { string s = ""; while (!Accept(symbols)) { s += (char)data[index]; Skip(); } return s; } /// <summary> /// Reads input until the given symbol is found. /// </summary> /// <returns>The input until the given symbol.</returns> /// <param name="symbol">The symbol that can occur after the string to read.</param> string ReadInputUntil(char symbol) { String s = ""; while (!Accept(symbol)) { s += (char)data[index]; Skip(); } return s; } /// <summary> /// Parses the property list from the beginning and returns the root object /// of the property list. /// </summary> /// <returns>The root object of the property list. This can either be a NSDictionary or a NSArray.</returns> /// <exception cref="FormatException">When an error occured during parsing</exception> public NSObject Parse() { index = 0; //Skip Unicode byte order mark (BOM) if (data.Length >= 3 && (data[0] & 0xFF) == 0xEF && (data[1] & 0xFF) == 0xBB && (data[2] & 0xFF) == 0xBF) Skip(3); SkipWhitespacesAndComments(); Expect(DICTIONARY_BEGIN_TOKEN, ARRAY_BEGIN_TOKEN, COMMENT_BEGIN_TOKEN); try { return ParseObject(); } catch (IndexOutOfRangeException) { throw new FormatException(String.Format("Reached end of input unexpectedly at {0}.", index)); } } /// <summary> /// Parses the NSObject found at the current position in the property list /// data stream. /// </summary> /// <returns>The parsed NSObject.</returns> /// <seealso cref="ASCIIPropertyListParser.index"/> NSObject ParseObject() { switch (data[index]) { case (byte)ARRAY_BEGIN_TOKEN: { return ParseArray(); } case (byte)DICTIONARY_BEGIN_TOKEN: { return ParseDictionary(); } case (byte)DATA_BEGIN_TOKEN: { return ParseData(); } case (byte)QUOTEDSTRING_BEGIN_TOKEN: { string quotedString = ParseQuotedString(); //apple dates are quoted strings of length 20 and after the 4 year digits a dash is found if (quotedString.Length == 20 && quotedString[4] == DATE_DATE_FIELD_DELIMITER) { try { return new NSDate(quotedString); } catch (Exception) { //not a date? --> return string return new NSString(quotedString); } } return new NSString(quotedString); } default: { //0-9 if (data[index] > 0x2F && data[index] < 0x3A) { //could be a date or just a string return ParseDateString(); } else { //non-numerical -> string or boolean string parsedString = ParseString(); return new NSString(parsedString); } } } } /// <summary> /// Parses an array from the current parsing position. /// The prerequisite for calling this method is, that an array begin token has been read. /// </summary> /// <returns>The array found at the parsing position.</returns> NSArray ParseArray() { //Skip begin token Skip(); SkipWhitespacesAndComments(); List<NSObject> objects = new List<NSObject>(); while (!Accept(ARRAY_END_TOKEN)) { objects.Add(ParseObject()); SkipWhitespacesAndComments(); if (Accept(ARRAY_ITEM_DELIMITER_TOKEN)) { Skip(); } else { break; //must have reached end of array } SkipWhitespacesAndComments(); } //parse end token Read(ARRAY_END_TOKEN); return new NSArray(objects.ToArray()); } /// <summary> /// Parses a dictionary from the current parsing position. /// The prerequisite for calling this method is, that a dictionary begin token has been read. /// </summary> /// <returns>The dictionary found at the parsing position.</returns> NSDictionary ParseDictionary() { //Skip begin token Skip(); SkipWhitespacesAndComments(); NSDictionary dict = new NSDictionary(); while (!Accept(DICTIONARY_END_TOKEN)) { //Parse key string keyString; if (Accept(QUOTEDSTRING_BEGIN_TOKEN)) keyString = ParseQuotedString(); else keyString = ParseString(); SkipWhitespacesAndComments(); //Parse assign token Read(DICTIONARY_ASSIGN_TOKEN); SkipWhitespacesAndComments(); NSObject nso = ParseObject(); dict.Add(keyString, nso); SkipWhitespacesAndComments(); Read(DICTIONARY_ITEM_DELIMITER_TOKEN); SkipWhitespacesAndComments(); } //skip end token Skip(); return dict; } /// <summary> /// Parses a data object from the current parsing position. /// This can either be a NSData object or a GnuStep NSNumber or NSDate. /// The prerequisite for calling this method is, that a data begin token has been read. /// </summary> /// <returns>The data object found at the parsing position.</returns> NSObject ParseData() { NSObject obj = null; //Skip begin token Skip(); if (Accept(DATA_GSOBJECT_BEGIN_TOKEN)) { Skip(); Expect(DATA_GSBOOL_BEGIN_TOKEN, DATA_GSDATE_BEGIN_TOKEN, DATA_GSINT_BEGIN_TOKEN, DATA_GSREAL_BEGIN_TOKEN); if (Accept(DATA_GSBOOL_BEGIN_TOKEN)) { //Boolean Skip(); Expect(DATA_GSBOOL_TRUE_TOKEN, DATA_GSBOOL_FALSE_TOKEN); if (Accept(DATA_GSBOOL_TRUE_TOKEN)) obj = new NSNumber(true); else obj = new NSNumber(false); //Skip the parsed boolean token Skip(); } else if (Accept(DATA_GSDATE_BEGIN_TOKEN)) { //Date Skip(); string dateString = ReadInputUntil(DATA_END_TOKEN); obj = new NSDate(dateString); } else if (Accept(DATA_GSINT_BEGIN_TOKEN, DATA_GSREAL_BEGIN_TOKEN)) { //Number Skip(); string numberString = ReadInputUntil(DATA_END_TOKEN); obj = new NSNumber(numberString); } //parse data end token Read(DATA_END_TOKEN); } else { string dataString = ReadInputUntil(DATA_END_TOKEN); dataString = Regex.Replace(dataString, "\\s+", ""); int numBytes = dataString.Length / 2; byte[] bytes = new byte[numBytes]; for (int i = 0; i < bytes.Length; i++) { string byteString = dataString.Substring(i * 2, 2); int byteValue = Convert.ToInt32(byteString, 16); bytes[i] = (byte)byteValue; } obj = new NSData(bytes); //skip end token Skip(); } return obj; } /// <summary> /// Attempts to parse a plain string as a date if possible. /// </summary> /// <returns>A NSDate if the string represents such an object. Otherwise a NSString is returned.</returns> NSObject ParseDateString() { string numericalString = ParseString(); if (numericalString.Length > 4 && numericalString[4] == DATE_DATE_FIELD_DELIMITER) { try { return new NSDate(numericalString); } catch (Exception) { //An exception occurs if the string is not a date but just a string } } return new NSString(numericalString); } /// <summary> /// Parses a plain string from the current parsing position. /// The string is made up of all characters to the next whitespace, delimiter token or assignment token. /// </summary> /// <returns>The string found at the current parsing position.</returns> string ParseString() { return ReadInputUntil(WHITESPACE_SPACE, WHITESPACE_TAB, WHITESPACE_NEWLINE, WHITESPACE_CARRIAGE_RETURN, ARRAY_ITEM_DELIMITER_TOKEN, DICTIONARY_ITEM_DELIMITER_TOKEN, DICTIONARY_ASSIGN_TOKEN, ARRAY_END_TOKEN); } /// <summary> /// Parses a quoted string from the current parsing position. /// The prerequisite for calling this method is, that a quoted string begin token has been read. /// </summary> /// <returns>The quoted string found at the parsing method with all special characters unescaped.</returns> /// <exception cref="FormatException">If an error occured during parsing.</exception> string ParseQuotedString() { //Skip begin token Skip(); string quotedString = ""; bool unescapedBackslash = true; //Read from opening quotation marks to closing quotation marks and skip escaped quotation marks while (data[index] != QUOTEDSTRING_END_TOKEN || (data[index - 1] == QUOTEDSTRING_ESCAPE_TOKEN && unescapedBackslash)) { quotedString += (char)data[index]; if (Accept(QUOTEDSTRING_ESCAPE_TOKEN)) { unescapedBackslash = !(data[index - 1] == QUOTEDSTRING_ESCAPE_TOKEN && unescapedBackslash); } Skip(); } string unescapedString; try { unescapedString = ParseQuotedString(quotedString); } catch (Exception) { throw new FormatException(String.Format("The quoted string could not be parsed at {0}.", index)); } //skip end token Skip(); return unescapedString; } /// <summary> /// Parses a string according to the format specified for ASCII property lists. /// Such strings can contain escape sequences which are unescaped in this method. /// </summary> /// <returns>The unescaped string in UTF-8 or ASCII format, depending on the contained characters.</returns> /// <param name="s">The escaped string according to the ASCII property list format, without leading and trailing quotation marks.</param> /// <exception cref="ArgumentException">If the en-/decoder for the UTF-8 or ASCII encoding could not be loaded</exception> /// <exception cref="EncoderFallbackException">If the string is encoded neither in ASCII nor in UTF-8</exception> public static string ParseQuotedString(string s) { List<byte> strBytes = new List<byte>(); var characters = (IEnumerable<char>)s.ToCharArray(); var c = characters.GetEnumerator(); while (c.MoveNext()) { switch (c.Current) { case '\\': { //An escaped sequence is following byte[] bts = Encoding.UTF8.GetBytes(ParseEscapedSequence(c)); foreach (byte b in bts) strBytes.Add(b); break; } default: { //a normal ASCII char strBytes.Add((byte)0); strBytes.Add((byte)c.Current); break; } } } byte[] bytArr = new byte[strBytes.Count]; int i = 0; foreach (byte b in strBytes) { bytArr[i] = b; i++; } //Build string string result = Encoding.BigEndianUnicode.GetString(bytArr); //If the string can be represented in the ASCII codepage // --> use ASCII encoding if (IsASCIIEncodable(result)) return Encoding.ASCII.GetString(Encoding.Convert(Encoding.BigEndianUnicode, Encoding.ASCII, bytArr)); //The string contains characters outside the ASCII codepage // --> use the UTF-8 encoded string return result; } /// <summary> /// Unescapes an escaped character sequence, e.g. \\u00FC. /// </summary> /// <returns>The unescaped character as a string.</returns> /// <param name="iterator">The string character iterator pointing to the first character after the backslash</param> /// <exception cref="EncoderFallbackException">If an invalid Unicode or ASCII escape sequence is found.</exception> private static string ParseEscapedSequence(IEnumerator<char> iterator) { iterator.MoveNext(); char c = iterator.Current; if (c == '\\') { return Encoding.UTF8.GetString(new byte[] { 0, (byte)'\\' }); } else if (c == '"') { return Encoding.UTF8.GetString(new byte[] { 0, (byte)'\"' }); } else if (c == 'b') { return Encoding.UTF8.GetString(new byte[] { 0, (byte)'\b' }); } else if (c == 'n') { return Encoding.UTF8.GetString(new byte[] { 0, (byte)'\n' }); } else if (c == 'r') { return Encoding.UTF8.GetString(new byte[] { 0, (byte)'\r' }); } else if (c == 't') { return Encoding.UTF8.GetString(new byte[] { 0, (byte)'\t' }); } else if (c == 'U' || c == 'u') { //4 digit hex Unicode value string byte1 = ""; iterator.MoveNext(); byte1 += iterator.Current; iterator.MoveNext(); byte1 += iterator.Current; string byte2 = ""; iterator.MoveNext(); byte2 += iterator.Current; iterator.MoveNext(); byte2 += iterator.Current; byte[] stringBytes = { (byte)Convert.ToInt32(byte1, 16), (byte)Convert.ToInt32(byte2, 16) }; return Encoding.UTF8.GetString(stringBytes); } else { //3 digit octal ASCII value string num = ""; num += c; iterator.MoveNext(); num += iterator.Current; iterator.MoveNext(); num += iterator.Current; int asciiCode = Convert.ToInt32(num, 8); byte[] stringBytes = { 0, (byte)asciiCode }; return Encoding.UTF8.GetString(stringBytes); } } internal static bool IsASCIIEncodable(string text) { foreach (char c in text) if ((int)c > 0x7F) return false; return true; } } }
2881099/dotnetGen_postgresql
851
MakeCode/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 有关程序集的常规信息通过下列属性集 // 控制。更改这些属性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("NicPetShop")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("NicPetShop")] [assembly: AssemblyCopyright("版权所有 (C) 2008")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 将 ComVisible 设置为 false 使此程序集中的类型 // 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型, // 则将该类型上的 ComVisible 属性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID [assembly: Guid("d26d6e70-6297-4f9c-992d-02c5478ca63b")] // 程序集的版本信息由下面四个值组成: // // 主版本 // 次版本 // 内部版本号 // 修订号 // [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
2881099/dotnetGen_postgresql
5,451
MakeCode/Properties/Settings.Designer.cs
//------------------------------------------------------------------------------ // <auto-generated> // 此代码由工具生成。 // 运行时版本:4.0.30319.42000 // // 对此文件的更改可能会导致不正确的行为,并且如果 // 重新生成代码,这些更改将会丢失。 // </auto-generated> //------------------------------------------------------------------------------ namespace MakeCode.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "14.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("")] public string txtServer_text { get { return ((string)(this["txtServer_text"])); } set { this["txtServer_text"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("")] public string txtUsername_text { get { return ((string)(this["txtUsername_text"])); } set { this["txtUsername_text"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("")] public string txtPassword_text { get { return ((string)(this["txtPassword_text"])); } set { this["txtPassword_text"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("")] public string txtSolution_text { get { return ((string)(this["txtSolution_text"])); } set { this["txtSolution_text"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("False")] public bool chkSolution_checked { get { return ((bool)(this["chkSolution_checked"])); } set { this["chkSolution_checked"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("True")] public bool chkIntegrated_Checked { get { return ((bool)(this["chkIntegrated_Checked"])); } set { this["chkIntegrated_Checked"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("False")] public bool chkMultiDB_checked { get { return ((bool)(this["chkMultiDB_checked"])); } set { this["chkMultiDB_checked"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("False")] public bool chkWebAdmin_checked { get { return ((bool)(this["chkWebAdmin_checked"])); } set { this["chkWebAdmin_checked"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("False")] public bool chkDownloadRes_checked { get { return ((bool)(this["chkDownloadRes_checked"])); } set { this["chkDownloadRes_checked"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("5432")] public string txtPort_text { get { return ((string)(this["txtPort_text"])); } set { this["txtPort_text"] = value; } } } }
2881099/dotnetGen_postgresql
2,443
MakeCode/Properties/Resources.Designer.cs
//------------------------------------------------------------------------------ // <auto-generated> // 此代码由工具生成。 // 运行时版本:4.0.30319.42000 // // 对此文件的更改可能会导致不正确的行为,并且如果 // 重新生成代码,这些更改将会丢失。 // </auto-generated> //------------------------------------------------------------------------------ namespace MakeCode.Properties { using System; /// <summary> /// 一个强类型的资源类,用于查找本地化的字符串等。 /// </summary> // 此类是由 StronglyTypedResourceBuilder // 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。 // 若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen // (以 /str 作为命令选项),或重新生成 VS 项目。 [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// 返回此类使用的缓存的 ResourceManager 实例。 /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("MakeCode.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// 使用此强类型资源类,为所有资源查找 /// 重写当前线程的 CurrentUICulture 属性。 /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
2881099/dotnetGen_postgresql
1,594
MakeCode/Properties/Settings.settings
<?xml version='1.0' encoding='utf-8'?> <SettingsFile xmlns="http://schemas.microsoft.com/VisualStudio/2004/01/settings" CurrentProfile="(Default)" GeneratedClassNamespace="MakeCode.Properties" GeneratedClassName="Settings"> <Profiles /> <Settings> <Setting Name="txtServer_text" Type="System.String" Scope="User"> <Value Profile="(Default)" /> </Setting> <Setting Name="txtUsername_text" Type="System.String" Scope="User"> <Value Profile="(Default)" /> </Setting> <Setting Name="txtPassword_text" Type="System.String" Scope="User"> <Value Profile="(Default)" /> </Setting> <Setting Name="txtSolution_text" Type="System.String" Scope="User"> <Value Profile="(Default)" /> </Setting> <Setting Name="chkSolution_checked" Type="System.Boolean" Scope="User"> <Value Profile="(Default)">False</Value> </Setting> <Setting Name="chkIntegrated_Checked" Type="System.Boolean" Scope="User"> <Value Profile="(Default)">True</Value> </Setting> <Setting Name="chkMultiDB_checked" Type="System.Boolean" Scope="User"> <Value Profile="(Default)">False</Value> </Setting> <Setting Name="chkWebAdmin_checked" Type="System.Boolean" Scope="User"> <Value Profile="(Default)">False</Value> </Setting> <Setting Name="chkDownloadRes_checked" Type="System.Boolean" Scope="User"> <Value Profile="(Default)">False</Value> </Setting> <Setting Name="txtPort_text" Type="System.String" Scope="User"> <Value Profile="(Default)">5432</Value> </Setting> </Settings> </SettingsFile>
2881099/dotnetGen_sqlserver
16,113
GenMs/plist-cil/NSObject.cs
// plist-cil - An open source library to parse and generate property lists for .NET // Copyright (C) 2015 Natalia Portillo // // This code is based on: // plist - An open source library to parse and generate property lists // Copyright (C) 2014 Daniel Dreibrodt // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. using System; using System.Text; using System.Collections.Generic; using System.IO; using System.Reflection; namespace PList { /// <summary> /// <para> /// Abstract interface for any object contained in a property list. /// </para><para> /// The names and functions of the various objects orient themselves /// towards Apple's Cocoa API. /// </para> /// </summary> /// @author Daniel Dreibrodt /// @author Natalia Portillo public abstract class NSObject { /// <summary> /// The newline character used for generating the XML output. /// To maintain compatibility with the Apple format, only a newline character /// is used (as opposed to cr+lf which is normally used on Windows). /// </summary> readonly internal static string NEWLINE = "\n"; /// <summary> /// The identation character used for generating the XML output. This is the /// tabulator character. /// </summary> readonly static string INDENT = "\t"; /// <summary> /// The maximum length of the text lines to be used when generating /// ASCII property lists. But this number is only a guideline it is not /// guaranteed that it will not be overstepped. /// </summary> internal readonly static int ASCII_LINE_LENGTH = 80; /// <summary> /// Generates the XML representation of the object (without XML headers or enclosing plist-tags). /// </summary> /// <param name="xml">The StringBuilder onto which the XML representation is appended.</param> /// <param name="level">The indentation level of the object.</param> internal abstract void ToXml(StringBuilder xml, int level); /// <summary> /// Assigns IDs to all the objects in this NSObject subtree. /// </summary> /// <param name="outPlist">The writer object that handles the binary serialization.</param> internal virtual void AssignIDs(BinaryPropertyListWriter outPlist) { outPlist.AssignID(this); } /// <summary> /// Generates the binary representation of the object. /// </summary> /// <param name="outPlist">The output stream to serialize the object to.</param> internal abstract void ToBinary(BinaryPropertyListWriter outPlist); /// <summary> /// Generates a valid XML property list including headers using this object as root. /// </summary> /// <returns>The XML representation of the property list including XML header and doctype information.</returns> public string ToXmlPropertyList() { StringBuilder xml = new StringBuilder("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); xml.Append(NSObject.NEWLINE); xml.Append("<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">"); xml.Append(NSObject.NEWLINE); xml.Append("<plist version=\"1.0\">"); xml.Append(NSObject.NEWLINE); ToXml(xml, 0); xml.Append(NSObject.NEWLINE); xml.Append("</plist>"); xml.Append(NSObject.NEWLINE); return xml.ToString(); } /// <summary> /// Generates the ASCII representation of this object. /// The generated ASCII representation does not end with a newline. /// Complies with https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/PropertyLists/OldStylePlists/OldStylePLists.html /// </summary> /// <param name="ascii">The StringBuilder onto which the ASCII representation is appended.</param> /// <param name="level">The indentation level of the object.</param> internal abstract void ToASCII(StringBuilder ascii, int level); /// <summary> /// Generates the ASCII representation of this object in the GnuStep format. /// The generated ASCII representation does not end with a newline. /// </summary> /// <param name="ascii">The StringBuilder onto which the ASCII representation is appended.</param> /// <param name="level">The indentation level of the object.</param> internal abstract void ToASCIIGnuStep(StringBuilder ascii, int level); /// <summary> /// Helper method that adds correct identation to the xml output. /// Calling this method will add <c>level</c> number of tab characters /// to the <c>xml</c> string. /// </summary> /// <param name="xml">The string builder for the XML document.</param> /// <param name="level">The level of identation.</param> internal static void Indent(StringBuilder xml, int level) { for (int i = 0; i < level; i++) xml.Append(INDENT); } /// <summary> /// Wraps the given value inside a NSObject. /// </summary> /// <param name="value">The value to represent as a NSObject.</param> /// <returns>A NSObject representing the given value.</returns> public static NSNumber Wrap(long value) { return new NSNumber(value); } /// <summary> /// Wraps the given value inside a NSObject. /// </summary> /// <param name="value">The value to represent as a NSObject.</param> /// <returns>A NSObject representing the given value.</returns> public static NSNumber Wrap(double value) { return new NSNumber(value); } /// <summary> /// Wraps the given value inside a NSObject. /// </summary> /// <param name="value">The value to represent as a NSObject.</param> /// <returns>A NSObject representing the given value.</returns> public static NSNumber Wrap(bool value) { return new NSNumber(value); } /// <summary> /// Wraps the given value inside a NSObject. /// </summary> /// <param name="value">The value to represent as a NSObject.</param> /// <returns>A NSObject representing the given value.</returns> public static NSData Wrap(byte[] value) { return new NSData(value); } /// <summary> /// Creates a NSArray with the contents of the given array. /// </summary> /// <param name="value">The value to represent as a NSObject.</param> /// <returns>A NSObject representing the given value.</returns> /// <exception cref="SystemException">When one of the objects contained in the array cannot be represented by a NSObject.</exception> public static NSArray Wrap(Object[] value) { NSArray arr = new NSArray(value.Length); for (int i = 0; i < value.Length; i++) { arr.Add(Wrap(value[i])); } return arr; } /// <summary> /// Creates a NSDictionary with the contents of the given map. /// </summary> /// <param name="value">The value to represent as a NSObject.</param> /// <returns>A NSObject representing the given value.</returns> /// <exception cref="SystemException">When one of the values contained in the map cannot be represented by a NSObject.</exception> public static NSDictionary Wrap(Dictionary<string, Object> value) { NSDictionary dict = new NSDictionary(); foreach (KeyValuePair<string, Object> kvp in value) dict.Add(kvp.Key, Wrap(kvp.Value)); return dict; } /// <summary> /// Creates a NSSet with the contents of this set. /// </summary> /// <param name="value">The value to represent as a NSObject.</param> /// <returns>A NSObject representing the given value.</returns> /// <exception cref="SystemException">When one of the values contained in the map cannot be represented by a NSObject.</exception> public static NSSet Wrap(List<Object> value) { NSSet set = new NSSet(); foreach (Object o in value) set.AddObject(Wrap(o)); return set; } /// <summary> /// <para> /// Creates a NSObject representing the given .NET Object. /// </para><para> /// Numerics of type <see cref="bool"/>, <see cref="int"/>, <see cref="long"/>, <see cref="short"/>, <see cref="byte"/>, <see cref="float"/> or <see cref="double"/> are wrapped as NSNumber objects. /// </para><para> /// Strings are wrapped as <see cref="NSString"/> objects and byte arrays as <see cref="NSData"/> objects. /// </para><para> /// DateTime objects are wrapped as <see cref="NSDate"/> objects. /// </para><para> /// Serializable classes are serialized and their data is stored in <see cref="NSData"/> objects. /// </para><para> /// Arrays and Collection objects are converted to <see cref="NSArray"/> where each array member is wrapped into a <see cref="NSObject"/>. /// </para><para> /// Dictionaries are converted to <see cref="NSDictionary"/>. Each key is converted to a string and each value wrapped into a <see cref="NSObject"/>. /// </para> /// </summary> /// <param name="o">The object to represent.</param> ///<returns>A NSObject equivalent to the given object.</returns> public static NSObject Wrap(Object o) { if (o == null) throw new NullReferenceException("A null object cannot be wrapped as a NSObject"); if (o is NSObject) return (NSObject)o; Type c = o.GetType(); if (typeof(bool).Equals(c)) { return Wrap((bool)o); } if (typeof(Byte).Equals(c)) { return Wrap((int)(Byte)o); } if (typeof(short).Equals(c)) { return Wrap((int)(short)o); } if (typeof(int).Equals(c)) { return Wrap((int)(int)o); } if (typeof(long).IsAssignableFrom(c)) { return Wrap((long)o); } if (typeof(float).Equals(c)) { return Wrap((double)(float)o); } if (typeof(double).IsAssignableFrom(c)) { return Wrap((double)o); } if (typeof(string).Equals(c)) { return new NSString((string)o); } if (typeof(DateTime).Equals(c)) { return new NSDate((DateTime)o); } if (c.IsArray) { Type cc = c.GetElementType(); if (cc.Equals(typeof(byte))) { return Wrap((byte[])o); } if (cc.Equals(typeof(bool))) { bool[] array = (bool[])o; NSArray nsa = new NSArray(array.Length); for (int i = 0; i < array.Length; i++) nsa.Add(Wrap(array[i])); return nsa; } if (cc.Equals(typeof(float))) { float[] array = (float[])o; NSArray nsa = new NSArray(array.Length); for (int i = 0; i < array.Length; i++) nsa.Add(Wrap(array[i])); return nsa; } if (cc.Equals(typeof(double))) { double[] array = (double[])o; NSArray nsa = new NSArray(array.Length); for (int i = 0; i < array.Length; i++) nsa.Add(Wrap(array[i])); return nsa; } if (cc.Equals(typeof(short))) { short[] array = (short[])o; NSArray nsa = new NSArray(array.Length); for (int i = 0; i < array.Length; i++) nsa.Add(Wrap(array[i])); return nsa; } if (cc.Equals(typeof(int))) { int[] array = (int[])o; NSArray nsa = new NSArray(array.Length); for (int i = 0; i < array.Length; i++) nsa.Add(Wrap(array[i])); return nsa; } if (cc.Equals(typeof(long))) { long[] array = (long[])o; NSArray nsa = new NSArray(array.Length); for (int i = 0; i < array.Length; i++) nsa.Add(Wrap(array[i])); return nsa; } return Wrap((Object[])o); } if (typeof(Dictionary<string, Object>).IsAssignableFrom(c)) { Dictionary<string, Object> netDict = (Dictionary<string, Object>)o; NSDictionary dict = new NSDictionary(); foreach (KeyValuePair<string, Object> kvp in netDict) { dict.Add(kvp.Key, Wrap(kvp.Value)); } return dict; } if (typeof(List<Object>).IsAssignableFrom(c)) return Wrap(((List<Object>)o).ToArray()); throw new PropertyListException(string.Format("Cannot wrap an object of type {0}.", o.GetType().Name)); } /// <summary> /// Converts this NSObject into an equivalent object /// of the .NET Runtime Environment. /// <para><see cref="NSArray"/> objects are converted to arrays.</para> /// <para><see cref="NSDictionary"/> objects are converted to objects extending the <see cref="Dictionary{TKey, TValue}"/> class.</para> /// <para><see cref="NSSet"/> objects are converted to objects extending the <see cref="List{NSObject}"/> class.</para> /// <para><see cref="NSNumber"/> objects are converted to primitive number values (<see cref="int"/>, <see cref="long"/>, <see cref="double"/> or <see cref="bool"/>).</para> /// <para><see cref="NSString"/> objects are converted to <see cref="string"/> objects.</para> /// <para><see cref="NSData"/> objects are converted to <see cref="byte"/> arrays.</para> /// <para><see cref="NSDate"/> objects are converted to <see cref="System.DateTime"/> objects.</para> /// <para><see cref="UID"/> objects are converted to <see cref="byte"/> arrays.</para> /// </summary> /// <returns>A native .NET object representing this NSObject's value.</returns> public Object ToObject() { if (this is NSArray) { NSObject[] arrayA = ((NSArray)this).GetArray(); Object[] arrayB = new Object[arrayA.Length]; for (int i = 0; i < arrayA.Length; i++) { arrayB[i] = arrayA[i].ToObject(); } return arrayB; } if (this is NSDictionary) { Dictionary<string, NSObject> dictA = ((NSDictionary)this).GetDictionary(); Dictionary<string, Object> dictB = new Dictionary<string, Object>(dictA.Count); foreach (KeyValuePair<string, NSObject> kvp in dictA) { dictB.Add(kvp.Key, kvp.Value.ToObject()); } return dictB; } if (this is NSSet) { List<NSObject> setA = ((NSSet)this).GetSet(); List<Object> setB = new List<Object>(); foreach (NSObject o in setA) { setB.Add(o.ToObject()); } return setB; } if (this is NSNumber) { NSNumber num = (NSNumber)this; switch (num.GetNSNumberType()) { case NSNumber.INTEGER: { long longVal = num.ToLong(); if (longVal > int.MaxValue || longVal < int.MinValue) return longVal; return num.ToInt(); } case NSNumber.REAL: return num.ToDouble(); case NSNumber.BOOLEAN: return num.ToBool(); default: return num.ToDouble(); } } if (this is NSString) { return ((NSString)this).GetContent(); } if (this is NSData) { return ((NSData)this).Bytes; } if (this is NSDate) { return ((NSDate)this).Date; } if (this is UID) { return ((UID)this).Bytes; } return this; } internal static bool ArrayEquals(byte[] arrayA, byte[] arrayB) { if (arrayA.Length == arrayB.Length) { for (int i = 0; i < arrayA.Length; i++) if (arrayA[i] != arrayB[i]) return false; return true; } return false; } internal static bool ArrayEquals(NSObject[] arrayA, NSObject[] arrayB) { if (arrayA.Length == arrayB.Length) { for (int i = 0; i < arrayA.Length; i++) { if (arrayA[i] != arrayB[i]) { return false; } } return true; } return false; } /// <summary> /// Determines if the specific NSObject is the same as the NSObject overriding this method. /// </summary> /// <param name="obj">The <see cref="PList.NSObject"/> to compare with the current <see cref="PList.NSObject"/>.</param> /// <returns><c>true</c> if the specified <see cref="PList.NSObject"/> is equal to the current /// <see cref="PList.NSObject"/>; otherwise, <c>false</c>.</returns> public abstract bool Equals(NSObject obj); } }
2881099/dotnetGen_sqlserver
5,877
GenMs/FastExcel/FastExcel.Write.cs
using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; namespace FastExcel { public partial class FastExcel { /// <summary> /// Write data to a sheet /// </summary> /// <param name="worksheet">A dataset</param> public void Write(Worksheet worksheet) { this.Write(worksheet, null, null); } /// <summary> /// Write data to a sheet /// </summary> /// <param name="worksheet">A dataset</param> /// <param name="sheetNumber">The number of the sheet starting at 1</param> /// <param name="existingHeadingRows">How many rows in the template sheet you would like to keep</param> public void Write(Worksheet worksheet, int sheetNumber, int existingHeadingRows = 0) { this.Write(worksheet, sheetNumber, null, existingHeadingRows); } /// <summary> /// Write data to a sheet /// </summary> /// <param name="worksheet">A dataset</param> /// <param name="sheetName">The display name of the sheet</param> /// <param name="existingHeadingRows">How many rows in the template sheet you would like to keep</param> public void Write(Worksheet worksheet, string sheetName, int existingHeadingRows = 0) { this.Write(worksheet, null, sheetName, existingHeadingRows); } /// <summary> /// Write a list of objects to a sheet /// </summary> /// <typeparam name="T">Row Object</typeparam> /// <param name="rows">IEnumerable list of objects</param> /// <param name="sheetNumber">The number of the sheet starting at 1</param> /// <param name="existingHeadingRows">How many rows in the template sheet you would like to keep</param> public void Write<T>(IEnumerable<T> rows, int sheetNumber, int existingHeadingRows = 0) { Worksheet data = new Worksheet(); data.PopulateRows<T>(rows); this.Write(data, sheetNumber, null, existingHeadingRows); } /// <summary> /// Write a list of objects to a sheet /// </summary> /// <typeparam name="T">Row Object</typeparam> /// <param name="rows">IEnumerable list of objects</param> /// <param name="sheetName">The display name of the sheet</param> /// <param name="existingHeadingRows">How many rows in the template sheet you would like to keep</param> public void Write<T>(IEnumerable<T> rows, string sheetName, int existingHeadingRows = 0) { Worksheet data = new Worksheet(); data.PopulateRows<T>(rows, existingHeadingRows); this.Write(data, null, sheetName, existingHeadingRows); } /// <summary> /// Write a list of objects to a sheet /// </summary> /// <typeparam name="T">Row Object</typeparam> /// <param name="objectList">IEnumerable list of objects</param> /// <param name="sheetNumber">The number of the sheet starting at 1</param> /// <param name="usePropertiesAsHeadings">Use property names from object list as headings</param> public void Write<T>(IEnumerable<T> objectList, int sheetNumber, bool usePropertiesAsHeadings) { Worksheet data = new Worksheet(); data.PopulateRows<T>(objectList, 0, usePropertiesAsHeadings); this.Write(data, sheetNumber, null, 0); } /// <summary> /// Write a list of objects to a sheet /// </summary> /// <typeparam name="T">Row Object</typeparam> /// <param name="rows">IEnumerable list of objects</param> /// <param name="sheetName">The display name of the sheet</param> /// <param name="usePropertiesAsHeadings">Use property names from object list as headings</param> public void Write<T>(IEnumerable<T> rows, string sheetName, bool usePropertiesAsHeadings) { Worksheet data = new Worksheet(); data.PopulateRows<T>(rows, 0, usePropertiesAsHeadings); this.Write(data, null, sheetName, 0); } private void Write(Worksheet worksheet, int? sheetNumber = null, string sheetName = null, int existingHeadingRows = 0) { CheckFiles(); try { if (!this.UpdateExisting) { File.Copy(this.TemplateFile.FullName, this.ExcelFile.FullName); } } catch (Exception ex) { throw new Exception("Could not copy template to output file path", ex); } PrepareArchive(); // Open worksheet worksheet.GetWorksheetProperties(this, sheetNumber, sheetName); worksheet.ExistingHeadingRows = existingHeadingRows; if (this.Archive.Mode != ZipArchiveMode.Update) { throw new Exception("FastExcel is in ReadOnly mode so cannot perform a write"); } // Check if ExistingHeadingRows will be overridden by the dataset if (worksheet.ExistingHeadingRows != 0 && worksheet.Rows.Where(r => r.RowNumber <= worksheet.ExistingHeadingRows).Any()) { throw new Exception("Existing Heading Rows was specified but some or all will be overridden by data rows. Check DataSet.Row.RowNumber against ExistingHeadingRows"); } using (Stream stream = this.Archive.GetEntry(worksheet.FileName).Open()) { // Open worksheet and read the data at the top and bottom of the sheet StreamReader streamReader = new StreamReader(stream); worksheet.ReadHeadersAndFooters(streamReader, ref worksheet); //Set the stream to the start stream.Position = 0; // Open the stream so we can override all content of the sheet StreamWriter streamWriter = new StreamWriter(stream); // TODO instead of saving the headers then writing them back get position where the headers finish then write from there streamWriter.Write(worksheet.Headers); if (!worksheet.Template) { worksheet.Headers = null; } this.SharedStrings.ReadWriteMode = true; // Add Rows foreach (Row row in worksheet.Rows) { streamWriter.Write(row.ToXmlString(this.SharedStrings)); } this.SharedStrings.ReadWriteMode = false; //Add Footers streamWriter.Write(worksheet.Footers); if (!worksheet.Template) { worksheet.Footers = null; } streamWriter.Flush(); } } } }
2881099/dotnetGen_sqlserver
3,559
GenMs/FastExcel/Row.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; namespace FastExcel { /// <summary> /// Row that contains the Cells /// </summary> public class Row { /// <summary> /// The Row Number (Row numbers start at 1) /// </summary> public int RowNumber { get; set; } /// <summary> /// The collection of cells for this row /// </summary> public IEnumerable<Cell> Cells { get; set; } /// <summary> /// Create a new Row /// </summary> /// <param name="rowNumber">Row number starting with 1</param> /// <param name="cells">Cells on this row</param> public Row(int rowNumber, IEnumerable<Cell> cells) { if (rowNumber <= 0) { throw new Exception("Row numbers starting at 1"); } this.RowNumber = rowNumber; this.Cells = cells; } public Row(XElement rowElement, SharedStrings sharedStrings) { try { this.RowNumber = (from a in rowElement.Attributes("r") select int.Parse(a.Value)).First(); } catch (Exception ex) { throw new Exception("Row Number not found", ex); } if (rowElement.HasElements) { this.Cells = GetCells(rowElement, sharedStrings); } } private IEnumerable<Cell> GetCells(XElement rowElement, SharedStrings sharedStrings) { foreach (XElement cellElement in rowElement.Elements()) { Cell cell = new Cell(cellElement, sharedStrings); if (cell.Value != null) { yield return cell; } } } internal StringBuilder ToXmlString(SharedStrings sharedStrings) { StringBuilder row = new StringBuilder(); if (this.Cells != null && Cells.Any()) { row.AppendFormat("<row r=\"{0}\">", this.RowNumber); try { foreach (Cell cell in this.Cells) { row.Append(cell.ToXmlString(sharedStrings, this.RowNumber)); } } finally { row.Append("</row>"); } } return row; } /// <summary> /// Merge this row and the passed one togeather /// </summary> /// <param name="row">Row to be merged into this one</param> internal void Merge(Row row) { // Merge cells List<Cell> outputList = new List<Cell>(); foreach (var cell in this.Cells.Union(row.Cells).GroupBy(c => c.ColumnNumber)) { int count = cell.Count(); if (count == 1) { outputList.Add(cell.First()); } else { cell.First().Merge(cell.Skip(1).First()); outputList.Add(cell.First()); } } // Sort this.Cells = (from c in outputList orderby c.ColumnNumber select c); } } }
2881099/dotnetGen_postgresql
863
ServerWinService/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 有关程序集的常规信息通过下列属性集 // 控制。更改这些属性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("ServerWinService")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ServerWinService")] [assembly: AssemblyCopyright("版权所有 (C) 2007")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 将 ComVisible 设置为 false 使此程序集中的类型 // 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型, // 则将该类型上的 ComVisible 属性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID [assembly: Guid("3d782f35-0953-5580-8273-e45d913562b7")] // 程序集的版本信息由下面四个值组成: // // 主版本 // 次版本 // 内部版本号 // 修订号 // [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]