상속: MonoBehaviour
예제 #1
0
        /// <summary>
        /// TEMP METHOD
        /// </summary>
        public static void FmMyWeapon(Network.WorldClient client, Database.Records.WorldItemRecord item, int type)
        {
            foreach (var effect in item.Engine.Effects)
            {
                if (effect.ID == 100)
                {
                    switch (type)
                    {
                        case 1://Force
                            effect.ID = 97;
                            break;

                        case 2://feu
                            effect.ID = 99;
                            break;

                        case 3://chance
                            effect.ID = 96;
                            break;

                        case 4://agi
                            effect.ID = 98;
                            break;
                    }
                }
            }
        }
예제 #2
0
        public static Transfer GetForRequest(Network.Entities.FileTransferRequest req)
        {
            Transfer t = null;

            switch (req.FileType)
            {
                case "data":
                    t = new UnsavedBinaryTransfer();
                    break;
                case "file":
                    t = new ExistingFileTransfer();
                    break;
                case "cont":
                    t = new ContactTransfer();
                    break;
                default:
                    break;
            }

            if (t != null)
            {
                t.FileName = req.FileName;
                t.FileLength = req.FileLength;
            }

            t.IsReading = false;
            t.PrepareForWriting();

            return t;
        }
예제 #3
0
		private static string GenerateWif(Key key, string password, Network network)
		{
			var vch = key.ToBytes();
			//Compute the Bitcoin address (ASCII),
			var addressBytes = Encoders.ASCII.DecodeData(key.PubKey.GetAddress(network).ToWif());
			// and take the first four bytes of SHA256(SHA256()) of it. Let's call this "addresshash".
			var addresshash = Hashes.Hash256(addressBytes).ToBytes().SafeSubarray(0, 4);

			var derived = SCrypt.BitcoinComputeDerivedKey(Encoding.UTF8.GetBytes(password), addresshash);

			var encrypted = EncryptKey(vch, derived);



			var version = network.GetVersionBytes(Base58Type.ENCRYPTED_SECRET_KEY_NO_EC);
			byte flagByte = 0;
			flagByte |= 0x0C0;
			flagByte |= (key.IsCompressed ? (byte)0x20 : (byte)0x00);

			var bytes = version
							.Concat(new[] { flagByte })
							.Concat(addresshash)
							.Concat(encrypted).ToArray();
			return Encoders.Base58Check.EncodeData(bytes);
		}
예제 #4
0
 public DrivenNode(NodeDefinition nd, Network net, int instnc)
     : base(nd, net, instnc)
 {
     visualNotificationDeferrals = 0;
     visualsNeedNotification = false;
     handlingLongMessage = false;
 }
예제 #5
0
        /// <summary>
        /// Sends the specified writer.
        /// </summary>
        /// <param name="writer">The writer.</param>
        /// <param name="version">The version.</param>
        /// <remarks></remarks>
        protected override void OnSend(Network.BigEndianStream writer, int version)
        {
            if (writer == null)
                throw new ArgumentNullException("writer");
            writer.Write(Code);

        }
예제 #6
0
		protected Base58Data(byte[] rawBytes, Network network)
		{
			if(network == null)
				throw new ArgumentNullException("network");
			_Network = network;
			SetData(rawBytes);
		}
예제 #7
0
 public Time()
 {
     blnFailNotificationSent = false;
     this.network = Program.network;
     this.thread = new Thread(MonitorTime);
     thread.Start();
 }
예제 #8
0
		public NodeServerTester(Network network = null)
		{
			int retry = 0;
			network = network ?? Network.TestNet;
			while(true)
			{
				try
				{
					var a = _Rand.Next(4000, 60000);
					var b = _Rand.Next(4000, 60000);
					_Server1 = new NodeServer(network, internalPort: a);
					_Server1.AllowLocalPeers = true;
					_Server1.ExternalEndpoint = new IPEndPoint(IPAddress.Parse("127.0.0.1").MapToIPv6Ex(), a);
					_Server1.Listen();
					_Server2 = new NodeServer(network, internalPort: b);
					_Server2.AllowLocalPeers = true;
					_Server2.ExternalEndpoint = new IPEndPoint(IPAddress.Parse("127.0.0.1").MapToIPv6Ex(), b);
					_Server2.Listen();
					break;
				}
				catch(Exception)
				{
					if(_Server1 != null)
						_Server1.Dispose();
					if(_Server2 != null)
						_Server2.Dispose();
					retry++;
					if(retry == 5)
						throw;
				}
			}
		}
예제 #9
0
        public void GetWallReturnsAllPostsForUserAndSubscriptions()
        {
            var userName = "******";
            var message = "New Message";
            var anotherMessage = "Another Message";

            var secondUserName = "******";
            var secondUserMessage = "Second User Message";

            var thirdUserName = "******";
            var thirdUserMessage = "Third User Message";

            var network = new Network();
            network.AddPost(userName, message);
            network.AddPost(userName, anotherMessage);
            network.AddPost(secondUserName, secondUserMessage);
            network.AddPost(thirdUserName, thirdUserMessage);
            network.Follow(userName, secondUserName);

            // Results for A's wall should contain all 3 posts from users A and B.
            var results = network.GetWall(userName);
            Assert.IsTrue(results.Count() == 3);
            Assert.IsTrue(results.Any(x => x.Message == message));
            Assert.IsTrue(results.Any(x => x.Message == anotherMessage));
            Assert.IsTrue(results.Any(x => x.Message == secondUserMessage));

            // However, results when looking at B's wall should only return B's posts.
            results = network.GetWall(secondUserName);
            Assert.IsTrue(results.Count() == 1);
            Assert.IsTrue(results.Any(x => x.Message == secondUserMessage));
        }
예제 #10
0
 void Bot_OnMessage(Network n, Irc.IrcEventArgs e)
 {
     if (IsMatch("^autoop \\?$", e.Data.Message)) {
         AnswerWithNotice(n, e, FormatBold("Use of AutoOp plugin:"));
         AnswerWithNotice(n, e, "No remote commands available. All configuration has to be done manually in the Configuration.xml.");
     }
 }
예제 #11
0
 void Op(Network n, string mask, string nick, string channel)
 {
     foreach (XmlElement elem in Bot.Configuration["Plugins"]["AutoOp"].GetElementsByTagName("Op")) {
         if (IsMatch(elem.InnerText, mask))
             n.Op(channel, nick);
     }
 }
예제 #12
0
        public static void BoostCaract(Network.WorldClient client, int type)
        {
            Engines.Stats.SingleStats Stat = client.Character.Stats.GetStats(type);
            if (client.Character.CaractPoint <= 0)
                return;

            Database.Records.BreedRecord breed = Helper.BreedHelper.GetBreed(client.Character.Breed);

            if (breed == null)
                return;

            Engines.Breeds.StatFloor floor = breed.Engine.GetFloorForValue((Enums.StatsTypeEnum)type, Stat.Base);

            if (floor == null)
                return;

            if (client.Character.CaractPoint < floor.Cost)
                return;

            Stat.Base += floor.Value;
            client.Character.CaractPoint -= floor.Cost;

            if ((Enums.StatsTypeEnum)type == Enums.StatsTypeEnum.Life)
                client.Character.CurrentLife += floor.Value;
        }
예제 #13
0
 public static Network CopyNetwork(Network original)
 {
     Network ret = new Network(original.Transform);
     original.UpdateIndices();
     //Creating Neurons
     for (int i = 0; i < original.Inputs.Count; i++)
     {
         ret.CreatePerceptron(original.Inputs[i].Transform);
     }
     for (int i = 0; i < original.Body.Count; i++)
     {
         ret.CreateNeuron(original.Body[i].Threshhold, original.Body[i].Transform);
     }
     for (int i = 0; i < original.Outputs.Count; i++)
     {
         ret.CreateConsolidator(original.Outputs[i].Transform);
     }
     //Creating connections
     for(int i = 0; i < ret.Neurons.Count; i++)
     {
         Neuron orig = original.Neurons[i];
         Neuron inp = ret.Neurons[i];
         for(int j = 0; j < orig.Outputs.Count; j++)
         {
             Neuron outp = ret.Neurons[orig.Outputs[j].Output.GlobIndex];
             ret.CreateDendron(inp, outp, orig.Outputs[j].Factor);
         }
     }
     return ret;
 }
예제 #14
0
    protected void addnetwork_button_Click(object sender, EventArgs e)
    {
        if (addnetwork_name.Text != "" && addnetwork_pattern.Text != "")
        {
            String name = addnetwork_name.Text;
            bool exists = false;
            for (int i = 0; i < Results.Items.Count; i++)
            {
                if(Results.Items[i].Text.Equals(name) ){
                    exists = true;
                    break;
                }
            }
            if(exists) {
                addnetwork_label.Text = "Network already exists!";
            }
            else {
                Network network = new Network(addnetwork_name.Text.ToString(), addnetwork_pattern.Text.ToString());
                Network savedNetwork = NetworkDataService.addNetwork(network);
                // Results.Items.Add(new ListItem(savedNetwork.name, savedNetwork.id.ToString()));
                addnetwork_label.Text = "Network Added Successfully!";
            }

        }
        else
        {
            addnetwork_label.Text = "Please fill in both fields";
        }
    }
예제 #15
0
        public void IRenderableMaze(Network network, PictureBox renderBox)
        {
            if (bmp != null)
            {
                bmp.Dispose();
            }

            colBackground = backgroundPanel.BackColor;
            colCorridor = corridorPanel.BackColor;
            colWall = wallPanel.BackColor;
            worldScale = (float)scaleCtrl.Value;

            worldOffset.X = 0.0f;
            worldOffset.Y = 0.0f;

            corridorWidth = (float)corridorWidthCtrl.Value;
            wallWidth = (float)wallWidthCtrl.Value;
            //corrWidth = (float)10.0f;

            if (network is ShapeNetwork)
            {
                RenderShapeNetwork(network);
            }
            else if(network is PolarNetwork)
            {
                RenderPolarNetwork((PolarNetwork)network);
            }

            renderBox.Image = bmp;
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="NeuralNetworkEnsemble"/> class. 
        ///   Constructor
        /// </summary>
        /// <param name="networks">
        /// An array of trained networks that will work as hash functions
        /// </param>
        /// <exception cref="NeuralNetworkHashingException">
        /// Can not create a NN Ensemble out of no networks
        /// </exception>
        public NeuralNetworkEnsemble(Network[] networks)
        {
            if (networks == null || networks.Length == 0)
            {
                throw new NeuralNetworkHashingException("Can not create a NN Ensemble out of no networks");
            }

            inputsCount = networks[0].InputCount;

            // Check all inputs
            foreach (Network network in networks)
            {
                if (network.InputCount != inputsCount)
                {
                    throw new NeuralNetworkHashingException("All networks should have the same inputs count");
                }

                if (network.MedianResponces == null)
                {
                    throw new NeuralNetworkHashingException(
                        "Median responses of one of the networks is null," + " please run Median Responses computation for each of the networks and try again");
                }
            }

            this.networks = networks;

            foreach (Network network in this.networks)
            {
                totalOutputs += network.GetLayerNeuronCount(network.LayerCount - 1);
            }

            outputVector = new byte[totalOutputs];
        }
예제 #17
0
        public void EdgesTest()
        {
            Network network = new Network();
            NetworkEdge networkEdge;

            network.Nodes.Add();
            network.Nodes.Add();

            Assert.AreEqual(2, network.Nodes.Count);

            for (int i = 0; i < 5; i++)
            {
                networkEdge = network.Edges.Add(network.Nodes[0], network.Nodes[1]);

                Assert.IsNotNull(networkEdge);

                //Проверим, существует ли другие вершины или дуги с таким же индексом.
                CheckNetworkObjectId(networkEdge);
            }
            Assert.AreEqual(5, network.Edges.Count);

            network.Edges.RemoveAt(0);
            network.Edges.RemoveAt(1);
            Assert.AreEqual(3, network.Edges.Count);

            network.Nodes.RemoveAt(0);
            Assert.AreEqual(1, network.Nodes.Count);

            network.Nodes.Add();
            Assert.AreEqual(2, network.Nodes.Count);

            networkEdge = network.Edges.Add(network.Nodes[0], network.Nodes[1]);
            Assert.IsNotNull(networkEdge);
            CheckNetworkObjectId(networkEdge);
        }
예제 #18
0
        public NeuralNetwork()
            : base(Color.Red, false)
        {
            BackgroundImage = PlayingGround.field;

            network = new Network(stInputov, stOutputov, stHidenLayer, stNevronovNaHidenLayer);
        }
예제 #19
0
 public void AddMember(Network.WorldClient client)
 {
     lock (this.Clients)
     {
         this.Clients.Add(client);
     }
 }
예제 #20
0
        /// <summary>
        /// Receives the specified reader.
        /// </summary>
        /// <param name="reader">The reader.</param>
        /// <param name="version">The version.</param>
        /// <remarks></remarks>
        protected override void OnReceive(Network.BigEndianStream reader, int version)
        {
            if (reader == null)
                throw new ArgumentNullException("reader");

            Reason = reader.ReadClassicString();
        }
        private void initializeData(Network network)
        {
            Weights = new double[network.Nodes.Length][][];
            this.InputLayerSize = network.Nodes[0][0].Weights.Length - 1; // -bias

            int weightCnt = this.InputLayerSize + 1;

            var layerCnt = network.Nodes.Length;
            // for each layer
            for (int i = 0; i < layerCnt; ++i)
            {
                var layerSize = network.Nodes[i].Length;
                Weights[i] = new double[layerSize][];

                // for each node
                for (int j = layerSize - 1; j >= 0; --j)
                {
                    Weights[i][j] = new double[weightCnt];
                    // for each weight
                    for (int k = weightCnt - 1; k >= 0; --k)
                        Weights[i][j][k] = network.Nodes[i][j].Weights[k];
                }

                // prepare weightCnt for next layer
                weightCnt = layerSize + 1;
            }
        }
예제 #22
0
 public LightContentDialog(HueLamp light, Network network)
 {
     this.InitializeComponent();
     this.light = light;
     this.network = network;
     this.DataContext = light;
 }
예제 #23
0
 public MainPage()
 {
     this.InitializeComponent();
     Network network = new Network();
     var mainViewModel = new MainViewModel();
     mainViewModel.MenuItems.Add(new SimpleNavMenuItem
     {
         Label = "Lights",
         DestinationPage = typeof(LightsPage),
         Symbol = (Symbol)Convert.ToChar(""),
         Arguments = network
     });
     mainViewModel.MenuItems.Add(new SimpleNavMenuItem
     {
         Label = "Room",
         DestinationPage = typeof(RoomPage),
         Symbol = Symbol.Street,
         Arguments = network
         
     });
     mainViewModel.MenuItems.Add(new SimpleNavMenuItem
     {
         Label = "Settings",
         DestinationPage = typeof(SettingsPage),
         Symbol = Symbol.Setting,
         Arguments = network
     });
     DataContext = mainViewModel;
 }
예제 #24
0
		public static string GetWrappedBase58(string base58, Network network)
		{
			var coloredVersion = network.GetVersionBytes(Base58Type.COLORED_ADDRESS);
			var inner = Encoders.Base58Check.DecodeData(base58);
			inner = inner.Skip(coloredVersion.Length).ToArray();
			return Encoders.Base58Check.EncodeData(inner);
		}
예제 #25
0
        void Bot_OnMessage(Network network, Irc.IrcEventArgs e)
        {
            if (IsMatch("^seen \\?$", e.Data.Message)) {
                AnswerWithNotice(network, e, FormatBold("Use of Seen plugin:"));
                AnswerWithNotice(network, e, FormatItalic("seen <nick>") + " - Displays information when the Bot last saw <nick>.");
            }
            else if (IsMatch("^seen (?<nick>.*)$", e.Data.Message)) {
                SeenInfo i = FindName(network.Name, Matches["nick"].ToString(), l);
                if (i == null)
                    Answer(network, e, "I never saw " + Matches["nick"].ToString() + " before.");
                else if (i.Ident == e.Data.Ident)
                    Answer(network, e, "Looking for yourself, eh?");
                else {
                    string hour = "hours";
                    string minute = "minutes";
                    TimeSpan t = (TimeSpan)(DateTime.Now - i.Date);
                    if (t.TotalHours == 1)
                        hour = "hour";
                    if (t.Minutes == 1)
                        minute = "minute";
                    Answer(network, e, "I saw " + Matches["nick"].ToString() + " " + Convert.ToInt16(t.TotalHours).ToString() + " " + hour + " and " + t.Minutes.ToString() + " " + minute + " ago, " + i.Text + ".");
                }
            }

            NewSeen(network.Name, e.Data.Nick, e.Data.Ident, "on " + e.Data.Channel + ", saying " + e.Data.Message);
        }
예제 #26
0
		public static char PrefixForNetwork(Network network) {
			switch(network) {
			case Network.Bitcoin:
				return '1';
			case Network.Testnet:
				return '2';
			case Network.Friendly:
				return 'F';
			case Network.Litecoin:
				return 'L';
			case Network.Namecoin:
				return 'N';
			case Network.Fairbrix:
				return 'f';
			case Network.GeistGeld:
				return 'g';
			case Network.I0coin:
				return 'j';
			case Network.Solidcoin:
				return 's';
			case Network.Tenebrix:
				return 't';
			default:
				throw new ArgumentException(String.Format("No known network prefix for network {0}", network));
			}
		}
예제 #27
0
        public Engine()
        {
            mRenderer = new vRenderer();
            mInput = new Input();
            mNetwork = new Network();
            mScript = new Script();

            mWorld = new cWorld();

            bool other = false;

            for (int y = 0; y < 10; y++)
            {
                for (int x = 0; x < 10; x++)
                {
                    World_Geom geom = new World_Geom(new Vector2(x*64, y*64), "tex_bookshelf.bmp");

                    if (!other)
                    {
                        //geom = new World_Geom(new Vector2(x, y), "tex2.bmp");

                        e_pillar door = new e_pillar(new Vector2(x+0.5f, y+0.5f), "tex_3.bmp");
                        mWorld.AddEntity(door);
                    }

                    mWorld.AddGeometry(geom);
                    other = !other;
                }
                other = !other;
            }
        }
예제 #28
0
        public AddRemoveNode(NodeChangeType nodeChangeType, Node node, Node parent1, Node parent2, List<Node> outputs, Network network)
        {
            if (node == null)
                throw new ArgumentNullException("node");
            if (parent1 == null)
                throw new ArgumentNullException("parent1");
            if (parent2 == null)
                throw new ArgumentNullException("parent2");
            if (outputs == null)
                throw new ArgumentNullException("output");
            //if (node == parent1 || node == parent2 || node == outputs || //TODO: FIX THIS checker
            //    parent1 == parent2 || parent1 == outputs || parent2 == outputs)
            //    throw new ArgumentException();

            nodeChangeType_ = nodeChangeType;
            node_ = node;
            parent1_ = parent1;
            parent2_ = parent2;
            outputs_ = outputs;
            network_ = network;

            // NODE: it is only way I was able to create to make parent 2 children stay in same order after revert
            parent2NodeToInsertAfter_ = null;
            if (nodeChangeType == NodeChangeType.Remove)
            {
                LinkedListNode<Node> parent2LinkedListNodeToInsertAfter = parent2_.Outputs.Find(node_).Previous;
                if (parent2LinkedListNodeToInsertAfter != null)
                {
                    parent2NodeToInsertAfter_ = parent2_.Outputs.Find(node_).Previous.Value;
                }
            }
        }
예제 #29
0
        public static void Run()
        {
            var trainingSets = GenerateTrainingSets(100);

            Network network;
            double error = 0;
            do
            {
                Console.WriteLine("Optimizing...");
                network = new Network(trainingSets[0].Inputs.Length, 2, 10, trainingSets[0].Outputs.Length);
                network.Weights = BruteOptimizer.OptimizeMulti(network, trainingSets);
                error = network.Error(trainingSets, network.Weights);
                Console.WriteLine("Error from last optimization attempt: " + error);
            } while (error > 3);

            Console.WriteLine("Optimization complete!");
            while (true)
            {
                Console.Write("Enter space-separated inputs: ");
                var inputs = Console.ReadLine().Split(' ');
                if (inputs.Length == 1)
                {
                    break;
                }
                var inputArray = new double[] { double.Parse(inputs[0].Trim()), double.Parse(inputs[1].Trim()) };
                Console.WriteLine(network.Pulse(inputArray)[0]);
            }
        }
 public override int GetStakeMinConfirmations(int height, Network network)
 {
     return(height < 55 ? 50 : 60);
 }
예제 #31
0
        public async Task TestServicesAsync(string networkString)
        {
            var network          = Network.GetNetwork(networkString);
            var blocksToDownload = new HashSet <uint256>();

            if (network == Network.Main)
            {
                blocksToDownload.Add(new uint256("00000000000000000037c2de35bd85f3e57f14ddd741ce6cee5b28e51473d5d0"));
                blocksToDownload.Add(new uint256("000000000000000000115315a43cb0cdfc4ea54a0e92bed127f4e395e718d8f9"));
                blocksToDownload.Add(new uint256("00000000000000000011b5b042ad0522b69aae36f7de796f563c895714bbd629"));
            }
            else if (network == Network.TestNet)
            {
                blocksToDownload.Add(new uint256("0000000097a664c4084b49faa6fd4417055cb8e5aac480abc31ddc57a8208524"));
                blocksToDownload.Add(new uint256("000000009ed5b82259ecd2aa4cd1f119db8da7a70e7ea78d9c9f603e01f93bcc"));
                blocksToDownload.Add(new uint256("00000000e6da8c2da304e9f5ad99c079df2c3803b49efded3061ecaf206ddc66"));
            }
            else
            {
                throw new NotSupportedException(network.ToString());
            }

            var manager    = KeyManager.CreateNew(out Mnemonic mnemonic, "password");
            var dataFolder = Path.Combine(SharedFixture.DataDir, nameof(TestServicesAsync));

            Directory.CreateDirectory(SharedFixture.DataDir);

            var             addressManagerFilePath = Path.Combine(SharedFixture.DataDir, $"AddressManager{network}.dat");
            var             blocksFolderPath       = Path.Combine(SharedFixture.DataDir, $"Blocks{network}");
            var             connectionParameters   = new NodeConnectionParameters();
            AddressManager  addressManager         = null;
            BlockDownloader downloader             = null;

            try
            {
                try
                {
                    addressManager = AddressManager.LoadPeerFile(addressManagerFilePath);
                    Logger.LogInfo <WalletService>($"Loaded {nameof(AddressManager)} from `{addressManagerFilePath}`.");
                }
                catch (FileNotFoundException ex)
                {
                    Logger.LogInfo <WalletService>($"{nameof(AddressManager)} did not exist at `{addressManagerFilePath}`. Initializing new one.");
                    Logger.LogTrace <WalletService>(ex);
                    addressManager = new AddressManager();
                }

                connectionParameters.TemplateBehaviors.Add(new AddressManagerBehavior(addressManager));
                var memPoolService = new MemPoolService();
                connectionParameters.TemplateBehaviors.Add(new MemPoolBehavior(memPoolService));

                using (var nodes = new NodesGroup(network, connectionParameters,
                                                  new NodeRequirement
                {
                    RequiredServices = NodeServices.Network,
                    MinVersion = ProtocolVersion.WITNESS_VERSION
                }))
                {
                    downloader = new BlockDownloader(nodes, blocksFolderPath);
                    Assert.True(Directory.Exists(blocksFolderPath));
                    downloader.Start();
                    foreach (var hash in blocksToDownload)
                    {
                        downloader.QueToDownload(hash);
                    }
                    var wallet = new WalletService(dataFolder, network, manager, nodes, memPoolService);
                    try
                    {
                        nodes.ConnectedNodes.Added         += ConnectedNodes_Added;
                        nodes.ConnectedNodes.Removed       += ConnectedNodes_Removed;
                        memPoolService.TransactionReceived += MemPoolService_TransactionReceived;

                        nodes.Connect();
                        // Using the interlocked, not because it makes sense in this context, but to
                        // set an example that these values are often concurrency sensitive
                        var times = 0;
                        while (Interlocked.Read(ref _nodeCount) < 3)
                        {
                            if (times > 4200)                             // 7 minutes
                            {
                                throw new TimeoutException($"Connection test timed out.");
                            }
                            await Task.Delay(100);

                            times++;
                        }

                        times = 0;
                        while (Interlocked.Read(ref _mempoolTransactionCount) < 3)
                        {
                            if (times > 3000)                             // 3 minutes
                            {
                                throw new TimeoutException($"{nameof(MemPoolService)} test timed out.");
                            }
                            await Task.Delay(100);

                            times++;
                        }

                        foreach (var hash in blocksToDownload)
                        {
                            times = 0;
                            while (downloader.GetBlock(hash) == null)
                            {
                                if (times > 1800)                                 // 3 minutes
                                {
                                    throw new TimeoutException($"{nameof(BlockDownloader)} test timed out.");
                                }
                                await Task.Delay(100);

                                times++;
                            }
                            Assert.True(File.Exists(Path.Combine(blocksFolderPath, hash.ToString())));
                            Logger.LogInfo <WalletTests>($"Full block is downloaded: {hash}.");
                        }
                    }
                    finally
                    {
                        nodes.ConnectedNodes.Added         -= ConnectedNodes_Added;
                        nodes.ConnectedNodes.Removed       -= ConnectedNodes_Removed;
                        memPoolService.TransactionReceived -= MemPoolService_TransactionReceived;
                    }
                }
            }
            finally
            {
                downloader?.Stop();

                // So next test will download the block.
                foreach (var hash in blocksToDownload)
                {
                    downloader.TryRemove(hash);
                }
                Directory.Delete(blocksFolderPath, recursive: true);

                addressManager?.SavePeerFile(addressManagerFilePath, network);
                Logger.LogInfo <WalletTests>($"Saved {nameof(AddressManager)} to `{addressManagerFilePath}`.");
            }
        }
예제 #32
0
 /// <summary>
 /// Prints command-line help.
 /// </summary>
 /// <param name="network">The network to extract values from.</param>
 public static void PrintHelp(Network network)
 {
     WalletSettings.PrintHelp(network);
 }
예제 #33
0
파일: Plugin.cs 프로젝트: yuweiApp/ice
        public void Initialize()
        {
            bool ipv4 = _communicator.GetPropertyAsBool("Ice.IPv4") ?? true;
            bool preferIPv6 = _communicator.GetPropertyAsBool("Ice.PreferIPv6Address") ?? false;

            string address;
            if (ipv4 && !preferIPv6)
            {
                address = _communicator.GetProperty($"{_name}.Address") ?? "239.255.0.1";
            }
            else
            {
                address = _communicator.GetProperty($"{_name}.Address") ?? "ff15::1";
            }
            int port = _communicator.GetPropertyAsInt($"{_name}.Port") ?? 4061;
            string intf = _communicator.GetProperty($"{_name}.Interface") ?? "";

            string lookupEndpoints = _communicator.GetProperty($"{_name}.Lookup") ?? "";
            if (lookupEndpoints.Length == 0)
            {
                int ipVersion = ipv4 && !preferIPv6 ? Network.EnableIPv4 : Network.EnableIPv6;
                List<string> interfaces = Network.GetInterfacesForMulticast(intf, ipVersion);
                lookupEndpoints = string.Join(":", interfaces.Select(
                    intf => $"udp -h \"{address}\" -p {port} --interface \"{intf}\""));
            }

            if (_communicator.GetProperty($"{_name}.Reply.Endpoints") == null)
            {
                _communicator.SetProperty($"{_name}.Reply.Endpoints",
                    intf.Length == 0 ? "udp -h *" : $"udp -h \"{intf}\"");
            }

            if (_communicator.GetProperty($"{_name}.Locator.Endpoints") == null)
            {
                _communicator.SetProperty($"{_name}.Locator.AdapterId", Guid.NewGuid().ToString());
            }

            _replyAdapter = _communicator.CreateObjectAdapter(_name + ".Reply");
            _locatorAdapter = _communicator.CreateObjectAdapter(_name + ".Locator");

            // We don't want those adapters to be registered with the locator so clear their locator.
            _replyAdapter.Locator = null;
            _locatorAdapter.Locator = null;

            var lookupPrx = ILookupPrx.Parse($"IceLocatorDiscovery/Lookup -d:{lookupEndpoints}", _communicator);
            // No collocation optimization or router for the multicast proxy!
            lookupPrx = lookupPrx.Clone(clearRouter: false, collocationOptimized: false);

            ILocatorPrx voidLocator = _locatorAdapter.AddWithUUID(new VoidLocator(), ILocatorPrx.Factory);

            var lookupReplyId = new Identity(Guid.NewGuid().ToString(), "");
            ILookupReplyPrx? locatorReplyPrx = _replyAdapter.CreateProxy(lookupReplyId, ILookupReplyPrx.Factory).Clone(
                invocationMode: InvocationMode.Datagram);
            _defaultLocator = _communicator.DefaultLocator;

            string instanceName = _communicator.GetProperty($"{_name}.InstanceName") ?? "";
            var locatorId = new Identity("Locator", instanceName.Length > 0 ? instanceName : Guid.NewGuid().ToString());
            _locator = new Locator(_name, lookupPrx, _communicator, instanceName, voidLocator, locatorReplyPrx);
            _locatorPrx = _locatorAdapter.Add(locatorId, _locator, ILocatorPrx.Factory);
            _communicator.DefaultLocator = _locatorPrx;

            _replyAdapter.Add(lookupReplyId, new LookupReply(_locator));

            _replyAdapter.Activate();
            _locatorAdapter.Activate();
        }
예제 #34
0
    /*
     * getPlayerAmount() {
     * }
     */

    //spawn/resp
    private void SpawnPlayer()
    {
        Network.Instantiate(playerPrefab, new Vector3(0f, 5f, 0f), Quaternion.identity, 0);
        //playersAmount++;
        addPlayer();
    }
예제 #35
0
 private void JoinServer(HostData hostData)
 {
     Network.Connect(hostData);
 }
예제 #36
0
 public static PaymentACK Load(byte[] data, Network network)
 {
     return(Load(new MemoryStream(data), network));
 }
예제 #37
0
 private void SpawnPlayer()
 {
     Network.Instantiate(playerPrefab, new Vector3(0f, 40f, 0f), Quaternion.identity, 0);
 }
예제 #38
0
 /// <summary>
 /// Initializes custom serializers for DBreeze engine.
 /// </summary>
 public void Initialize(Network network)
 {
     this.Network = network;
     CustomSerializator.ByteArraySerializator   = this.Serializer;
     CustomSerializator.ByteArrayDeSerializator = this.Deserializer;
 }
예제 #39
0
 private void StartServer()
 {
     MasterServer.ipAddress = "127.0.0.1";
     Network.InitializeServer(4, 25000, !Network.HavePublicAddress());
     MasterServer.RegisterHost(typeName, gameName);
 }
예제 #40
0
 /// <summary>
 /// Get the default configuration. Invoked via reflection.
 /// </summary>
 /// <param name="builder">The string builder to add the settings to.</param>
 /// <param name="network">The network to base the defaults off.</param>
 public static void BuildDefaultConfigurationFile(StringBuilder builder, Network network)
 {
     StoreSettings.BuildDefaultConfigurationFile(builder, network);
 }
예제 #41
0
        /// <summary>
        /// Gets a VM network.
        /// </summary>
        /// <param name='fabricName'>
        /// Required. Fabric unique name.
        /// </param>
        /// <param name='networkName'>
        /// Required. Network name.
        /// </param>
        /// <param name='customRequestHeaders'>
        /// Optional. Request header parameters.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The response model for the Network object.
        /// </returns>
        public async Task <NetworkResponse> GetAsync(string fabricName, string networkName, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken)
        {
            // Validate
            if (fabricName == null)
            {
                throw new ArgumentNullException("fabricName");
            }
            if (networkName == null)
            {
                throw new ArgumentNullException("networkName");
            }

            // Tracing
            bool   shouldTrace  = TracingAdapter.IsEnabled;
            string invocationId = null;

            if (shouldTrace)
            {
                invocationId = TracingAdapter.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("fabricName", fabricName);
                tracingParameters.Add("networkName", networkName);
                tracingParameters.Add("customRequestHeaders", customRequestHeaders);
                TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
            }

            // Construct URL
            string url = "";

            url = url + "/Subscriptions/";
            if (this.Client.Credentials.SubscriptionId != null)
            {
                url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
            }
            url = url + "/resourceGroups/";
            url = url + Uri.EscapeDataString(this.Client.ResourceGroupName);
            url = url + "/providers/";
            url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
            url = url + "/";
            url = url + Uri.EscapeDataString(this.Client.ResourceType);
            url = url + "/";
            url = url + Uri.EscapeDataString(this.Client.ResourceName);
            url = url + "/replicationFabrics/";
            url = url + Uri.EscapeDataString(fabricName);
            url = url + "/replicationNetworks/";
            url = url + Uri.EscapeDataString(networkName);
            List <string> queryParameters = new List <string>();

            queryParameters.Add("api-version=2015-11-10");
            if (queryParameters.Count > 0)
            {
                url = url + "?" + string.Join("&", queryParameters);
            }
            string baseUrl = this.Client.BaseUri.AbsoluteUri;

            // Trim '/' character from the end of baseUrl and beginning of url.
            if (baseUrl[baseUrl.Length - 1] == '/')
            {
                baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
            }
            if (url[0] == '/')
            {
                url = url.Substring(1);
            }
            url = baseUrl + "/" + url;
            url = url.Replace(" ", "%20");

            // Create HTTP transport objects
            HttpRequestMessage httpRequest = null;

            try
            {
                httpRequest            = new HttpRequestMessage();
                httpRequest.Method     = HttpMethod.Get;
                httpRequest.RequestUri = new Uri(url);

                // Set Headers
                httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId);
                httpRequest.Headers.Add("x-ms-version", "2015-01-01");

                // Set Credentials
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                // Send Request
                HttpResponseMessage httpResponse = null;
                try
                {
                    if (shouldTrace)
                    {
                        TracingAdapter.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                    if (shouldTrace)
                    {
                        TracingAdapter.ReceiveResponse(invocationId, httpResponse);
                    }
                    HttpStatusCode statusCode = httpResponse.StatusCode;
                    if (statusCode != HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
                        if (shouldTrace)
                        {
                            TracingAdapter.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    NetworkResponse result = null;
                    // Deserialize Response
                    if (statusCode == HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                        result = new NetworkResponse();
                        JToken responseDoc = null;
                        if (string.IsNullOrEmpty(responseContent) == false)
                        {
                            responseDoc = JToken.Parse(responseContent);
                        }

                        if (responseDoc != null && responseDoc.Type != JTokenType.Null)
                        {
                            Network networkInstance = new Network();
                            result.Network = networkInstance;

                            JToken propertiesValue = responseDoc["properties"];
                            if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
                            {
                                NetworkProperties propertiesInstance = new NetworkProperties();
                                networkInstance.Properties = propertiesInstance;

                                JToken fabricTypeValue = propertiesValue["fabricType"];
                                if (fabricTypeValue != null && fabricTypeValue.Type != JTokenType.Null)
                                {
                                    string fabricTypeInstance = ((string)fabricTypeValue);
                                    propertiesInstance.FabricType = fabricTypeInstance;
                                }

                                JToken subnetsArray = propertiesValue["subnets"];
                                if (subnetsArray != null && subnetsArray.Type != JTokenType.Null)
                                {
                                    foreach (JToken subnetsValue in ((JArray)subnetsArray))
                                    {
                                        Subnet subnetInstance = new Subnet();
                                        propertiesInstance.Subnets.Add(subnetInstance);

                                        JToken nameValue = subnetsValue["name"];
                                        if (nameValue != null && nameValue.Type != JTokenType.Null)
                                        {
                                            string nameInstance = ((string)nameValue);
                                            subnetInstance.Name = nameInstance;
                                        }

                                        JToken friendlyNameValue = subnetsValue["friendlyName"];
                                        if (friendlyNameValue != null && friendlyNameValue.Type != JTokenType.Null)
                                        {
                                            string friendlyNameInstance = ((string)friendlyNameValue);
                                            subnetInstance.FriendlyName = friendlyNameInstance;
                                        }

                                        JToken addressListArray = subnetsValue["addressList"];
                                        if (addressListArray != null && addressListArray.Type != JTokenType.Null)
                                        {
                                            foreach (JToken addressListValue in ((JArray)addressListArray))
                                            {
                                                subnetInstance.AddressList.Add(((string)addressListValue));
                                            }
                                        }
                                    }
                                }

                                JToken friendlyNameValue2 = propertiesValue["friendlyName"];
                                if (friendlyNameValue2 != null && friendlyNameValue2.Type != JTokenType.Null)
                                {
                                    string friendlyNameInstance2 = ((string)friendlyNameValue2);
                                    propertiesInstance.FriendlyName = friendlyNameInstance2;
                                }

                                JToken networkTypeValue = propertiesValue["networkType"];
                                if (networkTypeValue != null && networkTypeValue.Type != JTokenType.Null)
                                {
                                    string networkTypeInstance = ((string)networkTypeValue);
                                    propertiesInstance.NetworkType = networkTypeInstance;
                                }
                            }

                            JToken idValue = responseDoc["id"];
                            if (idValue != null && idValue.Type != JTokenType.Null)
                            {
                                string idInstance = ((string)idValue);
                                networkInstance.Id = idInstance;
                            }

                            JToken nameValue2 = responseDoc["name"];
                            if (nameValue2 != null && nameValue2.Type != JTokenType.Null)
                            {
                                string nameInstance2 = ((string)nameValue2);
                                networkInstance.Name = nameInstance2;
                            }

                            JToken typeValue = responseDoc["type"];
                            if (typeValue != null && typeValue.Type != JTokenType.Null)
                            {
                                string typeInstance = ((string)typeValue);
                                networkInstance.Type = typeInstance;
                            }

                            JToken locationValue = responseDoc["location"];
                            if (locationValue != null && locationValue.Type != JTokenType.Null)
                            {
                                string locationInstance = ((string)locationValue);
                                networkInstance.Location = locationInstance;
                            }

                            JToken tagsSequenceElement = ((JToken)responseDoc["tags"]);
                            if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
                            {
                                foreach (JProperty property in tagsSequenceElement)
                                {
                                    string tagsKey   = ((string)property.Name);
                                    string tagsValue = ((string)property.Value);
                                    networkInstance.Tags.Add(tagsKey, tagsValue);
                                }
                            }
                        }
                    }
                    result.StatusCode = statusCode;
                    if (httpResponse.Headers.Contains("x-ms-request-id"))
                    {
                        result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                    }

                    if (shouldTrace)
                    {
                        TracingAdapter.Exit(invocationId, result);
                    }
                    return(result);
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }
예제 #42
0
        /// <summary>
        /// 解析优酷视频源文件地址
        /// </summary>
        ///<remarks>自动应答会检查前缀为<i>youku</i>的所有设置</remarks>
        public ParseResult Parse(ParseRequest request)
        {
            ParseResult pr     = new ParseResult();
            string      urlpre = @"http://v.youku.com/player/getPlayList/VideoIDS/%ID%/timezone/+08/version/5/source/video?n=3&ran=4656&password=%PW%";
            string      url    = urlpre.Replace(@"%ID%", request.Id).Replace(@"%PW%", request.Password);
            string      xmldoc = Network.GetHtmlSource(url, Encoding.UTF8, request.Proxy);
            //选择语言
            Regex rLang = new Regex(@"(?<=""audiolang"":\[).+?(?=\])");
            Match mLang = rLang.Match(xmldoc);

            if (mLang.Success)             //如果存在多种语言
            {
                string                      langs       = mLang.Value;
                Regex                       rLanguage   = new Regex(@"""lang"":""(?<lang>.+?)"",""vid"":""(?<vid>.+?)""");
                MatchCollection             mcLanguages = rLanguage.Matches(langs);
                Dictionary <string, string> langDict    = new Dictionary <string, string>();
                foreach (Match mLanguage in mcLanguages)
                {
                    langDict.Add(mLanguage.Groups["vid"].Value, Tools.ReplaceUnicode2Str(mLanguage.Groups["lang"].Value));
                }
                //string chosenId = ToolForm.CreateSingleSelectForm("您正在下载的视频有多种语言版本,请选择语言:", langDict, "", request.AutoAnswers, "youku");
                string chosenId = "";
                foreach (KeyValuePair <string, string> kvp in langDict)
                {
                    chosenId = kvp.Key;
                    break;
                }
                request.Id = chosenId;
                url        = urlpre.Replace(@"%ID%", request.Id).Replace(@"%PW%", request.Password);
                xmldoc     = Network.GetHtmlSource(url, Encoding.UTF8, request.Proxy);
            }

            //正则表达式提取各个参数
            string regexstring = "\"seed\":(?<seed>\\w+),.+\"key1\":\"(?<key1>\\w+)\",\"key2\":\"(?<key2>\\w+)\".+\"streamfileids\":{\"(?<fileposfix>\\w+)\":\"(?<fileID>[0-9\\*]+)";
            Regex  r           = new Regex(regexstring);
            Match  m           = r.Match(xmldoc);
            //提取参数
            double seed = Double.Parse(m.Groups["seed"].Value);
            string key1 = m.Groups["key1"].Value;
            string key2 = m.Groups["key2"].Value;


            //提取各视频参数
            Regex  rStreamFileIds = new Regex(@"""streamfileids"":{(?<fileids>.+?)}");
            Match  mStreamFileIds = rStreamFileIds.Match(xmldoc);
            string fileIds        = mStreamFileIds.Groups["fileids"].Value;

            var    dict       = new Dictionary <string, string>();
            string defaultres = "";

            //是否有超清模式
            if (fileIds.Contains("hd2"))
            {
                dict.Add("hd2", "超清(hd2)");
                defaultres = "hd2";
            }
            //是否有高清模式
            if (fileIds.Contains("mp4"))
            {
                dict.Add("mp4", "高清(mp4)");
                defaultres = "mp4";
            }
            //是否有普通清晰度
            if (fileIds.Contains("flv"))
            {
                dict.Add("flv", "标清(flv)");
                defaultres = "flv";
            }


            string fileposfix = null;
            string strSelect  = null;

            //自动应答
            if (request.AutoAnswers.Count > 0)
            {
                foreach (var item in request.AutoAnswers)
                {
                    if (item.Prefix == "youku")
                    {
                        if (fileIds.Contains(item.Identify))
                        {
                            strSelect  = item.Identify;
                            fileposfix = item.Identify;
                            break;
                        }
                    }
                }
            }

            if (string.IsNullOrEmpty(fileposfix))
            {
                //如果多余一种清晰度
                if (dict.Count > 1)
                {
                    fileposfix = ToolForm.CreateSingleSelectForm("您正在下载优酷视频,请选择视频清晰度:", dict, defaultres, request.AutoAnswers, "youku");
                }
                else
                {
                    fileposfix = defaultres;
                }
                strSelect = fileposfix;
            }

            //修正高清
            if (fileposfix == "hd2")
            {
                fileposfix = "flv";
            }


            //取得FileID
            Regex  rFileID = new Regex(@"""" + strSelect + @""":""(?<fileid>.+?)""");
            Match  mFileID = rFileID.Match(fileIds);
            string fileID  = mFileID.Groups["fileid"].Value;

            //提取视频个数
            int    flv_no     = 0;
            string regexFlvNo = @"""segs"":{""\w+"":\[(?<content>.+?)\]";
            Regex  rn         = new Regex(regexFlvNo);
            Match  mn         = rn.Match(xmldoc);

            char[] tmp_content = mn.Groups["content"].Value.ToCharArray();
            foreach (char item in tmp_content)
            {
                if (item == '{')
                {
                    flv_no++;
                }
            }

            //提取key
            Regex  rSegs    = new Regex(@"segs"":{(?<segs>.+?)},""streamsizes");
            Match  mSegs    = rSegs.Match(xmldoc);
            string segs     = mSegs.Groups["segs"].Value;
            Regex  rSegsSub = new Regex(@"""" + strSelect + @""":\[(?<segssub>.+?)\]");
            Match  mSegsSub = rSegsSub.Match(segs);
            string segssub  = mSegsSub.Groups["segssub"].Value;


            string          regexKey = @"""k"":""(?<k>\w+)"",""k2"":""(?<k2>\w+)""";
            MatchCollection mcKey    = Regex.Matches(segssub, regexKey);
            List <string>   keys     = new List <string>();

            foreach (Match mKey in mcKey)
            {
                keys.Add("?K=" + mKey.Groups["k"].Value + ",k2:" + mKey.Groups["k2"].Value);
            }

            //生成sid
            string sid = genSid();
            //生成fileid
            string fileid = getFileID(fileID, seed);
            //生成key
            //string key = genKey(key1, key2);
            //添加各个地址
            List <string> lst = new List <string>();

            for (int i = 0; i < flv_no; i++)
            {
                //得到地址
                string u = "http://f.youku.com/player/getFlvPath/sid/" + sid + "_" + string.Format("{0:D2}", i) +
                           "/st/" + fileposfix + "/fileid/" + fileid.Substring(0, 8) + string.Format("{0:D2}", i)
                           + fileid.Substring(10) + keys[i];
                //添加地址
                pr.Items.Add(new ParseResultItem(new Uri(u)));
            }

            //提取各项详细信息
            MatchCollection mcSegs = Regex.Matches(segssub, @"{.+?}");

            for (int i = 0; i < mcSegs.Count; i++)
            {
                MatchCollection mcKeys = Regex.Matches(mcSegs[i].Value, @"""(?<key>\w+)"":""(?<value>\w+)""");
                foreach (Match mkey in mcKeys)
                {
                    string k = mkey.Groups["key"].Value;
                    string v = mkey.Groups["value"].Value;
                    //修正length和order
                    if (k.Equals("seconds"))
                    {
                        k = "length";
                        v = (Int32.Parse(v) * 1000).ToString();
                    }
                    if (k.Equals("no"))
                    {
                        k = "order";
                    }
                    pr.Items[i].Information.Add(k, v);
                }
            }

            return(pr);
        }
예제 #43
0
    void OnGUI()
    {
        if (Network.peerType == NetworkPeerType.Disconnected)
        {
            matrixSliderGUI.GetComponent <Canvas>().enabled = false;
            IP = GUI.TextField(new Rect(100, 100, 200, 50), IP);
            if (GUI.Button(new Rect(100, 150, 200, 50), "Start Client"))
            {
                Network.Connect(IP, Port);
            }
            if (GUI.Button(new Rect(100, 200, 200, 50), "Start Server"))
            {
                Network.InitializeServer(10, Port);
            }
        }
        else
        {
            if (Network.peerType == NetworkPeerType.Client)
            {
                matrixSliderGUI.GetComponent <Canvas>().enabled = true;

                if (!questionAllowed)
                {
                    matrixSliderGUI.GetComponent <MatrixSlider>().SwitchButtonsStaus(false);

                    GUI.Label(new Rect(100, 100, 100, 25), "Client");

                    if (GUI.Button(new Rect(100, 125, 220, 50), "Question!"))
                    {
                        GetComponent <NetworkView>().RPC("Questions", RPCMode.All, true);
                    }

                    if (GUI.Button(new Rect(100, 175, 220, 50), "Logout"))
                    {
                        Network.Disconnect(250);
                    }
                }
                else
                {
                    if (questionFlag)
                    {
                        matrixSliderGUI.GetComponent <MatrixSlider>().SwitchButtonsStaus(true);
                        GetComponent <NetworkView>().RPC("Questions", RPCMode.All, false);
                    }
                }
            }

            if (Network.peerType == NetworkPeerType.Server)
            {
                GUI.Label(new Rect(100, Screen.height - 300, 100, 25), "Server");
                GUI.Label(new Rect(100, Screen.height - 200, 100, 25), "Connections: " + Network.connections.Length);

                if (GUI.Button(new Rect(100, Screen.height - 100, 200, 50), "Logout"))
                {
                    Network.Disconnect(250);
                }

                if (questionFlag)
                {
                    if (GUI.Button(new Rect(Screen.width / 2 - 110, Screen.height / 2 - 25, 220, 50), "Please!"))
                    {
                        GetComponent <NetworkView>().RPC("QuestionAllowed", RPCMode.All);
                    }
                }

                if (questionAllowed)
                {
                    if (GUI.Button(new Rect(Screen.width / 2 - 110, Screen.height / 2 - 25, 220, 50), "Finished!"))
                    {
                        GetComponent <NetworkView>().RPC("QuestionFinished", RPCMode.All);
                    }
                }

                matrixSliderGUI.GetComponent <Canvas>().enabled = true;
            }
        }
    }
        /// <summary>
        /// Creates a proof of work block assembler.
        /// </summary>
        /// <param name="consensusLoop">Consensus loop.</param>
        /// <param name="consensusRules"></param>
        /// <param name="dateTimeProvider">Date and time provider.</param>
        /// <param name="mempool">Memory pool for transactions.</param>
        /// <param name="mempoolLock">Async lock for memory pool.</param>
        /// <param name="network">Network running on.</param>
        /// <returns>Proof of work block assembler.</returns>
        private static PowBlockDefinition CreatePowBlockAssembler(IConsensusLoop consensusLoop, IConsensusRules consensusRules, IDateTimeProvider dateTimeProvider, LoggerFactory loggerFactory, TxMempool mempool, MempoolSchedulerLock mempoolLock, Network network)
        {
            var options = new BlockDefinitionOptions
            {
                BlockMaxWeight = network.Consensus.Option <PowConsensusOptions>().MaxBlockWeight,
                BlockMaxSize   = network.Consensus.Option <PowConsensusOptions>().MaxBlockSerializedSize
            };

            var blockMinFeeRate = new FeeRate(PowMining.DefaultBlockMinTxFee);

            options.BlockMinFeeRate = blockMinFeeRate;

            return(new PowBlockDefinition(consensusLoop, dateTimeProvider, loggerFactory, mempool, mempoolLock, network, consensusRules, options));
        }
예제 #45
0
 /// <summary>
 /// Prints command-line help. Invoked via reflection.
 /// </summary>
 /// <param name="network">The network to extract values from.</param>
 public static void PrintHelp(Network network)
 {
     StoreSettings.PrintHelp(network);
 }
        public void Setup()
        {
            _network = new Network();


            Setup("fakemac");
            SetupRoutesOnInterface(new[]
            {
                new NetworkRoute
                {
                    gateway = "10.1.10.20",
                    netmask = "255.255.255.0",
                    route   = "10.1.10.1"
                },
                new NetworkRoute
                {
                    gateway = "10.1.10.20",
                    netmask = "255.255.255.0",
                    route   = "10.1.10.2"
                }
            });
            _networkInterface1       = NetworkInterface;
            _networkInterface1.label = "public";
            _network.Interfaces.Add("fakemac", _networkInterface1);

            Setup("fakemac1");
            SetupRoutesOnInterface(new[]
            {
                new NetworkRoute
                {
                    gateway = "10.1.10.20",
                    netmask = "255.255.255.0",
                    route   = "10.1.10.1"
                },
                new NetworkRoute
                {
                    gateway = "10.1.10.20",
                    netmask = "255.255.255.0",
                    route   = "10.1.10.3"
                }
            });
            _networkInterface2         = NetworkInterface;
            _networkInterface2.gateway = "10.1.1.1";
            _network.Interfaces.Add("fakemac1", _networkInterface2);

            _executableProcessQueue = MockRepository.GenerateMock <IExecutableProcessQueue>();
            _executableProcessQueue.Expect(x => x.Go()).Repeat.Once();

            _registryReader = MockRepository.GenerateMock <IRegistryReader>();
            _registryReader.Stub(x => x.GetValuesFrom(Arg <string> .Is.Anything))
            .Return(new List <string> {
                "0.0.0.0,0.0.0.0,172.16.251.2,2",
                "1.2.3.4,5.6.7.8,9.10.11.12.13,10"
            });

            _logger = MockRepository.GenerateMock <ILogger>();

            ExecutableProcessQueue.Replay();
            _setNetworkRoutes = new SetNetworkRoutes(_executableProcessQueue, _registryReader, _logger);
            _setNetworkRoutes.Execute(_network);
        }
        /// <summary>
        /// Creates the test chain with some default blocks and txs.
        /// </summary>
        /// <param name="network">Network to create the chain on.</param>
        /// <param name="scriptPubKey">Public key to create blocks/txs with.</param>
        /// <returns>Context object representing the test chain.</returns>
        public static async Task <ITestChainContext> CreateAsync(Network network, Script scriptPubKey, string dataDir)
        {
            var nodeSettings = new NodeSettings(network, args: new string[] { $"-datadir={dataDir}" });

            ILoggerFactory    loggerFactory    = nodeSettings.LoggerFactory;
            IDateTimeProvider dateTimeProvider = DateTimeProvider.Default;

            network.Consensus.Options = new PowConsensusOptions();
            var consensusSettings  = new ConsensusSettings(nodeSettings);
            var chain              = new ConcurrentChain(network);
            var cachedCoinView     = new CachedCoinView(new InMemoryCoinView(chain.Tip.HashBlock), DateTimeProvider.Default, loggerFactory);
            var networkPeerFactory = new NetworkPeerFactory(network, dateTimeProvider, loggerFactory, new PayloadProvider().DiscoverPayloads(), new SelfEndpointTracker());

            var peerAddressManager = new PeerAddressManager(DateTimeProvider.Default, nodeSettings.DataFolder, loggerFactory, new SelfEndpointTracker());
            var peerDiscovery      = new PeerDiscovery(new AsyncLoopFactory(loggerFactory), loggerFactory, Network.Main, networkPeerFactory, new NodeLifetime(), nodeSettings, peerAddressManager);
            var connectionSettings = new ConnectionManagerSettings(nodeSettings);
            var connectionManager  = new ConnectionManager(dateTimeProvider, loggerFactory, network, networkPeerFactory, nodeSettings, new NodeLifetime(), new NetworkPeerConnectionParameters(), peerAddressManager, new IPeerConnector[] { }, peerDiscovery, connectionSettings);

            var            blockPuller    = new LookaheadBlockPuller(chain, connectionManager, new LoggerFactory());
            var            peerBanning    = new PeerBanning(connectionManager, loggerFactory, dateTimeProvider, peerAddressManager);
            var            deployments    = new NodeDeployments(network, chain);
            ConsensusRules consensusRules = new PowConsensusRules(network, loggerFactory, dateTimeProvider, chain, deployments, consensusSettings, new Checkpoints(), new InMemoryCoinView(new uint256()), new Mock <ILookaheadBlockPuller>().Object).Register(new FullNodeBuilderConsensusExtension.PowConsensusRulesRegistration());
            var            consensusLoop  = new ConsensusLoop(new AsyncLoopFactory(loggerFactory), new NodeLifetime(), chain, cachedCoinView, blockPuller, deployments, loggerFactory, new ChainState(new InvalidBlockHashStore(dateTimeProvider)), connectionManager, dateTimeProvider, new Signals.Signals(), consensusSettings, nodeSettings, peerBanning, consensusRules);
            await consensusLoop.StartAsync();

            var blockPolicyEstimator = new BlockPolicyEstimator(new MempoolSettings(nodeSettings), loggerFactory, nodeSettings);
            var mempool     = new TxMempool(dateTimeProvider, blockPolicyEstimator, loggerFactory, nodeSettings);
            var mempoolLock = new MempoolSchedulerLock();

            // Simple block creation, nothing special yet:
            PowBlockDefinition blockDefinition = CreatePowBlockAssembler(consensusLoop, consensusRules, dateTimeProvider, loggerFactory as LoggerFactory, mempool, mempoolLock, network);
            BlockTemplate      newBlock        = blockDefinition.Build(chain.Tip, scriptPubKey);

            chain.SetTip(newBlock.Block.Header);

            RuleContext ruleContext = consensusRules.CreateRuleContext(new ValidationContext {
                Block = newBlock.Block
            }, consensusLoop.Tip);

            ruleContext.MinedBlock = true;
            await consensusLoop.ValidateAndExecuteBlockAsync(ruleContext);

            List <BlockInfo> blockinfo = CreateBlockInfoList();

            // We can't make transactions until we have inputs
            // Therefore, load 100 blocks :)
            int baseheight = 0;
            var blocks     = new List <Block>();
            var srcTxs     = new List <Transaction>();

            for (int i = 0; i < blockinfo.Count; ++i)
            {
                Block currentBlock = newBlock.Block.Clone(); // pointer for convenience
                currentBlock.Header.HashPrevBlock = chain.Tip.HashBlock;
                currentBlock.Header.Version       = 1;
                currentBlock.Header.Time          = Utils.DateTimeToUnixTime(chain.Tip.GetMedianTimePast()) + 1;
                Transaction txCoinbase = currentBlock.Transactions[0].Clone();
                txCoinbase.Inputs.Clear();
                txCoinbase.Version = 1;
                txCoinbase.AddInput(new TxIn(new Script(new[] { Op.GetPushOp(blockinfo[i].extraNonce), Op.GetPushOp(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()));
                currentBlock.Transactions[0] = txCoinbase;

                if (srcTxs.Count == 0)
                {
                    baseheight = chain.Height;
                }
                if (srcTxs.Count < 4)
                {
                    srcTxs.Add(currentBlock.Transactions[0]);
                }
                currentBlock.UpdateMerkleRoot();

                currentBlock.Header.Nonce = blockinfo[i].nonce;

                chain.SetTip(currentBlock.Header);
                RuleContext ruleContextForBlock = consensusRules.CreateRuleContext(new ValidationContext {
                    Block = currentBlock
                }, consensusLoop.Tip);
                ruleContextForBlock.MinedBlock = true;
                await consensusLoop.ValidateAndExecuteBlockAsync(ruleContextForBlock);

                blocks.Add(currentBlock);
            }

            // Just to make sure we can still make simple blocks
            blockDefinition = CreatePowBlockAssembler(consensusLoop, consensusRules, dateTimeProvider, loggerFactory as LoggerFactory, mempool, mempoolLock, network);
            newBlock        = blockDefinition.Build(chain.Tip, scriptPubKey);

            var mempoolValidator = new MempoolValidator(mempool, mempoolLock, dateTimeProvider, new MempoolSettings(nodeSettings), chain, cachedCoinView, loggerFactory, nodeSettings, consensusRules);

            return(new TestChainContext {
                MempoolValidator = mempoolValidator, SrcTxs = srcTxs
            });
        }
 public SmartContractFeature(IConsensusManager consensusLoop, ILoggerFactory loggerFactory, Network network, IStateRepositoryRoot stateRoot)
 {
     this.consensusManager = consensusLoop;
     this.logger           = loggerFactory.CreateLogger(this.GetType().FullName);
     this.network          = network;
     this.stateRoot        = stateRoot;
 }
예제 #49
0
 private void Refresh(int inputs, List <int> hiddens, int outputs)
 {
     Net = new Network(inputs, hiddens, outputs);
 }
예제 #50
0
        private static IEnumerable <SauceNaoDataResult> ParseResults(string url)
        {
            var doc  = new HtmlDocument();
            var html = Network.GetString(BASIC_RESULT + url);


            doc.LoadHtml(html);

            // todo: improve

            var results = doc.DocumentNode.SelectNodes("//div[@class='result']");

            var images = new List <SauceNaoDataResult>();

            foreach (var result in results)
            {
                if (result.GetAttributeValue("id", String.Empty) == "result-hidden-notification")
                {
                    continue;
                }

                var n = result.FirstChild.FirstChild;

                //var resulttableimage = n.ChildNodes[0];
                var resulttablecontent = n.ChildNodes[1];

                var resultmatchinfo      = resulttablecontent.FirstChild;
                var resultsimilarityinfo = resultmatchinfo.FirstChild;

                // Contains links
                var resultmiscinfo = resultmatchinfo.ChildNodes[1];

                var    links1 = resultmiscinfo.SelectNodes("a/@href");
                string?link1  = links1?[0].GetAttributeValue("href", null);


                var resultcontent = resulttablecontent.ChildNodes[1];

                //var resulttitle = resultcontent.ChildNodes[0];

                var resultcontentcolumn = resultcontent.ChildNodes[1];

                // Other way of getting links
                var    links2 = resultcontentcolumn.SelectNodes("a/@href");
                string?link2  = links2?[0].GetAttributeValue("href", null);

                string?link = link1 ?? link2;

                var(creator, material) = FindInfo(resultcontent);
                float similarity = Single.Parse(resultsimilarityinfo.InnerText.Replace("%", String.Empty));


                var i = new SauceNaoDataResult
                {
                    Urls       = new[] { link } !,
                    Similarity = similarity,
                    Creator    = creator,
                };

                images.Add(i);
            }

            return(images);
        }
예제 #51
0
        public IEnumerator Connect()
        {
            yield return(new WaitForSeconds(2f));

            Network.Connect(hostList[0]);
        }
예제 #52
0
 /// <summary>
 /// Initializes logger factory for inherited tests.
 /// </summary>
 public TestBase(Network network)
 {
     this.Network             = network;
     this.DataStoreSerializer = new DataStoreSerializer(network.Consensus.ConsensusFactory);
 }
예제 #53
0
        public async Task DescribeImageAsync()
        {
            IsBusy        = true;
            StatusMessage = null;

            string baseDescription            = null;
            string facesRecognizedDescription = null;
            string emotionDescription         = null;

            MessengerInstance.Send(new NotificationMessage(Constants.TakingPhoto));

            try
            {
                StatusMessage = AppResources.QueryingVisionService;
                using (var stream = await streamingService.GetCurrentFrameAsync())
                {
                    if (stream != null)
                    {
                        if (await Network.IsInternetAvailableAsync())
                        {
                            var imageBytes = await stream.ToArrayAsync();

                            MessengerInstance.Send(new NotificationMessage <byte[]>(imageBytes, Constants.PhotoTaken));

                            var visualFeatures = new VisualFeature[] { VisualFeature.Description, VisualFeature.Faces };
                            var result         = await visionService.AnalyzeImageAsync(stream, visualFeatures);

                            Caption originalDescription;
                            Caption filteredDescription;

                            if (result.IsValid(out originalDescription, out filteredDescription))
                            {
                                baseDescription = filteredDescription.Text;

                                if (Language != Constants.DefaultLanguge && IsTranslatorServiceRegistered)
                                {
                                    // The description needs to be translated.
                                    StatusMessage = AppResources.Translating;
                                    var translation = await translatorService.TranslateAsync(filteredDescription.Text, from : Constants.DefaultLanguge, to : Language);

                                    if (Settings.ShowOriginalDescriptionOnTranslation)
                                    {
                                        baseDescription = $"{translation} ({filteredDescription.Text})";
                                    }
                                    else
                                    {
                                        baseDescription = translation;
                                    }
                                }

                                if (Settings.ShowDescriptionConfidence)
                                {
                                    baseDescription = $"{baseDescription} ({Math.Round(filteredDescription.Confidence, 2)})";
                                }

                                try
                                {
                                    // If there is one or more faces, asks the service information about them.
                                    if (IsEmotionServiceRegistered && result.Faces?.Count() > 0)
                                    {
                                        StatusMessage = AppResources.RecognizingFaces;
                                        var messages = new StringBuilder();

                                        foreach (var face in result.Faces)
                                        {
                                            using (var ms = new MemoryStream(imageBytes))
                                            {
                                                var emotions = await emotionService.RecognizeAsync(ms, face.FaceRectangle.ToRectangle());

                                                var bestEmotion = emotions.FirstOrDefault()?.Scores.GetBestEmotion();

                                                // Creates the emotion description text to be speeched (if there are interesting information).
                                                var emotionMessage = SpeechHelper.GetEmotionMessage(face, bestEmotion, includeAge: Settings.GuessAge);
                                                if (!string.IsNullOrWhiteSpace(emotionMessage))
                                                {
                                                    messages.Append(emotionMessage);
                                                }
                                            }
                                        }

                                        // Checks if at least one emotion has been actually recognized.
                                        if (messages.Length > 0)
                                        {
                                            // Describes how many faces have been recognized.
                                            if (result.Faces.Count() == 1)
                                            {
                                                facesRecognizedDescription = AppResources.FaceRecognizedSingular;
                                            }
                                            else
                                            {
                                                facesRecognizedDescription = $"{string.Format(AppResources.FacesRecognizedPlural, result.Faces.Count())} {Constants.SentenceEnd}";
                                            }

                                            emotionDescription = messages.ToString();
                                        }
                                    }
                                }
                                catch (Microsoft.ProjectOxford.Common.ClientException ex) when(ex.Error.Code.ToLower() == "unauthorized")
                                {
                                    // Unable to access the service (tipically, due to invalid registration keys).
                                    baseDescription = AppResources.UnableToAccessService;
                                }
                                catch
                                { }
                            }
                            else
                            {
                                if (Settings.ShowRawDescriptionOnInvalidRecognition && originalDescription != null)
                                {
                                    baseDescription = $"{AppResources.RecognitionFailed} ({originalDescription.Text}, {Math.Round(originalDescription.Confidence, 2)})";
                                }
                                else
                                {
                                    baseDescription = AppResources.RecognitionFailed;
                                }
                            }
                        }
                        else
                        {
                            // Internet isn't available, the service cannot be reached.
                            baseDescription = AppResources.NoConnection;
                        }
                    }
                    else
                    {
                        baseDescription = AppResources.UnableToTakePhoto;
                    }
                }
            }
            catch (WebException)
            {
                // Internet isn't available, the service cannot be reached.
                baseDescription = AppResources.NoConnection;
            }
            catch (ClientException)
            {
                // Unable to access the service (tipically, due to invalid registration keys).
                baseDescription = AppResources.UnableToAccessService;
            }
            catch (Exception ex)
            {
                var error = AppResources.RecognitionError;

                if (Settings.ShowExceptionOnError)
                {
                    error = $"{error} ({ex.Message})";
                }

                baseDescription = error;
            }

            // Shows and speaks the result.
            var message = $"{baseDescription}{Constants.SentenceEnd} {facesRecognizedDescription} {emotionDescription}";

            StatusMessage = this.GetNormalizedMessage(message);

            await SpeechHelper.TrySpeechAsync(message);

            IsBusy = false;
        }
예제 #54
0
        public virtual void CheckTransaction(Network network, ConsensusOptions options, Transaction tx)
        {
            // Basic checks that don't depend on any context.
            if (tx.Inputs.Count == 0)
            {
                this.Logger.LogTrace("(-)[TX_NO_INPUT]");
                ConsensusErrors.BadTransactionNoInput.Throw();
            }

            if (tx.Outputs.Count == 0)
            {
                this.Logger.LogTrace("(-)[TX_NO_OUTPUT]");
                ConsensusErrors.BadTransactionNoOutput.Throw();
            }

            // Size limits (this doesn't take the witness into account, as that hasn't been checked for malleability).
            if (tx.GetSize(TransactionOptions.None, network.Consensus.ConsensusFactory) > options.MaxBlockBaseSize)
            {
                this.Logger.LogTrace("(-)[TX_OVERSIZE]");
                ConsensusErrors.BadTransactionOversize.Throw();
            }

            // Check for negative or overflow output values
            long valueOut = 0;

            foreach (TxOut txout in tx.Outputs)
            {
                if (txout.Value.Satoshi < 0)
                {
                    this.Logger.LogTrace("(-)[TX_OUTPUT_NEGATIVE]");
                    ConsensusErrors.BadTransactionNegativeOutput.Throw();
                }

                if (txout.Value.Satoshi > network.Consensus.MaxMoney)
                {
                    this.Logger.LogTrace("(-)[TX_OUTPUT_TOO_LARGE]");
                    ConsensusErrors.BadTransactionTooLargeOutput.Throw();
                }

                valueOut += txout.Value;
                if (!this.MoneyRange(network.Consensus, valueOut))
                {
                    this.Logger.LogTrace("(-)[TX_TOTAL_OUTPUT_TOO_LARGE]");
                    ConsensusErrors.BadTransactionTooLargeTotalOutput.Throw();
                }
            }

            // Check for duplicate inputs.
            var inOutPoints = new HashSet <OutPoint>();

            foreach (TxIn txin in tx.Inputs)
            {
                if (inOutPoints.Contains(txin.PrevOut))
                {
                    this.Logger.LogTrace("(-)[TX_DUP_INPUTS]");
                    ConsensusErrors.BadTransactionDuplicateInputs.Throw();
                }

                inOutPoints.Add(txin.PrevOut);
            }

            if (tx.IsCoinBase)
            {
                if ((tx.Inputs[0].ScriptSig.Length < 2) || (tx.Inputs[0].ScriptSig.Length > 100))
                {
                    this.Logger.LogTrace("(-)[BAD_COINBASE_SIZE]");
                    ConsensusErrors.BadCoinbaseSize.Throw();
                }
            }
            else
            {
                foreach (TxIn txin in tx.Inputs)
                {
                    if (txin.PrevOut.IsNull)
                    {
                        this.Logger.LogTrace("(-)[TX_NULL_PREVOUT]");
                        ConsensusErrors.BadTransactionNullPrevout.Throw();
                    }
                }
            }
        }
예제 #55
0
 static TestBase()
 {
     AssertionHandler.CatchAssertions();
     NodeConfiguration.Initialize(LocalNetwork.Instance.Name, "");
     Network = NodeConfiguration.GetNetwork();
 }
예제 #56
0
 public BitcoinScriptAddress(string address, Network expectedNetwork)
     : base(address, expectedNetwork)
 {
 }
예제 #57
0
 public ChainTests()
 {
     this.network     = KnownNetworks.Main;
     this.networkTest = KnownNetworks.TestNet;
 }
예제 #58
0
        private void button26_Click(object sender, EventArgs e)
        {
            string[] nombres = { "Vacio", "Torres", "Caballos", "Alfiles", "Reinas", "Reyes", "Peones" };

            //ActivationNetwork rna = EntrenarRNA();

            // rna.Save("save1.rna");
            // para cada imagen en la direccion de entrenamiento
            DirectoryInfo sc = new DirectoryInfo(rutaEjemplos);

            FileInfo[] s = sc.GetFiles();
            Bitmap[,] Matzs = null;
            double[][] Carz = new double[8 * 8][];
            double[]   Obj  =
            {
                1, 2, 3, 4, 5, 3, 2, 1,
                6, 6, 6, 6, 6, 6, 6, 6,
                0, 0, 0, 0, 0, 0, 0, 0,
                0, 0, 0, 0, 0, 0, 0, 0,
                0, 0, 0, 0, 0, 0, 0, 0,
                0, 0, 0, 0, 0, 0, 0, 0,
                6, 6, 6, 6, 6, 6, 6, 6,
                1, 2, 3, 4, 5, 3, 2, 1,
            };

            for (int k = 0; k < 64; k++)
            {
                Carz[k] = new double[6];
            }

            int b = 0;

            foreach (FileInfo imgEjemp in s)
            {
                ImagenEntrada.Image           = PictureAnalizer.ImagenColor2Gray((Bitmap)Image.FromFile(imgEjemp.FullName));
                PictureAnalizer.ImagenEntrada = (Bitmap)ImagenEntrada.Image;

                Mascara mX = new Mascara(Mascara.PRDF_Opdr_LPcX, new Size(3, 3), new Point(1, 1));
                Mascara mY = new Mascara(Mascara.PRDF_Opdr_LpcY, new Size(3, 3), new Point(1, 1));

                ImagenEntrada.Image = PictureAnalizer.DetectarBordes(mX, mY, 0, (Bitmap)ImagenEntrada.Image);
                ImagenEntrada.Image.Save(@"C:\Users\frodo\Desktop\ejemplos - copia\" + "imgBorde" + b.ToString() + ".jpeg");
                b++;


                Matzs = PictureAnalizer.DividirImagen((Bitmap)ImagenEntrada.Image, 8);
                ImagenEntrada.Refresh();
                System.Threading.Thread.Sleep(1000);


                int n = 0;
                for (int i = 0; i < 8; i++)
                {
                    for (int j = 0; j < 8; j++)
                    {
                        Bitmap im = Matzs[j, i];
                        ImagenEntrada.Image = im;
                        int           p      = (int)Obj[n];
                        string        dir    = "Piesas/" + nombres[p] + "/";
                        DirectoryInfo dest   = new DirectoryInfo(dir);
                        FileInfo[]    infDir = dest.GetFiles();
                        switch (p)
                        {
                        case 0: im.Save(dir + nombres[p] + infDir.Length + ".jpeg"); break;

                        case 1: im.Save(dir + nombres[p] + infDir.Length + ".jpeg"); break;

                        case 2: im.Save(dir + nombres[p] + infDir.Length + ".jpeg"); break;

                        case 3: im.Save(dir + nombres[p] + infDir.Length + ".jpeg"); break;

                        case 4: im.Save(dir + nombres[p] + infDir.Length + ".jpeg"); break;

                        case 5: im.Save(dir + nombres[p] + infDir.Length + ".jpeg"); break;

                        case 6: im.Save(dir + nombres[p] + infDir.Length + ".jpeg"); break;
                        }

                        Carz[n] = PictureAnalizer.CalcularCaracteristicasTextura(im);


                        for (int v = 0; v < Carz[n].Length; v++)
                        {
                            Console.WriteLine(Carz[n][v]);
                        }



                        ImagenEntrada.Refresh();
                        System.Threading.Thread.Sleep(100);
                        n++;
                    }
                }
            }



            List <Bitmap[]>   ListaEntradas = new List <Bitmap[]>();
            List <double[][]> ListaCarz     = new List <double[][]>();
            double            carTota       = 0;

            for (int k = 0; k < 7; k++)
            {
                ListaEntradas.Add(new Bitmap[1]);
                ListaCarz.Add(new double[6][]);
            }


            string[] rutasInternas = Directory.GetDirectories("Piesas/");
            for (int i = 0; i < rutasInternas.Length; i++)
            {
                string        ruta      = rutasInternas[i];
                string[]      rutaSgmnt = ruta.Split('/');
                int           indx      = Array.IndexOf(nombres.ToArray(), rutaSgmnt[1]);
                DirectoryInfo infDir    = new DirectoryInfo(ruta);
                FileInfo[]    infFile   = infDir.GetFiles("*.jpeg", SearchOption.AllDirectories);
                Bitmap[]      imgArr    = new Bitmap[infFile.Length];
                double[][]    carArr    = new double[infFile.Length][];
                carTota += infFile.Length;

                for (int j = 0; j < imgArr.Length; j++)
                {
                    imgArr[j] = (Bitmap)Image.FromFile(infFile[j].FullName);
                    carArr[j] = PictureAnalizer.CalcularCaracteristicasTextura(imgArr[j]);
                }

                ListaEntradas[indx] = imgArr;
                ListaCarz[indx]     = carArr;
            }

            double[][] lSalidas = new double[(int)carTota][];

            // { "Vacio", "Torres", "Caballos","Alfiles", "Reinas", "Reyes", "Peones" };


            int c = 2;

            double[][] MatEntr = new double[(int)carTota][];
            int        t       = 0;
            int        pi      = 0;

            foreach (double[][] Mat in ListaCarz)
            {
                foreach (double[] vector in Mat)
                {
                    MatEntr[t] = vector;

                    switch (pi)
                    {
                    case 0: lSalidas[t] = new double[] { 0, 0, 0, 0 }; break;

                    case 1: lSalidas[t] = new double[] { 0, 0, 0, 1 }; break;

                    case 2: lSalidas[t] = new double[] { 0, 0, 1, 0 }; break;

                    case 3: lSalidas[t] = new double[] { 0, 0, 1, 1 }; break;

                    case 4: lSalidas[t] = new double[] { 0, 1, 0, 0 }; break;

                    case 5: lSalidas[t] = new double[] { 0, 1, 0, 1 }; break;

                    case 6: lSalidas[t] = new double[] { 0, 1, 1, 0 }; break;
                    }

                    t++;
                }
                pi++;
            }

            ActivationNetwork rna = null;

            if (!Directory.Exists("rnsa.rna"))
            {
                rna = CrearRNA(MatEntr, lSalidas);
                rna.Save("rnsa.rna");
            }
            else
            {
                rna = (ActivationNetwork)Network.Load("rnsa.rna");
            }

            Bitmap [] ns = ListaEntradas[0];
            foreach (Bitmap x in ns)
            {
                double [] text = rna.Compute(PictureAnalizer.CalcularCaracteristicasTextura(x));



                int l = 0;
                for (int f = 0; f < text.Length; f++)
                {
                    if (text[f] == 1)
                    {
                        l += (int)Math.Pow(2, f);
                    }
                }
                Console.Write(l + " ");
            }



            // generar arbol
            nodo r = new nodo(8, "s");

            arbol a1 = new arbol();

            r.tablero = a1.TabEjemplo;
            a1.raiz   = r;

            arbol a2 = new arbol();

            r.tablero = a2.TabEjemplo;
            a2.raiz   = r;
            imprimirTablero(r);

            nodo n1 = a1.generarMovimientos(a1.raiz, arbol.ColorBlanco);

            imprimirTablero(n1);


            for (int i = 0; i < 10; i++)
            {
                n1 = a1.generarMovimientos(n1, arbol.ColorBlanco);
                imprimirTablero(n1);

                nodo n2 = a2.generarMovimientos(n1, arbol.ColorNegroo);
                imprimirTablero(n2);

                n1 = n2;
            }
        }
 public ConsensusManagerTests()
 {
     this.powNetwork = new BitcoinRegTest();
 }
예제 #60
-1
 public OpenchainClient(NBitcoin.Key openChainKey, string assetName, Uri openChainUri, Network network)
 {
     this.openChainKey = openChainKey;
     this.assetName = assetName;
     this.openChainUri = openChainUri;
     this.network = network;
 }