working on it ...

Filters

Explore Public Snippets

Sort by

Found 19k snippets matching: into

    public by cghersi modified Jan 31, 2014  474492  4  7  0

    C#: Parse a comma separated string into a collection of numeric items

    This method can be used with any separator you need, just setting the 'separator' input
    public static List<long> ParseIntoListOfLongs(string content, char separator = ',')
    {
        List<long> ids = new List<long>();
    
        if (string.IsNullOrEmpty(content))
            return ids;
    
        string[] strIds = content.Split(separator);
        foreach (string str in strIds)
        {
            long id = -1;
            if (long.TryParse(str, out id))
            {
                if (id > 0)
                    ids.Add(id);
            }
        }
    
        return ids;
    }
    

    public by Justin P modified Mar 2, 2016  407608  14  3  0

    How to setup notifications FROM Sonarr INTO Slack!!

    How to setup notifications FROM Sonarr INTO Slack!!: Sonarr-SlackNotifications
    Grab the URL for Incoming WebHooks from Slack:
    
      https://my.slack.com/services/new/incoming-webhook/
    
    After you complete that step, it looks a little like this:
    
      https://hooks.slack.com/TXXXXX/BXXXXX/XXXXXXXXXX
    
    Next create a new bash script with this code:
    
      #!/bin/bash
      curl -X POST --data-urlencode "payload={\"username\": \"Sonarr\", \"icon_emoji\": \":ghost:\", \"text\": \"$sonarr_eventtype: $sonarr_series_title S$sonarr_episodefile_seasonnumber E$sonarr_episodefile_episodenumbers ($sonarr_episodefile_quality)\"}" $1
      
    I personally have mine on the same drive as my Download Directories, so its all in one place - I use OS X FYI.
    
      /Volumes/Downloader/sonarr/scripts/slack.sh
      
    Now set the permissions so it can be executed by everyone, you can modify this if you know what user Sonarr runs under on your system.
    
      sudo chmod a+x ~/scripts/sonarr/slack.sh
      
    Now, go into Sonarr, Settings, "Connect" or the notifications page, and select "Custom Script"
    
    In the Text Fields:
    
      Name: <Name your notification>
      Path: <put full path to slack.sh here>
      Arguments: <put your Slack Webhook URL here>
      
    as in:
    
      Name: Slack
      Path: /Volumes/Downloader/slack/scripts/slack.sh
      Arguments: https://hooks.slack.com/TXXXXX/BXXXXX/XXXXXXXXXX
      
    Copied and edited liberally from <https://github.com/Sonarr/Sonarr/wiki/Sonarr-notifications-in-Slack-using-curl>
    
    

    public by cghersi modified Jan 10, 2017  289540  1  8  0

    How to read a file into a string in Java

    This simple snippet reads a file and put the content into a returned string
    private static String readFileAsString(String filePath) throws java.io.IOException{
    
    	StringBuffer fileData = new StringBuffer(1000);
    	BufferedReader reader = new BufferedReader(new FileReader(filePath));
    	char[] buf = new char[1024];
    	int numRead=0;
    	while((numRead=reader.read(buf)) != -1){
    		String readData = String.valueOf(buf, 0, numRead);
    		fileData.append(readData);
    		buf = new char[1024];
    	}
    
    	reader.close();
    	return fileData.toString();
    }            

    public by Drowze modified Nov 3, 2015  279346  1  3  0

    Compress all files in a folder into individual 7z files

    Compress all files in a folder into individual 7z files: Compress_individual_files.txt
    FOR %i IN (*.*) DO 7z.exe a -m0=LZMA2 -mmt=x "%~ni.7z" "%i"
    
    where x = number of cores
    
    

    public by ejmurray modified Jan 22, 2016  249621  16  3  0

    Photo management script. This script will copy photos from "~/Pictures/iPhone Incoming" into a tree the script creates, with folders representing month and years, and photo names timestamped. Completely based on the work of the amazing Dr. Drang; se...

    Photo management script. This script will copy photos from "~/Pictures/iPhone Incoming" into a tree the script creates, with folders representing month and years, and photo names timestamped. Completely based on the work of the amazing Dr. Drang; see here: http://www.leancrew.com/all-this/2013/10/photo-management-via-the-finder/ You can see mor
    #!/usr/bin/python
    
    import sys
    import os, shutil
    import subprocess
    import os.path
    from datetime import datetime
    
    ######################## Functions #########################
    
    def photoDate(f):
      "Return the date/time on which the given photo was taken."
    
      cDate = subprocess.check_output(['sips', '-g', 'creation', f])
      cDate = cDate.split('\n')[1].lstrip().split(': ')[1]
      return datetime.strptime(cDate, "%Y:%m:%d %H:%M:%S")
    
    
    ###################### Main program ########################
    
    # Where the photos are and where they're going.
    sourceDir = os.environ['HOME'] + '/Pictures/iPhone Incoming'
    destDir = os.environ['HOME'] + '/Pictures/iPhone'
    errorDir = destDir + '/Unsorted/'
    
    # The format for the new file names.
    fmt = "%Y-%m-%d %H-%M-%S"
    
    # The problem files.
    problems = []
    
    # Get all the JPEGs in the source folder.
    photos = os.listdir(sourceDir)
    photos = [ x for x in photos if x[-4:] == '.jpg' or x[-4:] == '.JPG' ]
    
    # Prepare to output as processing occurs
    lastMonth = 0
    lastYear = 0
    
    # Create the destination folder if necessary
    if not os.path.exists(destDir):
      os.makedirs(destDir)
    if not os.path.exists(errorDir):
      os.makedirs(errorDir)
    
    # Copy photos into year and month subfolders. Name the copies according to
    # their timestamps. If more than one photo has the same timestamp, add
    # suffixes 'a', 'b', etc. to the names. 
    for photo in photos:
      # print "Processing %s..." % photo
      original = sourceDir + '/' + photo
      suffix = 'a'
      try:
        pDate = photoDate(original)
        yr = pDate.year
        mo = pDate.month
    
        if not lastYear == yr or not lastMonth == mo:
          sys.stdout.write('\nProcessing %04d-%02d...' % (yr, mo))
          lastMonth = mo
          lastYear = yr
        else:
          sys.stdout.write('.')
        
        newname = pDate.strftime(fmt)
        thisDestDir = destDir + '/%04d/%02d' % (yr, mo)
        if not os.path.exists(thisDestDir):
          os.makedirs(thisDestDir)
    
        duplicate = thisDestDir + '/%s.jpg' % (newname)
        while os.path.exists(duplicate):
          newname = pDate.strftime(fmt) + suffix
          duplicate = destDir + '/%04d/%02d/%s.jpg' % (yr, mo, newname)
          suffix = chr(ord(suffix) + 1)
        shutil.copy2(original, duplicate)
      except Exception:
        shutil.copy2(original, errorDir + photo)
        problems.append(photo)
      except:
        sys.exit("Execution stopped.")
    
    # Report the problem files, if any.
    if len(problems) > 0:
      print "\nProblem files:"
      print "\n".join(problems)
      print "These can be found in: %s" % errorDir
    
    
    

    public by sherazam modified Jan 13, 2016  228084  0  5  0

    How to Insert Check Boxes or HTML into Word Docs during Mail Merge inside .NET Apps

    How to Insert Check Boxes or HTML into Word Docs during Mail Merge inside .NET Apps
    // Enter here the actual content of the snippet.            
    //[C# Code Sample]
     
    using System;
    using System.IO;
    using System.Reflection;
    using Aspose.Words;
    using Aspose.Words.Fields;
    using Aspose.Words.MailMerging;
    
    namespace MailMergeFormFields
    {
        /// <summary>
        /// This sample shows how to insert check boxes and text input form fields during mail merge into a document.
        /// </summary>
        class Program
        {
            /// <summary>
            /// The main entry point for the application.
            /// </summary>
            public static void Main(string[] args)
            {
                Program program = new Program();
                program.Execute();
            }
    
            private void Execute()
            {
                string exeDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + Path.DirectorySeparatorChar;
                string dataDir = new Uri(new Uri(exeDir), @"../../Data/").LocalPath;
    
                // Load the template document.
                Document doc = new Document(dataDir + "Template.doc");
    
                // Setup mail merge event handler to do the custom work.
                doc.MailMerge.FieldMergingCallback = new HandleMergeField();
    
                // This is the data for mail merge.
                String[] fieldNames = new String[] {"RecipientName", "SenderName", "FaxNumber", "PhoneNumber",
                    "Subject", "Body", "Urgent", "ForReview", "PleaseComment"};
                Object[] fieldValues = new Object[] {"Josh", "Jenny", "123456789", "", "Hello",
                    "<b>HTML Body Test message 1</b>", true, false, true};
    
                // Execute the mail merge.
                doc.MailMerge.Execute(fieldNames, fieldValues);
    
                // Save the finished document.
                doc.Save(dataDir + "Template Out.doc");
            }
    
            private class HandleMergeField : IFieldMergingCallback
            {
                /// <summary>
                /// This handler is called for every mail merge field found in the document,
                ///  for every record found in the data source.
                /// </summary>
                void IFieldMergingCallback.FieldMerging(FieldMergingArgs e)
                {
                    if (mBuilder == null)
                        mBuilder = new DocumentBuilder(e.Document);
    
                    // We decided that we want all boolean values to be output as check box form fields.
                    if (e.FieldValue is bool)
                    {
                        // Move the "cursor" to the current merge field.
                        mBuilder.MoveToMergeField(e.FieldName);
    
                        // It is nice to give names to check boxes. Lets generate a name such as MyField21 or so.
                        string checkBoxName = string.Format("{0}{1}", e.FieldName, e.RecordIndex);
    
                        // Insert a check box.
                        mBuilder.InsertCheckBox(checkBoxName, (bool)e.FieldValue, 0);
    
                        // Nothing else to do for this field.
                        return;
                    }
    
                    // We want to insert html during mail merge.
                    if (e.FieldName == "Body")
                    {
                        mBuilder.MoveToMergeField(e.FieldName);
                        mBuilder.InsertHtml((string)e.FieldValue);
                    }
    
                    // Another example, we want the Subject field to come out as text input form field.
                    if (e.FieldName == "Subject")
                    {
                        mBuilder.MoveToMergeField(e.FieldName);
                        string textInputName = string.Format("{0}{1}", e.FieldName, e.RecordIndex);
                        mBuilder.InsertTextInput(textInputName, TextFormFieldType.Regular, "", (string)e.FieldValue, 0);
                    }
                }
    
                void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs args)
                {
                    // Do nothing.
                }
    
                private DocumentBuilder mBuilder;
            }
        }
    }
     
    //[VB.NET Code Sample]
     
    
    Imports Microsoft.VisualBasic
    Imports System
    Imports System.IO
    Imports System.Reflection
    Imports Aspose.Words
    Imports Aspose.Words.Fields
    Imports Aspose.Words.MailMerging
    
    Namespace MailMergeFormFields
        ''' <summary>
        ''' This sample shows how to insert check boxes and text input form fields during mail merge into a document.
        ''' </summary>
        Friend Class Program
            ''' <summary>
            ''' The main entry point for the application.
            ''' </summary>
            Public Shared Sub Main(ByVal args() As String)
                Dim program As New Program()
                program.Execute()
            End Sub
    
            Private Sub Execute()
                Dim exeDir As String = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + Path.DirectorySeparatorChar
                Dim dataDir As String = New Uri(New Uri(exeDir), "../../Data/").LocalPath
    
                ' Load the template document.
                Dim doc As New Document(dataDir & "Template.doc")
    
                ' Setup mail merge event handler to do the custom work.
                doc.MailMerge.FieldMergingCallback = New HandleMergeField()
    
                ' This is the data for mail merge.
                Dim fieldNames() As String = {"RecipientName", "SenderName", "FaxNumber", "PhoneNumber", "Subject", "Body", "Urgent", "ForReview", "PleaseComment"}
                Dim fieldValues() As Object = {"Josh", "Jenny", "123456789", "", "Hello", "<b>HTML Body Test message 1</b>", True, False, True}
    
                ' Execute the mail merge.
                doc.MailMerge.Execute(fieldNames, fieldValues)
    
                ' Save the finished document.
                doc.Save(dataDir & "Template Out.doc")
            End Sub
    
            Private Class HandleMergeField
                Implements IFieldMergingCallback
                ''' <summary>
                ''' This handler is called for every mail merge field found in the document,
                '''  for every record found in the data source.
                ''' </summary>
                Private Sub IFieldMergingCallback_FieldMerging(ByVal e As FieldMergingArgs) Implements IFieldMergingCallback.FieldMerging
                    If mBuilder Is Nothing Then
                        mBuilder = New DocumentBuilder(e.Document)
                    End If
    
                    ' We decided that we want all boolean values to be output as check box form fields.
                    If TypeOf e.FieldValue Is Boolean Then
                        ' Move the "cursor" to the current merge field.
                        mBuilder.MoveToMergeField(e.FieldName)
    
                        ' It is nice to give names to check boxes. Lets generate a name such as MyField21 or so.
                        Dim checkBoxName As String = String.Format("{0}{1}", e.FieldName, e.RecordIndex)
    
                        ' Insert a check box.
                        mBuilder.InsertCheckBox(checkBoxName, CBool(e.FieldValue), 0)
    
                        ' Nothing else to do for this field.
                        Return
                    End If
    
                    ' We want to insert html during mail merge.
                    If e.FieldName = "Body" Then
                        mBuilder.MoveToMergeField(e.FieldName)
                        mBuilder.InsertHtml(DirectCast(e.FieldValue, String))
                    End If
    
                    ' Another example, we want the Subject field to come out as text input form field.
                    If e.FieldName = "Subject" Then
                        mBuilder.MoveToMergeField(e.FieldName)
                        Dim textInputName As String = String.Format("{0}{1}", e.FieldName, e.RecordIndex)
                        mBuilder.InsertTextInput(textInputName, TextFormFieldType.Regular, "", CStr(e.FieldValue), 0)
                    End If
                End Sub
    
                Private Sub ImageFieldMerging(ByVal args As ImageFieldMergingArgs) Implements IFieldMergingCallback.ImageFieldMerging
                    ' Do nothing.
                End Sub
    
                Private mBuilder As DocumentBuilder
            End Class
        End Class
    End Namespace
    
    

    public by cghersi modified Aug 12, 2014  204169  0  6  2

    Embed a browser into SWT Dialog and manage the firing of popups from links in the displayed page

    This is how to manage an embedded browser. Note: unfortunately this seems not working on some versions of Mac OS X.
    try {
    	Browser browser = new Browser(this, SWT.NONE);
    	browser.setJavascriptEnabled(true);
    	browser.setUrl("www.myurl.com");
    	browser.addOpenWindowListener(new OpenWindowListener() {
    		public void open(WindowEvent event) {
    			log.debug("Opening browser:" + event);
    			new Thread( new Runnable() {
    	            public void run() {
    	            	log.debug("some stuff t do here...");
    	            }
    			}).start();
    			
    			final Shell shell = new Shell(event.display);
    		    shell.setText("My Browser page");
    		    shell.setLayout(new FillLayout());
    		    event.browser = new Browser(shell, SWT.NONE);
    		    shell.open();
    		    
    		    event.browser.addCloseWindowListener(new CloseWindowListener() {
    				@Override
    				public void close(WindowEvent event) {
    					log.debug("closing");
    					shell.setVisible(false);
    				}
    			});
    		}
    	});
    } catch (Throwable t) {
    	//on some architecture seems that SWT Browser is not working...
    	log.warn("Cannot display SWT Browser");
    }

    public by christopher modified May 8, 2014  206211  18  3  0

    Draw things with the turtle api built into python. It can be slow due to fact its not an actual GUI system. However it is fun to toy with.

    Draw things with the turtle api built into python. It can be slow due to fact its not an actual GUI system. However it is fun to toy with.: drawUtils.py
    #import sys #Currently not needed
    import time
    from turtle import *
    
    #Draw a box
    def drawBox(x1, x2, y1, y2, penColor="Black", fillColor="Black"):
        turtle = Turtle()
        d = delay()
        delay(0)
        turtle.hideturtle()
        turtle.up()
        turtle.pencolor(penColor)
        turtle.fillcolor(fillColor)
        turtle.goto(x1, y1)
        turtle.down()
        turtle.begin_fill()
        turtle.goto(x1, y2)
        turtle.goto(x2, y2)
        turtle.goto(x2, y1)
        turtle.goto(x1, y1)
        turtle.end_fill()
        turtle.up()
        del turtle
        delay(d)
        del d
        
    def drawCircle(size,
                   x = None, y = None,
                   usePen = True,
                   useFill = True,
                   fillColor = "Black",
                   penColor = ["Black"],
                   penSize = 5,
                   pieces = 1):
        if (pieces < 1):
            pieces = 1
        if not(usePen) and not(useFill):
            raise Exception("No pen or fill makes this useless! Please specify at least one of them as True")
        turtle = Turtle()
    
        #Store previous delay
        d = delay()
    
        #Set to draw instantly.
        delay(0)
    
    
        turtle.up() #Pickup pen
        turtle.ht() #Hide the turtle
        if (x == None): #Set default value
            x = (0-(size/2))
        if (y == None): #Set default value
            y = (0-(size/2))
        
        turtle.goto(x, y) #Goto co ords
        icM = len(penColor) #Check size of array and limit it.
        if (icM < 1):
            raise Exception("penColor must have at least one entry in array!")
    
        b = 0 #Store the first color index
    
    
        incD =  (360/pieces)#Incrementation of degrees./
        if (useFill):
            turtle.begin_fill()
        if (usePen):
            turtle.down()
            turtle.pensize(penSize)
        for i in range(-1, pieces):
            ic = penColor[b]
            turtle.fillcolor(fillColor)
            turtle.pencolor(ic)
            turtle.circle(size, incD)
            b += 1
            if not(b < icM):
                b = 0
        turtle.end_fill()
        #Reset delay
        delay(d)
    
        del turtle
    
    
    
    
    def drawTriangle(h, w, x = None, y = None, useFill = True, usePen = True, penColor = "Black", fillColor = "Black", penSize = 1):
        if (x == None): #Set default values
            x = 0-(w/2)
        if (y == None): #Set default values
            y = 0-(h/2)
        else:
            y += (h/2)
        x1, x2 = x-(w/2), x+(w/2)
        y1, y2 = y-(h/2), y+(h/2)
        d = delay()
        delay(0)
        turtle = Turtle()
        turtle.ht()
        turtle.up()
        turtle.goto(x1, y1)
        if (useFill):
            turtle.begin_fill()
            turtle.fillcolor(fillColor)
        if (usePen):
            turtle.down()
            turtle.pencolor(penColor)
        print("x1=",x1,"x2=",x2,"y1=", y1,"y2=", y2,"y=", y,"x=", x) #Debug code
        turtle.goto(x2, y1)
        turtle.goto(x, y2)
        turtle.goto(x1, y1)
        turtle.up()
        turtle.end_fill()
        del turtle
        delay(d)
    
    def drawHouse(size, x = 0, y = 0):
        pass
    
    
    
    
    
    ########This is a test area for use Simply uncomment code
    setup()
    title("PLACE TITLE HERE")
    
    ##Use the api below here to create simple drawings on a window. Or do more complex stuff.
    ##This is not exactly a proper module so it can not be imported or atleast I do not think. I am still learning python.
    ##Enjoy!
    
    
    
    
    
    

    public by Geometry modified Jul 31, 2016  148153  0  3  0

    GetCommandBuffer: Gets the bytes representing the specified command. returned buffer can be used to streamline multiple writes into one Write on the Socket using the <see cref="M:Enyim.Caching.Memcached.PooledSocket.Write(IList&lt;ArraySegment&lt;b...

    Gets the bytes representing the specified command. returned buffer can be used to streamline multiple writes into one Write on the Socket using the The command to be converted. The buffer containing the bytes representing the command. The command must be terminated by \r\n. The Nagle algorithm is disabled on the socket to speed things up, so it's
    C#
    using System;
    using System.IO;
    using System.Text;
    using System.Collections.Generic;
    
    /// <summary>
    /// Gets the bytes representing the specified command. returned buffer can be used to streamline multiple writes into one Write on the Socket
    /// using the <see cref="M:Enyim.Caching.Memcached.PooledSocket.Write(IList&lt;ArraySegment&lt;byte&gt;&gt;)"/>
    /// </summary>
    /// <param name="value">The command to be converted.</param>
    /// <returns>The buffer containing the bytes representing the command. The command must be terminated by \r\n.</returns>
    /// <remarks>The Nagle algorithm is disabled on the socket to speed things up, so it's recommended to convert a command into a buffer
    /// and use the <see cref="M:Enyim.Caching.Memcached.PooledSocket.Write(IList&lt;ArraySegment&lt;byte&gt;&gt;)"/> to send the command and the additional buffers in one transaction.</remarks>
    public unsafe static IList<ArraySegment<byte>> GetCommandBuffer(string value)
    {
    	var data = new ArraySegment<byte>(Encoding.ASCII.GetBytes(value));
    
    	return new ArraySegment<byte>[] { data };
    }

    public by Fabax modified Aug 30, 2013  153548  0  4  0

    turn string into json p

    turn string into json p: echo Json
    function echoJSON($data) {
      $json = json_encode($data);
    	echo isset($_GET['callback'])
    		? "{$_GET['callback']}($json)"
    		: $json;	
    }
    
    
    • Public Snippets
    • Channels Snippets