コード例 #1
0
        public virtual String toPPString()
        {
            StringBuilder buf = new StringBuilder();
            IEnumerator   itr = value_Renamed.GetEnumerator();

            buf.Append("    (" + name + " ");
            int count = 0;

            while (itr.MoveNext())
            {
                MultiValue mv = (MultiValue)itr.Current;
                if (count > 0)
                {
                    buf.Append("&");
                }
                if (mv.Negated)
                {
                    buf.Append("~" + ConversionUtils.formatSlot(mv.Value));
                }
                else
                {
                    buf.Append(ConversionUtils.formatSlot(mv.Value));
                }
                count++;
            }
            buf.Append(")" + Constants.LINEBREAK);
            return(buf.ToString());
        }
コード例 #2
0
ファイル: Decoder.cs プロジェクト: justenau/ReedMullerCode
        /// <summary>
        /// Decodes vector using Fast Hadamard Transform.
        /// 0s in the vector are changed to '-1', then the encoded vector is multiplied with H matrixes and the results
        /// and summed up together. The index of the highest absolute value in the sum vector is used for decoding.
        /// Index value is transformed to reversed binary number with '1' in front of it the highest value
        /// was positive and '0' if it was negative. The final vector is the decoded vector.
        /// </summary>
        /// <param name="vector">Encoded vector</param>
        /// <param name="m">Code parameter m</param>
        /// <returns>Decoded vector</returns>
        public static Vector DecodeSingleVector(Vector vector, int m)
        {
            var transformedVector = vector.TranformBitsFromZeroToMinusOne();

            // Multiply vector with H matrixes and sum up the results to a single vector
            for (int i = 1; i <= m; i++)
            {
                var calculationMatrix = HadamardTransformMatrix.GetTransformMatrix(i, m);
                transformedVector = MatrixUtils.MutltiplyVectorWithMatrix(transformedVector, calculationMatrix, Convert.ToInt32(Math.Pow(2, m)));
            }

            // Get the index of the highest absolute value in the vector and convert it to binary representation
            var vectorDataAbsValues = transformedVector.Data.Select(x => Math.Abs(x)).ToList();
            var maxPosition         = vectorDataAbsValues.IndexOf(vectorDataAbsValues.Max());
            var reversedBinaryValue = Convert.ToString(maxPosition, 2);

            var zerosToAddCount = m - reversedBinaryValue.Length;

            if (zerosToAddCount != 0)
            {
                reversedBinaryValue = new string('0', zerosToAddCount) + reversedBinaryValue;
            }

            // Add the first digit, based on if the highest value was positive or negative
            reversedBinaryValue += transformedVector.Data[maxPosition] < 0 ? '0' : '1';

            var binaryValue = reversedBinaryValue.ToCharArray();

            Array.Reverse(binaryValue);
            var decodedVectorData = ConversionUtils.ConvertStringToIntegerArray(new string(binaryValue));

            return(new Vector(decodedVectorData));
        }
コード例 #3
0
        private byte[] HandleMessage(TcpClient client, byte[] data)
        {
            int i = 0;

            NetworkStream networkStream = client.GetStream();

            byte[] respData = new byte[_maxResponseBufferSize];

            if (data.Length > 0)
            {
                _messageWriter.WriteLine("--->Recvd {0} bytes from client", data.Length);
                _messageWriter.WriteLine(ConversionUtils.ConvertToString(data));

                //write new data from client to socket
                networkStream.Write(data, 0, data.Length);
            }

            try
            {
                if (networkStream.DataAvailable)
                {
                    i = networkStream.Read(respData, 0, respData.Length);
                    _messageWriter.WriteLine("Read Resp: {0}", i);
                }
            }
            catch (Exception except)
            {
                _messageWriter.WriteLine("Error: {0}", except.Message);
            }

            Array.Resize(ref respData, i);

            return(respData);
        }
コード例 #4
0
 public List <DenormalisedRecord> ToDenormalisedRecord(Domain.Dmarc.AggregateReport aggregateReport, string originalUri)
 {
     return(aggregateReport.Records.Select(record => new DenormalisedRecord(
                                               originalUri,
                                               aggregateReport.ReportMetadata?.OrgName,
                                               aggregateReport.ReportMetadata?.Email,
                                               aggregateReport.ReportMetadata?.ExtraContactInfo,
                                               ConversionUtils.UnixTimeStampToDateTime(aggregateReport.ReportMetadata.Range.Begin),
                                               ConversionUtils.UnixTimeStampToDateTime(aggregateReport.ReportMetadata.Range.End),
                                               aggregateReport.PolicyPublished?.Domain,
                                               aggregateReport.PolicyPublished?.Adkim,
                                               aggregateReport.PolicyPublished?.Aspf,
                                               aggregateReport.PolicyPublished.P,
                                               aggregateReport.PolicyPublished?.Sp,
                                               aggregateReport.PolicyPublished?.Pct,
                                               record.Row?.SourceIp,
                                               record.Row.Count,
                                               record.Row?.PolicyEvaluated?.Disposition,
                                               record.Row?.PolicyEvaluated?.Dkim,
                                               record.Row.PolicyEvaluated.Spf,
                                               record.Row?.PolicyEvaluated?.Reasons != null ? string.Join(",", record.Row?.PolicyEvaluated?.Reasons.Select(_ => _.PolicyOverride.ToString())) : null,
                                               record.Row?.PolicyEvaluated?.Reasons != null ? string.Join(",", record.Row?.PolicyEvaluated?.Reasons.Where(_ => _.Comment != null).Select(_ => _.Comment.ToString())) : null,
                                               record.Identifiers?.EnvelopeTo,
                                               record.Identifiers?.HeaderFrom,
                                               record.AuthResults?.Dkim != null ? string.Join(",", record.AuthResults?.Dkim.Where(_ => _.Domain != null).Select(_ => _.Domain)) : null,
                                               record.AuthResults?.Dkim != null ? string.Join(",", record.AuthResults?.Dkim.Select(_ => _.Result)) : null,
                                               record.AuthResults?.Dkim != null ? string.Join(",", record.AuthResults?.Dkim.Where(_ => _.HumanResult != null).Select(_ => _.HumanResult)) : null,
                                               record.AuthResults?.Spf != null ? string.Join(",", record.AuthResults?.Spf.Where(_ => _.Domain != null).Select(_ => _.Domain)) : null,
                                               record.AuthResults?.Spf != null ? string.Join(",", record.AuthResults?.Spf.Select(_ => _.Result)) : null)).ToList());
 }
コード例 #5
0
 public AggregateReportEntity Convert(AggregateReportInfo aggregateReport)
 {
     return(new AggregateReportEntity
     {
         RequestId = aggregateReport.EmailMetadata.RequestId,
         OrginalUri = aggregateReport.EmailMetadata.OriginalUri,
         AttachmentFilename = aggregateReport.AttachmentMetadata.Filename,
         Version = aggregateReport.AggregateReport.Version,
         OrgName = aggregateReport.AggregateReport.ReportMetadata?.OrgName,
         ReportId = aggregateReport.AggregateReport.ReportMetadata.ReportId,
         Email = aggregateReport.AggregateReport.ReportMetadata?.Email,
         ExtraContactInfo = aggregateReport.AggregateReport.ReportMetadata?.ExtraContactInfo,
         BeginDate = ConversionUtils.UnixTimeStampToDateTime(aggregateReport.AggregateReport.ReportMetadata.Range.Begin),
         EndDate = ConversionUtils.UnixTimeStampToDateTime(aggregateReport.AggregateReport.ReportMetadata.Range.End),
         EffectiveDate = ConversionUtils.UnixTimeStampToDateTime(aggregateReport.AggregateReport.ReportMetadata.Range.EffectiveDate),
         Domain = aggregateReport.AggregateReport.PolicyPublished?.Domain,
         Adkim = Convert(aggregateReport.AggregateReport.PolicyPublished?.Adkim),
         Aspf = Convert(aggregateReport.AggregateReport.PolicyPublished?.Aspf),
         P = Convert(aggregateReport.AggregateReport.PolicyPublished.P),
         Sp = Convert(aggregateReport.AggregateReport.PolicyPublished?.Sp),
         Pct = aggregateReport.AggregateReport.PolicyPublished?.Pct,
         Fo = aggregateReport.AggregateReport.PolicyPublished.Fo,
         Records = aggregateReport.AggregateReport.Records?.Select(ConvertToEntity).ToList()
     });
 }
コード例 #6
0
 /// <summary>
 /// Pick the shape in the view. Use helper function trace the local bounding box.
 /// </summary>
 /// <param name="rayStart">trace ray start</param>
 /// <param name="rayEnd">trace ray end</param>
 /// <param name="result">esult structure to fill in</param>
 public override void OnTraceShape(ShapeTraceMode_e mode, Vector3F rayStart, Vector3F rayEnd, ref ShapeTraceResult result)
 {
     if (ConversionUtils.TraceOrientedBoundingBox(LocalBoundingBox, Position, RotationMatrix, rayStart, rayEnd, ref result))
     {
         result.hitShape = this;
     }
 }
コード例 #7
0
        private void Tunnel_DataReceived(object sender, DataReceivedEventArgs e)
        {
            byte[] data     = e.Data;
            string response = ConversionUtils.ConvertToString(data);

            _messageWriter.WriteLine("Response from Server: " + response);
        }
コード例 #8
0
ファイル: RokuRemote.cs プロジェクト: yozepi/Roku.Net
        public async Task <ActiveAppInfo> GetActiveAppAsync()
        {
            var request = _requestFactory.Create();

            using (var response = await request.GetResponseAsync(UrlUtils.ActiveAppUrlFor(this.Url), "GET"))
            {
                ActiveAppInfo result = null;
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    result = new ActiveAppInfo
                    {
                        IsSuccess         = false,
                        StatusCode        = response.StatusCode,
                        StatusDescription = response.StatusDescription
                    };
                }
                else
                {
                    result                   = ConversionUtils.XmlToInstance <ActiveAppInfo>(response.GetResponseStream());
                    result.IsSuccess         = true;
                    result.StatusCode        = response.StatusCode;
                    result.StatusDescription = response.StatusDescription;
                }
                return(result);
            }
        }
コード例 #9
0
        static void Main(string[] args)
        {
            Console.WriteLine("Escreva o alfabeto separado por virgula: ");
            string operands = Console.ReadLine();

            Console.WriteLine("Escreva uma ER: ");
            string er = Console.ReadLine();

            Thompson t = new Thompson(ConversionUtils.ToPostFix(er, operands.Split(',').ToList()));

            t.Resolve();
            Graph graphInitial = t.Graph;

            AFD afd = new AFD(graphInitial, operands.Split(','));

            Console.WriteLine($"\nAutômato Inicial\n{graphInitial.ToString()}");

            Console.WriteLine("AFD Equivalente: ");
            afd.Resolve();
            afd.PrintGraph();
            Graph graphAfd = afd.Graph;

            Console.WriteLine("AFD Minimizado: ");

            AFDMinimize minimize = new AFDMinimize(graphAfd, new string[] { "a", "b" });

            minimize.Resolve();

            Console.WriteLine(minimize.PrintGraph());

            Console.ReadKey();
        }
コード例 #10
0
        static void Main(string[] args)
        {
            try
            {
                Console.WriteLine("Projeto 02\nAlfabeto separado por (,):");
                string operands = Console.ReadLine();
                Console.WriteLine("\nExpressão Regular válida: ");
                string regularExpression = Console.ReadLine();

                Input input = new Input(operands.Split(','), regularExpression);

                InputUtils inputUtils = new InputUtils(input);

                if (inputUtils.Validate())
                {
                    Thompson thompson = new Thompson(ConversionUtils.ToPostFix(input.RegularExpression, input.Operands));
                    thompson.Resolve();
                    thompson.PrintGraph().ForEach(o => { Console.WriteLine(o); });
                }

                else
                {
                    throw new Exception("O autômato não possui entradas válidas.");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Erro ao gerar autômato: {ex.Message}");
            }
            finally
            {
                Console.ReadKey();
            }
        }
コード例 #11
0
        public void SetStringValue([CanBeNull] string value,
                                   [CanBeNull] CultureInfo cultureInfo = null)
        {
            if (cultureInfo == null)
            {
                cultureInfo = CultureInfo.CurrentCulture;
            }

            if (Equals(_formattedStringValue, value) &&
                Equals(cultureInfo, _formattedStringValueCulture))
            {
                return;
            }

            Assert.NotNull(DataType, "Parameter data type not defined");

            // verify that the string value can be cast to the correct data type, assuming it is in
            // the current culture.
            _formattedStringValueCulture = cultureInfo;

            object castValue;

            if (!ConversionUtils.TryParseTo(DataType, value,
                                            _formattedStringValueCulture,
                                            out castValue))
            {
                throw new ArgumentException(
                          $"Invalid parameter value for {TestParameterName}: {value}");
            }

            _formattedStringValue = value;
            _stringValue          = GetStringValueInPersistedCulture(castValue);
        }
コード例 #12
0
        private void CompareStringVsFloatJSON()
        {
            float[]       weights = new float[10000];
            StringBuilder builder = new StringBuilder();

            for (int i = 0; i < weights.Length; i++)
            {
                float val = UnityEngine.Random.Range(-3f, 3f);
                builder.Append(ConversionUtils.FloatToString(val));
                weights[i] = val;
            }

            JObject floatJSON = new JObject();

            floatJSON["weights"] = new JArray(weights);

            JObject stringJSON = new JObject();

            stringJSON["weights"] = builder.ToString();

            string floatOutputPath  = string.Format("/Users/Keiwan/Desktop/{0}_floats.json", weights.Length);
            string stringOutputPath = string.Format("/Users/Keiwan/Desktop/{0}_string.json", weights.Length);

            File.WriteAllText(floatOutputPath, floatJSON.ToString(Formatting.None));
            File.WriteAllText(stringOutputPath, stringJSON.ToString(Formatting.None));
        }
コード例 #13
0
        private void _pollTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            List <byte> data = new List <byte>();
            IEnumerable <TwitterDirectMessage> directMessages;

            System.Console.Write(_service.GetRateLimitStatus().RemainingHits);
            if (_lastMessageReceivedId != -1)
            {
                directMessages = _service.ListDirectMessagesReceivedSince(_lastMessageReceivedId);
            }
            else
            {
                directMessages = _service.ListDirectMessagesReceived();
            }
            foreach (TwitterDirectMessage directMessage in directMessages)
            {
                data.AddRange(ConversionUtils.ConvertToBytes(directMessage.Text));
            }

            if (data.Count > 0)
            {
                if (DataReceived != null)
                {
                    DataReceived(this, new DataReceivedEventArgs(data.ToArray()));
                }
            }
        }
コード例 #14
0
        public override void ExecuteCmdlet()
        {
            ExecutionBlock(() =>
            {
                base.ExecuteCmdlet();

                ResourceIdentifier resourceIdentifier = new ResourceIdentifier(VaultId);
                string vaultName         = resourceIdentifier.ResourceName;
                string resourceGroupName = resourceIdentifier.ResourceGroupName;

                string backupManagementType = "";
                string workloadType         = "";
                string containerName        = "";
                if (ParameterSetName == IdParamSet)
                {
                    Dictionary <UriEnums, string> keyValueDict = HelperUtils.ParseUri(ParentID);
                    containerName = HelperUtils.GetContainerUri(keyValueDict, ParentID);
                    if (containerName.Split(new string[] { ";" }, System.StringSplitOptions.None)[0].ToLower() == "vmappcontainer")
                    {
                        backupManagementType = ServiceClientModel.BackupManagementType.AzureWorkload;
                    }
                    string protectableItem = HelperUtils.GetProtectableItemUri(keyValueDict, ParentID);
                    if (protectableItem.Split(new string[] { ";" }, System.StringSplitOptions.None)[0].ToLower() == "sqlinstance" ||
                        protectableItem.Split(new string[] { ";" }, System.StringSplitOptions.None)[0].ToLower() == "sqlavailabilitygroupcontainer")
                    {
                        workloadType = ServiceClientModel.WorkloadType.SQLDataBase;
                    }
                }
                else
                {
                    backupManagementType = Container.BackupManagementType.ToString();
                    workloadType         = ConversionUtils.GetServiceClientWorkloadType(WorkloadType.ToString());
                    containerName        = Container.Name;
                }
                ODataQuery <BMSPOQueryObject> queryParam = new ODataQuery <BMSPOQueryObject>(
                    q => q.BackupManagementType
                    == backupManagementType &&
                    q.WorkloadType == workloadType &&
                    q.ContainerName == containerName);

                WriteDebug("going to query service to get list of protectable items");
                List <WorkloadProtectableItemResource> protectableItems =
                    ServiceClientAdapter.ListProtectableItem(
                        queryParam,
                        vaultName: vaultName,
                        resourceGroupName: resourceGroupName);
                WriteDebug("Successfully got response from service");
                List <ProtectableItemBase> itemModels = ConversionHelpers.GetProtectableItemModelList(protectableItems);

                if (ParameterSetName == FilterParamSet)
                {
                    string protectableItemType = ItemType.ToString();
                    itemModels = itemModels.Where(itemModel =>
                    {
                        return(((AzureWorkloadProtectableItem)itemModel).ProtectableItemType == protectableItemType);
                    }).ToList();
                }
                WriteObject(itemModels, enumerateCollection: true);
            });
        }
コード例 #15
0
        public void CanRecognizeValidGuidsFastEnough()
        {
            // call once to make sure the regex is compiled (happens on first call)
            ConversionUtils.IsValidGuid(Guid.NewGuid().ToString());

            const int    count           = 100000;
            const double maxMilliseconds = 200;

            var guids = new List <string>(count);

            for (int i = 0; i < count; i++)
            {
                guids.Add(Guid.NewGuid().ToString());
            }

            var watch = new Stopwatch();

            watch.Start();

            foreach (string guidString in guids)
            {
                bool valid = ConversionUtils.IsValidGuid(guidString);
                if (!valid)
                {
                    Assert.Fail("guid not recognized as valid: {0}", guidString);
                }
            }

            watch.Stop();

            Console.Out.WriteLine("Generating {0} guids took {1:N0} ms", count,
                                  watch.ElapsedMilliseconds);

            Assert.Less(watch.ElapsedMilliseconds, maxMilliseconds, "guid validation too slow");
        }
        public override List <object> Create(AggregateReportInfo aggregateReportInfo)
        {
            DateTime      effectiveDate = ConversionUtils.UnixTimeStampToDateTime(aggregateReportInfo.AggregateReport.ReportMetadata.Range.EffectiveDate);
            List <string> ipAddresses   = aggregateReportInfo.AggregateReport.Records.Select(_ => _.Row.SourceIp).Distinct().ToList();

            return(ipAddresses
                   .Batch(IpBatchSize)
                   .Select(_ => new AggregateReportIpAddresses(aggregateReportInfo.EmailMetadata.RequestId, aggregateReportInfo.EmailMetadata.MessageId, effectiveDate, _.ToList()))
                   .Cast <object>()
                   .ToList());
        }
コード例 #17
0
 public void TestCanCreateCompatListFrom()
 {
     Assert.False(ConversionUtils.CanCreateCompatListFor(null));
     Assert.False(ConversionUtils.CanCreateCompatListFor(typeof(IList <>)));
     Assert.True(ConversionUtils.CanCreateCompatListFor(typeof(IList <string>)));
     Assert.True(ConversionUtils.CanCreateCompatListFor(typeof(List <string>)));
     Assert.False(ConversionUtils.CanCreateCompatListFor(typeof(List <>)));
     Assert.False(ConversionUtils.CanCreateCompatListFor(typeof(LinkedList <int>)));
     Assert.True(ConversionUtils.CanCreateCompatListFor(typeof(Collection <int>)));
     Assert.True(ConversionUtils.CanCreateCompatListFor(typeof(ArrayList)));
 }
コード例 #18
0
ファイル: VectorView.cs プロジェクト: justenau/ReedMullerCode
        /// <summary>
        /// Send encoded vector through the channel with provided error probability p.
        /// </summary>
        private void SendBtn_Click(object sender, EventArgs e)
        {
            var p = panel.P;

            ReceivedVector = Channel.SendBinaryMessage(EncodedVector, p, out List <int> distortedPlaces);

            receivedVectorField.Text   = ConversionUtils.ConvertIntegerArrayToString(ReceivedVector.Data);
            distortionPlaceholder.Text = string.Join(",", distortedPlaces);
            ChangeDecodingFieldVisibility(true);
            ChangeDecodedFieldVisibility(false);
        }
コード例 #19
0
        private static void AssertValidGuid(string guidString)
        {
            Console.WriteLine(guidString);

            Assert.IsTrue(ConversionUtils.IsValidGuid(guidString));

            string upper = guidString.ToUpper();

            Console.WriteLine(upper);

            Assert.IsTrue(ConversionUtils.IsValidGuid(upper));
        }
コード例 #20
0
    /// <summary>
    /// Loads the simulation from save file with the format version 2
    /// </summary>
    /// <param name="name">The name of the simulation save.</param>
    /// <param name="content">The Content of the save file.</param>
    public static SimulationData ParseSimulationData(string name, string content, LegacySimulationLoader.SplitOptions splitOptions)
    {
        var creatureName = name.Split('-')[0].Replace(" ", "");

        if (string.IsNullOrEmpty(creatureName))
        {
            creatureName = "Unnamed";
        }

        var components = content.Split(splitOptions.SPLIT_ARRAY, System.StringSplitOptions.None);

        var simulationSettings = SimulationSettings.Decode(components[1]);
        var networkSettings    = NeuralNetworkSettings.Decode(components[2]);

        var creatureData   = components[3];
        var creatureDesign = CreatureSerializer.ParseCreatureDesign(creatureData);

        creatureDesign.Name = creatureName;

        var bestChromosomesData = new List <string>(components[4].Split(splitOptions.NEWLINE_SPLIT, StringSplitOptions.None));
        var bestChromosomes     = new List <ChromosomeData>();

        foreach (var chromosomeData in bestChromosomesData)
        {
            if (chromosomeData != "")
            {
                var stats = ChromosomeStats.FromString(chromosomeData);
                var data  = new StringChromosomeData(stats.chromosome, stats.stats);
                bestChromosomes.Add(data.ToChromosomeData());
            }
        }

        var chromosomeComponents = components[5].Split(splitOptions.NEWLINE_SPLIT, StringSplitOptions.None);
        var currentChromosomes   = new List <float[]>();

        foreach (var chromosome in chromosomeComponents)
        {
            if (chromosome != "")
            {
                currentChromosomes.Add(ConversionUtils.BinaryStringToFloatArray(chromosome));
            }
        }

        var sceneDescription = DefaultSimulationScenes.DefaultSceneForObjective(simulationSettings.Objective);

        sceneDescription.PhysicsConfiguration = ScenePhysicsConfiguration.Legacy;

        return(new SimulationData(
                   simulationSettings, networkSettings, creatureDesign,
                   sceneDescription, bestChromosomes, currentChromosomes.ToArray(),
                   bestChromosomes.Count
                   ));
    }
コード例 #21
0
        /// <summary>
        /// When "Send" button is clicked, a new thread is run not to block the main thread.
        /// "Send" button is disabled until the thread finished its job.
        /// Input image is converted to vectors, which are sent through the channel with provided
        /// error probability p. Image vectors are sent two ways - encoded and later decoded after receiving them
        /// from the channel and not encoded.
        /// </summary>
        private void SendImageBtn_Click(object sender, EventArgs e)
        {
            panel.SendBtn.Enabled = false;
            new Thread(() =>
            {
                var p = panel.P;

                // Convert image to vectors and separate the header (it is not sent through the channel)
                var bitmapToVector     = new Vector(ConversionUtils.ConvertBitmapToIntArray(UploadedImage));
                var bitmapHeader       = bitmapToVector.Data.Take(54 * 8);
                var bitmapVectorToSend = new Vector(bitmapToVector.Data.Skip(54 * 8).ToArray());

                try
                {
                    // Encode input image vectors
                    var encodedVector = Encoder.EncodeBinarySequence(bitmapVectorToSend, M, out int additionalBits);

                    // Send (not)encoded vectors through the channel
                    var receivedNotEncoded = Channel.SendBinaryMessage(bitmapVectorToSend, p, out _);
                    var receivedEncoded    = Channel.SendBinaryMessage(encodedVector, p, out _);

                    // Decode received encoded vectors
                    var decoded = Decoder.DecodeBinarySequence(receivedEncoded, M);

                    DeconvertedNotEncoded = ConversionUtils.ConvertIntArrayToImage(bitmapHeader.Concat(receivedNotEncoded.Data).ToArray());
                    DeconvertedEncoded    = ConversionUtils.ConvertIntArrayToImage(bitmapHeader.Concat(decoded.Data).ToArray(), additionalBits);
                }
                // Handling 'out of memory' failure
                catch (OutOfMemoryException)
                {
                    MessageBox.Show("System is out of memory!");
                    return;
                }
                // There can be cases where corrupted Bitmap is provided and cannot be reconverted to the image
                catch
                {
                    MessageBox.Show("Corrupted Bitmap has been provided.");
                    this.BeginInvoke((Action)(() =>
                    {
                        panel.SendBtn.Enabled = true;
                        return;
                    }));
                }

                this.BeginInvoke((Action)(() =>
                {
                    notEncodedPicture.Image = DeconvertedNotEncoded;
                    encodedPicture.Image = DeconvertedEncoded;
                    panel.SendBtn.Enabled = true;
                    this.ChangeReceivedControlsVisibility(true);
                }));
            }).Start();
        }
コード例 #22
0
 public void TestCreateList()
 {
     Assert.Null(ConversionUtils.CreateCompatListFor(null));
     Assert.Null(ConversionUtils.CreateCompatListFor(typeof(IList <>)));
     Assert.IsType <List <string> >(ConversionUtils.CreateCompatListFor(typeof(IList <string>)));
     Assert.IsType <List <string> >(ConversionUtils.CreateCompatListFor(typeof(List <string>)));
     Assert.Null(ConversionUtils.CreateCompatListFor(typeof(List <>)));
     Assert.Null(ConversionUtils.CreateCompatListFor(typeof(LinkedList <int>)));
     Assert.IsType <Collection <int> >(ConversionUtils.CreateCompatListFor(typeof(Collection <int>)));
     Assert.IsType <ArrayList>(ConversionUtils.CreateCompatListFor(typeof(ArrayList)));
     Assert.IsType <ArrayList>(ConversionUtils.CreateCompatListFor(typeof(IList)));
 }
コード例 #23
0
        public void Send(byte[] data)
        {
            byte[] messageBuffer = new byte[MAX_MESSAGE_SIZE];
            int    currentIndex  = 0;

            while (currentIndex < data.Length)
            {
                messageBuffer = data.Skip(currentIndex).Take(MAX_MESSAGE_SIZE).ToArray();
                string messageString = ConversionUtils.ConvertToString(messageBuffer);
                _service.SendDirectMessage(_serverUserName, messageString);
                currentIndex += MAX_MESSAGE_SIZE;
            }
        }
コード例 #24
0
        public LabelEditResult CommitLabelEdit(int row, int column, string newText)
        {
            MemberInfo memberInfo = m_Parameters[row];

            if (m_ReadOnly)
            {
                m_VirtualTreeControl.EndLabelEdit(true);
                return(LabelEditResult.CancelEdit);
            }

            bool refreshTree = false;

            if (memberInfo.Member.IsClass)
            {
                refreshTree = true;

                if (newText == NULL_VALUE_TEXT)
                {
                    memberInfo.Value = null;
                }
                else
                {
                    memberInfo.Value = DynamicMethodCompilerCache.CreateInstance(memberInfo.Member.Type);
                }
            }
            else
            {
                try
                {
                    memberInfo.Value = ConversionUtils.ChangeType(newText, memberInfo.Member.Type);
                }
                catch
                {
                    m_VirtualTreeControl.EndLabelEdit(true);
                    return(LabelEditResult.CancelEdit);
                }
            }

            if (refreshTree)
            {
                m_VirtualTreeControl.BeginUpdate();
                m_RelativeRow             = row;
                m_VirtualTree.ListShuffle = true;
                m_VirtualTree.Realign(this);
                m_VirtualTreeControl.EndUpdate();
                m_VirtualTree.ListShuffle = false;
            }
            PropagateValueUpdateEvent();

            return(LabelEditResult.AcceptEdit);
        }
コード例 #25
0
        public void HandleMessages()
        {
            int i;

            Byte[] temp = new Byte[_maxClientBufferSize];
            Byte[] bytes;


            _networkStream = _client.GetStream();

            // Loop to receive all the data sent by the client.
            while (_client.Connected && !_disconnect)
            {
                i = 0;

                try
                {
                    i = _networkStream.Read(temp, 0, temp.Length);
                }
                catch
                {
                    _disconnect = true;
                }


                if (i > 0)
                {
                    bytes = new byte[i + (int)HeaderIndex.HeaderSize];

                    //copy connection number into transmit array.
                    byte[] connNumBytes = BitConverter.GetBytes(_socketId);
                    Array.Copy(connNumBytes, 0, bytes, (int)HeaderIndex.ConnectionNumber, sizeof(UInt16));

                    //copy data from networkstream into transmit array
                    Array.Copy(temp, 0, bytes, (int)HeaderIndex.HeaderSize, i);

                    _messageWriter.WriteLine("--->Sent {0} bytes to server", bytes.Length);
                    _messageWriter.WriteLine(ConversionUtils.ConvertToString(bytes));
                    _tunnel.Send(bytes);
                }
                else
                {
                    break;
                }
            }

            // Shutdown and end connection
            _tunnel.DataReceived -= new EventHandler <DataReceivedEventArgs>(Tunnel_DataReceived);
            _client.Close();
        }
コード例 #26
0
ファイル: TextView.cs プロジェクト: justenau/ReedMullerCode
        /// <summary>
        /// When "Send" button is clicked, a new thread is run not to block the main thread.
        /// "Send" button is disabled until the thread finished its job.
        /// Input text is converted to vectors, which are sent through the channel with provided
        /// error probability p. Text is sent two ways - encoded and later decoded after receiving it
        /// from the channel and not encoded.
        /// </summary>
        private void SendBtn_Click(object sender, EventArgs e)
        {
            probabilityPanel.SendBtn.Enabled = false;
            new Thread(() =>
            {
                // If no text is provided, cancel further processes
                if (messageBox.Text.Length == 0)
                {
                    BeginInvoke((Action)(() =>
                    {
                        encodedTextBox.Text = "";
                        notEncodedTextBox.Text = "";
                        probabilityPanel.SendBtn.Enabled = true;
                        return;
                    }));
                }

                var p               = probabilityPanel.P;
                var textToBinary    = ConversionUtils.CovertStringToBinaryArray(messageBox.Text);
                var inputTextVector = new Vector(textToBinary);

                // Handling 'out of memory' failure
                try
                {
                    // Ecode input text vectors
                    var encodedTextVectors = Encoder.EncodeBinarySequence(inputTextVector, M, out int additionalBitCount);

                    // Sent (not)encoded text vectors through the channel
                    var receivedEncodedTextVector    = Channel.SendBinaryMessage(encodedTextVectors, p, out _);
                    var receivedNotEncodedTextVector = Channel.SendBinaryMessage(inputTextVector, p, out _);

                    // Decoded received encoded text vector
                    var decodedText = Decoder.DecodeBinarySequence(receivedEncodedTextVector, M);

                    SentEncodedResult    = ConversionUtils.ConvertBinaryArrayToString(decodedText.Data, additionalBitCount);
                    SentNotEncodedResult = ConversionUtils.ConvertBinaryArrayToString(receivedNotEncodedTextVector.Data, 0);
                }
                catch (OutOfMemoryException)
                {
                    MessageBox.Show("System is out of memory!");
                    return;
                }

                BeginInvoke((Action)(() => {
                    encodedTextBox.Text = SentEncodedResult;
                    notEncodedTextBox.Text = SentNotEncodedResult;
                    probabilityPanel.SendBtn.Enabled = true;
                }));
            }).Start();
        }
        public override void ExecuteCmdlet()
        {
            ExecutionBlock(() =>
            {
                base.ExecuteCmdlet();

                ResourceIdentifier resourceIdentifier = new ResourceIdentifier(VaultId);
                string vaultName = resourceIdentifier.ResourceName;
                string vaultResourceGroupName = resourceIdentifier.ResourceGroupName;
                string workloadType           = ConversionUtils.GetServiceClientWorkloadType(WorkloadType.ToString());
                string backupManagementType   = Container.BackupManagementType.ToString();
                ODataQuery <BMSContainersInquiryQueryObject> queryParams = new ODataQuery <BMSContainersInquiryQueryObject>(
                    q => q.WorkloadType == workloadType && q.BackupManagementType == backupManagementType);
                string errorMessage = string.Empty;
                var inquiryResponse = ServiceClientAdapter.InquireContainer(
                    Container.Name,
                    queryParams,
                    vaultName,
                    vaultResourceGroupName);

                var operationStatus = TrackingHelpers.GetOperationResult(
                    inquiryResponse,
                    operationId =>
                    ServiceClientAdapter.GetRegisterContainerOperationResult(
                        operationId,
                        Container.Name,
                        vaultName: vaultName,
                        resourceGroupName: vaultResourceGroupName));

                if (inquiryResponse.Response.StatusCode
                    == SystemNet.HttpStatusCode.OK)
                {
                    Logger.Instance.WriteDebug(errorMessage);
                }

                //Now wait for the operation to Complete
                if (inquiryResponse.Response.StatusCode
                    != SystemNet.HttpStatusCode.NoContent)
                {
                    errorMessage = string.Format(Resources.TriggerEnquiryFailureErrorCode,
                                                 inquiryResponse.Response.StatusCode);
                    Logger.Instance.WriteDebug(errorMessage);
                }
                if (PassThru.IsPresent)
                {
                    WriteObject(Container);
                }
            }, ShouldProcess(Container.Name, VerbsLifecycle.Invoke));
        }
コード例 #28
0
        public DataSet GetUnusedWP()
        {
            DataSet ds;

            try
            {
                ds = this.GetEntity().GetCustomDataSet("SelectWPUnused", this);
                ConversionUtils.MakeUniqueKey(ds.Tables[0], new string[] { "IdProject", "IdPhase", "IdWP" });
            }
            catch (Exception ex)
            {
                throw new IndException(ex);
            }
            return(ds);
        }
コード例 #29
0
        public static void convertBankers(Excel sheet, Excel sheetEn)
        {
            int rowCount       = sheet.getRowCount();
            int firstSheetCols = sheet.getColumnCount();

            sheet.changeSheet(2);
            int secondSheetCols               = sheet.getColumnCount();
            List <OutsideItem> bankerItems    = new List <OutsideItem>();
            CatConversionList  categoriesList = new CatConversionList();

            for (int i = 1; i < rowCount; i++)
            {
                BankersItem item = new BankersItem();
                sheet.changeSheet(1);
                item.sku            = sheet.readCell(i, 0);
                item.productName    = sheet.readCell(i, 2);
                item.productNameEn  = sheetEn.readCell(i, 2);
                item.description    = sheet.readCell(i, 3);
                item.descriptionEn  = sheetEn.readCell(i, 3);
                item.lineName       = sheet.readCell(i, 4);
                item.categories     = sheet.readCell(i, 6).Split('|');
                item.searchKeywords = sheet.readCell(i, 7).Split('|');
                item.defaultImage   = sheet.readCell(i, 8);
                item.colors         = sheet.readCell(i, 9).Split('|');
                item.size           = sheet.readCell(i, 10);
                sheet.changeSheet(2);
                int index = 5;
                while (!sheet.readCell(i, index).Equals("") && index < sheet.getColumnCount())
                {
                    int    quantity = Int32.Parse(sheet.readDoubleCell(i, index) + "");
                    Double price    = Double.Parse(sheet.readDoubleCell(i, index + 1) + "");
                    item.quantities.Add(quantity);
                    item.prices.Add(price);
                    index += 3;
                }
                bankerItems.Add(item);
            }
            List <ProduitDB> dbItems = ConversionUtils.getProducts(bankerItems);
            Excel            output  = Excel.createAndUseFile(sheet.getPath());

            ProduitDB.writeDBHeader(output);
            for (var i = 0; i < dbItems.Count; i++)
            {
                ProduitDB item = (ProduitDB)dbItems[i];
                ProduitDB.writeDBItem(output, (i + 1), item);
            }
            output.save();
        }
コード例 #30
0
        public void testOneSlot()
        {
            Defclass    dc    = new Defclass(typeof(TestBean2));
            Deftemplate dtemp = dc.createDeftemplate("testBean2");
            TestBean2   bean  = new TestBean2();

            Slot[]         slts = dtemp.AllSlots;
            ObjectTypeNode otn  = new ObjectTypeNode(1, dtemp);
            AlphaNode      an   = new AlphaNode(1);

            slts[0].Value = ConversionUtils.convert(110);
            an.Operator   = Constants.EQUAL;
            an.Slot       = (slts[0]);
            Console.WriteLine("node::" + an.ToString());
            Assert.IsNotNull(an.ToString(), "Should have a value.");
        }