working on it ...

Filters

Explore Public Snippets

Sort by

Found 3,166 snippets matching: entry

    public by Geometry  45195  0  4  0

    Main: The main entry point for the application.

    The main entry point for the application.
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new MainForm());
    }

    public by lbottaro  2562  1  6  0

    How to create a Java HashMap and iterate through keys and values

    This is how to simply create a templated Map, using HashMap and loop through its keys and values
    final Map<String, Object> myMap = new HashMap<String, Object>();
            myMap.put("key1", "true");
            myMap.put("key2", "123");
    
    for (Map.Entry<String, Object> entry : myMap.entrySet())
    {
        System.out.println(entry.getKey() + "/" + entry.getValue());
    }                                                          

    public by lbottaro  3074  1  8  0

    How to create a Set<T> map in java

    This simple snippet shows how to instantiate a HashSet map
    import java.util.*;
    
    public class HashSetGenerator {
        public static void main(String[] args) {
            Set<String> s = new HashSet<String>();
            for (String a : args)
                   s.add(a);
                   System.out.println(s.size() + " contains words: " + s);
        }
    }                                                

    public by Geometry  1179  0  5  0

    Main: The main entry point for the application.

    The main entry point for the application.
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new MainForm());
    }

    public by michaelp  1919  0  3  0

    From blog entry "Displaying formatted HTML in Rails"

    From blog entry "Displaying formatted HTML in Rails": gistfile1.html
    <img src="http://i.imgur.com/v7q2NBN.jpg" title="Hosted by 
    imgur.com" height="350" width="350" style="float:left;margin: 0px 30px 30px 0px;" />
    
    <h1 style="margin: 0px 0px 30px 0px;">Displaying formatted HTML in Rails</h1>
    
    <h2 style="margin: 0px 0px 30px 0px;">The problem</h2>
    
    <p style="margin: 0px 0px 30px 0px;">Third party blogging platforms drive me bonkers.  <a href="http://en.wikipedia.org/wiki/Tumblr" target="_blank">Tumblr</a> requires you to be a CSS wizard in order to customize anything.  <a href="http://en.wikipedia.org/wiki/Blogger_(service)" target="_blank">Blogger</a> is pretty good, it still hosts my old <a href="http://captainrecruiter.blogspot.com" target="_blank">Captain Recruiter blog</a>, but it's not designed to be anything more than a standalone blog and I don't like that limitation.  After a few attempts to use it, I still don't understand <a href="http://en.wikipedia.org/wiki/Wordpress" target="_blank">Wordpress</a>.  So given my I-want-a-blog-built-just-for-me itch, I decided to write this blog and then use it to blog!</p>
    
    <p style="margin: 0px 0px 30px 0px;">Given that I'm working to improve my mastery of Ruby on Rails, using Rails to write the blog was the obvious choice.  It took very little time to create a working blog and deploy to my staging server on Heroku.  I'd written a blog for blogging.  Neat!  Now it was time to test the sucker out.  I clicked on the link for creating a new article, entered the title "testing testing 123", and then plopped an h1 header with the text "hello world", clicked submit, and immediately the learning began.</p>
    
    <p style="margin: 0px 0px 30px 0px;">It turns out when you submit content containing HTML via a form and display that content, Rails doesn't automatically render the HTML in the method you expected to see it.  Here's an example:</p>
    
    <ul style="margin: 0px 0px 30px 0px;">
    <li style="margin: 0px 0px 15px 45px;list-style:none;">I was expecting to see this:  <h1 style="display:inline">hello world</h1></li>
    <li style="margin: 0px 0px 15px 45px;list-style:none;">But instead I got this:  &#60h1&#62hello world&#60/h1&#62</li>
    </ul>
    
    <h2 style="margin: 0px 0px 30px 0px;">What's happening here?</h2>
    
    <p style="margin: 0px 0px 30px 0px;">By default, Rails escapes HTML characters before displaying them.  This security feature is meant to protect my lil' ol' blog app from <a href="http://en.wikipedia.org/wiki/Code_injection#HTML-script_injection_.28cross-site_scripting.29" target="_blank">HTML injection</a>, also known as cross site scripting.  I certainly don't want <a href="http://www.youtube.com/watch?v=XAoEtVejYwA" target="_blank">cheeseyman12 inviting himself</a> to my blogging party (I lead an exciting life).</p>
    
    <h2 style="margin: 0px 0px 30px 0px;">The solution</h2>
    
    <p style="margin: 0px 0px 30px 0px;">The solution was as simple as using a method called html_safe, a really dumb name for a something that introduces a security risk.  All I needed to do is make one small change to the HTML:</p>
    
    <ul style="margin: 0px 0px 30px 0px;">
    <li style="margin: 0px 0px 15px 45px;list-style:none;">I was using <%= @entry.body %> to get this:  &#60h1&#62hello world&#60/h1&#62</li>
    <li style="margin: 0px 0px 15px 45px;list-style:none;">Now I'm using <%= @entry.body.html_safe %> to get this:  <h1 style="display:inline">hello world</li>
    </ul>
    
    <h2 style="margin: 0px 0px 30px 0px;">Some context</h2>
    
    <p style="margin: 0px 0px 30px 0px;">I'm writing a blogging tool and I'd like to keep things as simple as possible until I figure out what I really want.  As of now, a blog entry only has a title and body.  As you can see, this blog post has an image, multiple sections, and has been formatted via HTML and CSS.  Some of that CSS lives in my the rails app as a stylesheet and some of the HTML is stored in the show.html.erb.  This rest of the HTML and CSS is stored in the database as the Entry body, getting formatted with the html_safe method.</p>
    
    <p style="margin: 0px 0px 30px 0px;">Here's a gist of <a href="https://gist.github.com/amorphid/6322728" target="_blank">the original HTML</a> stored in the body of this entry.  It's ugly and needs to be seriously refactored (I'm especially annoyed by all of the nasty style tags), but it gets the job done.  As a CSS newbie learning on my own, I'm okay with shipping something messy.  The mess is compartmentalized and can be restyled when I care to do so.  Take a look at the source for this page.  Maybe I came through at a later date and cleaned it up!</p>
    
    

    public by DavidEGrayson  1753  1  3  0

    Prototype, non-working MSYS2 launcher I made a while ago that adds custom entries to its taskbar entry so you can right-click on it and use it to launch different versions of MSYS2.

    Prototype, non-working MSYS2 launcher I made a while ago that adds custom entries to its taskbar entry so you can right-click on it and use it to launch different versions of MSYS2.: msys2launcher.cpp
    #define NTDDI_VERSION NTDDI_WIN7
    #define _WIN32_WINNT _WIN32_WINNT_WIN7
    
    #include <stdio.h>
    #include <unistd.h>
    #include <windows.h>
    #include <propvarutil.h>
    #include <shellapi.h>
    #include <propsys.h>
    #include <propkey.h>
    #include <shobjidl.h>
    #include <objectarray.h>
    
    wchar_t appId[] = L"davidegrayson/msys2launcher";
    
    LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
    int setAppId(HWND);
    int setupTaskbar(HWND);
    int setupTasks(void);
    int launchMsys2(const char * msystem);
    
    DWORD wmTaskbarButtonCreated = -1;
    
    int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
        LPSTR szCmdLine, int iCmdShow)
    {
        wmTaskbarButtonCreated = RegisterWindowMessage("TaskbarButtonCreated");
    
        setvbuf(stderr, NULL, _IONBF, 0);
    
        if(strcmp(szCmdLine, "msys2") == 0)
        {
            return launchMsys2("MSYS2");
        }
    
        static char appName[] = "testwin32";
    
        WNDCLASSEX wndclass;
        wndclass.cbSize = sizeof(wndclass);
        wndclass.style = CS_HREDRAW | CS_VREDRAW;
        wndclass.lpfnWndProc = WndProc;
        wndclass.cbClsExtra = 0;
        wndclass.cbWndExtra = 0;
        wndclass.hInstance = hInstance;
        wndclass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
        wndclass.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
        wndclass.hCursor = LoadCursor(NULL, IDC_ARROW);
        wndclass.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
        wndclass.lpszClassName = appName;
        wndclass.lpszMenuName = NULL;
        RegisterClassEx(&wndclass);
    
        HWND hwnd = CreateWindow(appName, szCmdLine,
            WS_OVERLAPPEDWINDOW,
            CW_USEDEFAULT, CW_USEDEFAULT,
            CW_USEDEFAULT, CW_USEDEFAULT,
            NULL, NULL, hInstance, NULL);
    
        setAppId(hwnd);
    
        ShowWindow(hwnd, iCmdShow);
        UpdateWindow(hwnd);
    
        while(1)
        {
            MSG msg;
            BOOL bRet = GetMessage(&msg, NULL, 0, 0);
            if (bRet == -1)
            {
                // Error
                fprintf(stderr, "GetMessage returned -1\n");
                return 1;
            }
            else if (bRet == 0)
            {
                // WM_QUIT message
                return msg.wParam;
            }
    	TranslateMessage(&msg);
    	DispatchMessage(&msg);
        }
    }
    
    int setAppId(HWND hwnd)
    {
        PROPVARIANT pv;
        HRESULT result = InitPropVariantFromString(appId, &pv);
        if (result != S_OK)
        {
            fprintf(stderr, "InitPropVariantFromString error\n");
            return -1;
        }
    
        IPropertyStore* pps;
        result = SHGetPropertyStoreForWindow(hwnd, IID_PPV_ARGS(&pps));
        if (result != S_OK)
        {
            fprintf(stderr, "SHGetPropertyStoreForWindow failed\n");
            return -1;
        }
    
        result = pps->SetValue(PKEY_AppUserModel_ID, pv);
        if (result != S_OK)
        {
            fprintf(stderr, "SetValue failed\n");
            return -1;
        }
    
        result = pps->Commit();
        if (result != S_OK)
        {
            fprintf(stderr, "Commit failed\n");
            return -1;
        }
    
        return 0;
    }
    
    LRESULT CALLBACK WndProc(HWND hwnd, UINT iMsg, WPARAM wParam, LPARAM lParam)
    {
        switch (iMsg)
        {
        case WM_CREATE:
            return 0;
    
        case WM_PAINT:
        {
            PAINTSTRUCT ps;
    	HDC hdc = BeginPaint(hwnd, &ps);
    	TextOut(hdc, 100, 100, "Hello, world!", 13);
    	EndPaint(hwnd, &ps);
    	return 0;
        }
    
        case WM_DESTROY:
    	PostQuitMessage(0);
    	return 0;
        }
    
        if (iMsg == wmTaskbarButtonCreated)
        {
            setupTaskbar(hwnd);
            setupTasks();
        }
    
        return DefWindowProc(hwnd, iMsg, wParam, lParam);
    }
    
    int setupTaskbar(HWND hwnd)
    {
        fprintf(stderr, "Taskbar button created\n");
    
        ITaskbarList3 * ptl;
        HRESULT result = CoCreateInstance(
            CLSID_TaskbarList, NULL, CLSCTX_ALL,
            IID_ITaskbarList3, (void**)&ptl);
        if (FAILED(result))
        {
            fprintf(stderr, "CoCreateInstance for TaskBarList3 failed\n");
            return 1;
        }
    
        ptl->Release();
        return 0;
    }
    
    int setupTasks()
    {
        HRESULT result;
    
        ICustomDestinationList * cdl;
        result = CoCreateInstance(CLSID_DestinationList, NULL, CLSCTX_ALL, IID_PPV_ARGS(&cdl));
        if (FAILED(result))
        {
            fprintf(stderr, "CoCreateInstance for CustomDestinationList failed.\n");
            return 1;
        }
    
        result = cdl->SetAppID(appId);
        if (FAILED(result))
        {
            fprintf(stderr, "Setting app ID for CDL failed.\n");
            return 1;
        }
    
        IObjectArray * removedItems;
        UINT minSlots;
        result = cdl->BeginList(&minSlots, IID_PPV_ARGS(&removedItems));
        if (FAILED(result))
        {
            fprintf(stderr, "BeginList failed\n");
            return 1;
        }
    
        IObjectCollection * tasks;
        result = CoCreateInstance(CLSID_EnumerableObjectCollection, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&tasks));
        if (FAILED(result))
        {
            fprintf(stderr, "Creating collection failed\n");
            return 1;
        }
    
        {
            IShellLinkW * shellLink;
            result = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&shellLink));
            if (FAILED(result))
            {
                fprintf(stderr, "Creating a ShellLink failed.\n");
                return 1;
            }
    
            shellLink->SetArguments(L"msys2");
            shellLink->SetDescription(L"Launch the MSYS2 Shell");
            shellLink->SetIconLocation(L"C:\\msys64\\msys2.ico", 0);
            shellLink->SetPath(L"C:\\Users\\David\\Documents\\msys2-launcher\\msys2launcher.exe");
    
            IPropertyStore * propertyStore;
            if (FAILED(shellLink->QueryInterface(&propertyStore)))
            {
                fprintf(stderr, "Converting ShellLink to IPropertyStore failed.\n");
                return 1;
            }
    
            PROPVARIANT propertyValue;
            InitPropVariantFromString(L"MSYS2 Shell", &propertyValue);
            propertyStore->SetValue(PKEY_Title, propertyValue);
            propertyStore->Commit();
            PropVariantClear(&propertyValue);
            propertyStore->Release();
    
            tasks->AddObject(shellLink);
            shellLink->Release();
        }
    
        IObjectArray * tasksArray;
        result = tasks->QueryInterface(&tasksArray);
        if (FAILED(result))
        {
            fprintf(stderr, "Converting to array failed\n");
            return 1;
        }
    
        result = cdl->AppendCategory(L"Tasks", tasks);
        if (FAILED(result))
        {
            fprintf(stderr, "Appending category failed: %#lx\n", result);
            return 1;
        }
    
        result = cdl->CommitList();
        if (result != S_OK)
        {
            fprintf(stderr, "CommitList failed\n");
            return 1;
        }
    
        removedItems->Release();
        tasks->Release();
        tasksArray->Release();
        return 0;
    }
    
    int launchMsys2(const char * msystem)
    {
        fprintf(stderr, "Launching msys2 shell\n");
    
        STARTUPINFO startupInfo;
        ZeroMemory(&startupInfo, sizeof(startupInfo));
        startupInfo.cb = sizeof(startupInfo);
    
        // TODO: fill in startupInfo
    
        PROCESS_INFORMATION info;
        ZeroMemory(&info, sizeof(info));
    
        BOOL success = SetEnvironmentVariable("MSYSTEM", msystem);
        if (!success)
        {
            fprintf(stderr, "Failed to set MSYSTEM.\n");
            return 0;
        }
    
    
        char commandLine[] = "mintty --option AppID=davidegrayson/msys2launcher -i /msys2.ico /usr/bin/bash --login";
        success = CreateProcess(
            "C:\\msys64\\usr\\bin\\mintty.exe",
            commandLine,
            NULL,
            NULL,
            FALSE,
            0,
            NULL,  // lpEnvironment
            NULL,  // lpCurrentDirectory
            &startupInfo,
            &info
            );
        if (!success)
        {
            fprintf(stderr, "CreateProcess failed\n");
            return 1;
        }
    
        CloseHandle(info.hProcess);
        CloseHandle(info.hThread);
        return 0;
    }
    
    
    

    public by oscoder  1693  0  4  0

    ORM models should represent a single entry in your table

    ORM models should represent a single entry in your table. Using the ORM find_all() it will want to select all attributes in the table. Since your id should be unique, each row is essentially distinct.
    
    If you are just wanting to get a list of the distinct transaction_timestamp values, you could add a method to your model to retrieve just that. Something like:
    
    public function get_distinct_timestamps()
    {
        return DB::select('transaction_timestamp')
                ->from($this->_table_name)
                ->distinct('transaction_timestamp')
                ->execute()
                ->as_array();
    }
    Then you can use:
    
    $timestamps = Model::factory('transactions')->get_distinct_timestamps();
    foreach($timestamps as $timestamp)
    {
        $value = $timestamp['transaction_timestamp'];
    }
    Of course this is just an example. You might not want to return an array. But you are not limited to using the ORM query methods.
    
    Another option to get ORM objects with distinct transaction_timestamp is to:
    
    Model_Transactions::factory('transactions')
        ->group_by('transaction_timestamp')
        ->find_all();

    public by Zenitram.PRO  2329  21  5  3

    Adding element in an Array.

    We Made a Friend! We have our address book in the contacts array, but what if we make a new friend and want to add them as well? Objects, just like other types of data, can be put into arrays with a array[position] = object statement. To append something to the end of the array, you need to put it in the position one after the last item. S
    var bob = {
        firstName: "Bob",
        lastName: "Jones",
        phoneNumber: "(650) 777-7777",
        email: "bob.jones@example.com"
    };
    
    var mary = {
        firstName: "Mary",
        lastName: "Johnson",
        phoneNumber: "(650) 888-8888",
        email: "mary.johnson@example.com"
    };
    
    var contacts = [bob, mary];
    
    function printPerson(person) {
        console.log(person.firstName + " " + person.lastName);
    }
    
    function list() {
    	var contactsLength = contacts.length;
    	for (var i = 0; i < contactsLength; i++) {
    		printPerson(contacts[i]);
    	}
    }
    
    /*Create a search function
    then call it passing "Jones"*/
    function search(lastName)
    {
        contactsLength = contacts.length;
    	for (var i = 0; i < contactsLength; i++) 
    	{
    	    if (lastName === contacts[i]["lastName"])
    	    {
    	        printPerson(contacts[i]);
    	    }
    	}
    }
    
    function add(firstName, lastName, email, phoneNumber)
    {
        contacts[contacts.length] = {
        firstName: firstName,
        lastName: lastName,
        phoneNumber: phoneNumber,
        email: email
        };
    }
    
    add("paul", "martinez", "paul.martinez@examle.com", "+63 987 654 3210");
    list();
                                        

    public by mprisznyak  2259  0  6  4

    Defensive handling of data structures

    If dictionary key does not exist then initialize the entry
    # some data structure you must work with
    tally = {"girls": 0, "boys": 2}
    
    # more girls, please! 
    # and you must really make sure girls are treated right
    
    # BAD!
    # Look before you leap: LBYL
    if tally.has_key("girls"):
        tally["girls"] += 10
    else:    
        tally["girls"] = 0
        
    # GOOD!
    # It's easier to ask forgiveness than permission:  EAFP
    GIRLS = "girls"  # give no chance for typos: use a 'constant'!
    try:
        tally[GIRLS] += 10
    except KeyError as e:  # no bare exceptions!
        # inform your users about important/unexpected changes
        print "{key} counter initialized ".format(key=e) 
        tally[GIRLS] = 0
    
    # PS: yes, I know about the "setdefault" method of Python dictionaries 
    #     and also about "defaultdict" in the "collections" module
    #     I wanted to demonstrate EAFP vs. LBYL.  
    #     EAFP is almost always better practice in Python than LBYL.

    public by dogutumerdem  2007  3  5  0

    WinMain for CLI

    After creating CLI Empty project, use this snippet to add entry point.
    #include <windows.h>
    #include "MyForm.h"
    
    #using <System.dll>
    #using <System.Windows.Forms.dll>
    
    using namespace System;
    using namespace System::Windows::Forms;
    
    using namespace Project1;
    
    int APIENTRY WinMain(HINSTANCE hInstance,
    	HINSTANCE hPrevInstance,
    	LPSTR lpCmdLine,
    	int nCmdShow)
    {
    	MyForm ^form1 = gcnew MyForm();
    	form1->ShowDialog();
    }
    • Public Snippets
    • Channels Snippets