working on it ...

Filters

Explore InChannel Snippets

Sort by

Found 500 snippets

    public by DinhoPutz  54  0  3  0

    Somar valores de um objeto no JavaScript

    Soma os campos de mesmo nome nos itens de um objeto
    var objeto = [
        { valor: 10 }, 
        { valor: 15 }
    ];
    
    objeto;
    
    var somaValores = function (novoObjeto) {
        // Aqui realiza a soma dos valores da propriedade "valor" dentro do objeto
        var total2 = novoObjeto.reduce((total, valor) => total + valor.valor, 0);
        // Resultado da soma 
        console.log( total2 );
    }
    somaValores(objeto);

    public by davizin  169  1  3  0

    /cc/

    /cc/
    
    >eu ainda sinto saudades.
    >eu vi ela de longe andando esses dias no shopping, meu coração ameaçou a acelerar eu sussurrei : calma
    >e eu que sou feito de erros e acertos, assumo que ela foi os dois, mas ainda assim foi minha melhor escolha
    >ela continua linda, desde aquele dia que ela disse: "me beija"
    >nós tínhamos uma mania péssima de achar q a gente ia dar certo, planejamos desde as coisas mais simples como viagens e nome dos nossos filhos
    >até coisas mais complexas como um pra sempre.
    >eu queria ligar pra ela e dizer que o tempo me ajudou a entender meus sentimentos, e que nesse lance entre errar e acertar
    >tem um pouco dos dois em nós
    >eu sinto saudade, não dela, mas de tudo o que poderíamos ter sido.
    >ela nunca soube se ficava ou se ia embora. Eu deveria ter entendido isso
    >é complicado falar sobre saudade, porque com as mesmas linhas que escrevo que ainda amo e ainda quero, também posso usá-las para me enforcar.
    >quando se trata dela, sou inapto a me adaptar à falta que ela me faz
    >tem um pouco dela em mim, sempre.
    >lembro dela sentada com um copo de cerveja na mão me olhando em silêncio, rindo baixinho sem motivo
    >lembro do olhar como quem me agradecia por alguma coisa
    >lembro dela me beijar e dizer
    "amor, me leva embora. quero foder com você"
    >lembro do dia em que terminamos, e ela chorando me disse "me leva embora".
    >e isso também fudeu comigo
    

    public by troy  109  2  5  2

    How can I get an image from raw binary pixel content?

    Given a raw binary content, this gives me a stream that can be easily turned into an Image
    public static async Task<InMemoryRandomAccessStream> ImageFromBytes(this byte[] imagePixels, int width, int dpi, Rect frame)
    {
    	//BitmapImage bitmap = new BitmapImage();
    	int xStart = (int)frame.X;
    	int yStart = (int)frame.Y;
    	int frameWidth = (int)frame.Width;
    	int frameHeight = (int)frame.Height;
    	byte[] framePixels = new byte[4 * frameWidth * frameHeight];
    	for (int y = 0; y < frameHeight; y++)
    	{
    		for (int x = 0; x < frameWidth; x++)
    		{
    			int frameOffset = (4 * y * frameWidth) + (4 * x);
    			int imageOffset = (4 * (y + yStart) * width) + (4 * (x + xStart));
    			framePixels[frameOffset] = imagePixels[imageOffset];
    			framePixels[frameOffset + 1] = imagePixels[imageOffset + 1];
    			framePixels[frameOffset + 2] = imagePixels[imageOffset + 2];
    			framePixels[frameOffset + 3] = imagePixels[imageOffset + 3];
    		}
    	}
    
    	InMemoryRandomAccessStream bitmapStream = new InMemoryRandomAccessStream();
    	BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, bitmapStream);
    	encoder.SetPixelData(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Straight, (uint)frameWidth, (uint)frameHeight, dpi, dpi, framePixels);
    
    	try
    	{
    		await encoder.FlushAsync();
    	}
    	catch
    	{
    		return bitmapStream;
    	}
    
    	return bitmapStream;
    }				

    public by troy  370  1  6  1

    What is the size of this file?

    Tells me the size of the given file using the basic properties of UWP StorageFile.
    public static async Task<ulong> GetFileSize(this string filename)
    {
    	StorageFile file = await GetFile(filename);
    	if (file == null)
    		return 0;
    	try
    	{
    		BasicProperties fileSize = await file.GetBasicPropertiesAsync();
    		return fileSize.Size;
    	}
    	catch (Exception e)
    	{
    		s_log.ErrorFormat("Cannot read file {0} due to {1}", filename, e.Message);
    		return 0;
    	}
    }						

    public by guantalamo56  86  0  4  -2

    UWP: Get an image from local resources

    Build an Image object from local resources. The image should be stored as content in the Assets folder of the project.
    public static Image ImageFromName(this string imageName)
    {
    	if (imageName == null)
    		return null;
    	if (!imageName.StartsWith("ms-appx:///Assets/"))
    		imageName = "ms-appx:///Assets/" + imageName;
    	return new Image
    	{
    		Source = new BitmapImage(new Uri(imageName, UriKind.RelativeOrAbsolute))
    	};
    }				

    public by guantalamo56  88  1  4  0

    UWP: retrieve the binary content of a file, given its URL

    This is meant to be used with images, but can be applied to any kind of binary content...
    public static async Task<byte[]> ToByteArrayImage(this Uri imageUri)
    {
    	RandomAccessStreamReference streamRef = RandomAccessStreamReference.CreateFromUri(imageUri);
    	IRandomAccessStreamWithContentType streamWithContent = await streamRef.OpenReadAsync();
    	byte[] buffer = new byte[streamWithContent.Size];
    	await streamWithContent.ReadAsync(buffer.AsBuffer(), (uint)streamWithContent.Size, InputStreamOptions.None);
    	return buffer;
    }				

    public by guantalamo56  90  0  4  0

    UWP: turn byte array into image

    Given a byte array, let's turn it into an Image that can be used in UWP UI contexts.
    public static async Task<Image> ToImage(this byte[] input)
    {
    	if (input == null)
    		return null;
    	BitmapImage biSource = new BitmapImage();
    	using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream())
    	{
    		await stream.WriteAsync(input.AsBuffer());
    		stream.Seek(0);
    		await biSource.SetSourceAsync(stream);
    	}
    
    	return new Image { Source = biSource };
    }					

    public by cicero81  98  0  4  0

    Find line number and member name via reflection

    This method allows to know the line number and the method name of the caller
    using System.Reflection;
    using System.Runtime.CompilerServices;
    
    public static void Fail(this object testClass, string message = "",
    			[CallerLineNumber] int lineNumber = 0,
    			[CallerMemberName] string caller = null)
    {
    	throw new FailTestException(string.Format("{0}.{1} failed at line {2} {3}", 
    		testClass.GetType().FullName, caller, lineNumber, message));
    }				

    public by cicero81  102  1  4  0

    Create your own test suite to run

    This set of methods allow to run a test suite without unit test frameworks like XUnit etc. It can be used across all the C# applications, e.g. UWP
        public static async Task<List<TestResult>> RunTests()
    		{
    			List<TestResult> res = new List<TestResult>();
    
    			// Consider the namespace of the tests:
    			IEnumerable<Type> typelist = GetTypesInNamespace(Assembly.GetExecutingAssembly(), "LiquidTextUWP.Tests");
    			foreach (Type testClass in typelist)
    			{
    				// Get all the test methods in the class:
    				foreach (MethodInfo method in testClass.GetMethods())
    				{
    					LTTestAttribute testAttr = method.GetCustomAttributes<LTTestAttribute>().FirstOrDefault();
    					if (testAttr == null)
    						continue;
    					object instance = Activator.CreateInstance(testClass);
    					try
    					{
    						if (testAttr.IsAsync)
    							await (Task) method.Invoke(instance, null);
    						else
    							method.Invoke(instance, null);
    						res.Add(new TestResult(true));
    					}
    					catch (Exception e)
    					{
    						res.Add(new TestResult(false, string.Format("{0} - {1}", e.Message, e.InnerException?.Message)));
    					}
    				}
    			}
    
    			return res;
    		}
    
    		private static IEnumerable<Type> GetTypesInNamespace(Assembly assembly, string nameSpace)
    		{
    			return assembly.GetTypes().Where(t => (t.Namespace != null) && t.Namespace.StartsWith(nameSpace));
    		}
    		
    		public struct TestResult
    	{
    		public bool Success { get; set; }
    		public string ErrorMsg { get; set; }
    
    		public TestResult(bool success, string msg = "")
    		{
    			Success = success;
    			ErrorMsg = msg;
    		}
    	}
    
    	[AttributeUsage(AttributeTargets.Method)]
    	public class LTTestAttribute : Attribute
    	{
    		public bool IsAsync { get; set; } = false;
    	}

    public by gwarah  975  5  6  0

    Is a file in a directory tree?

    This script is a shell function that performs exactly this check, even if the parameters are symbolic links and/or relative directories. See "How to Use" section to install this snippet
    #!/bin/bash
    # /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
    # * File       : dircontains.sh
    # * Goal       : checks if <parent> direcory contains <file>
    # * Requisites :
    # *     1. SHELL=bash
    # * History    :
    # *   #version;date;description
    # *   0.2.0; 29/07/2018; now can check if any kind of file is in <parent>
    # *   0.1.0; 27/07/2018; first release (tested in bash environment)
    # */
    
    #
    # Tested in: ubuntu 16.04/bash
    #
    
    #
    # How to use
    #
    # 1. put this script into a directory (Ex: ~/scripts)
    #
    # 2. insert this code in your ~/.bashrc:
    # . ~/scripts/dircontains.sh
    #
    # 3. open a new shell session and test it:
    #
    # dircontains <dir_parent> <file>
    #
    # 4.
    # the result is in $? var
    # $?=0, <file> is in <dir_parent>
    # $?=1, <file> is not in <dir_parent>
    # $?=2, error
    #
    
    function dircontains_syntax {
        local msg=$1
        echo "${msg}" >&2
        echo "syntax: dircontains <parent> <file>" >&2
        return 1
    }
    
    function dircontains {
        local result=1
        local parent=""
        local parent_pwd=""
        local child=""
        local child_dir=""
        local child_pwd=""
        local curdir="$(pwd)"
        local v_aux=""
    
        # parameters checking
        if [ $# -ne 2 ]; then
            dircontains_syntax "exactly 2 parameters required"
            return 2
        fi
        parent="${1}"
        child="${2}"
        
        # exchange to absolute path
        parent="$(readlink -f "${parent}")"
        child="$(readlink -f "${child}")"
        dir_child="${child}"
    
        # file/directory checking
        if [ ! -d "${parent}" ];  then
            dircontains_syntax "parent dir ${parent} not a directory or doesn't exist"
            return 2
        elif [ ! -e "${child}" ];  then
            dircontains_syntax "file ${child} not found"
            return 2
        elif [ ! -d "${child}" ];  then
            # not directory? get the path of file
            dir_child=`dirname "${child}"`
        fi
    
        # get directories from $(pwd)
        cd "${parent}"
        parent_pwd="$(pwd)"
        cd "${curdir}"  # to avoid errors due relative paths
        cd "${dir_child}"
        child_pwd="$(pwd)"
    
        # checking if is parent
        [ "${child_pwd:0:${#parent_pwd}}" = "${parent_pwd}" ] && result=0
    
        # return to current directory
        cd "${curdir}"
        return $result
    }												
    • Public Snippets
    • Channels Snippets