working on it ...

Filters

Explore Public Snippets

Sort by

Found 37k snippets matching: function

    public by micurs modified Mar 4, 2014  6865862  353  9  18

    Typescript: passing a class member function as parameter to another function

    Typescript introduces the class construct and the concept of member functions. However if you try to pass a instance member function as parameter to another function the binding with the instance is lost. To solve this problem you can use the capability of javascript (and Typescript) to support closures on anonymous function (or lambda expressio
    ///<reference path='../types/node.d.ts'/>
    ///<reference path='../types/underscore.d.ts'/>
    
    import _ = require("underscore");
    
    class SomePeople {
      values : string[] = [ 'John', 'Mary', 'Peter'];
    
      out() {
        _.each( this.values, (v) => process.stdout.write( v + '\n') );
      }
    }
    // This function accept a function it will execute internally
    function outSomething( outFunc : () => any ) {
      outFunc();
    }
    
    var crowd = new SomePeople();
    
    // This won't work since the actual crowd instance binding will be lost
    outSomething( crowd.out );
    
    // This will work: the closure within the lambda expression retain the
    // crowd instance and its data
    outSomething( () => crowd.out() );
        

    public by micurs modified Dec 23, 2013  747891  18  7  0

    JQuery typescript interface for $.ajax() callbacks

    To use JQuery $.ajax() you must define your callback functions with the following interfaces
    interface OnSuccessAjaxCallback {
      (data: any, textStatus?: string, jqXHR?: JQueryXHR): any;
    }
    interface OnErrorAjaxCallback {
      (jqXHR?: JQueryXHR, textStatus?: string, errorThrow?: string) : any;
    }
    

    public by lbottaro modified Feb 16, 2013  463486  0  7  0

    Excel function to calculate the average of positive data in range

    This excel function calculate the average of a specific range of cells, regarding only positive values. Zero or less than zero value won't be used in average calculation. The italian version of this snippet can be used as well on OpenOffice 3.
    =SUMIF(B2:B6;">0")/MAX(COUNTIF(B2:B6;">0");1)
    
    # Italian version
    =SOMMA.SE(B2:B6;">0")/MAX(CONTA.SE(B2:B6;">0");1)

    public by Zenitram.PRO modified May 4, 2016  404409  3  5  1

    Adding an Element in an Array using a Function.

    Arrays of Objects Remember that an object is just another type, like a string or number but more complex. This means that just as we can make arrays of numbers and strings, we can also make arrays of objects. Here we have our Person constructor which should look familiar. We can use this constructor to make an array of Person objects, similar
    // Our person constructor
    function Person (name, age) {
        this.name = name;
        this.age = age;
    }
    
    // Now we can make an array of people
    var family = new Array();
    family[0] = new Person("alice", 40);
    family[1] = new Person("bob", 42);
    family[2] = new Person("michelle", 8);
    // add the last family member, "timmy", who is 6 years old
    family[3] = new Person("timmy", 6);
                                                    

    public by JMichaelTX modified Feb 26, 2016  351546  2  3  0

    AppleScript Trim Function / Handler Using ASObjC (Shane Stanley)

    AppleScript Trim Function / Handler Using ASObjC (Shane Stanley): trimThis Function AS.applescript
    ###BEGIN~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    #    trimThis()      Trim (remove) Characters from Left and/or Right of String
    #
    #    Ver 1.1          2016-02-25
    #    AUTHOR:          Shane Stanley
    #                     (minor revisions by JMichaelTX)
    #    REF:             MacScripter / Trim [Remove Spaces]
    #                     http://macscripter.net/viewtopic.php?pid=182209#p182209
    #  PARAMETERS:
    #    • pstrCharToTrim    : A list of characters to trim, or true to use default
    #    • pstrSourceText    : The text to be trimmed
    #    • pstrTrimDirection : Direction of Trim left, right or any value for full
    ###——————————————————————————————————————————————————————————————————————————————————
    
    on trimThis(pstrSourceText, pstrCharToTrim, pstrTrimDirection)
      
      --- SET CHARACTERS TO TRIM ---
      
      if pstrCharToTrim = missing value or pstrCharToTrim = true then
        -- SPACE, TAB, RETURN, newline characters (U+000A–U+000D, U+0085)
        -- Equiv to: ASCII character 10, return, ASCII character 0
        
        set setToTrim to current application's NSCharacterSet's whitespaceAndNewlineCharacterSet()
      else
        set setToTrim to current application's NSCharacterSet's characterSetWithCharactersInString:pstrCharToTrim
      end if
      
      set anNSString to current application's NSString's stringWithString:pstrSourceText
      
      --- TRIM STRING BASED ON REQUESTED DIRECTION ---
      
      if pstrTrimDirection = left then -- FROM LEFT SIDE OF STRING
        
        set theRange to anNSString's rangeOfCharacterFromSet:(setToTrim's invertedSet())
        if |length| of theRange = 0 then return ""
        set anNSString to anNSString's substringFromIndex:(theRange's location)
        
      else if pstrTrimDirection = right then -- FROM RIGHT SIDE OF STRING
        set theRange to anNSString's rangeOfCharacterFromSet:(setToTrim's invertedSet()) options:(current application's NSBackwardsSearch)
        if |length| of theRange = 0 then return ""
        set anNSString to anNSString's substringToIndex:(theRange's location)
        
      else -- FROM BOTH SIDES OF STRING
        set anNSString to anNSString's stringByTrimmingCharactersInSet:setToTrim
      end if
      
      return anNSString as text
    end trimThis
    ###END~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    

    public by clsw modified Nov 21, 2014  350003  0  6  1

    Image upload to API, return direct link. (IMGUR)

    Imgur, one of the best image hosts in the world, has a fantastic API, this is a VERY simple and usable implementation of it, just pass an image to the function and it will return the direct link to yout image, heavily commented and easy to use.
    public string UploadImage(Image img)
            {
                //get a dev key from api.imgur.com, anonymous usage (no user auth) only.
                string devkey = "YOUR_CLIENT_ID (e.g. abcde1f234567g8)";
    
                //define the WebClient we'll use to communicate with Imgur.
                WebClient w = new WebClient();
                
                //adds the Header to authorize this application with Imgur, must include a valid CLIENT_ID from 'devkey' above.
                w.Headers.Add("Authorization", "Client-ID " + devkey);
    
                System.Collections.Specialized.NameValueCollection Keys = new System.Collections.Specialized.NameValueCollection();
                try
                {
                    //Converts the image to a byte array so it can be turned into a string for upload.
                    using (MemoryStream stream = new MemoryStream())
                    {
                        img.Save(stream, ImageFormat.Png);
                        Keys.Add("image", Convert.ToBase64String(stream.ToArray()));
                    }
                    
                    //uploads the string-formatted-image and waits for the response.
                    byte[] responseArray = w.UploadValues("https://api.imgur.com/3/image", Keys);
                    dynamic result = Encoding.ASCII.GetString(responseArray);
    
                    //formats the (long and technical) result into just the direct image link.
                    Regex reg = new Regex("link\":\"(.*?)\""); Match match = reg.Match(result);
                    string url = match.ToString().Replace("link\":\"", "").Replace("\"", "").Replace("\\/", "/");
    
                    //returns the online address of the image.
                    return url;
                }
                catch (Exception s) { MessageBox.Show(s.Message); return "err"; }
            }

    public by JMichaelTX modified Feb 11, 2016  263275  0  3  0

    JXA Functions to Get and Set Keyboard Maestro (KM) Variables using JavaScript for Automation (JXA)

    JXA Functions to Get and Set Keyboard Maestro (KM) Variables using JavaScript for Automation (JXA): Get & Set Functions for KM Variables JXA.js
    //=====================================================================	
    function setKMVar(pstrName, pstrValue) {
    //=====================================================================	
    
    	var app = Application.currentApplication()
    	app.includeStandardAdditions = true
    
    	var appKM = Application("Keyboard Maestro Engine")
    		
    	var oVars = appKM.variables
    		
    	try {
    		oVars[pstrName].name();
    		
    	} catch (e) {
    		appKM.variables.push(appKM.Variable({'name': pstrName	}));
    		
    		app.displayNotification(
    			pstrName, 
    			{
    				withTitle: "Set KM Variable",
    				subtitle:  "Variable was Created",
    				soundName: "Basso"
    		  });
    
    		}	// END try/catch
    		
    		oVars[pstrName].value = pstrValue
    		
    		return
    		
    }	// END function setKMVar
    //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
    
    //=====================================================================	
    function getKMVar(pstrName) {
    //=====================================================================	
    
    	var app = Application.currentApplication()
    	app.includeStandardAdditions = true
    
    	var appKM = Application("Keyboard Maestro Engine")
    		
    	var oVars = appKM.variables
    		
    	try {
    		var strValue = oVars[pstrName].value();
    		
    	} catch (e) {
    		
    		strValue = undefined
    		
    		app.beep()
    		var oAns = app.displayAlert('KM Variable does NOT exist', {
    				message: 'Var Name: ' + pstrName,
    				as: 'critical'
    			})
    
    		}	// END try/catch
    				
    		return strValue
    		
    }	// END function getKMVar
    //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
    
    
    

    public by micurs modified Oct 20, 2014  267804  11  7  2

    Check if Event was Triggered or Native

    You can easily add extra argument when triggering an event function programmatically in jquery. This way you can recognize if the event was triggered by a real mouse click rather than a direct call to the .click() function. As seen on http://css-tricks.com/snippets/jquery/check-if-event-was-triggered-or-native/
    $('button').click(function(event, wasTriggered) {
        if (wasTriggered) {
            alert('triggered in code');
        } else {
            alert('triggered by mouse');
        }
    });
    
    $('button').trigger('click', true);

    public by David Grayson modified Aug 20, 2015  198544  1  3  0

    Woe unto any user that doesn't know that "pow" is a standard library function in C. The C standard allows this inconsistent behavior, sadly (Section 7.1.3 of N1124). I think C++ is better, at least based on how GCC behaves.

    Woe unto any user that doesn't know that "pow" is a standard library function in C. The C standard allows this inconsistent behavior, sadly (Section 7.1.3 of N1124). I think C++ is better, at least based on how GCC behaves.: pow_wtf.c
    #include <stdio.h>
    
    double pow(double x, double y)
    {
        return x + y;
    }
    
    int main()
    {
        volatile int y = 1;
        printf("%f\n", pow(10, y));  // prints 11.000000
        printf("%f\n", pow(10, 1));  // prints 10.000000
        return 0;
    }
    
    

    public by sTiLL-iLL modified Dec 1, 2015  235357  1  7  15

    ES5 Array funKtion polly-fillerz...

    just in case your browser sucks
    
    // filler for Array.prototype.bind()
    
    if (!Function.prototype.bind) {
      Function.prototype.bind = function(that) {
        if (typeof this !== 'function') {
          throw new TypeError('obj is not callable');
        }
        var a_Argz = Array.prototype.slice.call(arguments, 1), noop = function() {},
            bFnky = this, bnd  = function() {
              return bFnky.apply(this instanceof noop && that? this: that,
                     a_Argz.concat(Array.prototype.slice.call(arguments)));
            };
    
        noop.prototype = this.prototype;
        bnd.prototype = new noop();
        return bnd;
      };
    }
    
    // different approach for isArray()...
    
    function isArray (list) {
      
    }
    
    if (!Array.isArray) {
      Array.isArray = function(argz) {
        return Object.prototype.toString.call(argz) === '[object Array]';
      };
    }
    
    function isArray (list) {
      if (Array.isArray) {
        return Array.isArray(list);
      }
    }
    
    function isArray (list) {
      if (Array.isArray) {
        return Array.isArray(list);
      }
      return Object.prototype.toString.call(list) === '[object Array]';
    }
    
    
    var isArray;
    var isArray = (function () {
      
    })();
    
    var isArray = (function () {
      if (Array.isArray) {
        return Array.isArray;
      }
    })();
    
    var isArray = (function () {
      if (Array.isArray) {
        return Array.isArray;
      }
      return function (list) {
        return Object.prototype.toString.call(list) === '[object Array]';
      };
    })();
    
    function (list) {
      return Object.prototype.toString.call(list) === '[object Array]';
    }                        
    • Public Snippets
    • Channels Snippets