repo_id
stringlengths
6
101
size
int64
367
5.14M
file_path
stringlengths
2
269
content
stringlengths
367
5.14M
27182812/ChatGLM-LLaMA-chinese-insturct
17,119
src/transformers/models/m2m_100/tokenization_m2m_100.py
# Copyright 2021 The Fairseq Authors 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. """Tokenization classes for M2M100.""" import json import os from pathlib import Path from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple, Union import sentencepiece from ...tokenization_utils import BatchEncoding, PreTrainedTokenizer from ...utils import logging logger = logging.get_logger(__name__) SPIECE_UNDERLINE = "▁" VOCAB_FILES_NAMES = { "vocab_file": "vocab.json", "spm_file": "sentencepiece.bpe.model", "tokenizer_config_file": "tokenizer_config.json", } PRETRAINED_VOCAB_FILES_MAP = { "vocab_file": { "facebook/m2m100_418M": "https://huggingface.co/facebook/m2m100_418M/resolve/main/vocab.json", "facebook/m2m100_1.2B": "https://huggingface.co/facebook/m2m100_1.2B/resolve/main/vocab.json", }, "spm_file": { "facebook/m2m100_418M": "https://huggingface.co/facebook/m2m100_418M/resolve/main/sentencepiece.bpe.model", "facebook/m2m100_1.2B": "https://huggingface.co/facebook/m2m100_1.2B/resolve/main/sentencepiece.bpe.model", }, "tokenizer_config_file": { "facebook/m2m100_418M": "https://huggingface.co/facebook/m2m100_418M/resolve/main/tokenizer_config.json", "facebook/m2m100_1.2B": "https://huggingface.co/facebook/m2m100_1.2B/resolve/main/tokenizer_config.json", }, } PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = { "facebook/m2m100_418M": 1024, } # fmt: off FAIRSEQ_LANGUAGE_CODES = { "m2m100": ["af", "am", "ar", "ast", "az", "ba", "be", "bg", "bn", "br", "bs", "ca", "ceb", "cs", "cy", "da", "de", "el", "en", "es", "et", "fa", "ff", "fi", "fr", "fy", "ga", "gd", "gl", "gu", "ha", "he", "hi", "hr", "ht", "hu", "hy", "id", "ig", "ilo", "is", "it", "ja", "jv", "ka", "kk", "km", "kn", "ko", "lb", "lg", "ln", "lo", "lt", "lv", "mg", "mk", "ml", "mn", "mr", "ms", "my", "ne", "nl", "no", "ns", "oc", "or", "pa", "pl", "ps", "pt", "ro", "ru", "sd", "si", "sk", "sl", "so", "sq", "sr", "ss", "su", "sv", "sw", "ta", "th", "tl", "tn", "tr", "uk", "ur", "uz", "vi", "wo", "xh", "yi", "yo", "zh", "zu"], "wmt21": ['en', 'ha', 'is', 'ja', 'cs', 'ru', 'zh', 'de'] } # fmt: on class M2M100Tokenizer(PreTrainedTokenizer): """ Construct an M2M100 tokenizer. Based on [SentencePiece](https://github.com/google/sentencepiece). 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: vocab_file (`str`): Path to the vocabulary file. spm_file (`str`): Path to [SentencePiece](https://github.com/google/sentencepiece) file (generally has a .spm extension) that contains the vocabulary. src_lang (`str`, *optional*): A string representing the source language. tgt_lang (`str`, *optional*): A string representing the target language. eos_token (`str`, *optional*, defaults to `"</s>"`): The end of sequence token. sep_token (`str`, *optional*, defaults to `"</s>"`): The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for sequence classification or for a text and a question for question answering. It is also used as the last token of a sequence built with 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. pad_token (`str`, *optional*, defaults to `"<pad>"`): The token used for padding, for example when batching sequences of different lengths. language_codes (`str`, *optional*, defaults to `"m2m100"`): What language codes to use. Should be one of `"m2m100"` or `"wmt21"`. sp_model_kwargs (`dict`, *optional*): Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things, to set: - `enable_sampling`: Enable subword regularization. - `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout. - `nbest_size = {0,1}`: No sampling is performed. - `nbest_size > 1`: samples from the nbest_size results. - `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice) using forward-filtering-and-backward-sampling algorithm. - `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for BPE-dropout. Examples: ```python >>> from transformers import M2M100Tokenizer >>> tokenizer = M2M100Tokenizer.from_pretrained("facebook/m2m100_418M", src_lang="en", tgt_lang="ro") >>> src_text = " UN Chief Says There Is No Military Solution in Syria" >>> tgt_text = "Şeful ONU declară că nu există o soluţie militară în Siria" >>> model_inputs = tokenizer(src_text, text_target=tgt_text, return_tensors="pt") >>> model(**model_inputs) # should work ```""" vocab_files_names = VOCAB_FILES_NAMES max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP model_input_names = ["input_ids", "attention_mask"] prefix_tokens: List[int] = [] suffix_tokens: List[int] = [] def __init__( self, vocab_file, spm_file, src_lang=None, tgt_lang=None, bos_token="<s>", eos_token="</s>", sep_token="</s>", pad_token="<pad>", unk_token="<unk>", language_codes="m2m100", sp_model_kwargs: Optional[Dict[str, Any]] = None, num_madeup_words=8, **kwargs, ) -> None: self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs self.language_codes = language_codes fairseq_language_code = FAIRSEQ_LANGUAGE_CODES[language_codes] self.lang_code_to_token = {lang_code: f"__{lang_code}__" for lang_code in fairseq_language_code} kwargs["additional_special_tokens"] = kwargs.get("additional_special_tokens", []) kwargs["additional_special_tokens"] += [ self.get_lang_token(lang_code) for lang_code in fairseq_language_code if self.get_lang_token(lang_code) not in kwargs["additional_special_tokens"] ] super().__init__( src_lang=src_lang, tgt_lang=tgt_lang, bos_token=bos_token, eos_token=eos_token, sep_token=sep_token, unk_token=unk_token, pad_token=pad_token, language_codes=language_codes, sp_model_kwargs=self.sp_model_kwargs, num_madeup_words=num_madeup_words, **kwargs, ) self.vocab_file = vocab_file self.encoder = load_json(vocab_file) self.decoder = {v: k for k, v in self.encoder.items()} self.spm_file = spm_file self.sp_model = load_spm(spm_file, self.sp_model_kwargs) self.encoder_size = len(self.encoder) self.lang_token_to_id = { self.get_lang_token(lang_code): self.encoder_size + i for i, lang_code in enumerate(fairseq_language_code) } self.lang_code_to_id = {lang_code: self.encoder_size + i for i, lang_code in enumerate(fairseq_language_code)} self.id_to_lang_token = {v: k for k, v in self.lang_token_to_id.items()} self._src_lang = src_lang if src_lang is not None else "en" self.tgt_lang = tgt_lang self.cur_lang_id = self.get_lang_id(self._src_lang) self.set_src_lang_special_tokens(self._src_lang) self.num_madeup_words = num_madeup_words @property def vocab_size(self) -> int: return len(self.encoder) + len(self.lang_token_to_id) @property def src_lang(self) -> str: return self._src_lang @src_lang.setter def src_lang(self, new_src_lang: str) -> None: self._src_lang = new_src_lang self.set_src_lang_special_tokens(self._src_lang) def _tokenize(self, text: str) -> List[str]: return self.sp_model.encode(text, out_type=str) def _convert_token_to_id(self, token): if token in self.lang_token_to_id: return self.lang_token_to_id[token] return self.encoder.get(token, self.encoder[self.unk_token]) def _convert_id_to_token(self, index: int) -> str: """Converts an index (integer) in a token (str) using the decoder.""" if index in self.id_to_lang_token: return self.id_to_lang_token[index] return self.decoder.get(index, self.unk_token) def convert_tokens_to_string(self, tokens): """Converts a sequence of tokens (string) in a single string.""" current_sub_tokens = [] out_string = "" for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: out_string += self.sp_model.decode(current_sub_tokens) + token current_sub_tokens = [] else: current_sub_tokens.append(token) out_string += self.sp_model.decode(current_sub_tokens) return out_string.strip() def get_special_tokens_mask( self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False ) -> List[int]: """ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding special tokens using the tokenizer `prepare_for_model` method. Args: token_ids_0 (`List[int]`): List of IDs. token_ids_1 (`List[int]`, *optional*): Optional second list of IDs for sequence pairs. already_has_special_tokens (`bool`, *optional*, defaults to `False`): Whether or not the token list is already formatted with special tokens for the model. Returns: `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token. """ if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True ) prefix_ones = [1] * len(self.prefix_tokens) suffix_ones = [1] * len(self.suffix_tokens) if token_ids_1 is None: return prefix_ones + ([0] * len(token_ids_0)) + suffix_ones return prefix_ones + ([0] * len(token_ids_0)) + ([0] * len(token_ids_1)) + suffix_ones def build_inputs_with_special_tokens( self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None ) -> List[int]: """ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and adding special tokens. An MBART sequence has the following format, where `X` represents the sequence: - `input_ids` (for encoder) `X [eos, src_lang_code]` - `decoder_input_ids`: (for decoder) `X [eos, tgt_lang_code]` BOS is never used. Pairs of sequences are not the expected use case, but they will be handled without a separator. Args: token_ids_0 (`List[int]`): List of IDs to which the special tokens will be added. token_ids_1 (`List[int]`, *optional*): Optional second list of IDs for sequence pairs. Returns: `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens. """ if token_ids_1 is None: return self.prefix_tokens + token_ids_0 + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_0 + token_ids_1 + self.suffix_tokens def get_vocab(self) -> Dict: vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)} vocab.update(self.added_tokens_encoder) return vocab def __getstate__(self) -> Dict: state = self.__dict__.copy() state["sp_model"] = None return state def __setstate__(self, d: Dict) -> None: self.__dict__ = d # for backward compatibility if not hasattr(self, "sp_model_kwargs"): self.sp_model_kwargs = {} self.sp_model = load_spm(self.spm_file, self.sp_model_kwargs) def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]: save_dir = Path(save_directory) if not save_dir.is_dir(): raise OSError(f"{save_directory} should be a directory") vocab_save_path = save_dir / ( (filename_prefix + "-" if filename_prefix else "") + self.vocab_files_names["vocab_file"] ) spm_save_path = save_dir / ( (filename_prefix + "-" if filename_prefix else "") + self.vocab_files_names["spm_file"] ) save_json(self.encoder, vocab_save_path) if os.path.abspath(self.spm_file) != os.path.abspath(spm_save_path) and os.path.isfile(self.spm_file): copyfile(self.spm_file, spm_save_path) elif not os.path.isfile(self.spm_file): with open(spm_save_path, "wb") as fi: content_spiece_model = self.sp_model.serialized_model_proto() fi.write(content_spiece_model) return (str(vocab_save_path), str(spm_save_path)) def prepare_seq2seq_batch( self, src_texts: List[str], src_lang: str = "en", tgt_texts: Optional[List[str]] = None, tgt_lang: str = "ro", **kwargs, ) -> BatchEncoding: self.src_lang = src_lang self.tgt_lang = tgt_lang self.set_src_lang_special_tokens(self.src_lang) return super().prepare_seq2seq_batch(src_texts, tgt_texts, **kwargs) def _build_translation_inputs(self, raw_inputs, src_lang: Optional[str], tgt_lang: Optional[str], **extra_kwargs): """Used by translation pipeline, to prepare inputs for the generate function""" if src_lang is None or tgt_lang is None: raise ValueError("Translation requires a `src_lang` and a `tgt_lang` for this model") self.src_lang = src_lang inputs = self(raw_inputs, add_special_tokens=True, **extra_kwargs) tgt_lang_id = self.get_lang_id(tgt_lang) inputs["forced_bos_token_id"] = tgt_lang_id return inputs def _switch_to_input_mode(self): self.set_src_lang_special_tokens(self.src_lang) def _switch_to_target_mode(self): self.set_tgt_lang_special_tokens(self.tgt_lang) def set_src_lang_special_tokens(self, src_lang: str) -> None: """Reset the special tokens to the source lang setting. No prefix and suffix=[eos, src_lang_code].""" lang_token = self.get_lang_token(src_lang) self.cur_lang_id = self.lang_token_to_id[lang_token] self.prefix_tokens = [self.cur_lang_id] self.suffix_tokens = [self.eos_token_id] def set_tgt_lang_special_tokens(self, tgt_lang: str) -> None: """Reset the special tokens to the target language setting. No prefix and suffix=[eos, tgt_lang_code].""" lang_token = self.get_lang_token(tgt_lang) self.cur_lang_id = self.lang_token_to_id[lang_token] self.prefix_tokens = [self.cur_lang_id] self.suffix_tokens = [self.eos_token_id] def get_lang_token(self, lang: str) -> str: return self.lang_code_to_token[lang] def get_lang_id(self, lang: str) -> int: lang_token = self.get_lang_token(lang) return self.lang_token_to_id[lang_token] def load_spm(path: str, sp_model_kwargs: Dict[str, Any]) -> sentencepiece.SentencePieceProcessor: spm = sentencepiece.SentencePieceProcessor(**sp_model_kwargs) spm.Load(str(path)) return spm def load_json(path: str) -> Union[Dict, List]: with open(path, "r") as f: return json.load(f) def save_json(data, path: str) -> None: with open(path, "w") as f: json.dump(data, f, indent=2)
2881099/csredis
84,120
src/CSRedisCore/RedisHelperAsync.cs
using CSRedis; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; #if net40 #else partial class RedisHelper<TMark> { #region 缓存壳 /// <summary> /// 缓存壳 /// </summary> /// <typeparam name="T">缓存类型</typeparam> /// <param name="key">不含prefix前辍</param> /// <param name="timeoutSeconds">缓存秒数</param> /// <param name="getDataAsync">获取源数据的函数</param> /// <returns></returns> public static Task<T> CacheShellAsync<T>(string key, int timeoutSeconds, Func<Task<T>> getDataAsync) => Instance.CacheShellAsync(key, timeoutSeconds, getDataAsync); /// <summary> /// 缓存壳(哈希表) /// </summary> /// <typeparam name="T">缓存类型</typeparam> /// <param name="key">不含prefix前辍</param> /// <param name="field">字段</param> /// <param name="timeoutSeconds">缓存秒数</param> /// <param name="getDataAsync">获取源数据的函数</param> /// <returns></returns> public static Task<T> CacheShellAsync<T>(string key, string field, int timeoutSeconds, Func<Task<T>> getDataAsync) => Instance.CacheShellAsync(key, field, timeoutSeconds, getDataAsync); /// <summary> /// 缓存壳(哈希表),将 fields 每个元素存储到单独的缓存片,实现最大化复用 /// </summary> /// <typeparam name="T">缓存类型</typeparam> /// <param name="key">不含prefix前辍</param> /// <param name="fields">字段</param> /// <param name="timeoutSeconds">缓存秒数</param> /// <param name="getDataAsync">获取源数据的函数,输入参数是没有缓存的 fields,返回值应该是 (field, value)[]</param> /// <returns></returns> public static Task<(string key, T value)[]> CacheShellAsync<T>(string key, string[] fields, int timeoutSeconds, Func<string[], Task<(string, T)[]>> getDataAsync) => Instance.CacheShellAsync(key, fields, timeoutSeconds, getDataAsync); #endregion #region 连接命令 /// <summary> /// 打印字符串 /// </summary> /// <param name="nodeKey">分区key</param> /// <param name="message">消息</param> /// <returns></returns> public static Task<string> EchoAsync(string nodeKey, string message) => Instance.EchoAsync(nodeKey, message); /// <summary> /// 打印字符串 /// </summary> /// <param name="message">消息</param> /// <returns></returns> public static Task<string> EchoAsync(string message) => Instance.EchoAsync(message); /// <summary> /// 查看服务是否运行 /// </summary> /// <param name="nodeKey">分区key</param> /// <returns></returns> public static Task<bool> PingAsync(string nodeKey) => Instance.PingAsync(nodeKey); /// <summary> /// 查看服务是否运行 /// </summary> /// <returns></returns> public static Task<bool> PingAsync() => Instance.PingAsync(); #endregion #region Script /// <summary> /// 执行脚本 /// </summary> /// <param name="script">Lua 脚本</param> /// <param name="key">用于定位分区节点,不含prefix前辍</param> /// <param name="args">参数</param> /// <returns></returns> public static Task<object> EvalAsync(string script, string key, params object[] args) => Instance.EvalAsync(script, key, args); /// <summary> /// 执行脚本 /// </summary> /// <param name="sha1">脚本缓存的sha1</param> /// <param name="key">用于定位分区节点,不含prefix前辍</param> /// <param name="args">参数</param> /// <returns></returns> public static Task<object> EvalSHAAsync(string sha1, string key, params object[] args) => Instance.EvalSHAAsync(sha1, key, args); /// <summary> /// 校验所有分区节点中,脚本是否已经缓存。任何分区节点未缓存sha1,都返回false。 /// </summary> /// <param name="sha1">脚本缓存的sha1</param> /// <returns></returns> public static Task<bool[]> ScriptExistsAsync(params string[] sha1) => Instance.ScriptExistsAsync(sha1); /// <summary> /// 清除所有分区节点中,所有 Lua 脚本缓存 /// </summary> public static Task ScriptFlushAsync() => Instance.ScriptFlushAsync(); /// <summary> /// 杀死所有分区节点中,当前正在运行的 Lua 脚本 /// </summary> public static Task ScriptKillAsync() => Instance.ScriptKillAsync(); /// <summary> /// 在所有分区节点中,缓存脚本后返回 sha1(同样的脚本在任何服务器,缓存后的 sha1 都是相同的) /// </summary> /// <param name="script">Lua 脚本</param> /// <returns></returns> public static Task<string> ScriptLoadAsync(string script) => Instance.ScriptLoadAsync(script); #endregion #region Pub/Sub /// <summary> /// 用于将信息发送到指定分区节点的频道,最终消息发布格式:1|message /// </summary> /// <param name="channel">频道名</param> /// <param name="message">消息文本</param> /// <returns></returns> public static Task<long> PublishAsync(string channel, string message) => Instance.PublishAsync(channel, message); /// <summary> /// 用于将信息发送到指定分区节点的频道,与 Publish 方法不同,不返回消息id头,即 1| /// </summary> /// <param name="channel">频道名</param> /// <param name="message">消息文本</param> /// <returns></returns> public static Task<long> PublishNoneMessageIdAsync(string channel, string message) => Instance.PublishNoneMessageIdAsync(channel, message); /// <summary> /// 查看所有订阅频道 /// </summary> /// <param name="pattern"></param> /// <returns></returns> public static Task<string[]> PubSubChannelsAsync(string pattern) => Instance.PubSubChannelsAsync(pattern); /// <summary> /// 查看所有模糊订阅端的数量 /// </summary> /// <returns></returns> [Obsolete("分区模式下,其他客户端的模糊订阅可能不会返回")] public static Task<long> PubSubNumPatAsync() => Instance.PubSubNumPatAsync(); /// <summary> /// 查看所有订阅端的数量 /// </summary> /// <param name="channels">频道</param> /// <returns></returns> [Obsolete("分区模式下,其他客户端的订阅可能不会返回")] public static Task<Dictionary<string, long>> PubSubNumSubAsync(params string[] channels) => Instance.PubSubNumSubAsync(channels); #endregion #region HyperLogLog /// <summary> /// 添加指定元素到 HyperLogLog /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="elements">元素</param> /// <returns></returns> public static Task<bool> PfAddAsync<T>(string key, params T[] elements) => Instance.PfAddAsync(key, elements); /// <summary> /// 返回给定 HyperLogLog 的基数估算值 /// </summary> /// <param name="keys">不含prefix前辍</param> /// <returns></returns> [Obsolete("分区模式下,若keys分散在多个分区节点时,将报错")] public static Task<long> PfCountAsync(params string[] keys) => Instance.PfCountAsync(keys); /// <summary> /// 将多个 HyperLogLog 合并为一个 HyperLogLog /// </summary> /// <param name="destKey">新的 HyperLogLog,不含prefix前辍</param> /// <param name="sourceKeys">源 HyperLogLog,不含prefix前辍</param> /// <returns></returns> [Obsolete("分区模式下,若keys分散在多个分区节点时,将报错")] public static Task<bool> PfMergeAsync(string destKey, params string[] sourceKeys) => Instance.PfMergeAsync(destKey, sourceKeys); #endregion #region Sorted Set /// <summary> /// 向有序集合添加一个或多个成员,或者更新已存在成员的分数 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="scoreMembers">一个或多个成员分数</param> /// <returns></returns> public static Task<long> ZAddAsync(string key, params (decimal, object)[] scoreMembers) => Instance.ZAddAsync(key, scoreMembers); /// <summary> /// 获取有序集合的成员数量 /// </summary> /// <param name="key">不含prefix前辍</param> /// <returns></returns> public static Task<long> ZCardAsync(string key) => Instance.ZCardAsync(key); /// <summary> /// 计算在有序集合中指定区间分数的成员数量 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="min">分数最小值 decimal.MinValue 1</param> /// <param name="max">分数最大值 decimal.MaxValue 10</param> /// <returns></returns> public static Task<long> ZCountAsync(string key, decimal min, decimal max) => Instance.ZCountAsync(key, min, max); /// <summary> /// 计算在有序集合中指定区间分数的成员数量 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="min">分数最小值 -inf (1 1</param> /// <param name="max">分数最大值 +inf (10 10</param> /// <returns></returns> public static Task<long> ZCountAsync(string key, string min, string max) => Instance.ZCountAsync(key, min, max); /// <summary> /// 有序集合中对指定成员的分数加上增量 increment /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="member">成员</param> /// <param name="increment">增量值(默认=1)</param> /// <returns></returns> public static Task<decimal> ZIncrByAsync(string key, string member, decimal increment = 1) => Instance.ZIncrByAsync(key, member, increment); /// <summary> /// 计算给定的一个或多个有序集的交集,将结果集存储在新的有序集合 destination 中 /// </summary> /// <param name="destination">新的有序集合,不含prefix前辍</param> /// <param name="weights">使用 WEIGHTS 选项,你可以为 每个 给定有序集 分别 指定一个乘法因子。如果没有指定 WEIGHTS 选项,乘法因子默认设置为 1 。</param> /// <param name="aggregate">Sum | Min | Max</param> /// <param name="keys">一个或多个有序集合,不含prefix前辍</param> /// <returns></returns> public static Task<long> ZInterStoreAsync(string destination, decimal[] weights, RedisAggregate aggregate, params string[] keys) => Instance.ZInterStoreAsync(destination, weights, aggregate, keys); /// <summary> /// 通过索引区间返回有序集合成指定区间内的成员 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="start">开始位置,0表示第一个元素,-1表示最后一个元素</param> /// <param name="stop">结束位置,0表示第一个元素,-1表示最后一个元素</param> /// <returns></returns> public static Task<string[]> ZRangeAsync(string key, long start, long stop) => Instance.ZRangeAsync(key, start, stop); /// <summary> /// 通过索引区间返回有序集合成指定区间内的成员 /// </summary> /// <typeparam name="T">byte[] 或其他类型</typeparam> /// <param name="key">不含prefix前辍</param> /// <param name="start">开始位置,0表示第一个元素,-1表示最后一个元素</param> /// <param name="stop">结束位置,0表示第一个元素,-1表示最后一个元素</param> /// <returns></returns> public static Task<T[]> ZRangeAsync<T>(string key, long start, long stop) => Instance.ZRangeAsync<T>(key, start, stop); /// <summary> /// 通过索引区间返回有序集合成指定区间内的成员和分数 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="start">开始位置,0表示第一个元素,-1表示最后一个元素</param> /// <param name="stop">结束位置,0表示第一个元素,-1表示最后一个元素</param> /// <returns></returns> public static Task<(string member, decimal score)[]> ZRangeWithScoresAsync(string key, long start, long stop) => Instance.ZRangeWithScoresAsync(key, start, stop); /// <summary> /// 通过索引区间返回有序集合成指定区间内的成员和分数 /// </summary> /// <typeparam name="T">byte[] 或其他类型</typeparam> /// <param name="key">不含prefix前辍</param> /// <param name="start">开始位置,0表示第一个元素,-1表示最后一个元素</param> /// <param name="stop">结束位置,0表示第一个元素,-1表示最后一个元素</param> /// <returns></returns> public static Task<(T member, decimal score)[]> ZRangeWithScoresAsync<T>(string key, long start, long stop) => Instance.ZRangeWithScoresAsync<T>(key, start, stop); /// <summary> /// 通过分数返回有序集合指定区间内的成员 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="min">分数最小值 decimal.MinValue 1</param> /// <param name="max">分数最大值 decimal.MaxValue 10</param> /// <param name="limit">返回多少成员</param> /// <param name="offset">返回条件偏移位置</param> /// <returns></returns> public static Task<string[]> ZRangeByScoreAsync(string key, decimal min, decimal max, long? limit = null, long offset = 0) => Instance.ZRangeByScoreAsync(key, min, max, limit, offset); /// <summary> /// 通过分数返回有序集合指定区间内的成员 /// </summary> /// <typeparam name="T">byte[] 或其他类型</typeparam> /// <param name="key">不含prefix前辍</param> /// <param name="min">分数最小值 decimal.MinValue 1</param> /// <param name="max">分数最大值 decimal.MaxValue 10</param> /// <param name="limit">返回多少成员</param> /// <param name="offset">返回条件偏移位置</param> /// <returns></returns> public static Task<T[]> ZRangeByScoreAsync<T>(string key, decimal min, decimal max, long? limit = null, long offset = 0) => Instance.ZRangeByScoreAsync<T>(key, min, max, limit, offset); /// <summary> /// 通过分数返回有序集合指定区间内的成员 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="min">分数最小值 -inf (1 1</param> /// <param name="max">分数最大值 +inf (10 10</param> /// <param name="limit">返回多少成员</param> /// <param name="offset">返回条件偏移位置</param> /// <returns></returns> public static Task<string[]> ZRangeByScoreAsync(string key, string min, string max, long? limit = null, long offset = 0) => Instance.ZRangeByScoreAsync(key, min, max, limit, offset); /// <summary> /// 通过分数返回有序集合指定区间内的成员 /// </summary> /// <typeparam name="T">byte[] 或其他类型</typeparam> /// <param name="key">不含prefix前辍</param> /// <param name="min">分数最小值 -inf (1 1</param> /// <param name="max">分数最大值 +inf (10 10</param> /// <param name="limit">返回多少成员</param> /// <param name="offset">返回条件偏移位置</param> /// <returns></returns> public static Task<T[]> ZRangeByScoreAsync<T>(string key, string min, string max, long? limit = null, long offset = 0) => Instance.ZRangeByScoreAsync<T>(key, min, max, limit, offset); /// <summary> /// 通过分数返回有序集合指定区间内的成员和分数 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="min">分数最小值 decimal.MinValue 1</param> /// <param name="max">分数最大值 decimal.MaxValue 10</param> /// <param name="limit">返回多少成员</param> /// <param name="offset">返回条件偏移位置</param> /// <returns></returns> public static Task<(string member, decimal score)[]> ZRangeByScoreWithScoresAsync(string key, decimal min, decimal max, long? limit = null, long offset = 0) => Instance.ZRangeByScoreWithScoresAsync(key, min, max, limit, offset); /// <summary> /// 通过分数返回有序集合指定区间内的成员和分数 /// </summary> /// <typeparam name="T">byte[] 或其他类型</typeparam> /// <param name="key">不含prefix前辍</param> /// <param name="min">分数最小值 decimal.MinValue 1</param> /// <param name="max">分数最大值 decimal.MaxValue 10</param> /// <param name="limit">返回多少成员</param> /// <param name="offset">返回条件偏移位置</param> /// <returns></returns> public static Task<(T member, decimal score)[]> ZRangeByScoreWithScoresAsync<T>(string key, decimal min, decimal max, long? limit = null, long offset = 0) => Instance.ZRangeByScoreWithScoresAsync<T>(key, min, max, limit, offset); /// <summary> /// 通过分数返回有序集合指定区间内的成员和分数 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="min">分数最小值 -inf (1 1</param> /// <param name="max">分数最大值 +inf (10 10</param> /// <param name="limit">返回多少成员</param> /// <param name="offset">返回条件偏移位置</param> /// <returns></returns> public static Task<(string member, decimal score)[]> ZRangeByScoreWithScoresAsync(string key, string min, string max, long? limit = null, long offset = 0) => Instance.ZRangeByScoreWithScoresAsync(key, min, max, limit, offset); /// <summary> /// 通过分数返回有序集合指定区间内的成员和分数 /// </summary> /// <typeparam name="T">byte[] 或其他类型</typeparam> /// <param name="key">不含prefix前辍</param> /// <param name="min">分数最小值 -inf (1 1</param> /// <param name="max">分数最大值 +inf (10 10</param> /// <param name="limit">返回多少成员</param> /// <param name="offset">返回条件偏移位置</param> /// <returns></returns> public static Task<(T member, decimal score)[]> ZRangeByScoreWithScoresAsync<T>(string key, string min, string max, long? limit = null, long offset = 0) => Instance.ZRangeByScoreWithScoresAsync<T>(key, min, max, limit, offset); /// <summary> /// 返回有序集合中指定成员的索引 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="member">成员</param> /// <returns></returns> public static Task<long?> ZRankAsync(string key, object member) => Instance.ZRankAsync(key, member); /// <summary> /// 移除有序集合中的一个或多个成员 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="member">一个或多个成员</param> /// <returns></returns> public static Task<long> ZRemAsync<T>(string key, params T[] member) => Instance.ZRemAsync(key, member); /// <summary> /// 移除有序集合中给定的排名区间的所有成员 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="start">开始位置,0表示第一个元素,-1表示最后一个元素</param> /// <param name="stop">结束位置,0表示第一个元素,-1表示最后一个元素</param> /// <returns></returns> public static Task<long> ZRemRangeByRankAsync(string key, long start, long stop) => Instance.ZRemRangeByRankAsync(key, start, stop); /// <summary> /// 移除有序集合中给定的分数区间的所有成员 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="min">分数最小值 decimal.MinValue 1</param> /// <param name="max">分数最大值 decimal.MaxValue 10</param> /// <returns></returns> public static Task<long> ZRemRangeByScoreAsync(string key, decimal min, decimal max) => Instance.ZRemRangeByScoreAsync(key, min, max); /// <summary> /// 移除有序集合中给定的分数区间的所有成员 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="min">分数最小值 -inf (1 1</param> /// <param name="max">分数最大值 +inf (10 10</param> /// <returns></returns> public static Task<long> ZRemRangeByScoreAsync(string key, string min, string max) => Instance.ZRemRangeByScoreAsync(key, min, max); /// <summary> /// 返回有序集中指定区间内的成员,通过索引,分数从高到底 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="start">开始位置,0表示第一个元素,-1表示最后一个元素</param> /// <param name="stop">结束位置,0表示第一个元素,-1表示最后一个元素</param> /// <returns></returns> public static Task<string[]> ZRevRangeAsync(string key, long start, long stop) => Instance.ZRevRangeAsync(key, start, stop); /// <summary> /// 返回有序集中指定区间内的成员,通过索引,分数从高到底 /// </summary> /// <typeparam name="T">byte[] 或其他类型</typeparam> /// <param name="key">不含prefix前辍</param> /// <param name="start">开始位置,0表示第一个元素,-1表示最后一个元素</param> /// <param name="stop">结束位置,0表示第一个元素,-1表示最后一个元素</param> /// <returns></returns> public static Task<T[]> ZRevRangeAsync<T>(string key, long start, long stop) => Instance.ZRevRangeAsync<T>(key, start, stop); /// <summary> /// 返回有序集中指定区间内的成员和分数,通过索引,分数从高到底 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="start">开始位置,0表示第一个元素,-1表示最后一个元素</param> /// <param name="stop">结束位置,0表示第一个元素,-1表示最后一个元素</param> /// <returns></returns> public static Task<(string member, decimal score)[]> ZRevRangeWithScoresAsync(string key, long start, long stop) => Instance.ZRevRangeWithScoresAsync(key, start, stop); /// <summary> /// 返回有序集中指定区间内的成员和分数,通过索引,分数从高到底 /// </summary> /// <typeparam name="T">byte[] 或其他类型</typeparam> /// <param name="key">不含prefix前辍</param> /// <param name="start">开始位置,0表示第一个元素,-1表示最后一个元素</param> /// <param name="stop">结束位置,0表示第一个元素,-1表示最后一个元素</param> /// <returns></returns> public static Task<(T member, decimal score)[]> ZRevRangeWithScoresAsync<T>(string key, long start, long stop) => Instance.ZRevRangeWithScoresAsync<T>(key, start, stop); /// <summary> /// 返回有序集中指定分数区间内的成员,分数从高到低排序 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="max">分数最大值 decimal.MaxValue 10</param> /// <param name="min">分数最小值 decimal.MinValue 1</param> /// <param name="limit">返回多少成员</param> /// <param name="offset">返回条件偏移位置</param> /// <returns></returns> public static Task<string[]> ZRevRangeByScoreAsync(string key, decimal max, decimal min, long? limit = null, long? offset = 0) => Instance.ZRevRangeByScoreAsync(key, max, min, limit, offset); /// <summary> /// 返回有序集中指定分数区间内的成员,分数从高到低排序 /// </summary> /// <typeparam name="T">byte[] 或其他类型</typeparam> /// <param name="key">不含prefix前辍</param> /// <param name="max">分数最大值 decimal.MaxValue 10</param> /// <param name="min">分数最小值 decimal.MinValue 1</param> /// <param name="limit">返回多少成员</param> /// <param name="offset">返回条件偏移位置</param> /// <returns></returns> public static Task<T[]> ZRevRangeByScoreAsync<T>(string key, decimal max, decimal min, long? limit = null, long offset = 0) => Instance.ZRevRangeByScoreAsync<T>(key, max, min, limit, offset); /// <summary> /// 返回有序集中指定分数区间内的成员,分数从高到低排序 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="max">分数最大值 +inf (10 10</param> /// <param name="min">分数最小值 -inf (1 1</param> /// <param name="limit">返回多少成员</param> /// <param name="offset">返回条件偏移位置</param> /// <returns></returns> public static Task<string[]> ZRevRangeByScoreAsync(string key, string max, string min, long? limit = null, long? offset = 0) => Instance.ZRevRangeByScoreAsync(key, max, min, limit, offset); /// <summary> /// 返回有序集中指定分数区间内的成员,分数从高到低排序 /// </summary> /// <typeparam name="T">byte[] 或其他类型</typeparam> /// <param name="key">不含prefix前辍</param> /// <param name="max">分数最大值 +inf (10 10</param> /// <param name="min">分数最小值 -inf (1 1</param> /// <param name="limit">返回多少成员</param> /// <param name="offset">返回条件偏移位置</param> /// <returns></returns> public static Task<T[]> ZRevRangeByScoreAsync<T>(string key, string max, string min, long? limit = null, long offset = 0) => Instance.ZRevRangeByScoreAsync<T>(key, max, min, limit, offset); /// <summary> /// 返回有序集中指定分数区间内的成员和分数,分数从高到低排序 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="max">分数最大值 decimal.MaxValue 10</param> /// <param name="min">分数最小值 decimal.MinValue 1</param> /// <param name="limit">返回多少成员</param> /// <param name="offset">返回条件偏移位置</param> /// <returns></returns> public static Task<(string member, decimal score)[]> ZRevRangeByScoreWithScoresAsync(string key, decimal max, decimal min, long? limit = null, long offset = 0) => Instance.ZRevRangeByScoreWithScoresAsync(key, max, min, limit, offset); /// <summary> /// 返回有序集中指定分数区间内的成员和分数,分数从高到低排序 /// </summary> /// <typeparam name="T">byte[] 或其他类型</typeparam> /// <param name="key">不含prefix前辍</param> /// <param name="max">分数最大值 decimal.MaxValue 10</param> /// <param name="min">分数最小值 decimal.MinValue 1</param> /// <param name="limit">返回多少成员</param> /// <param name="offset">返回条件偏移位置</param> /// <returns></returns> public static Task<(T member, decimal score)[]> ZRevRangeByScoreWithScoresAsync<T>(string key, decimal max, decimal min, long? limit = null, long offset = 0) => Instance.ZRevRangeByScoreWithScoresAsync<T>(key, max, min, limit, offset); /// <summary> /// 返回有序集中指定分数区间内的成员和分数,分数从高到低排序 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="max">分数最大值 +inf (10 10</param> /// <param name="min">分数最小值 -inf (1 1</param> /// <param name="limit">返回多少成员</param> /// <param name="offset">返回条件偏移位置</param> /// <returns></returns> public static Task<(string member, decimal score)[]> ZRevRangeByScoreWithScoresAsync(string key, string max, string min, long? limit = null, long offset = 0) => Instance.ZRevRangeByScoreWithScoresAsync(key, max, min, limit, offset); /// <summary> /// 返回有序集中指定分数区间内的成员和分数,分数从高到低排序 /// </summary> /// <typeparam name="T">byte[] 或其他类型</typeparam> /// <param name="key">不含prefix前辍</param> /// <param name="max">分数最大值 +inf (10 10</param> /// <param name="min">分数最小值 -inf (1 1</param> /// <param name="limit">返回多少成员</param> /// <param name="offset">返回条件偏移位置</param> /// <returns></returns> public static Task<(T member, decimal score)[]> ZRevRangeByScoreWithScoresAsync<T>(string key, string max, string min, long? limit = null, long offset = 0) => Instance.ZRevRangeByScoreWithScoresAsync<T>(key, max, min, limit, offset); /// <summary> /// 返回有序集合中指定成员的排名,有序集成员按分数值递减(从大到小)排序 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="member">成员</param> /// <returns></returns> public static Task<long?> ZRevRankAsync(string key, object member) => Instance.ZRevRankAsync(key, member); /// <summary> /// 返回有序集中,成员的分数值 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="member">成员</param> /// <returns></returns> public static Task<decimal?> ZScoreAsync(string key, object member) => Instance.ZScoreAsync(key, member); /// <summary> /// 计算给定的一个或多个有序集的并集,将结果集存储在新的有序集合 destination 中 /// </summary> /// <param name="destination">新的有序集合,不含prefix前辍</param> /// <param name="weights">使用 WEIGHTS 选项,你可以为 每个 给定有序集 分别 指定一个乘法因子。如果没有指定 WEIGHTS 选项,乘法因子默认设置为 1 。</param> /// <param name="aggregate">Sum | Min | Max</param> /// <param name="keys">一个或多个有序集合,不含prefix前辍</param> /// <returns></returns> public static Task<long> ZUnionStoreAsync(string destination, decimal[] weights, RedisAggregate aggregate, params string[] keys) => Instance.ZUnionStoreAsync(destination, weights, aggregate, keys); /// <summary> /// 迭代有序集合中的元素 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="cursor">位置</param> /// <param name="pattern">模式</param> /// <param name="count">数量</param> /// <returns></returns> public static Task<RedisScan<(string member, decimal score)>> ZScanAsync(string key, long cursor, string pattern = null, long? count = null) => Instance.ZScanAsync(key, cursor, pattern, count); /// <summary> /// 迭代有序集合中的元素 /// </summary> /// <typeparam name="T">byte[] 或其他类型</typeparam> /// <param name="key">不含prefix前辍</param> /// <param name="cursor">位置</param> /// <param name="pattern">模式</param> /// <param name="count">数量</param> /// <returns></returns> public static Task<RedisScan<(T member, decimal score)>> ZScanAsync<T>(string key, long cursor, string pattern = null, long? count = null) => Instance.ZScanAsync<T>(key, cursor, pattern, count); /// <summary> /// 当有序集合的所有成员都具有相同的分值时,有序集合的元素会根据成员的字典序来进行排序,这个命令可以返回给定的有序集合键 key 中,值介于 min 和 max 之间的成员。 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="min">'(' 表示包含在范围,'[' 表示不包含在范围,'+' 正无穷大,'-' 负无限。 ZRANGEBYLEX zset - + ,命令将返回有序集合中的所有元素</param> /// <param name="max">'(' 表示包含在范围,'[' 表示不包含在范围,'+' 正无穷大,'-' 负无限。 ZRANGEBYLEX zset - + ,命令将返回有序集合中的所有元素</param> /// <param name="limit">返回多少成员</param> /// <param name="offset">返回条件偏移位置</param> /// <returns></returns> public static Task<string[]> ZRangeByLexAsync(string key, string min, string max, long? limit = null, long offset = 0) => Instance.ZRangeByLexAsync(key, min, max, limit, offset); /// <summary> /// 当有序集合的所有成员都具有相同的分值时,有序集合的元素会根据成员的字典序来进行排序,这个命令可以返回给定的有序集合键 key 中,值介于 min 和 max 之间的成员。 /// </summary> /// <typeparam name="T">byte[] 或其他类型</typeparam> /// <param name="key">不含prefix前辍</param> /// <param name="min">'(' 表示包含在范围,'[' 表示不包含在范围,'+' 正无穷大,'-' 负无限。 ZRANGEBYLEX zset - + ,命令将返回有序集合中的所有元素</param> /// <param name="max">'(' 表示包含在范围,'[' 表示不包含在范围,'+' 正无穷大,'-' 负无限。 ZRANGEBYLEX zset - + ,命令将返回有序集合中的所有元素</param> /// <param name="limit">返回多少成员</param> /// <param name="offset">返回条件偏移位置</param> /// <returns></returns> public static Task<T[]> ZRangeByLexAsync<T>(string key, string min, string max, long? limit = null, long offset = 0) => Instance.ZRangeByLexAsync<T>(key, min, max, limit, offset); /// <summary> /// 当有序集合的所有成员都具有相同的分值时,有序集合的元素会根据成员的字典序来进行排序,这个命令可以返回给定的有序集合键 key 中,值介于 min 和 max 之间的成员。 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="min">'(' 表示包含在范围,'[' 表示不包含在范围,'+' 正无穷大,'-' 负无限。 ZRANGEBYLEX zset - + ,命令将返回有序集合中的所有元素</param> /// <param name="max">'(' 表示包含在范围,'[' 表示不包含在范围,'+' 正无穷大,'-' 负无限。 ZRANGEBYLEX zset - + ,命令将返回有序集合中的所有元素</param> /// <returns></returns> public static Task<long> ZRemRangeByLexAsync(string key, string min, string max) => Instance.ZRemRangeByLexAsync(key, min, max); /// <summary> /// 当有序集合的所有成员都具有相同的分值时,有序集合的元素会根据成员的字典序来进行排序,这个命令可以返回给定的有序集合键 key 中,值介于 min 和 max 之间的成员。 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="min">'(' 表示包含在范围,'[' 表示不包含在范围,'+' 正无穷大,'-' 负无限。 ZRANGEBYLEX zset - + ,命令将返回有序集合中的所有元素</param> /// <param name="max">'(' 表示包含在范围,'[' 表示不包含在范围,'+' 正无穷大,'-' 负无限。 ZRANGEBYLEX zset - + ,命令将返回有序集合中的所有元素</param> /// <returns></returns> public static Task<long> ZLexCountAsync(string key, string min, string max) => Instance.ZLexCountAsync(key, min, max); #endregion #region Set /// <summary> /// 向集合添加一个或多个成员 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="members">一个或多个成员</param> /// <returns></returns> public static Task<long> SAddAsync<T>(string key, params T[] members) => Instance.SAddAsync(key, members); /// <summary> /// 获取集合的成员数 /// </summary> /// <param name="key">不含prefix前辍</param> /// <returns></returns> public static Task<long> SCardAsync(string key) => Instance.SCardAsync(key); /// <summary> /// 返回给定所有集合的差集 /// </summary> /// <param name="keys">不含prefix前辍</param> /// <returns></returns> public static Task<string[]> SDiffAsync(params string[] keys) => Instance.SDiffAsync(keys); /// <summary> /// 返回给定所有集合的差集 /// </summary> /// <typeparam name="T">byte[] 或其他类型</typeparam> /// <param name="keys">不含prefix前辍</param> /// <returns></returns> public static Task<T[]> SDiffAsync<T>(params string[] keys) => Instance.SDiffAsync<T>(keys); /// <summary> /// 返回给定所有集合的差集并存储在 destination 中 /// </summary> /// <param name="destination">新的无序集合,不含prefix前辍</param> /// <param name="keys">一个或多个无序集合,不含prefix前辍</param> /// <returns></returns> public static Task<long> SDiffStoreAsync(string destination, params string[] keys) => Instance.SDiffStoreAsync(destination, keys); /// <summary> /// 返回给定所有集合的交集 /// </summary> /// <param name="keys">不含prefix前辍</param> /// <returns></returns> public static Task<string[]> SInterAsync(params string[] keys) => Instance.SInterAsync(keys); /// <summary> /// 返回给定所有集合的交集 /// </summary> /// <typeparam name="T">byte[] 或其他类型</typeparam> /// <param name="keys">不含prefix前辍</param> /// <returns></returns> public static Task<T[]> SInterAsync<T>(params string[] keys) => Instance.SInterAsync<T>(keys); /// <summary> /// 返回给定所有集合的交集并存储在 destination 中 /// </summary> /// <param name="destination">新的无序集合,不含prefix前辍</param> /// <param name="keys">一个或多个无序集合,不含prefix前辍</param> /// <returns></returns> public static Task<long> SInterStoreAsync(string destination, params string[] keys) => Instance.SInterStoreAsync(destination, keys); /// <summary> /// 判断 member 元素是否是集合 key 的成员 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="member">成员</param> /// <returns></returns> public static Task<bool> SIsMemberAsync(string key, object member) => Instance.SIsMemberAsync(key, member); /// <summary> /// 返回集合中的所有成员 /// </summary> /// <param name="key">不含prefix前辍</param> /// <returns></returns> public static Task<string[]> SMembersAsync(string key) => Instance.SMembersAsync(key); /// <summary> /// 返回集合中的所有成员 /// </summary> /// <typeparam name="T">byte[] 或其他类型</typeparam> /// <param name="key">不含prefix前辍</param> /// <returns></returns> public static Task<T[]> SMembersAsync<T>(string key) => Instance.SMembersAsync<T>(key); /// <summary> /// 将 member 元素从 source 集合移动到 destination 集合 /// </summary> /// <param name="source">无序集合key,不含prefix前辍</param> /// <param name="destination">目标无序集合key,不含prefix前辍</param> /// <param name="member">成员</param> /// <returns></returns> public static Task<bool> SMoveAsync(string source, string destination, object member) => Instance.SMoveAsync(source, destination, member); /// <summary> /// 移除并返回集合中的一个随机元素 /// </summary> /// <param name="key">不含prefix前辍</param> /// <returns></returns> public static Task<string> SPopAsync(string key) => Instance.SPopAsync(key); /// <summary> /// 移除并返回集合中的一个随机元素 /// </summary> /// <typeparam name="T">byte[] 或其他类型</typeparam> /// <param name="key">不含prefix前辍</param> /// <returns></returns> public static Task<T> SPopAsync<T>(string key) => Instance.SPopAsync<T>(key); /// <summary> /// [redis-server 3.2] 移除并返回集合中的一个或多个随机元素 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="count">移除并返回的个数</param> /// <returns></returns> public static Task<string[]> SPopAsync(string key, long count) => Instance.SPopAsync(key, count); /// <summary> /// [redis-server 3.2] 移除并返回集合中的一个或多个随机元素 /// </summary> /// <typeparam name="T">byte[] 或其他类型</typeparam> /// <param name="key">不含prefix前辍</param> /// <param name="count">移除并返回的个数</param> /// <returns></returns> public static Task<T[]> SPopAsync<T>(string key, long count) => Instance.SPopAsync<T>(key, count); /// <summary> /// 返回集合中的一个随机元素 /// </summary> /// <param name="key">不含prefix前辍</param> /// <returns></returns> public static Task<string> SRandMemberAsync(string key) => Instance.SRandMemberAsync(key); /// <summary> /// 返回集合中的一个随机元素 /// </summary> /// <typeparam name="T">byte[] 或其他类型</typeparam> /// <param name="key">不含prefix前辍</param> /// <returns></returns> public static Task<T> SRandMemberAsync<T>(string key) => Instance.SRandMemberAsync<T>(key); /// <summary> /// 返回集合中一个或多个随机数的元素 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="count">返回个数</param> /// <returns></returns> public static Task<string[]> SRandMembersAsync(string key, int count = 1) => Instance.SRandMembersAsync(key, count); /// <summary> /// 返回集合中一个或多个随机数的元素 /// </summary> /// <typeparam name="T">byte[] 或其他类型</typeparam> /// <param name="key">不含prefix前辍</param> /// <param name="count">返回个数</param> /// <returns></returns> public static Task<T[]> SRandMembersAsync<T>(string key, int count = 1) => Instance.SRandMembersAsync<T>(key, count); /// <summary> /// 移除集合中一个或多个成员 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="members">一个或多个成员</param> /// <returns></returns> public static Task<long> SRemAsync<T>(string key, params T[] members) => Instance.SRemAsync(key, members); /// <summary> /// 返回所有给定集合的并集 /// </summary> /// <param name="keys">不含prefix前辍</param> /// <returns></returns> public static Task<string[]> SUnionAsync(params string[] keys) => Instance.SUnionAsync(keys); /// <summary> /// 返回所有给定集合的并集 /// </summary> /// <typeparam name="T">byte[] 或其他类型</typeparam> /// <param name="keys">不含prefix前辍</param> /// <returns></returns> public static Task<T[]> SUnionAsync<T>(params string[] keys) => Instance.SUnionAsync<T>(keys); /// <summary> /// 所有给定集合的并集存储在 destination 集合中 /// </summary> /// <param name="destination">新的无序集合,不含prefix前辍</param> /// <param name="keys">一个或多个无序集合,不含prefix前辍</param> /// <returns></returns> public static Task<long> SUnionStoreAsync(string destination, params string[] keys) => Instance.SUnionStoreAsync(destination, keys); /// <summary> /// 迭代集合中的元素 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="cursor">位置</param> /// <param name="pattern">模式</param> /// <param name="count">数量</param> /// <returns></returns> public static Task<RedisScan<string>> SScanAsync(string key, long cursor, string pattern = null, long? count = null) => Instance.SScanAsync(key, cursor, pattern, count); /// <summary> /// 迭代集合中的元素 /// </summary> /// <typeparam name="T">byte[] 或其他类型</typeparam> /// <param name="key">不含prefix前辍</param> /// <param name="cursor">位置</param> /// <param name="pattern">模式</param> /// <param name="count">数量</param> /// <returns></returns> public static Task<RedisScan<T>> SScanAsync<T>(string key, long cursor, string pattern = null, long? count = null) => Instance.SScanAsync<T>(key, cursor, pattern, count); #endregion #region List /// <summary> /// 通过索引获取列表中的元素 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="index">索引</param> /// <returns></returns> public static Task<string> LIndexAsync(string key, long index) => Instance.LIndexAsync(key, index); /// <summary> /// 通过索引获取列表中的元素 /// </summary> /// <typeparam name="T">byte[] 或其他类型</typeparam> /// <param name="key">不含prefix前辍</param> /// <param name="index">索引</param> /// <returns></returns> public static Task<T> LIndexAsync<T>(string key, long index) => Instance.LIndexAsync<T>(key, index); /// <summary> /// 在列表中的元素前面插入元素 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="pivot">列表的元素</param> /// <param name="value">新元素</param> /// <returns></returns> public static Task<long> LInsertBeforeAsync(string key, object pivot, object value) => Instance.LInsertBeforeAsync(key, pivot, value); /// <summary> /// 在列表中的元素后面插入元素 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="pivot">列表的元素</param> /// <param name="value">新元素</param> /// <returns></returns> public static Task<long> LInsertAfterAsync(string key, object pivot, object value) => Instance.LInsertAfterAsync(key, pivot, value); /// <summary> /// 获取列表长度 /// </summary> /// <param name="key">不含prefix前辍</param> /// <returns></returns> public static Task<long> LLenAsync(string key) => Instance.LLenAsync(key); /// <summary> /// 移出并获取列表的第一个元素 /// </summary> /// <param name="key">不含prefix前辍</param> /// <returns></returns> public static Task<string> LPopAsync(string key) => Instance.LPopAsync(key); /// <summary> /// 移出并获取列表的第一个元素 /// </summary> /// <typeparam name="T">byte[] 或其他类型</typeparam> /// <param name="key">不含prefix前辍</param> /// <returns></returns> public static Task<T> LPopAsync<T>(string key) => Instance.LPopAsync<T>(key); /// <summary> /// 将一个或多个值插入到列表头部 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="value">一个或多个值</param> /// <returns>执行 LPUSH 命令后,列表的长度</returns> public static Task<long> LPushAsync<T>(string key, params T[] value) => Instance.LPushAsync(key, value); /// <summary> /// 将一个值插入到已存在的列表头部 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="value">值</param> /// <returns>执行 LPUSHX 命令后,列表的长度。</returns> public static Task<long> LPushXAsync(string key, object value) => Instance.LPushXAsync(key, value); /// <summary> /// 获取列表指定范围内的元素 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="start">开始位置,0表示第一个元素,-1表示最后一个元素</param> /// <param name="stop">结束位置,0表示第一个元素,-1表示最后一个元素</param> /// <returns></returns> public static Task<string[]> LRangeAsync(string key, long start, long stop) => Instance.LRangeAsync(key, start, stop); /// <summary> /// 获取列表指定范围内的元素 /// </summary> /// <typeparam name="T">byte[] 或其他类型</typeparam> /// <param name="key">不含prefix前辍</param> /// <param name="start">开始位置,0表示第一个元素,-1表示最后一个元素</param> /// <param name="stop">结束位置,0表示第一个元素,-1表示最后一个元素</param> /// <returns></returns> public static Task<T[]> LRangeAsync<T>(string key, long start, long stop) => Instance.LRangeAsync<T>(key, start, stop); /// <summary> /// 根据参数 count 的值,移除列表中与参数 value 相等的元素 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="count">移除的数量,大于0时从表头删除数量count,小于0时从表尾删除数量-count,等于0移除所有</param> /// <param name="value">元素</param> /// <returns></returns> public static Task<long> LRemAsync(string key, long count, object value) => Instance.LRemAsync(key, count, value); /// <summary> /// 通过索引设置列表元素的值 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="index">索引</param> /// <param name="value">值</param> /// <returns></returns> public static Task<bool> LSetAsync(string key, long index, object value) => Instance.LSetAsync(key, index, value); /// <summary> /// 对一个列表进行修剪,让列表只保留指定区间内的元素,不在指定区间之内的元素都将被删除 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="start">开始位置,0表示第一个元素,-1表示最后一个元素</param> /// <param name="stop">结束位置,0表示第一个元素,-1表示最后一个元素</param> /// <returns></returns> public static Task<bool> LTrimAsync(string key, long start, long stop) => Instance.LTrimAsync(key, start, stop); /// <summary> /// 移除并获取列表最后一个元素 /// </summary> /// <param name="key">不含prefix前辍</param> /// <returns></returns> public static Task<string> RPopAsync(string key) => Instance.RPopAsync(key); /// <summary> /// 移除并获取列表最后一个元素 /// </summary> /// <typeparam name="T">byte[] 或其他类型</typeparam> /// <param name="key">不含prefix前辍</param> /// <returns></returns> public static Task<T> RPopAsync<T>(string key) => Instance.RPopAsync<T>(key); /// <summary> /// 将列表 source 中的最后一个元素(尾元素)弹出,并返回给客户端。 /// 将 source 弹出的元素插入到列表 destination ,作为 destination 列表的的头元素。 /// </summary> /// <param name="source">源key,不含prefix前辍</param> /// <param name="destination">目标key,不含prefix前辍</param> /// <returns></returns> public static Task<string> RPopLPushAsync(string source, string destination) => Instance.RPopLPushAsync(source, destination); /// <summary> /// 将列表 source 中的最后一个元素(尾元素)弹出,并返回给客户端。 /// 将 source 弹出的元素插入到列表 destination ,作为 destination 列表的的头元素。 /// </summary> /// <typeparam name="T">byte[] 或其他类型</typeparam> /// <param name="source">源key,不含prefix前辍</param> /// <param name="destination">目标key,不含prefix前辍</param> /// <returns></returns> public static Task<T> RPopLPushAsync<T>(string source, string destination) => Instance.RPopLPushAsync<T>(source, destination); /// <summary> /// 在列表中添加一个或多个值 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="value">一个或多个值</param> /// <returns>执行 RPUSH 命令后,列表的长度</returns> public static Task<long> RPushAsync<T>(string key, params T[] value) => Instance.RPushAsync(key, value); /// <summary> /// 为已存在的列表添加值 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="value">一个或多个值</param> /// <returns>执行 RPUSHX 命令后,列表的长度</returns> public static Task<long> RPushXAsync(string key, object value) => Instance.RPushAsync(key, value); #endregion #region Hash /// <summary> /// 删除一个或多个哈希表字段 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="fields">字段</param> /// <returns></returns> public static Task<long> HDelAsync(string key, params string[] fields) => Instance.HDelAsync(key, fields); /// <summary> /// 查看哈希表 key 中,指定的字段是否存在 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="field">字段</param> /// <returns></returns> public static Task<bool> HExistsAsync(string key, string field) => Instance.HExistsAsync(key, field); /// <summary> /// 获取存储在哈希表中指定字段的值 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="field">字段</param> /// <returns></returns> public static Task<string> HGetAsync(string key, string field) => Instance.HGetAsync(key, field); /// <summary> /// 获取存储在哈希表中指定字段的值 /// </summary> /// <typeparam name="T">byte[] 或其他类型</typeparam> /// <param name="key">不含prefix前辍</param> /// <param name="field">字段</param> /// <returns></returns> public static Task<T> HGetAsync<T>(string key, string field) => Instance.HGetAsync<T>(key, field); /// <summary> /// 获取在哈希表中指定 key 的所有字段和值 /// </summary> /// <param name="key">不含prefix前辍</param> /// <returns></returns> public static Task<Dictionary<string, string>> HGetAllAsync(string key) => Instance.HGetAllAsync(key); /// <summary> /// 获取在哈希表中指定 key 的所有字段和值 /// </summary> /// <typeparam name="T">byte[] 或其他类型</typeparam> /// <param name="key">不含prefix前辍</param> /// <returns></returns> public static Task<Dictionary<string, T>> HGetAllAsync<T>(string key) => Instance.HGetAllAsync<T>(key); /// <summary> /// 为哈希表 key 中的指定字段的整数值加上增量 increment /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="field">字段</param> /// <param name="value">增量值(默认=1)</param> /// <returns></returns> public static Task<long> HIncrByAsync(string key, string field, long value = 1) => Instance.HIncrByAsync(key, field, value); /// <summary> /// 为哈希表 key 中的指定字段的整数值加上增量 increment /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="field">字段</param> /// <param name="value">增量值(默认=1)</param> /// <returns></returns> public static Task<decimal> HIncrByFloatAsync(string key, string field, decimal value = 1) => Instance.HIncrByFloatAsync(key, field, value); /// <summary> /// 获取所有哈希表中的字段 /// </summary> /// <param name="key">不含prefix前辍</param> /// <returns></returns> public static Task<string[]> HKeysAsync(string key) => Instance.HKeysAsync(key); /// <summary> /// 获取哈希表中字段的数量 /// </summary> /// <param name="key">不含prefix前辍</param> /// <returns></returns> public static Task<long> HLenAsync(string key) => Instance.HLenAsync(key); /// <summary> /// 获取存储在哈希表中多个字段的值 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="fields">字段</param> /// <returns></returns> public static Task<string[]> HMGetAsync(string key, params string[] fields) => Instance.HMGetAsync(key, fields); /// <summary> /// 获取存储在哈希表中多个字段的值 /// </summary> /// <typeparam name="T">byte[] 或其他类型</typeparam> /// <param name="key">不含prefix前辍</param> /// <param name="fields">一个或多个字段</param> /// <returns></returns> public static Task<T[]> HMGetAsync<T>(string key, params string[] fields) => Instance.HMGetAsync<T>(key, fields); /// <summary> /// 同时将多个 field-value (域-值)对设置到哈希表 key 中 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="keyValues">key1 value1 [key2 value2]</param> /// <returns></returns> public static Task<bool> HMSetAsync(string key, params object[] keyValues) => Instance.HMSetAsync(key, keyValues); /// <summary> /// 将哈希表 key 中的字段 field 的值设为 value /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="field">字段</param> /// <param name="value">值</param> /// <returns>如果字段是哈希表中的一个新建字段,并且值设置成功,返回true。如果哈希表中域字段已经存在且旧值已被新值覆盖,返回false。</returns> public static Task<bool> HSetAsync(string key, string field, object value) => Instance.HSetAsync(key, field, value); /// <summary> /// 只有在字段 field 不存在时,设置哈希表字段的值 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="field">字段</param> /// <param name="value">值(string 或 byte[])</param> /// <returns></returns> public static Task<bool> HSetNxAsync(string key, string field, object value) => Instance.HSetNxAsync(key, field, value); /// <summary> /// 获取哈希表中所有值 /// </summary> /// <param name="key">不含prefix前辍</param> /// <returns></returns> public static Task<string[]> HValsAsync(string key) => Instance.HValsAsync(key); /// <summary> /// 获取哈希表中所有值 /// </summary> /// <typeparam name="T">byte[] 或其他类型</typeparam> /// <param name="key">不含prefix前辍</param> /// <returns></returns> public static Task<T[]> HValsAsync<T>(string key) => Instance.HValsAsync<T>(key); /// <summary> /// 迭代哈希表中的键值对 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="cursor">位置</param> /// <param name="pattern">模式</param> /// <param name="count">数量</param> /// <returns></returns> public static Task<RedisScan<(string field, string value)>> HScanAsync(string key, long cursor, string pattern = null, long? count = null) => Instance.HScanAsync(key, cursor, pattern, count); /// <summary> /// 迭代哈希表中的键值对 /// </summary> /// <typeparam name="T">byte[] 或其他类型</typeparam> /// <param name="key">不含prefix前辍</param> /// <param name="cursor">位置</param> /// <param name="pattern">模式</param> /// <param name="count">数量</param> /// <returns></returns> public static Task<RedisScan<(string field, T value)>> HScanAsync<T>(string key, long cursor, string pattern = null, long? count = null) => Instance.HScanAsync<T>(key, cursor, pattern, count); /// <summary> /// [redis-server 5.0.0] 删除并返回有序集合key中的最多count个具有最高得分的成员。如未指定,count的默认值为1。指定一个大于有序集合的基数的count不会产生错误。 当返回多个元素时候,得分最高的元素将是第一个元素,然后是分数较低的元素。 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="count">数量</param> /// <returns></returns> public static Task<(string member, decimal score)[]> ZPopMaxAsync(string key, long count) => Instance.ZPopMaxAsync(key, count); /// <summary> /// [redis-server 5.0.0] 删除并返回有序集合key中的最多count个具有最高得分的成员。如未指定,count的默认值为1。指定一个大于有序集合的基数的count不会产生错误。 当返回多个元素时候,得分最高的元素将是第一个元素,然后是分数较低的元素。 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="count">数量</param> /// <returns></returns> public static Task<(T member, decimal score)[]> ZPopMaxAsync<T>(string key, long count) => Instance.ZPopMaxAsync<T>(key, count); /// <summary> /// [redis-server 5.0.0] 删除并返回有序集合key中的最多count个具有最低得分的成员。如未指定,count的默认值为1。指定一个大于有序集合的基数的count不会产生错误。 当返回多个元素时候,得分最低的元素将是第一个元素,然后是分数较高的元素。 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="count">数量</param> /// <returns></returns> public static Task<(string member, decimal score)[]> ZPopMinAsync(string key, long count) => Instance.ZPopMinAsync(key, count); /// <summary> /// [redis-server 5.0.0] 删除并返回有序集合key中的最多count个具有最低得分的成员。如未指定,count的默认值为1。指定一个大于有序集合的基数的count不会产生错误。 当返回多个元素时候,得分最低的元素将是第一个元素,然后是分数较高的元素。 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="count">数量</param> /// <returns></returns> public static Task<(T member, decimal score)[]> ZPopMinAsync<T>(string key, long count) => Instance.ZPopMinAsync<T>(key, count); #endregion #region String /// <summary> /// 如果 key 已经存在并且是一个字符串, APPEND 命令将指定的 value 追加到该 key 原来值(value)的末尾 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="value">字符串</param> /// <returns>追加指定值之后, key 中字符串的长度</returns> public static Task<long> AppendAsync(string key, object value) => Instance.AppendAsync(key, value); /// <summary> /// 计算给定位置被设置为 1 的比特位的数量 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="start">开始位置</param> /// <param name="end">结束位置</param> /// <returns></returns> public static Task<long> BitCountAsync(string key, long start, long end) => Instance.BitCountAsync(key, start, end); /// <summary> /// 对一个或多个保存二进制位的字符串 key 进行位元操作,并将结果保存到 destkey 上 /// </summary> /// <param name="op">And | Or | XOr | Not</param> /// <param name="destKey">不含prefix前辍</param> /// <param name="keys">不含prefix前辍</param> /// <returns>保存到 destkey 的长度,和输入 key 中最长的长度相等</returns> public static Task<long> BitOpAsync(RedisBitOp op, string destKey, params string[] keys) => Instance.BitOpAsync(op, destKey, keys); /// <summary> /// 对 key 所储存的值,查找范围内第一个被设置为1或者0的bit位 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="bit">查找值</param> /// <param name="start">开始位置,-1是最后一个,-2是倒数第二个</param> /// <param name="end">结果位置,-1是最后一个,-2是倒数第二个</param> /// <returns>返回范围内第一个被设置为1或者0的bit位</returns> public static Task<long> BitPosAsync(string key, bool bit, long? start = null, long? end = null) => Instance.BitPosAsync(key, bit, start, end); /// <summary> /// 获取指定 key 的值 /// </summary> /// <param name="key">不含prefix前辍</param> /// <returns></returns> public static Task<string> GetAsync(string key) => Instance.GetAsync(key); /// <summary> /// 获取指定 key 的值 /// </summary> /// <typeparam name="T">byte[] 或其他类型</typeparam> /// <param name="key">不含prefix前辍</param> /// <returns></returns> public static Task<T> GetAsync<T>(string key) => Instance.GetAsync<T>(key); /// <summary> /// 对 key 所储存的值,获取指定偏移量上的位(bit) /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="offset">偏移量</param> /// <returns></returns> public static Task<bool> GetBitAsync(string key, uint offset) => Instance.GetBitAsync(key, offset); /// <summary> /// 返回 key 中字符串值的子字符 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="start">开始位置,0表示第一个元素,-1表示最后一个元素</param> /// <param name="end">结束位置,0表示第一个元素,-1表示最后一个元素</param> /// <returns></returns> public static Task<string> GetRangeAsync(string key, long start, long end) => Instance.GetRangeAsync(key, start, end); /// <summary> /// 返回 key 中字符串值的子字符 /// </summary> /// <typeparam name="T">byte[] 或其他类型</typeparam> /// <param name="key">不含prefix前辍</param> /// <param name="start">开始位置,0表示第一个元素,-1表示最后一个元素</param> /// <param name="end">结束位置,0表示第一个元素,-1表示最后一个元素</param> /// <returns></returns> public static Task<T> GetRangeAsync<T>(string key, long start, long end) => Instance.GetRangeAsync<T>(key, start, end); /// <summary> /// 将给定 key 的值设为 value ,并返回 key 的旧值(old value) /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="value">值</param> /// <returns></returns> public static Task<string> GetSetAsync(string key, object value) => Instance.GetSetAsync(key, value); /// <summary> /// 将给定 key 的值设为 value ,并返回 key 的旧值(old value) /// </summary> /// <typeparam name="T">byte[] 或其他类型</typeparam> /// <param name="key">不含prefix前辍</param> /// <param name="value">值</param> /// <returns></returns> public static Task<T> GetSetAsync<T>(string key, object value) => Instance.GetSetAsync<T>(key, value); /// <summary> /// 将 key 所储存的值加上给定的增量值(increment) /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="value">增量值(默认=1)</param> /// <returns></returns> public static Task<long> IncrByAsync(string key, long value = 1) => Instance.IncrByAsync(key, value); /// <summary> /// 将 key 所储存的值加上给定的浮点增量值(increment) /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="value">增量值(默认=1)</param> /// <returns></returns> public static Task<decimal> IncrByFloatAsync(string key, decimal value = 1) => Instance.IncrByFloatAsync(key, value); /// <summary> /// 获取多个指定 key 的值(数组) /// </summary> /// <param name="keys">不含prefix前辍</param> /// <returns></returns> public static Task<string[]> MGetAsync(params string[] keys) => Instance.MGetAsync(keys); /// <summary> /// 获取多个指定 key 的值(数组) /// </summary> /// <typeparam name="T">byte[] 或其他类型</typeparam> /// <param name="keys">不含prefix前辍</param> /// <returns></returns> public static Task<T[]> MGetAsync<T>(params string[] keys) => Instance.MGetAsync<T>(keys); /// <summary> /// 同时设置一个或多个 key-value 对 /// </summary> /// <param name="keyValues">key1 value1 [key2 value2]</param> /// <returns></returns> public static Task<bool> MSetAsync(params object[] keyValues) => Instance.MSetAsync(keyValues); /// <summary> /// 同时设置一个或多个 key-value 对,当且仅当所有给定 key 都不存在 /// </summary> /// <param name="keyValues">key1 value1 [key2 value2]</param> /// <returns></returns> public static Task<bool> MSetNxAsync(params object[] keyValues) => Instance.MSetNxAsync(keyValues); /// <summary> /// 设置指定 key 的值,所有写入参数object都支持string | byte[] | 数值 | 对象 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="value">值</param> /// <param name="expireSeconds">过期(秒单位)</param> /// <param name="exists">Nx, Xx</param> /// <returns></returns> public static Task<bool> SetAsync(string key, object value, int expireSeconds = -1, RedisExistence? exists = null) => Instance.SetAsync(key, value, expireSeconds, exists); public static Task<bool> SetAsync(string key, object value, TimeSpan expire, RedisExistence? exists = null) => Instance.SetAsync(key, value, expire, exists); /// <summary> /// 对 key 所储存的字符串值,设置或清除指定偏移量上的位(bit) /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="offset">偏移量</param> /// <param name="value">值</param> /// <returns></returns> public static Task<bool> SetBitAsync(string key, uint offset, bool value) => Instance.SetBitAsync(key, offset, value); /// <summary> /// 只有在 key 不存在时设置 key 的值 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="value">值</param> /// <returns></returns> public static Task<bool> SetNxAsync(string key, object value) => Instance.SetNxAsync(key, value); /// <summary> /// 用 value 参数覆写给定 key 所储存的字符串值,从偏移量 offset 开始 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="offset">偏移量</param> /// <param name="value">值</param> /// <returns>被修改后的字符串长度</returns> public static Task<long> SetRangeAsync(string key, uint offset, object value) => Instance.SetRangeAsync(key, offset, value); /// <summary> /// 返回 key 所储存的字符串值的长度 /// </summary> /// <param name="key">不含prefix前辍</param> /// <returns></returns> public static Task<long> StrLenAsync(string key) => Instance.StrLenAsync(key); #endregion #region Key /// <summary> /// 用于在 key 存在时删除 key /// </summary> /// <param name="key">不含prefix前辍</param> /// <returns></returns> public static Task<long> DelAsync(params string[] key) => Instance.DelAsync(key); /// <summary> /// 序列化给定 key ,并返回被序列化的值 /// </summary> /// <param name="key">不含prefix前辍</param> /// <returns></returns> public static Task<byte[]> DumpAsync(string key) => Instance.DumpAsync(key); /// <summary> /// 检查给定 key 是否存在 /// </summary> /// <param name="key">不含prefix前辍</param> /// <returns></returns> public static Task<bool> ExistsAsync(string key) => Instance.ExistsAsync(key); /// <summary> /// [redis-server 3.0] 检查给定多个 key 是否存在 /// </summary> /// <param name="keys">不含prefix前辍</param> /// <returns></returns> public static Task<long> ExistsAsync(string[] keys) => Instance.ExistsAsync(keys); /// <summary> /// 为给定 key 设置过期时间 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="seconds">过期秒数</param> /// <returns></returns> public static Task<bool> ExpireAsync(string key, int seconds) => Instance.ExpireAsync(key, seconds); /// <summary> /// 为给定 key 设置过期时间 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="expire">过期时间</param> /// <returns></returns> public static Task<bool> ExpireAsync(string key, TimeSpan expire) => Instance.ExpireAsync(key, expire); /// <summary> /// 为给定 key 设置过期时间 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="expire">过期时间</param> /// <returns></returns> public static Task<bool> ExpireAtAsync(string key, DateTime expire) => Instance.ExpireAtAsync(key, expire); /// <summary> /// 查找所有分区节点中符合给定模式(pattern)的 key /// </summary> /// <param name="pattern">如:runoob*</param> /// <returns></returns> public static Task<string[]> KeysAsync(string pattern) => Instance.KeysAsync(pattern); /// <summary> /// 将当前数据库的 key 移动到给定的数据库 db 当中 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="database">数据库</param> /// <returns></returns> public static Task<bool> MoveAsync(string key, int database) => Instance.MoveAsync(key, database); /// <summary> /// 该返回给定 key 锁储存的值所使用的内部表示(representation) /// </summary> /// <param name="key">不含prefix前辍</param> /// <returns></returns> public static Task<string> ObjectEncodingAsync(string key) => Instance.ObjectEncodingAsync(key); /// <summary> /// 该返回给定 key 引用所储存的值的次数。此命令主要用于除错 /// </summary> /// <param name="key">不含prefix前辍</param> /// <returns></returns> public static Task<long?> ObjectRefCountAsync(string key) => Instance.ObjectRefCountAsync(key); /// <summary> /// 返回给定 key 自储存以来的空转时间(idle, 没有被读取也没有被写入),以秒为单位 /// </summary> /// <param name="key">不含prefix前辍</param> /// <returns></returns> public static Task<long?> ObjectIdleTimeAsync(string key) => Instance.ObjectIdleTimeAsync(key); /// <summary> /// 移除 key 的过期时间,key 将持久保持 /// </summary> /// <param name="key">不含prefix前辍</param> /// <returns></returns> public static Task<bool> PersistAsync(string key) => Instance.PersistAsync(key); /// <summary> /// 为给定 key 设置过期时间(毫秒) /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="milliseconds">过期毫秒数</param> /// <returns></returns> public static Task<bool> PExpireAsync(string key, int milliseconds) => Instance.PExpireAsync(key, milliseconds); /// <summary> /// 为给定 key 设置过期时间(毫秒) /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="expire">过期时间</param> /// <returns></returns> public static Task<bool> PExpireAsync(string key, TimeSpan expire) => Instance.PExpireAsync(key, expire); /// <summary> /// 为给定 key 设置过期时间(毫秒) /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="expire">过期时间</param> /// <returns></returns> public static Task<bool> PExpireAtAsync(string key, DateTime expire) => Instance.PExpireAtAsync(key, expire); /// <summary> /// 以毫秒为单位返回 key 的剩余的过期时间 /// </summary> /// <param name="key">不含prefix前辍</param> /// <returns></returns> public static Task<long> PTtlAsync(string key) => Instance.PTtlAsync(key); /// <summary> /// 从所有节点中随机返回一个 key /// </summary> /// <returns>返回的 key 如果包含 prefix前辍,则会去除后返回</returns> public static Task<string> RandomKeyAsync() => Instance.RandomKeyAsync(); /// <summary> /// 修改 key 的名称 /// </summary> /// <param name="key">旧名称,不含prefix前辍</param> /// <param name="newKey">新名称,不含prefix前辍</param> /// <returns></returns> public static Task<bool> RenameAsync(string key, string newKey) => Instance.RenameAsync(key, newKey); /// <summary> /// 修改 key 的名称 /// </summary> /// <param name="key">旧名称,不含prefix前辍</param> /// <param name="newKey">新名称,不含prefix前辍</param> /// <returns></returns> public static Task<bool> RenameNxAsync(string key, string newKey) => Instance.RenameNxAsync(key, newKey); /// <summary> /// 反序列化给定的序列化值,并将它和给定的 key 关联 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="serializedValue">序列化值</param> /// <returns></returns> public static Task<bool> RestoreAsync(string key, byte[] serializedValue) => Instance.RestoreAsync(key, serializedValue); /// <summary> /// 反序列化给定的序列化值,并将它和给定的 key 关联 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="ttlMilliseconds">毫秒为单位为 key 设置生存时间</param> /// <param name="serializedValue">序列化值</param> /// <returns></returns> public static Task<bool> RestoreAsync(string key, long ttlMilliseconds, byte[] serializedValue) => Instance.RestoreAsync(key, ttlMilliseconds, serializedValue); /// <summary> /// 返回给定列表、集合、有序集合 key 中经过排序的元素,参数资料:http://doc.redisfans.com/key/sort.html /// </summary> /// <param name="key">列表、集合、有序集合,不含prefix前辍</param> /// <param name="count">数量</param> /// <param name="offset">偏移量</param> /// <param name="by">排序字段</param> /// <param name="dir">排序方式</param> /// <param name="isAlpha">对字符串或数字进行排序</param> /// <param name="get">根据排序的结果来取出相应的键值</param> /// <returns></returns> public static Task<string[]> SortAsync(string key, long? count = null, long offset = 0, string by = null, RedisSortDir? dir = null, bool? isAlpha = null, params string[] get) => Instance.SortAsync(key, count, offset, by, dir, isAlpha, get); /// <summary> /// 保存给定列表、集合、有序集合 key 中经过排序的元素,参数资料:http://doc.redisfans.com/key/sort.html /// </summary> /// <param name="key">列表、集合、有序集合,不含prefix前辍</param> /// <param name="destination">目标key,不含prefix前辍</param> /// <param name="count">数量</param> /// <param name="offset">偏移量</param> /// <param name="by">排序字段</param> /// <param name="dir">排序方式</param> /// <param name="isAlpha">对字符串或数字进行排序</param> /// <param name="get">根据排序的结果来取出相应的键值</param> /// <returns></returns> public static Task<long> SortAndStoreAsync(string key, string destination, long? count = null, long offset = 0, string by = null, RedisSortDir? dir = null, bool? isAlpha = null, params string[] get) => Instance.SortAndStoreAsync(key, destination, count, offset, by, dir, isAlpha, get); /// <summary> /// 以秒为单位,返回给定 key 的剩余生存时间 /// </summary> /// <param name="key">不含prefix前辍</param> /// <returns></returns> public static Task<long> TtlAsync(string key) => Instance.TtlAsync(key); /// <summary> /// 返回 key 所储存的值的类型 /// </summary> /// <param name="key">不含prefix前辍</param> /// <returns></returns> public static Task<KeyType> TypeAsync(string key) => Instance.TypeAsync(key); /// <summary> /// 迭代当前数据库中的数据库键 /// </summary> /// <param name="cursor">位置</param> /// <param name="pattern">模式</param> /// <param name="count">数量</param> /// <returns></returns> public static Task<RedisScan<string>> ScanAsync(long cursor, string pattern = null, long? count = null) => Instance.ScanAsync(cursor, pattern, count); /// <summary> /// 迭代当前数据库中的数据库键 /// </summary> /// <typeparam name="T">byte[] 或其他类型</typeparam> /// <param name="cursor">位置</param> /// <param name="pattern">模式</param> /// <param name="count">数量</param> /// <returns></returns> public static Task<RedisScan<T>> ScanAsync<T>(long cursor, string pattern = null, long? count = null) => Instance.ScanAsync<T>(cursor, pattern, count); #endregion #region Geo redis-server 3.2 /// <summary> /// 将指定的地理空间位置(纬度、经度、成员)添加到指定的key中。这些数据将会存储到sorted set这样的目的是为了方便使用GEORADIUS或者GEORADIUSBYMEMBER命令对数据进行半径查询等操作。 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="longitude">经度</param> /// <param name="latitude">纬度</param> /// <param name="member">成员</param> /// <returns>是否成功</returns> public static Task<bool> GeoAddAsync(string key, decimal longitude, decimal latitude, object member) => Instance.GeoAddAsync(key, longitude, latitude, member); /// <summary> /// 将指定的地理空间位置(纬度、经度、成员)添加到指定的key中。这些数据将会存储到sorted set这样的目的是为了方便使用GEORADIUS或者GEORADIUSBYMEMBER命令对数据进行半径查询等操作。 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="values">批量添加的值</param> /// <returns>添加到sorted set元素的数目,但不包括已更新score的元素。</returns> public static Task<long> GeoAddAsync(string key, params (decimal longitude, decimal latitude, object member)[] values) => Instance.GeoAddAsync(key, values); /// <summary> /// 返回两个给定位置之间的距离。如果两个位置之间的其中一个不存在, 那么命令返回空值。GEODIST 命令在计算距离时会假设地球为完美的球形, 在极限情况下, 这一假设最大会造成 0.5% 的误差。 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="member1">成员1</param> /// <param name="member2">成员2</param> /// <param name="unit">m 表示单位为米;km 表示单位为千米;mi 表示单位为英里;ft 表示单位为英尺;</param> /// <returns>计算出的距离会以双精度浮点数的形式被返回。 如果给定的位置元素不存在, 那么命令返回空值。</returns> public static Task<decimal?> GeoDistAsync(string key, object member1, object member2, GeoUnit unit = GeoUnit.m) => Instance.GeoDistAsync(key, member1, member2, unit); /// <summary> /// 返回一个或多个位置元素的 Geohash 表示。通常使用表示位置的元素使用不同的技术,使用Geohash位置52点整数编码。由于编码和解码过程中所使用的初始最小和最大坐标不同,编码的编码也不同于标准。 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="members">多个查询的成员</param> /// <returns>一个数组, 数组的每个项都是一个 geohash 。 命令返回的 geohash 的位置与用户给定的位置元素的位置一一对应。</returns> public static Task<string[]> GeoHashAsync(string key, object[] members) => Instance.GeoHashAsync(key, members); /// <summary> /// 从key里返回所有给定位置元素的位置(经度和纬度)。 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="members">多个查询的成员</param> /// <returns>GEOPOS 命令返回一个数组, 数组中的每个项都由两个元素组成: 第一个元素为给定位置元素的经度, 而第二个元素则为给定位置元素的纬度。当给定的位置元素不存在时, 对应的数组项为空值。</returns> public static Task<(decimal longitude, decimal latitude)?[]> GeoPosAsync(string key, object[] members) => Instance.GeoPosAsync(key, members); /// <summary> /// 以给定的经纬度为中心, 返回键包含的位置元素当中, 与中心的距离不超过给定最大距离的所有位置元素。 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="longitude">经度</param> /// <param name="latitude">纬度</param> /// <param name="radius">距离</param> /// <param name="unit">m 表示单位为米;km 表示单位为千米;mi 表示单位为英里;ft 表示单位为英尺;</param> /// <param name="count">虽然用户可以使用 COUNT 选项去获取前 N 个匹配元素, 但是因为命令在内部可能会需要对所有被匹配的元素进行处理, 所以在对一个非常大的区域进行搜索时, 即使只使用 COUNT 选项去获取少量元素, 命令的执行速度也可能会非常慢。 但是从另一方面来说, 使用 COUNT 选项去减少需要返回的元素数量, 对于减少带宽来说仍然是非常有用的。</param> /// <param name="sorting">排序</param> /// <returns></returns> public static Task<string[]> GeoRadiusAsync(string key, decimal longitude, decimal latitude, decimal radius, GeoUnit unit = GeoUnit.m, long? count = null, GeoOrderBy? sorting = null) => Instance.GeoRadiusAsync(key, longitude, latitude, radius, unit, count, sorting); /// <summary> /// 以给定的经纬度为中心, 返回键包含的位置元素当中, 与中心的距离不超过给定最大距离的所有位置元素。 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="longitude">经度</param> /// <param name="latitude">纬度</param> /// <param name="radius">距离</param> /// <param name="unit">m 表示单位为米;km 表示单位为千米;mi 表示单位为英里;ft 表示单位为英尺;</param> /// <param name="count">虽然用户可以使用 COUNT 选项去获取前 N 个匹配元素, 但是因为命令在内部可能会需要对所有被匹配的元素进行处理, 所以在对一个非常大的区域进行搜索时, 即使只使用 COUNT 选项去获取少量元素, 命令的执行速度也可能会非常慢。 但是从另一方面来说, 使用 COUNT 选项去减少需要返回的元素数量, 对于减少带宽来说仍然是非常有用的。</param> /// <param name="sorting">排序</param> /// <returns></returns> public static Task<T[]> GeoRadiusAsync<T>(string key, decimal longitude, decimal latitude, decimal radius, GeoUnit unit = GeoUnit.m, long? count = null, GeoOrderBy? sorting = null) => Instance.GeoRadiusAsync<T>(key, longitude, latitude, radius, unit, count, sorting); /// <summary> /// 以给定的经纬度为中心, 返回键包含的位置元素当中, 与中心的距离不超过给定最大距离的所有位置元素(包含距离)。 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="longitude">经度</param> /// <param name="latitude">纬度</param> /// <param name="radius">距离</param> /// <param name="unit">m 表示单位为米;km 表示单位为千米;mi 表示单位为英里;ft 表示单位为英尺;</param> /// <param name="count">虽然用户可以使用 COUNT 选项去获取前 N 个匹配元素, 但是因为命令在内部可能会需要对所有被匹配的元素进行处理, 所以在对一个非常大的区域进行搜索时, 即使只使用 COUNT 选项去获取少量元素, 命令的执行速度也可能会非常慢。 但是从另一方面来说, 使用 COUNT 选项去减少需要返回的元素数量, 对于减少带宽来说仍然是非常有用的。</param> /// <param name="sorting">排序</param> /// <returns></returns> public static Task<(string member, decimal dist)[]> GeoRadiusWithDistAsync(string key, decimal longitude, decimal latitude, decimal radius, GeoUnit unit = GeoUnit.m, long? count = null, GeoOrderBy? sorting = null) => Instance.GeoRadiusWithDistAsync(key, longitude, latitude, radius, unit, count, sorting); /// <summary> /// 以给定的经纬度为中心, 返回键包含的位置元素当中, 与中心的距离不超过给定最大距离的所有位置元素(包含距离)。 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="longitude">经度</param> /// <param name="latitude">纬度</param> /// <param name="radius">距离</param> /// <param name="unit">m 表示单位为米;km 表示单位为千米;mi 表示单位为英里;ft 表示单位为英尺;</param> /// <param name="count">虽然用户可以使用 COUNT 选项去获取前 N 个匹配元素, 但是因为命令在内部可能会需要对所有被匹配的元素进行处理, 所以在对一个非常大的区域进行搜索时, 即使只使用 COUNT 选项去获取少量元素, 命令的执行速度也可能会非常慢。 但是从另一方面来说, 使用 COUNT 选项去减少需要返回的元素数量, 对于减少带宽来说仍然是非常有用的。</param> /// <param name="sorting">排序</param> /// <returns></returns> public static Task<(T member, decimal dist)[]> GeoRadiusWithDistAsync<T>(string key, decimal longitude, decimal latitude, decimal radius, GeoUnit unit = GeoUnit.m, long? count = null, GeoOrderBy? sorting = null) => Instance.GeoRadiusWithDistAsync<T>(key, longitude, latitude, radius, unit, count, sorting); ///// <summary> ///// 以给定的经纬度为中心, 返回键包含的位置元素当中, 与中心的距离不超过给定最大距离的所有位置元素(包含经度、纬度)。 ///// </summary> ///// <param name="key">不含prefix前辍</param> ///// <param name="longitude">经度</param> ///// <param name="latitude">纬度</param> ///// <param name="radius">距离</param> ///// <param name="unit">m 表示单位为米;km 表示单位为千米;mi 表示单位为英里;ft 表示单位为英尺;</param> ///// <param name="count">虽然用户可以使用 COUNT 选项去获取前 N 个匹配元素, 但是因为命令在内部可能会需要对所有被匹配的元素进行处理, 所以在对一个非常大的区域进行搜索时, 即使只使用 COUNT 选项去获取少量元素, 命令的执行速度也可能会非常慢。 但是从另一方面来说, 使用 COUNT 选项去减少需要返回的元素数量, 对于减少带宽来说仍然是非常有用的。</param> ///// <param name="sorting">排序</param> ///// <returns></returns> //private static Task<(string member, decimal longitude, decimal latitude)[]> GeoRadiusWithCoordAsync(string key, decimal longitude, decimal latitude, decimal radius, GeoUnit unit = GeoUnit.m, long? count = null, GeoOrderBy? sorting = null) => // Instance.GeoRadiusWithCoordAsync(key, longitude, latitude, radius, unit, count, sorting); ///// <summary> ///// 以给定的经纬度为中心, 返回键包含的位置元素当中, 与中心的距离不超过给定最大距离的所有位置元素(包含经度、纬度)。 ///// </summary> ///// <param name="key">不含prefix前辍</param> ///// <param name="longitude">经度</param> ///// <param name="latitude">纬度</param> ///// <param name="radius">距离</param> ///// <param name="unit">m 表示单位为米;km 表示单位为千米;mi 表示单位为英里;ft 表示单位为英尺;</param> ///// <param name="count">虽然用户可以使用 COUNT 选项去获取前 N 个匹配元素, 但是因为命令在内部可能会需要对所有被匹配的元素进行处理, 所以在对一个非常大的区域进行搜索时, 即使只使用 COUNT 选项去获取少量元素, 命令的执行速度也可能会非常慢。 但是从另一方面来说, 使用 COUNT 选项去减少需要返回的元素数量, 对于减少带宽来说仍然是非常有用的。</param> ///// <param name="sorting">排序</param> ///// <returns></returns> //private static Task<(T member, decimal longitude, decimal latitude)[]> GeoRadiusWithCoordAsync<T>(string key, decimal longitude, decimal latitude, decimal radius, GeoUnit unit = GeoUnit.m, long? count = null, GeoOrderBy? sorting = null) => // Instance.GeoRadiusWithCoordAsync<T>(key, longitude, latitude, radius, unit, count, sorting); /// <summary> /// 以给定的经纬度为中心, 返回键包含的位置元素当中, 与中心的距离不超过给定最大距离的所有位置元素(包含距离、经度、纬度)。 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="longitude">经度</param> /// <param name="latitude">纬度</param> /// <param name="radius">距离</param> /// <param name="unit">m 表示单位为米;km 表示单位为千米;mi 表示单位为英里;ft 表示单位为英尺;</param> /// <param name="count">虽然用户可以使用 COUNT 选项去获取前 N 个匹配元素, 但是因为命令在内部可能会需要对所有被匹配的元素进行处理, 所以在对一个非常大的区域进行搜索时, 即使只使用 COUNT 选项去获取少量元素, 命令的执行速度也可能会非常慢。 但是从另一方面来说, 使用 COUNT 选项去减少需要返回的元素数量, 对于减少带宽来说仍然是非常有用的。</param> /// <param name="sorting">排序</param> /// <returns></returns> public static Task<(string member, decimal dist, decimal longitude, decimal latitude)[]> GeoRadiusWithDistAndCoordAsync(string key, decimal longitude, decimal latitude, decimal radius, GeoUnit unit = GeoUnit.m, long? count = null, GeoOrderBy? sorting = null) => Instance.GeoRadiusWithDistAndCoordAsync(key, longitude, latitude, radius, unit, count, sorting); /// <summary> /// 以给定的经纬度为中心, 返回键包含的位置元素当中, 与中心的距离不超过给定最大距离的所有位置元素(包含距离、经度、纬度)。 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="longitude">经度</param> /// <param name="latitude">纬度</param> /// <param name="radius">距离</param> /// <param name="unit">m 表示单位为米;km 表示单位为千米;mi 表示单位为英里;ft 表示单位为英尺;</param> /// <param name="count">虽然用户可以使用 COUNT 选项去获取前 N 个匹配元素, 但是因为命令在内部可能会需要对所有被匹配的元素进行处理, 所以在对一个非常大的区域进行搜索时, 即使只使用 COUNT 选项去获取少量元素, 命令的执行速度也可能会非常慢。 但是从另一方面来说, 使用 COUNT 选项去减少需要返回的元素数量, 对于减少带宽来说仍然是非常有用的。</param> /// <param name="sorting">排序</param> /// <returns></returns> public static Task<(T member, decimal dist, decimal longitude, decimal latitude)[]> GeoRadiusWithDistAndCoordAsync<T>(string key, decimal longitude, decimal latitude, decimal radius, GeoUnit unit = GeoUnit.m, long? count = null, GeoOrderBy? sorting = null) => Instance.GeoRadiusWithDistAndCoordAsync<T>(key, longitude, latitude, radius, unit, count, sorting); /// <summary> /// 以给定的成员为中心, 返回键包含的位置元素当中, 与中心的距离不超过给定最大距离的所有位置元素。 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="member">成员</param> /// <param name="radius">距离</param> /// <param name="unit">m 表示单位为米;km 表示单位为千米;mi 表示单位为英里;ft 表示单位为英尺;</param> /// <param name="count">虽然用户可以使用 COUNT 选项去获取前 N 个匹配元素, 但是因为命令在内部可能会需要对所有被匹配的元素进行处理, 所以在对一个非常大的区域进行搜索时, 即使只使用 COUNT 选项去获取少量元素, 命令的执行速度也可能会非常慢。 但是从另一方面来说, 使用 COUNT 选项去减少需要返回的元素数量, 对于减少带宽来说仍然是非常有用的。</param> /// <param name="sorting">排序</param> /// <returns></returns> public static Task<string[]> GeoRadiusByMemberAsync(string key, object member, decimal radius, GeoUnit unit = GeoUnit.m, long? count = null, GeoOrderBy? sorting = null) => Instance.GeoRadiusByMemberAsync(key, member, radius, unit, count, sorting); /// <summary> /// 以给定的成员为中心, 返回键包含的位置元素当中, 与中心的距离不超过给定最大距离的所有位置元素。 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="member">成员</param> /// <param name="radius">距离</param> /// <param name="unit">m 表示单位为米;km 表示单位为千米;mi 表示单位为英里;ft 表示单位为英尺;</param> /// <param name="count">虽然用户可以使用 COUNT 选项去获取前 N 个匹配元素, 但是因为命令在内部可能会需要对所有被匹配的元素进行处理, 所以在对一个非常大的区域进行搜索时, 即使只使用 COUNT 选项去获取少量元素, 命令的执行速度也可能会非常慢。 但是从另一方面来说, 使用 COUNT 选项去减少需要返回的元素数量, 对于减少带宽来说仍然是非常有用的。</param> /// <param name="sorting">排序</param> /// <returns></returns> public static Task<T[]> GeoRadiusByMemberAsync<T>(string key, object member, decimal radius, GeoUnit unit = GeoUnit.m, long? count = null, GeoOrderBy? sorting = null) => Instance.GeoRadiusByMemberAsync<T>(key, member, radius, unit, count, sorting); /// <summary> /// 以给定的成员为中心, 返回键包含的位置元素当中, 与中心的距离不超过给定最大距离的所有位置元素(包含距离)。 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="member">成员</param> /// <param name="radius">距离</param> /// <param name="unit">m 表示单位为米;km 表示单位为千米;mi 表示单位为英里;ft 表示单位为英尺;</param> /// <param name="count">虽然用户可以使用 COUNT 选项去获取前 N 个匹配元素, 但是因为命令在内部可能会需要对所有被匹配的元素进行处理, 所以在对一个非常大的区域进行搜索时, 即使只使用 COUNT 选项去获取少量元素, 命令的执行速度也可能会非常慢。 但是从另一方面来说, 使用 COUNT 选项去减少需要返回的元素数量, 对于减少带宽来说仍然是非常有用的。</param> /// <param name="sorting">排序</param> /// <returns></returns> public static Task<(string member, decimal dist)[]> GeoRadiusByMemberWithDistAsync(string key, object member, decimal radius, GeoUnit unit = GeoUnit.m, long? count = null, GeoOrderBy? sorting = null) => Instance.GeoRadiusByMemberWithDistAsync(key, member, radius, unit, count, sorting); /// <summary> /// 以给定的成员为中心, 返回键包含的位置元素当中, 与中心的距离不超过给定最大距离的所有位置元素(包含距离)。 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="member">成员</param> /// <param name="radius">距离</param> /// <param name="unit">m 表示单位为米;km 表示单位为千米;mi 表示单位为英里;ft 表示单位为英尺;</param> /// <param name="count">虽然用户可以使用 COUNT 选项去获取前 N 个匹配元素, 但是因为命令在内部可能会需要对所有被匹配的元素进行处理, 所以在对一个非常大的区域进行搜索时, 即使只使用 COUNT 选项去获取少量元素, 命令的执行速度也可能会非常慢。 但是从另一方面来说, 使用 COUNT 选项去减少需要返回的元素数量, 对于减少带宽来说仍然是非常有用的。</param> /// <param name="sorting">排序</param> /// <returns></returns> public static Task<(T member, decimal dist)[]> GeoRadiusByMemberWithDistAsync<T>(string key, object member, decimal radius, GeoUnit unit = GeoUnit.m, long? count = null, GeoOrderBy? sorting = null) => Instance.GeoRadiusByMemberWithDistAsync<T>(key, member, radius, unit, count, sorting); ///// <summary> ///// 以给定的成员为中心, 返回键包含的位置元素当中, 与中心的距离不超过给定最大距离的所有位置元素(包含经度、纬度)。 ///// </summary> ///// <param name="key">不含prefix前辍</param> ///// <param name="member">成员</param> ///// <param name="radius">距离</param> ///// <param name="unit">m 表示单位为米;km 表示单位为千米;mi 表示单位为英里;ft 表示单位为英尺;</param> ///// <param name="count">虽然用户可以使用 COUNT 选项去获取前 N 个匹配元素, 但是因为命令在内部可能会需要对所有被匹配的元素进行处理, 所以在对一个非常大的区域进行搜索时, 即使只使用 COUNT 选项去获取少量元素, 命令的执行速度也可能会非常慢。 但是从另一方面来说, 使用 COUNT 选项去减少需要返回的元素数量, 对于减少带宽来说仍然是非常有用的。</param> ///// <param name="sorting">排序</param> ///// <returns></returns> //private static Task<(string member, decimal longitude, decimal latitude)[]> GeoRadiusByMemberWithCoordAsync(string key, object member, decimal radius, GeoUnit unit = GeoUnit.m, long? count = null, GeoOrderBy? sorting = null) => // Instance.GeoRadiusByMemberWithCoordAsync(key, member, radius, unit, count, sorting); ///// <summary> ///// 以给定的成员为中心, 返回键包含的位置元素当中, 与中心的距离不超过给定最大距离的所有位置元素(包含经度、纬度)。 ///// </summary> ///// <param name="key">不含prefix前辍</param> ///// <param name="member">成员</param> ///// <param name="radius">距离</param> ///// <param name="unit">m 表示单位为米;km 表示单位为千米;mi 表示单位为英里;ft 表示单位为英尺;</param> ///// <param name="count">虽然用户可以使用 COUNT 选项去获取前 N 个匹配元素, 但是因为命令在内部可能会需要对所有被匹配的元素进行处理, 所以在对一个非常大的区域进行搜索时, 即使只使用 COUNT 选项去获取少量元素, 命令的执行速度也可能会非常慢。 但是从另一方面来说, 使用 COUNT 选项去减少需要返回的元素数量, 对于减少带宽来说仍然是非常有用的。</param> ///// <param name="sorting">排序</param> ///// <returns></returns> //private static Task<(T member, decimal longitude, decimal latitude)[]> GeoRadiusByMemberWithCoordAsync<T>(string key, object member, decimal radius, GeoUnit unit = GeoUnit.m, long? count = null, GeoOrderBy? sorting = null) => // Instance.GeoRadiusByMemberWithCoordAsync<T>(key, member, radius, unit, count, sorting); /// <summary> /// 以给定的成员为中心, 返回键包含的位置元素当中, 与中心的距离不超过给定最大距离的所有位置元素(包含距离、经度、纬度)。 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="member">成员</param> /// <param name="radius">距离</param> /// <param name="unit">m 表示单位为米;km 表示单位为千米;mi 表示单位为英里;ft 表示单位为英尺;</param> /// <param name="count">虽然用户可以使用 COUNT 选项去获取前 N 个匹配元素, 但是因为命令在内部可能会需要对所有被匹配的元素进行处理, 所以在对一个非常大的区域进行搜索时, 即使只使用 COUNT 选项去获取少量元素, 命令的执行速度也可能会非常慢。 但是从另一方面来说, 使用 COUNT 选项去减少需要返回的元素数量, 对于减少带宽来说仍然是非常有用的。</param> /// <param name="sorting">排序</param> /// <returns></returns> public static Task<(string member, decimal dist, decimal longitude, decimal latitude)[]> GeoRadiusByMemberWithDistAndCoordAsync(string key, object member, decimal radius, GeoUnit unit = GeoUnit.m, long? count = null, GeoOrderBy? sorting = null) => Instance.GeoRadiusByMemberWithDistAndCoordAsync(key, member, radius, unit, count, sorting); /// <summary> /// 以给定的成员为中心, 返回键包含的位置元素当中, 与中心的距离不超过给定最大距离的所有位置元素(包含距离、经度、纬度)。 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="member">成员</param> /// <param name="radius">距离</param> /// <param name="unit">m 表示单位为米;km 表示单位为千米;mi 表示单位为英里;ft 表示单位为英尺;</param> /// <param name="count">虽然用户可以使用 COUNT 选项去获取前 N 个匹配元素, 但是因为命令在内部可能会需要对所有被匹配的元素进行处理, 所以在对一个非常大的区域进行搜索时, 即使只使用 COUNT 选项去获取少量元素, 命令的执行速度也可能会非常慢。 但是从另一方面来说, 使用 COUNT 选项去减少需要返回的元素数量, 对于减少带宽来说仍然是非常有用的。</param> /// <param name="sorting">排序</param> /// <returns></returns> public static Task<(T member, decimal dist, decimal longitude, decimal latitude)[]> GeoRadiusByMemberWithDistAndCoordAsync<T>(string key, object member, decimal radius, GeoUnit unit = GeoUnit.m, long? count = null, GeoOrderBy? sorting = null) => Instance.GeoRadiusByMemberWithDistAndCoordAsync<T>(key, member, radius, unit, count, sorting); #endregion } #endif
2877025939/PlanADScrollView
7,546
PlanADScrollView/PlanADScrollView/PlanADScrollView/PlanADScrollView.m
// // PlanADScrollView.m // PlanADScrollView // // Created by anan on 2017/10/18. // Copyright © 2017年 Plan. All rights reserved. // #import "PlanADScrollView.h" #import "PlanADCollectionViewCell.h" #import "PlanPageControl.h" #define PlanSections 100 @interface PlanADScrollView()<UICollectionViewDataSource, UICollectionViewDelegate> /** 图片地址数组 */ @property (nonatomic,copy) NSArray *imageUrls; @property (nonatomic,strong) UICollectionView *collectionView; @property (nonatomic,strong) PlanPageControl *pageControl; @property (nonatomic,strong) NSTimer *timer; @property (nonatomic,strong) UIImage *placeholderimage; @end @implementation PlanADScrollView /** imageUrls 网络请求的图片url placeholderimage 占位图片 */ - (instancetype)initWithFrame:(CGRect)frame imageUrls:(NSArray *)imageUrls placeholderimage:(UIImage*)placeholderimage { self = [super initWithFrame:frame]; if (self) { [self creatrUIImageUrls:imageUrls placeholderimage:placeholderimage]; } return self; } - (void)creatrUIImageUrls:(NSArray *)imageUrls placeholderimage:(UIImage*)placeholderimage { [self addSubview:self.collectionView]; [self addSubview:self.pageControl]; [self addTimer]; self.imageUrls = imageUrls; [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:PlanSections/2] atScrollPosition:UICollectionViewScrollPositionLeft animated:YES]; self.pageControl.numberOfPages = imageUrls.count; self.placeholderimage =placeholderimage; } #pragma mark 添加定时器 -(void)addTimer{ NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(nextpage) userInfo:nil repeats:YES]; [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes]; self.timer = timer ; } #pragma mark 删除定时器 -(void)removeTimer{ [self.timer invalidate]; self.timer = nil; } -(void)nextpage{ NSIndexPath *currentIndexPath = [[self.collectionView indexPathsForVisibleItems] lastObject]; NSIndexPath *currentIndexPathReset = [NSIndexPath indexPathForItem:currentIndexPath.item inSection:100/2]; [self.collectionView scrollToItemAtIndexPath:currentIndexPathReset atScrollPosition:UICollectionViewScrollPositionLeft animated:NO]; NSInteger nextItem = currentIndexPathReset.item +1; NSInteger nextSection = currentIndexPathReset.section; if (nextItem==self.imageUrls.count) { nextItem=0; nextSection++; } NSIndexPath *nextIndexPath = [NSIndexPath indexPathForItem:nextItem inSection:nextSection]; [self.collectionView scrollToItemAtIndexPath:nextIndexPath atScrollPosition:UICollectionViewScrollPositionLeft animated:YES]; } #pragma mark - UICollectionViewDataSource -(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{ return PlanSections; } - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{ return self.imageUrls.count; } - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{ PlanADCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"PlanADCell" forIndexPath:indexPath]; [cell imageStr:self.imageUrls[indexPath.row] placeholderimage:self.placeholderimage]; return cell; } - (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{ if([self.delegate respondsToSelector:@selector(PlanADScrollViewdidSelectAtIndex:)]){ [self.delegate PlanADScrollViewdidSelectAtIndex:indexPath.row]; } } -(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{ [self removeTimer]; } #pragma mark 当用户停止的时候调用 -(void) scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{ [self addTimer]; } #pragma mark 设置页码 -(void)scrollViewDidScroll:(UIScrollView *)scrollView{ int page = (int) (scrollView.contentOffset.x/scrollView.frame.size.width+0.5)%self.imageUrls.count; self.pageControl.currentPage =page; } -(NSString *)controllerTitle{ return @"无限轮播"; } #pragma mark -绘图 //绘制长方形 -(UIImage *)createImageColor:(UIColor *)color size:(CGSize)size { //开启图形上下文 UIGraphicsBeginImageContextWithOptions(size, NO, 0); //绘制颜色区域 UIBezierPath *path = [UIBezierPath bezierPathWithRect:CGRectMake(0, 0, size.width, size.height)]; [color setFill]; [path fill]; //从图形上下文获取图片 UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); //关闭图形上下文 UIGraphicsEndImageContext(); return newImage; } #pragma mark - 设置选择图片和 默认图片 -(void)currentImage:(UIImage *)currentImage pageImage:(UIImage*)pageImage{ self.pageControl.currentImage = currentImage; self.pageControl.pageImage = pageImage; } #pragma mark - set方法 -(void)setPageContolStyle:(PlanPageContolStyle)pageContolStyle{ _pageContolStyle =pageContolStyle; if (pageContolStyle == PlanPageContolStyleNone) { self.pageControl.pointSize = CGSizeMake(8, 8); }else if (pageContolStyle == PlanPageContolStyleRectangle){ self.pageControl.pointSize = CGSizeMake(10, 4); self.pageControl.currentImage =[self createImageColor:[UIColor whiteColor] size:CGSizeMake(10, 5)]; self.pageControl.pageImage =[self createImageColor:[UIColor blueColor] size:CGSizeMake(10, 5)]; }else if(pageContolStyle == PlanPageContolStyleImage){ self.pageControl.pointSize = CGSizeMake(8, 8); self.pageControl.currentImage =[UIImage imageNamed:@"check"]; self.pageControl.pageImage =[UIImage imageNamed:@"check1"]; } } #pragma mark - 懒加载 -(UICollectionView *)collectionView{ if (!_collectionView ) { UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init]; flowLayout.minimumLineSpacing = 0; flowLayout.minimumInteritemSpacing = 0; flowLayout.itemSize = CGSizeMake(self.frame.size.width,self.frame.size.height); flowLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0); flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal; _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height) collectionViewLayout:flowLayout]; _collectionView.backgroundColor = [UIColor yellowColor]; _collectionView.dataSource = self; _collectionView.delegate = self; _collectionView.showsHorizontalScrollIndicator = NO; _collectionView.pagingEnabled = YES; [_collectionView registerClass:[PlanADCollectionViewCell class] forCellWithReuseIdentifier:@"PlanADCell"]; } return _collectionView; } -(UIPageControl *)pageControl{ if (!_pageControl) { _pageControl = [[PlanPageControl alloc] initWithFrame:CGRectMake(self.frame.size.width*0.5, self.frame.size.height-30, self.frame.size.width*0.5, 20)]; // _pageControl.center = CGPointMake(self.frame.size.width*0.5, self.frame.size.height-10); // _pageControl.bounds = CGRectMake(0, 0, 100, 40); _pageControl.pageIndicatorTintColor = [UIColor blueColor]; _pageControl.currentPageIndicatorTintColor = [UIColor whiteColor]; _pageControl.enabled = NO; _pageControl.pointSize = CGSizeMake(8, 8); } return _pageControl; } @end
2877025939/PlanADScrollView
1,567
PlanADScrollView/PlanADScrollView/PlanADScrollView/PlanPageControl.m
// // PlanPageControl.m // PlanADScrollView // // Created by anan on 2017/10/19. // Copyright © 2017年 Plan. All rights reserved. // #import "PlanPageControl.h" @interface PlanPageControl() @end @implementation PlanPageControl - (instancetype)init { self = [super init]; if (self) { } return self; } //从写setCurrentPage方法,可以修改 点的间距 和 点的图片 -(void)setCurrentPage:(NSInteger)page{ //NSLog(@"setCurrentPage"); [super setCurrentPage:page]; for (int i=0; i<[self.subviews count]; i++) { UIView* point = [self.subviews objectAtIndex:i]; [point setFrame:CGRectMake(point.frame.origin.x, point.frame.origin.y, self.pointSize.width, self.pointSize.height)]; if ([point.subviews count] == 0) { UIImageView * view = [[UIImageView alloc]initWithFrame:point.bounds]; [point addSubview:view]; }; UIImageView * view = point.subviews[0]; if (i==self.currentPage) { if (self.currentImage) { view.image=self.currentImage; point.backgroundColor = [UIColor clearColor]; }else { view.image = nil; point.backgroundColor = self.currentPageIndicatorTintColor; } }else if (self.pageImage) { view.image=self.pageImage; point.backgroundColor = [UIColor clearColor]; }else { view.image = nil; point.backgroundColor = self.pageIndicatorTintColor; } } } @end
27182812/ChatGLM-LLaMA-chinese-insturct
3,158
src/transformers/models/m2m_100/convert_m2m100_original_checkpoint_to_pytorch.py
# Copyright 2021 The Fairseq Authors 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. import argparse import torch from torch import nn from transformers import M2M100Config, M2M100ForConditionalGeneration def remove_ignore_keys_(state_dict): ignore_keys = [ "encoder.version", "decoder.version", "model.encoder.version", "model.decoder.version", "decoder.output_projection.weight", "_float_tensor", "encoder.embed_positions._float_tensor", "decoder.embed_positions._float_tensor", ] for k in ignore_keys: state_dict.pop(k, None) def make_linear_from_emb(emb): vocab_size, emb_size = emb.weight.shape lin_layer = nn.Linear(vocab_size, emb_size, bias=False) lin_layer.weight.data = emb.weight.data return lin_layer def convert_fairseq_m2m100_checkpoint_from_disk(checkpoint_path): m2m_100 = torch.load(checkpoint_path, map_location="cpu") args = m2m_100["args"] or m2m_100["cfg"]["model"] state_dict = m2m_100["model"] remove_ignore_keys_(state_dict) vocab_size = state_dict["encoder.embed_tokens.weight"].shape[0] config = M2M100Config( vocab_size=vocab_size, max_position_embeddings=1024, encoder_layers=args.encoder_layers, decoder_layers=args.decoder_layers, encoder_attention_heads=args.encoder_attention_heads, decoder_attention_heads=args.decoder_attention_heads, encoder_ffn_dim=args.encoder_ffn_embed_dim, decoder_ffn_dim=args.decoder_ffn_embed_dim, d_model=args.encoder_embed_dim, encoder_layerdrop=args.encoder_layerdrop, decoder_layerdrop=args.decoder_layerdrop, dropout=args.dropout, attention_dropout=args.attention_dropout, activation_dropout=args.activation_dropout, activation_function="relu", ) state_dict["shared.weight"] = state_dict["decoder.embed_tokens.weight"] model = M2M100ForConditionalGeneration(config) model.model.load_state_dict(state_dict, strict=False) model.lm_head = make_linear_from_emb(model.model.shared) return model if __name__ == "__main__": parser = argparse.ArgumentParser() # Required parameters parser.add_argument("fairseq_path", type=str, help="path to a model.pt on local filesystem.") parser.add_argument("pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.") args = parser.parse_args() model = convert_fairseq_m2m100_checkpoint_from_disk(args.fairseq_pathß) model.save_pretrained(args.pytorch_dump_folder_path)
2881099/csredis
150,754
src/CSRedisCore/CSRedisClientAsync.cs
using CSRedis.Internal.ObjectPool; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Threading; using System.Threading.Tasks; #if net40 #else namespace CSRedis { public partial class CSRedisClient { ConcurrentDictionary<string, AutoPipe> _autoPipe = new ConcurrentDictionary<string, AutoPipe>(); class AutoPipe { public Object<RedisClient> Client; public long GetTimes; public long TimesZore; public bool IsSingleEndPipe; public Exception ReturnException; } async Task<AutoPipe> GetClientAsync(RedisClientPool pool) { if (pool._policy._asyncPipeline == false) return new AutoPipe { Client = await pool.GetAsync(), GetTimes = 1, TimesZore = 0, IsSingleEndPipe = false }; if (_autoPipe.TryGetValue(pool.Key, out var ap) && ap.IsSingleEndPipe == false) { if (pool.UnavailableException != null) throw new Exception($"【{pool._policy.Name}】状态不可用,等待后台检查程序恢复方可使用。{pool.UnavailableException?.Message}", pool.UnavailableException); Interlocked.Increment(ref ap.GetTimes); return ap; } ap = new AutoPipe { Client = await pool.GetAsync(), GetTimes = 1, TimesZore = 0, IsSingleEndPipe = false }; if (_autoPipe.TryAdd(pool.Key, ap)) { ap.Client.Value._asyncPipe = new ConcurrentQueue<TaskCompletionSource<object>>(); new Thread(() => { var rc = ap.Client.Value; void trySetException(Exception ex) { pool.SetUnavailable(ex, ap.Client.LastGetTimeCopy); while (rc._asyncPipe?.IsEmpty == false) { TaskCompletionSource<object> trytsc = null; if (rc._asyncPipe?.TryDequeue(out trytsc) == true) trytsc.TrySetException(ex); } rc._asyncPipe = null; pool.Return(ap.Client); _autoPipe.TryRemove(pool.Key, out var oldap); } while (true) { Thread.CurrentThread.Join(1); if (rc._asyncPipe?.IsEmpty == false) { try { var ret = rc.EndPipe(); if (ret.Length == 1) ap.IsSingleEndPipe = true; else if (ret.Length > 1) ap.IsSingleEndPipe = false; foreach (var rv in ret) { TaskCompletionSource<object> trytsc = null; if (rc._asyncPipe?.TryDequeue(out trytsc) == true) trytsc.TrySetResult(rv); } } catch (Exception ex) { trySetException(ex); return; } continue; } if (ap.ReturnException != null) { trySetException(ap.ReturnException); return; } var tmpTimes = Interlocked.Increment(ref ap.TimesZore); if (tmpTimes >= 10) ap.IsSingleEndPipe = false; if (tmpTimes >= 1000) { rc._asyncPipe = null; pool.Return(ap.Client, ap.ReturnException); _autoPipe.TryRemove(pool.Key, out var oldap); break; } } }).Start(); } return ap; } void ReturnClient(AutoPipe ap, Object<RedisClient> obj, RedisClientPool pool, Exception ex) { if (ap == null) return; var times = Interlocked.Decrement(ref ap.GetTimes); if (times <= 0) Interlocked.Exchange(ref ap.TimesZore, 0); ap.ReturnException = ex; if (_autoPipe.TryGetValue(pool.Key, out var dicap) == false || dicap != ap) pool.Return(ap.Client, ap.ReturnException); } async Task<T> GetAndExecuteAsync<T>(RedisClientPool pool, Func<Object<RedisClient>, Task<T>> handerAsync, int jump = 100, int errtimes = 0) { AutoPipe ap = null; Object<RedisClient> obj = null; Exception ex = null; var redirect = ParseClusterRedirect(null); try { ap = await GetClientAsync(pool); obj = ap.Client; while (true) { //因网络出错重试,默认1次 try { var ret = await handerAsync(obj); return ret; } catch (RedisException ex3) { redirect = ParseClusterRedirect(ex3); //官方集群跳转 if (redirect == null || jump <= 0) { ex = ex3; if (SentinelManager != null && ex.Message.Contains("READONLY")) { //哨兵轮询 if (pool.SetUnavailable(ex, obj.LastGetTimeCopy) == true) BackgroundGetSentinelMasterValue(); } throw ex; } break; } catch (Exception ex2) { ex = ex2; if (pool.UnavailableException != null) throw ex; var isPong = false; try { await obj.Value.PingAsync(); isPong = true; } catch { obj.ResetValue(); } if (isPong == false || ++errtimes > pool._policy._tryit) { if (SentinelManager != null) { //哨兵轮询 if (pool.SetUnavailable(ex, obj.LastGetTimeCopy) == true) BackgroundGetSentinelMasterValue(); throw new Exception($"Redis Sentinel Master is switching:{ex.Message}"); } throw ex; //重试次数完成 } else { ex = null; Trace.WriteLine($"csredis tryit ({errtimes}) ..."); } } } } finally { ReturnClient(ap, obj, pool, ex); //pool.Return(obj, ex); } if (redirect == null) return await GetAndExecuteAsync<T>(pool, handerAsync, jump - 1, errtimes); var redirectHanderAsync = redirect.Value.isMoved ? handerAsync : async redirectObj => { await redirectObj.Value.CallAsync("ASKING"); return await handerAsync(redirectObj); }; return await GetAndExecuteAsync<T>(GetRedirectPool(redirect.Value, pool), redirectHanderAsync, jump - 1); } async Task<T> NodesNotSupportAsync<T>(string[] keys, T defaultValue, Func<Object<RedisClient>, string[], Task<T>> callbackAsync) { if (keys == null || keys.Any() == false) return defaultValue; var rules = Nodes.Count > 1 ? keys.Select(a => NodeRuleRaw(a)).Distinct() : new[] { Nodes.FirstOrDefault().Key }; if (rules.Count() > 1) throw new Exception("由于开启了分区模式,keys 分散在多个节点,无法使用此功能"); var pool = Nodes.TryGetValue(rules.First(), out var b) ? b : Nodes.First().Value; string[] rkeys = new string[keys.Length]; for (int a = 0; a < keys.Length; a++) rkeys[a] = string.Concat(pool.Prefix, keys[a]); if (rkeys.Length == 0) return defaultValue; return await GetAndExecuteAsync(pool, conn => callbackAsync(conn, rkeys)); } Task<T> NodesNotSupportAsync<T>(string key, Func<Object<RedisClient>, string, Task<T>> callback) { if (IsMultiNode) throw new Exception("由于开启了分区模式,无法使用此功能"); return ExecuteScalarAsync<T>(key, callback); } #region 缓存壳 /// <summary> /// 缓存壳 /// </summary> /// <typeparam name="T">缓存类型</typeparam> /// <param name="key">不含prefix前辍</param> /// <param name="timeoutSeconds">缓存秒数</param> /// <param name="getDataAsync">获取源数据的函数</param> /// <returns></returns> async public Task<T> CacheShellAsync<T>(string key, int timeoutSeconds, Func<Task<T>> getDataAsync) { if (timeoutSeconds == 0) return await getDataAsync(); var cacheValue = await GetAsync(key); if (cacheValue != null) { try { return this.DeserializeObject<T>(cacheValue); } catch { await DelAsync(key); throw; } } var ret = await getDataAsync(); await SetAsync(key, this.SerializeObject(ret), timeoutSeconds); return ret; } /// <summary> /// 缓存壳(哈希表) /// </summary> /// <typeparam name="T">缓存类型</typeparam> /// <param name="key">不含prefix前辍</param> /// <param name="field">字段</param> /// <param name="timeoutSeconds">缓存秒数</param> /// <param name="getDataAsync">获取源数据的函数</param> /// <returns></returns> async public Task<T> CacheShellAsync<T>(string key, string field, int timeoutSeconds, Func<Task<T>> getDataAsync) { if (timeoutSeconds == 0) return await getDataAsync(); var cacheValue = await HGetAsync(key, field); if (cacheValue != null) { try { var value = this.DeserializeObject<(T, long)>(cacheValue); if (DateTime.Now.Subtract(_dt1970.AddSeconds(value.Item2)).TotalSeconds <= timeoutSeconds) return value.Item1; } catch { await HDelAsync(key, field); throw; } } var ret = await getDataAsync(); await HSetAsync(key, field, this.SerializeObject((ret, (long)DateTime.Now.Subtract(_dt1970).TotalSeconds))); return ret; } /// <summary> /// 缓存壳(哈希表),将 fields 每个元素存储到单独的缓存片,实现最大化复用 /// </summary> /// <typeparam name="T">缓存类型</typeparam> /// <param name="key">不含prefix前辍</param> /// <param name="fields">字段</param> /// <param name="timeoutSeconds">缓存秒数</param> /// <param name="getDataAsync">获取源数据的函数,输入参数是没有缓存的 fields,返回值应该是 (field, value)[]</param> /// <returns></returns> async public Task<(string key, T value)[]> CacheShellAsync<T>(string key, string[] fields, int timeoutSeconds, Func<string[], Task<(string, T)[]>> getDataAsync) { fields = fields?.Distinct().ToArray(); if (fields == null || fields.Length == 0) return new (string, T)[0]; if (timeoutSeconds == 0) return await getDataAsync(fields); var ret = new (string, T)[fields.Length]; var cacheValue = await HMGetAsync(key, fields); var fieldsMGet = new Dictionary<string, int>(); for (var a = 0; a < ret.Length; a++) { if (cacheValue[a] != null) { try { var value = this.DeserializeObject<(T, long)>(cacheValue[a]); if (DateTime.Now.Subtract(_dt1970.AddSeconds(value.Item2)).TotalSeconds <= timeoutSeconds) { ret[a] = (fields[a], value.Item1); continue; } } catch { await HDelAsync(key, fields[a]); throw; } } fieldsMGet.Add(fields[a], a); } if (fieldsMGet.Any()) { var getDataIntput = fieldsMGet.Keys.ToArray(); var data = await getDataAsync(getDataIntput); var mset = new object[fieldsMGet.Count * 2]; var msetIndex = 0; foreach (var d in data) { if (fieldsMGet.ContainsKey(d.Item1) == false) throw new Exception($"使用 CacheShell 请确认 getData 返回值 (string, T)[] 中的 Item1 值: {d.Item1} 存在于 输入参数: {string.Join(",", getDataIntput)}"); ret[fieldsMGet[d.Item1]] = d; mset[msetIndex++] = d.Item1; mset[msetIndex++] = this.SerializeObject((d.Item2, (long)DateTime.Now.Subtract(_dt1970).TotalSeconds)); fieldsMGet.Remove(d.Item1); } foreach (var fieldNull in fieldsMGet.Keys) { ret[fieldsMGet[fieldNull]] = (fieldNull, default(T)); mset[msetIndex++] = fieldNull; mset[msetIndex++] = this.SerializeObject((default(T), (long)DateTime.Now.Subtract(_dt1970).TotalSeconds)); } if (mset.Any()) await HMSetAsync(key, mset); } return ret; } #endregion #region 分区方式 ExecuteAsync async private Task<T> ExecuteScalarAsync<T>(string key, Func<Object<RedisClient>, string, Task<T>> handerAsync) { if (key == null) return default(T); var pool = NodeRuleRaw == null || Nodes.Count == 1 ? Nodes.First().Value : (Nodes.TryGetValue(NodeRuleRaw(key), out var b) ? b : Nodes.First().Value); key = string.Concat(pool.Prefix, key); return await GetAndExecuteAsync(pool, conn => handerAsync(conn, key)); } async private Task<T[]> ExecuteArrayAsync<T>(string[] key, Func<Object<RedisClient>, string[], Task<T[]>> handerAsync) { if (key == null || key.Any() == false) return new T[0]; if (NodeRuleRaw == null || Nodes.Count == 1) { var pool = Nodes.First().Value; var keys = key.Select(a => string.Concat(pool.Prefix, a)).ToArray(); return await GetAndExecuteAsync(pool, conn => handerAsync(conn, keys)); } var rules = new Dictionary<string, List<(string, int)>>(); for (var a = 0; a < key.Length; a++) { var rule = NodeRuleRaw(key[a]); if (rules.ContainsKey(rule)) rules[rule].Add((key[a], a)); else rules.Add(rule, new List<(string, int)> { (key[a], a) }); } T[] ret = new T[key.Length]; foreach (var r in rules) { var pool = Nodes.TryGetValue(r.Key, out var b) ? b : Nodes.First().Value; var keys = r.Value.Select(a => string.Concat(pool.Prefix, a.Item1)).ToArray(); await GetAndExecuteAsync(pool, async conn => { var vals = await handerAsync(conn, keys); for (var z = 0; z < r.Value.Count; z++) { ret[r.Value[z].Item2] = vals == null || z >= vals.Length ? default(T) : vals[z]; } return 0; }); } return ret; } async private Task<long> ExecuteNonQueryAsync(string[] key, Func<Object<RedisClient>, string[], Task<long>> handerAsync) { if (key == null || key.Any() == false) return 0; if (NodeRuleRaw == null || Nodes.Count == 1) { var pool = Nodes.First().Value; var keys = key.Select(a => string.Concat(pool.Prefix, a)).ToArray(); return await GetAndExecuteAsync(pool, conn => handerAsync(conn, keys)); } var rules = new Dictionary<string, List<string>>(); for (var a = 0; a < key.Length; a++) { var rule = NodeRuleRaw(key[a]); if (rules.ContainsKey(rule)) rules[rule].Add(key[a]); else rules.Add(rule, new List<string> { key[a] }); } long affrows = 0; foreach (var r in rules) { var pool = Nodes.TryGetValue(r.Key, out var b) ? b : Nodes.First().Value; var keys = r.Value.Select(a => string.Concat(pool.Prefix, a)).ToArray(); affrows += await GetAndExecuteAsync(pool, conn => handerAsync(conn, keys)); } return affrows; } #endregion #region 服务器命令 public partial class NodesServerManagerProvider { async Task<(string node, T value)[]> NodesInternalAsync<T>(Func<Object<RedisClient>, Task<T>> handleAsync) { var ret = new List<(string, T)>(); foreach (var pool in _csredis.Nodes.Values) ret.Add((pool.Key, await _csredis.GetAndExecuteAsync(pool, c => handleAsync(c)))); return ret.ToArray(); } /// <summary> /// 异步执行一个 AOF(AppendOnly File) 文件重写操作 /// </summary> /// <returns></returns> public Task<(string node, string value)[]> BgRewriteAofAsync() => NodesInternalAsync(c => c.Value.BgRewriteAofAsync()); /// <summary> /// 在后台异步保存当前数据库的数据到磁盘 /// </summary> /// <returns></returns> public Task<(string node, string value)[]> BgSaveAsync() => NodesInternalAsync(c => c.Value.BgSaveAsync()); /// <summary> /// 关闭客户端连接 /// </summary> /// <param name="ip">ip</param> /// <param name="port">端口</param> /// <returns></returns> public Task<(string node, string value)[]> ClientKillAsync(string ip, int port) => NodesInternalAsync(c => c.Value.ClientKillAsync(ip, port)); /// <summary> /// 关闭客户端连接 /// </summary> /// <param name="addr">ip:port</param> /// <param name="id">客户唯一标识</param> /// <param name="type">类型:normal | slave | pubsub</param> /// <param name="skipMe">跳过自己</param> /// <returns></returns> public Task<(string node, long value)[]> ClientKillAsync(string addr = null, string id = null, ClientKillType? type = null, bool? skipMe = null) => NodesInternalAsync(c => c.Value.ClientKillAsync(addr, id, type?.ToString(), skipMe)); /// <summary> /// 获取连接到服务器的客户端连接列表 /// </summary> /// <returns></returns> public Task<(string node, string value)[]> ClientListAsync() => NodesInternalAsync(c => c.Value.ClientListAsync()); /// <summary> /// 获取连接的名称 /// </summary> /// <returns></returns> public Task<(string node, string value)[]> ClientGetNameAsync() => NodesInternalAsync(c => c.Value.ClientGetNameAsync()); /// <summary> /// 在指定时间内终止运行来自客户端的命令 /// </summary> /// <param name="timeout">阻塞时间</param> /// <returns></returns> public Task<(string node, string value)[]> ClientPauseAsync(TimeSpan timeout) => NodesInternalAsync(c => c.Value.ClientPauseAsync(timeout)); /// <summary> /// 设置当前连接的名称 /// </summary> /// <param name="connectionName">连接名称</param> /// <returns></returns> public Task<(string node, string value)[]> ClientSetNameAsync(string connectionName) => NodesInternalAsync(c => c.Value.ClientSetNameAsync(connectionName)); /// <summary> /// 返回当前服务器时间 /// </summary> /// <returns></returns> public Task<(string node, DateTime value)[]> TimeAsync() => NodesInternalAsync(c => c.Value.TimeAsync()); /// <summary> /// 获取指定配置参数的值 /// </summary> /// <param name="parameter">参数</param> /// <returns></returns> public Task<(string node, Dictionary<string, string> value)[]> ConfigGetAsync(string parameter) => NodesInternalAsync(async c => (await c.Value.ConfigGetAsync(parameter)).ToDictionary(z => z.Item1, y => y.Item2)); /// <summary> /// 对启动 Redis 服务器时所指定的 redis.conf 配置文件进行改写 /// </summary> /// <returns></returns> public Task<(string node, string value)[]> ConfigRewriteAsync() => NodesInternalAsync(c => c.Value.ConfigRewriteAsync()); /// <summary> /// 修改 redis 配置参数,无需重启 /// </summary> /// <param name="parameter">参数</param> /// <param name="value">值</param> /// <returns></returns> public Task<(string node, string value)[]> ConfigSetAsync(string parameter, string value) => NodesInternalAsync(c => c.Value.ConfigSetAsync(parameter, value)); /// <summary> /// 重置 INFO 命令中的某些统计数据 /// </summary> /// <returns></returns> public Task<(string node, string value)[]> ConfigResetStatAsync() => NodesInternalAsync(c => c.Value.ConfigResetStatAsync()); /// <summary> /// 返回当前数据库的 key 的数量 /// </summary> /// <returns></returns> public Task<(string node, long value)[]> DbSizeAsync() => NodesInternalAsync(c => c.Value.DbSizeAsync()); /// <summary> /// 让 Redis 服务崩溃 /// </summary> /// <returns></returns> public Task<(string node, string value)[]> DebugSegFaultAsync() => NodesInternalAsync(c => c.Value.DebugSegFaultAsync()); /// <summary> /// 删除所有数据库的所有key /// </summary> /// <returns></returns> public Task<(string node, string value)[]> FlushAllAsync() => NodesInternalAsync(c => c.Value.FlushAllAsync()); /// <summary> /// 删除当前数据库的所有key /// </summary> /// <returns></returns> public Task<(string node, string value)[]> FlushDbAsync() => NodesInternalAsync(c => c.Value.FlushDbAsync()); /// <summary> /// 获取 Redis 服务器的各种信息和统计数值 /// </summary> /// <param name="section">部分(all|default|server|clients|memory|persistence|stats|replication|cpu|commandstats|cluster|keyspace)</param> /// <returns></returns> public Task<(string node, string value)[]> InfoAsync(InfoSection? section = null) => NodesInternalAsync(c => c.Value.InfoAsync(section?.ToString())); /// <summary> /// 返回最近一次 Redis 成功将数据保存到磁盘上的时间 /// </summary> /// <returns></returns> public Task<(string node, DateTime value)[]> LastSaveAsync() => NodesInternalAsync(c => c.Value.LastSaveAsync()); /// <summary> /// 返回主从实例所属的角色 /// </summary> /// <returns></returns> public Task<(string node, RedisRole value)[]> RoleAsync() => NodesInternalAsync(c => c.Value.RoleAsync()); /// <summary> /// 同步保存数据到硬盘 /// </summary> /// <returns></returns> public Task<(string node, string value)[]> SaveAsync() => NodesInternalAsync(c => c.Value.SaveAsync()); /// <summary> /// 异步保存数据到硬盘,并关闭服务器 /// </summary> /// <param name="isSave">是否保存</param> /// <returns></returns> public Task<(string node, string value)[]> ShutdownAsync(bool isSave = true) => NodesInternalAsync(c => c.Value.ShutdownAsync(isSave)); /// <summary> /// 将服务器转变为指定服务器的从属服务器(slave server),如果当前服务器已经是某个主服务器(master server)的从属服务器,那么执行 SLAVEOF host port 将使当前服务器停止对旧主服务器的同步,丢弃旧数据集,转而开始对新主服务器进行同步。 /// </summary> /// <param name="host">主机</param> /// <param name="port">端口</param> /// <returns></returns> public Task<(string node, string value)[]> SlaveOfAsync(string host, int port) => NodesInternalAsync(c => c.Value.SlaveOfAsync(host, port)); /// <summary> /// 从属服务器执行命令 SLAVEOF NO ONE 将使得这个从属服务器关闭复制功能,并从从属服务器转变回主服务器,原来同步所得的数据集不会被丢弃。 /// </summary> /// <returns></returns> public Task<(string node, string value)[]> SlaveOfNoOneAsync() => NodesInternalAsync(c => c.Value.SlaveOfNoOneAsync()); /// <summary> /// 管理 redis 的慢日志,按数量获取 /// </summary> /// <param name="count">数量</param> /// <returns></returns> public Task<(string node, RedisSlowLogEntry[] value)[]> SlowLogGetAsync(long? count = null) => NodesInternalAsync(c => c.Value.SlowLogGetAsync(count)); /// <summary> /// 管理 redis 的慢日志,总数量 /// </summary> /// <returns></returns> public Task<(string node, long value)[]> SlowLogLenAsync() => NodesInternalAsync(c => c.Value.SlowLogLenAsync()); /// <summary> /// 管理 redis 的慢日志,清空 /// </summary> /// <returns></returns> public Task<(string node, string value)[]> SlowLogResetAsync() => NodesInternalAsync(c => c.Value.SlowLogResetAsync()); /// <summary> /// 用于复制功能(replication)的内部命令 /// </summary> /// <returns></returns> public Task<(string node, byte[] value)[]> SyncAsync() => NodesInternalAsync(c => c.Value.SyncAsync()); } public partial class NodeServerManagerProvider { /// <summary> /// 异步执行一个 AOF(AppendOnly File) 文件重写操作 /// </summary> /// <returns></returns> public Task<string> BgRewriteAofAsync() => _csredis.GetAndExecute(_pool, c => c.Value.BgRewriteAofAsync()); /// <summary> /// 在后台异步保存当前数据库的数据到磁盘 /// </summary> /// <returns></returns> public Task<string> BgSaveAsync() => _csredis.GetAndExecute(_pool, c => c.Value.BgSaveAsync()); /// <summary> /// 关闭客户端连接 /// </summary> /// <param name="ip">ip</param> /// <param name="port">端口</param> /// <returns></returns> public Task<string> ClientKillAsync(string ip, int port) => _csredis.GetAndExecute(_pool, c => c.Value.ClientKillAsync(ip, port)); /// <summary> /// 关闭客户端连接 /// </summary> /// <param name="addr">ip:port</param> /// <param name="id">客户唯一标识</param> /// <param name="type">类型:normal | slave | pubsub</param> /// <param name="skipMe">跳过自己</param> /// <returns></returns> public Task<long> ClientKillAsync(string addr = null, string id = null, ClientKillType? type = null, bool? skipMe = null) => _csredis.GetAndExecute(_pool, c => c.Value.ClientKillAsync(addr, id, type?.ToString(), skipMe)); /// <summary> /// 获取连接到服务器的客户端连接列表 /// </summary> /// <returns></returns> public Task<string> ClientListAsync() => _csredis.GetAndExecute(_pool, c => c.Value.ClientListAsync()); /// <summary> /// 获取连接的名称 /// </summary> /// <returns></returns> public Task<string> ClientGetNameAsync() => _csredis.GetAndExecute(_pool, c => c.Value.ClientGetNameAsync()); /// <summary> /// 在指定时间内终止运行来自客户端的命令 /// </summary> /// <param name="timeout">阻塞时间</param> /// <returns></returns> public Task<string> ClientPauseAsync(TimeSpan timeout) => _csredis.GetAndExecute(_pool, c => c.Value.ClientPauseAsync(timeout)); /// <summary> /// 设置当前连接的名称 /// </summary> /// <param name="connectionName">连接名称</param> /// <returns></returns> public Task<string> ClientSetNameAsync(string connectionName) => _csredis.GetAndExecute(_pool, c => c.Value.ClientSetNameAsync(connectionName)); /// <summary> /// 返回当前服务器时间 /// </summary> /// <returns></returns> public Task<DateTime> TimeAsync() => _csredis.GetAndExecute(_pool, c => c.Value.TimeAsync()); /// <summary> /// 获取指定配置参数的值 /// </summary> /// <param name="parameter">参数</param> /// <returns></returns> async public Task<Dictionary<string, string>> ConfigGetAsync(string parameter) => (await _csredis.GetAndExecute(_pool, c => c.Value.ConfigGetAsync(parameter))).ToDictionary(z => z.Item1, y => y.Item2); /// <summary> /// 对启动 Redis 服务器时所指定的 redis.conf 配置文件进行改写 /// </summary> /// <returns></returns> public Task<string> ConfigRewriteAsync() => _csredis.GetAndExecute(_pool, c => c.Value.ConfigRewriteAsync()); /// <summary> /// 修改 redis 配置参数,无需重启 /// </summary> /// <param name="parameter">参数</param> /// <param name="value">值</param> /// <returns></returns> public Task<string> ConfigSetAsync(string parameter, string value) => _csredis.GetAndExecute(_pool, c => c.Value.ConfigSetAsync(parameter, value)); /// <summary> /// 重置 INFO 命令中的某些统计数据 /// </summary> /// <returns></returns> public Task<string> ConfigResetStatAsync() => _csredis.GetAndExecute(_pool, c => c.Value.ConfigResetStatAsync()); /// <summary> /// 返回当前数据库的 key 的数量 /// </summary> /// <returns></returns> public Task<long> DbSizeAsync() => _csredis.GetAndExecute(_pool, c => c.Value.DbSizeAsync()); /// <summary> /// 让 Redis 服务崩溃 /// </summary> /// <returns></returns> public Task<string> DebugSegFaultAsync() => _csredis.GetAndExecute(_pool, c => c.Value.DebugSegFaultAsync()); /// <summary> /// 删除所有数据库的所有key /// </summary> /// <returns></returns> public Task<string> FlushAllAsync() => _csredis.GetAndExecute(_pool, c => c.Value.FlushAllAsync()); /// <summary> /// 删除当前数据库的所有key /// </summary> /// <returns></returns> public Task<string> FlushDbAsync() => _csredis.GetAndExecute(_pool, c => c.Value.FlushDbAsync()); /// <summary> /// 获取 Redis 服务器的各种信息和统计数值 /// </summary> /// <param name="section">部分(Server | Clients | Memory | Persistence | Stats | Replication | CPU | Keyspace)</param> /// <returns></returns> public Task<string> InfoAsync(InfoSection? section = null) => _csredis.GetAndExecute(_pool, c => c.Value.InfoAsync(section?.ToString())); /// <summary> /// 返回最近一次 Redis 成功将数据保存到磁盘上的时间 /// </summary> /// <returns></returns> public Task<DateTime> LastSaveAsync() => _csredis.GetAndExecute(_pool, c => c.Value.LastSaveAsync()); /// <summary> /// 返回主从实例所属的角色 /// </summary> /// <returns></returns> public Task<RedisRole> RoleAsync() => _csredis.GetAndExecute(_pool, c => c.Value.RoleAsync()); /// <summary> /// 同步保存数据到硬盘 /// </summary> /// <returns></returns> public Task<string> SaveAsync() => _csredis.GetAndExecute(_pool, c => c.Value.SaveAsync()); /// <summary> /// 异步保存数据到硬盘,并关闭服务器 /// </summary> /// <param name="isSave">是否保存</param> /// <returns></returns> public Task<string> ShutdownAsync(bool isSave = true) => _csredis.GetAndExecute(_pool, c => c.Value.ShutdownAsync(isSave)); /// <summary> /// 将服务器转变为指定服务器的从属服务器(slave server),如果当前服务器已经是某个主服务器(master server)的从属服务器,那么执行 SLAVEOF host port 将使当前服务器停止对旧主服务器的同步,丢弃旧数据集,转而开始对新主服务器进行同步。 /// </summary> /// <param name="host">主机</param> /// <param name="port">端口</param> /// <returns></returns> public Task<string> SlaveOfAsync(string host, int port) => _csredis.GetAndExecute(_pool, c => c.Value.SlaveOfAsync(host, port)); /// <summary> /// 从属服务器执行命令 SLAVEOF NO ONE 将使得这个从属服务器关闭复制功能,并从从属服务器转变回主服务器,原来同步所得的数据集不会被丢弃。 /// </summary> /// <returns></returns> public Task<string> SlaveOfNoOneAsync() => _csredis.GetAndExecute(_pool, c => c.Value.SlaveOfNoOneAsync()); /// <summary> /// 管理 redis 的慢日志,按数量获取 /// </summary> /// <param name="count">数量</param> /// <returns></returns> public Task<RedisSlowLogEntry[]> SlowLogGetAsync(long? count = null) => _csredis.GetAndExecute(_pool, c => c.Value.SlowLogGetAsync(count)); /// <summary> /// 管理 redis 的慢日志,总数量 /// </summary> /// <returns></returns> public Task<long> SlowLogLenAsync() => _csredis.GetAndExecute(_pool, c => c.Value.SlowLogLenAsync()); /// <summary> /// 管理 redis 的慢日志,清空 /// </summary> /// <returns></returns> public Task<string> SlowLogResetAsync() => _csredis.GetAndExecute(_pool, c => c.Value.SlowLogResetAsync()); /// <summary> /// 用于复制功能(replication)的内部命令 /// </summary> /// <returns></returns> public Task<byte[]> SyncAsync() => _csredis.GetAndExecute(_pool, c => c.Value.SyncAsync()); } #endregion #region 连接命令 /// <summary> /// 验证密码是否正确 /// </summary> /// <param name="nodeKey">分区key</param> /// <param name="password">密码</param> /// <returns></returns> [Obsolete("不建议手工执行,连接池自己管理最佳")] private Task<bool> AuthAsync(string nodeKey, string password) => GetAndExecuteAsync(GetNodeOrThrowNotFound(nodeKey), async c => await c.Value.AuthAsync(password) == "OK"); /// <summary> /// 打印字符串 /// </summary> /// <param name="nodeKey">分区key</param> /// <param name="message">消息</param> /// <returns></returns> public Task<string> EchoAsync(string nodeKey, string message) => GetAndExecuteAsync(GetNodeOrThrowNotFound(nodeKey), c => c.Value.EchoAsync(message)); /// <summary> /// 打印字符串 /// </summary> /// <param name="message">消息</param> /// <returns></returns> public Task<string> EchoAsync(string message) => GetAndExecuteAsync(Nodes.First().Value, c => c.Value.EchoAsync(message)); /// <summary> /// 查看服务是否运行 /// </summary> /// <param name="nodeKey">分区key</param> /// <returns></returns> public Task<bool> PingAsync(string nodeKey) => GetAndExecuteAsync(GetNodeOrThrowNotFound(nodeKey), async c => await c.Value.PingAsync() == "PONG"); /// <summary> /// 查看服务是否运行 /// </summary> /// <returns></returns> public Task<bool> PingAsync() => GetAndExecuteAsync(Nodes.First().Value, async c => await c.Value.PingAsync() == "PONG"); /// <summary> /// 关闭当前连接 /// </summary> /// <param name="nodeKey">分区key</param> /// <returns></returns> [Obsolete("不建议手工执行,连接池自己管理最佳")] private Task<bool> QuitAsync(string nodeKey) => GetAndExecuteAsync(GetNodeOrThrowNotFound(nodeKey), async c => await c.Value.QuitAsync() == "OK"); /// <summary> /// 切换到指定的数据库 /// </summary> /// <param name="nodeKey">分区key</param> /// <param name="index">数据库</param> /// <returns></returns> [Obsolete("不建议手工执行,连接池所有连接应该指向同一数据库,若手工修改将导致数据的不一致")] private Task<bool> SelectAsync(string nodeKey, int index) => GetAndExecuteAsync(GetNodeOrThrowNotFound(nodeKey), async c => await c.Value.SelectAsync(index) == "OK"); #endregion #region Script /// <summary> /// 执行脚本 /// </summary> /// <param name="script">Lua 脚本</param> /// <param name="key">用于定位分区节点,不含prefix前辍</param> /// <param name="args">参数</param> /// <returns></returns> public Task<object> EvalAsync(string script, string key, params object[] args) { var args2 = args?.Select(z => this.SerializeRedisValueInternal(z)).ToArray(); return ExecuteScalarAsync(key, (c, k) => c.Value.EvalAsync(script, new[] { k }, args2)); } /// <summary> /// 执行脚本 /// </summary> /// <param name="sha1">脚本缓存的sha1</param> /// <param name="key">用于定位分区节点,不含prefix前辍</param> /// <param name="args">参数</param> /// <returns></returns> public Task<object> EvalSHAAsync(string sha1, string key, params object[] args) { var args2 = args?.Select(z => this.SerializeRedisValueInternal(z)).ToArray(); return ExecuteScalarAsync(key, (c, k) => c.Value.EvalSHAAsync(sha1, new[] { k }, args2)); } /// <summary> /// 校验所有分区节点中,脚本是否已经缓存。任何分区节点未缓存sha1,都返回false。 /// </summary> /// <param name="sha1">脚本缓存的sha1</param> /// <returns></returns> async public Task<bool[]> ScriptExistsAsync(params string[] sha1) { var ret = new List<bool>(); foreach (var pool in Nodes.Values) ret.Add((await GetAndExecuteAsync(pool, c => c.Value.ScriptExistsAsync(sha1)))?.Where(z => z == false).Any() == false); return ret.ToArray(); } /// <summary> /// 清除所有分区节点中,所有 Lua 脚本缓存 /// </summary> async public Task ScriptFlushAsync() { foreach (var pool in Nodes.Values) await GetAndExecuteAsync(pool, c => c.Value.ScriptFlushAsync()); } /// <summary> /// 杀死所有分区节点中,当前正在运行的 Lua 脚本 /// </summary> async public Task ScriptKillAsync() { foreach (var pool in Nodes.Values) await GetAndExecuteAsync(pool, c => c.Value.ScriptKillAsync()); } /// <summary> /// 在所有分区节点中,缓存脚本后返回 sha1(同样的脚本在任何服务器,缓存后的 sha1 都是相同的) /// </summary> /// <param name="script">Lua 脚本</param> /// <returns></returns> async public Task<string> ScriptLoadAsync(string script) { string sha1 = null; foreach (var pool in Nodes.Values) sha1 = await GetAndExecuteAsync(pool, c => c.Value.ScriptLoadAsync(script)); return sha1; } #endregion #region Pub/Sub /// <summary> /// 用于将信息发送到指定分区节点的频道,最终消息发布格式:1|message /// </summary> /// <param name="channel">频道名</param> /// <param name="message">消息文本</param> /// <returns></returns> async public Task<long> PublishAsync(string channel, string message) { var msgid = await HIncrByAsync("csredisclient:Publish:msgid", channel, 1); return await ExecuteScalarAsync(channel, (c, k) => c.Value.PublishAsync(channel, $"{msgid}|{message}")); } /// <summary> /// 用于将信息发送到指定分区节点的频道,与 Publish 方法不同,不返回消息id头,即 1| /// </summary> /// <param name="channel">频道名</param> /// <param name="message">消息文本</param> /// <returns></returns> public Task<long> PublishNoneMessageIdAsync(string channel, string message) => ExecuteScalarAsync(channel, (c, k) => c.Value.PublishAsync(channel, message)); /// <summary> /// 查看所有订阅频道 /// </summary> /// <param name="pattern"></param> /// <returns></returns> async public Task<string[]> PubSubChannelsAsync(string pattern) { var ret = new List<string>(); foreach (var pool in Nodes.Values) ret.AddRange(await GetAndExecuteAsync(pool, c => c.Value.PubSubChannelsAsync(pattern))); return ret.ToArray(); } /// <summary> /// 查看所有模糊订阅端的数量 /// </summary> /// <returns></returns> [Obsolete("分区模式下,其他客户端的模糊订阅可能不会返回")] public Task<long> PubSubNumPatAsync() => GetAndExecuteAsync(Nodes.First().Value, c => c.Value.PubSubNumPatAsync()); /// <summary> /// 查看所有订阅端的数量 /// </summary> /// <param name="channels">频道</param> /// <returns></returns> [Obsolete("分区模式下,其他客户端的订阅可能不会返回")] async public Task<Dictionary<string, long>> PubSubNumSubAsync(params string[] channels) => (await ExecuteArrayAsync(channels, (c, k) => { var prefix = (c.Pool as RedisClientPool).Prefix; return c.Value.PubSubNumSubAsync(k.Select(z => string.IsNullOrEmpty(prefix) == false && z.StartsWith(prefix) ? z.Substring(prefix.Length) : z).ToArray()); })).ToDictionary(z => z.Item1, y => y.Item2); #endregion #region HyperLogLog /// <summary> /// 添加指定元素到 HyperLogLog /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="elements">元素</param> /// <returns></returns> async public Task<bool> PfAddAsync<T>(string key, params T[] elements) { if (elements == null || elements.Any() == false) return false; var args = elements.Select(z => this.SerializeRedisValueInternal(z)).ToArray(); return await ExecuteScalarAsync(key, (c, k) => c.Value.PfAddAsync(k, args)); } /// <summary> /// 返回给定 HyperLogLog 的基数估算值 /// </summary> /// <param name="keys">不含prefix前辍</param> /// <returns></returns> [Obsolete("分区模式下,若keys分散在多个分区节点时,将报错")] public Task<long> PfCountAsync(params string[] keys) => NodesNotSupportAsync(keys, 0, (c, k) => c.Value.PfCountAsync(k)); /// <summary> /// 将多个 HyperLogLog 合并为一个 HyperLogLog /// </summary> /// <param name="destKey">新的 HyperLogLog,不含prefix前辍</param> /// <param name="sourceKeys">源 HyperLogLog,不含prefix前辍</param> /// <returns></returns> [Obsolete("分区模式下,若keys分散在多个分区节点时,将报错")] public Task<bool> PfMergeAsync(string destKey, params string[] sourceKeys) => NodesNotSupportAsync(new[] { destKey }.Concat(sourceKeys).ToArray(), false, async (c, k) => await c.Value.PfMergeAsync(k.First(), k.Skip(1).ToArray()) == "OK"); #endregion #region Sorted Set /// <summary> /// [redis-server 5.0.0] 删除并返回有序集合key中的最多count个具有最高得分的成员。如未指定,count的默认值为1。指定一个大于有序集合的基数的count不会产生错误。 当返回多个元素时候,得分最高的元素将是第一个元素,然后是分数较低的元素。 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="count">数量</param> /// <returns></returns> async public Task<(string member, decimal score)[]> ZPopMaxAsync(string key, long count) => (await ExecuteScalarAsync(key, (c, k) => c.Value.ZPopMaxAsync(k, count))).Select(a => (a.Item1, a.Item2)).ToArray(); /// <summary> /// [redis-server 5.0.0] 删除并返回有序集合key中的最多count个具有最高得分的成员。如未指定,count的默认值为1。指定一个大于有序集合的基数的count不会产生错误。 当返回多个元素时候,得分最高的元素将是第一个元素,然后是分数较低的元素。 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="count">数量</param> /// <returns></returns> async public Task<(T member, decimal score)[]> ZPopMaxAsync<T>(string key, long count) => this.DeserializeRedisValueTuple1Internal<T, decimal>(await ExecuteScalarAsync(key, (c, k) => c.Value.ZPopMaxBytesAsync(k, count))); /// <summary> /// [redis-server 5.0.0] 删除并返回有序集合key中的最多count个具有最低得分的成员。如未指定,count的默认值为1。指定一个大于有序集合的基数的count不会产生错误。 当返回多个元素时候,得分最低的元素将是第一个元素,然后是分数较高的元素。 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="count">数量</param> /// <returns></returns> async public Task<(string member, decimal score)[]> ZPopMinAsync(string key, long count) => (await ExecuteScalarAsync(key, (c, k) => c.Value.ZPopMinAsync(k, count))).Select(a => (a.Item1, a.Item2)).ToArray(); /// <summary> /// [redis-server 5.0.0] 删除并返回有序集合key中的最多count个具有最低得分的成员。如未指定,count的默认值为1。指定一个大于有序集合的基数的count不会产生错误。 当返回多个元素时候,得分最低的元素将是第一个元素,然后是分数较高的元素。 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="count">数量</param> /// <returns></returns> async public Task<(T member, decimal score)[]> ZPopMinAsync<T>(string key, long count) => this.DeserializeRedisValueTuple1Internal<T, decimal>(await ExecuteScalarAsync(key, (c, k) => c.Value.ZPopMinBytesAsync(k, count))); /// <summary> /// 向有序集合添加一个或多个成员,或者更新已存在成员的分数 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="scoreMembers">一个或多个成员分数</param> /// <returns></returns> async public Task<long> ZAddAsync(string key, params (decimal, object)[] scoreMembers) { if (scoreMembers == null || scoreMembers.Any() == false) return 0; var args = scoreMembers.Select(a => new Tuple<decimal, object>(a.Item1, this.SerializeRedisValueInternal(a.Item2))).ToArray(); return await ExecuteScalarAsync(key, (c, k) => c.Value.ZAddAsync(k, args)); } /// <summary> /// 获取有序集合的成员数量 /// </summary> /// <param name="key">不含prefix前辍</param> /// <returns></returns> public Task<long> ZCardAsync(string key) => ExecuteScalarAsync(key, (c, k) => c.Value.ZCardAsync(k)); /// <summary> /// 计算在有序集合中指定区间分数的成员数量 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="min">分数最小值 decimal.MinValue 1</param> /// <param name="max">分数最大值 decimal.MaxValue 10</param> /// <returns></returns> public Task<long> ZCountAsync(string key, decimal min, decimal max) => ExecuteScalarAsync(key, (c, k) => c.Value.ZCountAsync(k, min == decimal.MinValue ? "-inf" : min.ToString(), max == decimal.MaxValue ? "+inf" : max.ToString())); /// <summary> /// 计算在有序集合中指定区间分数的成员数量 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="min">分数最小值 -inf (1 1</param> /// <param name="max">分数最大值 +inf (10 10</param> /// <returns></returns> public Task<long> ZCountAsync(string key, string min, string max) => ExecuteScalarAsync(key, (c, k) => c.Value.ZCountAsync(k, min, max)); /// <summary> /// 有序集合中对指定成员的分数加上增量 increment /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="member">成员</param> /// <param name="increment">增量值(默认=1)</param> /// <returns></returns> public Task<decimal> ZIncrByAsync(string key, string member, decimal increment = 1) { var args = this.SerializeRedisValueInternal(member); return ExecuteScalarAsync(key, (c, k) => c.Value.ZIncrByAsync(k, increment, args)); } /// <summary> /// 计算给定的一个或多个有序集的交集,将结果集存储在新的有序集合 destination 中 /// </summary> /// <param name="destination">新的有序集合,不含prefix前辍</param> /// <param name="weights">使用 WEIGHTS 选项,你可以为 每个 给定有序集 分别 指定一个乘法因子。如果没有指定 WEIGHTS 选项,乘法因子默认设置为 1 。</param> /// <param name="aggregate">Sum | Min | Max</param> /// <param name="keys">一个或多个有序集合,不含prefix前辍</param> /// <returns></returns> public Task<long> ZInterStoreAsync(string destination, decimal[] weights, RedisAggregate aggregate, params string[] keys) { if (keys == null || keys.Length == 0) throw new Exception("keys 参数不可为空"); if (weights != null && weights.Length != keys.Length) throw new Exception("weights 和 keys 参数长度必须相同"); return NodesNotSupportAsync(new[] { destination }.Concat(keys).ToArray(), 0, (c, k) => c.Value.ZInterStoreAsync(k.First(), weights, aggregate, k.Skip(1).ToArray())); } /// <summary> /// 通过索引区间返回有序集合成指定区间内的成员 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="start">开始位置,0表示第一个元素,-1表示最后一个元素</param> /// <param name="stop">结束位置,0表示第一个元素,-1表示最后一个元素</param> /// <returns></returns> public Task<string[]> ZRangeAsync(string key, long start, long stop) => ExecuteScalarAsync(key, (c, k) => c.Value.ZRangeAsync(k, start, stop, false)); /// <summary> /// 通过索引区间返回有序集合成指定区间内的成员 /// </summary> /// <typeparam name="T">byte[] 或其他类型</typeparam> /// <param name="key">不含prefix前辍</param> /// <param name="start">开始位置,0表示第一个元素,-1表示最后一个元素</param> /// <param name="stop">结束位置,0表示第一个元素,-1表示最后一个元素</param> /// <returns></returns> async public Task<T[]> ZRangeAsync<T>(string key, long start, long stop) => this.DeserializeRedisValueArrayInternal<T>(await ExecuteScalarAsync(key, (c, k) => c.Value.ZRangeBytesAsync(k, start, stop, false))); /// <summary> /// 通过索引区间返回有序集合成指定区间内的成员和分数 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="start">开始位置,0表示第一个元素,-1表示最后一个元素</param> /// <param name="stop">结束位置,0表示第一个元素,-1表示最后一个元素</param> /// <returns></returns> async public Task<(string member, decimal score)[]> ZRangeWithScoresAsync(string key, long start, long stop) => (await ExecuteScalarAsync(key, (c, k) => c.Value.ZRangeWithScoresAsync(k, start, stop))).Select(a => (a.Item1, a.Item2)).ToArray(); /// <summary> /// 通过索引区间返回有序集合成指定区间内的成员和分数 /// </summary> /// <typeparam name="T">byte[] 或其他类型</typeparam> /// <param name="key">不含prefix前辍</param> /// <param name="start">开始位置,0表示第一个元素,-1表示最后一个元素</param> /// <param name="stop">结束位置,0表示第一个元素,-1表示最后一个元素</param> /// <returns></returns> async public Task<(T member, decimal score)[]> ZRangeWithScoresAsync<T>(string key, long start, long stop) => this.DeserializeRedisValueTuple1Internal<T, decimal>(await ExecuteScalarAsync(key, (c, k) => c.Value.ZRangeBytesWithScoresAsync(k, start, stop))); /// <summary> /// 通过分数返回有序集合指定区间内的成员 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="min">分数最小值 decimal.MinValue 1</param> /// <param name="max">分数最大值 decimal.MaxValue 10</param> /// <param name="count">返回多少成员</param> /// <param name="offset">返回条件偏移位置</param> /// <returns></returns> public Task<string[]> ZRangeByScoreAsync(string key, decimal min, decimal max, long? count = null, long offset = 0) => ExecuteScalarAsync(key, (c, k) => c.Value.ZRangeByScoreAsync(k, min == decimal.MinValue ? "-inf" : min.ToString(), max == decimal.MaxValue ? "+inf" : max.ToString(), false, offset, count)); /// <summary> /// 通过分数返回有序集合指定区间内的成员 /// </summary> /// <typeparam name="T">byte[] 或其他类型</typeparam> /// <param name="key">不含prefix前辍</param> /// <param name="min">分数最小值 decimal.MinValue 1</param> /// <param name="max">分数最大值 decimal.MaxValue 10</param> /// <param name="count">返回多少成员</param> /// <param name="offset">返回条件偏移位置</param> /// <returns></returns> async public Task<T[]> ZRangeByScoreAsync<T>(string key, decimal min, decimal max, long? count = null, long offset = 0) => this.DeserializeRedisValueArrayInternal<T>(await ExecuteScalarAsync(key, (c, k) => c.Value.ZRangeBytesByScoreAsync(k, min == decimal.MinValue ? "-inf" : min.ToString(), max == decimal.MaxValue ? "+inf" : max.ToString(), false, offset, count))); /// <summary> /// 通过分数返回有序集合指定区间内的成员 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="min">分数最小值 -inf (1 1</param> /// <param name="max">分数最大值 +inf (10 10</param> /// <param name="count">返回多少成员</param> /// <param name="offset">返回条件偏移位置</param> /// <returns></returns> public Task<string[]> ZRangeByScoreAsync(string key, string min, string max, long? count = null, long offset = 0) => ExecuteScalarAsync(key, (c, k) => c.Value.ZRangeByScoreAsync(k, min, max, false, offset, count)); /// <summary> /// 通过分数返回有序集合指定区间内的成员 /// </summary> /// <typeparam name="T">byte[] 或其他类型</typeparam> /// <param name="key">不含prefix前辍</param> /// <param name="min">分数最小值 -inf (1 1</param> /// <param name="max">分数最大值 +inf (10 10</param> /// <param name="count">返回多少成员</param> /// <param name="offset">返回条件偏移位置</param> /// <returns></returns> async public Task<T[]> ZRangeByScoreAsync<T>(string key, string min, string max, long? count = null, long offset = 0) => this.DeserializeRedisValueArrayInternal<T>(await ExecuteScalarAsync(key, (c, k) => c.Value.ZRangeBytesByScoreAsync(k, min, max, false, offset, count))); /// <summary> /// 通过分数返回有序集合指定区间内的成员和分数 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="min">分数最小值 decimal.MinValue 1</param> /// <param name="max">分数最大值 decimal.MaxValue 10</param> /// <param name="count">返回多少成员</param> /// <param name="offset">返回条件偏移位置</param> /// <returns></returns> async public Task<(string member, decimal score)[]> ZRangeByScoreWithScoresAsync(string key, decimal min, decimal max, long? count = null, long offset = 0) => (await ExecuteScalarAsync(key, (c, k) => c.Value.ZRangeByScoreWithScoresAsync(k, min == decimal.MinValue ? "-inf" : min.ToString(), max == decimal.MaxValue ? "+inf" : max.ToString(), offset, count))).Select(z => (z.Item1, z.Item2)).ToArray(); /// <summary> /// 通过分数返回有序集合指定区间内的成员和分数 /// </summary> /// <typeparam name="T">byte[] 或其他类型</typeparam> /// <param name="key">不含prefix前辍</param> /// <param name="min">分数最小值 decimal.MinValue 1</param> /// <param name="max">分数最大值 decimal.MaxValue 10</param> /// <param name="count">返回多少成员</param> /// <param name="offset">返回条件偏移位置</param> /// <returns></returns> async public Task<(T member, decimal score)[]> ZRangeByScoreWithScoresAsync<T>(string key, decimal min, decimal max, long? count = null, long offset = 0) => this.DeserializeRedisValueTuple1Internal<T, decimal>(await ExecuteScalarAsync(key, (c, k) => c.Value.ZRangeBytesByScoreWithScoresAsync(k, min == decimal.MinValue ? "-inf" : min.ToString(), max == decimal.MaxValue ? "+inf" : max.ToString(), offset, count))); /// <summary> /// 通过分数返回有序集合指定区间内的成员和分数 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="min">分数最小值 -inf (1 1</param> /// <param name="max">分数最大值 +inf (10 10</param> /// <param name="count">返回多少成员</param> /// <param name="offset">返回条件偏移位置</param> /// <returns></returns> async public Task<(string member, decimal score)[]> ZRangeByScoreWithScoresAsync(string key, string min, string max, long? count = null, long offset = 0) => (await ExecuteScalarAsync(key, (c, k) => c.Value.ZRangeByScoreWithScoresAsync(k, min, max, offset, count))).Select(z => (z.Item1, z.Item2)).ToArray(); /// <summary> /// 通过分数返回有序集合指定区间内的成员和分数 /// </summary> /// <typeparam name="T">byte[] 或其他类型</typeparam> /// <param name="key">不含prefix前辍</param> /// <param name="min">分数最小值 -inf (1 1</param> /// <param name="max">分数最大值 +inf (10 10</param> /// <param name="count">返回多少成员</param> /// <param name="offset">返回条件偏移位置</param> /// <returns></returns> async public Task<(T member, decimal score)[]> ZRangeByScoreWithScoresAsync<T>(string key, string min, string max, long? count = null, long offset = 0) => this.DeserializeRedisValueTuple1Internal<T, decimal>(await ExecuteScalarAsync(key, (c, k) => c.Value.ZRangeBytesByScoreWithScoresAsync(k, min, max, offset, count))); /// <summary> /// 返回有序集合中指定成员的索引 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="member">成员</param> /// <returns></returns> public Task<long?> ZRankAsync(string key, object member) { var args = this.SerializeRedisValueInternal(member); return ExecuteScalarAsync(key, (c, k) => c.Value.ZRankAsync(k, args)); } /// <summary> /// 移除有序集合中的一个或多个成员 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="member">一个或多个成员</param> /// <returns></returns> async public Task<long> ZRemAsync<T>(string key, params T[] member) { if (member == null || member.Any() == false) return 0; var args = member.Select(z => this.SerializeRedisValueInternal(z)).ToArray(); return await ExecuteScalarAsync(key, (c, k) => c.Value.ZRemAsync(k, args)); } /// <summary> /// 移除有序集合中给定的排名区间的所有成员 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="start">开始位置,0表示第一个元素,-1表示最后一个元素</param> /// <param name="stop">结束位置,0表示第一个元素,-1表示最后一个元素</param> /// <returns></returns> public Task<long> ZRemRangeByRankAsync(string key, long start, long stop) => ExecuteScalarAsync(key, (c, k) => c.Value.ZRemRangeByRankAsync(k, start, stop)); /// <summary> /// 移除有序集合中给定的分数区间的所有成员 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="min">分数最小值 decimal.MinValue 1</param> /// <param name="max">分数最大值 decimal.MaxValue 10</param> /// <returns></returns> public Task<long> ZRemRangeByScoreAsync(string key, decimal min, decimal max) => ExecuteScalarAsync(key, (c, k) => c.Value.ZRemRangeByScoreAsync(k, min == decimal.MinValue ? "-inf" : min.ToString(), max == decimal.MaxValue ? "+inf" : max.ToString())); /// <summary> /// 移除有序集合中给定的分数区间的所有成员 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="min">分数最小值 -inf (1 1</param> /// <param name="max">分数最大值 +inf (10 10</param> /// <returns></returns> public Task<long> ZRemRangeByScoreAsync(string key, string min, string max) => ExecuteScalarAsync(key, (c, k) => c.Value.ZRemRangeByScoreAsync(k, min, max)); /// <summary> /// 返回有序集中指定区间内的成员,通过索引,分数从高到底 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="start">开始位置,0表示第一个元素,-1表示最后一个元素</param> /// <param name="stop">结束位置,0表示第一个元素,-1表示最后一个元素</param> /// <returns></returns> public Task<string[]> ZRevRangeAsync(string key, long start, long stop) => ExecuteScalarAsync(key, (c, k) => c.Value.ZRevRangeAsync(k, start, stop, false)); /// <summary> /// 返回有序集中指定区间内的成员,通过索引,分数从高到底 /// </summary> /// <typeparam name="T">byte[] 或其他类型</typeparam> /// <param name="key">不含prefix前辍</param> /// <param name="start">开始位置,0表示第一个元素,-1表示最后一个元素</param> /// <param name="stop">结束位置,0表示第一个元素,-1表示最后一个元素</param> /// <returns></returns> async public Task<T[]> ZRevRangeAsync<T>(string key, long start, long stop) => this.DeserializeRedisValueArrayInternal<T>(await ExecuteScalarAsync(key, (c, k) => c.Value.ZRevRangeBytesAsync(k, start, stop, false))); /// <summary> /// 返回有序集中指定区间内的成员和分数,通过索引,分数从高到底 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="start">开始位置,0表示第一个元素,-1表示最后一个元素</param> /// <param name="stop">结束位置,0表示第一个元素,-1表示最后一个元素</param> /// <returns></returns> async public Task<(string member, decimal score)[]> ZRevRangeWithScoresAsync(string key, long start, long stop) => (await ExecuteScalarAsync(key, (c, k) => c.Value.ZRevRangeWithScoresAsync(k, start, stop))).Select(a => (a.Item1, a.Item2)).ToArray(); /// <summary> /// 返回有序集中指定区间内的成员和分数,通过索引,分数从高到底 /// </summary> /// <typeparam name="T">byte[] 或其他类型</typeparam> /// <param name="key">不含prefix前辍</param> /// <param name="start">开始位置,0表示第一个元素,-1表示最后一个元素</param> /// <param name="stop">结束位置,0表示第一个元素,-1表示最后一个元素</param> /// <returns></returns> async public Task<(T member, decimal score)[]> ZRevRangeWithScoresAsync<T>(string key, long start, long stop) => this.DeserializeRedisValueTuple1Internal<T, decimal>(await ExecuteScalarAsync(key, (c, k) => c.Value.ZRevRangeBytesWithScoresAsync(k, start, stop))); /// <summary> /// 返回有序集中指定分数区间内的成员,分数从高到低排序 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="max">分数最大值 decimal.MaxValue 10</param> /// <param name="min">分数最小值 decimal.MinValue 1</param> /// <param name="count">返回多少成员</param> /// <param name="offset">返回条件偏移位置</param> /// <returns></returns> public Task<string[]> ZRevRangeByScoreAsync(string key, decimal max, decimal min, long? count = null, long? offset = 0) => ExecuteScalarAsync(key, (c, k) => c.Value.ZRevRangeByScoreAsync(k, max == decimal.MaxValue ? "+inf" : max.ToString(), min == decimal.MinValue ? "-inf" : min.ToString(), false, offset, count)); /// <summary> /// 返回有序集中指定分数区间内的成员,分数从高到低排序 /// </summary> /// <typeparam name="T">byte[] 或其他类型</typeparam> /// <param name="key">不含prefix前辍</param> /// <param name="max">分数最大值 decimal.MaxValue 10</param> /// <param name="min">分数最小值 decimal.MinValue 1</param> /// <param name="count">返回多少成员</param> /// <param name="offset">返回条件偏移位置</param> /// <returns></returns> async public Task<T[]> ZRevRangeByScoreAsync<T>(string key, decimal max, decimal min, long? count = null, long offset = 0) => this.DeserializeRedisValueArrayInternal<T>(await ExecuteScalarAsync(key, (c, k) => c.Value.ZRevRangeBytesByScoreAsync(k, max == decimal.MaxValue ? "+inf" : max.ToString(), min == decimal.MinValue ? "-inf" : min.ToString(), false, offset, count))); /// <summary> /// 返回有序集中指定分数区间内的成员,分数从高到低排序 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="max">分数最大值 +inf (10 10</param> /// <param name="min">分数最小值 -inf (1 1</param> /// <param name="count">返回多少成员</param> /// <param name="offset">返回条件偏移位置</param> /// <returns></returns> public Task<string[]> ZRevRangeByScoreAsync(string key, string max, string min, long? count = null, long? offset = 0) => ExecuteScalarAsync(key, (c, k) => c.Value.ZRevRangeByScoreAsync(k, max, min, false, offset, count)); /// <summary> /// 返回有序集中指定分数区间内的成员,分数从高到低排序 /// </summary> /// <typeparam name="T">byte[] 或其他类型</typeparam> /// <param name="key">不含prefix前辍</param> /// <param name="max">分数最大值 +inf (10 10</param> /// <param name="min">分数最小值 -inf (1 1</param> /// <param name="count">返回多少成员</param> /// <param name="offset">返回条件偏移位置</param> /// <returns></returns> async public Task<T[]> ZRevRangeByScoreAsync<T>(string key, string max, string min, long? count = null, long offset = 0) => this.DeserializeRedisValueArrayInternal<T>(await ExecuteScalarAsync(key, (c, k) => c.Value.ZRevRangeBytesByScoreAsync(k, max, min, false, offset, count))); /// <summary> /// 返回有序集中指定分数区间内的成员和分数,分数从高到低排序 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="max">分数最大值 decimal.MaxValue 10</param> /// <param name="min">分数最小值 decimal.MinValue 1</param> /// <param name="count">返回多少成员</param> /// <param name="offset">返回条件偏移位置</param> /// <returns></returns> async public Task<(string member, decimal score)[]> ZRevRangeByScoreWithScoresAsync(string key, decimal max, decimal min, long? count = null, long offset = 0) => (await ExecuteScalarAsync(key, (c, k) => c.Value.ZRevRangeByScoreWithScoresAsync(k, max == decimal.MaxValue ? "+inf" : max.ToString(), min == decimal.MinValue ? "-inf" : min.ToString(), offset, count))).Select(z => (z.Item1, z.Item2)).ToArray(); /// <summary> /// 返回有序集中指定分数区间内的成员和分数,分数从高到低排序 /// </summary> /// <typeparam name="T">byte[] 或其他类型</typeparam> /// <param name="key">不含prefix前辍</param> /// <param name="max">分数最大值 decimal.MaxValue 10</param> /// <param name="min">分数最小值 decimal.MinValue 1</param> /// <param name="count">返回多少成员</param> /// <param name="offset">返回条件偏移位置</param> /// <returns></returns> async public Task<(T member, decimal score)[]> ZRevRangeByScoreWithScoresAsync<T>(string key, decimal max, decimal min, long? count = null, long offset = 0) => this.DeserializeRedisValueTuple1Internal<T, decimal>(await ExecuteScalarAsync(key, (c, k) => c.Value.ZRevRangeBytesByScoreWithScoresAsync(k, max == decimal.MaxValue ? "+inf" : max.ToString(), min == decimal.MinValue ? "-inf" : min.ToString(), offset, count))); /// <summary> /// 返回有序集中指定分数区间内的成员和分数,分数从高到低排序 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="max">分数最大值 +inf (10 10</param> /// <param name="min">分数最小值 -inf (1 1</param> /// <param name="count">返回多少成员</param> /// <param name="offset">返回条件偏移位置</param> /// <returns></returns> async public Task<(string member, decimal score)[]> ZRevRangeByScoreWithScoresAsync(string key, string max, string min, long? count = null, long offset = 0) => (await ExecuteScalarAsync(key, (c, k) => c.Value.ZRevRangeByScoreWithScoresAsync(k, max, min, offset, count))).Select(z => (z.Item1, z.Item2)).ToArray(); /// <summary> /// 返回有序集中指定分数区间内的成员和分数,分数从高到低排序 /// </summary> /// <typeparam name="T">byte[] 或其他类型</typeparam> /// <param name="key">不含prefix前辍</param> /// <param name="max">分数最大值 +inf (10 10</param> /// <param name="min">分数最小值 -inf (1 1</param> /// <param name="count">返回多少成员</param> /// <param name="offset">返回条件偏移位置</param> /// <returns></returns> async public Task<(T member, decimal score)[]> ZRevRangeByScoreWithScoresAsync<T>(string key, string max, string min, long? count = null, long offset = 0) => this.DeserializeRedisValueTuple1Internal<T, decimal>(await ExecuteScalarAsync(key, (c, k) => c.Value.ZRevRangeBytesByScoreWithScoresAsync(k, max, min, offset, count))); /// <summary> /// 返回有序集合中指定成员的排名,有序集成员按分数值递减(从大到小)排序 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="member">成员</param> /// <returns></returns> public Task<long?> ZRevRankAsync(string key, object member) { var args = this.SerializeRedisValueInternal(member); return ExecuteScalarAsync(key, (c, k) => c.Value.ZRevRankAsync(k, args)); } /// <summary> /// 返回有序集中,成员的分数值 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="member">成员</param> /// <returns></returns> public Task<decimal?> ZScoreAsync(string key, object member) { var args = this.SerializeRedisValueInternal(member); return ExecuteScalarAsync(key, (c, k) => c.Value.ZScoreAsync(k, args)); } /// <summary> /// 计算给定的一个或多个有序集的并集,将结果集存储在新的有序集合 destination 中 /// </summary> /// <param name="destination">新的有序集合,不含prefix前辍</param> /// <param name="weights">使用 WEIGHTS 选项,你可以为 每个 给定有序集 分别 指定一个乘法因子。如果没有指定 WEIGHTS 选项,乘法因子默认设置为 1 。</param> /// <param name="aggregate">Sum | Min | Max</param> /// <param name="keys">一个或多个有序集合,不含prefix前辍</param> /// <returns></returns> public Task<long> ZUnionStoreAsync(string destination, decimal[] weights, RedisAggregate aggregate, params string[] keys) { if (keys == null || keys.Length == 0) throw new Exception("keys 参数不可为空"); if (weights != null && weights.Length != keys.Length) throw new Exception("weights 和 keys 参数长度必须相同"); return NodesNotSupportAsync(new[] { destination }.Concat(keys).ToArray(), 0, (c, k) => c.Value.ZUnionStoreAsync(k.First(), weights, aggregate, k.Skip(1).ToArray())); } /// <summary> /// 迭代有序集合中的元素 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="cursor">位置</param> /// <param name="pattern">模式</param> /// <param name="count">数量</param> /// <returns></returns> async public Task<RedisScan<(string member, decimal score)>> ZScanAsync(string key, long cursor, string pattern = null, long? count = null) { var scan = await ExecuteScalarAsync(key, (c, k) => c.Value.ZScanAsync(k, cursor, pattern, count)); return new RedisScan<(string, decimal)>(scan.Cursor, scan.Items.Select(z => (z.Item1, z.Item2)).ToArray()); } /// <summary> /// 迭代有序集合中的元素 /// </summary> /// <typeparam name="T">byte[] 或其他类型</typeparam> /// <param name="key">不含prefix前辍</param> /// <param name="cursor">位置</param> /// <param name="pattern">模式</param> /// <param name="count">数量</param> /// <returns></returns> async public Task<RedisScan<(T member, decimal score)>> ZScanAsync<T>(string key, long cursor, string pattern = null, long? count = null) { var scan = await ExecuteScalarAsync(key, (c, k) => c.Value.ZScanBytesAsync(k, cursor, pattern, count)); return new RedisScan<(T, decimal)>(scan.Cursor, this.DeserializeRedisValueTuple1Internal<T, decimal>(scan.Items)); } /// <summary> /// 当有序集合的所有成员都具有相同的分值时,有序集合的元素会根据成员的字典序来进行排序,这个命令可以返回给定的有序集合键 key 中,值介于 min 和 max 之间的成员。 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="min">'(' 表示包含在范围,'[' 表示不包含在范围,'+' 正无穷大,'-' 负无限。 ZRANGEBYLEX zset - + ,命令将返回有序集合中的所有元素</param> /// <param name="max">'(' 表示包含在范围,'[' 表示不包含在范围,'+' 正无穷大,'-' 负无限。 ZRANGEBYLEX zset - + ,命令将返回有序集合中的所有元素</param> /// <param name="count">返回多少成员</param> /// <param name="offset">返回条件偏移位置</param> /// <returns></returns> public Task<string[]> ZRangeByLexAsync(string key, string min, string max, long? count = null, long offset = 0) => ExecuteScalarAsync(key, (c, k) => c.Value.ZRangeByLexAsync(k, min, max, offset, count)); /// <summary> /// 当有序集合的所有成员都具有相同的分值时,有序集合的元素会根据成员的字典序来进行排序,这个命令可以返回给定的有序集合键 key 中,值介于 min 和 max 之间的成员。 /// </summary> /// <typeparam name="T">byte[] 或其他类型</typeparam> /// <param name="key">不含prefix前辍</param> /// <param name="min">'(' 表示包含在范围,'[' 表示不包含在范围,'+' 正无穷大,'-' 负无限。 ZRANGEBYLEX zset - + ,命令将返回有序集合中的所有元素</param> /// <param name="max">'(' 表示包含在范围,'[' 表示不包含在范围,'+' 正无穷大,'-' 负无限。 ZRANGEBYLEX zset - + ,命令将返回有序集合中的所有元素</param> /// <param name="count">返回多少成员</param> /// <param name="offset">返回条件偏移位置</param> /// <returns></returns> async public Task<T[]> ZRangeByLexAsync<T>(string key, string min, string max, long? count = null, long offset = 0) => this.DeserializeRedisValueArrayInternal<T>(await ExecuteScalarAsync(key, (c, k) => c.Value.ZRangeBytesByLexAsync(k, min, max, offset, count))); /// <summary> /// 当有序集合的所有成员都具有相同的分值时,有序集合的元素会根据成员的字典序来进行排序,这个命令可以返回给定的有序集合键 key 中,值介于 min 和 max 之间的成员。 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="min">'(' 表示包含在范围,'[' 表示不包含在范围,'+' 正无穷大,'-' 负无限。 ZRANGEBYLEX zset - + ,命令将返回有序集合中的所有元素</param> /// <param name="max">'(' 表示包含在范围,'[' 表示不包含在范围,'+' 正无穷大,'-' 负无限。 ZRANGEBYLEX zset - + ,命令将返回有序集合中的所有元素</param> /// <returns></returns> public Task<long> ZRemRangeByLexAsync(string key, string min, string max) => ExecuteScalarAsync(key, (c, k) => c.Value.ZRemRangeByLexAsync(k, min, max)); /// <summary> /// 当有序集合的所有成员都具有相同的分值时,有序集合的元素会根据成员的字典序来进行排序,这个命令可以返回给定的有序集合键 key 中,值介于 min 和 max 之间的成员。 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="min">'(' 表示包含在范围,'[' 表示不包含在范围,'+' 正无穷大,'-' 负无限。 ZRANGEBYLEX zset - + ,命令将返回有序集合中的所有元素</param> /// <param name="max">'(' 表示包含在范围,'[' 表示不包含在范围,'+' 正无穷大,'-' 负无限。 ZRANGEBYLEX zset - + ,命令将返回有序集合中的所有元素</param> /// <returns></returns> public Task<long> ZLexCountAsync(string key, string min, string max) => ExecuteScalarAsync(key, (c, k) => c.Value.ZLexCountAsync(k, min, max)); #endregion #region Set /// <summary> /// 向集合添加一个或多个成员 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="members">一个或多个成员</param> /// <returns></returns> async public Task<long> SAddAsync<T>(string key, params T[] members) { if (members == null || members.Any() == false) return 0; var args = members.Select(z => this.SerializeRedisValueInternal(z)).ToArray(); return await ExecuteScalarAsync(key, (c, k) => c.Value.SAddAsync(k, args)); } /// <summary> /// 获取集合的成员数 /// </summary> /// <param name="key">不含prefix前辍</param> /// <returns></returns> public Task<long> SCardAsync(string key) => ExecuteScalarAsync(key, (c, k) => c.Value.SCardAsync(k)); /// <summary> /// 返回给定所有集合的差集 /// </summary> /// <param name="keys">不含prefix前辍</param> /// <returns></returns> public Task<string[]> SDiffAsync(params string[] keys) => NodesNotSupportAsync(keys, new string[0], (c, k) => c.Value.SDiffAsync(k)); /// <summary> /// 返回给定所有集合的差集 /// </summary> /// <typeparam name="T">byte[] 或其他类型</typeparam> /// <param name="keys">不含prefix前辍</param> /// <returns></returns> async public Task<T[]> SDiffAsync<T>(params string[] keys) => this.DeserializeRedisValueArrayInternal<T>(await NodesNotSupportAsync(keys, new byte[0][], (c, k) => c.Value.SDiffBytesAsync(k))); /// <summary> /// 返回给定所有集合的差集并存储在 destination 中 /// </summary> /// <param name="destination">新的无序集合,不含prefix前辍</param> /// <param name="keys">一个或多个无序集合,不含prefix前辍</param> /// <returns></returns> public Task<long> SDiffStoreAsync(string destination, params string[] keys) => NodesNotSupportAsync(new[] { destination }.Concat(keys).ToArray(), 0, (c, k) => c.Value.SDiffStoreAsync(k.First(), k.Skip(1).ToArray())); /// <summary> /// 返回给定所有集合的交集 /// </summary> /// <param name="keys">不含prefix前辍</param> /// <returns></returns> public Task<string[]> SInterAsync(params string[] keys) => NodesNotSupportAsync(keys, new string[0], (c, k) => c.Value.SInterAsync(k)); /// <summary> /// 返回给定所有集合的交集 /// </summary> /// <typeparam name="T">byte[] 或其他类型</typeparam> /// <param name="keys">不含prefix前辍</param> /// <returns></returns> async public Task<T[]> SInterAsync<T>(params string[] keys) => this.DeserializeRedisValueArrayInternal<T>(await NodesNotSupportAsync(keys, new byte[0][], (c, k) => c.Value.SInterBytesAsync(k))); /// <summary> /// 返回给定所有集合的交集并存储在 destination 中 /// </summary> /// <param name="destination">新的无序集合,不含prefix前辍</param> /// <param name="keys">一个或多个无序集合,不含prefix前辍</param> /// <returns></returns> public Task<long> SInterStoreAsync(string destination, params string[] keys) => NodesNotSupportAsync(new[] { destination }.Concat(keys).ToArray(), 0, (c, k) => c.Value.SInterStoreAsync(k.First(), k.Skip(1).ToArray())); /// <summary> /// 判断 member 元素是否是集合 key 的成员 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="member">成员</param> /// <returns></returns> public Task<bool> SIsMemberAsync(string key, object member) { var args = this.SerializeRedisValueInternal(member); return ExecuteScalarAsync(key, (c, k) => c.Value.SIsMemberAsync(k, args)); } /// <summary> /// 返回集合中的所有成员 /// </summary> /// <param name="key">不含prefix前辍</param> /// <returns></returns> public Task<string[]> SMembersAsync(string key) => ExecuteScalarAsync(key, (c, k) => c.Value.SMembersAsync(k)); /// <summary> /// 返回集合中的所有成员 /// </summary> /// <typeparam name="T">byte[] 或其他类型</typeparam> /// <param name="key">不含prefix前辍</param> /// <returns></returns> async public Task<T[]> SMembersAsync<T>(string key) => this.DeserializeRedisValueArrayInternal<T>(await ExecuteScalarAsync(key, (c, k) => c.Value.SMembersBytesAsync(k))); /// <summary> /// 将 member 元素从 source 集合移动到 destination 集合 /// </summary> /// <param name="source">无序集合key,不含prefix前辍</param> /// <param name="destination">目标无序集合key,不含prefix前辍</param> /// <param name="member">成员</param> /// <returns></returns> async public Task<bool> SMoveAsync(string source, string destination, object member) { string rule = string.Empty; if (Nodes.Count > 1) { var rule1 = NodeRuleRaw(source); var rule2 = NodeRuleRaw(destination); if (rule1 != rule2) { if (await SRemAsync(source, member) <= 0) return false; return await SAddAsync(destination, member) > 0; } rule = rule1; } var pool = Nodes.TryGetValue(rule, out var b) ? b : Nodes.First().Value; var key1 = string.Concat(pool.Prefix, source); var key2 = string.Concat(pool.Prefix, destination); var args = this.SerializeRedisValueInternal(member); return await GetAndExecuteAsync(pool, conn => conn.Value.SMoveAsync(key1, key2, args)); } /// <summary> /// 移除并返回集合中的一个随机元素 /// </summary> /// <param name="key">不含prefix前辍</param> /// <returns></returns> public Task<string> SPopAsync(string key) => ExecuteScalarAsync(key, (c, k) => c.Value.SPopAsync(k)); /// <summary> /// 移除并返回集合中的一个随机元素 /// </summary> /// <typeparam name="T">byte[] 或其他类型</typeparam> /// <param name="key">不含prefix前辍</param> /// <returns></returns> async public Task<T> SPopAsync<T>(string key) => this.DeserializeRedisValueInternal<T>(await ExecuteScalarAsync(key, (c, k) => c.Value.SPopBytesAsync(k))); /// <summary> /// [redis-server 3.2] 移除并返回集合中的一个或多个随机元素 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="count">移除并返回的个数</param> /// <returns></returns> public Task<string[]> SPopAsync(string key, long count) => ExecuteScalarAsync(key, (c, k) => c.Value.SPopAsync(k, count)); /// <summary> /// [redis-server 3.2] 移除并返回集合中的一个或多个随机元素 /// </summary> /// <typeparam name="T">byte[] 或其他类型</typeparam> /// <param name="key">不含prefix前辍</param> /// <param name="count">移除并返回的个数</param> /// <returns></returns> async public Task<T[]> SPopAsync<T>(string key, long count) => this.DeserializeRedisValueArrayInternal<T>(await ExecuteScalarAsync(key, (c, k) => c.Value.SPopBytesAsync(k, count))); /// <summary> /// 返回集合中的一个随机元素 /// </summary> /// <param name="key">不含prefix前辍</param> /// <returns></returns> public Task<string> SRandMemberAsync(string key) => ExecuteScalarAsync(key, (c, k) => c.Value.SRandMemberAsync(k)); /// <summary> /// 返回集合中的一个随机元素 /// </summary> /// <typeparam name="T">byte[] 或其他类型</typeparam> /// <param name="key">不含prefix前辍</param> /// <returns></returns> async public Task<T> SRandMemberAsync<T>(string key) => this.DeserializeRedisValueInternal<T>(await ExecuteScalarAsync(key, (c, k) => c.Value.SRandMemberBytesAsync(k))); /// <summary> /// 返回集合中一个或多个随机数的元素 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="count">返回个数</param> /// <returns></returns> public Task<string[]> SRandMembersAsync(string key, int count = 1) => ExecuteScalarAsync(key, (c, k) => c.Value.SRandMembersAsync(k, count)); /// <summary> /// 返回集合中一个或多个随机数的元素 /// </summary> /// <typeparam name="T">byte[] 或其他类型</typeparam> /// <param name="key">不含prefix前辍</param> /// <param name="count">返回个数</param> /// <returns></returns> async public Task<T[]> SRandMembersAsync<T>(string key, int count = 1) => this.DeserializeRedisValueArrayInternal<T>(await ExecuteScalarAsync(key, (c, k) => c.Value.SRandMembersBytesAsync(k, count))); /// <summary> /// 移除集合中一个或多个成员 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="members">一个或多个成员</param> /// <returns></returns> async public Task<long> SRemAsync<T>(string key, params T[] members) { if (members == null || members.Any() == false) return 0; var args = members.Select(z => this.SerializeRedisValueInternal(z)).ToArray(); return await ExecuteScalarAsync(key, (c, k) => c.Value.SRemAsync(k, args)); } /// <summary> /// 返回所有给定集合的并集 /// </summary> /// <param name="keys">不含prefix前辍</param> /// <returns></returns> public Task<string[]> SUnionAsync(params string[] keys) => NodesNotSupportAsync(keys, new string[0], (c, k) => c.Value.SUnionAsync(k)); /// <summary> /// 返回所有给定集合的并集 /// </summary> /// <typeparam name="T">byte[] 或其他类型</typeparam> /// <param name="keys">不含prefix前辍</param> /// <returns></returns> async public Task<T[]> SUnionAsync<T>(params string[] keys) => this.DeserializeRedisValueArrayInternal<T>(await NodesNotSupportAsync(keys, new byte[0][], (c, k) => c.Value.SUnionBytesAsync(k))); /// <summary> /// 所有给定集合的并集存储在 destination 集合中 /// </summary> /// <param name="destination">新的无序集合,不含prefix前辍</param> /// <param name="keys">一个或多个无序集合,不含prefix前辍</param> /// <returns></returns> public Task<long> SUnionStoreAsync(string destination, params string[] keys) => NodesNotSupportAsync(new[] { destination }.Concat(keys).ToArray(), 0, (c, k) => c.Value.SUnionStoreAsync(k.First(), k.Skip(1).ToArray())); /// <summary> /// 迭代集合中的元素 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="cursor">位置</param> /// <param name="pattern">模式</param> /// <param name="count">数量</param> /// <returns></returns> public Task<RedisScan<string>> SScanAsync(string key, long cursor, string pattern = null, long? count = null) => ExecuteScalarAsync(key, (c, k) => c.Value.SScanAsync(k, cursor, pattern, count)); /// <summary> /// 迭代集合中的元素 /// </summary> /// <typeparam name="T">byte[] 或其他类型</typeparam> /// <param name="key">不含prefix前辍</param> /// <param name="cursor">位置</param> /// <param name="pattern">模式</param> /// <param name="count">数量</param> /// <returns></returns> async public Task<RedisScan<T>> SScanAsync<T>(string key, long cursor, string pattern = null, long? count = null) { var scan = await ExecuteScalarAsync(key, (c, k) => c.Value.SScanBytesAsync(k, cursor, pattern, count)); return new RedisScan<T>(scan.Cursor, this.DeserializeRedisValueArrayInternal<T>(scan.Items)); } #endregion #region List /// <summary> /// 通过索引获取列表中的元素 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="index">索引</param> /// <returns></returns> public Task<string> LIndexAsync(string key, long index) => ExecuteScalarAsync(key, (c, k) => c.Value.LIndexAsync(k, index)); /// <summary> /// 通过索引获取列表中的元素 /// </summary> /// <typeparam name="T">byte[] 或其他类型</typeparam> /// <param name="key">不含prefix前辍</param> /// <param name="index">索引</param> /// <returns></returns> async public Task<T> LIndexAsync<T>(string key, long index) => this.DeserializeRedisValueInternal<T>(await ExecuteScalarAsync(key, (c, k) => c.Value.LIndexBytesAsync(k, index))); /// <summary> /// 在列表中的元素前面插入元素 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="pivot">列表的元素</param> /// <param name="value">新元素</param> /// <returns></returns> public Task<long> LInsertBeforeAsync(string key, object pivot, object value) { var args = this.SerializeRedisValueInternal(value); return ExecuteScalarAsync(key, (c, k) => c.Value.LInsertAsync(k, RedisInsert.Before, pivot, args)); } /// <summary> /// 在列表中的元素后面插入元素 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="pivot">列表的元素</param> /// <param name="value">新元素</param> /// <returns></returns> public Task<long> LInsertAfterAsync(string key, object pivot, object value) { var args = this.SerializeRedisValueInternal(value); return ExecuteScalarAsync(key, (c, k) => c.Value.LInsertAsync(k, RedisInsert.After, pivot, args)); } /// <summary> /// 获取列表长度 /// </summary> /// <param name="key">不含prefix前辍</param> /// <returns></returns> public Task<long> LLenAsync(string key) => ExecuteScalarAsync(key, (c, k) => c.Value.LLenAsync(k)); /// <summary> /// 移出并获取列表的第一个元素 /// </summary> /// <param name="key">不含prefix前辍</param> /// <returns></returns> public Task<string> LPopAsync(string key) => ExecuteScalarAsync(key, (c, k) => c.Value.LPopAsync(k)); /// <summary> /// 移出并获取列表的第一个元素 /// </summary> /// <typeparam name="T">byte[] 或其他类型</typeparam> /// <param name="key">不含prefix前辍</param> /// <returns></returns> async public Task<T> LPopAsync<T>(string key) => this.DeserializeRedisValueInternal<T>(await ExecuteScalarAsync(key, (c, k) => c.Value.LPopBytesAsync(k))); /// <summary> /// 将一个或多个值插入到列表头部 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="value">一个或多个值</param> /// <returns>执行 LPUSH 命令后,列表的长度</returns> async public Task<long> LPushAsync<T>(string key, params T[] value) { if (value == null || value.Any() == false) return 0; var args = value.Select(z => this.SerializeRedisValueInternal(z)).ToArray(); return await ExecuteScalarAsync(key, (c, k) => c.Value.LPushAsync(k, args)); } /// <summary> /// 将一个值插入到已存在的列表头部 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="value">值</param> /// <returns>执行 LPUSHX 命令后,列表的长度。</returns> public Task<long> LPushXAsync(string key, object value) { var args = this.SerializeRedisValueInternal(value); return ExecuteScalarAsync(key, (c, k) => c.Value.LPushXAsync(k, args)); } /// <summary> /// 获取列表指定范围内的元素 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="start">开始位置,0表示第一个元素,-1表示最后一个元素</param> /// <param name="stop">结束位置,0表示第一个元素,-1表示最后一个元素</param> /// <returns></returns> public Task<string[]> LRangeAsync(string key, long start, long stop) => ExecuteScalarAsync(key, (c, k) => c.Value.LRangeAsync(k, start, stop)); /// <summary> /// 获取列表指定范围内的元素 /// </summary> /// <typeparam name="T">byte[] 或其他类型</typeparam> /// <param name="key">不含prefix前辍</param> /// <param name="start">开始位置,0表示第一个元素,-1表示最后一个元素</param> /// <param name="stop">结束位置,0表示第一个元素,-1表示最后一个元素</param> /// <returns></returns> async public Task<T[]> LRangeAsync<T>(string key, long start, long stop) => this.DeserializeRedisValueArrayInternal<T>(await ExecuteScalarAsync(key, (c, k) => c.Value.LRangeBytesAsync(k, start, stop))); /// <summary> /// 根据参数 count 的值,移除列表中与参数 value 相等的元素 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="count">移除的数量,大于0时从表头删除数量count,小于0时从表尾删除数量-count,等于0移除所有</param> /// <param name="value">元素</param> /// <returns></returns> public Task<long> LRemAsync(string key, long count, object value) { var args = this.SerializeRedisValueInternal(value); return ExecuteScalarAsync(key, (c, k) => c.Value.LRemAsync(k, count, args)); } /// <summary> /// 通过索引设置列表元素的值 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="index">索引</param> /// <param name="value">值</param> /// <returns></returns> async public Task<bool> LSetAsync(string key, long index, object value) { var args = this.SerializeRedisValueInternal(value); return await ExecuteScalarAsync(key, (c, k) => c.Value.LSetAsync(k, index, args)) == "OK"; } /// <summary> /// 对一个列表进行修剪,让列表只保留指定区间内的元素,不在指定区间之内的元素都将被删除 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="start">开始位置,0表示第一个元素,-1表示最后一个元素</param> /// <param name="stop">结束位置,0表示第一个元素,-1表示最后一个元素</param> /// <returns></returns> public Task<bool> LTrimAsync(string key, long start, long stop) => ExecuteScalarAsync(key, async (c, k) => await c.Value.LTrimAsync(k, start, stop) == "OK"); /// <summary> /// 移除并获取列表最后一个元素 /// </summary> /// <param name="key">不含prefix前辍</param> /// <returns></returns> public Task<string> RPopAsync(string key) => ExecuteScalarAsync(key, (c, k) => c.Value.RPopAsync(k)); /// <summary> /// 移除并获取列表最后一个元素 /// </summary> /// <typeparam name="T">byte[] 或其他类型</typeparam> /// <param name="key">不含prefix前辍</param> /// <returns></returns> async public Task<T> RPopAsync<T>(string key) => this.DeserializeRedisValueInternal<T>(await ExecuteScalarAsync(key, (c, k) => c.Value.RPopBytesAsync(k))); /// <summary> /// 将列表 source 中的最后一个元素(尾元素)弹出,并返回给客户端。 /// 将 source 弹出的元素插入到列表 destination ,作为 destination 列表的的头元素。 /// </summary> /// <param name="source">源key,不含prefix前辍</param> /// <param name="destination">目标key,不含prefix前辍</param> /// <returns></returns> public Task<string> RPopLPushAsync(string source, string destination) => NodesNotSupportAsync(new[] { source, destination }, null, (c, k) => c.Value.RPopLPushAsync(k.First(), k.Last())); /// <summary> /// 将列表 source 中的最后一个元素(尾元素)弹出,并返回给客户端。 /// 将 source 弹出的元素插入到列表 destination ,作为 destination 列表的的头元素。 /// </summary> /// <typeparam name="T">byte[] 或其他类型</typeparam> /// <param name="source">源key,不含prefix前辍</param> /// <param name="destination">目标key,不含prefix前辍</param> /// <returns></returns> async public Task<T> RPopLPushAsync<T>(string source, string destination) => this.DeserializeRedisValueInternal<T>(await NodesNotSupportAsync(new[] { source, destination }, null, (c, k) => c.Value.RPopBytesLPushAsync(k.First(), k.Last()))); /// <summary> /// 在列表中添加一个或多个值 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="value">一个或多个值</param> /// <returns>执行 RPUSH 命令后,列表的长度</returns> async public Task<long> RPushAsync<T>(string key, params T[] value) { if (value == null || value.Any() == false) return 0; var args = value.Select(z => this.SerializeRedisValueInternal(z)).ToArray(); return await ExecuteScalarAsync(key, (c, k) => c.Value.RPushAsync(k, args)); } /// <summary> /// 为已存在的列表添加值 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="value">一个或多个值</param> /// <returns>执行 RPUSHX 命令后,列表的长度</returns> public Task<long> RPushXAsync(string key, object value) { var args = this.SerializeRedisValueInternal(value); return ExecuteScalarAsync(key, (c, k) => c.Value.RPushXAsync(k, args)); } #endregion #region Hash /// <summary> /// [redis-server 3.2.0] 返回hash指定field的value的字符串长度,如果hash或者field不存在,返回0. /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="field">字段</param> /// <returns></returns> public Task<long> HStrLenAsync(string key, string field) => ExecuteScalarAsync(key, (c, k) => c.Value.HStrLenAsync(k, field)); /// <summary> /// 删除一个或多个哈希表字段 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="fields">字段</param> /// <returns></returns> async public Task<long> HDelAsync(string key, params string[] fields) => fields == null || fields.Any() == false ? 0 : await ExecuteScalarAsync(key, (c, k) => c.Value.HDelAsync(k, fields)); /// <summary> /// 查看哈希表 key 中,指定的字段是否存在 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="field">字段</param> /// <returns></returns> public Task<bool> HExistsAsync(string key, string field) => ExecuteScalarAsync(key, (c, k) => c.Value.HExistsAsync(k, field)); /// <summary> /// 获取存储在哈希表中指定字段的值 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="field">字段</param> /// <returns></returns> public Task<string> HGetAsync(string key, string field) => ExecuteScalarAsync(key, (c, k) => c.Value.HGetAsync(k, field)); /// <summary> /// 获取存储在哈希表中指定字段的值 /// </summary> /// <typeparam name="T">byte[] 或其他类型</typeparam> /// <param name="key">不含prefix前辍</param> /// <param name="field">字段</param> /// <returns></returns> async public Task<T> HGetAsync<T>(string key, string field) => this.DeserializeRedisValueInternal<T>(await ExecuteScalarAsync(key, (c, k) => c.Value.HGetBytesAsync(k, field))); /// <summary> /// 获取在哈希表中指定 key 的所有字段和值 /// </summary> /// <param name="key">不含prefix前辍</param> /// <returns></returns> public Task<Dictionary<string, string>> HGetAllAsync(string key) => ExecuteScalarAsync(key, (c, k) => c.Value.HGetAllAsync(k)); /// <summary> /// 获取在哈希表中指定 key 的所有字段和值 /// </summary> /// <typeparam name="T">byte[] 或其他类型</typeparam> /// <param name="key">不含prefix前辍</param> /// <returns></returns> async public Task<Dictionary<string, T>> HGetAllAsync<T>(string key) => this.DeserializeRedisValueDictionaryInternal<string, T>(await ExecuteScalarAsync(key, (c, k) => c.Value.HGetAllBytesAsync(k))); /// <summary> /// 为哈希表 key 中的指定字段的整数值加上增量 increment /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="field">字段</param> /// <param name="value">增量值(默认=1)</param> /// <returns></returns> public Task<long> HIncrByAsync(string key, string field, long value = 1) => ExecuteScalarAsync(key, (c, k) => c.Value.HIncrByAsync(k, field, value)); /// <summary> /// 为哈希表 key 中的指定字段的整数值加上增量 increment /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="field">字段</param> /// <param name="value">增量值(默认=1)</param> /// <returns></returns> public Task<decimal> HIncrByFloatAsync(string key, string field, decimal value) => ExecuteScalarAsync(key, (c, k) => c.Value.HIncrByFloatAsync(k, field, value)); /// <summary> /// 获取所有哈希表中的字段 /// </summary> /// <param name="key">不含prefix前辍</param> /// <returns></returns> public Task<string[]> HKeysAsync(string key) => ExecuteScalarAsync(key, (c, k) => c.Value.HKeysAsync(k)); /// <summary> /// 获取哈希表中字段的数量 /// </summary> /// <param name="key">不含prefix前辍</param> /// <returns></returns> public Task<long> HLenAsync(string key) => ExecuteScalarAsync(key, (c, k) => c.Value.HLenAsync(k)); /// <summary> /// 获取存储在哈希表中多个字段的值 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="fields">字段</param> /// <returns></returns> async public Task<string[]> HMGetAsync(string key, params string[] fields) => fields == null || fields.Any() == false ? new string[0] : await ExecuteScalarAsync(key, (c, k) => c.Value.HMGetAsync(k, fields)); /// <summary> /// 获取存储在哈希表中多个字段的值 /// </summary> /// <typeparam name="T">byte[] 或其他类型</typeparam> /// <param name="key">不含prefix前辍</param> /// <param name="fields">一个或多个字段</param> /// <returns></returns> async public Task<T[]> HMGetAsync<T>(string key, params string[] fields) => fields == null || fields.Any() == false ? new T[0] : this.DeserializeRedisValueArrayInternal<T>(await ExecuteScalarAsync(key, (c, k) => c.Value.HMGetBytesAsync(k, fields))); /// <summary> /// 同时将多个 field-value (域-值)对设置到哈希表 key 中 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="keyValues">key1 value1 [key2 value2]</param> /// <returns></returns> async public Task<bool> HMSetAsync(string key, params object[] keyValues) { if (keyValues == null || keyValues.Any() == false) return false; if (keyValues.Length % 2 != 0) throw new Exception("keyValues 参数是键值对,不应该出现奇数(数量),请检查使用姿势。"); var parms = new List<object>(); for (var a = 0; a < keyValues.Length; a += 2) { var k = string.Concat(keyValues[a]); var v = keyValues[a + 1]; if (string.IsNullOrEmpty(k)) throw new Exception("keyValues 参数是键值对,并且 key 不可为空"); parms.Add(k); parms.Add(this.SerializeRedisValueInternal(v)); } return await ExecuteScalarAsync(key, (c, k) => c.Value.HMSetAsync(k, parms.ToArray())) == "OK"; } /// <summary> /// 将哈希表 key 中的字段 field 的值设为 value /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="field">字段</param> /// <param name="value">值</param> /// <returns>如果字段是哈希表中的一个新建字段,并且值设置成功,返回true。如果哈希表中域字段已经存在且旧值已被新值覆盖,返回false。</returns> public Task<bool> HSetAsync(string key, string field, object value) { var args = this.SerializeRedisValueInternal(value); return ExecuteScalarAsync(key, (c, k) => c.Value.HSetAsync(k, field, args)); } /// <summary> /// 只有在字段 field 不存在时,设置哈希表字段的值 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="field">字段</param> /// <param name="value">值(string 或 byte[])</param> /// <returns></returns> public Task<bool> HSetNxAsync(string key, string field, object value) { var args = this.SerializeRedisValueInternal(value); return ExecuteScalarAsync(key, (c, k) => c.Value.HSetNxAsync(k, field, args)); } /// <summary> /// 获取哈希表中所有值 /// </summary> /// <param name="key">不含prefix前辍</param> /// <returns></returns> public Task<string[]> HValsAsync(string key) => ExecuteScalarAsync(key, (c, k) => c.Value.HValsAsync(k)); /// <summary> /// 获取哈希表中所有值 /// </summary> /// <typeparam name="T">byte[] 或其他类型</typeparam> /// <param name="key">不含prefix前辍</param> /// <returns></returns> async public Task<T[]> HValsAsync<T>(string key) => this.DeserializeRedisValueArrayInternal<T>(await ExecuteScalarAsync(key, (c, k) => c.Value.HValsBytesAsync(k))); /// <summary> /// 迭代哈希表中的键值对 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="cursor">位置</param> /// <param name="pattern">模式</param> /// <param name="count">数量</param> /// <returns></returns> async public Task<RedisScan<(string field, string value)>> HScanAsync(string key, long cursor, string pattern = null, long? count = null) { var scan = await ExecuteScalarAsync(key, (c, k) => c.Value.HScanAsync(k, cursor, pattern, count)); return new RedisScan<(string, string)>(scan.Cursor, scan.Items.Select(z => (z.Item1, z.Item2)).ToArray()); } /// <summary> /// 迭代哈希表中的键值对 /// </summary> /// <typeparam name="T">byte[] 或其他类型</typeparam> /// <param name="key">不含prefix前辍</param> /// <param name="cursor">位置</param> /// <param name="pattern">模式</param> /// <param name="count">数量</param> /// <returns></returns> async public Task<RedisScan<(string field, T value)>> HScanAsync<T>(string key, long cursor, string pattern = null, long? count = null) { var scan = await ExecuteScalarAsync(key, (c, k) => c.Value.HScanBytesAsync(k, cursor, pattern, count)); return new RedisScan<(string, T)>(scan.Cursor, scan.Items.Select(z => (z.Item1, this.DeserializeRedisValueInternal<T>(z.Item2))).ToArray()); } #endregion #region String /// <summary> /// 如果 key 已经存在并且是一个字符串, APPEND 命令将指定的 value 追加到该 key 原来值(value)的末尾 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="value">字符串</param> /// <returns>追加指定值之后, key 中字符串的长度</returns> public Task<long> AppendAsync(string key, object value) { var args = this.SerializeRedisValueInternal(value); return ExecuteScalarAsync(key, (c, k) => c.Value.AppendAsync(k, args)); } /// <summary> /// 计算给定位置被设置为 1 的比特位的数量 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="start">开始位置</param> /// <param name="end">结束位置</param> /// <returns></returns> public Task<long> BitCountAsync(string key, long start, long end) => ExecuteScalarAsync(key, (c, k) => c.Value.BitCountAsync(k, start, end)); /// <summary> /// 对一个或多个保存二进制位的字符串 key 进行位元操作,并将结果保存到 destkey 上 /// </summary> /// <param name="op">And | Or | XOr | Not</param> /// <param name="destKey">不含prefix前辍</param> /// <param name="keys">不含prefix前辍</param> /// <returns>保存到 destkey 的长度,和输入 key 中最长的长度相等</returns> async public Task<long> BitOpAsync(RedisBitOp op, string destKey, params string[] keys) { if (string.IsNullOrEmpty(destKey)) throw new Exception("destKey 不能为空"); if (keys == null || keys.Length == 0) throw new Exception("keys 不能为空"); return await NodesNotSupportAsync(new[] { destKey }.Concat(keys).ToArray(), 0, (c, k) => c.Value.BitOpAsync(op, k.First(), k.Skip(1).ToArray())); } /// <summary> /// 对 key 所储存的值,查找范围内第一个被设置为1或者0的bit位 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="bit">查找值</param> /// <param name="start">开始位置,-1是最后一个,-2是倒数第二个</param> /// <param name="end">结果位置,-1是最后一个,-2是倒数第二个</param> /// <returns>返回范围内第一个被设置为1或者0的bit位</returns> public Task<long> BitPosAsync(string key, bool bit, long? start = null, long? end = null) => ExecuteScalarAsync(key, (c, k) => c.Value.BitPosAsync(k, bit, start, end)); /// <summary> /// 获取指定 key 的值 /// </summary> /// <param name="key">不含prefix前辍</param> /// <returns></returns> public Task<string> GetAsync(string key) => ExecuteScalarAsync(key, (c, k) => c.Value.GetAsync(k)); /// <summary> /// 获取指定 key 的值 /// </summary> /// <typeparam name="T">byte[] 或其他类型</typeparam> /// <param name="key">不含prefix前辍</param> /// <returns></returns> async public Task<T> GetAsync<T>(string key) => this.DeserializeRedisValueInternal<T>(await ExecuteScalarAsync(key, (c, k) => c.Value.GetBytesAsync(k))); /// <summary> /// 对 key 所储存的值,获取指定偏移量上的位(bit) /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="offset">偏移量</param> /// <returns></returns> public Task<bool> GetBitAsync(string key, uint offset) => ExecuteScalarAsync(key, (c, k) => c.Value.GetBitAsync(k, offset)); /// <summary> /// 返回 key 中字符串值的子字符 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="start">开始位置,0表示第一个元素,-1表示最后一个元素</param> /// <param name="end">结束位置,0表示第一个元素,-1表示最后一个元素</param> /// <returns></returns> public Task<string> GetRangeAsync(string key, long start, long end) => ExecuteScalarAsync(key, (c, k) => c.Value.GetRangeAsync(k, start, end)); /// <summary> /// 返回 key 中字符串值的子字符 /// </summary> /// <typeparam name="T">byte[] 或其他类型</typeparam> /// <param name="key">不含prefix前辍</param> /// <param name="start">开始位置,0表示第一个元素,-1表示最后一个元素</param> /// <param name="end">结束位置,0表示第一个元素,-1表示最后一个元素</param> /// <returns></returns> async public Task<T> GetRangeAsync<T>(string key, long start, long end) => this.DeserializeRedisValueInternal<T>(await ExecuteScalarAsync(key, (c, k) => c.Value.GetRangeBytesAsync(k, start, end))); /// <summary> /// 将给定 key 的值设为 value ,并返回 key 的旧值(old value) /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="value">值</param> /// <returns></returns> public Task<string> GetSetAsync(string key, object value) { var args = this.SerializeRedisValueInternal(value); return ExecuteScalarAsync(key, (c, k) => c.Value.GetSetAsync(k, args)); } /// <summary> /// 将给定 key 的值设为 value ,并返回 key 的旧值(old value) /// </summary> /// <typeparam name="T">byte[] 或其他类型</typeparam> /// <param name="key">不含prefix前辍</param> /// <param name="value">值</param> /// <returns></returns> async public Task<T> GetSetAsync<T>(string key, object value) { var args = this.SerializeRedisValueInternal(value); return this.DeserializeRedisValueInternal<T>(await ExecuteScalarAsync(key, (c, k) => c.Value.GetSetBytesAsync(k, args))); } /// <summary> /// 将 key 所储存的值加上给定的增量值(increment) /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="value">增量值(默认=1)</param> /// <returns></returns> public Task<long> IncrByAsync(string key, long value = 1) => ExecuteScalarAsync(key, (c, k) => c.Value.IncrByAsync(k, value)); /// <summary> /// 将 key 所储存的值加上给定的浮点增量值(increment) /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="value">增量值(默认=1)</param> /// <returns></returns> public Task<decimal> IncrByFloatAsync(string key, decimal value) => ExecuteScalarAsync(key, (c, k) => c.Value.IncrByFloatAsync(k, value)); /// <summary> /// 获取多个指定 key 的值(数组) /// </summary> /// <param name="keys">不含prefix前辍</param> /// <returns></returns> public Task<string[]> MGetAsync(params string[] keys) => ExecuteArrayAsync(keys, (c, k) => c.Value.MGetAsync(k)); /// <summary> /// 获取多个指定 key 的值(数组) /// </summary> /// <typeparam name="T">byte[] 或其他类型</typeparam> /// <param name="keys">不含prefix前辍</param> /// <returns></returns> async public Task<T[]> MGetAsync<T>(params string[] keys) => this.DeserializeRedisValueArrayInternal<T>(await ExecuteArrayAsync(keys, (c, k) => c.Value.MGetBytesAsync(k))); /// <summary> /// 同时设置一个或多个 key-value 对 /// </summary> /// <param name="keyValues">key1 value1 [key2 value2]</param> /// <returns></returns> public Task<bool> MSetAsync(params object[] keyValues) => MSetInternalAsync(RedisExistence.Xx, keyValues); /// <summary> /// 同时设置一个或多个 key-value 对,当且仅当所有给定 key 都不存在 /// </summary> /// <param name="keyValues">key1 value1 [key2 value2]</param> /// <returns></returns> public Task<bool> MSetNxAsync(params object[] keyValues) => MSetInternalAsync(RedisExistence.Nx, keyValues); async internal Task<bool> MSetInternalAsync(RedisExistence exists, params object[] keyValues) { if (keyValues == null || keyValues.Any() == false) return false; if (keyValues.Length % 2 != 0) throw new Exception("keyValues 参数是键值对,不应该出现奇数(数量),请检查使用姿势。"); var dic = new Dictionary<string, object>(); for (var a = 0; a < keyValues.Length; a += 2) { var k = string.Concat(keyValues[a]); var v = this.SerializeRedisValueInternal(keyValues[a + 1]); if (string.IsNullOrEmpty(k)) throw new Exception("keyValues 参数是键值对,并且 key 不可为空"); if (dic.ContainsKey(k)) dic[k] = v; else dic.Add(k, v); } Func<Object<RedisClient>, string[], Task<long>> handle = async (c, k) => { var prefix = (c.Pool as RedisClientPool)?.Prefix; var parms = new object[k.Length * 2]; for (var a = 0; a < k.Length; a++) { parms[a * 2] = k[a]; parms[a * 2 + 1] = dic[string.IsNullOrEmpty(prefix) ? k[a] : k[a].Substring(prefix.Length)]; } if (exists == RedisExistence.Nx) return await c.Value.MSetNxAsync(parms) ? 1 : 0; return await c.Value.MSetAsync(parms) == "OK" ? 1 : 0; }; if (exists == RedisExistence.Nx) return await NodesNotSupportAsync(dic.Keys.ToArray(), 0, handle) > 0; return await ExecuteNonQueryAsync(dic.Keys.ToArray(), handle) > 0; } /// <summary> /// 设置指定 key 的值,所有写入参数object都支持string | byte[] | 数值 | 对象 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="value">值</param> /// <param name="expireSeconds">过期(秒单位)</param> /// <param name="exists">Nx, Xx</param> /// <returns></returns> async public Task<bool> SetAsync(string key, object value, int expireSeconds = -1, RedisExistence? exists = null) { object redisValule = this.SerializeRedisValueInternal(value); if (expireSeconds <= 0 && exists == null) return await ExecuteScalarAsync(key, (c, k) => c.Value.SetAsync(k, redisValule)) == "OK"; if (expireSeconds <= 0 && exists != null) return await ExecuteScalarAsync(key, (c, k) => c.Value.SetAsync(k, redisValule, null, exists)) == "OK"; if (expireSeconds > 0 && exists == null) return await ExecuteScalarAsync(key, (c, k) => c.Value.SetAsync(k, redisValule, expireSeconds, null)) == "OK"; if (expireSeconds > 0 && exists != null) return await ExecuteScalarAsync(key, (c, k) => c.Value.SetAsync(k, redisValule, expireSeconds, exists)) == "OK"; return false; } async public Task<bool> SetAsync(string key, object value, TimeSpan expire, RedisExistence? exists = null) { object redisValule = this.SerializeRedisValueInternal(value); if (expire <= TimeSpan.Zero && exists == null) return await ExecuteScalarAsync(key, (c, k) => c.Value.SetAsync(k, redisValule)) == "OK"; if (expire <= TimeSpan.Zero && exists != null) return await ExecuteScalarAsync(key, (c, k) => c.Value.SetAsync(k, redisValule, null, exists)) == "OK"; if (expire > TimeSpan.Zero && exists == null) return await ExecuteScalarAsync(key, (c, k) => c.Value.SetAsync(k, redisValule, expire, null)) == "OK"; if (expire > TimeSpan.Zero && exists != null) return await ExecuteScalarAsync(key, (c, k) => c.Value.SetAsync(k, redisValule, expire, exists)) == "OK"; return false; } /// <summary> /// 对 key 所储存的字符串值,设置或清除指定偏移量上的位(bit) /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="offset">偏移量</param> /// <param name="value">值</param> /// <returns></returns> public Task<bool> SetBitAsync(string key, uint offset, bool value) => ExecuteScalarAsync(key, (c, k) => c.Value.SetBitAsync(k, offset, value)); /// <summary> /// 只有在 key 不存在时设置 key 的值 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="value">值</param> /// <returns></returns> public Task<bool> SetNxAsync(string key, object value) { var args = this.SerializeRedisValueInternal(value); return ExecuteScalarAsync(key, (c, k) => c.Value.SetNxAsync(k, args)); } /// <summary> /// 用 value 参数覆写给定 key 所储存的字符串值,从偏移量 offset 开始 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="offset">偏移量</param> /// <param name="value">值</param> /// <returns>被修改后的字符串长度</returns> public Task<long> SetRangeAsync(string key, uint offset, object value) { var args = this.SerializeRedisValueInternal(value); return ExecuteScalarAsync(key, (c, k) => c.Value.SetRangeAsync(k, offset, args)); } /// <summary> /// 返回 key 所储存的字符串值的长度 /// </summary> /// <param name="key">不含prefix前辍</param> /// <returns></returns> public Task<long> StrLenAsync(string key) => ExecuteScalarAsync(key, (c, k) => c.Value.StrLenAsync(k)); #endregion #region Key /// <summary> /// [redis-server 3.2.1] 修改指定key(s) 最后访问时间 若key不存在,不做操作 /// </summary> /// <param name="key">不含prefix前辍</param> /// <returns></returns> public Task<long> TouchAsync(params string[] key) => ExecuteNonQueryAsync(key, (c, k) => c.Value.TouchAsync(k)); /// <summary> /// [redis-server 4.0.0] Delete a key, 该命令和DEL十分相似:删除指定的key(s),若key不存在则该key被跳过。但是,相比DEL会产生阻塞,该命令会在另一个线程中回收内存,因此它是非阻塞的。 这也是该命令名字的由来:仅将keys从keyspace元数据中删除,真正的删除会在后续异步操作。 /// </summary> /// <param name="key">不含prefix前辍</param> /// <returns></returns> public Task<long> UnLinkAsync(params string[] key) => ExecuteNonQueryAsync(key, (c, k) => c.Value.UnLinkAsync(k)); /// <summary> /// 用于在 key 存在时删除 key /// </summary> /// <param name="key">不含prefix前辍</param> /// <returns></returns> public Task<long> DelAsync(params string[] key) => ExecuteNonQueryAsync(key, (c, k) => c.Value.DelAsync(k)); /// <summary> /// 序列化给定 key ,并返回被序列化的值 /// </summary> /// <param name="key">不含prefix前辍</param> /// <returns></returns> public Task<byte[]> DumpAsync(string key) => ExecuteScalarAsync(key, (c, k) => c.Value.DumpAsync(k)); /// <summary> /// 检查给定 key 是否存在 /// </summary> /// <param name="key">不含prefix前辍</param> /// <returns></returns> public Task<bool> ExistsAsync(string key) => ExecuteScalarAsync(key, (c, k) => c.Value.ExistsAsync(k)); /// <summary> /// [redis-server 3.0] 检查给定多个 key 是否存在 /// </summary> /// <param name="keys">不含prefix前辍</param> /// <returns></returns> public Task<long> ExistsAsync(string[] keys) => NodesNotSupportAsync(keys, 0, (c, k) => c.Value.ExistsAsync(k)); /// <summary> /// 为给定 key 设置过期时间 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="seconds">过期秒数</param> /// <returns></returns> public Task<bool> ExpireAsync(string key, int seconds) => ExecuteScalarAsync(key, (c, k) => c.Value.ExpireAsync(k, seconds)); /// <summary> /// 为给定 key 设置过期时间 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="expire">过期时间</param> /// <returns></returns> public Task<bool> ExpireAsync(string key, TimeSpan expire) => ExecuteScalarAsync(key, (c, k) => c.Value.ExpireAsync(k, expire)); /// <summary> /// 为给定 key 设置过期时间 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="expire">过期时间</param> /// <returns></returns> public Task<bool> ExpireAtAsync(string key, DateTime expire) => ExecuteScalarAsync(key, (c, k) => c.Value.ExpireAtAsync(k, expire)); /// <summary> /// 查找所有分区节点中符合给定模式(pattern)的 key /// </summary> /// <param name="pattern">如:runoob*</param> /// <returns></returns> async public Task<string[]> KeysAsync(string pattern) { List<string> ret = new List<string>(); foreach (var pool in Nodes) ret.AddRange(await GetAndExecuteAsync(pool.Value, conn => conn.Value.KeysAsync(pattern))); return ret.ToArray(); } /// <summary> /// 将当前数据库的 key 移动到给定的数据库 db 当中 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="database">数据库</param> /// <returns></returns> public Task<bool> MoveAsync(string key, int database) => ExecuteScalarAsync(key, (c, k) => c.Value.MoveAsync(k, database)); /// <summary> /// 该返回给定 key 锁储存的值所使用的内部表示(representation) /// </summary> /// <param name="key">不含prefix前辍</param> /// <returns></returns> public Task<string> ObjectEncodingAsync(string key) => ExecuteScalarAsync(key, (c, k) => c.Value.ObjectEncodingAsync(k)); /// <summary> /// 该返回给定 key 引用所储存的值的次数。此命令主要用于除错 /// </summary> /// <param name="key">不含prefix前辍</param> /// <returns></returns> public Task<long?> ObjectRefCountAsync(string key) => ExecuteScalarAsync(key, (c, k) => c.Value.ObjectAsync(RedisObjectSubCommand.RefCount, k)); /// <summary> /// 返回给定 key 自储存以来的空转时间(idle, 没有被读取也没有被写入),以秒为单位 /// </summary> /// <param name="key">不含prefix前辍</param> /// <returns></returns> public Task<long?> ObjectIdleTimeAsync(string key) => ExecuteScalarAsync(key, (c, k) => c.Value.ObjectAsync(RedisObjectSubCommand.IdleTime, k)); /// <summary> /// 移除 key 的过期时间,key 将持久保持 /// </summary> /// <param name="key">不含prefix前辍</param> /// <returns></returns> public Task<bool> PersistAsync(string key) => ExecuteScalarAsync(key, (c, k) => c.Value.PersistAsync(k)); /// <summary> /// 为给定 key 设置过期时间(毫秒) /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="milliseconds">过期毫秒数</param> /// <returns></returns> public Task<bool> PExpireAsync(string key, int milliseconds) => ExecuteScalarAsync(key, (c, k) => c.Value.PExpireAsync(k, milliseconds)); /// <summary> /// 为给定 key 设置过期时间(毫秒) /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="expire">过期时间</param> /// <returns></returns> public Task<bool> PExpireAsync(string key, TimeSpan expire) => ExecuteScalarAsync(key, (c, k) => c.Value.PExpireAsync(k, expire)); /// <summary> /// 为给定 key 设置过期时间(毫秒) /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="expire">过期时间</param> /// <returns></returns> public Task<bool> PExpireAtAsync(string key, DateTime expire) => ExecuteScalarAsync(key, (c, k) => c.Value.PExpireAtAsync(k, expire)); /// <summary> /// 以毫秒为单位返回 key 的剩余的过期时间 /// </summary> /// <param name="key">不含prefix前辍</param> /// <returns></returns> public Task<long> PTtlAsync(string key) => ExecuteScalarAsync(key, (c, k) => c.Value.PTtlAsync(k)); /// <summary> /// 从所有节点中随机返回一个 key /// </summary> /// <returns>返回的 key 如果包含 prefix前辍,则会去除后返回</returns> public Task<string> RandomKeyAsync() => GetAndExecuteAsync(Nodes[NodesIndex[_rnd.Next(0, NodesIndex.Count)]], async c => { var rk = await c.Value.RandomKeyAsync(); var prefix = (c.Pool as RedisClientPool).Prefix; if (string.IsNullOrEmpty(prefix) == false && rk.StartsWith(prefix)) return rk.Substring(prefix.Length); return rk; }); /// <summary> /// 修改 key 的名称 /// </summary> /// <param name="key">旧名称,不含prefix前辍</param> /// <param name="newKey">新名称,不含prefix前辍</param> /// <returns></returns> async public Task<bool> RenameAsync(string key, string newKey) { string rule = string.Empty; if (Nodes.Count > 1) { var rule1 = NodeRuleRaw(key); var rule2 = NodeRuleRaw(newKey); if (rule1 != rule2) { var ret = StartPipe(a => a.Dump(key).Del(key)); int.TryParse(ret[1]?.ToString(), NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out var tryint); if (ret[0] == null || tryint <= 0) return false; return await RestoreAsync(newKey, (byte[])ret[0]); } rule = rule1; } var pool = Nodes.TryGetValue(rule, out var b) ? b : Nodes.First().Value; var key1 = string.Concat(pool.Prefix, key); var key2 = string.Concat(pool.Prefix, newKey); return await GetAndExecuteAsync(pool, conn => conn.Value.RenameAsync(key1, key2)) == "OK"; } /// <summary> /// 修改 key 的名称 /// </summary> /// <param name="key">旧名称,不含prefix前辍</param> /// <param name="newKey">新名称,不含prefix前辍</param> /// <returns></returns> public Task<bool> RenameNxAsync(string key, string newKey) => NodesNotSupportAsync(new[] { key, newKey }, false, (c, k) => c.Value.RenameNxAsync(k.First(), k.Last())); /// <summary> /// 反序列化给定的序列化值,并将它和给定的 key 关联 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="serializedValue">序列化值</param> /// <returns></returns> public Task<bool> RestoreAsync(string key, byte[] serializedValue) => ExecuteScalarAsync(key, async (c, k) => await c.Value.RestoreAsync(k, 0, serializedValue) == "OK"); /// <summary> /// 反序列化给定的序列化值,并将它和给定的 key 关联 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="ttlMilliseconds">毫秒为单位为 key 设置生存时间</param> /// <param name="serializedValue">序列化值</param> /// <returns></returns> public Task<bool> RestoreAsync(string key, long ttlMilliseconds, byte[] serializedValue) => ExecuteScalarAsync(key, async (c, k) => await c.Value.RestoreAsync(k, ttlMilliseconds, serializedValue) == "OK"); /// <summary> /// 返回给定列表、集合、有序集合 key 中经过排序的元素,参数资料:http://doc.redisfans.com/key/sort.html /// </summary> /// <param name="key">列表、集合、有序集合,不含prefix前辍</param> /// <param name="offset">偏移量</param> /// <param name="count">数量</param> /// <param name="by">排序字段</param> /// <param name="dir">排序方式</param> /// <param name="isAlpha">对字符串或数字进行排序</param> /// <param name="get">根据排序的结果来取出相应的键值</param> /// <returns></returns> public Task<string[]> SortAsync(string key, long? count = null, long offset = 0, string by = null, RedisSortDir? dir = null, bool? isAlpha = null, params string[] get) => NodesNotSupportAsync(key, (c, k) => c.Value.SortAsync(k, offset, count, by, dir, isAlpha, get)); /// <summary> /// 保存给定列表、集合、有序集合 key 中经过排序的元素,参数资料:http://doc.redisfans.com/key/sort.html /// </summary> /// <param name="key">列表、集合、有序集合,不含prefix前辍</param> /// <param name="destination">目标key,不含prefix前辍</param> /// <param name="offset">偏移量</param> /// <param name="count">数量</param> /// <param name="by">排序字段</param> /// <param name="dir">排序方式</param> /// <param name="isAlpha">对字符串或数字进行排序</param> /// <param name="get">根据排序的结果来取出相应的键值</param> /// <returns></returns> public Task<long> SortAndStoreAsync(string key, string destination, long? count = null, long offset = 0, string by = null, RedisSortDir? dir = null, bool? isAlpha = null, params string[] get) => NodesNotSupportAsync(key, (c, k) => c.Value.SortAndStoreAsync(k, (c.Pool as RedisClientPool)?.Prefix + destination, offset, count, by, dir, isAlpha, get)); /// <summary> /// 以秒为单位,返回给定 key 的剩余生存时间 /// </summary> /// <param name="key">不含prefix前辍</param> /// <returns></returns> public Task<long> TtlAsync(string key) => ExecuteScalarAsync(key, (c, k) => c.Value.TtlAsync(k)); /// <summary> /// 返回 key 所储存的值的类型 /// </summary> /// <param name="key">不含prefix前辍</param> /// <returns></returns> async public Task<KeyType> TypeAsync(string key) => Enum.TryParse(await ExecuteScalarAsync(key, (c, k) => c.Value.TypeAsync(k)), true, out KeyType tryenum) ? tryenum : KeyType.None; /// <summary> /// 迭代当前数据库中的数据库键 /// </summary> /// <param name="cursor">位置</param> /// <param name="pattern">模式</param> /// <param name="count">数量</param> /// <returns></returns> public Task<RedisScan<string>> ScanAsync(long cursor, string pattern = null, long? count = null) => NodesNotSupportAsync("ScanAsync", (c, k) => c.Value.ScanAsync(cursor, pattern, count)); /// <summary> /// 迭代当前数据库中的数据库键 /// </summary> /// <typeparam name="T">byte[] 或其他类型</typeparam> /// <param name="cursor">位置</param> /// <param name="pattern">模式</param> /// <param name="count">数量</param> /// <returns></returns> async public Task<RedisScan<T>> ScanAsync<T>(long cursor, string pattern = null, long? count = null) { var scan = await NodesNotSupportAsync("ScanAsync<T>", (c, k) => c.Value.ScanBytesAsync(cursor, pattern, count)); return new RedisScan<T>(scan.Cursor, this.DeserializeRedisValueArrayInternal<T>(scan.Items)); } #endregion #region Geo redis-server 3.2 /// <summary> /// 将指定的地理空间位置(纬度、经度、成员)添加到指定的key中。这些数据将会存储到sorted set这样的目的是为了方便使用GEORADIUS或者GEORADIUSBYMEMBER命令对数据进行半径查询等操作。 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="longitude">经度</param> /// <param name="latitude">纬度</param> /// <param name="member">成员</param> /// <returns>是否成功</returns> async public Task<bool> GeoAddAsync(string key, decimal longitude, decimal latitude, object member) => await GeoAddAsync(key, (longitude, latitude, member)) == 1; /// <summary> /// 将指定的地理空间位置(纬度、经度、成员)添加到指定的key中。这些数据将会存储到sorted set这样的目的是为了方便使用GEORADIUS或者GEORADIUSBYMEMBER命令对数据进行半径查询等操作。 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="values">批量添加的值</param> /// <returns>添加到sorted set元素的数目,但不包括已更新score的元素。</returns> async public Task<long> GeoAddAsync(string key, params (decimal longitude, decimal latitude, object member)[] values) { if (values == null || values.Any() == false) return 0; var args = values.Select(z => (z.longitude, z.latitude, this.SerializeRedisValueInternal(z.member))).ToArray(); return await ExecuteScalarAsync(key, (c, k) => c.Value.GeoAddAsync(k, args)); } /// <summary> /// 返回两个给定位置之间的距离。如果两个位置之间的其中一个不存在, 那么命令返回空值。GEODIST 命令在计算距离时会假设地球为完美的球形, 在极限情况下, 这一假设最大会造成 0.5% 的误差。 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="member1">成员1</param> /// <param name="member2">成员2</param> /// <param name="unit">m 表示单位为米;km 表示单位为千米;mi 表示单位为英里;ft 表示单位为英尺;</param> /// <returns>计算出的距离会以双精度浮点数的形式被返回。 如果给定的位置元素不存在, 那么命令返回空值。</returns> public Task<decimal?> GeoDistAsync(string key, object member1, object member2, GeoUnit unit = GeoUnit.m) { var args1 = this.SerializeRedisValueInternal(member1); var args2 = this.SerializeRedisValueInternal(member2); return ExecuteScalarAsync(key, (c, k) => c.Value.GeoDistAsync(k, args1, args2, unit)); } /// <summary> /// 返回一个或多个位置元素的 Geohash 表示。通常使用表示位置的元素使用不同的技术,使用Geohash位置52点整数编码。由于编码和解码过程中所使用的初始最小和最大坐标不同,编码的编码也不同于标准。 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="members">多个查询的成员</param> /// <returns>一个数组, 数组的每个项都是一个 geohash 。 命令返回的 geohash 的位置与用户给定的位置元素的位置一一对应。</returns> async public Task<string[]> GeoHashAsync(string key, object[] members) { if (members == null || members.Any() == false) return new string[0]; var args = members.Select(z => this.SerializeRedisValueInternal(z)).ToArray(); return await ExecuteScalarAsync(key, (c, k) => c.Value.GeoHashAsync(k, args)); } /// <summary> /// 从key里返回所有给定位置元素的位置(经度和纬度)。 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="members">多个查询的成员</param> /// <returns>GEOPOS 命令返回一个数组, 数组中的每个项都由两个元素组成: 第一个元素为给定位置元素的经度, 而第二个元素则为给定位置元素的纬度。当给定的位置元素不存在时, 对应的数组项为空值。</returns> async public Task<(decimal longitude, decimal latitude)?[]> GeoPosAsync(string key, object[] members) { if (members == null || members.Any() == false) return new (decimal, decimal)?[0]; var args = members.Select(z => this.SerializeRedisValueInternal(z)).ToArray(); return await ExecuteScalarAsync(key, (c, k) => c.Value.GeoPosAsync(k, args)); } /// <summary> /// 以给定的经纬度为中心, 返回键包含的位置元素当中, 与中心的距离不超过给定最大距离的所有位置元素。 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="longitude">经度</param> /// <param name="latitude">纬度</param> /// <param name="radius">距离</param> /// <param name="unit">m 表示单位为米;km 表示单位为千米;mi 表示单位为英里;ft 表示单位为英尺;</param> /// <param name="count">虽然用户可以使用 COUNT 选项去获取前 N 个匹配元素, 但是因为命令在内部可能会需要对所有被匹配的元素进行处理, 所以在对一个非常大的区域进行搜索时, 即使只使用 COUNT 选项去获取少量元素, 命令的执行速度也可能会非常慢。 但是从另一方面来说, 使用 COUNT 选项去减少需要返回的元素数量, 对于减少带宽来说仍然是非常有用的。</param> /// <param name="sorting">排序</param> /// <returns></returns> async public Task<string[]> GeoRadiusAsync(string key, decimal longitude, decimal latitude, decimal radius, GeoUnit unit = GeoUnit.m, long? count = null, GeoOrderBy? sorting = null) => (await ExecuteScalarAsync(key, (c, k) => c.Value.GeoRadiusAsync(k, longitude, latitude, radius, unit, count, sorting, false, false, false))).Select(a => a.member).ToArray(); /// <summary> /// 以给定的经纬度为中心, 返回键包含的位置元素当中, 与中心的距离不超过给定最大距离的所有位置元素。 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="longitude">经度</param> /// <param name="latitude">纬度</param> /// <param name="radius">距离</param> /// <param name="unit">m 表示单位为米;km 表示单位为千米;mi 表示单位为英里;ft 表示单位为英尺;</param> /// <param name="count">虽然用户可以使用 COUNT 选项去获取前 N 个匹配元素, 但是因为命令在内部可能会需要对所有被匹配的元素进行处理, 所以在对一个非常大的区域进行搜索时, 即使只使用 COUNT 选项去获取少量元素, 命令的执行速度也可能会非常慢。 但是从另一方面来说, 使用 COUNT 选项去减少需要返回的元素数量, 对于减少带宽来说仍然是非常有用的。</param> /// <param name="sorting">排序</param> /// <returns></returns> async public Task<T[]> GeoRadiusAsync<T>(string key, decimal longitude, decimal latitude, decimal radius, GeoUnit unit = GeoUnit.m, long? count = null, GeoOrderBy? sorting = null) => (await ExecuteScalarAsync(key, (c, k) => c.Value.GeoRadiusBytesAsync(k, longitude, latitude, radius, unit, count, sorting, false, false, false))).Select(a => this.DeserializeRedisValueInternal<T>(a.member)).ToArray(); /// <summary> /// 以给定的经纬度为中心, 返回键包含的位置元素当中, 与中心的距离不超过给定最大距离的所有位置元素(包含距离)。 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="longitude">经度</param> /// <param name="latitude">纬度</param> /// <param name="radius">距离</param> /// <param name="unit">m 表示单位为米;km 表示单位为千米;mi 表示单位为英里;ft 表示单位为英尺;</param> /// <param name="count">虽然用户可以使用 COUNT 选项去获取前 N 个匹配元素, 但是因为命令在内部可能会需要对所有被匹配的元素进行处理, 所以在对一个非常大的区域进行搜索时, 即使只使用 COUNT 选项去获取少量元素, 命令的执行速度也可能会非常慢。 但是从另一方面来说, 使用 COUNT 选项去减少需要返回的元素数量, 对于减少带宽来说仍然是非常有用的。</param> /// <param name="sorting">排序</param> /// <returns></returns> async public Task<(string member, decimal dist)[]> GeoRadiusWithDistAsync(string key, decimal longitude, decimal latitude, decimal radius, GeoUnit unit = GeoUnit.m, long? count = null, GeoOrderBy? sorting = null) => (await ExecuteScalarAsync(key, (c, k) => c.Value.GeoRadiusAsync(k, longitude, latitude, radius, unit, count, sorting, false, true, false))).Select(a => (a.member, a.dist)).ToArray(); /// <summary> /// 以给定的经纬度为中心, 返回键包含的位置元素当中, 与中心的距离不超过给定最大距离的所有位置元素(包含距离)。 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="longitude">经度</param> /// <param name="latitude">纬度</param> /// <param name="radius">距离</param> /// <param name="unit">m 表示单位为米;km 表示单位为千米;mi 表示单位为英里;ft 表示单位为英尺;</param> /// <param name="count">虽然用户可以使用 COUNT 选项去获取前 N 个匹配元素, 但是因为命令在内部可能会需要对所有被匹配的元素进行处理, 所以在对一个非常大的区域进行搜索时, 即使只使用 COUNT 选项去获取少量元素, 命令的执行速度也可能会非常慢。 但是从另一方面来说, 使用 COUNT 选项去减少需要返回的元素数量, 对于减少带宽来说仍然是非常有用的。</param> /// <param name="sorting">排序</param> /// <returns></returns> async public Task<(T member, decimal dist)[]> GeoRadiusWithDistAsync<T>(string key, decimal longitude, decimal latitude, decimal radius, GeoUnit unit = GeoUnit.m, long? count = null, GeoOrderBy? sorting = null) => (await ExecuteScalarAsync(key, (c, k) => c.Value.GeoRadiusBytesAsync(k, longitude, latitude, radius, unit, count, sorting, false, true, false))).Select(a => (this.DeserializeRedisValueInternal<T>(a.member), a.dist)).ToArray(); /// <summary> /// 以给定的经纬度为中心, 返回键包含的位置元素当中, 与中心的距离不超过给定最大距离的所有位置元素(包含经度、纬度)。 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="longitude">经度</param> /// <param name="latitude">纬度</param> /// <param name="radius">距离</param> /// <param name="unit">m 表示单位为米;km 表示单位为千米;mi 表示单位为英里;ft 表示单位为英尺;</param> /// <param name="count">虽然用户可以使用 COUNT 选项去获取前 N 个匹配元素, 但是因为命令在内部可能会需要对所有被匹配的元素进行处理, 所以在对一个非常大的区域进行搜索时, 即使只使用 COUNT 选项去获取少量元素, 命令的执行速度也可能会非常慢。 但是从另一方面来说, 使用 COUNT 选项去减少需要返回的元素数量, 对于减少带宽来说仍然是非常有用的。</param> /// <param name="sorting">排序</param> /// <returns></returns> async private Task<(string member, decimal longitude, decimal latitude)[]> GeoRadiusWithCoordAsync(string key, decimal longitude, decimal latitude, decimal radius, GeoUnit unit = GeoUnit.m, long? count = null, GeoOrderBy? sorting = null) => (await ExecuteScalarAsync(key, (c, k) => c.Value.GeoRadiusAsync(k, longitude, latitude, radius, unit, count, sorting, true, false, false))).Select(a => (a.member, a.longitude, a.latitude)).ToArray(); /// <summary> /// 以给定的经纬度为中心, 返回键包含的位置元素当中, 与中心的距离不超过给定最大距离的所有位置元素(包含经度、纬度)。 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="longitude">经度</param> /// <param name="latitude">纬度</param> /// <param name="radius">距离</param> /// <param name="unit">m 表示单位为米;km 表示单位为千米;mi 表示单位为英里;ft 表示单位为英尺;</param> /// <param name="count">虽然用户可以使用 COUNT 选项去获取前 N 个匹配元素, 但是因为命令在内部可能会需要对所有被匹配的元素进行处理, 所以在对一个非常大的区域进行搜索时, 即使只使用 COUNT 选项去获取少量元素, 命令的执行速度也可能会非常慢。 但是从另一方面来说, 使用 COUNT 选项去减少需要返回的元素数量, 对于减少带宽来说仍然是非常有用的。</param> /// <param name="sorting">排序</param> /// <returns></returns> async private Task<(T member, decimal longitude, decimal latitude)[]> GeoRadiusWithCoordAsync<T>(string key, decimal longitude, decimal latitude, decimal radius, GeoUnit unit = GeoUnit.m, long? count = null, GeoOrderBy? sorting = null) => (await ExecuteScalarAsync(key, (c, k) => c.Value.GeoRadiusBytesAsync(k, longitude, latitude, radius, unit, count, sorting, true, false, false))).Select(a => (this.DeserializeRedisValueInternal<T>(a.member), a.longitude, a.latitude)).ToArray(); /// <summary> /// 以给定的经纬度为中心, 返回键包含的位置元素当中, 与中心的距离不超过给定最大距离的所有位置元素(包含距离、经度、纬度)。 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="longitude">经度</param> /// <param name="latitude">纬度</param> /// <param name="radius">距离</param> /// <param name="unit">m 表示单位为米;km 表示单位为千米;mi 表示单位为英里;ft 表示单位为英尺;</param> /// <param name="count">虽然用户可以使用 COUNT 选项去获取前 N 个匹配元素, 但是因为命令在内部可能会需要对所有被匹配的元素进行处理, 所以在对一个非常大的区域进行搜索时, 即使只使用 COUNT 选项去获取少量元素, 命令的执行速度也可能会非常慢。 但是从另一方面来说, 使用 COUNT 选项去减少需要返回的元素数量, 对于减少带宽来说仍然是非常有用的。</param> /// <param name="sorting">排序</param> /// <returns></returns> async public Task<(string member, decimal dist, decimal longitude, decimal latitude)[]> GeoRadiusWithDistAndCoordAsync(string key, decimal longitude, decimal latitude, decimal radius, GeoUnit unit = GeoUnit.m, long? count = null, GeoOrderBy? sorting = null) => (await ExecuteScalarAsync(key, (c, k) => c.Value.GeoRadiusAsync(k, longitude, latitude, radius, unit, count, sorting, true, true, false))).Select(a => (a.member, a.dist, a.longitude, a.latitude)).ToArray(); /// <summary> /// 以给定的经纬度为中心, 返回键包含的位置元素当中, 与中心的距离不超过给定最大距离的所有位置元素(包含距离、经度、纬度)。 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="longitude">经度</param> /// <param name="latitude">纬度</param> /// <param name="radius">距离</param> /// <param name="unit">m 表示单位为米;km 表示单位为千米;mi 表示单位为英里;ft 表示单位为英尺;</param> /// <param name="count">虽然用户可以使用 COUNT 选项去获取前 N 个匹配元素, 但是因为命令在内部可能会需要对所有被匹配的元素进行处理, 所以在对一个非常大的区域进行搜索时, 即使只使用 COUNT 选项去获取少量元素, 命令的执行速度也可能会非常慢。 但是从另一方面来说, 使用 COUNT 选项去减少需要返回的元素数量, 对于减少带宽来说仍然是非常有用的。</param> /// <param name="sorting">排序</param> /// <returns></returns> async public Task<(T member, decimal dist, decimal longitude, decimal latitude)[]> GeoRadiusWithDistAndCoordAsync<T>(string key, decimal longitude, decimal latitude, decimal radius, GeoUnit unit = GeoUnit.m, long? count = null, GeoOrderBy? sorting = null) => (await ExecuteScalarAsync(key, (c, k) => c.Value.GeoRadiusBytesAsync(k, longitude, latitude, radius, unit, count, sorting, true, true, false))).Select(a => (this.DeserializeRedisValueInternal<T>(a.member), a.dist, a.longitude, a.latitude)).ToArray(); /// <summary> /// 以给定的成员为中心, 返回键包含的位置元素当中, 与中心的距离不超过给定最大距离的所有位置元素。 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="member">成员</param> /// <param name="radius">距离</param> /// <param name="unit">m 表示单位为米;km 表示单位为千米;mi 表示单位为英里;ft 表示单位为英尺;</param> /// <param name="count">虽然用户可以使用 COUNT 选项去获取前 N 个匹配元素, 但是因为命令在内部可能会需要对所有被匹配的元素进行处理, 所以在对一个非常大的区域进行搜索时, 即使只使用 COUNT 选项去获取少量元素, 命令的执行速度也可能会非常慢。 但是从另一方面来说, 使用 COUNT 选项去减少需要返回的元素数量, 对于减少带宽来说仍然是非常有用的。</param> /// <param name="sorting">排序</param> /// <returns></returns> async public Task<string[]> GeoRadiusByMemberAsync(string key, object member, decimal radius, GeoUnit unit = GeoUnit.m, long? count = null, GeoOrderBy? sorting = null) => (await ExecuteScalarAsync(key, (c, k) => c.Value.GeoRadiusByMemberAsync(k, member, radius, unit, count, sorting, false, false, false))).Select(a => a.member).ToArray(); /// <summary> /// 以给定的成员为中心, 返回键包含的位置元素当中, 与中心的距离不超过给定最大距离的所有位置元素。 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="member">成员</param> /// <param name="radius">距离</param> /// <param name="unit">m 表示单位为米;km 表示单位为千米;mi 表示单位为英里;ft 表示单位为英尺;</param> /// <param name="count">虽然用户可以使用 COUNT 选项去获取前 N 个匹配元素, 但是因为命令在内部可能会需要对所有被匹配的元素进行处理, 所以在对一个非常大的区域进行搜索时, 即使只使用 COUNT 选项去获取少量元素, 命令的执行速度也可能会非常慢。 但是从另一方面来说, 使用 COUNT 选项去减少需要返回的元素数量, 对于减少带宽来说仍然是非常有用的。</param> /// <param name="sorting">排序</param> /// <returns></returns> async public Task<T[]> GeoRadiusByMemberAsync<T>(string key, object member, decimal radius, GeoUnit unit = GeoUnit.m, long? count = null, GeoOrderBy? sorting = null) => (await ExecuteScalarAsync(key, (c, k) => c.Value.GeoRadiusBytesByMemberAsync(k, member, radius, unit, count, sorting, false, false, false))).Select(a => this.DeserializeRedisValueInternal<T>(a.member)).ToArray(); /// <summary> /// 以给定的成员为中心, 返回键包含的位置元素当中, 与中心的距离不超过给定最大距离的所有位置元素(包含距离)。 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="member">成员</param> /// <param name="radius">距离</param> /// <param name="unit">m 表示单位为米;km 表示单位为千米;mi 表示单位为英里;ft 表示单位为英尺;</param> /// <param name="count">虽然用户可以使用 COUNT 选项去获取前 N 个匹配元素, 但是因为命令在内部可能会需要对所有被匹配的元素进行处理, 所以在对一个非常大的区域进行搜索时, 即使只使用 COUNT 选项去获取少量元素, 命令的执行速度也可能会非常慢。 但是从另一方面来说, 使用 COUNT 选项去减少需要返回的元素数量, 对于减少带宽来说仍然是非常有用的。</param> /// <param name="sorting">排序</param> /// <returns></returns> async public Task<(string member, decimal dist)[]> GeoRadiusByMemberWithDistAsync(string key, object member, decimal radius, GeoUnit unit = GeoUnit.m, long? count = null, GeoOrderBy? sorting = null) => (await ExecuteScalarAsync(key, (c, k) => c.Value.GeoRadiusByMemberAsync(k, member, radius, unit, count, sorting, false, true, false))).Select(a => (a.member, a.dist)).ToArray(); /// <summary> /// 以给定的成员为中心, 返回键包含的位置元素当中, 与中心的距离不超过给定最大距离的所有位置元素(包含距离)。 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="member">成员</param> /// <param name="radius">距离</param> /// <param name="unit">m 表示单位为米;km 表示单位为千米;mi 表示单位为英里;ft 表示单位为英尺;</param> /// <param name="count">虽然用户可以使用 COUNT 选项去获取前 N 个匹配元素, 但是因为命令在内部可能会需要对所有被匹配的元素进行处理, 所以在对一个非常大的区域进行搜索时, 即使只使用 COUNT 选项去获取少量元素, 命令的执行速度也可能会非常慢。 但是从另一方面来说, 使用 COUNT 选项去减少需要返回的元素数量, 对于减少带宽来说仍然是非常有用的。</param> /// <param name="sorting">排序</param> /// <returns></returns> async public Task<(T member, decimal dist)[]> GeoRadiusByMemberWithDistAsync<T>(string key, object member, decimal radius, GeoUnit unit = GeoUnit.m, long? count = null, GeoOrderBy? sorting = null) => (await ExecuteScalarAsync(key, (c, k) => c.Value.GeoRadiusBytesByMemberAsync(k, member, radius, unit, count, sorting, false, true, false))).Select(a => (this.DeserializeRedisValueInternal<T>(a.member), a.dist)).ToArray(); /// <summary> /// 以给定的成员为中心, 返回键包含的位置元素当中, 与中心的距离不超过给定最大距离的所有位置元素(包含经度、纬度)。 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="member">成员</param> /// <param name="radius">距离</param> /// <param name="unit">m 表示单位为米;km 表示单位为千米;mi 表示单位为英里;ft 表示单位为英尺;</param> /// <param name="count">虽然用户可以使用 COUNT 选项去获取前 N 个匹配元素, 但是因为命令在内部可能会需要对所有被匹配的元素进行处理, 所以在对一个非常大的区域进行搜索时, 即使只使用 COUNT 选项去获取少量元素, 命令的执行速度也可能会非常慢。 但是从另一方面来说, 使用 COUNT 选项去减少需要返回的元素数量, 对于减少带宽来说仍然是非常有用的。</param> /// <param name="sorting">排序</param> /// <returns></returns> async private Task<(string member, decimal longitude, decimal latitude)[]> GeoRadiusByMemberWithCoordAsync(string key, object member, decimal radius, GeoUnit unit = GeoUnit.m, long? count = null, GeoOrderBy? sorting = null) => (await ExecuteScalarAsync(key, (c, k) => c.Value.GeoRadiusByMemberAsync(k, member, radius, unit, count, sorting, true, false, false))).Select(a => (a.member, a.longitude, a.latitude)).ToArray(); /// <summary> /// 以给定的成员为中心, 返回键包含的位置元素当中, 与中心的距离不超过给定最大距离的所有位置元素(包含经度、纬度)。 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="member">成员</param> /// <param name="radius">距离</param> /// <param name="unit">m 表示单位为米;km 表示单位为千米;mi 表示单位为英里;ft 表示单位为英尺;</param> /// <param name="count">虽然用户可以使用 COUNT 选项去获取前 N 个匹配元素, 但是因为命令在内部可能会需要对所有被匹配的元素进行处理, 所以在对一个非常大的区域进行搜索时, 即使只使用 COUNT 选项去获取少量元素, 命令的执行速度也可能会非常慢。 但是从另一方面来说, 使用 COUNT 选项去减少需要返回的元素数量, 对于减少带宽来说仍然是非常有用的。</param> /// <param name="sorting">排序</param> /// <returns></returns> async private Task<(T member, decimal longitude, decimal latitude)[]> GeoRadiusByMemberWithCoordAsync<T>(string key, object member, decimal radius, GeoUnit unit = GeoUnit.m, long? count = null, GeoOrderBy? sorting = null) => (await ExecuteScalarAsync(key, (c, k) => c.Value.GeoRadiusBytesByMemberAsync(k, member, radius, unit, count, sorting, true, false, false))).Select(a => (this.DeserializeRedisValueInternal<T>(a.member), a.longitude, a.latitude)).ToArray(); /// <summary> /// 以给定的成员为中心, 返回键包含的位置元素当中, 与中心的距离不超过给定最大距离的所有位置元素(包含距离、经度、纬度)。 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="member">成员</param> /// <param name="radius">距离</param> /// <param name="unit">m 表示单位为米;km 表示单位为千米;mi 表示单位为英里;ft 表示单位为英尺;</param> /// <param name="count">虽然用户可以使用 COUNT 选项去获取前 N 个匹配元素, 但是因为命令在内部可能会需要对所有被匹配的元素进行处理, 所以在对一个非常大的区域进行搜索时, 即使只使用 COUNT 选项去获取少量元素, 命令的执行速度也可能会非常慢。 但是从另一方面来说, 使用 COUNT 选项去减少需要返回的元素数量, 对于减少带宽来说仍然是非常有用的。</param> /// <param name="sorting">排序</param> /// <returns></returns> async public Task<(string member, decimal dist, decimal longitude, decimal latitude)[]> GeoRadiusByMemberWithDistAndCoordAsync(string key, object member, decimal radius, GeoUnit unit = GeoUnit.m, long? count = null, GeoOrderBy? sorting = null) => (await ExecuteScalarAsync(key, (c, k) => c.Value.GeoRadiusByMemberAsync(k, member, radius, unit, count, sorting, true, true, false))).Select(a => (a.member, a.dist, a.longitude, a.latitude)).ToArray(); /// <summary> /// 以给定的成员为中心, 返回键包含的位置元素当中, 与中心的距离不超过给定最大距离的所有位置元素(包含距离、经度、纬度)。 /// </summary> /// <param name="key">不含prefix前辍</param> /// <param name="member">成员</param> /// <param name="radius">距离</param> /// <param name="unit">m 表示单位为米;km 表示单位为千米;mi 表示单位为英里;ft 表示单位为英尺;</param> /// <param name="count">虽然用户可以使用 COUNT 选项去获取前 N 个匹配元素, 但是因为命令在内部可能会需要对所有被匹配的元素进行处理, 所以在对一个非常大的区域进行搜索时, 即使只使用 COUNT 选项去获取少量元素, 命令的执行速度也可能会非常慢。 但是从另一方面来说, 使用 COUNT 选项去减少需要返回的元素数量, 对于减少带宽来说仍然是非常有用的。</param> /// <param name="sorting">排序</param> /// <returns></returns> async public Task<(T member, decimal dist, decimal longitude, decimal latitude)[]> GeoRadiusByMemberWithDistAndCoordAsync<T>(string key, object member, decimal radius, GeoUnit unit = GeoUnit.m, long? count = null, GeoOrderBy? sorting = null) => (await ExecuteScalarAsync(key, (c, k) => c.Value.GeoRadiusBytesByMemberAsync(k, member, radius, unit, count, sorting, true, true, false))).Select(a => (this.DeserializeRedisValueInternal<T>(a.member), a.dist, a.longitude, a.latitude)).ToArray(); #endregion } } #endif
27182812/ChatGLM-LLaMA-chinese-insturct
2,316
src/transformers/models/vit_hybrid/__init__.py
# Copyright 2022 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_torch_available, is_vision_available _import_structure = {"configuration_vit_hybrid": ["VIT_HYBRID_PRETRAINED_CONFIG_ARCHIVE_MAP", "ViTHybridConfig"]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _import_structure["modeling_vit_hybrid"] = [ "VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST", "ViTHybridForImageClassification", "ViTHybridModel", "ViTHybridPreTrainedModel", ] try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _import_structure["image_processing_vit_hybrid"] = ["ViTHybridImageProcessor"] if TYPE_CHECKING: from .configuration_vit_hybrid import VIT_HYBRID_PRETRAINED_CONFIG_ARCHIVE_MAP, ViTHybridConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vit_hybrid import ( VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST, ViTHybridForImageClassification, ViTHybridModel, ViTHybridPreTrainedModel, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_vit_hybrid import ViTHybridImageProcessor else: import sys sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
2881099/csredis
2,378
src/Microsoft.Extensions.Caching.CSRedis/Microsoft.Extensions.Caching.CSRedis.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFrameworks>netstandard2.0;net8.0;net7.0;net6.0;net5.0;netcoreapp3.1;netcoreapp2.1</TargetFrameworks> <AssemblyName>Caching.CSRedis</AssemblyName> <PackageId>Caching.CSRedis</PackageId> <RootNamespace>Caching.CSRedis</RootNamespace> <Version>3.8.800</Version> <GeneratePackageOnBuild>true</GeneratePackageOnBuild> <PackageProjectUrl>https://github.com/2881099/csredis/tree/master/src/Microsoft.Extensions.Caching.CSRedis/README.md</PackageProjectUrl> <Description>分布式缓存 CSRedisCore 实现 Microsoft.Extensions.Caching</Description> <RepositoryUrl>https://github.com/2881099/csredis/tree/master/src/Microsoft.Extensions.Caching.CSRedis/README.md</RepositoryUrl> <PackageTags>caching csredis redis c# 分布式缓存 集群 负载 cluster Microsoft.Extensions.Caching</PackageTags> <SignAssembly>true</SignAssembly> <AssemblyOriginatorKeyFile>key.snk</AssemblyOriginatorKeyFile> <DelaySign>false</DelaySign> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'"> <DocumentationFile>bin\Debug\netstandard2.0\Caching.CSRedis.xml</DocumentationFile> <WarningLevel>3</WarningLevel> <NoWarn>1701;1702;1591</NoWarn> </PropertyGroup> <ItemGroup Condition="'$(TargetFramework)' == 'net8.0' or '$(TargetFramework)' == 'netstandard2.0'"> <PackageReference Include="Microsoft.Extensions.Caching.Abstractions" Version="8.0.0" /> </ItemGroup> <ItemGroup Condition="'$(TargetFramework)' == 'net7.0'"> <PackageReference Include="Microsoft.Extensions.Caching.Abstractions" Version="7.0.0" /> </ItemGroup> <ItemGroup Condition="'$(TargetFramework)' == 'net6.0'"> <PackageReference Include="Microsoft.Extensions.Caching.Abstractions" Version="6.0.0" /> </ItemGroup> <ItemGroup Condition="'$(TargetFramework)' == 'net5.0'"> <PackageReference Include="Microsoft.Extensions.Caching.Abstractions" Version="5.0.0" /> </ItemGroup> <ItemGroup Condition="'$(TargetFramework)' == 'netcoreapp3.1'"> <PackageReference Include="Microsoft.Extensions.Caching.Abstractions" Version="3.1.10" /> </ItemGroup> <ItemGroup Condition="'$(TargetFramework)' == 'netcoreapp2.1'"> <PackageReference Include="Microsoft.Extensions.Caching.Abstractions" Version="2.1.23" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\CSRedisCore\CSRedisCore.csproj" /> </ItemGroup> </Project>
27182812/ChatGLM-LLaMA-chinese-insturct
13,413
src/transformers/models/vit_hybrid/convert_vit_hybrid_timm_to_pytorch.py
# coding=utf-8 # Copyright 2022 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 ViT hybrid checkpoints from the timm library.""" import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from timm.data import resolve_data_config from timm.data.transforms_factory import create_transform from transformers import ( BitConfig, ViTHybridConfig, ViTHybridForImageClassification, ViTHybridImageProcessor, ViTHybridModel, ) from transformers.image_utils import PILImageResampling from transformers.utils import logging logging.set_verbosity_info() logger = logging.get_logger(__name__) # here we list all keys to be renamed (original name on the left, our name on the right) def create_rename_keys(config, base_model=False): rename_keys = [] # fmt: off # stem: rename_keys.append(("cls_token", "vit.embeddings.cls_token")) rename_keys.append(("pos_embed", "vit.embeddings.position_embeddings")) rename_keys.append(("patch_embed.proj.weight", "vit.embeddings.patch_embeddings.projection.weight")) rename_keys.append(("patch_embed.proj.bias", "vit.embeddings.patch_embeddings.projection.bias")) # backbone rename_keys.append(("patch_embed.backbone.stem.conv.weight", "vit.embeddings.patch_embeddings.backbone.bit.embedder.convolution.weight")) rename_keys.append(("patch_embed.backbone.stem.norm.weight", "vit.embeddings.patch_embeddings.backbone.bit.embedder.norm.weight")) rename_keys.append(("patch_embed.backbone.stem.norm.bias", "vit.embeddings.patch_embeddings.backbone.bit.embedder.norm.bias")) for stage_idx in range(len(config.backbone_config.depths)): for layer_idx in range(config.backbone_config.depths[stage_idx]): rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.conv1.weight", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.conv1.weight")) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm1.weight", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm1.weight")) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm1.bias", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm1.bias")) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.conv2.weight", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.conv2.weight")) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm2.weight", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm2.weight")) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm2.bias", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm2.bias")) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.conv3.weight", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.conv3.weight")) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm3.weight", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm3.weight")) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm3.bias", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm3.bias")) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.0.downsample.conv.weight", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.0.downsample.conv.weight")) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.0.downsample.norm.weight", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.0.downsample.norm.weight")) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.0.downsample.norm.bias", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.0.downsample.norm.bias")) # transformer encoder for i in range(config.num_hidden_layers): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((f"blocks.{i}.norm1.weight", f"vit.encoder.layer.{i}.layernorm_before.weight")) rename_keys.append((f"blocks.{i}.norm1.bias", f"vit.encoder.layer.{i}.layernorm_before.bias")) rename_keys.append((f"blocks.{i}.attn.proj.weight", f"vit.encoder.layer.{i}.attention.output.dense.weight")) rename_keys.append((f"blocks.{i}.attn.proj.bias", f"vit.encoder.layer.{i}.attention.output.dense.bias")) rename_keys.append((f"blocks.{i}.norm2.weight", f"vit.encoder.layer.{i}.layernorm_after.weight")) rename_keys.append((f"blocks.{i}.norm2.bias", f"vit.encoder.layer.{i}.layernorm_after.bias")) rename_keys.append((f"blocks.{i}.mlp.fc1.weight", f"vit.encoder.layer.{i}.intermediate.dense.weight")) rename_keys.append((f"blocks.{i}.mlp.fc1.bias", f"vit.encoder.layer.{i}.intermediate.dense.bias")) rename_keys.append((f"blocks.{i}.mlp.fc2.weight", f"vit.encoder.layer.{i}.output.dense.weight")) rename_keys.append((f"blocks.{i}.mlp.fc2.bias", f"vit.encoder.layer.{i}.output.dense.bias")) if base_model: # layernorm + pooler rename_keys.extend( [ ("norm.weight", "layernorm.weight"), ("norm.bias", "layernorm.bias"), ("pre_logits.fc.weight", "pooler.dense.weight"), ("pre_logits.fc.bias", "pooler.dense.bias"), ] ) # if just the base model, we should remove "vit" from all keys that start with "vit" rename_keys = [(pair[0], pair[1][4:]) if pair[1].startswith("vit") else pair for pair in rename_keys] else: # layernorm + classification head rename_keys.extend( [ ("norm.weight", "vit.layernorm.weight"), ("norm.bias", "vit.layernorm.bias"), ("head.weight", "classifier.weight"), ("head.bias", "classifier.bias"), ] ) # fmt: on return rename_keys # we split up the matrix of each encoder layer into queries, keys and values def read_in_q_k_v(state_dict, config, base_model=False): for i in range(config.num_hidden_layers): if base_model: prefix = "" else: prefix = "vit." # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) in_proj_weight = state_dict.pop(f"blocks.{i}.attn.qkv.weight") in_proj_bias = state_dict.pop(f"blocks.{i}.attn.qkv.bias") # next, add query, keys and values (in that order) to the state dict state_dict[f"{prefix}encoder.layer.{i}.attention.attention.query.weight"] = in_proj_weight[ : config.hidden_size, : ] state_dict[f"{prefix}encoder.layer.{i}.attention.attention.query.bias"] = in_proj_bias[: config.hidden_size] state_dict[f"{prefix}encoder.layer.{i}.attention.attention.key.weight"] = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] state_dict[f"{prefix}encoder.layer.{i}.attention.attention.key.bias"] = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] state_dict[f"{prefix}encoder.layer.{i}.attention.attention.value.weight"] = in_proj_weight[ -config.hidden_size :, : ] state_dict[f"{prefix}encoder.layer.{i}.attention.attention.value.bias"] = in_proj_bias[-config.hidden_size :] def remove_classification_head_(state_dict): ignore_keys = ["head.weight", "head.bias"] for k in ignore_keys: state_dict.pop(k, None) def rename_key(dct, old, new): val = dct.pop(old) dct[new] = val # 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 @torch.no_grad() def convert_vit_checkpoint(vit_name, pytorch_dump_folder_path, push_to_hub=False): """ Copy/paste/tweak model's weights to our ViT structure. """ # define default ViT hybrid configuration backbone_config = BitConfig( global_padding="same", layer_type="bottleneck", depths=(3, 4, 9), out_features=["stage3"], embedding_dynamic_padding=True, ) config = ViTHybridConfig(backbone_config=backbone_config, image_size=384, num_labels=1000) base_model = False # load original model from timm timm_model = timm.create_model(vit_name, pretrained=True) timm_model.eval() # load state_dict of original model, remove and rename some keys state_dict = timm_model.state_dict() if base_model: remove_classification_head_(state_dict) rename_keys = create_rename_keys(config, base_model) for src, dest in rename_keys: rename_key(state_dict, src, dest) read_in_q_k_v(state_dict, config, base_model) repo_id = "huggingface/label-files" filename = "imagenet-1k-id2label.json" 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()} # load HuggingFace model if vit_name[-5:] == "in21k": model = ViTHybridModel(config).eval() else: model = ViTHybridForImageClassification(config).eval() model.load_state_dict(state_dict) # create image processor transform = create_transform(**resolve_data_config({}, model=timm_model)) timm_transforms = transform.transforms pillow_resamplings = { "bilinear": PILImageResampling.BILINEAR, "bicubic": PILImageResampling.BICUBIC, "nearest": PILImageResampling.NEAREST, } processor = ViTHybridImageProcessor( do_resize=True, size={"shortest_edge": timm_transforms[0].size}, resample=pillow_resamplings[timm_transforms[0].interpolation.value], do_center_crop=True, crop_size={"height": timm_transforms[1].size[0], "width": timm_transforms[1].size[1]}, do_normalize=True, image_mean=timm_transforms[-1].mean.tolist(), image_std=timm_transforms[-1].std.tolist(), ) image = prepare_img() timm_pixel_values = transform(image).unsqueeze(0) pixel_values = processor(image, return_tensors="pt").pixel_values # verify pixel values assert torch.allclose(timm_pixel_values, pixel_values) # verify logits with torch.no_grad(): outputs = model(pixel_values) logits = outputs.logits print("Predicted class:", logits.argmax(-1).item()) if base_model: timm_pooled_output = timm_model.forward_features(pixel_values) assert timm_pooled_output.shape == outputs.pooler_output.shape assert torch.allclose(timm_pooled_output, outputs.pooler_output, atol=1e-3) else: timm_logits = timm_model(pixel_values) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(timm_logits, outputs.logits, atol=1e-3) print("Looks ok!") if pytorch_dump_folder_path is not None: Path(pytorch_dump_folder_path).mkdir(exist_ok=True) print(f"Saving model {vit_name} to {pytorch_dump_folder_path}") model.save_pretrained(pytorch_dump_folder_path) print(f"Saving processor to {pytorch_dump_folder_path}") processor.save_pretrained(pytorch_dump_folder_path) if push_to_hub: print(f"Pushing model and processor to the hub {vit_name}") model.push_to_hub(f"ybelkada/{vit_name}") processor.push_to_hub(f"ybelkada/{vit_name}") if __name__ == "__main__": parser = argparse.ArgumentParser() # Required parameters parser.add_argument( "--vit_name", default="vit_base_r50_s16_384", type=str, help="Name of the hybrid ViT timm model you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) parser.add_argument( "--push_to_hub", action="store_true", help="Whether to upload the model to the HuggingFace hub." ) args = parser.parse_args() convert_vit_checkpoint(args.vit_name, args.pytorch_dump_folder_path, args.push_to_hub)
2881099/csredis
3,805
src/Microsoft.Extensions.Caching.CSRedis/IDistributedCacheExtensions.cs
using System.IO; using System.Runtime.Serialization.Formatters.Binary; using System.Threading.Tasks; #if NET7_0_OR_GREATER #else namespace Microsoft.Extensions.Caching.Distributed { public static class IDistributedCacheExtensions { /// <summary> /// 获取缓存,反序列化成对象返回 /// </summary> /// <param name="cache"></param> /// <param name="key">key</param> /// <returns>对象</returns> public static object GetObject(this IDistributedCache cache, string key) { return Deserialize(cache.Get(key)); } /// <summary> /// 获取缓存,反序列化成对象返回 /// </summary> /// <typeparam name="T">反序列化类型</typeparam> /// <param name="cache"></param> /// <param name="key">key</param> /// <returns>对象</returns> public static T GetObject<T>(this IDistributedCache cache, string key) { var obj = Deserialize(cache.Get(key)); if (obj == null) return default(T); return (T)obj; } /// <summary> /// 获取缓存,反序列化成对象 /// </summary> /// <param name="cache"></param> /// <param name="key">key</param> /// <returns>对象</returns> async public static Task<object> GetObjectAsync(this IDistributedCache cache, string key) { return Deserialize(await cache.GetAsync(key)); } /// <summary> /// 获取缓存,反序列化成对象 /// </summary> /// <typeparam name="T">反序列化类型</typeparam> /// <param name="cache"></param> /// <param name="key">key</param> /// <returns>对象</returns> async public static Task<T> GetObjectAsync<T>(this IDistributedCache cache, string key) { var obj = Deserialize(await cache.GetAsync(key)); if (obj == null) return default(T); return (T)obj; } /// <summary> /// 序列化对象后,设置缓存 /// </summary> /// <param name="cache"></param> /// <param name="key">key</param> /// <param name="value">对象</param> public static void SetObject(this IDistributedCache cache, string key, object value) { var data = Serialize(value); if (data == null) cache.Remove(key); else cache.Set(key, Serialize(value)); } /// <summary> /// 序列化对象后,设置缓存 /// </summary> /// <param name="cache"></param> /// <param name="key">key</param> /// <param name="value">对象</param> /// <param name="options">策略</param> public static void SetObject(this IDistributedCache cache, string key, object value, DistributedCacheEntryOptions options) { var data = Serialize(value); if (data == null) cache.Remove(key); else cache.Set(key, Serialize(value), options); } /// <summary> /// 序列化对象后,设置缓存 /// </summary> /// <param name="cache"></param> /// <param name="key">key</param> /// <param name="value">对象</param> public static Task SetObjectAsync(this IDistributedCache cache, string key, object value) { var data = Serialize(value); if (data == null) return cache.RemoveAsync(key); else return cache.SetAsync(key, Serialize(value)); } /// <summary> /// 序列化对象后,设置缓存 /// </summary> /// <param name="cache"></param> /// <param name="key">key</param> /// <param name="value">对象</param> /// <param name="options">策略</param> public static Task SetObjectAsync(this IDistributedCache cache, string key, object value, DistributedCacheEntryOptions options) { var data = Serialize(value); if (data == null) return cache.RemoveAsync(key); else return cache.SetAsync(key, Serialize(value), options); } public static byte[] Serialize(object value) { if (value == null) return null; using (MemoryStream ms = new MemoryStream()) { var formatter = new BinaryFormatter(); formatter.Serialize(ms, value); return ms.GetBuffer(); } } public static object Deserialize(byte[] stream) { if (stream == null) return null; using (MemoryStream ms = new MemoryStream(stream)) { var formatter = new BinaryFormatter(); return formatter.Deserialize(ms); } } } } #endif
2881099/csredis
1,974
src/Microsoft.Extensions.Caching.CSRedis/README.md
由于 StackExchange.Redis 不可靠,导致 Microsoft.Extensions.Caching.Redis 不能放心使用。故使用 CSRedisCore 作为分布式缓存。 | Package Name | NuGet | Downloads | | |--------------| ------- | ---- | -- | | CSRedisCore | [![nuget](https://img.shields.io/nuget/v/CSRedisCore.svg?style=flat-square)](https://www.nuget.org/packages/CSRedisCore) | [![stats](https://img.shields.io/nuget/dt/CSRedisCore.svg?style=flat-square)](https://www.nuget.org/stats/packages/CSRedisCore?groupby=Version) | | Caching.CSRedis | [![nuget](https://img.shields.io/nuget/v/Caching.CSRedis.svg?style=flat-square)](https://www.nuget.org/packages/Caching.CSRedis) | [![stats](https://img.shields.io/nuget/dt/Caching.CSRedis.svg?style=flat-square)](https://www.nuget.org/stats/packages/Caching.CSRedis?groupby=Version) | IDistributedCache | # 使用方法 > Install-Package Caching.CSRedis ## 普通模式 ```csharp var csredis = new CSRedis.CSRedisClient("127.0.0.1:6379,password=123,defaultDatabase=13,ssl=false,writeBuffer=10240,poolsize=50,prefix=key前辍"); services.AddSingleton<IDistributedCache>(new Microsoft.Extensions.Caching.Redis.CSRedisCache(csredis)); ``` # 集群模式 ```csharp var csredis = new CSRedis.CSRedisClient(null, "127.0.0.1:6371,password=123,defaultDatabase=11,poolsize=10,ssl=false,writeBuffer=10240,prefix=key前辍", "127.0.0.1:6372,password=123,defaultDatabase=12,poolsize=11,ssl=false,writeBuffer=10240,prefix=key前辍", "127.0.0.1:6373,password=123,defaultDatabase=13,poolsize=12,ssl=false,writeBuffer=10240,prefix=key前辍", "127.0.0.1:6374,password=123,defaultDatabase=14,poolsize=13,ssl=false,writeBuffer=10240,prefix=key前辍"); services.AddSingleton<IDistributedCache>(new Microsoft.Extensions.Caching.Redis.CSRedisCache(csredis)); ``` # 缓存对象扩展方法 ```csharp IDistributedCache cache = xxxx; object obj1 = new xxxx(); cache.SetObject("key1", obj1); object obj2 = cache.GetObject("key1"); T obj3 = cache.GetObject<T>("key1"); ``` # 批量删除 ```csharp IDistributedCache cache = xxxx; cache.Remove("key1|key2"); ```
27182812/ChatGLM-LLaMA-chinese-insturct
16,128
src/transformers/models/vit_hybrid/image_processing_vit_hybrid.py
# coding=utf-8 # Copyright 2022 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 ViT hybrid.""" 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, convert_to_rgb, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging logger = logging.get_logger(__name__) if is_vision_available(): import PIL class ViTHybridImageProcessor(BaseImageProcessor): r""" Constructs a ViT Hybrid 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 the `preprocess` method. size (`Dict[str, int]` *optional*, defaults to `{"shortest_edge": 224}`): Size of the image after resizing. The shortest edge of the image is resized to size["shortest_edge"], with the longest edge resized to keep the input aspect ratio. Can be overridden by `size` in the `preprocess` method. resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BICUBIC`): Resampling filter to use if resizing the image. Can be overridden by `resample` in the `preprocess` method. do_center_crop (`bool`, *optional*, defaults to `True`): Whether to center crop the image to the specified `crop_size`. Can be overridden by `do_center_crop` in the `preprocess` method. crop_size (`Dict[str, int]` *optional*, defaults to 224): Size of the output image after applying `center_crop`. Can be overridden by `crop_size` in the `preprocess` method. do_rescale (`bool`, *optional*, defaults to `True`): Whether to rescale the image by the specified scale `rescale_factor`. Can be overridden by `do_rescale` 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 `rescale_factor` in the `preprocess` method. do_normalize: Whether to normalize the image. Can be overridden by `do_normalize` 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`): Image standard deviation. do_convert_rgb (`bool`, *optional*, defaults to `True`): 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. """ model_input_names = ["pixel_values"] def __init__( self, do_resize: bool = True, size: Dict[str, int] = None, resample: PILImageResampling = PILImageResampling.BICUBIC, do_center_crop: bool = True, crop_size: Dict[str, int] = None, do_rescale: bool = True, rescale_factor: Union[int, float] = 1 / 255, do_normalize: bool = True, image_mean: Optional[Union[float, List[float]]] = None, image_std: Optional[Union[float, List[float]]] = None, do_convert_rgb: bool = True, **kwargs, ) -> None: super().__init__(**kwargs) size = size if size is not None else {"shortest_edge": 224} size = get_size_dict(size, default_to_square=False) crop_size = crop_size if crop_size is not None else {"height": 224, "width": 224} crop_size = get_size_dict(crop_size, default_to_square=True, 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.do_normalize = do_normalize self.image_mean = image_mean if image_mean is not None else OPENAI_CLIP_MEAN self.image_std = image_std if image_std is not None else OPENAI_CLIP_STD self.do_convert_rgb = do_convert_rgb def resize( self, image: np.ndarray, size: Dict[str, int], resample: PILImageResampling = PILImageResampling.BICUBIC, data_format: Optional[Union[str, ChannelDimension]] = None, **kwargs, ) -> np.ndarray: """ Resize an image. The shortest edge of the image is resized to size["shortest_edge"], with the longest edge resized to keep the input aspect ratio. Args: image (`np.ndarray`): Image to resize. size (`Dict[str, int]`): Size of the output image. resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BICUBIC`): Resampling filter to use when resiizing 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, default_to_square=False) if "shortest_edge" not in size: raise ValueError(f"The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}") output_size = get_resize_output_image_size(image, size=size["shortest_edge"], default_to_square=False) return resize(image, size=output_size, 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. If the image is too small to be cropped to the size given, it will be padded (so the returned result will always be of size `size`). Args: image (`np.ndarray`): Image to center crop. size (`Dict[str, int]`): Size of the output image in the form of a dictionary with keys `height` and `width`. 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` parameter must contain the keys (height, 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], 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. 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 rescale(image, scale=scale, data_format=data_format, **kwargs) 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: PILImageResampling = None, do_center_crop: bool = None, crop_size: int = None, do_rescale: bool = None, rescale_factor: float = None, do_normalize: bool = None, image_mean: Optional[Union[float, List[float]]] = None, image_std: Optional[Union[float, List[float]]] = None, do_convert_rgb: bool = None, return_tensors: Optional[Union[str, TensorType]] = None, data_format: Optional[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 resizing. Shortest edge of the image is resized to size["shortest_edge"], with the longest edge resized to keep the input aspect ratio. resample (`int`, *optional*, defaults to `self.resample`): Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`. 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 center crop. Only has an effect if `do_center_crop` is set to `True`. do_rescale (`bool`, *optional*, defaults to `self.do_rescale`): Whether to rescale the image. rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`): Rescale factor to rescale the image by if `do_rescale` is set to `True`. 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 to use for normalization. Only has an effect if `do_normalize` is set to `True`. image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`): Image standard deviation to use for normalization. Only has an effect if `do_normalize` is set to `True`. do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb`): Whether to convert the image to RGB. return_tensors (`str` or `TensorType`, *optional*): The type of tensors to return. Can be one of: - Unset: 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. - Unset: defaults to the channel dimension format of the input image. """ do_resize = do_resize if do_resize is not None else self.do_resize size = size if size is not None else self.size size = get_size_dict(size, param_name="size", default_to_square=False) 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 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", default_to_square=True) 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 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 do_convert_rgb = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb 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: raise ValueError("Size 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.") # PIL RGBA images are converted to RGB if do_convert_rgb: images = [convert_to_rgb(image) for image in images] # 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) for image in images] if do_normalize: images = [self.normalize(image=image, mean=image_mean, 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/csredis
9,512
src/Microsoft.Extensions.Caching.CSRedis/CSRedisCache.cs
using System; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Caching.Distributed; namespace Microsoft.Extensions.Caching.Redis { public class CSRedisCache : IDistributedCache { private CSRedis.CSRedisClient _redisClient; public CSRedisCache(CSRedis.CSRedisClient redisClient) { _redisClient = redisClient; } // KEYS[1] = = key // ARGV[1] = absolute-expiration - ticks as long (-1 for none) // ARGV[2] = sliding-expiration - ticks as long (-1 for none) // ARGV[3] = relative-expiration (long, in seconds, -1 for none) - Min(absolute-expiration - Now, sliding-expiration) // ARGV[4] = data - byte[] // this order should not change LUA script depends on it private const string SetScript = (@" redis.call('HMSET', KEYS[1], 'absexp', ARGV[1], 'sldexp', ARGV[2], 'data', ARGV[4]) if ARGV[3] ~= '-1' then redis.call('EXPIRE', KEYS[1], ARGV[3]) end return 1"); private const string AbsoluteExpirationKey = "absexp"; private const string SlidingExpirationKey = "sldexp"; private const string DataKey = "data"; private const long NotPresent = -1; private readonly SemaphoreSlim _connectionLock = new SemaphoreSlim(initialCount: 1, maxCount: 1); public byte[] Get(string key) { if (key == null) { throw new ArgumentNullException(nameof(key)); } return GetAndRefresh(key, getData: true); } public async Task<byte[]> GetAsync(string key, CancellationToken token = default(CancellationToken)) { if (key == null) { throw new ArgumentNullException(nameof(key)); } token.ThrowIfCancellationRequested(); return await GetAndRefreshAsync(key, getData: true, token: token); } public void Set(string key, byte[] value, DistributedCacheEntryOptions options) { if (key == null) { throw new ArgumentNullException(nameof(key)); } if (value == null) { throw new ArgumentNullException(nameof(value)); } if (options == null) { throw new ArgumentNullException(nameof(options)); } var creationTime = DateTimeOffset.UtcNow; var absoluteExpiration = GetAbsoluteExpiration(creationTime, options); var result = _redisClient.Eval(SetScript, key, new object[] { absoluteExpiration?.Ticks ?? NotPresent, options.SlidingExpiration?.Ticks ?? NotPresent, GetExpirationInSeconds(creationTime, absoluteExpiration, options) ?? NotPresent, value }); } public async Task SetAsync(string key, byte[] value, DistributedCacheEntryOptions options, CancellationToken token = default(CancellationToken)) { if (key == null) { throw new ArgumentNullException(nameof(key)); } if (value == null) { throw new ArgumentNullException(nameof(value)); } if (options == null) { throw new ArgumentNullException(nameof(options)); } token.ThrowIfCancellationRequested(); var creationTime = DateTimeOffset.UtcNow; var absoluteExpiration = GetAbsoluteExpiration(creationTime, options); await _redisClient.EvalAsync(SetScript, key, new object[] { absoluteExpiration?.Ticks ?? NotPresent, options.SlidingExpiration?.Ticks ?? NotPresent, GetExpirationInSeconds(creationTime, absoluteExpiration, options) ?? NotPresent, value }); } public void Refresh(string key) { if (key == null) { throw new ArgumentNullException(nameof(key)); } GetAndRefresh(key, getData: false); } public async Task RefreshAsync(string key, CancellationToken token = default(CancellationToken)) { if (key == null) { throw new ArgumentNullException(nameof(key)); } token.ThrowIfCancellationRequested(); await GetAndRefreshAsync(key, getData: false, token: token); } private byte[] GetAndRefresh(string key, bool getData) { if (key == null) { throw new ArgumentNullException(nameof(key)); } // This also resets the LRU status as desired. // TODO: Can this be done in one operation on the server side? Probably, the trick would just be the DateTimeOffset math. object[] results; byte[] value = null; if (getData) { var ret = _redisClient.HMGet<byte[]>(key, AbsoluteExpirationKey, SlidingExpirationKey, DataKey); results = new object[] { ret[0] == null ? null : Encoding.UTF8.GetString(ret[0]), ret[1] == null ? null : Encoding.UTF8.GetString(ret[1]), value = ret[2] }; } else { results = _redisClient.HMGet(key, AbsoluteExpirationKey, SlidingExpirationKey); } // TODO: Error handling if (results.Length >= 2) { MapMetadata(results, out DateTimeOffset? absExpr, out TimeSpan? sldExpr); Refresh(key, absExpr, sldExpr); } if (results.Length >= 3) { return value; } return null; } private async Task<byte[]> GetAndRefreshAsync(string key, bool getData, CancellationToken token = default(CancellationToken)) { if (key == null) { throw new ArgumentNullException(nameof(key)); } token.ThrowIfCancellationRequested(); // This also resets the LRU status as desired. // TODO: Can this be done in one operation on the server side? Probably, the trick would just be the DateTimeOffset math. object[] results; byte[] value = null; if (getData) { var ret = await _redisClient.HMGetAsync<byte[]>(key, AbsoluteExpirationKey, SlidingExpirationKey, DataKey); results = new object[] { ret[0] == null ? null : Encoding.UTF8.GetString(ret[0]), ret[1] == null ? null : Encoding.UTF8.GetString(ret[1]), value = ret[2] }; } else { results = await _redisClient.HMGetAsync(key, AbsoluteExpirationKey, SlidingExpirationKey); } // TODO: Error handling if (results.Length >= 2) { MapMetadata(results, out DateTimeOffset? absExpr, out TimeSpan? sldExpr); await RefreshAsync(key, absExpr, sldExpr, token); } if (results.Length >= 3) { return value; } return null; } public void Remove(string key) { if (key == null) { throw new ArgumentNullException(nameof(key)); } _redisClient.Del(key.Split('|')); // TODO: Error handling } public async Task RemoveAsync(string key, CancellationToken token = default(CancellationToken)) { if (key == null) { throw new ArgumentNullException(nameof(key)); } await _redisClient.DelAsync(key.Split('|')); // TODO: Error handling } private void MapMetadata(object[] results, out DateTimeOffset? absoluteExpiration, out TimeSpan? slidingExpiration) { absoluteExpiration = null; slidingExpiration = null; if (long.TryParse(results[0]?.ToString(), out var absoluteExpirationTicks) && absoluteExpirationTicks != NotPresent) { absoluteExpiration = new DateTimeOffset(absoluteExpirationTicks, TimeSpan.Zero); } if (long.TryParse(results[1]?.ToString(), out var slidingExpirationTicks) && slidingExpirationTicks != NotPresent) { slidingExpiration = new TimeSpan(slidingExpirationTicks); } } private void Refresh(string key, DateTimeOffset? absExpr, TimeSpan? sldExpr) { if (key == null) { throw new ArgumentNullException(nameof(key)); } // Note Refresh has no effect if there is just an absolute expiration (or neither). TimeSpan? expr = null; if (sldExpr.HasValue) { if (absExpr.HasValue) { var relExpr = absExpr.Value - DateTimeOffset.Now; expr = relExpr <= sldExpr.Value ? relExpr : sldExpr; } else { expr = sldExpr; } _redisClient.Expire(key, expr ?? TimeSpan.Zero); // TODO: Error handling } } private async Task RefreshAsync(string key, DateTimeOffset? absExpr, TimeSpan? sldExpr, CancellationToken token = default(CancellationToken)) { if (key == null) { throw new ArgumentNullException(nameof(key)); } token.ThrowIfCancellationRequested(); // Note Refresh has no effect if there is just an absolute expiration (or neither). TimeSpan? expr = null; if (sldExpr.HasValue) { if (absExpr.HasValue) { var relExpr = absExpr.Value - DateTimeOffset.Now; expr = relExpr <= sldExpr.Value ? relExpr : sldExpr; } else { expr = sldExpr; } await _redisClient.ExpireAsync(key, expr ?? TimeSpan.Zero); // TODO: Error handling } } private static long? GetExpirationInSeconds(DateTimeOffset creationTime, DateTimeOffset? absoluteExpiration, DistributedCacheEntryOptions options) { if (absoluteExpiration.HasValue && options.SlidingExpiration.HasValue) { return (long) Math.Min( (absoluteExpiration.Value - creationTime).TotalSeconds, options.SlidingExpiration.Value.TotalSeconds); } else if (absoluteExpiration.HasValue) { return (long) (absoluteExpiration.Value - creationTime).TotalSeconds; } else if (options.SlidingExpiration.HasValue) { return (long) options.SlidingExpiration.Value.TotalSeconds; } return null; } private static DateTimeOffset? GetAbsoluteExpiration(DateTimeOffset creationTime, DistributedCacheEntryOptions options) { if (options.AbsoluteExpiration.HasValue && options.AbsoluteExpiration <= creationTime) { throw new ArgumentOutOfRangeException( nameof(DistributedCacheEntryOptions.AbsoluteExpiration), options.AbsoluteExpiration.Value, "The absolute expiration value must be in the future."); } var absoluteExpiration = options.AbsoluteExpiration; if (options.AbsoluteExpirationRelativeToNow.HasValue) { absoluteExpiration = creationTime + options.AbsoluteExpirationRelativeToNow; } return absoluteExpiration; } } }
2877025939/PlanADScrollView
16,021
PlanADScrollView/PlanADScrollView/SDWebImage/SDWebImage/SDWebImageManager.m
/* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import "SDWebImageManager.h" #import <objc/message.h> #import "NSImage+WebCache.h" @interface SDWebImageCombinedOperation : NSObject <SDWebImageOperation> @property (assign, nonatomic, getter = isCancelled) BOOL cancelled; @property (copy, nonatomic, nullable) SDWebImageNoParamsBlock cancelBlock; @property (strong, nonatomic, nullable) NSOperation *cacheOperation; @end @interface SDWebImageManager () @property (strong, nonatomic, readwrite, nonnull) SDImageCache *imageCache; @property (strong, nonatomic, readwrite, nonnull) SDWebImageDownloader *imageDownloader; @property (strong, nonatomic, nonnull) NSMutableSet<NSURL *> *failedURLs; @property (strong, nonatomic, nonnull) NSMutableArray<SDWebImageCombinedOperation *> *runningOperations; @end @implementation SDWebImageManager + (nonnull instancetype)sharedManager { static dispatch_once_t once; static id instance; dispatch_once(&once, ^{ instance = [self new]; }); return instance; } - (nonnull instancetype)init { SDImageCache *cache = [SDImageCache sharedImageCache]; SDWebImageDownloader *downloader = [SDWebImageDownloader sharedDownloader]; return [self initWithCache:cache downloader:downloader]; } - (nonnull instancetype)initWithCache:(nonnull SDImageCache *)cache downloader:(nonnull SDWebImageDownloader *)downloader { if ((self = [super init])) { _imageCache = cache; _imageDownloader = downloader; _failedURLs = [NSMutableSet new]; _runningOperations = [NSMutableArray new]; } return self; } - (nullable NSString *)cacheKeyForURL:(nullable NSURL *)url { if (!url) { return @""; } if (self.cacheKeyFilter) { return self.cacheKeyFilter(url); } else { return url.absoluteString; } } - (void)cachedImageExistsForURL:(nullable NSURL *)url completion:(nullable SDWebImageCheckCacheCompletionBlock)completionBlock { NSString *key = [self cacheKeyForURL:url]; BOOL isInMemoryCache = ([self.imageCache imageFromMemoryCacheForKey:key] != nil); if (isInMemoryCache) { // making sure we call the completion block on the main queue dispatch_async(dispatch_get_main_queue(), ^{ if (completionBlock) { completionBlock(YES); } }); return; } [self.imageCache diskImageExistsWithKey:key completion:^(BOOL isInDiskCache) { // the completion block of checkDiskCacheForImageWithKey:completion: is always called on the main queue, no need to further dispatch if (completionBlock) { completionBlock(isInDiskCache); } }]; } - (void)diskImageExistsForURL:(nullable NSURL *)url completion:(nullable SDWebImageCheckCacheCompletionBlock)completionBlock { NSString *key = [self cacheKeyForURL:url]; [self.imageCache diskImageExistsWithKey:key completion:^(BOOL isInDiskCache) { // the completion block of checkDiskCacheForImageWithKey:completion: is always called on the main queue, no need to further dispatch if (completionBlock) { completionBlock(isInDiskCache); } }]; } - (id <SDWebImageOperation>)loadImageWithURL:(nullable NSURL *)url options:(SDWebImageOptions)options progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock completed:(nullable SDInternalCompletionBlock)completedBlock { // Invoking this method without a completedBlock is pointless NSAssert(completedBlock != nil, @"If you mean to prefetch the image, use -[SDWebImagePrefetcher prefetchURLs] instead"); // Very common mistake is to send the URL using NSString object instead of NSURL. For some strange reason, Xcode won't // throw any warning for this type mismatch. Here we failsafe this error by allowing URLs to be passed as NSString. if ([url isKindOfClass:NSString.class]) { url = [NSURL URLWithString:(NSString *)url]; } // Prevents app crashing on argument type error like sending NSNull instead of NSURL if (![url isKindOfClass:NSURL.class]) { url = nil; } __block SDWebImageCombinedOperation *operation = [SDWebImageCombinedOperation new]; __weak SDWebImageCombinedOperation *weakOperation = operation; BOOL isFailedUrl = NO; if (url) { @synchronized (self.failedURLs) { isFailedUrl = [self.failedURLs containsObject:url]; } } if (url.absoluteString.length == 0 || (!(options & SDWebImageRetryFailed) && isFailedUrl)) { [self callCompletionBlockForOperation:operation completion:completedBlock error:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil] url:url]; return operation; } @synchronized (self.runningOperations) { [self.runningOperations addObject:operation]; } NSString *key = [self cacheKeyForURL:url]; operation.cacheOperation = [self.imageCache queryCacheOperationForKey:key done:^(UIImage *cachedImage, NSData *cachedData, SDImageCacheType cacheType) { if (operation.isCancelled) { [self safelyRemoveOperationFromRunning:operation]; return; } if ((!cachedImage || options & SDWebImageRefreshCached) && (![self.delegate respondsToSelector:@selector(imageManager:shouldDownloadImageForURL:)] || [self.delegate imageManager:self shouldDownloadImageForURL:url])) { if (cachedImage && options & SDWebImageRefreshCached) { // If image was found in the cache but SDWebImageRefreshCached is provided, notify about the cached image // AND try to re-download it in order to let a chance to NSURLCache to refresh it from server. [self callCompletionBlockForOperation:weakOperation completion:completedBlock image:cachedImage data:cachedData error:nil cacheType:cacheType finished:YES url:url]; } // download if no image or requested to refresh anyway, and download allowed by delegate SDWebImageDownloaderOptions downloaderOptions = 0; if (options & SDWebImageLowPriority) downloaderOptions |= SDWebImageDownloaderLowPriority; if (options & SDWebImageProgressiveDownload) downloaderOptions |= SDWebImageDownloaderProgressiveDownload; if (options & SDWebImageRefreshCached) downloaderOptions |= SDWebImageDownloaderUseNSURLCache; if (options & SDWebImageContinueInBackground) downloaderOptions |= SDWebImageDownloaderContinueInBackground; if (options & SDWebImageHandleCookies) downloaderOptions |= SDWebImageDownloaderHandleCookies; if (options & SDWebImageAllowInvalidSSLCertificates) downloaderOptions |= SDWebImageDownloaderAllowInvalidSSLCertificates; if (options & SDWebImageHighPriority) downloaderOptions |= SDWebImageDownloaderHighPriority; if (options & SDWebImageScaleDownLargeImages) downloaderOptions |= SDWebImageDownloaderScaleDownLargeImages; if (cachedImage && options & SDWebImageRefreshCached) { // force progressive off if image already cached but forced refreshing downloaderOptions &= ~SDWebImageDownloaderProgressiveDownload; // ignore image read from NSURLCache if image if cached but force refreshing downloaderOptions |= SDWebImageDownloaderIgnoreCachedResponse; } SDWebImageDownloadToken *subOperationToken = [self.imageDownloader downloadImageWithURL:url options:downloaderOptions progress:progressBlock completed:^(UIImage *downloadedImage, NSData *downloadedData, NSError *error, BOOL finished) { __strong __typeof(weakOperation) strongOperation = weakOperation; if (!strongOperation || strongOperation.isCancelled) { // Do nothing if the operation was cancelled // See #699 for more details // if we would call the completedBlock, there could be a race condition between this block and another completedBlock for the same object, so if this one is called second, we will overwrite the new data } else if (error) { [self callCompletionBlockForOperation:strongOperation completion:completedBlock error:error url:url]; if ( error.code != NSURLErrorNotConnectedToInternet && error.code != NSURLErrorCancelled && error.code != NSURLErrorTimedOut && error.code != NSURLErrorInternationalRoamingOff && error.code != NSURLErrorDataNotAllowed && error.code != NSURLErrorCannotFindHost && error.code != NSURLErrorCannotConnectToHost) { @synchronized (self.failedURLs) { [self.failedURLs addObject:url]; } } } else { if ((options & SDWebImageRetryFailed)) { @synchronized (self.failedURLs) { [self.failedURLs removeObject:url]; } } BOOL cacheOnDisk = !(options & SDWebImageCacheMemoryOnly); if (options & SDWebImageRefreshCached && cachedImage && !downloadedImage) { // Image refresh hit the NSURLCache cache, do not call the completion block } else if (downloadedImage && (!downloadedImage.images || (options & SDWebImageTransformAnimatedImage)) && [self.delegate respondsToSelector:@selector(imageManager:transformDownloadedImage:withURL:)]) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{ UIImage *transformedImage = [self.delegate imageManager:self transformDownloadedImage:downloadedImage withURL:url]; if (transformedImage && finished) { BOOL imageWasTransformed = ![transformedImage isEqual:downloadedImage]; // pass nil if the image was transformed, so we can recalculate the data from the image [self.imageCache storeImage:transformedImage imageData:(imageWasTransformed ? nil : downloadedData) forKey:key toDisk:cacheOnDisk completion:nil]; } [self callCompletionBlockForOperation:strongOperation completion:completedBlock image:transformedImage data:downloadedData error:nil cacheType:SDImageCacheTypeNone finished:finished url:url]; }); } else { if (downloadedImage && finished) { [self.imageCache storeImage:downloadedImage imageData:downloadedData forKey:key toDisk:cacheOnDisk completion:nil]; } [self callCompletionBlockForOperation:strongOperation completion:completedBlock image:downloadedImage data:downloadedData error:nil cacheType:SDImageCacheTypeNone finished:finished url:url]; } } if (finished) { [self safelyRemoveOperationFromRunning:strongOperation]; } }]; operation.cancelBlock = ^{ [self.imageDownloader cancel:subOperationToken]; __strong __typeof(weakOperation) strongOperation = weakOperation; [self safelyRemoveOperationFromRunning:strongOperation]; }; } else if (cachedImage) { __strong __typeof(weakOperation) strongOperation = weakOperation; [self callCompletionBlockForOperation:strongOperation completion:completedBlock image:cachedImage data:cachedData error:nil cacheType:cacheType finished:YES url:url]; [self safelyRemoveOperationFromRunning:operation]; } else { // Image not in cache and download disallowed by delegate __strong __typeof(weakOperation) strongOperation = weakOperation; [self callCompletionBlockForOperation:strongOperation completion:completedBlock image:nil data:nil error:nil cacheType:SDImageCacheTypeNone finished:YES url:url]; [self safelyRemoveOperationFromRunning:operation]; } }]; return operation; } - (void)saveImageToCache:(nullable UIImage *)image forURL:(nullable NSURL *)url { if (image && url) { NSString *key = [self cacheKeyForURL:url]; [self.imageCache storeImage:image forKey:key toDisk:YES completion:nil]; } } - (void)cancelAll { @synchronized (self.runningOperations) { NSArray<SDWebImageCombinedOperation *> *copiedOperations = [self.runningOperations copy]; [copiedOperations makeObjectsPerformSelector:@selector(cancel)]; [self.runningOperations removeObjectsInArray:copiedOperations]; } } - (BOOL)isRunning { BOOL isRunning = NO; @synchronized (self.runningOperations) { isRunning = (self.runningOperations.count > 0); } return isRunning; } - (void)safelyRemoveOperationFromRunning:(nullable SDWebImageCombinedOperation*)operation { @synchronized (self.runningOperations) { if (operation) { [self.runningOperations removeObject:operation]; } } } - (void)callCompletionBlockForOperation:(nullable SDWebImageCombinedOperation*)operation completion:(nullable SDInternalCompletionBlock)completionBlock error:(nullable NSError *)error url:(nullable NSURL *)url { [self callCompletionBlockForOperation:operation completion:completionBlock image:nil data:nil error:error cacheType:SDImageCacheTypeNone finished:YES url:url]; } - (void)callCompletionBlockForOperation:(nullable SDWebImageCombinedOperation*)operation completion:(nullable SDInternalCompletionBlock)completionBlock image:(nullable UIImage *)image data:(nullable NSData *)data error:(nullable NSError *)error cacheType:(SDImageCacheType)cacheType finished:(BOOL)finished url:(nullable NSURL *)url { dispatch_main_async_safe(^{ if (operation && !operation.isCancelled && completionBlock) { completionBlock(image, data, error, cacheType, finished, url); } }); } @end @implementation SDWebImageCombinedOperation - (void)setCancelBlock:(nullable SDWebImageNoParamsBlock)cancelBlock { // check if the operation is already cancelled, then we just call the cancelBlock if (self.isCancelled) { if (cancelBlock) { cancelBlock(); } _cancelBlock = nil; // don't forget to nil the cancelBlock, otherwise we will get crashes } else { _cancelBlock = [cancelBlock copy]; } } - (void)cancel { self.cancelled = YES; if (self.cacheOperation) { [self.cacheOperation cancel]; self.cacheOperation = nil; } if (self.cancelBlock) { self.cancelBlock(); // TODO: this is a temporary fix to #809. // Until we can figure the exact cause of the crash, going with the ivar instead of the setter // self.cancelBlock = nil; _cancelBlock = nil; } } @end
27182812/ChatGLM-LLaMA-chinese-insturct
7,223
src/transformers/models/vit_hybrid/configuration_vit_hybrid.py
# coding=utf-8 # Copyright 2022 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. """ ViT Hybrid model configuration""" import copy from typing import Dict from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto.configuration_auto import CONFIG_MAPPING from ..bit import BitConfig logger = logging.get_logger(__name__) VIT_HYBRID_PRETRAINED_CONFIG_ARCHIVE_MAP = { "google/vit-hybrid-base-bit-384": "https://huggingface.co/vit-hybrid-base-bit-384/resolve/main/config.json", # See all ViT hybrid models at https://huggingface.co/models?filter=vit } class ViTHybridConfig(PretrainedConfig): r""" This is the configuration class to store the configuration of a [`ViTHybridModel`]. It is used to instantiate a ViT Hybrid 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 ViT Hybrid [google/vit-hybrid-base-bit-384](https://huggingface.co/google/vit-hybrid-base-bit-384) architecture. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the documentation from [`PretrainedConfig`] for more information. Args: hidden_size (`int`, *optional*, defaults to 768): Dimensionality of the encoder layers and the pooler layer. num_hidden_layers (`int`, *optional*, defaults to 12): Number of hidden layers in the Transformer encoder. num_attention_heads (`int`, *optional*, defaults to 12): Number of attention heads for each attention layer in the Transformer encoder. intermediate_size (`int`, *optional*, defaults to 3072): Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder. hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`): The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`, `"relu"`, `"selu"` and `"gelu_new"` are supported. hidden_dropout_prob (`float`, *optional*, defaults to 0.1): The dropout probability for all fully connected layers in the embeddings, encoder, and pooler. attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1): The dropout ratio for the attention probabilities. initializer_range (`float`, *optional*, defaults to 0.02): The standard deviation of the truncated_normal_initializer for initializing all weight matrices. layer_norm_eps (`float`, *optional*, defaults to 1e-12): The epsilon used by the layer normalization layers. image_size (`int`, *optional*, defaults to 224): The size (resolution) of each image. patch_size (`int`, *optional*, defaults to 1): The size (resolution) of each patch. num_channels (`int`, *optional*, defaults to 3): The number of input channels. qkv_bias (`bool`, *optional*, defaults to `True`): Whether to add a bias to the queries, keys and values. backbone_config (`Union[Dict[str, Any], PretrainedConfig]`, *optional*, defaults to `None`): The configuration of the backbone in a dictionary or the config object of the backbone. backbone_featmap_shape (`List[int]`, *optional*, defaults to `[1, 1024, 24, 24]`): Used only for the `hybrid` embedding type. The shape of the feature maps of the backbone. Example: ```python >>> from transformers import ViTHybridConfig, ViTHybridModel >>> # Initializing a ViT Hybrid vit-hybrid-base-bit-384 style configuration >>> configuration = ViTHybridConfig() >>> # Initializing a model (with random weights) from the vit-hybrid-base-bit-384 style configuration >>> model = ViTHybridModel(configuration) >>> # Accessing the model configuration >>> configuration = model.config ```""" model_type = "vit-hybrid" def __init__( self, backbone_config=None, hidden_size=768, num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072, hidden_act="gelu", hidden_dropout_prob=0.0, attention_probs_dropout_prob=0.0, initializer_range=0.02, layer_norm_eps=1e-12, image_size=224, patch_size=1, num_channels=3, backbone_featmap_shape=[1, 1024, 24, 24], qkv_bias=True, **kwargs, ): super().__init__(**kwargs) if backbone_config is None: logger.info("`backbone_config` is `None`. Initializing the config with a `BiT` backbone.") backbone_config = { "global_padding": "same", "layer_type": "bottleneck", "depths": [3, 4, 9], "out_features": ["stage3"], "embedding_dynamic_padding": True, } if isinstance(backbone_config, dict): if "model_type" in backbone_config: backbone_config_class = CONFIG_MAPPING[backbone_config["model_type"]] else: logger.info( "`model_type` is not found in `backbone_config`. Use `Bit` as the backbone configuration class." ) backbone_config_class = BitConfig backbone_config = backbone_config_class(**backbone_config) self.backbone_featmap_shape = backbone_featmap_shape self.backbone_config = backbone_config self.hidden_size = hidden_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.intermediate_size = intermediate_size self.hidden_act = hidden_act self.hidden_dropout_prob = hidden_dropout_prob self.attention_probs_dropout_prob = attention_probs_dropout_prob self.initializer_range = initializer_range self.layer_norm_eps = layer_norm_eps self.image_size = image_size self.patch_size = patch_size self.num_channels = num_channels self.qkv_bias = qkv_bias def to_dict(self) -> Dict[str, any]: """ Serializes this instance to a Python dictionary. Override the default [`~PretrainedConfig.to_dict`]. Returns: `Dict[str, any]`: Dictionary of all the attributes that make up this configuration instance, """ output = copy.deepcopy(self.__dict__) output["backbone_config"] = self.backbone_config.to_dict() output["model_type"] = self.__class__.model_type return output
2877025939/PlanADScrollView
13,859
PlanADScrollView/PlanADScrollView/SDWebImage/SDWebImage/SDWebImageDownloader.m
/* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import "SDWebImageDownloader.h" #import "SDWebImageDownloaderOperation.h" #import <ImageIO/ImageIO.h> @implementation SDWebImageDownloadToken @end @interface SDWebImageDownloader () <NSURLSessionTaskDelegate, NSURLSessionDataDelegate> @property (strong, nonatomic, nonnull) NSOperationQueue *downloadQueue; @property (weak, nonatomic, nullable) NSOperation *lastAddedOperation; @property (assign, nonatomic, nullable) Class operationClass; @property (strong, nonatomic, nonnull) NSMutableDictionary<NSURL *, SDWebImageDownloaderOperation *> *URLOperations; @property (strong, nonatomic, nullable) SDHTTPHeadersMutableDictionary *HTTPHeaders; // This queue is used to serialize the handling of the network responses of all the download operation in a single queue @property (SDDispatchQueueSetterSementics, nonatomic, nullable) dispatch_queue_t barrierQueue; // The session in which data tasks will run @property (strong, nonatomic) NSURLSession *session; @end @implementation SDWebImageDownloader + (void)initialize { // Bind SDNetworkActivityIndicator if available (download it here: http://github.com/rs/SDNetworkActivityIndicator ) // To use it, just add #import "SDNetworkActivityIndicator.h" in addition to the SDWebImage import if (NSClassFromString(@"SDNetworkActivityIndicator")) { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Warc-performSelector-leaks" id activityIndicator = [NSClassFromString(@"SDNetworkActivityIndicator") performSelector:NSSelectorFromString(@"sharedActivityIndicator")]; #pragma clang diagnostic pop // Remove observer in case it was previously added. [[NSNotificationCenter defaultCenter] removeObserver:activityIndicator name:SDWebImageDownloadStartNotification object:nil]; [[NSNotificationCenter defaultCenter] removeObserver:activityIndicator name:SDWebImageDownloadStopNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:activityIndicator selector:NSSelectorFromString(@"startActivity") name:SDWebImageDownloadStartNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:activityIndicator selector:NSSelectorFromString(@"stopActivity") name:SDWebImageDownloadStopNotification object:nil]; } } + (nonnull instancetype)sharedDownloader { static dispatch_once_t once; static id instance; dispatch_once(&once, ^{ instance = [self new]; }); return instance; } - (nonnull instancetype)init { return [self initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; } - (nonnull instancetype)initWithSessionConfiguration:(nullable NSURLSessionConfiguration *)sessionConfiguration { if ((self = [super init])) { _operationClass = [SDWebImageDownloaderOperation class]; _shouldDecompressImages = YES; _executionOrder = SDWebImageDownloaderFIFOExecutionOrder; _downloadQueue = [NSOperationQueue new]; _downloadQueue.maxConcurrentOperationCount = 6; _downloadQueue.name = @"com.hackemist.SDWebImageDownloader"; _URLOperations = [NSMutableDictionary new]; #ifdef SD_WEBP _HTTPHeaders = [@{@"Accept": @"image/webp,image/*;q=0.8"} mutableCopy]; #else _HTTPHeaders = [@{@"Accept": @"image/*;q=0.8"} mutableCopy]; #endif _barrierQueue = dispatch_queue_create("com.hackemist.SDWebImageDownloaderBarrierQueue", DISPATCH_QUEUE_CONCURRENT); _downloadTimeout = 15.0; sessionConfiguration.timeoutIntervalForRequest = _downloadTimeout; /** * Create the session for this task * We send nil as delegate queue so that the session creates a serial operation queue for performing all delegate * method calls and completion handler calls. */ self.session = [NSURLSession sessionWithConfiguration:sessionConfiguration delegate:self delegateQueue:nil]; } return self; } - (void)dealloc { [self.session invalidateAndCancel]; self.session = nil; [self.downloadQueue cancelAllOperations]; SDDispatchQueueRelease(_barrierQueue); } - (void)setValue:(nullable NSString *)value forHTTPHeaderField:(nullable NSString *)field { if (value) { self.HTTPHeaders[field] = value; } else { [self.HTTPHeaders removeObjectForKey:field]; } } - (nullable NSString *)valueForHTTPHeaderField:(nullable NSString *)field { return self.HTTPHeaders[field]; } - (void)setMaxConcurrentDownloads:(NSInteger)maxConcurrentDownloads { _downloadQueue.maxConcurrentOperationCount = maxConcurrentDownloads; } - (NSUInteger)currentDownloadCount { return _downloadQueue.operationCount; } - (NSInteger)maxConcurrentDownloads { return _downloadQueue.maxConcurrentOperationCount; } - (void)setOperationClass:(nullable Class)operationClass { if (operationClass && [operationClass isSubclassOfClass:[NSOperation class]] && [operationClass conformsToProtocol:@protocol(SDWebImageDownloaderOperationInterface)]) { _operationClass = operationClass; } else { _operationClass = [SDWebImageDownloaderOperation class]; } } - (nullable SDWebImageDownloadToken *)downloadImageWithURL:(nullable NSURL *)url options:(SDWebImageDownloaderOptions)options progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock completed:(nullable SDWebImageDownloaderCompletedBlock)completedBlock { __weak SDWebImageDownloader *wself = self; return [self addProgressCallback:progressBlock completedBlock:completedBlock forURL:url createCallback:^SDWebImageDownloaderOperation *{ __strong __typeof (wself) sself = wself; NSTimeInterval timeoutInterval = sself.downloadTimeout; if (timeoutInterval == 0.0) { timeoutInterval = 15.0; } // In order to prevent from potential duplicate caching (NSURLCache + SDImageCache) we disable the cache for image requests if told otherwise NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:(options & SDWebImageDownloaderUseNSURLCache ? NSURLRequestUseProtocolCachePolicy : NSURLRequestReloadIgnoringLocalCacheData) timeoutInterval:timeoutInterval]; request.HTTPShouldHandleCookies = (options & SDWebImageDownloaderHandleCookies); request.HTTPShouldUsePipelining = YES; if (sself.headersFilter) { request.allHTTPHeaderFields = sself.headersFilter(url, [sself.HTTPHeaders copy]); } else { request.allHTTPHeaderFields = sself.HTTPHeaders; } SDWebImageDownloaderOperation *operation = [[sself.operationClass alloc] initWithRequest:request inSession:sself.session options:options]; operation.shouldDecompressImages = sself.shouldDecompressImages; if (sself.urlCredential) { operation.credential = sself.urlCredential; } else if (sself.username && sself.password) { operation.credential = [NSURLCredential credentialWithUser:sself.username password:sself.password persistence:NSURLCredentialPersistenceForSession]; } if (options & SDWebImageDownloaderHighPriority) { operation.queuePriority = NSOperationQueuePriorityHigh; } else if (options & SDWebImageDownloaderLowPriority) { operation.queuePriority = NSOperationQueuePriorityLow; } [sself.downloadQueue addOperation:operation]; if (sself.executionOrder == SDWebImageDownloaderLIFOExecutionOrder) { // Emulate LIFO execution order by systematically adding new operations as last operation's dependency [sself.lastAddedOperation addDependency:operation]; sself.lastAddedOperation = operation; } return operation; }]; } - (void)cancel:(nullable SDWebImageDownloadToken *)token { dispatch_barrier_async(self.barrierQueue, ^{ SDWebImageDownloaderOperation *operation = self.URLOperations[token.url]; BOOL canceled = [operation cancel:token.downloadOperationCancelToken]; if (canceled) { [self.URLOperations removeObjectForKey:token.url]; } }); } - (nullable SDWebImageDownloadToken *)addProgressCallback:(SDWebImageDownloaderProgressBlock)progressBlock completedBlock:(SDWebImageDownloaderCompletedBlock)completedBlock forURL:(nullable NSURL *)url createCallback:(SDWebImageDownloaderOperation *(^)())createCallback { // The URL will be used as the key to the callbacks dictionary so it cannot be nil. If it is nil immediately call the completed block with no image or data. if (url == nil) { if (completedBlock != nil) { completedBlock(nil, nil, nil, NO); } return nil; } __block SDWebImageDownloadToken *token = nil; dispatch_barrier_sync(self.barrierQueue, ^{ SDWebImageDownloaderOperation *operation = self.URLOperations[url]; if (!operation) { operation = createCallback(); self.URLOperations[url] = operation; __weak SDWebImageDownloaderOperation *woperation = operation; operation.completionBlock = ^{ SDWebImageDownloaderOperation *soperation = woperation; if (!soperation) return; if (self.URLOperations[url] == soperation) { [self.URLOperations removeObjectForKey:url]; }; }; } id downloadOperationCancelToken = [operation addHandlersForProgress:progressBlock completed:completedBlock]; token = [SDWebImageDownloadToken new]; token.url = url; token.downloadOperationCancelToken = downloadOperationCancelToken; }); return token; } - (void)setSuspended:(BOOL)suspended { (self.downloadQueue).suspended = suspended; } - (void)cancelAllDownloads { [self.downloadQueue cancelAllOperations]; } #pragma mark Helper methods - (SDWebImageDownloaderOperation *)operationWithTask:(NSURLSessionTask *)task { SDWebImageDownloaderOperation *returnOperation = nil; for (SDWebImageDownloaderOperation *operation in self.downloadQueue.operations) { if (operation.dataTask.taskIdentifier == task.taskIdentifier) { returnOperation = operation; break; } } return returnOperation; } #pragma mark NSURLSessionDataDelegate - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler { // Identify the operation that runs this task and pass it the delegate method SDWebImageDownloaderOperation *dataOperation = [self operationWithTask:dataTask]; [dataOperation URLSession:session dataTask:dataTask didReceiveResponse:response completionHandler:completionHandler]; } - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data { // Identify the operation that runs this task and pass it the delegate method SDWebImageDownloaderOperation *dataOperation = [self operationWithTask:dataTask]; [dataOperation URLSession:session dataTask:dataTask didReceiveData:data]; } - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask willCacheResponse:(NSCachedURLResponse *)proposedResponse completionHandler:(void (^)(NSCachedURLResponse *cachedResponse))completionHandler { // Identify the operation that runs this task and pass it the delegate method SDWebImageDownloaderOperation *dataOperation = [self operationWithTask:dataTask]; [dataOperation URLSession:session dataTask:dataTask willCacheResponse:proposedResponse completionHandler:completionHandler]; } #pragma mark NSURLSessionTaskDelegate - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error { // Identify the operation that runs this task and pass it the delegate method SDWebImageDownloaderOperation *dataOperation = [self operationWithTask:task]; [dataOperation URLSession:session task:task didCompleteWithError:error]; } - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task willPerformHTTPRedirection:(NSHTTPURLResponse *)response newRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURLRequest * _Nullable))completionHandler { completionHandler(request); } - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler { // Identify the operation that runs this task and pass it the delegate method SDWebImageDownloaderOperation *dataOperation = [self operationWithTask:task]; [dataOperation URLSession:session task:task didReceiveChallenge:challenge completionHandler:completionHandler]; } @end
2881099/csredis
3,578
src/CSRedisCore/Internal/RedisTransaction.cs
using CSRedis.Internal.Commands; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CSRedis.Internal { class RedisTransaction { readonly RedisConnector _connector; readonly RedisArray _execCommand; readonly List<Tuple<string, object[]>> _pipeCommands = new List<Tuple<string, object[]>>(); public event EventHandler<RedisTransactionQueuedEventArgs> TransactionQueued; bool _active; public bool Active { get { return _active; } } public RedisTransaction(RedisConnector connector) { _connector = connector; _execCommand = RedisCommands.Exec(); } public string Start() { _active = true; return _connector.Call(RedisCommands.Multi()); } public T Write<T>(RedisCommand<T> command) { string response = _connector.Call(RedisCommands.AsTransaction(command)); OnTransactionQueued(command, response); _execCommand.AddParser(x => command.Parse(x)); return default(T); } public object[] Execute() { _active = false; if (_connector.IsConnected && _connector.IsPipelined) { _connector.Call(_execCommand); object[] response = _connector.EndPipe(); for (int i = 1; i < response.Length - 1; i++) OnTransactionQueued(_pipeCommands[i - 1].Item1, _pipeCommands[i - 1].Item2, response[i - 1].ToString()); object transaction_response = response[response.Length - 1]; if (!(transaction_response is object[])) throw new RedisProtocolException("Unexpected response"); return transaction_response as object[]; } return _connector.Call(_execCommand); } public string Abort() { _active = false; return _connector.Call(RedisCommands.Discard()); } void OnTransactionQueued<T>(RedisCommand<T> command, string response) { if (_connector.IsPipelined) _pipeCommands.Add(Tuple.Create(command.Command, command.Arguments)); else OnTransactionQueued(command.Command, command.Arguments, response); } void OnTransactionQueued(string command, object[] args, string response) { if (TransactionQueued != null) TransactionQueued(this, new RedisTransactionQueuedEventArgs(response, command, args)); } #if net40 #else public Task<string> StartAsync() { _active = true; return _connector.CallAsync(RedisCommands.Multi()); } public Task<T> WriteAsync<T>(RedisCommand<T> command) { lock (_execCommand) { _execCommand.AddParser(x => command.Parse(x)); return _connector.CallAsync(RedisCommands.AsTransaction(command)) .ContinueWith(t => OnTransactionQueued(command, t.Result)) .ContinueWith(t => default(T)); } } public Task<object[]> ExecuteAsync() { _active = false; return _connector.CallAsync(_execCommand); } public Task<string> AbortAsync() { _active = false; return _connector.CallAsync(RedisCommands.Discard()); } #endif } }
2877025939/PlanADScrollView
2,857
PlanADScrollView/PlanADScrollView/SDWebImage/SDWebImage/SDWebImageCompat.h
/* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * (c) Jamie Pinkham * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import <TargetConditionals.h> #ifdef __OBJC_GC__ #error SDWebImage does not support Objective-C Garbage Collection #endif // Apple's defines from TargetConditionals.h are a bit weird. // Seems like TARGET_OS_MAC is always defined (on all platforms). // To determine if we are running on OSX, we can only relly on TARGET_OS_IPHONE=0 and all the other platforms #if !TARGET_OS_IPHONE && !TARGET_OS_IOS && !TARGET_OS_TV && !TARGET_OS_WATCH #define SD_MAC 1 #else #define SD_MAC 0 #endif // iOS and tvOS are very similar, UIKit exists on both platforms // Note: watchOS also has UIKit, but it's very limited #if TARGET_OS_IOS || TARGET_OS_TV #define SD_UIKIT 1 #else #define SD_UIKIT 0 #endif #if TARGET_OS_IOS #define SD_IOS 1 #else #define SD_IOS 0 #endif #if TARGET_OS_TV #define SD_TV 1 #else #define SD_TV 0 #endif #if TARGET_OS_WATCH #define SD_WATCH 1 #else #define SD_WATCH 0 #endif #if SD_MAC #import <AppKit/AppKit.h> #ifndef UIImage #define UIImage NSImage #endif #ifndef UIImageView #define UIImageView NSImageView #endif #ifndef UIView #define UIView NSView #endif #else #if __IPHONE_OS_VERSION_MIN_REQUIRED != 20000 && __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_5_0 #error SDWebImage doesn't support Deployment Target version < 5.0 #endif #if SD_UIKIT #import <UIKit/UIKit.h> #endif #if SD_WATCH #import <WatchKit/WatchKit.h> #endif #endif #ifndef NS_ENUM #define NS_ENUM(_type, _name) enum _name : _type _name; enum _name : _type #endif #ifndef NS_OPTIONS #define NS_OPTIONS(_type, _name) enum _name : _type _name; enum _name : _type #endif #if OS_OBJECT_USE_OBJC #undef SDDispatchQueueRelease #undef SDDispatchQueueSetterSementics #define SDDispatchQueueRelease(q) #define SDDispatchQueueSetterSementics strong #else #undef SDDispatchQueueRelease #undef SDDispatchQueueSetterSementics #define SDDispatchQueueRelease(q) (dispatch_release(q)) #define SDDispatchQueueSetterSementics assign #endif extern UIImage *SDScaledImageForKey(NSString *key, UIImage *image); typedef void(^SDWebImageNoParamsBlock)(); extern NSString *const SDWebImageErrorDomain; #ifndef dispatch_main_async_safe #define dispatch_main_async_safe(block)\ if (strcmp(dispatch_queue_get_label(DISPATCH_CURRENT_QUEUE_LABEL), dispatch_queue_get_label(dispatch_get_main_queue())) == 0) {\ block();\ } else {\ dispatch_async(dispatch_get_main_queue(), block);\ } #endif static int64_t kAsyncTestTimeout = 5;
2877025939/PlanADScrollView
5,019
PlanADScrollView/PlanADScrollView/SDWebImage/SDWebImage/SDWebImagePrefetcher.m
/* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import "SDWebImagePrefetcher.h" @interface SDWebImagePrefetcher () @property (strong, nonatomic, nonnull) SDWebImageManager *manager; @property (strong, nonatomic, nullable) NSArray<NSURL *> *prefetchURLs; @property (assign, nonatomic) NSUInteger requestedCount; @property (assign, nonatomic) NSUInteger skippedCount; @property (assign, nonatomic) NSUInteger finishedCount; @property (assign, nonatomic) NSTimeInterval startedTime; @property (copy, nonatomic, nullable) SDWebImagePrefetcherCompletionBlock completionBlock; @property (copy, nonatomic, nullable) SDWebImagePrefetcherProgressBlock progressBlock; @end @implementation SDWebImagePrefetcher + (nonnull instancetype)sharedImagePrefetcher { static dispatch_once_t once; static id instance; dispatch_once(&once, ^{ instance = [self new]; }); return instance; } - (nonnull instancetype)init { return [self initWithImageManager:[SDWebImageManager new]]; } - (nonnull instancetype)initWithImageManager:(SDWebImageManager *)manager { if ((self = [super init])) { _manager = manager; _options = SDWebImageLowPriority; _prefetcherQueue = dispatch_get_main_queue(); self.maxConcurrentDownloads = 3; } return self; } - (void)setMaxConcurrentDownloads:(NSUInteger)maxConcurrentDownloads { self.manager.imageDownloader.maxConcurrentDownloads = maxConcurrentDownloads; } - (NSUInteger)maxConcurrentDownloads { return self.manager.imageDownloader.maxConcurrentDownloads; } - (void)startPrefetchingAtIndex:(NSUInteger)index { if (index >= self.prefetchURLs.count) return; self.requestedCount++; [self.manager loadImageWithURL:self.prefetchURLs[index] options:self.options progress:nil completed:^(UIImage *image, NSData *data, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { if (!finished) return; self.finishedCount++; if (image) { if (self.progressBlock) { self.progressBlock(self.finishedCount,(self.prefetchURLs).count); } } else { if (self.progressBlock) { self.progressBlock(self.finishedCount,(self.prefetchURLs).count); } // Add last failed self.skippedCount++; } if ([self.delegate respondsToSelector:@selector(imagePrefetcher:didPrefetchURL:finishedCount:totalCount:)]) { [self.delegate imagePrefetcher:self didPrefetchURL:self.prefetchURLs[index] finishedCount:self.finishedCount totalCount:self.prefetchURLs.count ]; } if (self.prefetchURLs.count > self.requestedCount) { dispatch_async(self.prefetcherQueue, ^{ [self startPrefetchingAtIndex:self.requestedCount]; }); } else if (self.finishedCount == self.requestedCount) { [self reportStatus]; if (self.completionBlock) { self.completionBlock(self.finishedCount, self.skippedCount); self.completionBlock = nil; } self.progressBlock = nil; } }]; } - (void)reportStatus { NSUInteger total = (self.prefetchURLs).count; if ([self.delegate respondsToSelector:@selector(imagePrefetcher:didFinishWithTotalCount:skippedCount:)]) { [self.delegate imagePrefetcher:self didFinishWithTotalCount:(total - self.skippedCount) skippedCount:self.skippedCount ]; } } - (void)prefetchURLs:(nullable NSArray<NSURL *> *)urls { [self prefetchURLs:urls progress:nil completed:nil]; } - (void)prefetchURLs:(nullable NSArray<NSURL *> *)urls progress:(nullable SDWebImagePrefetcherProgressBlock)progressBlock completed:(nullable SDWebImagePrefetcherCompletionBlock)completionBlock { [self cancelPrefetching]; // Prevent duplicate prefetch request self.startedTime = CFAbsoluteTimeGetCurrent(); self.prefetchURLs = urls; self.completionBlock = completionBlock; self.progressBlock = progressBlock; if (urls.count == 0) { if (completionBlock) { completionBlock(0,0); } } else { // Starts prefetching from the very first image on the list with the max allowed concurrency NSUInteger listCount = self.prefetchURLs.count; for (NSUInteger i = 0; i < self.maxConcurrentDownloads && self.requestedCount < listCount; i++) { [self startPrefetchingAtIndex:i]; } } } - (void)cancelPrefetching { self.prefetchURLs = nil; self.skippedCount = 0; self.requestedCount = 0; self.finishedCount = 0; [self.manager cancelAll]; } @end
2881099/csredis
2,453
src/CSRedisCore/Internal/RedisPipeline.cs
using CSRedis.Internal.IO; using System; using System.Collections.Generic; using System.Collections.Concurrent; using System.IO; using System.Linq; using System.Text; namespace CSRedis.Internal { class RedisPipeline : IDisposable { readonly RedisIO _io; readonly MemoryStream _buffer; readonly object _bufferLock = new object(); readonly ConcurrentQueue<Func<object>> _parsers; public bool Active { get; private set; } internal RedisPipeline(RedisIO io) { _io = io; _buffer = new MemoryStream(); _parsers = new ConcurrentQueue<Func<object>>(); } public T Write<T>(RedisCommand<T> command) { var data = _io.Writer.Prepare(command); lock (_bufferLock) { _buffer.Write(data, 0, data.Length); _parsers.Enqueue(() => command.Parse(_io.Reader)); } return default(T); } public void Begin() { Active = true; } public object[] Flush() { try { object[] results = new object[0]; if (_parsers.IsEmpty == false) { lock (_bufferLock) { if (_parsers.IsEmpty == false) { _buffer.Position = 0; //Console.WriteLine(Encoding.UTF8.GetString(_buffer.ToArray())); _io.Write(_buffer); _buffer.SetLength(0); results = new object[_parsers.Count]; } } } for (int i = 0; i < results.Length; i++) if (_parsers.TryDequeue(out var func)) { try { results[i] = func(); } catch(Exception ex) { throw ex; } } return results; } finally { Active = false; } } public void Dispose() { _buffer.Dispose(); } } }
27182812/ChatGLM-LLaMA-chinese-insturct
31,950
src/transformers/models/vit_hybrid/modeling_vit_hybrid.py
# coding=utf-8 # Copyright 2022 Google AI, Ross Wightman, 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 ViT Hybrid model.""" import collections.abc import math from typing import Dict, List, Optional, Set, 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 BaseModelOutput, BaseModelOutputWithPooling, ImageClassifierOutput from ...modeling_utils import PreTrainedModel from ...pytorch_utils import find_pruneable_heads_and_indices, prune_linear_layer from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging from ..auto import AutoBackbone from .configuration_vit_hybrid import ViTHybridConfig logger = logging.get_logger(__name__) # General docstring _CONFIG_FOR_DOC = "ViTHybridConfig" # Base docstring _CHECKPOINT_FOR_DOC = "google/vit-hybrid-base-bit-384" _EXPECTED_OUTPUT_SHAPE = [1, 197, 768] # Image classification docstring _IMAGE_CLASS_CHECKPOINT = "google/vit-hybrid-base-bit-384" _IMAGE_CLASS_EXPECTED_OUTPUT = "tabby, tabby cat" VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST = [ "google/vit-hybrid-base-bit-384", # See all ViT hybrid models at https://huggingface.co/models?filter=vit-hybrid ] class ViTHybridEmbeddings(nn.Module): """ Construct the CLS token, position and patch embeddings. Optionally, also the mask token. """ # Copied from transformers.models.vit.modeling_vit.ViTEmbeddings.__init__ with ViT->ViTHybrid def __init__(self, config: ViTHybridConfig, use_mask_token: bool = False) -> None: super().__init__() self.cls_token = nn.Parameter(torch.randn(1, 1, config.hidden_size)) self.mask_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size)) if use_mask_token else None self.patch_embeddings = ViTHybridPatchEmbeddings(config) num_patches = self.patch_embeddings.num_patches self.position_embeddings = nn.Parameter(torch.randn(1, num_patches + 1, config.hidden_size)) self.dropout = nn.Dropout(config.hidden_dropout_prob) self.config = config def interpolate_pos_encoding(self, embeddings: torch.Tensor, height: int, width: int) -> torch.Tensor: """ This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher resolution images. Source: https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174 """ num_patches = embeddings.shape[1] - 1 num_positions = self.position_embeddings.shape[1] - 1 if num_patches == num_positions and height == width: return self.position_embeddings class_pos_embed = self.position_embeddings[:, 0] patch_pos_embed = self.position_embeddings[:, 1:] dim = embeddings.shape[-1] height = height // self.config.patch_size width = width // self.config.patch_size # we add a small number to avoid floating point error in the interpolation # see discussion at https://github.com/facebookresearch/dino/issues/8 height, width = height + 0.1, width + 0.1 patch_pos_embed = patch_pos_embed.reshape(1, int(math.sqrt(num_positions)), int(math.sqrt(num_positions)), dim) patch_pos_embed = patch_pos_embed.permute(0, 3, 1, 2) patch_pos_embed = nn.functional.interpolate( patch_pos_embed, scale_factor=(height / math.sqrt(num_positions), width / math.sqrt(num_positions)), mode="bicubic", align_corners=False, ) if int(height) != patch_pos_embed.shape[-2] or int(width) != patch_pos_embed.shape[-1]: raise ValueError(f"Invalid height or width: {height}, {width}") patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim) return torch.cat((class_pos_embed.unsqueeze(0), patch_pos_embed), dim=1) def forward( self, pixel_values: torch.Tensor, bool_masked_pos: Optional[torch.BoolTensor] = None, interpolate_pos_encoding: bool = False, ) -> torch.Tensor: batch_size, num_channels, height, width = pixel_values.shape embeddings = self.patch_embeddings(pixel_values, interpolate_pos_encoding=interpolate_pos_encoding) if bool_masked_pos is not None: seq_length = embeddings.shape[1] mask_tokens = self.mask_token.expand(batch_size, seq_length, -1) # replace the masked visual tokens by mask_tokens mask = bool_masked_pos.unsqueeze(-1).type_as(mask_tokens) embeddings = embeddings * (1.0 - mask) + mask_tokens * mask # add the [CLS] token to the embedded patch tokens cls_tokens = self.cls_token.expand(batch_size, -1, -1) embeddings = torch.cat((cls_tokens, embeddings), dim=1) # add positional encoding to each token if interpolate_pos_encoding: embeddings = embeddings + self.interpolate_pos_encoding(embeddings, height, width) else: embeddings = embeddings + self.position_embeddings embeddings = self.dropout(embeddings) return embeddings class ViTHybridPatchEmbeddings(nn.Module): """ This class turns `pixel_values` of shape `(batch_size, num_channels, height, width)` into the initial `hidden_states` (patch embeddings) of shape `(batch_size, seq_length, hidden_size)` to be consumed by a Transformer. """ def __init__(self, config, feature_size=None): super().__init__() image_size, patch_size = config.image_size, config.patch_size num_channels, hidden_size = config.num_channels, config.hidden_size image_size = image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, image_size) patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size) self.backbone = AutoBackbone.from_config(config.backbone_config) if self.backbone.config.model_type != "bit": raise ValueError(f"Backbone model type {self.backbone.model_type} is not supported.") feature_dim = self.backbone.channels[-1] if feature_size is None: feature_map = config.backbone_featmap_shape feature_size = feature_map[-2:] feature_dim = feature_map[1] else: feature_size = ( feature_size if isinstance(feature_size, collections.abc.Iterable) else (feature_size, feature_size) ) feature_dim = self.backbone.channels[-1] self.grid_size = (feature_size[0] // patch_size[0], feature_size[1] // patch_size[1]) self.num_patches = self.grid_size[0] * self.grid_size[1] self.image_size = image_size self.patch_size = patch_size self.num_channels = num_channels self.projection = nn.Conv2d(feature_dim, hidden_size, kernel_size=patch_size, stride=patch_size) def forward(self, pixel_values: torch.Tensor, interpolate_pos_encoding: bool = False) -> torch.Tensor: _, num_channels, height, width = pixel_values.shape if num_channels != self.num_channels: raise ValueError( "Make sure that the channel dimension of the pixel values match with the one set in the configuration." ) if not interpolate_pos_encoding: if height != self.image_size[0] or width != self.image_size[1]: raise ValueError( f"Input image size ({height}*{width}) doesn't match model" f" ({self.image_size[0]}*{self.image_size[1]})." ) features = self.backbone(pixel_values).feature_maps[-1] embeddings = self.projection(features).flatten(2).transpose(1, 2) return embeddings # Copied from transformers.models.vit.modeling_vit.ViTSelfAttention with ViT->ViTHybrid class ViTHybridSelfAttention(nn.Module): def __init__(self, config: ViTHybridConfig) -> None: super().__init__() if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"): raise ValueError( f"The hidden size {config.hidden_size,} is not a multiple of the number of attention " f"heads {config.num_attention_heads}." ) self.num_attention_heads = config.num_attention_heads self.attention_head_size = int(config.hidden_size / config.num_attention_heads) self.all_head_size = self.num_attention_heads * self.attention_head_size self.query = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias) self.key = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias) self.value = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias) self.dropout = nn.Dropout(config.attention_probs_dropout_prob) def transpose_for_scores(self, x: torch.Tensor) -> torch.Tensor: new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size) x = x.view(new_x_shape) return x.permute(0, 2, 1, 3) def forward( self, hidden_states, head_mask: Optional[torch.Tensor] = None, output_attentions: bool = False ) -> Union[Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor]]: mixed_query_layer = self.query(hidden_states) key_layer = self.transpose_for_scores(self.key(hidden_states)) value_layer = self.transpose_for_scores(self.value(hidden_states)) query_layer = self.transpose_for_scores(mixed_query_layer) # Take the dot product between "query" and "key" to get the raw attention scores. attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2)) attention_scores = attention_scores / math.sqrt(self.attention_head_size) # Normalize the attention scores to probabilities. attention_probs = nn.functional.softmax(attention_scores, dim=-1) # This is actually dropping out entire tokens to attend to, which might # seem a bit unusual, but is taken from the original Transformer paper. attention_probs = self.dropout(attention_probs) # Mask heads if we want to if head_mask is not None: attention_probs = attention_probs * head_mask context_layer = torch.matmul(attention_probs, value_layer) context_layer = context_layer.permute(0, 2, 1, 3).contiguous() new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,) context_layer = context_layer.view(new_context_layer_shape) outputs = (context_layer, attention_probs) if output_attentions else (context_layer,) return outputs # Copied from transformers.models.vit.modeling_vit.ViTSelfOutput with ViT->ViTHybrid class ViTHybridSelfOutput(nn.Module): """ The residual connection is defined in ViTHybridLayer instead of here (as is the case with other models), due to the layernorm applied before each block. """ def __init__(self, config: ViTHybridConfig) -> None: super().__init__() self.dense = nn.Linear(config.hidden_size, config.hidden_size) self.dropout = nn.Dropout(config.hidden_dropout_prob) def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor: hidden_states = self.dense(hidden_states) hidden_states = self.dropout(hidden_states) return hidden_states # Copied from transformers.models.vit.modeling_vit.ViTAttention with ViT->ViTHybrid class ViTHybridAttention(nn.Module): def __init__(self, config: ViTHybridConfig) -> None: super().__init__() self.attention = ViTHybridSelfAttention(config) self.output = ViTHybridSelfOutput(config) self.pruned_heads = set() def prune_heads(self, heads: Set[int]) -> None: if len(heads) == 0: return heads, index = find_pruneable_heads_and_indices( heads, self.attention.num_attention_heads, self.attention.attention_head_size, self.pruned_heads ) # Prune linear layers self.attention.query = prune_linear_layer(self.attention.query, index) self.attention.key = prune_linear_layer(self.attention.key, index) self.attention.value = prune_linear_layer(self.attention.value, index) self.output.dense = prune_linear_layer(self.output.dense, index, dim=1) # Update hyper params and store pruned heads self.attention.num_attention_heads = self.attention.num_attention_heads - len(heads) self.attention.all_head_size = self.attention.attention_head_size * self.attention.num_attention_heads self.pruned_heads = self.pruned_heads.union(heads) def forward( self, hidden_states: torch.Tensor, head_mask: Optional[torch.Tensor] = None, output_attentions: bool = False, ) -> Union[Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor]]: self_outputs = self.attention(hidden_states, head_mask, output_attentions) attention_output = self.output(self_outputs[0], hidden_states) outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them return outputs # Copied from transformers.models.vit.modeling_vit.ViTIntermediate with ViT->ViTHybrid class ViTHybridIntermediate(nn.Module): def __init__(self, config: ViTHybridConfig) -> None: super().__init__() self.dense = nn.Linear(config.hidden_size, config.intermediate_size) if isinstance(config.hidden_act, str): self.intermediate_act_fn = ACT2FN[config.hidden_act] else: self.intermediate_act_fn = config.hidden_act def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: hidden_states = self.dense(hidden_states) hidden_states = self.intermediate_act_fn(hidden_states) return hidden_states # Copied from transformers.models.vit.modeling_vit.ViTOutput with ViT->ViTHybrid class ViTHybridOutput(nn.Module): def __init__(self, config: ViTHybridConfig) -> None: super().__init__() self.dense = nn.Linear(config.intermediate_size, config.hidden_size) self.dropout = nn.Dropout(config.hidden_dropout_prob) def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor: hidden_states = self.dense(hidden_states) hidden_states = self.dropout(hidden_states) hidden_states = hidden_states + input_tensor return hidden_states class ViTHybridLayer(nn.Module): """This corresponds to the Block class in the timm implementation.""" def __init__(self, config: ViTHybridConfig) -> None: super().__init__() self.chunk_size_feed_forward = config.chunk_size_feed_forward self.seq_len_dim = 1 self.attention = ViTHybridAttention(config) self.intermediate = ViTHybridIntermediate(config) self.output = ViTHybridOutput(config) self.layernorm_before = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) self.layernorm_after = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) def forward( self, hidden_states: torch.Tensor, head_mask: Optional[torch.Tensor] = None, output_attentions: bool = False, ) -> Union[Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor]]: self_attention_outputs = self.attention( self.layernorm_before(hidden_states), # in ViTHybrid, layernorm is applied before self-attention head_mask, output_attentions=output_attentions, ) attention_output = self_attention_outputs[0] outputs = self_attention_outputs[1:] # add self attentions if we output attention weights # first residual connection # We assign to correct device for `accelerate`, check: https://github.com/huggingface/transformers/pull/20705/ hidden_states = attention_output + hidden_states.to(attention_output.device) # in ViTHybrid, layernorm is also applied after self-attention layer_output = self.layernorm_after(hidden_states) layer_output = self.intermediate(layer_output) # second residual connection is done here layer_output = self.output(layer_output, hidden_states) outputs = (layer_output,) + outputs return outputs # Copied from transformers.models.vit.modeling_vit.ViTEncoder with ViT->ViTHybrid class ViTHybridEncoder(nn.Module): def __init__(self, config: ViTHybridConfig) -> None: super().__init__() self.config = config self.layer = nn.ModuleList([ViTHybridLayer(config) for _ in range(config.num_hidden_layers)]) self.gradient_checkpointing = False def forward( self, hidden_states: torch.Tensor, head_mask: Optional[torch.Tensor] = None, output_attentions: bool = False, output_hidden_states: bool = False, return_dict: bool = True, ) -> Union[tuple, BaseModelOutput]: all_hidden_states = () if output_hidden_states else None all_self_attentions = () if output_attentions else None for i, layer_module in enumerate(self.layer): if output_hidden_states: all_hidden_states = all_hidden_states + (hidden_states,) layer_head_mask = head_mask[i] if head_mask is not None else None if self.gradient_checkpointing and self.training: def create_custom_forward(module): def custom_forward(*inputs): return module(*inputs, output_attentions) return custom_forward layer_outputs = torch.utils.checkpoint.checkpoint( create_custom_forward(layer_module), hidden_states, layer_head_mask, ) else: layer_outputs = layer_module(hidden_states, layer_head_mask, output_attentions) hidden_states = layer_outputs[0] if output_attentions: all_self_attentions = all_self_attentions + (layer_outputs[1],) if output_hidden_states: all_hidden_states = all_hidden_states + (hidden_states,) if not return_dict: return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None) return BaseModelOutput( last_hidden_state=hidden_states, hidden_states=all_hidden_states, attentions=all_self_attentions, ) # Copied from transformers.models.vit.modeling_vit.ViTPreTrainedModel with ViT->ViTHybrid class ViTHybridPreTrainedModel(PreTrainedModel): """ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models. """ config_class = ViTHybridConfig base_model_prefix = "vit" main_input_name = "pixel_values" supports_gradient_checkpointing = True _no_split_modules = [] def _init_weights(self, module: Union[nn.Linear, nn.Conv2d, nn.LayerNorm]) -> None: """Initialize the weights""" if isinstance(module, (nn.Linear, nn.Conv2d)): # Upcast the input in `fp32` and cast it back to desired `dtype` to avoid # `trunc_normal_cpu` not implemented in `half` issues module.weight.data = nn.init.trunc_normal_( module.weight.data.to(torch.float32), mean=0.0, std=self.config.initializer_range ).to(module.weight.dtype) 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) elif isinstance(module, ViTHybridEmbeddings): module.position_embeddings.data = nn.init.trunc_normal_( module.position_embeddings.data.to(torch.float32), mean=0.0, std=self.config.initializer_range, ).to(module.position_embeddings.dtype) module.cls_token.data = nn.init.trunc_normal_( module.cls_token.data.to(torch.float32), mean=0.0, std=self.config.initializer_range, ).to(module.cls_token.dtype) def _set_gradient_checkpointing(self, module: ViTHybridEncoder, value: bool = False) -> None: if isinstance(module, ViTHybridEncoder): module.gradient_checkpointing = value VIT_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 ([`ViTHybridConfig`]): 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. """ VIT_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 [`ViTHybridImageProcessor.__call__`] for details. 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**. 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 ViT Hybrid Model transformer outputting raw hidden-states without any specific head on top.", VIT_START_DOCSTRING, ) # Copied from transformers.models.vit.modeling_vit.ViTModel with ViT->ViTHybrid class ViTHybridModel(ViTHybridPreTrainedModel): def __init__(self, config: ViTHybridConfig, add_pooling_layer: bool = True, use_mask_token: bool = False): super().__init__(config) self.config = config self.embeddings = ViTHybridEmbeddings(config, use_mask_token=use_mask_token) self.encoder = ViTHybridEncoder(config) self.layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) self.pooler = ViTHybridPooler(config) if add_pooling_layer else None # Initialize weights and apply final processing self.post_init() def get_input_embeddings(self) -> ViTHybridPatchEmbeddings: return self.embeddings.patch_embeddings def _prune_heads(self, heads_to_prune: Dict[int, List[int]]) -> None: """ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base class PreTrainedModel """ for layer, heads in heads_to_prune.items(): self.encoder.layer[layer].attention.prune_heads(heads) @add_start_docstrings_to_model_forward(VIT_INPUTS_DOCSTRING) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC, output_type=BaseModelOutputWithPooling, config_class=_CONFIG_FOR_DOC, modality="vision", expected_output=_EXPECTED_OUTPUT_SHAPE, ) def forward( self, pixel_values: Optional[torch.Tensor] = None, bool_masked_pos: Optional[torch.BoolTensor] = None, head_mask: Optional[torch.Tensor] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, interpolate_pos_encoding: Optional[bool] = None, return_dict: Optional[bool] = None, ) -> Union[Tuple, BaseModelOutputWithPooling]: 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 if pixel_values is None: raise ValueError("You have to specify pixel_values") # 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] # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length] head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers) # TODO: maybe have a cleaner way to cast the input (from `ImageProcessor` side?) expected_dtype = self.embeddings.patch_embeddings.projection.weight.dtype if pixel_values.dtype != expected_dtype: pixel_values = pixel_values.to(expected_dtype) embedding_output = self.embeddings( pixel_values, bool_masked_pos=bool_masked_pos, interpolate_pos_encoding=interpolate_pos_encoding ) encoder_outputs = self.encoder( embedding_output, head_mask=head_mask, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) sequence_output = encoder_outputs[0] sequence_output = self.layernorm(sequence_output) pooled_output = self.pooler(sequence_output) if self.pooler is not None else None if not return_dict: head_outputs = (sequence_output, pooled_output) if pooled_output is not None else (sequence_output,) return head_outputs + encoder_outputs[1:] return BaseModelOutputWithPooling( last_hidden_state=sequence_output, pooler_output=pooled_output, hidden_states=encoder_outputs.hidden_states, attentions=encoder_outputs.attentions, ) # Copied from transformers.models.vit.modeling_vit.ViTPooler with ViT->ViTHybrid class ViTHybridPooler(nn.Module): def __init__(self, config: ViTHybridConfig): super().__init__() self.dense = nn.Linear(config.hidden_size, config.hidden_size) self.activation = nn.Tanh() def forward(self, hidden_states): # We "pool" the model by simply taking the hidden state corresponding # to the first token. first_token_tensor = hidden_states[:, 0] pooled_output = self.dense(first_token_tensor) pooled_output = self.activation(pooled_output) return pooled_output @add_start_docstrings( """ ViT Hybrid Model transformer with an image classification head on top (a linear layer on top of the final hidden state of the [CLS] token) e.g. for ImageNet. """, VIT_START_DOCSTRING, ) # Copied from transformers.models.vit.modeling_vit.ViTForImageClassification with ViT->ViTHybrid class ViTHybridForImageClassification(ViTHybridPreTrainedModel): def __init__(self, config: ViTHybridConfig) -> None: super().__init__(config) self.num_labels = config.num_labels self.vit = ViTHybridModel(config, add_pooling_layer=False) # Classifier head self.classifier = nn.Linear(config.hidden_size, config.num_labels) if config.num_labels > 0 else nn.Identity() # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(VIT_INPUTS_DOCSTRING) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT, output_type=ImageClassifierOutput, config_class=_CONFIG_FOR_DOC, expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT, ) def forward( self, pixel_values: Optional[torch.Tensor] = None, head_mask: Optional[torch.Tensor] = None, labels: Optional[torch.Tensor] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, interpolate_pos_encoding: Optional[bool] = None, return_dict: Optional[bool] = None, ) -> Union[tuple, ImageClassifierOutput]: 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.vit( pixel_values, head_mask=head_mask, output_attentions=output_attentions, output_hidden_states=output_hidden_states, interpolate_pos_encoding=interpolate_pos_encoding, return_dict=return_dict, ) sequence_output = outputs[0] logits = self.classifier(sequence_output[:, 0, :]) 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[1:] return ((loss,) + output) if loss is not None else output return ImageClassifierOutput( loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions, )
2877025939/PlanADScrollView
10,722
PlanADScrollView/PlanADScrollView/SDWebImage/SDWebImage/SDWebImageManager.h
/* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import "SDWebImageCompat.h" #import "SDWebImageOperation.h" #import "SDWebImageDownloader.h" #import "SDImageCache.h" typedef NS_OPTIONS(NSUInteger, SDWebImageOptions) { /** * By default, when a URL fail to be downloaded, the URL is blacklisted so the library won't keep trying. * This flag disable this blacklisting. */ SDWebImageRetryFailed = 1 << 0, /** * By default, image downloads are started during UI interactions, this flags disable this feature, * leading to delayed download on UIScrollView deceleration for instance. */ SDWebImageLowPriority = 1 << 1, /** * This flag disables on-disk caching */ SDWebImageCacheMemoryOnly = 1 << 2, /** * This flag enables progressive download, the image is displayed progressively during download as a browser would do. * By default, the image is only displayed once completely downloaded. */ SDWebImageProgressiveDownload = 1 << 3, /** * Even if the image is cached, respect the HTTP response cache control, and refresh the image from remote location if needed. * The disk caching will be handled by NSURLCache instead of SDWebImage leading to slight performance degradation. * This option helps deal with images changing behind the same request URL, e.g. Facebook graph api profile pics. * If a cached image is refreshed, the completion block is called once with the cached image and again with the final image. * * Use this flag only if you can't make your URLs static with embedded cache busting parameter. */ SDWebImageRefreshCached = 1 << 4, /** * In iOS 4+, continue the download of the image if the app goes to background. This is achieved by asking the system for * extra time in background to let the request finish. If the background task expires the operation will be cancelled. */ SDWebImageContinueInBackground = 1 << 5, /** * Handles cookies stored in NSHTTPCookieStore by setting * NSMutableURLRequest.HTTPShouldHandleCookies = YES; */ SDWebImageHandleCookies = 1 << 6, /** * Enable to allow untrusted SSL certificates. * Useful for testing purposes. Use with caution in production. */ SDWebImageAllowInvalidSSLCertificates = 1 << 7, /** * By default, images are loaded in the order in which they were queued. This flag moves them to * the front of the queue. */ SDWebImageHighPriority = 1 << 8, /** * By default, placeholder images are loaded while the image is loading. This flag will delay the loading * of the placeholder image until after the image has finished loading. */ SDWebImageDelayPlaceholder = 1 << 9, /** * We usually don't call transformDownloadedImage delegate method on animated images, * as most transformation code would mangle it. * Use this flag to transform them anyway. */ SDWebImageTransformAnimatedImage = 1 << 10, /** * By default, image is added to the imageView after download. But in some cases, we want to * have the hand before setting the image (apply a filter or add it with cross-fade animation for instance) * Use this flag if you want to manually set the image in the completion when success */ SDWebImageAvoidAutoSetImage = 1 << 11, /** * By default, images are decoded respecting their original size. On iOS, this flag will scale down the * images to a size compatible with the constrained memory of devices. * If `SDWebImageProgressiveDownload` flag is set the scale down is deactivated. */ SDWebImageScaleDownLargeImages = 1 << 12 }; typedef void(^SDExternalCompletionBlock)(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL); typedef void(^SDInternalCompletionBlock)(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL); typedef NSString * _Nullable (^SDWebImageCacheKeyFilterBlock)(NSURL * _Nullable url); @class SDWebImageManager; @protocol SDWebImageManagerDelegate <NSObject> @optional /** * Controls which image should be downloaded when the image is not found in the cache. * * @param imageManager The current `SDWebImageManager` * @param imageURL The url of the image to be downloaded * * @return Return NO to prevent the downloading of the image on cache misses. If not implemented, YES is implied. */ - (BOOL)imageManager:(nonnull SDWebImageManager *)imageManager shouldDownloadImageForURL:(nullable NSURL *)imageURL; /** * Allows to transform the image immediately after it has been downloaded and just before to cache it on disk and memory. * NOTE: This method is called from a global queue in order to not to block the main thread. * * @param imageManager The current `SDWebImageManager` * @param image The image to transform * @param imageURL The url of the image to transform * * @return The transformed image object. */ - (nullable UIImage *)imageManager:(nonnull SDWebImageManager *)imageManager transformDownloadedImage:(nullable UIImage *)image withURL:(nullable NSURL *)imageURL; @end /** * The SDWebImageManager is the class behind the UIImageView+WebCache category and likes. * It ties the asynchronous downloader (SDWebImageDownloader) with the image cache store (SDImageCache). * You can use this class directly to benefit from web image downloading with caching in another context than * a UIView. * * Here is a simple example of how to use SDWebImageManager: * * @code SDWebImageManager *manager = [SDWebImageManager sharedManager]; [manager loadImageWithURL:imageURL options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { if (image) { // do something with image } }]; * @endcode */ @interface SDWebImageManager : NSObject @property (weak, nonatomic, nullable) id <SDWebImageManagerDelegate> delegate; @property (strong, nonatomic, readonly, nullable) SDImageCache *imageCache; @property (strong, nonatomic, readonly, nullable) SDWebImageDownloader *imageDownloader; /** * The cache filter is a block used each time SDWebImageManager need to convert an URL into a cache key. This can * be used to remove dynamic part of an image URL. * * The following example sets a filter in the application delegate that will remove any query-string from the * URL before to use it as a cache key: * * @code [[SDWebImageManager sharedManager] setCacheKeyFilter:^(NSURL *url) { url = [[NSURL alloc] initWithScheme:url.scheme host:url.host path:url.path]; return [url absoluteString]; }]; * @endcode */ @property (nonatomic, copy, nullable) SDWebImageCacheKeyFilterBlock cacheKeyFilter; /** * Returns global SDWebImageManager instance. * * @return SDWebImageManager shared instance */ + (nonnull instancetype)sharedManager; /** * Allows to specify instance of cache and image downloader used with image manager. * @return new instance of `SDWebImageManager` with specified cache and downloader. */ - (nonnull instancetype)initWithCache:(nonnull SDImageCache *)cache downloader:(nonnull SDWebImageDownloader *)downloader NS_DESIGNATED_INITIALIZER; /** * Downloads the image at the given URL if not present in cache or return the cached version otherwise. * * @param url The URL to the image * @param options A mask to specify options to use for this request * @param progressBlock A block called while image is downloading * @note the progress block is executed on a background queue * @param completedBlock A block called when operation has been completed. * * This parameter is required. * * This block has no return value and takes the requested UIImage as first parameter and the NSData representation as second parameter. * In case of error the image parameter is nil and the third parameter may contain an NSError. * * The forth parameter is an `SDImageCacheType` enum indicating if the image was retrieved from the local cache * or from the memory cache or from the network. * * The fith parameter is set to NO when the SDWebImageProgressiveDownload option is used and the image is * downloading. This block is thus called repeatedly with a partial image. When image is fully downloaded, the * block is called a last time with the full image and the last parameter set to YES. * * The last parameter is the original image URL * * @return Returns an NSObject conforming to SDWebImageOperation. Should be an instance of SDWebImageDownloaderOperation */ - (nullable id <SDWebImageOperation>)loadImageWithURL:(nullable NSURL *)url options:(SDWebImageOptions)options progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock completed:(nullable SDInternalCompletionBlock)completedBlock; /** * Saves image to cache for given URL * * @param image The image to cache * @param url The URL to the image * */ - (void)saveImageToCache:(nullable UIImage *)image forURL:(nullable NSURL *)url; /** * Cancel all current operations */ - (void)cancelAll; /** * Check one or more operations running */ - (BOOL)isRunning; /** * Async check if image has already been cached * * @param url image url * @param completionBlock the block to be executed when the check is finished * * @note the completion block is always executed on the main queue */ - (void)cachedImageExistsForURL:(nullable NSURL *)url completion:(nullable SDWebImageCheckCacheCompletionBlock)completionBlock; /** * Async check if image has already been cached on disk only * * @param url image url * @param completionBlock the block to be executed when the check is finished * * @note the completion block is always executed on the main queue */ - (void)diskImageExistsForURL:(nullable NSURL *)url completion:(nullable SDWebImageCheckCacheCompletionBlock)completionBlock; /** *Return the cache key for a given URL */ - (nullable NSString *)cacheKeyForURL:(nullable NSURL *)url; @end
2877025939/PlanADScrollView
1,709
PlanADScrollView/PlanADScrollView/SDWebImage/SDWebImage/UIImage+GIF.m
/* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * (c) Laurin Brandner * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import "UIImage+GIF.h" #import <ImageIO/ImageIO.h> #import "objc/runtime.h" #import "NSImage+WebCache.h" @implementation UIImage (GIF) + (UIImage *)sd_animatedGIFWithData:(NSData *)data { if (!data) { return nil; } CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL); size_t count = CGImageSourceGetCount(source); UIImage *staticImage; if (count <= 1) { staticImage = [[UIImage alloc] initWithData:data]; } else { // we will only retrieve the 1st frame. the full GIF support is available via the FLAnimatedImageView category. // this here is only code to allow drawing animated images as static ones #if SD_WATCH CGFloat scale = 1; scale = [WKInterfaceDevice currentDevice].screenScale; #elif SD_UIKIT CGFloat scale = 1; scale = [UIScreen mainScreen].scale; #endif CGImageRef CGImage = CGImageSourceCreateImageAtIndex(source, 0, NULL); #if SD_UIKIT || SD_WATCH UIImage *frameImage = [UIImage imageWithCGImage:CGImage scale:scale orientation:UIImageOrientationUp]; staticImage = [UIImage animatedImageWithImages:@[frameImage] duration:0.0f]; #elif SD_MAC staticImage = [[UIImage alloc] initWithCGImage:CGImage size:NSZeroSize]; #endif CGImageRelease(CGImage); } CFRelease(source); return staticImage; } - (BOOL)isGIF { return (self.images != nil); } @end
2877025939/PlanADScrollView
6,734
PlanADScrollView/PlanADScrollView/SDWebImage/SDWebImage/UIButton+WebCache.m
/* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import "UIButton+WebCache.h" #if SD_UIKIT #import "objc/runtime.h" #import "UIView+WebCacheOperation.h" #import "UIView+WebCache.h" static char imageURLStorageKey; typedef NSMutableDictionary<NSNumber *, NSURL *> SDStateImageURLDictionary; @implementation UIButton (WebCache) - (nullable NSURL *)sd_currentImageURL { NSURL *url = self.imageURLStorage[@(self.state)]; if (!url) { url = self.imageURLStorage[@(UIControlStateNormal)]; } return url; } - (nullable NSURL *)sd_imageURLForState:(UIControlState)state { return self.imageURLStorage[@(state)]; } #pragma mark - Image - (void)sd_setImageWithURL:(nullable NSURL *)url forState:(UIControlState)state { [self sd_setImageWithURL:url forState:state placeholderImage:nil options:0 completed:nil]; } - (void)sd_setImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder { [self sd_setImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:nil]; } - (void)sd_setImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options { [self sd_setImageWithURL:url forState:state placeholderImage:placeholder options:options completed:nil]; } - (void)sd_setImageWithURL:(nullable NSURL *)url forState:(UIControlState)state completed:(nullable SDExternalCompletionBlock)completedBlock { [self sd_setImageWithURL:url forState:state placeholderImage:nil options:0 completed:completedBlock]; } - (void)sd_setImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder completed:(nullable SDExternalCompletionBlock)completedBlock { [self sd_setImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:completedBlock]; } - (void)sd_setImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options completed:(nullable SDExternalCompletionBlock)completedBlock { if (!url) { [self.imageURLStorage removeObjectForKey:@(state)]; return; } self.imageURLStorage[@(state)] = url; __weak typeof(self)weakSelf = self; [self sd_internalSetImageWithURL:url placeholderImage:placeholder options:options operationKey:[NSString stringWithFormat:@"UIButtonImageOperation%@", @(state)] setImageBlock:^(UIImage *image, NSData *imageData) { [weakSelf setImage:image forState:state]; } progress:nil completed:completedBlock]; } #pragma mark - Background image - (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url forState:(UIControlState)state { [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:nil options:0 completed:nil]; } - (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder { [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:nil]; } - (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options { [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:options completed:nil]; } - (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url forState:(UIControlState)state completed:(nullable SDExternalCompletionBlock)completedBlock { [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:nil options:0 completed:completedBlock]; } - (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder completed:(nullable SDExternalCompletionBlock)completedBlock { [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:completedBlock]; } - (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options completed:(nullable SDExternalCompletionBlock)completedBlock { if (!url) { [self.imageURLStorage removeObjectForKey:@(state)]; return; } self.imageURLStorage[@(state)] = url; __weak typeof(self)weakSelf = self; [self sd_internalSetImageWithURL:url placeholderImage:placeholder options:options operationKey:[NSString stringWithFormat:@"UIButtonBackgroundImageOperation%@", @(state)] setImageBlock:^(UIImage *image, NSData *imageData) { [weakSelf setBackgroundImage:image forState:state]; } progress:nil completed:completedBlock]; } - (void)sd_setImageLoadOperation:(id<SDWebImageOperation>)operation forState:(UIControlState)state { [self sd_setImageLoadOperation:operation forKey:[NSString stringWithFormat:@"UIButtonImageOperation%@", @(state)]]; } - (void)sd_cancelImageLoadForState:(UIControlState)state { [self sd_cancelImageLoadOperationWithKey:[NSString stringWithFormat:@"UIButtonImageOperation%@", @(state)]]; } - (void)sd_setBackgroundImageLoadOperation:(id<SDWebImageOperation>)operation forState:(UIControlState)state { [self sd_setImageLoadOperation:operation forKey:[NSString stringWithFormat:@"UIButtonBackgroundImageOperation%@", @(state)]]; } - (void)sd_cancelBackgroundImageLoadForState:(UIControlState)state { [self sd_cancelImageLoadOperationWithKey:[NSString stringWithFormat:@"UIButtonBackgroundImageOperation%@", @(state)]]; } - (SDStateImageURLDictionary *)imageURLStorage { SDStateImageURLDictionary *storage = objc_getAssociatedObject(self, &imageURLStorageKey); if (!storage) { storage = [NSMutableDictionary dictionary]; objc_setAssociatedObject(self, &imageURLStorageKey, storage, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } return storage; } @end #endif
2877025939/PlanADScrollView
4,638
PlanADScrollView/PlanADScrollView/SDWebImage/SDWebImage/SDWebImageDownloaderOperation.h
/* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import <Foundation/Foundation.h> #import "SDWebImageDownloader.h" #import "SDWebImageOperation.h" extern NSString * _Nonnull const SDWebImageDownloadStartNotification; extern NSString * _Nonnull const SDWebImageDownloadReceiveResponseNotification; extern NSString * _Nonnull const SDWebImageDownloadStopNotification; extern NSString * _Nonnull const SDWebImageDownloadFinishNotification; /** Describes a downloader operation. If one wants to use a custom downloader op, it needs to inherit from `NSOperation` and conform to this protocol */ @protocol SDWebImageDownloaderOperationInterface<NSObject> - (nonnull instancetype)initWithRequest:(nullable NSURLRequest *)request inSession:(nullable NSURLSession *)session options:(SDWebImageDownloaderOptions)options; - (nullable id)addHandlersForProgress:(nullable SDWebImageDownloaderProgressBlock)progressBlock completed:(nullable SDWebImageDownloaderCompletedBlock)completedBlock; - (BOOL)shouldDecompressImages; - (void)setShouldDecompressImages:(BOOL)value; - (nullable NSURLCredential *)credential; - (void)setCredential:(nullable NSURLCredential *)value; @end @interface SDWebImageDownloaderOperation : NSOperation <SDWebImageDownloaderOperationInterface, SDWebImageOperation, NSURLSessionTaskDelegate, NSURLSessionDataDelegate> /** * The request used by the operation's task. */ @property (strong, nonatomic, readonly, nullable) NSURLRequest *request; /** * The operation's task */ @property (strong, nonatomic, readonly, nullable) NSURLSessionTask *dataTask; @property (assign, nonatomic) BOOL shouldDecompressImages; /** * Was used to determine whether the URL connection should consult the credential storage for authenticating the connection. * @deprecated Not used for a couple of versions */ @property (nonatomic, assign) BOOL shouldUseCredentialStorage __deprecated_msg("Property deprecated. Does nothing. Kept only for backwards compatibility"); /** * The credential used for authentication challenges in `-connection:didReceiveAuthenticationChallenge:`. * * This will be overridden by any shared credentials that exist for the username or password of the request URL, if present. */ @property (nonatomic, strong, nullable) NSURLCredential *credential; /** * The SDWebImageDownloaderOptions for the receiver. */ @property (assign, nonatomic, readonly) SDWebImageDownloaderOptions options; /** * The expected size of data. */ @property (assign, nonatomic) NSInteger expectedSize; /** * The response returned by the operation's connection. */ @property (strong, nonatomic, nullable) NSURLResponse *response; /** * Initializes a `SDWebImageDownloaderOperation` object * * @see SDWebImageDownloaderOperation * * @param request the URL request * @param session the URL session in which this operation will run * @param options downloader options * * @return the initialized instance */ - (nonnull instancetype)initWithRequest:(nullable NSURLRequest *)request inSession:(nullable NSURLSession *)session options:(SDWebImageDownloaderOptions)options NS_DESIGNATED_INITIALIZER; /** * Adds handlers for progress and completion. Returns a tokent that can be passed to -cancel: to cancel this set of * callbacks. * * @param progressBlock the block executed when a new chunk of data arrives. * @note the progress block is executed on a background queue * @param completedBlock the block executed when the download is done. * @note the completed block is executed on the main queue for success. If errors are found, there is a chance the block will be executed on a background queue * * @return the token to use to cancel this set of handlers */ - (nullable id)addHandlersForProgress:(nullable SDWebImageDownloaderProgressBlock)progressBlock completed:(nullable SDWebImageDownloaderCompletedBlock)completedBlock; /** * Cancels a set of callbacks. Once all callbacks are canceled, the operation is cancelled. * * @param token the token representing a set of callbacks to cancel * * @return YES if the operation was stopped because this was the last token to be canceled. NO otherwise. */ - (BOOL)cancel:(nullable id)token; @end
2881099/csredis
89,556
src/CSRedisCore/Internal/RedisCommand.cs
using CSRedis.Internal.Commands; using CSRedis.Internal.IO; using CSRedis.Internal.Utilities; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; namespace CSRedis { static class RedisCommands { #region Connection public static RedisStatus Auth(string user, string password) { if (string.IsNullOrEmpty(user)) return new RedisStatus("AUTH", password); return new RedisStatus("AUTH", user, password); } public static RedisString Echo(string message) { return new RedisString("ECHO", message); } public static RedisStatus Ping() { return new RedisStatus("PING"); } public static RedisStatus Quit() { return new RedisStatus("QUIT"); } public static RedisStatus Select(int index) { return new RedisStatus("SELECT", index); } #endregion #region Keys public static RedisInt Touch(params string[] keys) { return new RedisInt("TOUCH", keys); } public static RedisInt UnLink(params string[] keys) { return new RedisInt("UNLINK", keys); } public static RedisInt Del(params string[] keys) { return new RedisInt("DEL", keys); } public static RedisBytes Dump(string key) { return new RedisBytes("DUMP", key); } public static RedisBool Exists(string key) { return new RedisBool("EXISTS", key); } public static RedisInt Exists(string[] keys) { return new RedisInt("EXISTS", keys); } public static RedisBool Expire(string key, TimeSpan expiration) { return new RedisBool("EXPIRE", key, (int)expiration.TotalSeconds); } public static RedisBool Expire(string key, int seconds) { return new RedisBool("EXPIRE", key, seconds); } public static RedisBool ExpireAt(string key, DateTime expirationDate) { return ExpireAt(key, (int)RedisDate.ToTimestamp(expirationDate).TotalSeconds); } public static RedisBool ExpireAt(string key, int timestamp) { return new RedisBool("EXPIREAT", key, timestamp); } public static RedisArray.Strings Keys(string pattern) { return new RedisArray.Strings("KEYS", pattern); } public static RedisStatus Migrate(string host, int port, string key, int destinationDb, int timeoutMilliseconds) { return new RedisStatus("MIGRATE", host, port, key, destinationDb, timeoutMilliseconds); } public static RedisStatus Migrate(string host, int port, string key, int destinationDb, TimeSpan timeout) { return Migrate(host, port, key, destinationDb, (int)timeout.TotalMilliseconds); } public static RedisBool Move(string key, int database) { return new RedisBool("MOVE", key, database); } public static RedisString ObjectEncoding(params string[] arguments) { object[] args = RedisArgs.Concat("ENCODING", arguments); return new RedisString("OBJECT", args); } public static RedisInt.Nullable Object(RedisObjectSubCommand subCommand, params string[] arguments) { object[] args = RedisArgs.Concat(subCommand.ToString().ToUpperInvariant(), arguments); return new RedisInt.Nullable("OBJECT", args); } public static RedisBool Persist(string key) { return new RedisBool("PERSIST", key); } public static RedisBool PExpire(string key, TimeSpan expiration) { return new RedisBool("PEXPIRE", key, (int)expiration.TotalMilliseconds); } public static RedisBool PExpire(string key, long milliseconds) { return new RedisBool("PEXPIRE", key, milliseconds); } public static RedisBool PExpireAt(string key, DateTime date) { return PExpireAt(key, (long)RedisDate.ToTimestamp(date).TotalMilliseconds); } public static RedisBool PExpireAt(string key, long timestamp) { return new RedisBool("PEXPIREAT", key, timestamp); } public static RedisInt PTtl(string key) { return new RedisInt("PTTL", key); } public static RedisString RandomKey() { return new RedisString("RANDOMKEY"); } public static RedisStatus Rename(string key, string newKey) { return new RedisStatus("RENAME", key, newKey); } public static RedisBool RenameNx(string key, string newKey) { return new RedisBool("RENAMENX", key, newKey); } public static RedisStatus Restore(string key, long ttl, byte[] serializedValue) { return new RedisStatus("RESTORE", key, ttl, serializedValue); } public static RedisArray.Generic<Dictionary<string, string>> Sort(string key, long? offset = null, long? count = null, string by = null, RedisSortDir? dir = null, bool? isAlpha = null, bool? isHash = null, params string[] get) { List<string> args = new List<string>(); args.Add(key); if (by != null) args.AddRange(new[] { "BY", by }); if (offset.HasValue && count.HasValue) args.AddRange(new[] { "LIMIT", offset.Value.ToString(), count.Value.ToString() }); foreach (var pattern in get) args.AddRange(new[] { "GET", pattern }); if (dir.HasValue) args.Add(dir.ToString().ToUpperInvariant()); if (isAlpha.HasValue && isAlpha.Value) args.Add("ALPHA"); return new RedisArray.Generic<Dictionary<string, string>>(new RedisHash("SORT", args.ToArray())); } public static RedisArray.Strings Sort(string key, long? offset = null, long? count = null, string by = null, RedisSortDir? dir = null, bool? isAlpha = null, params string[] get) { List<string> args = new List<string>(); args.Add(key); if (by != null) args.AddRange(new[] { "BY", by }); if (count.HasValue) args.AddRange(new[] { "LIMIT", offset?.ToString() ?? "0", count.Value.ToString() }); foreach (var pattern in get) args.AddRange(new[] { "GET", pattern }); if (dir.HasValue) args.Add(dir.ToString().ToUpperInvariant()); if (isAlpha.HasValue && isAlpha.Value) args.Add("ALPHA"); return new RedisArray.Strings("SORT", args.ToArray()); } public static RedisInt SortAndStore(string key, string destination, long? offset = null, long? count = null, string by = null, RedisSortDir? dir = null, bool? isAlpha = null, params string[] get) { List<string> args = new List<string>(); args.Add(key); if (by != null) args.AddRange(new[] { "BY", by }); if (count.HasValue) args.AddRange(new[] { "LIMIT", offset?.ToString() ?? "0", count.Value.ToString() }); foreach (var pattern in get) args.AddRange(new[] { "GET", pattern }); if (dir.HasValue) args.Add(dir.ToString().ToUpperInvariant()); if (isAlpha.HasValue && isAlpha.Value) args.Add("ALPHA"); args.AddRange(new[] { "STORE", destination }); return new RedisInt("SORT", args.ToArray()); } public static RedisInt Ttl(string key) { return new RedisInt("TTL", key); } public static RedisStatus Type(string key) { return new RedisStatus("TYPE", key); } public static RedisScanCommand<string> Scan(long cursor, string pattern = null, long? count = null) { var args = new List<object>(); args.Add(cursor); if (pattern != null) args.AddRange(new[] { "MATCH", pattern }); if (count != null) args.AddRange(new object[] { "COUNT", count }); return new RedisScanCommand<string>( new RedisArray.Strings("SCAN", args.ToArray())); } public static RedisScanCommand<byte[]> ScanBytes(long cursor, string pattern = null, long? count = null) { var args = new List<object>(); args.Add(cursor); if (pattern != null) args.AddRange(new[] { "MATCH", pattern }); if (count != null) args.AddRange(new object[] { "COUNT", count }); return new RedisScanCommand<byte[]>( new RedisArray.Bytes("SCAN", args.ToArray())); } #endregion #region Hashes public static RedisInt HStrLen(string key, string field) { object[] args = RedisArgs.Concat(key, field); return new RedisInt("HSTRLEN", args); } public static RedisInt HDel(string key, params string[] fields) { object[] args = RedisArgs.Concat(key, fields); return new RedisInt("HDEL", args); } public static RedisBool HExists(string key, string field) { return new RedisBool("HEXISTS", key, field); } public static RedisString HGet(string key, string field) { return new RedisString("HGET", key, field); } public static RedisBytes HGetBytes(string key, string field) { return new RedisBytes("HGET", key, field); } public static RedisHash.Generic<T> HGetAll<T>(string key) where T : class { return new RedisHash.Generic<T>("HGETALL", key); } public static RedisHash HGetAll(string key) { return new RedisHash("HGETALL", key); } public static RedisHashBytes HGetAllBytes(string key) { return new RedisHashBytes("HGETALL", key); } public static RedisInt HIncrBy(string key, string field, long increment) { return new RedisInt("HINCRBY", key, field, increment); } public static RedisFloat HIncrByFloat(string key, string field, decimal increment) { return new RedisFloat("HINCRBYFLOAT", key, field, increment); } public static RedisArray.Strings HKeys(string key) { return new RedisArray.Strings("HKEYS", key); } public static RedisInt HLen(string key) { return new RedisInt("HLEN", key); } public static RedisArray.Strings HMGet(string key, params string[] fields) { object[] args = RedisArgs.Concat(key, fields); return new RedisArray.Strings("HMGET", args); } public static RedisArray.Bytes HMGetBytes(string key, params string[] fields) { object[] args = RedisArgs.Concat(key, fields); return new RedisArray.Bytes("HMGET", args); } public static RedisStatus HMSet(string key, Dictionary<string, object> dict) { List<object> args = new List<object> { key }; args.AddRange(RedisArgs.FromDict(dict)); return new RedisStatus("HMSET", args.ToArray()); } public static RedisStatus HMSet<T>(string key, T obj) where T : class { List<object> args = new List<object> { key }; args.AddRange(RedisArgs.FromObject(obj)); return new RedisStatus("HMSET", args.ToArray()); } public static RedisStatus HMSet(string key, params object[] keyValues) { List<object> args = new List<object> { key }; for (int i = 0; i < keyValues.Length; i += 2) { if (keyValues[i] != null && keyValues[i + 1] != null) args.AddRange(new[] { keyValues[i], keyValues[i + 1] }); } return new RedisStatus("HMSET", args.ToArray()); } public static RedisBool HSet(string key, string field, object value) { return new RedisBool("HSET", key, field, value); } public static RedisBool HSetNx(string key, string field, object value) { return new RedisBool("HSETNX", key, field, value); } public static RedisArray.Strings HVals(string key) { return new RedisArray.Strings("HVALS", key); } public static RedisArray.Bytes HValsBytes(string key) { return new RedisArray.Bytes("HVALS", key); } public static RedisScanCommand<Tuple<string, string>> HScan(string key, long cursor, string pattern = null, long? count = null) { var args = new List<object>(); args.Add(key); args.Add(cursor); if (pattern != null) args.AddRange(new[] { "MATCH", pattern }); if (count != null) args.AddRange(new object[] { "COUNT", count }); return new RedisScanCommand<Tuple<string, string>>( new RedisArray.WeakPairs<string, string>("HSCAN", args.ToArray())); //new RedisArray.Generic<Tuple<string, string>>( //new RedisTuple.Generic<string, string>.Bulk("HSCAN", args.ToArray()))); } public static RedisScanCommand<Tuple<string, byte[]>> HScanBytes(string key, long cursor, string pattern = null, long? count = null) { var args = new List<object>(); args.Add(key); args.Add(cursor); if (pattern != null) args.AddRange(new[] { "MATCH", pattern }); if (count != null) args.AddRange(new object[] { "COUNT", count }); return new RedisScanCommand<Tuple<string, byte[]>>( new RedisArray.StrongPairs<string, byte[]>(new RedisString(null), new RedisBytes(null), "HSCAN", args.ToArray())); //new RedisArray.Generic<Tuple<string, string>>( //new RedisTuple.Generic<string, string>.Bulk("HSCAN", args.ToArray()))); } #endregion #region Lists public static RedisTuple BLPopWithKey(int timeout, params string[] keys) { object[] args = RedisArgs.Concat(keys, new object[] { timeout }); return new RedisTuple("BLPOP", args); } public static RedisTuple.Generic<string, byte[]> BLPopBytesWithKey(int timeout, params string[] keys) { object[] args = RedisArgs.Concat(keys, new object[] { timeout }); return new RedisTuple.Generic<string, byte[]>.Single(new RedisString(null), new RedisBytes(null), "BLPOP", args); } public static RedisTuple BLPopWithKey(TimeSpan timeout, params string[] keys) { return BLPopWithKey((int)timeout.TotalSeconds, keys); } public static RedisTuple.Generic<string, byte[]> BLPopBytesWithKey(TimeSpan timeout, params string[] keys) { return BLPopBytesWithKey((int)timeout.TotalSeconds, keys); } public static RedisArray.IndexOf<string> BLPop(int timeout, params string[] keys) { object[] args = RedisArgs.Concat(keys, new object[] { timeout }); return new RedisArray.IndexOf<string>(new RedisString("BLPOP", args), 1); } public static RedisArray.IndexOf<byte[]> BLPopBytes(int timeout, params string[] keys) { object[] args = RedisArgs.Concat(keys, new object[] { timeout }); return new RedisArray.IndexOf<byte[]>(new RedisBytes("BLPOP", args), 1); } public static RedisArray.IndexOf<string> BLPop(TimeSpan timeout, params string[] keys) { return BLPop((int)timeout.TotalSeconds, keys); } public static RedisArray.IndexOf<byte[]> BLPopBytes(TimeSpan timeout, params string[] keys) { return BLPopBytes((int)timeout.TotalSeconds, keys); } public static RedisTuple BRPopWithKey(int timeout, params string[] keys) { object[] args = RedisArgs.Concat(keys, new object[] { timeout }); return new RedisTuple("BRPOP", args); } public static RedisTuple.Generic<string, byte[]> BRPopBytesWithKey(int timeout, params string[] keys) { object[] args = RedisArgs.Concat(keys, new object[] { timeout }); return new RedisTuple.Generic<string, byte[]>.Single(new RedisString(null), new RedisBytes(null), "BRPOP", args); } public static RedisTuple BRPopWithKey(TimeSpan timeout, params string[] keys) { return BRPopWithKey((int)timeout.TotalSeconds, keys); } public static RedisTuple.Generic<string, byte[]> BRPopBytesWithKey(TimeSpan timeout, params string[] keys) { return BRPopBytesWithKey((int)timeout.TotalSeconds, keys); } public static RedisArray.IndexOf<string> BRPop(int timeout, params string[] keys) { object[] args = RedisArgs.Concat(keys, new object[] { timeout }); return new RedisArray.IndexOf<string>(new RedisString("BRPOP", args), 1); } public static RedisArray.IndexOf<byte[]> BRPopBytes(int timeout, params string[] keys) { object[] args = RedisArgs.Concat(keys, new object[] { timeout }); return new RedisArray.IndexOf<byte[]>(new RedisBytes("BRPOP", args), 1); } public static RedisArray.IndexOf<string> BRPop(TimeSpan timeout, params string[] keys) { return BRPop((int)timeout.TotalSeconds, keys); } public static RedisArray.IndexOf<byte[]> BRPopBytes(TimeSpan timeout, params string[] keys) { return BRPopBytes((int)timeout.TotalSeconds, keys); } public static RedisString.Nullable BRPopLPush(string source, string destination, int timeout) { return new RedisString.Nullable("BRPOPLPUSH", source, destination, timeout); } public static RedisBytes BRPopBytesLPush(string source, string destination, int timeout) { return new RedisBytes("BRPOPLPUSH", source, destination, timeout); } public static RedisString.Nullable BRPopLPush(string source, string destination, TimeSpan timeout) { return BRPopLPush(source, destination, (int)timeout.TotalSeconds); } public static RedisBytes BRPopBytesLPush(string source, string destination, TimeSpan timeout) { return BRPopBytesLPush(source, destination, (int)timeout.TotalSeconds); } public static RedisString LIndex(string key, long index) { return new RedisString("LINDEX", key, index); } public static RedisBytes LIndexBytes(string key, long index) { return new RedisBytes("LINDEX", key, index); } public static RedisInt LInsert(string key, RedisInsert insertType, object pivot, object value) { return new RedisInt("LINSERT", key, insertType.ToString().ToUpperInvariant(), pivot, value); } public static RedisInt LLen(string key) { return new RedisInt("LLEN", key); } public static RedisString LPop(string key) { return new RedisString("LPOP", key); } public static RedisBytes LPopBytes(string key) { return new RedisBytes("LPOP", key); } public static RedisInt LPush(string key, params object[] values) { object[] args = RedisArgs.Concat(new[] { key }, values); return new RedisInt("LPUSH", args); } public static RedisInt LPushX(string key, object value) { return new RedisInt("LPUSHX", key, value); } public static RedisArray.Strings LRange(string key, long start, long stop) { return new RedisArray.Strings("LRANGE", key, start, stop); } public static RedisArray.Bytes LRangeBytes(string key, long start, long stop) { return new RedisArray.Bytes("LRANGE", key, start, stop); } public static RedisInt LRem(string key, long count, object value) { return new RedisInt("LREM", key, count, value); } public static RedisStatus LSet(string key, long index, object value) { return new RedisStatus("LSET", key, index, value); } public static RedisStatus LTrim(string key, long start, long stop) { return new RedisStatus("LTRIM", key, start, stop); } public static RedisString RPop(string key) { return new RedisString("RPOP", key); } public static RedisBytes RPopBytes(string key) { return new RedisBytes("RPOP", key); } public static RedisString RPopLPush(string source, string destination) { return new RedisString("RPOPLPUSH", source, destination); } public static RedisBytes RPopBytesLPush(string source, string destination) { return new RedisBytes("RPOPLPUSH", source, destination); } public static RedisInt RPush(string key, params object[] values) { object[] args = RedisArgs.Concat(key, values); return new RedisInt("RPUSH", args); } public static RedisInt RPushX(string key, object value) { return new RedisInt("RPUSHX", key, value); } #endregion #region Sets public static RedisInt SAdd(string key, params object[] members) { object[] args = RedisArgs.Concat(key, members); return new RedisInt("SADD", args); } public static RedisInt SCard(string key) { return new RedisInt("SCARD", key); } public static RedisArray.Strings SDiff(params string[] keys) { return new RedisArray.Strings("SDIFF", keys); } public static RedisArray.Bytes SDiffBytes(params string[] keys) { return new RedisArray.Bytes("SDIFF", keys); } public static RedisInt SDiffStore(string destination, params string[] keys) { object[] args = RedisArgs.Concat(destination, keys); return new RedisInt("SDIFFSTORE", args); } public static RedisArray.Strings SInter(params string[] keys) { return new RedisArray.Strings("SINTER", keys); } public static RedisArray.Bytes SInterBytes(params string[] keys) { return new RedisArray.Bytes("SINTER", keys); } public static RedisInt SInterStore(string destination, params string[] keys) { object[] args = RedisArgs.Concat(destination, keys); return new RedisInt("SINTERSTORE", args); } public static RedisBool SIsMember(string key, object member) { return new RedisBool("SISMEMBER", key, member); } public static RedisArray.Strings SMembers(string key) { return new RedisArray.Strings("SMEMBERS", key); } public static RedisArray.Bytes SMembersBytes(string key) { return new RedisArray.Bytes("SMEMBERS", key); } public static RedisBool SMove(string source, string destination, object member) { return new RedisBool("SMOVE", source, destination, member); } public static RedisString SPop(string key) { return new RedisString("SPOP", key); } public static RedisBytes SPopBytes(string key) { return new RedisBytes("SPOP", key); } public static RedisArray.Strings SPop(string key, long count) { return new RedisArray.Strings("SPOP", key, count); } public static RedisArray.Bytes SPopBytes(string key, long count) { return new RedisArray.Bytes("SPOP", key, count); } public static RedisString SRandMember(string key) { return new RedisString("SRANDMEMBER", key); } public static RedisBytes SRandMemberBytes(string key) { return new RedisBytes("SRANDMEMBER", key); } public static RedisArray.Strings SRandMembers(string key, long count) { return new RedisArray.Strings("SRANDMEMBER", key, count); } public static RedisArray.Bytes SRandMembersBytes(string key, long count) { return new RedisArray.Bytes("SRANDMEMBER", key, count); } public static RedisInt SRem(string key, params object[] members) { object[] args = RedisArgs.Concat(key, members); return new RedisInt("SREM", args); } public static RedisArray.Strings SUnion(params string[] keys) { return new RedisArray.Strings("SUNION", keys); } public static RedisArray.Bytes SUnionBytes(params string[] keys) { return new RedisArray.Bytes("SUNION", keys); } public static RedisInt SUnionStore(string destination, params string[] keys) { object[] args = RedisArgs.Concat(destination, keys); return new RedisInt("SUNIONSTORE", args); } public static RedisScanCommand<string> SScan(string key, long cursor, string pattern = null, long? count = null) { var args = new List<object>(); args.Add(key); args.Add(cursor); if (pattern != null) args.AddRange(new[] { "MATCH", pattern }); if (count != null) args.AddRange(new object[] { "COUNT", count }); return new RedisScanCommand<string>( new RedisArray.Strings("SSCAN", args.ToArray())); } public static RedisScanCommand<byte[]> SScanBytes(string key, long cursor, string pattern = null, long? count = null) { var args = new List<object>(); args.Add(key); args.Add(cursor); if (pattern != null) args.AddRange(new[] { "MATCH", pattern }); if (count != null) args.AddRange(new object[] { "COUNT", count }); return new RedisScanCommand<byte[]>( new RedisArray.Bytes("SSCAN", args.ToArray())); } #endregion #region Sorted Sets public static RedisArray.WeakPairs<string, decimal> ZPopMax(string key, long count) { return new RedisArray.WeakPairs<string, decimal>("ZPOPMAX", key, count); } public static RedisArray.StrongPairs<byte[], decimal> ZPopMaxBytes(string key, long count) { return new RedisArray.StrongPairs<byte[], decimal>(new RedisBytes(null), new RedisFloat(null), "ZPOPMAX", key, count); } public static RedisArray.WeakPairs<string, decimal> ZPopMin(string key, long count) { return new RedisArray.WeakPairs<string, decimal>("ZPOPMIN", key, count); } public static RedisArray.StrongPairs<byte[], decimal> ZPopMinBytes(string key, long count) { return new RedisArray.StrongPairs<byte[], decimal>(new RedisBytes(null), new RedisFloat(null), "ZPOPMIN", key, count); } public static RedisInt ZAdd<TScore, TMember>(string key, params Tuple<TScore, TMember>[] scoreMembers) { object[] args = RedisArgs.Concat(key, RedisArgs.GetTupleArgs(scoreMembers)); return new RedisInt("ZADD", args); } public static RedisInt ZAdd(string key, params object[] scoreMembers) { object[] args = RedisArgs.Concat(key, scoreMembers); return new RedisInt("ZADD", args); } public static RedisInt ZCard(string key) { return new RedisInt("ZCARD", key); } public static RedisInt ZCount(string key, decimal min, decimal max, bool exclusiveMin = false, bool exclusiveMax = false) { string min_score = RedisArgs.GetScore(min, exclusiveMin); string max_score = RedisArgs.GetScore(max, exclusiveMax); return ZCount(key, min_score, max_score); } public static RedisInt ZCount(string key, string min, string max) { return new RedisInt("ZCOUNT", key, min, max); } public static RedisFloat ZIncrBy(string key, decimal increment, object member) { return new RedisFloat("ZINCRBY", key, increment, member); } public static RedisInt ZInterStore(string destination, decimal[] weights = null, RedisAggregate? aggregate = null, params string[] keys) { List<object> args = new List<object>(); args.Add(destination); args.Add(keys.Length); args.AddRange(keys); if (weights != null && weights.Length > 0) { args.Add("WEIGHTS"); foreach (var weight in weights) args.Add(weight); } if (aggregate != null) { args.Add("AGGREGATE"); args.Add(aggregate.ToString().ToUpperInvariant()); } return new RedisInt("ZINTERSTORE", args.ToArray()); } public static RedisArray.Strings ZRange(string key, long start, long stop, bool withScores = false) { string[] args = withScores ? new[] { key, start.ToString(), stop.ToString(), "WITHSCORES" } : new[] { key, start.ToString(), stop.ToString() }; return new RedisArray.Strings("ZRANGE", args); } public static RedisArray.Bytes ZRangeBytes(string key, long start, long stop, bool withScores = false) { string[] args = withScores ? new[] { key, start.ToString(), stop.ToString(), "WITHSCORES" } : new[] { key, start.ToString(), stop.ToString() }; return new RedisArray.Bytes("ZRANGE", args); } public static RedisArray.WeakPairs<string, decimal> ZRangeWithScores(string key, long start, long stop) { return new RedisArray.WeakPairs<string, decimal>("ZRANGE", key, start, stop, "WITHSCORES"); } public static RedisArray.StrongPairs<byte[], decimal> ZRangeBytesWithScores(string key, long start, long stop) { return new RedisArray.StrongPairs<byte[], decimal>(new RedisBytes(null), new RedisFloat(null), "ZRANGE", key, start, stop, "WITHSCORES"); } public static RedisArray.Strings ZRangeByScore(string key, decimal min, decimal max, bool withScores = false, bool exclusiveMin = false, bool exclusiveMax = false, long? offset = null, long? count = null) { string min_score = RedisArgs.GetScore(min, exclusiveMin); string max_score = RedisArgs.GetScore(max, exclusiveMax); return ZRangeByScore(key, min_score, max_score, withScores, offset, count); } public static RedisArray.Bytes ZRangeBytesByScore(string key, decimal min, decimal max, bool withScores = false, bool exclusiveMin = false, bool exclusiveMax = false, long? offset = null, long? count = null) { string min_score = RedisArgs.GetScore(min, exclusiveMin); string max_score = RedisArgs.GetScore(max, exclusiveMax); return ZRangeBytesByScore(key, min_score, max_score, withScores, offset, count); } public static RedisArray.WeakPairs<string, decimal> ZRangeByScoreWithScores(string key, decimal min, decimal max, bool exclusiveMin = false, bool exclusiveMax = false, long? offset = null, long? count = null) { string min_score = RedisArgs.GetScore(min, exclusiveMin); string max_score = RedisArgs.GetScore(max, exclusiveMax); return ZRangeByScoreWithScores(key, min_score, max_score, offset, count); } public static RedisArray.StrongPairs<byte[], decimal> ZRangeBytesByScoreWithScores(string key, decimal min, decimal max, bool exclusiveMin = false, bool exclusiveMax = false, long? offset = null, long? count = null) { string min_score = RedisArgs.GetScore(min, exclusiveMin); string max_score = RedisArgs.GetScore(max, exclusiveMax); return ZRangeBytesByScoreWithScores(key, min_score, max_score, offset, count); } public static RedisArray.Strings ZRangeByScore(string key, string min, string max, bool withScores = false, long? offset = null, long? count = null) { object[] args = new[] { key, min, max }; if (withScores) args = RedisArgs.Concat(args, new[] { "WITHSCORES" }); if (offset.HasValue && count.HasValue) args = RedisArgs.Concat(args, new[] { "LIMIT", offset.Value.ToString(), count.Value.ToString() }); return new RedisArray.Strings("ZRANGEBYSCORE", args); } public static RedisArray.Bytes ZRangeBytesByScore(string key, string min, string max, bool withScores = false, long? offset = null, long? count = null) { object[] args = new[] { key, min, max }; if (withScores) args = RedisArgs.Concat(args, new[] { "WITHSCORES" }); if (offset.HasValue && count.HasValue) args = RedisArgs.Concat(args, new[] { "LIMIT", offset.Value.ToString(), count.Value.ToString() }); return new RedisArray.Bytes("ZRANGEBYSCORE", args); } public static RedisArray.WeakPairs<string, decimal> ZRangeByScoreWithScores(string key, string min, string max, long? offset = null, long? count = null) { object[] args = new[] { key, min, max, "WITHSCORES" }; if (offset.HasValue && count.HasValue) args = RedisArgs.Concat(args, new[] { "LIMIT", offset.Value.ToString(), count.Value.ToString() }); return new RedisArray.WeakPairs<string, decimal>("ZRANGEBYSCORE", args); } public static RedisArray.StrongPairs<byte[], decimal> ZRangeBytesByScoreWithScores(string key, string min, string max, long? offset = null, long? count = null) { object[] args = new[] { key, min, max, "WITHSCORES" }; if (offset.HasValue && count.HasValue) args = RedisArgs.Concat(args, new[] { "LIMIT", offset.Value.ToString(), count.Value.ToString() }); return new RedisArray.StrongPairs<byte[], decimal>(new RedisBytes(null), new RedisFloat(null), "ZRANGEBYSCORE", args); } public static RedisInt.Nullable ZRank(string key, object member) { return new RedisInt.Nullable("ZRANK", key, member); } public static RedisInt ZRem(string key, params object[] members) { object[] args = RedisArgs.Concat(new[] { key }, members); return new RedisInt("ZREM", args); } public static RedisInt ZRemRangeByRank(string key, long start, long stop) { return new RedisInt("ZREMRANGEBYRANK", key, start, stop); } public static RedisInt ZRemRangeByScore(string key, decimal min, decimal max, bool exclusiveMin = false, bool exclusiveMax = false) { string min_score = RedisArgs.GetScore(min, exclusiveMin); string max_score = RedisArgs.GetScore(max, exclusiveMax); return ZRemRangeByScore(key, min_score, max_score); } public static RedisInt ZRemRangeByScore(string key, string min, string max) { return new RedisInt("ZREMRANGEBYSCORE", key, min, max); } public static RedisArray.Strings ZRevRange(string key, long start, long stop, bool withScores = false) { string[] args = withScores ? new[] { key, start.ToString(), stop.ToString(), "WITHSCORES" } : new[] { key, start.ToString(), stop.ToString() }; return new RedisArray.Strings("ZREVRANGE", args); } public static RedisArray.Bytes ZRevRangeBytes(string key, long start, long stop, bool withScores = false) { string[] args = withScores ? new[] { key, start.ToString(), stop.ToString(), "WITHSCORES" } : new[] { key, start.ToString(), stop.ToString() }; return new RedisArray.Bytes("ZREVRANGE", args); } public static RedisArray.WeakPairs<string, decimal> ZRevRangeWithScores(string key, long start, long stop) { return new RedisArray.WeakPairs<string, decimal>("ZREVRANGE", key, start.ToString(), stop.ToString(), "WITHSCORES"); } public static RedisArray.StrongPairs<byte[], decimal> ZRevRangeBytesWithScores(string key, long start, long stop) { return new RedisArray.StrongPairs<byte[], decimal>(new RedisBytes(null), new RedisFloat(null), "ZREVRANGE", key, start.ToString(), stop.ToString(), "WITHSCORES"); } public static RedisArray.Strings ZRevRangeByScore(string key, decimal max, decimal min, bool withScores = false, bool exclusiveMax = false, bool exclusiveMin = false, long? offset = null, long? count = null) { string min_score = RedisArgs.GetScore(min, exclusiveMin); string max_score = RedisArgs.GetScore(max, exclusiveMax); return ZRevRangeByScore(key, max_score, min_score, withScores, offset, count); } public static RedisArray.Bytes ZRevRangeBytesByScore(string key, decimal max, decimal min, bool withScores = false, bool exclusiveMax = false, bool exclusiveMin = false, long? offset = null, long? count = null) { string min_score = RedisArgs.GetScore(min, exclusiveMin); string max_score = RedisArgs.GetScore(max, exclusiveMax); return ZRevRangeBytesByScore(key, max_score, min_score, withScores, offset, count); } public static RedisArray.Strings ZRevRangeByScore(string key, string max, string min, bool withScores = false, long? offset = null, long? count = null) { object[] args = new[] { key, max, min }; if (withScores) args = RedisArgs.Concat(args, new[] { "WITHSCORES" }); if (count.HasValue) args = RedisArgs.Concat(args, new[] { "LIMIT", (offset ?? 0).ToString(), count.Value.ToString() }); return new RedisArray.Strings("ZREVRANGEBYSCORE", args); } public static RedisArray.Bytes ZRevRangeBytesByScore(string key, string max, string min, bool withScores = false, long? offset = null, long? count = null) { object[] args = new[] { key, max, min }; if (withScores) args = RedisArgs.Concat(args, new[] { "WITHSCORES" }); if (count.HasValue) args = RedisArgs.Concat(args, new[] { "LIMIT", (offset ?? 0).ToString(), count.Value.ToString() }); return new RedisArray.Bytes("ZREVRANGEBYSCORE", args); } public static RedisArray.WeakPairs<string, decimal> ZRevRangeByScoreWithScores(string key, decimal max, decimal min, bool exclusiveMax = false, bool exclusiveMin = false, long? offset = null, long? count = null) { string min_score = RedisArgs.GetScore(min, exclusiveMin); string max_score = RedisArgs.GetScore(max, exclusiveMax); return ZRevRangeByScoreWithScores(key, max_score, min_score, offset, count); } public static RedisArray.StrongPairs<byte[], decimal> ZRevRangeBytesByScoreWithScores(string key, decimal max, decimal min, bool exclusiveMax = false, bool exclusiveMin = false, long? offset = null, long? count = null) { string min_score = RedisArgs.GetScore(min, exclusiveMin); string max_score = RedisArgs.GetScore(max, exclusiveMax); return ZRevRangeBytesByScoreWithScores(key, max_score, min_score, offset, count); } public static RedisArray.WeakPairs<string, decimal> ZRevRangeByScoreWithScores(string key, string max, string min, long? offset = null, long? count = null) { object[] args = new[] { key, max, min, "WITHSCORES" }; if (count.HasValue) args = RedisArgs.Concat(args, new[] { "LIMIT", (offset ?? 0).ToString(), count.Value.ToString() }); return new RedisArray.WeakPairs<string, decimal>("ZREVRANGEBYSCORE", args); } public static RedisArray.StrongPairs<byte[], decimal> ZRevRangeBytesByScoreWithScores(string key, string max, string min, long? offset = null, long? count = null) { object[] args = new[] { key, max, min, "WITHSCORES" }; if (count.HasValue) args = RedisArgs.Concat(args, new[] { "LIMIT", (offset ?? 0).ToString(), count.Value.ToString() }); return new RedisArray.StrongPairs<byte[], decimal>(new RedisBytes(null), new RedisFloat(null), "ZREVRANGEBYSCORE", args); } public static RedisInt.Nullable ZRevRank(string key, object member) { return new RedisInt.Nullable("ZREVRANK", key, member); } public static RedisFloat.Nullable ZScore(string key, object member) { return new RedisFloat.Nullable("ZSCORE", key, member); } public static RedisInt ZUnionStore(string destination, decimal[] weights = null, RedisAggregate? aggregate = null, params string[] keys) { List<object> args = new List<object>(); args.Add(destination); args.Add(keys.Length); args.AddRange(keys); if (weights != null && weights.Length > 0) { args.Add("WEIGHTS"); foreach (var weight in weights) args.Add(weight); } if (aggregate != null) { args.Add("AGGREGATE"); args.Add(aggregate.ToString().ToUpperInvariant()); } return new RedisInt("ZUNIONSTORE", args.ToArray()); } public static RedisScanCommand<Tuple<string, decimal>> ZScan(string key, long cursor, string pattern = null, long? count = null) { var args = new List<object>(); args.Add(key); args.Add(cursor); if (pattern != null) args.AddRange(new[] { "MATCH", pattern }); if (count != null) args.AddRange(new object[] { "COUNT", count }); return new RedisScanCommand<Tuple<string, decimal>>( new RedisArray.WeakPairs<string, decimal>("ZSCAN", args.ToArray())); //<Tuple<string, decimal>>( //new RedisTuple.Generic<string, decimal>.Bulk("ZSCAN", args.ToArray()))); } public static RedisScanCommand<Tuple<byte[], decimal>> ZScanBytes(string key, long cursor, string pattern = null, long? count = null) { var args = new List<object>(); args.Add(key); args.Add(cursor); if (pattern != null) args.AddRange(new[] { "MATCH", pattern }); if (count != null) args.AddRange(new object[] { "COUNT", count }); return new RedisScanCommand<Tuple<byte[], decimal>>( new RedisArray.StrongPairs<byte[], decimal>( new RedisBytes(null), new RedisFloat(null), "ZSCAN", args.ToArray())); //<Tuple<string, decimal>>( //new RedisTuple.Generic<string, decimal>.Bulk("ZSCAN", args.ToArray()))); } public static RedisArray.Strings ZRangeByLex(string key, string min, string max, long? offset = null, long? count = null) { List<object> args = new List<object>(); args.Add(key); args.Add(min); args.Add(max); if (offset != null && count != null) args.AddRange(new object[] { "LIMIT", offset, count }); return new RedisArray.Strings("ZRANGEBYLEX", args.ToArray()); } public static RedisArray.Bytes ZRangeBytesByLex(string key, string min, string max, long? offset = null, long? count = null) { List<object> args = new List<object>(); args.Add(key); args.Add(min); args.Add(max); if (offset != null && count != null) args.AddRange(new object[] { "LIMIT", offset, count }); return new RedisArray.Bytes("ZRANGEBYLEX", args.ToArray()); } public static RedisInt ZRemRangeByLex(string key, string min, string max) { return new RedisInt("ZREMRANGEBYLEX", key, min, max); } public static RedisInt ZLexCount(string key, string min, string max) { return new RedisInt("ZLEXCOUNT", key, min, max); } #endregion #region PubSub public static RedisSubscription PSubscribe(params string[] channelPatterns) { return new RedisSubscription("PSUBSCRIBE", channelPatterns); } public static RedisInt Publish(string channel, string message) { return new RedisInt("PUBLISH", channel, message); } public static RedisArray.Strings PubSubChannels(string pattern = null) { var args = new List<string>(); args.Add("CHANNELS"); if (pattern != null) args.Add(pattern); return new RedisArray.Strings("PUBSUB", args.ToArray()); } public static RedisArray.StrongPairs<string, long> PubSubNumSub(params string[] channels) { object[] args = RedisArgs.Concat("NUMSUB", channels); return new RedisArray.StrongPairs<string, long>( new RedisString(null), new RedisInt(null), "PUBSUB", args); } public static RedisInt PubSubNumPat() { return new RedisInt("PUBSUB", "NUMPAT"); } public static RedisSubscription PUnsubscribe(params string[] channelPatterns) { return new RedisSubscription("PUNSUBSCRIBE", channelPatterns); } public static RedisSubscription Subscribe(params string[] channels) { return new RedisSubscription("SUBSCRIBE", channels); } public static RedisSubscription Unsubscribe(params string[] channels) { return new RedisSubscription("UNSUBSCRIBE", channels); } #endregion #region Scripting public static RedisObject.Strings Eval(string script, string[] keys, params object[] arguments) { object[] args = RedisArgs.Concat(new object[] { script, keys.Length }, keys, arguments); return new RedisObject.Strings("EVAL", args); } public static RedisObject.Strings EvalSHA(string sha1, string[] keys, params object[] arguments) { object[] args = RedisArgs.Concat(new object[] { sha1, keys.Length }, keys, arguments); return new RedisObject.Strings("EVALSHA", args); } public static RedisArray.Generic<bool> ScriptExists(params string[] sha1s) { return new RedisArray.Generic<bool>(new RedisBool("SCRIPT EXISTS", sha1s)); } public static RedisStatus ScriptFlush() { return new RedisStatus("SCRIPT FLUSH"); } public static RedisStatus ScriptKill() { return new RedisStatus("SCRIPT KILL"); } public static RedisString ScriptLoad(string script) { return new RedisString("SCRIPT LOAD", script); } #endregion #region Strings public static RedisInt Append(string key, object value) { return new RedisInt("APPEND", key, value); } public static RedisInt BitCount(string key, long? start = null, long? end = null) { string[] args = start.HasValue && end.HasValue ? new[] { key, start.Value.ToString(), end.Value.ToString() } : new[] { key }; return new RedisInt("BITCOUNT", args); } public static RedisInt BitOp(RedisBitOp operation, string destKey, params string[] keys) { object[] args = RedisArgs.Concat(new[] { operation.ToString().ToUpperInvariant(), destKey }, keys); return new RedisInt("BITOP", args); } public static RedisInt BitPos(string key, bool bit, long? start = null, long? end = null) { List<object> args = new List<object>(); args.Add(key); if (bit) args.Add("1"); else args.Add("0"); if (start != null) { args.Add(start); if (end != null) args.Add(end); } return new RedisInt("BITPOS", args.ToArray()); } public static RedisInt Decr(string key) { return new RedisInt("DECR", key); } public static RedisInt DecrBy(string key, long decrement) { return new RedisInt("DECRBY", key, decrement); } public static RedisString Get(string key) { return new RedisString("GET", key); } public static RedisBytes GetBytes(string key) { return new RedisBytes("GET", key); } public static RedisBool GetBit(string key, uint offset) { return new RedisBool("GETBIT", key, offset); } public static RedisString GetRange(string key, long start, long end) { return new RedisString("GETRANGE", key, start, end); } public static RedisBytes GetRangeBytes(string key, long start, long end) { return new RedisBytes("GETRANGE", key, start, end); } public static RedisString GetSet(string key, object value) { return new RedisString("GETSET", key, value); } public static RedisBytes GetSetBytes(string key, object value) { return new RedisBytes("GETSET", key, value); } public static RedisInt Incr(string key) { return new RedisInt("INCR", key); } public static RedisInt IncrBy(string key, long increment) { return new RedisInt("INCRBY", key, increment); } public static RedisFloat IncrByFloat(string key, decimal increment) { return new RedisFloat("INCRBYFLOAT", key, increment); } public static RedisArray.Strings MGet(params string[] keys) { return new RedisArray.Strings("MGET", keys); } public static RedisArray.Bytes MGetBytes(params string[] keys) { return new RedisArray.Bytes("MGET", keys); } public static RedisStatus MSet(params Tuple<string, object>[] keyValues) { object[] args = RedisArgs.GetTupleArgs(keyValues); return new RedisStatus("MSET", args); } public static RedisStatus MSet(params object[] keyValues) { return new RedisStatus("MSET", keyValues); } public static RedisBool MSetNx(params Tuple<string, object>[] keyValues) { object[] args = RedisArgs.GetTupleArgs(keyValues); return new RedisBool("MSETNX", args); } public static RedisBool MSetNx(params object[] keyValues) { return new RedisBool("MSETNX", keyValues); } public static RedisStatus PSetEx(string key, long milliseconds, object value) { return new RedisStatus("PSETEX", key, milliseconds, value); } public static RedisStatus Set(string key, object value) { return new RedisStatus("SET", key, value); } public static RedisStatus.Nullable Set(string key, object value, TimeSpan expiration, RedisExistence? condition = null) { return Set(key, value, (long)expiration.TotalMilliseconds, condition); } public static RedisStatus.Nullable Set(string key, object value, int? expirationSeconds = null, RedisExistence? condition = null) { return Set(key, value, expirationSeconds, null, condition); } public static RedisStatus.Nullable Set(string key, object value, long? expirationMilliseconds = null, RedisExistence? condition = null) { return Set(key, value, null, expirationMilliseconds, condition); } private static RedisStatus.Nullable Set(string key, object value, int? expirationSeconds = null, long? expirationMilliseconds = null, RedisExistence? exists = null) { var args = new List<object> { key, value }; if (expirationSeconds != null) args.AddRange(new[] { "EX", expirationSeconds.ToString() }); if (expirationMilliseconds != null) args.AddRange(new[] { "PX", expirationMilliseconds.ToString() }); if (exists != null) args.AddRange(new[] { exists.ToString().ToUpperInvariant() }); return new RedisStatus.Nullable("SET", args.ToArray()); } public static RedisBool SetBit(string key, uint offset, bool value) { return new RedisBool("SETBIT", key, offset, value ? "1" : "0"); } public static RedisStatus SetEx(string key, long seconds, object value) { return new RedisStatus("SETEX", key, seconds, value); } public static RedisBool SetNx(string key, object value) { return new RedisBool("SETNX", key, value); } public static RedisInt SetRange(string key, uint offset, object value) { return new RedisInt("SETRANGE", key, offset, value); } public static RedisInt StrLen(string key) { return new RedisInt("STRLEN", key); } #endregion #region Server public static RedisStatus BgRewriteAof() { return new RedisStatus("BGREWRITEAOF"); } public static RedisStatus BgSave() { return new RedisStatus("BGSAVE"); } public static RedisString ClientGetName() { return new RedisString("CLIENT GETNAME"); } public static RedisStatus ClientKill(string ip, int port) { return new RedisStatus("CLIENT KILL", ip, port); } public static RedisInt ClientKill(string addr = null, string id = null, string type = null, bool? skipMe = null) { var args = new List<string>(); if (addr != null) args.AddRange(new[] { "ADDR", addr }); if (id != null) args.AddRange(new[] { "ID", id }); if (type != null) args.AddRange(new[] { "TYPE", type }); if (skipMe != null) args.AddRange(new[] { "SKIPME", skipMe.Value ? "yes" : "no" }); return new RedisInt("CLIENT KILL", args.ToArray()); } public static RedisString ClientList() { return new RedisString("CLIENT LIST"); } public static RedisStatus ClientPause(TimeSpan timeout) { return ClientPause((int)timeout.TotalMilliseconds); } public static RedisStatus ClientPause(int milliseconds) { return new RedisStatus("CLIENT PAUSE", milliseconds); } public static RedisStatus ClientSetName(string connectionName) { return new RedisStatus("CLIENT SETNAME", connectionName); } public static RedisArray.WeakPairs<string, string> ConfigGet(string parameter) { return new RedisArray.WeakPairs<string, string>("CONFIG GET", parameter); } public static RedisStatus ConfigResetStat() { return new RedisStatus("CONFIG RESETSTAT"); } public static RedisStatus ConfigRewrite() { return new RedisStatus("CONFIG REWRITE"); } public static RedisStatus ConfigSet(string parameter, string value) { return new RedisStatus("CONFIG SET", parameter, value); } public static RedisInt DbSize() { return new RedisInt("DBSIZE"); } public static RedisStatus DebugSegFault() { return new RedisStatus("DEBUG SEGFAULT"); } public static RedisStatus FlushAll() { return new RedisStatus("FLUSHALL"); } public static RedisStatus FlushDb() { return new RedisStatus("FLUSHDB"); } public static RedisString Info(string section = null) { return new RedisString("INFO", section == null ? new string[0] : new[] { section }); } public static RedisDate LastSave() { return new RedisDate("LASTSAVE"); } public static RedisStatus Monitor() { return new RedisStatus("MONITOR"); } public static RedisRoleCommand Role() { return new RedisRoleCommand("ROLE"); } public static RedisStatus Save() { return new RedisStatus("SAVE"); } public static RedisStatus.Empty Shutdown(bool? save = null) { string[] args; if (save.HasValue && save.Value) args = new[] { "SAVE" }; else if (save.HasValue && !save.Value) args = new[] { "NOSAVE" }; else args = new string[0]; return new RedisStatus.Empty("SHUTDOWN", args); } public static RedisStatus SlaveOf(string host, int port) { return new RedisStatus("SLAVEOF", host, port); } public static RedisStatus SlaveOfNoOne() { return new RedisStatus("SLAVEOF", "NO", "ONE"); } public static RedisArray.Generic<RedisSlowLogEntry> SlowLogGet(long? count = null) { var args = new List<object>(); args.Add("GET"); if (count.HasValue) args.Add(count.Value); return new RedisArray.Generic<RedisSlowLogEntry>( new RedisSlowLogCommand("SLOWLOG", args.ToArray())); } public static RedisInt SlowLogLen() { return new RedisInt("SLOWLOG", "LEN"); } public static RedisStatus SlowLogReset() { return new RedisStatus("SLOWLOG", "RESET"); } public static RedisBytes Sync() { return new RedisBytes("SYNC"); } public static RedisDate.Micro Time() { return new RedisDate.Micro("TIME"); } #endregion #region Transactions public static RedisStatus Discard() { return new RedisStatus("DISCARD"); } public static RedisArray Exec() { return new RedisArray("EXEC"); } public static RedisStatus Multi() { return new RedisStatus("MULTI"); } public static RedisStatus Unwatch() { return new RedisStatus("UNWATCH"); } public static RedisStatus Watch(params string[] keys) { return new RedisStatus("WATCH", keys); } #endregion #region HyperLogLog public static RedisBool PfAdd(string key, params object[] elements) { object[] args = RedisArgs.Concat(key, elements); return new RedisBool("PFADD", args); } public static RedisInt PfCount(params string[] keys) { return new RedisInt("PFCOUNT", keys); } public static RedisStatus PfMerge(string destKey, params string[] sourceKeys) { object[] args = RedisArgs.Concat(destKey, sourceKeys); return new RedisStatus("PFMERGE", args); } #endregion #region Streams public static RedisInt XAck(string key, string group, params string[] id) { var args = new List<object>(); args.AddRange(new object[] { key, group }); args.AddRange(id.Select(a => (object)a)); return new RedisInt("XACK", args.ToArray()); } public static RedisString XAdd(string key, long maxLen, string id = "*", params (string, string)[] fieldValues) { var args = new List<object>(); args.Add(key); if (maxLen > 0) args.AddRange(new object[] { "MAXLEN", maxLen }); else if (maxLen < 0) args.AddRange(new object[] { "MAXLEN", "~", Math.Abs(maxLen) }); args.Add(id); args.AddRange(fieldValues.Select(a => new[] { a.Item1, a.Item2 }).SelectMany(a => a).Select(a => (object)a)); return new RedisString("XADD", args.ToArray()); } public static RedisXRangeCommand XClaim(string key, string group, string consumer, long minIdleTime, params string[] id) { var args = new List<object>(); args.AddRange(new object[] { key, group, consumer, minIdleTime }); args.AddRange(id.Select(a => (object)a)); return new RedisXRangeCommand("XCLAIM", args.ToArray()); } public static RedisXRangeCommand XClaim(string key, string group, string consumer, long minIdleTime, string[] id, long idle, long retryCount, bool force) { var args = new List<object>(); args.AddRange(new object[] { key, group, consumer, minIdleTime }); args.AddRange(id.Select(a => (object)a)); args.AddRange(new object[] { "IDLE", idle, "RETRYCOUNT", retryCount }); if (force) args.Add("FORCE"); return new RedisXRangeCommand("XCLAIM", args.ToArray()); } public static RedisArray.Strings XClaimJustId(string key, string group, string consumer, long minIdleTime, params string[] id) { var args = new List<object>(); args.AddRange(new object[] { key, group, consumer, minIdleTime }); args.AddRange(id.Select(a => (object)a)); args.Add("JUSTID"); return new RedisArray.Strings("XCLAIM", args.ToArray()); } public static RedisArray.Strings XClaimJustId(string key, string group, string consumer, long minIdleTime, string[] id, long idle, long retryCount, bool force) { var args = new List<object>(); args.AddRange(new object[] { key, group, consumer, minIdleTime }); args.AddRange(id.Select(a => (object)a)); args.AddRange(new object[] { "IDLE", idle, "RETRYCOUNT", retryCount }); if (force) args.Add("FORCE"); args.Add("JUSTID"); return new RedisArray.Strings("XCLAIM", args.ToArray()); } public static RedisInt XDel(string key, params string[] id) { object[] args = RedisArgs.Concat(key, id); return new RedisInt("XDEL", args); } public static class XGroup { public static RedisStatus Create(string key, string group, string id = "$", bool MkStream = false) { var args = new List<object>(); args.AddRange(new object[] { "CREATE", key, group, id, }); if (MkStream) args.Add("MKSTREAM"); return new RedisStatus("XGROUP", args.ToArray()); } public static RedisStatus SetId(string key, string group, string id = "$") { return new RedisStatus("XGROUP", "SETID", key, group, id); } public static RedisBool Destroy(string key, string group) { return new RedisBool("XGROUP", "DESTROY", key, group); } public static RedisBool DelConsumer(string key, string group, string consumer) { return new RedisBool("XGROUP", "DELCONSUMER", key, group, consumer); } } //XINFO public static RedisXInfoStreamCommand XInfoStream(string key) { return new RedisXInfoStreamCommand("XINFO", "STREAM", key); } public static RedisXInfoGroupsCommand XInfoGroups(string key) { return new RedisXInfoGroupsCommand("XINFO", "GROUPS", key); } public static RedisXInfoConsumersCommand XInfoConsumers(string key, string group) { return new RedisXInfoConsumersCommand("XINFO", "CONSUMERS", key, group); } public static RedisInt XLen(string key) { return new RedisInt("XLEN", key); } //XPENDING public static RedisXPendingCommand XPending(string key, string group) { return new RedisXPendingCommand("XPENDING", key, group); } public static RedisXPendingStartEndCountCommand XPending(string key, string group, string start, string end, long count, string consumer = null) { if (string.IsNullOrEmpty(consumer)) return new RedisXPendingStartEndCountCommand("XPENDING", key, group, start, end, count); return new RedisXPendingStartEndCountCommand("XPENDING", key, group, start, end, count, consumer); } public static RedisXRangeCommand XRange(string key, string start, string end, long count = 1) { var args = new List<object>(); args.AddRange(new[] { key, start, end }); if (count > 0) args.AddRange(new[] { "COUNT", count.ToString() }); return new RedisXRangeCommand("XRANGE", args.ToArray()); } public static RedisXRangeCommand XRevRange(string key, string end, string start, long count = 1) { var args = new List<object>(); args.AddRange(new[] { key, start, end }); if (count > 0) args.AddRange(new[] { "COUNT", count.ToString() }); return new RedisXRangeCommand("XREVRANGE", args.ToArray()); } public static RedisXReadCommand XRead(long count, long block, params (string key, string id)[] streams) { var args = new List<object>(); if (count > 0) args.AddRange(new[] { "COUNT", count.ToString() }); if (block > 0) args.AddRange(new[] { "BLOCK", block.ToString() }); args.Add("STREAMS"); args.AddRange(streams.Select(a => (object)a.key)); args.AddRange(streams.Select(a => (object)a.id)); return new RedisXReadCommand("XREAD", args.ToArray()); } public static RedisXReadCommand XReadGroup(string group, string consumer, long count, long block, params (string key, string id)[] streams) { var args = new List<object>(); args.AddRange(new[] { "GROUP", group, consumer }); if (count > 0) args.AddRange(new[] { "COUNT", count.ToString() }); if (block > 0) args.AddRange(new[] { "BLOCK", block.ToString() }); args.Add("STREAMS"); args.AddRange(streams.Select(a => (object)a.key)); args.AddRange(streams.Select(a => (object)a.id)); return new RedisXReadCommand("XREADGROUP", args.ToArray()); } public static RedisInt XTrim(string key, long maxLen) { if (maxLen > 0) return new RedisInt("XTRIM", key, "MAXLEN", maxLen.ToString()); return new RedisInt("XTRIM", key, "MAXLEN", "~", Math.Abs(maxLen).ToString()); } #endregion #region Bloom Filter public static RedisStatus BfReserve(string key, decimal errorRate, long capacity, int expansion = 2, bool nonScaling = false) { var args = new List<object>(); args.AddRange(new object[] { key, errorRate, capacity }); if (expansion != 2) args.AddRange(new object[] { "EXPANSION", expansion }); if (nonScaling) args.Add("NONSCALING"); return new RedisStatus("BF.RESERVE", args.ToArray()); } public static RedisBool BfAdd(string key, object item) { return new RedisBool("BF.ADD", key, item); } public static RedisArray.Generic<bool> BfMAdd(string key, object[] items) { var args = new List<object>(); args.Add(key); args.AddRange(items); return new RedisArray.Generic<bool>(new RedisBool("BF.MADD", args.ToArray())); } public static RedisArray.Generic<bool> BfInsert(string key, object[] items, long? capacity = null, string error = null, int expansion = 2, bool noCreate = false, bool nonScaling = false) { var args = new List<object>(); args.AddRange(new object[] { key }); if (capacity != null) args.AddRange(new object[] { "CAPACITY", capacity }); if (string.IsNullOrEmpty(error) == false) args.AddRange(new object[] { "ERROR", error }); if (expansion != 2) args.Add(new object[] { "EXPANSION", expansion }); if (noCreate) args.Add("NOCREATE"); if (nonScaling) args.Add("NONSCALING"); args.Add("ITEMS"); args.AddRange(items); return new RedisArray.Generic<bool>(new RedisBool("BF.INSERT", args.ToArray())); } public static RedisBool BfExists(string key, object item) { return new RedisBool("BF.EXISTS", key, item); } public static RedisArray.Generic<bool> BfMExists(string key, object[] items) { var args = new List<object>(); args.Add(key); args.AddRange(items); return new RedisArray.Generic<bool>(new RedisBool("BF.MEXISTS", args.ToArray())); } public static RedisScanCommand<byte[]> BfScanDump(string key, long iter) { return new RedisScanCommand<byte[]>( new RedisArray.Bytes("BF.SCANDUMP", key, iter)); } public static RedisStatus BfLoadChunk(string key, long iter, byte[] data) { return new RedisStatus("BF.LOADCHUNK", key, iter, data); } public static RedisBfInfoCommand BfInfo(string key) { return new RedisBfInfoCommand("BF.INFO", key); } public class RedisBfInfoCommand : RedisCommand<(long capacity, long size, long numberOfFilters, long numberOfItemsInserted, long expansionRate)> { public RedisBfInfoCommand(string command, params object[] args) : base(command, args) { } public override (long capacity, long size, long numberOfFilters, long numberOfItemsInserted, long expansionRate) Parse(RedisReader reader) { long capacity = 0; long size = 0; long numberOfFilters = 0; long numberOfItemsInserted = 0; long expansionRate = 0; reader.ExpectType(RedisMessage.MultiBulk); long count = reader.ReadInt(false); if (count % 2 != 0) throw new RedisProtocolException("BF.INFO 返回数据格式 1级 MultiBulk 长度应该为偶数"); for (var b = 0; b < count; b += 2) { var key = reader.ReadBulkString().ToLower(); switch (key) { case "capacity": capacity = reader.ReadInt(); break; case "size": size = reader.ReadInt(); break; case "number of filters": numberOfFilters = reader.ReadInt(); break; case "number of items inserted": numberOfItemsInserted = reader.ReadInt(); break; case "expansion rate": expansionRate = reader.ReadInt(); break; default: reader.ReadBulkString(); break; } } return (capacity, size, numberOfFilters, numberOfItemsInserted, expansionRate); } } #endregion #region RedisBloom Cuckoo Filter public static RedisStatus CfReserve(string key, long capacity, long? bucketSize = null, long? maxIterations = null, int? expansion = null) { var args = new List<object>(); args.AddRange(new object[] { key, capacity }); if (bucketSize != 2) args.AddRange(new object[] { "BUCKETSIZE", bucketSize }); if (maxIterations != 2) args.AddRange(new object[] { "MAXITERATIONS", maxIterations }); if (expansion != 2) args.AddRange(new object[] { "EXPANSION", expansion }); return new RedisStatus("CF.RESERVE", args.ToArray()); } public static RedisBool CfAdd(bool nx, string key, object item) { return new RedisBool(nx ? "CF.ADDNX": "CF.ADD", key, item); } public static RedisArray.Generic<bool> CfInsert(bool nx, string key, object[] items, long? capacity = null, bool noCreate = false) { var args = new List<object>(); args.AddRange(new object[] { key }); if (capacity != null) args.AddRange(new object[] { "CAPACITY", capacity }); if (noCreate) args.Add("NOCREATE"); args.Add("ITEMS"); args.AddRange(items); return new RedisArray.Generic<bool>(new RedisBool(nx ? "CF.INSERTNX" : "CF.INSERT", args.ToArray())); } public static RedisBool CfExists(string key, object item) { return new RedisBool("CF.EXISTS", key, item); } public static RedisBool CfDel(string key, object item) { return new RedisBool("CF.DEL", key, item); } public static RedisInt CfCount(string key, object item) { return new RedisInt("CF.COUNT", key, item); } public static RedisScanCommand<byte[]> CfScanDump(string key, long iter) { return new RedisScanCommand<byte[]>( new RedisArray.Bytes("CF.SCANDUMP", key, iter)); } public static RedisStatus CfLoadChunk(string key, long iter, byte[] data) { return new RedisStatus("CF.LOADCHUNK", key, iter, data); } public static RedisCfInfoCommand CfInfo(string key) { return new RedisCfInfoCommand("CF.INFO", key); } public class RedisCfInfoCommand : RedisCommand<(long size, long numberOfBuckets, long numberOfFilter, long numberOfItemsInserted, long numberOfItemsDeleted, long bucketSize, long expansionRate, long maxIteration)> { public RedisCfInfoCommand(string command, params object[] args) : base(command, args) { } public override (long size, long numberOfBuckets, long numberOfFilter, long numberOfItemsInserted, long numberOfItemsDeleted, long bucketSize, long expansionRate, long maxIteration) Parse(RedisReader reader) { long size = 0; long numberOfBuckets = 0; long numberOfFilter = 0; long numberOfItemsInserted = 0; long numberOfItemsDeleted = 0; long bucketSize = 0; long expansionRate = 0; long maxIteration = 0; reader.ExpectType(RedisMessage.MultiBulk); long count = reader.ReadInt(false); if (count % 2 != 0) throw new RedisProtocolException("CF.INFO 返回数据格式 1级 MultiBulk 长度应该为偶数"); for (var b = 0; b < count; b += 2) { var key = reader.ReadBulkString().ToLower(); switch (key) { case "size": size = reader.ReadInt(); break; case "number of buckets": numberOfBuckets = reader.ReadInt(); break; case "number of filter": numberOfFilter = reader.ReadInt(); break; case "number of items inserted": numberOfItemsInserted = reader.ReadInt(); break; case "number of items deleted": numberOfItemsDeleted = reader.ReadInt(); break; case "bucket size": bucketSize = reader.ReadInt(); break; case "expansion rate": expansionRate = reader.ReadInt(); break; case "max iteration": maxIteration = reader.ReadInt(); break; default: reader.ReadBulkString(); break; } } return (size, numberOfBuckets, numberOfFilter, numberOfItemsInserted, numberOfItemsDeleted, bucketSize, expansionRate, maxIteration); } } #endregion #region RedisBloom Count-Min Sketch public static RedisStatus CmsInitByDim(string key, long width, long depth) { return new RedisStatus("CMS.INITBYDIM", key, width, depth); } public static RedisStatus CmsInitByProb(string key, decimal error, decimal probability) { return new RedisStatus("CMS.INITBYPROB", key, error, probability); } public static RedisArray.Generic<long> CmsIncrBy(string key, params (object item, long increment)[] items) { var args = new List<object>(); args.AddRange(new object[] { key }); foreach (var item in items) args.AddRange(new object[] { item.item, item.increment }); return new RedisArray.Generic<long>(new RedisInt("CMS.INCRBY", args.ToArray())); } public static RedisArray.Generic<long> CmsQuery(string key, object[] items) { var args = new List<object>(); args.AddRange(new object[] { key }); args.AddRange(items); return new RedisArray.Generic<long>(new RedisInt("CMS.QUERY", args.ToArray())); } public static RedisStatus CmsMerge(string dest, long numKeys, string[] src, long[] weights) { var args = new List<object>(); args.AddRange(new object[] { dest, numKeys }); args.AddRange(src); if (weights?.Any() == true) { args.Add("WEIGHTS"); args.AddRange(weights.Select(a => (object)a)); } return new RedisStatus("CMS.MERGE", args.ToArray()); } public static RedisCmsInfoCommand CmsInfo(string key) { return new RedisCmsInfoCommand("CMS.INFO", key); } public class RedisCmsInfoCommand : RedisCommand<(long width, long depth, long count)> { public RedisCmsInfoCommand(string command, params object[] args) : base(command, args) { } public override (long width, long depth, long count) Parse(RedisReader reader) { long width = 0; long depth = 0; long count = 0; reader.ExpectType(RedisMessage.MultiBulk); long arrayCount = reader.ReadInt(false); if (arrayCount % 2 != 0) throw new RedisProtocolException("CMS.INFO 返回数据格式 1级 MultiBulk 长度应该为偶数"); for (var b = 0; b < arrayCount; b += 2) { var key = reader.ReadBulkString().ToLower(); switch (key) { case "width": width = reader.ReadInt(); break; case "depth": depth = reader.ReadInt(); break; case "count": count = reader.ReadInt(); break; default: reader.ReadBulkString(); break; } } return (width, depth, count); } } #endregion #region RedisBloom TopK Filter public static RedisStatus TopkReserve(string key, long topk, long width, long depth, decimal decay) { return new RedisStatus("TOPK.RESERVE", key, topk, width, depth, decay); } public static RedisArray.Generic<string> TopkAdd(string key, object[] items) { var args = new List<object>(); args.AddRange(new object[] { key }); args.AddRange(items); return new RedisArray.Generic<string>(new RedisString("TOPK.ADD", args.ToArray())); } public static RedisArray.Generic<string> TopkIncrBy(string key, params (object item, long increment)[] items) { var args = new List<object>(); args.AddRange(new object[] { key }); foreach (var item in items) args.AddRange(new object[] { item.item, item.increment }); return new RedisArray.Generic<string>(new RedisString("TOPK.INCRBY", args.ToArray())); } public static RedisArray.Generic<bool> TopkQuery(string key, object[] items) { var args = new List<object>(); args.AddRange(new object[] { key }); args.AddRange(items); return new RedisArray.Generic<bool>(new RedisBool("TOPK.QUERY", args.ToArray())); } public static RedisArray.Generic<long> TopkCount(string key, object[] items) { var args = new List<object>(); args.AddRange(new object[] { key }); args.AddRange(items); return new RedisArray.Generic<long>(new RedisInt("TOPK.COUNT", args.ToArray())); } public static RedisArray.Generic<string> TopkList(string key) { return new RedisArray.Generic<string>(new RedisString("TOPK.LIST", key)); } public static RedisTopkInfoCommand TopkInfo(string key) { return new RedisTopkInfoCommand("TOPK.INFO", key); } public class RedisTopkInfoCommand : RedisCommand<(long k, long width, long depth, decimal decay)> { public RedisTopkInfoCommand(string command, params object[] args) : base(command, args) { } public override (long k, long width, long depth, decimal decay) Parse(RedisReader reader) { long k = 0; long width = 0; long depth = 0; decimal decay = 0; reader.ExpectType(RedisMessage.MultiBulk); long arrayCount = reader.ReadInt(false); if (arrayCount % 2 != 0) throw new RedisProtocolException("CMS.INFO 返回数据格式 1级 MultiBulk 长度应该为偶数"); for (var b = 0; b < arrayCount; b += 2) { var key = reader.ReadBulkString().ToLower(); switch (key) { case "k": k = reader.ReadInt(); break; case "width": width = reader.ReadInt(); break; case "depth": depth = reader.ReadInt(); break; case "decay": decay = decimal.Parse(reader.ReadBulkString(), NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat); break; default: reader.ReadBulkString(); break; } } return (k, width, depth, decay); } } #endregion public static class Sentinel { public static RedisArray.Generic<RedisSentinelInfo> Sentinels(string masterName) { return new RedisArray.Generic<RedisSentinelInfo>(new RedisHash.Generic<RedisSentinelInfo>("SENTINEL", "sentinels", masterName)); } public static RedisArray.Generic<RedisMasterInfo> Masters() { return new RedisArray.Generic<RedisMasterInfo>(new RedisHash.Generic<RedisMasterInfo>("SENTINEL", "masters")); } public static RedisHash.Generic<RedisMasterInfo> Master(string masterName) { return new RedisHash.Generic<RedisMasterInfo>("SENTINEL", "master", masterName); } public static RedisArray.Generic<RedisSlaveInfo> Slaves(string masterName) { return new RedisArray.Generic<RedisSlaveInfo>(new RedisHash.Generic<RedisSlaveInfo>("SENTINEL", "slaves", masterName)); } public static RedisIsMasterDownByAddrCommand IsMasterDownByAddr(string ip, int port, long currentEpoch, string runId) { return new RedisIsMasterDownByAddrCommand("SENTINEL", "is-master-down-by-addr", ip, port, currentEpoch, runId); } public static RedisTuple.Generic<string, int>.Single GetMasterAddrByName(string masterName) { return new RedisTuple.Generic<string, int>.Single( new RedisString(null), new RedisString.Integer(null), "SENTINEL", new[] { "get-master-addr-by-name", masterName }); } public static RedisInt Reset(string pattern) { return new RedisInt("SENTINEL", "reset", pattern); } public static RedisStatus Failover(string masterName) { return new RedisStatus("SENTINEL", "failover", masterName); } public static RedisStatus Monitor(string name, int port, int quorum) { return new RedisStatus("SENTINEL", "MONITOR", name, port, quorum); } public static RedisStatus Remove(string name) { return new RedisStatus("SENTINEL", "REMOVE", name); } public static RedisStatus Set(string masterName, string option, string value) { return new RedisStatus("SENTINEL", "SET", masterName, option, value); } public static RedisArray PendingScripts() { return new RedisArray("SENTINEL", "pending-scripts"); } } public static RedisObject Call(string command, params string[] args) { return new RedisObject(command, args); } public static RedisStatus AsTransaction<T>(RedisCommand<T> command) { return new RedisStatus(command.Command, command.Arguments); } } internal class RedisCommand { readonly string _command; readonly object[] _args; public string Command { get { return _command; } } public object[] Arguments { get { return _args; } } protected RedisCommand(string command, params object[] args) { _command = command; _args = args; } } internal abstract class RedisCommand<T> : RedisCommand { protected RedisCommand(string command, params object[] args) : base(command, args) { } public abstract T Parse(RedisReader reader); public override string ToString() { return String.Format("{0} {1}", Command, String.Join(" ", Arguments)); } } }
2881099/csredis
1,601
src/CSRedisCore/Internal/SubscriptionListener.cs
using CSRedis.Internal.Commands; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CSRedis.Internal { class SubscriptionListener : RedisListener<RedisSubscriptionResponse> { long _count; public event EventHandler<RedisSubscriptionReceivedEventArgs> MessageReceived; public event EventHandler<RedisSubscriptionChangedEventArgs> Changed; public SubscriptionListener(RedisConnector connection) : base(connection) { } public void Send(RedisSubscription command) { Write(command); if (!Listening) Listen(command.Parse); } protected override void OnParsed(RedisSubscriptionResponse response) { if (response is RedisSubscriptionChannel) OnReceivedChannel(response as RedisSubscriptionChannel); else if (response is RedisSubscriptionMessage) OnReceivedMessage(response as RedisSubscriptionMessage); } protected override bool Continue() { return _count > 0; } void OnReceivedChannel(RedisSubscriptionChannel channel) { _count = channel.Count; if (Changed != null) Changed(this, new RedisSubscriptionChangedEventArgs(channel)); } void OnReceivedMessage(RedisSubscriptionMessage message) { if (MessageReceived != null) MessageReceived(this, new RedisSubscriptionReceivedEventArgs(message)); } } }
2881099/csredis
7,174
src/CSRedisCore/Internal/RedisConnector.cs
using CSRedis.Internal.IO; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; namespace CSRedis.Internal { class RedisConnector { readonly int _concurrency; readonly int _bufferSize; internal readonly IRedisSocket _redisSocket; readonly EndPoint _endPoint; internal readonly RedisIO _io; public event EventHandler Connected; public bool IsConnected { get { return _redisSocket.Connected; } } public EndPoint EndPoint { get { return _endPoint; } } public bool IsPipelined { get { return _io.IsPipelined; } } public RedisPipeline Pipeline { get { return _io.Pipeline; } } public int ReconnectAttempts { get; set; } public int ReconnectWait { get; set; } public int ReceiveTimeout { get { return _redisSocket.ReceiveTimeout; } set { _redisSocket.ReceiveTimeout = value; } } public int SendTimeout { get { return _redisSocket.SendTimeout; } set { _redisSocket.SendTimeout = value; } } public Encoding Encoding { get { return _io.Encoding; } set { _io.Encoding = value; } } public RedisConnector(EndPoint endPoint, IRedisSocket socket, int concurrency, int bufferSize) { _concurrency = concurrency; _bufferSize = bufferSize; _endPoint = endPoint; _redisSocket = socket; _io = new RedisIO(); //_autoPipeline = new AutoPipelineOption(_io); } public bool Connect(int timeout) { _redisSocket.Connect(_endPoint, timeout); if (_redisSocket.Connected) OnConnected(); return _redisSocket.Connected; } #if net40 #else public Task<bool> ConnectAsync() { return _redisSocket.ConnectAsync(_endPoint); } #endif //public IAutoPipelineOption AutoPipeline => _autoPipeline; //AutoPipelineOption _autoPipeline; public T Call<T>(RedisCommand<T> command) { ConnectIfNotConnected(); try { if (IsPipelined) return _io.Pipeline.Write(command); //if (_autoPipeline.IsEnabled) // return _autoPipeline.EnqueueSync(command); //Console.WriteLine("--------------Call " + command.ToString()); _io.Write(_io.Writer.Prepare(command)); return command.Parse(_io.Reader); } catch (IOException) { if (ReconnectAttempts == 0) throw; Reconnect(); return Call(command); } catch (RedisException ex) { throw new RedisException($"{ex.Message}\r\nCommand: {command}", ex); } } public void CallNoneRead(RedisCommand command) { ConnectIfNotConnected(); try { //Console.WriteLine("--------------Call " + command.ToString()); _io.Write(_io.Writer.Prepare(command)); } catch (IOException) { if (ReconnectAttempts == 0) throw; Reconnect(); CallNoneRead(command); } catch (RedisException ex) { throw new RedisException($"{ex.Message}\r\nCommand: {command}", ex); } } #if net40 #else async public Task<T> CallAsync<T>(RedisCommand<T> command) { //if (_autoPipeline.IsEnabled) // return _autoPipeline.EnqueueAsync(command); //Console.WriteLine("--------------CallAsync"); await _io.WriteAsync(command); //_io.Stream.BeginRead() return command.Parse(_io.Reader); } #endif public void Write(RedisCommand command) { ConnectIfNotConnected(); try { //Console.WriteLine("--------------Write"); _io.Write(_io.Writer.Prepare(command)); } catch (IOException) { if (ReconnectAttempts == 0) throw; Reconnect(); Write(command); } } public T Read<T>(Func<RedisReader, T> func) { ExpectConnected(); try { return func(_io.Reader); } catch (IOException) { if (ReconnectAttempts == 0) throw; Reconnect(); return Read(func); } } public void Read(Stream destination, int bufferSize) { ExpectConnected(); try { _io.Reader.ExpectType(RedisMessage.Bulk); _io.Reader.ReadBulkBytes(destination, bufferSize, false); } catch (IOException) { if (ReconnectAttempts == 0) throw; Reconnect(); Read(destination, bufferSize); } } public void BeginPipe() { ConnectIfNotConnected(); _io.Pipeline.Begin(); } public object[] EndPipe() { ExpectConnected(); try { return _io.Pipeline.Flush(); } catch (IOException) { if (ReconnectAttempts == 0) throw; Reconnect(); return EndPipe(); } } public void Dispose() { _io.Dispose(); if (_redisSocket != null) _redisSocket.Dispose(); } void Reconnect() { int attempts = 0; while (attempts++ < ReconnectAttempts || ReconnectAttempts == -1) { if (Connect(5000)) return; Thread.Sleep(TimeSpan.FromMilliseconds(ReconnectWait)); } throw new IOException("Could not reconnect after " + attempts + " attempts"); } void OnConnected() { _io.SetStream(_redisSocket.GetStream()); if (Connected != null) Connected(this, new EventArgs()); } void OnAsyncConnected(object sender, EventArgs args) { OnConnected(); } void ConnectIfNotConnected() { if (!IsConnected) Connect(5000); } void ExpectConnected() { if (!IsConnected) throw new RedisClientException("Client is not connected"); } } }
2881099/csredis
1,440
src/CSRedisCore/Internal/RedisListener.cs
using CSRedis.Internal.IO; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Sockets; using System.Text; namespace CSRedis.Internal { internal abstract class RedisListener<TResponse> { private readonly RedisConnector _connection; public bool Listening { get; private set; } protected RedisConnector Connection { get { return _connection; } } protected RedisListener(RedisConnector connection) { _connection = connection; } protected void Listen(Func<RedisReader, TResponse> func) { Listening = true; do { try { TResponse value = _connection.Read(func); OnParsed(value); } catch (IOException) { if (_connection.IsConnected) throw; break; } } while (Continue()); Listening = false; } protected void Write<T>(RedisCommand<T> command) { _connection.Write(command); } protected T Call<T>(RedisCommand<T> command) { return _connection.Call(command); } protected abstract void OnParsed(TResponse value); protected abstract bool Continue(); } }
2881099/csredis
2,338
src/CSRedisCore/Internal/Commands/RedisHash.cs
using CSRedis.Internal.IO; using CSRedis.Internal.Utilities; using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Reflection; namespace CSRedis.Internal.Commands { class RedisHash : RedisCommand<Dictionary<string, string>> { public RedisHash(string command, params object[] args) : base(command, args) { } public override Dictionary<string, string> Parse(RedisReader reader) { return ToDict(reader); } static Dictionary<string, string> ToDict(RedisReader reader) { reader.ExpectType(RedisMessage.MultiBulk); long count = reader.ReadInt(false); var dict = new Dictionary<string, string>(); string key = String.Empty; for (int i = 0; i < count; i++) { if (i % 2 == 0) key = reader.ReadBulkString(); else dict[key] = reader.ReadBulkString(); } return dict; } public class Generic<T> : RedisCommand<T> where T : class { public Generic(string command, params object[] args) : base(command, args) { } public override T Parse(RedisReader reader) { return Serializer<T>.Deserialize(RedisHash.ToDict(reader)); } } } class RedisHashBytes : RedisCommand<Dictionary<string, byte[]>> { public RedisHashBytes(string command, params object[] args) : base(command, args) { } public override Dictionary<string, byte[]> Parse(RedisReader reader) { return ToDict(reader); } static Dictionary<string, byte[]> ToDict(RedisReader reader) { reader.ExpectType(RedisMessage.MultiBulk); long count = reader.ReadInt(false); var dict = new Dictionary<string, byte[]>(); string key = String.Empty; for (int i = 0; i < count; i++) { if (i % 2 == 0) key = reader.ReadBulkString(); else dict[key] = reader.ReadBulkBytes(); } return dict; } } }
2881099/csredis
6,406
src/CSRedisCore/Internal/Commands/RedisTuple.cs
using CSRedis.Internal.IO; using System; using System.ComponentModel; using System.IO; namespace CSRedis.Internal.Commands { class RedisTuple : RedisCommand<Tuple<string, string>> { public RedisTuple(string command, params object[] args) : base(command, args) { } public override Tuple<string, string> Parse(RedisReader reader) { reader.ExpectType(RedisMessage.MultiBulk); long count = reader.ReadInt(false); if (count != 2) return null; //使用 BLPop 命令在 RedisArray.cs 中报错的解决办法。 #22 //reader.ExpectSize(2); return Tuple.Create(reader.ReadBulkString(), reader.ReadBulkString()); } public abstract class Generic<T1, T2> : RedisCommand<Tuple<T1, T2>> { readonly RedisCommand<T1> _command1; readonly RedisCommand<T2> _command2; protected Generic(RedisCommand<T1> command1, RedisCommand<T2> command2, string command, params object[] args) : base(command, args) { _command1 = command1; _command2 = command2; } protected Tuple<T1, T2> Create(RedisReader reader) { return Tuple.Create(_command1.Parse(reader), _command2.Parse(reader)); } public class Repeating : Generic<T1, T2> { public Repeating(RedisCommand<T1> command1, RedisCommand<T2> command2, string command, params object[] args) : base(command1, command2, command, args) { } public override Tuple<T1, T2> Parse(RedisReader reader) { return Create(reader); } } public class Single : Generic<T1, T2> { public Single(RedisCommand<T1> command1, RedisCommand<T2> command2, string command, params object[] args) : base(command1, command2, command, args) { } public override Tuple<T1, T2> Parse(RedisReader reader) { reader.ExpectMultiBulk(2); return Create(reader); } } } public abstract class Generic<T1, T2, T3> : RedisCommand<Tuple<T1, T2, T3>> { readonly RedisCommand<T1> _command1; readonly RedisCommand<T2> _command2; readonly RedisCommand<T3> _command3; protected Generic(RedisCommand<T1> command1, RedisCommand<T2> command2, RedisCommand<T3> command3, string command, params object[] args) : base(command, args) { _command1 = command1; _command2 = command2; _command3 = command3; } protected Tuple<T1, T2, T3> Create(RedisReader reader) { return Tuple.Create(_command1.Parse(reader), _command2.Parse(reader), _command3.Parse(reader)); } public class Repeating : Generic<T1, T2, T3> { public Repeating(RedisCommand<T1> command1, RedisCommand<T2> command2, RedisCommand<T3> command3, string command, params object[] args) : base(command1, command2, command3, command, args) { } public override Tuple<T1, T2, T3> Parse(RedisReader reader) { return Create(reader); } } public class Single : Generic<T1, T2, T3> { public Single(RedisCommand<T1> command1, RedisCommand<T2> command2, RedisCommand<T3> command3, string command, params object[] args) : base(command1, command2, command3, command, args) { } public override Tuple<T1, T2, T3> Parse(RedisReader reader) { reader.ExpectMultiBulk(3); return Create(reader); } } } public abstract class Generic<T1, T2, T3, T4> : RedisCommand<Tuple<T1, T2, T3, T4>> { readonly RedisCommand<T1> _command1; readonly RedisCommand<T2> _command2; readonly RedisCommand<T3> _command3; readonly RedisCommand<T4> _command4; protected Generic(RedisCommand<T1> command1, RedisCommand<T2> command2, RedisCommand<T3> command3, RedisCommand<T4> command4, string command, params object[] args) : base(command, args) { _command1 = command1; _command2 = command2; _command3 = command3; _command4 = command4; } protected Tuple<T1, T2, T3, T4> Create(RedisReader reader) { return Tuple.Create( _command1.Parse(reader), _command2 == null ? default(T2) : _command2.Parse(reader), _command3 == null ? default(T3) : _command3.Parse(reader), _command4 == null ? default(T4) : _command4.Parse(reader)); } public class Repeating : Generic<T1, T2, T3, T4> { public Repeating(RedisCommand<T1> command1, RedisCommand<T2> command2, RedisCommand<T3> command3, RedisCommand<T4> command4, string command, params object[] args) : base(command1, command2, command3, command4, command, args) { } public override Tuple<T1, T2, T3, T4> Parse(RedisReader reader) { return Create(reader); } } public class Single : Generic<T1, T2, T3, T4> { public Single(RedisCommand<T1> command1, RedisCommand<T2> command2, RedisCommand<T3> command3, RedisCommand<T4> command4, string command, params object[] args) : base(command1, command2, command3, command4, command, args) { } public override Tuple<T1, T2, T3, T4> Parse(RedisReader reader) { var size = 1 + (_command2 == null ? 0 : 1) + (_command3 == null ? 0 : 1) + (_command4 == null ? 0 : 1); if (size > 1) reader.ExpectMultiBulk(size); return Create(reader); } } } } }
27182812/ChatGLM-LLaMA-chinese-insturct
2,037
src/transformers/models/speech_encoder_decoder/__init__.py
# Copyright 2021 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_flax_available, is_torch_available _import_structure = {"configuration_speech_encoder_decoder": ["SpeechEncoderDecoderConfig"]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _import_structure["modeling_speech_encoder_decoder"] = ["SpeechEncoderDecoderModel"] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _import_structure["modeling_flax_speech_encoder_decoder"] = ["FlaxSpeechEncoderDecoderModel"] if TYPE_CHECKING: from .configuration_speech_encoder_decoder import SpeechEncoderDecoderConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speech_encoder_decoder import SpeechEncoderDecoderModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_speech_encoder_decoder import FlaxSpeechEncoderDecoderModel else: import sys sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
2877025939/PlanADScrollView
1,044
PlanADScrollView/PlanADScrollView/SDWebImage/SDWebImage/UIView+WebCacheOperation.h
/* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import "SDWebImageCompat.h" #if SD_UIKIT || SD_MAC #import "SDWebImageManager.h" @interface UIView (WebCacheOperation) /** * Set the image load operation (storage in a UIView based dictionary) * * @param operation the operation * @param key key for storing the operation */ - (void)sd_setImageLoadOperation:(nullable id)operation forKey:(nullable NSString *)key; /** * Cancel all operations for the current UIView and key * * @param key key for identifying the operations */ - (void)sd_cancelImageLoadOperationWithKey:(nullable NSString *)key; /** * Just remove the operations corresponding to the current UIView and key without cancelling them * * @param key key for identifying the operations */ - (void)sd_removeImageLoadOperationWithKey:(nullable NSString *)key; @end #endif
2877025939/PlanADScrollView
7,425
PlanADScrollView/PlanADScrollView/SDWebImage/SDWebImage/UIView+WebCache.m
/* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import "UIView+WebCache.h" #if SD_UIKIT || SD_MAC #import "objc/runtime.h" #import "UIView+WebCacheOperation.h" static char imageURLKey; #if SD_UIKIT static char TAG_ACTIVITY_INDICATOR; static char TAG_ACTIVITY_STYLE; #endif static char TAG_ACTIVITY_SHOW; @implementation UIView (WebCache) - (nullable NSURL *)sd_imageURL { return objc_getAssociatedObject(self, &imageURLKey); } - (void)sd_internalSetImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options operationKey:(nullable NSString *)operationKey setImageBlock:(nullable SDSetImageBlock)setImageBlock progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock completed:(nullable SDExternalCompletionBlock)completedBlock { NSString *validOperationKey = operationKey ?: NSStringFromClass([self class]); [self sd_cancelImageLoadOperationWithKey:validOperationKey]; objc_setAssociatedObject(self, &imageURLKey, url, OBJC_ASSOCIATION_RETAIN_NONATOMIC); if (!(options & SDWebImageDelayPlaceholder)) { dispatch_main_async_safe(^{ [self sd_setImage:placeholder imageData:nil basedOnClassOrViaCustomSetImageBlock:setImageBlock]; }); } if (url) { // check if activityView is enabled or not if ([self sd_showActivityIndicatorView]) { [self sd_addActivityIndicator]; } __weak __typeof(self)wself = self; id <SDWebImageOperation> operation = [SDWebImageManager.sharedManager loadImageWithURL:url options:options progress:progressBlock completed:^(UIImage *image, NSData *data, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { __strong __typeof (wself) sself = wself; [sself sd_removeActivityIndicator]; if (!sself) { return; } dispatch_main_async_safe(^{ if (!sself) { return; } if (image && (options & SDWebImageAvoidAutoSetImage) && completedBlock) { completedBlock(image, error, cacheType, url); return; } else if (image) { [sself sd_setImage:image imageData:data basedOnClassOrViaCustomSetImageBlock:setImageBlock]; [sself sd_setNeedsLayout]; } else { if ((options & SDWebImageDelayPlaceholder)) { [sself sd_setImage:placeholder imageData:nil basedOnClassOrViaCustomSetImageBlock:setImageBlock]; [sself sd_setNeedsLayout]; } } if (completedBlock && finished) { completedBlock(image, error, cacheType, url); } }); }]; [self sd_setImageLoadOperation:operation forKey:validOperationKey]; } else { dispatch_main_async_safe(^{ [self sd_removeActivityIndicator]; if (completedBlock) { NSError *error = [NSError errorWithDomain:SDWebImageErrorDomain code:-1 userInfo:@{NSLocalizedDescriptionKey : @"Trying to load a nil url"}]; completedBlock(nil, error, SDImageCacheTypeNone, url); } }); } } - (void)sd_cancelCurrentImageLoad { [self sd_cancelImageLoadOperationWithKey:NSStringFromClass([self class])]; } - (void)sd_setImage:(UIImage *)image imageData:(NSData *)imageData basedOnClassOrViaCustomSetImageBlock:(SDSetImageBlock)setImageBlock { if (setImageBlock) { setImageBlock(image, imageData); return; } #if SD_UIKIT || SD_MAC if ([self isKindOfClass:[UIImageView class]]) { UIImageView *imageView = (UIImageView *)self; imageView.image = image; } #endif #if SD_UIKIT if ([self isKindOfClass:[UIButton class]]) { UIButton *button = (UIButton *)self; [button setImage:image forState:UIControlStateNormal]; } #endif } - (void)sd_setNeedsLayout { #if SD_UIKIT [self setNeedsLayout]; #elif SD_MAC [self setNeedsLayout:YES]; #endif } #pragma mark - Activity indicator #pragma mark - #if SD_UIKIT - (UIActivityIndicatorView *)activityIndicator { return (UIActivityIndicatorView *)objc_getAssociatedObject(self, &TAG_ACTIVITY_INDICATOR); } - (void)setActivityIndicator:(UIActivityIndicatorView *)activityIndicator { objc_setAssociatedObject(self, &TAG_ACTIVITY_INDICATOR, activityIndicator, OBJC_ASSOCIATION_RETAIN); } #endif - (void)sd_setShowActivityIndicatorView:(BOOL)show { objc_setAssociatedObject(self, &TAG_ACTIVITY_SHOW, @(show), OBJC_ASSOCIATION_RETAIN); } - (BOOL)sd_showActivityIndicatorView { return [objc_getAssociatedObject(self, &TAG_ACTIVITY_SHOW) boolValue]; } #if SD_UIKIT - (void)sd_setIndicatorStyle:(UIActivityIndicatorViewStyle)style{ objc_setAssociatedObject(self, &TAG_ACTIVITY_STYLE, [NSNumber numberWithInt:style], OBJC_ASSOCIATION_RETAIN); } - (int)sd_getIndicatorStyle{ return [objc_getAssociatedObject(self, &TAG_ACTIVITY_STYLE) intValue]; } #endif - (void)sd_addActivityIndicator { #if SD_UIKIT if (!self.activityIndicator) { self.activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:[self sd_getIndicatorStyle]]; self.activityIndicator.translatesAutoresizingMaskIntoConstraints = NO; dispatch_main_async_safe(^{ [self addSubview:self.activityIndicator]; [self addConstraint:[NSLayoutConstraint constraintWithItem:self.activityIndicator attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0.0]]; [self addConstraint:[NSLayoutConstraint constraintWithItem:self.activityIndicator attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0.0]]; }); } dispatch_main_async_safe(^{ [self.activityIndicator startAnimating]; }); #endif } - (void)sd_removeActivityIndicator { #if SD_UIKIT if (self.activityIndicator) { [self.activityIndicator removeFromSuperview]; self.activityIndicator = nil; } #endif } @end #endif
2877025939/PlanADScrollView
1,274
PlanADScrollView/PlanADScrollView/SDWebImage/SDWebImage/NSData+ImageContentType.m
/* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * (c) Fabrice Aneche * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import "NSData+ImageContentType.h" @implementation NSData (ImageContentType) + (SDImageFormat)sd_imageFormatForImageData:(nullable NSData *)data { if (!data) { return SDImageFormatUndefined; } uint8_t c; [data getBytes:&c length:1]; switch (c) { case 0xFF: return SDImageFormatJPEG; case 0x89: return SDImageFormatPNG; case 0x47: return SDImageFormatGIF; case 0x49: case 0x4D: return SDImageFormatTIFF; case 0x52: // R as RIFF for WEBP if (data.length < 12) { return SDImageFormatUndefined; } NSString *testString = [[NSString alloc] initWithData:[data subdataWithRange:NSMakeRange(0, 12)] encoding:NSASCIIStringEncoding]; if ([testString hasPrefix:@"RIFF"] && [testString hasSuffix:@"WEBP"]) { return SDImageFormatWebP; } } return SDImageFormatUndefined; } @end
2877025939/PlanADScrollView
4,865
PlanADScrollView/PlanADScrollView/SDWebImage/SDWebImage/UIImageView+WebCache.m
/* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import "UIImageView+WebCache.h" #if SD_UIKIT || SD_MAC #import "objc/runtime.h" #import "UIView+WebCacheOperation.h" #import "UIView+WebCache.h" @implementation UIImageView (WebCache) - (void)sd_setImageWithURL:(nullable NSURL *)url { [self sd_setImageWithURL:url placeholderImage:nil options:0 progress:nil completed:nil]; } - (void)sd_setImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder { [self sd_setImageWithURL:url placeholderImage:placeholder options:0 progress:nil completed:nil]; } - (void)sd_setImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options { [self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:nil]; } - (void)sd_setImageWithURL:(nullable NSURL *)url completed:(nullable SDExternalCompletionBlock)completedBlock { [self sd_setImageWithURL:url placeholderImage:nil options:0 progress:nil completed:completedBlock]; } - (void)sd_setImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder completed:(nullable SDExternalCompletionBlock)completedBlock { [self sd_setImageWithURL:url placeholderImage:placeholder options:0 progress:nil completed:completedBlock]; } - (void)sd_setImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options completed:(nullable SDExternalCompletionBlock)completedBlock { [self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:completedBlock]; } - (void)sd_setImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock completed:(nullable SDExternalCompletionBlock)completedBlock { [self sd_internalSetImageWithURL:url placeholderImage:placeholder options:options operationKey:nil setImageBlock:nil progress:progressBlock completed:completedBlock]; } - (void)sd_setImageWithPreviousCachedImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock completed:(nullable SDExternalCompletionBlock)completedBlock { NSString *key = [[SDWebImageManager sharedManager] cacheKeyForURL:url]; UIImage *lastPreviousCachedImage = [[SDImageCache sharedImageCache] imageFromCacheForKey:key]; [self sd_setImageWithURL:url placeholderImage:lastPreviousCachedImage ?: placeholder options:options progress:progressBlock completed:completedBlock]; } #if SD_UIKIT #pragma mark - Animation of multiple images - (void)sd_setAnimationImagesWithURLs:(nonnull NSArray<NSURL *> *)arrayOfURLs { [self sd_cancelCurrentAnimationImagesLoad]; __weak __typeof(self)wself = self; NSMutableArray<id<SDWebImageOperation>> *operationsArray = [[NSMutableArray alloc] init]; for (NSURL *logoImageURL in arrayOfURLs) { id <SDWebImageOperation> operation = [SDWebImageManager.sharedManager loadImageWithURL:logoImageURL options:0 progress:nil completed:^(UIImage *image, NSData *data, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { if (!wself) return; dispatch_main_async_safe(^{ __strong UIImageView *sself = wself; [sself stopAnimating]; if (sself && image) { NSMutableArray<UIImage *> *currentImages = [[sself animationImages] mutableCopy]; if (!currentImages) { currentImages = [[NSMutableArray alloc] init]; } [currentImages addObject:image]; sself.animationImages = currentImages; [sself setNeedsLayout]; } [sself startAnimating]; }); }]; [operationsArray addObject:operation]; } [self sd_setImageLoadOperation:[operationsArray copy] forKey:@"UIImageViewAnimationImages"]; } - (void)sd_cancelCurrentAnimationImagesLoad { [self sd_cancelImageLoadOperationWithKey:@"UIImageViewAnimationImages"]; } #endif @end #endif
2877025939/PlanADScrollView
2,899
PlanADScrollView/PlanADScrollView/SDWebImage/SDWebImage/UIView+WebCache.h
/* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import "SDWebImageCompat.h" #if SD_UIKIT || SD_MAC #import "SDWebImageManager.h" typedef void(^SDSetImageBlock)(UIImage * _Nullable image, NSData * _Nullable imageData); @interface UIView (WebCache) /** * Get the current image URL. * * Note that because of the limitations of categories this property can get out of sync * if you use setImage: directly. */ - (nullable NSURL *)sd_imageURL; /** * Set the imageView `image` with an `url` and optionally a placeholder image. * * The download is asynchronous and cached. * * @param url The url for the image. * @param placeholder The image to be set initially, until the image request finishes. * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. * @param operationKey A string to be used as the operation key. If nil, will use the class name * @param setImageBlock Block used for custom set image code * @param progressBlock A block called while image is downloading * @note the progress block is executed on a background queue * @param completedBlock A block called when operation has been completed. This block has no return value * and takes the requested UIImage as first parameter. In case of error the image parameter * is nil and the second parameter may contain an NSError. The third parameter is a Boolean * indicating if the image was retrieved from the local cache or from the network. * The fourth parameter is the original image url. */ - (void)sd_internalSetImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options operationKey:(nullable NSString *)operationKey setImageBlock:(nullable SDSetImageBlock)setImageBlock progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock completed:(nullable SDExternalCompletionBlock)completedBlock; /** * Cancel the current download */ - (void)sd_cancelCurrentImageLoad; #if SD_UIKIT #pragma mark - Activity indicator /** * Show activity UIActivityIndicatorView */ - (void)sd_setShowActivityIndicatorView:(BOOL)show; /** * set desired UIActivityIndicatorViewStyle * * @param style The style of the UIActivityIndicatorView */ - (void)sd_setIndicatorStyle:(UIActivityIndicatorViewStyle)style; - (BOOL)sd_showActivityIndicatorView; - (void)sd_addActivityIndicator; - (void)sd_removeActivityIndicator; #endif @end #endif
2881099/csredis
4,353
src/CSRedisCore/Internal/Commands/RedisArray.cs
using CSRedis.Internal.IO; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CSRedis.Internal.Commands { class RedisArray : RedisCommand<object[]> { readonly Queue<Func<RedisReader, object>> _parsers = new Queue<Func<RedisReader, object>>(); public RedisArray(string command, params object[] args) : base(command, args) { } public override object[] Parse(RedisReader reader) { if (_parsers.Count == 0) return reader.ReadMultiBulk(bulkAsString: true); reader.ExpectType(RedisMessage.MultiBulk); long count = reader.ReadInt(false); if (count != _parsers.Count) throw new RedisProtocolException(String.Format("Expecting {0} array items; got {1}", _parsers.Count, count)); object[] results = new object[_parsers.Count]; for (int i = 0; i < results.Length; i++) results[i] = _parsers.Dequeue()(reader); return results; } public void AddParser(Func<RedisReader, object> parser) { _parsers.Enqueue(parser); } public class Generic<T> : RedisCommand<T[]> { readonly RedisCommand<T> _memberCommand; protected RedisCommand<T> MemberCommand { get { return _memberCommand; } } public Generic(RedisCommand<T> memberCommand) : base(memberCommand.Command, memberCommand.Arguments) { _memberCommand = memberCommand; } public override T[] Parse(RedisReader reader) { reader.ExpectType(RedisMessage.MultiBulk); long count = reader.ReadInt(false); return Read(count, reader); } protected virtual T[] Read(long count, RedisReader reader) { if (count < 0) return null; T[] array = new T[count]; for (int i = 0; i < array.Length; i++) array[i] = _memberCommand.Parse(reader); return array; } } public class IndexOf<T> : RedisCommand<T> { readonly RedisCommand<T> _command; readonly int _index; public IndexOf(RedisCommand<T> command, int index) : base(command.Command, command.Arguments) { _command = command; _index = index; } public override T Parse(RedisReader reader) { reader.ExpectType(RedisMessage.MultiBulk); long count = reader.ReadInt(false); if (count == -1) return default(T); //使用 BLPop 命令在 RedisArray.cs 中报错的解决办法。 #22 T[] array = new T[count]; for (int i = 0; i < array.Length; i++) array[i] = _command.Parse(reader); return array[_index]; } } public class Strings : Generic<string> { public Strings(string command, params object[] args) : base(new RedisString(command, args)) { } } public class Bytes : Generic<byte[]> { public Bytes(string command, params object[] args) : base(new RedisBytes(command, args)) { } } public class StrongPairs<T1, T2> : Generic<Tuple<T1, T2>> { public StrongPairs(RedisCommand<T1> command1, RedisCommand<T2> command2, string command, params object[] args) : base(new RedisTuple.Generic<T1, T2>.Repeating(command1, command2, command, args)) { } protected override Tuple<T1, T2>[] Read(long count, RedisReader reader) { var array = new Tuple<T1, T2>[count / 2]; for (int i = 0; i < count; i += 2) array[i / 2] = MemberCommand.Parse(reader); return array; } } public class WeakPairs<T1, T2> : StrongPairs<T1, T2> { public WeakPairs(string command, params object[] args) : base(new RedisString.Converter<T1>(null), new RedisString.Converter<T2>(null), command, args) { } } } }
2877025939/PlanADScrollView
22,939
PlanADScrollView/PlanADScrollView/SDWebImage/SDWebImage/SDImageCache.m
/* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import "SDImageCache.h" #import "SDWebImageDecoder.h" #import "UIImage+MultiFormat.h" #import <CommonCrypto/CommonDigest.h> #import "UIImage+GIF.h" #import "NSData+ImageContentType.h" #import "NSImage+WebCache.h" #import "SDImageCacheConfig.h" // See https://github.com/rs/SDWebImage/pull/1141 for discussion @interface AutoPurgeCache : NSCache @end @implementation AutoPurgeCache - (nonnull instancetype)init { self = [super init]; if (self) { #if SD_UIKIT [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(removeAllObjects) name:UIApplicationDidReceiveMemoryWarningNotification object:nil]; #endif } return self; } - (void)dealloc { #if SD_UIKIT [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidReceiveMemoryWarningNotification object:nil]; #endif } @end FOUNDATION_STATIC_INLINE NSUInteger SDCacheCostForImage(UIImage *image) { #if SD_MAC return image.size.height * image.size.width; #elif SD_UIKIT || SD_WATCH return image.size.height * image.size.width * image.scale * image.scale; #endif } @interface SDImageCache () #pragma mark - Properties @property (strong, nonatomic, nonnull) NSCache *memCache; @property (strong, nonatomic, nonnull) NSString *diskCachePath; @property (strong, nonatomic, nullable) NSMutableArray<NSString *> *customPaths; @property (SDDispatchQueueSetterSementics, nonatomic, nullable) dispatch_queue_t ioQueue; @end @implementation SDImageCache { NSFileManager *_fileManager; } #pragma mark - Singleton, init, dealloc + (nonnull instancetype)sharedImageCache { static dispatch_once_t once; static id instance; dispatch_once(&once, ^{ instance = [self new]; }); return instance; } - (instancetype)init { return [self initWithNamespace:@"default"]; } - (nonnull instancetype)initWithNamespace:(nonnull NSString *)ns { NSString *path = [self makeDiskCachePath:ns]; return [self initWithNamespace:ns diskCacheDirectory:path]; } - (nonnull instancetype)initWithNamespace:(nonnull NSString *)ns diskCacheDirectory:(nonnull NSString *)directory { if ((self = [super init])) { NSString *fullNamespace = [@"com.hackemist.SDWebImageCache." stringByAppendingString:ns]; // Create IO serial queue _ioQueue = dispatch_queue_create("com.hackemist.SDWebImageCache", DISPATCH_QUEUE_SERIAL); _config = [[SDImageCacheConfig alloc] init]; // Init the memory cache _memCache = [[AutoPurgeCache alloc] init]; _memCache.name = fullNamespace; // Init the disk cache if (directory != nil) { _diskCachePath = [directory stringByAppendingPathComponent:fullNamespace]; } else { NSString *path = [self makeDiskCachePath:ns]; _diskCachePath = path; } dispatch_sync(_ioQueue, ^{ _fileManager = [NSFileManager new]; }); #if SD_UIKIT // Subscribe to app events [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clearMemory) name:UIApplicationDidReceiveMemoryWarningNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deleteOldFiles) name:UIApplicationWillTerminateNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(backgroundDeleteOldFiles) name:UIApplicationDidEnterBackgroundNotification object:nil]; #endif } return self; } - (void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self]; SDDispatchQueueRelease(_ioQueue); } - (void)checkIfQueueIsIOQueue { const char *currentQueueLabel = dispatch_queue_get_label(DISPATCH_CURRENT_QUEUE_LABEL); const char *ioQueueLabel = dispatch_queue_get_label(self.ioQueue); if (strcmp(currentQueueLabel, ioQueueLabel) != 0) { NSLog(@"This method should be called from the ioQueue"); } } #pragma mark - Cache paths - (void)addReadOnlyCachePath:(nonnull NSString *)path { if (!self.customPaths) { self.customPaths = [NSMutableArray new]; } if (![self.customPaths containsObject:path]) { [self.customPaths addObject:path]; } } - (nullable NSString *)cachePathForKey:(nullable NSString *)key inPath:(nonnull NSString *)path { NSString *filename = [self cachedFileNameForKey:key]; return [path stringByAppendingPathComponent:filename]; } - (nullable NSString *)defaultCachePathForKey:(nullable NSString *)key { return [self cachePathForKey:key inPath:self.diskCachePath]; } - (nullable NSString *)cachedFileNameForKey:(nullable NSString *)key { const char *str = key.UTF8String; if (str == NULL) { str = ""; } unsigned char r[CC_MD5_DIGEST_LENGTH]; CC_MD5(str, (CC_LONG)strlen(str), r); NSString *filename = [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%@", r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9], r[10], r[11], r[12], r[13], r[14], r[15], [key.pathExtension isEqualToString:@""] ? @"" : [NSString stringWithFormat:@".%@", key.pathExtension]]; return filename; } - (nullable NSString *)makeDiskCachePath:(nonnull NSString*)fullNamespace { NSArray<NSString *> *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); return [paths[0] stringByAppendingPathComponent:fullNamespace]; } #pragma mark - Store Ops - (void)storeImage:(nullable UIImage *)image forKey:(nullable NSString *)key completion:(nullable SDWebImageNoParamsBlock)completionBlock { [self storeImage:image imageData:nil forKey:key toDisk:YES completion:completionBlock]; } - (void)storeImage:(nullable UIImage *)image forKey:(nullable NSString *)key toDisk:(BOOL)toDisk completion:(nullable SDWebImageNoParamsBlock)completionBlock { [self storeImage:image imageData:nil forKey:key toDisk:toDisk completion:completionBlock]; } - (void)storeImage:(nullable UIImage *)image imageData:(nullable NSData *)imageData forKey:(nullable NSString *)key toDisk:(BOOL)toDisk completion:(nullable SDWebImageNoParamsBlock)completionBlock { if (!image || !key) { if (completionBlock) { completionBlock(); } return; } // if memory cache is enabled if (self.config.shouldCacheImagesInMemory) { NSUInteger cost = SDCacheCostForImage(image); [self.memCache setObject:image forKey:key cost:cost]; } if (toDisk) { dispatch_async(self.ioQueue, ^{ NSData *data = imageData; if (!data && image) { SDImageFormat imageFormatFromData = [NSData sd_imageFormatForImageData:data]; data = [image sd_imageDataAsFormat:imageFormatFromData]; } [self storeImageDataToDisk:data forKey:key]; if (completionBlock) { dispatch_async(dispatch_get_main_queue(), ^{ completionBlock(); }); } }); } else { if (completionBlock) { completionBlock(); } } } - (void)storeImageDataToDisk:(nullable NSData *)imageData forKey:(nullable NSString *)key { if (!imageData || !key) { return; } [self checkIfQueueIsIOQueue]; if (![_fileManager fileExistsAtPath:_diskCachePath]) { [_fileManager createDirectoryAtPath:_diskCachePath withIntermediateDirectories:YES attributes:nil error:NULL]; } // get cache Path for image key NSString *cachePathForKey = [self defaultCachePathForKey:key]; // transform to NSUrl NSURL *fileURL = [NSURL fileURLWithPath:cachePathForKey]; [_fileManager createFileAtPath:cachePathForKey contents:imageData attributes:nil]; // disable iCloud backup if (self.config.shouldDisableiCloud) { [fileURL setResourceValue:@YES forKey:NSURLIsExcludedFromBackupKey error:nil]; } } #pragma mark - Query and Retrieve Ops - (void)diskImageExistsWithKey:(nullable NSString *)key completion:(nullable SDWebImageCheckCacheCompletionBlock)completionBlock { dispatch_async(_ioQueue, ^{ BOOL exists = [_fileManager fileExistsAtPath:[self defaultCachePathForKey:key]]; // fallback because of https://github.com/rs/SDWebImage/pull/976 that added the extension to the disk file name // checking the key with and without the extension if (!exists) { exists = [_fileManager fileExistsAtPath:[self defaultCachePathForKey:key].stringByDeletingPathExtension]; } if (completionBlock) { dispatch_async(dispatch_get_main_queue(), ^{ completionBlock(exists); }); } }); } - (nullable UIImage *)imageFromMemoryCacheForKey:(nullable NSString *)key { return [self.memCache objectForKey:key]; } - (nullable UIImage *)imageFromDiskCacheForKey:(nullable NSString *)key { UIImage *diskImage = [self diskImageForKey:key]; if (diskImage && self.config.shouldCacheImagesInMemory) { NSUInteger cost = SDCacheCostForImage(diskImage); [self.memCache setObject:diskImage forKey:key cost:cost]; } return diskImage; } - (nullable UIImage *)imageFromCacheForKey:(nullable NSString *)key { // First check the in-memory cache... UIImage *image = [self imageFromMemoryCacheForKey:key]; if (image) { return image; } // Second check the disk cache... image = [self imageFromDiskCacheForKey:key]; return image; } - (nullable NSData *)diskImageDataBySearchingAllPathsForKey:(nullable NSString *)key { NSString *defaultPath = [self defaultCachePathForKey:key]; NSData *data = [NSData dataWithContentsOfFile:defaultPath]; if (data) { return data; } // fallback because of https://github.com/rs/SDWebImage/pull/976 that added the extension to the disk file name // checking the key with and without the extension data = [NSData dataWithContentsOfFile:defaultPath.stringByDeletingPathExtension]; if (data) { return data; } NSArray<NSString *> *customPaths = [self.customPaths copy]; for (NSString *path in customPaths) { NSString *filePath = [self cachePathForKey:key inPath:path]; NSData *imageData = [NSData dataWithContentsOfFile:filePath]; if (imageData) { return imageData; } // fallback because of https://github.com/rs/SDWebImage/pull/976 that added the extension to the disk file name // checking the key with and without the extension imageData = [NSData dataWithContentsOfFile:filePath.stringByDeletingPathExtension]; if (imageData) { return imageData; } } return nil; } - (nullable UIImage *)diskImageForKey:(nullable NSString *)key { NSData *data = [self diskImageDataBySearchingAllPathsForKey:key]; if (data) { UIImage *image = [UIImage sd_imageWithData:data]; image = [self scaledImageForKey:key image:image]; if (self.config.shouldDecompressImages) { image = [UIImage decodedImageWithImage:image]; } return image; } else { return nil; } } - (nullable UIImage *)scaledImageForKey:(nullable NSString *)key image:(nullable UIImage *)image { return SDScaledImageForKey(key, image); } - (nullable NSOperation *)queryCacheOperationForKey:(nullable NSString *)key done:(nullable SDCacheQueryCompletedBlock)doneBlock { if (!key) { if (doneBlock) { doneBlock(nil, nil, SDImageCacheTypeNone); } return nil; } // First check the in-memory cache... UIImage *image = [self imageFromMemoryCacheForKey:key]; if (image) { NSData *diskData = nil; if ([image isGIF]) { diskData = [self diskImageDataBySearchingAllPathsForKey:key]; } if (doneBlock) { doneBlock(image, diskData, SDImageCacheTypeMemory); } return nil; } NSOperation *operation = [NSOperation new]; dispatch_async(self.ioQueue, ^{ if (operation.isCancelled) { // do not call the completion if cancelled return; } @autoreleasepool { NSData *diskData = [self diskImageDataBySearchingAllPathsForKey:key]; UIImage *diskImage = [self diskImageForKey:key]; if (diskImage && self.config.shouldCacheImagesInMemory) { NSUInteger cost = SDCacheCostForImage(diskImage); [self.memCache setObject:diskImage forKey:key cost:cost]; } if (doneBlock) { dispatch_async(dispatch_get_main_queue(), ^{ doneBlock(diskImage, diskData, SDImageCacheTypeDisk); }); } } }); return operation; } #pragma mark - Remove Ops - (void)removeImageForKey:(nullable NSString *)key withCompletion:(nullable SDWebImageNoParamsBlock)completion { [self removeImageForKey:key fromDisk:YES withCompletion:completion]; } - (void)removeImageForKey:(nullable NSString *)key fromDisk:(BOOL)fromDisk withCompletion:(nullable SDWebImageNoParamsBlock)completion { if (key == nil) { return; } if (self.config.shouldCacheImagesInMemory) { [self.memCache removeObjectForKey:key]; } if (fromDisk) { dispatch_async(self.ioQueue, ^{ [_fileManager removeItemAtPath:[self defaultCachePathForKey:key] error:nil]; if (completion) { dispatch_async(dispatch_get_main_queue(), ^{ completion(); }); } }); } else if (completion){ completion(); } } # pragma mark - Mem Cache settings - (void)setMaxMemoryCost:(NSUInteger)maxMemoryCost { self.memCache.totalCostLimit = maxMemoryCost; } - (NSUInteger)maxMemoryCost { return self.memCache.totalCostLimit; } - (NSUInteger)maxMemoryCountLimit { return self.memCache.countLimit; } - (void)setMaxMemoryCountLimit:(NSUInteger)maxCountLimit { self.memCache.countLimit = maxCountLimit; } #pragma mark - Cache clean Ops - (void)clearMemory { [self.memCache removeAllObjects]; } - (void)clearDiskOnCompletion:(nullable SDWebImageNoParamsBlock)completion { dispatch_async(self.ioQueue, ^{ [_fileManager removeItemAtPath:self.diskCachePath error:nil]; [_fileManager createDirectoryAtPath:self.diskCachePath withIntermediateDirectories:YES attributes:nil error:NULL]; if (completion) { dispatch_async(dispatch_get_main_queue(), ^{ completion(); }); } }); } - (void)deleteOldFiles { [self deleteOldFilesWithCompletionBlock:nil]; } - (void)deleteOldFilesWithCompletionBlock:(nullable SDWebImageNoParamsBlock)completionBlock { dispatch_async(self.ioQueue, ^{ NSURL *diskCacheURL = [NSURL fileURLWithPath:self.diskCachePath isDirectory:YES]; NSArray<NSString *> *resourceKeys = @[NSURLIsDirectoryKey, NSURLContentModificationDateKey, NSURLTotalFileAllocatedSizeKey]; // This enumerator prefetches useful properties for our cache files. NSDirectoryEnumerator *fileEnumerator = [_fileManager enumeratorAtURL:diskCacheURL includingPropertiesForKeys:resourceKeys options:NSDirectoryEnumerationSkipsHiddenFiles errorHandler:NULL]; NSDate *expirationDate = [NSDate dateWithTimeIntervalSinceNow:-self.config.maxCacheAge]; NSMutableDictionary<NSURL *, NSDictionary<NSString *, id> *> *cacheFiles = [NSMutableDictionary dictionary]; NSUInteger currentCacheSize = 0; // Enumerate all of the files in the cache directory. This loop has two purposes: // // 1. Removing files that are older than the expiration date. // 2. Storing file attributes for the size-based cleanup pass. NSMutableArray<NSURL *> *urlsToDelete = [[NSMutableArray alloc] init]; for (NSURL *fileURL in fileEnumerator) { NSError *error; NSDictionary<NSString *, id> *resourceValues = [fileURL resourceValuesForKeys:resourceKeys error:&error]; // Skip directories and errors. if (error || !resourceValues || [resourceValues[NSURLIsDirectoryKey] boolValue]) { continue; } // Remove files that are older than the expiration date; NSDate *modificationDate = resourceValues[NSURLContentModificationDateKey]; if ([[modificationDate laterDate:expirationDate] isEqualToDate:expirationDate]) { [urlsToDelete addObject:fileURL]; continue; } // Store a reference to this file and account for its total size. NSNumber *totalAllocatedSize = resourceValues[NSURLTotalFileAllocatedSizeKey]; currentCacheSize += totalAllocatedSize.unsignedIntegerValue; cacheFiles[fileURL] = resourceValues; } for (NSURL *fileURL in urlsToDelete) { [_fileManager removeItemAtURL:fileURL error:nil]; } // If our remaining disk cache exceeds a configured maximum size, perform a second // size-based cleanup pass. We delete the oldest files first. if (self.config.maxCacheSize > 0 && currentCacheSize > self.config.maxCacheSize) { // Target half of our maximum cache size for this cleanup pass. const NSUInteger desiredCacheSize = self.config.maxCacheSize / 2; // Sort the remaining cache files by their last modification time (oldest first). NSArray<NSURL *> *sortedFiles = [cacheFiles keysSortedByValueWithOptions:NSSortConcurrent usingComparator:^NSComparisonResult(id obj1, id obj2) { return [obj1[NSURLContentModificationDateKey] compare:obj2[NSURLContentModificationDateKey]]; }]; // Delete files until we fall below our desired cache size. for (NSURL *fileURL in sortedFiles) { if ([_fileManager removeItemAtURL:fileURL error:nil]) { NSDictionary<NSString *, id> *resourceValues = cacheFiles[fileURL]; NSNumber *totalAllocatedSize = resourceValues[NSURLTotalFileAllocatedSizeKey]; currentCacheSize -= totalAllocatedSize.unsignedIntegerValue; if (currentCacheSize < desiredCacheSize) { break; } } } } if (completionBlock) { dispatch_async(dispatch_get_main_queue(), ^{ completionBlock(); }); } }); } #if SD_UIKIT - (void)backgroundDeleteOldFiles { Class UIApplicationClass = NSClassFromString(@"UIApplication"); if(!UIApplicationClass || ![UIApplicationClass respondsToSelector:@selector(sharedApplication)]) { return; } UIApplication *application = [UIApplication performSelector:@selector(sharedApplication)]; __block UIBackgroundTaskIdentifier bgTask = [application beginBackgroundTaskWithExpirationHandler:^{ // Clean up any unfinished task business by marking where you // stopped or ending the task outright. [application endBackgroundTask:bgTask]; bgTask = UIBackgroundTaskInvalid; }]; // Start the long-running task and return immediately. [self deleteOldFilesWithCompletionBlock:^{ [application endBackgroundTask:bgTask]; bgTask = UIBackgroundTaskInvalid; }]; } #endif #pragma mark - Cache Info - (NSUInteger)getSize { __block NSUInteger size = 0; dispatch_sync(self.ioQueue, ^{ NSDirectoryEnumerator *fileEnumerator = [_fileManager enumeratorAtPath:self.diskCachePath]; for (NSString *fileName in fileEnumerator) { NSString *filePath = [self.diskCachePath stringByAppendingPathComponent:fileName]; NSDictionary<NSString *, id> *attrs = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil]; size += [attrs fileSize]; } }); return size; } - (NSUInteger)getDiskCount { __block NSUInteger count = 0; dispatch_sync(self.ioQueue, ^{ NSDirectoryEnumerator *fileEnumerator = [_fileManager enumeratorAtPath:self.diskCachePath]; count = fileEnumerator.allObjects.count; }); return count; } - (void)calculateSizeWithCompletionBlock:(nullable SDWebImageCalculateSizeBlock)completionBlock { NSURL *diskCacheURL = [NSURL fileURLWithPath:self.diskCachePath isDirectory:YES]; dispatch_async(self.ioQueue, ^{ NSUInteger fileCount = 0; NSUInteger totalSize = 0; NSDirectoryEnumerator *fileEnumerator = [_fileManager enumeratorAtURL:diskCacheURL includingPropertiesForKeys:@[NSFileSize] options:NSDirectoryEnumerationSkipsHiddenFiles errorHandler:NULL]; for (NSURL *fileURL in fileEnumerator) { NSNumber *fileSize; [fileURL getResourceValue:&fileSize forKey:NSURLFileSizeKey error:NULL]; totalSize += fileSize.unsignedIntegerValue; fileCount += 1; } if (completionBlock) { dispatch_async(dispatch_get_main_queue(), ^{ completionBlock(fileCount, totalSize); }); } }); } @end
2877025939/PlanADScrollView
22,363
PlanADScrollView/PlanADScrollView/SDWebImage/SDWebImage/SDWebImageDownloaderOperation.m
/* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import "SDWebImageDownloaderOperation.h" #import "SDWebImageDecoder.h" #import "UIImage+MultiFormat.h" #import <ImageIO/ImageIO.h> #import "SDWebImageManager.h" #import "NSImage+WebCache.h" NSString *const SDWebImageDownloadStartNotification = @"SDWebImageDownloadStartNotification"; NSString *const SDWebImageDownloadReceiveResponseNotification = @"SDWebImageDownloadReceiveResponseNotification"; NSString *const SDWebImageDownloadStopNotification = @"SDWebImageDownloadStopNotification"; NSString *const SDWebImageDownloadFinishNotification = @"SDWebImageDownloadFinishNotification"; static NSString *const kProgressCallbackKey = @"progress"; static NSString *const kCompletedCallbackKey = @"completed"; typedef NSMutableDictionary<NSString *, id> SDCallbacksDictionary; @interface SDWebImageDownloaderOperation () @property (strong, nonatomic, nonnull) NSMutableArray<SDCallbacksDictionary *> *callbackBlocks; @property (assign, nonatomic, getter = isExecuting) BOOL executing; @property (assign, nonatomic, getter = isFinished) BOOL finished; @property (strong, nonatomic, nullable) NSMutableData *imageData; // This is weak because it is injected by whoever manages this session. If this gets nil-ed out, we won't be able to run // the task associated with this operation @property (weak, nonatomic, nullable) NSURLSession *unownedSession; // This is set if we're using not using an injected NSURLSession. We're responsible of invalidating this one @property (strong, nonatomic, nullable) NSURLSession *ownedSession; @property (strong, nonatomic, readwrite, nullable) NSURLSessionTask *dataTask; @property (SDDispatchQueueSetterSementics, nonatomic, nullable) dispatch_queue_t barrierQueue; #if SD_UIKIT @property (assign, nonatomic) UIBackgroundTaskIdentifier backgroundTaskId; #endif @end @implementation SDWebImageDownloaderOperation { size_t width, height; #if SD_UIKIT || SD_WATCH UIImageOrientation orientation; #endif BOOL responseFromCached; } @synthesize executing = _executing; @synthesize finished = _finished; - (nonnull instancetype)init { return [self initWithRequest:nil inSession:nil options:0]; } - (nonnull instancetype)initWithRequest:(nullable NSURLRequest *)request inSession:(nullable NSURLSession *)session options:(SDWebImageDownloaderOptions)options { if ((self = [super init])) { _request = [request copy]; _shouldDecompressImages = YES; _options = options; _callbackBlocks = [NSMutableArray new]; _executing = NO; _finished = NO; _expectedSize = 0; _unownedSession = session; responseFromCached = YES; // Initially wrong until `- URLSession:dataTask:willCacheResponse:completionHandler: is called or not called _barrierQueue = dispatch_queue_create("com.hackemist.SDWebImageDownloaderOperationBarrierQueue", DISPATCH_QUEUE_CONCURRENT); } return self; } - (void)dealloc { SDDispatchQueueRelease(_barrierQueue); } - (nullable id)addHandlersForProgress:(nullable SDWebImageDownloaderProgressBlock)progressBlock completed:(nullable SDWebImageDownloaderCompletedBlock)completedBlock { SDCallbacksDictionary *callbacks = [NSMutableDictionary new]; if (progressBlock) callbacks[kProgressCallbackKey] = [progressBlock copy]; if (completedBlock) callbacks[kCompletedCallbackKey] = [completedBlock copy]; dispatch_barrier_async(self.barrierQueue, ^{ [self.callbackBlocks addObject:callbacks]; }); return callbacks; } - (nullable NSArray<id> *)callbacksForKey:(NSString *)key { __block NSMutableArray<id> *callbacks = nil; dispatch_sync(self.barrierQueue, ^{ // We need to remove [NSNull null] because there might not always be a progress block for each callback callbacks = [[self.callbackBlocks valueForKey:key] mutableCopy]; [callbacks removeObjectIdenticalTo:[NSNull null]]; }); return [callbacks copy]; // strip mutability here } - (BOOL)cancel:(nullable id)token { __block BOOL shouldCancel = NO; dispatch_barrier_sync(self.barrierQueue, ^{ [self.callbackBlocks removeObjectIdenticalTo:token]; if (self.callbackBlocks.count == 0) { shouldCancel = YES; } }); if (shouldCancel) { [self cancel]; } return shouldCancel; } - (void)start { @synchronized (self) { if (self.isCancelled) { self.finished = YES; [self reset]; return; } #if SD_UIKIT Class UIApplicationClass = NSClassFromString(@"UIApplication"); BOOL hasApplication = UIApplicationClass && [UIApplicationClass respondsToSelector:@selector(sharedApplication)]; if (hasApplication && [self shouldContinueWhenAppEntersBackground]) { __weak __typeof__ (self) wself = self; UIApplication * app = [UIApplicationClass performSelector:@selector(sharedApplication)]; self.backgroundTaskId = [app beginBackgroundTaskWithExpirationHandler:^{ __strong __typeof (wself) sself = wself; if (sself) { [sself cancel]; [app endBackgroundTask:sself.backgroundTaskId]; sself.backgroundTaskId = UIBackgroundTaskInvalid; } }]; } #endif NSURLSession *session = self.unownedSession; if (!self.unownedSession) { NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration]; sessionConfig.timeoutIntervalForRequest = 15; /** * Create the session for this task * We send nil as delegate queue so that the session creates a serial operation queue for performing all delegate * method calls and completion handler calls. */ self.ownedSession = [NSURLSession sessionWithConfiguration:sessionConfig delegate:self delegateQueue:nil]; session = self.ownedSession; } self.dataTask = [session dataTaskWithRequest:self.request]; self.executing = YES; } [self.dataTask resume]; if (self.dataTask) { for (SDWebImageDownloaderProgressBlock progressBlock in [self callbacksForKey:kProgressCallbackKey]) { progressBlock(0, NSURLResponseUnknownLength, self.request.URL); } dispatch_async(dispatch_get_main_queue(), ^{ [[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStartNotification object:self]; }); } else { [self callCompletionBlocksWithError:[NSError errorWithDomain:NSURLErrorDomain code:0 userInfo:@{NSLocalizedDescriptionKey : @"Connection can't be initialized"}]]; } #if SD_UIKIT Class UIApplicationClass = NSClassFromString(@"UIApplication"); if(!UIApplicationClass || ![UIApplicationClass respondsToSelector:@selector(sharedApplication)]) { return; } if (self.backgroundTaskId != UIBackgroundTaskInvalid) { UIApplication * app = [UIApplication performSelector:@selector(sharedApplication)]; [app endBackgroundTask:self.backgroundTaskId]; self.backgroundTaskId = UIBackgroundTaskInvalid; } #endif } - (void)cancel { @synchronized (self) { [self cancelInternal]; } } - (void)cancelInternal { if (self.isFinished) return; [super cancel]; if (self.dataTask) { [self.dataTask cancel]; dispatch_async(dispatch_get_main_queue(), ^{ [[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStopNotification object:self]; }); // As we cancelled the connection, its callback won't be called and thus won't // maintain the isFinished and isExecuting flags. if (self.isExecuting) self.executing = NO; if (!self.isFinished) self.finished = YES; } [self reset]; } - (void)done { self.finished = YES; self.executing = NO; [self reset]; } - (void)reset { dispatch_barrier_async(self.barrierQueue, ^{ [self.callbackBlocks removeAllObjects]; }); self.dataTask = nil; self.imageData = nil; if (self.ownedSession) { [self.ownedSession invalidateAndCancel]; self.ownedSession = nil; } } - (void)setFinished:(BOOL)finished { [self willChangeValueForKey:@"isFinished"]; _finished = finished; [self didChangeValueForKey:@"isFinished"]; } - (void)setExecuting:(BOOL)executing { [self willChangeValueForKey:@"isExecuting"]; _executing = executing; [self didChangeValueForKey:@"isExecuting"]; } - (BOOL)isConcurrent { return YES; } #pragma mark NSURLSessionDataDelegate - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler { //'304 Not Modified' is an exceptional one if (![response respondsToSelector:@selector(statusCode)] || (((NSHTTPURLResponse *)response).statusCode < 400 && ((NSHTTPURLResponse *)response).statusCode != 304)) { NSInteger expected = response.expectedContentLength > 0 ? (NSInteger)response.expectedContentLength : 0; self.expectedSize = expected; for (SDWebImageDownloaderProgressBlock progressBlock in [self callbacksForKey:kProgressCallbackKey]) { progressBlock(0, expected, self.request.URL); } self.imageData = [[NSMutableData alloc] initWithCapacity:expected]; self.response = response; dispatch_async(dispatch_get_main_queue(), ^{ [[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadReceiveResponseNotification object:self]; }); } else { NSUInteger code = ((NSHTTPURLResponse *)response).statusCode; //This is the case when server returns '304 Not Modified'. It means that remote image is not changed. //In case of 304 we need just cancel the operation and return cached image from the cache. if (code == 304) { [self cancelInternal]; } else { [self.dataTask cancel]; } dispatch_async(dispatch_get_main_queue(), ^{ [[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStopNotification object:self]; }); [self callCompletionBlocksWithError:[NSError errorWithDomain:NSURLErrorDomain code:((NSHTTPURLResponse *)response).statusCode userInfo:nil]]; [self done]; } if (completionHandler) { completionHandler(NSURLSessionResponseAllow); } } - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data { [self.imageData appendData:data]; if ((self.options & SDWebImageDownloaderProgressiveDownload) && self.expectedSize > 0) { // The following code is from http://www.cocoaintheshell.com/2011/05/progressive-images-download-imageio/ // Thanks to the author @Nyx0uf // Get the total bytes downloaded const NSInteger totalSize = self.imageData.length; // Update the data source, we must pass ALL the data, not just the new bytes CGImageSourceRef imageSource = CGImageSourceCreateWithData((__bridge CFDataRef)self.imageData, NULL); if (width + height == 0) { CFDictionaryRef properties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, NULL); if (properties) { NSInteger orientationValue = -1; CFTypeRef val = CFDictionaryGetValue(properties, kCGImagePropertyPixelHeight); if (val) CFNumberGetValue(val, kCFNumberLongType, &height); val = CFDictionaryGetValue(properties, kCGImagePropertyPixelWidth); if (val) CFNumberGetValue(val, kCFNumberLongType, &width); val = CFDictionaryGetValue(properties, kCGImagePropertyOrientation); if (val) CFNumberGetValue(val, kCFNumberNSIntegerType, &orientationValue); CFRelease(properties); // When we draw to Core Graphics, we lose orientation information, // which means the image below born of initWithCGIImage will be // oriented incorrectly sometimes. (Unlike the image born of initWithData // in didCompleteWithError.) So save it here and pass it on later. #if SD_UIKIT || SD_WATCH orientation = [[self class] orientationFromPropertyValue:(orientationValue == -1 ? 1 : orientationValue)]; #endif } } if (width + height > 0 && totalSize < self.expectedSize) { // Create the image CGImageRef partialImageRef = CGImageSourceCreateImageAtIndex(imageSource, 0, NULL); #if SD_UIKIT || SD_WATCH // Workaround for iOS anamorphic image if (partialImageRef) { const size_t partialHeight = CGImageGetHeight(partialImageRef); CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGContextRef bmContext = CGBitmapContextCreate(NULL, width, height, 8, width * 4, colorSpace, kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedFirst); CGColorSpaceRelease(colorSpace); if (bmContext) { CGContextDrawImage(bmContext, (CGRect){.origin.x = 0.0f, .origin.y = 0.0f, .size.width = width, .size.height = partialHeight}, partialImageRef); CGImageRelease(partialImageRef); partialImageRef = CGBitmapContextCreateImage(bmContext); CGContextRelease(bmContext); } else { CGImageRelease(partialImageRef); partialImageRef = nil; } } #endif if (partialImageRef) { #if SD_UIKIT || SD_WATCH UIImage *image = [UIImage imageWithCGImage:partialImageRef scale:1 orientation:orientation]; #elif SD_MAC UIImage *image = [[UIImage alloc] initWithCGImage:partialImageRef size:NSZeroSize]; #endif NSString *key = [[SDWebImageManager sharedManager] cacheKeyForURL:self.request.URL]; UIImage *scaledImage = [self scaledImageForKey:key image:image]; if (self.shouldDecompressImages) { image = [UIImage decodedImageWithImage:scaledImage]; } else { image = scaledImage; } CGImageRelease(partialImageRef); [self callCompletionBlocksWithImage:image imageData:nil error:nil finished:NO]; } } CFRelease(imageSource); } for (SDWebImageDownloaderProgressBlock progressBlock in [self callbacksForKey:kProgressCallbackKey]) { progressBlock(self.imageData.length, self.expectedSize, self.request.URL); } } - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask willCacheResponse:(NSCachedURLResponse *)proposedResponse completionHandler:(void (^)(NSCachedURLResponse *cachedResponse))completionHandler { responseFromCached = NO; // If this method is called, it means the response wasn't read from cache NSCachedURLResponse *cachedResponse = proposedResponse; if (self.request.cachePolicy == NSURLRequestReloadIgnoringLocalCacheData) { // Prevents caching of responses cachedResponse = nil; } if (completionHandler) { completionHandler(cachedResponse); } } #pragma mark NSURLSessionTaskDelegate - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error { @synchronized(self) { self.dataTask = nil; dispatch_async(dispatch_get_main_queue(), ^{ [[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStopNotification object:self]; if (!error) { [[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadFinishNotification object:self]; } }); } if (error) { [self callCompletionBlocksWithError:error]; } else { if ([self callbacksForKey:kCompletedCallbackKey].count > 0) { /** * See #1608 and #1623 - apparently, there is a race condition on `NSURLCache` that causes a crash * Limited the calls to `cachedResponseForRequest:` only for cases where we should ignore the cached response * and images for which responseFromCached is YES (only the ones that cannot be cached). * Note: responseFromCached is set to NO inside `willCacheResponse:`. This method doesn't get called for large images or images behind authentication */ if (self.options & SDWebImageDownloaderIgnoreCachedResponse && responseFromCached && [[NSURLCache sharedURLCache] cachedResponseForRequest:self.request]) { // hack [self callCompletionBlocksWithImage:nil imageData:nil error:nil finished:YES]; } else if (self.imageData) { UIImage *image = [UIImage sd_imageWithData:self.imageData]; NSString *key = [[SDWebImageManager sharedManager] cacheKeyForURL:self.request.URL]; image = [self scaledImageForKey:key image:image]; // Do not force decoding animated GIFs if (!image.images) { if (self.shouldDecompressImages) { if (self.options & SDWebImageDownloaderScaleDownLargeImages) { #if SD_UIKIT || SD_WATCH image = [UIImage decodedAndScaledDownImageWithImage:image]; [self.imageData setData:UIImagePNGRepresentation(image)]; #endif } else { image = [UIImage decodedImageWithImage:image]; } } } if (CGSizeEqualToSize(image.size, CGSizeZero)) { [self callCompletionBlocksWithError:[NSError errorWithDomain:SDWebImageErrorDomain code:0 userInfo:@{NSLocalizedDescriptionKey : @"Downloaded image has 0 pixels"}]]; } else { [self callCompletionBlocksWithImage:image imageData:self.imageData error:nil finished:YES]; } } else { [self callCompletionBlocksWithError:[NSError errorWithDomain:SDWebImageErrorDomain code:0 userInfo:@{NSLocalizedDescriptionKey : @"Image data is nil"}]]; } } } [self done]; } - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler { NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling; __block NSURLCredential *credential = nil; if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) { if (!(self.options & SDWebImageDownloaderAllowInvalidSSLCertificates)) { disposition = NSURLSessionAuthChallengePerformDefaultHandling; } else { credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]; disposition = NSURLSessionAuthChallengeUseCredential; } } else { if (challenge.previousFailureCount == 0) { if (self.credential) { credential = self.credential; disposition = NSURLSessionAuthChallengeUseCredential; } else { disposition = NSURLSessionAuthChallengeCancelAuthenticationChallenge; } } else { disposition = NSURLSessionAuthChallengeCancelAuthenticationChallenge; } } if (completionHandler) { completionHandler(disposition, credential); } } #pragma mark Helper methods #if SD_UIKIT || SD_WATCH + (UIImageOrientation)orientationFromPropertyValue:(NSInteger)value { switch (value) { case 1: return UIImageOrientationUp; case 3: return UIImageOrientationDown; case 8: return UIImageOrientationLeft; case 6: return UIImageOrientationRight; case 2: return UIImageOrientationUpMirrored; case 4: return UIImageOrientationDownMirrored; case 5: return UIImageOrientationLeftMirrored; case 7: return UIImageOrientationRightMirrored; default: return UIImageOrientationUp; } } #endif - (nullable UIImage *)scaledImageForKey:(nullable NSString *)key image:(nullable UIImage *)image { return SDScaledImageForKey(key, image); } - (BOOL)shouldContinueWhenAppEntersBackground { return self.options & SDWebImageDownloaderContinueInBackground; } - (void)callCompletionBlocksWithError:(nullable NSError *)error { [self callCompletionBlocksWithImage:nil imageData:nil error:error finished:YES]; } - (void)callCompletionBlocksWithImage:(nullable UIImage *)image imageData:(nullable NSData *)imageData error:(nullable NSError *)error finished:(BOOL)finished { NSArray<id> *completionBlocks = [self callbacksForKey:kCompletedCallbackKey]; dispatch_main_async_safe(^{ for (SDWebImageDownloaderCompletedBlock completedBlock in completionBlocks) { completedBlock(image, imageData, error, finished); } }); } @end
27182812/ChatGLM-LLaMA-chinese-insturct
45,067
src/transformers/models/speech_encoder_decoder/modeling_flax_speech_encoder_decoder.py
# coding=utf-8 # Copyright 2022 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. """ Classes to support Flax Speech-Encoder-Decoder architectures""" import os from typing import Optional, Tuple, Union import flax.linen as nn import jax import jax.numpy as jnp from flax.core.frozen_dict import FrozenDict, freeze, unfreeze from flax.traverse_util import flatten_dict, unflatten_dict from jax import lax from jax.random import PRNGKey from ...modeling_flax_outputs import FlaxBaseModelOutput, FlaxCausalLMOutputWithCrossAttentions, FlaxSeq2SeqLMOutput from ...modeling_flax_utils import FlaxPreTrainedModel from ...utils import add_start_docstrings, add_start_docstrings_to_model_forward, logging, replace_return_docstrings from ..auto.configuration_auto import AutoConfig from ..auto.modeling_flax_auto import FlaxAutoModel, FlaxAutoModelForCausalLM from .configuration_speech_encoder_decoder import SpeechEncoderDecoderConfig logger = logging.get_logger(__name__) _CONFIG_FOR_DOC = "SpeechEncoderDecoderConfig" SPEECH_ENCODER_DECODER_START_DOCSTRING = r""" This class can be used to initialize a speech-sequence-to-text-sequence model with any pretrained speech autoencoding model as the encoder and any pretrained text autoregressive model as the decoder. The encoder is loaded via [`~AutoModel.from_pretrained`] function and the decoder is loaded via [`~AutoModelForCausalLM.from_pretrained`] function. Cross-attention layers are automatically added to the decoder and should be fine-tuned on a downstream generative task, like summarization. The effectiveness of initializing sequence-to-sequence models with pretrained checkpoints for sequence generation tasks was shown in [Leveraging Pre-trained Checkpoints for Sequence Generation Tasks](https://arxiv.org/abs/1907.12461) by Sascha Rothe, Shashi Narayan, Aliaksei Severyn. Michael Matena, Yanqi Zhou, Wei Li, Peter J. Liu. Additionally, in [Large-Scale Self- and Semi-Supervised Learning for Speech Translation](https://arxiv.org/abs/2104.06678) it is shown how leveraging large pretrained speech models for speech translation yields a significant performance improvement. After such an Speech-Encoder Decoder model has been trained/fine-tuned, it can be saved/loaded just like any other models (see the examples for more information). This model inherits from [`FlaxPreTrainedModel`]. 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 Flax Linen [flax.nn.Module](https://flax.readthedocs.io/en/latest/_autosummary/flax.nn.module.html) subclass. Use it as a regular Flax Module and refer to the Flax documentation for all matter related to general usage and behavior. Parameters: config ([`SpeechEncoderDecoderConfig`]): 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 [`~FlaxPreTrainedModel.from_pretrained`] method to load the model weights. dtype (`jax.numpy.dtype`, *optional*, defaults to `jax.numpy.float32`): The data type of the computation. Can be one of `jax.numpy.float32`, `jax.numpy.float16` (on GPUs) and `jax.numpy.bfloat16` (on TPUs). This can be used to enable mixed-precision training or half-precision inference on GPUs or TPUs. If specified all the computation will be performed with the given `dtype`. **Note that this only specifies the dtype of the computation and does not influence the dtype of model parameters.** If you wish to change the dtype of the model parameters, see [`~FlaxPreTrainedModel.to_fp16`] and [`~FlaxPreTrainedModel.to_bf16`]. """ SPEECH_ENCODER_DECODER_INPUTS_DOCSTRING = r""" Args: inputs (`jnp.ndarray` of shape `(batch_size, sequence_length)` or `(batch_size, sequence_length, feature_dim)`, *optional*): Float values of input raw speech waveform or speech features. Values can be obtained by loading a `.flac` or `.wav` audio file into an array of type `List[float]` or a `numpy.ndarray`, *e.g.* via the soundfile library (`pip install soundfile`). To prepare the array into `inputs`, either the [`Wav2Vec2Processor`] or [`Speech2TextProcessor`] should be used for padding and conversion into a tensor of type `torch.FloatTensor`. attention_mask (`jnp.ndarray` of shape `(batch_size, sequence_length)`, *optional*): Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: - 1 for tokens that are **not masked**, - 0 for tokens that are **masked**. [What are attention masks?](../glossary#attention-mask) decoder_input_ids (`jnp.ndarray` of shape `(batch_size, target_sequence_length)`, *optional*): Indices of decoder input sequence tokens in the vocabulary. Indices can be obtained using [`PreTrainedTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input IDs?](../glossary#input-ids) If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see `past_key_values`). For sequence to sequence training, `decoder_input_ids` should be provided. `decoder_input_ids` should be created outside of the model by shifting the `labels` to the right, replacing -100 by the `pad_token_id` and prepending them with the `decoder_start_token_id`. decoder_attention_mask (`jnp.ndarray` of shape `(batch_size, target_sequence_length)`, *optional*): Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also be used by default. decoder_position_ids (`numpy.ndarray` of shape `(batch_size, sequence_length)`, *optional*): Indices of positions of each decoder input sequence tokens in the position embeddings. Selected in the range `[0, config.decoder.max_position_embeddings - 1]`. 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*): If set to `True`, the model will return a [`~utils.FlaxSeq2SeqLMOutput`] instead of a plain tuple. """ SPEECH_ENCODER_DECODER_ENCODE_INPUTS_DOCSTRING = r""" Args: inputs (`jnp.ndarray` of shape `(batch_size, sequence_length)` or `(batch_size, sequence_length, feature_dim)`, *optional*): Float values of input raw speech waveform or speech features. Values can be obtained by loading a *.flac* or *.wav* audio file into an array of type *List[float]* or a *numpy.ndarray*, *e.g.* via the soundfile library (*pip install soundfile*). To prepare the array into *inputs*, either the [`Wav2Vec2Processor`] or [`Speech2TextProcessor`] should be used for padding and conversion into a tensor of type *torch.FloatTensor*. attention_mask (`jnp.ndarray` of shape `(batch_size, sequence_length)`, *optional*): Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: - 1 for tokens that are **not masked**, - 0 for tokens that are **masked**. [What are attention masks?](../glossary#attention-mask) 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*): If set to `True`, the model will return a [`~utils.FlaxBaseModelOutput`] instead of a plain tuple. """ SPEECH_ENCODER_DECODER_DECODE_INPUTS_DOCSTRING = r""" Args: decoder_input_ids (`jnp.ndarray` of shape `(batch_size, target_sequence_length)`, *optional*): Indices of decoder input sequence tokens in the vocabulary. Indices can be obtained using [`PreTrainedTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are decoder input IDs?](../glossary#decoder-input-ids) If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see `past_key_values`). For sequence to sequence training, `decoder_input_ids` should be provided. `decoder_input_ids` should be created outside of the model by shifting the `labels` to the right, replacing -100 by the `pad_token_id` and prepending them with the `decoder_start_token_id`. encoder_outputs (`tuple(tuple(jnp.ndarray)`): Tuple consists of (`last_hidden_state`, *optional*: `hidden_states`, *optional*: `attentions`) `last_hidden_state` of shape `(batch_size, sequence_length, hidden_size)`, *optional*) is a sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention of the decoder. encoder_attention_mask (`jnp.ndarray` of shape `(batch_size, sequence_length)`, *optional*): Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: - 1 for tokens that are **not masked**, - 0 for tokens that are **masked**. [What are attention masks?](../glossary#attention-mask) decoder_attention_mask (`jnp.ndarray` of shape `(batch_size, target_sequence_length)`, *optional*): Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also be used by default. decoder_position_ids (`numpy.ndarray` of shape `(batch_size, sequence_length)`, *optional*): Indices of positions of each decoder input sequence tokens in the position embeddings. Selected in the range `[0, config.decoder.max_position_embeddings - 1]`. past_key_values (`Dict[str, np.ndarray]`, *optional*, returned by `init_cache` or when passing previous `past_key_values`): Dictionary of pre-computed hidden-states (key and values in the attention blocks) that can be used for fast auto-regressive decoding. Pre-computed key and value hidden-states are of shape *[batch_size, max_length]*. 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*): If set to `True`, the model will return a [`~utils.FlaxCausalLMOutputWithCrossAttentions`] instead of a plain tuple. """ class FlaxSpeechEncoderDecoderModule(nn.Module): config: SpeechEncoderDecoderConfig dtype: jnp.dtype = jnp.float32 def setup(self): encoder_config = self.config.encoder decoder_config = self.config.decoder # Copied from `modeling_hybrid_clip.py` with modifications. from ...models.auto.modeling_flax_auto import FLAX_MODEL_FOR_CAUSAL_LM_MAPPING, FLAX_MODEL_MAPPING encoder_module = FLAX_MODEL_MAPPING[encoder_config.__class__].module_class decoder_module = FLAX_MODEL_FOR_CAUSAL_LM_MAPPING[decoder_config.__class__].module_class self.encoder = encoder_module(encoder_config, dtype=self.dtype) self.decoder = decoder_module(decoder_config, dtype=self.dtype) # encoder outputs might need to be projected to different dimension for decoder if ( self.encoder.config.hidden_size != self.decoder.config.hidden_size and self.decoder.config.cross_attention_hidden_size is None ): self.enc_to_dec_proj = nn.Dense( self.decoder.config.hidden_size, kernel_init=jax.nn.initializers.normal(self.decoder.config.initializer_range), dtype=self.dtype, ) else: self.enc_to_dec_proj = None def _get_feat_extract_output_lengths( self, input_lengths: Union[jnp.ndarray, int], add_adapter: Optional[bool] = None ): """ Computes the output length of the convolutional layers """ add_adapter = self.config.encoder.add_adapter if add_adapter is None else add_adapter def _conv_out_length(input_length, kernel_size, stride): # 1D convolutional layer output length formula taken # from https://pytorch.org/docs/stable/generated/torch.nn.Conv1d.html return (input_length - kernel_size) // stride + 1 for kernel_size, stride in zip(self.config.encoder.conv_kernel, self.config.encoder.conv_stride): input_lengths = _conv_out_length(input_lengths, kernel_size, stride) if add_adapter: for _ in range(self.config.encoder.num_adapter_layers): input_lengths = _conv_out_length(input_lengths, 1, self.config.encoder.adapter_stride) return input_lengths def _get_encoder_module(self): return self.encoder def _get_projection_module(self): return self.enc_to_dec_proj def _get_decoder_module(self): return self.decoder def __call__( self, inputs, attention_mask, decoder_input_ids, decoder_attention_mask, decoder_position_ids, encoder_outputs=None, output_attentions: bool = False, output_hidden_states: bool = False, return_dict: bool = True, deterministic: bool = True, freeze_feature_encoder: bool = False, ): if encoder_outputs is None: encoder_outputs = self.encoder( inputs, attention_mask=attention_mask, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, deterministic=deterministic, freeze_feature_encoder=freeze_feature_encoder, ) encoder_hidden_states = encoder_outputs[0] # optionally project encoder_hidden_states if self.enc_to_dec_proj is not None: encoder_hidden_states = self.enc_to_dec_proj(encoder_hidden_states) # compute correct encoder attention mask if attention_mask is not None: encoder_attention_mask = self.encoder._get_feature_vector_attention_mask( encoder_hidden_states.shape[1], attention_mask ) else: encoder_attention_mask = None # flax script modeling_flax_wav2vec2.py decoder_outputs = self.decoder( input_ids=decoder_input_ids, attention_mask=decoder_attention_mask, position_ids=decoder_position_ids, encoder_hidden_states=encoder_hidden_states, encoder_attention_mask=encoder_attention_mask, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, deterministic=deterministic, ) if not return_dict: return decoder_outputs + encoder_outputs return FlaxSeq2SeqLMOutput( logits=decoder_outputs.logits, decoder_hidden_states=decoder_outputs.hidden_states, decoder_attentions=decoder_outputs.attentions, cross_attentions=decoder_outputs.cross_attentions, encoder_last_hidden_state=encoder_hidden_states, encoder_hidden_states=encoder_outputs.hidden_states, encoder_attentions=encoder_outputs.attentions, ) @add_start_docstrings(SPEECH_ENCODER_DECODER_START_DOCSTRING) class FlaxSpeechEncoderDecoderModel(FlaxPreTrainedModel): r""" [`FlaxSpeechEncoderDecoderModel`] is a generic model class that will be instantiated as a transformer architecture with the module (flax.nn.Module) of one of the base model classes of the library as encoder module and another one as decoder module when created with the :meth*~transformers.FlaxAutoModel.from_pretrained* class method for the encoder and :meth*~transformers.FlaxAutoModelForCausalLM.from_pretrained* class method for the decoder. """ config_class = SpeechEncoderDecoderConfig base_model_prefix: str = "speech_encoder_decoder" module_class = FlaxSpeechEncoderDecoderModule def __init__( self, config: SpeechEncoderDecoderConfig, input_shape: Optional[Tuple] = None, seed: int = 0, dtype: jnp.dtype = jnp.float32, _do_init: bool = True, **kwargs, ): if not _do_init: raise ValueError( "`FlaxSpeechEncoderDecoderModel` cannot be created without initializing, `_do_init` must be `True`." ) if config.decoder.cross_attention_hidden_size is not None: # Raise ValueError or option to project enc to dec hidden_size (eg EncAdapterLayer) if config.decoder.cross_attention_hidden_size != config.encoder.hidden_size: raise ValueError( "If `cross_attention_hidden_size` is specified in the decoder's configuration, it has to be equal" f" to the encoder's `hidden_size`. Got {config.decoder.cross_attention_hidden_size} for" f" `config.decoder.cross_attention_hidden_size` and {config.encoder.hidden_size} for" " `config.encoder.hidden_size`." ) # make sure input & output embeddings are not tied config.tie_word_embeddings = False module = self.module_class(config=config, dtype=dtype, **kwargs) if input_shape is None: # speech encoders almost always downsample the sequence length dimension encoder_input_length = 1024 decoder_input_length = module._get_feat_extract_output_lengths(encoder_input_length) input_shape = ((1, encoder_input_length), (1, decoder_input_length)) super().__init__(config, module, input_shape=input_shape, seed=seed, dtype=dtype, _do_init=_do_init) def init_weights(self, rng: jax.random.PRNGKey, input_shape: Tuple, params: FrozenDict = None) -> FrozenDict: encoder_input_shape, decoder_input_shape = input_shape # init input DeviceArrays inputs = jnp.zeros(encoder_input_shape, dtype="f4") attention_mask = jnp.ones_like(inputs, dtype="i4") decoder_input_ids = jnp.zeros(decoder_input_shape, dtype="i4") decoder_attention_mask = jnp.ones_like(decoder_input_ids) batch_size, sequence_length = inputs.shape decoder_batch_size, decoder_sequence_length = decoder_input_ids.shape if not decoder_batch_size == batch_size: raise ValueError( f"The inputs of encoder and decoder should have the same batch size, but got {batch_size} for encoder" f" and {decoder_batch_size} for decoder." ) decoder_position_ids = jnp.broadcast_to( jnp.arange(decoder_sequence_length)[None, :], (decoder_batch_size, decoder_sequence_length) ) params_rng, dropout_rng = jax.random.split(rng) rngs = {"params": params_rng, "dropout": dropout_rng} random_params = self.module.init( rngs, inputs, attention_mask, decoder_input_ids, decoder_attention_mask, decoder_position_ids, )["params"] if params is not None: random_params = flatten_dict(unfreeze(random_params)) params = flatten_dict(unfreeze(params)) for missing_key in self._missing_keys: params[missing_key] = random_params[missing_key] self._missing_keys = set() return freeze(unflatten_dict(params)) else: return random_params def init_cache(self, batch_size, max_length, encoder_outputs): r""" Args: batch_size (`int`): batch_size used for fast auto-regressive decoding. Defines the batch size of the initialized cache. max_length (`int`): maximum possible length for auto-regressive decoding. Defines the sequence length of the initialized cache. encoder_outputs (`Union[FlaxBaseModelOutput, tuple(tuple(jnp.ndarray)]`): `encoder_outputs` consists of (`last_hidden_state`, *optional*: `hidden_states`, *optional*: `attentions`). `last_hidden_state` of shape `(batch_size, sequence_length, hidden_size)`, *optional*) is a sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention of the decoder. """ # init input variables to retrieve cache decoder_input_ids = jnp.ones((batch_size, max_length), dtype="i4") decoder_attention_mask = jnp.ones_like(decoder_input_ids) decoder_position_ids = jnp.broadcast_to( jnp.arange(jnp.atleast_2d(decoder_input_ids).shape[-1]), decoder_input_ids.shape ) def _decoder_forward(module, decoder_input_ids, decoder_attention_mask, decoder_position_ids, **kwargs): decoder_module = module._get_decoder_module() return decoder_module( input_ids=decoder_input_ids, attention_mask=decoder_attention_mask, position_ids=decoder_position_ids, **kwargs, ) init_variables = self.module.init( jax.random.PRNGKey(0), decoder_input_ids=decoder_input_ids, decoder_attention_mask=decoder_attention_mask, decoder_position_ids=decoder_position_ids, encoder_hidden_states=encoder_outputs[0], init_cache=True, method=_decoder_forward, # we only need to call the decoder to init the cache ) return unfreeze(init_variables["cache"]) def _get_feat_extract_output_lengths( self, input_lengths: Union[jnp.ndarray, int], add_adapter: Optional[bool] = None ): return self.module._get_feat_extract_output_lengths(input_lengths, add_adapter=add_adapter) @add_start_docstrings(SPEECH_ENCODER_DECODER_ENCODE_INPUTS_DOCSTRING) @replace_return_docstrings(output_type=FlaxBaseModelOutput, config_class=_CONFIG_FOR_DOC) def encode( self, inputs: jnp.ndarray, attention_mask: Optional[jnp.ndarray] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, train: bool = False, freeze_feature_encoder: bool = False, params: dict = None, dropout_rng: PRNGKey = None, ): r""" Returns: Example: ```python >>> from transformers import FlaxSpeechEncoderDecoderModel >>> # initialize a wav2vec2-2-bart from pretrained wav2vec2 and bart models. Note that the cross-attention layers will be randomly initialized >>> model = FlaxSpeechEncoderDecoderModel.from_encoder_decoder_pretrained( ... "facebook/wav2vec2-large-lv60", "facebook/bart-large" ... ) >>> inputs = jnp.ones((2, 5000), dtype=jnp.float32) >>> encoder_outputs = model.encode(inputs) ```""" 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.return_dict if attention_mask is None: attention_mask = jnp.ones_like(inputs, dtype="i4") # Handle any PRNG if needed rngs = {} if dropout_rng is not None: rngs["dropout"] = dropout_rng def _encoder_forward(module, inputs, attention_mask, **kwargs): encode_module = module._get_encoder_module() return encode_module(inputs, attention_mask, **kwargs) outputs = self.module.apply( {"params": params or self.params}, inputs=jnp.array(inputs, dtype="f4"), attention_mask=jnp.array(attention_mask, dtype="i4"), output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, deterministic=not train, freeze_feature_encoder=freeze_feature_encoder, rngs=rngs, method=_encoder_forward, ) if return_dict: outputs = FlaxBaseModelOutput( last_hidden_state=outputs.last_hidden_state, hidden_states=outputs.hidden_states, attentions=outputs.attentions, ) return outputs @add_start_docstrings(SPEECH_ENCODER_DECODER_DECODE_INPUTS_DOCSTRING) @replace_return_docstrings(output_type=FlaxCausalLMOutputWithCrossAttentions, config_class=_CONFIG_FOR_DOC) def decode( self, decoder_input_ids, encoder_outputs, encoder_attention_mask: Optional[jnp.ndarray] = None, decoder_attention_mask: Optional[jnp.ndarray] = None, decoder_position_ids: Optional[jnp.ndarray] = None, past_key_values: dict = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, train: bool = False, params: dict = None, dropout_rng: PRNGKey = None, ): r""" Returns: Example: ```python >>> from transformers import FlaxSpeechEncoderDecoderModel >>> import jax.numpy as jnp >>> # initialize a wav2vec2-2-bart from pretrained wav2vec2 and bart models. Note that the cross-attention layers will be randomly initialized >>> model = FlaxSpeechEncoderDecoderModel.from_encoder_decoder_pretrained( ... "facebook/wav2vec2-large-lv60", "facebook/bart-large" ... ) >>> inputs = jnp.ones((2, 5000), dtype=jnp.float32) >>> encoder_outputs = model.encode(inputs) >>> decoder_start_token_id = model.config.decoder.bos_token_id >>> decoder_input_ids = jnp.ones((inputs.shape[0], 1), dtype="i4") * decoder_start_token_id >>> outputs = model.decode(decoder_input_ids, encoder_outputs) >>> logits = outputs.logits ```""" 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.return_dict encoder_hidden_states = encoder_outputs[0] if encoder_attention_mask is None: batch_size, sequence_length = encoder_hidden_states.shape[:2] encoder_attention_mask = jnp.ones((batch_size, sequence_length)) batch_size, sequence_length = decoder_input_ids.shape if decoder_attention_mask is None: decoder_attention_mask = jnp.ones((batch_size, sequence_length)) if decoder_position_ids is None: if past_key_values is not None: raise ValueError("Make sure to provide `decoder_position_ids` when passing `past_key_values`.") decoder_position_ids = jnp.broadcast_to( jnp.arange(sequence_length)[None, :], (batch_size, sequence_length) ) # Handle any PRNG if needed rngs = {} if dropout_rng is not None: rngs["dropout"] = dropout_rng params = {"params": params or self.params} # if past_key_values are passed then cache is already initialized a private flag init_cache has to be # passed down to ensure cache is used. It has to be made sure that cache is marked as mutable so that # it can be changed by FlaxBartAttention module if past_key_values: params["cache"] = past_key_values mutable = ["cache"] else: mutable = False def _decoder_forward( module, decoder_input_ids, decoder_attention_mask, decoder_position_ids, encoder_hidden_states, **kwargs ): projection_module = module._get_projection_module() decoder_module = module._get_decoder_module() # optionally project encoder_hidden_states if projection_module is not None: encoder_hidden_states = projection_module(encoder_hidden_states) return decoder_module( decoder_input_ids, decoder_attention_mask, decoder_position_ids, encoder_hidden_states=encoder_hidden_states, **kwargs, ) outputs = self.module.apply( params, decoder_input_ids=jnp.array(decoder_input_ids, dtype="i4"), decoder_attention_mask=jnp.array(decoder_attention_mask, dtype="i4"), decoder_position_ids=jnp.array(decoder_position_ids, dtype="i4"), encoder_hidden_states=encoder_hidden_states, encoder_attention_mask=jnp.array(encoder_attention_mask, dtype="i4"), output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, deterministic=not train, rngs=rngs, mutable=mutable, method=_decoder_forward, ) # add updated cache to model output if past_key_values is not None and return_dict: outputs, past = outputs outputs["past_key_values"] = unfreeze(past["cache"]) return outputs elif past_key_values is not None and not return_dict: outputs, past = outputs outputs = outputs[:1] + (unfreeze(past["cache"]),) + outputs[1:] return outputs @add_start_docstrings_to_model_forward(SPEECH_ENCODER_DECODER_INPUTS_DOCSTRING) @replace_return_docstrings(output_type=FlaxSeq2SeqLMOutput, config_class=_CONFIG_FOR_DOC) def __call__( self, inputs: jnp.ndarray, attention_mask: Optional[jnp.ndarray] = None, decoder_input_ids: Optional[jnp.ndarray] = None, decoder_attention_mask: Optional[jnp.ndarray] = None, decoder_position_ids: Optional[jnp.ndarray] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, train: bool = False, freeze_feature_encoder: bool = False, params: dict = None, dropout_rng: PRNGKey = None, ): r""" Returns: Examples: ```python >>> from transformers import FlaxSpeechEncoderDecoderModel, AutoTokenizer >>> # load a fine-tuned wav2vec2-2-bart model >>> model = FlaxSpeechEncoderDecoderModel.from_pretrained("patrickvonplaten/wav2vec2-2-bart-large") >>> # load output tokenizer >>> tokenizer_output = AutoTokenizer.from_pretrained("facebook/bart-large") >>> inputs = jnp.ones((2, 5000), dtype=jnp.float32) >>> # use bart's special bos, pad and eos tokens >>> model.config.decoder_start_token_id = model.decoder.config.bos_token_id >>> model.config.pad_token_id = model.decoder.config.pad_token_id >>> model.config.eos_token_id = model.decoder.config.eos_token_id >>> outputs = model.generate(inputs) # Assert something? More interesting input? dtype correct? ``` """ 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.return_dict # prepare encoder inputs if attention_mask is None: attention_mask = jnp.ones_like(inputs, dtype="i4") # prepare decoder inputs if decoder_input_ids is None: raise ValueError( "`decoder_input_ids` cannot be `None`. For sequence to sequence training, `decoder_position_ids` must" " be specified as an input argument." ) if decoder_attention_mask is None: decoder_attention_mask = jnp.ones_like(decoder_input_ids) if decoder_position_ids is None: batch_size, sequence_length = decoder_input_ids.shape decoder_position_ids = jnp.broadcast_to( jnp.arange(sequence_length)[None, :], (batch_size, sequence_length) ) # Handle any PRNG if needed rngs = {"dropout": dropout_rng} if dropout_rng is not None else {} return self.module.apply( {"params": params or self.params}, inputs=jnp.array(inputs, dtype="f4"), attention_mask=jnp.array(attention_mask, dtype="i4"), decoder_input_ids=jnp.array(decoder_input_ids, dtype="i4"), decoder_attention_mask=jnp.array(decoder_attention_mask, dtype="i4"), decoder_position_ids=jnp.array(decoder_position_ids, dtype="i4"), output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, deterministic=not train, freeze_feature_encoder=freeze_feature_encoder, rngs=rngs, ) def prepare_inputs_for_generation( self, decoder_input_ids, max_length, attention_mask: Optional[jnp.DeviceArray] = None, decoder_attention_mask: Optional[jnp.DeviceArray] = None, encoder_outputs=None, **kwargs, ): # initializing the cache batch_size, seq_length = decoder_input_ids.shape past_key_values = self.init_cache(batch_size, max_length, encoder_outputs) # Note that usually one would have to put 0's in the attention_mask for x > input.shape[-1] and x < cache_length. # But since the decoder uses a causal mask, those positions are masked anyways. # Thus we can create a single static attention_mask here, which is more efficient for compilation extended_attention_mask = jnp.ones((batch_size, max_length), dtype="i4") if decoder_attention_mask is not None: decoder_position_ids = decoder_attention_mask.cumsum(axis=-1) - 1 extended_attention_mask = lax.dynamic_update_slice(extended_attention_mask, decoder_attention_mask, (0, 0)) else: decoder_position_ids = jnp.broadcast_to( jnp.arange(seq_length, dtype="i4")[None, :], (batch_size, seq_length) ) return { "past_key_values": past_key_values, "encoder_outputs": encoder_outputs, "encoder_attention_mask": attention_mask, "decoder_attention_mask": extended_attention_mask, "decoder_position_ids": decoder_position_ids, } def update_inputs_for_generation(self, model_outputs, model_kwargs): model_kwargs["past_key_values"] = model_outputs.past_key_values model_kwargs["decoder_position_ids"] = model_kwargs["decoder_position_ids"][:, -1:] + 1 return model_kwargs @classmethod def from_encoder_decoder_pretrained( cls, encoder_pretrained_model_name_or_path: Optional[Union[str, os.PathLike]] = None, decoder_pretrained_model_name_or_path: Optional[Union[str, os.PathLike]] = None, *model_args, **kwargs, ) -> FlaxPreTrainedModel: r""" Instantiate an encoder and a decoder from one or two base classes of the library from pretrained model checkpoints. Params: encoder_pretrained_model_name_or_path (`Union[str, os.PathLike]`, *optional*): Information necessary to initiate the encoder. Can be either: - A string, the *model id* of a pretrained model hosted inside a model repo on huggingface.co. Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a user or organization name, like `dbmdz/bert-base-german-cased`. - A path to a *directory* containing model weights saved using [`~FlaxPreTrainedModel.save_pretrained`], e.g., `./my_model_directory/`. decoder_pretrained_model_name_or_path (`Union[str, os.PathLike]`, *optional*, defaults to `None`): Information necessary to initiate the decoder. Can be either: - A string, the *model id* of a pretrained model hosted inside a model repo on huggingface.co. Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a user or organization name, like `dbmdz/bert-base-german-cased`. - A path to a *directory* containing model weights saved using [`~FlaxPreTrainedModel.save_pretrained`], e.g., `./my_model_directory/`. model_args (remaining positional arguments, *optional*): All remaning positional arguments will be passed to the underlying model's `__init__` method. kwargs (remaining dictionary of keyword arguments, *optional*): Can be used to update the configuration object (after it being loaded) and initiate the model (e.g., `output_attentions=True`). - To update the encoder configuration, use the prefix *encoder_* for each configuration parameter. - To update the decoder configuration, use the prefix *decoder_* for each configuration parameter. - To update the parent model configuration, do not use a prefix for each configuration parameter. Behaves differently depending on whether a `config` is provided or automatically loaded. Example: ```python >>> from transformers import FlaxSpeechEncoderDecoderModel >>> # initialize a wav2vec2-2-bart from pretrained wav2vec2 and bart models. Note that the cross-attention layers will be randomly initialized >>> model = FlaxSpeechEncoderDecoderModel.from_encoder_decoder_pretrained( ... "facebook/wav2vec2-large-lv60", "facebook/bart-large" ... ) >>> # saving model after fine-tuning >>> model.save_pretrained("./wav2vec2-2-bart-large") >>> # load fine-tuned model >>> model = FlaxSpeechEncoderDecoderModel.from_pretrained("./wav2vec2-2-bart-large") ```""" kwargs_encoder = { argument[len("encoder_") :]: value for argument, value in kwargs.items() if argument.startswith("encoder_") } kwargs_decoder = { argument[len("decoder_") :]: value for argument, value in kwargs.items() if argument.startswith("decoder_") } # remove encoder, decoder kwargs from kwargs for key in kwargs_encoder.keys(): del kwargs["encoder_" + key] for key in kwargs_decoder.keys(): del kwargs["decoder_" + key] # Load and initialize the encoder and decoder # The distinction between encoder and decoder at the model level is made # by the value of the flag `is_decoder` that we need to set correctly. encoder = kwargs_encoder.pop("model", None) if encoder is None: if encoder_pretrained_model_name_or_path is None: raise ValueError( "If `encoder_model` is not defined as an argument, a `encoder_pretrained_model_name_or_path` has " "to be defined." ) if "config" not in kwargs_encoder: encoder_config, kwargs_encoder = AutoConfig.from_pretrained( encoder_pretrained_model_name_or_path, **kwargs_encoder, return_unused_kwargs=True ) if encoder_config.is_decoder is True or encoder_config.add_cross_attention is True: logger.info( f"Initializing {encoder_pretrained_model_name_or_path} as a encoder model " "from a decoder model. Cross-attention and casual mask are disabled." ) encoder_config.is_decoder = False encoder_config.add_cross_attention = False kwargs_encoder["config"] = encoder_config encoder = FlaxAutoModel.from_pretrained( encoder_pretrained_model_name_or_path, *model_args, **kwargs_encoder ) decoder = kwargs_decoder.pop("model", None) if decoder is None: if decoder_pretrained_model_name_or_path is None: raise ValueError( "If `decoder_model` is not defined as an argument, a `decoder_pretrained_model_name_or_path` has " "to be defined." ) if "config" not in kwargs_decoder: decoder_config, kwargs_decoder = AutoConfig.from_pretrained( decoder_pretrained_model_name_or_path, **kwargs_decoder, return_unused_kwargs=True ) if decoder_config.is_decoder is False or decoder_config.add_cross_attention is False: logger.info( f"Initializing {decoder_pretrained_model_name_or_path} as a decoder model. Cross attention" f" layers are added to {decoder_pretrained_model_name_or_path} and randomly initialized if" f" {decoder_pretrained_model_name_or_path}'s architecture allows for cross attention layers." ) decoder_config.is_decoder = True decoder_config.add_cross_attention = True kwargs_decoder["config"] = decoder_config if kwargs_decoder["config"].is_decoder is False or kwargs_decoder["config"].add_cross_attention is False: logger.warning( f"Decoder model {decoder_pretrained_model_name_or_path} is not initialized as a decoder. " f"In order to initialize {decoder_pretrained_model_name_or_path} as a decoder, " "make sure that the attributes `is_decoder` and `add_cross_attention` of `decoder_config` " "passed to `.from_encoder_decoder_pretrained(...)` are set to `True` or do not pass a " "`decoder_config` to `.from_encoder_decoder_pretrained(...)`" ) decoder = FlaxAutoModelForCausalLM.from_pretrained(decoder_pretrained_model_name_or_path, **kwargs_decoder) # instantiate config with corresponding kwargs dtype = kwargs.pop("dtype", jnp.float32) config = SpeechEncoderDecoderConfig.from_encoder_decoder_configs(encoder.config, decoder.config, **kwargs) # make sure input & output word embeddings are not tied config.tie_word_embeddings = False # init model model = cls(config, dtype=dtype) model.params["encoder"] = encoder.params model.params["decoder"] = decoder.params return model
2877025939/PlanADScrollView
2,133
PlanADScrollView/PlanADScrollView/SDWebImage/SDWebImage/UIView+WebCacheOperation.m
/* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import "UIView+WebCacheOperation.h" #if SD_UIKIT || SD_MAC #import "objc/runtime.h" static char loadOperationKey; typedef NSMutableDictionary<NSString *, id> SDOperationsDictionary; @implementation UIView (WebCacheOperation) - (SDOperationsDictionary *)operationDictionary { SDOperationsDictionary *operations = objc_getAssociatedObject(self, &loadOperationKey); if (operations) { return operations; } operations = [NSMutableDictionary dictionary]; objc_setAssociatedObject(self, &loadOperationKey, operations, OBJC_ASSOCIATION_RETAIN_NONATOMIC); return operations; } - (void)sd_setImageLoadOperation:(nullable id)operation forKey:(nullable NSString *)key { if (key) { [self sd_cancelImageLoadOperationWithKey:key]; if (operation) { SDOperationsDictionary *operationDictionary = [self operationDictionary]; operationDictionary[key] = operation; } } } - (void)sd_cancelImageLoadOperationWithKey:(nullable NSString *)key { // Cancel in progress downloader from queue SDOperationsDictionary *operationDictionary = [self operationDictionary]; id operations = operationDictionary[key]; if (operations) { if ([operations isKindOfClass:[NSArray class]]) { for (id <SDWebImageOperation> operation in operations) { if (operation) { [operation cancel]; } } } else if ([operations conformsToProtocol:@protocol(SDWebImageOperation)]){ [(id<SDWebImageOperation>) operations cancel]; } [operationDictionary removeObjectForKey:key]; } } - (void)sd_removeImageLoadOperationWithKey:(nullable NSString *)key { if (key) { SDOperationsDictionary *operationDictionary = [self operationDictionary]; [operationDictionary removeObjectForKey:key]; } } @end #endif
2881099/csredis
12,682
src/CSRedisCore/Internal/Commands/RedisStreamCommand.cs
using CSRedis.Internal.IO; using System.Globalization; namespace CSRedis.Internal.Commands { class RedisXRangeCommand : RedisCommand<(string id, string[] items)[]> { public RedisXRangeCommand(string command, params object[] args) : base(command, args) { } public override (string id, string[] items)[] Parse(RedisReader reader) { (string id, string[] items)[] ret = null; reader.ExpectType(RedisMessage.MultiBulk); long count = reader.ReadInt(false); if (count == -1) return ret; ret = new (string id, string[] items)[count]; for (var a = 0; a < count; a++) { reader.ExpectType(RedisMessage.MultiBulk); var lvl2Count = reader.ReadInt(false); if (lvl2Count != 2) throw new RedisProtocolException("XRange/XRevRange/XClaim 返回数据格式 2级 MultiBulk 长度应该为 2"); var id = reader.ReadBulkString(); reader.ExpectType(RedisMessage.MultiBulk); var lvl3Count = reader.ReadInt(false); var items = new string[lvl3Count]; for (var e = 0; e < lvl3Count; e++) { items[e] = reader.ReadBulkString(); } ret[a] = (id, items); } return ret; } } class RedisXReadCommand : RedisCommand<(string key, (string id, string[] items)[] data)[]> { public RedisXReadCommand(string command, params object[] args) : base(command, args) { } public override (string key, (string id, string[] items)[] data)[] Parse(RedisReader reader) { (string key, (string id, string[] items)[])[] ret = null; reader.ExpectType(RedisMessage.MultiBulk); var count = reader.ReadInt(false); if (count == -1) return ret; ret = new (string key, (string id, string[] items)[] data)[count]; for (var a = 0; a < count; a++) { reader.ExpectType(RedisMessage.MultiBulk); var lvl2Count = reader.ReadInt(false); if (lvl2Count != 2) throw new RedisProtocolException("XRead 返回数据格式 2级 MultiBulk 长度应该为 2"); var key = reader.ReadBulkString(); reader.ExpectType(RedisMessage.MultiBulk); var lvl3Count = reader.ReadInt(false); var data = new (string id, string[] items)[lvl3Count]; for (var c = 0; c < lvl3Count; c++) { reader.ExpectType(RedisMessage.MultiBulk); var lvl4Count = reader.ReadInt(false); if (lvl4Count != 2) throw new RedisProtocolException("XRead 返回数据格式 4级 MultiBulk 长度应该为 2"); var id = reader.ReadBulkString(); reader.ExpectType(RedisMessage.MultiBulk); var lvl5Count = reader.ReadInt(false); var items = new string[lvl5Count]; for (var e = 0; e < lvl5Count; e++) { items[e] = reader.ReadBulkString(); } data[c] = (id, items); } ret[a] = (key, data); } return ret; } } class RedisXPendingCommand : RedisCommand<(long count, string minId, string maxId, (string consumer, long count)[] pendings)> { public RedisXPendingCommand(string command, params object[] args) : base(command, args) { } public override (long count, string minId, string maxId, (string consumer, long count)[] pendings) Parse(RedisReader reader) { reader.ExpectType(RedisMessage.MultiBulk); long count = reader.ReadInt(false); if (count != 4) throw new RedisProtocolException("XPedding 返回数据格式 1级 MultiBulk 长度应该为 4"); var retCount = reader.ReadInt(); var minId = reader.ReadBulkString(); var maxId = reader.ReadBulkString(); reader.ExpectType(RedisMessage.MultiBulk); var lvl2Count = reader.ReadInt(false); if (lvl2Count < 0) lvl2Count = 0; var pendings = new (string consumer, long count)[lvl2Count]; for (var a = 0; a < lvl2Count; a++) { reader.ExpectType(RedisMessage.MultiBulk); var lvl3Count = reader.ReadInt(false); if (lvl3Count != 2) throw new RedisProtocolException("XPedding 返回数据格式 3级 MultiBulk 长度应该为 2"); pendings[a] = (reader.ReadBulkString(), long.Parse(reader.ReadBulkString(), NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat)); } return (retCount, minId, maxId, pendings); } } class RedisXPendingStartEndCountCommand : RedisCommand<(string id, string consumer, long idle, long transferTimes)[]> { public RedisXPendingStartEndCountCommand(string command, params object[] args) : base(command, args) { } public override (string id, string consumer, long idle, long transferTimes)[] Parse(RedisReader reader) { reader.ExpectType(RedisMessage.MultiBulk); long count = reader.ReadInt(false); var ret = new (string id, string consumer, long idle, long transferTimes)[count]; for (var a = 0; a < count; a++) { var id = reader.ReadBulkString(); var consumer = reader.ReadBulkString(); var idle = reader.ReadInt(); var transferTimes = reader.ReadInt(); ret[a] = (id, consumer, idle, transferTimes); } return ret; } } class RedisXInfoStreamCommand : RedisCommand<(long length, long radixTreeKeys, long radixTreeNodes, long groups, string lastGeneratedId, (string id, string[] items) firstEntry, (string id, string[] items) lastEntry)> { public RedisXInfoStreamCommand(string command, params object[] args) : base(command, args) { } public override (long length, long radixTreeKeys, long radixTreeNodes, long groups, string lastGeneratedId, (string id, string[] items) firstEntry, (string id, string[] items) lastEntry) Parse(RedisReader reader) { reader.ExpectType(RedisMessage.MultiBulk); long count = reader.ReadInt(false); if (count % 2 != 0) throw new RedisProtocolException("XInfo Stream 返回数据格式 1级 MultiBulk 长度应该为偶数"); (long length, long radixTreeKeys, long radixTreeNodes, long groups, string lastGeneratedId, (string id, string[] items) firstEntry, (string id, string[] items) lastEntry) ret = default((long length, long radixTreeKeys, long radixTreeNodes, long groups, string lastGeneratedId, (string id, string[] items) firstEntry, (string id, string[] items) lastEntry)); for (var a = 0; a < count; a += 2) { var key = reader.ReadBulkString().ToLower(); switch (key) { case "length": ret.length = reader.ReadInt(); break; case "radix-tree-keys": ret.radixTreeKeys = reader.ReadInt(); break; case "radix-tree-nodes": ret.radixTreeNodes = reader.ReadInt(); break; case "groups": ret.groups = reader.ReadInt(); break; case "last-generated-id": ret.lastGeneratedId = reader.ReadBulkString(); break; case "first-entry": case "last-entry": reader.ExpectType(RedisMessage.MultiBulk); var lvl2Count = reader.ReadInt(false); if (lvl2Count != 2) throw new RedisProtocolException("XInfo Stream 返回数据格式 2级 MultiBulk 长度应该为 2"); var id = reader.ReadBulkString(); reader.ExpectType(RedisMessage.MultiBulk); var lvl3Count = reader.ReadInt(false); var items = new string[lvl3Count]; for (var e = 0; e < lvl3Count; e++) items[e] = reader.ReadBulkString(); if (key == "first-entry") ret.firstEntry = (id, items); else ret.lastEntry = (id, items); break; default: reader.ReadBulkString(); break; } } return ret; } } class RedisXInfoGroupsCommand : RedisCommand<(string name, long consumers, long pending, string lastDeliveredId)[]> { public RedisXInfoGroupsCommand(string command, params object[] args) : base(command, args) { } public override (string name, long consumers, long pending, string lastDeliveredId)[] Parse(RedisReader reader) { reader.ExpectType(RedisMessage.MultiBulk); long count = reader.ReadInt(false); var ret = new (string name, long consumers, long pending, string lastDeliveredId)[count]; for (var a = 0; a < count; a++) { reader.ExpectType(RedisMessage.MultiBulk); long lvl2Count = reader.ReadInt(false); if (lvl2Count % 2 != 0) throw new RedisProtocolException("XInfo Groups 返回数据格式 2级 MultiBulk 长度应该为偶数"); for (var b = 0; b < lvl2Count; b+= 2) { var key = reader.ReadBulkString().ToLower(); switch (key) { case "name": ret[a].name = reader.ReadBulkString(); break; case "consumers": ret[a].consumers = reader.ReadInt(); break; case "pending": ret[a].pending = reader.ReadInt(); break; case "last-delivered-id": ret[a].lastDeliveredId = reader.ReadBulkString(); break; case "entries-read": reader.ReadInt(); break; case "lag": reader.ReadInt(); break; default: reader.ReadBulkString(); break; } } } return ret; } } class RedisXInfoConsumersCommand : RedisCommand<(string name, long pending, long idle)[]> { public RedisXInfoConsumersCommand(string command, params object[] args) : base(command, args) { } public override (string name, long pending, long idle)[] Parse(RedisReader reader) { reader.ExpectType(RedisMessage.MultiBulk); long count = reader.ReadInt(false); var ret = new (string name, long pending, long idle)[count]; for (var a = 0; a < count; a++) { reader.ExpectType(RedisMessage.MultiBulk); long lvl2Count = reader.ReadInt(false); if (lvl2Count % 2 != 0) throw new RedisProtocolException("XInfo Consumers 返回数据格式 2级 MultiBulk 长度应该为偶数"); for (var b = 0; b < lvl2Count; b += 2) { var key = reader.ReadBulkString().ToLower(); switch (key) { case "name": ret[a].name = reader.ReadBulkString(); break; case "pending": ret[a].pending = reader.ReadInt(); break; case "idle": ret[a].idle = reader.ReadInt(); break; default: reader.ReadBulkString(); break; } } } return ret; } } }
27182812/ChatGLM-LLaMA-chinese-insturct
5,087
src/transformers/models/speech_encoder_decoder/configuration_speech_encoder_decoder.py
# coding=utf-8 # Copyright 2021 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. import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto.configuration_auto import AutoConfig logger = logging.get_logger(__name__) class SpeechEncoderDecoderConfig(PretrainedConfig): r""" [`SpeechEncoderDecoderConfig`] is the configuration class to store the configuration of a [`SpeechEncoderDecoderModel`]. It is used to instantiate an Encoder Decoder model according to the specified arguments, defining the encoder and decoder configs. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the documentation from [`PretrainedConfig`] for more information. Args: kwargs (*optional*): Dictionary of keyword arguments. Notably: - **encoder** ([`PretrainedConfig`], *optional*) -- An instance of a configuration object that defines the encoder config. - **decoder** ([`PretrainedConfig`], *optional*) -- An instance of a configuration object that defines the decoder config. Examples: ```python >>> from transformers import BertConfig, Wav2Vec2Config, SpeechEncoderDecoderConfig, SpeechEncoderDecoderModel >>> # Initializing a Wav2Vec2 & BERT style configuration >>> config_encoder = Wav2Vec2Config() >>> config_decoder = BertConfig() >>> config = SpeechEncoderDecoderConfig.from_encoder_decoder_configs(config_encoder, config_decoder) >>> # Initializing a Wav2Vec2Bert model from a Wav2Vec2 & bert-base-uncased style configurations >>> model = SpeechEncoderDecoderModel(config=config) >>> # Accessing the model configuration >>> config_encoder = model.config.encoder >>> config_decoder = model.config.decoder >>> # set decoder config to causal lm >>> config_decoder.is_decoder = True >>> config_decoder.add_cross_attention = True >>> # Saving the model, including its configuration >>> model.save_pretrained("my-model") >>> # loading model and config from pretrained folder >>> encoder_decoder_config = SpeechEncoderDecoderConfig.from_pretrained("my-model") >>> model = SpeechEncoderDecoderModel.from_pretrained("my-model", config=encoder_decoder_config) ```""" model_type = "speech-encoder-decoder" is_composition = True def __init__(self, **kwargs): super().__init__(**kwargs) if "encoder" not in kwargs or "decoder" not in kwargs: raise ValueError( f"A configuraton of type {self.model_type} cannot be instantiated because not both `encoder` and" f" `decoder` sub-configurations are passed, but only {kwargs}" ) encoder_config = kwargs.pop("encoder") encoder_model_type = encoder_config.pop("model_type") decoder_config = kwargs.pop("decoder") decoder_model_type = decoder_config.pop("model_type") self.encoder = AutoConfig.for_model(encoder_model_type, **encoder_config) self.decoder = AutoConfig.for_model(decoder_model_type, **decoder_config) self.is_encoder_decoder = True @classmethod def from_encoder_decoder_configs( cls, encoder_config: PretrainedConfig, decoder_config: PretrainedConfig, **kwargs ) -> PretrainedConfig: r""" Instantiate a [`SpeechEncoderDecoderConfig`] (or a derived class) from a pre-trained encoder model configuration and decoder model configuration. Returns: [`SpeechEncoderDecoderConfig`]: An instance of a configuration object """ logger.info("Setting `config.is_decoder=True` and `config.add_cross_attention=True` for decoder_config") decoder_config.is_decoder = True decoder_config.add_cross_attention = True return cls(encoder=encoder_config.to_dict(), decoder=decoder_config.to_dict(), **kwargs) def to_dict(self): """ Serializes this instance to a Python dictionary. Override the default *to_dict()* from *PretrainedConfig*. Returns: `Dict[str, any]`: Dictionary of all the attributes that make up this configuration instance, """ output = copy.deepcopy(self.__dict__) output["encoder"] = self.encoder.to_dict() output["decoder"] = self.decoder.to_dict() output["model_type"] = self.__class__.model_type return output
2881099/csredis
2,085
src/CSRedisCore/Internal/Commands/RedisSubscription.cs
using CSRedis.Internal.IO; using System.IO; namespace CSRedis.Internal.Commands { class RedisSubscription : RedisCommand<RedisSubscriptionResponse> { public RedisSubscription(string command, params object[] args) : base(command, args) { } public override RedisSubscriptionResponse Parse(RedisReader reader) { reader.ExpectType(RedisMessage.MultiBulk); long count = reader.ReadInt(false); string type = reader.ReadBulkString(); switch (type) { case "subscribe": case "unsubscribe": case "psubscribe": case "punsubscribe": return ParseChannel(type, reader); case "message": case "pmessage": return ParseMessage(type, reader); } throw new RedisProtocolException("Unexpected type " + type); } static RedisSubscriptionChannel ParseChannel(string type, RedisReader reader) { switch (type) { case "subscribe": case "unsubscribe": return new RedisSubscriptionChannel(type, reader.ReadBulkString(), null, reader.ReadInt()); case "psubscribe": case "punsubscribe": return new RedisSubscriptionChannel(type, null, reader.ReadBulkString(), reader.ReadInt()); } throw new RedisProtocolException("Unexpected type " + type); } static RedisSubscriptionMessage ParseMessage(string type, RedisReader reader) { if (type == "message") return new RedisSubscriptionMessage(type, reader.ReadBulkString(), reader.ReadBulkString()); else if (type == "pmessage") return new RedisSubscriptionMessage(type, reader.ReadBulkString(), reader.ReadBulkString(), reader.ReadBulkString()); throw new RedisProtocolException("Unexpected type " + type); } } }
2877025939/PlanADScrollView
4,972
PlanADScrollView/PlanADScrollView/SDWebImage/SDWebImage/UIImage+MultiFormat.m
/* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import "UIImage+MultiFormat.h" #import "UIImage+GIF.h" #import "NSData+ImageContentType.h" #import <ImageIO/ImageIO.h> #ifdef SD_WEBP #import "UIImage+WebP.h" #endif @implementation UIImage (MultiFormat) + (nullable UIImage *)sd_imageWithData:(nullable NSData *)data { if (!data) { return nil; } UIImage *image; SDImageFormat imageFormat = [NSData sd_imageFormatForImageData:data]; if (imageFormat == SDImageFormatGIF) { image = [UIImage sd_animatedGIFWithData:data]; } #ifdef SD_WEBP else if (imageFormat == SDImageFormatWebP) { image = [UIImage sd_imageWithWebPData:data]; } #endif else { image = [[UIImage alloc] initWithData:data]; #if SD_UIKIT || SD_WATCH UIImageOrientation orientation = [self sd_imageOrientationFromImageData:data]; if (orientation != UIImageOrientationUp) { image = [UIImage imageWithCGImage:image.CGImage scale:image.scale orientation:orientation]; } #endif } return image; } #if SD_UIKIT || SD_WATCH +(UIImageOrientation)sd_imageOrientationFromImageData:(nonnull NSData *)imageData { UIImageOrientation result = UIImageOrientationUp; CGImageSourceRef imageSource = CGImageSourceCreateWithData((__bridge CFDataRef)imageData, NULL); if (imageSource) { CFDictionaryRef properties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, NULL); if (properties) { CFTypeRef val; int exifOrientation; val = CFDictionaryGetValue(properties, kCGImagePropertyOrientation); if (val) { CFNumberGetValue(val, kCFNumberIntType, &exifOrientation); result = [self sd_exifOrientationToiOSOrientation:exifOrientation]; } // else - if it's not set it remains at up CFRelease((CFTypeRef) properties); } else { //NSLog(@"NO PROPERTIES, FAIL"); } CFRelease(imageSource); } return result; } #pragma mark EXIF orientation tag converter // Convert an EXIF image orientation to an iOS one. // reference see here: http://sylvana.net/jpegcrop/exif_orientation.html + (UIImageOrientation) sd_exifOrientationToiOSOrientation:(int)exifOrientation { UIImageOrientation orientation = UIImageOrientationUp; switch (exifOrientation) { case 1: orientation = UIImageOrientationUp; break; case 3: orientation = UIImageOrientationDown; break; case 8: orientation = UIImageOrientationLeft; break; case 6: orientation = UIImageOrientationRight; break; case 2: orientation = UIImageOrientationUpMirrored; break; case 4: orientation = UIImageOrientationDownMirrored; break; case 5: orientation = UIImageOrientationLeftMirrored; break; case 7: orientation = UIImageOrientationRightMirrored; break; default: break; } return orientation; } #endif - (nullable NSData *)sd_imageData { return [self sd_imageDataAsFormat:SDImageFormatUndefined]; } - (nullable NSData *)sd_imageDataAsFormat:(SDImageFormat)imageFormat { NSData *imageData = nil; if (self) { #if SD_UIKIT || SD_WATCH int alphaInfo = CGImageGetAlphaInfo(self.CGImage); BOOL hasAlpha = !(alphaInfo == kCGImageAlphaNone || alphaInfo == kCGImageAlphaNoneSkipFirst || alphaInfo == kCGImageAlphaNoneSkipLast); BOOL usePNG = hasAlpha; // the imageFormat param has priority here. But if the format is undefined, we relly on the alpha channel if (imageFormat != SDImageFormatUndefined) { usePNG = (imageFormat == SDImageFormatPNG); } if (usePNG) { imageData = UIImagePNGRepresentation(self); } else { imageData = UIImageJPEGRepresentation(self, (CGFloat)1.0); } #else NSBitmapImageFileType imageFileType = NSJPEGFileType; if (imageFormat == SDImageFormatGIF) { imageFileType = NSGIFFileType; } else if (imageFormat == SDImageFormatPNG) { imageFileType = NSPNGFileType; } imageData = [NSBitmapImageRep representationOfImageRepsInArray:self.representations usingType:imageFileType properties:@{}]; #endif } return imageData; } @end
2881099/csredis
2,775
src/CSRedisCore/Internal/Commands/RedisRoleCommand.cs
 using CSRedis.Internal.IO; using System; using System.Globalization; namespace CSRedis.Internal.Commands { class RedisRoleCommand : RedisCommand<RedisRole> { public RedisRoleCommand(string command, params object[] args) : base(command, args) { } public override RedisRole Parse(RedisReader reader) { reader.ExpectType(RedisMessage.MultiBulk); int count = (int)reader.ReadInt(false); string role = reader.ReadBulkString(); switch (role) { case "master": return ParseMaster(count, role, reader); case "slave": return ParseSlave(count, role, reader); case "sentinel": return ParseSentinel(count, role, reader); default: throw new RedisProtocolException("Unexpected role: " + role); } } static RedisMasterRole ParseMaster(int num, string role, RedisReader reader) { reader.ExpectSize(3, num); long offset = reader.ReadInt(); reader.ExpectType(RedisMessage.MultiBulk); var slaves = new Tuple<string, int, long>[reader.ReadInt(false)]; for (int i = 0; i < slaves.Length; i++) { reader.ExpectType(RedisMessage.MultiBulk); reader.ExpectSize(3); string ip = reader.ReadBulkString(); int port = Int32.Parse(reader.ReadBulkString(), NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat); long.TryParse(reader.ReadBulkString(), NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out var slave_offset); slaves[i] = new Tuple<string, int, long>(ip, port, slave_offset); } return new RedisMasterRole(role, offset, slaves); } static RedisSlaveRole ParseSlave(int num, string role, RedisReader reader) { reader.ExpectSize(5, num); string master_ip = reader.ReadBulkString(); int port = (int)reader.ReadInt(); string state = reader.ReadBulkString(); long data = reader.ReadInt(); return new RedisSlaveRole(role, master_ip, port, state, data); } static RedisSentinelRole ParseSentinel(int num, string role, RedisReader reader) { reader.ExpectSize(2, num); reader.ExpectType(RedisMessage.MultiBulk); string[] masters = new string[reader.ReadInt(false)]; for (int i = 0; i < masters.Length; i++) masters[i] = reader.ReadBulkString(); return new RedisSentinelRole(role, masters); } } }
27182812/ChatGLM-LLaMA-chinese-insturct
14,760
src/transformers/models/speech_encoder_decoder/convert_mbart_wav2vec2_seq2seq_original_to_pytorch.py
# coding=utf-8 # Copyright 2021 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 Wav2Vec2 checkpoint.""" import argparse import fairseq import torch from torch import nn from transformers import ( MBart50Tokenizer, MBartConfig, MBartForCausalLM, SpeechEncoderDecoderConfig, SpeechEncoderDecoderModel, Wav2Vec2Config, Wav2Vec2FeatureExtractor, Wav2Vec2Model, logging, ) logging.set_verbosity_info() logger = logging.get_logger(__name__) MAPPING = { "post_extract_proj": "feature_projection.projection", "encoder.pos_conv.0": "encoder.pos_conv_embed.conv", "self_attn.k_proj": "encoder.layers.*.attention.k_proj", "self_attn.v_proj": "encoder.layers.*.attention.v_proj", "self_attn.q_proj": "encoder.layers.*.attention.q_proj", "self_attn.out_proj": "encoder.layers.*.attention.out_proj", "self_attn_layer_norm": "encoder.layers.*.layer_norm", "fc1": "encoder.layers.*.feed_forward.intermediate_dense", "fc2": "encoder.layers.*.feed_forward.output_dense", "final_layer_norm": "encoder.layers.*.final_layer_norm", "encoder.layer_norm": "encoder.layer_norm", "w2v_model.layer_norm": "feature_projection.layer_norm", "quantizer.weight_proj": "quantizer.weight_proj", "quantizer.vars": "quantizer.codevectors", "project_q": "project_q", "final_proj": "project_hid", "w2v_encoder.proj": "lm_head", "mask_emb": "masked_spec_embed", } TOP_LEVEL_KEYS = [ "lm_head", "quantizer.weight_proj", "quantizer.codevectors", "project_q", "project_hid", ] def set_recursively(hf_pointer, key, value, full_name, weight_type): for attribute in key.split("."): hf_pointer = getattr(hf_pointer, attribute) if weight_type is not None: hf_shape = getattr(hf_pointer, weight_type).shape else: hf_shape = hf_pointer.shape assert hf_shape == value.shape, ( f"Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be" f" {value.shape} for {full_name}" ) if weight_type == "weight": hf_pointer.weight.data = value elif weight_type == "weight_g": hf_pointer.weight_g.data = value elif weight_type == "weight_v": hf_pointer.weight_v.data = value elif weight_type == "bias": hf_pointer.bias.data = value else: hf_pointer.data = value logger.info(f"{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}.") def recursively_load_weights_wav2vec2(fairseq_model, hf_model): unused_weights = [] fairseq_dict = fairseq_model.state_dict() feature_extractor = hf_model.feature_extractor adapter = hf_model.adapter for name, value in fairseq_dict.items(): is_used = False if "conv_layers" in name: load_conv_layer( name, value, feature_extractor, unused_weights, hf_model.config.feat_extract_norm == "group", ) is_used = True elif any(x in name for x in ["adaptor", "w2v_encoder.proj.", "w2v_proj_ln."]): load_adapter(name, value, adapter, unused_weights) is_used = True else: for key, mapped_key in MAPPING.items(): if key in name or key.split("w2v_model.")[-1] == name.split(".")[0]: is_used = True if "*" in mapped_key: layer_index = name.split(key)[0].split(".")[-2] mapped_key = mapped_key.replace("*", layer_index) if "weight_g" in name: weight_type = "weight_g" elif "weight_v" in name: weight_type = "weight_v" elif "bias" in name: weight_type = "bias" elif "weight" in name: weight_type = "weight" else: weight_type = None set_recursively(hf_model, mapped_key, value, name, weight_type) continue if not is_used: unused_weights.append(name) logger.warning(f"Unused weights: {unused_weights}") def load_conv_layer(full_name, value, feature_extractor, unused_weights, use_group_norm): name = full_name.split("conv_layers.")[-1] items = name.split(".") layer_id = int(items[0]) type_id = int(items[1]) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( f"{full_name} has size {value.shape}, but" f" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found." ) feature_extractor.conv_layers[layer_id].conv.bias.data = value logger.info(f"Feat extract conv layer {layer_id} was initialized from {full_name}.") elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( f"{full_name} has size {value.shape}, but" f" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found." ) feature_extractor.conv_layers[layer_id].conv.weight.data = value logger.info(f"Feat extract conv layer {layer_id} was initialized from {full_name}.") elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( f"{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was" " found." ) feature_extractor.conv_layers[layer_id].layer_norm.bias.data = value logger.info(f"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.") elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( f"{full_name} has size {value.shape}, but" f" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found." ) feature_extractor.conv_layers[layer_id].layer_norm.weight.data = value logger.info(f"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.") else: unused_weights.append(full_name) def load_adapter(full_name, value, adapter, unused_weights): name = full_name.split("adaptor.")[-1] items = name.split(".") if items[1].isdigit(): layer_id = int(items[1]) else: layer_id = None if "adaptor" not in full_name: if "proj_ln" in full_name: # has to be layer norm if "bias" in name: assert ( value.shape == adapter.proj_layer_norm.bias.data.shape ), f"{full_name} has size {value.shape}, but {adapter.proj_layer_norm.bias.data.shape} was found." adapter.proj_layer_norm.bias.data = value logger.info(f"Adapter proj layer norm bias was initialized from {full_name}.") if "weight" in name: assert ( value.shape == adapter.proj_layer_norm.weight.data.shape ), f"{full_name} has size {value.shape}, but {adapter.proj_layer_norm.weight.data.shape} was found." adapter.proj_layer_norm.weight.data = value else: # has to be projection layer if "bias" in name: assert ( value.shape == adapter.proj.bias.data.shape ), f"{full_name} has size {value.shape}, but {adapter.proj.bias.data.shape} was found." adapter.proj.bias.data = value logger.info(f"Adapter proj layer bias was initialized from {full_name}.") if "weight" in name: assert ( value.shape == adapter.proj.weight.data.shape ), f"{full_name} has size {value.shape}, but {adapter.proj.weight.data.shape} was found." adapter.proj.weight.data = value logger.info(f"Adapter proj layer weight was initialized from {full_name}.") elif isinstance(layer_id, int): if "bias" in name: assert ( value.shape == adapter.layers[layer_id].conv.bias.data.shape ), f"{full_name} has size {value.shape}, but {adapter.layers[layer_id].conv.bias.data.shape} was found." adapter.layers[layer_id].conv.bias.data = value logger.info(f"Adapter layer {layer_id} bias was initialized from {full_name}.") elif "weight" in name: assert ( value.shape == adapter.layers[layer_id].conv.weight.data.shape ), f"{full_name} has size {value.shape}, but {adapter.layers[layer_id].conv.weight.data.shape} was found." adapter.layers[layer_id].conv.weight.data = value logger.info(f"Adapter layer {layer_id} bias was initialized from {full_name}.") else: unused_weights.append(full_name) def make_linear_from_emb(emb): vocab_size, emb_size = emb.weight.shape lin_layer = nn.Linear(vocab_size, emb_size, bias=False) lin_layer.weight.data = emb.weight.data return lin_layer @torch.no_grad() def convert_wav2vec2_checkpoint( checkpoint_path, pytorch_dump_folder_path, dict_path, config_yaml_path, encoder_config_path, decoder_config_path, add_adapter, adapter_kernel_size, adapter_stride, decoder_start_token_id, encoder_output_dim, ): """ Copy/paste/tweak model's weights to transformers design. """ # load configs encoder_config = Wav2Vec2Config.from_pretrained( encoder_config_path, add_adapter=True, adapter_stride=adapter_stride, adapter_kernel_size=adapter_kernel_size, use_auth_token=True, output_hidden_size=encoder_output_dim, ) decoder_config = MBartConfig.from_pretrained(decoder_config_path) # load model model, _, _ = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path], arg_overrides={ "config_yaml": config_yaml_path, "data": "/".join(dict_path.split("/")[:-1]), "w2v_path": checkpoint_path, "load_pretrained_decoder_from": None, }, ) model = model[0].eval() # load feature extractor feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained(encoder_config_path, use_auth_token=True) # set weights for wav2vec2 encoder hf_encoder = Wav2Vec2Model(encoder_config) recursively_load_weights_wav2vec2(model.encoder, hf_encoder) # load decoder weights hf_decoder = MBartForCausalLM(decoder_config) missing_keys, unexpected_keys = hf_decoder.model.decoder.load_state_dict(model.decoder.state_dict(), strict=False) logger.warning(f"The following keys are missing when loading the decoder weights: {missing_keys}") logger.warning(f"The following keys are unexpected when loading the decoder weights: {unexpected_keys}") hf_wav2vec = SpeechEncoderDecoderModel(encoder=hf_encoder, decoder=hf_decoder) hf_wav2vec.config.tie_word_embeddings = False tokenizer = MBart50Tokenizer(dict_path) tokenizer.save_pretrained(pytorch_dump_folder_path) config = hf_wav2vec.config.to_dict() config["pad_token_id"] = tokenizer.pad_token_id config["bos_token_id"] = tokenizer.bos_token_id config["eos_token_id"] = tokenizer.eos_token_id config["tokenizer_class"] = "mbart50" config["feature_extractor_type"] = "wav2vec2" config["decoder_start_token_id"] = tokenizer.eos_token_id config["forced_bos_token_id"] = 250004 config["forced_eos_token_id"] = tokenizer.eos_token_id hf_wav2vec.config = SpeechEncoderDecoderConfig.from_dict(config) hf_wav2vec.save_pretrained(pytorch_dump_folder_path) feature_extractor.save_pretrained(pytorch_dump_folder_path) if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.") parser.add_argument("--checkpoint_path", default=None, type=str, help="Path to fairseq checkpoint") parser.add_argument("--dict_path", default=None, type=str, help="Path to dict of fine-tuned model") parser.add_argument("--config_yaml_path", default=None, type=str, help="Path to yaml file of fine-tuned model") parser.add_argument( "--encoder_config_path", default="facebook/wav2vec2-xls-r-1b", type=str, help="Path to hf encoder wav2vec2 checkpoint config", ) parser.add_argument( "--decoder_config_path", default="facebook/mbart-large-50-one-to-many-mmt", type=str, help="Path to hf decoder checkpoint config", ) parser.add_argument("--add_adapter", default=True, type=bool, help="whethere to add model adapter layers") parser.add_argument("--adapter_stride", default=2, type=int, help="stride of adapter layers") parser.add_argument("--adapter_kernel_size", default=3, type=int, help="kernel size of adapter layers") parser.add_argument("--encoder_output_dim", default=1024, type=int, help="encoder output dim") parser.add_argument("--start_token_id", default=250004, type=int, help="`decoder_start_token_id` of model config") args = parser.parse_args() convert_wav2vec2_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.dict_path, args.config_yaml_path, encoder_config_path=args.encoder_config_path, decoder_config_path=args.decoder_config_path, add_adapter=args.add_adapter, adapter_kernel_size=args.adapter_kernel_size, adapter_stride=args.adapter_stride, decoder_start_token_id=args.start_token_id, encoder_output_dim=args.encoder_output_dim, )
2877025939/PlanADScrollView
8,965
PlanADScrollView/PlanADScrollView/SDWebImage/SDWebImage/SDImageCache.h
/* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import <Foundation/Foundation.h> #import "SDWebImageCompat.h" @class SDImageCacheConfig; typedef NS_ENUM(NSInteger, SDImageCacheType) { /** * The image wasn't available the SDWebImage caches, but was downloaded from the web. */ SDImageCacheTypeNone, /** * The image was obtained from the disk cache. */ SDImageCacheTypeDisk, /** * The image was obtained from the memory cache. */ SDImageCacheTypeMemory }; typedef void(^SDCacheQueryCompletedBlock)(UIImage * _Nullable image, NSData * _Nullable data, SDImageCacheType cacheType); typedef void(^SDWebImageCheckCacheCompletionBlock)(BOOL isInCache); typedef void(^SDWebImageCalculateSizeBlock)(NSUInteger fileCount, NSUInteger totalSize); /** * SDImageCache maintains a memory cache and an optional disk cache. Disk cache write operations are performed * asynchronous so it doesn’t add unnecessary latency to the UI. */ @interface SDImageCache : NSObject #pragma mark - Properties /** * Cache Config object - storing all kind of settings */ @property (nonatomic, nonnull, readonly) SDImageCacheConfig *config; /** * The maximum "total cost" of the in-memory image cache. The cost function is the number of pixels held in memory. */ @property (assign, nonatomic) NSUInteger maxMemoryCost; /** * The maximum number of objects the cache should hold. */ @property (assign, nonatomic) NSUInteger maxMemoryCountLimit; #pragma mark - Singleton and initialization /** * Returns global shared cache instance * * @return SDImageCache global instance */ + (nonnull instancetype)sharedImageCache; /** * Init a new cache store with a specific namespace * * @param ns The namespace to use for this cache store */ - (nonnull instancetype)initWithNamespace:(nonnull NSString *)ns; /** * Init a new cache store with a specific namespace and directory * * @param ns The namespace to use for this cache store * @param directory Directory to cache disk images in */ - (nonnull instancetype)initWithNamespace:(nonnull NSString *)ns diskCacheDirectory:(nonnull NSString *)directory NS_DESIGNATED_INITIALIZER; #pragma mark - Cache paths - (nullable NSString *)makeDiskCachePath:(nonnull NSString*)fullNamespace; /** * Add a read-only cache path to search for images pre-cached by SDImageCache * Useful if you want to bundle pre-loaded images with your app * * @param path The path to use for this read-only cache path */ - (void)addReadOnlyCachePath:(nonnull NSString *)path; #pragma mark - Store Ops /** * Asynchronously store an image into memory and disk cache at the given key. * * @param image The image to store * @param key The unique image cache key, usually it's image absolute URL * @param completionBlock A block executed after the operation is finished */ - (void)storeImage:(nullable UIImage *)image forKey:(nullable NSString *)key completion:(nullable SDWebImageNoParamsBlock)completionBlock; /** * Asynchronously store an image into memory and disk cache at the given key. * * @param image The image to store * @param key The unique image cache key, usually it's image absolute URL * @param toDisk Store the image to disk cache if YES * @param completionBlock A block executed after the operation is finished */ - (void)storeImage:(nullable UIImage *)image forKey:(nullable NSString *)key toDisk:(BOOL)toDisk completion:(nullable SDWebImageNoParamsBlock)completionBlock; /** * Asynchronously store an image into memory and disk cache at the given key. * * @param image The image to store * @param imageData The image data as returned by the server, this representation will be used for disk storage * instead of converting the given image object into a storable/compressed image format in order * to save quality and CPU * @param key The unique image cache key, usually it's image absolute URL * @param toDisk Store the image to disk cache if YES * @param completionBlock A block executed after the operation is finished */ - (void)storeImage:(nullable UIImage *)image imageData:(nullable NSData *)imageData forKey:(nullable NSString *)key toDisk:(BOOL)toDisk completion:(nullable SDWebImageNoParamsBlock)completionBlock; /** * Synchronously store image NSData into disk cache at the given key. * * @warning This method is synchronous, make sure to call it from the ioQueue * * @param imageData The image data to store * @param key The unique image cache key, usually it's image absolute URL */ - (void)storeImageDataToDisk:(nullable NSData *)imageData forKey:(nullable NSString *)key; #pragma mark - Query and Retrieve Ops /** * Async check if image exists in disk cache already (does not load the image) * * @param key the key describing the url * @param completionBlock the block to be executed when the check is done. * @note the completion block will be always executed on the main queue */ - (void)diskImageExistsWithKey:(nullable NSString *)key completion:(nullable SDWebImageCheckCacheCompletionBlock)completionBlock; /** * Operation that queries the cache asynchronously and call the completion when done. * * @param key The unique key used to store the wanted image * @param doneBlock The completion block. Will not get called if the operation is cancelled * * @return a NSOperation instance containing the cache op */ - (nullable NSOperation *)queryCacheOperationForKey:(nullable NSString *)key done:(nullable SDCacheQueryCompletedBlock)doneBlock; /** * Query the memory cache synchronously. * * @param key The unique key used to store the image */ - (nullable UIImage *)imageFromMemoryCacheForKey:(nullable NSString *)key; /** * Query the disk cache synchronously. * * @param key The unique key used to store the image */ - (nullable UIImage *)imageFromDiskCacheForKey:(nullable NSString *)key; /** * Query the cache (memory and or disk) synchronously after checking the memory cache. * * @param key The unique key used to store the image */ - (nullable UIImage *)imageFromCacheForKey:(nullable NSString *)key; #pragma mark - Remove Ops /** * Remove the image from memory and disk cache asynchronously * * @param key The unique image cache key * @param completion A block that should be executed after the image has been removed (optional) */ - (void)removeImageForKey:(nullable NSString *)key withCompletion:(nullable SDWebImageNoParamsBlock)completion; /** * Remove the image from memory and optionally disk cache asynchronously * * @param key The unique image cache key * @param fromDisk Also remove cache entry from disk if YES * @param completion A block that should be executed after the image has been removed (optional) */ - (void)removeImageForKey:(nullable NSString *)key fromDisk:(BOOL)fromDisk withCompletion:(nullable SDWebImageNoParamsBlock)completion; #pragma mark - Cache clean Ops /** * Clear all memory cached images */ - (void)clearMemory; /** * Async clear all disk cached images. Non-blocking method - returns immediately. * @param completion A block that should be executed after cache expiration completes (optional) */ - (void)clearDiskOnCompletion:(nullable SDWebImageNoParamsBlock)completion; /** * Async remove all expired cached image from disk. Non-blocking method - returns immediately. * @param completionBlock A block that should be executed after cache expiration completes (optional) */ - (void)deleteOldFilesWithCompletionBlock:(nullable SDWebImageNoParamsBlock)completionBlock; #pragma mark - Cache Info /** * Get the size used by the disk cache */ - (NSUInteger)getSize; /** * Get the number of images in the disk cache */ - (NSUInteger)getDiskCount; /** * Asynchronously calculate the disk cache's size. */ - (void)calculateSizeWithCompletionBlock:(nullable SDWebImageCalculateSizeBlock)completionBlock; #pragma mark - Cache Paths /** * Get the cache path for a certain key (needs the cache path root folder) * * @param key the key (can be obtained from url using cacheKeyForURL) * @param path the cache path root folder * * @return the cache path */ - (nullable NSString *)cachePathForKey:(nullable NSString *)key inPath:(nonnull NSString *)path; /** * Get the default cache path for a certain key * * @param key the key (can be obtained from url using cacheKeyForURL) * * @return the default cache path */ - (nullable NSString *)defaultCachePathForKey:(nullable NSString *)key; @end
2877025939/PlanADScrollView
1,832
PlanADScrollView/PlanADScrollView/SDWebImage/SDWebImage/SDWebImageCompat.m
/* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import "SDWebImageCompat.h" #if !__has_feature(objc_arc) #error SDWebImage is ARC only. Either turn on ARC for the project or use -fobjc-arc flag #endif inline UIImage *SDScaledImageForKey(NSString * _Nullable key, UIImage * _Nullable image) { if (!image) { return nil; } #if SD_MAC return image; #elif SD_UIKIT || SD_WATCH if ((image.images).count > 0) { NSMutableArray<UIImage *> *scaledImages = [NSMutableArray array]; for (UIImage *tempImage in image.images) { [scaledImages addObject:SDScaledImageForKey(key, tempImage)]; } return [UIImage animatedImageWithImages:scaledImages duration:image.duration]; } else { #if SD_WATCH if ([[WKInterfaceDevice currentDevice] respondsToSelector:@selector(screenScale)]) { #elif SD_UIKIT if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) { #endif CGFloat scale = 1; if (key.length >= 8) { NSRange range = [key rangeOfString:@"@2x."]; if (range.location != NSNotFound) { scale = 2.0; } range = [key rangeOfString:@"@3x."]; if (range.location != NSNotFound) { scale = 3.0; } } UIImage *scaledImage = [[UIImage alloc] initWithCGImage:image.CGImage scale:scale orientation:image.imageOrientation]; image = scaledImage; } return image; } #endif } NSString *const SDWebImageErrorDomain = @"SDWebImageErrorDomain";
2881099/csredis
1,846
src/CSRedisCore/Internal/Commands/RedisString.cs
using CSRedis.Internal.IO; using System; using System.ComponentModel; using System.Globalization; namespace CSRedis.Internal.Commands { class RedisString : RedisCommand<string> { public RedisString(string command, params object[] args) : base(command, args) { } public override string Parse(RedisReader reader) { return reader.ReadBulkString(); } public class Nullable : RedisString { public Nullable(string command, params object[] args) : base(command, args) { } public override string Parse(RedisReader reader) { RedisMessage type = reader.ReadType(); if (type == RedisMessage.Bulk) return reader.ReadBulkString(false); reader.ReadMultiBulk(false); return null; } } public class Integer : RedisCommand<int> { public Integer(string command, params object[] args) : base(command, args) { } public override int Parse(RedisReader reader) { return Int32.Parse(reader.ReadBulkString(), NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat); } } public class Converter<T> : RedisCommand<T> { static Lazy<TypeConverter> converter = new Lazy<TypeConverter>(() => TypeDescriptor.GetConverter(typeof(T))); public Converter(string command, params object[] args) : base(command, args) { } public override T Parse(RedisReader reader) { return (T)converter.Value.ConvertFromInvariantString(reader.ReadBulkString()); } } } }
2881099/csredis
1,034
src/CSRedisCore/Internal/Commands/RedisSlowLogCommand.cs
using CSRedis.Internal.IO; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CSRedis.Internal.Commands { class RedisSlowLogCommand : RedisCommand<RedisSlowLogEntry> { public RedisSlowLogCommand(string command, object[] args) : base(command, args) { } public override RedisSlowLogEntry Parse(RedisReader reader) { reader.ExpectType(RedisMessage.MultiBulk); reader.ExpectSize(4); long id = reader.ReadInt(); long timestamp = reader.ReadInt(); long microseconds = reader.ReadInt(); reader.ExpectType(RedisMessage.MultiBulk); string[] arguments = new string[reader.ReadInt(false)]; for (int i = 0; i < arguments.Length; i++) arguments[i] = reader.ReadBulkString(); return new RedisSlowLogEntry(id, RedisDate.FromTimestamp(timestamp), RedisDate.Micro.FromMicroseconds(microseconds), arguments); } } }
2881099/csredis
2,076
src/CSRedisCore/Internal/Commands/RedisDate.cs
using CSRedis.Internal.IO; using System; using System.Globalization; using System.IO; namespace CSRedis.Internal.Commands { class RedisDate : RedisCommand<DateTime> { static readonly DateTime _epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); public RedisDate(string command, params object[] args) : base(command, args) { } public override DateTime Parse(RedisReader reader) { return FromTimestamp(reader.ReadInt()); } public class Micro : RedisCommand<DateTime> { public Micro(string command, params object[] args) : base(command, args) { } public override DateTime Parse(RedisReader reader) { reader.ExpectType(RedisMessage.MultiBulk); reader.ExpectSize(2); var timestamp = Int32.Parse(reader.ReadBulkString(), NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat); var microseconds = long.Parse(reader.ReadBulkString(), NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat); return FromTimestamp(timestamp, microseconds); } public static DateTime FromTimestamp(long timestamp, long microseconds) { return RedisDate.FromTimestamp(timestamp) + FromMicroseconds(microseconds); } public static TimeSpan FromMicroseconds(long microseconds) { return TimeSpan.FromTicks(microseconds * (TimeSpan.TicksPerMillisecond / 1000)); } public static long ToMicroseconds(TimeSpan span) { return span.Ticks / (TimeSpan.TicksPerMillisecond / 1000); } } public static DateTime FromTimestamp(long seconds) { return _epoch + TimeSpan.FromSeconds(seconds); } public static TimeSpan ToTimestamp(DateTime date) { return date.ToUniversalTime().Subtract(_epoch); } } }
2877025939/PlanADScrollView
4,161
PlanADScrollView/PlanADScrollView/SDWebImage/SDWebImage/SDWebImagePrefetcher.h
/* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import <Foundation/Foundation.h> #import "SDWebImageManager.h" @class SDWebImagePrefetcher; @protocol SDWebImagePrefetcherDelegate <NSObject> @optional /** * Called when an image was prefetched. * * @param imagePrefetcher The current image prefetcher * @param imageURL The image url that was prefetched * @param finishedCount The total number of images that were prefetched (successful or not) * @param totalCount The total number of images that were to be prefetched */ - (void)imagePrefetcher:(nonnull SDWebImagePrefetcher *)imagePrefetcher didPrefetchURL:(nullable NSURL *)imageURL finishedCount:(NSUInteger)finishedCount totalCount:(NSUInteger)totalCount; /** * Called when all images are prefetched. * @param imagePrefetcher The current image prefetcher * @param totalCount The total number of images that were prefetched (whether successful or not) * @param skippedCount The total number of images that were skipped */ - (void)imagePrefetcher:(nonnull SDWebImagePrefetcher *)imagePrefetcher didFinishWithTotalCount:(NSUInteger)totalCount skippedCount:(NSUInteger)skippedCount; @end typedef void(^SDWebImagePrefetcherProgressBlock)(NSUInteger noOfFinishedUrls, NSUInteger noOfTotalUrls); typedef void(^SDWebImagePrefetcherCompletionBlock)(NSUInteger noOfFinishedUrls, NSUInteger noOfSkippedUrls); /** * Prefetch some URLs in the cache for future use. Images are downloaded in low priority. */ @interface SDWebImagePrefetcher : NSObject /** * The web image manager */ @property (strong, nonatomic, readonly, nonnull) SDWebImageManager *manager; /** * Maximum number of URLs to prefetch at the same time. Defaults to 3. */ @property (nonatomic, assign) NSUInteger maxConcurrentDownloads; /** * SDWebImageOptions for prefetcher. Defaults to SDWebImageLowPriority. */ @property (nonatomic, assign) SDWebImageOptions options; /** * Queue options for Prefetcher. Defaults to Main Queue. */ @property (nonatomic, assign, nonnull) dispatch_queue_t prefetcherQueue; @property (weak, nonatomic, nullable) id <SDWebImagePrefetcherDelegate> delegate; /** * Return the global image prefetcher instance. */ + (nonnull instancetype)sharedImagePrefetcher; /** * Allows you to instantiate a prefetcher with any arbitrary image manager. */ - (nonnull instancetype)initWithImageManager:(nonnull SDWebImageManager *)manager NS_DESIGNATED_INITIALIZER; /** * Assign list of URLs to let SDWebImagePrefetcher to queue the prefetching, * currently one image is downloaded at a time, * and skips images for failed downloads and proceed to the next image in the list. * Any previously-running prefetch operations are canceled. * * @param urls list of URLs to prefetch */ - (void)prefetchURLs:(nullable NSArray<NSURL *> *)urls; /** * Assign list of URLs to let SDWebImagePrefetcher to queue the prefetching, * currently one image is downloaded at a time, * and skips images for failed downloads and proceed to the next image in the list. * Any previously-running prefetch operations are canceled. * * @param urls list of URLs to prefetch * @param progressBlock block to be called when progress updates; * first parameter is the number of completed (successful or not) requests, * second parameter is the total number of images originally requested to be prefetched * @param completionBlock block to be called when prefetching is completed * first param is the number of completed (successful or not) requests, * second parameter is the number of skipped requests */ - (void)prefetchURLs:(nullable NSArray<NSURL *> *)urls progress:(nullable SDWebImagePrefetcherProgressBlock)progressBlock completed:(nullable SDWebImagePrefetcherCompletionBlock)completionBlock; /** * Remove and cancel queued list */ - (void)cancelPrefetching; @end
2877025939/PlanADScrollView
4,236
PlanADScrollView/PlanADScrollView/SDWebImage/SDWebImage/UIImageView+HighlightedWebCache.h
/* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import "SDWebImageCompat.h" #if SD_UIKIT #import "SDWebImageManager.h" /** * Integrates SDWebImage async downloading and caching of remote images with UIImageView for highlighted state. */ @interface UIImageView (HighlightedWebCache) /** * Set the imageView `highlightedImage` with an `url`. * * The download is asynchronous and cached. * * @param url The url for the image. */ - (void)sd_setHighlightedImageWithURL:(nullable NSURL *)url; /** * Set the imageView `highlightedImage` with an `url` and custom options. * * The download is asynchronous and cached. * * @param url The url for the image. * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. */ - (void)sd_setHighlightedImageWithURL:(nullable NSURL *)url options:(SDWebImageOptions)options; /** * Set the imageView `highlightedImage` with an `url`. * * The download is asynchronous and cached. * * @param url The url for the image. * @param completedBlock A block called when operation has been completed. This block has no return value * and takes the requested UIImage as first parameter. In case of error the image parameter * is nil and the second parameter may contain an NSError. The third parameter is a Boolean * indicating if the image was retrieved from the local cache or from the network. * The fourth parameter is the original image url. */ - (void)sd_setHighlightedImageWithURL:(nullable NSURL *)url completed:(nullable SDExternalCompletionBlock)completedBlock; /** * Set the imageView `highlightedImage` with an `url` and custom options. * * The download is asynchronous and cached. * * @param url The url for the image. * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. * @param completedBlock A block called when operation has been completed. This block has no return value * and takes the requested UIImage as first parameter. In case of error the image parameter * is nil and the second parameter may contain an NSError. The third parameter is a Boolean * indicating if the image was retrieved from the local cache or from the network. * The fourth parameter is the original image url. */ - (void)sd_setHighlightedImageWithURL:(nullable NSURL *)url options:(SDWebImageOptions)options completed:(nullable SDExternalCompletionBlock)completedBlock; /** * Set the imageView `highlightedImage` with an `url` and custom options. * * The download is asynchronous and cached. * * @param url The url for the image. * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. * @param progressBlock A block called while image is downloading * @note the progress block is executed on a background queue * @param completedBlock A block called when operation has been completed. This block has no return value * and takes the requested UIImage as first parameter. In case of error the image parameter * is nil and the second parameter may contain an NSError. The third parameter is a Boolean * indicating if the image was retrieved from the local cache or from the network. * The fourth parameter is the original image url. */ - (void)sd_setHighlightedImageWithURL:(nullable NSURL *)url options:(SDWebImageOptions)options progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock completed:(nullable SDExternalCompletionBlock)completedBlock; @end #endif
2877025939/PlanADScrollView
8,571
PlanADScrollView/PlanADScrollView/SDWebImage/SDWebImage/SDWebImageDownloader.h
/* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import <Foundation/Foundation.h> #import "SDWebImageCompat.h" #import "SDWebImageOperation.h" typedef NS_OPTIONS(NSUInteger, SDWebImageDownloaderOptions) { SDWebImageDownloaderLowPriority = 1 << 0, SDWebImageDownloaderProgressiveDownload = 1 << 1, /** * By default, request prevent the use of NSURLCache. With this flag, NSURLCache * is used with default policies. */ SDWebImageDownloaderUseNSURLCache = 1 << 2, /** * Call completion block with nil image/imageData if the image was read from NSURLCache * (to be combined with `SDWebImageDownloaderUseNSURLCache`). */ SDWebImageDownloaderIgnoreCachedResponse = 1 << 3, /** * In iOS 4+, continue the download of the image if the app goes to background. This is achieved by asking the system for * extra time in background to let the request finish. If the background task expires the operation will be cancelled. */ SDWebImageDownloaderContinueInBackground = 1 << 4, /** * Handles cookies stored in NSHTTPCookieStore by setting * NSMutableURLRequest.HTTPShouldHandleCookies = YES; */ SDWebImageDownloaderHandleCookies = 1 << 5, /** * Enable to allow untrusted SSL certificates. * Useful for testing purposes. Use with caution in production. */ SDWebImageDownloaderAllowInvalidSSLCertificates = 1 << 6, /** * Put the image in the high priority queue. */ SDWebImageDownloaderHighPriority = 1 << 7, /** * Scale down the image */ SDWebImageDownloaderScaleDownLargeImages = 1 << 8, }; typedef NS_ENUM(NSInteger, SDWebImageDownloaderExecutionOrder) { /** * Default value. All download operations will execute in queue style (first-in-first-out). */ SDWebImageDownloaderFIFOExecutionOrder, /** * All download operations will execute in stack style (last-in-first-out). */ SDWebImageDownloaderLIFOExecutionOrder }; extern NSString * _Nonnull const SDWebImageDownloadStartNotification; extern NSString * _Nonnull const SDWebImageDownloadStopNotification; typedef void(^SDWebImageDownloaderProgressBlock)(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL); typedef void(^SDWebImageDownloaderCompletedBlock)(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, BOOL finished); typedef NSDictionary<NSString *, NSString *> SDHTTPHeadersDictionary; typedef NSMutableDictionary<NSString *, NSString *> SDHTTPHeadersMutableDictionary; typedef SDHTTPHeadersDictionary * _Nullable (^SDWebImageDownloaderHeadersFilterBlock)(NSURL * _Nullable url, SDHTTPHeadersDictionary * _Nullable headers); /** * A token associated with each download. Can be used to cancel a download */ @interface SDWebImageDownloadToken : NSObject @property (nonatomic, strong, nullable) NSURL *url; @property (nonatomic, strong, nullable) id downloadOperationCancelToken; @end /** * Asynchronous downloader dedicated and optimized for image loading. */ @interface SDWebImageDownloader : NSObject /** * Decompressing images that are downloaded and cached can improve performance but can consume lot of memory. * Defaults to YES. Set this to NO if you are experiencing a crash due to excessive memory consumption. */ @property (assign, nonatomic) BOOL shouldDecompressImages; /** * The maximum number of concurrent downloads */ @property (assign, nonatomic) NSInteger maxConcurrentDownloads; /** * Shows the current amount of downloads that still need to be downloaded */ @property (readonly, nonatomic) NSUInteger currentDownloadCount; /** * The timeout value (in seconds) for the download operation. Default: 15.0. */ @property (assign, nonatomic) NSTimeInterval downloadTimeout; /** * Changes download operations execution order. Default value is `SDWebImageDownloaderFIFOExecutionOrder`. */ @property (assign, nonatomic) SDWebImageDownloaderExecutionOrder executionOrder; /** * Singleton method, returns the shared instance * * @return global shared instance of downloader class */ + (nonnull instancetype)sharedDownloader; /** * Set the default URL credential to be set for request operations. */ @property (strong, nonatomic, nullable) NSURLCredential *urlCredential; /** * Set username */ @property (strong, nonatomic, nullable) NSString *username; /** * Set password */ @property (strong, nonatomic, nullable) NSString *password; /** * Set filter to pick headers for downloading image HTTP request. * * This block will be invoked for each downloading image request, returned * NSDictionary will be used as headers in corresponding HTTP request. */ @property (nonatomic, copy, nullable) SDWebImageDownloaderHeadersFilterBlock headersFilter; /** * Creates an instance of a downloader with specified session configuration. * *Note*: `timeoutIntervalForRequest` is going to be overwritten. * @return new instance of downloader class */ - (nonnull instancetype)initWithSessionConfiguration:(nullable NSURLSessionConfiguration *)sessionConfiguration NS_DESIGNATED_INITIALIZER; /** * Set a value for a HTTP header to be appended to each download HTTP request. * * @param value The value for the header field. Use `nil` value to remove the header. * @param field The name of the header field to set. */ - (void)setValue:(nullable NSString *)value forHTTPHeaderField:(nullable NSString *)field; /** * Returns the value of the specified HTTP header field. * * @return The value associated with the header field field, or `nil` if there is no corresponding header field. */ - (nullable NSString *)valueForHTTPHeaderField:(nullable NSString *)field; /** * Sets a subclass of `SDWebImageDownloaderOperation` as the default * `NSOperation` to be used each time SDWebImage constructs a request * operation to download an image. * * @param operationClass The subclass of `SDWebImageDownloaderOperation` to set * as default. Passing `nil` will revert to `SDWebImageDownloaderOperation`. */ - (void)setOperationClass:(nullable Class)operationClass; /** * Creates a SDWebImageDownloader async downloader instance with a given URL * * The delegate will be informed when the image is finish downloaded or an error has happen. * * @see SDWebImageDownloaderDelegate * * @param url The URL to the image to download * @param options The options to be used for this download * @param progressBlock A block called repeatedly while the image is downloading * @note the progress block is executed on a background queue * @param completedBlock A block called once the download is completed. * If the download succeeded, the image parameter is set, in case of error, * error parameter is set with the error. The last parameter is always YES * if SDWebImageDownloaderProgressiveDownload isn't use. With the * SDWebImageDownloaderProgressiveDownload option, this block is called * repeatedly with the partial image object and the finished argument set to NO * before to be called a last time with the full image and finished argument * set to YES. In case of error, the finished argument is always YES. * * @return A token (SDWebImageDownloadToken) that can be passed to -cancel: to cancel this operation */ - (nullable SDWebImageDownloadToken *)downloadImageWithURL:(nullable NSURL *)url options:(SDWebImageDownloaderOptions)options progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock completed:(nullable SDWebImageDownloaderCompletedBlock)completedBlock; /** * Cancels a download that was previously queued using -downloadImageWithURL:options:progress:completed: * * @param token The token received from -downloadImageWithURL:options:progress:completed: that should be canceled. */ - (void)cancel:(nullable SDWebImageDownloadToken *)token; /** * Sets the download queue suspension state */ - (void)setSuspended:(BOOL)suspended; /** * Cancels all download operations in the queue */ - (void)cancelAllDownloads; @end
2877025939/PlanADScrollView
8,646
PlanADScrollView/PlanADScrollView/SDWebImage/SDWebImage/UIImageView+WebCache.h
/* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import "SDWebImageCompat.h" #if SD_UIKIT || SD_MAC #import "SDWebImageManager.h" /** * Integrates SDWebImage async downloading and caching of remote images with UIImageView. * * Usage with a UITableViewCell sub-class: * * @code #import <SDWebImage/UIImageView+WebCache.h> ... - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *MyIdentifier = @"MyIdentifier"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyIdentifier] autorelease]; } // Here we use the provided sd_setImageWithURL: method to load the web image // Ensure you use a placeholder image otherwise cells will be initialized with no image [cell.imageView sd_setImageWithURL:[NSURL URLWithString:@"http://example.com/image.jpg"] placeholderImage:[UIImage imageNamed:@"placeholder"]]; cell.textLabel.text = @"My Text"; return cell; } * @endcode */ @interface UIImageView (WebCache) /** * Set the imageView `image` with an `url`. * * The download is asynchronous and cached. * * @param url The url for the image. */ - (void)sd_setImageWithURL:(nullable NSURL *)url; /** * Set the imageView `image` with an `url` and a placeholder. * * The download is asynchronous and cached. * * @param url The url for the image. * @param placeholder The image to be set initially, until the image request finishes. * @see sd_setImageWithURL:placeholderImage:options: */ - (void)sd_setImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder; /** * Set the imageView `image` with an `url`, placeholder and custom options. * * The download is asynchronous and cached. * * @param url The url for the image. * @param placeholder The image to be set initially, until the image request finishes. * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. */ - (void)sd_setImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options; /** * Set the imageView `image` with an `url`. * * The download is asynchronous and cached. * * @param url The url for the image. * @param completedBlock A block called when operation has been completed. This block has no return value * and takes the requested UIImage as first parameter. In case of error the image parameter * is nil and the second parameter may contain an NSError. The third parameter is a Boolean * indicating if the image was retrieved from the local cache or from the network. * The fourth parameter is the original image url. */ - (void)sd_setImageWithURL:(nullable NSURL *)url completed:(nullable SDExternalCompletionBlock)completedBlock; /** * Set the imageView `image` with an `url`, placeholder. * * The download is asynchronous and cached. * * @param url The url for the image. * @param placeholder The image to be set initially, until the image request finishes. * @param completedBlock A block called when operation has been completed. This block has no return value * and takes the requested UIImage as first parameter. In case of error the image parameter * is nil and the second parameter may contain an NSError. The third parameter is a Boolean * indicating if the image was retrieved from the local cache or from the network. * The fourth parameter is the original image url. */ - (void)sd_setImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder completed:(nullable SDExternalCompletionBlock)completedBlock; /** * Set the imageView `image` with an `url`, placeholder and custom options. * * The download is asynchronous and cached. * * @param url The url for the image. * @param placeholder The image to be set initially, until the image request finishes. * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. * @param completedBlock A block called when operation has been completed. This block has no return value * and takes the requested UIImage as first parameter. In case of error the image parameter * is nil and the second parameter may contain an NSError. The third parameter is a Boolean * indicating if the image was retrieved from the local cache or from the network. * The fourth parameter is the original image url. */ - (void)sd_setImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options completed:(nullable SDExternalCompletionBlock)completedBlock; /** * Set the imageView `image` with an `url`, placeholder and custom options. * * The download is asynchronous and cached. * * @param url The url for the image. * @param placeholder The image to be set initially, until the image request finishes. * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. * @param progressBlock A block called while image is downloading * @note the progress block is executed on a background queue * @param completedBlock A block called when operation has been completed. This block has no return value * and takes the requested UIImage as first parameter. In case of error the image parameter * is nil and the second parameter may contain an NSError. The third parameter is a Boolean * indicating if the image was retrieved from the local cache or from the network. * The fourth parameter is the original image url. */ - (void)sd_setImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock completed:(nullable SDExternalCompletionBlock)completedBlock; /** * Set the imageView `image` with an `url` and optionally a placeholder image. * * The download is asynchronous and cached. * * @param url The url for the image. * @param placeholder The image to be set initially, until the image request finishes. * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. * @param progressBlock A block called while image is downloading * @note the progress block is executed on a background queue * @param completedBlock A block called when operation has been completed. This block has no return value * and takes the requested UIImage as first parameter. In case of error the image parameter * is nil and the second parameter may contain an NSError. The third parameter is a Boolean * indicating if the image was retrieved from the local cache or from the network. * The fourth parameter is the original image url. */ - (void)sd_setImageWithPreviousCachedImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock completed:(nullable SDExternalCompletionBlock)completedBlock; #if SD_UIKIT #pragma mark - Animation of multiple images /** * Download an array of images and starts them in an animation loop * * @param arrayOfURLs An array of NSURL */ - (void)sd_setAnimationImagesWithURLs:(nonnull NSArray<NSURL *> *)arrayOfURLs; - (void)sd_cancelCurrentAnimationImagesLoad; #endif @end #endif
2881099/csredis
1,820
src/CSRedisCore/Internal/Commands/RedisStatus.cs
 using CSRedis.Internal.IO; using CSRedis.Internal.Utilities; using System; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.IO; namespace CSRedis.Internal.Commands { class RedisStatus : RedisCommand<string> { public RedisStatus(string command, params object[] args) : base(command, args) { } public override string Parse(RedisReader reader) { return reader.ReadStatus(); } public class Empty : RedisCommand<string> { public Empty(string command, params object[] args) : base(command, args) { } public override string Parse(RedisReader reader) { RedisMessage type = reader.ReadType(); if ((int)type == -1) return String.Empty; else if (type == RedisMessage.Error) throw new RedisException(reader.ReadStatus(false)); throw new RedisProtocolException("Unexpected type: " + type); } } public class Nullable : RedisCommand<string> { public Nullable(string command, params object[] args) : base(command, args) { } public override string Parse(RedisReader reader) { RedisMessage type = reader.ReadType(); if (type == RedisMessage.Status) return reader.ReadStatus(false); object[] result = reader.ReadMultiBulk(false); if (result != null) throw new RedisProtocolException("Expecting null MULTI BULK response. Received: " + result.ToString()); return null; } } } }
2881099/csredis
1,066
src/CSRedisCore/Internal/Commands/RedisFloat.cs
using CSRedis.Internal.IO; using System; using System.Globalization; namespace CSRedis.Internal.Commands { class RedisFloat : RedisCommand<decimal> { public RedisFloat(string command, params object[] args) : base(command, args) { } public override decimal Parse(RedisReader reader) { return FromString(reader.ReadBulkString()); } static decimal FromString(string input) { return decimal.Parse(input, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat); } public class Nullable : RedisCommand<decimal?> { public Nullable(string command, params object[] args) : base(command, args) { } public override decimal? Parse(RedisReader reader) { string result = reader.ReadBulkString(); if (string.IsNullOrEmpty(result)) return null; return RedisFloat.FromString(result); } } } }
2881099/csredis
1,257
src/CSRedisCore/Internal/IO/RedisAsyncCommandToken.cs
using CSRedis.Internal.IO; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CSRedis.Internal.IO { interface IRedisAsyncCommandToken { Task Task { get; } RedisCommand Command { get; } void SetResult(RedisReader reader); void SetException(Exception e); } class RedisAsyncCommandToken<T> : IRedisAsyncCommandToken { readonly TaskCompletionSource<T> _tcs; readonly RedisCommand<T> _command; public TaskCompletionSource<T> TaskSource { get { return _tcs; } } public RedisCommand Command { get { return _command; } } public Task Task { get { return _tcs.Task; } } public RedisAsyncCommandToken(RedisCommand<T> command) { _tcs = new TaskCompletionSource<T>(); _command = command; } public void SetResult(RedisReader reader) { if (reader == null) { _tcs.SetResult(default(T)); return; } _tcs.SetResult(_command.Parse(reader)); } public void SetException(Exception e) { _tcs.SetException(e); } } }
2877025939/PlanADScrollView
2,064
PlanADScrollView/PlanADScrollView/SDWebImage/SDWebImage/UIImageView+HighlightedWebCache.m
/* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import "UIImageView+HighlightedWebCache.h" #if SD_UIKIT #import "UIView+WebCacheOperation.h" #import "UIView+WebCache.h" @implementation UIImageView (HighlightedWebCache) - (void)sd_setHighlightedImageWithURL:(nullable NSURL *)url { [self sd_setHighlightedImageWithURL:url options:0 progress:nil completed:nil]; } - (void)sd_setHighlightedImageWithURL:(nullable NSURL *)url options:(SDWebImageOptions)options { [self sd_setHighlightedImageWithURL:url options:options progress:nil completed:nil]; } - (void)sd_setHighlightedImageWithURL:(nullable NSURL *)url completed:(nullable SDExternalCompletionBlock)completedBlock { [self sd_setHighlightedImageWithURL:url options:0 progress:nil completed:completedBlock]; } - (void)sd_setHighlightedImageWithURL:(nullable NSURL *)url options:(SDWebImageOptions)options completed:(nullable SDExternalCompletionBlock)completedBlock { [self sd_setHighlightedImageWithURL:url options:options progress:nil completed:completedBlock]; } - (void)sd_setHighlightedImageWithURL:(nullable NSURL *)url options:(SDWebImageOptions)options progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock completed:(nullable SDExternalCompletionBlock)completedBlock { __weak typeof(self)weakSelf = self; [self sd_internalSetImageWithURL:url placeholderImage:nil options:options operationKey:@"UIImageViewImageOperationHighlighted" setImageBlock:^(UIImage *image, NSData *imageData) { weakSelf.highlightedImage = image; } progress:progressBlock completed:completedBlock]; } @end #endif
2877025939/PlanADScrollView
12,306
PlanADScrollView/PlanADScrollView/SDWebImage/SDWebImage/SDWebImageDecoder.m
/* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * (c) james <https://github.com/mystcolor> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import "SDWebImageDecoder.h" @implementation UIImage (ForceDecode) #if SD_UIKIT || SD_WATCH static const size_t kBytesPerPixel = 4; static const size_t kBitsPerComponent = 8; + (nullable UIImage *)decodedImageWithImage:(nullable UIImage *)image { if (![UIImage shouldDecodeImage:image]) { return image; } // autorelease the bitmap context and all vars to help system to free memory when there are memory warning. // on iOS7, do not forget to call [[SDImageCache sharedImageCache] clearMemory]; @autoreleasepool{ CGImageRef imageRef = image.CGImage; CGColorSpaceRef colorspaceRef = [UIImage colorSpaceForImageRef:imageRef]; size_t width = CGImageGetWidth(imageRef); size_t height = CGImageGetHeight(imageRef); size_t bytesPerRow = kBytesPerPixel * width; // kCGImageAlphaNone is not supported in CGBitmapContextCreate. // Since the original image here has no alpha info, use kCGImageAlphaNoneSkipLast // to create bitmap graphics contexts without alpha info. CGContextRef context = CGBitmapContextCreate(NULL, width, height, kBitsPerComponent, bytesPerRow, colorspaceRef, kCGBitmapByteOrderDefault|kCGImageAlphaNoneSkipLast); if (context == NULL) { return image; } // Draw the image into the context and retrieve the new bitmap image without alpha CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef); CGImageRef imageRefWithoutAlpha = CGBitmapContextCreateImage(context); UIImage *imageWithoutAlpha = [UIImage imageWithCGImage:imageRefWithoutAlpha scale:image.scale orientation:image.imageOrientation]; CGContextRelease(context); CGImageRelease(imageRefWithoutAlpha); return imageWithoutAlpha; } } /* * Defines the maximum size in MB of the decoded image when the flag `SDWebImageScaleDownLargeImages` is set * Suggested value for iPad1 and iPhone 3GS: 60. * Suggested value for iPad2 and iPhone 4: 120. * Suggested value for iPhone 3G and iPod 2 and earlier devices: 30. */ static const CGFloat kDestImageSizeMB = 60.0f; /* * Defines the maximum size in MB of a tile used to decode image when the flag `SDWebImageScaleDownLargeImages` is set * Suggested value for iPad1 and iPhone 3GS: 20. * Suggested value for iPad2 and iPhone 4: 40. * Suggested value for iPhone 3G and iPod 2 and earlier devices: 10. */ static const CGFloat kSourceImageTileSizeMB = 20.0f; static const CGFloat kBytesPerMB = 1024.0f * 1024.0f; static const CGFloat kPixelsPerMB = kBytesPerMB / kBytesPerPixel; static const CGFloat kDestTotalPixels = kDestImageSizeMB * kPixelsPerMB; static const CGFloat kTileTotalPixels = kSourceImageTileSizeMB * kPixelsPerMB; static const CGFloat kDestSeemOverlap = 2.0f; // the numbers of pixels to overlap the seems where tiles meet. + (nullable UIImage *)decodedAndScaledDownImageWithImage:(nullable UIImage *)image { if (![UIImage shouldDecodeImage:image]) { return image; } if (![UIImage shouldScaleDownImage:image]) { return [UIImage decodedImageWithImage:image]; } CGContextRef destContext; // autorelease the bitmap context and all vars to help system to free memory when there are memory warning. // on iOS7, do not forget to call [[SDImageCache sharedImageCache] clearMemory]; @autoreleasepool { CGImageRef sourceImageRef = image.CGImage; CGSize sourceResolution = CGSizeZero; sourceResolution.width = CGImageGetWidth(sourceImageRef); sourceResolution.height = CGImageGetHeight(sourceImageRef); float sourceTotalPixels = sourceResolution.width * sourceResolution.height; // Determine the scale ratio to apply to the input image // that results in an output image of the defined size. // see kDestImageSizeMB, and how it relates to destTotalPixels. float imageScale = kDestTotalPixels / sourceTotalPixels; CGSize destResolution = CGSizeZero; destResolution.width = (int)(sourceResolution.width*imageScale); destResolution.height = (int)(sourceResolution.height*imageScale); // current color space CGColorSpaceRef colorspaceRef = [UIImage colorSpaceForImageRef:sourceImageRef]; size_t bytesPerRow = kBytesPerPixel * destResolution.width; // Allocate enough pixel data to hold the output image. void* destBitmapData = malloc( bytesPerRow * destResolution.height ); if (destBitmapData == NULL) { return image; } // kCGImageAlphaNone is not supported in CGBitmapContextCreate. // Since the original image here has no alpha info, use kCGImageAlphaNoneSkipLast // to create bitmap graphics contexts without alpha info. destContext = CGBitmapContextCreate(destBitmapData, destResolution.width, destResolution.height, kBitsPerComponent, bytesPerRow, colorspaceRef, kCGBitmapByteOrderDefault|kCGImageAlphaNoneSkipLast); if (destContext == NULL) { free(destBitmapData); return image; } CGContextSetInterpolationQuality(destContext, kCGInterpolationHigh); // Now define the size of the rectangle to be used for the // incremental blits from the input image to the output image. // we use a source tile width equal to the width of the source // image due to the way that iOS retrieves image data from disk. // iOS must decode an image from disk in full width 'bands', even // if current graphics context is clipped to a subrect within that // band. Therefore we fully utilize all of the pixel data that results // from a decoding opertion by achnoring our tile size to the full // width of the input image. CGRect sourceTile = CGRectZero; sourceTile.size.width = sourceResolution.width; // The source tile height is dynamic. Since we specified the size // of the source tile in MB, see how many rows of pixels high it // can be given the input image width. sourceTile.size.height = (int)(kTileTotalPixels / sourceTile.size.width ); sourceTile.origin.x = 0.0f; // The output tile is the same proportions as the input tile, but // scaled to image scale. CGRect destTile; destTile.size.width = destResolution.width; destTile.size.height = sourceTile.size.height * imageScale; destTile.origin.x = 0.0f; // The source seem overlap is proportionate to the destination seem overlap. // this is the amount of pixels to overlap each tile as we assemble the ouput image. float sourceSeemOverlap = (int)((kDestSeemOverlap/destResolution.height)*sourceResolution.height); CGImageRef sourceTileImageRef; // calculate the number of read/write operations required to assemble the // output image. int iterations = (int)( sourceResolution.height / sourceTile.size.height ); // If tile height doesn't divide the image height evenly, add another iteration // to account for the remaining pixels. int remainder = (int)sourceResolution.height % (int)sourceTile.size.height; if(remainder) { iterations++; } // Add seem overlaps to the tiles, but save the original tile height for y coordinate calculations. float sourceTileHeightMinusOverlap = sourceTile.size.height; sourceTile.size.height += sourceSeemOverlap; destTile.size.height += kDestSeemOverlap; for( int y = 0; y < iterations; ++y ) { @autoreleasepool { sourceTile.origin.y = y * sourceTileHeightMinusOverlap + sourceSeemOverlap; destTile.origin.y = destResolution.height - (( y + 1 ) * sourceTileHeightMinusOverlap * imageScale + kDestSeemOverlap); sourceTileImageRef = CGImageCreateWithImageInRect( sourceImageRef, sourceTile ); if( y == iterations - 1 && remainder ) { float dify = destTile.size.height; destTile.size.height = CGImageGetHeight( sourceTileImageRef ) * imageScale; dify -= destTile.size.height; destTile.origin.y += dify; } CGContextDrawImage( destContext, destTile, sourceTileImageRef ); CGImageRelease( sourceTileImageRef ); } } CGImageRef destImageRef = CGBitmapContextCreateImage(destContext); CGContextRelease(destContext); if (destImageRef == NULL) { return image; } UIImage *destImage = [UIImage imageWithCGImage:destImageRef scale:image.scale orientation:image.imageOrientation]; CGImageRelease(destImageRef); if (destImage == nil) { return image; } return destImage; } } + (BOOL)shouldDecodeImage:(nullable UIImage *)image { // Prevent "CGBitmapContextCreateImage: invalid context 0x0" error if (image == nil) { return NO; } // do not decode animated images if (image.images != nil) { return NO; } CGImageRef imageRef = image.CGImage; CGImageAlphaInfo alpha = CGImageGetAlphaInfo(imageRef); BOOL anyAlpha = (alpha == kCGImageAlphaFirst || alpha == kCGImageAlphaLast || alpha == kCGImageAlphaPremultipliedFirst || alpha == kCGImageAlphaPremultipliedLast); // do not decode images with alpha if (anyAlpha) { return NO; } return YES; } + (BOOL)shouldScaleDownImage:(nonnull UIImage *)image { BOOL shouldScaleDown = YES; CGImageRef sourceImageRef = image.CGImage; CGSize sourceResolution = CGSizeZero; sourceResolution.width = CGImageGetWidth(sourceImageRef); sourceResolution.height = CGImageGetHeight(sourceImageRef); float sourceTotalPixels = sourceResolution.width * sourceResolution.height; float imageScale = kDestTotalPixels / sourceTotalPixels; if (imageScale < 1) { shouldScaleDown = YES; } else { shouldScaleDown = NO; } return shouldScaleDown; } + (CGColorSpaceRef)colorSpaceForImageRef:(CGImageRef)imageRef { // current CGColorSpaceModel imageColorSpaceModel = CGColorSpaceGetModel(CGImageGetColorSpace(imageRef)); CGColorSpaceRef colorspaceRef = CGImageGetColorSpace(imageRef); BOOL unsupportedColorSpace = (imageColorSpaceModel == kCGColorSpaceModelUnknown || imageColorSpaceModel == kCGColorSpaceModelMonochrome || imageColorSpaceModel == kCGColorSpaceModelCMYK || imageColorSpaceModel == kCGColorSpaceModelIndexed); if (unsupportedColorSpace) { colorspaceRef = CGColorSpaceCreateDeviceRGB(); CFAutorelease(colorspaceRef); } return colorspaceRef; } #elif SD_MAC + (nullable UIImage *)decodedImageWithImage:(nullable UIImage *)image { return image; } + (nullable UIImage *)decodedAndScaledDownImageWithImage:(nullable UIImage *)image { return image; } #endif @end
2881099/csredis
2,116
src/CSRedisCore/Internal/IO/RedisWriter.cs
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CSRedis.Internal.IO { class RedisWriter { const char Bulk = (char)RedisMessage.Bulk; const char MultiBulk = (char)RedisMessage.MultiBulk; const string EOL = "\r\n"; readonly RedisIO _io; public RedisWriter(RedisIO io) { _io = io; } public byte[] Prepare(RedisCommand command) { var parts = command.Command.Split(' '); int length = parts.Length + command.Arguments.Length; StringBuilder sb = new StringBuilder(); sb.Append(MultiBulk).Append(length).Append(EOL); foreach (var part in parts) sb.Append(Bulk).Append(_io.Encoding.GetByteCount(part)).Append(EOL).Append(part).Append(EOL); MemoryStream ms = new MemoryStream(); var data = _io.Encoding.GetBytes(sb.ToString()); ms.Write(data, 0, data.Length); foreach (var arg in command.Arguments) { if (arg != null && arg.GetType() == typeof(byte[])) { data = arg as byte[]; var data2 = _io.Encoding.GetBytes($"{Bulk}{data.Length}{EOL}"); ms.Write(data2, 0, data2.Length); ms.Write(data, 0, data.Length); ms.Write(new byte[] { 13, 10 }, 0, 2); } else { string str = String.Format(CultureInfo.InvariantCulture, "{0}", arg); data = _io.Encoding.GetBytes($"{Bulk}{_io.Encoding.GetByteCount(str)}{EOL}{str}{EOL}"); ms.Write(data, 0, data.Length); } //string str = String.Format(CultureInfo.InvariantCulture, "{0}", arg); //sb.Append(Bulk).Append(_io.Encoding.GetByteCount(str)).Append(EOL).Append(str).Append(EOL); } return ms.ToArray(); } } }
27182812/ChatGLM-LLaMA-chinese-insturct
11,984
src/transformers/models/speech_encoder_decoder/convert_speech_to_text_wav2vec2_seq2seq_original_to_pytorch.py
# coding=utf-8 # Copyright 2021 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 Wav2Vec2 checkpoint.""" import argparse import json import os import fairseq import torch from torch import nn from transformers import ( Speech2Text2Config, Speech2Text2ForCausalLM, Speech2Text2Tokenizer, SpeechEncoderDecoderConfig, SpeechEncoderDecoderModel, Wav2Vec2Config, Wav2Vec2FeatureExtractor, Wav2Vec2Model, logging, ) logging.set_verbosity_info() logger = logging.get_logger(__name__) MAPPING = { "post_extract_proj": "feature_projection.projection", "encoder.pos_conv.0": "encoder.pos_conv_embed.conv", "self_attn.k_proj": "encoder.layers.*.attention.k_proj", "self_attn.v_proj": "encoder.layers.*.attention.v_proj", "self_attn.q_proj": "encoder.layers.*.attention.q_proj", "self_attn.out_proj": "encoder.layers.*.attention.out_proj", "self_attn_layer_norm": "encoder.layers.*.layer_norm", "fc1": "encoder.layers.*.feed_forward.intermediate_dense", "fc2": "encoder.layers.*.feed_forward.output_dense", "final_layer_norm": "encoder.layers.*.final_layer_norm", "encoder.layer_norm": "encoder.layer_norm", "w2v_model.layer_norm": "feature_projection.layer_norm", "quantizer.weight_proj": "quantizer.weight_proj", "quantizer.vars": "quantizer.codevectors", "project_q": "project_q", "final_proj": "project_hid", "w2v_encoder.proj": "lm_head", "mask_emb": "masked_spec_embed", } TOP_LEVEL_KEYS = [ "lm_head", "quantizer.weight_proj", "quantizer.codevectors", "project_q", "project_hid", ] def set_recursively(hf_pointer, key, value, full_name, weight_type): for attribute in key.split("."): hf_pointer = getattr(hf_pointer, attribute) if weight_type is not None: hf_shape = getattr(hf_pointer, weight_type).shape else: hf_shape = hf_pointer.shape assert hf_shape == value.shape, ( f"Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be" f" {value.shape} for {full_name}" ) if weight_type == "weight": hf_pointer.weight.data = value elif weight_type == "weight_g": hf_pointer.weight_g.data = value elif weight_type == "weight_v": hf_pointer.weight_v.data = value elif weight_type == "bias": hf_pointer.bias.data = value else: hf_pointer.data = value logger.info(f"{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}.") def recursively_load_weights_wav2vec2(fairseq_model, hf_model): unused_weights = [] fairseq_dict = fairseq_model.state_dict() feature_extractor = hf_model.feature_extractor # if encoder has different dim to decoder -> use proj_weight proj_weight = None for name, value in fairseq_dict.items(): is_used = False if "conv_layers" in name: load_conv_layer( name, value, feature_extractor, unused_weights, hf_model.config.feat_extract_norm == "group", ) is_used = True elif name.split(".")[0] == "proj": proj_weight = fairseq_model.proj is_used = True else: for key, mapped_key in MAPPING.items(): if key in name or key.split("w2v_model.")[-1] == name.split(".")[0]: is_used = True if "*" in mapped_key: layer_index = name.split(key)[0].split(".")[-2] mapped_key = mapped_key.replace("*", layer_index) if "weight_g" in name: weight_type = "weight_g" elif "weight_v" in name: weight_type = "weight_v" elif "bias" in name: weight_type = "bias" elif "weight" in name: weight_type = "weight" else: weight_type = None set_recursively(hf_model, mapped_key, value, name, weight_type) continue if not is_used: unused_weights.append(name) logger.warning(f"Unused weights: {unused_weights}") return proj_weight def load_conv_layer(full_name, value, feature_extractor, unused_weights, use_group_norm): name = full_name.split("conv_layers.")[-1] items = name.split(".") layer_id = int(items[0]) type_id = int(items[1]) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( f"{full_name} has size {value.shape}, but" f" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found." ) feature_extractor.conv_layers[layer_id].conv.bias.data = value logger.info(f"Feat extract conv layer {layer_id} was initialized from {full_name}.") elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( f"{full_name} has size {value.shape}, but" f" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found." ) feature_extractor.conv_layers[layer_id].conv.weight.data = value logger.info(f"Feat extract conv layer {layer_id} was initialized from {full_name}.") elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( f"{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was" " found." ) feature_extractor.conv_layers[layer_id].layer_norm.bias.data = value logger.info(f"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.") elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( f"{full_name} has size {value.shape}, but" f" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found." ) feature_extractor.conv_layers[layer_id].layer_norm.weight.data = value logger.info(f"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.") else: unused_weights.append(full_name) def make_linear_from_emb(emb): vocab_size, emb_size = emb.weight.shape lin_layer = nn.Linear(vocab_size, emb_size, bias=False) lin_layer.weight.data = emb.weight.data return lin_layer def create_vocab_dict(dict_path): with open(dict_path, "r", encoding="utf-8") as f: lines = f.readlines() words = [line.split(" ")[0] for line in lines] num_words = len(words) vocab_dict = { "<s>": 0, "<pad>": 1, "</s>": 2, "<unk>": 3, } vocab_dict.update({k: v for k, v in zip(words, range(4, num_words + 4))}) return vocab_dict @torch.no_grad() def convert_wav2vec2_checkpoint( checkpoint_path, pytorch_dump_folder_path, dict_path, encoder_config_path, decoder_config_path, vocab_size, num_decoder_layers, ): """ Copy/paste/tweak model's weights to transformers design. """ encoder_config = Wav2Vec2Config.from_pretrained(encoder_config_path) decoder_config = Speech2Text2Config.from_pretrained( decoder_config_path, vocab_size=vocab_size, decoder_layers=num_decoder_layers, do_stable_layer_norm=True ) feature_extractor = Wav2Vec2FeatureExtractor( feature_size=1, sampling_rate=16000, padding_value=0, do_normalize=True, return_attention_mask=True, ) model, _, _ = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path], arg_overrides={"data": "/".join(dict_path.split("/")[:-1])} ) model = model[0].eval() # set weights for wav2vec2 encoder hf_encoder = Wav2Vec2Model(encoder_config) projection_layer = recursively_load_weights_wav2vec2(model.encoder, hf_encoder) hf_decoder = Speech2Text2ForCausalLM(decoder_config) missing_keys, unexpected_keys = hf_decoder.model.decoder.load_state_dict(model.decoder.state_dict(), strict=False) # set output linear layer unexpected_keys.remove("embed_out") hf_decoder.lm_head.weight = nn.Parameter(model.decoder.embed_out.detach()) # layer norm is init to identity matrix so leaving it is fine logger.warning(f"The following keys are missing when loading the decoder weights: {missing_keys}") logger.warning(f"The following keys are unexpected when loading the decoder weights: {unexpected_keys}") hf_wav2vec = SpeechEncoderDecoderModel(encoder=hf_encoder, decoder=hf_decoder) hf_wav2vec.config.tie_word_embeddings = False # add projection layer hf_wav2vec.enc_to_dec_proj.weight = nn.Parameter(projection_layer.weight) hf_wav2vec.enc_to_dec_proj.bias = nn.Parameter(projection_layer.bias) vocab_dict = create_vocab_dict(dict_path) with open(os.path.join(pytorch_dump_folder_path, "vocab.json"), "w") as fp: json.dump(vocab_dict, fp) tokenizer = Speech2Text2Tokenizer(os.path.join(pytorch_dump_folder_path, "vocab.json")) tokenizer.save_pretrained(pytorch_dump_folder_path) config = hf_wav2vec.config.to_dict() config["pad_token_id"] = tokenizer.pad_token_id config["bos_token_id"] = tokenizer.bos_token_id config["eos_token_id"] = tokenizer.eos_token_id config["tokenizer_class"] = "speech_to_text_2" config["feature_extractor_type"] = "wav2vec2" hf_wav2vec.config = SpeechEncoderDecoderConfig.from_dict(config) hf_wav2vec.save_pretrained(pytorch_dump_folder_path) feature_extractor.save_pretrained(pytorch_dump_folder_path) if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.") parser.add_argument("--checkpoint_path", default=None, type=str, help="Path to fairseq checkpoint") parser.add_argument("--dict_path", default=None, type=str, help="Path to dict of fine-tuned model") parser.add_argument( "--encoder_config_path", default="facebook/wav2vec2-large-lv60", type=str, help="Path to hf encoder wav2vec2 checkpoint config", ) parser.add_argument( "--decoder_config_path", default="facebook/s2t-small-mustc-en-fr-st", type=str, help="Path to hf decoder s2t checkpoint config", ) parser.add_argument("--vocab_size", default=10224, type=int, help="Vocab size of decoder") parser.add_argument("--num_decoder_layers", default=7, type=int, help="Number of decoder layers") args = parser.parse_args() convert_wav2vec2_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.dict_path, encoder_config_path=args.encoder_config_path, decoder_config_path=args.decoder_config_path, vocab_size=args.vocab_size, num_decoder_layers=args.num_decoder_layers, )
2881099/csredis
5,086
src/CSRedisCore/Internal/IO/RedisIO.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Security; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; namespace CSRedis.Internal.IO { class RedisIO : IDisposable { readonly RedisWriter _writer; RedisReader _reader; RedisPipeline _pipeline; Stream _stream; object _streamLock = new object(); public Stream Stream => GetOrThrow(_stream); public RedisWriter Writer => _writer; public RedisReader Reader => GetOrThrow(_reader); public Encoding Encoding { get; set; } public RedisPipeline Pipeline => GetOrThrow(_pipeline); public bool IsPipelined => _pipeline == null ? false : _pipeline.Active; public RedisIO() { _writer = new RedisWriter(this); Encoding = new UTF8Encoding(false); } public void SetStream(Stream stream) { if (_stream != null) { try { _stream.Close(); } catch { } try { _stream.Dispose(); } catch { } } _stream = stream; _reader = new RedisReader(this); _pipeline = new RedisPipeline(this); } #if net40 #else async public Task<int> WriteAsync(RedisCommand command) { var data = _writer.Prepare(command); await Stream.WriteAsync(data, 0, data.Length); return data.Length; //var tcs = new TaskCompletionSource<int>(); //lock (_streamLock) //{ // Stream.BeginWrite(data, 0, data.Length, asyncResult => // { // try // { // _stream.EndWrite(asyncResult); // tcs.TrySetResult(data.Length); // } // catch (Exception ex) // { // tcs.TrySetException(ex); // } // }, null); // Stream.Flush(); //} //return tcs.Task; } #endif public void Write(byte[] data) { lock (_streamLock) { Stream.Write(data, 0, data.Length); Stream.Flush(); } } public void Write(Stream stream) { lock (_streamLock) { stream.CopyTo(Stream); Stream.Flush(); } } public int ReadByte() { lock (_streamLock) return Stream.ReadByte(); } public int Read(byte[] data, int offset, int count) { lock (_streamLock) return Stream.Read(data, offset, count); } public Byte[] ReadAll() { var ns = _stream as NetworkStream; if (ns != null) { using (var ms = new MemoryStream()) { try { var data = new byte[1024]; while (ns.DataAvailable && ns.CanRead) { int numBytesRead = 0; lock (_streamLock) numBytesRead = ns.Read(data, 0, data.Length); if (numBytesRead <= 0) break; ms.Write(data, 0, numBytesRead); if (numBytesRead < data.Length) break; } } catch { } return ms.ToArray(); } } var ss = _stream as SslStream; if (ss != null) { using (var ms = new MemoryStream()) { try { var data = new byte[1024]; while (ss.CanRead) { int numBytesRead = 0; lock (_streamLock) numBytesRead = ss.Read(data, 0, data.Length); if (numBytesRead <= 0) break; ms.Write(data, 0, numBytesRead); if (numBytesRead < data.Length) break; } } catch { } return ms.ToArray(); } } return new byte[0]; } public void Dispose() { if (_pipeline != null) _pipeline.Dispose(); if (_stream != null) { try { _stream.Close(); } catch { } try { _stream.Dispose(); } catch { } } } static T GetOrThrow<T>(T obj) { if (obj == null) throw new RedisClientException("Connection was not opened"); return obj; } } }
2881099/dotnetGen_mysql
9,121
README.md
# .NETCore 2.1 + Mysql 生成器 作者面向web应用开发13年,在项目实践与学习中去旧换新,吸取优点,从高质量、强规范、快速开发方向累积,形成生成器工具减少项目后端开发难度。 > navicat 模型工具创建和管理ER图,从数据库导入/同步结构到数据库,后使用本生成器一键同步c#实体,以及各种规范的花式和你想象不到的语法,支持缓存,支持数据库99%类型,挖掘数据库特性,避免过多重复劳动和不规范、不健壮的代码。 优势: * 1、根据主键、唯一键、外键(1对1,1对多,多对多)生成功能丰富的数据库 SDK; * 2、严格把控数据库,避免随意创建表或字段,有标准的ER图数据库规范; * 3、统一规范数据库操作类与方法(相比EF太随意的用法好管理很多),一条心堆业务; * 4、优化每一个细节,决不允许低级错误干扰我们的业务逻辑(相比ORM,生成的代码更专注); 适合场境: * 1、新项目开发,只管设计数据ER图,无须考虑db相关代码; * 2、老项目数据库访问方式不堪入目的,表数量越多收益越大; [下载生成器winform客户端](https://files.cnblogs.com/files/kellynic/%E7%94%9F%E6%88%90%E5%99%A8mysql.zip),推荐安装命令工具 dotnet tool install -g GenMy * [.NETCore 快速开发做一个简易商城](https://www.cnblogs.com/kellynic/p/9712483.html) * [.NETCore 基于 dbfirst 体验快速开发项目](https://www.cnblogs.com/kellynic/p/9706082.html) * [新人指导教学](https://pan.baidu.com/s/1gx8ClLF7AzL06j2D43kBWQ) https://pan.baidu.com/s/1gx8ClLF7AzL06j2D43kBWQ 密码:lr6n 学习QQ群:8578575 ---- ## 在已有的项目上生成 ```shell dotnet new mvc GenMy 数据库ip[:3306] -U 登陆名 -P 密码 -D 数据库1[,数据库2] -N 命名空间 ``` ## 生成完整的模块化解决方案 ```shell GenMy 数据库ip[:3306] -U 登陆名 -P 密码 -D 数据库1[,数据库2] -N 命名空间 -R -S -A ``` dotnetGen 保持相同的开发与使用习惯,实现了面向 mysql、SQLServer、PostgreSQL 三种数据库快速开发,也可混合使用。 | <font color=gray>功能对比</font> | [dotnetGen_mysql](https://github.com/2881099/dotnetGen_mysql) | [dotnetGen_sqlserver](https://github.com/2881099/dotnetGen_sqlserver) | [dotnetGen_postgresql](https://github.com/2881099/dotnetGen_postgresql) | | ----------------: | --------------: | -------------------: | -------------------: | | windows | √ | √ | √ | | linux | √ | √ | √ | | 连接池 | √ | √ | √ | | 事务 | √ | √ | √ | | 多数据库 | √ | - | - | | 读写分离 | √ | √ | √ | | 表 | √ | √ | √ | | 表关系(1对1) | √ | √ | √ | | 表关系(1对多) | √ | √ | √ | | 表关系(多对多) | √ | √ | √ | | 表主键 | √ | √ | √ | | 表唯一键 | √ | √ | √ | | 存储过程 | - | √ | - | | 视图 | √ | √ | √ | | 软删除 | √ | √ | √ | | 类型映射 | √ | √ | √ | | 枚举 | √ | - | √ | | 自定义类型 | - | - | √ | | gis | √ | - | √ | | 数组 | - | - | √ | | 字典 | - | - | √ | | xml | - | - | - | | json | - | - | √ | | 缓存 | √ | √ | √ | | 命令行生成 | √ | √ | √ | | RESTful | √ | √ | √ | | 后台管理功能 | √ | √ | √ | ### 测试数据库 ![](20170825201740.png) ```sql SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for song -- ---------------------------- DROP TABLE IF EXISTS `song`; CREATE TABLE `song` ( `id` int(11) NOT NULL AUTO_INCREMENT, `title` varchar(128) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '歌名', `url` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '地址', `create_time` datetime DEFAULT NULL COMMENT '创建时间', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- ---------------------------- -- Table structure for song_tag -- ---------------------------- DROP TABLE IF EXISTS `song_tag`; CREATE TABLE `song_tag` ( `song_id` int(11) NOT NULL COMMENT '歌曲', `tag_id` int(11) NOT NULL COMMENT '标签', PRIMARY KEY (`song_id`,`tag_id`), KEY `fk_song_tag_tag_1` (`tag_id`), CONSTRAINT `fk_song_tag_song_1` FOREIGN KEY (`song_id`) REFERENCES `song` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_song_tag_tag_1` FOREIGN KEY (`tag_id`) REFERENCES `tag` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- ---------------------------- -- Table structure for tag -- ---------------------------- DROP TABLE IF EXISTS `tag`; CREATE TABLE `tag` ( `id` int(11) NOT NULL AUTO_INCREMENT, `parent_id` int(11) DEFAULT NULL COMMENT '父标签', `name` varchar(128) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '名称', PRIMARY KEY (`id`), KEY `fk_tag_tag_1` (`parent_id`), CONSTRAINT `fk_tag_tag_1` FOREIGN KEY (`parent_id`) REFERENCES `tag` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- ---------------------------- -- Table structure for topic -- ---------------------------- DROP TABLE IF EXISTS `topic`; CREATE TABLE `topic` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `title` varchar(255) DEFAULT NULL COMMENT '标题', `cardtype` enum('视频','图文01','图文02','链接') DEFAULT NULL COMMENT '卡片类型', `carddata` text COMMENT '卡片渲染数据', `content` text COMMENT '内容', `clicks` bigint(20) unsigned DEFAULT NULL COMMENT '点击次数', `create_time` datetime DEFAULT NULL COMMENT '创建时间', `update_time` datetime DEFAULT NULL COMMENT '修改时间', `order_time` datetime DEFAULT NULL COMMENT '排序时间', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; ``` # 模块化框架目录结构介绍 ## Module 所有业务接口约定在 Module 划分并行开发,互不依赖 Module/Admin 生成的后台管理模块,http://localhost:5001/module/Admin 可访问 Module/Test 生成的测试模块 ## WebHost WebHost 编译的时候,会将 Module/* 编译结果复制到当前目录 WebHost 只当做主引擎运行时按需加载相应的 Module WebHost 依赖 npm ,请安装 node,并在目录执行 npm install WebHost 依赖 gulp-cli,请执行全局安装 npm install --global gulp-cli 运行步骤: 1、打开 vs 右击 Module 目录全部编译; 2、cd WebHost && npm install && dotnet build && dotnet run ## Infrastructure Module 里面每个子模块的依赖所需 #### xx.db 包含一切数据库操作的封装 xx.Model(实体映射) xx.BLL(静态方法封装) xx.DAL(数据访问) 生成名特征取数据库名首字母大写(如: 表 test 对应 xx.Model.TestInfo、xx.BLL.Test、xx.DAL.Test) 数据库设计命名习惯:所有命名(username, stats_click)、外键字段(user_id) 仅支持主键作为外键,不支持组合字段,不支持唯一键作为外键 修改数据库后,双击“./GenMy只更新db.bat”可快速覆盖,所有类都使用 partial,方便扩展亦不会被二次生成覆盖 # 数据库相关方法 ## 添加记录 ```csharp // 如有 create_time 字段并且类型为日期,内部会初始化 TestInfo newitem1 = Test.Insert(Title: "添加的标题", Content: "这是一段添加的内容"); TestInfo newitem2 = Test.Insert(new TestInfo { Title = "添加的标题", Content = "这是一段添加的内容" }); ``` ## 添加记录(批量) ```csharp List<TestInfo> newitems1 = Test.Insert(new [] { new TestInfo { Title = "添加的标题1", Content = "这是一段添加的内容1" }, new TestInfo { Title = "添加的标题2", Content = "这是一段添加的内容2" } }); ``` ## 更新记录 ```csharp // 更新 id = 1 所有字段 Test.Update(new TestInfo { Id: 1, Title = "添加的标题", Content = "这是一段添加的内容", Clicks = 1 }); // 更新 id = 1 指定字段 Test.UpdateDiy(1).SetTitle("修改后的标题").SetContent("修改后的内容").SetClicks(1).ExecuteNonQuery(); // update 表名 set clicks = clicks + 1 where id = 1 Test.UpdateDiy(1).SetClicksIncrement(1).ExecuteNonQuery(); // 使用实体层修改 new TestInfo { Id = 1 }.UpdateDiy.SetClicksIncrement(1).ExecuteNonQuery(); ``` ## 更新记录(批量) ```csharp //先查找 clicks 在 0 - 100 的记录 List<TestInfo> newitems1 = Test.Select.WhereClicksRange(0, 100).ToList(); // update 表名 set clicks = clicks + 1 where id in (newitems1所有id) newitems1.UpdateDiy().SetClicksIncrement(1).ExecuteNonQuery(); ``` > 警告:批量更新的方法,在事务中使用会导致死锁 ## 删除记录 ```csharp // 删除 id = 1 的记录 Test.Delete(1); ``` ## 按主键/唯一键获取单条记录 > appsettings可配置缓存时间,以上所有增、改、删都会删除缓存保障同步 ```csharp //按主键获取 UserInfo user1 = User.GetItem(1); //按唯一键 UserInfo user2 = User.GetItemByUsername("2881099@qq.com"); // 返回 null 或 UserInfo ``` ## 查询(核心) ```csharp //BLL.表名.Select 是一个链式查询对象,几乎支持所有查询,包括 group by、inner join等等,最终 ToList ToOne Aggregate 执行 sql List<UserInfo> users1 = User.Select.WhereUsername("2881099@qq.com").WherePassword("******").WhereStatus(正常).ToList(); //返回 new List<UserInfo>() 或 有元素的 List,永不返回 null //返回指定列,返回List<元组> var users2 = User.Select.WhereStatus(正常).Aggregate<(int id, string title)>("id,title"); //多表查询,只返回 a 表字段 var users3 = User.Select.Where(a => a.Obj_user_group.Id == a.Group_id).ToList(); //join查询,返回 a, b 表字段 ,b 表结果填充至 a.Obj_user_group 对象,类似 ef.Include var users4 = User.Select.InnerJoin(a => a.Obj_user_group.Id == a.Group_id).ToList(); //分组查询 var users5 = User.Select.GroupBy("group_id").Aggregate<(int groupId, int count)>("group_id, count(1)"); //等等... ``` ## 事务 ```csharp //错误会回滚,事务内支持所有生成的同步方法(不支持生成对应的Async方法) var user = User.GetItem(1); SqlHelper.Transaction(() => { if (user.UpdateDiy.SetAmountIncrement(-num).Where("amount > {0}", num).ExecuteNonQuery() <= 0) throw new Exception("余额不足"); var order = user.AddOrder(Amount: 1, Count: num, Count_off: num); }); ``` ## 缓存 1、根据主键、唯一键缓存 BLL GetItem、GetItemBy唯一键,使用了默认缓存策略180秒,用来缓存一条记录,db 层自动维护缓存同步,例如: ```csharp //只有第一次查询了数据库,后面99次读取redis的缓存值 UserInfo u; for (var a = 0; a < 100; a++) u = User.GetItemByUsername("2881099@qq.com"); //执行类似以下的数据变动方法,会删除redis对应的缓存 u.UpdateDiy.SetLogin_time(DateTime.Now).ExecuteNonQuery(); ``` 2、缓存一个查询结果 BLL Select.ToList(10, "cache_key"),将查询结果缓存10秒,需要手工删除redis对应的键 ## 读写分离 内置实现读和写分离,一个【主库】多个【从库】,【从库】的查询策略为随机方式。 若某【从库】发生故障,将切换到其他可用【从库】,若已全部不可用则使用【主库】查询。 出现故障【从库】被隔离起来间隔性的检查可用状态,以待恢复。 ```csharp Topic.Select.WhereId(1).ToOne(); //读【从库】(默认) Topic.Select.Master().WhereId(1).ToOne(); //读【主库】 ``` #### 测试 > ![](https://www.cnblogs.com/images/cnblogs_com/kellynic/133561/o_1111.jpg) > ![](https://www.cnblogs.com/images/cnblogs_com/kellynic/133561/o_2222.png) > ![](https://www.cnblogs.com/images/cnblogs_com/kellynic/133561/o_3333.png) # 生成规则 ## 不会生成 * 没有主键,不会生成 增、改、删 方法 * 有自增字段,不会生成 批量 Insert 方法 ## 特别规则 * 字段类型 point,会生成 > 表.Select.Where字段MbrContains(查找地理位置多少米范围内的记录,距离由近到远排序) * 字段类型 string 相关并且长度 <= 300,会生成 > 表.Select.Where字段Like * 99%的数据类型被支持
2881099/csredis
6,812
src/CSRedisCore/Internal/IO/RedisReader.cs
using System; using System.Globalization; using System.IO; using System.Text; namespace CSRedis.Internal.IO { internal partial class RedisReader { readonly RedisIO _io; public RedisReader(RedisIO io) { _io = io; } public RedisMessage ReadType() { RedisMessage type = (RedisMessage)_io.ReadByte(); //Console.WriteLine($"ReadType: {type}"); if (type == RedisMessage.Error) throw new RedisException(ReadStatus(false)); return type; } public string ReadStatus(bool checkType = true) { if (checkType) ExpectType(RedisMessage.Status); return ReadLine(); } public long ReadInt(bool checkType = true) { if (checkType) ExpectType(RedisMessage.Int); string line = ReadLine(); return Int64.Parse(line.ToString(), NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat); } public object ReadBulk(bool checkType = true, bool asString = false) { if (asString) return ReadBulkString(checkType); else return ReadBulkBytes(checkType); } public byte[] ReadBulkBytes(bool checkType = true) { if (checkType) ExpectType(RedisMessage.Bulk); int size = (int)ReadInt(false); if (size == -1) return null; byte[] bulk = new byte[size]; int bytes_read = 0; int bytes_remaining = size; while (bytes_read < size) bytes_read += _io.Read(bulk, bytes_read, size - bytes_read); //Console.WriteLine($"ReadBulkBytes1: {Encoding.UTF8.GetString(bulk)}"); ExpectBytesRead(size, bytes_read); ReadCRLF(); return bulk; } public void ReadBulkBytes(Stream destination, int bufferSize, bool checkType = true) { if (checkType) ExpectType(RedisMessage.Bulk); int size = (int)ReadInt(false); if (size == -1) return; byte[] buffer = new byte[bufferSize]; int position = 0; while (position < size) { int bytes_to_buffer = Math.Min(buffer.Length, size - position); int bytes_read = 0; while (bytes_read < bytes_to_buffer) { int bytes_to_read = Math.Min(bytes_to_buffer - bytes_read, size - position); bytes_read += _io.Read(buffer, bytes_read, bytes_to_read); } position += bytes_read; destination.Write(buffer, 0, bytes_read); } //Console.WriteLine($"ReadBulkBytes2: {Encoding.UTF8.GetString(buffer)}"); ExpectBytesRead(size, position); ReadCRLF(); } public string ReadBulkString(bool checkType = true) { byte[] bulk = ReadBulkBytes(checkType); if (bulk == null) return null; return _io.Encoding.GetString(bulk); } public void ExpectType(RedisMessage expectedType) { RedisMessage type = ReadType(); if ((int)type == -1) { var alldata = _io.ReadAll(); try { _io.Dispose(); } catch { } throw new EndOfStreamException($"Unexpected end of stream; expected type '{expectedType}'; data = '{Encoding.UTF8.GetString(alldata)}'"); } if (type != expectedType) throw new RedisProtocolException($"Unexpected response type: {type} (expecting {expectedType})"); } public void ExpectMultiBulk(long expectedSize) { ExpectType(RedisMessage.MultiBulk); ExpectSize(expectedSize); } public void ExpectSize(long expectedSize) { long size = ReadInt(false); ExpectSize(expectedSize, size); } public void ExpectSize(long expectedSize, long actualSize) { if (actualSize != expectedSize) throw new RedisProtocolException("Expected " + expectedSize + " elements; got " + actualSize); } public void ReadCRLF() // TODO: remove hardcoded { var r = _io.ReadByte(); var n = _io.ReadByte(); //Console.WriteLine($"ReadCRLF: {r} {n}"); if (r != (byte)13 && n != (byte)10) throw new RedisProtocolException(String.Format("Expecting CRLF; got bytes: {0}, {1}", r, n)); } public object[] ReadMultiBulk(bool checkType = true, bool bulkAsString = false) { if (checkType) ExpectType(RedisMessage.MultiBulk); long count = ReadInt(false); if (count == -1) return null; object[] lines = new object[count]; for (int i = 0; i < count; i++) lines[i] = Read(bulkAsString); return lines; } public object Read(bool bulkAsString = false) { RedisMessage type = ReadType(); switch (type) { case RedisMessage.Bulk: return ReadBulk(false, bulkAsString); case RedisMessage.Int: return ReadInt(false); case RedisMessage.MultiBulk: return ReadMultiBulk(false, bulkAsString); case RedisMessage.Status: return ReadStatus(false); case RedisMessage.Error: throw new RedisException(ReadStatus(false)); default: throw new RedisProtocolException("Unsupported response type: " + type); } } string ReadLine() { if (!_io.Stream.CanRead) { return string.Empty; } StringBuilder stringBuilder = new StringBuilder(); bool flag = false; int c = -1; //Judgment _io.ReadByte() of return -1 while ((c = _io.ReadByte()) != -1) { if ((char)c == '\r') { flag = true; continue; } //Judgment '\r\n',or only '\n' if (((char)c == '\n') || ((char)c == '\n' && flag)) { break; } stringBuilder.Append((char)c); flag = false; } return stringBuilder.ToString(); } void ExpectBytesRead(long expecting, long actual) { if (actual != expecting) throw new RedisProtocolException(String.Format("Expecting {0} bytes; got {1} bytes", expecting, actual)); } } }
2881099/FreeIM
4,875
readme.md
# FreeIM v2.0.0 - 调整:已将 ClientId Guid 改为 long; - 修复:JoinChan/LeaveChan 数量统计问题; - 增加:SendBroadcastMessage 广播消息; - 优化:SendChanMessage 性能; FreeIM 使用 websocket 协议实现简易、高性能(单机支持5万+连接)、集群即时通讯组件,支持点对点通讯、群聊通讯、上线下线事件消息等众多实用性功能。 `ImCore` 已正式改名为 `FreeIM`。 使用场景:好友聊天、群聊天、直播间、实时评论区、游戏。 *接受定制项目开发,详细请联系作者* 如果对本项目感兴趣,欢迎加入 FreeSql QQ讨论群:8578575 > dotnet add package FreeIM ## ImServer 服务端 ```csharp public void Configure(IApplicationBuilder app) { app.UseFreeImServer(new ImServerOptions { Redis = new FreeRedis.RedisClient("127.0.0.1:6379,poolsize=5"), Servers = new[] { "127.0.0.1:6001" }, //集群配置 Server = "127.0.0.1:6001" }); } //dotnet run --urls=http://127.0.0.1:6001 ``` > 一套永远不需要迭代更新的 `ImServer` 服务端,支持 .NET8.0 AOT 发布(C++运行时)。 ## WebApi 业务端 ```csharp public void Configure(IApplicationBuilder app) { //... ImHelper.Initialization(new ImClientOptions { Redis = new FreeRedis.RedisClient("127.0.0.1:6379,poolsize=5"), Servers = new[] { "127.0.0.1:6001" } }); ImHelper.EventBus( t => Console.WriteLine(t.clientId + "上线了"), t => Console.WriteLine(t.clientId + "下线了")); } ``` | ImHelper方法 | 参数 | 描述 | | - | - | - | | PrevConnectServer | (clientId, string) | 在终端准备连接 websocket 前调用 | | SendMessage | (发送者, 接收者, 消息内容, 是否回执) | 发送消息 | | GetClientListByOnline | - | 返回所有在线clientId | | HasOnline | clientId | 判断客户端是否在线 | | ForceOffline | clientId | 强制下线 | | EventBus | (上线委托, 离线委托) | socket上线与下线事件 | | 频道 | 参数 | 描述 | | - | - | - | | JoinChan | (clientId, 频道名) | 加入 | | LeaveChan | (clientId, 频道名) | 离开 | | GetChanClientList | (频道名) | 获取频道所有clientId | | GetChanList | - | 获取所有频道和在线人数 | | GetChanListByClientId | (clientId) | 获取用户参与的所有频道 | | GetChanOnline | (频道名) | 获取频道的在线人数 | | SendChanMessage | (clientId, 频道名, 消息内容) | 发送消息,所有在线的用户将收到消息 | | SendBroadcastMessage | (clientId, 频道名, 消息内容) | 发送广播消息 | - clientId 应该与用户id相同,或者关联; - 频道适用临时的群聊需求,如聊天室、讨论区; > ImHelper 支持 .NetFramework 4.5+、.NetStandard 2.0 ## Html5 终端 终端连接 websocket 前,应该先请求 `WebApi` 获得授权过的地址(ImHelper.PrevConnectServer),伪代码: ```javascript ajax('/prev-connect-imserver', function(data) { var url = data; //此时的值:ws://127.0.0.1:6001/ws?token=xxxxx var sock = new WebSocket(url); sock.onmessage = function (e) { //... }; }) ``` ## 项目演示 运行环境:.NET6.0 + redis-server 2.8+ > cd ImServer && dotnet run --urls=http://*:6001 > cd WebApi && dotnet run 打开多个浏览器,分别访问 http://127.0.0.1:5000 发送群消息 ![image](https://user-images.githubusercontent.com/16286519/187127834-d3bb2339-8a9b-4d8c-a0ed-3f1d35b4c7c3.png) ## 分析痛点 协议痛点:如果浏览器使用 websocket 协议,iOS 使用其他协议,协议不一致将很难维护。 职责痛点:IM 的系统一般涉及【我的好友】、【我的群】、【历史消息】等等。。 `ImServer` 与 `WebApi`(业务方) 该保持何种关系呢? 用户A向好友B发送消息,分析一下: * 需要判断B是否为A好友; * 需要判断A是否有权限; 获取历史聊天记录,多个 `终端` websocket.send('gethistory'),再在 onmessage 定位回调处理,多麻烦啊? 诸如此类业务判断会很复杂,使用 `ImServer` 做业务逻辑,最终 `ImServer` 和 `终端` 都将变成巨无霸难以维护。 ## 设计思路 `终端`(如浏览器/小程序/iOS/android) 统一使用 websocket 连接 `ImServer`; `ImServer`(支持集群)根据 clientId 分区管理 websocket 连接; `WebApi` 使用 ImHelper 调用方法(如:SendMessage、群聊相关方法),将数据推至 Redis chan; `ImServer` 订阅 Redis chan,收到消息后向 `终端` 推送消息; - 缓解了并发推送消息过多的问题; - 解决了连接数过多的问题; - 解耦了业务和通讯,架构更加清淅; * `ImServer` 充当消息转发,连接维护,代码万年不变、且不需要重启维护 * `WebApi` 负责所有业务 举例1、用户A向B发送消息:`终端`A ajax -> `WebApi` -> `ImServer` -> `终端`B websocket.onmessage; 举例2、获取历史聊天记录:`终端` 请求 `WebApi`(业务方) 接口,返回json(历史消息)。 举例3、A向B发文件的例子: - A向 `WebApi` 传文件 - `WebApi` 通知 `ImServer`,ImHelper.SendMessage(B, "A正在给传送文件...") - B收到消息,A正在给传送文件... - `WebApi` 文件接收完成时通知 `ImServer`,ImHelper.SendMessage(B, "A文件传输完毕(含文件链接)") - B收到消息,A文件传输完毕(含文件链接) FreeIM 强依赖 redis-server 组件功能: - 集成了 redis 轻量级的订阅发布功能,实现消息缓冲发送,后期可更换为其他技术 - 使用了 redis 存储一些关系数据,如在线 clientId、频道信息、授权信息等 ## 集群分区 单个 `ImServer` 实例支持多少个客户端连接,3万?如果在线用户有10万人,怎么办??? 部署 4 个 `ImServer`: - `ImServer`1 订阅 redisChan1 - `ImServer`2 订阅 redisChan2 - `ImServer`3 订阅 redisChan3 - `ImServer`4 订阅 redisChan4 `WebApi`(业务方) 根据接收方的 clientId 后四位 16 进制与节点总数取模,定位到对应的 redisChan,进行 redis->publish 操作将消息定位到相应的 `ImServer`。 每个 `ImServer` 管理着对应的终端连接,当接收到 redis 订阅消息后,向对应的终端连接推送数据。 ## 事件消息 IM 系统比较常用的有上线、下线,在 `ImServer` 层才能准确捕捉事件,但业务代码不合适在这上面编写了。 此时采用 redis 发布订阅,将上线、下线等事件向指定频道发布,`WebApi`(业务方) 通过 ImHelper.EventBus 方法进行订阅捕捉。 ![image](https://user-images.githubusercontent.com/16286519/62150466-a46e3980-b330-11e9-86f3-d050160f0913.png) ## 有感而发 为什么说 SignalR 不合适做 IM? 1、IM 的特点必定是长连接,轮训的功能用不上; 2、因为 SignalR 是双工通讯的设计,`终端` 使用 hub.invoke 发送命令给 SignalR 服务端处理业务,适合用来代替 ajax 减少 http 请求数量; 3、过多使用 hub,SignalR 服务端会被业务入侵,业务变化频繁后不得不重新发布版本,每次部署所有终端都会断开连接,遇到5分钟发一次业务补丁的时候,类似离线和上线提示好友的功能就无法实现; FreeIM 业务和推送分离设计,`终端` 连接永不更新重启 `ImServer` ,业务代码全部在 `WebApi` 编写,因此重启 `WebApi` 不会造成连接断开。 ## 💕 Donation (捐赠) > 感谢你的打赏 - [Alipay](https://www.cnblogs.com/FreeSql/gallery/image/338860.html) - [WeChat](https://www.cnblogs.com/FreeSql/gallery/image/338859.html) ## 🗄 License (许可证) [MIT](LICENSE)
2877025939/PlanADScrollView
11,180
PlanADScrollView/PlanADScrollView/SDWebImage/SDWebImage/UIButton+WebCache.h
/* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import "SDWebImageCompat.h" #if SD_UIKIT #import "SDWebImageManager.h" /** * Integrates SDWebImage async downloading and caching of remote images with UIButtonView. */ @interface UIButton (WebCache) /** * Get the current image URL. */ - (nullable NSURL *)sd_currentImageURL; #pragma mark - Image /** * Get the image URL for a control state. * * @param state Which state you want to know the URL for. The values are described in UIControlState. */ - (nullable NSURL *)sd_imageURLForState:(UIControlState)state; /** * Set the imageView `image` with an `url`. * * The download is asynchronous and cached. * * @param url The url for the image. * @param state The state that uses the specified title. The values are described in UIControlState. */ - (void)sd_setImageWithURL:(nullable NSURL *)url forState:(UIControlState)state; /** * Set the imageView `image` with an `url` and a placeholder. * * The download is asynchronous and cached. * * @param url The url for the image. * @param state The state that uses the specified title. The values are described in UIControlState. * @param placeholder The image to be set initially, until the image request finishes. * @see sd_setImageWithURL:placeholderImage:options: */ - (void)sd_setImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder; /** * Set the imageView `image` with an `url`, placeholder and custom options. * * The download is asynchronous and cached. * * @param url The url for the image. * @param state The state that uses the specified title. The values are described in UIControlState. * @param placeholder The image to be set initially, until the image request finishes. * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. */ - (void)sd_setImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options; /** * Set the imageView `image` with an `url`. * * The download is asynchronous and cached. * * @param url The url for the image. * @param state The state that uses the specified title. The values are described in UIControlState. * @param completedBlock A block called when operation has been completed. This block has no return value * and takes the requested UIImage as first parameter. In case of error the image parameter * is nil and the second parameter may contain an NSError. The third parameter is a Boolean * indicating if the image was retrieved from the local cache or from the network. * The fourth parameter is the original image url. */ - (void)sd_setImageWithURL:(nullable NSURL *)url forState:(UIControlState)state completed:(nullable SDExternalCompletionBlock)completedBlock; /** * Set the imageView `image` with an `url`, placeholder. * * The download is asynchronous and cached. * * @param url The url for the image. * @param state The state that uses the specified title. The values are described in UIControlState. * @param placeholder The image to be set initially, until the image request finishes. * @param completedBlock A block called when operation has been completed. This block has no return value * and takes the requested UIImage as first parameter. In case of error the image parameter * is nil and the second parameter may contain an NSError. The third parameter is a Boolean * indicating if the image was retrieved from the local cache or from the network. * The fourth parameter is the original image url. */ - (void)sd_setImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder completed:(nullable SDExternalCompletionBlock)completedBlock; /** * Set the imageView `image` with an `url`, placeholder and custom options. * * The download is asynchronous and cached. * * @param url The url for the image. * @param state The state that uses the specified title. The values are described in UIControlState. * @param placeholder The image to be set initially, until the image request finishes. * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. * @param completedBlock A block called when operation has been completed. This block has no return value * and takes the requested UIImage as first parameter. In case of error the image parameter * is nil and the second parameter may contain an NSError. The third parameter is a Boolean * indicating if the image was retrieved from the local cache or from the network. * The fourth parameter is the original image url. */ - (void)sd_setImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options completed:(nullable SDExternalCompletionBlock)completedBlock; #pragma mark - Background image /** * Set the backgroundImageView `image` with an `url`. * * The download is asynchronous and cached. * * @param url The url for the image. * @param state The state that uses the specified title. The values are described in UIControlState. */ - (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url forState:(UIControlState)state; /** * Set the backgroundImageView `image` with an `url` and a placeholder. * * The download is asynchronous and cached. * * @param url The url for the image. * @param state The state that uses the specified title. The values are described in UIControlState. * @param placeholder The image to be set initially, until the image request finishes. * @see sd_setImageWithURL:placeholderImage:options: */ - (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder; /** * Set the backgroundImageView `image` with an `url`, placeholder and custom options. * * The download is asynchronous and cached. * * @param url The url for the image. * @param state The state that uses the specified title. The values are described in UIControlState. * @param placeholder The image to be set initially, until the image request finishes. * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. */ - (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options; /** * Set the backgroundImageView `image` with an `url`. * * The download is asynchronous and cached. * * @param url The url for the image. * @param state The state that uses the specified title. The values are described in UIControlState. * @param completedBlock A block called when operation has been completed. This block has no return value * and takes the requested UIImage as first parameter. In case of error the image parameter * is nil and the second parameter may contain an NSError. The third parameter is a Boolean * indicating if the image was retrieved from the local cache or from the network. * The fourth parameter is the original image url. */ - (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url forState:(UIControlState)state completed:(nullable SDExternalCompletionBlock)completedBlock; /** * Set the backgroundImageView `image` with an `url`, placeholder. * * The download is asynchronous and cached. * * @param url The url for the image. * @param state The state that uses the specified title. The values are described in UIControlState. * @param placeholder The image to be set initially, until the image request finishes. * @param completedBlock A block called when operation has been completed. This block has no return value * and takes the requested UIImage as first parameter. In case of error the image parameter * is nil and the second parameter may contain an NSError. The third parameter is a Boolean * indicating if the image was retrieved from the local cache or from the network. * The fourth parameter is the original image url. */ - (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder completed:(nullable SDExternalCompletionBlock)completedBlock; /** * Set the backgroundImageView `image` with an `url`, placeholder and custom options. * * The download is asynchronous and cached. * * @param url The url for the image. * @param placeholder The image to be set initially, until the image request finishes. * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. * @param completedBlock A block called when operation has been completed. This block has no return value * and takes the requested UIImage as first parameter. In case of error the image parameter * is nil and the second parameter may contain an NSError. The third parameter is a Boolean * indicating if the image was retrieved from the local cache or from the network. * The fourth parameter is the original image url. */ - (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options completed:(nullable SDExternalCompletionBlock)completedBlock; #pragma mark - Cancel /** * Cancel the current image download */ - (void)sd_cancelImageLoadForState:(UIControlState)state; /** * Cancel the current backgroundImage download */ - (void)sd_cancelBackgroundImageLoadForState:(UIControlState)state; @end #endif
2881099/dotnetGen_mysql
1,261
GenMy/Deflate.cs
using System; using System.IO; using System.IO.Compression; using System.Text; public static class Deflate { public static string cs_head = string.Empty; public static byte[] Decompress(Stream stream) { try { stream.Position = 0; using (MemoryStream ms = new MemoryStream()) { using (DeflateStream def = new DeflateStream(stream, CompressionMode.Decompress)) { byte[] data = new byte[1024]; int size = 0; while ((size = def.Read(data, 0, data.Length)) > 0) { ms.Write(data, 0, size); } } return ms.ToArray(); } } catch { return (stream as MemoryStream).ToArray(); }; } public static byte[] Decompress(byte[] bt) { return Decompress(new MemoryStream(bt)); } public static byte[] Compress(string text) { if (text.Trim().StartsWith("using ")) { text = Deflate.cs_head + text; } return Compress(Encoding.UTF8.GetBytes(text)); } public static byte[] Compress(byte[] bt) { return Compress(bt, 0, bt.Length); } public static byte[] Compress(byte[] bt, int startIndex, int length) { using (MemoryStream ms = new MemoryStream()) { using (DeflateStream def = new DeflateStream(ms, CompressionMode.Compress)) { def.Write(bt, startIndex, length); } return ms.ToArray(); } } }
2881099/csredis
3,919
src/CSRedisCore/Internal/IO/RedisSocket.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Security; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; namespace CSRedis.Internal.IO { class RedisSocketException : Exception { public RedisSocketException(string message) : base(message) { } } class RedisSocket : IRedisSocket { readonly bool _ssl; internal Socket _socket; EndPoint _remote; public bool Connected { get { return _socket == null ? false : _socket.Connected; } } public int ReceiveTimeout { get { return _socket.ReceiveTimeout; } set { _socket.ReceiveTimeout = value; } } public int SendTimeout { get { return _socket.SendTimeout; } set { _socket.SendTimeout = value; } } public RedisSocket(bool ssl) { _ssl = ssl; } public void Connect(EndPoint endpoint, int timeout) { InitSocket(endpoint); IAsyncResult result = _socket.BeginConnect(endpoint, null, null); if (!result.AsyncWaitHandle.WaitOne(timeout, true)) throw new RedisSocketException("Connect to server timeout"); } #if net40 #else TaskCompletionSource<bool> connectTcs; public Task<bool> ConnectAsync(EndPoint endpoint) { InitSocket(endpoint); if (connectTcs != null) connectTcs.TrySetCanceled(); connectTcs = new TaskCompletionSource<bool>(); _socket.BeginConnect(endpoint, asyncResult => { try { _socket.EndConnect(asyncResult); connectTcs.TrySetResult(true); } catch (Exception ex) { connectTcs.TrySetException(ex); } }, null); return connectTcs.Task; } #endif public Stream GetStream() { Stream netStream = new NetworkStream(_socket, true); if (!_ssl) return netStream; var sslStream = new SslStream(netStream, true); #if net40 sslStream.AuthenticateAsClient(GetHostForAuthentication()); #else sslStream.AuthenticateAsClientAsync(GetHostForAuthentication()).Wait(); #endif return sslStream; } bool isDisposed = false; public void Dispose() { if (isDisposed) return; isDisposed = true; try { _socket.Shutdown(SocketShutdown.Both); } catch { } try { _socket.Close(); } catch { } try { _socket.Dispose(); } catch { } } void InitSocket(EndPoint endpoint) { if (_socket != null) { try { _socket.Shutdown(SocketShutdown.Both); } catch { } try { _socket.Close(); } catch { } try { _socket.Dispose(); } catch { } } isDisposed = false; _socket = endpoint.AddressFamily == AddressFamily.InterNetworkV6 ? new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp) : new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); _remote = endpoint; } string GetHostForAuthentication() { if (_remote == null) throw new ArgumentNullException("Remote endpoint is not set"); else if (_remote is DnsEndPoint) return (_remote as DnsEndPoint).Host; else if (_remote is IPEndPoint) return (_remote as IPEndPoint).Address.ToString(); throw new InvalidOperationException("Cannot get remote host"); } } }
2881099/dotnetGen_mysql
25,778
GenMy/ConsoleApp.cs
using Model; using MySql.Data.MySqlClient; using MySql.Data.Types; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading; namespace GenMy { public class ConsoleApp { ClientInfo _client; ClientSocket _socket; public string ConnectionString { get { string connStr = "Data Source={0};Port={1};User ID={2};Password={3};Initial Catalog={4};Charset=utf8"; return string.Format(connStr, this._client.Server, this._client.Port, this._client.Username, this._client.Password, string.IsNullOrEmpty(this._client.Database) ? "" : this._client.Database.Split(',')[0]); } } public string Server; public int Port; public string Username; public string Password; public string Database; public string SolutionName; public bool IsMakeSolution; public bool IsMakeWebAdmin; public bool IsDownloadRes; public string OutputPath; public ConsoleApp(string[] args, ManualResetEvent wait) { this.OutputPath = Directory.GetCurrentDirectory(); string args0 = args[0].Trim().ToLower(); if (args[0] == "?" || args0 == "--help" || args0 == "-help") { var bgcolor = Console.BackgroundColor; var fgcolor = Console.ForegroundColor; Console.BackgroundColor = ConsoleColor.DarkYellow; Console.ForegroundColor = ConsoleColor.White; Console.Write("##"); Console.Write("#################################"); Console.Write("##"); Console.BackgroundColor = bgcolor; Console.ForegroundColor = fgcolor; Console.WriteLine(""); Console.BackgroundColor = ConsoleColor.DarkYellow; Console.ForegroundColor = ConsoleColor.White; Console.Write("##"); Console.BackgroundColor = ConsoleColor.DarkYellow; Console.ForegroundColor = ConsoleColor.DarkRed; Console.Write(" "); Console.BackgroundColor = ConsoleColor.DarkYellow; Console.ForegroundColor = ConsoleColor.White; Console.Write("##"); Console.BackgroundColor = bgcolor; Console.ForegroundColor = fgcolor; Console.WriteLine(""); Console.BackgroundColor = ConsoleColor.DarkYellow; Console.ForegroundColor = ConsoleColor.White; Console.Write("##"); Console.BackgroundColor = ConsoleColor.DarkYellow; Console.ForegroundColor = ConsoleColor.DarkRed; Console.Write(" .NETCore 2.1 + MySQL 生成器 "); Console.BackgroundColor = ConsoleColor.DarkYellow; Console.ForegroundColor = ConsoleColor.White; Console.Write("##"); Console.BackgroundColor = bgcolor; Console.ForegroundColor = fgcolor; Console.WriteLine(""); Console.BackgroundColor = ConsoleColor.DarkYellow; Console.ForegroundColor = ConsoleColor.White; Console.Write("##"); Console.BackgroundColor = ConsoleColor.DarkYellow; Console.ForegroundColor = ConsoleColor.DarkRed; Console.Write(" "); Console.BackgroundColor = ConsoleColor.DarkYellow; Console.ForegroundColor = ConsoleColor.White; Console.Write("##"); Console.BackgroundColor = bgcolor; Console.ForegroundColor = fgcolor; Console.WriteLine(""); Console.BackgroundColor = ConsoleColor.DarkYellow; Console.ForegroundColor = ConsoleColor.White; Console.Write("##"); Console.Write("#################################"); Console.Write("##"); Console.BackgroundColor = bgcolor; Console.ForegroundColor = ConsoleColor.DarkYellow; Console.Write(@" 用于快速创建和更新 .NETCore 2.1 + MySQL 项目,非常合适敏捷开发; Github: https://github.com/2881099/dotnetgen_mysql "); Console.ForegroundColor = ConsoleColor.DarkYellow; Console.Write("Example:"); Console.ForegroundColor = fgcolor; Console.WriteLine(@" > GenMy 127.0.0.1[:3306] -U root -P 123456 -D dyschool -N dyschool -S -A -R -O ""c:/dyschool/"" -U MySql账号 -P MySql密码 -D 需要生成的数据库,多个使用,分隔 -N 字符串,生成代码的解决方案名,命名空间 -S 生成解决方案,在项目第一次生成时使用 -A 生成后台管理 -R 下载资源 -O 输出路径(默认:当前目录)"); wait.Set(); return; } string[] ss = args[0].Split(new char[] { ':' }, 2); this.Server = ss[0]; if (int.TryParse(ss.Length == 2 ? ss[1] : "3306", out this.Port) == false) this.Port = 3306; for (int a = 1; a < args.Length; a++) { switch (args[a]) { case "-U": if (a + 1 >= args.Length) Console.WriteLine("-U 参数错误"); else this.Username = args[a + 1]; a++; break; case "-P": if (a + 1 >= args.Length) Console.WriteLine("-P 参数错误"); else this.Password = args[a + 1]; a++; break; case "-D": if (a + 1 >= args.Length) Console.WriteLine("-D 参数错误"); else this.Database = args[a + 1]; a++; break; case "-O": if (a + 1 >= args.Length) Console.WriteLine("-O 参数错误"); else this.OutputPath = args[a + 1]; a++; break; case "-N": if (a + 1 >= args.Length) Console.WriteLine("-N 参数错误"); else this.SolutionName = args[a + 1]; a++; break; case "-S": this.IsMakeSolution = true; break; case "-A": this.IsMakeWebAdmin = true; break; case "-R": this.IsDownloadRes = true; break; } } this._client = new ClientInfo(this.Server, this.Port, this.Username, this.Password); StreamReader sr = new StreamReader(System.Net.WebRequest.Create("https://files.cnblogs.com/files/kellynic/GenMy_server.css").GetResponse().GetResponseStream(), Encoding.UTF8); string server = sr.ReadToEnd()?.Trim(); //server = "127.0.0.1:18888"; Uri uri = new Uri("tcp://" + server + "/"); this._socket = new ClientSocket(); this._socket.Error += Socket_OnError; this._socket.Receive += Socket_OnReceive; this._socket.Connect(uri.Host, uri.Port); Thread.CurrentThread.Join(TimeSpan.FromSeconds(1)); if (this._socket.Running == false) { wait.Set(); return; } WriteLine("正在生成,稍候 …", ConsoleColor.DarkGreen); SocketMessager messager = new SocketMessager("GetDatabases", this._client); this._socket.Write(messager, delegate (object sender2, ClientSocketReceiveEventArgs e2) { List<DatabaseInfo> dbs = e2.Messager.Arg as List<DatabaseInfo>; }); this._client.Database = this.Database; List<TableInfo> tables = null; messager = new SocketMessager("GetTablesByDatabase", this._client.Database); this._socket.Write(messager, delegate (object sender2, ClientSocketReceiveEventArgs e2) { tables = e2.Messager.Arg as List<TableInfo>; }); if (tables == null) { Console.WriteLine("[" + DateTime.Now.ToString("MM-dd HH:mm:ss") + "] 无法读取表"); this._socket.Close(); this._socket.Dispose(); wait.Set(); return; } tables.ForEach(a => a.IsOutput = true); List<BuildInfo> bs = null; messager = new SocketMessager("Build", new object[] { SolutionName, IsMakeSolution, string.Join("", tables.ConvertAll<string>(delegate(TableInfo table){ return string.Concat(table.IsOutput ? 1 : 0); }).ToArray()), IsMakeWebAdmin, IsDownloadRes }); this._socket.Write(messager, delegate (object sender2, ClientSocketReceiveEventArgs e2) { bs = e2.Messager.Arg as List<BuildInfo>; if (e2.Messager.Arg is Exception) throw e2.Messager.Arg as Exception; }, TimeSpan.FromSeconds(60 * 5)); if (bs != null) { foreach (BuildInfo b in bs) { string path = Path.Combine(OutputPath, b.Path); Directory.CreateDirectory(Path.GetDirectoryName(path)); string fileName = Path.GetFileName(b.Path); string ext = Path.GetExtension(b.Path); Encoding encode = Encoding.UTF8; if (fileName.EndsWith(".rar") || fileName.EndsWith(".zip") || fileName.EndsWith(".dll")) { using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write)) { fs.Write(b.Data, 0, b.Data.Length); fs.Close(); } continue; } byte[] data = Deflate.Decompress(b.Data); string content = Encoding.UTF8.GetString(data); if (string.Compare(fileName, "web.config") == 0) { string place = System.Web.HttpUtility.HtmlEncode(this.ConnectionString); content = content.Replace("{connectionString}", place); } if (fileName.EndsWith(".json")) { content = content.Replace("{connectionString}", this.ConnectionString); } if (string.Compare(ext, ".refresh") == 0) { encode = Encoding.Unicode; } using (StreamWriter sw = new StreamWriter(path, false, encode)) { sw.Write(content); sw.Close(); } } var appsettingsPath = Path.Combine(OutputPath, "appsettings.json"); var appsettingsPathWebHost = Path.Combine(OutputPath, @"src\WebHost\appsettings.json"); var htmZipPath = Path.Combine(OutputPath, "htm.zip"); //解压htm.zip if (this.IsDownloadRes && File.Exists(htmZipPath)) { try { System.IO.Compression.ZipFile.ExtractToDirectory(htmZipPath, OutputPath, Encoding.UTF8, true); } catch (Exception ex) { var color = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine($"解压 htm.zip 失败:{ex.Message}"); Console.ForegroundColor = color; } } if (this.IsMakeSolution) { WriteLine("代码已生成完毕!使用 -S 生成完整项目,正在建立脚手架,大约需要10秒 …", ConsoleColor.DarkGreen); var shellret = ShellRun(OutputPath, "gulp -v"); if (!string.IsNullOrEmpty(shellret.err)) { WriteLine(""); WriteLine(@"正在安装gulp-cli …", ConsoleColor.DarkGreen); shellret = ShellRun(OutputPath, "npm install --global gulp-cli"); if (!string.IsNullOrEmpty(shellret.err)) WriteLine(shellret.err, ConsoleColor.Red); if (!string.IsNullOrEmpty(shellret.warn)) WriteLine(shellret.warn, ConsoleColor.Yellow); if (!string.IsNullOrEmpty(shellret.info)) WriteLine(shellret.info, ConsoleColor.DarkGray); } //WriteLine(""); //WriteLine("正在还原项目 …", ConsoleColor.DarkGreen); //shellret = ShellRun(OutputPath, "dotnet1 restore"); //if (!string.IsNullOrEmpty(shellret.err)) WriteLine(shellret.err, ConsoleColor.Red); //if (!string.IsNullOrEmpty(shellret.warn)) WriteLine(shellret.warn, ConsoleColor.Yellow); //if (!string.IsNullOrEmpty(shellret.info)) WriteLine(shellret.info, ConsoleColor.DarkGray); WriteLine(""); WriteLine(@"正在编译Module\Test …", ConsoleColor.DarkGreen); shellret = ShellRun(Path.Combine(OutputPath, @"src\Module\Test"), "dotnet build"); if (!string.IsNullOrEmpty(shellret.err)) WriteLine(shellret.err, ConsoleColor.Red); if (!string.IsNullOrEmpty(shellret.warn)) WriteLine(shellret.warn, ConsoleColor.Yellow); if (!string.IsNullOrEmpty(shellret.info)) WriteLine(shellret.info, ConsoleColor.DarkGray); WriteLine(""); WriteLine(@"正在编译Module\Admin …", ConsoleColor.DarkGreen); shellret = ShellRun(Path.Combine(OutputPath, @"src\Module\Admin"), "dotnet build"); if (!string.IsNullOrEmpty(shellret.err)) WriteLine(shellret.err, ConsoleColor.Red); if (!string.IsNullOrEmpty(shellret.warn)) WriteLine(shellret.warn, ConsoleColor.Yellow); if (!string.IsNullOrEmpty(shellret.info)) WriteLine(shellret.info, ConsoleColor.DarkGray); WriteLine(""); WriteLine("正在安装npm包 …", ConsoleColor.DarkGreen); shellret = ShellRun(Path.Combine(OutputPath, @"src\WebHost"), "npm install"); if (!string.IsNullOrEmpty(shellret.err)) WriteLine(shellret.err, ConsoleColor.Red); if (!string.IsNullOrEmpty(shellret.warn)) WriteLine(shellret.warn, ConsoleColor.Yellow); if (!string.IsNullOrEmpty(shellret.info)) WriteLine(shellret.info, ConsoleColor.DarkGray); WriteLine(""); WriteLine("正在编译WebHost …", ConsoleColor.DarkGreen); shellret = ShellRun(Path.Combine(OutputPath, @"src\WebHost"), "dotnet build"); if (!string.IsNullOrEmpty(shellret.err)) WriteLine(shellret.err, ConsoleColor.Red); if (!string.IsNullOrEmpty(shellret.warn)) WriteLine(shellret.warn, ConsoleColor.Yellow); if (!string.IsNullOrEmpty(shellret.info)) WriteLine(shellret.info, ConsoleColor.DarkGray); WriteLine(""); WriteLine($"脚手架建立完成。", ConsoleColor.DarkGreen); //WriteLine(""); //Write($"项目运行依赖 ", ConsoleColor.DarkYellow); //Write($"redis-server", ConsoleColor.Green); //Write($",安装地址:", ConsoleColor.DarkYellow); //Write("https://files.cnblogs.com/files/kellynic/Redis-x64-2.8.2402.zip", ConsoleColor.Blue); //WriteLine($",或前往官方下载", ConsoleColor.DarkYellow); WriteLine(""); WriteLine($"{Path.Combine(OutputPath, @"src\WebHost")} 目执行 dotnet run", ConsoleColor.DarkYellow); WriteLine(""); //Console.WriteLine(ShellRun(Path.Combine(OutputPath, @"src\WebHost"), "dotnet run")); var pro = new System.Diagnostics.Process(); pro.StartInfo = new System.Diagnostics.ProcessStartInfo("dotnet", "run --urls=http://0.0.0.0:5000") { WorkingDirectory = Path.Combine(OutputPath, @"src\WebHost"), EnvironmentVariables = { ["ASPNETCORE_ENVIRONMENT"] = "Development" } }; pro.Start(); pro.WaitForExit(); } //如果三个选项为false,并且 src\WebHost\appsettings.json 不存在,则在当前目录使用 appsettings.json if (this.IsDownloadRes == false && this.IsMakeSolution == false && this.IsMakeWebAdmin == false && File.Exists(appsettingsPathWebHost) == false) { var appsettings = Newtonsoft.Json.JsonConvert.DeserializeObject(File.Exists(appsettingsPath) ? File.ReadAllText(appsettingsPath) : "{}") as JToken; var oldtxt = appsettings.ToString(); if (appsettings["ConnectionStrings"] == null) appsettings["ConnectionStrings"] = new JObject(); if (appsettings["ConnectionStrings"][$"{this.SolutionName}_mysql"] == null) appsettings["ConnectionStrings"][$"{this.SolutionName}_mysql"] = this.ConnectionString + ";SslMode=none;Max pool size=100"; if (appsettings["ConnectionStrings"]["redis1"] == null) appsettings["ConnectionStrings"]["redis1"] = $"127.0.0.1:6379,password=,defaultDatabase=13,poolsize=10,ssl=false,writeBuffer=20480,prefix={this.SolutionName}"; if (appsettings["ConnectionStrings"]["redis2"] == null) appsettings["ConnectionStrings"]["redis2"] = $"127.0.0.1:6379,password=,defaultDatabase=13,poolsize=10,ssl=false,writeBuffer=20480,prefix={this.SolutionName}"; if (appsettings[$"{this.SolutionName}_BLL_ITEM_CACHE"] == null) appsettings[$"{this.SolutionName}_BLL_ITEM_CACHE"] = JToken.FromObject(new { Timeout = 180 }); if (appsettings["Logging"] == null) appsettings["Logging"] = new JObject(); if (appsettings["Logging"]["IncludeScopes"] == null) appsettings["Logging"]["IncludeScopes"] = false; if (appsettings["Logging"]["LogLevel"] == null) appsettings["Logging"]["LogLevel"] = new JObject(); if (appsettings["Logging"]["LogLevel"]["Default"] == null) appsettings["Logging"]["LogLevel"]["Default"] = "Debug"; if (appsettings["Logging"]["LogLevel"]["System"] == null) appsettings["Logging"]["LogLevel"]["System"] = "Information"; if (appsettings["Logging"]["LogLevel"]["Microsoft"] == null) appsettings["Logging"]["LogLevel"]["Microsoft"] = "Information"; var newtxt = appsettings.ToString(); if (newtxt != oldtxt) File.WriteAllText(appsettingsPath, newtxt, Encoding.UTF8); //增加当前目录 .csproj nuguet 引用 <PackageReference Include="dng.Mysql" Version="" /> string csprojPath = Directory.GetFiles(OutputPath, "*.csproj").FirstOrDefault(); if (!string.IsNullOrEmpty(csprojPath) && File.Exists(csprojPath)) { if (Regex.IsMatch(File.ReadAllText(csprojPath), @"dng\.Mysql""\s+Version=""", RegexOptions.IgnoreCase) == false) { System.Diagnostics.Process pro = new System.Diagnostics.Process(); pro.StartInfo = new System.Diagnostics.ProcessStartInfo("dotnet", "add package dng.Mysql") { WorkingDirectory = OutputPath }; pro.Start(); pro.WaitForExit(); } if (Regex.IsMatch(File.ReadAllText(csprojPath), @"CSRedisCore""\s+Version=""", RegexOptions.IgnoreCase) == false) { System.Diagnostics.Process pro = new System.Diagnostics.Process(); pro.StartInfo = new System.Diagnostics.ProcessStartInfo("dotnet", "add package CSRedisCore") { WorkingDirectory = OutputPath }; pro.Start(); pro.WaitForExit(); } } //向startup.cs注入代码 string startupPath = Path.Combine(OutputPath, "Startup.cs"); if (!string.IsNullOrEmpty(startupPath) && File.Exists(startupPath)) { //web项目才需要 Caching.CSRedis if (Regex.IsMatch(File.ReadAllText(csprojPath), @"Caching.CSRedis""\s+Version=""", RegexOptions.IgnoreCase) == false) { System.Diagnostics.Process pro = new System.Diagnostics.Process(); pro.StartInfo = new System.Diagnostics.ProcessStartInfo("dotnet", "add package Caching.CSRedis") { WorkingDirectory = OutputPath }; pro.Start(); pro.WaitForExit(); } bool isChanged = false; var startupCode = File.ReadAllText(startupPath); if (Regex.IsMatch(startupCode, @"using\s+Microsoft\.Extensions\.Caching\.Distributed;") == false) { isChanged = true; startupCode = "using Microsoft.Extensions.Caching.Distributed;\r\n" + startupCode; } if (Regex.IsMatch(startupCode, @"using\s+Microsoft\.Extensions\.Logging;") == false) { isChanged = true; startupCode = "using Microsoft.Extensions.Logging;\r\n" + startupCode; } if (Regex.IsMatch(startupCode, @"using\s+Microsoft\.Extensions\.Configuration;") == false) { isChanged = true; startupCode = "using Microsoft.Extensions.Configuration;\r\n" + startupCode; } var servicesName = "services"; if (startupCode.IndexOf("RedisHelper.Initialization") == -1) { startupCode = Regex.Replace(startupCode, @"[\t ]+public\s+void\s+ConfigureServices\s*\(\s*IServiceCollection\s+(\w+)[^\{]+\{", m => { isChanged = true; var connStr1 = @"Configuration[""ConnectionStrings:redis2""]"; var connStr2 = @"Configuration[""ConnectionStrings:redis1""]"; if (File.Exists(appsettingsPath) == false) { connStr1 = $"127.0.0.1:6379,password=,defaultDatabase=13,poolsize=50,ssl=false,writeBuffer=20480,prefix={this.SolutionName}"; connStr2 = $"127.0.0.1:6379,password=,defaultDatabase=13,poolsize=50,ssl=false,writeBuffer=20480,prefix={this.SolutionName}"; } return m.Groups[0].Value + $@" //单redis节点模式,如需开启集群负载,请将注释去掉并做相应配置 RedisHelper.Initialization( csredis: new CSRedis.CSRedisClient(//null, //{connStr1}, {connStr2})); {servicesName = m.Groups[1].Value}.AddSingleton<IDistributedCache>(new Microsoft.Extensions.Caching.Redis.CSRedisCache(RedisHelper.Instance)); "; }, RegexOptions.Multiline); } if (Regex.IsMatch(startupCode, @"\s+IConfiguration(Root)?\s+Configuration(;|\s+\{)") == false) { startupCode = Regex.Replace(startupCode, @"[\t ]+public\s+void\s+ConfigureServices\s*\(\s*IServiceCollection\s+(\w+)[^\{]+\{", m => { isChanged = true; return $@" public IConfiguration Configuration {{ get; set; }} {m.Groups[0].Value} Configuration = {servicesName = m.Groups[1].Value}.BuildServiceProvider().GetService<IConfiguration>();"; }, RegexOptions.Multiline); } if (startupCode.IndexOf(this.SolutionName + ".BLL.SqlHelper.Initialization") == -1) { startupCode = Regex.Replace(startupCode, @"([\t ]+public\s+void\s+Configure\s*\()([^\{]+)\{", m => { isChanged = true; var str1 = m.Groups[1].Value; var str2 = m.Groups[2].Value; var loggerFactory = Regex.Match(str2, @"\bILoggerFactory\s+(\w+)"); if (loggerFactory.Success == false) str2 = "ILoggerFactory loggerFactory, " + str2; loggerFactory = Regex.Match(str2, @"\bILoggerFactory\s+(\w+)"); var appName = Regex.Match(str2, @"\bIApplicationBuilder\s+(\w+)"); if (appName.Success == false) str2 = "IApplicationBuilder app, " + str2; appName = Regex.Match(str2, @"\bIApplicationBuilder\s+(\w+)"); var connStr = $@"Configuration[""ConnectionStrings:{this.SolutionName}_mysql""]"; if (File.Exists(appsettingsPath) == false) { connStr = $"{this.ConnectionString};SslMode=none;Max pool size=100"; } return str1 + str2 + $@"{{ {this.SolutionName}.BLL.SqlHelper.Initialization({appName.Groups[1].Value}.ApplicationServices.GetService<IDistributedCache>(), Configuration.GetSection(""{this.SolutionName}_BLL_ITEM_CACHE""), {connStr}, /* 此参数可以配置【从数据库】 */ null, {loggerFactory.Groups[1].Value}.CreateLogger(""{this.SolutionName}_DAL_sqlhelper"")); "; }, RegexOptions.Multiline); } if (isChanged) File.WriteAllText(startupPath, startupCode); } } if (File.Exists(Path.Combine(OutputPath, "GenMy只更新db.bat")) == false) { var batPath = Path.Combine(OutputPath, $"GenMy_{this.SolutionName}_{this.Server}_{this.Database}.bat"); if (File.Exists(batPath) == false) File.WriteAllText(batPath, $@" GenMy {this.Server}:{this.Port} -U {this.Username} -P {this.Password} -D {this.Database} -N {this.SolutionName}"); } } this._socket.Close(); this._socket.Dispose(); GC.Collect(); ConsoleColor fc = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("[" + DateTime.Now.ToString("MM-dd HH:mm:ss") + "] The code files be maked in \"" + OutputPath + "\", please check."); Console.ForegroundColor = fc; wait.Set(); } private void Socket_OnError(object sender, ClientSocketErrorEventArgs e) { Console.WriteLine("[" + DateTime.Now.ToString("MM-dd HH:mm:ss") + "] " + e.Exception.Message); } private void Socket_OnReceive(object sender, ClientSocketReceiveEventArgs e) { SocketMessager messager = null; switch (e.Messager.Action) { case "ExecuteDataSet": string sql = e.Messager.Arg.ToString(); DataSet ds = null; try { ds = ConsoleApp.ExecuteDataSet(this.ConnectionString, sql); } catch (Exception ex) { this.Socket_OnError(this, new ClientSocketErrorEventArgs(ex, 0)); } messager = new SocketMessager(e.Messager.Action, ds); messager.Id = e.Messager.Id; this._socket.Write(messager); break; case "ExecuteNonQuery": string sql2 = e.Messager.Arg.ToString(); int val = 0; try { val = ConsoleApp.ExecuteNonQuery(this.ConnectionString, sql2); } catch (Exception ex) { this.Socket_OnError(this, new ClientSocketErrorEventArgs(ex, 0)); } messager = new SocketMessager(e.Messager.Action, val); messager.Id = e.Messager.Id; this._socket.Write(messager); break; default: Console.WriteLine("[" + DateTime.Now.ToString("MM-dd HH:mm:ss") + "] " + "您当前使用的版本未能实现功能!"); break; } } public static int ExecuteNonQuery(string connectionString, string cmdText) { int val = 0; using (MySqlConnection conn = new MySqlConnection(connectionString + ";SslMode=none;AllowPublicKeyRetrieval=true;")) { MySqlCommand cmd = new MySqlCommand(cmdText, conn); try { cmd.Connection.Open(); val = cmd.ExecuteNonQuery(); } catch { cmd.Parameters.Clear(); cmd.Connection.Close(); throw; } } return val; } public static DataSet ExecuteDataSet(string connectionString, string cmdText) { DataSet ds = new DataSet(); using (MySqlConnection conn = new MySqlConnection(connectionString + ";SslMode=none;AllowPublicKeyRetrieval=true;")) { MySqlCommand cmd = new MySqlCommand(cmdText, conn); MySqlDataAdapter sda = new MySqlDataAdapter(cmd); try { cmd.Connection.Open(); sda.Fill(ds); } catch { cmd.Parameters.Clear(); cmd.Connection.Close(); throw; } cmd.Connection.Close(); cmd.Parameters.Clear(); } return ds; } public static (string info, string warn, string err) ShellRun(string cddir, params string[] bat) { if (bat == null || bat.Any() == false) return ("", "", ""); var proc = new System.Diagnostics.Process(); proc.StartInfo = new System.Diagnostics.ProcessStartInfo { CreateNoWindow = true, FileName = "cmd.exe", UseShellExecute = false, RedirectStandardError = true, RedirectStandardInput = true, RedirectStandardOutput = true, WorkingDirectory = cddir }; proc.Start(); foreach (var cmd in bat) proc.StandardInput.WriteLine(cmd); proc.StandardInput.WriteLine("exit"); var outStr = proc.StandardOutput.ReadToEnd(); var errStr = proc.StandardError.ReadToEnd(); proc.Close(); var idx = outStr.IndexOf($">{bat[0]}"); if (idx != -1) { idx = outStr.IndexOf("\n", idx); if (idx != -1) outStr = outStr.Substring(idx + 1); } idx = outStr.LastIndexOf(">exit"); if (idx != -1) { idx = outStr.LastIndexOf("\n", idx); if (idx != -1) outStr = outStr.Remove(idx); } outStr = outStr.Trim(); if (outStr == "") outStr = null; if (errStr == "") errStr = null; return (outStr, string.IsNullOrEmpty(outStr) ? null : errStr, string.IsNullOrEmpty(outStr) ? errStr : null); } public static void WriteLine(string text, ConsoleColor? foregroundColor = null, ConsoleColor? backgroundColor = null) => Write($"{text}\r\n", foregroundColor, backgroundColor); public static void Write(string text, ConsoleColor? foregroundColor = null, ConsoleColor? backgroundColor = null) { var bgcolor = Console.BackgroundColor; var fgcolor = Console.ForegroundColor; if (backgroundColor != null) Console.BackgroundColor = backgroundColor.Value; if (foregroundColor != null) Console.ForegroundColor = foregroundColor.Value; Console.Write(text); if (backgroundColor != null) Console.BackgroundColor = bgcolor; if (foregroundColor != null) Console.ForegroundColor = fgcolor; } } }
27182812/ChatGLM-LLaMA-chinese-insturct
32,943
src/transformers/models/speech_encoder_decoder/modeling_speech_encoder_decoder.py
# coding=utf-8 # Copyright 2021 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. """ Classes to support Speech-Encoder-Text-Decoder architectures""" from typing import Optional, Tuple, Union import torch from torch import nn from torch.nn import CrossEntropyLoss from ...configuration_utils import PretrainedConfig from ...modeling_outputs import BaseModelOutput, Seq2SeqLMOutput from ...modeling_utils import PreTrainedModel from ...utils import add_start_docstrings, add_start_docstrings_to_model_forward, logging, replace_return_docstrings from ..auto.configuration_auto import AutoConfig from ..auto.modeling_auto import AutoModel, AutoModelForCausalLM from .configuration_speech_encoder_decoder import SpeechEncoderDecoderConfig logger = logging.get_logger(__name__) _CONFIG_FOR_DOC = "SpeechEncoderDecoderConfig" SPEECH_ENCODER_DECODER_START_DOCSTRING = r""" This class can be used to initialize a speech-sequence-to-text-sequence model with any pretrained speech autoencoding model as the encoder and any pretrained text autoregressive model as the decoder. The encoder is loaded via [`~AutoModel.from_pretrained`] function and the decoder is loaded via [`~AutoModelForCausalLM.from_pretrained`] function. Cross-attention layers are automatically added to the decoder and should be fine-tuned on a downstream generative task, like summarization. The effectiveness of initializing sequence-to-sequence models with pretrained checkpoints for sequence generation tasks was shown in [Leveraging Pre-trained Checkpoints for Sequence Generation Tasks](https://arxiv.org/abs/1907.12461) by Sascha Rothe, Shashi Narayan, Aliaksei Severyn. Michael Matena, Yanqi Zhou, Wei Li, Peter J. Liu. Additionally, in [Large-Scale Self- and Semi-Supervised Learning for Speech Translation](https://arxiv.org/abs/2104.06678) it is shown how leveraging large pretrained speech models for speech translation yields a significant performance improvement. After such an Speech-Encoder Decoder model has been trained/fine-tuned, it can be saved/loaded just like any other models (see the examples for more information). 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 ([`SpeechEncoderDecoderConfig`]): 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. """ SPEECH_ENCODER_DECODER_INPUTS_DOCSTRING = r""" Args: inputs (`torch.FloatTensor` of shape `(batch_size, sequence_length)` or `(batch_size, sequence_length, feature_dim)`, *optional*): Float values of input raw speech waveform or speech features. Values can be obtained by loading a `.flac` or `.wav` audio file into an array of type `List[float]` or a `numpy.ndarray`, *e.g.* via the soundfile library (`pip install soundfile`). To prepare the array into `inputs`, either the [`Wav2Vec2Processor`] or [`Speech2TextProcessor`] should be used for padding and conversion into a tensor of type `torch.FloatTensor`. attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*): Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: - 1 for tokens that are **not masked**, - 0 for tokens that are **masked**. [What are attention masks?](../glossary#attention-mask) decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*): Indices of decoder input sequence tokens in the vocabulary. Indices can be obtained using [`PreTrainedTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input IDs?](../glossary#input-ids) If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see `past_key_values`). For training, `decoder_input_ids` are automatically created by the model by shifting the `labels` to the right, replacing -100 by the `pad_token_id` and prepending them with the `decoder_start_token_id`. decoder_attention_mask (`torch.BoolTensor` of shape `(batch_size, target_sequence_length)`, *optional*): Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also be used by default. encoder_outputs (`tuple(torch.FloatTensor)`, *optional*): This tuple must consist of (`last_hidden_state`, *optional*: `hidden_states`, *optional*: `attentions`) `last_hidden_state` (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`) is a tensor of hidden-states at the output of the last layer of the encoder. Used in the cross-attention of the decoder. past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`): Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding. If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `decoder_input_ids` of shape `(batch_size, sequence_length)`. 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. decoder_inputs_embeds (`torch.FloatTensor` of shape `(batch_size, target_sequence_length, hidden_size)`, *optional*): Optionally, instead of passing `decoder_input_ids` you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert `decoder_input_ids` indices into associated vectors than the model's internal embedding lookup matrix. labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Labels for computing the masked language modeling loss for the decoder. Indices should be in `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]` use_cache (`bool`, *optional*): If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see `past_key_values`). 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. input_values (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*): Float values of input raw speech waveform. Values can be obtained by loading a *.flac* or *.wav* audio file into an array of type *List[float]* or a *numpy.ndarray*, *e.g.* via the soundfile library (*pip install soundfile*). To prepare the array into *input_values*, the [`Wav2Vec2Processor`] should be used for padding and conversion into a tensor of type *torch.FloatTensor*. See [`Wav2Vec2Processor.__call__`] for details. input_features (`torch.FloatTensor` of shape `(batch_size, sequence_length, feature_size)`, *optional*): Float values of fbank features extracted from the raw speech waveform. Raw speech waveform can be obtained by loading a `.flac` or `.wav` audio file into an array of type `List[float]` or a `numpy.ndarray`, *e.g.* via the soundfile library (`pip install soundfile`). To prepare the array into `input_features`, the [`Speech2TextFeatureExtractor`] should be used for extracting the fbank features, padding and conversion into a tensor of type `torch.FloatTensor`. See [`~Speech2TextFeatureExtractor.__call__`] return_dict (`bool`, *optional*): If set to `True`, the model will return a [`~utils.Seq2SeqLMOutput`] instead of a plain tuple. kwargs (*optional*): Remaining dictionary of keyword arguments. Keyword arguments come in two flavors: - Without a prefix which will be input as `**encoder_kwargs` for the encoder forward function. - With a *decoder_* prefix which will be input as `**decoder_kwargs` for the decoder forward function. """ # Copied from transformers.models.encoder_decoder.modeling_encoder_decoder.shift_tokens_right def shift_tokens_right(input_ids: torch.Tensor, pad_token_id: int, decoder_start_token_id: int): """ Shift input ids one token to the right. """ shifted_input_ids = input_ids.new_zeros(input_ids.shape) shifted_input_ids[:, 1:] = input_ids[:, :-1].clone() if decoder_start_token_id is None: raise ValueError("Make sure to set the decoder_start_token_id attribute of the model's configuration.") shifted_input_ids[:, 0] = decoder_start_token_id if pad_token_id is None: raise ValueError("Make sure to set the pad_token_id attribute of the model's configuration.") # replace possible -100 values in labels by `pad_token_id` shifted_input_ids.masked_fill_(shifted_input_ids == -100, pad_token_id) return shifted_input_ids @add_start_docstrings(SPEECH_ENCODER_DECODER_START_DOCSTRING) class SpeechEncoderDecoderModel(PreTrainedModel): r""" [`SpeechEncoderDecoderModel`] is a generic model class that will be instantiated as a transformer architecture with one of the base model classes of the library as encoder and another one as decoder when created with the :meth*~transformers.AutoModel.from_pretrained* class method for the encoder and :meth*~transformers.AutoModelForCausalLM.from_pretrained* class method for the decoder. """ config_class = SpeechEncoderDecoderConfig base_model_prefix = "speech_encoder_decoder" main_input_name = "inputs" supports_gradient_checkpointing = True def __init__( self, config: Optional[PretrainedConfig] = None, encoder: Optional[PreTrainedModel] = None, decoder: Optional[PreTrainedModel] = None, ): if config is None and (encoder is None or decoder is None): raise ValueError("Either a configuration or an encoder and a decoder has to be provided.") if config is None: config = SpeechEncoderDecoderConfig.from_encoder_decoder_configs(encoder.config, decoder.config) else: if not isinstance(config, self.config_class): raise ValueError(f"Config: {config} has to be of type {self.config_class}") if config.decoder.cross_attention_hidden_size is not None: if config.decoder.cross_attention_hidden_size != config.encoder.hidden_size: raise ValueError( "If `cross_attention_hidden_size` is specified in the decoder's configuration, it has to be equal" f" to the encoder's `hidden_size`. Got {config.decoder.cross_attention_hidden_size} for" f" `config.decoder.cross_attention_hidden_size` and {config.encoder.hidden_size} for" " `config.encoder.hidden_size`." ) # initialize with config # make sure input & output embeddings is not tied config.tie_word_embeddings = False super().__init__(config) if encoder is None: encoder = AutoModel.from_config(config.encoder) if decoder is None: decoder = AutoModelForCausalLM.from_config(config.decoder) self.encoder = encoder self.decoder = decoder if self.encoder.config.to_dict() != self.config.encoder.to_dict(): logger.warning( f"Config of the encoder: {self.encoder.__class__} is overwritten by shared encoder config:" f" {self.config.encoder}" ) if self.decoder.config.to_dict() != self.config.decoder.to_dict(): logger.warning( f"Config of the decoder: {self.decoder.__class__} is overwritten by shared decoder config:" f" {self.config.decoder}" ) # make sure that the individual model's config refers to the shared config # so that the updates to the config will be synced self.encoder.config = self.config.encoder self.decoder.config = self.config.decoder # get encoder output hidden size self.encoder_output_dim = getattr(config.encoder, "output_hidden_size", config.encoder.hidden_size) if ( self.encoder_output_dim != self.decoder.config.hidden_size and self.decoder.config.cross_attention_hidden_size is None ): # encoder outputs might need to be projected to different dimension for decoder self.enc_to_dec_proj = nn.Linear(self.encoder.config.hidden_size, self.decoder.config.hidden_size) if self.encoder.get_output_embeddings() is not None: raise ValueError( f"The encoder {self.encoder} should not have a LM Head. Please use a model without LM Head" ) def _set_gradient_checkpointing(self, module, value=False): # call both encoder and decoder function on gradient checkpointing self.encoder._set_gradient_checkpointing(module, value=value) self.decoder._set_gradient_checkpointing(module, value=value) def get_encoder(self): return self.encoder def get_decoder(self): return self.decoder def get_output_embeddings(self): return self.decoder.get_output_embeddings() def set_output_embeddings(self, new_embeddings): return self.decoder.set_output_embeddings(new_embeddings) def freeze_feature_encoder(self): """ Calling this function will disable the gradient computation for the feature encoder of the speech encoder so that its parameters will not be updated during training. """ self.encoder.freeze_feature_encoder() @classmethod def from_pretrained(cls, *args, **kwargs): # At the moment fast initialization is not supported for composite models if kwargs.get("_fast_init", False): logger.warning( "Fast initialization is currently not supported for SpeechEncoderDecoderModel. " "Falling back to slow initialization..." ) kwargs["_fast_init"] = False return super().from_pretrained(*args, **kwargs) @classmethod def from_encoder_decoder_pretrained( cls, encoder_pretrained_model_name_or_path: str = None, decoder_pretrained_model_name_or_path: str = None, *model_args, **kwargs, ) -> PreTrainedModel: r""" Instantiate an encoder and a decoder from one or two base classes of the library from pretrained model checkpoints. The model is set in evaluation mode by default using `model.eval()` (Dropout modules are deactivated). To train the model, you need to first set it back in training mode with `model.train()`. Params: encoder_pretrained_model_name_or_path (`str`, *optional*): Information necessary to initiate the encoder. Can be either: - A string, the *model id* of a pretrained model hosted inside a model repo on huggingface.co. Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a user or organization name, like `dbmdz/bert-base-german-cased`. - A path to a *directory* containing model weights saved using [`~PreTrainedModel.save_pretrained`], e.g., `./my_model_directory/`. - A path or url to a *tensorflow index checkpoint file* (e.g, `./tf_model/model.ckpt.index`). In this case, `from_tf` should be set to `True` and a configuration object should be provided as `config` argument. This loading path is slower than converting the TensorFlow checkpoint in a PyTorch model using the provided conversion scripts and loading the PyTorch model afterwards. decoder_pretrained_model_name_or_path (`str`, *optional*, defaults to `None`): Information necessary to initiate the decoder. Can be either: - A string, the *model id* of a pretrained model hosted inside a model repo on huggingface.co. Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a user or organization name, like `dbmdz/bert-base-german-cased`. - A path to a *directory* containing model weights saved using [`~PreTrainedModel.save_pretrained`], e.g., `./my_model_directory/`. - A path or url to a *tensorflow index checkpoint file* (e.g, `./tf_model/model.ckpt.index`). In this case, `from_tf` should be set to `True` and a configuration object should be provided as `config` argument. This loading path is slower than converting the TensorFlow checkpoint in a PyTorch model using the provided conversion scripts and loading the PyTorch model afterwards. model_args (remaining positional arguments, *optional*): All remaning positional arguments will be passed to the underlying model's `__init__` method. kwargs (remaining dictionary of keyword arguments, *optional*): Can be used to update the configuration object (after it being loaded) and initiate the model (e.g., `output_attentions=True`). - To update the encoder configuration, use the prefix *encoder_* for each configuration parameter. - To update the decoder configuration, use the prefix *decoder_* for each configuration parameter. - To update the parent model configuration, do not use a prefix for each configuration parameter. Behaves differently depending on whether a `config` is provided or automatically loaded. Example: ```python >>> from transformers import SpeechEncoderDecoderModel >>> # initialize a wav2vec2bert from a pretrained Wav2Vec2 and a pretrained BERT model. Note that the cross-attention layers will be randomly initialized >>> model = SpeechEncoderDecoderModel.from_encoder_decoder_pretrained( ... "facebook/wav2vec2-base-960h", "bert-base-uncased" ... ) >>> # saving model after fine-tuning >>> model.save_pretrained("./wav2vec2bert") >>> # load fine-tuned model >>> model = SpeechEncoderDecoderModel.from_pretrained("./wav2vec2bert") ```""" kwargs_encoder = { argument[len("encoder_") :]: value for argument, value in kwargs.items() if argument.startswith("encoder_") } kwargs_decoder = { argument[len("decoder_") :]: value for argument, value in kwargs.items() if argument.startswith("decoder_") } # remove encoder, decoder kwargs from kwargs for key in kwargs_encoder.keys(): del kwargs["encoder_" + key] for key in kwargs_decoder.keys(): del kwargs["decoder_" + key] # Load and initialize the encoder and decoder # The distinction between encoder and decoder at the model level is made # by the value of the flag `is_decoder` that we need to set correctly. encoder = kwargs_encoder.pop("model", None) if encoder is None: if encoder_pretrained_model_name_or_path is None: raise ValueError( "If `encoder_model` is not defined as an argument, a `encoder_pretrained_model_name_or_path` has " "to be defined." ) if "config" not in kwargs_encoder: encoder_config, kwargs_encoder = AutoConfig.from_pretrained( encoder_pretrained_model_name_or_path, **kwargs_encoder, return_unused_kwargs=True ) if encoder_config.is_decoder is True or encoder_config.add_cross_attention is True: logger.info( f"Initializing {encoder_pretrained_model_name_or_path} as a encoder model " "from a decoder model. Cross-attention and casual mask are disabled." ) encoder_config.is_decoder = False encoder_config.add_cross_attention = False kwargs_encoder["config"] = encoder_config encoder = AutoModel.from_pretrained(encoder_pretrained_model_name_or_path, *model_args, **kwargs_encoder) decoder = kwargs_decoder.pop("model", None) if decoder is None: if decoder_pretrained_model_name_or_path is None: raise ValueError( "If `decoder_model` is not defined as an argument, a `decoder_pretrained_model_name_or_path` has " "to be defined." ) if "config" not in kwargs_decoder: decoder_config, kwargs_decoder = AutoConfig.from_pretrained( decoder_pretrained_model_name_or_path, **kwargs_decoder, return_unused_kwargs=True ) if decoder_config.is_decoder is False or decoder_config.add_cross_attention is False: logger.info( f"Initializing {decoder_pretrained_model_name_or_path} as a decoder model. Cross attention" f" layers are added to {decoder_pretrained_model_name_or_path} and randomly initialized if" f" {decoder_pretrained_model_name_or_path}'s architecture allows for cross attention layers." ) decoder_config.is_decoder = True decoder_config.add_cross_attention = True kwargs_decoder["config"] = decoder_config if kwargs_decoder["config"].is_decoder is False or kwargs_decoder["config"].add_cross_attention is False: logger.warning( f"Decoder model {decoder_pretrained_model_name_or_path} is not initialized as a decoder. " f"In order to initialize {decoder_pretrained_model_name_or_path} as a decoder, " "make sure that the attributes `is_decoder` and `add_cross_attention` of `decoder_config` " "passed to `.from_encoder_decoder_pretrained(...)` are set to `True` or do not pass a " "`decoder_config` to `.from_encoder_decoder_pretrained(...)`" ) decoder = AutoModelForCausalLM.from_pretrained(decoder_pretrained_model_name_or_path, **kwargs_decoder) # instantiate config with corresponding kwargs config = SpeechEncoderDecoderConfig.from_encoder_decoder_configs(encoder.config, decoder.config, **kwargs) # make sure input & output embeddings is not tied config.tie_word_embeddings = False return cls(encoder=encoder, decoder=decoder, config=config) @add_start_docstrings_to_model_forward(SPEECH_ENCODER_DECODER_INPUTS_DOCSTRING) @replace_return_docstrings(output_type=Seq2SeqLMOutput, config_class=_CONFIG_FOR_DOC) def forward( self, inputs: Optional[torch.FloatTensor] = None, attention_mask: Optional[torch.FloatTensor] = None, decoder_input_ids: Optional[torch.LongTensor] = None, decoder_attention_mask: Optional[torch.BoolTensor] = None, encoder_outputs: Optional[Tuple[torch.FloatTensor]] = None, past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None, decoder_inputs_embeds: Optional[torch.FloatTensor] = None, labels: Optional[torch.LongTensor] = None, use_cache: Optional[bool] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, input_values: Optional[torch.FloatTensor] = None, input_features: Optional[torch.FloatTensor] = None, return_dict: Optional[bool] = None, **kwargs, ) -> Union[Tuple[torch.FloatTensor], Seq2SeqLMOutput]: r""" Returns: Examples: ```python >>> from transformers import SpeechEncoderDecoderModel, AutoProcessor >>> from datasets import load_dataset >>> import torch >>> processor = AutoProcessor.from_pretrained("facebook/wav2vec2-xls-r-300m-en-to-15") >>> model = SpeechEncoderDecoderModel.from_pretrained("facebook/wav2vec2-xls-r-300m-en-to-15") >>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") >>> input_values = processor(ds[0]["audio"]["array"], return_tensors="pt").input_values >>> # Inference: Translate English speech to German >>> generated = model.generate(input_values) >>> decoded = processor.batch_decode(generated, skip_special_tokens=True)[0] >>> decoded 'Mr. Quilter ist der Apostel der Mittelschicht und wir freuen uns, sein Evangelium willkommen heißen zu können.' >>> # Training: Train model on English transcription >>> labels = processor(text=ds[0]["text"], return_tensors="pt").input_ids >>> loss = model(input_values, labels=labels).loss >>> loss.backward() ```""" return_dict = return_dict if return_dict is not None else self.config.use_return_dict kwargs_encoder = {argument: value for argument, value in kwargs.items() if not argument.startswith("decoder_")} kwargs_decoder = { argument[len("decoder_") :]: value for argument, value in kwargs.items() if argument.startswith("decoder_") } if encoder_outputs is None: if inputs is None: if input_values is not None and input_features is not None: raise ValueError("You cannot specify both input_values and input_features at the same time") elif input_values is not None: inputs = input_values elif input_features is not None: inputs = input_features else: raise ValueError("You have to specify either input_values or input_features") encoder_outputs = self.encoder( inputs, attention_mask=attention_mask, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, **kwargs_encoder, ) elif isinstance(encoder_outputs, tuple): encoder_outputs = BaseModelOutput(*encoder_outputs) encoder_hidden_states = encoder_outputs[0] # optionally project encoder_hidden_states if ( self.encoder_output_dim != self.decoder.config.hidden_size and self.decoder.config.cross_attention_hidden_size is None ): encoder_hidden_states = self.enc_to_dec_proj(encoder_hidden_states) # compute correct encoder attention mask if attention_mask is not None: encoder_attention_mask = self.encoder._get_feature_vector_attention_mask( encoder_hidden_states.shape[1], attention_mask ) else: encoder_attention_mask = None if (labels is not None) and (decoder_input_ids is None and decoder_inputs_embeds is None): decoder_input_ids = shift_tokens_right( labels, self.config.pad_token_id, self.config.decoder_start_token_id ) # Decode decoder_outputs = self.decoder( input_ids=decoder_input_ids, attention_mask=decoder_attention_mask, encoder_hidden_states=encoder_hidden_states, encoder_attention_mask=encoder_attention_mask, inputs_embeds=decoder_inputs_embeds, output_attentions=output_attentions, output_hidden_states=output_hidden_states, use_cache=use_cache, past_key_values=past_key_values, return_dict=return_dict, **kwargs_decoder, ) # Compute loss independent from decoder (as some shift the logits inside them) loss = None if labels is not None: logits = decoder_outputs.logits if return_dict else decoder_outputs[0] loss_fct = CrossEntropyLoss() loss = loss_fct(logits.reshape(-1, self.decoder.config.vocab_size), labels.reshape(-1)) if not return_dict: if loss is not None: return (loss,) + decoder_outputs + encoder_outputs else: return decoder_outputs + encoder_outputs return Seq2SeqLMOutput( loss=loss, logits=decoder_outputs.logits, past_key_values=decoder_outputs.past_key_values, decoder_hidden_states=decoder_outputs.hidden_states, decoder_attentions=decoder_outputs.attentions, cross_attentions=decoder_outputs.cross_attentions, encoder_last_hidden_state=encoder_hidden_states, encoder_hidden_states=encoder_outputs.hidden_states, encoder_attentions=encoder_outputs.attentions, ) def prepare_decoder_input_ids_from_labels(self, labels: torch.Tensor): return shift_tokens_right(labels, self.config.pad_token_id, self.config.decoder_start_token_id) def prepare_inputs_for_generation( self, input_ids, past_key_values=None, attention_mask=None, use_cache=None, encoder_outputs=None, **kwargs ): decoder_inputs = self.decoder.prepare_inputs_for_generation(input_ids, past_key_values=past_key_values) decoder_attention_mask = decoder_inputs["attention_mask"] if "attention_mask" in decoder_inputs else None input_dict = { "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "decoder_input_ids": decoder_inputs["input_ids"], "encoder_outputs": encoder_outputs, "past_key_values": decoder_inputs["past_key_values"], "use_cache": use_cache, } return input_dict def resize_token_embeddings(self, *args, **kwargs): raise NotImplementedError( "Resizing the embedding layers via the SpeechEncoderDecoderModel directly is not supported. Please use the" " respective methods of the wrapped decoder object (model.decoder.resize_token_embeddings(...))" ) def _reorder_cache(self, past_key_values, beam_idx): # apply decoder cache reordering here return self.decoder._reorder_cache(past_key_values, beam_idx)
2881099/csredis
11,937
src/CSRedisCore/Internal/Utilities/Serializer.cs
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Runtime.Serialization; namespace CSRedis.Internal.Utilities { internal static class Serializer<T> where T : class { static readonly Lazy<Func<T, Dictionary<string, string>>> _propertySerializer; static readonly Lazy<Func<Dictionary<string, string>, T>> _propertyDeserializer; static readonly Lazy<Func<T, Dictionary<string, string>>> _serializer; static readonly Lazy<Func<Dictionary<string, string>, T>> _deserializer; static Serializer() { _propertySerializer = new Lazy<Func<T, Dictionary<string, string>>>(CompilePropertySerializer); _propertyDeserializer = new Lazy<Func<Dictionary<string, string>, T>>(CompilePropertyDeserializer); _serializer = new Lazy<Func<T, Dictionary<string, string>>>(CompileSerializer); _deserializer = new Lazy<Func<Dictionary<string, string>, T>>(CompileDeserializer); } public static Dictionary<string, string> Serialize(T obj) { if (typeof(ISerializable).IsAssignableFrom(typeof(T))) return _serializer.Value(obj); else return _propertySerializer.Value(obj); } public static T Deserialize(Dictionary<string, string> fields) { if (typeof(ISerializable).IsAssignableFrom(typeof(T))) return _deserializer.Value(fields); else return _propertyDeserializer.Value(fields); } static Func<T, Dictionary<string, string>> CompilePropertySerializer() { var o_t = typeof(T); var o = Expression.Parameter(o_t, "o"); var d_t = typeof(Dictionary<string, string>); var d = Expression.Variable(d_t, "d"); var d_init = Expression.MemberInit(Expression.New(d_t)); var d_add = d_t.GetMethod("Add"); var d_setters = o_t.GetProperties(BindingFlags.Public | BindingFlags.Instance) // build setters via Add(k,v) .Where(x => x.CanRead) .Select(x => { var prop = Expression.Property(o, x.Name); var prop_mi_to_string = x.PropertyType.GetMethod("ToString", new Type[0]); var add_to_dict = Expression.Call(d, d_add, Expression.Constant(x.Name), Expression.Call(prop, prop_mi_to_string)); if (!x.PropertyType.IsByRef) return (Expression)add_to_dict; else return (Expression)Expression.IfThen( Expression.Not(Expression.Equal(prop, Expression.Constant(null))), add_to_dict); }); // run this var body = Expression.Block(new[] { d }, // scope variables Expression.Assign(d, d_init), // initialize Expression.Block(d_setters), // set d); // return return Expression.Lambda<Func<T, Dictionary<string, string>>>(body, o) .Compile(); } static Func<Dictionary<string, string>, T> CompilePropertyDeserializer() { var o_t = typeof(T); var o = Expression.Variable(o_t, "o"); var o_new = Expression.New(typeof(T)); var d_t = typeof(Dictionary<string, string>); var d = Expression.Parameter(d_t, "d"); var d_mi_try_get_value = d_t.GetMethod("TryGetValue"); var item_t = typeof(String); var item = Expression.Variable(item_t, "item"); var tc_t = typeof(TypeConverter); var tc = Expression.Variable(tc_t, "tc"); var tc_mi_can_convert_from = tc_t.GetMethod("CanConvertFrom", new[] { typeof(Type) }); var tc_mi_convert_from = tc_t.GetMethod("ConvertFrom", new[] { typeof(Object) }); var td_t = typeof(TypeDescriptor); var td_mi_get_converter = td_t.GetMethod("GetConverter", new[] { typeof(Type) }); var binds = o_t.GetProperties(BindingFlags.Public | BindingFlags.Instance) .Where(x => x.CanRead) .Select(x => { var value_t = x.PropertyType; var value = Expression.Variable(value_t, "value"); var target = Expression.Label(x.PropertyType); return Expression.Bind(x, Expression.Block(new[] { item, value }, Expression.Assign(tc, Expression.Call(null, td_mi_get_converter, Expression.Constant(x.PropertyType))), Expression.IfThen( Expression.Call(d, d_mi_try_get_value, Expression.Constant(x.Name), item), Expression.IfThen( Expression.NotEqual(item, Expression.Constant(null)), Expression.IfThen( Expression.Call(tc, tc_mi_can_convert_from, Expression.Constant(typeof(String))), Expression.Block( Expression.Assign(value, Expression.Convert(Expression.Call(tc, tc_mi_convert_from, item), x.PropertyType)), Expression.Return(target, value, x.PropertyType))))), Expression.Label(target, value) )); }).ToArray(); var body = Expression.Block(new[] { o, tc }, Expression.MemberInit(o_new, binds) ); return Expression.Lambda<Func<Dictionary<string, string>, T>>(body, d) .Compile(); } static Func<T, Dictionary<string, string>> CompileSerializer() { var o_t = typeof(T); var o = Expression.Parameter(o_t, "original"); var o_get_object_data = o_t.GetMethod("GetObjectData"); var d_t = typeof(Dictionary<string, string>); var d = Expression.Variable(d_t, "d"); // define object variable var d_init = Expression.MemberInit(Expression.New(d_t)); // object ctor var d_add = d_t.GetMethod("Add"); // add method var fc_t = typeof(IFormatterConverter);// typeof(LocalVariableInfo); var fc = Expression.Variable(fc_t, "fc"); var fc_init = Expression.MemberInit(Expression.New(typeof(System.Runtime.Serialization.FormatterConverter))); //Expression.MemberInit(Expression.New(fc_t)); var info_t = typeof(SerializationInfo); var info = Expression.Variable(info_t, "info"); var info_ctor = info_t.GetConstructor(new[] { typeof(Type), fc_t }); var info_init = Expression.MemberInit(Expression.New(info_ctor, Expression.Constant(o_t), fc)); var info_get_enumerator = info_t.GetMethod("GetEnumerator"); var ctx_t = typeof(StreamingContext); var ctx = Expression.Variable(ctx_t, "ctx"); var ctx_init = Expression.MemberInit(Expression.New(ctx_t)); var enumerator_t = typeof(SerializationInfoEnumerator); var enumerator = Expression.Variable(enumerator_t, "enumerator"); var enumerator_move_next = enumerator_t.GetMethod("MoveNext"); var enumerator_name = Expression.Property(enumerator, "Name"); var enumerator_value = Expression.Property(enumerator, "Value"); var mi_to_string = typeof(Object).GetMethod("ToString", new Type[0]); var exit_loop = Expression.Label("exit_loop"); var body = Expression.Block(new[] { d, fc, info, ctx }, Expression.Assign(d, d_init), Expression.Assign(fc, fc_init), Expression.Assign(info, info_init), Expression.Assign(ctx, ctx_init), Expression.Call(o, o_get_object_data, info, ctx), Expression.Block(new[] { enumerator }, Expression.Assign(enumerator, Expression.Call(info, info_get_enumerator)), Expression.Loop( Expression.IfThenElse( Expression.Call(enumerator, enumerator_move_next), // test Expression.IfThen( Expression.NotEqual(enumerator_value, Expression.Constant(null)), Expression.Call(d, d_add, enumerator_name, Expression.Call(enumerator_value, mi_to_string)) ), Expression.Break(exit_loop)), // if false exit_loop)), d); // return // compile return Expression.Lambda<Func<T, Dictionary<string, string>>>(body, o) .Compile(); } static Func<Dictionary<string, string>, T> CompileDeserializer() { var o_t = typeof(T); var o_ctor = o_t.GetConstructor(new[] { typeof(SerializationInfo), typeof(StreamingContext) }); var d_t = typeof(Dictionary<string, string>); var d = Expression.Parameter(d_t, "d"); var d_mi_get_enumerator = d_t.GetMethod("GetEnumerator"); var fc_t = typeof(IFormatterConverter);// typeof(LocalVariableInfo); var fc = Expression.Variable(fc_t, "fc"); var fc_init = Expression.MemberInit(Expression.New(typeof(System.Runtime.Serialization.FormatterConverter))); //Expression.MemberInit(Expression.New(fc_t)); var info_t = typeof(SerializationInfo); var info = Expression.Variable(info_t, "info"); var info_ctor = info_t.GetConstructor(new[] { typeof(Type), fc_t }); var info_init = Expression.MemberInit(Expression.New(info_ctor, Expression.Constant(o_t), fc)); var info_mi_add_value = info_t.GetMethod("AddValue", new[] { typeof(String), typeof(Object) }); var ctx_t = typeof(StreamingContext); var ctx = Expression.Variable(ctx_t, "ctx"); var ctx_init = Expression.MemberInit(Expression.New(ctx_t)); var enumerator_t = typeof(Dictionary<string, string>.Enumerator); var enumerator = Expression.Variable(enumerator_t, "enumerator"); var enumerator_mi_move_next = enumerator_t.GetMethod("MoveNext"); var enumerator_current = Expression.Property(enumerator, "Current"); var kvp_t = typeof(KeyValuePair<string, string>); var kvp_pi_key = kvp_t.GetProperty("Key"); var kvp_pi_value = kvp_t.GetProperty("Value"); var exit_loop = Expression.Label("exit_loop"); var body = Expression.Block(new[] { fc, info, ctx, enumerator }, Expression.Assign(fc, fc_init), Expression.Assign(info, info_init), Expression.Assign(ctx, ctx_init), Expression.Assign(enumerator, Expression.Call(d, d_mi_get_enumerator)), Expression.Loop( Expression.IfThenElse( Expression.Call(enumerator, enumerator_mi_move_next), Expression.Call(info, info_mi_add_value, Expression.Property(enumerator_current, kvp_pi_key), Expression.Property(enumerator_current, kvp_pi_value)), Expression.Break(exit_loop)), exit_loop), Expression.MemberInit(Expression.New(o_ctor, info, ctx)) ); return Expression.Lambda<Func<Dictionary<string, string>, T>>(body, d) .Compile(); } } }
2881099/csredis
3,648
src/CSRedisCore/Internal/Utilities/RedisArgs.cs
using System; using System.Collections.Generic; using System.Globalization; namespace CSRedis.Internal.Utilities { static class RedisArgs { /// <summary> /// Join arrays /// </summary> /// <param name="arrays">Arrays to join</param> /// <returns>Array of ToString() elements in each array</returns> public static object[] Concat(params object[][] arrays) { int count = 0; foreach (var ar in arrays) count += ar.Length; int pos = 0; object[] output = new object[count]; for (int i = 0; i < arrays.Length; i++) { for (int j = 0; j < arrays[i].Length; j++) { object obj = arrays[i][j]; output[pos++] = obj;// obj == null ? String.Empty : (obj is byte[] ? obj : String.Format(CultureInfo.InvariantCulture, "{0}", obj)); } } return output; } /// <summary> /// Joine string with arrays /// </summary> /// <param name="str">Leading string element</param> /// <param name="arrays">Array to join</param> /// <returns>Array of str and ToString() elements of arrays</returns> public static object[] Concat(string str, params object[] arrays) { return Concat(new[] { str }, arrays); } /// <summary> /// Convert array of two-element tuple into flat array arguments /// </summary> /// <typeparam name="TItem1">Type of first item</typeparam> /// <typeparam name="TItem2">Type of second item</typeparam> /// <param name="tuples">Array of tuple arguments</param> /// <returns>Flattened array of arguments</returns> public static object[] GetTupleArgs<TItem1, TItem2>(Tuple<TItem1, TItem2>[] tuples) { List<object> args = new List<object>(); foreach (var kvp in tuples) args.AddRange(new object[] { kvp.Item1, kvp.Item2 }); return args.ToArray(); } /// <summary> /// Parse score for +/- infinity and inclusive/exclusive /// </summary> /// <param name="score">Numeric base score</param> /// <param name="isExclusive">Score is exclusive, rather than inclusive</param> /// <returns>String representing Redis score/range notation</returns> public static string GetScore(decimal score, bool isExclusive) { if (score == decimal.MinValue) return "-inf"; else if (score == decimal.MaxValue) return "+inf"; else if (isExclusive) return '(' + score.ToString(); else return score.ToString(); } public static object[] FromDict(Dictionary<string, object> dict) { var array = new List<object>(); foreach (var keyValue in dict) { if (keyValue.Key != null && keyValue.Value != null) array.AddRange(new[] { keyValue.Key, keyValue.Value }); } return array.ToArray(); } public static object[] FromObject<T>(T obj) where T : class { var dict = Serializer<T>.Serialize(obj); object[] array = new object[dict.Count * 2]; int i = 0; foreach (var item in dict) { array[i++] = item.Key; array[i++] = item.Value; } return array; } } }
2881099/csredis
2,368
src/CSRedisCore/Internal/ObjectPool/IPolicy.cs
using System; using System.Threading.Tasks; namespace CSRedis.Internal.ObjectPool { public interface IPolicy<T> { /// <summary> /// 名称 /// </summary> string Name { get; set; } /// <summary> /// 池容量 /// </summary> int PoolSize { get; set; } /// <summary> /// 默认获取超时设置 /// </summary> TimeSpan SyncGetTimeout { get; set; } /// <summary> /// 空闲时间,获取时若超出,则重新创建 /// </summary> TimeSpan IdleTimeout { get; set; } /// <summary> /// 异步获取排队队列大小,小于等于0不生效 /// </summary> int AsyncGetCapacity { get; set; } /// <summary> /// 获取超时后,是否抛出异常 /// </summary> bool IsThrowGetTimeoutException { get; set; } /// <summary> /// 监听 AppDomain.CurrentDomain.ProcessExit/Console.CancelKeyPress 事件自动释放 /// </summary> bool IsAutoDisposeWithSystem { get; set; } /// <summary> /// 后台定时检查可用性间隔秒数 /// </summary> int CheckAvailableInterval { get; set; } /// <summary> /// 对象池的对象被创建时 /// </summary> /// <returns>返回被创建的对象</returns> T OnCreate(); /// <summary> /// 销毁对象 /// </summary> /// <param name="obj">资源对象</param> void OnDestroy(T obj); /// <summary> /// 从对象池获取对象超时的时候触发,通过该方法统计 /// </summary> void OnGetTimeout(); /// <summary> /// 从对象池获取对象成功的时候触发,通过该方法统计或初始化对象 /// </summary> /// <param name="obj">资源对象</param> void OnGet(Object<T> obj); #if net40 #else /// <summary> /// 从对象池获取对象成功的时候触发,通过该方法统计或初始化对象 /// </summary> /// <param name="obj">资源对象</param> Task OnGetAsync(Object<T> obj); #endif /// <summary> /// 归还对象给对象池的时候触发 /// </summary> /// <param name="obj">资源对象</param> void OnReturn(Object<T> obj); /// <summary> /// 检查可用性 /// </summary> /// <param name="obj">资源对象</param> /// <returns></returns> bool OnCheckAvailable(Object<T> obj); /// <summary> /// 事件:可用时触发 /// </summary> void OnAvailable(); /// <summary> /// 事件:不可用时触发 /// </summary> void OnUnavailable(); } }
2881099/dotnetGen_mysql
981
GenMy/GenMy.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>netcoreapp2.1</TargetFramework> <GeneratePackageOnBuild>true</GeneratePackageOnBuild> <IsPackable>true</IsPackable> <PackAsTool>true</PackAsTool> <Authors>2881099</Authors> <Company>2881099</Company> <Product>dotnetGen</Product> <Description>快速创建和更新 .NETCore 2.1 + MySQL 项目,非常合适敏捷开发; dotnet tool install -g GenMy</Description> <PackageProjectUrl>https://github.com/2881099/dotnetgen_mysql</PackageProjectUrl> <RepositoryUrl>https://github.com/2881099/dotnetgen_mysql</RepositoryUrl> <Version>1.1.14</Version> <PackageTags>生成器 mysql core mariadb</PackageTags> </PropertyGroup> <ItemGroup> <PackageReference Include="MySql.Data" Version="8.0.12" /> <PackageReference Include="Newtonsoft.Json" Version="13.0.1" /> <PackageReference Include="System.IO.Compression.ZipFile" Version="4.3.0" /> </ItemGroup> </Project>
2881099/dotnetGen_mysql
1,053
Server/log4net.config
<?xml version="1.0" encoding="utf-8" ?> <configuration> <!-- Register a section handler for the log4net section --> <configSections> <section name="log4net" type="System.Configuration.IgnoreSectionHandler" /> </configSections> <!-- This section contains the log4net configuration settings --> <log4net> <!-- remotor --> <appender name="remotor__rolling_file_appender" type="log4net.Appender.RollingFileAppender"> <file value="d:\Ҷ\logs\mc\rolling.txt" /> <appendToFile value="true" /> <maxSizeRollBackups value="20" /> <maximumFileSize value="1048576" /> <rollingStyle value="Size" /> <staticLogFileName value="true" /> <lockingModel type="log4net.Appender.FileAppender+MinimalLock" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%date %-5level %logger (%property{log4net:HostName}) - %message%newline" /> </layout> </appender> <logger name="remotor"> <level value="DEBUG" /> <appender-ref ref="remotor__rolling_file_appender" /> </logger> </log4net> </configuration>
2881099/dotnetGen_mysql
2,986
Server/Logger.cs
using System; [assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)] namespace Server { /// <summary> /// ־ /// </summary> [Serializable] public class Logger { protected readonly string _Name; private log4net.ILog _Log; protected log4net.ILog Log { get { if (_Log == null) _Log = log4net.LogManager.GetLogger(_Name); return _Log; } } protected Logger() { } public Logger(string name) { this._Name = name; } /// <summary> /// ȫ־ /// </summary> public static readonly Logger remotor = new Logger("remotor"); public void Debug(object message, Exception exception) { Log.Debug(message, exception); } public void Debug(object message) { Log.Debug(message); } public void DebugFormat(IFormatProvider provider, string format, params object[] args) { Log.DebugFormat(provider, format, args); } public void DebugFormat(string format, params object[] args) { Log.DebugFormat(format, args); } public void Error(object message, Exception exception) { Log.Error(message, exception); } public void Error(object message) { Log.Error(message); } public void ErrorFormat(IFormatProvider provider, string format, params object[] args) { Log.ErrorFormat(provider, format, args); } public void ErrorFormat(string format, params object[] args) { Log.ErrorFormat(format, args); } public void Fatal(object message, Exception exception) { Log.Fatal("" + message, exception); } public void Fatal(object message) { Log.Fatal("" + message); } public void FatalFormat(IFormatProvider provider, string format, params object[] args) { Log.FatalFormat(provider, format, args); } public void FatalFormat(string format, params object[] args) { Log.FatalFormat(format, args); } public void Info(object message, Exception exception) { Log.Info(message, exception); } public void Info(object message) { Log.Info(message); } public void InfoFormat(IFormatProvider provider, string format, params object[] args) { Log.InfoFormat(provider, format, args); } public void InfoFormat(string format, params object[] args) { Log.InfoFormat(format, args); } public bool IsDebugEnabled { get { return Log.IsDebugEnabled; } } public bool IsErrorEnabled { get { return Log.IsErrorEnabled; } } public bool IsFatalEnabled { get { return Log.IsFatalEnabled; } } public bool IsInfoEnabled { get { return Log.IsInfoEnabled; } } public bool IsWarnEnabled { get { return Log.IsWarnEnabled; } } public void Warn(object message, Exception exception) { Log.Warn(message, exception); } public void Warn(object message) { Log.Warn(message); } public void WarnFormat(IFormatProvider provider, string format, params object[] args) { Log.WarnFormat(provider, format, args); } public void WarnFormat(string format, params object[] args) { Log.WarnFormat(format, args); } } }
2881099/dotnetGen_mysql
12,795
Server/CodeBuild(DB).cs
using System; using System.Collections.Generic; using System.Data; using System.Text; using System.Text.RegularExpressions; using Model; namespace Server { internal partial class CodeBuild : IDisposable { private ClientInfo _client; private AcceptSocket _socket; private List<TableInfo> _tables; private Dictionary<string, Dictionary<string, string>> _column_coments = new Dictionary<string, Dictionary<string, string>>(); public CodeBuild(ClientInfo client, AcceptSocket socket) { _client = client; _socket = socket; } private object[][] GetDataSet(string commandText) { SocketMessager messager = new SocketMessager("ExecuteDataSet", commandText); _socket.Write(messager, delegate(object sender, ServerSocketReceiveEventArgs e) { messager = e.Messager; }); object[][] ret = messager.Arg as object[][]; //.netcore if (ret == null) { DataSet ds = messager.Arg as DataSet; //.net if (ds != null) { List<object[]> tmp = new List<object[]>(); foreach (DataRow row in ds.Tables[0].Rows) tmp.Add(row.ItemArray); ret = tmp.ToArray(); } } return ret; } private int ExecuteNonQuery(string commandText) { SocketMessager messager = new SocketMessager("ExecuteNonQuery", commandText); _socket.Write(messager, delegate(object sender, ServerSocketReceiveEventArgs e) { messager = e.Messager; }); int val; int.TryParse(string.Concat(messager.Arg), out val); return val; } public List<DatabaseInfo> GetDatabases() { Logger.remotor.Info("GetDatabases: " + _client.Server + "," + _client.Username + "," + _client.Password); List<DatabaseInfo> loc1 = null; object[][] ds = this.GetDataSet(@"select schema_name from information_schema.schemata where schema_name not in ('information_schema', 'mysql', 'performance_schema')"); if (ds == null) return loc1; loc1 = new List<DatabaseInfo>(); foreach (object[] row in ds) { loc1.Add(new DatabaseInfo(string.Concat(row[0]))); } return loc1; } public List<TableInfo> GetTablesByDatabase(string database) { _client.Database = database; Logger.remotor.Info("GetTablesByDatabase: " + _client.Server + "," + _client.Username + "," + _client.Password + "," + _client.Database); string[] dbs = database.Split(','); List<TableInfo> loc1 = _tables = null; Dictionary<string, TableInfo> loc2 = new Dictionary<string, TableInfo>(); Dictionary<string, Dictionary<string, ColumnInfo>> loc3 = new Dictionary<string, Dictionary<string, ColumnInfo>>(); object[][] ds = this.GetDataSet(string.Format(@" select concat(a.table_schema, '.', a.table_name) 'id', a.table_schema 'owner', a.table_name 'table', 'T' from information_schema.tables a where a.table_schema in ('{0}') ", database.Replace("'", "''").Replace(",", "','"))); if (ds == null) return loc1; List<string> loc6 = new List<string>(); List<string> loc66 = new List<string>(); foreach (object[] row in ds) { string table_id = string.Concat(row[0]); string owner = string.Concat(row[1]); string table = string.Concat(row[2]); string type = string.Concat(row[3]); if (dbs.Length == 1) { table_id = table_id.Substring(table_id.IndexOf('.') + 1); owner = ""; } loc2.Add(table_id, new TableInfo(table_id, owner, table, type)); loc3.Add(table_id, new Dictionary<string, ColumnInfo>()); switch (type) { case "T": loc6.Add(table.Replace("'", "''")); break; case "P": loc66.Add(table.Replace("'", "''")); break; } } if (loc6.Count == 0) return loc1; string loc8 = "'" + string.Join("','", loc6.ToArray()) + "'"; string loc88 = "'" + string.Join("','", loc66.ToArray()) + "'"; ds = this.GetDataSet(string.Format(@" SELECT concat(a.table_schema, '.', a.table_name), a.column_name, a.data_type, ifnull(a.character_maximum_length, 0) 'len', a.column_type, case when a.is_nullable then 1 else 0 end 'is_nullable', case when locate('auto_increment', a.extra) > 0 then 1 else 0 end 'is_identity', a.column_comment 'comment' from information_schema.columns a where a.table_schema in ('{1}') and a.table_name in ({0}) ", loc8, database.Replace("'", "''").Replace(",", "','"))); if (ds == null) return loc1; foreach (object[] row in ds) { string table_id = string.Concat(row[0]); string column = string.Concat(row[1]); string type = string.Concat(row[2]); //long max_length = long.Parse(string.Concat(row[3])); string sqlType = string.Concat(row[4]); Match m_len = Regex.Match(sqlType, @"\w+\((\d+)"); long max_length = m_len.Success ? int.Parse(m_len.Groups[1].Value) : -1; bool is_nullable = string.Concat(row[5]) == "1"; bool is_identity = string.Concat(row[6]) == "1"; string comment = string.Concat(row[7]); if (string.IsNullOrEmpty(comment)) comment = column; if (max_length == 0) max_length = -1; if (dbs.Length == 1) { table_id = table_id.Substring(table_id.IndexOf('.') + 1); } loc3[table_id].Add(column, new ColumnInfo( column, CodeBuild.GetDBType(type, sqlType.EndsWith(" unsigned")), max_length, sqlType, DataSort.ASC, is_nullable, is_identity, false, false)); if (!_column_coments.ContainsKey(table_id)) _column_coments.Add(table_id, new Dictionary<string, string>()); if (!_column_coments[table_id].ContainsKey(column)) _column_coments[table_id].Add(column, comment); else _column_coments[table_id][column] = comment; } ds = this.GetDataSet(string.Format(@" select concat(a.constraint_schema, '.', a.table_name) 'table_id', a.column_name, concat(a.constraint_schema, '/', a.table_name, '/', a.constraint_name) 'index_id', 1 'IsUnique', case when constraint_name = 'PRIMARY' then 1 else 0 end 'IsPrimaryKey', 0 'IsClustered', 0 'IsDesc' from information_schema.key_column_usage a where a.constraint_schema in ('{1}') and a.table_name in ({0}) and isnull(position_in_unique_constraint) ", loc8, database.Replace("'", "''").Replace(",", "','"))); if (ds == null) return loc1; Dictionary<string, Dictionary<string, List<ColumnInfo>>> indexColumns = new Dictionary<string, Dictionary<string, List<ColumnInfo>>>(); Dictionary<string, Dictionary<string, List<ColumnInfo>>> uniqueColumns = new Dictionary<string, Dictionary<string, List<ColumnInfo>>>(); foreach (object[] row in ds) { string table_id = string.Concat(row[0]); string column = string.Concat(row[1]); string index_id = string.Concat(row[2]); bool is_unique = string.Concat(row[3]) == "1"; bool is_primary_key = string.Concat(row[4]) == "1"; bool is_clustered = string.Concat(row[5]) == "1"; int is_desc = int.Parse(string.Concat(row[6])); if (dbs.Length == 1) { table_id = table_id.Substring(table_id.IndexOf('.') + 1); } if (loc3.ContainsKey(table_id) == false || loc3[table_id].ContainsKey(column) == false) continue; ColumnInfo loc9 = loc3[table_id][column]; if (loc9.IsClustered == false && is_clustered) loc9.IsClustered = is_clustered; if (loc9.IsPrimaryKey == false && is_primary_key) loc9.IsPrimaryKey = is_primary_key; if (loc9.Orderby == DataSort.NONE) loc9.Orderby = (DataSort)is_desc; Dictionary<string, List<ColumnInfo>> loc10 = null; List<ColumnInfo> loc11 = null; if (!indexColumns.TryGetValue(table_id, out loc10)) { indexColumns.Add(table_id, loc10 = new Dictionary<string, List<ColumnInfo>>()); } if (!loc10.TryGetValue(index_id, out loc11)) { loc10.Add(index_id, loc11 = new List<ColumnInfo>()); } loc11.Add(loc9); if (is_unique) { if (!uniqueColumns.TryGetValue(table_id, out loc10)) { uniqueColumns.Add(table_id, loc10 = new Dictionary<string, List<ColumnInfo>>()); } if (!loc10.TryGetValue(index_id, out loc11)) { loc10.Add(index_id, loc11 = new List<ColumnInfo>()); } loc11.Add(loc9); } } foreach (string table_id in indexColumns.Keys) { foreach (List<ColumnInfo> columns in indexColumns[table_id].Values) { loc2[table_id].Indexes.Add(columns); } } foreach (string table_id in uniqueColumns.Keys) { foreach (List<ColumnInfo> columns in uniqueColumns[table_id].Values) { columns.Sort(delegate(ColumnInfo c1, ColumnInfo c2) { return c1.Name.CompareTo(c2.Name); }); loc2[table_id].Uniques.Add(columns); } } ds = this.GetDataSet(string.Format(@" select concat(a.constraint_schema, '.', a.table_name) 'table_id', a.column_name, concat(a.constraint_schema, '/', a.constraint_name) 'FKId', concat(a.referenced_table_schema, '.', a.referenced_table_name) 'ref_table_id', 1 'IsForeignKey', a.referenced_column_name 'ref_column', null 'ref_sln', null 'ref_table' from information_schema.key_column_usage a where a.constraint_schema in ('{1}') and a.table_name in ({0}) and not isnull(position_in_unique_constraint) ", loc8, database.Replace("'", "''").Replace(",", "','"))); if (ds == null) return loc1; Dictionary<string, Dictionary<string, ForeignKeyInfo>> fkColumns = new Dictionary<string, Dictionary<string, ForeignKeyInfo>>(); foreach (object[] row in ds) { string table_id = string.Concat(row[0]); string column = string.Concat(row[1]); string fk_id = string.Concat(row[2]); string ref_table_id = string.Concat(row[3]); bool is_foreign_key = string.Concat(row[4]) == "1"; string referenced_column = string.Concat(row[5]); string referenced_db = string.Concat(row[6]); string referenced_table = string.Concat(row[7]); if (dbs.Length == 1) { table_id = table_id.Substring(table_id.IndexOf('.') + 1); ref_table_id = ref_table_id.Substring(ref_table_id.IndexOf('.') + 1); } if (loc3.ContainsKey(table_id) == false || loc3[table_id].ContainsKey(column) == false) continue; ColumnInfo loc9 = loc3[table_id][column]; TableInfo loc10 = null; ColumnInfo loc11 = null; bool isThisSln = !string.IsNullOrEmpty(ref_table_id); if (isThisSln) { if (loc2.ContainsKey(ref_table_id) == false) continue; loc10 = loc2[ref_table_id]; loc11 = loc3[ref_table_id][referenced_column]; } else { } Dictionary<string, ForeignKeyInfo> loc12 = null; ForeignKeyInfo loc13 = null; if (!fkColumns.TryGetValue(table_id, out loc12)) { fkColumns.Add(table_id, loc12 = new Dictionary<string, ForeignKeyInfo>()); } if (!loc12.TryGetValue(fk_id, out loc13)) { if (isThisSln) { loc13 = new ForeignKeyInfo(loc2[table_id], loc10); } else { loc13 = new ForeignKeyInfo(referenced_db, referenced_table, is_foreign_key); } loc12.Add(fk_id, loc13); } loc13.Columns.Add(loc9); if (isThisSln) { loc13.ReferencedColumns.Add(loc11); } else { loc13.ReferencedColumnNames.Add(referenced_column); } } foreach (string table_id in fkColumns.Keys) { foreach (ForeignKeyInfo fk in fkColumns[table_id].Values) { loc2[table_id].ForeignKeys.Add(fk); } } foreach (string table_id in loc3.Keys) { foreach (ColumnInfo loc5 in loc3[table_id].Values) { loc2[table_id].Columns.Add(loc5); if (loc5.IsIdentity) { loc2[table_id].Identitys.Add(loc5); } if (loc5.IsClustered) { loc2[table_id].Clustereds.Add(loc5); } if (loc5.IsPrimaryKey) { loc2[table_id].PrimaryKeys.Add(loc5); } } } loc1 = _tables = new List<TableInfo>(); foreach (TableInfo loc4 in loc2.Values) { if (loc4.PrimaryKeys.Count == 0 && loc4.Uniques.Count > 0) { foreach (ColumnInfo loc5 in loc4.Uniques[0]) { loc5.IsPrimaryKey = true; loc4.PrimaryKeys.Add(loc5); } } this.Sort(loc4); loc1.Add(loc4); } loc1.Sort(delegate (TableInfo t1, TableInfo t2) { return t1.FullName.CompareTo(t2.FullName); }); loc2.Clear(); loc3.Clear(); return loc1; } protected virtual void Sort(TableInfo table) { table.PrimaryKeys.Sort(delegate (ColumnInfo c1, ColumnInfo c2) { return c1.Name.CompareTo(c2.Name); }); table.Columns.Sort(delegate(ColumnInfo c1, ColumnInfo c2) { int compare = c2.IsPrimaryKey.CompareTo(c1.IsPrimaryKey); if (compare == 0) { bool b1 = table.ForeignKeys.Find(delegate(ForeignKeyInfo fk) { return fk.Columns.Find(delegate(ColumnInfo c3) { return c3.Name == c1.Name; }) != null; }) != null; bool b2 = table.ForeignKeys.Find(delegate(ForeignKeyInfo fk) { return fk.Columns.Find(delegate(ColumnInfo c3) { return c3.Name == c2.Name; }) != null; }) != null; compare = b2.CompareTo(b1); } if (compare == 0) compare = c1.Name.CompareTo(c2.Name); return compare; }); } #region IDisposable Ա public void Dispose() { if (_tables != null) { _tables.Clear(); } } #endregion } }
2881099/csredis
2,649
src/CSRedisCore/Internal/ObjectPool/Object.cs
using System; using System.Threading; namespace CSRedis.Internal.ObjectPool { public class Object<T> : IDisposable { public static Object<T> InitWith(IObjectPool<T> pool, int id, T value) { return new Object<T> { Pool = pool, Id = id, Value = value, LastGetThreadId = Thread.CurrentThread.ManagedThreadId, LastGetTime = DateTime.Now, LastGetTimeCopy = DateTime.Now }; } /// <summary> /// 所属对象池 /// </summary> public IObjectPool<T> Pool { get; internal set; } /// <summary> /// 在对象池中的唯一标识 /// </summary> public int Id { get; internal set; } /// <summary> /// 资源对象 /// </summary> public T Value { get; internal set; } internal long _getTimes; /// <summary> /// 被获取的总次数 /// </summary> public long GetTimes => _getTimes; /// 最后获取时的时间 public DateTime LastGetTime { get; internal set; } public DateTime LastGetTimeCopy { get; internal set; } /// <summary> /// 最后归还时的时间 /// </summary> public DateTime LastReturnTime { get; internal set; } /// <summary> /// 创建时间 /// </summary> public DateTime CreateTime { get; internal set; } = DateTime.Now; /// <summary> /// 最后获取时的线程id /// </summary> public int LastGetThreadId { get; internal set; } /// <summary> /// 最后归还时的线程id /// </summary> public int LastReturnThreadId { get; internal set; } public override string ToString() { return $"{this.Value}, Times: {this.GetTimes}, ThreadId(R/G): {this.LastReturnThreadId}/{this.LastGetThreadId}, Time(R/G): {this.LastReturnTime.ToString("yyyy-MM-dd HH:mm:ss:ms")}/{this.LastGetTime.ToString("yyyy-MM-dd HH:mm:ss:ms")}"; } /// <summary> /// 重置 Value 值 /// </summary> public void ResetValue() { if (this.Value != null) { try { this.Pool.Policy.OnDestroy(this.Value); } catch { } try { (this.Value as IDisposable)?.Dispose(); } catch { } } T value = default(T); try { value = this.Pool.Policy.OnCreate(); } catch { } this.Value = value; this.LastReturnTime = DateTime.Now; } internal bool _isReturned = false; public void Dispose() { Pool?.Return(this); } } }
27182812/ChatGLM-LLaMA-chinese-insturct
2,350
src/transformers/models/retribert/__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_tokenizers_available, is_torch_available _import_structure = { "configuration_retribert": ["RETRIBERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "RetriBertConfig"], "tokenization_retribert": ["RetriBertTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _import_structure["tokenization_retribert_fast"] = ["RetriBertTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _import_structure["modeling_retribert"] = [ "RETRIBERT_PRETRAINED_MODEL_ARCHIVE_LIST", "RetriBertModel", "RetriBertPreTrainedModel", ] if TYPE_CHECKING: from .configuration_retribert import RETRIBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, RetriBertConfig from .tokenization_retribert import RetriBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_retribert_fast import RetriBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_retribert import ( RETRIBERT_PRETRAINED_MODEL_ARCHIVE_LIST, RetriBertModel, RetriBertPreTrainedModel, ) else: import sys sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
2881099/dotnetGen_mysql
12,660
Server/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; 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(); } catch (Exception ex) { this._running = false; this.OnError(ex); return; } this._tcpListenerThread = new Thread(delegate() { while (this._running) { try { TcpClient tcpClient = this._tcpListener.AcceptTcpClient(); new Thread(delegate() { try { AcceptSocket acceptSocket = new AcceptSocket(this, tcpClient, this._id); this.OnAccepted(acceptSocket); } catch (Exception ex) { this.OnError(ex); } }).Start(); } 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(); } } 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(3)); 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)) { 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) { e.AcceptSocket.Write(SocketMessager.SYS_HELLO_WELCOME, delegate(object sender2, ServerSocketReceiveEventArgs e2) { if (e2.Messager.Id == SocketMessager.SYS_HELLO_WELCOME.Id && string.Compare(e2.Messager.Action, SocketMessager.SYS_HELLO_WELCOME.Action) == 0) { e.AcceptSocket._accepted = true; } }, TimeSpan.FromSeconds(5)); 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.Error(this, 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)) { new Thread(delegate() { try { receive.ReceiveHandler(this, e); } catch (Exception ex) { this.OnError(ex); } finally { receive.Wait.Set(); } }).Start(); } else { new Thread(delegate() { this.OnReceive(e); }).Start(); } } 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(100); } catch (Exception ex) { this._running = false; this.OnError(ex); } } this.Close(); this.OnClosed(); }); this._thread.Start(); } public void Close() { this._running = false; this._tcpClient.Close(); 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) { if (!messager._isChangeId) { messager.Id = -messager.Id; } 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); } } } } /// <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(); this._wait.Close(); } #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/csredis
19,479
src/CSRedisCore/Internal/ObjectPool/ObjectPool.cs
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Text; using System.Threading; using System.Threading.Tasks; namespace CSRedis.Internal.ObjectPool { internal class TestTrace { internal static void WriteLine(string text, ConsoleColor backgroundColor) { try //#643 { var bgcolor = Console.BackgroundColor; var forecolor = Console.ForegroundColor; Console.BackgroundColor = backgroundColor; switch (backgroundColor) { case ConsoleColor.Yellow: Console.ForegroundColor = ConsoleColor.White; break; case ConsoleColor.DarkGreen: Console.ForegroundColor = ConsoleColor.White; break; } Console.Write(text); Console.BackgroundColor = bgcolor; Console.ForegroundColor = forecolor; Console.WriteLine(); } catch { try { System.Diagnostics.Debug.WriteLine(text); } catch { } } } } /// <summary> /// 对象池管理类 /// </summary> /// <typeparam name="T">对象类型</typeparam> public partial class ObjectPool<T> : IObjectPool<T> { public IPolicy<T> Policy { get; protected set; } private object _allObjectsLock = new object(); internal List<Object<T>> _allObjects = new List<Object<T>>(); internal ConcurrentStack<Object<T>> _freeObjects = new ConcurrentStack<Object<T>>(); private ConcurrentQueue<GetSyncQueueInfo> _getSyncQueue = new ConcurrentQueue<GetSyncQueueInfo>(); private ConcurrentQueue<TaskCompletionSource<Object<T>>> _getAsyncQueue = new ConcurrentQueue<TaskCompletionSource<Object<T>>>(); private ConcurrentQueue<bool> _getQueue = new ConcurrentQueue<bool>(); public bool IsAvailable => this.UnavailableException == null; public Exception UnavailableException { get; private set; } public DateTime? UnavailableTime { get; private set; } public DateTime? AvailableTime { get; private set; } private object UnavailableLock = new object(); private bool running = true; public bool SetUnavailable(Exception exception, DateTime lastGetTime) { bool isseted = false; if (exception != null && UnavailableException == null) { lock (UnavailableLock) { if (UnavailableException == null) { if (lastGetTime < AvailableTime) return false; //已经恢复 UnavailableException = exception; UnavailableTime = DateTime.Now; AvailableTime = null; isseted = true; } } } if (isseted) { Policy.OnUnavailable(); CheckAvailable(Policy.CheckAvailableInterval); } return isseted; } /// <summary> /// 后台定时检查可用性 /// </summary> /// <param name="interval"></param> private void CheckAvailable(int interval) { new Thread(() => { if (UnavailableException != null) TestTrace.WriteLine($"【{Policy.Name}】Next recovery time:{DateTime.Now.AddSeconds(interval)}", ConsoleColor.DarkYellow); while (UnavailableException != null) { if (running == false) return; Thread.CurrentThread.Join(TimeSpan.FromSeconds(interval)); if (running == false) return; try { var conn = GetFree(false); if (conn == null) throw new Exception($"【{Policy.Name}】Failed to get resource {this.Statistics}"); try { try { Policy.OnCheckAvailable(conn); break; } catch { conn.ResetValue(); } if (Policy.OnCheckAvailable(conn) == false) throw new Exception($"【{Policy.Name}】An exception needs to be thrown"); break; } finally { Return(conn); } } catch (Exception ex) { TestTrace.WriteLine($"【{Policy.Name}】Next recovery time: {DateTime.Now.AddSeconds(interval)} ({ex.Message})", ConsoleColor.DarkYellow); } } RestoreToAvailable(); }).Start(); } private void RestoreToAvailable() { bool isRestored = false; if (UnavailableException != null) { lock (UnavailableLock) { if (UnavailableException != null) { lock (_allObjectsLock) _allObjects.ForEach(a => a.LastGetTime = a.LastReturnTime = new DateTime(2000, 1, 1)); UnavailableException = null; UnavailableTime = null; AvailableTime = DateTime.Now; isRestored = true; } } } if (isRestored) { Policy.OnAvailable(); TestTrace.WriteLine($"【{Policy.Name}】Recovered", ConsoleColor.DarkGreen); } } protected bool LiveCheckAvailable() { try { var conn = GetFree(false); if (conn == null) throw new Exception($"【{Policy.Name}】Failed to get resource {this.Statistics}"); try { if (Policy.OnCheckAvailable(conn) == false) throw new Exception("【{Policy.Name}】An exception needs to be thrown"); } finally { Return(conn); } } catch { return false; } RestoreToAvailable(); return true; } public string Statistics => $"Pool: {_freeObjects.Count}/{_allObjects.Count}, Get wait: {_getSyncQueue.Count}, GetAsync wait: {_getAsyncQueue.Count}"; public string StatisticsFullily { get { var sb = new StringBuilder(); sb.AppendLine(Statistics); sb.AppendLine(""); foreach (var obj in _allObjects) { sb.AppendLine($"{obj.Value}, Times: {obj.GetTimes}, ThreadId(R/G): {obj.LastReturnThreadId}/{obj.LastGetThreadId}, Time(R/G): {obj.LastReturnTime.ToString("yyyy-MM-dd HH:mm:ss:ms")}/{obj.LastGetTime.ToString("yyyy-MM-dd HH:mm:ss:ms")}, "); } return sb.ToString(); } } /// <summary> /// 创建对象池 /// </summary> /// <param name="poolsize">池大小</param> /// <param name="createObject">池内对象的创建委托</param> /// <param name="onGetObject">获取池内对象成功后,进行使用前操作</param> public ObjectPool(int poolsize, Func<T> createObject, Action<Object<T>> onGetObject = null) : this(new DefaultPolicy<T> { PoolSize = poolsize, CreateObject = createObject, OnGetObject = onGetObject }) { } /// <summary> /// 创建对象池 /// </summary> /// <param name="policy">策略</param> public ObjectPool(IPolicy<T> policy) { Policy = policy; AppDomain.CurrentDomain.ProcessExit += (s1, e1) => { if (Policy.IsAutoDisposeWithSystem) running = false; }; try { Console.CancelKeyPress += (s1, e1) => { if (e1.Cancel) return; if (Policy.IsAutoDisposeWithSystem) running = false; }; } catch { } } public void AutoFree() { if (running == false) return; if (UnavailableException != null) return; var list = new List<Object<T>>(); while (_freeObjects.TryPop(out var obj)) list.Add(obj); foreach (var obj in list) { if (obj != null && obj.Value == null || obj != null && Policy.IdleTimeout > TimeSpan.Zero && DateTime.Now.Subtract(obj.LastReturnTime) > Policy.IdleTimeout) { if (obj.Value != null) { Return(obj, true); continue; } } Return(obj); } } /// <summary> /// 获取可用资源,或创建资源 /// </summary> /// <returns></returns> private Object<T> GetFree(bool checkAvailable) { if (running == false) throw new ObjectDisposedException($"【{Policy.Name}】The ObjectPool has been disposed, see: https://github.com/dotnetcore/FreeSql/discussions/1079"); if (checkAvailable && UnavailableException != null) throw new Exception($"【{Policy.Name}】Status unavailable, waiting for recovery. {UnavailableException?.Message}", UnavailableException); if ((_freeObjects.TryPop(out var obj) == false || obj == null) && _allObjects.Count < Policy.PoolSize) { lock (_allObjectsLock) if (_allObjects.Count < Policy.PoolSize) _allObjects.Add(obj = new Object<T> { Pool = this, Id = _allObjects.Count + 1 }); } if (obj != null) obj._isReturned = false; if (obj != null && obj.Value == null || obj != null && Policy.IdleTimeout > TimeSpan.Zero && DateTime.Now.Subtract(obj.LastReturnTime) > Policy.IdleTimeout) { try { obj.ResetValue(); } catch { Return(obj); throw; } } return obj; } public Object<T> Get(TimeSpan? timeout = null) { var obj = GetFree(true); if (obj == null) { var queueItem = new GetSyncQueueInfo(); _getSyncQueue.Enqueue(queueItem); _getQueue.Enqueue(false); if (timeout == null) timeout = Policy.SyncGetTimeout; try { if (queueItem.Wait.Wait(timeout.Value)) obj = queueItem.ReturnValue; } catch { } if (obj == null) obj = queueItem.ReturnValue; if (obj == null) lock (queueItem.Lock) queueItem.IsTimeout = (obj = queueItem.ReturnValue) == null; if (obj == null) obj = queueItem.ReturnValue; if (queueItem.Exception != null) throw queueItem.Exception; if (obj == null) { Policy.OnGetTimeout(); if (Policy.IsThrowGetTimeoutException) throw new TimeoutException($"【{Policy.Name}】ObjectPool.Get() timeout {timeout.Value.TotalSeconds} seconds, see: https://github.com/dotnetcore/FreeSql/discussions/1081"); return null; } } try { Policy.OnGet(obj); } catch { Return(obj, true); throw; } obj.LastGetThreadId = Thread.CurrentThread.ManagedThreadId; obj.LastGetTime = DateTime.Now; obj.LastGetTimeCopy = DateTime.Now; Interlocked.Increment(ref obj._getTimes); return obj; } #if net40 #else async public Task<Object<T>> GetAsync() { var obj = GetFree(true); if (obj == null) { if (Policy.AsyncGetCapacity > 0 && _getAsyncQueue.Count >= Policy.AsyncGetCapacity - 1) throw new OutOfMemoryException($"【{Policy.Name}】ObjectPool.GetAsync() The queue is too long. Policy.AsyncGetCapacity = {Policy.AsyncGetCapacity}"); var tcs = new TaskCompletionSource<Object<T>>(); _getAsyncQueue.Enqueue(tcs); _getQueue.Enqueue(true); obj = await tcs.Task; //if (timeout == null) timeout = Policy.SyncGetTimeout; //if (tcs.Task.Wait(timeout.Value)) // obj = tcs.Task.Result; //if (obj == null) { // tcs.TrySetCanceled(); // Policy.GetTimeout(); // if (Policy.IsThrowGetTimeoutException) // throw new TimeoutException($"【{Policy.Name}】ObjectPool.GetAsync() timeout {timeout.Value.TotalSeconds} seconds, see: https://github.com/dotnetcore/FreeSql/discussions/1081"); // return null; //} } try { await Policy.OnGetAsync(obj); } catch { Return(obj, true); throw; } obj.LastGetThreadId = Thread.CurrentThread.ManagedThreadId; obj.LastGetTime = DateTime.Now; obj.LastGetTimeCopy = DateTime.Now; Interlocked.Increment(ref obj._getTimes); return obj; } #endif public void Return(Object<T> obj, bool isReset = false) { if (obj == null) return; if (obj._isReturned) return; if (running == false) { Policy.OnDestroy(obj.Value); try { (obj.Value as IDisposable)?.Dispose(); } catch { } return; } if (isReset) obj.ResetValue(); bool isReturn = false; while (isReturn == false && _getQueue.TryDequeue(out var isAsync)) { if (isAsync == false) { if (_getSyncQueue.TryDequeue(out var queueItem) && queueItem != null) { lock (queueItem.Lock) if (queueItem.IsTimeout == false) queueItem.ReturnValue = obj; if (queueItem.ReturnValue != null) { if (UnavailableException != null) { queueItem.Exception = new Exception($"【{Policy.Name}】Status unavailable, waiting for recovery. {UnavailableException?.Message}", UnavailableException); try { queueItem.Wait.Set(); } catch { } } else { obj.LastReturnThreadId = Thread.CurrentThread.ManagedThreadId; obj.LastReturnTime = DateTime.Now; try { queueItem.Wait.Set(); isReturn = true; } catch { } } } try { queueItem.Dispose(); } catch { } } } else { if (_getAsyncQueue.TryDequeue(out var tcs) && tcs != null && tcs.Task.IsCanceled == false) { if (UnavailableException != null) { try { tcs.TrySetException(new Exception($"【{Policy.Name}】Status unavailable, waiting for recovery. {UnavailableException?.Message}", UnavailableException)); } catch { } } else { obj.LastReturnThreadId = Thread.CurrentThread.ManagedThreadId; obj.LastReturnTime = DateTime.Now; try { isReturn = tcs.TrySetResult(obj); } catch { } } } } } //无排队,直接归还 if (isReturn == false) { try { Policy.OnReturn(obj); } catch { throw; } finally { obj.LastReturnThreadId = Thread.CurrentThread.ManagedThreadId; obj.LastReturnTime = DateTime.Now; obj._isReturned = true; _freeObjects.Push(obj); } } } public void Dispose() { running = false; while (_freeObjects.TryPop(out var fo)) ; while (_getSyncQueue.TryDequeue(out var sync)) { try { sync.Wait.Set(); } catch { } } while (_getAsyncQueue.TryDequeue(out var async)) async.TrySetCanceled(); while (_getQueue.TryDequeue(out var qs)) ; for (var a = 0; a < _allObjects.Count; a++) { Policy.OnDestroy(_allObjects[a].Value); try { (_allObjects[a].Value as IDisposable)?.Dispose(); } catch { } } _allObjects.Clear(); } class GetSyncQueueInfo : IDisposable { internal ManualResetEventSlim Wait { get; set; } = new ManualResetEventSlim(); internal Object<T> ReturnValue { get; set; } internal object Lock = new object(); internal bool IsTimeout { get; set; } = false; internal Exception Exception { get; set; } public void Dispose() { try { if (Wait != null) Wait.Dispose(); } catch { } } } } }
2881099/csredis
1,606
src/CSRedisCore/Internal/ObjectPool/IObjectPool.cs
using System; using System.Threading.Tasks; namespace CSRedis.Internal.ObjectPool { public interface IObjectPool<T> : IDisposable { IPolicy<T> Policy { get; } /// <summary> /// 是否可用 /// </summary> bool IsAvailable { get; } /// <summary> /// 不可用错误 /// </summary> Exception UnavailableException { get; } /// <summary> /// 不可用时间 /// </summary> DateTime? UnavailableTime { get; } /// <summary> /// 将对象池设置为不可用,后续 Get/GetAsync 均会报错,同时启动后台定时检查服务恢复可用 /// </summary> /// <param name="exception"></param> /// <param name="lastGetTime"></param> /// <returns>由【可用】变成【不可用】时返回true,否则返回false</returns> bool SetUnavailable(Exception exception, DateTime lastGetTime); /// <summary> /// 统计对象池中的对象 /// </summary> string Statistics { get; } /// <summary> /// 统计对象池中的对象(完整) /// </summary> string StatisticsFullily { get; } /// <summary> /// 获取资源 /// </summary> /// <param name="timeout">超时</param> /// <returns></returns> Object<T> Get(TimeSpan? timeout = null); #if net40 #else /// <summary> /// 获取资源 /// </summary> /// <returns></returns> Task<Object<T>> GetAsync(); #endif /// <summary> /// 使用完毕后,归还资源 /// </summary> /// <param name="obj">对象</param> /// <param name="isReset">是否重新创建</param> void Return(Object<T> obj, bool isReset = false); } }
2881099/dotnetGen_mysql
55,146
Server/CodeBuild(Const).cs
using System; using System.Collections.Generic; using System.Data; using System.Text; using Model; namespace Server { internal partial class CodeBuild { protected class CONST { public static readonly string corePath = @"src\"; public static readonly string moduleAdminPath = @"src\Module\Admin\"; public static readonly string webHostPath = @"src\WebHost\"; public static readonly string sln = #region 内容太长已被收起 @" Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 14 VisualStudioVersion = 14.0.25420.1 MinimumVisualStudioVersion = 10.0.40219.1 Project(""{{2150E333-8FDC-42A3-9474-1A3956D46DE8}}"") = ""src"", ""src"", ""{{{1}}}"" EndProject Project(""{{2150E333-8FDC-42A3-9474-1A3956D46DE8}}"") = ""Solution Items"", ""Solution Items"", ""{{{2}}}"" ProjectSection(SolutionItems) = preProject build.bat = build.bat readme.md = readme.md EndProjectSection EndProject Project(""{{2150E333-8FDC-42A3-9474-1A3956D46DE8}}"") = ""Module"", ""Module"", ""{{{3}}}"" EndProject Project(""{{2150E333-8FDC-42A3-9474-1A3956D46DE8}}"") = ""Test"", ""Test"", ""{{{4}}}"" EndProject Project(""{{9A19103F-16F7-4668-BE54-9A1E7A4F7556}}"") = ""{0}.db"", ""src\{0}.db\{0}.db.csproj"", ""{{{6}}}"" EndProject Project(""{{9A19103F-16F7-4668-BE54-9A1E7A4F7556}}"") = ""Infrastructure"", ""src\Infrastructure\Infrastructure.csproj"", ""{{{7}}}"" EndProject Project(""{{9A19103F-16F7-4668-BE54-9A1E7A4F7556}}"") = ""WebHost"", ""src\WebHost\WebHost.csproj"", ""{{{8}}}"" EndProject Project(""{{9A19103F-16F7-4668-BE54-9A1E7A4F7556}}"") = ""Admin"", ""src\Module\Admin\Admin.csproj"", ""{{{9}}}"" EndProject Project(""{{9A19103F-16F7-4668-BE54-9A1E7A4F7556}}"") = ""Test"", ""src\Module\Test\Test.csproj"", ""{{{10}}}"" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {{{6}}}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {{{6}}}.Debug|Any CPU.Build.0 = Debug|Any CPU {{{6}}}.Release|Any CPU.ActiveCfg = Release|Any CPU {{{6}}}.Release|Any CPU.Build.0 = Release|Any CPU {{{7}}}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {{{7}}}.Debug|Any CPU.Build.0 = Debug|Any CPU {{{7}}}.Release|Any CPU.ActiveCfg = Release|Any CPU {{{7}}}.Release|Any CPU.Build.0 = Release|Any CPU {{{8}}}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {{{8}}}.Debug|Any CPU.Build.0 = Debug|Any CPU {{{8}}}.Release|Any CPU.ActiveCfg = Release|Any CPU {{{8}}}.Release|Any CPU.Build.0 = Release|Any CPU {{{9}}}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {{{9}}}.Debug|Any CPU.Build.0 = Debug|Any CPU {{{9}}}.Release|Any CPU.ActiveCfg = Release|Any CPU {{{9}}}.Release|Any CPU.Build.0 = Release|Any CPU {{{10}}}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {{{10}}}.Debug|Any CPU.Build.0 = Debug|Any CPU {{{10}}}.Release|Any CPU.ActiveCfg = Release|Any CPU {{{10}}}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(NestedProjects) = preSolution {{{3}}} = {{{1}}} {{{6}}} = {{{1}}} {{{7}}} = {{{1}}} {{{8}}} = {{{1}}} {{{9}}} = {{{3}}} {{{10}}} = {{{3}}} EndGlobalSection EndGlobal "; #endregion public static readonly string DAL_DBUtility_SqlHelper_cs = #region 内容太长已被收起 @"using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Threading.Tasks; using Microsoft.Extensions.Caching.Distributed; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using MySql.Data.MySqlClient; namespace {0}.BLL {{ /// <summary> /// dng.Mysql代理类 /// </summary> public abstract partial class SqlHelper : {0}.DAL.SqlHelper {{ }} }} namespace {0}.DAL {{ /// <summary> /// dng.Mysql代理类 /// </summary> public abstract partial class SqlHelper {{ internal static Executer Instance {{ get; private set; }} public static MySqlConnectionPool Pool => Instance.MasterPool; public static List<MySqlConnectionPool> SlavePools => Instance.SlavePools; /// <summary> /// 是否跟踪记录SQL执行性能日志 /// </summary> public static bool IsTracePerformance {{ get => Instance.IsTracePerformance; set => Instance.IsTracePerformance = value; }} public static void Initialization(IDistributedCache cache, IConfiguration cacheStrategy, string masterConnectionString, string[] slaveConnectionString, ILogger log) {{ CacheStrategy = cacheStrategy; Instance = new Executer(cache, masterConnectionString, slaveConnectionString, log); }} public static string Addslashes(string filter, params object[] parms) {{ return Executer.Addslashes(filter, parms); }} /// <summary> /// 若使用读写分离,查询【从库】条件cmdText.StartsWith(""SELECT ""),否则查询【主库】 /// </summary> /// <param name=""readerHander""></param> /// <param name=""cmdText""></param> /// <param name=""cmdParms""></param> public static void ExecuteReader(Action<MySqlDataReader> readerHander, string cmdText, params MySqlParameter[] cmdParms) => Instance.ExecuteReader(readerHander, CommandType.Text, cmdText, cmdParms); /// <summary> /// 若使用读写分离,查询【从库】条件cmdText.StartsWith(""SELECT ""),否则查询【主库】 /// </summary> /// <param name=""cmdText""></param> /// <param name=""cmdParms""></param> public static object[][] ExecuteArray(string cmdText, params MySqlParameter[] cmdParms) => Instance.ExecuteArray(CommandType.Text, cmdText, cmdParms); /// <summary> /// 在【主库】执行 /// </summary> /// <param name=""cmdText""></param> /// <param name=""cmdParms""></param> public static int ExecuteNonQuery(string cmdText, params MySqlParameter[] cmdParms) => Instance.ExecuteNonQuery(CommandType.Text, cmdText, cmdParms); /// <summary> /// 在【主库】执行 /// </summary> /// <param name=""cmdText""></param> /// <param name=""cmdParms""></param> public static object ExecuteScalar(string cmdText, params MySqlParameter[] cmdParms) => Instance.ExecuteScalar(CommandType.Text, cmdText, cmdParms); /// <summary> /// 若使用读写分离,查询【从库】条件cmdText.StartsWith(""SELECT ""),否则查询【主库】 /// </summary> /// <param name=""readerHander""></param> /// <param name=""cmdText""></param> /// <param name=""cmdParms""></param> public static Task ExecuteReaderAsync(Func<MySqlDataReader, Task> readerHander, string cmdText, params MySqlParameter[] cmdParms) => Instance.ExecuteReaderAsync(readerHander, CommandType.Text, cmdText, cmdParms); /// <summary> /// 若使用读写分离,查询【从库】条件cmdText.StartsWith(""SELECT ""),否则查询【主库】 /// </summary> /// <param name=""cmdText""></param> /// <param name=""cmdParms""></param> public static Task<object[][]> ExecuteArrayAsync(string cmdText, params MySqlParameter[] cmdParms) => Instance.ExecuteArrayAsync(CommandType.Text, cmdText, cmdParms); /// <summary> /// 在【主库】执行 /// </summary> /// <param name=""cmdText""></param> /// <param name=""cmdParms""></param> public static Task<int> ExecuteNonQueryAsync(string cmdText, params MySqlParameter[] cmdParms) => Instance.ExecuteNonQueryAsync(CommandType.Text, cmdText, cmdParms); /// <summary> /// 在【主库】执行 /// </summary> /// <param name=""cmdText""></param> /// <param name=""cmdParms""></param> public static Task<object> ExecuteScalarAsync(string cmdText, params MySqlParameter[] cmdParms) => Instance.ExecuteScalarAsync(CommandType.Text, cmdText, cmdParms); /// <summary> /// 开启事务(不支持异步),60秒未执行完将自动提交 /// </summary> /// <param name=""handler"">事务体 () => {{}}</param> public static void Transaction(Action handler) => Instance.Transaction(handler); /// <summary> /// 开启事务(不支持异步) /// </summary> /// <param name=""handler"">事务体 () => {{}}</param> /// <param name=""timeout"">超时,未执行完将自动提交</param> public static void Transaction(Action handler, TimeSpan timeout) => Instance.Transaction(handler, timeout); /// <summary> /// 生成类似Mongodb的ObjectId有序、不重复Guid /// </summary> /// <returns></returns> public static Guid NewMongodbId() => Executer.NewMongodbId(); /// <summary> /// 循环或批量删除缓存键,项目启动时检测:Cache.Remove(""key1|key2"") 若成功删除 key1、key2,说明支持批量删除 /// </summary> /// <param name=""keys"">缓存键[数组]</param> public static void CacheRemove(params string[] keys) => Instance.CacheRemove(keys); /// <summary> /// 循环或批量删除缓存键,项目启动时检测:Cache.Remove(""key1|key2"") 若成功删除 key1、key2,说明支持批量删除 /// </summary> /// <param name=""keys"">缓存键[数组]</param> async static public Task CacheRemoveAsync(params string[] keys) => await Instance.CacheRemoveAsync(keys); public static IDistributedCache Cache => Instance.Cache; internal static IConfiguration CacheStrategy {{ get; private set; }} /// <summary> /// 缓存壳 /// </summary> /// <typeparam name=""T"">缓存类型</typeparam> /// <param name=""key"">缓存键</param> /// <param name=""timeoutSeconds"">缓存秒数</param> /// <param name=""getData"">获取源数据的函数</param> /// <param name=""serialize"">序列化函数</param> /// <param name=""deserialize"">反序列化函数</param> /// <returns></returns> public static T CacheShell<T>(string key, int timeoutSeconds, Func<T> getData, Func<T, string> serialize = null, Func<string, T> deserialize = null) => Instance.CacheShell(key, timeoutSeconds, getData, serialize, deserialize); /// <summary> /// 缓存壳(哈希表) /// </summary> /// <typeparam name=""T"">缓存类型</typeparam> /// <param name=""key"">缓存键</param> /// <param name=""field"">字段</param> /// <param name=""timeoutSeconds"">缓存秒数</param> /// <param name=""getData"">获取源数据的函数</param> /// <param name=""serialize"">序列化函数</param> /// <param name=""deserialize"">反序列化函数</param> /// <returns></returns> public static T CacheShell<T>(string key, string field, int timeoutSeconds, Func<T> getData, Func<(T, long), string> serialize = null, Func<string, (T, long)> deserialize = null) => Instance.CacheShell(key, field, timeoutSeconds, getData, serialize, deserialize); /// <summary> /// 缓存壳 /// </summary> /// <typeparam name=""T"">缓存类型</typeparam> /// <param name=""key"">缓存键</param> /// <param name=""timeoutSeconds"">缓存秒数</param> /// <param name=""getDataAsync"">获取源数据的函数</param> /// <param name=""serialize"">序列化函数</param> /// <param name=""deserialize"">反序列化函数</param> /// <returns></returns> async public static Task<T> CacheShellAsync<T>(string key, int timeoutSeconds, Func<Task<T>> getDataAsync, Func<T, string> serialize = null, Func<string, T> deserialize = null) => await Instance.CacheShellAsync(key, timeoutSeconds, getDataAsync, serialize, deserialize); /// <summary> /// 缓存壳(哈希表) /// </summary> /// <typeparam name=""T"">缓存类型</typeparam> /// <param name=""key"">缓存键</param> /// <param name=""field"">字段</param> /// <param name=""timeoutSeconds"">缓存秒数</param> /// <param name=""getDataAsync"">获取源数据的函数</param> /// <param name=""serialize"">序列化函数</param> /// <param name=""deserialize"">反序列化函数</param> /// <returns></returns> async public static Task<T> CacheShellAsync<T>(string key, string field, int timeoutSeconds, Func<Task<T>> getDataAsync, Func<(T, long), string> serialize = null, Func<string, (T, long)> deserialize = null) => await Instance.CacheShellAsync(key, field, timeoutSeconds, getDataAsync, serialize, deserialize); }} }}"; #endregion public static readonly string BLL_Build_ItemCache_cs = #region 内容太长已被收起 @"using System; using System.Collections.Generic; namespace {0}.BLL {{ public partial class ItemCache {{ private static Dictionary<string, long> _dic1 = new Dictionary<string, long>(); private static Dictionary<long, Dictionary<string, string>> _dic2 = new Dictionary<long, Dictionary<string, string>>(); private static LinkedList<long> _linked = new LinkedList<long>(); private static object _dic1_lock = new object(); private static object _dic2_lock = new object(); private static object _linked_lock = new object(); public static void Clear() {{ lock(_dic1_lock) {{ _dic1.Clear(); }} lock(_dic2_lock) {{ _dic2.Clear(); }} lock(_linked_lock) {{ _linked.Clear(); }} }} public static void Remove(string key) {{ if (string.IsNullOrEmpty(key)) return; long time; if (_dic1.TryGetValue(key, out time) == false) return; lock (_dic1_lock) {{ _dic1.Remove(key); }} if (_dic2.ContainsKey(time)) {{ lock (_dic2_lock) {{ _dic2.Remove(time); }} }} lock (_linked_lock) {{ _linked.Remove(time); }} }} public static string Get(string key) {{ if (string.IsNullOrEmpty(key)) return null; long time; if (_dic1.TryGetValue(key, out time) == false) return null; Dictionary<string, string> dic; if (_dic2.TryGetValue(time, out dic) == false) {{ if (_dic1.ContainsKey(key)) {{ lock (_dic1_lock) {{ _dic1.Remove(key); }} }} return null; }} if (DateTime.Now.Subtract(new DateTime(2016, 5, 1)).TotalSeconds > time) {{ if (_dic1.ContainsKey(key)) {{ lock (_dic1_lock) {{ _dic1.Remove(key); }} }} if (_dic2.ContainsKey(time)) {{ lock (_dic2_lock) {{ _dic2.Remove(time); }} }} lock (_linked_lock) {{ _linked.Remove(time); }} return null; }} string ret; if (dic.TryGetValue(key, out ret) == false) return null; return ret; }} public static void Set(string key, string value, int expire) {{ if (string.IsNullOrEmpty(key) || expire <= 0) return; long time_cur = (long)DateTime.Now.Subtract(new DateTime(2016, 5, 1)).TotalSeconds; long time = time_cur + expire; long time2; if (_dic1.TryGetValue(key, out time2) == false) {{ lock (_dic1_lock) {{ if (_dic1.TryGetValue(key, out time2) == false) {{ _dic1.Add(key, time2 = time); }} }} }} if (time2 != time) {{ lock (_dic1_lock) {{ _dic1[key] = time; }} lock (_dic2_lock) {{ _dic2.Remove(time2); }} }} Dictionary<string, string> dic; bool isNew = false; if (_dic2.TryGetValue(time, out dic) == false) {{ lock (_dic2_lock) {{ if (_dic2.TryGetValue(time, out dic) == false) {{ _dic2.Add(time, dic = new Dictionary<string, string>()); isNew = true; }} if (dic.ContainsKey(key) == false) dic.Add(key, value); else dic[key] = value; }} }} else {{ lock (_dic2_lock) {{ if (dic.ContainsKey(key) == false) dic.Add(key, value); else dic[key] = value; }} }} if (isNew == true) {{ lock (_linked_lock) {{ if (_linked.Count == 0) {{ _linked.AddFirst(time); }} else {{ LinkedListNode<long> node = _linked.First; while (node != null) {{ if (node.Value < time_cur) {{ _linked.Remove(node); Dictionary<string, string> dic_del; if (_dic2.TryGetValue(node.Value, out dic_del)) {{ lock (_dic2_lock) {{ _dic2.Remove(node.Value); foreach (KeyValuePair<string, string> dic_del_in in dic_del) {{ if (_dic1.ContainsKey(dic_del_in.Key)) {{ lock (_dic1_lock) {{ _dic1.Remove(dic_del_in.Key); }} }} }} }} }} node = _linked.First; }} else break; }} if (node == null) _linked.AddFirst(time); else if (node != null && _linked.Last.Value < time) _linked.AddLast(time); else {{ while (node != null && node.Value < time) node = node.Next; if (node != null && node.Value != time) {{ _linked.AddBefore(node, time); }} }} }} }} }} }} }} }}"; #endregion public static readonly string Model_Build_ExtensionMethods_cs = #region 内容太长已被收起 @"using System; using System.Text; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; using {0}.Model; public static partial class {0}ExtensionMethods {{ {1} public static string GetJson(IEnumerable items) {{ StringBuilder sb = new StringBuilder(); sb.Append(""[""); IEnumerator ie = items.GetEnumerator(); if (ie.MoveNext()) {{ while (true) {{ sb.Append(string.Concat(ie.Current)); if (ie.MoveNext()) sb.Append("",""); else break; }} }} sb.Append(""]""); return sb.ToString(); }} public static IDictionary[] GetBson(IEnumerable items, Delegate func = null) {{ List<IDictionary> ret = new List<IDictionary>(); IEnumerator ie = items.GetEnumerator(); while (ie.MoveNext()) {{ if (ie.Current == null) ret.Add(null); else if (func == null) ret.Add(ie.Current.GetType().GetMethod(""ToBson"").Invoke(ie.Current, new object[] {{ false }}) as IDictionary); else {{ object obj = func.GetMethodInfo().Invoke(func.Target, new object[] {{ ie.Current }}); if (obj is IDictionary) ret.Add(obj as IDictionary); else {{ Hashtable ht = new Hashtable(); PropertyInfo[] pis = obj.GetType().GetProperties(); foreach (PropertyInfo pi in pis) ht[pi.Name] = pi.GetValue(obj); ret.Add(ht); }} }} }} return ret.ToArray(); }} }}"; #endregion public static readonly string Db_csproj = #region 内容太长已被收起 @"<Project Sdk=""Microsoft.NET.Sdk""> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <AssemblyName>{0}.db</AssemblyName> </PropertyGroup> <ItemGroup> <PackageReference Include=""dng.Mysql"" Version=""1.3.9"" /> <PackageReference Include=""CSRedisCore"" Version=""3.0.46"" /> </ItemGroup> </Project> "; #endregion public static readonly string Infrastructure_csproj = #region 内容太长已被收起 @"<Project Sdk=""Microsoft.NET.Sdk""> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningLevel>3</WarningLevel> </PropertyGroup> <ItemGroup> <ProjectReference Include=""..\{0}.db\{0}.db.csproj"" /> </ItemGroup> <ItemGroup> <PackageReference Include=""Caching.CSRedis"" Version=""3.0.46"" /> <PackageReference Include=""Microsoft.AspNetCore.Mvc"" Version=""2.1.1"" /> <PackageReference Include=""Microsoft.AspNetCore.Session"" Version=""2.1.1"" /> <PackageReference Include=""Microsoft.AspNetCore.Diagnostics"" Version=""2.1.1"" /> <PackageReference Include=""Microsoft.Extensions.Configuration.EnvironmentVariables"" Version=""2.1.1"" /> <PackageReference Include=""Microsoft.Extensions.Configuration.FileExtensions"" Version=""2.1.1"" /> <PackageReference Include=""Microsoft.Extensions.Configuration.Json"" Version=""2.1.1"" /> <PackageReference Include=""NLog.Extensions.Logging"" Version=""1.4.0"" /> <PackageReference Include=""NLog.Web.AspNetCore"" Version=""4.8.0"" /> <PackageReference Include=""Swashbuckle.AspNetCore"" Version=""4.0.1"" /> <PackageReference Include=""Swashbuckle.AspNetCore.Annotations"" Version=""4.0.1"" /> <PackageReference Include=""System.Text.Encoding.CodePages"" Version=""4.5.1"" /> </ItemGroup> </Project> "; #endregion public static readonly string WebHost_Extensions_StarupExtensions_cs = #region 内容太长已被收起 @"using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc.Razor; using Microsoft.CodeAnalysis; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.FileProviders; using Microsoft.Extensions.Logging; using Microsoft.Net.Http.Headers; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.Loader; public static class StarupExtensions {{ public static ConfigurationBuilder LoadInstalledModules(this ConfigurationBuilder build, IList<ModuleInfo> modules, IHostingEnvironment env) {{ var moduleRootFolder = new DirectoryInfo(Path.Combine(env.ContentRootPath, ""Module"")); var moduleFolders = moduleRootFolder.GetDirectories(); foreach (var moduleFolder in moduleFolders) {{ Assembly assembly = null; IModuleInitializer moduleInitializer = null; try {{ assembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(Path.Combine(moduleFolder.FullName, moduleFolder.Name + "".dll"")); var moduleInitializerType = assembly.GetTypes().FirstOrDefault(x => typeof(IModuleInitializer).IsAssignableFrom(x)); if ((moduleInitializerType != null) && (moduleInitializerType != typeof(IModuleInitializer))) {{ moduleInitializer = (IModuleInitializer)Activator.CreateInstance(moduleInitializerType); }} }} catch (FileLoadException) {{ throw; }} if (assembly.FullName.Contains(moduleFolder.Name)) modules.Add(new ModuleInfo {{ Name = moduleFolder.Name, Assembly = assembly, Initializer = moduleInitializer, Path = moduleFolder.FullName }}); }} return build; }} public static ConfigurationBuilder AddCustomizedJsonFile(this ConfigurationBuilder build, IList<ModuleInfo> modules, IHostingEnvironment env, string productPath) {{ build.SetBasePath(env.ContentRootPath).AddJsonFile(""appsettings.json"", true, true); foreach (var module in modules) {{ var jsonpath = $""Module/{{module.Name}}/appsettings.json""; if (File.Exists(Path.Combine(env.ContentRootPath, jsonpath))) build.AddJsonFile(jsonpath, true, true); }} if (env.IsProduction()) {{ build.AddJsonFile(Path.Combine(productPath, ""appsettings.json""), true, true); foreach (var module in modules) {{ var jsonpath = Path.Combine(productPath, $""Module_{{module.Name}}_appsettings.json""); if (File.Exists(Path.Combine(env.ContentRootPath, jsonpath))) build.AddJsonFile(jsonpath, true, true); }} }} return build; }} public static IServiceCollection AddCustomizedMvc(this IServiceCollection services, IList<ModuleInfo> modules) {{ var mvcBuilder = services.AddMvc().AddJsonOptions(a => {{ a.SerializerSettings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter()); a.SerializerSettings.DateFormatHandling = DateFormatHandling.IsoDateFormat; a.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Utc; }}) .AddRazorOptions(o => {{ foreach (var module in modules) {{ var a = MetadataReference.CreateFromFile(module.Assembly.Location); o.AdditionalCompilationReferences.Add(a); }} }}) .AddViewLocalization() .AddDataAnnotationsLocalization(); foreach (var module in modules) {{ mvcBuilder.AddApplicationPart(module.Assembly); }} services.Configure<RazorViewEngineOptions>(options => {{ options.ViewLocationExpanders.Add(new ModuleViewLocationExpander()); }}); return services; }} public static IApplicationBuilder UseCustomizedStaticFiles(this IApplicationBuilder app, IList<ModuleInfo> modules) {{ app.UseDefaultFiles(); app.UseStaticFiles(new StaticFileOptions() {{ OnPrepareResponse = (context) => {{ var headers = context.Context.Response.GetTypedHeaders(); headers.CacheControl = new CacheControlHeaderValue() {{ Public = true, MaxAge = TimeSpan.FromDays(60) }}; }} }}); return app; }} }} "; #endregion public static readonly string WebHost_Extensions_SwaggerExtensions_cs = #region 内容太长已被收起 @"using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.DependencyInjection; using Swashbuckle.AspNetCore.SwaggerGen; using System.IO; using System.Linq; namespace Swashbuckle.AspNetCore.Swagger {{ public class FormDataOperationFilter : IOperationFilter {{ public void Apply(Operation operation, OperationFilterContext context) {{ if (context.ApiDescription.TryGetMethodInfo(out var method) == false) return; var actattrs = method.GetCustomAttributes(false); if (actattrs.OfType<HttpPostAttribute>().Any() || actattrs.OfType<HttpPutAttribute>().Any()) if (operation.Consumes.Count == 0) operation.Consumes.Add(""application/x-www-form-urlencoded""); }} }} public static class SwashbuckleSwaggerExtensions {{ public static IServiceCollection AddCustomizedSwaggerGen(this IServiceCollection services) {{ services.AddSwaggerGen(options => {{ foreach (var doc in _docs) options.SwaggerDoc(doc, new Info {{ Version = doc }}); options.DocInclusionPredicate((docName, apiDesc) => {{ if (apiDesc.TryGetMethodInfo(out var method) == false) return false; var versions = method.DeclaringType.GetCustomAttributes(false) .OfType<ApiExplorerSettingsAttribute>() .Select(attr => attr.GroupName); if (docName == ""未分类"" && versions.Count() == 0) return true; return versions.Any(v => v == docName); }}); options.IgnoreObsoleteActions(); //options.IgnoreObsoleteControllers(); // 类、方法标记 [Obsolete],可以阻止【Swagger文档】生成 options.EnableAnnotations(); options.DescribeAllEnumsAsStrings(); options.CustomSchemaIds(a => a.FullName); options.OperationFilter<FormDataOperationFilter>(); string root = Path.Combine(Directory.GetCurrentDirectory(), ""Module""); string xmlFile = string.Empty; string[] dirs = Directory.GetDirectories(root); foreach (var d in dirs) {{ xmlFile = Path.Combine(d, $""{{new DirectoryInfo(d).Name}}.xml""); if (File.Exists(xmlFile)) options.IncludeXmlComments(xmlFile); // 使用前需开启项目注释 xmldoc }} var InfrastructureXml = Directory.GetFiles(Directory.GetCurrentDirectory(), ""Infrastructure.xml"", SearchOption.AllDirectories); if (InfrastructureXml.Any()) options.IncludeXmlComments(InfrastructureXml[0]); }}); return services; }} static string[] _docs = new[] {{ ""未分类"", ""公共"", ""cms"", ""后台管理"" }}; public static IApplicationBuilder UseCustomizedSwagger(this IApplicationBuilder app, IHostingEnvironment env) {{ return app.UseSwagger().UseSwaggerUI(options => {{ foreach (var doc in _docs) options.SwaggerEndpoint($""/swagger/{{doc}}/swagger.json"", doc); }}); }} }} }} "; #endregion public static readonly string WebHost_nlog_config = #region 内容太长已被收起 @"<?xml version=""1.0"" encoding=""utf-8"" ?> <nlog xmlns=""http://www.nlog-project.org/schemas/NLog.xsd"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" autoReload=""true"" internalLogLevel=""Warn"" internalLogFile=""internal-nlog.txt""> <!-- Load the ASP.NET Core plugin --> <extensions> <add assembly=""NLog.Web.AspNetCore""/> </extensions> <!-- Layout: https://github.com/NLog/NLog/wiki/Layout%20Renderers --> <targets> <target xsi:type=""File"" name=""allfile"" fileName=""../nlog/all-${{shortdate}}.log"" layout=""${{longdate}}|${{logger}}|${{uppercase:${{level}}}}|${{message}} ${{exception}}|${{aspnet-Request-Url}}"" /> <target xsi:type=""File"" name=""ownFile-web"" fileName=""../nlog/own-${{shortdate}}.log"" layout=""${{longdate}}|${{logger}}|${{uppercase:${{level}}}}| ${{message}} ${{exception}}|${{aspnet-Request-Url}}"" /> <target xsi:type=""File"" name=""SQLExecuter"" fileName=""../nlog/SQLExecuter-${{shortdate}}.log"" layout=""${{longdate}} ${{message}} ${{exception}}|${{aspnet-Request-Url}} ${{document-uri}} "" /> <target xsi:type=""Null"" name=""blackhole"" /> </targets> <rules> <logger name=""*"" minlevel=""Error"" writeTo=""allfile"" /> <logger name=""Microsoft.*"" minlevel=""Error"" writeTo=""blackhole"" final=""true"" /> <logger name=""*"" minlevel=""Error"" writeTo=""ownFile-web"" /> <logger name=""{0}_DAL_sqlhelper"" minlevel=""Warn"" writeTo=""SQLExecuter"" /> </rules> </nlog> "; #endregion public static readonly string WebHost_appsettings_json = #region 内容太长已被收起 @"{{ ""Logging"": {{ ""IncludeScopes"": false, ""LogLevel"": {{ ""Default"": ""Debug"", ""System"": ""Information"", ""Microsoft"": ""Information"" }} }}, ""ConnectionStrings"": {{ ""{0}_mysql"": ""{{connectionString}};SslMode=none;Max pool size=100"", ""redis1"": ""127.0.0.1:6379,password=,defaultDatabase=0,poolsize=50,ssl=false,writeBuffer=20480,prefix={0}"", ""redis2"": ""127.0.0.1:6379,password=,defaultDatabase=0,poolsize=50,ssl=false,writeBuffer=20480,prefix={0}"" }}, ""{0}_BLL_ITEM_CACHE"": {{ ""Timeout"": 180 }} }} "; #endregion public static readonly string WebHost_Program_cs = #region 内容太长已被收起 @"using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using System.IO; namespace {0}.WebHost {{ public class Program {{ public static void Main(string[] args) {{ var config = new ConfigurationBuilder() .AddCommandLine(args) .Build(); //dotnet run --urls=http://0.0.0.0:5000 var host = new WebHostBuilder() .UseConfiguration(config) .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration() .UseStartup<Startup>() .Build(); host.Run(); }} }} }} "; #endregion public static readonly string WebHost_Startup_cs = #region 内容太长已被收起 @"using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc.Razor; using Microsoft.Extensions.Caching.Distributed; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using NLog.Extensions.Logging; using Swashbuckle.AspNetCore.Swagger; using System; using System.Collections.Generic; using System.Text; namespace {0}.WebHost {{ public class Startup {{ public Startup(IHostingEnvironment env) {{ var builder = new ConfigurationBuilder() .LoadInstalledModules(Modules, env) .AddCustomizedJsonFile(Modules, env, ""/var/webos/{0}/""); this.Configuration = builder.AddEnvironmentVariables().Build(); this.env = env; Newtonsoft.Json.JsonConvert.DefaultSettings = () => {{ var st = new Newtonsoft.Json.JsonSerializerSettings(); st.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter()); st.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat; st.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.RoundtripKind; return st; }}; //去掉以下注释可开启 RedisHelper 静态类 //var csredis = new CSRedis.CSRedisClient(Configuration[""ConnectionStrings:redis1""]); //单redis节点模式 //RedisHelper.Initialization(csredis); }} public static List<ModuleInfo> Modules = new List<ModuleInfo>(); public IConfiguration Configuration {{ get; }} public IHostingEnvironment env {{ get; }} public void ConfigureServices(IServiceCollection services) {{ //下面这行代码依赖redis-server,注释后系统将以memory作为缓存存储的介质 //services.AddSingleton<IDistributedCache>(new Microsoft.Extensions.Caching.Redis.CSRedisCache(RedisHelper.Instance)); services.AddSingleton<IConfiguration>(Configuration); services.AddSingleton<IHostingEnvironment>(env); services.AddScoped<CustomExceptionFilter>(); services.AddSession(a => {{ a.IdleTimeout = TimeSpan.FromMinutes(30); a.Cookie.Name = ""Session_{0}""; }}); services.AddCors(options => options.AddPolicy(""cors_all"", builder => builder.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin())); services.AddCustomizedMvc(Modules); Modules.ForEach(module => module.Initializer?.ConfigureServices(services, env)); if (env.IsDevelopment()) services.AddCustomizedSwaggerGen(); }} public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IApplicationLifetime lifetime) {{ Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); Console.OutputEncoding = Encoding.GetEncoding(""GB2312""); Console.InputEncoding = Encoding.GetEncoding(""GB2312""); loggerFactory.AddConsole(Configuration.GetSection(""Logging"")); loggerFactory.AddNLog().AddDebug(); NLog.LogManager.LoadConfiguration(""nlog.config""); if (env.IsDevelopment()) app.UseDeveloperExceptionPage(); {0}.BLL.SqlHelper.Initialization(app.ApplicationServices.GetService<IDistributedCache>(), Configuration.GetSection(""{0}_BLL_ITEM_CACHE""), Configuration[""ConnectionStrings:{0}_mysql""], /* 此参数可以配置【从数据库】 */ null, loggerFactory.CreateLogger(""{0}_DAL_sqlhelper"")); app.UseSession(); app.UseCors(""cors_all""); app.UseMvc(); app.UseCustomizedStaticFiles(Modules); Modules.ForEach(module => module.Initializer?.Configure(app, env, loggerFactory, lifetime)); if (env.IsDevelopment()) app.UseCustomizedSwagger(env); }} }} }} "; #endregion public static readonly string WebHost_csproj = #region 内容太长已被收起 @"<Project Sdk=""Microsoft.NET.Sdk.Web""> <PropertyGroup> <TargetFramework>netcoreapp2.1</TargetFramework> <WarningLevel>3</WarningLevel> <ServerGarbageCollection>false</ServerGarbageCollection> <MvcRazorCompileOnPublish>false</MvcRazorCompileOnPublish> </PropertyGroup> <ItemGroup> <Folder Include=""wwwroot\"" /> <Compile Remove=""Module\**"" /> <Compile Remove=""wwwroot\module\**"" /> <Content Remove=""Module\**"" /> <Content Remove=""wwwroot\module\**"" /> <EmbeddedResource Remove=""Module\**"" /> <EmbeddedResource Remove=""wwwroot\module\**"" /> <None Remove=""Module\**"" /> <None Remove=""wwwroot\module\**"" /> <Content Update=""nlog.config""> <CopyToOutputDirectory>Always</CopyToOutputDirectory> </Content> </ItemGroup> <ItemGroup> <ProjectReference Include=""..\Infrastructure\Infrastructure.csproj"" /> </ItemGroup> <ItemGroup> <PackageReference Include=""Microsoft.AspNetCore.App"" /> </ItemGroup> <Target Name=""PostBuild"" AfterTargets=""PostBuildEvent""> <Exec Command=""gulp --gulpfile gulpfile.js copy-module"" /> </Target> </Project> "; #endregion public static readonly string Module_Admin_Controllers_SysController = #region 内容太长已被收起 @"using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; using {0}.BLL; using {0}.Model; namespace {0}.Module.Admin.Controllers {{ [Route(""[controller]"")] [Obsolete] public class SysController : Controller {{ [HttpGet(@""connection"")] public ContentResult Get_connection() {{ var sb = new StringBuilder(); var pools = new List<MySql.Data.MySqlClient.MySqlConnectionPool>(); pools.Add(SqlHelper.Pool); pools.AddRange(SqlHelper.SlavePools); for (var a = 0; a < pools.Count; a++) {{ var pool = pools[a]; sb.AppendLine($@""【{{pool.Policy.Name}}】  状态:{{(pool.IsAvailable ? ""正常"" : $""[{{pool.UnavailableTime}}] {{pool.UnavailableException.Message}}"")}} ------------------------------------------------------------------------------------------------------- {{pool.StatisticsFullily}} ""); }} return new ContentResult {{ ContentType = ""text/plan;charset=utf-8"", Content = sb.ToString() }}; }} [HttpGet(@""connection/redis"")] public ContentResult Get_connection_redis() {{ var sb = new StringBuilder(); foreach(var pool in RedisHelper.Nodes.Values) {{ sb.AppendLine($@""【{{pool.Policy.Name}}】  状态:{{(pool.IsAvailable ? ""正常"" : $""[{{pool.UnavailableTime}}] {{pool.UnavailableException.Message}}"")}} ------------------------------------------------------------------------------------------------------- Slots:{{RedisHelper.Instance.SlotCache.Count}}/16384, {{pool.StatisticsFullily}} ""); }} return new ContentResult {{ ContentType = ""text/plan;charset=utf-8"", Content = sb.ToString() }}; }} [HttpGet(@""init_sysdir"")] public APIReturn Get_init_sysdir() {{ /* if (Sysdir.SelectByParent_id(null).Count() > 0) return new APIReturn(-33, ""本系统已经初始化过,页面没经过任何操作退出。""); SysdirInfo dir1, dir2, dir3; dir1 = Sysdir.Insert(null, DateTime.Now, ""运营管理"", 1, null);{1} */ return new APIReturn(0, ""管理目录已初始化完成。""); }} }} }} "; #endregion public static readonly string Module_Admin_Controllers_LoginController = #region 内容太长已被收起 @"using System; using System.Collections.Generic; using System.Collections; using System.Linq; using System.Threading.Tasks; using System.ComponentModel.DataAnnotations; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using {0}.BLL; using {0}.Model; namespace {0}.Module.Admin.Controllers {{ [Route("""")] public class HomeController {{ [HttpGet] public RedirectResult Index() {{ return new RedirectResult(""/module/Admin""); }} }} [Route(""[controller]"")] [Obsolete] public class LoginController : BaseController {{ public LoginController(ILogger<LoginController> logger) : base(logger) {{ }} [HttpGet, 匿名访问] public ViewResult Index() {{ return View(); }} [HttpPost, 匿名访问] public APIReturn Post(LoginModel data) {{ HttpContext.Session.SetString(""login.username"", data.Username); return APIReturn.成功; }} public class LoginModel {{ [FromForm, Required(ErrorMessage = ""请输入登陆名"")] public string Username {{ get; set; }} [FromForm, Required(ErrorMessage = ""请输入密码"")] public string Password {{ get; set; }} }} }} }} "; #endregion public static readonly string Module_Admin_Views_Login_Index_cshtml = #region 内容太长已被收起 @"@{{ Layout = """"; }} <!DOCTYPE html> <html> <head> <meta charset=""utf-8""> <meta http-equiv=""X-UA-Compatible"" content=""IE=edge""> <title>{0}后台管理中心 - 登陆</title> <!-- Tell the browser to be responsive to screen width --> <meta content=""width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"" name=""viewport""> <link rel=""stylesheet"" href=""/module/admin/htm/bootstrap/css/bootstrap.min.css""> <link rel=""stylesheet"" href=""/module/admin/htm/plugins/font-awesome/css/font-awesome.min.css"" /> <link rel=""stylesheet"" href=""/module/admin/htm/css/system.css""> <script type=""text/javascript"" src=""/module/admin/htm/js/jQuery-2.1.4.min.js""></script> <script type=""text/javascript"" src=""/module/admin/htm/js/lib.js""></script> <!--[if lt IE 9]> <script type='text/javascript' src='/module/admin/htm/plugins/html5shiv/html5shiv.min.js'></script> <script type='text/javascript' src='/module/admin/htm/plugins/respond/respond.min.js'></script> <![endif]--> <style type=""text/css""> .login-box-body--has-errors{{animation:shake .5s .25s 1;-webkit-animation:shake .5s .25s 1}} @@keyframes shake{{0%,100%{{transform:translateX(0)}}20%,60%{{transform:translateX(-10px)}}40%,80%{{transform:translateX(10px)}}}} @@-webkit-keyframes shake{{0%,100%{{-webkit-transform:translateX(0)}}20%,60%{{-webkit-transform:translateX(-10px)}}40%,80%{{-webkit-transform:translateX(10px)}}}} </style> </head> <body class=""hold-transition login-page""> <div class=""login-box""> <div class=""login-logo""> <a href=""/module/admin/""><b>{0}</b>后台管理中心</a> </div> <div id=""error_msg"" style=""display:none;""> <div class=""alert alert-warning alert-dismissible""> <button type=""button"" class=""close"" data-dismiss=""alert"" aria-hidden=""true"">×</button> <h4><i class=""icon fa fa-warning""></i>警告!</h4> {{0}} </div> </div> <!-- /.login-logo --> <div class=""login-box-body""> <p class=""login-box-msg""></p> <iframe name=""iframe_form_login"" hidden></iframe> <form id=""form_login"" method=""post"" target=""iframe_form_login""> @Html.AntiForgeryToken() <input type=""hidden"" name=""__callback"" value=""login_callback"" /> <div class=""form-group has-feedback""> <input name=""username"" type=""text"" class=""form-control"" placeholder=""Username""> <span class=""glyphicon glyphicon-envelope form-control-feedback""></span> </div> <div class=""form-group has-feedback""> <input name=""password"" type=""password"" class=""form-control"" placeholder=""Password""> <span class=""glyphicon glyphicon-lock form-control-feedback""></span> </div> <div class=""row""> <div class=""col-xs-8""> </div> <!-- /.col --> <div class=""col-xs-4""> <button type=""submit"" class=""btn btn-primary btn-block btn-flat"">登 陆</button> </div> <!-- /.col --> </div> </form> </div> <!-- /.login-box-body --> </div> <!-- /.login-box --> <!-- jQuery 2.2.0 --> <script src=""/module/admin/htm/plugins/jQuery/jQuery-2.2.0.min.js""></script> <script src=""/module/admin/htm/bootstrap/js/bootstrap.min.js""></script> <script type=""text/javascript""> (function () {{ var msgtpl = $('#error_msg').html(); top.login_callback = function (rt) {{ if (rt.success) return location.href = '/module/admin/'; $('#error_msg').html(msgtpl.format(rt.message)).show(); $('div.login-box-body').addClass('login-box-body--has-errors'); setTimeout(function () {{ $('div.login-box-body').removeClass('login-box-body--has-errors'); }}, 2000); }}; }})(); </script> </body> </html> "; #endregion public static readonly string Module_Admin_Controller = #region 内容太长已被收起 @"using System; using System.Collections.Generic; using System.Collections; using System.Linq; using System.IO; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Configuration; using Newtonsoft.Json.Linq; using {0}.BLL; using {0}.Model; namespace {0}.Module.Admin.Controllers {{ [Route(""[controller]"")] public class {1}Controller : BaseController {{ public {1}Controller(ILogger<{1}Controller> logger) : base(logger) {{ }} [HttpGet] async public Task<ActionResult> List({12}[FromQuery] int limit = 20, [FromQuery] int page = 1) {{ var select = {19}{1}.Select{8};{9} var items = await select.Count(out var count){14}.Page(page, limit).ToListAsync(); ViewBag.items = items; ViewBag.count = count; return View(); }} [HttpGet(@""add"")] public ActionResult Edit() {{ return View(); }} [HttpGet(@""edit"")] async public Task<ActionResult> Edit({4}) {{ {1}Info item = await {19}{1}.GetItemAsync({5}); if (item == null) return APIReturn.记录不存在_或者没有权限; ViewBag.item = item; return View(); }} /***************************************** POST *****************************************/ [HttpPost(@""add"")] [ValidateAntiForgeryToken] async public Task<APIReturn> _Add({10}) {{ {1}Info item = new {1}Info();{13}{7} item = await {19}{1}.InsertAsync(item);{16} return APIReturn.成功.SetData(""item"", item.ToBson()); }} [HttpPost(@""edit"")] [ValidateAntiForgeryToken] async public Task<APIReturn> _Edit({4}{11}) {{ {1}Info item = await {19}{1}.GetItemAsync({5}); if (item == null) return APIReturn.记录不存在_或者没有权限;{6}{7} int affrows = await {19}{1}.UpdateAsync(item);{17} if (affrows > 0) return APIReturn.成功.SetMessage($""更新成功,影响行数:{{affrows}}""); return APIReturn.失败; }} [HttpPost(""del"")] [ValidateAntiForgeryToken]{18} }} }} "; #endregion public static readonly string Module_Admin_wwwroot_index_html = #region 内容太长已被收起 @"<!DOCTYPE html> <html lang=""zh-cmn-Hans""> <head> <meta charset=""utf-8"" /> <meta http-equiv=""X-UA-Compatible"" content=""IE=edge"" /> <title>{0}管理系统</title> <meta content=""width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"" name=""viewport"" /> <link href=""./htm/bootstrap/css/bootstrap.min.css"" rel=""stylesheet"" /> <link href=""./htm/plugins/font-awesome/css/font-awesome.min.css"" rel=""stylesheet"" /> <link href=""./htm/css/skins/_all-skins.css"" rel=""stylesheet"" /> <link href=""./htm/plugins/pace/pace.min.css"" rel=""stylesheet"" /> <link href=""./htm/plugins/datepicker/datepicker3.css"" rel=""stylesheet"" /> <link href=""./htm/plugins/timepicker/bootstrap-timepicker.min.css"" rel=""stylesheet"" /> <link href=""./htm/plugins/select2/select2.min.css"" rel=""stylesheet"" /> <link href=""./htm/plugins/treetable/css/jquery.treetable.css"" rel=""stylesheet"" /> <link href=""./htm/plugins/treetable/css/jquery.treetable.theme.default.css"" rel=""stylesheet"" /> <link href=""./htm/plugins/multiple-select/multiple-select.css"" rel=""stylesheet"" /> <link href=""./htm/css/system.css"" rel=""stylesheet"" /> <link href=""./htm/css/index.css"" rel=""stylesheet"" /> <script type=""text/javascript"" src=""./htm/js/jQuery-2.1.4.min.js""></script> <script type=""text/javascript"" src=""./htm/bootstrap/js/bootstrap.min.js""></script> <script type=""text/javascript"" src=""./htm/plugins/pace/pace.min.js""></script> <script type=""text/javascript"" src=""./htm/plugins/datepicker/bootstrap-datepicker.js""></script> <script type=""text/javascript"" src=""./htm/plugins/timepicker/bootstrap-timepicker.min.js""></script> <script type=""text/javascript"" src=""./htm/plugins/select2/select2.full.min.js""></script> <script type=""text/javascript"" src=""./htm/plugins/input-mask/jquery.inputmask.js""></script> <script type=""text/javascript"" src=""./htm/plugins/input-mask/jquery.inputmask.date.extensions.js""></script> <script type=""text/javascript"" src=""./htm/plugins/input-mask/jquery.inputmask.extensions.js""></script> <script type=""text/javascript"" src=""./htm/plugins/treetable/jquery.treetable.js""></script> <script type=""text/javascript"" src=""./htm/plugins/multiple-select/multiple-select.js""></script> <script type=""text/javascript"" src=""./htm/js/lib.js""></script> <script type=""text/javascript"" src=""./htm/js/bmw.js""></script> <!--[if lt IE 9]> <script type='text/javascript' src='./htm/plugins/html5shiv/html5shiv.min.js'></script> <script type='text/javascript' src='./htm/plugins/respond/respond.min.js'></script> <![endif]--> </head> <body class=""hold-transition skin-blue sidebar-mini""> <div class=""wrapper""> <!-- Main Header--> <header class=""main-header""> <!-- Logo--><a href=""./"" class=""logo""> <!-- mini logo for sidebar mini 50x50 pixels--><span class=""logo-mini""><b>{0}</b></span> <!-- logo for regular state and mobile devices--><span class=""logo-lg""><b>{0}管理系统</b></span> </a> <!-- Header Navbar--> <nav role=""navigation"" class=""navbar navbar-static-top""> <!-- Sidebar toggle button--><a href=""#"" data-toggle=""offcanvas"" role=""button"" class=""sidebar-toggle""><span class=""sr-only"">Toggle navigation</span></a> <!-- Navbar Right Menu--> <div class=""navbar-custom-menu""> <ul class=""nav navbar-nav""> <!-- User Account Menu--> <li class=""dropdown user user-menu""> <!-- Menu Toggle Button--><a href=""#"" data-toggle=""dropdown"" class=""dropdown-toggle""> <!-- The user image in the navbar--><img src=""/htm/img/user2-160x160.jpg"" alt=""User Image"" class=""user-image""> <!-- hidden-xs hides the username on small devices so only the image appears.--><span class=""hidden-xs""></span> </a> <ul class=""dropdown-menu""> <!-- The user image in the menu--> <li class=""user-header""> <img src=""/htm/img/user2-160x160.jpg"" alt=""User Image"" class=""img-circle""> <p></p> </li> <!-- Menu Footer--> <li class=""user-footer""> <div class=""pull-right""> <a href=""#"" onclick=""$('form#form_logout').submit();return false;"" class=""btn btn-default btn-flat"">安全退出</a> <form id=""form_logout"" method=""post"" action=""./exit.aspx""></form> </div> </li> </ul> </li> </ul> </div> </nav> </header> <!-- Left side column. contains the logo and sidebar--> <aside class=""main-sidebar""> <!-- sidebar: style can be found in sidebar.less--> <section class=""sidebar""> <!-- Sidebar Menu--> <ul class=""sidebar-menu""> <!-- Optionally, you can add icons to the links--> <li class=""treeview active""> <a href=""#""><i class=""fa fa-laptop""></i><span>通用管理</span><i class=""fa fa-angle-left pull-right""></i></a> <ul class=""treeview-menu"">{1} </ul> </li> </ul> <!-- /.sidebar-menu--> </section> <!-- /.sidebar--> </aside> <!-- Content Wrapper. Contains page content--> <div class=""content-wrapper""> <!-- Main content--> <section id=""right_content"" class=""content""> <div style=""display:none;""> <!-- Your Page Content Here--> <h1>这是一个测试首页</h1> <h2>swagger webapi:<a href='/swagger/' target='_blank'>/swagger/</a><h2> <h2>登陆地址:<a href='/login' target='_blank'>/login</a><h2> <h2><a href='/sys/connection' target='_blank'>查看 Mysql连接池</a><h2> <h2><a href='/sys/connection/redis' target='_blank'>查看 Redis连接池</a><h2> </div> </section> <!-- /.content--> </div> <!-- /.content-wrapper--> </div> <!-- ./wrapper--> <script type=""text/javascript"" src=""./htm/js/system.js""></script> <script type=""text/javascript"" src=""./htm/js/admin.js""></script> <script type=""text/javascript""> if (!location.hash) $('#right_content div:first').show(); // 路由功能 //针对上面的html初始化路由列表 function hash_encode(str) {{ return url_encode(base64.encode(str)).replace(/%/g, '_'); }} function hash_decode(str) {{ return base64.decode(url_decode(str.replace(/_/g, '%'))); }} window.div_left_router = {{}}; $('li.treeview.active ul li a').each(function(index, ele) {{ var href = $(ele).attr('href'); $(ele).attr('href', '#base64url' + hash_encode(href)); window.div_left_router[href] = $(ele).text(); }}); (function () {{ function Vipspa() {{ }} Vipspa.prototype.start = function (config) {{ Vipspa.mainView = $(config.view); startRouter(); window.onhashchange = function () {{ if (location._is_changed) return location._is_changed = false; startRouter(); }}; }}; function startRouter() {{ var hash = location.hash; if (hash === '') return //location.hash = $('li.treeview.active ul li a:first').attr('href');//'#base64url' + hash_encode('/resume_type/'); if (hash.indexOf('#base64url') !== 0) return; var act = hash_decode(hash.substr(10, hash.length - 10)); //叶湘勤增加的代码,加载或者提交form后,显示内容 function ajax_success(refererUrl) {{ if (refererUrl == location.pathname) {{ startRouter(); return function(){{}}; }} var hash = '#base64url' + hash_encode(refererUrl); if (location.hash != hash) {{ location._is_changed = true; location.hash = hash; }}'\'' return function (data, status, xhr) {{ var div; Function.prototype.ajax = $.ajax; top.mainViewNav = {{ url: refererUrl, trans: function (url) {{ var act = url; act = act.substr(0, 1) === '/' || act.indexOf('://') !== -1 || act.indexOf('data:') === 0 ? act : join_url(refererUrl, act); return act; }}, goto: function (url_or_form, target) {{ var form = url_or_form; if (typeof form === 'string') {{ var act = this.trans(form); if (String(target).toLowerCase() === '_blank') return window.open(act); location.hash = '#base64url' + hash_encode(act); }} else {{ if (!window.ajax_form_iframe_max) window.ajax_form_iframe_max = 1; window.ajax_form_iframe_max++; var iframe = $('<iframe name=""ajax_form_iframe{{0}}""></iframe>'.format(window.ajax_form_iframe_max)); Vipspa.mainView.append(iframe); var act = $(form).attr('action') || ''; act = act.substr(0, 1) === '/' || act.indexOf('://') !== -1 ? act : join_url(refererUrl, act); if ($(form).find(':file[name]').length > 0) $(form).attr('enctype', 'multipart/form-data'); $(form).attr('action', act); $(form).attr('target', iframe.attr('name')); iframe.on('load', function () {{ var doc = this.contentWindow ? this.contentWindow.document : this.document; if (doc.body.innerHTML.length === 0) return; if (doc.body.innerHTML.indexOf('Error:') === 0) return alert(doc.body.innerHTML.substr(6)); //以下 '<script ' + '是防止与本页面相匹配,不要删除 if (doc.body.innerHTML.indexOf('<script ' + 'type=""text/javascript"">location.href=""') === -1) {{ ajax_success(doc.location.pathname + doc.location.search)(doc.body.innerHTML, 200, null); }} }}); }} }}, reload: startRouter, query: qs_parseByUrl(refererUrl) }}; top.mainViewInit = function () {{ if (!div) return setTimeout(top.mainViewInit, 10); admin_init(function (selector) {{ if (/<[^>]+>/.test(selector)) return $(selector); return div.find(selector); }}, top.mainViewNav); }}; if (/<body[^>]*>/i.test(data)) data = data.match(/<body[^>]*>(([^<]|<(?!\/body>))*)<\/body>/i)[1]; div = Vipspa.mainView.html(data); }}; }}; $.ajax({{ type: 'GET', url: act, dataType: 'html', success: ajax_success(act), error: function (jqXHR, textStatus, errorThrown) {{ var data = jqXHR.responseText; if (/<body[^>]*>/i.test(data)) data = data.match(/<body[^>]*>(([^<]|<(?!\/body>))*)<\/body>/i)[1]; Vipspa.mainView.html(data); }} }}); }} window.vipspa = new Vipspa(); }})(); $(function () {{ vipspa.start({{ view: '#right_content', }}); }}); // 页面加载进度条 $(document).ajaxStart(function() {{ Pace.restart(); }}); </script> </body> </html>"; #endregion public static readonly string Module_Test_Controller = #region 内容太长已被收起 @"using System; using System.Collections.Generic; using System.Collections; using System.Linq; using System.IO; using System.Net; using System.Net.NetworkInformation; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Configuration; using Newtonsoft.Json.Linq; using {0}.BLL; using {0}.Model; namespace {0}.Module.Test.Controllers {{ [Route(""[controller]"")] public class {1}Controller : BaseController {{ public {1}Controller(ILogger<{1}Controller> logger) : base(logger) {{ }} [HttpGet] public APIReturn List() {{ return APIReturn.成功; }} }} }} "; #endregion public static readonly string Module_Test_Init_cs = #region 内容太长已被收起 @"using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Text; using {0}.BLL; using {0}.Model; namespace {0}.Module.{1} {{ /// <summary> /// 配置本 Module 依赖注入等,由 WebHost/Startup.cs 加载触发执行 /// </summary> public class Init : IModuleInitializer {{ public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IApplicationLifetime lifetime) {{ }} public void ConfigureServices(IServiceCollection services, IHostingEnvironment env) {{ }} }} }} "; #endregion public static readonly string Module_csproj = #region 内容太长已被收起 @"<Project Sdk=""Microsoft.NET.Sdk""> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningLevel>3</WarningLevel> </PropertyGroup> <ItemGroup> <ProjectReference Include=""..\..\Infrastructure\Infrastructure.csproj"" /> </ItemGroup> </Project> "; #endregion } } }
27182812/ChatGLM-LLaMA-chinese-insturct
22,022
src/transformers/models/retribert/tokenization_retribert.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. """Tokenization classes for RetriBERT.""" import collections import os import unicodedata from typing import List, Optional, Tuple from ...tokenization_utils import PreTrainedTokenizer, _is_control, _is_punctuation, _is_whitespace from ...utils import logging logger = logging.get_logger(__name__) VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt"} PRETRAINED_VOCAB_FILES_MAP = { "vocab_file": { "yjernite/retribert-base-uncased": ( "https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/vocab.txt" ), } } PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = { "yjernite/retribert-base-uncased": 512, } PRETRAINED_INIT_CONFIGURATION = { "yjernite/retribert-base-uncased": {"do_lower_case": True}, } # Copied from transformers.models.bert.tokenization_bert.load_vocab def load_vocab(vocab_file): """Loads a vocabulary file into a dictionary.""" vocab = collections.OrderedDict() with open(vocab_file, "r", encoding="utf-8") as reader: tokens = reader.readlines() for index, token in enumerate(tokens): token = token.rstrip("\n") vocab[token] = index return vocab # Copied from transformers.models.bert.tokenization_bert.whitespace_tokenize def whitespace_tokenize(text): """Runs basic whitespace cleaning and splitting on a piece of text.""" text = text.strip() if not text: return [] tokens = text.split() return tokens class RetriBertTokenizer(PreTrainedTokenizer): r""" Constructs a RetriBERT tokenizer. [`RetriBertTokenizer`] is identical to [`BertTokenizer`] and runs end-to-end tokenization: punctuation splitting and wordpiece. 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: vocab_file (`str`): File containing the vocabulary. do_lower_case (`bool`, *optional*, defaults to `True`): Whether or not to lowercase the input when tokenizing. do_basic_tokenize (`bool`, *optional*, defaults to `True`): Whether or not to do basic tokenization before WordPiece. never_split (`Iterable`, *optional*): Collection of tokens which will never be split during tokenization. Only has an effect when `do_basic_tokenize=True` 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. sep_token (`str`, *optional*, defaults to `"[SEP]"`): The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for sequence classification or for a text and a question for question answering. It is also used as the last token of a sequence built with special tokens. pad_token (`str`, *optional*, defaults to `"[PAD]"`): The token used for padding, for example when batching sequences of different lengths. cls_token (`str`, *optional*, defaults to `"[CLS]"`): The classifier token which is used when doing sequence classification (classification of the whole sequence instead of per-token classification). It is the first token of the sequence when built with special tokens. mask_token (`str`, *optional*, defaults to `"[MASK]"`): The token used for masking values. This is the token used when training this model with masked language modeling. This is the token which the model will try to predict. tokenize_chinese_chars (`bool`, *optional*, defaults to `True`): Whether or not to tokenize Chinese characters. This should likely be deactivated for Japanese (see this [issue](https://github.com/huggingface/transformers/issues/328)). strip_accents (`bool`, *optional*): Whether or not to strip all accents. If this option is not specified, then it will be determined by the value for `lowercase` (as in the original BERT). """ vocab_files_names = VOCAB_FILES_NAMES pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES pretrained_init_configuration = PRETRAINED_INIT_CONFIGURATION model_input_names = ["input_ids", "attention_mask"] # Copied from transformers.models.bert.tokenization_bert.BertTokenizer.__init__ def __init__( self, vocab_file, do_lower_case=True, do_basic_tokenize=True, never_split=None, unk_token="[UNK]", sep_token="[SEP]", pad_token="[PAD]", cls_token="[CLS]", mask_token="[MASK]", tokenize_chinese_chars=True, strip_accents=None, **kwargs, ): super().__init__( do_lower_case=do_lower_case, do_basic_tokenize=do_basic_tokenize, never_split=never_split, unk_token=unk_token, sep_token=sep_token, pad_token=pad_token, cls_token=cls_token, mask_token=mask_token, tokenize_chinese_chars=tokenize_chinese_chars, strip_accents=strip_accents, **kwargs, ) if not os.path.isfile(vocab_file): raise ValueError( f"Can't find a vocabulary file at path '{vocab_file}'. To load the vocabulary from a Google pretrained" " model use `tokenizer = BertTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`" ) self.vocab = load_vocab(vocab_file) self.ids_to_tokens = collections.OrderedDict([(ids, tok) for tok, ids in self.vocab.items()]) self.do_basic_tokenize = do_basic_tokenize if do_basic_tokenize: self.basic_tokenizer = BasicTokenizer( do_lower_case=do_lower_case, never_split=never_split, tokenize_chinese_chars=tokenize_chinese_chars, strip_accents=strip_accents, ) self.wordpiece_tokenizer = WordpieceTokenizer(vocab=self.vocab, unk_token=self.unk_token) @property # Copied from transformers.models.bert.tokenization_bert.BertTokenizer.do_lower_case def do_lower_case(self): return self.basic_tokenizer.do_lower_case @property # Copied from transformers.models.bert.tokenization_bert.BertTokenizer.vocab_size def vocab_size(self): return len(self.vocab) # Copied from transformers.models.bert.tokenization_bert.BertTokenizer.get_vocab def get_vocab(self): return dict(self.vocab, **self.added_tokens_encoder) # Copied from transformers.models.bert.tokenization_bert.BertTokenizer._tokenize def _tokenize(self, text): split_tokens = [] if self.do_basic_tokenize: for token in self.basic_tokenizer.tokenize(text, never_split=self.all_special_tokens): # If the token is part of the never_split set if token in self.basic_tokenizer.never_split: split_tokens.append(token) else: split_tokens += self.wordpiece_tokenizer.tokenize(token) else: split_tokens = self.wordpiece_tokenizer.tokenize(text) return split_tokens # Copied from transformers.models.bert.tokenization_bert.BertTokenizer._convert_token_to_id def _convert_token_to_id(self, token): """Converts a token (str) in an id using the vocab.""" return self.vocab.get(token, self.vocab.get(self.unk_token)) # Copied from transformers.models.bert.tokenization_bert.BertTokenizer._convert_id_to_token def _convert_id_to_token(self, index): """Converts an index (integer) in a token (str) using the vocab.""" return self.ids_to_tokens.get(index, self.unk_token) # Copied from transformers.models.bert.tokenization_bert.BertTokenizer.convert_tokens_to_string def convert_tokens_to_string(self, tokens): """Converts a sequence of tokens (string) in a single string.""" out_string = " ".join(tokens).replace(" ##", "").strip() return out_string # Copied from transformers.models.bert.tokenization_bert.BertTokenizer.build_inputs_with_special_tokens def build_inputs_with_special_tokens( self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None ) -> List[int]: """ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and adding special tokens. A BERT sequence has the following format: - single sequence: `[CLS] X [SEP]` - pair of sequences: `[CLS] A [SEP] B [SEP]` Args: token_ids_0 (`List[int]`): List of IDs to which the special tokens will be added. token_ids_1 (`List[int]`, *optional*): Optional second list of IDs for sequence pairs. Returns: `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens. """ if token_ids_1 is None: return [self.cls_token_id] + token_ids_0 + [self.sep_token_id] cls = [self.cls_token_id] sep = [self.sep_token_id] return cls + token_ids_0 + sep + token_ids_1 + sep # Copied from transformers.models.bert.tokenization_bert.BertTokenizer.get_special_tokens_mask def get_special_tokens_mask( self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False ) -> List[int]: """ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding special tokens using the tokenizer `prepare_for_model` method. Args: token_ids_0 (`List[int]`): List of IDs. token_ids_1 (`List[int]`, *optional*): Optional second list of IDs for sequence pairs. already_has_special_tokens (`bool`, *optional*, defaults to `False`): Whether or not the token list is already formatted with special tokens for the model. Returns: `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token. """ if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True ) if token_ids_1 is not None: return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1] return [1] + ([0] * len(token_ids_0)) + [1] # Copied from transformers.models.bert.tokenization_bert.BertTokenizer.create_token_type_ids_from_sequences def create_token_type_ids_from_sequences( self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None ) -> List[int]: """ Create a mask from the two sequences passed to be used in a sequence-pair classification task. A BERT sequence pair mask has the following format: ``` 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 | first sequence | second sequence | ``` If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s). Args: token_ids_0 (`List[int]`): List of IDs. token_ids_1 (`List[int]`, *optional*): Optional second list of IDs for sequence pairs. Returns: `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s). """ sep = [self.sep_token_id] cls = [self.cls_token_id] if token_ids_1 is None: return len(cls + token_ids_0 + sep) * [0] return len(cls + token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1] # Copied from transformers.models.bert.tokenization_bert.BertTokenizer.save_vocabulary def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]: index = 0 if os.path.isdir(save_directory): vocab_file = os.path.join( save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) else: vocab_file = (filename_prefix + "-" if filename_prefix else "") + save_directory with open(vocab_file, "w", encoding="utf-8") as writer: for token, token_index in sorted(self.vocab.items(), key=lambda kv: kv[1]): if index != token_index: logger.warning( f"Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive." " Please check that the vocabulary is not corrupted!" ) index = token_index writer.write(token + "\n") index += 1 return (vocab_file,) # Copied from transformers.models.bert.tokenization_bert.BasicTokenizer class BasicTokenizer(object): """ Constructs a BasicTokenizer that will run basic tokenization (punctuation splitting, lower casing, etc.). Args: do_lower_case (`bool`, *optional*, defaults to `True`): Whether or not to lowercase the input when tokenizing. never_split (`Iterable`, *optional*): Collection of tokens which will never be split during tokenization. Only has an effect when `do_basic_tokenize=True` tokenize_chinese_chars (`bool`, *optional*, defaults to `True`): Whether or not to tokenize Chinese characters. This should likely be deactivated for Japanese (see this [issue](https://github.com/huggingface/transformers/issues/328)). strip_accents (`bool`, *optional*): Whether or not to strip all accents. If this option is not specified, then it will be determined by the value for `lowercase` (as in the original BERT). """ def __init__(self, do_lower_case=True, never_split=None, tokenize_chinese_chars=True, strip_accents=None): if never_split is None: never_split = [] self.do_lower_case = do_lower_case self.never_split = set(never_split) self.tokenize_chinese_chars = tokenize_chinese_chars self.strip_accents = strip_accents def tokenize(self, text, never_split=None): """ Basic Tokenization of a piece of text. Split on "white spaces" only, for sub-word tokenization, see WordPieceTokenizer. Args: never_split (`List[str]`, *optional*) Kept for backward compatibility purposes. Now implemented directly at the base class level (see [`PreTrainedTokenizer.tokenize`]) List of token not to split. """ # union() returns a new set by concatenating the two sets. never_split = self.never_split.union(set(never_split)) if never_split else self.never_split text = self._clean_text(text) # This was added on November 1st, 2018 for the multilingual and Chinese # models. This is also applied to the English models now, but it doesn't # matter since the English models were not trained on any Chinese data # and generally don't have any Chinese data in them (there are Chinese # characters in the vocabulary because Wikipedia does have some Chinese # words in the English Wikipedia.). if self.tokenize_chinese_chars: text = self._tokenize_chinese_chars(text) orig_tokens = whitespace_tokenize(text) split_tokens = [] for token in orig_tokens: if token not in never_split: if self.do_lower_case: token = token.lower() if self.strip_accents is not False: token = self._run_strip_accents(token) elif self.strip_accents: token = self._run_strip_accents(token) split_tokens.extend(self._run_split_on_punc(token, never_split)) output_tokens = whitespace_tokenize(" ".join(split_tokens)) return output_tokens def _run_strip_accents(self, text): """Strips accents from a piece of text.""" text = unicodedata.normalize("NFD", text) output = [] for char in text: cat = unicodedata.category(char) if cat == "Mn": continue output.append(char) return "".join(output) def _run_split_on_punc(self, text, never_split=None): """Splits punctuation on a piece of text.""" if never_split is not None and text in never_split: return [text] chars = list(text) i = 0 start_new_word = True output = [] while i < len(chars): char = chars[i] if _is_punctuation(char): output.append([char]) start_new_word = True else: if start_new_word: output.append([]) start_new_word = False output[-1].append(char) i += 1 return ["".join(x) for x in output] def _tokenize_chinese_chars(self, text): """Adds whitespace around any CJK character.""" output = [] for char in text: cp = ord(char) if self._is_chinese_char(cp): output.append(" ") output.append(char) output.append(" ") else: output.append(char) return "".join(output) def _is_chinese_char(self, cp): """Checks whether CP is the codepoint of a CJK character.""" # This defines a "chinese character" as anything in the CJK Unicode block: # https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block) # # Note that the CJK Unicode block is NOT all Japanese and Korean characters, # despite its name. The modern Korean Hangul alphabet is a different block, # as is Japanese Hiragana and Katakana. Those alphabets are used to write # space-separated words, so they are not treated specially and handled # like the all of the other languages. if ( (cp >= 0x4E00 and cp <= 0x9FFF) or (cp >= 0x3400 and cp <= 0x4DBF) # or (cp >= 0x20000 and cp <= 0x2A6DF) # or (cp >= 0x2A700 and cp <= 0x2B73F) # or (cp >= 0x2B740 and cp <= 0x2B81F) # or (cp >= 0x2B820 and cp <= 0x2CEAF) # or (cp >= 0xF900 and cp <= 0xFAFF) or (cp >= 0x2F800 and cp <= 0x2FA1F) # ): # return True return False def _clean_text(self, text): """Performs invalid character removal and whitespace cleanup on text.""" output = [] for char in text: cp = ord(char) if cp == 0 or cp == 0xFFFD or _is_control(char): continue if _is_whitespace(char): output.append(" ") else: output.append(char) return "".join(output) # Copied from transformers.models.bert.tokenization_bert.WordpieceTokenizer class WordpieceTokenizer(object): """Runs WordPiece tokenization.""" def __init__(self, vocab, unk_token, max_input_chars_per_word=100): self.vocab = vocab self.unk_token = unk_token self.max_input_chars_per_word = max_input_chars_per_word def tokenize(self, text): """ Tokenizes a piece of text into its word pieces. This uses a greedy longest-match-first algorithm to perform tokenization using the given vocabulary. For example, `input = "unaffable"` wil return as output `["un", "##aff", "##able"]`. Args: text: A single token or whitespace separated tokens. This should have already been passed through *BasicTokenizer*. Returns: A list of wordpiece tokens. """ output_tokens = [] for token in whitespace_tokenize(text): chars = list(token) if len(chars) > self.max_input_chars_per_word: output_tokens.append(self.unk_token) continue is_bad = False start = 0 sub_tokens = [] while start < len(chars): end = len(chars) cur_substr = None while start < end: substr = "".join(chars[start:end]) if start > 0: substr = "##" + substr if substr in self.vocab: cur_substr = substr break end -= 1 if cur_substr is None: is_bad = True break sub_tokens.append(cur_substr) start = end if is_bad: output_tokens.append(self.unk_token) else: output_tokens.extend(sub_tokens) return output_tokens
2881099/csredis
1,576
src/CSRedisCore/Internal/ObjectPool/DefaultPolicy.cs
using System; using System.Threading.Tasks; namespace CSRedis.Internal.ObjectPool { public class DefaultPolicy<T> : IPolicy<T> { public string Name { get; set; } = typeof(DefaultPolicy<T>).GetType().FullName; public int PoolSize { get; set; } = 1000; public TimeSpan SyncGetTimeout { get; set; } = TimeSpan.FromSeconds(10); public TimeSpan IdleTimeout { get; set; } = TimeSpan.FromSeconds(50); public int AsyncGetCapacity { get; set; } = 10000; public bool IsThrowGetTimeoutException { get; set; } = true; public bool IsAutoDisposeWithSystem { get; set; } = true; public int CheckAvailableInterval { get; set; } = 3; public int Weight { get; set; } = 1; public Func<T> CreateObject; public Action<Object<T>> OnGetObject; public T OnCreate() { return CreateObject(); } public void OnDestroy(T obj) { } public void OnGet(Object<T> obj) { OnGetObject?.Invoke(obj); } #if net40 #else public Task OnGetAsync(Object<T> obj) { OnGetObject?.Invoke(obj); return Task.FromResult(true); } #endif public void OnGetTimeout() { } public void OnReturn(Object<T> obj) { } public bool OnCheckAvailable(Object<T> obj) { return true; } public void OnAvailable() { } public void OnUnavailable() { } } }
2881099/FreeIM
1,354
ImServer_aot/Program.cs
using Newtonsoft.Json; using System.Text; Console.WriteLine(typeof((Guid clientId, string clientMetaData))); Console.WriteLine(typeof(Tuple<Guid, string>)); var json = JsonConvert.SerializeObject((Guid.NewGuid(), new List<Guid> { Guid.NewGuid(), Guid.NewGuid() }, "xxx", true)); Console.Write(json); Console.WriteLine(JsonConvert.DeserializeObject<(Guid, List<Guid>, string, bool)>(json)); json = JsonConvert.SerializeObject((Guid.NewGuid(), "xxx")); Console.Write(json); Console.WriteLine(JsonConvert.DeserializeObject<(Guid, string)>(json)); var builder = WebApplication.CreateSlimBuilder(args); var app = builder.Build(); var configuration = app.Configuration; Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); Console.OutputEncoding = Encoding.GetEncoding("GB2312"); Console.InputEncoding = Encoding.GetEncoding("GB2312"); app.UseDeveloperExceptionPage(); var imOptions = new ImServerOptions { Redis = new FreeRedis.RedisClient(configuration["ImServerOption:RedisClient"]), Servers = configuration["ImServerOption:Servers"].Split(";"), Server = configuration["ImServerOption:Server"] }; app.UseFreeImServer(imOptions); var applicationLifeTime = app.Services.GetService<IHostApplicationLifetime>(); applicationLifeTime.ApplicationStopping.Register(() => { imOptions.Redis.Dispose(); }); app.Run($"http://{imOptions.Server}");
27182812/ChatGLM-LLaMA-chinese-insturct
9,015
src/transformers/models/retribert/tokenization_retribert_fast.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. """Tokenization classes for RetriBERT.""" import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_retribert import RetriBertTokenizer logger = logging.get_logger(__name__) VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"} PRETRAINED_VOCAB_FILES_MAP = { "vocab_file": { "yjernite/retribert-base-uncased": ( "https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/vocab.txt" ), }, "tokenizer_file": { "yjernite/retribert-base-uncased": ( "https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/tokenizer.json" ), }, } PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = { "yjernite/retribert-base-uncased": 512, } PRETRAINED_INIT_CONFIGURATION = { "yjernite/retribert-base-uncased": {"do_lower_case": True}, } class RetriBertTokenizerFast(PreTrainedTokenizerFast): r""" Construct a "fast" RetriBERT tokenizer (backed by HuggingFace's *tokenizers* library). [`RetriBertTokenizerFast`] is identical to [`BertTokenizerFast`] and runs end-to-end tokenization: punctuation splitting and wordpiece. 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`): File containing the vocabulary. do_lower_case (`bool`, *optional*, defaults to `True`): Whether or not to lowercase the input when tokenizing. 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. sep_token (`str`, *optional*, defaults to `"[SEP]"`): The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for sequence classification or for a text and a question for question answering. It is also used as the last token of a sequence built with special tokens. pad_token (`str`, *optional*, defaults to `"[PAD]"`): The token used for padding, for example when batching sequences of different lengths. cls_token (`str`, *optional*, defaults to `"[CLS]"`): The classifier token which is used when doing sequence classification (classification of the whole sequence instead of per-token classification). It is the first token of the sequence when built with special tokens. mask_token (`str`, *optional*, defaults to `"[MASK]"`): The token used for masking values. This is the token used when training this model with masked language modeling. This is the token which the model will try to predict. clean_text (`bool`, *optional*, defaults to `True`): Whether or not to clean the text before tokenization by removing any control characters and replacing all whitespaces by the classic one. tokenize_chinese_chars (`bool`, *optional*, defaults to `True`): Whether or not to tokenize Chinese characters. This should likely be deactivated for Japanese (see [this issue](https://github.com/huggingface/transformers/issues/328)). strip_accents (`bool`, *optional*): Whether or not to strip all accents. If this option is not specified, then it will be determined by the value for `lowercase` (as in the original BERT). wordpieces_prefix (`str`, *optional*, defaults to `"##"`): The prefix for subwords. """ vocab_files_names = VOCAB_FILES_NAMES pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES pretrained_init_configuration = PRETRAINED_INIT_CONFIGURATION slow_tokenizer_class = RetriBertTokenizer model_input_names = ["input_ids", "attention_mask"] # Copied from transformers.models.bert.tokenization_bert_fast.BertTokenizerFast.__init__ def __init__( self, vocab_file=None, tokenizer_file=None, do_lower_case=True, unk_token="[UNK]", sep_token="[SEP]", pad_token="[PAD]", cls_token="[CLS]", mask_token="[MASK]", tokenize_chinese_chars=True, strip_accents=None, **kwargs, ): super().__init__( vocab_file, tokenizer_file=tokenizer_file, do_lower_case=do_lower_case, unk_token=unk_token, sep_token=sep_token, pad_token=pad_token, cls_token=cls_token, mask_token=mask_token, tokenize_chinese_chars=tokenize_chinese_chars, strip_accents=strip_accents, **kwargs, ) normalizer_state = json.loads(self.backend_tokenizer.normalizer.__getstate__()) if ( normalizer_state.get("lowercase", do_lower_case) != do_lower_case or normalizer_state.get("strip_accents", strip_accents) != strip_accents or normalizer_state.get("handle_chinese_chars", tokenize_chinese_chars) != tokenize_chinese_chars ): normalizer_class = getattr(normalizers, normalizer_state.pop("type")) normalizer_state["lowercase"] = do_lower_case normalizer_state["strip_accents"] = strip_accents normalizer_state["handle_chinese_chars"] = tokenize_chinese_chars self.backend_tokenizer.normalizer = normalizer_class(**normalizer_state) self.do_lower_case = do_lower_case # Copied from transformers.models.bert.tokenization_bert_fast.BertTokenizerFast.build_inputs_with_special_tokens def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None): """ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and adding special tokens. A BERT sequence has the following format: - single sequence: `[CLS] X [SEP]` - pair of sequences: `[CLS] A [SEP] B [SEP]` Args: token_ids_0 (`List[int]`): List of IDs to which the special tokens will be added. token_ids_1 (`List[int]`, *optional*): Optional second list of IDs for sequence pairs. Returns: `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens. """ output = [self.cls_token_id] + token_ids_0 + [self.sep_token_id] if token_ids_1: output += token_ids_1 + [self.sep_token_id] return output # Copied from transformers.models.bert.tokenization_bert_fast.BertTokenizerFast.create_token_type_ids_from_sequences def create_token_type_ids_from_sequences( self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None ) -> List[int]: """ Create a mask from the two sequences passed to be used in a sequence-pair classification task. A BERT sequence pair mask has the following format: ``` 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 | first sequence | second sequence | ``` If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s). Args: token_ids_0 (`List[int]`): List of IDs. token_ids_1 (`List[int]`, *optional*): Optional second list of IDs for sequence pairs. Returns: `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s). """ sep = [self.sep_token_id] cls = [self.cls_token_id] if token_ids_1 is None: return len(cls + token_ids_0 + sep) * [0] return len(cls + token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1] # Copied from transformers.models.bert.tokenization_bert_fast.BertTokenizerFast.save_vocabulary 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)
2881099/FreeIM
11,326
FreeIM/FreeIM.xml
<?xml version="1.0"?> <doc> <assembly> <name>FreeIM</name> </assembly> <members> <member name="T:ImClient"> <summary> im 核心类实现 </summary> </member> <member name="F:ImClient.OnSend"> <summary> 推送消息的事件,可审查推向哪个Server节点 </summary> </member> <member name="M:ImClient.#ctor(ImClientOptions)"> <summary> 初始化 imclient </summary> <param name="options"></param> </member> <member name="M:ImClient.SelectServer(System.Int64)"> <summary> 负载分区规则:clientId求模 </summary> <param name="clientId">客户端id</param> <returns></returns> </member> <member name="M:ImClient.PrevConnectServer(System.Int64,System.String)"> <summary> ImServer 连接前的负载、授权,返回 ws 目标地址,使用该地址连接 websocket 服务端 </summary> <param name="clientId">客户端id</param> <param name="clientMetaData">客户端相关信息,比如ip</param> <returns>websocket 地址:ws://xxxx/ws?token=xxx</returns> </member> <member name="M:ImClient.SendMessage(System.Int64,System.Collections.Generic.IEnumerable{System.Int64},System.Object,System.Boolean)"> <summary> 向指定的多个客户端id发送消息 </summary> <param name="senderClientId">发送者的客户端id</param> <param name="receiveClientId">接收者的客户端id</param> <param name="message">消息</param> <param name="receipt">是否回执</param> </member> <member name="M:ImClient.GetClientListByOnline"> <summary> 获取所在线客户端id </summary> <returns></returns> </member> <member name="M:ImClient.HasOnline(System.Int64)"> <summary> 判断客户端是否在线 </summary> <param name="clientId"></param> <returns></returns> </member> <member name="M:ImClient.HasOnline(System.Collections.Generic.IEnumerable{System.Int64})"> <summary> 判断客户端是否在线 </summary> <param name="clientIds"></param> <returns></returns> </member> <member name="M:ImClient.ForceOffline(System.Int64)"> <summary> 强制下线 </summary> <param name="clientId"></param> </member> <member name="M:ImClient.EventBus(System.Action{System.ValueTuple{System.Int64,System.String}},System.Action{System.ValueTuple{System.Int64,System.String}})"> <summary> 事件订阅 </summary> <param name="online">上线</param> <param name="offline">下线</param> </member> <member name="M:ImClient.JoinChan(System.Int64,System.String[])"> <summary> 加入群聊频道,每次上线都必须重新加入 </summary> <param name="clientId">客户端id</param> <param name="chans">群聊频道名</param> </member> <member name="M:ImClient.LeaveChan(System.Int64,System.String[])"> <summary> 离开群聊频道 </summary> <param name="clientId">客户端id</param> <param name="chans">群聊频道名</param> </member> <member name="M:ImClient.LeaveChan(System.String,System.Int64[])"> <summary> 离开群聊频道 </summary> <param name="chan">群聊频道名</param> <param name="clientIds">客户端id</param> </member> <member name="M:ImClient.GetChanClientList(System.String)"> <summary> 获取群聊频道所有客户端id(测试) </summary> <param name="chan">群聊频道名</param> <returns></returns> </member> <member name="M:ImClient.ClearChanClient(System.String)"> <summary> 清理群聊频道的离线客户端(测试) </summary> <param name="chan">群聊频道名</param> </member> <member name="M:ImClient.GetChanList"> <summary> 获取所有群聊频道和在线人数 </summary> <returns>频道名和在线人数</returns> </member> <member name="M:ImClient.GetChanListByClientId(System.Int64)"> <summary> 获取用户参与的所有群聊频道 </summary> <param name="clientId">客户端id</param> <returns></returns> </member> <member name="M:ImClient.GetChanOnline(System.String)"> <summary> 获取群聊频道的在线人数 </summary> <param name="chan">群聊频道名</param> <returns>在线人数</returns> </member> <member name="M:ImClient.SendChanMessage(System.Int64,System.String,System.Object)"> <summary> 发送群聊消息,在线的用户将收到消息 </summary> <param name="senderClientId">发送者的客户端id</param> <param name="chan">群聊频道名</param> <param name="message">消息</param> </member> <member name="M:ImClient.SendBroadcastMessage(System.Object)"> <summary> 发送广播消息 </summary> <param name="message">消息</param> </member> <member name="T:ImClientOptions"> <summary> im 核心类实现的配置所需 </summary> </member> <member name="P:ImClientOptions.Redis"> <summary> 用于存储数据和发送消息 </summary> </member> <member name="P:ImClientOptions.Servers"> <summary> 负载的服务端 </summary> </member> <member name="P:ImClientOptions.PathMatch"> <summary> websocket请求的路径,默认值:/ws </summary> </member> <member name="P:ImClientOptions.JsonSerializerSettings"> <summary> Json 序列化设置 </summary> </member> <member name="P:ImSendEventArgs.SenderClientId"> <summary> 发送者的客户端id </summary> </member> <member name="P:ImSendEventArgs.ReceiveClientId"> <summary> 接收者的客户端id </summary> </member> <member name="P:ImSendEventArgs.Server"> <summary> imServer 服务器节点 </summary> </member> <member name="P:ImSendEventArgs.Message"> <summary> 消息 </summary> </member> <member name="P:ImSendEventArgs.Receipt"> <summary> 是否回执 </summary> </member> <member name="T:ImHelper"> <summary> im 核心类 ImClient 实现的静态代理类 </summary> </member> <member name="M:ImHelper.Initialization(ImClientOptions)"> <summary> 初始化 ImHelper </summary> <param name="options"></param> </member> <member name="M:ImHelper.PrevConnectServer(System.Int64,System.String)"> <summary> ImServer 连接前的负载、授权,返回 ws 目标地址,使用该地址连接 websocket 服务端 </summary> <param name="clientId">客户端id</param> <param name="clientMetaData">客户端相关信息,比如ip</param> <returns>websocket 地址:ws://xxxx/ws?token=xxx</returns> </member> <member name="M:ImHelper.SendMessage(System.Int64,System.Collections.Generic.IEnumerable{System.Int64},System.Object,System.Boolean)"> <summary> 向指定的多个客户端id发送消息 </summary> <param name="senderClientId">发送者的客户端id</param> <param name="receiveClientId">接收者的客户端id</param> <param name="message">消息</param> <param name="receipt">是否回执</param> </member> <member name="M:ImHelper.GetClientListByOnline"> <summary> 获取所在线客户端id </summary> <returns></returns> </member> <member name="M:ImHelper.HasOnline(System.Int64)"> <summary> 判断客户端是否在线 </summary> <param name="clientId"></param> <returns></returns> </member> <member name="M:ImHelper.HasOnline(System.Collections.Generic.IEnumerable{System.Int64})"> <summary> 判断客户端是否在线(多个) </summary> <param name="clientIds"></param> <returns></returns> </member> <member name="M:ImHelper.ForceOffline(System.Int64)"> <summary> 强制下线 </summary> <param name="clientId"></param> </member> <member name="M:ImHelper.EventBus(System.Action{System.ValueTuple{System.Int64,System.String}},System.Action{System.ValueTuple{System.Int64,System.String}})"> <summary> 事件订阅 </summary> <param name="online">上线</param> <param name="offline">下线</param> </member> <member name="M:ImHelper.JoinChan(System.Int64,System.String[])"> <summary> 加入群聊频道,每次上线都必须重新加入 </summary> <param name="clientId">客户端id</param> <param name="chans">群聊频道名</param> </member> <member name="M:ImHelper.LeaveChan(System.Int64,System.String[])"> <summary> 离开群聊频道 </summary> <param name="clientId">客户端id</param> <param name="chans">群聊频道名</param> </member> <member name="M:ImHelper.LeaveChan(System.String,System.Int64[])"> <summary> 离开群聊频道 </summary> <param name="chan">群聊频道名</param> <param name="clientIds">客户端id</param> </member> <member name="M:ImHelper.GetChanClientList(System.String)"> <summary> 获取群聊频道所有客户端id(测试) </summary> <param name="chan">群聊频道名</param> <returns></returns> </member> <member name="M:ImHelper.ClearChanClient(System.String)"> <summary> 清理群聊频道的离线客户端(测试) </summary> <param name="chan">群聊频道名</param> </member> <member name="M:ImHelper.GetChanList"> <summary> 获取所有群聊频道和在线人数 </summary> <returns>频道名和在线人数</returns> </member> <member name="M:ImHelper.GetChanListByClientId(System.Int64)"> <summary> 获取用户参与的所有群聊频道 </summary> <param name="clientId">客户端id</param> <returns></returns> </member> <member name="M:ImHelper.GetChanOnline(System.String)"> <summary> 获取群聊频道的在线人数 </summary> <param name="chan">群聊频道名</param> <returns>在线人数</returns> </member> <member name="M:ImHelper.SendChanMessage(System.Int64,System.String,System.Object)"> <summary> 发送群聊消息,所有在线的用户将收到消息 </summary> <param name="senderClientId">发送者的客户端id</param> <param name="chan">群聊频道名</param> <param name="message">消息</param> </member> <member name="M:ImHelper.SendBroadcastMessage(System.Object)"> <summary> 发送广播消息 </summary> <param name="message">消息</param> </member> </members> </doc>
2881099/FreeIM
12,527
FreeIM/ImClient.cs
using FreeRedis; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; /// <summary> /// im 核心类实现 /// </summary> public class ImClient { protected RedisClient _redis; protected string[] _servers; protected string _redisPrefix; protected string _pathMatch; protected JsonSerializerSettings _jsonSerializerSettings; /// <summary> /// 推送消息的事件,可审查推向哪个Server节点 /// </summary> public EventHandler<ImSendEventArgs> OnSend; /// <summary> /// 初始化 imclient /// </summary> /// <param name="options"></param> public ImClient(ImClientOptions options) { if (options.Redis == null) throw new ArgumentException("ImClientOptions.Redis 参数不能为空"); if (options.Servers.Any() == false) throw new ArgumentException("ImClientOptions.Servers 参数不能为空"); _redis = options.Redis; _servers = options.Servers; _redisPrefix = $"im_v2{options.PathMatch.Replace('/', '_')}"; _pathMatch = options.PathMatch ?? "/ws"; _jsonSerializerSettings = options.JsonSerializerSettings; } /// <summary> /// 负载分区规则:clientId求模 /// </summary> /// <param name="clientId">客户端id</param> /// <returns></returns> protected string SelectServer(long clientId) { var servers_idx = clientId % _servers.Length; if (servers_idx >= _servers.Length) servers_idx = 0; return _servers[servers_idx]; } /// <summary> /// ImServer 连接前的负载、授权,返回 ws 目标地址,使用该地址连接 websocket 服务端 /// </summary> /// <param name="clientId">客户端id</param> /// <param name="clientMetaData">客户端相关信息,比如ip</param> /// <returns>websocket 地址:ws://xxxx/ws?token=xxx</returns> public string PrevConnectServer(long clientId, string clientMetaData) { var server = SelectServer(clientId); var token = $"{Guid.NewGuid()}{Guid.NewGuid()}{Guid.NewGuid()}{Guid.NewGuid()}".Replace("-", ""); _redis.Set($"{_redisPrefix}Token{token}", JsonConvert.SerializeObject((clientId, clientMetaData), _jsonSerializerSettings), 10); return $"ws://{server}{_pathMatch}?token={token}"; } /// <summary> /// 向指定的多个客户端id发送消息 /// </summary> /// <param name="senderClientId">发送者的客户端id</param> /// <param name="receiveClientId">接收者的客户端id</param> /// <param name="message">消息</param> /// <param name="receipt">是否回执</param> public void SendMessage(long senderClientId, IEnumerable<long> receiveClientId, object message, bool receipt = false) { receiveClientId = receiveClientId.Distinct().ToArray(); Dictionary<string, ImSendEventArgs> redata = new Dictionary<string, ImSendEventArgs>(); foreach (var uid in receiveClientId) { string server = SelectServer(uid); if (redata.ContainsKey(server) == false) redata.Add(server, new ImSendEventArgs(server, senderClientId, message, receipt)); redata[server].ReceiveClientId.Add(uid); } var messageJson = JsonConvert.SerializeObject(message, _jsonSerializerSettings); using (var pipe = _redis.StartPipe()) { foreach (var sendArgs in redata.Values) { OnSend?.Invoke(this, sendArgs); pipe.Publish($"{_redisPrefix}Server{sendArgs.Server}", JsonConvert.SerializeObject((senderClientId, sendArgs.ReceiveClientId, messageJson, sendArgs.Receipt), _jsonSerializerSettings)); } pipe.EndPipe(); } } /// <summary> /// 获取所在线客户端id /// </summary> /// <returns></returns> public IEnumerable<long> GetClientListByOnline() { return _redis.HKeys($"{_redisPrefix}Online").Select(a => long.TryParse(a, out var tryval) ? tryval : 0).Where(a => a != 0); } /// <summary> /// 判断客户端是否在线 /// </summary> /// <param name="clientId"></param> /// <returns></returns> public bool HasOnline(long clientId) { return _redis.HGet<long>($"{_redisPrefix}Online", clientId.ToString()) > 0; } /// <summary> /// 判断客户端是否在线 /// </summary> /// <param name="clientIds"></param> /// <returns></returns> public bool[] HasOnline(IEnumerable<long> clientIds) { if (clientIds?.Any() != true) return new bool[0]; return _redis.HMGet<long>($"{_redisPrefix}Online", clientIds.Select(a => a.ToString()).ToArray()).Select(a => a > 0).ToArray(); } /// <summary> /// 强制下线 /// </summary> /// <param name="clientId"></param> public void ForceOffline(long clientId) { string server = SelectServer(clientId); _redis.Publish($"{_redisPrefix}Server{server}", $"__FreeIM__(ForceOffline){clientId}"); } /// <summary> /// 事件订阅 /// </summary> /// <param name="online">上线</param> /// <param name="offline">下线</param> public void EventBus( Action<(long clientId, string clientMetaData)> online, Action<(long clientId, string clientMetaData)> offline) { var chanOnline = $"evt_{_redisPrefix}Online"; var chanOffline = $"evt_{_redisPrefix}Offline"; _redis.Subscribe(new[] { chanOnline, chanOffline }, (chan, msg) => { if (chan == chanOnline) online(JsonConvert.DeserializeObject<(long clientId, string clientMetaData)>(msg as string)); if (chan == chanOffline) offline(JsonConvert.DeserializeObject<(long clientId, string clientMetaData)>(msg as string)); }); } #region 群聊频道,每次上线都必须重新加入 /// <summary> /// 加入群聊频道,每次上线都必须重新加入 /// </summary> /// <param name="clientId">客户端id</param> /// <param name="chans">群聊频道名</param> public void JoinChan(long clientId, params string[] chans) { if (chans?.Any() != true) return; using (var pipe = _redis.StartPipe()) { foreach (var chan in chans) { if (string.IsNullOrEmpty(chan)) continue; pipe.Eval($"if redis.call('HSETNX',KEYS[1],ARGV[1],0)==1 then redis.call('HSET',KEYS[2],ARGV[2],0) redis.call('HINCRBY',KEYS[3],ARGV[2],1) end return 1", new[] { $"{_redisPrefix}Chan{chan}", $"{_redisPrefix}Client{clientId}", $"{_redisPrefix}ListChan" }, new object[] { clientId, chan }); //pipe.HSet($"{_redisPrefix}Chan{chan}", clientId.ToString(), 0); //pipe.HSet($"{_redisPrefix}Client{clientId}", chan, 0); //pipe.HIncrBy($"{_redisPrefix}ListChan", chan, 1); } pipe.EndPipe(); } } /// <summary> /// 离开群聊频道 /// </summary> /// <param name="clientId">客户端id</param> /// <param name="chans">群聊频道名</param> public void LeaveChan(long clientId, params string[] chans) { if (chans?.Any() != true) return; using (var pipe = _redis.StartPipe()) { foreach (var chan in chans) { if (string.IsNullOrEmpty(chan)) continue; pipe.Eval($"if redis.call('HDEL',KEYS[1],ARGV[1])==1 then redis.call('HDEL',KEYS[2],ARGV[2]) if redis.call('HINCRBY',KEYS[3],ARGV[2],-1)<=0 then redis.call('HDEL',KEYS[3],ARGV[2]) end end return 1", new[] { $"{_redisPrefix}Chan{chan}", $"{_redisPrefix}Client{clientId}", $"{_redisPrefix}ListChan" }, new object[] { clientId, chan }); //pipe.HDel($"{_redisPrefix}Chan{chan}", clientId.ToString()); //pipe.HDel($"{_redisPrefix}Client{clientId}", chan); //pipe.Eval($"if redis.call('HINCRBY', KEYS[1], '{chan}', '-1') <= 0 then redis.call('HDEL', KEYS[1], '{chan}') end return 1", new[] { $"{_redisPrefix}ListChan" }); } pipe.EndPipe(); } } /// <summary> /// 离开群聊频道 /// </summary> /// <param name="chan">群聊频道名</param> /// <param name="clientIds">客户端id</param> public void LeaveChan(string chan, params long[] clientIds) { if (string.IsNullOrEmpty(chan)) return; if (clientIds?.Any() != true) return; using (var pipe = _redis.StartPipe()) { foreach (var clientId in clientIds) { if (string.IsNullOrEmpty(chan)) continue; pipe.Eval($"if redis.call('HDEL',KEYS[1],ARGV[1])==1 then redis.call('HDEL',KEYS[2],ARGV[2]) if redis.call('HINCRBY',KEYS[3],ARGV[2],-1)<=0 then redis.call('HDEL',KEYS[3],ARGV[2]) end end return 1", new[] { $"{_redisPrefix}Chan{chan}", $"{_redisPrefix}Client{clientId}", $"{_redisPrefix}ListChan" }, new object[] { clientId, chan }); //pipe.HDel($"{_redisPrefix}Chan{chan}", clientId.ToString()); //pipe.HDel($"{_redisPrefix}Client{clientId}", chan); //pipe.Eval($"if redis.call('HINCRBY', KEYS[1], '{chan}', '-1') <= 0 then redis.call('HDEL', KEYS[1], '{chan}') end return 1", new[] { $"{_redisPrefix}ListChan" }); } pipe.EndPipe(); } } /// <summary> /// 获取群聊频道所有客户端id(测试) /// </summary> /// <param name="chan">群聊频道名</param> /// <returns></returns> public long[] GetChanClientList(string chan) { if (string.IsNullOrEmpty(chan)) return new long[0]; return _redis.HKeys($"{_redisPrefix}Chan{chan}").Select(a => long.TryParse(a, out var tryval) ? tryval : 0).Where(a => a != 0).ToArray(); } /// <summary> /// 清理群聊频道的离线客户端(测试) /// </summary> /// <param name="chan">群聊频道名</param> public void ClearChanClient(string chan) { if (string.IsNullOrEmpty(chan)) return; var websocketIds = _redis.HKeys($"{_redisPrefix}Chan{chan}"); var offline = new List<string>(); var span = websocketIds.AsSpan(); var start = span.Length; while (start > 0) { start = start - 10; var length = 10; if (start < 0) { length = start + 10; start = 0; } var slice = span.Slice(start, length); var hvals = _redis.HMGet($"{_redisPrefix}Online", slice.ToArray().Select(b => b.ToString()).ToArray()); for (var a = length - 1; a >= 0; a--) { if (string.IsNullOrEmpty(hvals[a])) { offline.Add(span[start + a]); span[start + a] = null; } } } //删除离线订阅 if (offline.Any()) _redis.HDel($"{_redisPrefix}Chan{chan}", offline.ToArray()); } /// <summary> /// 获取所有群聊频道和在线人数 /// </summary> /// <returns>频道名和在线人数</returns> public IEnumerable<(string chan, long online)> GetChanList() { var ret = _redis.HGetAll<long>($"{_redisPrefix}ListChan"); return ret.Select(a => (a.Key, a.Value)); } /// <summary> /// 获取用户参与的所有群聊频道 /// </summary> /// <param name="clientId">客户端id</param> /// <returns></returns> public string[] GetChanListByClientId(long clientId) { return _redis.HKeys($"{_redisPrefix}Client{clientId}"); } /// <summary> /// 获取群聊频道的在线人数 /// </summary> /// <param name="chan">群聊频道名</param> /// <returns>在线人数</returns> public long GetChanOnline(string chan) { if (string.IsNullOrEmpty(chan)) return 0; return _redis.HGet<long>($"{_redisPrefix}ListChan", chan); } /// <summary> /// 发送群聊消息,在线的用户将收到消息 /// </summary> /// <param name="senderClientId">发送者的客户端id</param> /// <param name="chan">群聊频道名</param> /// <param name="message">消息</param> public void SendChanMessage(long senderClientId, string chan, object message) { var sendArgs = _servers.Select(server => new ImSendEventArgs(server, senderClientId, message, false) { Chan = chan }).ToArray(); var messageJson = JsonConvert.SerializeObject(message, _jsonSerializerSettings); using (var pipe = _redis.StartPipe()) { foreach (var arg in sendArgs) { OnSend?.Invoke(this, arg); pipe.Publish($"{_redisPrefix}Server{arg.Server}", $"__FreeIM__(ChanMessage){JsonConvert.SerializeObject((senderClientId, chan, messageJson), _jsonSerializerSettings)}"); } pipe.EndPipe(); } } /// <summary> /// 发送广播消息 /// </summary> /// <param name="message">消息</param> public void SendBroadcastMessage(object message) => SendChanMessage(0, null, message); #endregion }
2881099/dotnetGen_mysql
150,785
Server/CodeBuild(Code).cs
using System; using System.Collections.Generic; using MySql.Data.MySqlClient; using System.Text; using System.Text.RegularExpressions; using Model; namespace Server { internal partial class CodeBuild { public void SetOutput(bool[] outputs) { if (this._tables.Count == outputs.Length) { for (int a = 0; a < outputs.Length; a++) { this._tables[a].IsOutput = outputs[a]; } } } public List<BuildInfo> Build(string solutionName, bool isSolution, bool isMakeAdmin, bool isDownloadRes) { Logger.remotor.Info("Build: " + solutionName + ",isSolution: " + isSolution + ",isMakeAdmin: " + isMakeAdmin + ",isDownloadRes: " + isDownloadRes + "(" + _client.Server + "," + _client.Username + "," + _client.Password + "," + _client.Database + ")"); List<BuildInfo> loc1 = new List<BuildInfo>(); //solutionName = CodeBuild.UFString(solutionName); string dbName = CodeBuild.UFString(CodeBuild.GetCSName(_client.Database)); string connectionStringName = _client.Database + "ConnectionString"; string basicName = "Build"; string wwwroot_sitemap = ""; Dictionary<string, bool> isMakedHtmlSelect = new Dictionary<string, bool>(); StringBuilder Model_Build_ExtensionMethods_cs = new StringBuilder(); List<string> admin_controllers_syscontroller_init_sysdir = new List<string>(); StringBuilder sb1 = new StringBuilder(); StringBuilder sb2 = new StringBuilder(); StringBuilder sb3 = new StringBuilder(); StringBuilder sb4 = new StringBuilder(); StringBuilder sb5 = new StringBuilder(); StringBuilder sb6 = new StringBuilder(); StringBuilder sb7 = new StringBuilder(); StringBuilder sb8 = new StringBuilder(); StringBuilder sb9 = new StringBuilder(); StringBuilder sb10 = new StringBuilder(); StringBuilder sb11 = new StringBuilder(); StringBuilder sb12 = new StringBuilder(); StringBuilder sb13 = new StringBuilder(); StringBuilder sb14 = new StringBuilder(); StringBuilder sb15 = new StringBuilder(); StringBuilder sb16 = new StringBuilder(); StringBuilder sb17 = new StringBuilder(); StringBuilder sb18 = new StringBuilder(); StringBuilder sb19 = new StringBuilder(); StringBuilder sb20 = new StringBuilder(); StringBuilder sb21 = new StringBuilder(); StringBuilder sb22 = new StringBuilder(); StringBuilder sb23 = new StringBuilder(); StringBuilder sb24 = new StringBuilder(); StringBuilder sb25 = new StringBuilder(); StringBuilder sb26 = new StringBuilder(); StringBuilder sb27 = new StringBuilder(); StringBuilder sb28 = new StringBuilder(); StringBuilder sb29 = new StringBuilder(); AnonymousHandler clearSb = delegate () { sb1.Remove(0, sb1.Length); sb2.Remove(0, sb2.Length); sb3.Remove(0, sb3.Length); sb4.Remove(0, sb4.Length); sb5.Remove(0, sb5.Length); sb6.Remove(0, sb6.Length); sb7.Remove(0, sb7.Length); sb8.Remove(0, sb8.Length); sb9.Remove(0, sb9.Length); sb10.Remove(0, sb10.Length); sb11.Remove(0, sb11.Length); sb12.Remove(0, sb12.Length); sb13.Remove(0, sb13.Length); sb14.Remove(0, sb14.Length); sb15.Remove(0, sb15.Length); sb16.Remove(0, sb16.Length); sb17.Remove(0, sb17.Length); sb18.Remove(0, sb18.Length); sb19.Remove(0, sb19.Length); sb20.Remove(0, sb20.Length); sb21.Remove(0, sb21.Length); sb22.Remove(0, sb22.Length); sb23.Remove(0, sb23.Length); sb24.Remove(0, sb24.Length); sb25.Remove(0, sb25.Length); sb26.Remove(0, sb26.Length); sb27.Remove(0, sb27.Length); sb28.Remove(0, sb28.Length); sb29.Remove(0, sb29.Length); }; if (isSolution) { #region solution.sln sb1.AppendFormat(CONST.sln, solutionName, Guid.NewGuid().ToString().ToUpper(), Guid.NewGuid().ToString().ToUpper(), Guid.NewGuid().ToString().ToUpper(), Guid.NewGuid().ToString().ToUpper(), Guid.NewGuid().ToString().ToUpper(), Guid.NewGuid().ToString().ToUpper(), Guid.NewGuid().ToString().ToUpper(), Guid.NewGuid().ToString().ToUpper(), Guid.NewGuid().ToString().ToUpper(), Guid.NewGuid().ToString().ToUpper()); loc1.Add(new BuildInfo(string.Concat(CONST.corePath, @"..\", solutionName, ".sln"), Deflate.Compress(sb1.ToString()))); clearSb(); #endregion #region Project Infrastructure #region Controllers\BaseController.cs sb1.Append(Server.Properties.Resources.Infrastructure_Controllers_BaseController_cs); loc1.Add(new BuildInfo(string.Concat(CONST.corePath, @"Infrastructure\Controllers\BaseController.cs"), Deflate.Compress(sb1.ToString()))); clearSb(); #endregion #region Controllers\CustomExceptionFilter.cs sb1.Append(Server.Properties.Resources.Infrastructure_Controllers_CustomExceptionFilter_cs); loc1.Add(new BuildInfo(string.Concat(CONST.corePath, @"Infrastructure\Controllers\CustomExceptionFilter.cs"), Deflate.Compress(sb1.ToString()))); clearSb(); #endregion #region Extensions\GlobalExtensions.cs sb1.Append(Server.Properties.Resources.Infrastructure_Extensions_GlobalExtensions_cs); loc1.Add(new BuildInfo(string.Concat(CONST.corePath, @"Infrastructure\Extensions\GlobalExtensions.cs"), Deflate.Compress(sb1.ToString()))); clearSb(); #endregion #region ModuleBasic\IModuleInitializer.cs sb1.Append(Server.Properties.Resources.Infrastructure_ModuleBasic_IModuleInitializer_cs); loc1.Add(new BuildInfo(string.Concat(CONST.corePath, @"Infrastructure\ModuleBasic\IModuleInitializer.cs"), Deflate.Compress(sb1.ToString()))); clearSb(); #endregion #region ModuleBasic\ModuleInfo.cs sb1.Append(Server.Properties.Resources.Infrastructure_ModuleBasic_ModuleInfo_cs); loc1.Add(new BuildInfo(string.Concat(CONST.corePath, @"Infrastructure\ModuleBasic\ModuleInfo.cs"), Deflate.Compress(sb1.ToString()))); clearSb(); #endregion #region ModuleBasic\ModuleViewLocationExpander.cs sb1.Append(Server.Properties.Resources.Infrastructure_ModuleBasic_ModuleViewLocationExpander_cs); loc1.Add(new BuildInfo(string.Concat(CONST.corePath, @"Infrastructure\ModuleBasic\ModuleViewLocationExpander.cs"), Deflate.Compress(sb1.ToString()))); clearSb(); #endregion #region Infrastructure.csproj sb1.AppendFormat(CONST.Infrastructure_csproj, solutionName); loc1.Add(new BuildInfo(string.Concat(CONST.corePath, @"Infrastructure\Infrastructure.csproj"), Deflate.Compress(sb1.ToString()))); clearSb(); #endregion #endregion } foreach (TableInfo table in _tables) { if (table.IsOutput == false) continue; if (table.Type == "P") continue; //if (table.Uniques.Count == 0) { // throw new Exception("检查到表 “" + table.Owner + "." + table.Name + "” 没有设定惟一键!"); //} if (table.Columns.Count == 0) continue; #region commom variable define string uClass_Name = CodeBuild.UFString(table.ClassName); string nClass_Name = table.ClassName; string nTable_Name = string.Concat(string.IsNullOrEmpty(table.Owner) ? string.Empty : string.Concat(@"`", table.Owner, @"`."), @"`", table.Name, @"`"); //string.Concat("`", string.IsNullOrEmpty(table.Owner) ? string.Empty : string.Concat(table.Owner, "."), table.Name, "`"); string Class_Name_BLL_Full = string.Format(@"{0}.BLL.{1}", solutionName, uClass_Name); string Class_Name_Model_Full = string.Format(@"{0}.Model.{1}", solutionName, uClass_Name); string pkCsParam = ""; string pkCsParamNoType = ""; string pkCsParamNoTypeFieldInit = ""; string pkCsParamNoTypeByval = ""; string pkSqlParamFormat = ""; string pkSqlParam = ""; string pkSpNotNull = ""; string pkEvalsQuerystring = ""; string CsParam1 = ""; string CsParamNoType1 = ""; string CsParam2 = ""; string CsParamNoType2 = ""; string CsParam3 = ""; string CsParamNoType3 = ""; string csItemAllFieldCopy = ""; string pkMvcRoute = ""; string orderBy = table.Clustereds.Count > 0 ? string.Join(", ", table.Clustereds.ConvertAll<string>(delegate (ColumnInfo cli) { return "a.`" + cli.Name + "`" + (cli.Orderby == DataSort.ASC ? string.Empty : string.Concat(" ", cli.Orderby)); }).ToArray()) : table.Uniques.Count > 0 ? string.Join(", ", table.Uniques[0].ConvertAll<string>(delegate (ColumnInfo cli) { return "a.`" + cli.Name + "`" + (cli.Orderby == DataSort.ASC ? string.Empty : string.Concat(" ", cli.Orderby)); }).ToArray()) : ""; int pkSqlParamFormat_idx = -1; if (table.PrimaryKeys.Count > 0) { foreach (ColumnInfo columnInfo in table.PrimaryKeys) { pkCsParam += CodeBuild.GetCSType(columnInfo.Type, uClass_Name + columnInfo.Name.ToUpper(), columnInfo.SqlType).Replace("?", "") + " " + CodeBuild.UFString(columnInfo.Name) + ", "; pkCsParamNoType += CodeBuild.UFString(columnInfo.Name) + ", "; pkCsParamNoTypeFieldInit += UFString(columnInfo.Name) + " = " + UFString(columnInfo.Name) + ", "; pkCsParamNoTypeByval += string.Format(GetCSTypeValue(columnInfo.Type), CodeBuild.UFString(columnInfo.Name)) + ", "; pkSqlParamFormat += "`" + columnInfo.Name + "` = {" + ++pkSqlParamFormat_idx + "} AND "; pkSqlParam += "`" + columnInfo.Name + "` = ?" + columnInfo.Name + " AND "; pkSpNotNull += "isnull(?" + columnInfo.Name + ") = 0 AND "; pkEvalsQuerystring += string.Format("{0}=<%# Eval(\"{0}\") %>&", CodeBuild.UFString(columnInfo.Name)); pkMvcRoute += "{" + CodeBuild.UFString(columnInfo.Name) + "}/"; } pkCsParam = pkCsParam.Substring(0, pkCsParam.Length - 2); pkCsParamNoType = pkCsParamNoType.Substring(0, pkCsParamNoType.Length - 2); pkCsParamNoTypeFieldInit = pkCsParamNoTypeFieldInit.Substring(0, pkCsParamNoTypeFieldInit.Length - 2); pkCsParamNoTypeByval = pkCsParamNoTypeByval.Substring(0, pkCsParamNoTypeByval.Length - 2); pkSqlParamFormat = pkSqlParamFormat.Substring(0, pkSqlParamFormat.Length - 5); pkSqlParam = pkSqlParam.Substring(0, pkSqlParam.Length - 5); pkSpNotNull = pkSpNotNull.Substring(0, pkSpNotNull.Length - 5); pkEvalsQuerystring = pkEvalsQuerystring.Substring(0, pkEvalsQuerystring.Length - 1); } foreach (ColumnInfo columnInfo in table.Columns) { string getcstype = CodeBuild.GetCSType(columnInfo.Type, uClass_Name + columnInfo.Name.ToUpper(), columnInfo.SqlType); CsParam1 += getcstype + " " + CodeBuild.UFString(columnInfo.Name) + ", "; CsParamNoType1 += CodeBuild.UFString(columnInfo.Name) + ", "; csItemAllFieldCopy += string.Format(@" item.{0} = newitem.{0};", UFString(columnInfo.Name)); if (columnInfo.IsIdentity) { //CsParamNoType2 += "0, "; } else { CsParam2 += getcstype + " " + CodeBuild.UFString(columnInfo.Name) + ", "; CsParamNoType2 += string.Format("\r\n {0} = {0}, ", CodeBuild.UFString(columnInfo.Name)); if (getcstype == "DateTime?" && (columnInfo.Name.ToLower() == "create_time" || columnInfo.Name.ToLower() == "update_time") || getcstype == "bool?" && (columnInfo.Name.ToLower() == "is_deleted")) ; else { CsParam3 += getcstype + " " + UFString(columnInfo.Name) + ", "; CsParamNoType3 += string.Format("\r\n {0} = {0}, ", UFString(columnInfo.Name)); } } } CsParam1 = CsParam1.Substring(0, CsParam1.Length - 2); CsParamNoType1 = CsParamNoType1.Substring(0, CsParamNoType1.Length - 2); if (CsParam2.Length > 0) CsParam2 = CsParam2.Substring(0, CsParam2.Length - 2); if (CsParamNoType2.Length > 0) CsParamNoType2 = CsParamNoType2.Substring(0, CsParamNoType2.Length - 2); if (CsParam3.Length > 0) CsParam3 = CsParam3.Substring(0, CsParam3.Length - 2); if (CsParamNoType3.Length > 0) CsParamNoType3 = CsParamNoType3.Substring(0, CsParamNoType3.Length - 2); #endregion #region Model *.cs sb1.AppendFormat( @"using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Threading.Tasks; using Newtonsoft.Json; namespace {0}.Model {{ [JsonObject(MemberSerialization.OptIn)] public partial class {1}Info {{ #region fields ", solutionName, uClass_Name); Dictionary<string, string> innerjoinObjs = new Dictionary<string, string>(); bool Is_System_ComponentModel = false; int column_idx = -1; foreach (ColumnInfo column in table.Columns) { column_idx++; string csType = CodeBuild.GetCSType(column.Type, uClass_Name + column.Name.ToUpper(), column.SqlType); string nColumn_Name = column.Name; string uColumn_Name = CodeBuild.UFString(column.Name); string comment = _column_coments.ContainsKey(table.FullName) && _column_coments[table.FullName].ContainsKey(column.Name) ? _column_coments[table.FullName][column.Name] : column.Name; string prototype_comment = comment == column.Name ? "" : string.Format(@"/// <summary> /// {0} /// </summary> ", comment.Replace("\r\n", "\n").Replace("\n", "\r\n /// ")); sb1.AppendFormat( @" private {0} _{1}; ", csType, uColumn_Name); if (column.Type == MySqlDbType.Enum || column.Type == MySqlDbType.Set) { #region 生成 Enum/Set 枚举类型 sb16.AppendFormat(@" {2}public enum {0}{1} {{ ", uClass_Name, column.Name.ToUpper() + (column.Type == MySqlDbType.Set ? " : long" : ""), column.Type == MySqlDbType.Set ? "[Flags]\r\n " : ""); string slkdgjlksdjg = ""; int field_idx = 0; int unknow_idx = 0; string exp2 = string.Concat(column.SqlType); int quote_pos = -1; while (true) { int first_pos = quote_pos = exp2.IndexOf('\'', quote_pos + 1); if (quote_pos == -1) break; while (true) { quote_pos = exp2.IndexOf('\'', quote_pos + 1); if (quote_pos == -1) break; int r_cout = 0; //for (int p = 1; true; p++) { // if (exp2[quote_pos - p] == '\\') r_cout++; // else break; //} while(exp2[++quote_pos] == '\'') r_cout++; if (r_cout % 2 == 0/* && quote_pos - first_pos > 2*/) { string str2 = exp2.Substring(first_pos + 1, quote_pos - first_pos - 2).Replace("''", "'"); if (Regex.IsMatch(str2, @"^[\u0391-\uFFE5a-zA-Z_\$][\u0391-\uFFE5a-zA-Z_\$\d]*$")) slkdgjlksdjg += ", " + str2; else { slkdgjlksdjg += string.Format(@", /// <summary> /// {0} /// </summary> [Description(""{0}"")] Unknow{1}", str2.Replace("\"", "\\\""), ++unknow_idx); Is_System_ComponentModel = true; } if (column.Type == MySqlDbType.Set) slkdgjlksdjg += " = " + Math.Pow(2, field_idx++); if (column.Type == MySqlDbType.Enum && field_idx++ == 0) slkdgjlksdjg += " = 1"; break; } } if (quote_pos == -1) break; } sb16.Append(slkdgjlksdjg.Substring(2).TrimStart('\r', '\n', '\t')); sb16.AppendFormat(@" }}"); #endregion } string tmpinfo = string.Empty; List<string> tsvarr = new List<string>(); List<ForeignKeyInfo> fks = table.ForeignKeys.FindAll(delegate (ForeignKeyInfo fk) { int fkc1idx = 0; string fkcsBy = "By"; string fkcsParms = string.Empty; string fkcsIfNull = string.Empty; ColumnInfo fkc = fk.Columns.Find(delegate (ColumnInfo c1) { fkc1idx++; fkcsParms += string.Format(GetCSTypeValue(c1.Type), "_" + CodeBuild.UFString(c1.Name)) + ", "; fkcsIfNull += " && _" + CodeBuild.UFString(c1.Name) + " != null"; return c1.Name == column.Name; }); if (fk.ReferencedTable != null) { fk.ReferencedColumns.ForEach(delegate (ColumnInfo c1) { fkcsBy += CodeBuild.UFString(c1.Name) + "And"; }); } else { fk.ReferencedColumnNames.ForEach(delegate (string c1) { fkcsBy += CodeBuild.UFString(c1) + "And"; }); } if (fkc == null) return false; string FK_uClass_Name = fk.ReferencedTable != null ? CodeBuild.UFString(fk.ReferencedTable.ClassName) : CodeBuild.UFString(TableInfo.GetClassName(fk.ReferencedTableName)); string FK_uClass_Name_full = fk.ReferencedTable != null ? FK_uClass_Name : string.Format(@"{0}.Model.{1}", solutionName, FK_uClass_Name); string FK_uEntry_Name = fk.ReferencedTable != null ? CodeBuild.GetCSName(fk.ReferencedTable.Name) : CodeBuild.GetCSName(TableInfo.GetEntryName(fk.ReferencedTableName)); string tableNamefe3 = fk.ReferencedTable != null ? fk.ReferencedTable.Name : FK_uEntry_Name; string memberName = fk.Columns[0].Name.IndexOf(tableNamefe3) == -1 ? tableNamefe3 : (fk.Columns[0].Name.Substring(0, fk.Columns[0].Name.IndexOf(tableNamefe3)) + tableNamefe3); if (fk.Columns[0].Name.IndexOf(tableNamefe3) == 0 && fk.ReferencedTable != null) memberName = fk.ReferencedTable.ClassName; tsvarr.Add(string.Format(@"_obj_{0} = null;", memberName)); if (fkc1idx == fk.Columns.Count) { fkcsBy = fkcsBy.Remove(fkcsBy.Length - 3); fkcsParms = fkcsParms.Remove(fkcsParms.Length - 2); if (fk.ReferencedColumns.Count > 0 && fk.ReferencedColumns[0].IsPrimaryKey || fk.ReferencedTable == null && fk.ReferencedIsPrimaryKey) { fkcsBy = string.Empty; } sb1.AppendFormat( @" private {0}Info _obj_{1}; ", FK_uClass_Name_full, memberName); tmpinfo += string.Format( @" public {0}Info Obj_{1} {{ get {{ if (_obj_{1} == null{6}) _obj_{1} = BLL.{5}.GetItem{3}({4}); return _obj_{1}; }} internal set {{ _obj_{1} = value; }} }} ", FK_uClass_Name_full, memberName, solutionName, fkcsBy, fkcsParms, FK_uClass_Name, fkcsIfNull); //若不存在 Obj_外键表名,则增加,否则InnerJoin.ToList时会报错 “Obj_外键表名 不存在” //比如表只有一 creator_person_id 时,需附加成生一个 Obj_person 属性 string fkTableClassName = fk.ReferencedTable.ClassName; if (memberName == fkTableClassName) { //如果有 Obj_外键表名 属性,则不增加什么代码 if (innerjoinObjs.ContainsKey(fkTableClassName)) innerjoinObjs.Remove(fkTableClassName); innerjoinObjs.Add(fkTableClassName, ""); } else { if (innerjoinObjs.ContainsKey(fkTableClassName)) { if (!string.IsNullOrEmpty(innerjoinObjs[fkTableClassName])) //如果有多个相同外键,比如 a_person_id, b_person_id innerjoinObjs[fkTableClassName] = string.Format( @" /// <summary> /// 配合 InnerJoin .ToList 查询临时使用 /// </summary> public {0}Info Obj_{1} {{ get; internal set; }}", UFString(fkTableClassName), fkTableClassName, memberName); } else //如果只有一个外键,比如 a_person_id innerjoinObjs.Add(fkTableClassName, string.Format( @" /// <summary> /// 与 Obj_{2} 同引用 /// </summary> public {0}Info Obj_{1} {{ get {{ return this.Obj_{2}; }} internal set {{ this.Obj_{2} = value; }} }}", UFString(fkTableClassName), fkTableClassName, memberName)); } } return fkc != null; }); if (fks.Count > 0) { string tmpsetvalue = string.Format( @" {2}[JsonProperty] public {0} {1} {{ get {{ return _{1}; }} set {{ if (_{1} != value) ", csType, uColumn_Name, prototype_comment); string tsvstr = string.Join(@" ", tsvarr.ToArray()); if (fks.Count > 1) { tmpsetvalue += string.Format(@"{{ {0} }}", tsvstr); } else { tmpsetvalue += tsvstr; } tmpsetvalue += string.Format(@" _{0} = value; }} }} ", uColumn_Name); sb2.Append(tmpsetvalue); sb2.Append(tmpinfo); } else { sb2.AppendFormat( @" {2}[JsonProperty] public {0} {1} {{ get {{ return _{1}; }} set {{ _{1} = value; }} }} ", csType, uColumn_Name, prototype_comment); if (column.Type == MySqlDbType.Geometry) { /* sb2.AppendFormat( @" public {3} {1}ToGeometry() => string.IsNullOrEmpty(_{1}) ? null : new NetTopologySuite.IO.WKTReader().Read(_{1}) as {3}; ", csType, uColumn_Name, prototype_comment, GetCSTypeGeometry(column.SqlType)); */ } } sb3.AppendFormat("{0} {1}, ", csType, uColumn_Name); sb4.AppendFormat( @" _{0} = {0}; ", uColumn_Name); sb5.AppendFormat(@" __jsonIgnore.ContainsKey(""{0}"") ? string.Empty : string.Format("", {0} : {{0}}"", {1}), ", uColumn_Name, CodeBuild.GetToStringFieldConcat(column, uClass_Name + column.Name.ToUpper())); if (column.Type == MySqlDbType.Enum) sb10.AppendFormat(@" if (allField || !__jsonIgnore.ContainsKey(""{0}"")) ht[""{0}""] = {0}?.ToDescriptionOrString();", uColumn_Name); else if (column.Type == MySqlDbType.Set) sb10.AppendFormat(@" if (allField || !__jsonIgnore.ContainsKey(""{0}"")) ht[""{0}""] = {0}?.ToInt64().ToSet<{1}>().Select(a => a.ToDescriptionOrString());", uColumn_Name, uClass_Name + column.Name.ToUpper()); else sb10.AppendFormat(@" if (allField || !__jsonIgnore.ContainsKey(""{0}"")) ht[""{0}""] = {0};", uColumn_Name); sb7.AppendFormat(@" {0}, ""|"",", GetToStringStringify(column)); if (column.Type == MySqlDbType.Enum) sb8.AppendFormat(@" if (string.Compare(""null"", ret[{2}]) != 0) item.{0} = ({1})long.Parse(ret[{2}]);", uColumn_Name, uClass_Name + column.Name.ToUpper(), column_idx); else if (column.Type == MySqlDbType.Set) sb8.AppendFormat(@" if (string.Compare(""null"", ret[{2}]) != 0) item.{0} = ({1})long.Parse(ret[{2}]);", uColumn_Name, uClass_Name + column.Name.ToUpper(), column_idx); else sb8.AppendFormat(@" if (string.Compare(""null"", ret[{2}]) != 0) item.{0} = {1};", uColumn_Name, string.Format(CodeBuild.GetStringifyParse(column.Type, column.SqlType), "ret[" + column_idx + "]"), column_idx); } if (sb2.Length != 0) { sb2.Remove(sb2.Length - 2, 2); sb3.Remove(sb3.Length - 2, 2); sb5.Remove(sb5.Length - 2, 2); sb7.Remove(sb7.Length - 6, 6); } Dictionary<string, string> dic_objs = new Dictionary<string, string>(); // m -> n _tables.ForEach(delegate (TableInfo t2) { if (t2.ForeignKeys.Count > 2) { foreach(TableInfo t3 in _tables) { if (t3.FullName == t2.FullName) continue; ForeignKeyInfo fk3 = t3.ForeignKeys.Find(delegate (ForeignKeyInfo ffk3) { return ffk3.ReferencedTable.FullName == t2.FullName; }); if (fk3 != null) { if (fk3.Columns[0].IsPrimaryKey) if (fk3.Table.PrimaryKeys.Count == 1) return; //如果有外键是主键,并且它不是复合组合,则跳过 } } } ForeignKeyInfo fk_Common = null; List<ForeignKeyInfo> fks = t2.ForeignKeys.FindAll(delegate (ForeignKeyInfo ffk) { if (ffk.ReferencedTable.FullName == table.FullName/* && ffk.Table.FullName != table.FullName*/) { //注释这行条件为了增加 parent_id 的 obj 对象 fk_Common = ffk; return true; } return false; }); if (fks.Count == 0) return; ForeignKeyInfo fk = fks.Count > 1 ? fks.Find(delegate(ForeignKeyInfo ffk) { return string.Compare(table.Name + "_" + table.PrimaryKeys[0].Name, ffk.Columns[0].Name, true) == 0; }) : fks[0]; if (fk == null) fk = fks[0]; //if (fk.Table.FullName == table.FullName) return; //注释这行条件为了增加 parent_id 的 obj 对象 List<ForeignKeyInfo> fk2 = t2.ForeignKeys.FindAll(delegate (ForeignKeyInfo ffk2) { return ffk2.Columns[0].IsPrimaryKey && ffk2 != fk; }); // 1 -> 1 ForeignKeyInfo fk1v1 = table.ForeignKeys.Find(delegate (ForeignKeyInfo ffk2) { return ffk2.ReferencedTable.FullName == t2.FullName && ffk2.ReferencedColumns[0].IsPrimaryKey && ffk2.Columns[0].IsPrimaryKey; //这行条件为了增加 parent_id 的 obj 对象 }); if (fk1v1 != null) return; //t2.Columns string t2name = t2.Name; string tablename = table.Name; string addname = t2name; if (t2name.StartsWith(tablename + "_")) { addname = t2name.Substring(tablename.Length + 1); } else if (t2name.EndsWith("_" + tablename)) { addname = t2name.Remove(addname.Length - tablename.Length - 1); } else if (fk2.Count == 1 && t2name.EndsWith("_" + tablename)) { addname = t2name.Remove(t2name.Length - tablename.Length - 1); } else if (fk2.Count == 1 && t2name.EndsWith("_" + fk2[0].ReferencedTable.Name)) { addname = t2name; } string addname_schema = addname == t2.Name && t2.Owner != table.Owner ? t2.ClassName : addname; string parms1 = ""; string parmsNoneType1 = ""; string parms1_add = ""; string parmsNoneType1_add = ""; string parms2 = ""; string parmsNoneType2 = ""; string parms2_add = ""; string parmsNoneType2_add = ""; string parms3 = ""; string parmsNoneType3 = ""; string parms4 = ""; string parmsNoneType4 = ""; string parmsNoneType5 = ""; string pkNamesNoneType = ""; string updateDiySet = ""; string add_or_flag = "Add"; int ms = 0; //若中间表,两外键指向相同表,则选择 表名_主键名 此字段作为主参考字段 string main_column = fk.Columns[0].Name; var pkName = fk.ReferencedColumns[0].Name; foreach (ColumnInfo columnInfo in t2.Columns) { string csType = GetCSType(columnInfo.Type, "", columnInfo.SqlType); bool is_addignore = columnInfo.IsPrimaryKey && csType == "Guid?" || columnInfo.Name.ToLower() == "update_time" && csType == "DateTime?" || columnInfo.Name.ToLower() == "create_time" && csType == "DateTime?"; if (string.Compare(columnInfo.Name, main_column, true) == 0) { parmsNoneType2 += string.Format("\r\n {0} = this.{1}, ", CodeBuild.UFString(columnInfo.Name), CodeBuild.UFString(pkName)); //if (!is_addignore) parmsNoneType2_add += string.Format("\r\n {0} = this.{1}, ", CodeBuild.UFString(columnInfo.Name), CodeBuild.UFString(pkName)); parmsNoneType4 += string.Format(GetCSTypeValue(columnInfo.Type), "this." + CodeBuild.UFString(pkName)) + ", "; parmsNoneType5 += string.Format("\r\n item.{0} = this.{1};", CodeBuild.UFString(columnInfo.Name), CodeBuild.UFString(pkName)); if (columnInfo.IsPrimaryKey) pkNamesNoneType += string.Format(GetCSTypeValue(fk.ReferencedColumns[0].Type), "this." + CodeBuild.UFString(pkName)) + ", "; continue; } if (columnInfo.IsPrimaryKey) pkNamesNoneType += string.Format(GetCSTypeValue(columnInfo.Type), CodeBuild.UFString(columnInfo.Name)) + ", "; else if (columnInfo.Name.ToLower() == "create_time" && csType == "DateTime?") ; else updateDiySet += string.Format("\r\n\t\t\t\t.Set{0}({0})", CodeBuild.UFString(columnInfo.Name)); if (columnInfo.IsIdentity) { //parmsNoneType2 += "0, "; continue; } parms2 += CodeBuild.GetCSType(columnInfo.Type, CodeBuild.UFString(t2.ClassName) + columnInfo.Name.ToUpper(), columnInfo.SqlType) + " " + CodeBuild.UFString(columnInfo.Name) + ", "; parmsNoneType2 += string.Format("\r\n {0} = {0}, ", CodeBuild.UFString(columnInfo.Name)); if (!is_addignore) { parms2_add += CodeBuild.GetCSType(columnInfo.Type, CodeBuild.UFString(t2.ClassName) + columnInfo.Name.ToUpper(), columnInfo.SqlType) + " " + CodeBuild.UFString(columnInfo.Name) + ", "; parmsNoneType2_add += string.Format("\r\n {0} = {0}, ", CodeBuild.UFString(columnInfo.Name)); } ForeignKeyInfo fkk3 = t2.ForeignKeys.Find(delegate (ForeignKeyInfo fkk33) { return fkk33.Columns[0].Name == columnInfo.Name; }); if (fkk3 == null) { parms1 += CodeBuild.GetCSType(columnInfo.Type, CodeBuild.UFString(t2.ClassName) + columnInfo.Name.ToUpper(), columnInfo.SqlType) + " " + CodeBuild.UFString(columnInfo.Name) + ", "; parmsNoneType1 += CodeBuild.UFString(columnInfo.Name) + ", "; if (!is_addignore) { parms1_add += CodeBuild.GetCSType(columnInfo.Type, CodeBuild.UFString(t2.ClassName) + columnInfo.Name.ToUpper(), columnInfo.SqlType) + " " + CodeBuild.UFString(columnInfo.Name) + ", "; parmsNoneType1_add += CodeBuild.UFString(columnInfo.Name) + ", "; } } else { string fkk3_ReferencedTable_ObjName = fkk3.ReferencedTable.Name; string endStr = "_" + fkk3.ReferencedTable.Name + "_" + fkk3.ReferencedColumns[0].Name; if (columnInfo.Name.EndsWith(endStr)) fkk3_ReferencedTable_ObjName = columnInfo.Name.Remove(columnInfo.Name.Length - fkk3.ReferencedColumns[0].Name.Length - 1); fkk3_ReferencedTable_ObjName = CodeBuild.UFString(fkk3_ReferencedTable_ObjName); parms1 += CodeBuild.UFString(fkk3.ReferencedTable.ClassName) + "Info " + fkk3_ReferencedTable_ObjName + ", "; parmsNoneType1 += fkk3_ReferencedTable_ObjName + "." + CodeBuild.UFString(fkk3.ReferencedColumns[0].Name) + ", "; if (!is_addignore) { parms1_add += CodeBuild.UFString(fkk3.ReferencedTable.ClassName) + "Info " + fkk3_ReferencedTable_ObjName + ", "; parmsNoneType1_add += fkk3_ReferencedTable_ObjName + "." + CodeBuild.UFString(fkk3.ReferencedColumns[0].Name) + ", "; } if (columnInfo.IsPrimaryKey) { parms3 += CodeBuild.UFString(fkk3.ReferencedTable.ClassName) + "Info " + fkk3_ReferencedTable_ObjName + ", "; parmsNoneType3 += fkk3_ReferencedTable_ObjName + "." + CodeBuild.UFString(fkk3.ReferencedColumns[0].Name) + ", "; parms4 += CodeBuild.GetCSType(columnInfo.Type, CodeBuild.UFString(t2.ClassName) + columnInfo.Name.ToUpper(), columnInfo.SqlType) + " " + CodeBuild.UFString(columnInfo.Name) + ", "; parmsNoneType4 += string.Format(GetCSTypeValue(columnInfo.Type), CodeBuild.UFString(columnInfo.Name)) + ", "; } if (add_or_flag != "Flag" && fk.Columns[0].IsPrimaryKey) //中间表关系键,必须为主键 t2.Uniques.ForEach(delegate (List<ColumnInfo> cs) { if (cs.Count < 2) return; ms = 0; foreach (ColumnInfo c in cs) { if (t2.ForeignKeys.Find(delegate (ForeignKeyInfo ffkk2) { return ffkk2.Columns[0].Name == c.Name; }) != null) ms++; } if (ms == cs.Count) { add_or_flag = "Flag"; } }); } } if (parms1.Length > 0) parms1 = parms1.Remove(parms1.Length - 2); if (parmsNoneType1.Length > 0) parmsNoneType1 = parmsNoneType1.Remove(parmsNoneType1.Length - 2); if (parms1_add.Length > 0) parms1_add = parms1_add.Remove(parms1_add.Length - 2); if (parmsNoneType1_add.Length > 0) parmsNoneType1_add = parmsNoneType1_add.Remove(parmsNoneType1_add.Length - 2); if (parms2.Length > 0) parms2 = parms2.Remove(parms2.Length - 2); if (parmsNoneType2.Length > 0) parmsNoneType2 = parmsNoneType2.Remove(parmsNoneType2.Length - 2); if (parms2_add.Length > 0) parms2_add = parms2_add.Remove(parms2_add.Length - 2); if (parmsNoneType2_add.Length > 0) parmsNoneType2_add = parmsNoneType2_add.Remove(parmsNoneType2_add.Length - 2); if (parms3.Length > 0) parms3 = parms3.Remove(parms3.Length - 2); if (parmsNoneType3.Length > 0) parmsNoneType3 = parmsNoneType3.Remove(parmsNoneType3.Length - 2); if (parms4.Length > 0) parms4 = parms4.Remove(parms4.Length - 2); if (parmsNoneType4.Length > 0) parmsNoneType4 = parmsNoneType4.Remove(parmsNoneType4.Length - 2); if (pkNamesNoneType.Length > 0) pkNamesNoneType = pkNamesNoneType.Remove(pkNamesNoneType.Length - 2); if (add_or_flag == "Flag") { if (parms1 != parms2) { sb6.AppendFormat(@" public {0}Info Flag{1}({2}) => Flag{1}({3});", CodeBuild.UFString(t2.ClassName), CodeBuild.UFString(addname_schema), parms1, parmsNoneType1); sb17.AppendFormat(@" async public Task<{0}Info> Flag{1}Async({2}) => await Flag{1}Async({3});", CodeBuild.UFString(t2.ClassName), CodeBuild.UFString(addname_schema), parms1, parmsNoneType1); } sb6.AppendFormat(@" public {0}Info Flag{1}({2}) {{ {0}Info item = BLL.{0}.GetItem({5}); if (item == null) item = BLL.{0}.Insert(new {0}Info {{{3}}});{6} return item; }} ", CodeBuild.UFString(t2.ClassName), CodeBuild.UFString(addname_schema), parms2, parmsNoneType2.Replace("\t\t\t", "\t\t\t\t"), solutionName, pkNamesNoneType, updateDiySet.Length > 0 ? "\r\n\t\t\telse item.UpdateDiy" + updateDiySet + ".ExecuteNonQuery();" : string.Empty); sb17.AppendFormat(@" async public Task<{0}Info> Flag{1}Async({2}) {{ {0}Info item = await BLL.{0}.GetItemAsync({5}); if (item == null) item = await BLL.{0}.InsertAsync(new {0}Info {{{3}}});{6} return item; }} ", CodeBuild.UFString(t2.ClassName), CodeBuild.UFString(addname_schema), parms2, parmsNoneType2.Replace("\t\t\t", "\t\t\t\t"), solutionName, pkNamesNoneType, updateDiySet.Length > 0 ? "\r\n\t\t\telse await item.UpdateDiy" + updateDiySet + ".ExecuteNonQueryAsync();" : string.Empty); } else { //sb6.Append(addname + "," + t2.Name); if (parms1_add != parms2_add) { sb6.AppendFormat(@" public {0}Info Add{1}({2}) => Add{1}({3});", CodeBuild.UFString(t2.ClassName), CodeBuild.UFString(addname_schema), parms1_add, parmsNoneType1_add); sb17.AppendFormat(@" async public Task<{0}Info> Add{1}Async({2}) => await Add{1}Async({3});", CodeBuild.UFString(t2.ClassName), CodeBuild.UFString(addname_schema), parms1_add, parmsNoneType1_add); } sb6.AppendFormat(@" public {0}Info Add{1}({2}) => Add{1}(new {0}Info {{{3}}}); public {0}Info Add{1}({0}Info item) {{{5} return BLL.{0}.Insert(item); }} ", CodeBuild.UFString(t2.ClassName), CodeBuild.UFString(addname_schema), parms2_add, parmsNoneType2_add, solutionName, parmsNoneType5); sb17.AppendFormat(@" async public Task<{0}Info> Add{1}Async({2}) => await Add{1}Async(new {0}Info {{{3}}}); async public Task<{0}Info> Add{1}Async({0}Info item) {{{5} return await BLL.{0}.InsertAsync(item); }} ", CodeBuild.UFString(t2.ClassName), CodeBuild.UFString(addname_schema), parms2_add, parmsNoneType2_add, solutionName, parmsNoneType5); } if (add_or_flag == "Flag") { string deleteByUniqui = string.Empty; for (int deleteByUniqui_a = 0; deleteByUniqui_a < fk.Table.Uniques.Count; deleteByUniqui_a++) if (fk.Table.Uniques[deleteByUniqui_a].Count > 1 && fk.Table.Uniques[deleteByUniqui_a][0].IsPrimaryKey == false) { foreach (ColumnInfo deleteByuniquiCol in fk.Table.Uniques[deleteByUniqui_a]) deleteByUniqui = deleteByUniqui + "And" + CodeBuild.UFString(deleteByuniquiCol.Name); deleteByUniqui = "By" + deleteByUniqui.Substring(3); break; } sb6.AppendFormat(@" public int Unflag{1}({2}) => Unflag{1}({3}); public int Unflag{1}({4}) => BLL.{0}.Delete{9}({5}); public int Unflag{1}ALL() => BLL.{0}.DeleteBy{8}(this.{7}); ", CodeBuild.UFString(t2.ClassName), CodeBuild.UFString(addname_schema), parms3, parmsNoneType3, parms4, parmsNoneType4, solutionName, CodeBuild.UFString(pkName), CodeBuild.UFString(fk.Columns[0].Name), deleteByUniqui); sb17.AppendFormat(@" async public Task<int> Unflag{1}Async({2}) => await Unflag{1}Async({3}); async public Task<int> Unflag{1}Async({4}) => await BLL.{0}.Delete{9}Async({5}); async public Task<int> Unflag{1}ALLAsync() => await BLL.{0}.DeleteBy{8}Async(this.{7}); ", CodeBuild.UFString(t2.ClassName), CodeBuild.UFString(addname_schema), parms3, parmsNoneType3, parms4, parmsNoneType4, solutionName, CodeBuild.UFString(pkName), CodeBuild.UFString(fk.Columns[0].Name), deleteByUniqui); if (ms > 2) { } else { string civ = string.Format(GetCSTypeValue(fk.ReferencedColumns[0].Type), "_" + CodeBuild.UFString(pkName)); string f5 = t2name; //if (addname != f5) { string fk20_ReferencedTable_Name = fk2[0].ReferencedTable.Name; string fk_ReferencedTable_Name = fk.ReferencedTable.Name; if (f5.StartsWith(fk20_ReferencedTable_Name + "_")) f5 = f5.Substring(fk20_ReferencedTable_Name.Length + 1); else if (f5.EndsWith("_" + fk20_ReferencedTable_Name)) f5 = f5.Remove(f5.Length - fk20_ReferencedTable_Name.Length - 1); else if (string.Compare(t2name, fk20_ReferencedTable_Name + "_" + fk_ReferencedTable_Name) != 0 && string.Compare(t2name, fk_ReferencedTable_Name + "_" + fk20_ReferencedTable_Name) != 0) f5 = addname_schema; //} string objs_value = string.Format(@" private List<{0}Info> _obj_{1}s; public List<{0}Info> Obj_{1}s => _obj_{1}s ?? (_obj_{1}s = BLL.{0}.SelectBy{5}_{4}({3}).ToList());", CodeBuild.UFString(fk2[0].ReferencedTable.ClassName), addname, solutionName, civ, fk2[0].ReferencedTable.PrimaryKeys[0].Name, CodeBuild.UFString(f5)); //如果中间表字段 > 2,那么应该把其中间表也查询出来 if (t2.Columns.Count > 2) { string _f6 = fk.Columns[0].Name; string _f7 = fk.ReferencedTable.PrimaryKeys[0].Name; string _f8 = fk2[0].Columns[0].Name; string _f9 = GetCSType(fk2[0].ReferencedTable.PrimaryKeys[0].Type, CodeBuild.UFString(fk2[0].ReferencedTable.ClassName) + fk2[0].ReferencedTable.PrimaryKeys[0].Name.ToUpper(), fk2[0].ReferencedTable.PrimaryKeys[0].SqlType).Replace("?", ""); if (fk.ReferencedTable.ClassName == fk2[0].ReferencedTable.ClassName && string.Compare(main_column, fk.Columns[0].Name, true) != 0) { _f6 = fk2[0].Columns[0].Name; _f7 = fk2[0].ReferencedTable.PrimaryKeys[0].Name; _f8 = fk.Columns[0].Name; _f9 = GetCSType(fk2[0].Table.PrimaryKeys[0].Type, CodeBuild.UFString(fk2[0].Table.ClassName) + fk2[0].Table.PrimaryKeys[0].Name.ToUpper(), fk2[0].Table.PrimaryKeys[0].SqlType).Replace("?", ""); } objs_value = string.Format(@" public {2}Info Obj_{3} {{ set; get; }} private List<{0}Info> _obj_{1}s; /// <summary> /// 遍历时,可通过 Obj_{3} 可获取中间表数据 /// </summary> public List<{0}Info> Obj_{1}s =>_obj_{1}s ?? (_obj_{1}s = BLL.{0}.Select.InnerJoin<BLL.{2}>(""b"", ""b.`{6}` = a.`{5}`"").Where(""b.`{4}` = {{0}}"", {7}).ToList());", CodeBuild.UFString(fk2[0].ReferencedTable.ClassName), addname_schema, CodeBuild.UFString(t2.ClassName), t2.ClassName, _f6, _f7, _f8, civ.Replace(".Value", "")); } string objs_key = string.Format("Obj_{0}s", addname); if (dic_objs.ContainsKey(objs_key)) dic_objs[objs_key] = objs_value; else dic_objs.Add(objs_key, objs_value); } } else { string f2 = fk.Columns[0].Name.CompareTo("parent_id") == 0 ? t2name : fk.Columns[0].Name.Replace(tablename + "_" + table.PrimaryKeys[0].Name, "") + t2name; if (fk.Columns[0].IsPrimaryKey && fk.Table.PrimaryKeys.Count == 1) { //1对1关系,不应该生成 obj_xxxs string obj_value = string.Format(@" private {0}Info _obj_{1}; public {0}Info Obj_{1} {{ get {{ return _obj_{1} ?? (_{4} == null ? null : (_obj_{1} = BLL.{0}.GetItem(_{5}))); }} internal set {{ _obj_{1} = value; }} }}", CodeBuild.UFString(t2.ClassName), t2.ClassName, solutionName, CodeBuild.UFString(fk.Columns[0].Name), CodeBuild.UFString(fk.ReferencedColumns[0].Name), string.Format(GetCSTypeValue(fk.ReferencedColumns[0].Type), UFString(fk.ReferencedColumns[0].Name))); string objs_key = string.Format("Obj_{0}s", f2); if (!dic_objs.ContainsKey(objs_key)) dic_objs.Add(objs_key, obj_value); } else { string objs_value = string.Format(@" private List<{0}Info> _obj_{1}s; public List<{0}Info> Obj_{1}s => _obj_{1}s ?? (_obj_{1}s = BLL.{0}.SelectBy{3}(_{4}).Limit(500).ToList());", CodeBuild.UFString(t2.ClassName), f2, solutionName, CodeBuild.UFString(fk.Columns[0].Name), CodeBuild.UFString(table.PrimaryKeys[0].Name)); string objs_key = string.Format("Obj_{0}s", f2); if (!dic_objs.ContainsKey(objs_key)) dic_objs.Add(objs_key, objs_value); } } }); string[] dic_objs_values = new string[dic_objs.Count]; dic_objs.Values.CopyTo(dic_objs_values, 0); sb9.Append(string.Join("", dic_objs_values)); string[] innerjoinObjs_values = new string[innerjoinObjs.Count]; innerjoinObjs.Values.CopyTo(innerjoinObjs_values, 0); sb9.Append(string.Join("", innerjoinObjs_values)); string pkupdatediy = ""; if (table.PrimaryKeys.Count > 0) { string newguid = ""; foreach (ColumnInfo guidpk in table.PrimaryKeys) if (GetCSType(guidpk.Type, "", guidpk.SqlType) == "Guid?") newguid += string.Format(@" this.{0} = Guid.NewGuid();", UFString(guidpk.Name)); if (table.Columns.Count > table.PrimaryKeys.Count || !string.IsNullOrEmpty(newguid)) { ColumnInfo colUpdateTime = table.Columns.Find(delegate (ColumnInfo fcc) { return fcc.Name.ToLower() == "update_time" && GetCSType(fcc.Type, "", fcc.SqlType) == "DateTime?"; }); ColumnInfo colCreateTime = table.Columns.Find(delegate (ColumnInfo fcc) { return fcc.Name.ToLower() == "create_time" && GetCSType(fcc.Type, "", fcc.SqlType) == "DateTime?"; }); sb6.Insert(0, string.Format(@" public {1}Info Save() {{{2} if (this.{4} != null) {{ if (BLL.{1}.Update(this) == 0) return BLL.{1}.Insert(this); return this; }}{5}{3} return BLL.{1}.Insert(this); }}", solutionName, uClass_Name, colUpdateTime != null ? @" this." + UFString(colUpdateTime.Name) + " = DateTime.Now;" : "", colCreateTime != null ? @" this." + UFString(colCreateTime.Name) + " = DateTime.Now;" : "", pkCsParamNoType.Replace(", ", " != null && this."), newguid)); sb17.Insert(0, string.Format(@" async public Task<{1}Info> SaveAsync() {{{2} if (this.{4} != null) {{ if (await BLL.{1}.UpdateAsync(this) == 0) return await BLL.{1}.InsertAsync(this); return this; }}{5}{3} return await BLL.{1}.InsertAsync(this); }}", solutionName, uClass_Name, colUpdateTime != null ? @" this." + UFString(colUpdateTime.Name) + " = DateTime.Now;" : "", colCreateTime != null ? @" this." + UFString(colCreateTime.Name) + " = DateTime.Now;" : "", pkCsParamNoType.Replace(", ", " != null && this."), newguid)); } string[] pkisnullfields = pkCsParamNoTypeByval.Split(new string[] { ", " }, StringSplitOptions.None); string pkisnull = ""; foreach (string pkisnullfield in pkisnullfields) { if (pkisnullfield.EndsWith(".Value")) pkisnull += string.Format("_{0} == null || ", pkisnullfield.Replace(".Value", "")); } string pkisnullf3 = ""; if (!string.IsNullOrEmpty(pkisnull)) pkisnullf3 = string.Format("{0} ? null : ", pkisnull.Substring(0, pkisnull.Length - 4)); pkupdatediy = string.Format(@" public {0}.DAL.{1}.SqlUpdateBuild UpdateDiy => {3}BLL.{1}.UpdateDiy(new List<{1}Info> {{ this }}); ", solutionName, uClass_Name, pkCsParamNoTypeByval.Replace(", ", ", _"), pkisnullf3); } sb1.AppendFormat( @" #endregion public {0}Info() {{ }}", uClass_Name); //sb1.AppendFormat(@" // // [Obsolete] // public {0}Info({1}) {{ //{2} }}", uClass_Name, sb3.ToString(), sb4.ToString()); sb1.AppendFormat(@" {1}{2} #region 序列化,反序列化 protected static readonly string StringifySplit = ""@<{0}(Info]?#>""; public string Stringify() {{ return string.Concat({7}); }} public static {0}Info Parse(string stringify) {{ if (string.IsNullOrEmpty(stringify) || stringify == ""null"") return null; string[] ret = stringify.Split(new char[] {{ '|' }}, {6}, StringSplitOptions.None); if (ret.Length != {6}) throw new Exception($""格式不正确,{0}Info:{{stringify}}""); {0}Info item = new {0}Info();{8} return item; }} #endregion #region override private static Lazy<Dictionary<string, bool>> __jsonIgnoreLazy = new Lazy<Dictionary<string, bool>>(() => {{ FieldInfo field = typeof({0}Info).GetField(""JsonIgnore""); Dictionary<string, bool> ret = new Dictionary<string, bool>(); if (field != null) string.Concat(field.GetValue(null)).Split(',').ToList().ForEach(f => {{ if (!string.IsNullOrEmpty(f)) ret[f] = true; }}); return ret; }}); private static Dictionary<string, bool> __jsonIgnore => __jsonIgnoreLazy.Value; public override string ToString() {{ string json = string.Concat({3}, "" }}""); return string.Concat(""{{"", json.Substring(1)); }} public IDictionary ToBson(bool allField = false) {{ IDictionary ht = new Hashtable();{10} return ht; }} public object this[string key] {{ get {{ return this.GetType().GetProperty(key).GetValue(this); }} set {{ this.GetType().GetProperty(key).SetValue(this, value); }} }} #endregion #region properties {4}{9} #endregion {13} #region sync methods {5} #endregion #region async methods {12} #endregion }}{11} }} ", uClass_Name, "", "", sb5.ToString(), sb2.ToString(), sb6.ToString(), table.Columns.Count, sb7.ToString(), sb8.ToString(), sb9.ToString(), sb10.ToString(), sb16.ToString(), sb17.ToString(), pkupdatediy); loc1.Add(new BuildInfo(string.Concat(CONST.corePath, solutionName, @".db\Model\", basicName, @"\", uClass_Name, "Info.cs"), Deflate.Compress(Is_System_ComponentModel ? sb1.ToString().Replace("using System.Reflection;", "using System.ComponentModel;\r\nusing System.Reflection;") : sb1.ToString()))); clearSb(); Model_Build_ExtensionMethods_cs.AppendFormat(@" public static string ToJson(this {0}Info item) => string.Concat(item); public static string ToJson(this {0}Info[] items) => GetJson(items); public static string ToJson(this IEnumerable<{0}Info> items) => GetJson(items); public static IDictionary[] ToBson(this {0}Info[] items, Func<{0}Info, object> func = null) => GetBson(items, func); public static IDictionary[] ToBson(this IEnumerable<{0}Info> items, Func<{0}Info, object> func = null) => GetBson(items, func);", uClass_Name, solutionName); if (table.PrimaryKeys.Count > 0) Model_Build_ExtensionMethods_cs.AppendFormat(@" public static {1}.DAL.{0}.SqlUpdateBuild UpdateDiy(this List<{0}Info> items) => {1}.BLL.{0}.UpdateDiy(items);", uClass_Name, solutionName); Model_Build_ExtensionMethods_cs.AppendFormat(@" "); #endregion #region DAL *.cs #region use t-sql string sqlFields = ""; string sqlDelete = string.Format("DELETE FROM {0} ", nTable_Name); string sqlUpdate = string.Format("UPDATE {0} SET ", nTable_Name); string sqlInsert = string.Format("INSERT INTO {0}(", nTable_Name); string insertField = string.Empty; string insertParms = string.Empty; string temp1 = string.Empty; string temp2 = string.Empty; string temp3 = string.Empty; string temp4 = string.Empty; ColumnInfo identityColumn = null; foreach (ColumnInfo columnInfo in table.Columns) { if (columnInfo.IsIdentity == false) { if (columnInfo.Type == MySqlDbType.Geometry) temp1 += string.Format("`{0}` = ST_GeomFromText(?{0}), ", columnInfo.Name); else temp1 += string.Format("`{0}` = ?{0}, ", columnInfo.Name); temp2 += string.Format("`{0}`, ", columnInfo.Name); if (columnInfo.Type == MySqlDbType.Geometry) temp3 += string.Format("ST_GeomFromText(?{0}), ", columnInfo.Name); else temp3 += string.Format("?{0}, ", columnInfo.Name); } else identityColumn = columnInfo; if (columnInfo.Type == MySqlDbType.Geometry) temp4 += string.Format("AsText(a.`{0}`), ", columnInfo.Name); else temp4 += string.Format("a.`{0}`{1}, ", columnInfo.Name, columnInfo.Type == MySqlDbType.Enum || columnInfo.Type == MySqlDbType.Set ? "+0" : ""); } if (temp1.Length > 0) { temp1 = temp1.Substring(0, temp1.Length - 2); temp2 = temp2.Substring(0, temp2.Length - 2); temp3 = temp3.Substring(0, temp3.Length - 2); } temp4 = temp4.Substring(0, temp4.Length - 2); sqlFields = temp4; sqlDelete += "WHERE "; sqlUpdate += temp1 + string.Format(" WHERE {0}", pkSqlParam); sqlInsert += string.Format("{0}) VALUES({1})", temp2, temp3); insertField = temp2; insertParms = temp3; if (identityColumn != null) sqlInsert += "; SELECT LAST_INSERT_ID();"; temp1 = ""; temp2 = ""; temp3 = ""; temp4 = ""; sb1.AppendFormat( @"using System; using System.Collections.Generic; using System.Linq; using System.Data; using System.Threading.Tasks; using MySql.Data.MySqlClient; using {0}.Model; namespace {0}.DAL {{ public partial class {1} : IDAL {{ #region transact-sql define public string Table {{ get {{ return TSQL.Table; }} }} public string Field {{ get {{ return TSQL.Field; }} }} public string Sort {{ get {{ return TSQL.Sort; }} }} internal class TSQL {{ internal static readonly string Table = ""{3}""; internal static readonly string Field = ""{5}""; internal static readonly string Sort = ""{6}""; internal static readonly string Returning = ""{8}""; internal static readonly string Delete = ""DELETE FROM {3} WHERE ""; internal static readonly string InsertField = @""{2}""; internal static readonly string InsertValues = @""{4}""; internal static readonly string InsertMultiFormat = @""INSERT INTO {3}("" + InsertField + "") VALUES{{0}}""; internal static readonly string Insert = string.Format(InsertMultiFormat, $""({{InsertValues}}){{Returning}}""); }} #endregion #region common call protected static MySqlParameter GetParameter(string name, MySqlDbType type, int size, object value) {{ MySqlParameter parm = new MySqlParameter(name, type); if (size > 0) parm.Size = size; parm.Value = value; return parm; }} protected static MySqlParameter[] GetParameters({1}Info item) {{ return new MySqlParameter[] {{ {7}}}; }}", solutionName, uClass_Name, insertField, nTable_Name, insertParms, sqlFields, orderBy, CodeBuild.AppendParameters(table, " "), identityColumn != null ? "; SELECT LAST_INSERT_ID();" : ""); sb1.AppendFormat(@" public {0}Info GetItem(IDataReader dr) {{ int dataIndex = -1; return GetItem(dr, ref dataIndex) as {0}Info; }} public object GetItem(IDataReader dr, ref int dataIndex) {{ {0}Info item = new {0}Info();", uClass_Name); int getItemIndex = 0; foreach (ColumnInfo columnInfo in table.Columns) { ++getItemIndex; string csType = CodeBuild.GetCSType(columnInfo.Type, uClass_Name + columnInfo.Name.ToUpper(), columnInfo.SqlType); string csTypeGeometry = GetCSTypeGeometry(columnInfo.SqlType); if (csType == "byte[]") sb1.AppendFormat(@" if (!dr.IsDBNull(++dataIndex)) item.{0} = dr.GetValue(dataIndex) as byte[];", CodeBuild.UFString(columnInfo.Name)); else if (columnInfo.Type == MySqlDbType.Geometry && csTypeGeometry != "object") sb1.AppendFormat(@" if (!dr.IsDBNull(++dataIndex)) item.{0} = MygisGeometry.Parse(dr.GetString(dataIndex)) as {1};", CodeBuild.UFString(columnInfo.Name), csTypeGeometry); else if (columnInfo.Type == MySqlDbType.Geometry && csTypeGeometry == "object") sb1.AppendFormat(@" if (!dr.IsDBNull(++dataIndex)) item.{0} = dr.GetString(dataIndex);", CodeBuild.UFString(columnInfo.Name), csTypeGeometry); else if (columnInfo.Type == MySqlDbType.Enum) sb1.AppendFormat(@" if (!dr.IsDBNull(++dataIndex)) item.{0} = ({1}?)dr.GetInt64(dataIndex);", CodeBuild.UFString(columnInfo.Name), uClass_Name + columnInfo.Name.ToUpper()); else if (columnInfo.Type == MySqlDbType.Set) sb1.AppendFormat(@" if (!dr.IsDBNull(++dataIndex)) item.{0} = ({1}?)dr.GetInt64(dataIndex);", CodeBuild.UFString(columnInfo.Name), uClass_Name + columnInfo.Name.ToUpper()); else sb1.AppendFormat(@" if (!dr.IsDBNull(++dataIndex)) item.{0} = {1}dr.{2}(dataIndex);", CodeBuild.UFString(columnInfo.Name), CodeBuild.GetDbToCsConvert(columnInfo.Type), CodeBuild.GetDataReaderMethod(columnInfo.Type)); if (columnInfo.IsPrimaryKey) sb1.AppendFormat(@" if (item.{0} == null) {{ dataIndex += {1}; return null; }}", CodeBuild.UFString(columnInfo.Name), table.Columns.Count - getItemIndex); } sb1.AppendFormat(@" return item; }} private void CopyItemAllField({0}Info item, {0}Info newitem) {{{1} }}", uClass_Name, csItemAllFieldCopy); sb1.Append(sb4.ToString()); sb1.AppendFormat(@" #endregion", uClass_Name, table.Columns.Count + 1); string dal_async_code = string.Format(@" async public Task<{0}Info> GetItemAsync(MySqlDataReader dr) {{ var read = await GetItemAsync(dr, -1); return read.result as {0}Info; }} async public Task<(object result, int dataIndex)> GetItemAsync(MySqlDataReader dr, int dataIndex) {{ {0}Info item = new {0}Info();", uClass_Name); getItemIndex = 0; foreach (ColumnInfo columnInfo in table.Columns) { ++getItemIndex; string csType = CodeBuild.GetCSType(columnInfo.Type, uClass_Name + columnInfo.Name.ToUpper(), columnInfo.SqlType); string csTypeGeometry = GetCSTypeGeometry(columnInfo.SqlType); if (csType == "byte[]") dal_async_code += string.Format(@" if (!await dr.IsDBNullAsync(++dataIndex)) item.{0} = dr.GetValue(dataIndex) as byte[];", CodeBuild.UFString(columnInfo.Name)); else if (columnInfo.Type == MySqlDbType.Geometry && csTypeGeometry != "object") dal_async_code += string.Format(@" if (!await dr.IsDBNullAsync(++dataIndex)) item.{0} = MygisGeometry.Parse(dr.GetString(dataIndex)) as {1};", CodeBuild.UFString(columnInfo.Name), csTypeGeometry); else if (columnInfo.Type == MySqlDbType.Geometry && csTypeGeometry == "object") dal_async_code += string.Format(@" if (!await dr.IsDBNullAsync(++dataIndex)) item.{0} = dr.GetString(dataIndex);", CodeBuild.UFString(columnInfo.Name), csTypeGeometry); else if (columnInfo.Type == MySqlDbType.Enum) dal_async_code += string.Format(@" if (!await dr.IsDBNullAsync(++dataIndex)) item.{0} = ({1}?)dr.GetInt64(dataIndex);", CodeBuild.UFString(columnInfo.Name), uClass_Name + columnInfo.Name.ToUpper()); else if (columnInfo.Type == MySqlDbType.Set) dal_async_code += string.Format(@" if (!await dr.IsDBNullAsync(++dataIndex)) item.{0} = ({1}?)dr.GetInt64(dataIndex);", CodeBuild.UFString(columnInfo.Name), uClass_Name + columnInfo.Name.ToUpper()); else dal_async_code += string.Format(@" if (!await dr.IsDBNullAsync(++dataIndex)) item.{0} = {1}dr.{2}(dataIndex);", CodeBuild.UFString(columnInfo.Name), CodeBuild.GetDbToCsConvert(columnInfo.Type), CodeBuild.GetDataReaderMethod(columnInfo.Type)); if (columnInfo.IsPrimaryKey) dal_async_code += string.Format(@" if (item.{0} == null) {{ dataIndex += {1}; return (null, dataIndex); }}", CodeBuild.UFString(columnInfo.Name), table.Columns.Count - getItemIndex); } dal_async_code += string.Format(@" return (item, dataIndex); }}", uClass_Name); Dictionary<string, bool> del_exists = new Dictionary<string, bool>(); foreach (List<ColumnInfo> cs in table.Uniques) { string parms = string.Empty; string parmsBy = "By"; string sqlParms = string.Empty; string sqlParmsA = string.Empty; string sqlParmsANoneType = string.Empty; int sqlParmsAIndex = 0; foreach (ColumnInfo columnInfo in cs) { parms += CodeBuild.GetCSType(columnInfo.Type, uClass_Name + columnInfo.Name.ToUpper(), columnInfo.SqlType).Replace("?", "") + " " + CodeBuild.UFString(columnInfo.Name) + ", "; parmsBy += CodeBuild.UFString(columnInfo.Name) + "And"; sqlParms += "`" + columnInfo.Name + "` = ?" + columnInfo.Name + " AND "; sqlParmsA += "a.`" + columnInfo.Name + "` = {" + sqlParmsAIndex++ + "} AND "; sqlParmsANoneType += CodeBuild.UFString(columnInfo.Name) + ", "; } parms = parms.Substring(0, parms.Length - 2); parmsBy = parmsBy.Substring(0, parmsBy.Length - 3); sqlParms = sqlParms.Substring(0, sqlParms.Length - 5); sqlParmsA = sqlParmsA.Substring(0, sqlParmsA.Length - 5); sqlParmsANoneType = sqlParmsANoneType.Substring(0, sqlParmsANoneType.Length - 2); if (del_exists.ContainsKey(parms)) continue; del_exists.Add(parms, true); sb2.AppendFormat(@" public int Delete{2}({0}) {{ return SqlHelper.ExecuteNonQuery(string.Concat(TSQL.Delete, ""{1}""), {3}); }}", parms, sqlParms, cs[0].IsPrimaryKey ? string.Empty : parmsBy, CodeBuild.AppendParameters(cs, " ").Replace("?.ToInt64()", ".ToInt64()")); dal_async_code += string.Format(@" public Task<int> Delete{2}Async({0}) {{ return SqlHelper.ExecuteNonQueryAsync(string.Concat(TSQL.Delete, ""{1}""), {3}); }}", parms, sqlParms, cs[0].IsPrimaryKey ? string.Empty : parmsBy, CodeBuild.AppendParameters(cs, " ").Replace("?.ToInt64()", ".ToInt64()")); } table.ForeignKeys.ForEach(delegate (ForeignKeyInfo fkk) { string parms = string.Empty; string parmsBy = "By"; string sqlParms = string.Empty; foreach (ColumnInfo columnInfo in fkk.Columns) { parms += CodeBuild.GetCSType(columnInfo.Type, uClass_Name + columnInfo.Name.ToUpper(), columnInfo.SqlType) + " " + CodeBuild.UFString(columnInfo.Name) + ", "; parmsBy += CodeBuild.UFString(columnInfo.Name) + "And"; sqlParms += "`" + columnInfo.Name + "` = ?" + columnInfo.Name + " AND "; } parms = parms.Substring(0, parms.Length - 2); parmsBy = parmsBy.Substring(0, parmsBy.Length - 3); sqlParms = sqlParms.Substring(0, sqlParms.Length - 5); if (del_exists.ContainsKey(parms)) return; del_exists.Add(parms, true); sb2.AppendFormat(@" public int Delete{2}({0}) {{ return SqlHelper.ExecuteNonQuery(string.Concat(TSQL.Delete, ""{1}""), {3}); }}", parms, sqlParms, parmsBy, CodeBuild.AppendParameters(fkk.Columns, " ")); dal_async_code += string.Format(@" public Task<int> Delete{2}Async({0}) {{ return SqlHelper.ExecuteNonQueryAsync(string.Concat(TSQL.Delete, ""{1}""), {3}); }}", parms, sqlParms, parmsBy, CodeBuild.AppendParameters(fkk.Columns, " ")); }); if (table.PrimaryKeys.Count > 0) { #region 如果没有主键的处理UpdateBuild foreach (ColumnInfo col in table.Columns) { if (col.IsIdentity || col.IsPrimaryKey || table.PrimaryKeys.FindIndex(delegate (ColumnInfo pkf) { return pkf.Name == col.Name; }) != -1) continue; string lname = CodeBuild.LFString(col.Name); string valueParm = CodeBuild.AppendParameters(col, "", ""); valueParm = valueParm.Remove(valueParm.LastIndexOf(", ") + 2); if (col.Type == MySqlDbType.Geometry) sb5.AppendFormat(@" public SqlUpdateBuild Set{0}({2} value) {{ if (_dataSource != null) foreach (var item in _dataSource) item.{0} = value; return this.Set(""`{1}`"", $""ST_GeomFromText(?{1}_{{_parameters.Count}})"", {3}); }}", CodeBuild.UFString(col.Name), col.Name, CodeBuild.GetCSType(col.Type, uClass_Name + col.Name.ToUpper(), col.SqlType), CodeBuild.AppendParameters(col, "item.", "").Replace("\"?" + col.Name + "\"", "$\"?" + col.Name + "_{_parameters.Count}\"").Replace("item." + UFString(col.Name), "value")); else sb5.AppendFormat(@" public SqlUpdateBuild Set{0}({2} value) {{ if (_dataSource != null) foreach (var item in _dataSource) item.{0} = value; return this.Set(""`{1}`"", $""?{1}_{{_parameters.Count}}"", {3}value{4})); }}", CodeBuild.UFString(col.Name), col.Name, CodeBuild.GetCSType(col.Type, uClass_Name + col.Name.ToUpper(), col.SqlType), valueParm.Replace("\"?" + col.Name + "\"", "$\"?" + col.Name + "_{_parameters.Count}\""), col.Type == MySqlDbType.Enum || col.Type == MySqlDbType.Set ? "?.ToInt64()" : ""); if (table.ForeignKeys.FindIndex(delegate (ForeignKeyInfo fkf) { return fkf.Columns.FindIndex(delegate (ColumnInfo fkfpkf) { return fkfpkf.Name == col.Name; }) != -1; }) == -1) { string fptype = ""; string fpset_ = string.Format("item.{0} += value;", CodeBuild.UFString(col.Name)); string fparam = valueParm.Replace("\"?" + col.Name + "\"", "$\"?" + col.Name + "_{_parameters.Count}\""); if (col.Type == MySqlDbType.Byte || col.Type == MySqlDbType.UByte) { fptype = "byte"; fparam = fparam.Replace("MySqlDbType.UByte", "MySqlDbType.Byte"); } else if (col.Type == MySqlDbType.Int16 || col.Type == MySqlDbType.UInt16) { fptype = "short"; fparam = fparam.Replace("MySqlDbType.UInt16", "MySqlDbType.Int16"); if (col.Type == MySqlDbType.UInt16) fpset_ = string.Format("item.{0} = (ushort?)((short?)item.{0} + value);", CodeBuild.UFString(col.Name)); } else if (col.Type == MySqlDbType.Int24 || col.Type == MySqlDbType.UInt24 || col.Type == MySqlDbType.Int32 || col.Type == MySqlDbType.UInt32) { fptype = "int"; fparam = fparam.Replace("MySqlDbType.UInt24", "MySqlDbType.Int32").Replace("MySqlDbType.UInt32", "MySqlDbType.Int32"); if (col.Type == MySqlDbType.UInt24 || col.Type == MySqlDbType.UInt32) fpset_ = string.Format("item.{0} = (uint?)((int?)item.{0} + value);", CodeBuild.UFString(col.Name)); } else if (col.Type == MySqlDbType.Int64 || col.Type == MySqlDbType.UInt64) { fptype = "long"; fparam = fparam.Replace("MySqlDbType.UInt64", "MySqlDbType.Int64"); if (col.Type == MySqlDbType.UInt64) fpset_ = string.Format("item.{0} = (ulong?)((long?)item.{0} + value);", CodeBuild.UFString(col.Name)); } else if (col.Type == MySqlDbType.Double || col.Type == MySqlDbType.Float || col.Type == MySqlDbType.Decimal) { fptype = CodeBuild.GetCSType(col.Type, uClass_Name + col.Name.ToUpper(), col.SqlType).Replace("?", ""); } if ((col.Type == MySqlDbType.UInt32 || col.Type == MySqlDbType.UInt64) && (lname == "status" || lname.StartsWith("status_") || lname.EndsWith("_status"))) { fptype = ""; sb5.AppendFormat(@" public SqlUpdateBuild Set{0}Flag(int _0_16, bool isUnFlag = false) {{ {2} tmp1 = ({2})Math.Pow(2, _0_16); if (_dataSource != null) foreach (var item in _dataSource) item.{0} = isUnFlag ? ((item.{0} ?? 0) ^ tmp1) : ((item.{0} ?? 0) | tmp1); return this.Set(""`{1}`"", $""ifnull(`{1}`,0) {{(isUnFlag ? '^' : '|')}} ?{1}_{{_parameters.Count}}"", {3}tmp1)); }} public SqlUpdateBuild Set{0}UnFlag(int _0_16) {{ return this.Set{0}Flag(_0_16, true); }}", CodeBuild.UFString(col.Name), col.Name, GetCSType(col.Type, uClass_Name + col.Name.ToUpper(), col.SqlType).Replace("?", ""), valueParm.Replace("\"?" + col.Name + "\"", "string.Concat(\"?" + col.Name + "_\", _parameters.Count)")); } if (col.Type == MySqlDbType.Set) { fptype = ""; sb5.AppendFormat(@" public SqlUpdateBuild Set{0}Flag({4} value, bool isUnFlag = false) {{ if (_dataSource != null) foreach (var item in _dataSource) item.{0} = isUnFlag ? ((item.{0} ?? 0) ^ value) : ((item.{0} ?? 0) | value); return this.Set(""`{1}`"", $""ifnull(`{1}`+0,0) {{(isUnFlag ? '^' : '|')}} ?{1}_{{_parameters.Count}}"", {3}value.ToInt64())); }} public SqlUpdateBuild Set{0}UnFlag({4} value) {{ return this.Set{0}Flag(value, true); }}", CodeBuild.UFString(col.Name), col.Name, GetCSType(col.Type, uClass_Name + col.Name.ToUpper(), col.SqlType).Replace("?", ""), valueParm.Replace("\"?" + col.Name + "\"", "string.Concat(\"?" + col.Name + "_\", _parameters.Count)"), uClass_Name + col.Name.ToUpper()); } if (!string.IsNullOrEmpty(fptype)) { sb5.AppendFormat(@" public SqlUpdateBuild Set{0}Increment({2} value) {{ if (_dataSource != null) foreach (var item in _dataSource) {4} return this.Set(""`{1}`"", $""ifnull(`{1}`, 0) + ?{1}_{{_parameters.Count}}"", {3}value)); }}", CodeBuild.UFString(col.Name), col.Name, fptype, fparam, fpset_); } } sb6.AppendFormat(@" if (ignore.ContainsKey(""{1}"") == false) sub.Set{0}(item.{0});", CodeBuild.UFString(col.Name), col.Name); } string dal_insert_code = string.Format(@" public {0}Info Insert({0}Info item) {{ SqlHelper.ExecuteNonQuery(TSQL.Insert, GetParameters(item)); return item; }}", uClass_Name); if (identityColumn != null) { dal_insert_code = string.Format(@" public {0}Info Insert({0}Info item) {{ if ({2}.TryParse(string.Concat(SqlHelper.ExecuteScalar(TSQL.Insert, GetParameters(item))), out var loc1)) item.{1} = loc1; return item; }}", uClass_Name, CodeBuild.UFString(identityColumn.Name), CodeBuild.GetCSType(identityColumn.Type, uClass_Name + identityColumn.Name.ToUpper(), identityColumn.SqlType).Replace("?", "")); } if (identityColumn == null) { dal_insert_code += string.Format(@" public int Insert(IEnumerable<{0}Info> items) {{ var mp = InsertMakeParam(items); if (string.IsNullOrEmpty(mp.sql)) return 0; return SqlHelper.ExecuteNonQuery(mp.sql, mp.parms); }} public (string sql, MySqlParameter[] parms) InsertMakeParam(IEnumerable<{0}Info> items) {{ var itemsArr = items?.Where(a => a != null).ToArray(); if (itemsArr == null || itemsArr.Any() == false) return (null, null); var values = """"; var parms = new MySqlParameter[itemsArr.Length * {1}]; for (var a = 0; a < itemsArr.Length; a++) {{ var item = itemsArr[a]; values += $"",({{TSQL.InsertValues.Replace("", "", a + "", "")}}{{a}})""; var tmparms = GetParameters(item); for (var b = 0; b < tmparms.Length; b++) {{ tmparms[b].ParameterName += a; parms[a * {1} + b] = tmparms[b]; }} }} return (string.Format(TSQL.InsertMultiFormat, values.Substring(1)), parms); }}", uClass_Name, insertParms.Split(new[] { ", " }, StringSplitOptions.None).Length); } if (identityColumn != null) dal_async_code += string.Format(@" async public Task<{0}Info> InsertAsync({0}Info item) {{ if ({2}.TryParse(string.Concat(await SqlHelper.ExecuteScalarAsync(TSQL.Insert, GetParameters(item))), out var loc1)) item.{1} = loc1; return item; }}", uClass_Name, CodeBuild.UFString(identityColumn.Name), CodeBuild.GetCSType(identityColumn.Type, uClass_Name + identityColumn.Name.ToUpper(), identityColumn.SqlType).Replace("?", "")); else dal_async_code += string.Format(@" async public Task<{0}Info> InsertAsync({0}Info item) {{ await SqlHelper.ExecuteNonQueryAsync(TSQL.Insert, GetParameters(item)); return item; }}", uClass_Name); if (identityColumn == null) { dal_async_code += string.Format(@" async public Task<int> InsertAsync(IEnumerable<{0}Info> items) {{ var mp = InsertMakeParam(items); if (string.IsNullOrEmpty(mp.sql)) return 0; return await SqlHelper.ExecuteNonQueryAsync(mp.sql, mp.parms); }}", uClass_Name); } string strdalpkwherein = ""; foreach (ColumnInfo dalpkcol001 in table.PrimaryKeys) strdalpkwherein += string.Format(@" .Where(@""`{0}` IN ({{0}})"", _dataSource.Select(a => a.{1}).Distinct())", dalpkcol001.Name, UFString(dalpkcol001.Name)); if (!string.IsNullOrEmpty(strdalpkwherein)) strdalpkwherein = strdalpkwherein.Substring(strdalpkwherein.IndexOf(" ") + 6); sb1.AppendFormat(@" {1} public SqlUpdateBuild Update({0}Info item, string[] ignoreFields) {{ var sub = new SqlUpdateBuild(new List<{0}Info> {{ item }}); var ignore = ignoreFields?.ToDictionary(a => a, StringComparer.CurrentCultureIgnoreCase) ?? new Dictionary<string, string>();{8} return sub; }} #region class SqlUpdateBuild public partial class SqlUpdateBuild {{ protected List<{0}Info> _dataSource; protected Dictionary<string, {0}Info> _itemsDic; protected string _fields; protected string _where; protected List<MySqlParameter> _parameters = new List<MySqlParameter>(); public SqlUpdateBuild(List<{0}Info> dataSource) {{ _dataSource = dataSource; _itemsDic = _dataSource == null ? null : _dataSource.ToDictionary(a => $""{{a.{12}}}""); if (_dataSource != null && _dataSource.Any()) this{13}; }} public SqlUpdateBuild() {{ }} public override string ToString() {{ if (string.IsNullOrEmpty(_fields)) return string.Empty; if (string.IsNullOrEmpty(_where)) throw new Exception(""防止 {9}.DAL.{0}.SqlUpdateBuild 误修改,请必须设置 where 条件。""); return string.Concat(""UPDATE "", TSQL.Table, "" SET "", _fields.Substring(1), "" WHERE "", _where); }} public int ExecuteNonQuery() {{ string sql = this.ToString(); if (string.IsNullOrEmpty(sql)) return 0; var affrows = SqlHelper.ExecuteNonQuery(sql, _parameters.ToArray()); BLL.{0}.RemoveCache(_dataSource); return affrows; }} async public Task<int> ExecuteNonQueryAsync() {{ string sql = this.ToString(); if (string.IsNullOrEmpty(sql)) return 0; var affrows = await SqlHelper.ExecuteNonQueryAsync(sql, _parameters.ToArray()); await BLL.{0}.RemoveCacheAsync(_dataSource); return affrows; }} public SqlUpdateBuild Where(string filterFormat, params object[] values) {{ if (!string.IsNullOrEmpty(_where)) _where = string.Concat(_where, "" AND ""); _where = string.Concat(_where, ""("", SqlHelper.Addslashes(filterFormat, values), "")""); return this; }} public SqlUpdateBuild WhereExists<T>(SelectBuild<T> select) {{ return this.Where($""EXISTS({{select.ToString(""1"")}})""); }} public SqlUpdateBuild WhereNotExists<T>(SelectBuild<T> select) {{ return this.Where($""NOT EXISTS({{select.ToString(""1"")}})""); }} public SqlUpdateBuild Set(string field, string value, params MySqlParameter[] parms) {{ if (value.IndexOf('\'') != -1) throw new Exception(""{9}.DAL.{0}.SqlUpdateBuild 可能存在注入漏洞,不允许传递 ' 给参数 value,若使用正常字符串,请使用参数化传递。""); _fields = string.Concat(_fields, "", "", field, "" = "", value); if (parms != null && parms.Length > 0) _parameters.AddRange(parms); return this; }}{6} }} #endregion {10} {2} #region async{11} #endregion }} }}", uClass_Name, sb2.ToString(), sb3.ToString(), pkCsParam, pkSqlParamFormat, pkCsParamNoType, sb5.ToString(), pkCsParamNoTypeByval.Replace(", ", ", item."), sb6.ToString(), solutionName, dal_insert_code, dal_async_code, pkCsParamNoType.Replace(", ", "}_{a."), strdalpkwherein); #endregion } else { sb1.AppendFormat(@" #region async{1} #endregion }} }}", uClass_Name, dal_async_code); } #endregion loc1.Add(new BuildInfo(string.Concat(CONST.corePath, solutionName, @".db\DAL\", basicName, @"\", uClass_Name, ".cs"), Deflate.Compress(sb1.ToString()))); clearSb(); #endregion #region BLL *.cs sb1.AppendFormat( @"using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using MySql.Data.MySqlClient; using {0}.Model; namespace {0}.BLL {{ public partial class {1} {{ protected static readonly {0}.DAL.{1} dal = new {0}.DAL.{1}(); protected static readonly int itemCacheTimeout; static {1}() {{ if (!int.TryParse(SqlHelper.CacheStrategy[""Timeout_{1}""], out itemCacheTimeout)) int.TryParse(SqlHelper.CacheStrategy[""Timeout""], out itemCacheTimeout); }}", solutionName, uClass_Name); Dictionary<string, bool> uniques_dic = new Dictionary<string, bool>(); foreach (List<ColumnInfo> cs in table.Uniques) { string parms = string.Empty; foreach (ColumnInfo columnInfo in cs) { string getcstype = CodeBuild.GetCSType(columnInfo.Type, uClass_Name + columnInfo.Name.ToUpper(), columnInfo.SqlType); parms += getcstype.Replace("?", "") + " " + CodeBuild.UFString(columnInfo.Name) + ", "; } parms = parms.Substring(0, parms.Length - 2); if (uniques_dic.ContainsKey(parms)) continue; uniques_dic.Add(parms, true); } bool is_deleted_column = table.Columns.Find(delegate (ColumnInfo findIsDeleted) { string getcstype = CodeBuild.GetCSType(findIsDeleted.Type, uClass_Name + findIsDeleted.Name.ToUpper(), findIsDeleted.SqlType); return findIsDeleted.Name.ToLower() == "is_deleted" && getcstype == "bool?"; }) != null; string bll_async_code = ""; Dictionary<string, bool> del_exists2 = new Dictionary<string, bool>(); foreach (List<ColumnInfo> cs in table.Uniques) { string parms = string.Empty; string parmsNewItem = string.Empty; string parmsBy = "By"; string parmsNoneType = string.Empty; string parmsNodeTypeUpdateCacheRemove = string.Empty; string cacheCond = string.Empty; string cacheRemoveCode = string.Empty; string whereCondi = string.Empty; foreach (ColumnInfo columnInfo in cs) { string getcstype = CodeBuild.GetCSType(columnInfo.Type, uClass_Name + columnInfo.Name.ToUpper(), columnInfo.SqlType); parms += getcstype.Replace("?", "") + " " + CodeBuild.UFString(columnInfo.Name) + ", "; parmsNewItem += CodeBuild.UFString(columnInfo.Name) + " = " + CodeBuild.UFString(columnInfo.Name) + ", "; parmsBy += CodeBuild.UFString(columnInfo.Name) + "And"; parmsNoneType += CodeBuild.UFString(columnInfo.Name) + ", "; parmsNodeTypeUpdateCacheRemove += "item." + CodeBuild.UFString(columnInfo.Name) + ", \"_,_\", "; cacheCond += CodeBuild.UFString(columnInfo.Name) + " == null || "; whereCondi += string.Format(".Where{0}({1})", CodeBuild.UFString(columnInfo.Name), //getcstype.Contains("?") ? string.Concat("new ", getcstype, "(", CodeBuild.UFString(columnInfo.Name), ")") : CodeBuild.UFString(columnInfo.Name)); } parms = parms.Substring(0, parms.Length - 2); parmsNewItem = parmsNewItem.Substring(0, parmsNewItem.Length - 2); parmsBy = parmsBy.Substring(0, parmsBy.Length - 3); parmsNoneType = parmsNoneType.Substring(0, parmsNoneType.Length - 2); parmsNodeTypeUpdateCacheRemove = parmsNodeTypeUpdateCacheRemove.Substring(0, parmsNodeTypeUpdateCacheRemove.Length - 9); cacheCond = cacheCond.Substring(0, cacheCond.Length - 4); if (del_exists2.ContainsKey(parms)) continue; del_exists2.Add(parms, true); if (uniques_dic.Count > 1) sb2.AppendFormat(@" public static int Delete{2}({0}) {{ var affrows = dal.Delete{2}({1}); if (itemCacheTimeout > 0) RemoveCache(GetItem{2}({1})); return affrows; }}", parms, parmsNoneType, cs[0].IsPrimaryKey ? string.Empty : parmsBy); else sb2.AppendFormat(@" public static int Delete{2}({0}) {{ var affrows = dal.Delete{2}({1}); if (itemCacheTimeout > 0) RemoveCache(new {3}Info {{ {4} }}); return affrows; }}", parms, parmsNoneType, cs[0].IsPrimaryKey ? string.Empty : parmsBy, uClass_Name, parmsNewItem); if (uniques_dic.Count > 1) bll_async_code += string.Format(@" async public static Task<int> Delete{2}Async({0}) {{ var affrows = await dal.Delete{2}Async({1}); if (itemCacheTimeout > 0) await RemoveCacheAsync(GetItem{2}({1})); return affrows; }}", parms, parmsNoneType, cs[0].IsPrimaryKey ? string.Empty : parmsBy); else bll_async_code += string.Format(@" async public static Task<int> Delete{2}Async({0}) {{ var affrows = await dal.Delete{2}Async({1}); if (itemCacheTimeout > 0) await RemoveCacheAsync(new {3}Info {{ {4} }}); return affrows; }}", parms, parmsNoneType, cs[0].IsPrimaryKey ? string.Empty : parmsBy, uClass_Name, parmsNewItem); sb3.AppendFormat(@" public static {1}Info GetItem{2}({4}) => SqlHelper.CacheShell(string.Concat(""{0}_BLL:{1}{2}:"", {3}), itemCacheTimeout, () => Select{7}.ToOne(), item => item?.Stringify() ?? ""null"", str => str == ""null"" ? null : {1}Info.Parse(str));", solutionName, uClass_Name, cs[0].IsPrimaryKey ? string.Empty : parmsBy, parmsNodeTypeUpdateCacheRemove.Replace("item.", ""), parms, parmsNoneType, cacheCond, whereCondi); bll_async_code += string.Format(@" async public static Task<{1}Info> GetItem{2}Async({4}) => await SqlHelper.CacheShellAsync(string.Concat(""{0}_BLL:{1}{2}:"", {3}), itemCacheTimeout, () => Select{7}.ToOneAsync(), item => item?.Stringify() ?? ""null"", str => str == ""null"" ? null : {1}Info.Parse(str));", solutionName, uClass_Name, cs[0].IsPrimaryKey ? string.Empty : parmsBy, parmsNodeTypeUpdateCacheRemove.Replace("item.", ""), parms, parmsNoneType, cacheCond, whereCondi); sb4.AppendFormat(@" keys[keysIdx++] = string.Concat(""{0}_BLL:{1}{2}:"", {3});", solutionName, uClass_Name, cs[0].IsPrimaryKey ? string.Empty : parmsBy, parmsNodeTypeUpdateCacheRemove); } if (table.PrimaryKeys.Count > 0) { #region 如果没有主键的处理 sb2.AppendFormat(@"|deleteby_fk|"); var bllfields_ = ""; foreach(var col33 in table.Columns) { string comment = _column_coments.ContainsKey(table.FullName) && _column_coments[table.FullName].ContainsKey(col33.Name) ? _column_coments[table.FullName][col33.Name] : col33.Name; string prototype_comment = comment == col33.Name ? @" " : string.Format(@" /// <summary> /// {0} /// </summary> ", comment.Replace("\r\n", "\n").Replace("\n", "\r\n /// ")); bllfields_ += prototype_comment + UFString(col33.Name) + (bllfields_.Length == 0 ? " = 1, " : ", "); } if (bllfields_.Length > 0) bllfields_ = bllfields_.Substring(0, bllfields_.Length - 2); sb1.AppendFormat(@" #region delete, update, insert {0} #region enum _ public enum _ {{{1} }} #endregion ", sb2.ToString(), bllfields_); if (uniques_dic.Count > 1) sb1.AppendFormat(@" public static int Update({1}Info item, _ ignore1 = 0, _ ignore2 = 0, _ ignore3 = 0) => Update(item, new[] {{ ignore1, ignore2, ignore3 }}); public static int Update({1}Info item, _[] ignore) => dal.Update(item, ignore?.Where(a => a > 0).Select(a => Enum.GetName(typeof(_), a)).ToArray()).ExecuteNonQuery(); public static {0}.DAL.{1}.SqlUpdateBuild UpdateDiy({2}) => new {0}.DAL.{1}.SqlUpdateBuild(new List<{1}Info> {{ itemCacheTimeout <= 0 ? new {1}Info {{ {4} }} : GetItem({3}) }}); public static {0}.DAL.{1}.SqlUpdateBuild UpdateDiy(List<{1}Info> dataSource) => new {0}.DAL.{1}.SqlUpdateBuild(dataSource); /// <summary> /// 用于批量更新,不会更新缓存 /// </summary> public static {0}.DAL.{1}.SqlUpdateBuild UpdateDiyDangerous => new {0}.DAL.{1}.SqlUpdateBuild(); ", solutionName, uClass_Name, pkCsParam, pkCsParamNoType, pkCsParamNoTypeFieldInit); else { var xxxxtempskdf = ""; foreach (var xxxxtempskdfstr in pkCsParamNoType.Split(new string[] { ", " }, StringSplitOptions.None)) { xxxxtempskdf += xxxxtempskdfstr + " = " + xxxxtempskdfstr + ", "; } sb1.AppendFormat(@" public static int Update({1}Info item, _ ignore1 = 0, _ ignore2 = 0, _ ignore3 = 0) => Update(item, new[] {{ ignore1, ignore2, ignore3 }}); public static int Update({1}Info item, _[] ignore) => dal.Update(item, ignore?.Where(a => a > 0).Select(a => Enum.GetName(typeof(_), a)).ToArray()).ExecuteNonQuery(); public static {0}.DAL.{1}.SqlUpdateBuild UpdateDiy({2}) => new {0}.DAL.{1}.SqlUpdateBuild(new List<{1}Info> {{ new {1}Info {{ {4} }} }}); public static {0}.DAL.{1}.SqlUpdateBuild UpdateDiy(List<{1}Info> dataSource) => new {0}.DAL.{1}.SqlUpdateBuild(dataSource); /// <summary> /// 用于批量更新,不会更新缓存 /// </summary> public static {0}.DAL.{1}.SqlUpdateBuild UpdateDiyDangerous => new {0}.DAL.{1}.SqlUpdateBuild(); ", solutionName, uClass_Name, pkCsParam, pkCsParamNoType, xxxxtempskdf.Substring(0, xxxxtempskdf.Length - 2)); } bll_async_code += string.Format(@" public static Task<int> UpdateAsync({1}Info item, _ ignore1 = 0, _ ignore2 = 0, _ ignore3 = 0) => UpdateAsync(item, new[] {{ ignore1, ignore2, ignore3 }}); public static Task<int> UpdateAsync({1}Info item, _[] ignore) => dal.Update(item, ignore?.Where(a => a > 0).Select(a => Enum.GetName(typeof(_), a)).ToArray()).ExecuteNonQueryAsync(); ", solutionName, uClass_Name); if (table.Columns.Count > 5) sb1.AppendFormat(@" /// <summary> /// 适用字段较少的表;避规后续改表风险,字段数较大请改用 {0}.Insert({0}Info item) /// </summary> [Obsolete]", uClass_Name); sb1.AppendFormat(@" public static {0}Info Insert({1}) {{ return Insert(new {0}Info {{{2}}}); }}", uClass_Name, CsParam3, CsParamNoType3); if (table.Columns.Count > 5) bll_async_code += string.Format(@" /// <summary> /// 适用字段较少的表;避规后续改表风险,字段数较大请改用 {0}.Insert({0}Info item) /// </summary> [Obsolete]", uClass_Name); bll_async_code += string.Format(@" public static Task<{0}Info> InsertAsync({1}) {{ return InsertAsync(new {0}Info {{{2}}}); }}", uClass_Name, CsParam3, CsParamNoType3); var redisRemove = sb4.ToString(); string cspk2GuidSetValue = ""; string cspk2GuidSetValuesss = ""; foreach (ColumnInfo cspk2 in table.Columns) { string getcstype = CodeBuild.GetCSType(cspk2.Type, uClass_Name + cspk2.Name.ToUpper(), cspk2.SqlType); if (getcstype == "Guid?" && cspk2.IsPrimaryKey) { cspk2GuidSetValue += string.Format("\r\n if (item.{0} == null) item.{0} = SqlHelper.NewMongodbId();", UFString(cspk2.Name)); cspk2GuidSetValuesss += string.Format("\r\n foreach (var item in items) if (item != null && item.{0} == null) item.{0} = SqlHelper.NewMongodbId();", UFString(cspk2.Name)); } if (getcstype == "DateTime?" && cspk2.Name.ToLower() == "create_time" || getcstype == "DateTime?" && cspk2.Name.ToLower() == "update_time") { cspk2GuidSetValue += string.Format("\r\n if (item.{0} == null) item.{0} = DateTime.Now;", UFString(cspk2.Name)); cspk2GuidSetValuesss += string.Format("\r\n foreach (var item in items) if (item != null && item.{0} == null) item.{0} = DateTime.Now;", UFString(cspk2.Name)); } if (getcstype == "bool?" && cspk2.Name.ToLower() == "is_deleted") { cspk2GuidSetValue += string.Format("\r\n if (item.{0} == null) item.{0} = false;", UFString(cspk2.Name)); cspk2GuidSetValuesss += string.Format("\r\n foreach (var item in items) if (item != null && item.{0} == null) item.{0} = false;", UFString(cspk2.Name)); } } var bll_synccode_insertMulti = identityColumn == null ? string.Format(@" /// <summary> /// 批量插入 /// </summary> /// <param name=""items"">集合</param> /// <returns>影响的行数</returns> public static int Insert(IEnumerable<{0}Info> items) {{{1} var affrows = dal.Insert(items); if (itemCacheTimeout > 0) RemoveCache(items); return affrows; }}", uClass_Name, cspk2GuidSetValuesss) : ""; var bll_asynccode_insertMulti = identityColumn == null ? string.Format(@" /// <summary> /// 批量插入 /// </summary> /// <param name=""items"">集合</param> /// <returns>影响的行数</returns> async public static Task<int> InsertAsync(IEnumerable<{0}Info> items) {{{1} var affrows = await dal.InsertAsync(items); if (itemCacheTimeout > 0) await RemoveCacheAsync(items); return affrows; }}", uClass_Name, cspk2GuidSetValuesss) : ""; sb1.AppendFormat(@" public static {0}Info Insert({0}Info item) {{{7} item = dal.Insert(item); if (itemCacheTimeout > 0) RemoveCache(item); return item; }}{6} internal static void RemoveCache({0}Info item) => RemoveCache(item == null ? null : new [] {{ item }}); internal static void RemoveCache(IEnumerable<{0}Info> items) {{ if (itemCacheTimeout <= 0 || items == null || items.Any() == false) return; var keys = new string[items.Count() * {5}]; var keysIdx = 0; foreach (var item in items) {{{2} }} if (SqlHelper.Instance.CurrentThreadTransaction != null) SqlHelper.Instance.PreRemove(keys); else SqlHelper.CacheRemove(keys); }} #endregion {1} ", uClass_Name, sb3.ToString(), redisRemove, "", "", table.Uniques.Count, bll_synccode_insertMulti, cspk2GuidSetValue); bll_async_code += string.Format(@" async public static Task<{0}Info> InsertAsync({0}Info item) {{{7} item = await dal.InsertAsync(item); if (itemCacheTimeout > 0) await RemoveCacheAsync(item); return item; }}{6} internal static Task RemoveCacheAsync({0}Info item) => RemoveCacheAsync(item == null ? null : new [] {{ item }}); async internal static Task RemoveCacheAsync(IEnumerable<{0}Info> items) {{ if (itemCacheTimeout <= 0 || items == null || items.Any() == false) return; var keys = new string[items.Count() * {5}]; var keysIdx = 0; foreach (var item in items) {{{2} }} await SqlHelper.CacheRemoveAsync(keys); }} ", uClass_Name, "", redisRemove, "", "", table.Uniques.Count, bll_asynccode_insertMulti, cspk2GuidSetValue); #endregion } sb1.AppendFormat(@" public static List<{0}Info> GetItems() => Select.ToList();", uClass_Name, solutionName); if (is_deleted_column) sb1.AppendFormat(@" public static SelectBuild SelectRaw => new SelectBuild(dal); /// <summary> /// 开启软删除功能,默认查询 is_deleted = false 的数据,查询所有使用 SelectRaw,软删除数据使用 Update is_deleted = true,物理删除数据使用 Delete 方法 /// </summary> public static SelectBuild Select => SelectRaw.WhereIs_deleted(false);", uClass_Name, solutionName); else sb1.AppendFormat(@" public static SelectBuild Select => new SelectBuild(dal);", uClass_Name, solutionName); sb1.AppendFormat(@" public static SelectBuild SelectAs(string alias = ""a"") => Select.As(alias);", uClass_Name, solutionName); bll_async_code += string.Format(@" public static Task<List<{0}Info>> GetItemsAsync() => Select.ToListAsync();", uClass_Name, solutionName); Dictionary<string, bool> byItems = new Dictionary<string, bool>(); foreach (ForeignKeyInfo fk in table.ForeignKeys) { string fkcsBy = string.Empty; string fkcsParms = string.Empty; string fkcsTypeParms = string.Empty; string fkcsFilter = string.Empty; int fkcsFilterIdx = 0; foreach (ColumnInfo c1 in fk.Columns) { fkcsBy += CodeBuild.UFString(c1.Name) + "And"; fkcsParms += CodeBuild.UFString(c1.Name) + ", "; fkcsTypeParms += CodeBuild.GetCSType(c1.Type, uClass_Name + c1.Name.ToUpper(), c1.SqlType) + " " + CodeBuild.UFString(c1.Name) + ", "; fkcsFilter += "a.`" + c1.Name + "` = {" + fkcsFilterIdx++ + "} and "; } fkcsBy = fkcsBy.Remove(fkcsBy.Length - 3); fkcsParms = fkcsParms.Remove(fkcsParms.Length - 2); fkcsTypeParms = fkcsTypeParms.Remove(fkcsTypeParms.Length - 2); fkcsFilter = fkcsFilter.Remove(fkcsFilter.Length - 4); if (byItems.ContainsKey(fkcsBy)) continue; byItems.Add(fkcsBy, true); if (!del_exists2.ContainsKey(fkcsTypeParms)) { sb5.AppendFormat(@" public static int DeleteBy{2}({0}) {{ return dal.DeleteBy{2}({1}); }}", fkcsTypeParms, fkcsParms, fkcsBy); bll_async_code = string.Format(@" public static Task<int> DeleteBy{2}Async({0}) {{ return dal.DeleteBy{2}Async({1}); }}", fkcsTypeParms, fkcsParms, fkcsBy) + bll_async_code; del_exists2.Add(fkcsTypeParms, true); } if (fk.Columns.Count > 1) { sb1.AppendFormat( @" public static List<{0}Info> GetItemsBy{1}({2}) => Select.Where{1}({3}).ToList(); public static List<{0}Info> GetItemsBy{1}({2}, int limit) => Select.Where{1}({3}).Limit(limit).ToList(); public static SelectBuild SelectBy{1}({2}) => Select.Where{1}({3});", uClass_Name, fkcsBy, fkcsTypeParms, fkcsParms); bll_async_code += string.Format( @" public static Task<List<{0}Info>> GetItemsBy{1}Async({2}) => Select.Where{1}({3}).ToListAsync(); public static Task<List<{0}Info>> GetItemsBy{1}Async({2}, int limit) => Select.Where{1}({3}).Limit(limit).ToListAsync();", uClass_Name, fkcsBy, fkcsTypeParms, fkcsParms); sb6.AppendFormat(@" public SelectBuild Where{1}({2}) => base.Where(""{4}"", {3});", uClass_Name, fkcsBy, fkcsTypeParms, fkcsParms, fkcsFilter, solutionName); } else if (fk.Columns.Count == 1/* && fk.Columns[0].IsPrimaryKey == false*/) { string csType = CodeBuild.GetCSType(fk.Columns[0].Type, CodeBuild.UFString(fk.Table.ClassName) + fk.Columns[0].Name.ToUpper(), fk.Columns[0].SqlType); sb1.AppendFormat( @" public static List<{0}Info> GetItemsBy{1}(params {2}[] {1}) => Select.Where{1}({1}).ToList(); public static List<{0}Info> GetItemsBy{1}({2}[] {1}, int limit) => Select.Where{1}({1}).Limit(limit).ToList(); public static SelectBuild SelectBy{1}(params {2}[] {1}) => Select.Where{1}({1});", uClass_Name, fkcsBy, csType); bll_async_code += string.Format( @" public static Task<List<{0}Info>> GetItemsBy{1}Async(params {2}[] {1}) => Select.Where{1}({1}).ToListAsync(); public static Task<List<{0}Info>> GetItemsBy{1}Async({2}[] {1}, int limit) => Select.Where{1}({1}).Limit(limit).ToListAsync();", uClass_Name, fkcsBy, csType); sb6.AppendFormat(@" public SelectBuild Where{1}(params {2}[] {1}) => this.Where1Or(""a.`{3}` = {{0}}"", {1}); public SelectBuild Where{1}({4}.SelectBuild select, bool isNotIn = false) => this.Where($""a.`{3}` {{(isNotIn ? ""NOT IN"" : ""IN"")}} ({{select.ToString(""`{5}`"")}})"");", uClass_Name, fkcsBy, csType, fk.Columns[0].Name, UFString(fk.ReferencedTable.ClassName), fk.ReferencedColumns[0].Name); } } // m -> n _tables.ForEach(delegate (TableInfo t2) { List<ForeignKeyInfo> fks = t2.ForeignKeys.FindAll(delegate (ForeignKeyInfo ffk) { if (ffk.ReferencedTable.FullName == table.FullName) { return true; } return false; }); if (fks.Count == 0) return; ForeignKeyInfo fk = fks.Count > 1 ? fks.Find(delegate(ForeignKeyInfo ffk) { return string.Compare(table.Name + "_" + table.PrimaryKeys[0].Name, ffk.Columns[0].Name, true) == 0; }) : fks[0]; if (fk == null) fk = fks[0]; //if (fk.Table.FullName == table.FullName) return; List<ForeignKeyInfo> fk2 = t2.ForeignKeys.FindAll(delegate (ForeignKeyInfo ffk2) { return ffk2.Columns[0].IsPrimaryKey && ffk2 != fk; }); if (fk2.Count != 1) return; if (fk.Columns[0].IsPrimaryKey == false) return; //中间表关系键,必须为主键 //t2.Columns string t2name = t2.Name; string tablename = table.Name; string addname = t2name; if (t2name.StartsWith(tablename + "_")) { addname = t2name.Substring(tablename.Length + 1); } else if (t2name.EndsWith("_" + tablename)) { addname = t2name.Remove(addname.Length - tablename.Length - 1); } else if (fk2.Count == 1 && t2name.EndsWith("_" + tablename)) { addname = t2name.Remove(t2name.Length - tablename.Length - 1); } else if (fk2.Count == 1 && t2name.EndsWith("_" + fk2[0].ReferencedTable.Name)) { addname = t2name; } string addname_schema = addname == t2.Name && t2.Owner != table.Owner ? t2.ClassName : addname; string orgInfo = CodeBuild.UFString(fk2[0].ReferencedTable.ClassName); string fkcsBy = CodeBuild.UFString(addname_schema); if (byItems.ContainsKey(fkcsBy)) return; byItems.Add(fkcsBy, true); string civ = string.Format(GetCSTypeValue(fk2[0].ReferencedTable.PrimaryKeys[0].Type), CodeBuild.UFString(fk2[0].ReferencedTable.PrimaryKeys[0].Name)); sb1.AppendFormat(@" public static SelectBuild SelectBy{1}(params {2}Info[] {5}s) => Select.Where{1}({5}s); public static SelectBuild SelectBy{1}_{4}(params {3}[] {5}_ids) => Select.Where{1}_{4}({5}_ids);", uClass_Name, fkcsBy, orgInfo, GetCSType(fk2[0].ReferencedTable.PrimaryKeys[0].Type, CodeBuild.UFString(fk2[0].ReferencedTable.ClassName) + fk2[0].ReferencedTable.PrimaryKeys[0].Name.ToUpper(), fk2[0].ReferencedTable.PrimaryKeys[0].SqlType).Replace("?", ""), table.PrimaryKeys[0].Name, LFString(orgInfo)); string _f6 = fk.Columns[0].Name; string _f7 = fk.ReferencedTable.PrimaryKeys[0].Name; string _f8 = fk2[0].Columns[0].Name; string _f9 = GetCSType(fk2[0].ReferencedTable.PrimaryKeys[0].Type, CodeBuild.UFString(fk2[0].ReferencedTable.ClassName) + fk2[0].ReferencedTable.PrimaryKeys[0].Name.ToUpper(), fk2[0].ReferencedTable.PrimaryKeys[0].SqlType).Replace("?", ""); //若中间表,两外键指向相同表,则选择 表名_主键名 此字段作为主参考字段 string main_column = fk.Columns[0].Name; if (fk.ReferencedTable.ClassName == fk2[0].ReferencedTable.ClassName && string.Compare(main_column, fk.Columns[0].Name, true) == 0) { _f6 = fk2[0].Columns[0].Name; _f7 = fk2[0].ReferencedTable.PrimaryKeys[0].Name; _f8 = fk.Columns[0].Name; _f9 = GetCSType(fk2[0].Table.PrimaryKeys[0].Type, CodeBuild.UFString(fk2[0].Table.ClassName) + fk2[0].Table.PrimaryKeys[0].Name.ToUpper(), fk2[0].Table.PrimaryKeys[0].SqlType).Replace("?", ""); } sb6.AppendFormat(@" public SelectBuild Where{1}(params {2}Info[] {10}s) => Where{1}({10}s?.ToArray(), null); public SelectBuild Where{1}_{7}(params {9}[] {10}_ids) => Where{1}_{7}({10}_ids?.ToArray(), null); public SelectBuild Where{1}({2}Info[] {10}s, Action<{5}.SelectBuild> subCondition) => Where{1}_{7}({10}s?.Where<{2}Info>(a => a != null).Select<{2}Info, {9}>(a => a.{3}).ToArray(), subCondition); public SelectBuild Where{1}_{7}({9}[] {10}_ids, Action<{5}.SelectBuild> subCondition) {{ if ({10}_ids == null || {10}_ids.Length == 0) return this; {5}.SelectBuild subConditionSelect = {5}.Select.Where(string.Format(""`{6}` = a . `{7}` AND `{8}` IN ('{{0}}')"", string.Join(""','"", {10}_ids.Select(a => string.Concat(a).Replace(""'"", ""''""))))); subCondition?.Invoke(subConditionSelect); var subConditionSql = subConditionSelect.ToString(""`{6}`"").Replace("" a \r\nWHERE ("", "" WHERE (""); if (subCondition != null) subConditionSql = subConditionSql.Replace(""a.`"", ""`{12}`.`""); return base.Where($""EXISTS({{subConditionSql}})""); }}", uClass_Name, fkcsBy, orgInfo, civ, string.Empty, CodeBuild.UFString(t2.ClassName), _f6, _f7, _f8, _f9, LFString(orgInfo), t2.Owner, t2.Name); }); table.Columns.ForEach(delegate (ColumnInfo col) { string csType = CodeBuild.GetCSType(col.Type, uClass_Name + col.Name.ToUpper(), col.SqlType); string lname = col.Name.ToLower(); //if (col.IsPrimaryKey) return; //if (lname == "create_time" || // lname == "update_time") return; string fkcsBy = CodeBuild.UFString(col.Name); if (byItems.ContainsKey(fkcsBy)) return; byItems.Add(fkcsBy, true); string comment = _column_coments.ContainsKey(table.FullName) && _column_coments[table.FullName].ContainsKey(col.Name) ? _column_coments[table.FullName][col.Name] : col.Name; string prototype_comment = comment == col.Name ? "" : string.Format(@"/// <summary> /// {0},多个参数等于 OR 查询 /// </summary> ", comment.Replace("\r\n", "\n").Replace("\n", "\r\n /// ")); if (csType == "bool?" || csType == "Guid?") { sb6.AppendFormat(@" {4}public SelectBuild Where{1}(params {2}[] {1}) => this.Where1Or(""a.`{3}` = {{0}}"", {1});", uClass_Name, fkcsBy, col.IsPrimaryKey ? csType.Replace("?", "") : csType, col.Name, prototype_comment); return; } if (col.Type == MySqlDbType.Byte || col.Type == MySqlDbType.Int16 || col.Type == MySqlDbType.Int24 || col.Type == MySqlDbType.Int32 || col.Type == MySqlDbType.Int64 || col.Type == MySqlDbType.UByte || col.Type == MySqlDbType.UInt16 || col.Type == MySqlDbType.UInt24 || col.Type == MySqlDbType.UInt32 || col.Type == MySqlDbType.UInt64 || col.Type == MySqlDbType.Year) { sb6.AppendFormat(@" {4}public SelectBuild Where{1}(params {2}[] {1}) => this.Where1Or(""a.`{3}` = {{0}}"", {1});", uClass_Name, fkcsBy, col.IsPrimaryKey ? csType.Replace("?", "") : csType, col.Name, prototype_comment); return; } if (col.Type == MySqlDbType.Double || col.Type == MySqlDbType.Float || col.Type == MySqlDbType.Decimal) { sb6.AppendFormat(@" {4}public SelectBuild Where{1}(params {2}[] {1}) => this.Where1Or(""a.`{3}` = {{0}}"", {1});", uClass_Name, fkcsBy, csType, col.Name, prototype_comment); sb6.AppendFormat(@" public SelectBuild Where{1}Range({2} begin) => base.Where(""a.`{3}` >= {{0}}"", begin); public SelectBuild Where{1}Range({2} begin, {2} end) => end == null ? Where{1}Range(begin) : base.Where(""a.`{3}` between {{0}} and {{1}}"", begin, end);", uClass_Name, fkcsBy, csType, col.Name); return; } if (col.Type == MySqlDbType.Date || col.Type == MySqlDbType.Time || col.Type == MySqlDbType.Timestamp || col.Type == MySqlDbType.Datetime) { if (col.IsPrimaryKey) sb6.AppendFormat(@" {4}public SelectBuild Where{1}({2} {1}) => base.Where(""a.`{3}` = {{0}}"", {1});", uClass_Name, fkcsBy, csType, col.Name, prototype_comment); sb6.AppendFormat(@" public SelectBuild Where{1}Range({2} begin) => base.Where(""a.`{3}` >= {{0}}"", begin); public SelectBuild Where{1}Range({2} begin, {2} end) => end == null ? Where{1}Range(begin) : base.Where(""a.`{3}` between {{0}} and {{1}}"", begin, end);", uClass_Name, fkcsBy, csType, col.Name); return; } if ((col.Type == MySqlDbType.UInt32 || col.Type == MySqlDbType.UInt64) && (lname == "status" || lname.StartsWith("status_") || lname.EndsWith("_status"))) { sb6.AppendFormat(@" public SelectBuild Where{1}(params int[] _0_16) {{ if (_0_16 == null || _0_16.Length == 0) return this; {2}[] copy = new {2}[_0_16.Length]; for (int a = 0; a < _0_16.Length; a++) copy[a] = ({2})Math.Pow(2, _0_16[a]); return this.Where1Or(""(a.`{3}` & {{0}}) = {{0}}"", copy); }}", uClass_Name, fkcsBy, csType.Replace("?", ""), col.Name); return; } if (col.Type == MySqlDbType.Set) { sb6.AppendFormat(@" public SelectBuild Where{1}_IN(params {2}[] {1}s) => this.Where1Or(""(a.`{3}` & {{0}}) = {{0}}"", {1}s); {4}public SelectBuild Where{1}({2} {1}1) => this.Where{1}_IN({1}1); #region Where{1} public SelectBuild Where{1}({2} {1}1, {2} {1}2) => this.Where{1}_IN({1}1, {1}2); public SelectBuild Where{1}({2} {1}1, {2} {1}2, {2} {1}3) => this.Where{1}_IN({1}1, {1}2, {1}3); public SelectBuild Where{1}({2} {1}1, {2} {1}2, {2} {1}3, {2} {1}4) => this.Where{1}_IN({1}1, {1}2, {1}3, {1}4); public SelectBuild Where{1}({2} {1}1, {2} {1}2, {2} {1}3, {2} {1}4, {2} {1}5) => this.Where{1}_IN({1}1, {1}2, {1}3, {1}4, {1}5); #endregion", uClass_Name, fkcsBy, csType.Replace("?", ""), col.Name, prototype_comment); return; } if (col.Type == MySqlDbType.Enum) { sb6.AppendFormat(@" public SelectBuild Where{1}_IN(params {2}?[] {1}s) => this.Where1Or(""a.`{3}` = {{0}}"", {1}s); {4}public SelectBuild Where{1}({2} {1}1) => this.Where{1}_IN({1}1); #region Where{1} public SelectBuild Where{1}({2} {1}1, {2} {1}2) => this.Where{1}_IN({1}1, {1}2); public SelectBuild Where{1}({2} {1}1, {2} {1}2, {2} {1}3) => this.Where{1}_IN({1}1, {1}2, {1}3); public SelectBuild Where{1}({2} {1}1, {2} {1}2, {2} {1}3, {2} {1}4) => this.Where{1}_IN({1}1, {1}2, {1}3, {1}4); public SelectBuild Where{1}({2} {1}1, {2} {1}2, {2} {1}3, {2} {1}4, {2} {1}5) => this.Where{1}_IN({1}1, {1}2, {1}3, {1}4, {1}5); #endregion", uClass_Name, fkcsBy, csType.Replace("?", ""), col.Name, prototype_comment); return; } if (csType == "MygisPoint") { sb6.AppendFormat(@" /// <summary> /// 查找地理位置多少米范围内的记录,距离由近到远排序 /// </summary> /// <param name=""point"">经纬度</param> /// <param name=""meter"">米(=0时无限制)</param> /// <returns></returns> public SelectBuild Where{1}MbrContains(MygisPoint point, double meter = 0) => this.Where(meter > 0, @""MBRContains(LineString( Point({{0}} + 10 / ( 111.1 / COS(RADIANS({{1}}))), {{1}} + 10 / 111.1), Point({{0}} - 10 / ( 111.1 / COS(RADIANS({{1}}))), {{1}} - 10 / 111.1)), a.`{3}`)"", point.X, point.Y, meter);", uClass_Name, fkcsBy, csType.Replace("?", ""), col.Name); return; } if (csType == "string") { if (col.Length > 0 && col.Length < 301) sb6.AppendFormat(@" {4}public SelectBuild Where{1}(params {2}[] {1}) => this.Where1Or(""a.`{3}` = {{0}}"", {1});", uClass_Name, fkcsBy, csType, col.Name, prototype_comment); sb6.AppendFormat(@" public SelectBuild Where{1}Like(string pattern, bool isNotLike = false) => this.Where($@""a.`{3}` {{(isNotLike ? ""NOT LIKE"" : ""LIKE"")}} {{{{0}}}}"", pattern);", uClass_Name, fkcsBy, csType, col.Name); return; } }); sb1.AppendFormat(@" #region async{3} #endregion public partial class SelectBuild : SelectBuild<{0}Info, SelectBuild> {{{2} public SelectBuild(IDAL dal) : base(dal, SqlHelper.Instance) {{ }} }} }} }}", uClass_Name, solutionName, sb6.ToString(), bll_async_code); loc1.Add(new BuildInfo(string.Concat(CONST.corePath, solutionName, @".db\BLL\", basicName, @"\", uClass_Name, ".cs"), Deflate.Compress(sb1.ToString().Replace("|deleteby_fk|", sb5.ToString())))); clearSb(); #endregion if (table.PrimaryKeys.Count == 0) continue; #region admin if (isMakeAdmin) { #region common define string pkNames = string.Empty; string pkUrlQuerys = string.Empty; string pkHiddens = string.Empty; for (int a = 0; a < table.PrimaryKeys.Count; a++) { ColumnInfo col88 = table.PrimaryKeys[a]; pkNames += CodeBuild.UFString(col88.Name) + ","; pkUrlQuerys += string.Format(@"{0}=@item.{0}&", CodeBuild.UFString(col88.Name)); pkHiddens += string.Format(@"@item.{0},", CodeBuild.UFString(col88.Name)); } if (pkNames.Length > 0) pkNames = pkNames.Remove(pkNames.Length - 1); if (pkUrlQuerys.Length > 0) pkUrlQuerys = pkUrlQuerys.Remove(pkUrlQuerys.Length - 1); if (pkHiddens.Length > 0) pkHiddens = pkHiddens.Remove(pkHiddens.Length - 1); ForeignKeyInfo ttfk = table.ForeignKeys.Find(delegate (ForeignKeyInfo fkk) { return fkk.ReferencedTable != null && fkk.ReferencedTable.FullName == table.FullName; }); #endregion #region wwwroot_sitemap wwwroot_sitemap += string.Format(@" <li><a href=""/{0}/""><i class=""fa fa-circle-o""></i>{0}</a></li>", uClass_Name); #endregion #region init_sysdir admin_controllers_syscontroller_init_sysdir.Add(string.Format(@" dir2 = Sysdir.Insert(dir1.Id, DateTime.Now, ""{0}"", {1}, ""/{0}/""); dir3 = Sysdir.Insert(dir2.Id, DateTime.Now, ""列表"", 1, ""/{0}/""); dir3 = Sysdir.Insert(dir2.Id, DateTime.Now, ""添加"", 2, ""/{0}/add""); dir3 = Sysdir.Insert(dir2.Id, DateTime.Now, ""编辑"", 3, ""/{0}/edit""); dir3 = Sysdir.Insert(dir2.Id, DateTime.Now, ""删除"", 4, ""/{0}/del"");", nClass_Name, admin_controllers_syscontroller_init_sysdir.Count + 1)); #endregion #region Controller.cs string str_listTh = ""; string str_listTd = ""; string str_listTh1 = ""; string str_listTd1 = ""; string str_controller_list_join = ""; byte str_controller_list_join_alias = 97; string str_listCms2FilterFK = ""; string str_listCms2FilterFK_fkitems = ""; string keyLikes = string.Empty; string getListParamQuery = ""; bool ttfk_flag = false; string str_addhtml_mn = ""; string str_controller_insert_mn = ""; string str_controller_update_mn = ""; string str_fk_getlist = ""; string str_addjs_mn_initUI = ""; foreach (ColumnInfo col in table.Columns) { List<ColumnInfo> us = table.Uniques.Find(delegate (List<ColumnInfo> cs) { return cs.Find(delegate (ColumnInfo col88) { return col88.Name == col.Name; }) != null; }); if (us == null) us = new List<ColumnInfo>(); List<ForeignKeyInfo> fks_comb = table.ForeignKeys.FindAll(delegate (ForeignKeyInfo fk2) { return fk2.Columns.Count == 1 && fk2.Columns[0].Name == col.Name; }); string csType = CodeBuild.GetCSType(col.Type, uClass_Name + col.Name.ToUpper(), col.SqlType); string csUName = CodeBuild.UFString(col.Name); string comment = _column_coments.ContainsKey(table.FullName) && _column_coments[table.FullName].ContainsKey(col.Name) ? _column_coments[table.FullName][col.Name] : col.Name; if (csType == "string") { keyLikes += "a." + col.Name + " like {0} or "; } List<ForeignKeyInfo> fks = table.ForeignKeys.FindAll(delegate (ForeignKeyInfo fk88) { return fk88.Columns.Find(delegate (ColumnInfo col88) { return col88.Name == col.Name; }) != null; }); //外键 ForeignKeyInfo fk = null; string FK_uEntry_Name = string.Empty; string tableNamefe3 = string.Empty; string memberName = string.Empty; string strName = string.Empty; if (fks.Count > 0) { fk = fks[0]; FK_uEntry_Name = fk.ReferencedTable != null ? CodeBuild.GetCSName(fk.ReferencedTable.Name) : CodeBuild.GetCSName(TableInfo.GetEntryName(fk.ReferencedTableName)); tableNamefe3 = fk.ReferencedTable != null ? fk.ReferencedTable.Name : FK_uEntry_Name; memberName = fk.Columns[0].Name.IndexOf(tableNamefe3) == -1 ? tableNamefe3 : (fk.Columns[0].Name.Substring(0, fk.Columns[0].Name.IndexOf(tableNamefe3)) + tableNamefe3); if (fk.Columns[0].Name.IndexOf(tableNamefe3) == 0 && fk.ReferencedTable != null) memberName = fk.ReferencedTable.ClassName; ColumnInfo strNameCol = null; if (fk.ReferencedTable != null) { strNameCol = fk.ReferencedTable.Columns.Find(delegate (ColumnInfo col88) { return col88.Name.ToLower().IndexOf("name") != -1 || col88.Name.ToLower().IndexOf("title") != -1; }); if (strNameCol == null) strNameCol = fk.ReferencedTable.Columns.Find(delegate (ColumnInfo col88) { return GetCSType(col88.Type, CodeBuild.UFString(fk.ReferencedTable.ClassName) + col88.Name.ToUpper(), col88.SqlType) == "string" && col88.Length > 0 && col88.Length < 300; }); } strName = strNameCol != null ? "." + CodeBuild.UFString(strNameCol.Name) : string.Empty; } string Obj_name = string.Concat("Obj_", memberName, strName); if (!col.IsIdentity && fks.Count == 1) { ForeignKeyInfo fkcb = fks[0]; string FK_uClass_Name = fkcb.ReferencedTable != null ? CodeBuild.UFString(fkcb.ReferencedTable.ClassName) : CodeBuild.UFString(TableInfo.GetClassName(fkcb.ReferencedTableName)); getListParamQuery += string.Format(@"[FromQuery] {0}[] {1}, ", csType, csUName); sb3.AppendFormat(@" if ({0}.Length > 0) select.Where{0}({0});", csUName); } else if (!col.IsIdentity && us.Count == 1 || col.IsPrimaryKey && table.PrimaryKeys.Count == 1) { //主键或唯一键,非自动增值 } //前端js或者模板 if (!col.IsIdentity && fks.Count == 1 && fks[0].Table.FullName != fks[0].ReferencedTable.FullName) { str_listTh += string.Format(@"<th scope=""col"">{0}</th> ", comment); str_listTd += string.Format(@"<td>[@item.{0}] @item.Obj_{1}{2}</td> ", csUName, memberName, string.IsNullOrEmpty(strName) ? "" : ("?" + strName)); // str_controller_list_join += string.Format(@" //.LeftJoin<{0}>(""{3}"", ""{3}.{1} = a.{2}"")", CodeBuild.UFString(fks[0].ReferencedTable.ClassName), fks[0].ReferencedColumns[0].Name, fks[0].Columns[0].Name, (char)++str_controller_list_join_alias); str_controller_list_join += string.Format(@" .LeftJoin(a => a.Obj_{0}.{1} == a.{2})", fks[0].ReferencedTable.ClassName, UFString(fks[0].ReferencedColumns[0].Name), UFString(fks[0].Columns[0].Name), (char)++str_controller_list_join_alias); if (str_listCms2FilterFK_fkitems.Contains(" var fk_" + CodeBuild.LFString(fks[0].ReferencedTable.ClassName) + "s = ") == false) str_listCms2FilterFK_fkitems += string.Format(@" var fk_{1}s = {2}{0}.Select.ToList();", CodeBuild.UFString(fks[0].ReferencedTable.ClassName), CodeBuild.LFString(fks[0].ReferencedTable.ClassName), CodeBuild.UFString(fks[0].ReferencedTable.ClassName) == "User" ? solutionName + ".BLL." : ""); str_listCms2FilterFK += string.Format(@" {{ name: '{0}', field: '{4}', text: @Html.Json(fk_{1}s.Select(a => a.{2})), value: @Html.Json(fk_{1}s.Select(a => a.{3})) }},", CodeBuild.UFString(fks[0].ReferencedTable.ClassName), CodeBuild.LFString(fks[0].ReferencedTable.ClassName), string.IsNullOrEmpty(strName) ? "ToString()" : strName.TrimStart('.'), CodeBuild.UFString(fks[0].ReferencedColumns[0].Name), CodeBuild.UFString(fks[0].Columns[0].Name)); } else if (csType == "string" && !ttfk_flag) { ttfk_flag = true; string t1 = string.Format(@"<th scope=""col"">{0}</th> ", comment); string t2 = string.Format(@"<td>@item.{0}</td> ", csUName); str_listTh1 += t1; str_listTd1 += t2; if (ttfk == null || ttfk.Columns[0].Name.ToLower() != "parent_id") { str_listTh += t1; str_listTd += t2; } } else { str_listTh += string.Format(@"<th scope=""col"">{0}</th> ", comment); str_listTd += string.Format(@"<td>@item.{0}</td> ", csUName); } } if (keyLikes.Length > 0) { keyLikes = keyLikes.Remove(keyLikes.Length - 4); getListParamQuery = "[FromQuery] string key, " + getListParamQuery; sb2.AppendFormat(@" .Where(!string.IsNullOrEmpty(key), ""{0}"", string.Concat(""%"", key, ""%""))", keyLikes); } string itemSetValuePK = ""; string itemSetValuePKInsert = ""; string itemSetValueNotPK = ""; string itemCsParamInsertForm = ""; string itemCsParamUpdateForm = ""; table.Columns.ForEach(delegate (ColumnInfo col88) { string csLName = CodeBuild.LFString(col88.Name); string csUName = CodeBuild.UFString(col88.Name); string csType = CodeBuild.GetCSType(col88.Type, uClass_Name + col88.Name.ToUpper(), col88.SqlType); if (col88.IsPrimaryKey) { // itemSetValuePK += string.Format(@" //item.{0} = {0};", csUName); if (col88.IsIdentity) ; else { itemSetValuePKInsert += string.Format(@" item.{0} = {0};", csUName); itemCsParamInsertForm += string.Format(", [FromForm] {0} {1}", csType, csUName); } } else if (col88.IsIdentity) { } else if ((csLName == "img" || csLName.StartsWith("img_") || csLName.EndsWith("_img") || csLName == "path" || csLName.StartsWith("path_") || csLName.EndsWith("_path")) && (col88.Type == MySqlDbType.VarChar || col88.Type == MySqlDbType.VarString || col88.Type == MySqlDbType.String)) { //图片字段 itemCsParamInsertForm += string.Format(", [FromForm] {0} {1}, [FromForm] IFormFile {1}_file", csType, csUName); itemCsParamUpdateForm += string.Format(", [FromForm] {0} {1}, [FromForm] IFormFile {1}_file", csType, csUName); itemSetValuePKInsert += string.Format(@" if ({1}_file != null) {{ item.{1} = $""/upload/{{Guid.NewGuid().ToString()}}.png""; using (FileStream fs = new FileStream(System.IO.Path.Combine(AppContext.BaseDirectory, item.{1}), FileMode.Create)) {1}_file.CopyTo(fs); }} else item.{1} = {1};", "", csUName); itemSetValuePK += string.Format(@" if (!string.IsNullOrEmpty(item.{1}) && (item.{1} != {1} || {1}_file != null)) {{ string path = System.IO.Path.Combine(AppContext.BaseDirectory, item.{1}); if (System.IO.File.Exists(path)) System.IO.File.Delete(path); }} if ({1}_file != null) {{ item.{1} = $""/upload/{{Guid.NewGuid().ToString()}}.png""; using (FileStream fs = new FileStream(System.IO.Path.Combine(AppContext.BaseDirectory, item.{1}), FileMode.Create)) {1}_file.CopyTo(fs); }} else item.{1} = {1};", "", csUName); } else { string colvalue = ""; if (csType == "DateTime?" && ( string.Compare(csLName, "create_time", true) == 0 || string.Compare(csLName, "update_time", true) == 0 )) { colvalue = "DateTime.Now"; } else { string csType2 = csType; if (col88.Type == MySqlDbType.Set) csType2 = csType2.Replace("?", "[]"); if (csType2 == "bool?") csType2 = "bool"; itemCsParamInsertForm += string.Format(", [FromForm] {0} {1}", csType2, csUName); itemCsParamUpdateForm += string.Format(", [FromForm] {0} {1}", csType2, csUName); colvalue = csUName; } if (col88.Type == MySqlDbType.Set) itemSetValueNotPK += string.Format(@" item.{0} = null; {0}?.ToList().ForEach(a => item.{0} = (item.{0} ?? 0) | a);", csUName); else itemSetValueNotPK += string.Format(@" item.{0} = {1};", csUName, colvalue); } }); if (itemCsParamInsertForm.Length > 0) itemCsParamInsertForm = itemCsParamInsertForm.Substring(2); // m -> n _tables.ForEach(delegate (TableInfo t2) { ForeignKeyInfo fk = t2.ForeignKeys.Find(delegate (ForeignKeyInfo ffk) { if (ffk.ReferencedTable.FullName == table.FullName) { return true; } return false; }); if (fk == null) return; if (fk.Table.FullName == table.FullName) return; List<ForeignKeyInfo> fk2 = t2.ForeignKeys.FindAll(delegate (ForeignKeyInfo ffk2) { return ffk2 != fk; }); if (fk2.Count != 1) return; if (fk.Columns[0].IsPrimaryKey == false) return; //中间表关系键,必须为主键 if (t2.Columns.Count != 2) return; //mn表若不是两个字段,则不处理 //t2.Columns string t2name = t2.Name; string tablename = table.Name; string addname = t2name; if (t2name.StartsWith(tablename + "_")) { addname = t2name.Substring(tablename.Length + 1); } else if (t2name.EndsWith("_" + tablename)) { addname = t2name.Remove(addname.Length - tablename.Length - 1); } else if (fk2.Count == 1 && t2name.EndsWith("_" + tablename)) { addname = t2name.Remove(t2name.Length - tablename.Length - 1); } else if (fk2.Count == 1 && t2name.EndsWith("_" + fk2[0].ReferencedTable.Name)) { addname = t2name; } ColumnInfo strNameCol = fk2[0].ReferencedTable.Columns.Find(delegate (ColumnInfo col88) { return col88.Name.ToLower().IndexOf("name") != -1 || col88.Name.ToLower().IndexOf("title") != -1; }); if (strNameCol == null) strNameCol = fk2[0].ReferencedTable.Columns.Find(delegate (ColumnInfo col88) { return GetCSType(col88.Type, CodeBuild.UFString(fk2[0].ReferencedTable.ClassName) + col88.Name.ToUpper(), col88.SqlType) == "string" && col88.Length > 0 && col88.Length < 300; }); if (strNameCol == null) strNameCol = fk2[0].ReferencedTable.PrimaryKeys[0]; string strName = CodeBuild.UFString(strNameCol.Name); getListParamQuery += string.Format(@"[FromQuery] {0}[] {1}_{2}, ", GetCSType(fk2[0].ReferencedTable.PrimaryKeys[0].Type, CodeBuild.UFString(fk2[0].ReferencedTable.ClassName) + fk2[0].ReferencedTable.PrimaryKeys[0].Name.ToUpper(), fk2[0].ReferencedTable.PrimaryKeys[0].SqlType).Replace("?", ""), CodeBuild.UFString(addname), table.PrimaryKeys[0].Name); sb3.AppendFormat(@" if ({0}_{1}.Length > 0) select.Where{0}_{1}({0}_{1});", CodeBuild.UFString(addname), table.PrimaryKeys[0].Name); if (str_listCms2FilterFK_fkitems.Contains(" var fk_" + CodeBuild.LFString(fk2[0].ReferencedTable.ClassName) + "s = ") == false) str_listCms2FilterFK_fkitems += string.Format(@" var fk_{1}s = {2}{0}.Select.ToList();", CodeBuild.UFString(fk2[0].ReferencedTable.ClassName), CodeBuild.LFString(fk2[0].ReferencedTable.ClassName), CodeBuild.UFString(fk2[0].ReferencedTable.ClassName) == "User" ? solutionName + ".BLL." : ""); str_listCms2FilterFK += string.Format(@" {{ name: '{0}', field: '{4}', text: @Html.Json(fk_{1}s.Select(a => a.{2})), value: @Html.Json(fk_{1}s.Select(a => a.{3})) }},", CodeBuild.UFString(fk2[0].ReferencedTable.ClassName), CodeBuild.LFString(fk2[0].ReferencedTable.ClassName), string.IsNullOrEmpty(strName) ? "ToString()" : strName.TrimStart('.'), CodeBuild.UFString(fk2[0].ReferencedColumns[0].Name), CodeBuild.UFString(fk2[0].Columns[0].Name)); //add.html 标签关联 itemCsParamInsertForm += string.Format(", [FromForm] {0}[] mn_{1}", CodeBuild.GetCSType(fk2[0].ReferencedColumns[0].Type, CodeBuild.UFString(fk2[0].ReferencedTable.ClassName) + fk2[0].ReferencedColumns[0].Name.ToUpper(), fk2[0].ReferencedColumns[0].SqlType).Replace("?", ""), CodeBuild.UFString(addname)); itemCsParamUpdateForm += string.Format(", [FromForm] {0}[] mn_{1}", CodeBuild.GetCSType(fk2[0].ReferencedColumns[0].Type, CodeBuild.UFString(fk2[0].ReferencedTable.ClassName) + fk2[0].ReferencedColumns[0].Name.ToUpper(), fk2[0].ReferencedColumns[0].SqlType).Replace("?", ""), CodeBuild.UFString(addname)); str_controller_insert_mn += string.Format(@" //关联 {1} foreach ({0} mn_{1}_in in mn_{1}) item.Flag{1}(mn_{1}_in);", CodeBuild.GetCSType(fk2[0].ReferencedColumns[0].Type, CodeBuild.UFString(fk2[0].ReferencedTable.ClassName) + fk2[0].ReferencedColumns[0].Name.ToUpper(), fk2[0].ReferencedColumns[0].SqlType).Replace("?", ""), CodeBuild.UFString(addname)); str_controller_update_mn += string.Format(@" //关联 {1} if (mn_{1}.Length == 0) {{ item.Unflag{1}ALL(); }} else {{ List<{0}> mn_{1}_list = mn_{1}.ToList(); foreach (var Obj_{2} in item.Obj_{2}s) {{ int idx = mn_{1}_list.FindIndex(a => a == Obj_{2}.Id); if (idx == -1) item.Unflag{1}(Obj_{2}.Id); else mn_{1}_list.RemoveAt(idx); }} mn_{1}_list.ForEach(a => item.Flag{1}(a)); }}", CodeBuild.GetCSType(fk2[0].ReferencedColumns[0].Type, CodeBuild.UFString(fk2[0].ReferencedTable.ClassName) + fk2[0].ReferencedColumns[0].Name.ToUpper(), fk2[0].ReferencedColumns[0].SqlType).Replace("?", ""), CodeBuild.UFString(addname), CodeBuild.LFString(addname)); str_addhtml_mn += string.Format(@" <tr> <td>{1}</td> <td> <select name=""mn_{2}"" data-placeholder=""Select a {3}"" class=""form-control select2"" multiple> @foreach ({0}Info fk in fk_{1}s) {{ <option value=""@fk.{4}"">@fk.{5}</option> }} </select> </td> </tr>", CodeBuild.UFString(fk2[0].ReferencedTable.ClassName), CodeBuild.LFString(fk2[0].ReferencedTable.ClassName), CodeBuild.UFString(addname), CodeBuild.LFString(addname), CodeBuild.UFString(fk2[0].ReferencedColumns[0].Name), strName); if (str_fk_getlist.Contains(" var fk_" + CodeBuild.LFString(fk2[0].ReferencedTable.ClassName) + "s") == false) str_fk_getlist += string.Format(@" var fk_{1}s = {2}{0}.Select.ToList();", CodeBuild.UFString(fk2[0].ReferencedTable.ClassName), CodeBuild.LFString(fk2[0].ReferencedTable.ClassName), CodeBuild.UFString(fk2[0].ReferencedTable.ClassName) == "User" ? solutionName + ".BLL." : ""); str_addjs_mn_initUI += string.Format(@" item.mn_{0} = @Html.Json(item.Obj_{2}s); for (var a = 0; a < item.mn_{0}.length; a++) $(form.mn_{0}).find('option[value=""{{0}}""]'.format(item.mn_{0}[a].{1})).attr('selected', 'selected');", CodeBuild.UFString(addname), CodeBuild.UFString(fk2[0].ReferencedColumns[0].Name), CodeBuild.LFString(addname)); }); string str_mvcdel = string.Format(@" async public Task<APIReturn> _Del([FromForm] {2}[] id) {{ int affrows = 0; foreach ({2} id2 in id) affrows += await {3}{1}.DeleteAsync(id2); if (affrows > 0) return APIReturn.成功.SetMessage($""删除成功,影响行数:{{affrows}}""); return APIReturn.失败; }}", solutionName, uClass_Name, CodeBuild.GetCSType(table.PrimaryKeys[0].Type, CodeBuild.UFString(table.ClassName) + table.PrimaryKeys[0].Name.ToUpper(), table.PrimaryKeys[0].SqlType).Replace("?", ""), uClass_Name == "User" ? "BLL." : ""); if (table.PrimaryKeys.Count > 1) { string pkParses = ""; int pk_idx = 0; foreach (ColumnInfo pk in table.PrimaryKeys) { pkParses += ", " + string.Format(GetStringifyParse(pk.Type, pk.SqlType).Replace(".Replace(StringifySplit, \"|\")", ""), "vs[" + pk_idx++ + "]"); } pkParses = pkParses.Substring(2); str_mvcdel = string.Format(@" async public Task<APIReturn> _Del([FromForm] string[] id) {{ int affrows = 0; foreach (string id2 in id) {{ string[] vs = id2.Split(','); affrows += await {3}{1}.DeleteAsync({2}); }} if (affrows > 0) return APIReturn.成功.SetMessage($""删除成功,影响行数:{{affrows}}""); return APIReturn.失败; }}", solutionName, uClass_Name, pkParses, uClass_Name == "User" ? "BLL." : ""); } sb1.AppendFormat(CONST.Module_Admin_Controller, solutionName, uClass_Name, nClass_Name, pkMvcRoute, "[FromQuery] " + pkCsParam.Replace("?", "").Replace(", ", ", [FromQuery] "), pkCsParamNoType, itemSetValuePK, itemSetValueNotPK, sb2.ToString(), sb3.ToString(), itemCsParamInsertForm, itemCsParamUpdateForm, getListParamQuery, itemSetValuePKInsert, str_controller_list_join, "", str_controller_insert_mn, str_controller_update_mn, str_mvcdel, uClass_Name == "User" ? "BLL." : ""); loc1.Add(new BuildInfo(string.Concat(CONST.moduleAdminPath, @"\Controllers\", uClass_Name, @"Controller.cs"), Deflate.Compress(sb1.ToString()))); clearSb(); #endregion if (ttfk == null || ttfk.Columns[0].Name.ToLower() != "parent_id") { #region wwwroot/xxx/index.html foreach (ColumnInfo col in table.Columns) { List<ForeignKeyInfo> ffks = new List<ForeignKeyInfo>(); foreach (TableInfo fti in _tables) { ffks.AddRange(fti.ForeignKeys.FindAll(delegate (ForeignKeyInfo ffk) { if (ffk.ReferencedTable != null && ffk.ReferencedTable.FullName == table.FullName) { return ffk.ReferencedColumns.Find(delegate (ColumnInfo col88) { return col88.Name == col.Name; }) != null; } return false; })); } foreach (ForeignKeyInfo ffk in ffks) { string FFK_uClass_Name = CodeBuild.UFString(ffk.Table.ClassName); string FFK_nClass_Name = CodeBuild.UFString(ffk.Table.ClassName); string urlQuerys = string.Empty; ffk.Columns.ForEach(delegate (ColumnInfo col88) { string FFK_csUName = CodeBuild.UFString(col.Name); urlQuerys += string.Format("{0}=@item.{1}&", CodeBuild.UFString(col88.Name), FFK_csUName); }); if (urlQuerys.Length > 0) urlQuerys = urlQuerys.Remove(urlQuerys.Length - 1); str_listTh += string.Format(@"<th scope=""col"">&nbsp;</th> "); str_listTd += string.Format(@"<td><a href=""../{0}/?{1}"">{0}</a></td> ", FFK_nClass_Name, urlQuerys); } } sb1.AppendFormat(@"@{{ Layout = """"; }} <div class=""box""> <div class=""box-header with-border""> <h3 id=""box-title"" class=""box-title""></h3> <span class=""form-group mr15""></span><a href=""./add"" data-toggle=""modal"" class=""btn btn-success pull-right"">添加</a> </div> <div class=""box-body""> <div class=""table-responsive""> <form id=""form_search""> <div id=""div_filter""></div> </form> <form id=""form_list"" action=""./del"" method=""post""> @Html.AntiForgeryToken() <input type=""hidden"" name=""__callback"" value=""del_callback""/> <table id=""GridView1"" cellspacing=""0"" rules=""all"" border=""1"" style=""border-collapse:collapse;"" class=""table table-bordered table-hover""> <tr> <th scope=""col"" style=""width:2%;""><input type=""checkbox"" onclick=""$('#GridView1 tbody tr').each(function (idx, el) {{ var chk = $(el).find('td:first input[type=\'checkbox\']')[0]; if (chk) chk.checked = !chk.checked; }});"" /></th> {3}<th scope=""col"" style=""width:5%;"">&nbsp;</th> </tr> <tbody> @foreach({0}Info item in ViewBag.items) {{ <tr> <td><input type=""checkbox"" id=""id"" name=""id"" value=""{2}"" /></td> {4}<td><a href=""./edit?{1}"">修改</a></td> </tr> }} </tbody> </table> </form> <a id=""btn_delete_sel"" href=""#"" class=""btn btn-danger pull-right"">删除选中项</a> <div id=""kkpager""></div> </div> </div> </div> @{{{6} }} <script type=""text/javascript""> (function () {{ top.del_callback = function(rt) {{ if (rt.success) return top.mainViewNav.goto('./?' + new Date().getTime()); alert(rt.message); }}; var qs = _clone(top.mainViewNav.query); var page = cint(qs.page, 1); delete qs.page; $('#kkpager').html(cms2Pager(@ViewBag.count, page, 20, qs, 'page')); var fqs = _clone(top.mainViewNav.query); delete fqs.page; var fsc = [{5} null ]; fsc.pop(); cms2Filter(fsc, fqs); top.mainViewInit(); }})(); </script> ", uClass_Name, pkUrlQuerys, pkHiddens, str_listTh, str_listTd, str_listCms2FilterFK, str_listCms2FilterFK_fkitems); loc1.Add(new BuildInfo(string.Concat(CONST.moduleAdminPath, @"Views\", uClass_Name, @"\List.cshtml"), Deflate.Compress(sb1.ToString()))); clearSb(); #endregion } else { #region wwwroot/xxx/index.html(递归关系) sb1.AppendFormat(@"@{{ Layout = """"; }} <div class=""box""> <div class=""box-header with-border""> <h3 id=""box-title"" class=""box-title""></h3> <span class=""form-group mr15""></span><a href=""./add"" data-toggle=""modal"" class=""btn btn-success pull-right"">添加</a> </div> <div class=""box-body""> <div class=""table-responsive""> <form id=""form_list"" action=""./del"" method=""post""> @Html.AntiForgeryToken() <input type=""hidden"" name=""__callback"" value=""del_callback""/> <table id=""GridView1"" cellspacing=""0"" rules=""all"" border=""1"" style=""border-collapse:collapse;"" class=""table table-bordered table-hover""> <tr> {8}{6}<th scope=""col"" style=""width:5%;"">&nbsp;</th> <th scope=""col"" style=""width:5%;"">删除</th> </tr> <tbody> @foreach({0}Info item in ViewBag.items) {{ <tr data-tt-id=""@item.{1}"" data-tt-parent-id=""@item.{2}""> {9}{7}<td><a href=""./edit?{4}"">修改</a></td> <td><input id=""id"" name=""id"" type=""checkbox"" value=""{5}"" /></td> </tr> }} </tbody> </table> </form> </div> </div> </div> <div> <font color=""red"">*</font> 删除父项时,请先删除其所有子项。 <a id=""btn_delete_sel"" href=""#"" class=""btn btn-danger pull-right"">删除选中项</a> </div> <script type=""text/javascript""> (function() {{ top.del_callback = function(rt) {{ if (rt.success) return top.mainViewNav.goto('./?' + new Date().getTime()); alert(rt.message); }}; $('table#GridView1').treetable({{ expandable: true }}); $('table#GridView1').treetable('expandAll'); top.mainViewInit(); }})(); </script>", uClass_Name, CodeBuild.UFString(table.PrimaryKeys[0].Name), CodeBuild.UFString(ttfk.Columns[0].Name), "", pkUrlQuerys.Replace("a.", ""), pkHiddens.Replace("a.", ""), str_listTh.Replace("a.", ""), str_listTd.Replace("a.", ""), str_listTh1.Replace("a.", ""), str_listTd1.Replace("a.", "")); loc1.Add(new BuildInfo(string.Concat(CONST.moduleAdminPath, @"Views\", uClass_Name, @"\List.cshtml"), Deflate.Compress(sb1.ToString()))); clearSb(); #endregion } #region wwwroot/xxx/add.html foreach (ColumnInfo col in table.Columns) { string csType = CodeBuild.GetCSType(col.Type, uClass_Name + col.Name.ToUpper(), col.SqlType); string csUName = CodeBuild.UFString(col.Name); string lname = col.Name.ToLower(); string comment = _column_coments.ContainsKey(table.FullName) && _column_coments[table.FullName].ContainsKey(col.Name) ? _column_coments[table.FullName][col.Name] : col.Name; string rfvEmpty = string.Empty; List<ColumnInfo> us = table.Uniques.Find(delegate (List<ColumnInfo> cs) { return cs.Find(delegate (ColumnInfo col88) { return col88.Name == col.Name; }) != null; }); if (us == null) us = new List<ColumnInfo>(); List<ForeignKeyInfo> fks_comb = table.ForeignKeys.FindAll(delegate (ForeignKeyInfo fk) { return fk.Columns.Count == 1 && fk.Columns[0].Name == col.Name; }); if (csType == "bool?") { sb4.AppendFormat(@" <tr> <td>{1}</td> <td id=""{0}_td""><input name=""{0}"" type=""checkbox"" value=""true"" /></td> </tr>", csUName, comment); } else if (csType == "DateTime?" && ( string.Compare(lname, "create_time", true) == 0 || string.Compare(lname, "update_time", true) == 0 )) { sb14.AppendFormat(@" <tr> <td>{1}</td> <td><input name=""{0}"" type=""text"" readonly class=""datepicker"" style=""width:20%;background-color:#ddd;"" /></td> </tr>", csUName, comment); } else if (col.IsPrimaryKey && col.IsIdentity) { //主键自动增值 sb4.AppendFormat(@" @if (item != null) {{ <tr> <td>{1}</td> <td><input name=""{0}"" type=""text"" readonly class=""datepicker"" style=""width:20%;background-color:#ddd;"" /></td> </tr> }}", csUName, comment); } else if (fks_comb.Count == 1) { //外键下拉框 ForeignKeyInfo fkcb = fks_comb[0]; string FK_uClass_Name = fkcb.ReferencedTable != null ? CodeBuild.UFString(fkcb.ReferencedTable.ClassName) : CodeBuild.UFString(TableInfo.GetClassName(fkcb.ReferencedTableName)); ForeignKeyInfo fkrr = fkcb.ReferencedTable != null ? fkcb.ReferencedTable.ForeignKeys.Find(delegate (ForeignKeyInfo fkkk) { return fkkk.ReferencedTable != null && fkcb.ReferencedTable.FullName == fkkk.ReferencedTable.FullName; }) : null; bool isParentSelect = fkcb.ReferencedTable != null && fkrr != null; string FK_Column = fkcb.ReferencedTable != null ? CodeBuild.UFString(fkcb.ReferencedColumns[0].Name) : CodeBuild.UFString(fkcb.ReferencedColumnNames[0]); ColumnInfo strCol = fkcb.ReferencedTable.Columns.Find(delegate (ColumnInfo col99) { return col99.Name.ToLower().IndexOf("name") != -1 || col99.Name.ToLower().IndexOf("title") != -1; }); if (strCol == null) strCol = fkcb.ReferencedTable.Columns.Find(delegate (ColumnInfo col99) { return GetCSType(col99.Type, CodeBuild.UFString(fkcb.ReferencedTable.ClassName) + col99.Name.ToUpper(), col99.SqlType) == "string" && col99.Length > 0 && col99.Length < 300; }); string FK_Column_Text = fkcb.ReferencedTable != null && strCol != null ? CodeBuild.UFString(strCol.Name) : FK_Column; if (isParentSelect) { sb4.AppendFormat(@" <tr> <td>{1}</td> <td id=""{0}_td""></td> </tr>", csUName, comment); sb5.AppendFormat(@" $('#{3}_td').html(yieldTreeSelect(yieldTreeArray(@Html.Json(fk_{0}s), null, '{1}', '{2}'), '{{#{4}}}', '{1}')).find('select').attr('name', '{3}');", FK_uClass_Name, CodeBuild.UFString(fkcb.ReferencedColumns[0].Name), CodeBuild.UFString(fkrr.Columns[0].Name), csUName, FK_Column_Text); } else { sb4.AppendFormat(@" <tr> <td>{1}</td> <td> <select name=""{0}""> <option value="""">------ 请选择 ------</option> @foreach (var fk in fk_{4}s) {{ <option value=""@fk.{2}"">@fk.{3}</option> }} </select> </td> </tr>", csUName, comment, CodeBuild.UFString(fkcb.ReferencedColumns[0].Name), FK_Column_Text, FK_uClass_Name); } if (str_fk_getlist.Contains(" var fk_" + FK_uClass_Name + "s") == false) str_fk_getlist += string.Format(@" var fk_{0}s = {1}{0}.Select.ToList();", FK_uClass_Name, FK_uClass_Name == "User" ? solutionName + ".BLL." : ""); } else if ((col.Type == MySqlDbType.UInt32 || col.Type == MySqlDbType.UInt64) && (lname == "status" || lname.StartsWith("status_") || lname.EndsWith("_status"))) { //加载 multi 多状态字段 sb4.AppendFormat(@" <tr> <td>{1}</td> <td><input name=""{0}"" type=""hidden"" multi_status=""状态1,状态2,状态3,状态4,状态5"" /></td> </tr>", csUName, comment); } else if ( col.Type == MySqlDbType.Byte || col.Type == MySqlDbType.Int16 || col.Type == MySqlDbType.Int24 || col.Type == MySqlDbType.Int32 || col.Type == MySqlDbType.Int64 || col.Type == MySqlDbType.UByte || col.Type == MySqlDbType.UInt16 || col.Type == MySqlDbType.UInt24 || col.Type == MySqlDbType.UInt32 || col.Type == MySqlDbType.UInt64 || col.Type == MySqlDbType.Year) { sb4.AppendFormat(@" <tr> <td>{1}</td> <td><input name=""{0}"" type=""text"" class=""form-control"" data-inputmask=""'mask': '9', 'repeat': 6, 'greedy': false"" data-mask style=""width:200px;"" /></td> </tr>", csUName, comment); } else if (col.Type == MySqlDbType.Double || col.Type == MySqlDbType.Float || col.Type == MySqlDbType.Decimal) { sb4.AppendFormat(@" <tr> <td>{1}</td> <td> <div class=""input-group"" style=""width:200px;""> <span class=""input-group-addon"">¥</span> <input name=""{0}"" type=""text"" class=""form-control"" data-inputmask=""'mask': '9', 'repeat': 10, 'greedy': false"" data-mask /> <span class=""input-group-addon"">.00</span> </div> </td> </tr>", csUName, comment); } else if (col.Type == MySqlDbType.Date || col.Type == MySqlDbType.Time || col.Type == MySqlDbType.Timestamp || col.Type == MySqlDbType.Datetime) { //日期 sb4.AppendFormat(@" <tr> <td>{1}</td> <td><input name=""{0}"" type=""text"" class=""datepicker"" /></td> </tr>", csUName, comment); } else if (col.Type == MySqlDbType.Date) { //日期控件 sb4.AppendFormat(@" <tr> <td>{1}</td> <td> <div class=""input-group date"" style=""width:200px;""> <div class=""input-group-addon""><i class=""fa fa-calendar""></i></div> <input name=""{0}"" type=""text"" data-provide=""datepicker"" class=""form-control pull-right"" readonly /> </div> </td> </tr>", csUName, comment); } else if ((lname == "img" || lname.StartsWith("img_") || lname.EndsWith("_img") || lname == "path" || lname.StartsWith("path_") || lname.EndsWith("_path")) && (col.Type == MySqlDbType.VarChar || col.Type == MySqlDbType.VarString || col.Type == MySqlDbType.String)) { //图片字段 sb4.AppendFormat(@" <tr> <td>{1}</td> <td> <input name=""{0}"" type=""text"" class=""datepicker"" style=""width:60%;"" /> <input name=""{0}_file"" type=""file""> </td> </tr>", csUName, comment); } else if (col.Type == MySqlDbType.TinyText || col.Type == MySqlDbType.Text || col.Type == MySqlDbType.MediumText || col.Type == MySqlDbType.LongText) { //加载百度编辑器 sb4.AppendFormat(@" <tr> <td>{1}</td> <td><textarea name=""{0}"" style=""width:100%;height:100px;"" editor=""ueditor""></textarea></td> </tr>", csUName, comment); } else if (col.Type == MySqlDbType.Enum || col.Type == MySqlDbType.Set) { sb4.AppendFormat(@" <tr> <td>{1}</td> <td> <select name=""{0}""{3} @foreach (object eo in Enum.GetValues(typeof({2}))) {{ <option value=""@eo"">@eo</option> }} </select> </td> </tr>", csUName, comment, GetCSType(col.Type, CodeBuild.UFString(table.ClassName) + col.Name.ToUpper(), col.SqlType).Replace("?", ""), col.Type == MySqlDbType.Set ? string.Format(@" data-placeholder=""Select a {0}"" class=""form-control select2"" multiple>", comment) : @"><option value="""">------ 请选择 ------</option>"); } else { sb4.AppendFormat(@" <tr> <td>{1}</td> <td><input name=""{0}"" type=""text"" class=""datepicker"" style=""width:60%;"" /></td> </tr>", csUName, comment); } } sb4.Append(str_addhtml_mn); if (sb14.ToString().Length > 0) { sb14.Insert(0, @" @if (item != null) {"); sb14.Append(@" }"); } sb1.AppendFormat(@"@{{ Layout = """"; {0}Info item = ViewBag.item;{3} }} <div class=""box""> <div class=""box-header with-border""> <h3 class=""box-title"" id=""box-title""></h3> </div> <div class=""box-body""> <div class=""table-responsive""> <form id=""form_add"" method=""post""> @Html.AntiForgeryToken() <input type=""hidden"" name=""__callback"" value=""edit_callback"" /> <div> <table cellspacing=""0"" rules=""all"" class=""table table-bordered table-hover"" border=""1"" style=""border-collapse:collapse;"">{1}{5} <tr> <td width=""8%"">&nbsp</td> <td><input type=""submit"" value=""@(item == null ? ""添加"" : ""更新"")"" />&nbsp;<input type=""button"" value=""取消"" /></td> </tr> </table> </div> </form> </div> </div> </div> <script type=""text/javascript""> (function () {{ top.edit_callback = function (rt) {{ if (rt.success) return top.mainViewNav.goto('./?' + new Date().getTime()); alert(rt.message); }}; {2} var form = $('#form_add')[0]; var item = null; @if (item != null) {{ <text> item = @Html.Json(item); fillForm(form, item);{4} </text> }} top.mainViewInit(); }})(); </script>", uClass_Name, sb4.ToString(), sb5.ToString(), str_fk_getlist, str_addjs_mn_initUI, sb14.ToString()); loc1.Add(new BuildInfo(string.Concat(CONST.moduleAdminPath, @"Views\", uClass_Name, @"\Edit.cshtml"), Deflate.Compress(sb1.ToString()))); clearSb(); #endregion } #endregion } #region BLL ItemCache.cs sb1.AppendFormat(CONST.BLL_Build_ItemCache_cs, solutionName); //loc1.Add(new BuildInfo(string.Concat(CONST.corePath, solutionName, @".db\BLL\", basicName, @"\ItemCache.cs"), Deflate.Compress(sb1.ToString()))); clearSb(); #endregion #region Model ExtensionMethods.cs 扩展方法 sb1.AppendFormat(CONST.Model_Build_ExtensionMethods_cs, solutionName, Model_Build_ExtensionMethods_cs.ToString()); loc1.Add(new BuildInfo(string.Concat(CONST.corePath, solutionName, @".db\Model\", basicName, @"\ExtensionMethods.cs"), Deflate.Compress(sb1.ToString()))); clearSb(); #endregion #region DBUtility/SqlHelper.cs sb1.AppendFormat(CONST.DAL_DBUtility_SqlHelper_cs, solutionName, connectionStringName); loc1.Add(new BuildInfo(string.Concat(CONST.corePath, solutionName, @".db\DAL\DBUtility\SqlHelper.cs"), Deflate.Compress(sb1.ToString()))); clearSb(); #endregion if (isSolution) { #region db.csproj sb1.AppendFormat(CONST.Db_csproj, solutionName); loc1.Add(new BuildInfo(string.Concat(CONST.corePath, solutionName, @".db\", solutionName, ".db.csproj"), Deflate.Compress(sb1.ToString()))); clearSb(); #endregion #region Module/Test #region TestController.cs sb1.AppendFormat(CONST.Module_Test_Controller, solutionName, "Test"); loc1.Add(new BuildInfo(string.Concat(CONST.corePath, @"Module\Test\Controllers\TestController.cs"), Deflate.Compress(sb1.ToString()))); clearSb(); #endregion #region Init.cs sb1.AppendFormat(CONST.Module_Test_Init_cs, solutionName, "Test"); loc1.Add(new BuildInfo(string.Concat(CONST.corePath, @"Module\Test\Init.cs"), Deflate.Compress(sb1.ToString()))); clearSb(); #endregion #region appsettings.json loc1.Add(new BuildInfo(string.Concat(CONST.corePath, @"Module\Test\appsettings.json"), Deflate.Compress("{\r\n}"))); clearSb(); #endregion #region Views\_ViewStart.cshtml sb1.AppendFormat(@"@{{ Layout = ""_Layout""; }}", solutionName); loc1.Add(new BuildInfo(string.Concat(CONST.corePath, @"Module\Test\Views\_ViewStart.cshtml"), Deflate.Compress(sb1.ToString()))); clearSb(); #endregion #region Views\_ViewImports.cshtml sb1.AppendFormat(@"@using Newtonsoft.Json; @using {0}.BLL; @using {0}.Model; @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers ", solutionName); loc1.Add(new BuildInfo(string.Concat(CONST.corePath, @"Module\Test\Views\_ViewImports.cshtml"), Deflate.Compress(sb1.ToString()))); clearSb(); #endregion #region Views\Shared\_Layout.cshtml sb1.AppendFormat(@"<!DOCTYPE html> <html> <head> <meta charset=""utf-8""> <title>@ViewBag.title</title> <link rel=""stylesheet"" href=""//cdn.bootcss.com/semantic-ui/2.1.8/semantic.min.css""> <link rel=""stylesheet"" href=""/css/style.css""> <script src=""//cdn.bootcss.com/jquery/1.11.3/jquery.min.js""></script> <script src=""//cdn.bootcss.com/semantic-ui/2.1.8/semantic.min.js""></script> </head> <body> @RenderBody() </body> </html>", solutionName); loc1.Add(new BuildInfo(string.Concat(CONST.corePath, @"Module\Test\Views\Shared\_Layout.cshtml"), Deflate.Compress(sb1.ToString()))); clearSb(); #endregion #region Test.csproj sb1.AppendFormat(CONST.Module_csproj, "Test"); loc1.Add(new BuildInfo(string.Concat(CONST.corePath, @"Module\Test\Test.csproj"), Deflate.Compress(sb1.ToString()))); clearSb(); #endregion #endregion #region .gitattributes sb1.Append(Server.Properties.Resources._gitattributes); loc1.Add(new BuildInfo(string.Concat(CONST.corePath, @"..\.gitattributes"), Deflate.Compress(sb1.ToString()))); clearSb(); #endregion #region .gitignore sb1.Append(Server.Properties.Resources._gitignore); loc1.Add(new BuildInfo(string.Concat(CONST.corePath, @"..\.gitignore"), Deflate.Compress(sb1.ToString()))); clearSb(); #endregion #region build.bat sb1.Append(Server.Properties.Resources._build_bat); loc1.Add(new BuildInfo(string.Concat(CONST.corePath, @"..\build.bat"), Deflate.Compress(sb1.ToString()))); clearSb(); #endregion #region readme.md loc1.Add(new BuildInfo(string.Concat(CONST.corePath, @"..\readme.md"), Deflate.Compress(string.Format(@"# {0} .net core模块化开发框架 本项目由 [【dotnetGen_mysql】](https://github.com/2881099/dotnetGen_mysql) 工具生成 ## Module 所有业务接口约定在 Module 划分并行开发,互不依赖 Module/Admin 生成的后台管理模块,http://localhost:5001/module/Admin 可访问 Module/Test 生成的测试模块 ## WebHost WebHost 编译的时候,会将 Module/* 编译结果复制到当前目录 WebHost 只当做主引擎运行时按需加载相应的 Module WebHost 依赖 npm ,请安装 node,并在目录执行 npm install WebHost 依赖 gulp-cli,请执行全局安装 npm install --global gulp-cli 运行步骤: 1、打开 vs 右击 Module 目录全部编译; 2、cd WebHost && npm install && dotnet build && dotnet run ## Infrastructure Module 里面每个子模块的依赖所需 #### xx.db 包含一切数据库操作的封装 xx.Model(实体映射) xx.BLL(静态方法封装) xx.DAL(数据访问) 生成名特征取数据库名首字母大写(如: 表 test 对应 xx.Model.TestInfo、xx.BLL.Test、xx.DAL.Test) 数据库设计命名习惯:所有命名(username, stats_click)、外键字段(user_id) 仅支持主键作为外键,不支持组合字段,不支持唯一键作为外键 修改数据库后,双击“./GenMy只更新db.bat”可快速覆盖,所有类都使用 partial,方便扩展亦不会被二次生成覆盖 # 数据库相关方法 ## 添加记录 ```csharp // 如有 create_time 字段并且类型为日期,内部会初始化 TestInfo newitem1 = Test.Insert(Title: ""添加的标题"", Content: ""这是一段添加的内容""); TestInfo newitem2 = Test.Insert(new TestInfo {{ Title = ""添加的标题"", Content = ""这是一段添加的内容"" }}); ``` ## 添加记录(批量) ```csharp List<TestInfo> newitems1 = Test.Insert(new [] {{ new TestInfo {{ Title = ""添加的标题1"", Content = ""这是一段添加的内容1"" }}, new TestInfo {{ Title = ""添加的标题2"", Content = ""这是一段添加的内容2"" }} }}); ``` ## 更新记录 ```csharp // 更新 id = 1 所有字段 Test.Update(new TestInfo {{ Id: 1, Title = ""添加的标题"", Content = ""这是一段添加的内容"", Clicks = 1 }}); // 更新 id = 1 指定字段 Test.UpdateDiy(1).SetTitle(""修改后的标题"").SetContent(""修改后的内容"").SetClicks(1).ExecuteNonQuery(); // update 表名 set clicks = clicks + 1 where id = 1 Test.UpdateDiy(1).SetClicksIncrement(1).ExecuteNonQuery(); // 使用实体层修改 new TestInfo {{ Id = 1 }}.UpdateDiy.SetClicksIncrement(1).ExecuteNonQuery(); ``` ## 更新记录(批量) ```csharp //先查找 clicks 在 0 - 100 的记录 List<TestInfo> newitems1 = Test.Select.WhereClicksRange(0, 100).ToList(); // update 表名 set clicks = clicks + 1 where id in (newitems1所有id) newitems1.UpdateDiy().SetClicksIncrement(1).ExecuteNonQuery(); ``` > 警告:批量更新的方法,在事务中使用会导致死锁 ## 删除记录 ```csharp // 删除 id = 1 的记录 Test.Delete(1); ``` ## 按主键/唯一键获取单条记录 > appsettings可配置缓存时间,以上所有增、改、删都会删除缓存保障同步 ```csharp //按主键获取 UserInfo user1 = User.GetItem(1); //按唯一键 UserInfo user2 = User.GetItemByUsername(""2881099@qq.com""); // 返回 null 或 UserInfo ``` ## 查询(核心) ```csharp //BLL.表名.Select 是一个链式查询对象,几乎支持所有查询,包括 group by、inner join等等,最终 ToList ToOne Aggregate 执行 sql List<UserInfo> users1 = User.Select.WhereUsername(""2881099@qq.com"").WherePassword(""******"").WhereStatus(正常).ToList(); //返回 new List<UserInfo>() 或 有元素的 List,永不返回 null //返回指定列,返回List<元组> var users2 = User.Select.WhereStatus(正常).Aggregate<(int id, string title)>(""id,title""); //多表查询,只返回 a 表字段 var users3 = User.Select.Where(a => a.Obj_user_group.Id == a.Group_id).ToList(); //join查询,返回 a, b 表字段 ,b 表结果填充至 a.Obj_user_group 对象,类似 ef.Include var users4 = User.Select.InnerJoin(a => a.Obj_user_group.Id == a.Group_id).ToList(); //分组查询 var users5 = User.Select.GroupBy(""group_id"").Aggregate<(int groupId, int count)>(""group_id, count(1)""); //等等... ``` ## 事务 ```csharp //错误会回滚,事务内支持所有生成的同步方法(不支持生成对应的Async方法) var user = User.GetItem(1); SqlHelper.Transaction(() => {{ if (user.UpdateDiy.SetAmountIncrement(-num).Where(""amount > {{0}}"", num).ExecuteNonQuery() <= 0) throw new Exception(""余额不足""); var order = user.AddOrder(Amount: 1, Count: num, Count_off: num); }}); ``` ## 缓存 1、根据主键、唯一键缓存 BLL GetItem、GetItemBy唯一键,使用了默认缓存策略180秒,用来缓存一条记录,db 层自动维护缓存同步,例如: ```csharp //只有第一次查询了数据库,后面99次读取redis的缓存值 UserInfo u; for (var a = 0; a < 100; a++) u = User.GetItemByUsername(""2881099@qq.com""); //执行类似以下的数据变动方法,会删除redis对应的缓存 u.UpdateDiy.SetLogin_time(DateTime.Now).ExecuteNonQuery(); ``` 2、缓存一个查询结果 BLL Select.ToList(10, ""cache_key""),将查询结果缓存10秒,需要手工删除redis对应的键 ## 读写分离 内置实现读和写分离,一个【主库】多个【从库】,【从库】的查询策略为随机方式。 若某【从库】发生故障,将切换到其他可用【从库】,若已全部不可用则使用【主库】查询。 出现故障【从库】被隔离起来间隔性的检查可用状态,以待恢复。 ```csharp Topic.Select.WhereId(1).ToOne(); //读【从库】(默认) Topic.Select.Master().WhereId(1).ToOne(); //读【主库】 ``` # 生成规则 ## 不会生成 * 没有主键,不会生成 增、改、删 方法 * 有自增字段,不会生成 批量 Insert 方法 ## 特别规则 * 字段类型 point,会生成 > 表.Select.Where字段MbrContains(查找地理位置多少米范围内的记录,距离由近到远排序) * 字段类型 string 相关并且长度 <= 300,会生成 > 表.Select.Where字段Like * 99%的数据类型被支持 ", solutionName)))); clearSb(); #endregion #region GenMy只更新db.bat loc1.Add(new BuildInfo(string.Concat(CONST.corePath, @"..\GenMy只更新db.bat"), Deflate.Compress(string.Format(@" GenMy {0}:{1} -U {2} -P {3} -D {4} -N {5}", _client.Server, _client.Port, _client.Username, _client.Password, _client.Database, solutionName)))); clearSb(); #endregion } if (isMakeAdmin) { #region WebHost #region Extensions/StarupExtensions.cs sb1.AppendFormat(CONST.WebHost_Extensions_StarupExtensions_cs, solutionName); loc1.Add(new BuildInfo(string.Concat(CONST.webHostPath, @"\Extensions\StarupExtensions.cs"), Deflate.Compress(sb1.ToString()))); clearSb(); #endregion #region Extensions/SwaggerExtensions.cs sb1.AppendFormat(CONST.WebHost_Extensions_SwaggerExtensions_cs, solutionName); loc1.Add(new BuildInfo(string.Concat(CONST.webHostPath, @"\Extensions\SwaggerExtensions.cs"), Deflate.Compress(sb1.ToString()))); clearSb(); #endregion #region .gitignore sb1.Append(Server.Properties.Resources.WebHost_gitignore); loc1.Add(new BuildInfo(string.Concat(CONST.webHostPath, @".gitignore"), Deflate.Compress(sb1.ToString()))); clearSb(); #endregion #region appsettings.json sb1.AppendFormat(CONST.WebHost_appsettings_json, solutionName); loc1.Add(new BuildInfo(string.Concat(CONST.webHostPath, @"appsettings.json"), Deflate.Compress(sb1.ToString()))); clearSb(); #endregion #region gulpfile.js sb1.Append(Server.Properties.Resources.WebHost_gulpfile_js); loc1.Add(new BuildInfo(string.Concat(CONST.webHostPath, @"gulpfile.js"), Deflate.Compress(sb1.ToString()))); clearSb(); #endregion #region nlog.config sb1.AppendFormat(CONST.WebHost_nlog_config, solutionName); loc1.Add(new BuildInfo(string.Concat(CONST.webHostPath, @"nlog.config"), Deflate.Compress(sb1.ToString()))); clearSb(); #endregion #region package.json sb1.Append(Server.Properties.Resources.WebHost_package_json); loc1.Add(new BuildInfo(string.Concat(CONST.webHostPath, @"package.json"), Deflate.Compress(sb1.ToString()))); clearSb(); #endregion #region Program.cs sb1.AppendFormat(CONST.WebHost_Program_cs, solutionName); loc1.Add(new BuildInfo(string.Concat(CONST.webHostPath, @"Program.cs"), Deflate.Compress(sb1.ToString()))); clearSb(); #endregion #region Startup.cs sb1.AppendFormat(CONST.WebHost_Startup_cs, solutionName); loc1.Add(new BuildInfo(string.Concat(CONST.webHostPath, @"Startup.cs"), Deflate.Compress(sb1.ToString()))); clearSb(); #endregion #region web.config sb1.Append(Server.Properties.Resources.WebHost_web_config); loc1.Add(new BuildInfo(string.Concat(CONST.webHostPath, @"web.config"), Deflate.Compress(sb1.ToString()))); clearSb(); #endregion #region WebHost.csproj sb1.AppendFormat(CONST.WebHost_csproj, solutionName); loc1.Add(new BuildInfo(string.Concat(CONST.webHostPath, @"WebHost.csproj"), Deflate.Compress(sb1.ToString()))); clearSb(); #endregion #endregion #region Module/Admin #region SysController.cs sb1.AppendFormat(CONST.Module_Admin_Controllers_SysController, solutionName, string.Join(string.Empty, admin_controllers_syscontroller_init_sysdir.ToArray())); loc1.Add(new BuildInfo(string.Concat(CONST.moduleAdminPath, @"Controllers\SysController.cs"), Deflate.Compress(sb1.ToString()))); clearSb(); #endregion #region LoginController.cs sb1.AppendFormat(CONST.Module_Admin_Controllers_LoginController, solutionName); loc1.Add(new BuildInfo(string.Concat(CONST.moduleAdminPath, @"Controllers\LoginController.cs"), Deflate.Compress(sb1.ToString()))); clearSb(); #endregion #region Views\Admin\Login\Index.cshtml sb1.AppendFormat(CONST.Module_Admin_Views_Login_Index_cshtml, solutionName); loc1.Add(new BuildInfo(string.Concat(CONST.moduleAdminPath, @"Views\Login\Index.cshtml"), Deflate.Compress(sb1.ToString()))); clearSb(); #endregion #region wwwroot\index.html sb1.AppendFormat(CONST.Module_Admin_wwwroot_index_html, solutionName, wwwroot_sitemap); loc1.Add(new BuildInfo(string.Concat(CONST.moduleAdminPath, @"wwwroot\index.html"), Deflate.Compress(sb1.ToString()))); clearSb(); #endregion #region Init.cs sb1.AppendFormat(CONST.Module_Test_Init_cs, solutionName, "Admin"); loc1.Add(new BuildInfo(string.Concat(CONST.moduleAdminPath, @"Init.cs"), Deflate.Compress(sb1.ToString()))); clearSb(); #endregion #region appsettings.json loc1.Add(new BuildInfo(string.Concat(CONST.moduleAdminPath, @"appsettings.json"), Deflate.Compress("{\r\n}"))); clearSb(); #endregion #region Views\_ViewStart.cshtml sb1.AppendFormat(@"@{{ Layout = ""_Layout""; }}", solutionName); loc1.Add(new BuildInfo(string.Concat(CONST.moduleAdminPath, @"Views\_ViewStart.cshtml"), Deflate.Compress(sb1.ToString()))); clearSb(); #endregion #region Views\_ViewImports.cshtml sb1.AppendFormat(@"@using Newtonsoft.Json; @using {0}.BLL; @using {0}.Model; @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers ", solutionName); loc1.Add(new BuildInfo(string.Concat(CONST.moduleAdminPath, @"Views\_ViewImports.cshtml"), Deflate.Compress(sb1.ToString()))); clearSb(); #endregion #region Views\Shared\_Layout.cshtml sb1.AppendFormat(@"<!DOCTYPE html> <html> <head> <meta charset=""utf-8""> <title>@ViewBag.title</title> <link rel=""stylesheet"" href=""//cdn.bootcss.com/semantic-ui/2.1.8/semantic.min.css""> <link rel=""stylesheet"" href=""/css/style.css""> <script src=""//cdn.bootcss.com/jquery/1.11.3/jquery.min.js""></script> <script src=""//cdn.bootcss.com/semantic-ui/2.1.8/semantic.min.js""></script> </head> <body> @RenderBody() </body> </html>", solutionName); loc1.Add(new BuildInfo(string.Concat(CONST.moduleAdminPath, @"Views\Shared\_Layout.cshtml"), Deflate.Compress(sb1.ToString()))); clearSb(); #endregion #region Admin.csproj sb1.AppendFormat(CONST.Module_csproj, "Admin"); loc1.Add(new BuildInfo(string.Concat(CONST.moduleAdminPath, @"Admin.csproj"), Deflate.Compress(sb1.ToString()))); clearSb(); #endregion #endregion } if (isDownloadRes) { loc1.Add(new BuildInfo(string.Concat(CONST.corePath, @"..\htm.zip"), Server.Properties.Resources.htm_zip)); } GC.Collect(); return loc1; } } }
2881099/FreeIM
8,123
FreeIM/ImServer.cs
 #if ns20 using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using Newtonsoft.Json; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Net.WebSockets; using System.Text; using System.Threading; using System.Threading.Tasks; public static class FreeImServerExtenssions { static bool isUseWebSockets = false; /// <summary> /// 启用 ImServer 服务端 /// </summary> /// <param name="app"></param> /// <param name="options"></param> /// <returns></returns> public static IApplicationBuilder UseFreeImServer(this IApplicationBuilder app, ImServerOptions options) { app.Map(options.PathMatch, appcur => { var imserv = new ImServer(options); if (isUseWebSockets == false) { isUseWebSockets = true; appcur.UseWebSockets(); } appcur.Use((ctx, next) => imserv.Acceptor(ctx, next)); }); return app; } } /// <summary> /// im 核心类实现的配置所需 /// </summary> public class ImServerOptions : ImClientOptions { /// <summary> /// 设置服务名称,它应该是 servers 内的一个 /// </summary> public string Server { get; set; } } class ImServer : ImClient { protected string _server { get; set; } public ImServer(ImServerOptions options) : base(options) { _server = options.Server; _redis.Subscribe($"{_redisPrefix}Server{_server}", RedisSubScribleMessage); } const int BufferSize = 4096; ConcurrentDictionary<long, ConcurrentDictionary<Guid, ImServerClient>> _clients = new ConcurrentDictionary<long, ConcurrentDictionary<Guid, ImServerClient>>(); class ImServerClient { public WebSocket socket; public long clientId; public ImServerClient(WebSocket socket, long clientId) { this.socket = socket; this.clientId = clientId; } } internal async Task Acceptor(HttpContext context, Func<Task> next) { if (!context.WebSockets.IsWebSocketRequest) return; string token = context.Request.Query["token"]; if (string.IsNullOrEmpty(token)) return; var token_value = _redis.Get($"{_redisPrefix}Token{token}"); if (string.IsNullOrEmpty(token_value)) throw new Exception("授权错误:用户需通过 ImHelper.PrevConnectServer 获得包含 token 的连接"); var data = JsonConvert.DeserializeObject<(long clientId, string clientMetaData)>(token_value); var socket = await context.WebSockets.AcceptWebSocketAsync(); var cli = new ImServerClient(socket, data.clientId); var newid = Guid.NewGuid(); var wslist = _clients.GetOrAdd(data.clientId, cliid => new ConcurrentDictionary<Guid, ImServerClient>()); wslist.TryAdd(newid, cli); using (var pipe = _redis.StartPipe()) { pipe.HIncrBy($"{_redisPrefix}Online", data.clientId.ToString(), 1); pipe.Publish($"evt_{_redisPrefix}Online", token_value); pipe.EndPipe(); } var buffer = new byte[BufferSize]; var seg = new ArraySegment<byte>(buffer); try { while (socket.State == WebSocketState.Open && _clients.ContainsKey(data.clientId)) { var incoming = await socket.ReceiveAsync(seg, CancellationToken.None); var outgoing = new ArraySegment<byte>(buffer, 0, incoming.Count); } socket.Abort(); } catch { } wslist.TryRemove(newid, out var oldcli); if (wslist.Any() == false) _clients.TryRemove(data.clientId, out var oldwslist); _redis.Eval($"if redis.call('HINCRBY', KEYS[1], '{data.clientId}', '-1') <= 0 then redis.call('HDEL', KEYS[1], '{data.clientId}') end return 1", new[] { $"{_redisPrefix}Online" }); LeaveChan(data.clientId, GetChanListByClientId(data.clientId)); _redis.Publish($"evt_{_redisPrefix}Offline", token_value); } void RedisSubScribleMessage(string chan, object msg) { try { var msgtxt = msg as string; if (msgtxt.StartsWith("__FreeIM__(ForceOffline)")) { if (long.TryParse(msgtxt.Substring(24), out var clientId) && _clients.TryRemove(clientId, out var oldclients)) foreach (var oldcli in oldclients) { try { oldcli.Value.socket.CloseAsync(WebSocketCloseStatus.EndpointUnavailable, "disconnect", CancellationToken.None).GetAwaiter().GetResult(); } catch { } try { oldcli.Value.socket.Abort(); } catch { } try { oldcli.Value.socket.Dispose(); } catch { } } return; } IEnumerable<long> receiveClientIds = null; (long senderClientId, List<long>, string content, bool receipt) data; if (msgtxt.StartsWith("__FreeIM__(ChanMessage)")) { var chanData = JsonConvert.DeserializeObject<(long senderClientId, string receiveChan, string content)>(msgtxt.Substring(23)); data.senderClientId = chanData.senderClientId; data.content = chanData.content; data.receipt = false; receiveClientIds = string.IsNullOrEmpty(chanData.receiveChan) ? _clients.Keys : _redis.HKeys($"{_redisPrefix}Chan{chanData.receiveChan}").Select(a => long.TryParse(a, out var tryval) ? tryval : 0).Where(a => a != 0).ToList(); } else { data = JsonConvert.DeserializeObject<(long senderClientId, List<long>, string content, bool receipt)>(msgtxt); receiveClientIds = data.Item2; //Console.WriteLine($"收到消息:{data.content}" + (data.receipt ? "【需回执】" : "")); } var outgoing = new ArraySegment<byte>(Encoding.UTF8.GetBytes(data.content)); foreach (var clientId in receiveClientIds) { if (_clients.TryGetValue(clientId, out var wslist) == false) { //Console.WriteLine($"websocket{clientId} 离线了,{data.content}" + (data.receipt ? "【需回执】" : "")); if (data.senderClientId != 0 && clientId != data.senderClientId && data.receipt) SendMessage(clientId, new[] { data.senderClientId }, new { data.content, receipt = "用户不在线" }); continue; } ImServerClient[] sockarray = wslist.Values.ToArray(); //如果接收消息人是发送者,并且接收者只有1个以下,则不发送 //只有接收者为多端时,才转发消息通知其他端 if (clientId == data.senderClientId && sockarray.Length <= 1) continue; foreach (var sh in sockarray) sh.socket.SendAsync(outgoing, WebSocketMessageType.Text, true, CancellationToken.None) .ContinueWith(async (t, state) => { if (t.Exception != null) { var ws = state as WebSocket; try { await ws.CloseAsync(WebSocketCloseStatus.EndpointUnavailable, "disconnect", CancellationToken.None); } catch { } try { ws.Abort(); } catch { } try { ws.Dispose(); } catch { } } }, sh.socket); if (data.senderClientId != 0 && clientId != data.senderClientId && data.receipt) SendMessage(clientId, new[] { data.senderClientId }, new { data.content, receipt = "发送成功" }); } } catch (Exception ex) { Console.WriteLine($"FreeIM.ImServer 订阅方法出错了:{ex.Message}\r\n{ex.StackTrace}"); } } } #endif
2881099/FreeIM
1,641
FreeIM/FreeIM.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFrameworks>netstandard2.0;net45</TargetFrameworks> <Version>2.0.4</Version> <GeneratePackageOnBuild>true</GeneratePackageOnBuild> <Authors>YeXiangQin</Authors> <Description>.NET websocket 实现简易、高性能、集群即时通讯组件,支持点对点通讯、群聊通讯、上线下线事件消息等众多实用性功能.</Description> <PackageProjectUrl>https://github.com/2881099/FreeIM</PackageProjectUrl> <RepositoryUrl>https://github.com/2881099/FreeIM</RepositoryUrl> <RepositoryType>git</RepositoryType> <PackageLicenseExpression>MIT</PackageLicenseExpression> <PackageTags>im;websocket;signalr</PackageTags> <PackageId>$(AssemblyName)</PackageId> <Title>$(AssemblyName)</Title> <IsPackable>true</IsPackable> <GenerateAssemblyInfo>true</GenerateAssemblyInfo> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'"> <DocumentationFile>FreeIM.xml</DocumentationFile> <WarningLevel>3</WarningLevel> </PropertyGroup> <ItemGroup> <PackageReference Include="FreeRedis" Version="1.3.7" /> <PackageReference Include="Newtonsoft.Json" Version="13.0.1" /> </ItemGroup> <ItemGroup Condition="'$(TargetFramework)' == 'net45'"> <PackageReference Include="System.Memory" Version="4.5.5" /> <PackageReference Include="System.ValueTuple" Version="4.5.0" /> </ItemGroup> <ItemGroup Condition="'$(TargetFramework)' == 'netstandard2.0'"> <PackageReference Include="Microsoft.AspNetCore.WebSockets" Version="2.3.0" /> </ItemGroup> <PropertyGroup Condition="'$(TargetFramework)' == 'netstandard2.0'"> <DefineConstants>ns20;netstandard20</DefineConstants> </PropertyGroup> </Project>
2881099/FreeIM
4,910
FreeIM/ImHelper.cs
using System; using System.Collections.Generic; /// <summary> /// im 核心类 ImClient 实现的静态代理类 /// </summary> public static class ImHelper { static ImClient _instance; public static ImClient Instance => _instance ?? throw new Exception("使用前请初始化 ImHelper.Initialization(...);"); /// <summary> /// 初始化 ImHelper /// </summary> /// <param name="options"></param> public static void Initialization(ImClientOptions options) { _instance = new ImClient(options); } /// <summary> /// ImServer 连接前的负载、授权,返回 ws 目标地址,使用该地址连接 websocket 服务端 /// </summary> /// <param name="clientId">客户端id</param> /// <param name="clientMetaData">客户端相关信息,比如ip</param> /// <returns>websocket 地址:ws://xxxx/ws?token=xxx</returns> public static string PrevConnectServer(long clientId, string clientMetaData) => Instance.PrevConnectServer(clientId, clientMetaData); /// <summary> /// 向指定的多个客户端id发送消息 /// </summary> /// <param name="senderClientId">发送者的客户端id</param> /// <param name="receiveClientId">接收者的客户端id</param> /// <param name="message">消息</param> /// <param name="receipt">是否回执</param> public static void SendMessage(long senderClientId, IEnumerable<long> receiveClientId, object message, bool receipt = false) => Instance.SendMessage(senderClientId, receiveClientId, message, receipt); /// <summary> /// 获取所在线客户端id /// </summary> /// <returns></returns> public static IEnumerable<long> GetClientListByOnline() => Instance.GetClientListByOnline(); /// <summary> /// 判断客户端是否在线 /// </summary> /// <param name="clientId"></param> /// <returns></returns> public static bool HasOnline(long clientId) => Instance.HasOnline(clientId); /// <summary> /// 判断客户端是否在线(多个) /// </summary> /// <param name="clientIds"></param> /// <returns></returns> public static bool[] HasOnline(IEnumerable<long> clientIds) => Instance.HasOnline(clientIds); /// <summary> /// 强制下线 /// </summary> /// <param name="clientId"></param> public static void ForceOffline(long clientId) => Instance.ForceOffline(clientId); /// <summary> /// 事件订阅 /// </summary> /// <param name="online">上线</param> /// <param name="offline">下线</param> public static void EventBus( Action<(long clientId, string clientMetaData)> online, Action<(long clientId, string clientMetaData)> offline) => Instance.EventBus(online, offline); #region 群聊频道,每次上线都必须重新加入 /// <summary> /// 加入群聊频道,每次上线都必须重新加入 /// </summary> /// <param name="clientId">客户端id</param> /// <param name="chans">群聊频道名</param> public static void JoinChan(long clientId, params string[] chans) => Instance.JoinChan(clientId, chans); /// <summary> /// 离开群聊频道 /// </summary> /// <param name="clientId">客户端id</param> /// <param name="chans">群聊频道名</param> public static void LeaveChan(long clientId, params string[] chans) => Instance.LeaveChan(clientId, chans); /// <summary> /// 离开群聊频道 /// </summary> /// <param name="chan">群聊频道名</param> /// <param name="clientIds">客户端id</param> public static void LeaveChan(string chan, params long[] clientIds) => Instance.LeaveChan(chan, clientIds); /// <summary> /// 获取群聊频道所有客户端id(测试) /// </summary> /// <param name="chan">群聊频道名</param> /// <returns></returns> public static long[] GetChanClientList(string chan) => Instance.GetChanClientList(chan); /// <summary> /// 清理群聊频道的离线客户端(测试) /// </summary> /// <param name="chan">群聊频道名</param> public static void ClearChanClient(string chan) => Instance.ClearChanClient(chan); /// <summary> /// 获取所有群聊频道和在线人数 /// </summary> /// <returns>频道名和在线人数</returns> public static IEnumerable<(string chan, long online)> GetChanList() => Instance.GetChanList(); /// <summary> /// 获取用户参与的所有群聊频道 /// </summary> /// <param name="clientId">客户端id</param> /// <returns></returns> public static string[] GetChanListByClientId(long clientId) => Instance.GetChanListByClientId(clientId); /// <summary> /// 获取群聊频道的在线人数 /// </summary> /// <param name="chan">群聊频道名</param> /// <returns>在线人数</returns> public static long GetChanOnline(string chan) => Instance.GetChanOnline(chan); /// <summary> /// 发送群聊消息,所有在线的用户将收到消息 /// </summary> /// <param name="senderClientId">发送者的客户端id</param> /// <param name="chan">群聊频道名</param> /// <param name="message">消息</param> public static void SendChanMessage(long senderClientId, string chan, object message) => Instance.SendChanMessage(senderClientId, chan, message); /// <summary> /// 发送广播消息 /// </summary> /// <param name="message">消息</param> public static void SendBroadcastMessage(object message) => Instance.SendBroadcastMessage(message); #endregion }
2881099/FreeIM
1,432
FreeIM/ImClientOptions.cs
using FreeRedis; using Newtonsoft.Json; using System; using System.Collections.Generic; /// <summary> /// im 核心类实现的配置所需 /// </summary> public class ImClientOptions { /// <summary> /// 用于存储数据和发送消息 /// </summary> public RedisClient Redis { get; set; } /// <summary> /// 负载的服务端 /// </summary> public string[] Servers { get; set; } /// <summary> /// websocket请求的路径,默认值:/ws /// </summary> public string PathMatch { get; set; } = "/ws"; /// <summary> /// Json 序列化设置 /// </summary> public JsonSerializerSettings JsonSerializerSettings { get;set;} } public class ImSendEventArgs : EventArgs { /// <summary> /// 发送者的客户端id /// </summary> public long SenderClientId { get; } /// <summary> /// 接收者的客户端id /// </summary> public List<long> ReceiveClientId { get; } = new List<long>(); public string Chan { get; internal set; } /// <summary> /// imServer 服务器节点 /// </summary> public string Server { get; } /// <summary> /// 消息 /// </summary> public object Message { get; } /// <summary> /// 是否回执 /// </summary> public bool Receipt { get; } internal ImSendEventArgs(string server, long senderClientId, object message, bool receipt = false) { this.Server = server; this.SenderClientId = senderClientId; this.Message = message; this.Receipt = receipt; } }
27182812/ChatGLM-LLaMA-chinese-insturct
5,405
src/transformers/models/retribert/configuration_retribert.py
# coding=utf-8 # Copyright 2019-present, the HuggingFace Inc. team, The Google AI Language Team and Facebook, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ RetriBERT model configuration""" from ...configuration_utils import PretrainedConfig from ...utils import logging logger = logging.get_logger(__name__) # TODO: upload to AWS RETRIBERT_PRETRAINED_CONFIG_ARCHIVE_MAP = { "yjernite/retribert-base-uncased": ( "https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/config.json" ), } class RetriBertConfig(PretrainedConfig): r""" This is the configuration class to store the configuration of a [`RetriBertModel`]. It is used to instantiate a RetriBertModel 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 RetriBERT [yjernite/retribert-base-uncased](https://huggingface.co/yjernite/retribert-base-uncased) 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 30522): Vocabulary size of the RetriBERT model. Defines the number of different tokens that can be represented by the `inputs_ids` passed when calling [`RetriBertModel`] hidden_size (`int`, *optional*, defaults to 768): Dimensionality of the encoder layers and the pooler layer. num_hidden_layers (`int`, *optional*, defaults to 12): Number of hidden layers in the Transformer encoder. num_attention_heads (`int`, *optional*, defaults to 12): Number of attention heads for each attention layer in the Transformer encoder. intermediate_size (`int`, *optional*, defaults to 3072): Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder. hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`): The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`, `"relu"`, `"silu"` and `"gelu_new"` are supported. hidden_dropout_prob (`float`, *optional*, defaults to 0.1): The dropout probability for all fully connected layers in the embeddings, encoder, and pooler. attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1): The dropout ratio for the attention probabilities. max_position_embeddings (`int`, *optional*, defaults to 512): The maximum sequence length that this model might ever be used with. Typically set this to something large just in case (e.g., 512 or 1024 or 2048). type_vocab_size (`int`, *optional*, defaults to 2): The vocabulary size of the *token_type_ids* passed into [`BertModel`]. initializer_range (`float`, *optional*, defaults to 0.02): The standard deviation of the truncated_normal_initializer for initializing all weight matrices. layer_norm_eps (`float`, *optional*, defaults to 1e-12): The epsilon used by the layer normalization layers. share_encoders (`bool`, *optional*, defaults to `True`): Whether or not to use the same Bert-type encoder for the queries and document projection_dim (`int`, *optional*, defaults to 128): Final dimension of the query and document representation after projection """ model_type = "retribert" def __init__( self, vocab_size=30522, hidden_size=768, num_hidden_layers=8, num_attention_heads=12, intermediate_size=3072, hidden_act="gelu", hidden_dropout_prob=0.1, attention_probs_dropout_prob=0.1, max_position_embeddings=512, type_vocab_size=2, initializer_range=0.02, layer_norm_eps=1e-12, share_encoders=True, projection_dim=128, pad_token_id=0, **kwargs, ): super().__init__(pad_token_id=pad_token_id, **kwargs) self.vocab_size = vocab_size self.hidden_size = hidden_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.hidden_act = hidden_act self.intermediate_size = intermediate_size self.hidden_dropout_prob = hidden_dropout_prob self.attention_probs_dropout_prob = attention_probs_dropout_prob self.max_position_embeddings = max_position_embeddings self.type_vocab_size = type_vocab_size self.initializer_range = initializer_range self.layer_norm_eps = layer_norm_eps self.share_encoders = share_encoders self.projection_dim = projection_dim
2881099/dotnetGen_mysql
19,830
Server/CodeBuild(Lib).cs
using System; using System.Collections.Generic; using MySql.Data.MySqlClient; using System.Text; using System.Text.RegularExpressions; using Model; namespace Server { internal partial class CodeBuild { protected static MySqlDbType GetDBType(string strType, bool is_unsigned) { switch (strType.ToLower()) { case "bit": return MySqlDbType.Bit; case "tinyint": return is_unsigned ? MySqlDbType.UByte : MySqlDbType.Byte; case "smallint": return is_unsigned ? MySqlDbType.UInt16 : MySqlDbType.Int16; case "mediumint": return is_unsigned ? MySqlDbType.UInt24 : MySqlDbType.Int24; case "int": return is_unsigned ? MySqlDbType.UInt32 : MySqlDbType.Int32; case "bigint": return is_unsigned ? MySqlDbType.UInt64 : MySqlDbType.Int64; case "real": case "double": return MySqlDbType.Double; case "float": return MySqlDbType.Float; case "numeric": case "decimal": return MySqlDbType.Decimal; case "year": return MySqlDbType.Year; case "time": return MySqlDbType.Time; case "date": return MySqlDbType.Date; case "timestamp": return MySqlDbType.Timestamp; case "datetime": return MySqlDbType.Datetime; case "tinyblob": return MySqlDbType.TinyBlob; case "blob": return MySqlDbType.Blob; case "mediumblob": return MySqlDbType.MediumBlob; case "longblob": return MySqlDbType.LongBlob; case "binary": return MySqlDbType.Binary; case "varbinary": return MySqlDbType.VarBinary; case "tinytext": return MySqlDbType.TinyText; case "text": return MySqlDbType.Text; case "mediumtext": return MySqlDbType.MediumText; case "longtext": return MySqlDbType.LongText; case "char": return MySqlDbType.String; case "varchar": return MySqlDbType.VarChar; case "set": return MySqlDbType.Set; case "enum": return MySqlDbType.Enum; case "point": return MySqlDbType.Geometry; case "linestring": return MySqlDbType.Geometry; case "polygon": return MySqlDbType.Geometry; case "geometry": return MySqlDbType.Geometry; case "multipoint": return MySqlDbType.Geometry; case "multilinestring": return MySqlDbType.Geometry; case "multipolygon": return MySqlDbType.Geometry; case "geometrycollection": return MySqlDbType.Geometry; default: return MySqlDbType.String; } } protected static string GetDbToCsConvert(MySqlDbType type) { switch (type) { case MySqlDbType.Bit: return "(bool?)"; case MySqlDbType.Byte: return "(byte?)"; case MySqlDbType.Int16: return "(short?)"; case MySqlDbType.Int24: case MySqlDbType.Int32: return "(int?)"; case MySqlDbType.Int64: return "(long?)"; case MySqlDbType.UByte: return "(byte?)"; case MySqlDbType.UInt16: return "(ushort?)"; case MySqlDbType.UInt24: case MySqlDbType.UInt32: return "(uint?)"; case MySqlDbType.UInt64: return "(ulong?)"; case MySqlDbType.Double: return "(double?)"; case MySqlDbType.Float: return "(float?)"; case MySqlDbType.Decimal: return "(decimal?)"; case MySqlDbType.Year: return "(int?)"; case MySqlDbType.Time: return "(TimeSpan?)"; case MySqlDbType.Date: case MySqlDbType.Timestamp: case MySqlDbType.Datetime: return "(DateTime?)"; case MySqlDbType.TinyBlob: case MySqlDbType.Blob: case MySqlDbType.MediumBlob: case MySqlDbType.LongBlob: case MySqlDbType.Binary: case MySqlDbType.VarBinary: return "(byte[])"; case MySqlDbType.TinyText: case MySqlDbType.Text: case MySqlDbType.MediumText: case MySqlDbType.LongText: case MySqlDbType.String: case MySqlDbType.VarString: case MySqlDbType.VarChar: return ""; case MySqlDbType.Set: case MySqlDbType.Enum: return "(long?)"; case MySqlDbType.Geometry: return "(MygisGeometry)"; default: return ""; } } protected static string GetCSTypeValue(MySqlDbType type) { switch (type) { case MySqlDbType.Bit: case MySqlDbType.Byte: case MySqlDbType.Int16: case MySqlDbType.Int24: case MySqlDbType.Int32: case MySqlDbType.Int64: case MySqlDbType.UByte: case MySqlDbType.UInt16: case MySqlDbType.UInt24: case MySqlDbType.UInt32: case MySqlDbType.UInt64: case MySqlDbType.Double: case MySqlDbType.Float: case MySqlDbType.Decimal: case MySqlDbType.Year: case MySqlDbType.Time: case MySqlDbType.Date: case MySqlDbType.Timestamp: case MySqlDbType.Datetime: return "{0}.Value"; case MySqlDbType.TinyBlob: case MySqlDbType.Blob: case MySqlDbType.MediumBlob: case MySqlDbType.LongBlob: case MySqlDbType.Binary: case MySqlDbType.VarBinary: return "Convert.ToBase64String({0})"; case MySqlDbType.TinyText: case MySqlDbType.Text: case MySqlDbType.MediumText: case MySqlDbType.LongText: case MySqlDbType.String: case MySqlDbType.VarString: case MySqlDbType.VarChar: return "{0}"; case MySqlDbType.Set: case MySqlDbType.Enum: return "{0}"; case MySqlDbType.Geometry: return "{0}"; default: return ""; } } protected static string GetCSType(MySqlDbType type, string enumType, string sqlType) { switch (type) { case MySqlDbType.Bit: return "bool?"; case MySqlDbType.Byte: return "byte?"; case MySqlDbType.Int16: return "short?"; case MySqlDbType.Int24: case MySqlDbType.Int32: return "int?"; case MySqlDbType.Int64: return "long?"; case MySqlDbType.UByte: return "byte?"; case MySqlDbType.UInt16: return "ushort?"; case MySqlDbType.UInt24: case MySqlDbType.UInt32: return "uint?"; case MySqlDbType.UInt64: return "ulong?"; case MySqlDbType.Double: return "double?"; case MySqlDbType.Float: return "float?"; case MySqlDbType.Decimal: return "decimal?"; case MySqlDbType.Year: return "int?"; case MySqlDbType.Time: return "TimeSpan?"; case MySqlDbType.Date: case MySqlDbType.Timestamp: case MySqlDbType.Datetime: return "DateTime?"; case MySqlDbType.TinyBlob: case MySqlDbType.Blob: case MySqlDbType.MediumBlob: case MySqlDbType.LongBlob: case MySqlDbType.Binary: case MySqlDbType.VarBinary: return "byte[]"; case MySqlDbType.TinyText: case MySqlDbType.Text: case MySqlDbType.MediumText: case MySqlDbType.LongText: case MySqlDbType.String: case MySqlDbType.VarString: case MySqlDbType.VarChar: return "string"; case MySqlDbType.Set: return enumType + "?"; case MySqlDbType.Enum: return enumType + "?"; case MySqlDbType.Geometry: return GetCSTypeGeometry(sqlType); default: return "object"; } } protected static string GetCSTypeGeometry(string sqlType) { switch (sqlType) { case "point": return "MygisPoint"; case "linestring": return "MygisLineString"; case "polygon": return "MygisPolygon"; case "multipoint": return "MygisMultiPoint"; case "multilinestring": return "MygisMultiLineString"; case "multipolygon": return "MygisMultiPolygon"; } return "object"; } protected static string GetDataReaderMethod(MySqlDbType type) { switch (type) { case MySqlDbType.Bit: return "GetBoolean"; case MySqlDbType.Byte: return "GetByte"; case MySqlDbType.Int16: return "GetInt16"; case MySqlDbType.Int24: case MySqlDbType.Int32: return "GetInt32"; case MySqlDbType.Int64: return "GetInt64"; case MySqlDbType.UByte: return "GetByte"; case MySqlDbType.UInt16: return "GetInt16"; case MySqlDbType.UInt24: case MySqlDbType.UInt32: return "GetInt32"; case MySqlDbType.UInt64: return "GetInt64"; case MySqlDbType.Double: return "GetDouble"; case MySqlDbType.Float: return "GetFloat"; case MySqlDbType.Decimal: return "GetDecimal"; case MySqlDbType.Year: return "GetInt32"; case MySqlDbType.Time: return "GetValue"; case MySqlDbType.Date: case MySqlDbType.Timestamp: case MySqlDbType.Datetime: return "GetDateTime"; case MySqlDbType.TinyBlob: case MySqlDbType.Blob: case MySqlDbType.MediumBlob: case MySqlDbType.LongBlob: case MySqlDbType.Binary: case MySqlDbType.VarBinary: return "GetBytes"; case MySqlDbType.TinyText: case MySqlDbType.Text: case MySqlDbType.MediumText: case MySqlDbType.LongText: case MySqlDbType.String: case MySqlDbType.VarString: case MySqlDbType.VarChar: return "GetString"; case MySqlDbType.Set: case MySqlDbType.Enum: return "GetString"; case MySqlDbType.Geometry: return "GetString"; default: return "GetValue"; } } protected static string GetToStringFieldConcat(ColumnInfo columnInfo, string csType) { switch (columnInfo.Type) { case MySqlDbType.Bit: return string.Format("{0} == null ? \"null\" : ({0} == true ? \"true\" : \"false\")", CodeBuild.UFString(columnInfo.Name)); case MySqlDbType.Byte: case MySqlDbType.Int16: case MySqlDbType.Int24: case MySqlDbType.Int32: case MySqlDbType.Int64: case MySqlDbType.UByte: case MySqlDbType.UInt16: case MySqlDbType.UInt24: case MySqlDbType.UInt32: case MySqlDbType.UInt64: case MySqlDbType.Double: case MySqlDbType.Float: case MySqlDbType.Decimal: case MySqlDbType.Year: return string.Format("{0} == null ? \"null\" : {0}.ToString()", CodeBuild.UFString(columnInfo.Name)); case MySqlDbType.Time: return string.Format("{0} == null ? \"null\" : {0}.Value.TotalSeconds.ToString()", CodeBuild.UFString(columnInfo.Name)); case MySqlDbType.Date: case MySqlDbType.Timestamp: case MySqlDbType.Datetime: return string.Format("{0} == null ? \"null\" : {0}.Value.Subtract(new DateTime(1970, 1, 1)).TotalMilliseconds.ToString()", CodeBuild.UFString(columnInfo.Name)); case MySqlDbType.TinyBlob: case MySqlDbType.Blob: case MySqlDbType.MediumBlob: case MySqlDbType.LongBlob: case MySqlDbType.Binary: case MySqlDbType.VarBinary: return string.Format("{0} == null ? \"null\" : Convert.ToBase64String({0})", CodeBuild.UFString(columnInfo.Name)); case MySqlDbType.TinyText: case MySqlDbType.Text: case MySqlDbType.MediumText: case MySqlDbType.LongText: case MySqlDbType.String: case MySqlDbType.VarString: case MySqlDbType.VarChar: return string.Format("{0} == null ? \"null\" : string.Format(\"'{{0}}'\", {0}.Replace(\"\\\\\", \"\\\\\\\\\").Replace(\"\\r\\n\", \"\\\\r\\\\n\").Replace(\"'\", \"\\\\'\"))", CodeBuild.UFString(columnInfo.Name)); case MySqlDbType.Set: return string.Format("{0} == null ? \"null\" : string.Format(\"[ '{{0}}' ]\", string.Join(\"', '\", {0}.ToInt64().ToSet<{1}>().Select<{1}, string>(a => a.ToDescriptionOrString().Replace(\"\\\\\", \"\\\\\\\\\").Replace(\"\\r\\n\", \"\\\\r\\\\n\").Replace(\"'\", \"\\\\'\"))))", CodeBuild.UFString(columnInfo.Name), csType); case MySqlDbType.Enum: return string.Format("{0} == null ? \"null\" : string.Format(\"'{{0}}'\", {0}.ToDescriptionOrString().Replace(\"\\\\\", \"\\\\\\\\\").Replace(\"\\r\\n\", \"\\\\r\\\\n\").Replace(\"'\", \"\\\\'\"))", CodeBuild.UFString(columnInfo.Name)); case MySqlDbType.Geometry: string csTypeGeom = GetCSTypeGeometry(columnInfo.SqlType); string asText = csTypeGeom == "object" ? ".ToString()" : ".AsText()"; return string.Format("{0} == null ? \"null\" : string.Format(\"'{{0}}'\", {0}" + asText + ".Replace(\"\\\\\", \"\\\\\\\\\").Replace(\"\\r\\n\", \"\\\\r\\\\n\").Replace(\"'\", \"\\\\'\"))", CodeBuild.UFString(columnInfo.Name)); default: return string.Format("{0} == null ? \"null\" : {0}.ToString()", CodeBuild.UFString(columnInfo.Name)); } } protected static string GetToStringStringify(ColumnInfo columnInfo) { switch (columnInfo.Type) { case MySqlDbType.Bit: return "_" + CodeBuild.UFString(columnInfo.Name) + " == null ? \"null\" : (_" + CodeBuild.UFString(columnInfo.Name) + " == true ? \"1\" : \"0\")"; case MySqlDbType.Byte: case MySqlDbType.Int16: case MySqlDbType.Int24: case MySqlDbType.Int32: case MySqlDbType.Int64: case MySqlDbType.UByte: case MySqlDbType.UInt16: case MySqlDbType.UInt24: case MySqlDbType.UInt32: case MySqlDbType.UInt64: case MySqlDbType.Double: case MySqlDbType.Float: case MySqlDbType.Decimal: case MySqlDbType.Year: return "_" + CodeBuild.UFString(columnInfo.Name) + " == null ? \"null\" : _" + CodeBuild.UFString(columnInfo.Name) + ".ToString()"; case MySqlDbType.Time: return "_" + CodeBuild.UFString(columnInfo.Name) + " == null ? \"null\" : _" + CodeBuild.UFString(columnInfo.Name) + ".Value.TotalSeconds.ToString()"; case MySqlDbType.Date: case MySqlDbType.Timestamp: case MySqlDbType.Datetime: return "_" + CodeBuild.UFString(columnInfo.Name) + " == null ? \"null\" : _" + CodeBuild.UFString(columnInfo.Name) + ".Value.Ticks.ToString()"; case MySqlDbType.TinyBlob: case MySqlDbType.Blob: case MySqlDbType.MediumBlob: case MySqlDbType.LongBlob: case MySqlDbType.Binary: case MySqlDbType.VarBinary: return "_" + CodeBuild.UFString(columnInfo.Name) + " == null ? \"null\" : Convert.ToBase64String(_" + CodeBuild.UFString(columnInfo.Name) + ")"; case MySqlDbType.TinyText: case MySqlDbType.Text: case MySqlDbType.MediumText: case MySqlDbType.LongText: case MySqlDbType.String: case MySqlDbType.VarString: case MySqlDbType.VarChar: return "_" + CodeBuild.UFString(columnInfo.Name) + " == null ? \"null\" : _" + CodeBuild.UFString(columnInfo.Name) + ".Replace(\"|\", StringifySplit)"; case MySqlDbType.Set: case MySqlDbType.Enum: return "_" + CodeBuild.UFString(columnInfo.Name) + " == null ? \"null\" : _" + CodeBuild.UFString(columnInfo.Name) + ".ToInt64().ToString()"; case MySqlDbType.Geometry: string csTypeGeom = GetCSTypeGeometry(columnInfo.SqlType); string asText = csTypeGeom == "object" ? ".ToString()" : ".AsText()"; return "_" + CodeBuild.UFString(columnInfo.Name) + " == null ? \"null\" : _" + CodeBuild.UFString(columnInfo.Name) + asText + ".Replace(\"|\", StringifySplit)"; default: return "_" + CodeBuild.UFString(columnInfo.Name) + " == null ? \"null\" : _" + CodeBuild.UFString(columnInfo.Name) + ".ToString().Replace(\"|\", StringifySplit)"; } } protected static string GetStringifyParse(MySqlDbType type, string sqlType) { switch (type) { case MySqlDbType.Bit: return "{0} == \"1\""; case MySqlDbType.Byte: return "byte.Parse({0})"; case MySqlDbType.Int16: return "short.Parse({0})"; case MySqlDbType.Int24: case MySqlDbType.Int32: return "int.Parse({0})"; case MySqlDbType.Int64: return "long.Parse({0})"; case MySqlDbType.UByte: return "byte.Parse({0})"; case MySqlDbType.UInt16: return "ushort.Parse({0})"; case MySqlDbType.UInt24: case MySqlDbType.UInt32: return "uint.Parse({0})"; case MySqlDbType.UInt64: return "ulong.Parse({0})"; case MySqlDbType.Double: return "double.Parse({0})"; case MySqlDbType.Float: return "float.Parse({0})"; case MySqlDbType.Decimal: return "decimal.Parse({0})"; case MySqlDbType.Year: return "int.Parse({0})"; case MySqlDbType.Time: return "TimeSpan.FromSeconds(double.Parse({0}))"; case MySqlDbType.Date: case MySqlDbType.Timestamp: case MySqlDbType.Datetime: return "new DateTime(long.Parse({0}))"; case MySqlDbType.TinyBlob: case MySqlDbType.Blob: case MySqlDbType.MediumBlob: case MySqlDbType.LongBlob: case MySqlDbType.Binary: case MySqlDbType.VarBinary: return "Convert.FromBase64String({0})"; case MySqlDbType.TinyText: case MySqlDbType.Text: case MySqlDbType.MediumText: case MySqlDbType.LongText: case MySqlDbType.String: case MySqlDbType.VarString: case MySqlDbType.VarChar: case MySqlDbType.Set: return "{0}.Replace(StringifySplit, \"|\")"; case MySqlDbType.Enum: return "{0}.Replace(StringifySplit, \"|\")"; case MySqlDbType.Geometry: string csTypeGeom = GetCSTypeGeometry(sqlType); return "MygisGeometry.Parse({0}.Replace(StringifySplit, \"|\"))" + (csTypeGeom != "object" ? (" as " + csTypeGeom) : ""); default: return "{0}"; } } protected static string UFString(string text) { text = Regex.Replace(text, @"[^\w]", "_"); if (text.Length <= 1) return text.ToUpper(); else return text.Substring(0, 1).ToUpper() + text.Substring(1, text.Length - 1); } protected static string LFString(string text) { if (text.Length <= 1) return text.ToLower(); else return text.Substring(0, 1).ToLower() + text.Substring(1, text.Length - 1); } protected static string GetCSName(string name) { name = Regex.Replace(name.TrimStart('@'), @"[^\w]", "_"); return char.IsLetter(name, 0) ? name : string.Concat("_", name); } protected static string AppendParameter(ColumnInfo columnInfo, string value, string place) { if (columnInfo == null) return ""; string csTypeGeom = GetCSTypeGeometry(columnInfo.SqlType); string asText = csTypeGeom == "object" ? ".ToString()" : ".AsText()"; string returnValue = place + string.Format("GetParameter(\"{0}{1}\", MySqlDbType.{2}, {3}, {4}), \r\n", columnInfo.Name.StartsWith("?") ? null : "?", columnInfo.Name, columnInfo.Type.ToString().Replace("Datetime", "DateTime").Replace("Geometry", "Text"), columnInfo.Type == MySqlDbType.Geometry ? "-1" : columnInfo.Length.ToString(), //columnInfo.Type == MySqlDbType.Image ? string.Format("{0} == null ? 0 : {0}.Length", value + Lib.UFString(columnInfo.Name)) : columnInfo.Length.ToString(), value + CodeBuild.UFString(columnInfo.Name) + (columnInfo.Type == MySqlDbType.Enum || columnInfo.Type == MySqlDbType.Set ? "?.ToInt64()" : ( columnInfo.Type == MySqlDbType.Geometry ? asText : ""))); return returnValue; } protected static string AppendParameters(List<ColumnInfo> columnInfos, string value, string place) { string returnValue = ""; foreach (ColumnInfo columnInfo in columnInfos) { returnValue += AppendParameter(columnInfo, value, place); } return returnValue == "" ? "" : returnValue.Substring(0, returnValue.Length - 4); } protected static string AppendParameters(List<ColumnInfo> columnInfos, string place) { return AppendParameters(columnInfos, "", place); } protected static string AppendParameters(TableInfo table, string place) { return AppendParameters(table.Columns, "item.", place); } protected static string AppendParameters(ColumnInfo columnInfo, string value, string place) { string returnValue = AppendParameter(columnInfo, value, place); return returnValue == "" ? "" : returnValue.Substring(0, returnValue.Length - 4); } protected static string AppendAddslashes(ColumnInfo columnInfo, string value, string place) { if (columnInfo == null) return ""; string returnValue = place + value + CodeBuild.UFString(columnInfo.Name) + ", "; return returnValue; } protected static string AppendAddslashes(List<ColumnInfo> columnInfos, string value, string place) { string returnValue = ""; foreach (ColumnInfo columnInfo in columnInfos) { returnValue += AppendAddslashes(columnInfo, value, place); } return returnValue == "" ? "" : returnValue.Substring(0, returnValue.Length - 2); } protected static string AppendAddslashes(List<ColumnInfo> columnInfos, string place) { return AppendAddslashes(columnInfos, "", place); } protected static string AppendAddslashes(TableInfo table, string place) { return AppendAddslashes(table.Columns, "item.", place); } protected static string AppendAddslashes(ColumnInfo columnInfo, string place) { string returnValue = AppendParameter(columnInfo, "", place); return returnValue == "" ? "" : returnValue.Substring(0, returnValue.Length - 2); } } }
2881099/dotnetGen_mysql
3,910
Server/Protocol.cs
using System; using System.Collections.Generic; using System.Text; using Model; namespace Server { public class Protocol : IDisposable { internal ServerSocket _socket; private Dictionary<int, CodeBuild> _builds; private object _builds_lock = new object(); private Protocol(int port) { _builds = new Dictionary<int, CodeBuild>(); _socket = new ServerSocket(port); _socket.Closed += this.OnClosed; _socket.Accepted += this.OnAccepted; _socket.Error += this.OnError; _socket.Receive += this.OnReceive; _socket.Start(); } protected virtual void OnClosed(object sender, ServerSocketClosedEventArgs e) { _builds.Remove(e.AcceptSocketId); } protected virtual void OnReceive(object sender, ServerSocketReceiveEventArgs e) { switch (e.Messager.Action) { case "GetDatabases": ClientInfo ci = e.Messager.Arg as ClientInfo; if (ci == null) { e.AcceptSocket.AccessDenied(); } else { CodeBuild build = new CodeBuild(ci, e.AcceptSocket); lock (_builds_lock) { _builds.Remove(e.AcceptSocket.Id); _builds.Add(e.AcceptSocket.Id, build); } List<DatabaseInfo> dbs = build.GetDatabases(); SocketMessager messager = new SocketMessager(e.Messager.Action, dbs); messager.Id = e.Messager.Id; e.AcceptSocket.Write(messager); } break; case "GetTablesByDatabase": string database = string.Concat(e.Messager.Arg); if (string.IsNullOrEmpty(database)) { e.AcceptSocket.AccessDenied(); } else { CodeBuild build = null; if (!_builds.TryGetValue(e.AcceptSocket.Id, out build)) { e.AcceptSocket.AccessDenied(); } else { List<TableInfo> tables = build.GetTablesByDatabase(database); SocketMessager messager = new SocketMessager(e.Messager.Action, tables); messager.Id = e.Messager.Id; e.AcceptSocket.Write(messager); } } break; case "Build": object[] parms = e.Messager.Arg as object[]; if (parms.Length < 4) { e.AcceptSocket.AccessDenied(); } else { string solutionName = string.Concat(parms[0]); bool isSolution, isMakeAdmin, isDownloadRes; string op10 = string.Concat(parms[2]); if (string.IsNullOrEmpty(solutionName) || !bool.TryParse(string.Concat(parms[1]), out isSolution) || string.IsNullOrEmpty(op10)) { e.AcceptSocket.AccessDenied(); } else { isMakeAdmin = false; isDownloadRes = false; if (parms.Length >= 4) bool.TryParse(string.Concat(parms[3]), out isMakeAdmin); if (parms.Length >= 5) bool.TryParse(string.Concat(parms[4]), out isDownloadRes); CodeBuild build = null; if (!_builds.TryGetValue(e.AcceptSocket.Id, out build)) { e.AcceptSocket.AccessDenied(); } else { List<bool> outputs = new List<bool>(); char[] cs = op10.ToCharArray(); foreach (char c in cs) { outputs.Add(c == '1'); } build.SetOutput(outputs.ToArray()); object parm = null; try { parm = build.Build(solutionName, isSolution, isMakeAdmin, isDownloadRes); } catch (Exception ex) { parm = ex; } SocketMessager messager = new SocketMessager(e.Messager.Action, parm); messager.Id = e.Messager.Id; e.AcceptSocket.Write(messager); } } } break; default: e.AcceptSocket.AccessDenied(); break; } } protected virtual void OnAccepted(object sender, ServerSocketAcceptedEventArgs e) { } protected virtual void OnError(object sender, ServerSocketErrorEventArgs e) { Logger.remotor.Debug("Errors: " + e.Errors, e.Exception); } public static Protocol Create(int port) { return new Protocol(port); } #region IDisposable Ա public void Dispose() { if (_socket != null) { _socket.Dispose(); } } #endregion } }