private BinaryTerm(RiakFluentSearch search, string field, Op op, Term left) : base(search, field) { _op = op; _left = left; left.Owner = this; }
static void Main() { Op.sanity_check(); { Op op = new Op(100); Op opNew = op++; if (op.i != 101) throw new Exception("operator++ postfix failed (op)"); if (opNew.i != 100) throw new Exception("operator++ postfix failed (opNew)"); } { Op op = new Op(100); Op opNew = op--; if (op.i != 99) throw new Exception("operator-- postfix failed (op)"); if (opNew.i != 100) throw new Exception("operator-- postfix failed (opNew)"); } { Op op = new Op(100); Op opNew = ++op; if (op.i != 101) throw new Exception("operator++ prefix failed (op)"); if (opNew.i != 101) throw new Exception("operator++ prefix failed (opNew)"); } { Op op = new Op(100); Op opNew = --op; if (op.i != 99) throw new Exception("operator-- prefix failed (op)"); if (opNew.i != 99) throw new Exception("operator-- prefix failed (opNew)"); } // overloaded operator class Op k = new OpDerived(3); int check_k = k.IntCast(); Assert(check_k == 6); }
/// <summary> /// 创建查询条件片段。 /// </summary> /// <param name="propertyName">属性名</param> /// <param name="op">查询操作</param> /// <returns>2元组:结果一、查询条件片段;结果二、查询参数</returns> protected override Tuple<string, string> CreateFragment(string propertyName, Op op) { var criteria = string.Empty; var parameterName = string.Empty; switch (op) { case Op.Eq: case Op.Gt: case Op.Ge: case Op.Lt: case Op.Le: parameterName = propertyName + (this._parameterIndex++); criteria = string.Format(CriteriaFormat, propertyName, Operations[(int)op], parameterName); break; case Op.Like: parameterName = propertyName + (this._parameterIndex++); criteria = $"\"{propertyName}\" LIKE '%'||:{parameterName}||'%'"; break; case Op.IsNull: criteria = $"\"{propertyName}\" IS NULL"; break; case Op.IsNotNull: criteria = $"\"{propertyName}\" IS NOT NULL"; break; } return new Tuple<string, string>(criteria, parameterName); }
/// <summary> /// 构造方法。 /// </summary> /// <param name="column">属性</param> /// <param name="op">操作</param> /// <param name="value">值</param> internal Condition(string column, Op op, object value) { this.Op = op; this.Value = value; this.JoinType = "AND"; this.PropertyName = column; }
public NotationValue(string notation, int index, int end) { value = 1; op = Op.Add; type = NotationType.Value; switch (notation[index]) { case '+': { index++; break; } case '-': { op = Op.Sub; index++; break; } case '*': { op = Op.Mul; index++; break; } case '/': { op = Op.Div; index++; break; } case '^': { op = Op.Mod; index++; break; } } if (index <= end && char.IsDigit(notation[index])) { int i = index + 1; while (i <= end && char.IsDigit(notation[i])) i++; value = int.Parse(notation.Substring(index, i - index)); index = i; } if (index <= end && char.IsLetter(notation[index])) { Enum.TryParse<NotationType>(notation.Substring(index, end - index + 1), out type); } }
public Person(string name, int age, string dogName) { Name = name; Age = age; Pet = new Dog(dogName); action += (val) => val * val; }
public object Operator(Op op, params object[] args) { if (binaryOps.ContainsKey(op)) return binaryOps[op]((bool)args[0], (bool)args[1]); if (op == Op.Not) return !(bool)args[0]; throw new NotImplementedException(); }
public ActionCopyMoveRename(Op operation, FileInfo from, FileInfo to, ProcessedEpisode ep) { this.PercentDone = 0; this.Episode = ep; this.Operation = operation; this.From = from; this.To = to; }
/// <summary> /// Two CostantBaseOps are equivalent if they are of the same /// derived type and have the same type and value. /// </summary> /// <param name="other">the other Op</param> /// <returns>true, if these are equivalent (not a strict equality test)</returns> internal override bool IsEquivalent(Op other) { var otherConstant = other as ConstantBaseOp; return otherConstant != null && OpType == other.OpType && otherConstant.Type.EdmEquals(Type) && ((otherConstant.Value == null && Value == null) || otherConstant.Value.Equals(Value)); }
internal void Emit(Op op, Label label) { if (!label.IsEmpty()) { fixups.Add(ops.Count); Emit(op, label.GetIndex()); } else Emit(op, 0); }
private bool ignore; // ignore case private void Compile (string pattern) { if (pattern == null || pattern.IndexOfAny (InvalidChars) >= 0) throw new ArgumentException ("Invalid search pattern."); if (pattern == "*") { // common case ops = new Op (OpCode.True); return; } ops = null; int ptr = 0; Op last_op = null; while (ptr < pattern.Length) { Op op; switch (pattern [ptr]) { case '?': op = new Op (OpCode.AnyChar); ++ ptr; break; case '*': op = new Op (OpCode.AnyString); ++ ptr; break; default: op = new Op (OpCode.ExactString); int end = pattern.IndexOfAny (WildcardChars, ptr); if (end < 0) end = pattern.Length; op.Argument = pattern.Substring (ptr, end - ptr); if (ignore) op.Argument = op.Argument.ToLowerInvariant (); ptr = end; break; } if (last_op == null) ops = op; else last_op.Next = op; last_op = op; } if (last_op == null) ops = new Op (OpCode.End); else last_op.Next = new Op (OpCode.End); }
static Operator() { Op[] opArray = new Op[9]; opArray[3] = Op.EQ; opArray[4] = Op.NE; opArray[5] = Op.GT; opArray[6] = Op.GE; opArray[7] = Op.LT; opArray[8] = Op.LE; invertOp = opArray; }
/// <summary> /// </summary> public Expression(string attrbuteName, Op op, string attrbuteValue) { if (op == Op.Exists || op == Op.NotExists) throw new ArgumentException("op"); if (String.IsNullOrEmpty(attrbuteName)) throw new ArgumentException("attrbuteName"); _op = op; _attributeName = attrbuteName; _attributeValue = attrbuteValue; }
public Binary(Op op, string symbol = "") { _op = op; Left = new Lambda(); Right = new Lambda(); if (symbol == "") { StringBuilder sb = new StringBuilder(); sb.Append('[').Append(_opCount.ToString()).Append(']'); _symbol = sb.ToString(); _opCount++; } else { _symbol = symbol; } }
private static bool IsTypeTransitive(Op op) { switch (op) { case Op.Add: case Op.Subtract: case Op.Multiply: case Op.Remainder: case Op.Divide: case Op.AndAnd: case Op.OrOr: case Op.And: case Op.Or: case Op.ExclusiveOr: case Op.LeftShift: case Op.RightShift: return true; } return false; }
private void AddArg(Op op, ICollection<Node> argList) { if (TokType == TokenType.Identifer) { if (_reg16.ContainsKey(Keyword)) { argList.Add(_reg16[Keyword]); NextToken(); } else if (_reg8.ContainsKey(Keyword)) { argList.Add(_reg8[Keyword]); NextToken(); } else if (_specReg.ContainsKey(Keyword)) { argList.Add(_specReg[Keyword]); NextToken(); } else if (argList.Count == 0) { if (op == Op.Jr && _jrCond.ContainsKey(Keyword)) { argList.Add(_jrCond[Keyword]); NextToken(); } else if ((op == Op.Jp || op == Op.Ret || op == Op.Call) && _cond.ContainsKey(Keyword)) { argList.Add(_cond[Keyword]); NextToken(); } else argList.Add(Expression()); } else argList.Add(Expression()); } else argList.Add(Expression()); }
public static int GetArity(Op op) { switch (op) { case Op.Not: case Op.Negate: case Op.OnesComplement: case Op.Int32: case Op.UInt32: case Op.Int64: case Op.UInt64: case Op.BigInteger: case Op.Double: case Op.Complex: case Op.Rational: case Op.Random: return 1; case Op.New: case Op.NullCoalescing: return 0; default: return 2; } }
public static byte[] SegInt(BigInteger body) => Seg(Op.BigInt2Bytes(body));
/// <summary> /// Main program entry point /// </summary> static void Main(string[] args) { Op op = Op.None; bool cache = false; int period = 60 * 1000; DnsServiceRecord record = null; ProxySocketAddress address = null; // Parse command line try { for (int i = 0; i < args.Length; i++) { switch (args[i]) { case "-a": case "--all": if (op != Op.None) { throw new ArgumentException("Operations are mutual exclusive"); } op = Op.All; break; case "-s": case "--services": i++; if (op != Op.None) { throw new ArgumentException("Operations are mutual exclusive"); } op = Op.Browse; if (i < args.Length) { record = DnsServiceRecord.Parse(args[i]); } break; case "-t": case "--timeout": i++; if (i >= args.Length || !int.TryParse(args[i], out period)) { throw new ArgumentException($"Bad -t arg"); } break; case "-r": case "--resolve": i++; if (op != Op.None) { throw new ArgumentException("Operations are mutual exclusive"); } op = Op.Resolve; if (i < args.Length) { address = ProxySocketAddress.Parse(args[i]); } break; case "-d": case "--dir": i++; if (op != Op.None) { throw new ArgumentException("Operations are mutual exclusive"); } op = Op.Dir; if (i < args.Length) { address = ProxySocketAddress.Parse(args[i]); } break; case "--fs": if (op != Op.None) { throw new ArgumentException("Operations are mutual exclusive"); } op = Op.Fs; break; case "--use-cache": cache = true; break; case "-R": case "--relay": Socket.Provider = Provider.RelayProvider.CreateAsync().Result; break; case "-?": case "-h": case "--help": throw new ArgumentException("Help"); default: throw new ArgumentException($"Unknown {args[i]}"); } } } catch (Exception e) { Console.WriteLine(e.Message); Console.WriteLine( @" Browser - Proxy .net browser sample. usage: Browser [options] operation [args] Options: -t --timeout Timeout in ms to use for each browse request. --use-cache Return data from cache only (meaning depends on operation). --relay -R Use relay provider instead of default provider. --help -? -h Prints out this help. Operations (Mutually exclusive): -s --services Without further argument browses all domains. Otherwise browses for service types or service names in a domain. If service name is provided, resolves to host:port and txt. -a --all Browse all services in all domains on all proxies and resolve each one. (default!) -r --resolve Resolve host to address (getaddrbyhost) or address to host (gethostbyaddr) on all proxies. -d --dir Browse a folder on any proxy. --fs Browse entire file system on all proxies recursively. " ); return; } if (op == Op.Browse) { if (record != null) { if (string.IsNullOrEmpty(record.Name)) { var entries = BrowseServicesAsync( record.Type, record.Domain, period, cache).Result; } else { var entries = ResolveServiceAsync( record, period, cache).Result; } } else { var entries = BrowseDomainsAsync(period).Result; Console.WriteLine($"{entries.Count} entries found!!!"); } } else if (op == Op.Resolve) { var entries = ResolveAddressAsync(address, period, cache).Result; } else if (op == Op.Dir) { var files = BrowseFilesAsync(null, address?.Host, period, cache).Result; Console.WriteLine($"{files.Count} files/folders found!!!"); } else if (op == Op.Fs) { BrowseFilesRecursiveAsync(null, null, period, cache).Wait(); } else if (op == Op.All || op == Op.None) { Console.WriteLine("Browse and resolve all services"); var entries = ResolveServiceNamesAsync(period).Result; Console.WriteLine($"{entries.Count} entries resolved!!!"); } Console.WriteLine("Press a key to exit..."); Console.ReadKey(); }
public Exp e; //$TODO: rename to Expression. public UnaryExp(Op op, Exp exp, string filename, int start, int end) : base(filename, start, end) { this.op = op; this.e = exp; }
/// <summary> /// Gets or creates the cache. /// </summary> private ICache <TK, TV> GetOrCreateCache <TK, TV>(CacheConfiguration configuration, NearCacheConfiguration nearConfiguration, Op op) { IgniteArgumentCheck.NotNull(configuration, "configuration"); IgniteArgumentCheck.NotNull(configuration.Name, "CacheConfiguration.Name"); configuration.Validate(Logger); var cacheTarget = DoOutOpObject((int)op, s => { var w = BinaryUtils.Marshaller.StartMarshal(s); configuration.Write(w, ClientSocket.CurrentProtocolVersion); if (nearConfiguration != null) { w.WriteBoolean(true); nearConfiguration.Write(w); } else { w.WriteBoolean(false); } }); return(GetCache <TK, TV>(cacheTarget)); }
internal Exp(Param p) { this.param = p; this.op = Op.Param; }
public Exp(double value) { this.value = value; this.op = Op.Const; }
Exp(Op op, Exp a, Exp b) { this.a = a; this.b = b; this.op = op; }
public override string ToString() { return($"{Left.Name}{Op.String()}={Expression}"); }
public static void Initialize() { // Create and initialize a new workspace folder relative to the project root workspace = new Workspace(); workspace.KeepFiles = KeepFileType.Results; workspace.Init("workspace"); // Uncomment the following line to clear the workspace before each run // workspace.Clear(); // Extract JSON data from a zip file, if not already done if (!File.Exists("seattle-pet-licenses.json") || !File.Exists("washington-zip-codes.json")) { ZipFile.ExtractToDirectory("data.zip", "."); } // Import the main license table if (!workspace.TableExists("PetLicenses")) { List <PetLicense> collection = JsonConvert.DeserializeObject <List <PetLicense> >(File.ReadAllText("seattle-pet-licenses.json")); ObjectConnector <PetLicense> connector = new ObjectConnector <PetLicense>(workspace, collection); connector.GetData("PetLicenses"); workspace.Save(); } // Import the secondary location table if (!workspace.TableExists("Locations")) { List <Location> collection = JsonConvert.DeserializeObject <List <Location> >(File.ReadAllText("washington-zip-codes.json")); ObjectConnector <Location> connector = new ObjectConnector <Location>(workspace, collection); connector.GetData("Locations"); workspace.Save(); } // Retrieve the main table for use in constructing queries dynamic licenses = workspace.table("PetLicenses"); // Number of licenses, by species if (!workspace.QueryExists("BySpecies")) { dynamic query = workspace.query("BySpecies", new { licenses.Species, Count = Op.Count(licenses.Species) }); query.Query.Execute(); } // Number of licenses, by calendar year if (!workspace.QueryExists("ByYear")) { // Create a query with all base table columns and add a Year field, extracted from the DateTime value dynamic parent = workspace.query(new { _base = "*", Year = Op.DtPart(licenses.IssueDate, DateTimeParts.Year) }); // Derive another query from the unnamed query above and perform the aggregation dynamic query = workspace.query("ByYear", new { _range = parent.Year.Gte(2015), parent.Year, Count = Op.Count(parent.Year) }); query.Query.Execute(); } // Most popular dog names (sort criteria and row limits are applied later) if (!workspace.QueryExists("DogNames")) { // Use the _range attribute to limit the results to dogs only dynamic query = workspace.query("DogNames", new { _range = licenses.Species.Eq("Dog"), Species = licenses.Species, DogName = licenses.AnimalName, Count = Op.Count(licenses.AnimalName) }); query.Query.Execute(); } // List names for all species except dogs and cats if (!workspace.QueryExists("OtherAnimals")) { // Create a query with specified base table columns and use the _filter attribute to limit the results // (_filter is used instead of _range because the latter does not support the Ne operator) dynamic parent = workspace.query(new { _filter = licenses.Species.Ne("Dog").And().Ne("Cat"), licenses.LicenseNumber, licenses.Species, licenses.AnimalName }); // Derive another query from the unnamed query above and use First as the aggregation operator // (otherwise the query will not yield any results) dynamic query = workspace.query("OtherAnimals", new { parent.LicenseNumber, parent.Species, AnimalName = Op.First(parent.AnimalName) }); query.Query.Execute(); } // Retrieve the secondary table for use in a join query dynamic locations = workspace.table("Locations"); // Number of licenses in King County, by city if (!workspace.QueryExists("KingCounty")) { // Create a join from the main table (licenses) to the secondary table (locations) // * The addition expression to the left of the vertical bar denotes which secondary fields to include // * The equality expression to the right of the vertical bar specifies the join condition // * The assignment statement specifies a property of the anonymous type (its name is not significant) dynamic join = workspace.join(licenses, new { locale = locations.County + locations.City | licenses.ZipCode == locations.Zip }); // Derive another query from the join query above, specifying both a _range and an aggregation dynamic query = workspace.query("KingCounty", new { _range = join.County.Eq("King"), join.County, join.City, Count = Op.Count(join.LicenseNumber) }); query.Query.Execute(); } }
/// <summary> /// This helper tests various scenarios related to the <see cref="PosColdStakingRule"/>. The parameters determine the test cases. /// </summary> /// <param name="isColdCoinStake">Tests the scenario where a hotPubKey was used to spend a cold stake transaction input.</param> /// <param name="inputScriptPubKeysDiffer">Tests the scenario where some of the input scriptPubKeys differ.</param> /// <param name="outputScriptPubKeysDiffer">Tests the scenario where some of the output scriptPubKeys differ.</param> /// <param name="badSecondOutput">Tests the scenario where the second output is not an OP_RETURN followed by some data.</param> /// <param name="inputsExceedOutputs">Tests the scenario where the input amount exceeds the output amount.</param> /// <param name="inputsWithoutOutputs">Tests the scenario where the some inputs have no incoming outputs.</param> /// <param name="expectedError">The error expected by running this test. Set to <c>null</c> if no error is expected.</param> private async Task PosColdStakingRuleTestHelperAsync(bool isColdCoinStake, bool inputScriptPubKeysDiffer, bool outputScriptPubKeysDiffer, bool badSecondOutput, bool inputsExceedOutputs, bool inputsWithoutOutputs, ConsensusError expectedError) { Block block = this.ruleContext.ValidationContext.BlockToValidate; // Create two scripts that are different. var scriptPubKey1 = new Script(OpcodeType.OP_1); var scriptPubKey2 = new Script(OpcodeType.OP_2); // Add dummy first transaction. Transaction transaction = this.network.CreateTransaction(); transaction.Outputs.Add(new TxOut(Money.Zero, (IDestination)null)); block.Transactions.Add(transaction); // Create a previous transaction with scriptPubKey outputs. Transaction prevTransaction = this.network.CreateTransaction(); prevTransaction.Outputs.Add(new TxOut(15, scriptPubKey1)); prevTransaction.Outputs.Add(new TxOut(25, inputScriptPubKeysDiffer ? scriptPubKey2 : scriptPubKey1)); // Record the spendable outputs. var posRuleContext = this.ruleContext as PosRuleContext; posRuleContext.UnspentOutputSet.Update(this.network, prevTransaction, 0); // Create cold coin stake transaction. Transaction coinstakeTransaction = this.network.CreateTransaction(); coinstakeTransaction.Inputs.Add(new TxIn() { PrevOut = new OutPoint(prevTransaction, 0), ScriptSig = new Script() }); coinstakeTransaction.Inputs.Add(new TxIn() { PrevOut = new OutPoint(prevTransaction, inputsWithoutOutputs ? 2 : 1), ScriptSig = new Script() }); coinstakeTransaction.Outputs.Add(new TxOut(Money.Zero, (IDestination)null)); coinstakeTransaction.Outputs.Add(new TxOut(Money.Zero, badSecondOutput ? new Script() : new Script(OpcodeType.OP_RETURN, Op.GetPushOp(new Key().PubKey.Compress().ToBytes())))); coinstakeTransaction.Outputs.Add(new TxOut(inputsExceedOutputs ? 10 : 15, scriptPubKey1)); coinstakeTransaction.Outputs.Add(new TxOut(25, outputScriptPubKeysDiffer ? scriptPubKey2 : scriptPubKey1)); // Set this flag which is expected to be set by the preceding PosCoinview rule if this were run in an integrated scenario. (coinstakeTransaction as PosTransaction).IsColdCoinStake = isColdCoinStake; block.Transactions.Add(coinstakeTransaction); // Finalize the block and add it to the chain. block.Header.HashPrevBlock = this.ChainIndexer.Tip.HashBlock; block.Header.Time = (uint)1483747200; block.UpdateMerkleRoot(); Assert.True(BlockStake.IsProofOfStake(block)); this.ChainIndexer.SetTip(block.Header); // Execute the rule and check the outcome against what is expected. var rule = this.CreateRule <PosColdStakingRule>(); // Initialize the rule context. posRuleContext.ValidationContext.ChainedHeaderToValidate = this.ChainIndexer.Tip; posRuleContext.CoinStakePrevOutputs = coinstakeTransaction.Inputs.ToDictionary(txin => txin, txin => posRuleContext.UnspentOutputSet.GetOutputFor(txin)); posRuleContext.TotalCoinStakeValueIn = posRuleContext.CoinStakePrevOutputs.Sum(a => a.Value?.Value ?? 0); // If an error is expeected then capture the error and compare it against the expected error. if (expectedError != null) { ConsensusErrorException exception = Assert.Throws <ConsensusErrorException>(() => rule.RunAsync(this.ruleContext).GetAwaiter().GetResult()); Assert.Equal(expectedError, exception.ConsensusError); return; } // No error is expected. Attempt to run the rule normally. await rule.RunAsync(this.ruleContext); }
public static byte[] JoinSegs2Table(params byte[][] segs) => Op.JoinByteArray(segs);
public async Task InitializeAsync() { this.blockinfo = new List <Blockinfo>(); List <long> lst = blockinfoarr.Cast <long>().ToList(); for (int i = 0; i < lst.Count; i += 2) { this.blockinfo.Add(new Blockinfo { extranonce = (int)lst[i], nonce = (uint)lst[i + 1] }); } // Note that by default, these tests run with size accounting enabled. this.network = KnownNetworks.RegTest; byte[] hex = Encoders.Hex.DecodeData("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f"); this.scriptPubKey = new Script(new[] { Op.GetPushOp(hex), OpcodeType.OP_CHECKSIG }); this.entry = new TestMemPoolEntryHelper(); this.chain = new ConcurrentChain(this.network); this.network.Consensus.Options = new ConsensusOptions(); IDateTimeProvider dateTimeProvider = DateTimeProvider.Default; var inMemoryCoinView = new InMemoryCoinView(this.chain.Tip.HashBlock); this.cachedCoinView = new CachedCoinView(inMemoryCoinView, dateTimeProvider, new LoggerFactory(), new NodeStats(dateTimeProvider)); var loggerFactory = new ExtendedLoggerFactory(); loggerFactory.AddConsoleWithFilters(); var nodeSettings = new NodeSettings(args: new string[] { "-checkpoints" }); var consensusSettings = new ConsensusSettings(nodeSettings); var networkPeerFactory = new NetworkPeerFactory(this.network, dateTimeProvider, loggerFactory, new PayloadProvider().DiscoverPayloads(), new SelfEndpointTracker(loggerFactory), new Mock <IInitialBlockDownloadState>().Object, new ConnectionManagerSettings()); var peerAddressManager = new PeerAddressManager(DateTimeProvider.Default, nodeSettings.DataFolder, loggerFactory, new SelfEndpointTracker(loggerFactory)); var peerDiscovery = new PeerDiscovery(new AsyncLoopFactory(loggerFactory), loggerFactory, this.network, networkPeerFactory, new NodeLifetime(), nodeSettings, peerAddressManager); var connectionSettings = new ConnectionManagerSettings(nodeSettings); var selfEndpointTracker = new SelfEndpointTracker(loggerFactory); var connectionManager = new ConnectionManager(dateTimeProvider, loggerFactory, this.network, networkPeerFactory, nodeSettings, new NodeLifetime(), new NetworkPeerConnectionParameters(), peerAddressManager, new IPeerConnector[] { }, peerDiscovery, selfEndpointTracker, connectionSettings, new VersionProvider(), new Mock <INodeStats>().Object); var peerBanning = new PeerBanning(connectionManager, loggerFactory, dateTimeProvider, peerAddressManager); var deployments = new NodeDeployments(this.network, this.chain); var genesis = this.network.GetGenesis(); var chainState = new ChainState() { BlockStoreTip = new ChainedHeader(genesis.Header, genesis.GetHash(), 0) }; this.ConsensusRules = new PowConsensusRuleEngine(this.network, loggerFactory, dateTimeProvider, this.chain, deployments, consensusSettings, new Checkpoints(), this.cachedCoinView, chainState, new InvalidBlockHashStore(dateTimeProvider), new NodeStats(dateTimeProvider)).Register(); this.consensus = ConsensusManagerHelper.CreateConsensusManager(this.network, chainState: chainState, inMemoryCoinView: inMemoryCoinView, chain: this.chain); await this.consensus.InitializeAsync(chainState.BlockStoreTip); this.entry.Fee(11); this.entry.Height(11); var dateTimeProviderSet = new DateTimeProviderSet { time = dateTimeProvider.GetTime(), timeutc = dateTimeProvider.GetUtcNow() }; this.DateTimeProvider = dateTimeProviderSet; this.mempool = new TxMempool(dateTimeProvider, new BlockPolicyEstimator(new MempoolSettings(nodeSettings), loggerFactory, nodeSettings), loggerFactory, nodeSettings); this.mempoolLock = new MempoolSchedulerLock(); // We can't make transactions until we have inputs // Therefore, load 100 blocks :) this.baseheight = 0; var blocks = new List <Block>(); this.txFirst = new List <Transaction>(); this.nonce = 0; for (int i = 0; i < this.blockinfo.Count; ++i) { Block block = this.network.CreateBlock(); block.Header.HashPrevBlock = this.consensus.Tip.HashBlock; block.Header.Version = 1; block.Header.Time = Utils.DateTimeToUnixTime(this.chain.Tip.GetMedianTimePast()) + 1; Transaction txCoinbase = this.network.CreateTransaction(); txCoinbase.Version = 1; txCoinbase.AddInput(new TxIn(new Script(new[] { Op.GetPushOp(this.blockinfo[i].extranonce), Op.GetPushOp(this.chain.Height) }))); // Ignore the (optional) segwit commitment added by CreateNewBlock (as the hardcoded nonces don't account for this) txCoinbase.AddOutput(new TxOut(Money.Zero, new Script())); block.AddTransaction(txCoinbase); if (this.txFirst.Count == 0) { this.baseheight = this.chain.Height; } if (this.txFirst.Count < 4) { this.txFirst.Add(block.Transactions[0]); } block.Header.Bits = block.Header.GetWorkRequired(this.network, this.chain.Tip); block.UpdateMerkleRoot(); while (!block.CheckProofOfWork()) { block.Header.Nonce = ++this.nonce; } // Serialization sets the BlockSize property. block = Block.Load(block.ToBytes(), this.network); var res = await this.consensus.BlockMinedAsync(block); if (res == null) { throw new InvalidOperationException(); } blocks.Add(block); } // Just to make sure we can still make simple blocks this.newBlock = AssemblerForTest(this).Build(this.chain.Tip, this.scriptPubKey); Assert.NotNull(this.newBlock); }
private static byte[] GetQuiz(BigInteger quizID) { byte[] qdata = NuIO.GetStorageWithKeyPath("quiz", Op.BigInt2String(quizID)); return(NuTP.RespDataSucWithBody(qdata)); }
internal string OpToString(Op op) { switch (op) { default: throw new NotSupportedException(string.Format("Unknown op {0}.", op)); case Op.Ge: return(" >= "); case Op.Le: return(" <= "); case Op.Lt: return(" < "); case Op.Gt: return(" > "); case Op.Eq: return("="); case Op.Ne: return(" != "); case Op.In: return("in"); case Op.NotIn: return("not in"); case Op.Is: return("is"); case Op.IsNot: return("is not"); case Op.Xor: return("^"); case Op.LogOr: return("or"); case Op.LogAnd: return("and"); case Op.Shl: return(" << "); case Op.Shr: return(" >> "); case Op.Add: return(" + "); case Op.Sub: return(" - "); case Op.Mul: return(" * "); case Op.Div: return(" /"); case Op.IDiv: return(" // "); case Op.Mod: return("%"); case Op.Complement: return("~"); case Op.AugAdd: return(" += "); case Op.AugSub: return(" -= "); case Op.AugMul: return(" *= "); case Op.AugDiv: return(" /= "); case Op.AugMod: return(" %= "); case Op.AugAnd: return(" &= "); case Op.AugOr: return(" |= "); case Op.AugXor: return(" ^= "); case Op.AugShl: return(" <<= "); case Op.AugShr: return(" >>= "); case Op.AugExp: return(" **= "); case Op.AugIDiv: return(" //= "); case Op.BitAnd: return("&"); case Op.BitOr: return("|"); case Op.Not: return("not "); case Op.Exp: return(" ** "); case Op.Assign: return("="); } }
public static Tensor <Type> Create(Dim[] shape, Scalar <int> index, Tensor <Type> content = null) { content = content ?? Op.Ones <Type>(shape.DropLeft(1)); return(new OneHot <Type>(shape, index, content)); }
/// <summary> /// Create a canonical representation for the multiplication of two scalars. /// </summary> /// <remarks> /// 0 * y => 0 /// 1 * y => y /// -1 * y => -y /// a * ( b * yy) => (a * b) * yy /// a * ( - y) => (- a ) * y /// x * b => b * x /// a * ( b / yy) => (a * b) / yy /// x.Item[z] * y.Item[z] => (x * y).Item[z] /// </remarks> public static Scalar <Type> Create(Scalar <Type> x, Scalar <Type> y) { if (x == y) { return(Op.Square(x)); } var consx = x as Const; if (consx != null) { // 0 * y => 0 if (consx.IsZero) { return(consx); } // 1 * y => y if (consx.IsOne) { return(y); } // a * (b * yy) => (a * b) * yy var yMul = y as Mul <Type>; if (yMul != null && yMul.x is Const) { return((x * yMul.x) * yMul.y); } // a * (b / yy) => (a * b) / yy; var yDiv2 = y as Div <Type>; if (yDiv2 != null && yDiv2.x is Const) { return((x * yDiv2.x) / yDiv2.y); // important for softmax gradient optimization } // -1 * y => -y if (consx.IsMinusOne) { return(-y); } // a * ( - y) => (- a ) * y var yNeg = y as Neg <Type>; if (yNeg != null) { return(Create(-x, yNeg.x)); } } if (y is Const consy) { if (consx != null) { return(Numeric.Mul(consx.Value, consy.Value)); } // x * b => b * x else { return(Create(y, x)); } } // a * ( b / yy) => (a * b) / yy if (y is Div <Type> yDiv && !(y is Div <int>)) { return((x * yDiv.x) / yDiv.y); } if (x is Div <Type> xdiv) { // (a / y) * y => a if (xdiv.y == y) { return(xdiv.x); // important for softmax gradient optimization } var ymul = y as Mul <Type>; if (ymul != null) { // (xdiv.x / xdiv.y) * (ymul.x * ymul.y) => (xdiv.x * ymul.x * ymul.y) / xdiv.y if (ymul.y == xdiv.y) { return(xdiv.x * ymul.x); // important for sigmoid gradient optimization } if (ymul.x == xdiv.y) { return(xdiv.x * ymul.y); } return((xdiv.x * ymul.x * ymul.y) / xdiv.y); } return((xdiv.x * y) / xdiv.y); } // (-x) * y => -(x * y) if (x is Neg <Type> xneg) { return(Neg <Type> .Create(xneg.x *y)); } // x.Item[z] * y.Item[z] => (x * y).Item[z] // important for softmax gradient optimization if (x is Item <Type> xitem) { var yitem = y as Item <Type>; if (yitem != null && xitem.Indexes.SequenceEqual(yitem.Indexes)) { return((xitem.x * yitem.x).Item[xitem.Indexes]); } } // (a / b) * (b * c) => (a * c) if (x is Div <Type> xDiv) { var yMul = y as Mul <Type>; if (yMul != null && xDiv.y == yMul.x) { return(xDiv.x * yMul.y); } } return(new Mul <Type>(x, y)); }
public static string GetOperatorString(DSASM.Operator optr) { return(Op.GetOpSymbol(optr)); }
public override string ToString() { return(Op.String()); }
/// <summary> /// 条件比较 /// </summary> private static bool GetTFilterOk(string where, int quoteIndex, string sign, Op op, MDataColumn mdc, out TFilter tFilter) { bool result = false; tFilter = null; int index = where.ToLower().IndexOf(sign, 0, quoteIndex > 0 ? quoteIndex : where.Length); if (index > 0) { string columnAName = where.Substring(0, index).Trim(); int columnAIndex = mdc.GetIndex(columnAName); string valueB = where.Substring(index + sign.Length).Trim(' ', '\'').Replace("''", "'"); if (op == Op.In || op == Op.NotIn) { valueB = ',' + valueB.TrimStart('(', ')').Replace("'", "") + ",";//去除单引号。 } int columnBIndex = -1; if (quoteIndex == 0 && mdc.Contains(valueB)) //判断右侧的是否列名。 { columnBIndex = mdc.GetIndex(valueB); } tFilter = new TFilter(Ao.None, columnAName, columnAIndex, op, valueB, columnBIndex); if (columnBIndex == -1 && !string.IsNullOrEmpty(Convert.ToString(valueB)))//右侧是值类型,转换值的类型。 { if (columnAIndex > -1 && DataType.GetGroup(mdc[columnAIndex].SqlType) == 3)//bool型 { switch (Convert.ToString(tFilter._valueB).ToLower()) { case "true": case "1": case "on": tFilter._valueB = true; break; case "false": case "0": case "": tFilter._valueB = false; break; default: tFilter._valueB = null; break; } } else { try { tFilter._valueB = StaticTool.ChangeType(tFilter._valueB, columnAIndex > -1 ? typeof(string) : mdc[columnAIndex].ValueType); } catch { } } } result = true; } return result; }
public static byte[] SegBool(bool body) => Seg(Op.Bool2Bytes(body));
public Filter(string propertyName, object value, Op operation = Op.Equals) { PropertyName = propertyName; Value = value; Operation = operation; }
public static byte[] SegString(string body) => Seg(Op.String2Bytes(body));
private STATE this[Op op] { get { return m_state[(int)op]; } set { m_state[(int)op] = value; } }
private Node VisitPropertyOp(Op op, Node n, PropertyRef propertyRef, bool throwIfMissing) { PlanCompiler.Assert( op.OpType == OpType.Property || op.OpType == OpType.RelProperty, "Unexpected optype: " + op.OpType); var inputType = n.Child0.Op.Type; var outputType = op.Type; // First visit all my children VisitChildren(n); Node newNode = null; var inputTypeInfo = m_typeInfo.GetTypeInfo(inputType); if (TypeUtils.IsStructuredType(outputType)) { var outputTypeInfo = m_typeInfo.GetTypeInfo(outputType); var fieldTypes = new List<md.EdmProperty>(); var fieldValues = new List<Node>(); var expectedProperties = m_nodePropertyMap[n]; foreach (var npr in outputTypeInfo.PropertyRefList) { // Is this a property that's desired by my consumers? if (expectedProperties.Contains(npr)) { var newPropRef = npr.CreateNestedPropertyRef(propertyRef); md.EdmProperty newNestedProp; if (inputTypeInfo.TryGetNewProperty(newPropRef, throwIfMissing, out newNestedProp)) { var outputNestedProp = outputTypeInfo.GetNewProperty(npr); var field = BuildAccessor(n.Child0, newNestedProp); if (null != field) { fieldTypes.Add(outputNestedProp); fieldValues.Add(field); } } } } Op newRecordOp = m_command.CreateNewRecordOp(outputTypeInfo.FlattenedTypeUsage, fieldTypes); newNode = m_command.CreateNode(newRecordOp, fieldValues); } else { var newProp = inputTypeInfo.GetNewProperty(propertyRef); // Build an accessor over the new property newNode = BuildAccessorWithNulls(n.Child0, newProp); } return newNode; }
// <summary> // ApplyOp/JoinOp common processing // </summary> // <remarks> // If one of the inputs to any JoinOp/ApplyOp is a NestOp, then the NestOp // can be pulled above the join/apply if every input to the join/apply has // a key(s). The keys of the NestOp are augmented with the keys of the // other join inputs: // JoinOp/ApplyOp(NestOp(X, ...), Y) => NestOp(JoinOp/ApplyOp(X, Y), ...) // In addition, if the NestOp is on a 'nullable' side of a join (i.e. right side of // LeftOuterJoin/OuterApply or either side of FullOuterJoin), the driving node // of that NestOp (X) is capped with a project with a null sentinel and // the dependant collection nodes (the rest of the NestOp children) // are filtered based on that sentinel: // LOJ/OA/FOJ (X, NestOp(Y, Z1, Z2, ..ZN)) => NestOp( LOJ/OA/FOJ (X, PROJECT (Y, v = 1)), FILTER(Z1, v!=null), FILTER(Z2, v!=null), ... FILTER(ZN, v!=null)) // FOJ (NestOp(Y, Z1, Z2, ..ZN), X) => NestOp( LOJ/OA/FOJ (PROJECT (Y, v = 1), X), FILTER(Z1, v!=null), FILTER(Z2, v!=null), ... FILTER(ZN, v!=null)) // Also, FILTER(Zi, v != null) may be transformed to push the filter below any NestOps. // The definitions for collection vars corresponding to the filtered collection nodes (in m_definingNodeMap) // are also updated to filter based on the sentinel. // Requires: Every input to the join/apply must have a key. // </remarks> private Node ApplyOpJoinOp(Op op, Node n) { // First, visit my children VisitChildren(n); // Now determine if any of the input nodes are a nestOp. var countOfNestInputs = 0; foreach (var chi in n.Children) { var nestOp = chi.Op as NestBaseOp; if (null != nestOp) { countOfNestInputs++; if (OpType.SingleStreamNest == chi.Op.OpType) { // There should not be a SingleStreamNest in the tree, because we made a decision // that in essence means the only way to get a SingleStreamNest is to have a // PhysicalProject over something with an underlying NestOp. Having // // Project(Collect(PhysicalProject(...))) // // isn’t good enough, because that will get converted to a MultiStreamNest, with // the SingleStreamNest as the input to the MultiStreamNest. throw new InvalidOperationException( Strings.ADP_InternalProviderError((int)EntityUtil.InternalErrorCode.JoinOverSingleStreamNest)); } } } // If none of the inputs are a nest, then we don't really need to do anything. if (0 == countOfNestInputs) { return n; } // We can only pull the nest over a Join/Apply if it has keys, so // we can order things; if it doesn't have keys, we throw a NotSupported // exception. foreach (var chi in n.Children) { if (op.OpType != OpType.MultiStreamNest && chi.Op.IsRelOp) { var keys = Command.PullupKeys(chi); if (null == keys || keys.NoKeys) { throw new NotSupportedException(Strings.ADP_KeysRequiredForJoinOverNest(op.OpType.ToString())); } } } // Alright, we're OK to pull the nestOp over the joinOp/applyOp. // // That means: // // (1) build a new list of children for the nestOp and for the joinOp/applyOp // (2) build the new list of collectionInfos for the new nestOp. var newNestChildren = new List<Node>(); var newJoinApplyChildren = new List<Node>(); var newCollectionInfoList = new List<CollectionInfo>(); foreach (var chi in n.Children) { if (chi.Op.OpType == OpType.MultiStreamNest) { newCollectionInfoList.AddRange(((MultiStreamNestOp)chi.Op).CollectionInfo); // SQLBUDT #615513: If the nest op is on a 'nullable' side of join // (i.e. right side of LeftOuterJoin/OuterApply or either side of FullOuterJoin) // the driving node of that nest operation needs to be capped with a project with // a null sentinel and the dependant collection nodes need to be filtered based on that sentinel. // // LOJ/OA/FOJ (X, MSN(Y, Z1, Z2, ..ZN)) => MSN( LOJ/OA/FOJ (X, PROJECT (Y, v = 1)), FILTER(Z1, v!=null), FILTER(Z2, v!=null), ... FILTER(ZN, v!=null)) // FOJ (MSN(Y, Z1, Z2, ..ZN), X) => MSN( LOJ/OA/FOJ (PROJECT (Y, v = 1), X), FILTER(Z1, v!=null), FILTER(Z2, v!=null), ... FILTER(ZN, v!=null)) // // Note: we transform FILTER(Zi, v != null) to push the filter below any MSNs. if ((op.OpType == OpType.FullOuterJoin) || ((op.OpType == OpType.LeftOuterJoin || op.OpType == OpType.OuterApply) && n.Child1.Op.OpType == OpType.MultiStreamNest)) { Var sentinelVar = null; newJoinApplyChildren.Add(AugmentNodeWithConstant(chi.Child0, () => Command.CreateNullSentinelOp(), out sentinelVar)); // Update the definitions corresponding ot the collection vars to be filtered based on the sentinel. foreach (var collectionInfo in ((MultiStreamNestOp)chi.Op).CollectionInfo) { m_definingNodeMap[collectionInfo.CollectionVar].Child0 = ApplyIsNotNullFilter(m_definingNodeMap[collectionInfo.CollectionVar].Child0, sentinelVar); } for (var i = 1; i < chi.Children.Count; i++) { var newNestChild = ApplyIsNotNullFilter(chi.Children[i], sentinelVar); newNestChildren.Add(newNestChild); } } else { newJoinApplyChildren.Add(chi.Child0); for (var i = 1; i < chi.Children.Count; i++) { newNestChildren.Add(chi.Children[i]); } } } else { newJoinApplyChildren.Add(chi); } } // (3) create the new Join/Apply node using the existing op and the // new list of children from (1). var newJoinApplyNode = Command.CreateNode(op, newJoinApplyChildren); // (4) insert the apply op as the driving node of the nestOp (put it // at the beginning of the new nestOps' children. newNestChildren.Insert(0, newJoinApplyNode); // (5) build an updated list of output vars based upon the new join/apply // node, and ensure all the collection vars from the nestOp(s) are // included. var xni = newJoinApplyNode.GetExtendedNodeInfo(Command); var newOutputVars = Command.CreateVarVec(xni.Definitions); foreach (var ci in newCollectionInfoList) { newOutputVars.Set(ci.CollectionVar); } // (6) create the new nestop NestBaseOp newNestOp = Command.CreateMultiStreamNestOp(new List<SortKey>(), newOutputVars, newCollectionInfoList); var newNode = Command.CreateNode(newNestOp, newNestChildren); return newNode; }
public static byte[] JoinToTable(byte[] table, byte[] seg) => Op.JoinTwoByteArray(table, seg);
static void Edit([Domain("Users")] string user, string file, Op op) { Map<string, Op> userRevisions = revisions[user]; revisions = revisions.Override(user, userRevisions.Add(file, (op == Op.Delete ? Op.Delete : Op.Add))); }
public string GetRowAndColumn(string ApplicationId, int ObjectType, int RoleId) { // IServiceClient client = this.EbConfig.GetServiceStackClient(ViewBag.token, ViewBag.rToken); List <string> _permissionsData = new List <string>(); // FOR NEW MODE if (RoleId > 0) { var fr = this.ServiceClient.Get <GetPermissionsResponse>(new GetPermissionsRequest { id = RoleId, TenantAccountId = ViewBag.cid }); _permissionsData = fr.Permissions; } var resultlist = this.ServiceClient.Get <GetApplicationObjectsResponse>(new GetApplicationObjectsRequest { Id = Convert.ToInt32(ApplicationId), objtype = ObjectType }); ViewBag.dict = resultlist.Data; string html = @"<thead><tr><th>@Header</th></tr></thead><tbody>@tbody</tbody>"; string header = string.Empty; string tbody = string.Empty; if (ObjectType == 16) { foreach (var Op in Enum.GetValues(typeof(EbTableVisualization.Operations))) { header += "<th> @Operation </th>".Replace("@Operation", Op.ToString()); } foreach (var obj in resultlist.Data.Keys) { tbody += "<tr>"; tbody += "<td>{0}</td>".Fmt(resultlist.Data[obj]); foreach (var Op in Enum.GetValues(typeof(EbTableVisualization.Operations))) { var perm = string.Format("{0}_{1}", obj, (int)Op); var checked_string = _permissionsData.Contains(perm) ? "checked" : string.Empty; tbody += "<td><input type = 'checkbox' name ='permissions' value='{0}' class='form-check-input' aria-label='...' {1}></td>".Fmt(perm, checked_string); } tbody += "</tr>"; } } else if (ObjectType == 17) { foreach (var Op in Enum.GetValues(typeof(EbChartVisualization.Operations))) { header += "<th> @Operation </th>".Replace("@Operation", Op.ToString()); } foreach (var obj in resultlist.Data.Keys) { tbody += "<tr>"; tbody += "<td>{0}</td>".Fmt(resultlist.Data[obj]); foreach (var Op in Enum.GetValues(typeof(EbChartVisualization.Operations))) { var perm = string.Format("{0}_{1}", obj, (int)Op); var checked_string = _permissionsData.Contains(perm) ? "checked" : string.Empty; tbody += "<td><input type = 'checkbox' name ='permissions' value='{0}' class='form-check-input' aria-label='...' {1}></td>".Fmt(perm, checked_string); } tbody += "</tr>"; } } else if (ObjectType == 18) { foreach (var Op in Enum.GetValues(typeof(EbBotForm.Operations))) { header += "<th> @Operation </th>".Replace("@Operation", Op.ToString()); } foreach (var obj in resultlist.Data.Keys) { tbody += "<tr>"; tbody += "<td>{0}</td>".Fmt(resultlist.Data[obj]); foreach (var Op in Enum.GetValues(typeof(EbBotForm.Operations))) { var perm = string.Format("{0}_{1}", obj, (int)Op); var checked_string = _permissionsData.Contains(perm) ? "checked" : string.Empty; tbody += "<td><input type = 'checkbox' name ='permissions' value='{0}' class='form-check-input' aria-label='...' {1}></td>".Fmt(perm, checked_string); } tbody += "</tr>"; } } else if (ObjectType == 3) { foreach (var Op in Enum.GetValues(typeof(EbReport.Operations))) { header += "<th> @Operation </th>".Replace("@Operation", Op.ToString()); } foreach (var obj in resultlist.Data.Keys) { tbody += "<tr>"; tbody += "<td>{0}</td>".Fmt(resultlist.Data[obj]); foreach (var Op in Enum.GetValues(typeof(EbReport.Operations))) { var perm = string.Format("{0}_{1}", obj, (int)Op); var checked_string = _permissionsData.Contains(perm) ? "checked" : string.Empty; tbody += "<td><input type = 'checkbox' name ='permissions' value='{0}' class='form-check-input' aria-label='...' {1}></td>".Fmt(perm, checked_string); } tbody += "</tr>"; } } return(html.Replace("@Header", header).Replace("@tbody", tbody)); }
private static bool Compare(SqlDbType sqlType, object valueA, Op op, object valueB) { try { switch (op) { case Op.Big: case Op.BigEqual: switch (DataType.GetGroup(sqlType)) { case 1: //int return(op == Op.Big ? Convert.ToDecimal(valueA) > Convert.ToDecimal(valueB) : Convert.ToDecimal(valueA) >= Convert.ToDecimal(valueB)); case 2: //datetime return(op == Op.Big ? Convert.ToDateTime(valueA) > Convert.ToDateTime(valueB) : Convert.ToDateTime(valueA) >= Convert.ToDateTime(valueB)); default: int value = Convert.ToString(valueA).CompareTo(valueB); return(op == Op.Big ? value == 1 : value > -1); } case Op.Equal: return(string.Compare(Convert.ToString(valueA).TrimEnd(), Convert.ToString(valueB).TrimEnd(), true) == 0); case Op.NotEqual: return(string.Compare(Convert.ToString(valueA).TrimEnd(), Convert.ToString(valueB).TrimEnd(), true) != 0); case Op.Small: case Op.SmallEqual: switch (DataType.GetGroup(sqlType)) { case 1: //int return(op == Op.Small ? Convert.ToDecimal(valueA) < Convert.ToDecimal(valueB) : Convert.ToDecimal(valueA) <= Convert.ToDecimal(valueB)); case 2: //datetime return(op == Op.Small ? Convert.ToDateTime(valueA) < Convert.ToDateTime(valueB) : Convert.ToDateTime(valueA) <= Convert.ToDateTime(valueB)); default: int value = Convert.ToString(valueA).CompareTo(valueB); return(op == Op.Small ? value == -1 : value <= 0); } case Op.Like: case Op.NotLike: bool result = false; string bValue = Convert.ToString(valueB); if (!bValue.StartsWith("%")) { result = Convert.ToString(valueA).StartsWith(bValue.Trim('%'), StringComparison.OrdinalIgnoreCase); } else if (!bValue.EndsWith("%")) //'123 ' like '123%' { result = Convert.ToString(valueA).TrimEnd().EndsWith(bValue.Trim('%'), StringComparison.OrdinalIgnoreCase); } else { result = Convert.ToString(valueA).IndexOf(bValue.Trim('%'), StringComparison.OrdinalIgnoreCase) > -1; } return(op == Op.Like ? result : !result); case Op.In: return(Convert.ToString(valueB).Contains(',' + Convert.ToString(valueA) + ",")); case Op.NotIn: return(!Convert.ToString(valueB).Contains(',' + Convert.ToString(valueA) + ",")); } return(false); } catch { return(false); } }
private static bool Compare(SqlDbType sqlType, object valueA, Op op, object valueB) { try { switch (op) { case Op.Big: case Op.BigEqual: switch (DataType.GetGroup(sqlType)) { case 1://int return op == Op.Big ? ((int)valueA > Convert.ToInt32(valueB)) : ((int)valueA >= Convert.ToInt32(valueB)); case 2://datetime return op == Op.Big ? (DateTime)valueA > Convert.ToDateTime(valueB) : (DateTime)valueA >= Convert.ToDateTime(valueB); default: int value = Convert.ToString(valueA).CompareTo(valueB); return op == Op.Big ? value == 1 : value > -1; } case Op.Equal: return string.Compare(Convert.ToString(valueA), Convert.ToString(valueB), true) == 0; case Op.NotEqual: return string.Compare(Convert.ToString(valueA), Convert.ToString(valueB), true) != 0; case Op.Small: case Op.SmallEqual: switch (DataType.GetGroup(sqlType)) { case 1://int return op == Op.Small ? ((int)valueA < Convert.ToInt32(valueB)) : ((int)valueA <= Convert.ToInt32(valueB)); case 2://datetime return op == Op.Small ? (DateTime)valueA < Convert.ToDateTime(valueB) : (DateTime)valueA <= Convert.ToDateTime(valueB); default: int value = Convert.ToString(valueA).CompareTo(valueB); return op == Op.Small ? value == -1 : value <= 0; } case Op.Like: string bValue = Convert.ToString(valueB); if (!bValue.StartsWith("%")) { return Convert.ToString(valueA).StartsWith(bValue.Trim('%'), StringComparison.OrdinalIgnoreCase); } else if (!bValue.EndsWith("%")) { return Convert.ToString(valueA).EndsWith(bValue.Trim('%'), StringComparison.OrdinalIgnoreCase); } else { return Convert.ToString(valueA).IndexOf(bValue.Trim('%'), StringComparison.OrdinalIgnoreCase) > -1; } case Op.In: return Convert.ToString(valueB).Contains(',' + Convert.ToString(valueA) + ","); case Op.NotIn: return !Convert.ToString(valueB).Contains(',' + Convert.ToString(valueA) + ","); } return false; } catch { return false; } }
public static Transaction AddOpReturn(this Transaction transaction, byte[] opReturnContent) { transaction.AddOutput(new TxOut(Money.Zero, new Script(OpcodeType.OP_RETURN, Op.GetPushOp(opReturnContent)))); return(transaction); }
public TFilter(Ao ao, object valueA, int columnAIndex, Op op, object valueB, int columnBIndex) { _Ao = ao; _valueA = valueA; _columnAIndex = columnAIndex; _Op = op; _valueB = valueB; _columnBIndex = columnBIndex; }
public static Cmd ToCmd(Op op) { return(Cmd.IMM | (Cmd)op); }
/// <summary> /// Creates a new publish-subscribe exception. /// </summary> /// <param name="op">The operation that failed.</param> /// <param name="error">A description of the error.</param> /// <param name="elem">The stanza that caused the error.</param> public PubSubException(Op op, string error, XmlElement elem) : base(error) { Operation = op; Protocol = elem; }
public TrustedBroadcastRequest CreateRedeemTransaction(FeeRate feeRate, Script redeemDestination) { if (feeRate == null) { throw new ArgumentNullException(nameof(feeRate)); } var coin = InternalState.EscrowedCoin; var escrow = EscrowScriptBuilder.ExtractEscrowScriptPubKeyParameters(coin.Redeem); Transaction tx = new Transaction(); tx.LockTime = escrow.LockTime; tx.Inputs.Add(new TxIn(coin.Outpoint)); tx.Inputs[0].Sequence = 0; tx.Outputs.Add(new TxOut(coin.Amount, redeemDestination)); var vSize = tx.GetVirtualSize() + 80; tx.Inputs[0].ScriptSig = EscrowScriptBuilder.GenerateScriptSig(new TransactionSignature[] { null }) + Op.GetPushOp(coin.Redeem.ToBytes()); tx.Outputs[0].Value -= feeRate.GetFee(vSize); var redeemTransaction = new TrustedBroadcastRequest { Key = InternalState.RedeemKey, PreviousScriptPubKey = coin.Redeem.Hash.ScriptPubKey, Transaction = tx }; //Strip redeem script information so we check if TrustedBroadcastRequest can sign correctly redeemTransaction.Transaction = redeemTransaction.ReSign(new Coin(coin.Outpoint, coin.TxOut)); return(redeemTransaction); }
private void FireError(Op op, string message, XmlElement protocol) { Debug.WriteLine(string.Format("Error {0}ing pubsub node: {1}", op, message)); this[op] = STATE.Error; if (OnError != null) OnError(this, new PubSubException(op, message, protocol)); }
public override CType GetEvaluatedCType(EmitContext ec) { return((Op == Unop.Not) ? CBasicType.SignedInt : GetPromotedType(Right, Op.ToString(), ec)); }
// <summary> // Not Supported common processing // For all those cases where we don't intend to support // a nest operation as a child, we have this routine to // do the work. // </summary> private Node NestingNotSupported(Op op, Node n) { // First, visit my children VisitChildren(n); m_varRemapper.RemapNode(n); // Make sure we don't have a child that is a nest op. foreach (var chi in n.Children) { if (IsNestOpNode(chi)) { throw new NotSupportedException(Strings.ADP_NestingNotSupported(op.OpType.ToString(), chi.Op.OpType.ToString())); } } return n; }
public SignaturesRequest CreateSignatureRequest(Script cashoutDestination, FeeRate feeRate) { if (cashoutDestination == null) { throw new ArgumentNullException(nameof(cashoutDestination)); } if (feeRate == null) { throw new ArgumentNullException(nameof(feeRate)); } AssertState(PromiseClientStates.WaitingSignatureRequest); Transaction cashout = new Transaction(); cashout.AddInput(new TxIn(InternalState.EscrowedCoin.Outpoint)); cashout.Inputs[0].ScriptSig = new Script( Op.GetPushOp(TrustedBroadcastRequest.PlaceholderSignature), Op.GetPushOp(TrustedBroadcastRequest.PlaceholderSignature), Op.GetPushOp(InternalState.EscrowedCoin.Redeem.ToBytes()) ); cashout.Inputs[0].Witnessify(); cashout.AddOutput(new TxOut(InternalState.EscrowedCoin.Amount, cashoutDestination)); var virtualSize = cashout.HasWitness ? cashout.GetVirtualSize(_Network.Consensus.Options.WitnessScaleFactor) : cashout.GetSerializedSize(); cashout.Outputs[0].Value -= feeRate.GetFee(virtualSize); List <HashBase> hashes = new List <HashBase>(); for (int i = 0; i < Parameters.RealTransactionCount; i++) { RealHash h = new RealHash(cashout, InternalState.EscrowedCoin); h.FeeVariation = Money.Satoshis(i); hashes.Add(h); } for (int i = 0; i < Parameters.FakeTransactionCount; i++) { FakeHash h = new FakeHash(Parameters); h.Salt = new uint256(RandomUtils.GetBytes(32)); hashes.Add(h); } _Hashes = hashes.ToArray(); NBitcoin.Utils.Shuffle(_Hashes, RandomUtils.GetInt32()); for (int i = 0; i < _Hashes.Length; i++) { _Hashes[i].Index = i; } var fakeIndices = _Hashes.OfType <FakeHash>().Select(h => h.Index).ToArray(); uint256 indexSalt = null; var request = new SignaturesRequest { Hashes = _Hashes.Select(h => h.GetHash(_Network)).ToArray(), FakeIndexesHash = PromiseUtils.HashIndexes(ref indexSalt, fakeIndices), }; InternalState.IndexSalt = indexSalt; InternalState.Cashout = cashout.Clone(_Network.Consensus.ConsensusFactory); InternalState.Status = PromiseClientStates.WaitingCommitments; InternalState.FakeIndexes = fakeIndices; return(request); }
/// <summary> /// Add a simple IL instruction /// </summary> /// <param name="inst">the IL instruction</param> public void Inst(Op inst) { AddToBuffer(new Instr((int)inst)); }
public Operator(Op op, AstNode opnd1, AstNode opnd2) { _opType = op; _opnd1 = opnd1; _opnd2 = opnd2; }
static bool EditEnabled(string user, string file, Op op) { return (CanStep(user) && !revisions[user].ContainsKey(file) && (Repository.FileExists(file, version[user]) ? op != Op.Add : op == Op.Add)); }
public BinExp(Op op, Exp l, Exp r, string filename, int start, int end) : base(filename, start, end) { this.op = op; this.l = l; this.r = r; }