working on it ...

Filters

Explore Public Snippets

Sort by

Found 51k snippets matching: log

    public by miquelbotanch  264206  5  3  0

    Parse git log with PHP to an array

    Parse git log with PHP to an array: git_history.php
    <?php
    // Orginal Author: Ngo Minh Nam
    $dir = "/path/to/your/repo/";
    chdir($dir);
    $output = array();
    exec('git log -200 --pretty=format:%at%n%an%n%ae%n%h%n%s',$output);
    $history = array();
    $field = 0;
    foreach ($output as $line) {
    	if ($field == 0) {	$commit["date"] = $line;		}else  // unixtimestamp format
    	if ($field == 1) {	$commit["author"] = $line;		}else 
    	if ($field == 2) {	$commit["email"] = $line;		}else 
    	if ($field == 3) {	$commit["version"] = $line;		}else 
    	if ($field == 4) {	$commit["subject"] = $line;
    						$history[] = $commit;
    						unset($commit);
    						$field=-1;
    	}
    	$field++;
    }
    print "<pre>".print_r($history,true)."</pre>";
    
    

    public by huanshuai  219435  1  6  1

    Get logging config and start logging in Python

    import logging
    import os.path
    
    SCRIPT_DIR = os.path.abspath(os.path.dirname(__file__))
    
    def main():
        log_path = os.path.join(SCRIPT_DIR, 'logging.conf')
        logging.config.fileConfig(log_path, disable_existing_loggers=False)
        logger.info("start logging!")
    

    public by marksimon232  283239  0  7  1

    Swift 2: Custom logger that mimics NSLog

    Using this initializer, you can easily build a custom logger that mimics NSLog:
    public func SWLog(format: String, _ args: CVarArgType...) {
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = 
            NSDateFormatter.dateFormatFromTemplate(
                "mm:ss:SSS", options: 0, 
                locale: NSLocale.currentLocale())
        let timeString = 
            dateFormatter.stringFromDate(NSDate())
        print("\(timeString): " + 
            String(format: format, arguments: args))
    }

    public by atucom  192926  0  3  0

    automatically log speedtest results to file with timestamp for logging.

    automatically log speedtest results to file with timestamp for logging.: lolbandwidth.py
    #!/usr/bin/python
    #stolen and modified from the reddit post about the raspbeery pi tweeting at comcast
    #run this every 10 minutes (or w/e) with cron:
    #"crontab -e"
    #*/10 * * * * /home/pi/lolbandwidth.py
    import os
    import sys
    import csv
    import datetime
    import time
    
    def test():
            #run speedtest-cli
            print 'running test'
            #install with "pip install speedtest-cli"
            csvlog = '/home/pi/speed_data.csv'
            a = os.popen("speedtest-cli --simple").read()
            print 'ran'
            #split the 3 line result (ping,down,up)
            lines = a.split('\n')
            print a
            ts = time.time()
            date =datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
            #if speedtest could not connect set the speeds to 0
            if "Cannot" in a:
                    p = 100
                    d = 0
                    u = 0
            #extract the values for ping down and up values
            else:
                    p = lines[0][6:11]
                    d = lines[1][10:14]
                    u = lines[2][8:12]
            print date,p, d, u
            #save the data to file for local network plotting
            out_file = open(csvlog, 'a')
            writer = csv.writer(out_file)
            writer.writerow((ts*1000,p,d,u))
            out_file.close()
            return
            
    if __name__ == '__main__':
            test()
            print 'completed'
    
    
    

    public by merqlove  207877  2  4  2

    AngularJS / NodeWebkit logger service.

    AngularJS / NodeWebkit logger service.: logger.coffee
    'use strict';
    
    angular.module('vc.messages')
    .factory "logger", ['$log', 'NwService', ($log, NwService) ->
      log4js = require('log4js')
    
      log4js.configure {
        appenders: [
          {
            type: 'console'
            layout: {
              type: 'pattern'
              pattern: "%m%n"
            }
            category: 'console'
          },
          {
            type: 'file'
            absolute: true
            filename: NwService.dataPath() + '/app.log'
            category: 'file'
            maxLogSize: 1024*1024
            numBackups: 3
            layout: {
              type: 'pattern'
              pattern: "[%d %r] [%p] - %m%n"
            }
          },
        ]
        levels: {
          "[all]": "INFO",
          "console": NwService.isProduction() ? "OFF" : "DEBUG",
          "file": "ERROR"
        }
      }
    
      consoleLogger = log4js.getLogger('console')
    
      ['Trace','Debug','Info','Warn','Error','Fatal'].forEach (levelString) ->
        level = log4js.levels.toLevel(levelString)
    
        consoleLogger[levelString.toLowerCase()] = () ->
          return false unless consoleLogger.isLevelEnabled(level)
          args = Array.prototype.slice.call(arguments)
          switch levelString
            when 'Info', 'Warn'
              $log[levelString.toLowerCase()](args)
            else
              args.unshift(level)
              consoleLogger.log.apply(consoleLogger, args)
    
      return {
        file: log4js.getLogger('file')
        console: consoleLogger
      }
    ]
    
    

    public by cghersi @ MailUp API DEV  206823  8  6  1

    MailUp REST API - How to subscribe to a particular list several contacts with the "Confirmed Optin" Procedure

    This snippet takes advantage of the MailUp .NET SDK to setup the secure communication towards the server through OAuth2 two leg authentication. You can start digging into the MailUP API world by reading this content: http://help.mailup.com/display/mailupapi/REST+API An instance of MailUpClient class is able to manage one user at a time. A MailU
    public static void SubcribeRecipientsWithDoubleOptin(string clientID, string clientSecret, string username, string password)
    {
        // 1) Setup the MailUp Client:
        MailUpClient client = new MailUpClient(clientID, clientSecret);
        try
        {
            client.RetrieveAccessToken(username, password);
        }
        catch (MailUpException ex)
        {
            Console.WriteLine("Unable to access the service due to " + ex.Message);
            return;
        }
    
        // 2) Subscribe recipients:
        int idList = 1;
        List<ConsoleRecipientItem> recipients = new List<ConsoleRecipientItem>();
        ConsoleRecipientItem recipient1 = new ConsoleRecipientItem()
        {
            Email = "test1@mailup.com",
            Name = "First New Recipient" + DateTime.Now.ToFileTimeUtc(),
            MobileNumber = "3331234567",
            MobilePrefix = "39",
            Fields = new List<ConsoleRecipientDynamicFieldItem>()
            {
                new ConsoleRecipientDynamicFieldItem() { Id = 1, Value = "Name1_" + DateTime.Now.ToFileTimeUtc() },
                new ConsoleRecipientDynamicFieldItem() { Id = 2, Value = "LastName1_" + DateTime.Now.ToFileTimeUtc() }
                //here you can add all the fields you want to add...
            }
        };
        ConsoleRecipientItem recipient2 = new ConsoleRecipientItem()
        {
            Email = "test2@mailup.com",
            Name = "Second New Recipient" + DateTime.Now.ToFileTimeUtc(),
            MobileNumber = "3337654321",
            MobilePrefix = "39",
            Fields = new List<ConsoleRecipientDynamicFieldItem>()
            {
                new ConsoleRecipientDynamicFieldItem() { Id = 1, Value = "Name2_" + DateTime.Now.ToFileTimeUtc() },
                new ConsoleRecipientDynamicFieldItem() { Id = 2, Value = "LastName2_" + DateTime.Now.ToFileTimeUtc() }
                //here you can add all the fields you want to add...
            }
        };
        recipients.Add(recipient1);
        recipients.Add(recipient2);
        int subscriptionResult = 0;
        try
        {
            subscriptionResult = client.AddRecipientsToList(idList, recipients, true);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Cannot perform the operation due to " + ex.Message);
            return;
        }
    
        // 2.1) wait for the end of import task:
        if (subscriptionResult > 0)
        {
            Console.WriteLine("Recipients Import started; import ID:" + subscriptionResult);
    
            //optionally we can check the import status:
            bool completed = false;
            do
            {
                ConsoleImportStatus importStatus = client.CheckImportStatus(subscriptionResult);
                if (importStatus == null)
                {
                    Console.WriteLine("Cannot check the import status for import task #" + subscriptionResult);
                    return;
                }
                completed = importStatus.Completed;
            } while (!completed);
            Console.WriteLine("Recipients Added!");
        }
        else
        {
            Console.WriteLine("An error occurred while adding the recipients.");
            return;
        }
    
        // 3) Retrieve the sendingID of the confirmation email related to the previous task:
        int sendingID = -1;
        try
        {
            sendingID = client.GetSendingIDForImport(subscriptionResult);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Cannot retrieve sending ID due to " + ex.Message);
            return;
        }
        if (sendingID <= 0)
        {
            Console.WriteLine("Cannot retrieve sending ID.");
            return;
        }
    
        // 4) Send the confirmation email:
        EmailSendingItem sendingResult = null;
        try
        {
            sendingResult = client.SendEmailMessage(sendingID);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Cannot send email due to " + ex.Message);
            return;
        }
        if (sendingResult == null)
            Console.WriteLine("Cannot send confirmation email.");
        else
            Console.WriteLine("Confirmation email sent!");
    }
                

    public by Fresh-Dev  172113  3  3  0

    Hiding H1 for logo

    Hiding H1 for logo: hideH1Logo.css
    h1 {
        text-indent: -9999px;
        margin: 0 auto;
        width: 320px;
        height: 85px;
        background: transparent url("images/logo.png") no-repeat scroll;
    }
    
    

    public by fostus  110391  0  3  0

    widget logic parent page

    widget logic parent page: widget_logic.php
    global $post; return is_page('studii')||(in_array(8,get_post_ancestors($post)));
    
    

    public by cghersi @ MailUp API DEV  112988  11  5  0

    How to Retrieve your personal information with MailUp .NET SDK

    This snippet takes advantage of the MailUp .NET SDK to setup the secure communication towards the server through OAuth2 two leg authentication. You can start digging into the MailUP API world by reading this content: http://help.mailup.com/display/mailupapi/REST+API An instance of MailUpClient class is able to manage one user at a time. A MailU
    public static void GetPersonalDataFields(string clientID, string clientSecret, string username, string password)
    {
        // 1) Setup the MailUp Client:
        MailUpClient client = new MailUpClient(clientID, clientSecret);
        try
        {
            client.RetrieveAccessToken(username, password);
        }
        catch (MailUpException ex)
        {
            Console.WriteLine("Unable to access the service due to " + ex.Message);
            return;
        }
    
        // 2) Prepare the input:
        //nothing to do here...
    
        // 3) Invoke the web method:
        CollectionOf<ConsoleDynamicFieldItem> result = null;
        try
        {
            result = client.GetPersonalDataFields();
        }
        catch (Exception ex)
        {
            Console.WriteLine("Cannot perform the operation due to " + ex.Message);
            return;
        }
    
    
        if (result != null)
            Console.WriteLine("Personal Data Fields Retrieved: " + result.Count);
        else
            Console.WriteLine("Cannot retrieve Personal Data Fields.");
    }
    

    public by lbottaro  4864  10  7  0

    How to customize the WordPress Login Logo

    WordPress uses CSS to display a background image -- the WordPress logo -- in the link () inside the heading tag (). In this PHP example, the login_enqueue_scripts hook allows to insert CSS into the head of the login page so you can show your logo instead. You can replace the file named logo.png with the file-name of your logo, and store your logo
    function my_login_logo() { ?>
        <style type="text/css">
            body.login div#login h1 a {
                background-image: url(<?php echo get_bloginfo( 'template_directory' ) ?>/images/logo.png);
                padding-bottom: 30px;
            }
        </style>
    <?php }
    add_action( 'login_enqueue_scripts', 'my_login_logo' );
    
    • Public Snippets
    • Channels Snippets