Inheritance: MonoBehaviour
Example #1
1
        public async Task<Hash> PutAsync(long id, SemanticVersion version, IPackage package)
        {
            #region Preconditions

            if (package == null) throw new ArgumentNullException(nameof(package));

            #endregion

            var key = id.ToString() + "/" + version.ToString();

            using (var ms = new MemoryStream())
            {
                await package.ZipToStreamAsync(ms).ConfigureAwait(false);

                var hash = Hash.ComputeSHA256(ms, leaveOpen: true);

                var blob = new Blob(ms) {
                    ContentType = "application/zip"
                };

                await bucket.PutAsync(key, blob).ConfigureAwait(false);

                return hash;
            }
        }
Example #2
0
 /// <summary>
 /// Create a new Interest with the given name and interest lifetime and "none"
 /// for other values.
 /// </summary>
 ///
 /// <param name="name">The name for the interest.</param>
 /// <param name="interestLifetimeMilliseconds"></param>
 public Interest(Name name, double interestLifetimeMilliseconds)
 {
     this.name_ = new ChangeCounter(new Name());
     this.minSuffixComponents_ = -1;
     this.maxSuffixComponents_ = -1;
     this.keyLocator_ = new ChangeCounter(
             new KeyLocator());
     this.exclude_ = new ChangeCounter(new Exclude());
     this.childSelector_ = -1;
     this.mustBeFresh_ = true;
     this.interestLifetimeMilliseconds_ = -1;
     this.nonce_ = new Blob();
     this.getNonceChangeCount_ = 0;
     this.lpPacket_ = null;
     this.linkWireEncoding_ = new Blob();
     this.linkWireEncodingFormat_ = null;
     this.link_ = new ChangeCounter(null);
     this.selectedDelegationIndex_ = -1;
     this.defaultWireEncoding_ = new SignedBlob();
     this.getDefaultWireEncodingChangeCount_ = 0;
     this.changeCount_ = 0;
     if (name != null)
         name_.set(new Name(name));
     interestLifetimeMilliseconds_ = interestLifetimeMilliseconds;
 }
 /// <summary>
 /// Create an EncryptedContent where all the values are unspecified.
 /// </summary>
 ///
 public EncryptedContent()
 {
     this.algorithmType_ = net.named_data.jndn.encrypt.algo.EncryptAlgorithmType.NONE;
     this.keyLocator_ = new KeyLocator();
     this.initialVector_ = new Blob();
     this.payload_ = new Blob();
 }
Example #4
0
 //List all foders in the root of the container
 public List<Blob> ListFoldersInRootOfContainer(string container)
 {
     BlobStorage blobStorage = new BlobStorage(container);
     string blobPrefix = null;
     //Not to list the files in subfolder
     bool useFlatBlobListing = false;
     var blobs = blobStorage.Container.ListBlobs(blobPrefix, useFlatBlobListing, BlobListingDetails.None);
     //To get all the directory
     var folders = blobs.Where(b => b as CloudBlobDirectory != null).ToList();
     var list = new List<Blob>();
     string folderName;
     foreach (var folder in folders)
     {
         var blob = new Blob();
         //Get the folder name
         folderName = folder.Uri.ToString();
         folderName = folderName.Substring(0, folderName.Length - 1);
         folderName = folderName.Substring(folderName.LastIndexOf("/") + 1);
         //Assign the folder name and Uri
         blob.Name = folderName;
         blob.Uri = folder.Uri.ToString();
         list.Add(blob);
     }
     //Return the list
     return list;
 }
Example #5
0
		public IBlob Get(Uri uri)
		{
			IBlob blob = null;

			var options = new BlobRequestOptions { BlobListingDetails = BlobListingDetails.Metadata };

			var container = getContainer();
			var target = container.GetBlobReference(uri.ToString());

			try
			{
				target.FetchAttributes();
				blob = new Blob(target.Properties.ContentMD5, target.Properties.ETag)
					{ Content = target.DownloadByteArray(), ContentType = target.Properties.ContentType, };

				foreach (var key in target.Metadata.AllKeys)
				{
					blob.Metdata.Add(new KeyValuePair<string, string>(key, target.Metadata[key]));
				}
			}
			catch (StorageClientException s)
			{
				this.WriteErrorMessage(string.Format("An error occurred retrieving the blob from {0}", uri), s);
				blob = null;
			}

			return blob;
		}
Example #6
0
 public static byte[] ToByteArray(this Image img)
 {
     using (var blob = new Blob()) {
         img.Write(blob);
         return blob.ToArray();
     }
 }
    public bool[][] ComputeGrid(Blob[] blobs)
    {
        int sizeX = (int)(_gridBound.rect.width / GridStep) + 1;
        int sizeY = (int)(_gridBound.rect.height / GridStep) + 1;

        var grid = new bool[sizeY][];
        for (int i = 0; i < sizeY; i++)
            grid[i] = new bool[sizeX];

        for (int i = 0; i < sizeY; i++)
            for (int j = 0; j < sizeX; j++)
            {
                float y = _gridBound.offsetMin.y + i * GridStep;
                float x = _gridBound.offsetMin.x + j * GridStep;
                var pos = new Vector2(x, y);

                float totalWeigth = 0;
                foreach (Blob blob in blobs)
                {
                    float distance = Vector2.Distance(pos, blob.transform.position);

                    float weight = blob.WeightFunction(distance);
                    if (weight < 0)
                        weight = 0;

                    totalWeigth += weight;
                }

                grid[i][j] = totalWeigth > WeightThreshold;
            }

        return grid;
    }
Example #8
0
        private static void WritePEImage(
            Stream peStream, 
            MetadataBuilder metadataBuilder, 
            BlobBuilder ilBuilder, 
            MethodDefinitionHandle entryPointHandle,
            Blob mvidFixup = default(Blob),
            byte[] privateKeyOpt = null)
        {
            var peBuilder = new ManagedPEBuilder(
                entryPointHandle.IsNil ? PEHeaderBuilder.CreateLibraryHeader() : PEHeaderBuilder.CreateExecutableHeader(),
                new MetadataRootBuilder(metadataBuilder),
                ilBuilder,
                entryPoint: entryPointHandle,
                flags: CorFlags.ILOnly | (privateKeyOpt != null ? CorFlags.StrongNameSigned : 0),
                deterministicIdProvider: content => s_contentId);

            var peBlob = new BlobBuilder();

            var contentId = peBuilder.Serialize(peBlob);

            if (!mvidFixup.IsDefault)
            {
                new BlobWriter(mvidFixup).WriteGuid(contentId.Guid);
            }

            if (privateKeyOpt != null)
            {
                peBuilder.Sign(peBlob, content => SigningUtilities.CalculateRsaSignature(content, privateKeyOpt));
            }

            peBlob.WriteContentTo(peStream);
        }
Example #9
0
 public void do_not_convert_the_type_if_it_is_already_in_the_correct_type()
 {
     objectConverter.RegisterConverter<Blob>(b => new Blob());
     var theBlob = new Blob();
     theData["blob"] = theBlob;
     theRequest.Value<Blob>("blob").ShouldBeTheSameAs(theBlob);
 }
 /// <summary>
 /// Create a new GenericSignature with default values.
 /// </summary>
 ///
 public GenericSignature()
 {
     this.signature_ = new Blob();
     this.signatureInfoEncoding_ = new Blob();
     this.typeCode_ = -1;
     this.changeCount_ = 0;
 }
Example #11
0
        public void AttachBlobs()
        {
            Blob blob = new Blob(IOHelper.CreateTempFile("This is just a note.")).SetFilename("note1.txt");
            Entity result = client.Operation("Blob.Attach")
                                  .SetInput(blob)
                                  .SetParameter("document", blobContainer.Path)
                                  .Execute()
                                  .Result;
            Assert.True(result is Blob);
            Assert.Equal("This is just a note.", IOHelper.ReadText(((Blob)result).File));

            BlobList blobs = new BlobList();
            blobs.Add(new Blob(IOHelper.CreateTempFile("This is another note.")).SetFilename("note2.txt"));
            blobs.Add(Blob.FromFile("Puppy.docx"));

            result = client.Operation("Blob.Attach")
                           .SetInput(blobs)
                           .SetParameter("document", blobContainer.Path)
                           .SetParameter("xpath", "files:files")
                           .Execute()
                           .Result;
            Assert.True(result is BlobList);
            Assert.Equal(2, blobs.Count);
            Assert.Equal("This is another note.", IOHelper.ReadText(blobs[0].File));
            Assert.True(IOHelper.AreFilesEqual("Puppy.docx", blobs[1].File.FullName));
        }
 internal BlobStream(ConnectPackageCreationParameters connectPackageParameters, Blob blob)
 {
     _connectPackageParameters = connectPackageParameters;
     _blob = blob;
     _length = blob.ContentLength;
     _canWrite = true;
 }
 internal BlobStream(HealthRecordAccessor record, Blob blob)
 {
     _record = record;
     _blob = blob;
     _length = blob.ContentLength;
     _canWrite = true;
 }
Example #14
0
 public FourOhFourViewModel(FourOhFourReason reason, Blob blob)
 {
     Reason = reason;
     Blob = blob;
     Month = string.Empty;
     Year = DateTime.Now.Year.ToString(); 
 }
Example #15
0
        public override bool Equals(Blob blob)
        {
            var sb = blob as StreamBlob;
            if (sb != null)
            {
                if (_stream == sb._stream) return true;
                var fsa = _stream as FileStream;
                if (fsa == null) return false;
                var fsb = sb._stream as FileStream;
                if (fsb == null) return false;
                try
                {
                    return fsa.Name.Equals(fsb.Name);
                }
                catch
                {
                    return false;
                }
            }

            var fb = blob as FileBlob;
            if (fb == null) return false;

            var fs = _stream as FileStream;
            if (fs == null) return false;
            try
            {
                return fb.Filename.Equals(fs.Name);
            }
            catch
            {
                return false;
            }
        }
Example #16
0
        public IStorableObject ToGitObject(Repository repo, string sha)
        {
            using (GitObjectReader objectReader = new GitObjectReader(Content))
              {
            IStorableObject obj;
            switch (Type)
            {
              case ObjectType.Commit:
              obj = new Commit(repo, sha);
              break;
            case ObjectType.Tree:
              obj = new Tree(repo, sha);
              break;
            case ObjectType.Blob:
              obj = new Blob(repo, sha);
              break;
            case ObjectType.Tag:
              obj = new Tag(repo, sha);
              break;
            default:
              throw new NotImplementedException();
            }

            obj.Deserialize(objectReader);
            return obj;
              }
        }
Example #17
0
 /// <summary>
 /// Create a new KeyLocator with default values.
 /// </summary>
 ///
 public KeyLocator()
 {
     this.type_ = net.named_data.jndn.KeyLocatorType.NONE;
     this.keyData_ = new Blob();
     this.keyName_ = new ChangeCounter(new Name());
     this.changeCount_ = 0;
 }
Example #18
0
 // no content-type because we don't use it
 internal Blob()
 {
     // There *ought* to be an IBlob that we extend, but I'm lazy.
       this.parentBlob = null;
       this.start = 0;
       this.size = 0;
 }
Example #19
0
 public void FindLeastConnectedBlob()
 {
     Hashtable processingTable = new Hashtable ();
     processingTable.Add (gameObject.GetInstanceID (), gameObject);
     GameObject leastConnected = FindLeastConnectedBlob (gameObject, processingTable);
     leastConnectedBlob = leastConnected.GetComponent<Blob> ();
 }
Example #20
0
		public override bool Equals(Blob blob)
		{
			StreamBlob sb = blob as StreamBlob;
			if (sb != null)
			{
				if (this.stream == sb.stream) return true;
				FileStream fsa = this.stream as FileStream;
				if (fsa == null) return false;
				FileStream fsb = sb.stream as FileStream;
				if (fsb == null) return false;
				try
				{
					return fsa.Name.Equals(fsb.Name);
				}
				catch
				{
					return false;
				}
			}

			FileBlob fb = blob as FileBlob;
			if (fb == null) return false;
			
			FileStream fs = this.stream as FileStream;
			if (fs == null) return false;
			try
			{
				return fb.Filename.Equals(fs.Name);
			}
			catch
			{
				return false;
			}
		}
Example #21
0
        public static void testData() { 
            byte[] origData = new byte[1024];
			for (int i = 0; i < origData.Length; i++) {
				origData[i] = (byte)i;
			}
			
			{
				
                Blob blob = new Blob(origData, "application/octet-stream");
				Debug.Assert(origData.Length == blob.getSize());

				for (int i = 0; i < origData.Length; i++) {
					Debug.Assert(origData[i] == blob.getData()[i]);
				}
			}
			
			Data data = new Data(origData, "application/octet-stream");
			Blob blob2 = data.getBinary();
			
			byte[] newData = blob2.getData();
			
			if (newData.Length == origData.Length);
			for (int i = 0; i < origData.Length; i++) {
                Debug.Assert(newData[i] == origData[i]);
			}

        }
 public VenueMapNotFoundViewModel(Blob blob, FourOhFourReason reason)
 {
     Reason = reason;
     Blob = blob;
     Month = string.Empty;
     Year = DateTime.Now.Year.ToString();
 }
Example #23
0
        public async Task<Hash> PutAsync(long id, SemanticVersion version, IPackage package)
        {
            var key = prefix + id.ToString() + "/" + version.ToString();

            using (var ms = new MemoryStream())
            {
                await package.ZipToStreamAsync(ms).ConfigureAwait(false);

                ms.Position = 0;

                var hash = Hash.ComputeSHA256(ms, leaveOpen: true);

                var secret = SecretKey.Derive(password, hash.Data);

                using (var protector = new AesProtector(secret))
                {
                    using (var packageStream = protector.EncryptStream(ms))
                    {
                        var blob = new Blob(packageStream) {
                            ContentType = "application/zip"
                        };

                        await bucket.PutAsync(key, blob).ConfigureAwait(false);
                    }
                }

                return hash;
            }
        }
 /// <summary>
 /// Create a new HmacWithSha256Signature with default values.
 /// </summary>
 ///
 public HmacWithSha256Signature()
 {
     this.signature_ = new Blob();
     this.keyLocator_ = new ChangeCounter(
             new KeyLocator());
     this.changeCount_ = 0;
 }
 public void EndTurnAction(Blob blob)
 {
     if (blob.Damage >= blob.InitialDamage + DamageReducedEveryTurn)
     {
         blob.Damage -= DamageReducedEveryTurn;
     }
 }
Example #26
0
 public HashSet<string> GetWithPrefix(string prefix, int maxSize)
 {
     Blob<HashSet<KeyValuePair<string, string>>> rootBlob = new Blob<HashSet<KeyValuePair<string, string>>>(dir.GetBlobReference("root"));
     HashSet<KeyValuePair<string, string>> set = rootBlob.Get();
     set.RemoveWhere((p) => p.Key.StartsWith(prefix));
     return new HashSet<string>(set.Select((p) => p.Value));
 }
Example #27
0
        //List all files in a specific folder(for example, folder name:  a/b/c). return the list of blob info.
        public List<Blob> ListFilesInSpecificFolder(string container, string folderName)
        {
            BlobStorage blobStorage = new BlobStorage(container);
            //Add prefix before listing all files
            string blobPrefix = folderName + "/";
            if (string.IsNullOrEmpty(folderName) || string.IsNullOrWhiteSpace(folderName))
            {
                blobPrefix = null;
            }
            //Not to list the files in subfolder
            bool useFlatBlobListing = false;
            var blobs = blobStorage.Container.ListBlobs(blobPrefix, useFlatBlobListing, BlobListingDetails.None);
            //To get all files
            var files = blobs.Where(b => b as CloudBlobDirectory == null).ToList();

            var list = new List<Blob>();
            foreach (var file in files)
            {
                var blob = new Blob();
                //To get blob info
                blob.Name = Path.GetFileName(file.Uri.ToString());
                blob.Uri = file.Uri.ToString();
                list.Add(blob);
            }
            return list;
        }
	public void newBlobAdded(Blob blob)
	{
		int index = blobs.IndexOf(blob);
		BlobCell bc = blobPanel.blobCells[index];
		bc.progressBar.value = 0f;
		PressGridItem(index);
	}
Example #29
0
 public static void HandleBlobChange(StaticFile obj, MethodReturnEventArgs<Blob> e, Blob oldBlob, Blob newBlob)
 {
     if (oldBlob != null && newBlob != oldBlob)
     {
         throw new InvalidOperationException("Changing blob on static files is not allowed");
     }
     e.Result = newBlob;
 }
Example #30
0
 public void FindTarget()
 {
     Blob[] targets = GameObject.FindObjectsOfType<Blob> ();
     if (targets != null && targets.Length > 0) {
         int index = Random.Range (0, targets.Length);
         target = targets [index];
     }
 }
Example #31
0
        /// <summary>
        /// Run the trained model.  When run each hand-written image is fed in sequence (by label,
        /// e.g. 0,1,2,...,9 through the model, yet images within each label are selected at random.
        /// </summary>
        /// <param name="mycaffe">Specifies the mycaffe instance running the sequence run model.</param>
        /// <param name="bw">Specifies the background worker.</param>
        private void runModel(MyCaffeControl <float> mycaffe, BackgroundWorker bw)
        {
            Random random = new Random((int)DateTime.Now.Ticks);
            // Get the internal RUN net and associated blobs.
            Net <float>  net          = m_mycaffe.GetInternalNet(Phase.RUN);
            Blob <float> blobData     = net.FindBlob("data");
            Blob <float> blobClip1    = net.FindBlob("clip1");
            Blob <float> blobIp1      = net.FindBlob("ip1");
            List <float> rgPrediction = new List <float>();
            List <float> rgTarget     = new List <float>();
            List <float> rgT          = new List <float>();

            m_mycaffeInput.UpdateRunWeights();
            blobClip1.SetData(0);

            bool bForcedError = false;

            for (int i = 0; i < 100; i++)
            {
                if (m_evtCancel.WaitOne(0))
                {
                    return;
                }

                int nLabelSeq = m_nLabelSeq;
                if (m_evtForceError.WaitOne(0))
                {
                    nLabelSeq    = random.Next(10);
                    bForcedError = true;
                }
                else
                {
                    bForcedError = false;
                }

                // Get images one number at a time, in order by label, but randomly selected.
                SimpleDatum      sd  = m_imgDb.QueryImage(m_ds.TrainingSource.ID, 0, null, IMGDB_IMAGE_SELECTION_METHOD.RANDOM, nLabelSeq);
                ResultCollection res = m_mycaffeInput.Run(sd);

                Net <float>  inputNet             = m_mycaffeInput.GetInternalNet(Phase.RUN);
                Blob <float> input_ip             = inputNet.FindBlob(m_strInputOutputBlobName);
                Dictionary <string, float[]> data = Signal.GenerateSample(1, m_nLabelSeq / 10.0f, 1, m_model.InputLabel, m_model.TimeSteps);

                float[] rgFY1 = data["FY"];

                // Run the model.
                blobClip1.SetData(1);
                blobData.mutable_cpu_data = input_ip.mutable_cpu_data;
                net.Forward();
                rgPrediction.AddRange(blobIp1.mutable_cpu_data);

                // Graph and show the results.
                float[] rgFT = data["FT"];
                float[] rgFY = data["FY"];
                for (int j = 0; j < rgFT.Length; j++)
                {
                    rgT.Add(rgFT[j]);
                    rgTarget.Add(rgFY[j]);
                }

                while (rgTarget.Count * 5 > pbImage.Width)
                {
                    rgTarget.RemoveAt(0);
                    rgPrediction.RemoveAt(0);
                }

                // Plot the graph.
                PlotCollection plotsTarget = createPlots("Target", rgT.ToArray(), new List <float[]>()
                {
                    rgTarget.ToArray()
                }, 0);
                PlotCollection plotsPrediction = createPlots("Predicted", rgT.ToArray(), new List <float[]>()
                {
                    rgPrediction.ToArray()
                }, 0);
                PlotCollection    plotsAvePrediction = createPlotsAve("Predicted SMA", plotsPrediction, 10);
                PlotCollectionSet set = new PlotCollectionSet(new List <PlotCollection>()
                {
                    plotsTarget, plotsPrediction, plotsAvePrediction
                });

                // Create the graph image and display
                Image img = SimpleGraphingControl.QuickRender(set, pbImage.Width, pbImage.Height);
                img = drawInput(img, sd, res.DetectedLabel, bForcedError);

                bw.ReportProgress(0, img);
                Thread.Sleep(1000);

                m_nLabelSeq++;
                if (m_nLabelSeq == 10)
                {
                    m_nLabelSeq = 0;
                }
            }
        }
Example #32
0
 protected override void ApplyTriggerEffect(Blob source)
 {
     source.Damage *= AggressiveDamageMultiplier;
 }
Example #33
0
        public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
        {
            if (value is null)
            {
                return(null);
            }
            if (value.GetType().IsEnum == false && value.GetType().IsArray == true)
            {
                if (Conversions.ToBoolean(Operators.ConditionalCompareObjectEqual(value.Length, 0, false)))
                {
                    return(Array.CreateInstance(typeof(byte), 0));
                }
            }

            var  bl    = new Blob();
            var  vType = value.GetType();
            Type eType;

            if (vType == typeof(Blob))
            {
                bl = new Blob((Blob)value);
                return(bl);
            }

            if (vType.IsArray)
            {
                eType = value.GetType().GetElementType();
            }
            else
            {
                eType = vType;
            }
            if (vType.IsClass && (vType.BaseType == Blob.Types[(int)BlobTypes.Image] || vType == Blob.Types[(int)BlobTypes.Image]))
            {
                bl          = new Blob(ImageToBytes((Image)value));
                bl.BlobType = BlobTypes.Image;
                return(bl);
            }

            if (vType.IsEnum == true)
            {
                value      = BlobUtil.EnumToBytes(value);
                bl.Type    = vType;
                bl         = new Blob((byte[])value);
                bl.TypeLen = (int)bl.Length;
                return(bl);
            }
            else if (eType.IsEnum == true)
            {
                bl         = BlobUtil.EnumToBytes(value);
                bl.Type    = vType;
                bl.TypeLen = Marshal.SizeOf(value((object)0));
                return(bl);
            }

            switch (vType)
            {
            case var @case when @case == typeof(bool):
            {
                bool bol = Conversions.ToBoolean(value);
                if (bl is null)
                {
                    bl = new Blob();
                }
                bl.Type    = vType;
                bl.TypeLen = 1;
                if (bl.Length < 1L)
                {
                    bl.Length = 1L;
                }
                if (bol)
                {
                    bl.set_ByteAt(0L, 1);
                }
                else
                {
                    bl.set_ByteAt(0L, 0);
                }

                return(bl);
            }

            case var case1 when case1 == typeof(BigInteger):
            {
                BigInteger be = (BigInteger)value;
                bl         = be.ToByteArray();
                bl.Type    = vType;
                bl.TypeLen = (int)bl.Length;
                return(bl);
            }

            case var case2 when case2 == typeof(DateTime):
            {
                bl         = DateToBytes(Conversions.ToDate(value));
                bl.Type    = vType;
                bl.TypeLen = Marshal.SizeOf(value);
                return(bl);
            }

            case var case3 when case3 == typeof(DateTime[]):
            {
                bl         = DateArrayToBytes((DateTime[])value);
                bl.Type    = vType;
                bl.TypeLen = Marshal.SizeOf(value((object)0));
                return(bl);
            }

            case var case4 when case4 == typeof(byte[]):
            {
                bl.Type    = vType;
                bl.TypeLen = 1;
                bl         = (byte[])value;
                return(bl);
            }

            case var case5 when case5 == typeof(sbyte[]):
            {
                bl         = ToByteArray((sbyte[])value);
                bl.Type    = vType;
                bl.TypeLen = 1;
                return(bl);
            }

            case var case6 when case6 == typeof(string):
            {
                if (value is null)
                {
                    value = "";
                }
                else
                {
                    value = Conversions.ToString(value).Trim('\0');
                }

                if (Conversions.ToBoolean(Operators.ConditionalCompareObjectEqual(value, "", false)))
                {
                    bl.Type    = typeof(string);
                    bl.TypeLen = Marshal.SizeOf('A');
                    return(bl);
                }

                bl = Blob.Parse(value);

                // bl.Type = GetType(String)
                // bl.TypeLen = Marshal.SizeOf("A"c)
                // bl.Alloc(CStr(value).Length * 2)
                // Native.CopyMemory(bl.handle, CStr(value), CType(CStr(value).Length * 2, IntPtr))
                return(bl);
            }

            case var case7 when case7 == typeof(Guid):
            {
                bl          = (Blob)(bl + value.ToByteArray);
                bl.BlobType = BlobTypes.Guid;
                bl.ToString();
                return(bl);
            }

            case var case8 when case8 == typeof(Guid[]):
            {
                bl.BlobType = BlobTypes.Guid;
                foreach (Guid g in (IEnumerable)value)
                {
                    bl += g.ToByteArray();
                }
                return(bl);
            }

            case var case9 when case9 == typeof(Color):
            {
                Color cl;
                cl          = (Color)value;
                bl          = cl.ToArgb();
                bl.BlobType = BlobTypes.Color;
                return(bl);
            }

            case var case10 when case10 == typeof(Color[]):
            {
                Color[] cl;
                cl          = (Color[])value;
                bl.BlobType = BlobTypes.Color;
                bl.Length   = 4 * cl.Length;
                var gh = GCHandle.Alloc(cl, GCHandleType.Pinned);
                Native.MemCpy(bl.DangerousGetHandle(), gh.AddrOfPinnedObject(), (uint)bl.Length);
                gh.Free();
                return(bl);
            }

            case var case11 when case11 == typeof(decimal[]):
            {
                decimal[] dec = (decimal[])value;
                bl.Length   = dec.Length * 16;
                bl.BlobType = BlobTypes.Decimal;
                Native.MemCpy(bl.DangerousGetHandle(), dec, (uint)(dec.Length * 16));
                break;
            }

            case var case12 when case12 == typeof(decimal):
            {
                bl.BlobType = BlobTypes.Decimal;
                bl.Length   = 16L;
                bl.set_DecimalAt(0L, Conversions.ToDecimal(value));
                break;
            }

            case var case13 when case13 == typeof(double):
            case var case14 when case14 == typeof(float):
            case var case15 when case15 == typeof(long):
            case var case16 when case16 == typeof(ulong):
            case var case17 when case17 == typeof(int):
            case var case18 when case18 == typeof(uint):
            case var case19 when case19 == typeof(short):
            case var case20 when case20 == typeof(ushort):
            case var case21 when case21 == typeof(byte):
            case var case22 when case22 == typeof(sbyte):
            case var case23 when case23 == typeof(char):
            {
                switch (vType)
                {
                case var case24 when case24 == typeof(ulong):
                {
                    bl.Length = 8L;
                    bl.set_ULongAt(0L, Conversions.ToULong(value));
                    break;
                }

                case var case25 when case25 == typeof(uint):
                {
                    bl.Length = 4L;
                    bl.set_UIntegerAt(0L, Conversions.ToUInteger(value));
                    break;
                }

                case var case26 when case26 == typeof(ushort):
                {
                    bl.Length = 2L;
                    bl.set_UShortAt(0L, Conversions.ToUShort(value));
                    break;
                }

                case var case27 when case27 == typeof(sbyte):
                {
                    var u = BlobConverter.ToByteArray(new[] { value });
                    bl         = u;
                    bl.Type    = vType;
                    bl.TypeLen = Marshal.SizeOf(u[0]);
                    break;
                }

                case var case28 when case28 == typeof(byte):
                {
                    bl         = new[] { value };
                    bl.Type    = vType;
                    bl.TypeLen = Marshal.SizeOf(value);
                    break;
                }

                default:
                {
                    bl         = BitConverter.GetBytes(value);
                    bl.Type    = vType;
                    bl.TypeLen = Marshal.SizeOf(value);
                    break;
                }
                }

                bl.BlobType = Blob.TypeToBlobType(vType);
                return(bl);
            }

            case var case29 when case29 == typeof(double[]):
            case var case30 when case30 == typeof(float[]):
            case var case31 when case31 == typeof(long[]):
            case var case32 when case32 == typeof(ulong[]):
            case var case33 when case33 == typeof(int[]):
            case var case34 when case34 == typeof(uint[]):
            case var case35 when case35 == typeof(short[]):
            case var case36 when case36 == typeof(ushort[]):
            case var case37 when case37 == typeof(sbyte[]):
            case var case38 when case38 == typeof(char[]):
            {
                object a;
                switch (vType)
                {
                case var case39 when case39 == typeof(sbyte[]):
                {
                    a = ToByteArray((sbyte[])value);
                    break;
                }

                case var case40 when case40 == typeof(ushort[]):
                {
                    a = ToShortArray((ushort[])value);
                    break;
                }

                case var case41 when case41 == typeof(uint[]):
                {
                    a = ToIntegerArray((uint[])value);
                    break;
                }

                case var case42 when case42 == typeof(ulong[]):
                {
                    a = ToLongArray((ulong[])value);
                    break;
                }

                default:
                {
                    a = value;
                    break;
                }
                }

                int l;
                int e;
                l         = Conversions.ToInteger(value.Length);
                e         = Marshal.SizeOf(value((object)0));
                bl.Length = l * e;
                Marshal.Copy(a, (object)0, (object)bl.DangerousGetHandle(), l);
                bl.Type    = vType;
                bl.TypeLen = e;
                return(bl);
            }
            }

            if (value.GetType().IsValueType)
            {
                StructureToBlob(value, ref bl);
                return(bl);
            }

            return(base.ConvertFrom(context, culture, value));
        }
Example #34
0
        public override object CreateInstance(ITypeDescriptorContext context, IDictionary propertyValues)
        {
            var bl = new Blob();

            return(bl);
        }
Example #35
0
 bool IsBattleTile(Blob tuple) => tuple[0] == 0x0A;
Example #36
0
 bool IsNonBossTrapTileEx(Blob tuple) => IsBattleTile(tuple) && ((tuple[1] > 0 && tuple[1] < FirstBossEncounterIndex) || tuple[1] > LastBossEncounterIndex);
Example #37
0
 public GitDiffFile(Blob blob)
 {
     _blob = blob;
 }
Example #38
0
 /// <summary>
 /// Determines whether this blob is an image.
 /// </summary>
 public static bool IsImage(this Blob doc)
 {
     return(doc.FileExtension.ToLower().TrimStart(".")
            .IsAnyOf("jpg", "jpeg", "png", "bmp", "gif", "webp", "tiff", "svg"));
 }
Example #39
0
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="cuda">Cuda engine.</param>
 /// <param name="log">General log.</param>
 /// <param name="p">provides AccuracyParameter accuracy_param,
 /// with AccuracyLayer options:
 ///  - top_k (optional, default 1)
 ///          Sets the maximumrank k at which prediction is considered
 ///          correct, For example, if k = 5, a prediction is counted
 ///          correct if the correct label is among the top 5 predicted labels.</param>
 public AccuracyLayer(CudaDnn <T> cuda, Log log, LayerParameter p)
     : base(cuda, log, p)
 {
     m_type           = LayerParameter.LayerType.ACCURACY;
     m_blobNumsBuffer = new Blob <T>(cuda, log);
 }
Example #40
0
        public void RollCredits()
        {
            // Wallpaper over the JSR to the NASIR CRC to circumvent their neolithic DRM.
            Put(0x3CF34, Blob.FromHex("EAEAEA"));

            // Actual Credits. Each string[] is a page. Each "" skips a line, duh.
            // The lines have zero padding on all sides, and 16 usable characters in length.
            // Don't worry about the inefficiency of spaces as they are all trimmed and the
            // leading spaces are used to increment the PPU ptr precisely to save ROM space.
            List <string[]> texts = new List <string[]>();

            texts.Add(new string[] { "", "",
                                     " Final  Fantasy ",
                                     "", "",
                                     "   Randomizer   ", });
            texts.Add(new string[] { "", "",
                                     "   Programmed   ",
                                     "       By       ",
                                     "",
                                     "E N T R O P E R " });
            texts.Add(new string[] { "",
                                     "  Development   ",
                                     "", "",
                                     "  Entroper",
                                     "  MeridianBC",
                                     "  tartopan",
                                     "  nitz", });
            texts.Add(new string[] { " Special Thanks ",
                                     "",
                                     "fcoughlin, Disch",
                                     "Paulygon, anomie",
                                     "Derangedsquirrel",
                                     "AstralEsper, and",
                                     "",
                                     " The Entire FFR ",
                                     "    Community   ", });

            // Accumulate all our Credits pages before we set up the string pointer array.
            List <Blob> pages = new List <Blob>();

            foreach (string[] text in texts)
            {
                pages.Add(FF1Text.TextToCredits(text));
            }

            // Clobber the number of pages to render before we insert in the pointers.
            Data[0x37873] = (byte)pages.Count();

            // The first pointer is immediately after the pointer table.
            List <ushort> ptrs = new List <ushort>();

            ptrs.Add((ushort)(0xBB00 + pages.Count() * 2));

            for (int i = 1; i < pages.Count(); ++i)
            {
                ptrs.Add((ushort)(ptrs.Last() + pages[i - 1].Length));
            }

            // Collect it into one blob and blit it.
            pages.Insert(0, Blob.FromUShorts(ptrs.ToArray()));
            Blob credits = Blob.Concat(pages);

            System.Diagnostics.Debug.Assert(credits.Length <= 0x0100, "Credits too large!");
            Put(0x37B00, credits);
        }
Example #41
0
 public void EasterEggs()
 {
     Put(0x2ADDE, Blob.FromHex("91251A682CC18EB1B74DB32505C1BE9296991E2F1AB6A4A9A8BE05C1C1C1C1C1C19B929900"));
 }
Example #42
0
 public void EnableDash()
 {
     Put(0x03D077, Blob.FromHex("4A252DD002A54224205002A9044A6900853460"));
 }
Example #43
0
 public void EnableIdentifyTreasures()
 {
     Put(0x2B192, Blob.FromHex("C1010200000000"));
 }
Example #44
0
 public PhpString(byte[] value)
 {
     _blob = new Blob(value);
 }
Example #45
0
        public ID3D11InputLayout CreateInputLayout(InputElementDescription[] inputElements, Blob blob)
        {
            Guard.NotNull(inputElements, nameof(inputElements));
            Guard.NotNull(blob, nameof(blob));

            return(CreateInputLayout(inputElements, inputElements.Length, blob.BufferPointer, blob.BufferPointer));
        }
Example #46
0
 public PhpString(string value)
 {
     _blob = new Blob(value);    // TODO: _blob = string
 }
Example #47
0
 bool IsBossTrapTile(Blob tuple) => IsBattleTile(tuple) && tuple[1] <= LastBossEncounterIndex && tuple[1] >= FirstBossEncounterIndex;
Example #48
0
 public PhpString(PhpValue x, Context ctx)
 {
     _blob = new Blob();
     _blob.Add(x, ctx);
 }
Example #49
0
 bool IsRandomBattleTile(Blob tuple) => IsBattleTile(tuple) && (tuple[1] & 0x80) != 0x00;
Example #50
0
 public PhpString(Blob blob)
 {
     _blob = blob;
 }
 public object Instance(TileConfiguration tile, Blob config)
 {
     return(new GeneratorComponent(config));
 }
Example #52
0
        /// <summary>
        /// Reverse the transformation made when calling Transform.
        /// </summary>
        /// <param name="blob">Specifies the input blob.</param>
        /// <param name="bIncludeMean">Specifies whether or not to add the mean back.</param>
        /// <returns>The de-processed output Datum is returned.</returns>
        public Datum UnTransform(Blob <T> blob, bool bIncludeMean = true)
        {
            double[] rgData   = Utility.ConvertVec <T>(blob.update_cpu_data());
            byte[]   rgOutput = new byte[rgData.Length];
            int      nC       = blob.channels;
            int      nH       = blob.height;
            int      nW       = blob.width;

            int[]         rgChannelSwap = null;
            bool          bUseMeanImage = m_param.use_imagedb_mean;
            List <double> rgMeanValues  = null;

            double[] rgMean  = null;
            double   dfScale = m_param.scale;

            if (bUseMeanImage)
            {
                if (m_rgMeanData == null)
                {
                    m_log.FAIL("You must specify an imgMean parameter when using IMAGE mean subtraction.");
                }

                rgMean = m_rgMeanData;

                int nExpected = nC * nH * nW;
                m_log.CHECK_EQ(rgMean.Length, nExpected, "The size of the 'mean' image is incorrect!  Expected '" + nExpected.ToString() + "' elements, yet loaded '" + rgMean.Length + "' elements.");
            }

            if (m_rgMeanValues.Count > 0)
            {
                m_log.CHECK(m_rgMeanValues.Count == 1 || m_rgMeanValues.Count == nC, "Specify either 1 mean value or as many as channels: " + nC.ToString());
                rgMeanValues = new List <double>();

                for (int c = 0; c < nC; c++)
                {
                    // Replicate the mean value for simplicity.
                    if (c == 0 || m_rgMeanValues.Count == 1)
                    {
                        rgMeanValues.Add(m_rgMeanValues[0]);
                    }
                    else if (c > 0)
                    {
                        rgMeanValues.Add(m_rgMeanValues[c]);
                    }
                }

                rgMean = rgMeanValues.ToArray();
            }

            if (m_param.color_order == TransformationParameter.COLOR_ORDER.BGR)
            {
                rgChannelSwap = new int[] { 2, 1, 0 }
            }
            ;

            for (int c1 = 0; c1 < nC; c1++)
            {
                int c = (rgChannelSwap == null) ? c1 : rgChannelSwap[c1];

                for (int h = 0; h < nH; h++)
                {
                    for (int w = 0; w < nW; w++)
                    {
                        int    nDataIdx = (c * nH + h) * nW + w;
                        double dfVal    = (rgData[nDataIdx] / dfScale);

                        if (bIncludeMean)
                        {
                            if (bUseMeanImage)
                            {
                                dfVal += rgMean[nDataIdx];
                            }
                            else if (rgMean != null && rgMean.Length == nC)
                            {
                                dfVal += rgMean[c];
                            }
                        }

                        if (dfVal < 0)
                        {
                            dfVal = 0;
                        }
                        if (dfVal > 255)
                        {
                            dfVal = 255;
                        }

                        int nOutIdx = (c1 * nH + h) * nW + w;
                        rgOutput[nOutIdx] = (byte)dfVal;
                    }
                }
            }

            return(new Datum(false, nC, nW, nH, -1, DateTime.MinValue, rgOutput.ToList(), null, 0, false, -1));
        }
    }
Example #53
0
        public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
        {
            Blob bl = (Blob)value;

            bl.Align();
            if (bl.fOwn == true)
            {
                if (bl.Length == 0L)
                {
                    if (destinationType == typeof(string))
                    {
                        return("");
                    }
                    else
                    {
                        return(null);
                    }
                }
            }
            else if (destinationType == typeof(string))
            {
                return(bl.GrabString((IntPtr)0));
            }

            if (ReferenceEquals(destinationType, typeof(InstanceDescriptor)))
            {
                // ' See the next class converter for details on
                // ' InstanceDescriptor conversion

                System.Reflection.ConstructorInfo objC;
                // objC = objT.GetType.GetConstructor(New Type() {GetType(Single), GetType(Single), GetType(Single), GetType(Single), GetType(Ruler.RulerUnits)})
                // Return New InstanceDescriptor(objC, New Object() {objT.Left, objT.Top, objT.Width, objT.Height, objT.Units()})

                objC = bl.GetType().GetConstructor(new Type[] { typeof(byte[]), typeof(Type) });
                return(new InstanceDescriptor(objC, new object[] { (Blob)value, ((Blob)value).Type }));
            }

            if (destinationType.IsEnum == true)
            {
                return(BlobUtil.BytesToEnum(bl, destinationType));
            }
            else if (destinationType.IsArray == true && destinationType.GetElementType().IsEnum == true)
            {
                return(BlobUtil.BytesToEnum(bl, destinationType.GetElementType()));
            }

            if (destinationType.IsClass && (destinationType.BaseType == Blob.Types[(int)BlobTypes.Image] || destinationType == Blob.Types[(int)BlobTypes.Image]))
            {
                return(BytesToImage(bl.GrabBytes()));
            }

            switch (destinationType)
            {
            case var @case when @case == typeof(bool):
            {
                return(bl.get_ByteAt(0L) != 0);
            }

            case var case1 when case1 == typeof(BigInteger):
            {
                return(new BigInteger((byte[])bl));
            }

            case var case2 when case2 == typeof(DateTime):
            {
                return(BytesToDate(bl));
            }

            case var case3 when case3 == typeof(DateTime[]):
            {
                return(BytesToDateArray(bl));
            }

            case var case4 when case4 == typeof(byte[]):
            {
                byte[] a;
                a = new byte[(int)(bl.Length - 1L + 1)];
                Array.Copy((byte[])bl, a, bl.Length);
                return(a);
            }

            case var case5 when case5 == typeof(sbyte[]):
            {
                return(ToSByteArray(bl));
            }

            case var case6 when case6 == typeof(Guid[]):
            case var case7 when case7 == typeof(Guid):
            {
                if (destinationType == typeof(Guid))
                {
                    return(new Guid(bl.GrabBytes((IntPtr)0, 16)));
                }

                int    l = 16;
                int    e = (int)(bl.Length / (double)l);
                int    i;
                int    c = (int)(bl.Length - 1L);
                Guid[] gs;
                gs = new Guid[e];
                e  = 0;
                var loopTo = c;
                for (i = 0; l >= 0 ? i <= loopTo : i >= loopTo; i += l)
                {
                    gs[e] = new Guid(bl.GrabBytes((IntPtr)i, l));
                    e    += 1;
                }

                return(gs);
            }

            case var case8 when case8 == typeof(Color[]):
            case var case9 when case9 == typeof(Color):
            {
                if (destinationType == typeof(Color))
                {
                    Color cc;
                    cc = Color.FromArgb(bl);
                    return(cc);
                }

                int     l = 4;
                int     e = (int)(bl.Length / (double)l);
                int     i;
                int     c = (int)(bl.Length - 1L);
                Color[] cs;
                cs = new Color[e];
                e  = 0;
                var ptr     = bl.DangerousGetHandle();
                var loopTo1 = c;
                for (i = 0; l >= 0 ? i <= loopTo1 : i >= loopTo1; i += l)
                {
                    Native.CopyMemory(ref l, ptr, (IntPtr)4);
                    cs[e] = Color.FromArgb(l);
                    ptr   = ptr + l;
                    e    += 1;
                }

                return(cs);
            }

            case var case10 when case10 == typeof(string):
            {
                if (bl.Length == 0L)
                {
                    return("");
                }
                return(bl.ToString());
            }

            case var case11 when case11 == typeof(decimal[]):
            case var case12 when case12 == typeof(decimal):
            {
                decimal[] d;
                int[]     ints = bl;
                if (Conversions.ToBoolean(ints.Length % 4))
                {
                    throw new ArgumentException("Byte array is not aligned for the Decimal data type.");
                    return(null);
                }

                if (destinationType == typeof(decimal))
                {
                    if (ints.Length != 4)
                    {
                        Array.Resize(ref ints, 4);
                    }
                    return(new decimal(ints));
                }

                var dec = new int[4];
                int e   = bl.Count - 1;
                int i;
                d = new decimal[e + 1];
                var loopTo2 = e;
                for (i = 0; i <= loopTo2; i++)
                {
                    Array.Copy(ints, i, dec, 0, 4);
                    d[i] = new decimal(dec);
                }

                return(d);
            }

            case var case13 when case13 == typeof(double):
            {
                return(BitConverter.ToDouble(bl, 0));
            }

            case var case14 when case14 == typeof(float):
            {
                return(BitConverter.ToSingle(bl, 0));
            }

            case var case15 when case15 == typeof(ulong):
            {
                var u = ToULongArray(new[] { BitConverter.ToInt64(bl, 0) });
                return(u[0]);
            }

            case var case16 when case16 == typeof(long):
            {
                return(BitConverter.ToInt64(bl, 0));
            }

            case var case17 when case17 == typeof(uint):
            {
                var u = ToUIntegerArray(new[] { BitConverter.ToInt32(bl, 0) });
                return(u[0]);
            }

            case var case18 when case18 == typeof(int):
            {
                return(BitConverter.ToInt32(bl, 0));
            }

            case var case19 when case19 == typeof(ushort):
            {
                var u = ToUShortArray(new[] { BitConverter.ToInt16(bl, 0) });
                return(u[0]);
            }

            case var case20 when case20 == typeof(short):
            {
                return(BitConverter.ToInt16(bl, 0));
            }

            case var case21 when case21 == typeof(char):
            {
                return(BitConverter.ToChar(bl, 0));
            }

            case var case22 when case22 == typeof(byte):
            {
                return(bl.get_ByteAt(0L));
            }

            case var case23 when case23 == typeof(sbyte):
            {
                var u = ToSByteArray(bl);
                return(u[0]);
            }

            case var case24 when case24 == typeof(double[]):
            case var case25 when case25 == typeof(float[]):
            case var case26 when case26 == typeof(long[]):
            case var case27 when case27 == typeof(ulong[]):
            case var case28 when case28 == typeof(int[]):
            case var case29 when case29 == typeof(uint[]):
            case var case30 when case30 == typeof(short[]):
            case var case31 when case31 == typeof(ushort[]):
            case var case32 when case32 == typeof(char[]):
            {
                object a = Array.CreateInstance(destinationType.GetElementType(), 1);
                int    l;
                int    e;
                int    f = 0;
                IntPtr ptr;
                byte[] b = bl;
                l = Marshal.SizeOf(a((object)0));
                e = (int)(b.Length / (double)l);
                l = b.Length;
                switch (destinationType.GetElementType())
                {
                case var case33 when case33 == typeof(sbyte):
                {
                    a = Array.CreateInstance(typeof(byte), e);
                    break;
                }

                case var case34 when case34 == typeof(ushort):
                {
                    a = Array.CreateInstance(typeof(short), e);
                    break;
                }

                case var case35 when case35 == typeof(uint):
                {
                    a = Array.CreateInstance(typeof(int), e);
                    break;
                }

                case var case36 when case36 == typeof(ulong):
                {
                    a = Array.CreateInstance(typeof(long), e);
                    break;
                }

                default:
                {
                    a = Array.CreateInstance(destinationType.GetElementType(), e);
                    break;
                }
                }

                ptr = Marshal.AllocCoTaskMem(l);
                Marshal.Copy(b, 0, ptr, l);
                Marshal.Copy(ptr, a, (object)0, e);
                Marshal.FreeCoTaskMem(ptr);
                switch (destinationType.GetElementType())
                {
                case var case37 when case37 == typeof(sbyte):
                {
                    a = ToSByteArray((byte[])a);
                    break;
                }

                case var case38 when case38 == typeof(ushort):
                {
                    a = ToUShortArray((short[])a);
                    break;
                }

                case var case39 when case39 == typeof(uint):
                {
                    a = ToUIntegerArray((int[])a);
                    break;
                }

                case var case40 when case40 == typeof(ulong):
                {
                    a = ToULongArray((long[])a);
                    break;
                }
                }

                return(a);
            }
            }

            if (destinationType.IsValueType)
            {
                object o = null;
                BlobToStructure(bl, ref o);
                return(o);
            }

            return(base.ConvertTo(context, culture, value, destinationType));
        }
Example #54
0
 /// <summary>
 /// Transforms a list of Datum and places the transformed data into a Blob.
 /// </summary>
 /// <param name="rgDatum">Specifies a List of SimpleDatum to be transformed.</param>
 /// <param name="blobTransformed">Specifies the Blob where all transformed data is placed.</param>
 /// <param name="cuda">Specifies the CudaDnn connection to Cuda.</param>
 /// <param name="log">Specifies a Log for all output.</param>
 /// <param name="bJustFill">Optionally, specifies to just fill the data blob with the data without actually transforming it.</param>
 public void Transform(List <SimpleDatum> rgDatum, Blob <T> blobTransformed, CudaDnn <T> cuda, Log log, bool bJustFill = false)
 {
     Transform(rgDatum.ToArray(), blobTransformed, cuda, log, bJustFill);
 }
Example #55
0
 static async Task <IEnumerable <KeyVersion> > GetOldVersionKeys(Blob document)
 => await GetOldKeys(document).Select(s => new KeyVersion {
     Key = s
 });
Example #56
0
 internal static Task <byte[]> Load(Blob document) => Load(GetKey(document));
Example #57
0
 public override void Trigger(Blob source)
 {
     this.IsTriggered         = true;
     this.sourceInitialDamage = source.Damage;
     this.ApplyTriggerEffect(source);
 }
Example #58
0
 static string GetKey(Blob document)
 {
     return((document.FolderName + "/" + document.GetFileNameWithoutExtension()).KeepReplacing("//", "/").TrimStart("/"));
 }
Example #59
0
 /// <summary>
 /// Gets mutable access to the string value.
 /// </summary>
 public Blob EnsureWritable() => _blob.IsShared ? (_blob = _blob.ReleaseOne()) : _blob;
Example #60
0
 public PhpString(string x, string y)
 {
     _blob = new Blob(x, y);
 }