/// <summary> /// Calculation method. /// </summary> /// <param name="chain"> /// Source sequence. /// </param> /// <param name="link"> /// Link of intervals in chain. /// </param> /// <returns> /// Average remoteness dispersion <see cref="double"/> value. /// </returns> public double Calculate(Chain chain, Link link) { List<int> intervals = new List<int>(); for (int i = 0; i < chain.Alphabet.Cardinality; i++) { intervals.AddRange(chain.CongenericChain(i).GetIntervals(link).ToList()); } List<int> uniqueIntervals = intervals.Distinct().ToList(); List<int> intervalsCounts = new List<int>(); for (int i = 0; i < uniqueIntervals.Count; i++) { var currentInterval = uniqueIntervals[i]; intervalsCounts.Add(intervals.Count(interval => interval == currentInterval)); } double result = 0; double gDelta = geometricMean.Calculate(chain, link); int n = (int)intervalsCount.Calculate(chain, link); for (int i = 0; i < uniqueIntervals.Count; i++) { int nk = intervalsCounts[i]; double kDelta = uniqueIntervals[i]; double centeredRemoteness = Math.Log(kDelta, 2) - Math.Log(gDelta, 2); result += nk == 0 ? 0 : centeredRemoteness * centeredRemoteness * nk / n; } return result; }
/// <summary> /// Calculation method. /// </summary> /// <param name="chain"> /// Source sequence. /// </param> /// <param name="link"> /// Link of intervals in chain. /// </param> /// <returns> /// Average remoteness <see cref="double"/> value. /// </returns> public double Calculate(Chain chain, Link link) { double depth = depthCalculator.Calculate(chain, link); int nj = (int)intervalsCount.Calculate(chain, link); return nj == 0 ? 0 : depth / nj; }
public IsLegalResponse(ReasonEnum reason = ReasonEnum.Fine) { this.Reason = reason; this.Killed = new List<Chain>(); this.MergeResultant = new Chain(); this.AbsorbedInMerge = new List<Chain>(); }
public void RunFullBlockTest() { var generator = new FullBlockTestGenerator(Network.Main); ValidationState validation = new ValidationState(Network.Main); validation.CheckMerkleRoot = false; validation.CheckProofOfWork = false; var scan = new ScanState(new PubKeyHashScanner(generator.CoinbaseKey.PubKey.ID), new Chain(), new Account(), 0); scan.CheckDoubleSpend = true; var mainChain = new Chain(Network.Main); var indexed = new IndexedBlockStore(new InMemoryNoSqlRepository(), CreateBlockStore()); indexed.Put(Network.Main.GetGenesis()); foreach(var test in generator.GetBlocksToTest(true, true).list.OfType<BlockAndValidity>()) { indexed.Put(test.block); mainChain.GetOrAdd(test.block.Header); Assert.True(scan.Process(mainChain, indexed) == test.connects); //if(!) //{ // Assert.True(test.throwsException); //} Assert.Equal(test.heightAfterBlock, scan.Chain.Height); Assert.Equal(test.hashChainTipAfterBlock, scan.Chain.Tip.HashBlock); mainChain.SetTip(scan.Chain.Tip); } }
public static void Run() { Chain<int, double> chain = new Chain<int, double>() .Link<int>(x => { // Generate random array of ints int[] nums = new int[x]; Random rand = new Random(); for (int i = 0; i < x; i++) { nums[i] = rand.Next(100); } return nums; }) .Link<int[]>(x => { // order the numbers (pointless but why not) return x.OrderBy(y => y).ToArray(); }) .Link<int[]>(x => { // compute the average and return it double average = 0.0; for (int i = 0; i < x.Length; i++) { average += x[i]; } return average / x.Length; }); // Execute our chain, passing in 100 as the initial argument double avg = chain.Execute(100); Console.WriteLine("Average int chain finished, result: " + avg); }
public void Base64SerializationTest() { var generator = new PrimitveGenerator (PrimitiveType.Sphere, 12); var generator2 = new PrimitveGenerator (PrimitiveType.Cube, 234702); var chain = new Chain<List<GameObject>> () .Link (generator) .Link (generator2) ; var serialized = new Base64DeSerializer<Chain<List<GameObject>>> (chain); Assert.IsNotEmpty (serialized.Serialized); Assert.AreEqual (chain, serialized.Data); var byteSize = serialized.Serialized.Length * sizeof (Char); Console.WriteLine ("Serialized data is " + byteSize + " bytes."); var deserialized = new Base64DeSerializer<Chain<List<GameObject>>> (serialized.Serialized); Assert.AreEqual (serialized.Serialized, deserialized.Serialized); Assert.AreEqual (serialized.Data.Elements.Count, deserialized.Data.Elements.Count); var deserializedGenerator = (PrimitveGenerator)deserialized.Data.Elements[0]; Assert.AreEqual (generator.Amount, deserializedGenerator.Amount); Assert.AreEqual (generator.Type, deserializedGenerator.Type); var deserializedGenerator2 = (PrimitveGenerator)deserialized.Data.Elements[1]; Assert.AreEqual (generator2.Amount, deserializedGenerator2.Amount); Assert.AreEqual (generator2.Type, deserializedGenerator2.Type); }
public void TestExecutionError() { Chain<int, int> chain = new Chain<int, int>() .Link<int>(x => x) .Link<int>(x => { if (x == 0) throw new NullReferenceException(x.ToString()); else return x; }) .Link<int>(x => 100); ChainExecutionException chEE = null; try { int outcome = chain.Execute(0); } catch (ChainExecutionException chee) { chEE = chee; } Assert.IsNotNull(chEE); Assert.AreEqual<string>("0", chEE.InnerException.Message); }
public void EndChainInvolvement(Chain chain) { if (Chain != null && Chain == chain) { Chain.DecrementInvolvement(); Chain = null; } }
internal ChainSummary(Chain chain, int playerId) { this.ChainId = chain.Id; var playerGuess = chain.Guesses.FirstOrDefault(g => g.Contributor.UserId == playerId); this.PlayerGuess = new PlayerGuess(playerGuess.Content, playerGuess.Type.ToString()); this.OtherContributors = chain.Guesses.Where(g => g.Contributor.UserId != playerId).Select(g => g.Contributor.UserName).ToArray(); }
/// <summary> /// Creates a new multi-deep Markov Chain with the depth passed in /// </summary> /// <param name="depth">The depth to store information for words. Higher values mean more consistency but less flexibility. Minimum value of three.</param> public MultiDeepMarkovChain(int depth) { if (depth < 3) throw new ArgumentException("We currently only support Markov Chains 3 or deeper. Sorry :("); chains = new Dictionary<string, Chain>(); head = new Chain() { text = "[]" }; chains.Add("[]", head); this.depth = depth; }
/// <summary> /// Calculation method. /// </summary> /// <param name="chain"> /// Source sequence. /// </param> /// <param name="link"> /// Link of intervals in chain. /// </param> /// <returns> /// AT skew value as <see cref="double"/>. /// </returns> public double Calculate(Chain chain, Link link) { DnaProcessor.CheckDnaAlphabet(chain.Alphabet); var a = remotenessCalculator.Calculate(chain.GetOrCreateCongenericChain(new ValueString("A")), link); var t = remotenessCalculator.Calculate(chain.GetOrCreateCongenericChain(new ValueString("T")), link); return (int)(a + t) == 0 ? 0 : (a - t) / (a + t); }
public void BeginChainInvolvement(Chain chain) { if (Chain != null) { Chain.DecrementInvolvement(); } Chain = chain; Chain.IncrementInvolvement(); }
public bool Bind(Chain chain) { if (chain != null && this.chain != null && chain != this.chain && !this.chain.OnLinkAdoptedByAnotherChain(this, chain)) { return false; } this.chain = chain; return true; }
/// <summary> /// Calculated as base 2 logarithm of multiplication /// of intervals between nearest elements /// in congeneric sequence. /// </summary> /// <param name="chain"> /// Source sequence. /// </param> /// <param name="link"> /// Link of intervals in chain. /// </param> /// <returns> /// Average remoteness <see cref="double"/> value. /// </returns> public double Calculate(Chain chain, Link link) { double result = 0; for (int i = 0; i < chain.Alphabet.Cardinality; i++) { result += Calculate(chain.CongenericChain(i), link); } return result; }
public World() { this.thinkers = new Chain<Thinker>(); this.vertices = new List<Vertex>(); this.sectors = new List<Sector>(); this.sidedefs = new List<Sidedef>(); this.linedefs = new List<Linedef>(); this.things = new List<Thing>(); this.blockmap = null; }
/// <summary> /// Calculation method. /// </summary> /// <param name="chain"> /// Source sequence. /// </param> /// <param name="link"> /// Link of intervals in chain. /// </param> /// <returns> /// G+C Ratio value as <see cref="double"/>. /// </returns> public double Calculate(Chain chain, Link link) { DnaProcessor.CheckDnaAlphabet(chain.Alphabet); var g = remotenessCalculator.Calculate(chain.GetOrCreateCongenericChain(new ValueString("G")), link); var c = remotenessCalculator.Calculate(chain.GetOrCreateCongenericChain(new ValueString("C")), link); var l = remotenessCalculator.Calculate(chain, link); return 100 * (g + c) / l; }
/// <summary> /// Calculation method. /// </summary> /// <param name="chain"> /// Source sequence. /// </param> /// <param name="link"> /// Link of intervals in chain. /// </param> /// <returns> /// G+C skew value as <see cref="double"/>. /// </returns> public double Calculate(Chain chain, Link link) { DnaProcessor.CheckDnaAlphabet(chain.Alphabet); var g = counter.Calculate(chain.GetOrCreateCongenericChain(new ValueString("G")), link); var c = counter.Calculate(chain.GetOrCreateCongenericChain(new ValueString("C")), link); var result = (g - c) / (g + c); return result; }
public static void Run() { Chain<int, double> chain = new Chain<int, double>() .Link<int>(x => { // Generate random array of ints int[] nums = new int[x]; Random rand = new Random(); for (int i = 0; i < x; i++) { nums[i] = rand.Next(100); } return nums; }) .Link<int[]>(x => { // order the numbers (pointless but why not) return x.OrderBy(y => y).ToArray(); }) .Link<int[]>(x => { // compute the average and return it double average = 0.0; for (int i = 0; i < x.Length; i++) { average += x[i]; } return average / x.Length; }); int count = 0; int started = 0; chain.ExecuteFinished += (sender, e) => { Interlocked.Increment(ref count); }; int iters = 1000000; Queue<int> diff = new Queue<int>(iters); Stopwatch sw = Stopwatch.StartNew(); for (int i = 0; i < iters; i++) { started++; chain.ExecuteAsync(10); diff.Enqueue(started - count); } sw.Stop(); Console.WriteLine("Took: " + sw.Elapsed.ToString()); }
/// <summary> /// Calculation method. /// </summary> /// <param name="chain"> /// Source sequence. /// </param> /// <param name="link"> /// Link of intervals in chain. /// </param> /// <returns> /// Intervals count in chain as <see cref="double"/>. /// </returns> public double Calculate(Chain chain, Link link) { double sum = 0; for (int i = 0; i < chain.Alphabet.Cardinality; i++) { sum += Calculate(chain.CongenericChain(i), link); } return (int)sum; }
public void CanBuildChain() { Chain chain = new Chain(Network.Main); AppendBlock(chain); AppendBlock(chain); AppendBlock(chain); var b = AppendBlock(chain); Assert.Equal(4, chain.Height); Assert.Equal(4, b.Height); Assert.Equal(b.HashBlock, chain.Tip.HashBlock); }
public Chain CreateChain() { if (chains.Count == chains.Capacity) return null; Chain chain = new Chain(); chains.Add(chain); chain.Initialize(SignManager); return chain; }
static void Main(string[] args) { Dispatcher disp = new Dispatcher(); Chain TheChain = new Chain(); Dictionary<int, Command> chain = TheChain.getChain(); foreach (KeyValuePair<int, Command> entry in chain) { disp.run(entry.Value); } }
public ScanState(Scanner scanner, Chain chain, Account account, int startHeight) { if(scanner == null) throw new ArgumentNullException("scanner"); _Account = account; _Chain = chain; _Scanner = scanner; _StartHeight = startHeight; }
/// <summary> /// Calculation method. /// </summary> /// <param name="chain"> /// Source sequence. /// </param> /// <param name="link"> /// Redundant parameter, not used in calculations. /// </param> /// <returns> /// Average word length in <see cref="double"/> value. /// </returns> public double Calculate(Chain chain, Link link) { int chainLength = chain.GetLength(); int sum = 0; for (int i = 0; i < chainLength; i++) { sum += ((ValueString)chain[i]).Value.Length; } return sum / (double)chainLength; }
/// <summary> /// Calculation method. /// </summary> /// <param name="chain"> /// Source sequence. /// </param> /// <param name="link"> /// Link of intervals in chain. /// </param> /// <returns> /// G+C Ratio value as <see cref="double"/> . /// </returns> public double Calculate(Chain chain, Link link) { DnaProcessor.CheckDnaAlphabet(chain.Alphabet); var g = remotenessCalculator.Calculate(chain.GetOrCreateCongenericChain(new ValueString("G")), link); var c = remotenessCalculator.Calculate(chain.GetOrCreateCongenericChain(new ValueString("C")), link); var a = remotenessCalculator.Calculate(chain.GetOrCreateCongenericChain(new ValueString("A")), link); var t = remotenessCalculator.Calculate(chain.GetOrCreateCongenericChain(new ValueString("T")), link); var result = (g + c) / (a + t); return result; }
/// <summary> /// Calculation method for complete matrix of all pairs of elements. /// </summary> /// <param name="chain"> /// Source sequence. /// </param> /// <param name="link"> /// Link of intervals in chain. /// </param> /// <returns> /// Square matrix of characteristics of all pairs of elements. /// </returns> public List<List<double>> CalculateAll(Chain chain, Link link) { var result = new List<List<double>>(); for (int i = 0; i < chain.Alphabet.Cardinality; i++) { result.Add(new List<double>()); for (int j = 0; j < chain.Alphabet.Cardinality; j++) { result[i].Add(Calculate(chain.GetRelationIntervalsManager(i + 1, j + 1), link)); } } return result; }
/// <summary> /// Calculation method. /// </summary> /// <param name="chain"> /// Source sequence. /// </param> /// <param name="link"> /// Link of intervals in chain. /// </param> /// <returns> /// RY skew value as <see cref="double"/>. /// </returns> public double Calculate(Chain chain, Link link) { DnaProcessor.CheckDnaAlphabet(chain.Alphabet); var g = counter.Calculate(chain.GetOrCreateCongenericChain(new ValueString("G")), link); var c = counter.Calculate(chain.GetOrCreateCongenericChain(new ValueString("C")), link); var a = counter.Calculate(chain.GetOrCreateCongenericChain(new ValueString("A")), link); var t = counter.Calculate(chain.GetOrCreateCongenericChain(new ValueString("T")), link); var l = counter.Calculate(chain, link); var result = ((g + a) - (c + t)) / l; return result; }
/// <summary> /// Calculation method. /// </summary> /// <param name="chain"> /// Source sequence. /// </param> /// <param name="link"> /// Link of intervals in chain. /// </param> /// <returns> /// Variations count as <see cref="double"/>. /// </returns> public double Calculate(Chain chain, Link link) { int count = 1; for (int i = 0; i < chain.GetLength(); i++) { var j = chain[i] as ValuePhantom; if (j != null) { count *= ((ValuePhantom)chain[i]).Cardinality; } } return count; }
private void AddCode(Chain otherCode) { if (otherCode != null) { Chain thisCode = this.code; if (thisCode == null) { this.code = otherCode; } else { this.code = (c) => otherCode(thisCode(c)); } } }
public TestCase(int undirectedEdges, int xorEdges, double minMerge, double maxMerge, Chain[] chainsIn, String[] loopsOut, int numUnusedEdges) { this.undirectedEdges = undirectedEdges; this.xorEdges = xorEdges; this.minMerge = minMerge; this.maxMerge = maxMerge; this.chainsIn = chainsIn; this.loopsOut = loopsOut; this.numUnusedEdges = numUnusedEdges; }
internal Chain(Chain next, int index) { this.NextOrNull = next; this.Index = index; }
internal static IDialog <SandwichOrder> MakeRootDialog() { return(Chain.From(() => FormDialog.FromForm(SandwichOrder.BuildForm))); }
private static IDialog <RootForm> BuildRootForm() { return(Chain .From(() => FormDialog.FromForm(RootForm.BuildForm)) .Do(CompleteForm)); }
public async Task <List <Hash> > GetBlockHashesAsync(Chain chain, Hash firstHash, int count, Hash chainBranchBlockHash) { var first = await _blockManager.GetBlockHeaderAsync(firstHash); if (first == null) { return(new List <Hash>()); } var height = first.Height + count; var chainBranchBlockHashKey = chainBranchBlockHash.ToStorageKey(); ChainBlockLink chainBlockLink = null; if (chain.Branches.ContainsKey(chainBranchBlockHashKey)) { if (height > chain.Branches[chainBranchBlockHashKey]) { height = chain.Branches[chainBranchBlockHashKey]; count = (int)(height - first.Height); } } else { var branchChainBlockLink = await _chainManager.GetChainBlockLinkAsync(chainBranchBlockHash); if (height > branchChainBlockLink.Height) { height = branchChainBlockLink.Height; chainBlockLink = branchChainBlockLink; count = (int)(height - first.Height); } } var hashes = new List <Hash>(); if (count <= 0) { return(hashes); } if (chainBlockLink == null) { var last = await GetBlockHashByHeightAsync(chain, height, chainBranchBlockHash); if (last == null) { throw new InvalidOperationException("not support"); } chainBlockLink = await _chainManager.GetChainBlockLinkAsync(last); } hashes.Add(chainBlockLink.BlockHash); for (var i = 0; i < count - 1; i++) { chainBlockLink = await _chainManager.GetChainBlockLinkAsync(chainBlockLink.PreviousBlockHash); hashes.Add(chainBlockLink.BlockHash); } if (chainBlockLink.PreviousBlockHash != firstHash) { return(new List <Hash>()); } hashes.Reverse(); return(hashes); }
public void TestChain_Jolt_Count_Should_Be_22_10() { var chain = new Chain(_adapters); chain.GetJoltCount().Should().Be((22, 10)); }
public void AddGenesisBlock() { Chain.Add(CreateGenesisBlock()); }
/// <summary> /// POST: api/Messages /// Receive a message from a user and reply to it /// </summary> /// internal static IDialog <object> MakeRoot() { return(Chain.From(() => new AttendanceDialog())); //return Chain.ContinueWith(new UserLogin(), AttendanceDialog); }
public Chain attemptReduction(Chain nearParent, int farParentIndex) { Chain nnpc = null; Literal nearLiteral = nearParent.getHead(); Dictionary <String, List <Chain> > candidateHeads = null; if (nearLiteral.isPositiveLiteral()) { candidateHeads = negHeads; } else { candidateHeads = posHeads; } AtomicSentence nearAtom = nearLiteral.getAtomicSentence(); String nearestKey = nearAtom.getSymbolicName(); List <Chain> farParents = candidateHeads[nearestKey]; if (null != farParents) { Chain farParent = farParents[farParentIndex]; standardizeApart(farParent); Literal farLiteral = farParent.getHead(); AtomicSentence farAtom = farLiteral.getAtomicSentence(); Dictionary <Variable, Term> subst = unifier.unify(nearAtom, farAtom); // If I was able to unify with one // of the far heads if (null != subst) { // Want to always apply reduction uniformly Chain topChain = farParent; Literal botLit = nearLiteral; Chain botChain = nearParent; // Need to apply subst to all of the // literals in the reduction List <Literal> reduction = new List <Literal>(); foreach (Literal l in topChain.getTail()) { AtomicSentence atom = (AtomicSentence)substVisitor.subst( subst, l.getAtomicSentence()); reduction.Add(l.newInstance(atom)); } reduction.Add(new ReducedLiteral((AtomicSentence)substVisitor .subst(subst, botLit.getAtomicSentence()), botLit .isNegativeLiteral())); foreach (Literal l in botChain.getTail()) { AtomicSentence atom = (AtomicSentence)substVisitor.subst( subst, l.getAtomicSentence()); reduction.Add(l.newInstance(atom)); } nnpc = new Chain(reduction); nnpc.setProofStep(new ProofStepChainReduction(nnpc, nearParent, farParent, subst)); } } return(nnpc); }
public void SetNext(Chain NextInChain) { _nextInChain = NextInChain; }
private void UpdateFeatureName() { string name = ""; if (mode == Mode.MERGE) { var streams = StreamsBox.SelectedItems; string streamList = ""; HashSet <string> sourceNames = new HashSet <string>(); HashSet <string> featureNames = new HashSet <string>(); double sampleRate = 0; foreach (DatabaseStream stream in streams) { string[] tokens = stream.Name.Split(new char[] { '.' }, 2); sourceNames.Add(tokens[0]); if (tokens.Length > 1) { featureNames.Add(tokens[1]); } if (streamList == "") { sampleRate = stream.SampleRate; streamList = stream.Name; } else { streamList += ";" + stream.Name; } } string[] sourceArray; sourceArray = sourceNames.ToArray(); Array.Sort(sourceArray); sourceNames.Clear(); sourceNames.UnionWith(sourceArray); string medias = ""; foreach (string media in sourceNames) { if (medias == "") { medias = media; } else { medias += "+" + media; } } string[] featureStreams; featureStreams = featureNames.ToArray(); Array.Sort(featureStreams); featureNames.Clear(); featureNames.UnionWith(featureStreams); string features = ""; foreach (string feature in featureNames) { if (features == "") { features = feature; } else { features += "+" + feature; } } name = medias + "." + features; } else { if (StreamsBox.SelectedItem != null & ChainsBox.SelectedItem != null && StreamsBox.SelectedItem != null) { DatabaseStream stream = (DatabaseStream)StreamsBox.SelectedItem; Chain chain = (Chain)ChainsBox.SelectedItem; string leftContext = LeftContextTextBox.Text; string frameStep = FrameStepTextBox.Text; string rightContext = RightContextTextBox.Text; string streamMeta = "[" + leftContext + "," + frameStep + "," + rightContext + "]"; name = stream.Name + "." + chain.Name + streamMeta;; } } FeatureNameTextBox.Text = name; }
internal static IDialog <ReservaFlow> MakeRootDialog() { //To Call a FormDialog input the line below. return(Chain.From(() => FormDialog.FromForm(ReservaFlow.BuildFrom))); }
internal static IDialog <object> MakeRoot() { return(Chain.From(() => new DefaultLuisDialog())); }
internal static IDialog <RegisterForm> MakeRootDialog() { return(Chain.From(() => FormDialog.FromForm(RegisterForm.BuildForm))); }
public void UnderMoveBlock(Vector2 tablePosition, int color) { colorTable[0, (int)tablePosition.X] = colorTable[9, (int)tablePosition.X]; colorTable[9, (int)tablePosition.X] = 0; chainMode = Chain.Fall; }
public void AddBlockRange(Chain chain, RequestRange range) { var count = (uint)(1 + range.End - range.Start); AddBlockRange(chain, range.Start, count); }
public bool isAnswer(Chain nearParent) { bool isAns = false; if (answerChain.isEmpty()) { if (nearParent.isEmpty()) { proofs.Add(new ProofFinal(nearParent.getProofStep(), new Dictionary <Variable, Term>())); complete = true; isAns = true; } } else { if (nearParent.isEmpty()) { // This should not happen // as added an answer literal to sos, which // implies the database (i.e. premises) are // unsatisfiable to begin with. throw new ApplicationException( "Generated an empty chain while looking for an answer, implies original KB is unsatisfiable"); } if (1 == nearParent.getNumberLiterals() && nearParent.getHead().getAtomicSentence() .getSymbolicName().Equals( answerChain.getHead() .getAtomicSentence() .getSymbolicName())) { Dictionary <Variable, Term> answerBindings = new Dictionary <Variable, Term>(); List <Term> answerTerms = nearParent.getHead() .getAtomicSentence().getArgs(); int idx = 0; foreach (Variable v in answerLiteralVariables) { answerBindings.Add(v, (Term)answerTerms[idx]); idx++; } bool addNewAnswer = true; foreach (Proof p in proofs) { if (p.getAnswerBindings().Equals(answerBindings)) { addNewAnswer = false; break; } } if (addNewAnswer) { proofs.Add(new ProofFinal(nearParent.getProofStep(), answerBindings)); } isAns = true; } } if (DateTime.Now.Ticks > finishTime) { complete = true; // Indicate that I have run out of query time timedOut = true; } return(isAns); }
public ActionResult AddChain(/*string ChainName, DateTime StartingDate, string Frequency, DateTime EndDate*/ Chain ch) { Chain chain = new Chain(); chain.ChainName = ch.ChainName; chain.StartingDate = ch.StartingDate; chain.Frequency = ch.Frequency; chain.EndDate = ch.EndDate; Guid userId = (Guid)Membership.GetUser().ProviderUserKey; chain.UserId = userId; db.Chains.Add(chain); db.SaveChanges(); return(RedirectToAction("Index", "User")); }
// Recursive Depth Limited Search private void recursiveDLS(int maxDepth, int currentDepth, Chain nearParent, IndexedFarParents indexedFarParents, AnswerHandler ansHandler) { // Keep track of the maximum depth reached. ansHandler.updateMaxDepthReached(currentDepth); if (currentDepth == maxDepth) { return; } int noCandidateFarParents = indexedFarParents .getNumberCandidateFarParents(nearParent); if (null != tracer) { tracer.increment(currentDepth, noCandidateFarParents); } indexedFarParents.standardizeApart(nearParent); for (int farParentIdx = 0; farParentIdx < noCandidateFarParents; farParentIdx++) { // If have a complete answer, don't keep // checking candidate far parents if (ansHandler.isComplete()) { break; } // Reduction Chain nextNearParent = indexedFarParents.attemptReduction( nearParent, farParentIdx); if (null == nextNearParent) { // Unable to remove the head via reduction continue; } // Handle Canceling and Dropping bool cancelled = false; bool dropped = false; do { cancelled = false; Chain nextParent = null; while (nextNearParent != (nextParent = tryCancellation(nextNearParent))) { nextNearParent = nextParent; cancelled = true; } dropped = false; while (nextNearParent != (nextParent = tryDropping(nextNearParent))) { nextNearParent = nextParent; dropped = true; } } while (dropped || cancelled); // Check if have answer before // going to the next level if (!ansHandler.isAnswer(nextNearParent)) { // Keep track of the current # of // far parents that are possible for the next near parent. int noNextFarParents = indexedFarParents .getNumberFarParents(nextNearParent); // Add to indexed far parents nextNearParent = indexedFarParents.addToIndex(nextNearParent); // Check the next level recursiveDLS(maxDepth, currentDepth + 1, nextNearParent, indexedFarParents, ansHandler); // Reset the number of far parents possible // when recursing back up. indexedFarParents.resetNumberFarParentsTo(nextNearParent, noNextFarParents); } } }
internal static IDialog <object> MakeRoot() { return(Chain.From(() => new DevelopersDialog())); }
public Rpc(string provider, Chain chain) : this(provider, chain.ToString().ToLower()) { }
public async Task Chain_Catch() { var test = Chain .PostToChain() .Select(m => m.Text) .Where(a => false) .Catch <string, OperationCanceledException>((antecedent, error) => Chain.Return("world")) .PostToUser(); using (var container = Build(Options.ResolveDialogFromContainer)) { var builder = new ContainerBuilder(); builder .RegisterInstance(test) .As <IDialog <object> >(); builder.Update(container); await AssertScriptAsync(container, "hello", "world" ); } }
static void Main(string[] args) { // TestValidate(); var callDebug = Chain .From(() => new PromptDialog.PromptString("Locale?", null, 1)) .ContinueWith <string, Choices>(async(ctx, locale) => { Locale = await locale; CultureInfo.CurrentUICulture = CultureInfo.GetCultureInfo(Locale); CultureInfo.CurrentCulture = CultureInfo.CurrentUICulture; return(FormDialog.FromType <Choices>(FormOptions.PromptInStart)); }) .ContinueWith <Choices, object>(async(context, result) => { Choices choices; try { choices = await result; } catch (Exception error) { await context.PostAsync(error.ToString()); throw; } switch (choices.Choice) { case DebugOptions.AnnotationsAndNumbers: return(MakeForm(() => PizzaOrder.BuildForm(noNumbers: false))); case DebugOptions.AnnotationsAndNoNumbers: return(MakeForm(() => PizzaOrder.BuildForm(noNumbers: true))); case DebugOptions.AnnotationsAndText: return(MakeForm(() => PizzaOrder.BuildForm(style: ChoiceStyleOptions.AutoText))); case DebugOptions.NoAnnotations: return(MakeForm(() => PizzaOrder.BuildForm(noNumbers: true, ignoreAnnotations: true))); case DebugOptions.NoFieldOrder: return(MakeForm(() => new FormBuilder <PizzaOrder>().Build())); case DebugOptions.WithState: return(new FormDialog <PizzaOrder>(new PizzaOrder() { Size = SizeOptions.Large, Kind = PizzaOptions.BYOPizza }, () => PizzaOrder.BuildForm(noNumbers: false), options: FormOptions.PromptInStart, entities: new Luis.Models.EntityRecommendation[] { new Luis.Models.EntityRecommendation("Address", "abc", "DeliveryAddress") } )); case DebugOptions.Localized: { var form = PizzaOrder.BuildForm(false, false); using (var stream = new FileStream("pizza.resx", FileMode.Create)) using (var writer = new ResXResourceWriter(stream)) { form.SaveResources(writer); } Process.Start(new ProcessStartInfo(@"RView.exe", "pizza.resx -c " + Locale) { UseShellExecute = false, CreateNoWindow = true }).WaitForExit(); return(MakeForm(() => PizzaOrder.BuildForm(false, false, true))); } case DebugOptions.SimpleSandwichBot: return(MakeForm(() => SimpleSandwichOrder.BuildForm())); case DebugOptions.AnnotatedSandwichBot: return(MakeForm(() => AnnotatedSandwichOrder.BuildLocalizedForm())); case DebugOptions.JSONSandwichBot: return(MakeForm(() => AnnotatedSandwichOrder.BuildJsonForm())); default: throw new NotImplementedException(); } }) .Do(async(context, result) => { try { var item = await result; Debug.WriteLine(item); } catch (FormCanceledException e) { if (e.InnerException == null) { await context.PostAsync($"Quit on {e.Last} step."); } else { await context.PostAsync($"Exception {e.Message} on step {e.Last}."); } } }) .DefaultIfException() .Loop(); Interactive(callDebug).GetAwaiter().GetResult(); }
public async Task SetBestChainAsync(Chain chain, long bestChainHeight, Hash bestChainHash) { await _chainManager.SetBestChainAsync(chain, bestChainHeight, bestChainHash); }
public virtual UInt256 GetRequiredNextTarget(Chain chain) { try { // genesis block, use its target if (chain.Height == 0) { // lookup genesis block header var genesisBlockHeader = chain.Blocks[0].BlockHeader; return(genesisBlockHeader.CalculateTarget()); } // not on an adjustment interval, use previous block's target else if (chain.Height % DifficultyInterval != 0) { // lookup the previous block on the current blockchain var prevBlockHeader = chain.Blocks[chain.Height - 1].BlockHeader; return(prevBlockHeader.CalculateTarget()); } // on an adjustment interval, calculate the required next target else { // lookup the previous block on the current blockchain var prevBlockHeader = chain.Blocks[chain.Height - 1].BlockHeader; // get the block difficultyInterval blocks ago var startBlockHeader = chain.Blocks[chain.Height - DifficultyInterval].BlockHeader; //Debug.Assert(startChainedHeader.Height == blockchain.Height - DifficultyInternal); var actualTimespan = (long)prevBlockHeader.Time - (long)startBlockHeader.Time; var targetTimespan = DifficultyTargetTimespan; // limit adjustment to 4x or 1/4x if (actualTimespan < targetTimespan / 4) { actualTimespan = targetTimespan / 4; } else if (actualTimespan > targetTimespan * 4) { actualTimespan = targetTimespan * 4; } // calculate the new target var target = startBlockHeader.CalculateTarget(); target *= actualTimespan; target /= targetTimespan; // make sure target isn't too high (too low difficulty) if (target > HighestTarget) { target = HighestTarget; } return(target); } } catch (ArgumentException) { // invalid bits Debugger.Break(); throw new ValidationException(chain.LastBlock.Hash); } }
public async Task SendResumeAsyncTest() { var chain = Chain.PostToChain().Select(m => m.Text).Switch( new RegexCase <IDialog <string> >(new Regex("^resume"), (context, data) => { context.UserData.SetValue("resume", true); return(Chain.Return("resumed!")); }), new DefaultCase <string, IDialog <string> >((context, data) => { return(Chain.Return(data)); })).Unwrap().PostToUser(); using (new FiberTestBase.ResolveMoqAssembly(chain)) using (var container = Build(Options.InMemoryBotDataStore, chain)) { var msg = DialogTestBase.MakeTestMessage(); msg.Text = "testMsg"; await new TestAdapter().ProcessActivity((Activity)msg, async(context) => { using (var scope = DialogModule.BeginLifetimeScope(container, context)) { Func <IDialog <object> > MakeRoot = () => chain; scope.Resolve <Func <IDialog <object> > >(TypedParameter.From(MakeRoot)); await Conversation.SendAsync(scope, context); var queue = ((TestAdapter)context.Adapter).ActiveQueue; var reply = queue.Dequeue(); var botData = scope.Resolve <IBotData>(); await botData.LoadAsync(default(CancellationToken)); var dataBag = scope.Resolve <Func <IBotDataBag> >()(); Assert.IsTrue(dataBag.ContainsKey(ResumptionContext.RESUMPTION_CONTEXT_KEY)); Assert.IsNotNull(scope.Resolve <ConversationReference>()); } }); var conversationReference = msg.ToConversationReference(); var continuationMessage = conversationReference.GetPostToBotMessage(); await new TestAdapter().ProcessActivity((Activity)continuationMessage, async(context) => { using (var scope = DialogModule.BeginLifetimeScope(container, context)) { Func <IDialog <object> > MakeRoot = () => { throw new InvalidOperationException(); }; scope.Resolve <Func <IDialog <object> > >(TypedParameter.From(MakeRoot)); await scope.Resolve <IPostToBot>().PostAsync(new Activity { Text = "resume" }, CancellationToken.None); var queue = ((TestAdapter)context.Adapter).ActiveQueue; var reply = queue.Dequeue(); Assert.AreEqual("resumed!", reply.Text); var botData = scope.Resolve <IBotData>(); await botData.LoadAsync(default(CancellationToken)); Assert.IsTrue(botData.UserData.GetValue <bool>("resume")); } }); } }
public Convolution3DLayer(Chain parent) : base(parent) { }
public async Task InputHintTest() { var chain = Chain.PostToChain().Select(m => m.Text).ContinueWith <string, string>(async(context, result) => { var text = await result; if (text.ToLower().StartsWith("inputhint")) { var reply = context.MakeMessage(); reply.Text = "reply"; reply.InputHint = InputHints.ExpectingInput; await context.PostAsync(reply); return(Chain.Return($"{text}")); } else if (!text.ToLower().StartsWith("reset")) { for (int i = 0; i < 10; i++) { await context.PostAsync($"message:{i}"); } return(Chain.Return($"{text}")); } else { return(Chain.From(() => new PromptDialog.PromptConfirm("Are you sure you want to reset the count?", "Didn't get that!", 3, PromptStyle.Keyboard)).ContinueWith <bool, string>(async(ctx, res) => { string reply; if (await res) { ctx.UserData.SetValue("count", 0); reply = "Reset count."; } else { reply = "Did not reset count."; } return Chain.Return(reply); })); } }).PostToUser(); Func <IDialog <object> > MakeRoot = () => chain; using (new FiberTestBase.ResolveMoqAssembly(chain)) using (var container = Build(Options.InMemoryBotDataStore | Options.NeedsInputHint, chain)) { var msg = DialogTestBase.MakeTestMessage(); msg.Text = "test"; await new TestAdapter().ProcessActivity((Activity)msg, async(context) => { using (var scope = DialogModule.BeginLifetimeScope(container, context)) { scope.Resolve <Func <IDialog <object> > >(TypedParameter.From(MakeRoot)); await Conversation.SendAsync(scope, context); var queue = ((TestAdapter)context.Adapter).ActiveQueue; Assert.IsTrue(queue.Count > 0); while (queue.Count > 0) { var toUser = queue.Dequeue(); if (queue.Count > 0) { Assert.IsTrue(toUser.InputHint == InputHints.IgnoringInput); } else { Assert.IsTrue(toUser.InputHint == InputHints.AcceptingInput); } } } }); msg.Text = "inputhint"; await new TestAdapter().ProcessActivity((Activity)msg, async(context) => { using (var scope = DialogModule.BeginLifetimeScope(container, context)) { scope.Resolve <Func <IDialog <object> > >(TypedParameter.From(MakeRoot)); await Conversation.SendAsync(scope, context); var queue = ((TestAdapter)context.Adapter).ActiveQueue; Assert.IsTrue(queue.Count == 2); var toUser = queue.Dequeue(); Assert.AreEqual("reply", toUser.Text); Assert.IsTrue(toUser.InputHint == InputHints.ExpectingInput); } }); msg.Text = "reset"; await new TestAdapter().ProcessActivity((Activity)msg, async(context) => { using (var scope = DialogModule.BeginLifetimeScope(container, context)) { scope.Resolve <Func <IDialog <object> > >(TypedParameter.From(MakeRoot)); await Conversation.SendAsync(scope, context); var queue = ((TestAdapter)context.Adapter).ActiveQueue; Assert.IsTrue(queue.Count == 1); var toUser = queue.Dequeue(); Assert.IsTrue(toUser.InputHint == InputHints.ExpectingInput); Assert.IsNotNull(toUser.LocalTimestamp); } }); } }
public override void ChainDispose() { _array = null; _chain = null; }
public void standardizeApart(Chain c) { saIdx = StandardizeApartInPlace.standardizeApart(c, saIdx); }
public void Reset() { m_enum.Reset(); m_chain = null; }