Programs & Examples On #Boost smart ptr

Ignore mapping one property with Automapper

When mapping a view model back to a domain model, it can be much cleaner to simply validate the source member list rather than the destination member list

Mapper.CreateMap<OrderModel, Orders>(MemberList.Source); 

Now my mapping validation doesn't fail, requiring another Ignore(), every time I add a property to my domain class.

How to set background color of an Activity to white programmatically?

final View rootView = findViewById(android.R.id.content);
rootView.setBackgroundResource(...);

What does an exclamation mark mean in the Swift language?

john is an optional var and it can contain a nil value. To ensure that the value isn't nil use a ! at the end of the var name.

From documentation

“Once you’re sure that the optional does contain a value, you can access its underlying value by adding an exclamation mark (!) to the end of the optional’s name. The exclamation mark effectively says, “I know that this optional definitely has a value; please use it.”

Another way to check non nil value is (optional unwrapping)

    if let j = json {
        // do something with j
    }

How do you log all events fired by an element in jQuery?

I recently found and modified this snippet from an existing SO post that I have not been able to find again but I've found it very useful

// specify any elements you've attached listeners to here
const nodes = [document]

// https://developer.mozilla.org/en-US/docs/Web/Events
const logBrowserEvents = () => {
  const AllEvents = {
    AnimationEvent: ['animationend', 'animationiteration', 'animationstart'],
    AudioProcessingEvent: ['audioprocess'],
    BeforeUnloadEvent: ['beforeunload'],
    CompositionEvent: [
      'compositionend',
      'compositionstart',
      'compositionupdate',
    ],
    ClipboardEvent: ['copy', 'cut', 'paste'],
    DeviceLightEvent: ['devicelight'],
    DeviceMotionEvent: ['devicemotion'],
    DeviceOrientationEvent: ['deviceorientation'],
    DeviceProximityEvent: ['deviceproximity'],
    DragEvent: [
      'drag',
      'dragend',
      'dragenter',
      'dragleave',
      'dragover',
      'dragstart',
      'drop',
    ],
    Event: [
      'DOMContentLoaded',
      'abort',
      'afterprint',
      'beforeprint',
      'cached',
      'canplay',
      'canplaythrough',
      'change',
      'chargingchange',
      'chargingtimechange',
      'checking',
      'close',
      'dischargingtimechange',
      'downloading',
      'durationchange',
      'emptied',
      'ended',
      'error',
      'fullscreenchange',
      'fullscreenerror',
      'input',
      'invalid',
      'languagechange',
      'levelchange',
      'loadeddata',
      'loadedmetadata',
      'noupdate',
      'obsolete',
      'offline',
      'online',
      'open',
      'open',
      'orientationchange',
      'pause',
      'play',
      'playing',
      'pointerlockchange',
      'pointerlockerror',
      'ratechange',
      'readystatechange',
      'reset',
      'seeked',
      'seeking',
      'stalled',
      'submit',
      'success',
      'suspend',
      'timeupdate',
      'updateready',
      'visibilitychange',
      'volumechange',
      'waiting',
    ],
    FocusEvent: [
      'DOMFocusIn',
      'DOMFocusOut',
      'Unimplemented',
      'blur',
      'focus',
      'focusin',
      'focusout',
    ],
    GamepadEvent: ['gamepadconnected', 'gamepaddisconnected'],
    HashChangeEvent: ['hashchange'],
    KeyboardEvent: ['keydown', 'keypress', 'keyup'],
    MessageEvent: ['message'],
    MouseEvent: [
      'click',
      'contextmenu',
      'dblclick',
      'mousedown',
      'mouseenter',
      'mouseleave',
      'mousemove',
      'mouseout',
      'mouseover',
      'mouseup',
      'show',
    ],
    // https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Mutation_events
    MutationNameEvent: ['DOMAttributeNameChanged', 'DOMElementNameChanged'],
    MutationEvent: [
      'DOMAttrModified',
      'DOMCharacterDataModified',
      'DOMNodeInserted',
      'DOMNodeInsertedIntoDocument',
      'DOMNodeRemoved',
      'DOMNodeRemovedFromDocument',
      'DOMSubtreeModified',
    ],
    OfflineAudioCompletionEvent: ['complete'],
    OtherEvent: ['blocked', 'complete', 'upgradeneeded', 'versionchange'],
    UIEvent: [
      'DOMActivate',
      'abort',
      'error',
      'load',
      'resize',
      'scroll',
      'select',
      'unload',
    ],
    PageTransitionEvent: ['pagehide', 'pageshow'],
    PopStateEvent: ['popstate'],
    ProgressEvent: [
      'abort',
      'error',
      'load',
      'loadend',
      'loadstart',
      'progress',
    ],
    SensorEvent: ['compassneedscalibration', 'Unimplemented', 'userproximity'],
    StorageEvent: ['storage'],
    SVGEvent: [
      'SVGAbort',
      'SVGError',
      'SVGLoad',
      'SVGResize',
      'SVGScroll',
      'SVGUnload',
    ],
    SVGZoomEvent: ['SVGZoom'],
    TimeEvent: ['beginEvent', 'endEvent', 'repeatEvent'],
    TouchEvent: [
      'touchcancel',
      'touchend',
      'touchenter',
      'touchleave',
      'touchmove',
      'touchstart',
    ],
    TransitionEvent: ['transitionend'],
    WheelEvent: ['wheel'],
  }

  const RecentlyLoggedDOMEventTypes = {}

  Object.keys(AllEvents).forEach((DOMEvent) => {
    const DOMEventTypes = AllEvents[DOMEvent]

    if (Object.prototype.hasOwnProperty.call(AllEvents, DOMEvent)) {
      DOMEventTypes.forEach((DOMEventType) => {
        const DOMEventCategory = `${DOMEvent} ${DOMEventType}`

        nodes.forEach((node) => {
          node.addEventListener(
            DOMEventType,
            (e) => {
              if (RecentlyLoggedDOMEventTypes[DOMEventCategory]) return

              RecentlyLoggedDOMEventTypes[DOMEventCategory] = true

              // NOTE: throttle continuous events
              setTimeout(() => {
                RecentlyLoggedDOMEventTypes[DOMEventCategory] = false
              }, 1000)

              const isActive = e.target === document.activeElement

              // https://developer.mozilla.org/en-US/docs/Web/API/DocumentOrShadowRoot/activeElement
              const hasActiveElement = document.activeElement !== document.body

              const msg = [
                DOMEventCategory,
                'target:',
                e.target,
                ...(hasActiveElement
                  ? ['active:', document.activeElement]
                  : []),
              ]

              if (isActive) {
                console.info(...msg)
              }
            },
            true,
          )
        })
      })
    }
  })
}
logBrowserEvents()
// export default logBrowserEvents

HTTP URL Address Encoding in Java

You can use a function like this. Complete and modify it to your need :

/**
     * Encode URL (except :, /, ?, &, =, ... characters)
     * @param url to encode
     * @param encodingCharset url encoding charset
     * @return encoded URL
     * @throws UnsupportedEncodingException
     */
    public static String encodeUrl (String url, String encodingCharset) throws UnsupportedEncodingException{
            return new URLCodec().encode(url, encodingCharset).replace("%3A", ":").replace("%2F", "/").replace("%3F", "?").replace("%3D", "=").replace("%26", "&");
    }

Example of use :

String urlToEncode = ""http://www.growup.com/folder/intérieur-à_vendre?o=4";
Utils.encodeUrl (urlToEncode , "UTF-8")

The result is : http://www.growup.com/folder/int%C3%A9rieur-%C3%A0_vendre?o=4

Get json value from response

If response is in json and not a string then

alert(response.id);
or
alert(response['id']);

otherwise

var response = JSON.parse('{"id":"2231f87c-a62c-4c2c-8f5d-b76d11942301"}');
response.id ; //# => 2231f87c-a62c-4c2c-8f5d-b76d11942301

Unable to run Java code with Intellij IDEA

-First Move Your Code Files in side the "src" Folder

-Make sure your Main method is declared like the following

   public class Main {
         public static void main(String []args){


       }
    }

then:

  • Go to Project configurations
  • select Java application,
  • check allow parallel run
  • and select your main class

and it should work

Google Play error "Error while retrieving information from server [DF-DFERH-01]"

I had the same issue because of an incorrect product sku.

I was using android.test.purchase instead of android.test.purchased.

What is the Java equivalent for LINQ?

It sounds like the Linq that everyone is talking about here is just LinqToObjects. Which I believe only offers functionality that can already be accomplished today in Java, but with really ugly syntax.

What I see as the real power of Linq in .Net is that lambda expressions can be used in a context requiring either a Delegate or an Expression and will then be compiled into the appropriate form. This is what allows things like LinqToSql (or anything other than LinqToObjects) to work, and allows them to have a syntax identical to LinqToObjects.

It looks like all of the projects referred to above are only offering the capabilities of LinqToObjects. Which makes me thing that LinqToSql-type functionality is not on the horizon for Java.

What is the regex pattern for datetime (2008-09-01 12:35:45 )?

http://regexlib.com/REDetails.aspx?regexp_id=610

^(?=\d)(?:(?:31(?!.(?:0?[2469]|11))|(?:30|29)(?!.0?2)|29(?=.0?2.(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00)))(?:\x20|$))|(?:2[0-8]|1\d|0?[1-9]))([-./])(?:1[012]|0?[1-9])\1(?:1[6-9]|[2-9]\d)?\d\d(?:(?=\x20\d)\x20|$))?(((0?[1-9]|1[012])(:[0-5]\d){0,2}(\x20[AP]M))|([01]\d|2[0-3])(:[0-5]\d){1,2})?$


This RE validates both dates and/or times patterns. Days in Feb. are also validated for Leap years. Dates: in dd/mm/yyyy or d/m/yy format between 1/1/1600 - 31/12/9999. Leading zeroes are optional. Date separators can be either matching dashes(-), slashes(/) or periods(.) Times: in the hh:MM:ss AM/PM 12 hour format (12:00 AM - 11:59:59 PM) or hh:MM:ss military time format (00:00:00 - 23:59:59). The 12 hour time format: 1) may have a leading zero for the hour. 2) Minutes and seconds are optional for the 12 hour format 3) AM or PM is required and case sensitive. Military time 1) must have a leading zero for all hours less than 10. 2) Minutes are manditory. 3) seconds are optional. Datetimes: combination of the above formats. A date first then a time separated by a space. ex) dd/mm/yyyy hh:MM:ss


Edit: Make sure you copy the RegEx from the regexlib.com website as StackOverflow sometimes removes/destroys special chars.

Make anchor link go some pixels above where it's linked to

I just found an easy solution for myself. Had an margin-top of 15px

HTML

<h2 id="Anchor">Anchor</h2>

CSS

h2{margin-top:-60px; padding-top:75px;}

SQL state [99999]; error code [17004]; Invalid column type: 1111 With Spring SimpleJdbcCall

Probably, you need to insert schema identifier here:

in.addValue("po_system_users", null, OracleTypes.ARRAY, "your_schema.T_SYSTEM_USER_TAB");

Remove leading and trailing spaces?

Should be noted that strip() method would trim any leading and trailing whitespace characters from the string (if there is no passed-in argument). If you want to trim space character(s), while keeping the others (like newline), this answer might be helpful:

sample = '  some string\n'
sample_modified = sample.strip(' ')

print(sample_modified)  # will print 'some string\n'

strip([chars]): You can pass in optional characters to strip([chars]) method. Python will look for occurrences of these characters and trim the given string accordingly.

How to parse a CSV file using PHP

I been seeking the same thing without using some unsupported PHP class. Excel CSV dosn't always use the quote separators and escapes the quotes using "" because the algorithm was probably made back the 80's or something. After looking at several .csv parsers in the comments section on PHP.NET, I seen ones that even used callbacks or eval'd code and they either didnt work like needed or simply didnt work at all. So, I wrote my own routines for this and they work in the most basic PHP configuration. The array keys can either be numeric or named as the fields given in the header row. Hope this helps.

    function SW_ImplodeCSV(array $rows, $headerrow=true, $mode='EXCEL', $fmt='2D_FIELDNAME_ARRAY')
    // SW_ImplodeCSV - returns 2D array as string of csv(MS Excel .CSV supported)
    // AUTHOR: [email protected]
    // RELEASED: 9/21/13 BETA
      { $r=1; $row=array(); $fields=array(); $csv="";
        $escapes=array('\r', '\n', '\t', '\\', '\"');  //two byte escape codes
        $escapes2=array("\r", "\n", "\t", "\\", "\""); //actual code

        if($mode=='EXCEL')// escape code = ""
         { $delim=','; $enclos='"'; $rowbr="\r\n"; }
        else //mode=STANDARD all fields enclosed
           { $delim=','; $enclos='"'; $rowbr="\r\n"; }

          $csv=""; $i=-1; $i2=0; $imax=count($rows);

          while( $i < $imax )
          {
            // get field names
            if($i == -1)
             { $row=$rows[0];
               if($fmt=='2D_FIELDNAME_ARRAY')
                { $i2=0; $i2max=count($row);
                  while( list($k, $v) = each($row) )
                   { $fields[$i2]=$k;
                     $i2++;
                   }
                }
               else //if($fmt='2D_NUMBERED_ARRAY')
                { $i2=0; $i2max=(count($rows[0]));
                  while($i2<$i2max)
                   { $fields[$i2]=$i2;
                     $i2++;
                   }
                }

               if($headerrow==true) { $row=$fields; }
               else                 { $i=0; $row=$rows[0];}
             }
            else
             { $row=$rows[$i];
             }

            $i2=0;  $i2max=count($row); 
            while($i2 < $i2max)// numeric loop (order really matters here)
            //while( list($k, $v) = each($row) )
             { if($i2 != 0) $csv=$csv.$delim;

               $v=$row[$fields[$i2]];

               if($mode=='EXCEL') //EXCEL 2quote escapes
                    { $newv = '"'.(str_replace('"', '""', $v)).'"'; }
               else  //STANDARD
                    { $newv = '"'.(str_replace($escapes2, $escapes, $v)).'"'; }
               $csv=$csv.$newv;
               $i2++;
             }

            $csv=$csv."\r\n";

            $i++;
          }

         return $csv;
       }

    function SW_ExplodeCSV($csv, $headerrow=true, $mode='EXCEL', $fmt='2D_FIELDNAME_ARRAY')
     { // SW_ExplodeCSV - parses CSV into 2D array(MS Excel .CSV supported)
       // AUTHOR: [email protected]
       // RELEASED: 9/21/13 BETA
       //SWMessage("SW_ExplodeCSV() - CALLED HERE -");
       $rows=array(); $row=array(); $fields=array();// rows = array of arrays

       //escape code = '\'
       $escapes=array('\r', '\n', '\t', '\\', '\"');  //two byte escape codes
       $escapes2=array("\r", "\n", "\t", "\\", "\""); //actual code

       if($mode=='EXCEL')
        {// escape code = ""
          $delim=','; $enclos='"'; $esc_enclos='""'; $rowbr="\r\n";
        }
       else //mode=STANDARD 
        {// all fields enclosed
          $delim=','; $enclos='"'; $rowbr="\r\n";
        }

       $indxf=0; $indxl=0; $encindxf=0; $encindxl=0; $enc=0; $enc1=0; $enc2=0; $brk1=0; $rowindxf=0; $rowindxl=0; $encflg=0;
       $rowcnt=0; $colcnt=0; $rowflg=0; $colflg=0; $cell="";
       $headerflg=0; $quotedflg=0;
       $i=0; $i2=0; $imax=strlen($csv);   

       while($indxf < $imax)
         {
           //find first *possible* cell delimiters
           $indxl=strpos($csv, $delim, $indxf);  if($indxl===false) { $indxl=$imax; }
           $encindxf=strpos($csv, $enclos, $indxf); if($encindxf===false) { $encindxf=$imax; }//first open quote
           $rowindxl=strpos($csv, $rowbr, $indxf); if($rowindxl===false) { $rowindxl=$imax; }

           if(($encindxf>$indxl)||($encindxf>$rowindxl))
            { $quoteflg=0; $encindxf=$imax; $encindxl=$imax;
              if($rowindxl<$indxl) { $indxl=$rowindxl; $rowflg=1; }
            }
           else 
            { //find cell enclosure area (and real cell delimiter)
              $quoteflg=1;
              $enc=$encindxf; 
              while($enc<$indxl) //$enc = next open quote
               {// loop till unquoted delim. is found
                 $enc=strpos($csv, $enclos, $enc+1); if($enc===false) { $enc=$imax; }//close quote
                 $encindxl=$enc; //last close quote
                 $indxl=strpos($csv, $delim, $enc+1); if($indxl===false)  { $indxl=$imax; }//last delim.
                 $enc=strpos($csv, $enclos, $enc+1); if($enc===false) { $enc=$imax; }//open quote
                 if(($indxl==$imax)||($enc==$imax)) break;
               }
              $rowindxl=strpos($csv, $rowbr, $enc+1); if($rowindxl===false) { $rowindxl=$imax; }
              if($rowindxl<$indxl) { $indxl=$rowindxl; $rowflg=1; }
            }

           if($quoteflg==0)
            { //no enclosured content - take as is
              $colflg=1;
              //get cell 
             // $cell=substr($csv, $indxf, ($indxl-$indxf)-1);
              $cell=substr($csv, $indxf, ($indxl-$indxf));
            }
           else// if($rowindxl > $encindxf)
            { // cell enclosed
              $colflg=1;

             //get cell - decode cell content
              $cell=substr($csv, $encindxf+1, ($encindxl-$encindxf)-1);

              if($mode=='EXCEL') //remove EXCEL 2quote escapes
                { $cell=str_replace($esc_enclos, $enclos, $cell);
                }
              else //remove STANDARD esc. sceme
                { $cell=str_replace($escapes, $escapes2, $cell);
                }
            }

           if($colflg)
            {// read cell into array
              if( ($fmt=='2D_FIELDNAME_ARRAY') && ($headerflg==1) )
               { $row[$fields[$colcnt]]=$cell; }
              else if(($fmt=='2D_NUMBERED_ARRAY')||($headerflg==0))
               { $row[$colcnt]=$cell; } //$rows[$rowcnt][$colcnt] = $cell;

              $colcnt++; $colflg=0; $cell="";
              $indxf=$indxl+1;//strlen($delim);
            }
           if($rowflg)
            {// read row into big array
              if(($headerrow) && ($headerflg==0))
                {  $fields=$row;
                   $row=array();
                   $headerflg=1;
                }
              else
                { $rows[$rowcnt]=$row;
                  $row=array();
                  $rowcnt++; 
                }
               $colcnt=0; $rowflg=0; $cell="";
               $rowindxf=$rowindxl+2;//strlen($rowbr);
               $indxf=$rowindxf;
            }

           $i++;
           //SWMessage("SW_ExplodeCSV() - colcnt = ".$colcnt."   rowcnt = ".$rowcnt."   indxf = ".$indxf."   indxl = ".$indxl."   rowindxf = ".$rowindxf);
           //if($i>20) break;
         }

       return $rows;
     }

...bob can now go back to his speadsheets

jQuery Set Selected Option Using Next

$('#next').click( function(){
    $('#colored_background option:selected').next('option').attr('selected', 'selected');
    changeBackgroundColor();
});

Working at What is my favorite color?. Click on the arrows.

How to get the last char of a string in PHP?

substr("testers", -1); // returns "s"

Or, for multibytes strings :

substr("multibyte string…", -1); // returns "…"

curl_exec() always returns false

In my case I need to set VERIFYHOST and VERIFYPEER to false, like this:

curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

before the call to curl_exec($ch).

Because i am working between two development environments with self-assigned certificates. With valid certificates there is no need to set VERIFYHOST and VERIFYPEER to false because the curl_exec($ch) method will work and return the response you expect.

File content into unix variable with newlines

This is due to IFS (Internal Field Separator) variable which contains newline.

$ cat xx1
1
2

$ A=`cat xx1`
$ echo $A
1 2

$ echo "|$IFS|"
|       
|

A workaround is to reset IFS to not contain the newline, temporarily:

$ IFSBAK=$IFS
$ IFS=" "
$ A=`cat xx1` # Can use $() as well
$ echo $A
1
2
$ IFS=$IFSBAK

To REVERT this horrible change for IFS:

IFS=$IFSBAK

How to remove non UTF-8 characters from text file

This command:

iconv -f utf-8 -t utf-8 -c file.txt

will clean up your UTF-8 file, skipping all the invalid characters.

-f is the source format
-t the target format
-c skips any invalid sequence

Cross-browser custom styling for file upload button

This seems to take care of business pretty well. A fidde is here:

HTML

<label for="upload-file">A proper input label</label>

<div class="upload-button">

    <div class="upload-cover">
         Upload text or whatevers
    </div>

    <!-- this is later in the source so it'll be "on top" -->
    <input name="upload-file" type="file" />

</div> <!-- .upload-button -->

CSS

/* first things first - get your box-model straight*/
*, *:before, *:after {
    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
}

label {
    /* just positioning */
    float: left; 
    margin-bottom: .5em;
}

.upload-button {
    /* key */
    position: relative;
    overflow: hidden;

    /* just positioning */
    float: left; 
    clear: left;
}

.upload-cover { 
    /* basically just style this however you want - the overlaying file upload should spread out and fill whatever you turn this into */
    background-color: gray;
    text-align: center;
    padding: .5em 1em;
    border-radius: 2em;
    border: 5px solid rgba(0,0,0,.1);

    cursor: pointer;
}

.upload-button input[type="file"] {
    display: block;
    position: absolute;
    top: 0; left: 0;
    margin-left: -75px; /* gets that button with no-pointer-cursor off to the left and out of the way */
    width: 200%; /* over compensates for the above - I would use calc or sass math if not here*/
    height: 100%;
    opacity: .2; /* left this here so you could see. Make it 0 */
    cursor: pointer;
    border: 1px solid red;
}

.upload-button:hover .upload-cover {
    background-color: #f06;
}

List all files in one directory PHP

Check this out : readdir()

This bit of code should list all entries in a certain directory:

if ($handle = opendir('.')) {

    while (false !== ($entry = readdir($handle))) {

        if ($entry != "." && $entry != "..") {

            echo "$entry\n";
        }
    }

    closedir($handle);
}

Edit: miah's solution is much more elegant than mine, you should use his solution instead.

How do I disable Git Credential Manager for Windows?

I struck the same issue on Ubuntu 18.10 (Cosmic Cuttlefish), unable to remove using any normal means. I used git config --global --unset credential.helper, and that seemed to do the trick.

How to simulate browsing from various locations?

The only thing that springs to mind for this is to use a proxy server based in Europe. Either have your colleague set one up [if possible] or find a free proxy. A quick Google search came up with http://www.anonymousinet.com/ as the top result.

JavaScript isset() equivalent

It was really a problem for me when I was accessing a deeper property of an object so I made a function which will return the property value if exist otherwise it will return false. You may use it to save your time,

//Object on which we want to test
var foo = {
    bar: {
        bik: {
            baz: 'Hello world'
        }
    }
};


/*
USE: To get value from the object using it properties supplied (Deeper),
    if found it will return the property value if not found then will return false

You can use this function in two ways
WAY - 1:
Passing an object as parameter 1 and array of the properties as parameter 2
EG: getValueFromObject(foo, ['bar', 'bik', 'baz']);
WAY - 2: (This will work only if, your object available in window object)
Passing an STRING as parameter 1(Just similarly how we retrieve value form object using it's properties - difference is only the quote)
EG: getValueFromObject('foo.bar.bik.baz');
*/
function getValueFromObject(object, properties) {
    if(typeof(object) == 'string') {            //Here we extract our object and it's properties from the string
        properties = object.split('.');
        object = window[properties[0]];
        if(typeof(object) == 'undefined') {
            return false;
        }
        properties.shift();
    }
    var property = properties[0];
    properties.shift();
    if(object != null && typeof(object[property]) != 'undefined') {
        if(typeof(object[property]) == 'object') {
            if(properties.length != 0) {
                return getValueFromObject(object[property], properties);    //Recursive call to the function
            } else {
                return object[property];
            }
        } else {
            return object[property];
        }
    } else {
        return false;
    }
}
console.log(getValueFromObject('fooo.bar.bik.baz'));        //false
console.log(getValueFromObject('foo.bar.bik.baz'));         //Hello world
console.log(getValueFromObject('foo'));                     //false
console.log(getValueFromObject('foo.bar.bik'));             //returns an object { baz: 'Hello World' }
console.log(getValueFromObject(foo, ['bar', 'bik']));       //returns an object { baz: 'Hello World' }
console.log(getValueFromObject(foo, ['bar', 'bik', 'baz']));//Hello world

Automate scp file transfer using a shell script

Try lftp

lftp -u $user,$pass sftp://$host << --EOF--

cd $directory

put $srcfile

quit

--EOF--

Process list on Linux via Python

from psutil import process_iter
from termcolor import colored

names = []
ids = []

x = 0
z = 0
k = 0
for proc in process_iter():
    name = proc.name()
    y = len(name)
    if y>x:
        x = y
    if y<x:
        k = y
    id = proc.pid
    names.insert(z, name)
    ids.insert(z, id)
    z += 1

print(colored("Process Name", 'yellow'), (x-k-5)*" ", colored("Process Id", 'magenta'))
for b in range(len(names)-1):
    z = x
    print(colored(names[b], 'cyan'),(x-len(names[b]))*" ",colored(ids[b], 'white'))

Change SQLite database mode to read-write

Edit the DB: I was having problems editing the db. I ended up having to
sudo chown 'non root username' ts3server.sqlitedb
as long as it wasn't root, i could edit the file. Username is the username of my non root account.

Auto start TeamSpeak: as your non root account
crontab -e
@reboot /path to ts3server/ aka /home/ts3server/ts3server_startscript.sh start

Update OpenSSL on OS X with Homebrew

I had this issue and found that the installation of the newer openssl did actually work, but my PATH was setup incorrectly for it -- my $PATH had the ports path placed before my brew path so it always found the older version of openssl.

The fix for me was to put the path to brew (/usr/local/bin) at the front of my $PATH.

To find out where you're loading openssl from, run which openssl and note the output. It will be the location of the version your system is using when you run openssl. Its going to be somewhere other than the brewpath of "/usr/local/bin". Change your $PATH, close that terminal tab and open a new one, and run which openssl. You should see a different path now, probably under /usr/local/bin. Now run openssl version and you should see the new version you installed "OpenSSL 1.0.1e 11 Feb 2013".

How to get row count in sqlite using Android?

Once you get the cursor you can do

Cursor.getCount()

What is the difference between private and protected members of C++ classes?

Protected members can be accessed from derived classes. Private ones can't.

class Base {

private: 
  int MyPrivateInt;
protected: 
  int MyProtectedInt;
public:
  int MyPublicInt;
};

class Derived : Base
{
public:
  int foo1()  { return MyPrivateInt;} // Won't compile!
  int foo2()  { return MyProtectedInt;} // OK  
  int foo3()  { return MyPublicInt;} // OK
};??

class Unrelated 
{
private:
  Base B;
public:
  int foo1()  { return B.MyPrivateInt;} // Won't compile!
  int foo2()  { return B.MyProtectedInt;} // Won't compile
  int foo3()  { return B.MyPublicInt;} // OK
};

In terms of "best practice", it depends. If there's even a faint possibility that someone might want to derive a new class from your existing one and need access to internal members, make them Protected, not Private. If they're private, your class may become difficult to inherit from easily.

How to fix the "508 Resource Limit is reached" error in WordPress?

I've already encountered this error and this is the best solution I've found:

In your root folder (probably called public_html)please add this code to your .htaccess file...

REPLACE the 00.00.00.000 with YOUR IP address. If you don't know your IP address buzz over to What Is My IP - The IP Address Experts Since 1999

#By Marky WP Root Directory to deny entry for WP-Login & xmlrpc
<Files wp-login.php>
        order deny,allow
        deny from all
        allow from 00.00.00.000
    </Files>
<Files xmlrpc.php>
        order deny,allow
        deny from all
        allow from 00.00.00.000
    </Files>

In your wp-admin folder please add this code to your .htaccess file...

#By Marky WP Admin Folder to deny entry for entire admin folder
order deny,allow
deny from all
allow from 00.00.00.000
<Files index.php>
        order deny,allow
        deny from all
        allow from 00.00.00.000
    </Files>

From: https://www.quora.com/I-am-using-shared-hosting-and-my-I-O-usage-is-full-after-every-minute-What-is-this-I-O-usage-in-cPanel-How-can-I-reduce-it

How to use if statements in LESS

LESS has guard expressions for mixins, not individual attributes.

So you'd create a mixin like this:

.debug(@debug) when (@debug = true) {
    header {
      background-color: yellow;
      #title {
          background-color: orange;
      }
    }

    article {
      background-color: red;
    }
}

And turn it on or off by calling .debug(true); or .debug(false) (or not calling it at all).

Best way to read a large file into a byte array in C#?

I'd say BinaryReader is fine, but can be refactored to this, instead of all those lines of code for getting the length of the buffer:

public byte[] FileToByteArray(string fileName)
{
    byte[] fileData = null;

    using (FileStream fs = File.OpenRead(fileName)) 
    { 
        using (BinaryReader binaryReader = new BinaryReader(fs))
        {
            fileData = binaryReader.ReadBytes((int)fs.Length); 
        }
    }
    return fileData;
}

Should be better than using .ReadAllBytes(), since I saw in the comments on the top response that includes .ReadAllBytes() that one of the commenters had problems with files > 600 MB, since a BinaryReader is meant for this sort of thing. Also, putting it in a using statement ensures the FileStream and BinaryReader are closed and disposed.

Can't use SURF, SIFT in OpenCV

This is what worked for me in September 2020:

  1. Remove previous versions:
    pip uninstall opencv-python
    pip uninstall opencv-contrib-python
    
  2. Install this particular version (3.4.2.16 was no longer available)
    pip install opencv-python==3.4.2.17
    pip install opencv-contrib-python==3.4.2.17
    
  3. Create the detectors with:
    import cv2
    sift = cv2.xfeatures2d.SIFT_create()
    surf = cv2.xfeatures2d.SURF_create()
    

Using SVG as background image

With my solution you're able to get something similar:

svg background image css

Here is bulletproff solution:

Your html: <input class='calendarIcon'/>

Your SVG: i used fa-calendar-alt

fa-calendar-alt

(any IDE may open svg image as shown below)

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><path d="M148 288h-40c-6.6 0-12-5.4-12-12v-40c0-6.6 5.4-12 12-12h40c6.6 0 12 5.4 12 12v40c0 6.6-5.4 12-12 12zm108-12v-40c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm96 0v-40c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm-96 96v-40c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm-96 0v-40c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm192 0v-40c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm96-260v352c0 26.5-21.5 48-48 48H48c-26.5 0-48-21.5-48-48V112c0-26.5 21.5-48 48-48h48V12c0-6.6 5.4-12 12-12h40c6.6 0 12 5.4 12 12v52h128V12c0-6.6 5.4-12 12-12h40c6.6 0 12 5.4 12 12v52h48c26.5 0 48 21.5 48 48zm-48 346V160H48v298c0 3.3 2.7 6 6 6h340c3.3 0 6-2.7 6-6z"/></svg>

To use it at css background-image you gotta encode the svg to address valid string. I used this tool

As far as you got all stuff you need, you're coming to css

.calendarIcon{
      //your url will be something like this:
      background-image: url("data:image/svg+xml,***<here place encoded svg>***");
      background-repeat: no-repeat;
    }

Note: these styling wont have any effect on encoded svg image

.{
      fill: #f00; //neither this
      background-color: #f00; //nor this
}

because all changes over the image must be applied directly to its svg code

<svg xmlns="" path="" fill="#f00"/></svg>

To achive the location righthand i copied some Bootstrap spacing and my final css get the next look:

.calendarIcon{
      background-image: url("data:image/svg+xml,%3Csvg...svg%3E");
      background-repeat: no-repeat;
      padding-right: calc(1.5em + 0.75rem);
      background-position: center right calc(0.375em + 0.1875rem);
      background-size: calc(0.75em + 0.375rem) calc(0.75em + 0.375rem);
    }

Iterate over object in Angular

The dictionary is an object, not an array. I believe ng-repeat requires an array in Angular 2.

The simplest solution would be to create a pipe/filter that converts the object to an array on the fly. That said, you probably want to use an array as @basarat says.

Missing `server' JVM (Java\jre7\bin\server\jvm.dll.)

To Fix The "Missing "server" JVM at C:\Program Files\Java\jre7\bin\server\jvm­­.dll, please install or use the JRE or JDK that contains these missing components.

Follow these steps:

Go to oracle.com and install Java JRE7 (Check if Java 6 is not installed already)

After that, go to C:/Program files/java/jre7/bin

Here, create an folder called Server

Now go into the C:/Program files/java/jre7/bin/client folder

Copy all the data in this folder into the new C:/Program files/java/jre7/bin/Server folder

Converting a string to a date in JavaScript

use this code : (my problem was solved with this code)

function dateDiff(date1, date2){
var diff = {}                           // Initialisation du retour
var tmp = date2 - date1;

tmp = Math.floor(tmp/1000);             // Nombre de secondes entre les 2 dates
diff.sec = tmp % 60;                    // Extraction du nombre de secondes

tmp = Math.floor((tmp-diff.sec)/60);    // Nombre de minutes (partie entière)
diff.min = tmp % 60;                    // Extraction du nombre de minutes

tmp = Math.floor((tmp-diff.min)/60);    // Nombre d'heures (entières)
diff.hour = tmp % 24;                   // Extraction du nombre d'heures

tmp = Math.floor((tmp-diff.hour)/24);   // Nombre de jours restants
diff.day = tmp;

return diff;

}

Passing string parameter in JavaScript function

Change your code to

document.write("<td width='74'><button id='button' type='button' onclick='myfunction(\""+ name + "\")'>click</button></td>")

Javascript Audio Play on click

JavaScript

function playAudio(url) {
  new Audio(url).play();
}


HTML

<img src="image.png" onclick="playAudio('mysound.mp3')">


Supported in most modern browsers and easy to embed into HTML elements.

Simple Android grid example using RecyclerView with GridLayoutManager (like the old GridView)

Although I do like and appreciate Suragch's answer, I would like to leave a note because I found that coding the Adapter (MyRecyclerViewAdapter) to define and expose the Listener method onItemClick isn't the best way to do it, due to not using class encapsulation correctly. So my suggestion is to let the Adapter handle the Listening operations solely (that's his purpose!) and separate those from the Activity that uses the Adapter (MainActivity). So this is how I would set the Adapter class:

MyRecyclerViewAdapter.java

public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder> {

    private String[] mData = new String[0];
    private LayoutInflater mInflater;

    // Data is passed into the constructor
    public MyRecyclerViewAdapter(Context context, String[] data) {
        this.mInflater = LayoutInflater.from(context);
        this.mData = data;
    }

    // Inflates the cell layout from xml when needed
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = mInflater.inflate(R.layout.recyclerview_item, parent, false);
        ViewHolder viewHolder = new ViewHolder(view);
        return viewHolder;
    }

    // Binds the data to the textview in each cell
    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        String animal = mData[position];
        holder.myTextView.setText(animal);
    }

    // Total number of cells
    @Override
    public int getItemCount() {
        return mData.length;
    }

    // Stores and recycles views as they are scrolled off screen
    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        public TextView myTextView;

        public ViewHolder(View itemView) {
            super(itemView);
            myTextView = (TextView) itemView.findViewById(R.id.info_text);
            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View view) {
            onItemClick(view, getAdapterPosition());
        }
    }

    // Convenience method for getting data at click position
    public String getItem(int id) {
        return mData[id];
    }

    // Method that executes your code for the action received
    public void onItemClick(View view, int position) {
        Log.i("TAG", "You clicked number " + getItem(position).toString() + ", which is at cell position " + position);
    }
}

Please note the onItemClick method now defined in MyRecyclerViewAdapter that is the place where you would want to code your tasks for the event/action received.

There is only a small change to be done in order to complete this transformation: the Activity doesn't need to implement MyRecyclerViewAdapter.ItemClickListener anymore, because now that is done completely by the Adapter. This would then be the final modification:

MainActivity.java

public class MainActivity extends AppCompatActivity {

    MyRecyclerViewAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // data to populate the RecyclerView with
        String[] data = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48"};

        // set up the RecyclerView
        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.rvNumbers);
        int numberOfColumns = 6;
        recyclerView.setLayoutManager(new GridLayoutManager(this, numberOfColumns));
        adapter = new MyRecyclerViewAdapter(this, data);
        adapter.setClickListener(this);
        recyclerView.setAdapter(adapter);
    }
}

'Best' practice for restful POST response

Returning the whole object on an update would not seem very relevant, but I can hardly see why returning the whole object when it is created would be a bad practice in a normal use case. This would be useful at least to get the ID easily and to get the timestamps when relevant. This is actually the default behavior got when scaffolding with Rails.

I really do not see any advantage to returning only the ID and doing a GET request after, to get the data you could have got with your initial POST.

Anyway as long as your API is consistent I think that you should choose the pattern that fits your needs the best. There is not any correct way of how to build a REST API, imo.

Python: Best way to add to sys.path relative to the current running script

There is a problem with every answer provided that can be summarized as "just add this magical incantation to the beginning of your script. See what you can do with just a line or two of code." They will not work in every possible situation!

For example, one such magical incantation uses __file__. Unfortunately, if you package your script using cx_Freeze or you are using IDLE, this will result in an exception.

Another such magical incantation uses os.getcwd(). This will only work if you are running your script from the command prompt and the directory containing your script is the current working directory (that is you used the cd command to change into the directory prior to running the script). Eh gods! I hope I do not have to explain why this will not work if your Python script is in the PATH somewhere and you ran it by simply typing the name of your script file.

Fortunately, there is a magical incantation that will work in all the cases I have tested. Unfortunately, the magical incantation is more than just a line or two of code.

import inspect
import os
import sys

# Add script directory to sys.path.
# This is complicated due to the fact that __file__ is not always defined.

def GetScriptDirectory():
    if hasattr(GetScriptDirectory, "dir"):
        return GetScriptDirectory.dir
    module_path = ""
    try:
        # The easy way. Just use __file__.
        # Unfortunately, __file__ is not available when cx_Freeze is used or in IDLE.
        module_path = __file__
    except NameError:
        if len(sys.argv) > 0 and len(sys.argv[0]) > 0 and os.path.isabs(sys.argv[0]):
            module_path = sys.argv[0]
        else:
            module_path = os.path.abspath(inspect.getfile(GetScriptDirectory))
            if not os.path.exists(module_path):
                # If cx_Freeze is used the value of the module_path variable at this point is in the following format.
                # {PathToExeFile}\{NameOfPythonSourceFile}. This makes it necessary to strip off the file name to get the correct
                # path.
                module_path = os.path.dirname(module_path)
    GetScriptDirectory.dir = os.path.dirname(module_path)
    return GetScriptDirectory.dir

sys.path.append(os.path.join(GetScriptDirectory(), "lib"))
print(GetScriptDirectory())
print(sys.path)

As you can see, this is no easy task!

Remove First and Last Character C++

std::string trimmed(std::string str ) {
if(str.length() == 0 ) { return "" ; }
else if ( str == std::string(" ") ) { return "" ; } 
else {
    while(str.at(0) == ' ') { str.erase(0, 1);}
    while(str.at(str.length()-1) == ' ') { str.pop_back() ; }
    return str ;
    } 
}

How can I make Visual Studio wrap lines at 80 characters?

If the problem is simply that you want to know when you pass 80 characters for a single line, which is a common coding guideline limit, you can use a different approach: Editor Guidelines. This will add vertical column guides behind your code.

How to Load an Assembly to AppDomain with all references recursively?

You need to handle the AppDomain.AssemblyResolve or AppDomain.ReflectionOnlyAssemblyResolve events (depending on which load you're doing) in case the referenced assembly is not in the GAC or on the CLR's probing path.

AppDomain.AssemblyResolve

AppDomain.ReflectionOnlyAssemblyResolve

How to get current timestamp in string format in Java? "yyyy.MM.dd.HH.mm.ss"

Use java.util.Date class instead of Timestamp.

String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new Date());

This will get you the current date in the format specified.

What's the difference between nohup and ampersand

myprocess.out & would run the process in background using a subshell. If the current shell is terminated (say by logout), all subshells are also terminated so the background process would also be terminated. The nohup command ignores the HUP signal and thus even if the current shell is terminated, the subshell and myprocess.out would continue to run in the background. Another difference is that & alone doesn't redirect the stdout/stderr so if there are any output or error, those are displayed on the terminal. nohup on the other hand redirect the stdout/stderr to nohup.out or $HOME/nohup.out.

Adding header for HttpURLConnection

If you are using Java 8, use the code below.

URLConnection connection = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection) connection;

String basicAuth = Base64.getEncoder().encodeToString((username+":"+password).getBytes(StandardCharsets.UTF_8));
httpConn.setRequestProperty ("Authorization", "Basic "+basicAuth);

How to validate phone number using PHP?

Since phone numbers must conform to a pattern, you can use regular expressions to match the entered phone number against the pattern you define in regexp.

php has both ereg and preg_match() functions. I'd suggest using preg_match() as there's more documentation for this style of regex.

An example

$phone = '000-0000-0000';

if(preg_match("/^[0-9]{3}-[0-9]{4}-[0-9]{4}$/", $phone)) {
  // $phone is valid
}

Returning value from Thread

From Java 8 onwards we have CompletableFuture. On your case, you may use the method supplyAsync to get the result after execution.

Please find some reference here.

    CompletableFuture<Integer> completableFuture
      = CompletableFuture.supplyAsync(() -> yourMethod());

   completableFuture.get() //gives you the value

Icons missing in jQuery UI

Having the right CSS and JS libraries helps, this solved it for me

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.12.4.js"></script>
<script src="//code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

What is the use of WPFFontCache Service in WPF? WPFFontCache_v0400.exe taking 100 % CPU all the time this exe is running, why?

From MSDN:

The WPF Font Cache service shares font data between WPF applications. The first WPF application you run starts this service if the service is not already running. If you are using Windows Vista, you can set the "Windows Presentation Foundation (WPF) Font Cache 3.0.0.0" service from "Manual" (the default) to "Automatic (Delayed Start)" to reduce the initial start-up time of WPF applications.

There's no harm in disabling it, but WPF apps tend to start faster and load fonts faster with it running.
It is supposed to be a performance optimization. The fact that it is not in your case makes me suspect that perhaps your font cache is corrupted. To clear it, follow these steps:

  1. Stop the WPF Font Cache 4.0 service.
  2. Delete all of the WPFFontCache_v0400* files. In Windows XP, you'll find them in your C:\Documents and Settings\LocalService\Local Settings\Application Data\ folder.
  3. Start the service again.

How do I Geocode 20 addresses without receiving an OVER_QUERY_LIMIT response?

I have just tested Google Geocoder and got the same problem as you have. I noticed I only get the OVER_QUERY_LIMIT status once every 12 requests So I wait for 1 second (that's the minimum delay to wait) It slows down the application but less than waiting 1 second every request

info = getInfos(getLatLng(code)); //In here I call Google API
record(code, info);
generated++; 
if(generated%interval == 0) {
holdOn(delay); // Every x requests, I sleep for 1 second
}

With the basic holdOn method :

private void holdOn(long delay) {
        try {
            Thread.sleep(delay);
        } catch (InterruptedException ex) {
            // ignore
        }
    }

Hope it helps

convert xml to java object using jaxb (unmarshal)

Tests

On the Tests class we will add an @XmlRootElement annotation. Doing this will let your JAXB implementation know that when a document starts with this element that it should instantiate this class. JAXB is configuration by exception, this means you only need to add annotations where your mapping differs from the default. Since the testData property differs from the default mapping we will use the @XmlElement annotation. You may find the following tutorial helpful: http://wiki.eclipse.org/EclipseLink/Examples/MOXy/GettingStarted

package forum11221136;

import javax.xml.bind.annotation.*;

@XmlRootElement
public class Tests {

    TestData testData;

    @XmlElement(name="test-data")
    public TestData getTestData() {
        return testData;
    }

    public void setTestData(TestData testData) {
        this.testData = testData;
    }

}

TestData

On this class I used the @XmlType annotation to specify the order in which the elements should be ordered in. I added a testData property that appeared to be missing. I also used an @XmlElement annotation for the same reason as in the Tests class.

package forum11221136;

import java.util.List;
import javax.xml.bind.annotation.*;

@XmlType(propOrder={"title", "book", "count", "testData"})
public class TestData {
    String title;
    String book;
    String count;
    List<TestData> testData;

    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getBook() {
        return book;
    }
    public void setBook(String book) {
        this.book = book;
    }
    public String getCount() {
        return count;
    }
    public void setCount(String count) {
        this.count = count;
    }
    @XmlElement(name="test-data")
    public List<TestData> getTestData() {
        return testData;
    }
    public void setTestData(List<TestData> testData) {
        this.testData = testData;
    }
}

Demo

Below is an example of how to use the JAXB APIs to read (unmarshal) the XML and populate your domain model and then write (marshal) the result back to XML.

package forum11221136;

import java.io.File;
import javax.xml.bind.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Tests.class);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        File xml = new File("src/forum11221136/input.xml");
        Tests tests = (Tests) unmarshaller.unmarshal(xml);

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(tests, System.out);
    }

}

How to echo text during SQL script execution in SQLPLUS

The prompt command will echo text to the output:

prompt A useful comment.
select(*) from TableA;

Will be displayed as:

SQL> A useful comment.
SQL> 
  COUNT(*)
----------
     0

Correct way to write loops for promise.

function promiseLoop(promiseFunc, paramsGetter, conditionChecker, eachFunc, delay) {
    function callNext() {
        return promiseFunc.apply(null, paramsGetter())
            .then(eachFunc)
    }

    function loop(promise, fn) {
        if (delay) {
            return new Promise(function(resolve) {
                setTimeout(function() {
                    resolve();
                }, delay);
            })
                .then(function() {
                    return promise
                        .then(fn)
                        .then(function(condition) {
                            if (!condition) {
                                return true;
                            }
                            return loop(callNext(), fn)
                        })
                });
        }
        return promise
            .then(fn)
            .then(function(condition) {
                if (!condition) {
                    return true;
                }
                return loop(callNext(), fn)
            })
    }

    return loop(callNext(), conditionChecker);
}


function makeRequest(param) {
    return new Promise(function(resolve, reject) {
        var req = https.request(function(res) {
            var data = '';
            res.on('data', function (chunk) {
                data += chunk;
            });
            res.on('end', function () {
                resolve(data);
            });
        });
        req.on('error', function(e) {
            reject(e);
        });
        req.write(param);
        req.end();
    })
}

function getSomething() {
    var param = 0;

    var limit = 10;

    var results = [];

    function paramGetter() {
        return [param];
    }
    function conditionChecker() {
        return param <= limit;
    }
    function callback(result) {
        results.push(result);
        param++;
    }

    return promiseLoop(makeRequest, paramGetter, conditionChecker, callback)
        .then(function() {
            return results;
        });
}

getSomething().then(function(res) {
    console.log('results', res);
}).catch(function(err) {
    console.log('some error along the way', err);
});

How to search a list of tuples in Python

Your tuples are basically key-value pairs--a python dict--so:

l = [(1,"juca"),(22,"james"),(53,"xuxa"),(44,"delicia")]
val = dict(l)[53]

Edit -- aha, you say you want the index value of (53, "xuxa"). If this is really what you want, you'll have to iterate through the original list, or perhaps make a more complicated dictionary:

d = dict((n,i) for (i,n) in enumerate(e[0] for e in l))
idx = d[53]

How to check if directory exists in %PATH%?

This will look for an exact but case-insensitive match, so mind any trailing backslashes etc.:

for %P in ("%path:;=";"%") do @if /i %P=="PATH_TO_CHECK" echo %P exists in PATH

or, in a batch file (e.g. checkpath.bat) which takes an argument:

@for %%P in ("%path:;=";"%") do @if /i %%P=="%~1" echo %%P exists in PATH

In the latter form, one could call e.g. checkpath "%ProgramFiles%" to see if the specified path already exists in PATH.

Please note that this implementation assumes no semicolons or quotes are present inside a single path item.

C# How to determine if a number is a multiple of another?

I don't get that part about the string stuff, but why don't you use the modulo operator (%) to check if a number is dividable by another? If a number is dividable by another, the other is automatically a multiple of that number.

It goes like that:

   int a = 10; int b = 5;

   // is a a multiple of b 
   if ( a % b == 0 )  ....

How to solve "Kernel panic - not syncing - Attempted to kill init" -- without erasing any user data

I just came across this problem when I replaced a failing disk. I had copied over the system files to the new disk, and was good about replacing the old disk's UUID entry with the new disk's UUID in fstab.

However I had not replaced the UUID in the grub.conf (sometimes menu.lst) file in /boot/grub. So check your grub.conf file, and if the "kernel" line has something like

kernel ... root=UUID=906eaa97-f66a-4d39-a39d-5091c7095987 

it likely has the old disk's UUID. Replace it with the new disk's UUID and run grub-install (if you're in a live CD rescue you may need to chroot or specify the grub directory).

Bulk Record Update with SQL

Your approach is OK

Maybe slightly clearer (to me anyway!)

UPDATE
  T1
SET
  [Description] = t2.[Description]
FROM
   Table1 T1
   JOIN
   [Table2] t2 ON t2.[ID] = t1.DescriptionID

Both this and your query should run the same performance wise because it is the same query, just laid out differently.

REST response code for invalid data

I would recommend 422. It's not part of the main HTTP spec, but it is defined by a public standard (WebDAV) and it should be treated by browsers the same as any other 4xx status code.

From RFC 4918:

The 422 (Unprocessable Entity) status code means the server understands the content type of the request entity (hence a 415(Unsupported Media Type) status code is inappropriate), and the syntax of the request entity is correct (thus a 400 (Bad Request) status code is inappropriate) but was unable to process the contained instructions. For example, this error condition may occur if an XML request body contains well-formed (i.e., syntactically correct), but semantically erroneous, XML instructions.

How to get the first non-null value in Java?

Object coalesce(Object... objects)
{
    for(Object o : object)
        if(o != null)
            return o;
    return null;
}

How do you create a remote Git branch?

First, you must create your branch locally

git checkout -b your_branch

After that, you can work locally in your branch, when you are ready to share the branch, push it. The next command push the branch to the remote repository origin and tracks it

git push -u origin your_branch

Teammates can reach your branch, by doing:

git fetch
git checkout origin/your_branch

You can continue working in the branch and pushing whenever you want without passing arguments to git push (argumentless git push will push the master to remote master, your_branch local to remote your_branch, etc...)

git push

Teammates can push to your branch by doing commits and then push explicitly

... work ...
git commit
... work ...
git commit
git push origin HEAD:refs/heads/your_branch

Or tracking the branch to avoid the arguments to git push

git checkout --track -b your_branch origin/your_branch
... work ...
git commit
... work ...
git commit
git push

Check if program is running with bash shell script?

If you want to execute that command, you should probably change:

PROCESS_NUM='ps -ef | grep "$1" | grep -v "grep" | wc -l'

to:

PROCESS_NUM=$(ps -ef | grep "$1" | grep -v "grep" | wc -l)

AttributeError: 'datetime' module has no attribute 'strptime'

Use the correct call: strptime is a classmethod of the datetime.datetime class, it's not a function in the datetime module.

self.date = datetime.datetime.strptime(self.d, "%Y-%m-%d")

As mentioned by Jon Clements in the comments, some people do from datetime import datetime, which would bind the datetime name to the datetime class, and make your initial code work.

To identify which case you're facing (in the future), look at your import statements

  • import datetime: that's the module (that's what you have right now).
  • from datetime import datetime: that's the class.

MySQL joins and COUNT(*) from another table

Maybe I am off the mark here and not understanding the OP but why are you joining tables?

If you have a table with members and this table has a column named "group_id", you can just run a query on the members table to get a count of the members grouped by the group_id.

SELECT group_id, COUNT(*) as membercount 
FROM members 
GROUP BY group_id 
HAVING membercount > 4

This should have the least overhead simply because you are avoiding a join but should still give you what you wanted.

If you want the group details and description etc, then add a join from the members table back to the groups table to retrieve the name would give you the quickest result.

How to get first N elements of a list in C#?

var firstFiveItems = myList.Take(5);

Or to slice:

var secondFiveItems = myList.Skip(5).Take(5);

And of course often it's convenient to get the first five items according to some kind of order:

var firstFiveArrivals = myList.OrderBy(i => i.ArrivalTime).Take(5);

How to display two digits after decimal point in SQL Server

You can also use below code which helps me:

select convert(numeric(10,2), column_name) as Total from TABLE_NAME

where Total is alias of the field you want.

Cleanest Way to Invoke Cross-Thread Events

I have some code for this online. It's much nicer than the other suggestions; definitely check it out.

Sample usage:

private void mCoolObject_CoolEvent(object sender, CoolObjectEventArgs args)
{
    // You could use "() =>" in place of "delegate"; it's a style choice.
    this.Invoke(delegate
    {
        // Do the dirty work of my method here.
    });
}

set pythonpath before import statements

As also noted in the docs here.
Go to Python X.X/Lib and add these lines to the site.py there,

import sys
sys.path.append("yourpathstring")

This changes your sys.path so that on every load, it will have that value in it..

As stated here about site.py,

This module is automatically imported during initialization. Importing this module will append site-specific paths to the module search path and add a few builtins.

For other possible methods of adding some path to sys.path see these docs

encapsulation vs abstraction real world example

Abstraction

We use many abstractions in our day-to-day lives.Consider a car.Most of us have an abstract view of how a car works.We know how to interact with it to get it to do what we want it to do: we put in gas, turn a key, press some pedals, and so on. But we don't necessarily understand what is going on inside the car to make it move and we don't need to. Millions of us use cars everyday without understanding the details of how they work.Abstraction helps us get to school or work!

A program can be designed as a set of interacting abstractions. In Java, these abstractions are captured in classes. The creator of a class obviusly has to know its interface, just as the driver of a car can use the vehicle without knowing how the engine works.

Encapsulation

Consider a Banking system.Banking system have properties like account no,account type,balance ..etc. If someone is trying to change the balance of the account,attempt can be successful if there is no encapsulation. Therefore encapsulation allows class to have complete control over their properties.

How to reduce the space between <p> tags?

Try

margin: 0;
padding: 0;

If this doesn't work, try

line-height: normal;

How do I prevent mails sent through PHP mail() from going to spam?

You must to add a needle headers:

Sample code :

$headers = "From: [email protected]\r\n";
$headers .= "Reply-To: [email protected]\r\n";
$headers .= "Return-Path: [email protected]\r\n";
$headers .= "CC: [email protected]\r\n";
$headers .= "BCC: [email protected]\r\n";

if ( mail($to,$subject,$message,$headers) ) {
   echo "The email has been sent!";
   } else {
   echo "The email has failed!";
   }
?> 

Form/JavaScript not working on IE 11 with error DOM7011

This issue occurs if the server sends a "Cache-control:no-store" header or sends a "Cache-control:no-cache" header.

Shorthand for if-else statement

?: Operator

If you want to shorten If/Else you can use ?: operator as:

condition ? action-on-true : action-on-false(else)

For instance:

let gender = isMale ? 'Male' : 'Female';

In this case else part is mandatory.

&& Operator

In another case, if you have only if condition you can use && operator as:

condition && action;

For instance:

!this.settings && (this.settings = new TableSettings());

FYI: You have to try to avoid using if-else or at least decrease using it and try to replace it with Polymorphism or Inheritance. Go for being Anti-If guy.

Add Text on Image using PIL

One thing not mentioned in other answers is checking the text size. It is often needed to make sure the text fits the image (e.g. shorten the text if oversized) or to determine location to draw the text (e.g. aligned text top center). Pillow/PIL offers two methods to check the text size, one via ImageFont and one via ImageDraw. As shown below, the font doesn't handle multiple lined, while ImageDraw does.

In [28]: im = Image.new(mode='RGB',size=(240,240))                                                            
In [29]: font = ImageFont.truetype('arial')
In [30]: draw = ImageDraw.Draw(im)
In [31]: t1 = 'hello world!'
In [32]: t2 = 'hello \nworld!'
In [33]: font.getsize(t1), font.getsize(t2) # the height is the same
Out[33]: ((52, 10), (60, 10)) 
In [35]: draw.textsize(t1, font), draw.textsize(t2, font)  # handles multi-lined text
Out[35]: ((52, 10), (27, 24)) 

Error occurred during initialization of VM Could not reserve enough space for object heap Could not create the Java virtual machine

Anyway, here is how to fix it:

Go to Start->Control Panel->System->Advanced(tab)->Environment Variables->System Variables->New:

Variable name: _JAVA_OPTIONS

Variable value: -Xmx512M

taken from this link

How can I find the number of days between two Date objects in Ruby?

irb(main):005:0> a = Date.parse("12/1/2010")
=> #<Date: 4911063/2,0,2299161>

irb(main):007:0> b = Date.parse("12/21/2010")
=> #<Date: 4911103/2,0,2299161>

irb(main):016:0> c = b.mjd - a.mjd
=> 20

This uses a Modified Julian Day Number.

From wikipedia:

The Julian date (JD) is the interval of time in days and fractions of a day since January 1, 4713 BC Greenwich noon, Julian proleptic calendar.

Undoing a 'git push'

git push origin +7f6d03:master

This will revert your repo to mentioned commit number

How to encode URL parameters?

Using new ES6 Object.entries(), it makes for a fun little nested map/join:

_x000D_
_x000D_
const encodeGetParams = p => _x000D_
  Object.entries(p).map(kv => kv.map(encodeURIComponent).join("=")).join("&");_x000D_
_x000D_
const params = {_x000D_
  user: "María Rodríguez",_x000D_
  awesome: true,_x000D_
  awesomeness: 64,_x000D_
  "ZOMG+&=*(": "*^%*GMOZ"_x000D_
};_x000D_
_x000D_
console.log("https://example.com/endpoint?" + encodeGetParams(params))
_x000D_
_x000D_
_x000D_

How do I retrieve an HTML element's actual width and height?

Here is the code for WKWebView what determines a height of specific Dom element (doesn't work properly for whole page)

let html = "<body><span id=\"spanEl\" style=\"font-family: '\(taskFont.fontName)'; font-size: \(taskFont.pointSize - 4.0)pt; color: rgb(\(red), \(blue), \(green))\">\(textValue)</span></body>"
webView.navigationDelegate = self
webView.loadHTMLString(taskHTML, baseURL: nil)

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    webView.evaluateJavaScript("document.getElementById(\"spanEl\").getBoundingClientRect().height;") { [weak self] (response, error) in
        if let nValue = response as? NSNumber {

        }
    }
}

File path for project files?

You would do something like this to get the path "Data\ich_will.mp3" inside your application environments folder.

string fileName = "ich_will.mp3";
string path = Path.Combine(Environment.CurrentDirectory, @"Data\", fileName);

In my case it would return the following:

C:\MyProjects\Music\MusicApp\bin\Debug\Data\ich_will.mp3

I use Path.Combine and Environment.CurrentDirectory in my example. These are very useful and allows you to build a path based on the current location of your application. Path.Combine combines two or more strings to create a location, and Environment.CurrentDirectory provides you with the working directory of your application.

The working directory is not necessarily the same path as where your executable is located, but in most cases it should be, unless specified otherwise.

How to solve error: "Clock skew detected"?

I am going to answer my own question.

I added the following lines of code to my Makefile and it fixed the "clock skew" problem:

clean:  
    find . -type f | xargs touch
    rm -rf $(OBJS)

Emulator in Android Studio doesn't start

I'd like to post a link to this answer as it might help out any persons in this thread running into issues starting a virtual device with more then 768 mb of memory; How to make an AVD with > 768MB RAM To emulate Galaxy devices

What is href="#" and why is it used?

It's a link that links to nowhere essentially (it just adds "#" onto the URL). It's used for a number of different reasons. For instance, if you're using some sort of JavaScript/jQuery and don't want the actual HTML to link anywhere.

It's also used for page anchors, which is used to redirect to a different part of the page.

android - save image into gallery

 String filePath="/storage/emulated/0/DCIM"+app_name;
    File dir=new File(filePath);
    if(!dir.exists()){
        dir.mkdir();
    }

This code is in onCreate method.This code is for creating a directory of app_name. Now,this directory can be accessed using default file manager app in android. Use this string filePath wherever required to set your destination folder. I am sure this method works on Android 7 too because I tested on it.Hence,it can work on other versions of android too.

Maven plugin in Eclipse - Settings.xml file is missing

The settings file is never created automatically, you must create it yourself, whether you use embedded or "real" maven.

Create it at the following location <your home folder>/.m2/settings.xml e.g. C:\Users\YourUserName\.m2\settings.xml on Windows or /home/YourUserName/.m2/settings.xml on Linux

Here's an empty skeleton you can use:

<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
                      http://maven.apache.org/xsd/settings-1.0.0.xsd">
  <localRepository/>
  <interactiveMode/>
  <usePluginRegistry/>
  <offline/>
  <pluginGroups/>
  <servers/>
  <mirrors/>
  <proxies/>
  <profiles/>
  <activeProfiles/>
</settings>

If you use Eclipse to edit it, it will give you auto-completion when editing it.

And here's the Maven settings.xml Reference page

Asp Net Web API 2.1 get client IP address

I think this is the most clear solution, using an extension method:

public static class HttpRequestMessageExtensions
{
    private const string HttpContext = "MS_HttpContext";
    private const string RemoteEndpointMessage = "System.ServiceModel.Channels.RemoteEndpointMessageProperty";

    public static string GetClientIpAddress(this HttpRequestMessage request)
    {
        if (request.Properties.ContainsKey(HttpContext))
        {
            dynamic ctx = request.Properties[HttpContext];
            if (ctx != null)
            {
                return ctx.Request.UserHostAddress;
            }
        }

        if (request.Properties.ContainsKey(RemoteEndpointMessage))
        {
            dynamic remoteEndpoint = request.Properties[RemoteEndpointMessage];
            if (remoteEndpoint != null)
            {
                return remoteEndpoint.Address;
            }
        }

        return null;
    }
}

So just use it like:

var ipAddress = request.GetClientIpAddress();

We use this in our projects.

Source/Reference: Retrieving the client’s IP address in ASP.NET Web API

Twitter Bootstrap 3: How to center a block

center-block can be found in bootstrap 3.0 in utilities.less on line 12 and mixins.less on line 39

Preventing form resubmission

The PRG pattern can only prevent the resubmission caused by page refreshing. This is not a 100% safe measure.

Usually, I will take actions below to prevent resubmission:

  1. Client Side - Use javascript to prevent duplicate clicks on a button which will trigger form submission. You can just disable the button after the first click.

  2. Server Side - I will calculate a hash on the submitted parameters and save that hash in session or database, so when the duplicated submission was received we can detect the duplication then proper response to the client. However, you can manage to generate a hash at the client side.

In most of the occasions, these measures can help to prevent resubmission.

How can I use "e" (Euler's number) and power operation in python 2.7

Power is ** and e^ is math.exp:

x.append(1 - math.exp(-0.5 * (value1*value2)**2))

Capture Signature using HTML5 and iPad

Here's another canvas based version with variable width (based on drawing velocity) curves: demo at http://szimek.github.io/signature_pad and code at https://github.com/szimek/signature_pad.

signature sample

Mythical man month 10 lines per developer day - how close on large projects?

I like this quote:

If we wish to count lines of code, we should not regard them as "lines produced" but as "lines spent". - Edsger Dijkstra

Some times you have contributed more by removing code than adding

android download pdf from url then open it with a pdf reader

Hi the problem is in FileDownloader class

 urlConnection.setRequestMethod("GET");
    urlConnection.setDoOutput(true);

You need to remove the above two lines and everything will work fine. Please mark the question as answered if it is working as expected.

Latest solution for the same problem is updated Android PDF Write / Read using Android 9 (API level 28)

Attaching the working code with screenshots.

enter image description here

enter image description here

MainActivity.java

package com.example.downloadread;

import java.io.File;
import java.io.IOException;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    public void download(View v)
    {
        new DownloadFile().execute("http://maven.apache.org/maven-1.x/maven.pdf", "maven.pdf"); 
    }

    public void view(View v)
    {
        File pdfFile = new File(Environment.getExternalStorageDirectory() + "/testthreepdf/" + "maven.pdf");  // -> filename = maven.pdf
        Uri path = Uri.fromFile(pdfFile);
        Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
        pdfIntent.setDataAndType(path, "application/pdf");
        pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        try{
            startActivity(pdfIntent);
        }catch(ActivityNotFoundException e){
            Toast.makeText(MainActivity.this, "No Application available to view PDF", Toast.LENGTH_SHORT).show();
        }
    }

    private class DownloadFile extends AsyncTask<String, Void, Void>{

        @Override
        protected Void doInBackground(String... strings) {
            String fileUrl = strings[0];   // -> http://maven.apache.org/maven-1.x/maven.pdf
            String fileName = strings[1];  // -> maven.pdf
            String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
            File folder = new File(extStorageDirectory, "testthreepdf");
            folder.mkdir();

            File pdfFile = new File(folder, fileName);

            try{
                pdfFile.createNewFile();
            }catch (IOException e){
                e.printStackTrace();
            }
            FileDownloader.downloadFile(fileUrl, pdfFile);
            return null;
        }
    }


}

FileDownloader.java

package com.example.downloadread;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class FileDownloader {
    private static final int  MEGABYTE = 1024 * 1024;

    public static void downloadFile(String fileUrl, File directory){
        try {

            URL url = new URL(fileUrl);
            HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
            //urlConnection.setRequestMethod("GET");
            //urlConnection.setDoOutput(true);
            urlConnection.connect();

            InputStream inputStream = urlConnection.getInputStream();
            FileOutputStream fileOutputStream = new FileOutputStream(directory);
            int totalSize = urlConnection.getContentLength();

            byte[] buffer = new byte[MEGABYTE];
            int bufferLength = 0;
            while((bufferLength = inputStream.read(buffer))>0 ){
                fileOutputStream.write(buffer, 0, bufferLength);
            }
            fileOutputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.downloadread"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="18" />
    <uses-permission android:name="android.permission.INTERNET"></uses-permission>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
    <uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.downloadread.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="15dp"
        android:text="download"
        android:onClick="download" />

    <Button
        android:id="@+id/button2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/button1"
        android:layout_marginTop="38dp"
        android:text="view"
        android:onClick="view" />

</RelativeLayout>

Mercurial — revert back to old version and continue from there

The answers above were most useful and I learned a lot. However, for my needs the succinct answer is:

hg revert --all --rev ${1}

hg commit -m "Restoring branch ${1} as default"

where ${1} is the number of the revision or the name of the branch. These two lines are actually part of a bash script, but they work fine on their own if you want to do it manually.

This is useful if you need to add a hot fix to a release branch, but need to build from default (until we get our CI tools right and able to build from branches and later do away with release branches as well).

PHP validation/regex for URL

Use the filter_var() function to validate whether a string is URL or not:

var_dump(filter_var('example.com', FILTER_VALIDATE_URL));

It is bad practice to use regular expressions when not necessary.

EDIT: Be careful, this solution is not unicode-safe and not XSS-safe. If you need a complex validation, maybe it's better to look somewhere else.

Prevent RequireJS from Caching Required Scripts

I don't recommend using 'urlArgs' for cache bursting with RequireJS. As this does not solves the problem fully. Updating a version no will result in downloading all the resources, even though you have just changes a single resource.

To handle this issue i recommend using Grunt modules like 'filerev' for creating revision no. On top of this i have written a custom task in Gruntfile to update the revision no wherever required.

If needed i can share the code snippet for this task.

Integer division with remainder in JavaScript?

JavaScript calculates right the floor of negative numbers and the remainder of non-integer numbers, following the mathematical definitions for them.

FLOOR is defined as "the largest integer number smaller than the parameter", thus:

  • positive numbers: FLOOR(X)=integer part of X;
  • negative numbers: FLOOR(X)=integer part of X minus 1 (because it must be SMALLER than the parameter, i.e., more negative!)

REMAINDER is defined as the "left over" of a division (Euclidean arithmetic). When the dividend is not an integer, the quotient is usually also not an integer, i.e., there is no remainder, but if the quotient is forced to be an integer (and that's what happens when someone tries to get the remainder or modulus of a floating-point number), there will be a non-integer "left over", obviously.

JavaScript does calculate everything as expected, so the programmer must be careful to ask the proper questions (and people should be careful to answer what is asked!) Yarin's first question was NOT "what is the integer division of X by Y", but, instead, "the WHOLE number of times a given integer GOES INTO another". For positive numbers, the answer is the same for both, but not for negative numbers, because the integer division (dividend by divisor) will be -1 smaller than the times a number (divisor) "goes into" another (dividend). In other words, FLOOR will return the correct answer for an integer division of a negative number, but Yarin didn't ask that!

gammax answered correctly, that code works as asked by Yarin. On the other hand, Samuel is wrong, he didn't do the maths, I guess, or he would have seen that it does work (also, he didn't say what was the divisor of his example, but I hope it was 3):

Remainder = X % Y = -100 % 3 = -1

GoesInto = (X - Remainder) / Y = (-100 - -1) / 3 = -99 / 3 = -33

By the way, I tested the code on Firefox 27.0.1, it worked as expected, with positive and negative numbers and also with non-integer values, both for dividend and divisor. Example:

-100.34 / 3.57: GoesInto = -28, Remainder = -0.3800000000000079

Yes, I noticed, there is a precision problem there, but I didn't had time to check it (I don't know if it's a problem with Firefox, Windows 7 or with my CPU's FPU). For Yarin's question, though, which only involves integers, the gammax's code works perfectly.

HTTP Status 405 - Method Not Allowed Error for Rest API

I also had this problem and was able to solve it by enabling CORS support on the server. In my case it was an Azure server and it was easy: Enable CORS on Azure

So check for your server how it works and enable CORS. I didn't even need a browser plugin or proxy :)

Multiple "order by" in LINQ

Add "new":

var movies = _db.Movies.OrderBy( m => new { m.CategoryID, m.Name })

That works on my box. It does return something that can be used to sort. It returns an object with two values.

Similar, but different to sorting by a combined column, as follows.

var movies = _db.Movies.OrderBy( m => (m.CategoryID.ToString() + m.Name))

Is it possible to compile a program written in Python?

I think Compiling Python Code would be a good place to start:

Python source code is automatically compiled into Python byte code by the CPython interpreter. Compiled code is usually stored in PYC (or PYO) files, and is regenerated when the source is updated, or when otherwise necessary.

To distribute a program to people who already have Python installed, you can ship either the PY files or the PYC files. In recent versions, you can also create a ZIP archive containing PY or PYC files, and use a small “bootstrap script” to add that ZIP archive to the path.

To “compile” a Python program into an executable, use a bundling tool, such as Gordon McMillan’s installer (alternative download) (cross-platform), Thomas Heller’s py2exe (Windows), Anthony Tuininga’s cx_Freeze (cross-platform), or Bob Ippolito’s py2app (Mac). These tools puts your modules and data files in some kind of archive file, and creates an executable that automatically sets things up so that modules are imported from that archive. Some tools can embed the archive in the executable itself.

Python regular expressions return true/false

Match objects are always true, and None is returned if there is no match. Just test for trueness.

if re.match(...):

Detect URLs in text with JavaScript

tmp.innerText is undefined. You should use tmp.innerHTML

function strip(html) 
    {  
        var tmp = document.createElement("DIV"); 
        tmp.innerHTML = html; 
        var urlRegex =/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;   
        return tmp.innerHTML .replace(urlRegex, function(url) {     
        return '\n' + url 
    })

Override element.style using CSS

element.style comes from the markup.

<li style="display: none;">

Just remove the style attribute from the HTML.

How do I specify a password to 'psql' non-interactively?

  • in one line:

    export PGPASSWORD='password'; psql -h 'server name' -U 'user name' -d 'base name' -c 'command'
    

    with command a sql command such as "select * from schema.table"

  • or more readable:

    export PGPASSWORD='password'
    psql -h 'server name' -U 'user name' -d 'base name' \
         -c 'command' (eg. "select * from schema.table")
    

how to change background image of button when clicked/focused?

use this code create xml file in drawable folder name:button

<?xml version="1.0" encoding="utf-8"?>
  <selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item 
     android:state_pressed="true" 
     android:drawable="@drawable/buutton_pressed" />
  <item 
     android:drawable="@drawable/button_image" />
</selector>

and in button xml file

 android:background="@drawable/button"

iPhone app signing: A valid signing identity matching this profile could not be found in your keychain

Did you try rebooting your Mac and your device? Lame answer, but I always try that first.

Difference between natural join and inner join

A NATURAL join is just short syntax for a specific INNER join -- or "equi-join" -- and, once the syntax is unwrapped, both represent the same Relational Algebra operation. It's not a "different kind" of join, as with the case of OUTER (LEFT/RIGHT) or CROSS joins.

See the equi-join section on Wikipedia:

A natural join offers a further specialization of equi-joins. The join predicate arises implicitly by comparing all columns in both tables that have the same column-names in the joined tables. The resulting joined table contains only one column for each pair of equally-named columns.

Most experts agree that NATURAL JOINs are dangerous and therefore strongly discourage their use. The danger comes from inadvertently adding a new column, named the same as another column ...

That is, all NATURAL joins may be written as INNER joins (but the converse is not true). To do so, just create the predicate explicitly -- e.g. USING or ON -- and, as Jonathan Leffler pointed out, select the desired result-set columns to avoid "duplicates" if desired.

Happy coding.


(The NATURAL keyword can also be applied to LEFT and RIGHT joins, and the same applies. A NATURAL LEFT/RIGHT join is just a short syntax for a specific LEFT/RIGHT join.)

DateTimeFormat in TypeScript

This should work...

var displayDate = new Date().toLocaleDateString();

alert(displayDate);

But I suspect you are trying it on something else, for example:

var displayDate = Date.now.toLocaleDateString(); // No!

alert(displayDate);

PHP PDO returning single row

Thanks to Steven's suggestion to use fetchColumn, here's my recommendation to cut short one line from your code.

$DBH = new PDO( "connection string goes here" );
$STH = $DBH->query( "select figure from table1" );
$result = $STH->fetchColumn();
echo $result;
$DBH = null;

Enum String Name from Value

If you need to get a string "Visible" without getting EnumDisplayStatus instance you can do this:

int dbValue = GetDBValue();
string stringValue = Enum.GetName(typeof(EnumDisplayStatus), dbValue);

How to alert using jQuery

Don't do this, but this is how you would do it:

$(".overdue").each(function() { 
    alert("Your book is overdue"); 
});

The reason I say "don't do it" is because nothing is more annoying to users, in my opinion, than repeated pop-ups that cannot be stopped. Instead, just use the length property and let them know that "You have X books overdue".

PHP cURL vs file_get_contents

file_get_contents() is a simple screwdriver. Great for simple GET requests where the header, HTTP request method, timeout, cookiejar, redirects, and other important things do not matter.

fopen() with a stream context or cURL with setopt are powerdrills with every bit and option you can think of.

Passing variable number of arguments around

I'm unsure if this works for all compilers, but it has worked so far for me.

void inner_func(int &i)
{
  va_list vars;
  va_start(vars, i);
  int j = va_arg(vars);
  va_end(vars); // Generally useless, but should be included.
}

void func(int i, ...)
{
  inner_func(i);
}

You can add the ... to inner_func() if you want, but you don't need it. It works because va_start uses the address of the given variable as the start point. In this case, we are giving it a reference to a variable in func(). So it uses that address and reads the variables after that on the stack. The inner_func() function is reading from the stack address of func(). So it only works if both functions use the same stack segment.

The va_start and va_arg macros will generally work if you give them any var as a starting point. So if you want you can pass pointers to other functions and use those too. You can make your own macros easily enough. All the macros do is typecast memory addresses. However making them work for all the compilers and calling conventions is annoying. So it's generally easier to use the ones that come with the compiler.

Regex to get NUMBER only from String

Either [0-9] or \d1 should suffice if you only need a single digit. Append + if you need more.


1 The semantics are slightly different as \d potentially matches any decimal digit in any script out there that uses decimal digits.

How do DATETIME values work in SQLite?

SQlite does not have a specific datetime type. You can use TEXT, REAL or INTEGER types, whichever suits your needs.

Straight from the DOCS

SQLite does not have a storage class set aside for storing dates and/or times. Instead, the built-in Date And Time Functions of SQLite are capable of storing dates and times as TEXT, REAL, or INTEGER values:

  • TEXT as ISO8601 strings ("YYYY-MM-DD HH:MM:SS.SSS").
  • REAL as Julian day numbers, the number of days since noon in Greenwich on November 24, 4714 B.C. according to the proleptic Gregorian calendar.
  • INTEGER as Unix Time, the number of seconds since 1970-01-01 00:00:00 UTC.

Applications can chose to store dates and times in any of these formats and freely convert between formats using the built-in date and time functions.

SQLite built-in Date and Time functions can be found here.

Can pm2 run an 'npm start' script

If you use PM2 via node modules instead of globally, you'll need to set interpreter: 'none' in order for the above solutions to work. Related docs here.

In ecosystem.config.js:

  apps: [
    {
      name: 'myApp',
      script: 'yarn',
      args: 'start',
      interpreter: 'none',
    },
  ],

Multiple bluetooth connection

Not exactly true -- take a look at the specs summary

Logical link control and adaptation protocol (L2CAP)

L2CAP is used within the Bluetooth protocol stack. It passes packets to either the Host Controller Interface (HCI) or on a hostless system, directly to the Link Manager/ACL link. L2CAP's functions include:

  • Multiplexing data between different higher layer protocols.
  • Segmentation and reassembly of packets.
  • Providing one-way transmission management of multicast data to a group of other Bluetooth devices.
  • Quality of service (QoS) management for higher layer protocols.

L2CAP is used to communicate over the host ACL link. Its connection is established after the ACL link has been set up.

Scroll / Jump to id without jQuery

Add the function:

function scrollToForm() {
  document.querySelector('#form').scrollIntoView({behavior: 'smooth'});
}

Trigger the function:

<a href="javascript: scrollToForm();">Jump to form</a>

jquery ajax get responsetext from http url

Since jQuery AJAX requests fail if they are cross-domain, you can use cURL (in PHP) to set up a proxy server.

Suppose a PHP file responder.php has these contents:

$url = "https://www.google.com";
$ch      = curl_init( $url );
curl_set_opt($ch, CURLOPT_RETURNTRANSFER, "true")
$response= curl_exec( $ch );
curl_close( $ch );
return $response;

Your AJAX request should be to this responder.php file so that it executes the cross-domain request.

Update query PHP MySQL

You have to have single quotes around any VARCHAR content in your queries. So your update query should be:

mysql_query("UPDATE blogEntry SET content = '$udcontent', title = '$udtitle' WHERE id = $id");

Also, it is bad form to update your database directly with the content from a POST. You should sanitize your incoming data with the mysql_real_escape_string function.

Check if a string is a valid Windows directory (folder) path

Use this Code

string DirectoryName = "Sample Name For Directory Or File";
Path.GetInvalidFileNameChars()
  .Where(x => DirectoryName.Contains(x))
  .Count() > 0 || DirectoryName == "con"

Bootstrap 3 Glyphicons are not working

Here is what official documentation says regarding fonts not rendering.

Changing the icon font location Bootstrap assumes icon font files will be located in the ../fonts/ directory, relative to the compiled CSS files. Moving or renaming those font files means updating the CSS in one of three ways: Change the @icon-font-path and/or @icon-font-name variables in the source Less files. Utilize the relative URLs option provided by the Less compiler. Change the url() paths in the compiled CSS. Use whatever option best suits your specific development setup.

Other than that it could be that you missed to copy the fonts folder to the root directory

Java null check why use == instead of .equals()

I have encountered this case last night.
I determine that simply that:

Don't exist equals() method for null
So, you can not invoke an inexistent method if you don't have
-->>> That is reason for why we use == to check null

$.ajax - dataType

  • contentType is the HTTP header sent to the server, specifying a particular format.
    Example: I'm sending JSON or XML
  • dataType is you telling jQuery what kind of response to expect.
    Expecting JSON, or XML, or HTML, etc. The default is for jQuery to try and figure it out.

The $.ajax() documentation has full descriptions of these as well.


In your particular case, the first is asking for the response to be in UTF-8, the second doesn't care. Also the first is treating the response as a JavaScript object, the second is going to treat it as a string.

So the first would be:

success: function(data) {
  // get data, e.g. data.title;
}

The second:

success: function(data) {
  alert("Here's lots of data, just a string: " + data);
}

HTML: How to center align a form

<center><form></form></center>    

does work in most cases like The Wobbuffet mentioned above...

What causes the error "_pickle.UnpicklingError: invalid load key, ' '."?

I am not completely sure what you're trying to achieve by seeking to a specific offset and attempting to load individual values manually, the typical usage of the pickle module is:

# save data to a file
with open('myfile.pickle','wb') as fout:
    pickle.dump([1,2,3],fout)

# read data from a file
with open('myfile.pickle') as fin:
    print pickle.load(fin)

# output
>> [1, 2, 3]

If you dumped a list, you'll load a list, there's no need to load each item individually.

you're saying that you got an error before you were seeking to the -5000 offset, maybe the file you're trying to read is corrupted.

If you have access to the original data, I suggest you try saving it to a new file and reading it as in the example.

How to do a HTTP HEAD request from the windows command line?

There is a Win32 port of wget that works decently.

PowerShell's Invoke-WebRequest -Method Head would work as well.

Visual Studio keyboard shortcut to automatically add the needed 'using' statement

It's ctrl + . when, for example, you try to type List you need to type < at the end and press ctrl + . for it to work.

How to kill all active and inactive oracle sessions for user

inactive session the day before kill

_x000D_
_x000D_
begin_x000D_
    for i in (select * from v$session where status='INACTIVE' and (sysdate-PREV_EXEC_START)>1)_x000D_
    LOOP_x000D_
        EXECUTE IMMEDIATE(q'{ALTER SYSTEM KILL SESSION '}'||i.sid||q'[,]'  ||i.serial#||q'[']'||' IMMEDIATE');_x000D_
    END LOOP;_x000D_
end;
_x000D_
_x000D_
_x000D_

Lost connection to MySQL server at 'reading initial communication packet', system error: 0

  • I had port 3306 in Docker container but in Dockerfile it was 33060. I edited the port in Docker container to 33060

  • Must have been added to the Dockerfile

    ENV MYSQL_ROOT_HOST 172.17.0.1

Running Groovy script from the command line

#!/bin/sh
sed '1,2d' "$0"|$(which groovy) /dev/stdin; exit;

println("hello");

How to display string that contains HTML in twig template?

You can also use:

{{ word|striptags('<b>')|raw }}

so that only <b> tag will be allowed.

Examples of good gotos in C or C++

Knuth has written a paper "Structured programming with GOTO statements", you can get it e.g. from here. You'll find many examples there.

Finding out current index in EACH loop (Ruby)

x.each_with_index { |v, i| puts "current index...#{i}" }

Using .NET, how can you find the mime type of a file based on the file signature not the extension

Hello I have adapted Winista.MimeDetect project into .net core/framework with fallback into urlmon.dll Fell free to use it: nuget package.

   //init
   var mimeTypes = new MimeTypes();

   //usage by filepath
   var mimeType1 = mimeTypes.GetMimeTypeFromFile(filePath);

How do I perform the SQL Join equivalent in MongoDB?

We can merge/join all data inside only one collection with a easy function in few lines using the mongodb client console, and now we could be able of perform the desired query. Below a complete example,

.- Authors:

db.authors.insert([
    {
        _id: 'a1',
        name: { first: 'orlando', last: 'becerra' },
        age: 27
    },
    {
        _id: 'a2',
        name: { first: 'mayra', last: 'sanchez' },
        age: 21
    }
]);

.- Categories:

db.categories.insert([
    {
        _id: 'c1',
        name: 'sci-fi'
    },
    {
        _id: 'c2',
        name: 'romance'
    }
]);

.- Books

db.books.insert([
    {
        _id: 'b1',
        name: 'Groovy Book',
        category: 'c1',
        authors: ['a1']
    },
    {
        _id: 'b2',
        name: 'Java Book',
        category: 'c2',
        authors: ['a1','a2']
    },
]);

.- Book lending

db.lendings.insert([
    {
        _id: 'l1',
        book: 'b1',
        date: new Date('01/01/11'),
        lendingBy: 'jose'
    },
    {
        _id: 'l2',
        book: 'b1',
        date: new Date('02/02/12'),
        lendingBy: 'maria'
    }
]);

.- The magic:

db.books.find().forEach(
    function (newBook) {
        newBook.category = db.categories.findOne( { "_id": newBook.category } );
        newBook.lendings = db.lendings.find( { "book": newBook._id  } ).toArray();
        newBook.authors = db.authors.find( { "_id": { $in: newBook.authors }  } ).toArray();
        db.booksReloaded.insert(newBook);
    }
);

.- Get the new collection data:

db.booksReloaded.find().pretty()

.- Response :)

{
    "_id" : "b1",
    "name" : "Groovy Book",
    "category" : {
        "_id" : "c1",
        "name" : "sci-fi"
    },
    "authors" : [
        {
            "_id" : "a1",
            "name" : {
                "first" : "orlando",
                "last" : "becerra"
            },
            "age" : 27
        }
    ],
    "lendings" : [
        {
            "_id" : "l1",
            "book" : "b1",
            "date" : ISODate("2011-01-01T00:00:00Z"),
            "lendingBy" : "jose"
        },
        {
            "_id" : "l2",
            "book" : "b1",
            "date" : ISODate("2012-02-02T00:00:00Z"),
            "lendingBy" : "maria"
        }
    ]
}
{
    "_id" : "b2",
    "name" : "Java Book",
    "category" : {
        "_id" : "c2",
        "name" : "romance"
    },
    "authors" : [
        {
            "_id" : "a1",
            "name" : {
                "first" : "orlando",
                "last" : "becerra"
            },
            "age" : 27
        },
        {
            "_id" : "a2",
            "name" : {
                "first" : "mayra",
                "last" : "sanchez"
            },
            "age" : 21
        }
    ],
    "lendings" : [ ]
}

I hope this lines can help you.

How do I skip an iteration of a `foreach` loop?

Use the continue statement:

foreach(object number in mycollection) {
     if( number < 0 ) {
         continue;
     }
  }

Moving Git repository content to another repository preserving history

Simplest approach if the code is already tracked by Git then set new repository as your "origin" to push to.

cd existing-project
git remote set-url origin https://clone-url.git
git push -u origin --all
git push origin --tags

How to exit from ForEach-Object in PowerShell

You have two options to abruptly exit out of ForEach-Object pipeline in PowerShell:

  1. Apply exit logic in Where-Object first, then pass objects to Foreach-Object, or
  2. (where possible) convert Foreach-Object into a standard Foreach looping construct.

Let's see examples: Following scripts exit out of Foreach-Object loop after 2nd iteration (i.e. pipeline iterates only 2 times)":

Solution-1: use Where-Object filter BEFORE Foreach-Object:

[boolean]$exit = $false;
1..10 | Where-Object {$exit -eq $false} | Foreach-Object {
     if($_ -eq 2) {$exit = $true}    #OR $exit = ($_ -eq 2);
     $_;
}

OR

1..10 | Where-Object {$_ -le 2} | Foreach-Object {
     $_;
}

Solution-2: Converted Foreach-Object into standard Foreach looping construct:

Foreach ($i in 1..10) { 
     if ($i -eq 3) {break;}
     $i;
}

PowerShell should really provide a bit more straightforward way to exit or break out from within the body of a Foreach-Object pipeline. Note: return doesn't exit, it only skips specific iteration (similar to continue in most programming languages), here is an example of return:

Write-Host "Following will only skip one iteration (actually iterates all 10 times)";
1..10 | Foreach-Object {
     if ($_ -eq 3) {return;}  #skips only 3rd iteration.
     $_;
}

HTH

Go to first line in a file in vim?

In command mode (press Esc if you are not sure) you can use:

  • gg,
  • :1,
  • 1G,
  • or 1gg.

Call Class Method From Another Class

Just call it and supply self

class A:
    def m(self, x, y):
        print(x+y)

class B:
    def call_a(self):
        A.m(self, 1, 2)

b = B()
b.call_a()

output: 3

PowerShell The term is not recognized as cmdlet function script file or operable program

For the benefit of searchers, there is another way you can produce this error message - by missing the $ off the script block name when calling it.

e.g. I had a script block like so:

$qa = {
    param($question, $answer)
    Write-Host "Question = $question, Answer = $answer"
}

I tried calling it using:

&qa -question "Do you like powershell?" -answer "Yes!"

But that errored. The correct way was:

&$qa -question "Do you like powershell?" -answer "Yes!"

How to get a tab character?

Try &emsp;

as per the docs :

The character entities &ensp; and &emsp; denote an en space and an em space respectively, where an en space is half the point size and an em space is equal to the point size of the current font. For fixed pitch fonts, the user agent can treat the en space as being equivalent to A space character, and the em space as being equuivalent to two space characters.

Docs link : https://www.w3.org/MarkUp/html3/specialchars.html

Check if a string contains a string in C++

You can also use the System namespace. Then you can use the contains method.

#include <iostream>
using namespace System;

int main(){
    String ^ wholeString = "My name is Malindu";

    if(wholeString->ToLower()->Contains("malindu")){
        std::cout<<"Found";
    }
    else{
        std::cout<<"Not Found";
    }
}

PowerShell array initialization

Or try this an idea. Works with powershell 5.0+.

[bool[]]$tf=((,$False)*5)

Which command do I use to generate the build of a Vue app?

in your terminal

npm run build

and you host the dist folder. for more see this video

How to check the extension of a filename in a bash script?

You just can't be sure on a Unix system, that a .txt file truly is a text file. Your best bet is to use "file". Maybe try using:

file -ib "$file"

Then you can use a list of MIME types to match against or parse the first part of the MIME where you get stuff like "text", "application", etc.

what is the difference between uint16_t and unsigned short int incase of 64 bit processor?

uint16_t is unsigned 16-bit integer.

unsigned short int is unsigned short integer, but the size is implementation dependent. The standard only says it's at least 16-bit (i.e, minimum value of UINT_MAX is 65535). In practice, it usually is 16-bit, but you can't take that as guaranteed.

Note:

  1. If you want a portable unsigned 16-bit integer, use uint16_t.
  2. inttypes.h and stdint.h are both introduced in C99. If you are using C89, define your own type.
  3. uint16_t may not be provided in certain implementation(See reference below), but unsigned short int is always available.

Reference: C11(ISO/IEC 9899:201x) §7.20 Integer types

For each type described herein that the implementation provides) shall declare that typedef name and define the associated macros. Conversely, for each type described herein that the implementation does not provide, shall not declare that typedef name nor shall it define the associated macros. An implementation shall provide those types described as ‘‘required’’, but need not provide any of the others (described as ‘optional’’).

How to make a SIMPLE C++ Makefile

I suggest (note that the indent is a TAB):

tool: tool.o file1.o file2.o
    $(CXX) $(LDFLAGS) $^ $(LDLIBS) -o $@

or

LINK.o = $(CXX) $(LDFLAGS) $(TARGET_ARCH)
tool: tool.o file1.o file2.o

The latter suggestion is slightly better since it reuses GNU Make implicit rules. However, in order to work, a source file must have the same name as the final executable (i.e.: tool.c and tool).

Notice, it is not necessary to declare sources. Intermediate object files are generated using implicit rule. Consequently, this Makefile work for C and C++ (and also for Fortran, etc...).

Also notice, by default, Makefile use $(CC) as the linker. $(CC) does not work for linking C++ object files. We modify LINK.o only because of that. If you want to compile C code, you don't have to force the LINK.o value.

Sure, you can also add your compilation flags with variable CFLAGS and add your libraries in LDLIBS. For example:

CFLAGS = -Wall
LDLIBS = -lm

One side note: if you have to use external libraries, I suggest to use pkg-config in order to correctly set CFLAGS and LDLIBS:

CFLAGS += $(shell pkg-config --cflags libssl)
LDLIBS += $(shell pkg-config --libs libssl)

The attentive reader will notice that this Makefile does not rebuild properly if one header is changed. Add these lines to fix the problem:

override CPPFLAGS += -MMD
include $(wildcard *.d)

-MMD allows to build .d files that contains Makefile fragments about headers dependencies. The second line just uses them.

For sure, a well written Makefile should also include clean and distclean rules:

clean:
    $(RM) *.o *.d

distclean: clean
    $(RM) tool

Notice, $(RM) is the equivalent of rm -f, but it is a good practice to not call rm directly.

The all rule is also appreciated. In order to work, it should be the first rule of your file:

all: tool

You may also add an install rule:

PREFIX = /usr/local
install:
    install -m 755 tool $(DESTDIR)$(PREFIX)/bin

DESTDIR is empty by default. The user can set it to install your program at an alternative system (mandatory for cross-compilation process). Package maintainers for multiple distribution may also change PREFIX in order to install your package in /usr.

One final word: Do not place source files in sub-directories. If you really want to do that, keep this Makefile in the root directory and use full paths to identify your files (i.e. subdir/file.o).

So to summarise, your full Makefile should look like:

LINK.o = $(CXX) $(LDFLAGS) $(TARGET_ARCH)
PREFIX = /usr/local
override CPPFLAGS += -MMD
include $(wildcard *.d)

all: tool
tool: tool.o file1.o file2.o
clean:
    $(RM) *.o *.d
distclean: clean
    $(RM) tool
install:
    install -m 755 tool $(DESTDIR)$(PREFIX)/bin

Password Protect a SQLite DB. Is it possible?

You can password protect a SQLite3 DB. Before doing any operations, set the password as follows.

SQLiteConnection conn = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;");
conn.SetPassword("password");
conn.Open();

then next time you can access it like

conn = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;Password=password;");
conn.Open();

This wont allow any GUI editor to view your data. Some editors can decrypt the DB if you provide the password. The algorithm used is RSA.

Later if you wish to change the password, use

conn.ChangePassword("new_password");

To reset or remove password, use

conn.ChangePassword(String.Empty);

Opening PDF String in new window with javascript

I had this problem working with a FedEx shipment request. I perform the request with AJAX. The response includes tracking #, cost, as well as pdf string containing the shipping label.

Here's what I did:

Add a form:

<form id='getlabel' name='getlabel' action='getlabel.php' method='post' target='_blank'>
<input type='hidden' id='pdf' name='pdf'>
</form>

Use javascript to populate the hidden field's value with the pdf string and post the form.

Where getlabel.php:

<?
header('Content-Type: application/pdf');
header('Content-Length: '.strlen($_POST["pdf"]));
header('Content-Disposition: inline;');
header('Cache-Control: private, max-age=0, must-revalidate');
header('Pragma: public');
print $_POST["pdf"];
?>

Hibernate Criteria Join with 3 Tables

The fetch mode only says that the association must be fetched. If you want to add restrictions on an associated entity, you must create an alias, or a subcriteria. I generally prefer using aliases, but YMMV:

Criteria c = session.createCriteria(Dokument.class, "dokument");
c.createAlias("dokument.role", "role"); // inner join by default
c.createAlias("role.contact", "contact");
c.add(Restrictions.eq("contact.lastName", "Test"));
return c.list();

This is of course well explained in the Hibernate reference manual, and the javadoc for Criteria even has examples. Read the documentation: it has plenty of useful information.

Convert NSArray to NSString in Objective-C

NSString * result = [[array valueForKey:@"description"] componentsJoinedByString:@""];

How to change date format in JavaScript

Use your mydate object and call getMonth() and getFullYear()

See this for more info: http://www.w3schools.com/jsref/jsref_obj_date.asp

Created Button Click Event c#

You need an event handler which will fire when the button is clicked. Here is a quick way -

  var button = new Button();
  button.Text = "my button";

  this.Controls.Add(button);

  button.Click += (sender, args) =>
                       {
                           MessageBox.Show("Some stuff");
                           Close();
                       };

But it would be better to understand a bit more about buttons, events, etc.

If you use the visual studio UI to create a button and double click the button in design mode, this will create your event and hook it up for you. You can then go to the designer code (the default will be Form1.Designer.cs) where you will find the event:

 this.button1.Click += new System.EventHandler(this.button1_Click);

You will also see a LOT of other information setup for the button, such as location, etc. - which will help you create one the way you want and will improve your understanding of creating UI elements. E.g. a default button gives this on my 2012 machine:

        this.button1.Location = new System.Drawing.Point(128, 214);
        this.button1.Name = "button1";
        this.button1.Size = new System.Drawing.Size(75, 23);
        this.button1.TabIndex = 1;
        this.button1.Text = "button1";
        this.button1.UseVisualStyleBackColor = true;

As for closing the Form, it is as easy as putting Close(); within your event handler:

private void button1_Click(object sender, EventArgs e)
    {
       MessageBox.Show("some text");
       Close();
    }

T-SQL query to show table definition?

Visit http://www.stormrage.com/SQLStuff/sp_GetDDL_Latest.txt.

You will find the code of sp_getddl procedure for SQL Server. The purpose of the procedure is script any table, temp table or object.

USAGE:

exec sp_GetDDL GMACT

or

exec sp_GetDDL 'bob.example'

or

exec sp_GetDDL '[schemaname].[tablename]'

or

exec sp_GetDDL #temp

I tested it on SQL Server 2012, and it does an excellent job.

I'm not the author of the procedure. Any improvement you make to it send to Lowell Izaguirre ([email protected]).

Django 1.7 - makemigrations not detecting changes

You want to check the settings.py in the INSTALLED_APPS list and make sure all the apps with models are listed in there.

Running makemigrations in the project folder means it will look to update all the tables related to all the apps included in settings.py for the project. Once you include it, makemigrations will automatically include the app (this saves a lot of work so you don't have to run makemigrations app_name for every app in your project/site).

how to enable sqlite3 for php?

try this:

sudo apt-get --purge remove php5*
sudo apt-get install php5 php5-sqlite php5-mysql
sudo apt-get install php-pear php-apc php5-curl
sudo apt-get autoremove
sudo apt-get install php5-sqlite
sudo apt-get install libapache2-mod-fastcgi php5-fpm php5

Git: Permission denied (publickey) fatal - Could not read from remote repository. while cloning Git repository

I had a similar problem on linux. I solved the problem by logging into the github server and creating a deploy key. That's under settings for the repository. Then, I copied and pasted my public key (which is usually in ~/.ssh/id_rsa.pub, but your configuration might be different). There is a check box to give this key write access. Click on it (unless you are using git to deploy only, in which case, don't click on it).

Does uninstalling a package with "pip" also remove the dependent packages?

I have found the solution even though it might be a little difficult for some to carry out.

1st step (for python3 and linux):
pip3 install pip-autoremove
2nd step:
cd /home/usernamegoeshere/.local/bin/
3rd step:
gedit /home/usernamegoeshere/.local/lib/python3.8/site-packages/pip_autoremove.py
and change all pip(s) to pip3 4th step: ./pip-autoremove packagenamegoeshere

At least, this was what worked for me ...

Set width of dropdown element in HTML select dropdown options

Small And Better One

var i = 0;
$("#container > option").each(function(){ 
    if($(this).val().length > i) {
        i = $(this).val().length;

        console.log(i);
        console.log($(this).val());
    }
});

How to set top position using jquery

You can use CSS to do the trick:

$("#yourElement").css({ top: '100px' });

Is it possible to center text in select box?

I have always gotten away with the following hack to get it to work with css only.

padding-left: 45%;
font-size: 50px;

padding will center the text and can be tweaked for the text size :)

This is obviously not 100% correct from a validation point of view I guess but it does the job :)

how to create dynamic two dimensional array in java?

List<Integer>[] array;  
array = new List<Integer>[10]; 

this the second case in @TofuBeer's answer is incorrect. because can't create arrays with generics. u can use:

List<List<Integer>> array = new ArrayList<>();

Returning JSON from a PHP Script

If you query a database and need the result set in JSON format it can be done like this:

<?php

$db = mysqli_connect("localhost","root","","mylogs");
//MSG
$query = "SELECT * FROM logs LIMIT 20";
$result = mysqli_query($db, $query);
//Add all records to an array
$rows = array();
while($row = $result->fetch_array()){
    $rows[] = $row;
}
//Return result to jTable
$qryResult = array();
$qryResult['logs'] = $rows;
echo json_encode($qryResult);

mysqli_close($db);

?>

For help in parsing the result using jQuery take a look at this tutorial.

Right click to select a row in a Datagridview and show a menu to delete it

private void MyDataGridView_MouseDown(object sender, MouseEventArgs e)
{
    if(e.Button == MouseButtons.Right)
    {
        MyDataGridView.ClearSelection();
        MyDataGridView.Rows[e.RowIndex].Selected = true;
    }
}

private void DeleteRow_Click(object sender, EventArgs e)
{
    Int32 rowToDelete = MyrDataGridView.Rows.GetFirstRow(DataGridViewElementStates.Selected);
    MyDataGridView.Rows.RemoveAt(rowToDelete);
    MyDataGridView.ClearSelection();
}

Multiple returns from a function

Best Practice is to put your returned variables into array and then use list() to assign array values to variables.

<?php

function add_subt($val1, $val2) {
    $add = $val1 + $val2;
    $subt = $val1 - $val2;

    return array($add, $subt);
}

list($add_result, $subt_result) = add_subt(20, 7);
echo "Add: " . $add_result . '<br />';
echo "Subtract: " . $subt_result . '<br />';

?>

How to use default Android drawables

Java Usage example: myMenuItem.setIcon(android.R.drawable.ic_menu_save);

Resource Usage example: android:icon="@android:drawable/ic_menu_save"

How to pass arguments to a Dockerfile?

You are looking for --build-arg and the ARG instruction. These are new as of Docker 1.9. Check out https://docs.docker.com/engine/reference/builder/#arg. This will allow you to add ARG arg to the Dockerfile and then build with docker build --build-arg arg=2.3 ..

SQL Server: How to check if CLR is enabled?

The accepted answer needs a little clarification. The row will be there if CLR is enabled or disabled. Value will be 1 if enabled, or 0 if disabled.

I use this script to enable on a server, if the option is disabled:

if not exists(
    SELECT value
    FROM sys.configurations
    WHERE name = 'clr enabled'
     and value = 1
)
begin
    exec sp_configure @configname=clr_enabled, @configvalue=1
    reconfigure
end

Endless loop in C/C++

Well, there is a lot of taste in this one. I think people from a C background are more likely to prefer for(;;), which reads as "forever". If its for work, do what the locals do, if its for yourself, do the one that you can most easily read.

But in my experience, do { } while (1); is almost never used.

How can I copy network files using Robocopy?

I use the following format and works well.

robocopy \\SourceServer\Path \\TargetServer\Path filename.txt

to copy everything you can replace filename.txt with *.* and there are plenty of other switches to copy subfolders etc... see here: http://ss64.com/nt/robocopy.html

create multiple tag docker image

docker build  -t name1:tag1 -t name2:tag2 -f Dockerfile.ui .

Make header and footer files to be included in multiple html pages

It is also possible to load scripts and links into the header. I'll be adding it one of the examples above...

<!--load_essentials.js-->
document.write('<link rel="stylesheet" type="text/css" href="css/style.css" />');
document.write('<link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />');
document.write('<script src="js/jquery.js" type="text/javascript"></script>');

document.getElementById("myHead").innerHTML =
"<span id='headerText'>Title</span>"
+ "<span id='headerSubtext'>Subtitle</span>";
document.getElementById("myNav").innerHTML =
"<ul id='navLinks'>"
+ "<li><a href='index.html'>Home</a></li>"
+ "<li><a href='about.html'>About</a>"
+ "<li><a href='donate.html'>Donate</a></li>"
+ "</ul>";
document.getElementById("myFooter").innerHTML =
"<p id='copyright'>Copyright &copy; " + new Date().getFullYear() + " You. All"
+ " rights reserved.</p>"
+ "<p id='credits'>Layout by You</p>"
+ "<p id='contact'><a href='mailto:[email protected]'>Contact Us</a> / "
+ "<a href='mailto:[email protected]'>Report a problem.</a></p>";

<!--HTML-->
<header id="myHead"></header>
<nav id="myNav"></nav>
Content
<footer id="myFooter"></footer>

<script src="load_essentials.js"></script>

How to add hours to current time in python

from datetime import datetime, timedelta

nine_hours_from_now = datetime.now() + timedelta(hours=9)
#datetime.datetime(2012, 12, 3, 23, 24, 31, 774118)

And then use string formatting to get the relevant pieces:

>>> '{:%H:%M:%S}'.format(nine_hours_from_now)
'23:24:31'

If you're only formatting the datetime then you can use:

>>> format(nine_hours_from_now, '%H:%M:%S')
'23:24:31'

Or, as @eumiro has pointed out in comments - strftime

MySQL, Check if a column exists in a table with SQL

Select just column_name from information schema and put the result of this query into variable. Then test the variable to decide if table needs alteration or not.

P.S. Don't foget to specify TABLE_SCHEMA for COLUMNS table as well.

JBoss debugging in Eclipse

If you set up a JBoss server using the Eclipse WebTools, you can simply start the server in debug mode (debug button in the servers view). This will allow you to set breakpoints in the application that is running inside the JBoss.

How do you prevent install of "devDependencies" NPM modules for Node.js (package.json)?

npm will install dev dependencies when installing from inside a package (if there is a package.json in the current directory). If it is from another location (npm registry, git repo, different location on the filesystem) it only installs the dependencies.

Isn't the size of character in Java 2 bytes?

There are some great answers here but I wanted to point out the jvm is free to store a char value in any size space >= 2 bytes.

On many architectures there is a penalty for performing unaligned memory access so a char might easily be padded to 4 bytes. A volatile char might even be padded to the size of the CPU cache line to prevent false sharing. https://en.wikipedia.org/wiki/False_sharing

It might be non-intuitive to new Java programmers that a character array or a string is NOT simply multiple characters. You should learn and think about strings and arrays distinctly from "multiple characters".

I also want to point out that java characters are often misused. People don't realize they are writing code that won't properly handle codepoints over 16 bits in length.

How do I ignore files in a directory in Git?

PATTERN FORMAT

  • A blank line matches no files, so it can serve as a separator for readability.

  • A line starting with # serves as a comment.

  • An optional prefix ! which negates the pattern; any matching file excluded by a previous pattern will become included again. If a negated pattern matches, this will override lower precedence patterns sources.

  • If the pattern ends with a slash, it is removed for the purpose of the following description, but it would only find a match with a directory. In other words, foo/ will match a directory foo and paths underneath it, but will not match a regular file or a symbolic link foo (this is consistent with the way how pathspec works in general in git).

  • If the pattern does not contain a slash /, git treats it as a shell glob pattern and checks for a match against the pathname relative to the location of the .gitignore file (relative to the toplevel of the work tree if not from a .gitignore file).

  • Otherwise, git treats the pattern as a shell glob suitable for consumption by fnmatch(3) with the FNM_PATHNAME flag: wildcards in the pattern will not match a / in the pathname. For example, Documentation/*.html matches Documentation/git.html but not Documentation/ppc/ppc.html or tools/perf/Documentation/perf.html.

  • A leading slash matches the beginning of the pathname. For example, /*.c matches cat-file.c but not mozilla-sha1/sha1.c.

You can find more here

git help gitignore
or
man gitignore

How to load local html file into UIWebView

Swift iOS:

 // get server url from the plist directory
        var htmlFile = NSBundle.mainBundle().pathForResource("animation_bg", ofType: "html")!
        var htmlString = NSString(contentsOfFile: htmlFile, encoding: NSUTF8StringEncoding, error: nil)
        self.webView.loadHTMLString(htmlString, baseURL: nil)

How to Detect if I'm Compiling Code with a particular Visual Studio version?

This is a little old but should get you started:

//******************************************************************************
// Automated platform detection
//******************************************************************************

// _WIN32 is used by
// Visual C++
#ifdef _WIN32
#define __NT__
#endif

// Define __MAC__ platform indicator
#ifdef macintosh
#define __MAC__
#endif

// Define __OSX__ platform indicator
#ifdef __APPLE__
#define __OSX__
#endif

// Define __WIN16__ platform indicator 
#ifdef _Windows_
#ifndef __NT__
#define __WIN16__
#endif
#endif

// Define Windows CE platform indicator
#ifdef WIN32_PLATFORM_HPCPRO
#define __WINCE__
#endif

#if (_WIN32_WCE == 300) // for Pocket PC
#define __POCKETPC__
#define __WINCE__
//#if (_WIN32_WCE == 211) // for Palm-size PC 2.11 (Wyvern)
//#if (_WIN32_WCE == 201) // for Palm-size PC 2.01 (Gryphon)  
//#ifdef WIN32_PLATFORM_HPC2000 // for H/PC 2000 (Galileo)
#endif

How to slice a Pandas Data Frame by position?

I can see at least three options:

1.

df[:10]

2. Using head

df.head(10)

For negative values of n, this function returns all rows except the last n rows, equivalent to df[:-n] [Source].

3. Using iloc

df.iloc[:10]

PHP - how to create a newline character?

Use the PHP nl2br to get the newlines in a text string..

$text = "Manu is a good boy.(Enter)He can code well.

echo nl2br($text);

Result.

Manu is a good boy.

He can code well.

How do I write stderr to a file while using "tee" with a pipe?

To redirect stderr to a file, display stdout to screen, and also save stdout to a file:

./aaa.sh 2>ccc.out | tee ./bbb.out

EDIT: To display both stderr and stdout to screen and also save both to a file, you can use bash's I/O redirection:

#!/bin/bash

# Create a new file descriptor 4, pointed at the file
# which will receive stderr.
exec 4<>ccc.out

# Also print the contents of this file to screen.
tail -f ccc.out &

# Run the command; tee stdout as normal, and send stderr
# to our file descriptor 4.
./aaa.sh 2>&4 | tee bbb.out

# Clean up: Close file descriptor 4 and kill tail -f.
exec 4>&-
kill %1

Jump into interface implementation in Eclipse IDE

Here's what I do:

  • In the interface, move the cursor to the method name. Press F4. => Type Hierarchy view appears
  • In the lower part of the view, the method should already be selected. In its toolbar, click "Lock view and show members in hierarchy" (should be the leftmost toolbar icon).
  • In the upper part of the view, you can browse through all implementations of the method.

The procedure isn't very quick, but it gives you a good overview.

What are passive event listeners?

Passive event listeners are an emerging web standard, new feature shipped in Chrome 51 that provide a major potential boost to scroll performance. Chrome Release Notes.

It enables developers to opt-in to better scroll performance by eliminating the need for scrolling to block on touch and wheel event listeners.

Problem: All modern browsers have a threaded scrolling feature to permit scrolling to run smoothly even when expensive JavaScript is running, but this optimization is partially defeated by the need to wait for the results of any touchstart and touchmove handlers, which may prevent the scroll entirely by calling preventDefault() on the event.

Solution: {passive: true}

By marking a touch or wheel listener as passive, the developer is promising the handler won't call preventDefault to disable scrolling. This frees the browser up to respond to scrolling immediately without waiting for JavaScript, thus ensuring a reliably smooth scrolling experience for the user.

document.addEventListener("touchstart", function(e) {
    console.log(e.defaultPrevented);  // will be false
    e.preventDefault();   // does nothing since the listener is passive
    console.log(e.defaultPrevented);  // still false
}, Modernizr.passiveeventlisteners ? {passive: true} : false);

DOM Spec , Demo Video , Explainer Doc

Python: Removing list element while iterating over list

You can still use filter, moving to an outside function the element modification (iterating just once)

def do_the_magic(x):
    do_action(x)
    return check(x)

# you can get a different filtered list
filter(do_the_magic,yourList)

# or have it modified in place (as suggested by Steven Rumbalski, see comment)
yourList[:] = itertools.ifilter(do_the_magic, yourList)

Javascript: How to check if a string is empty?

But for a better check:

if(str === null || str === '')
{
    //enter code here
}

How do I get column names to print in this C# program?

foreach (DataRow row in dt.Rows)
{
    foreach (DataColumn column in dt.Columns)
    {
        ColumnName = column.ColumnName;
        ColumnData = row[column].ToString();
    }
}

How can I make a DateTimePicker display an empty string?

The basic concept is the same told by others. But its easier to implement this way when you have multiple dateTimePicker.

dateTimePicker1.Value = DateTime.Now;
dateTimePicker1.ValueChanged += new System.EventHandler(this.Dtp_ValueChanged);
dateTimePicker1.ShowCheckBox=true;
dateTimePicker1.Checked=false;


dateTimePicker2.Value = DateTime.Now;
dateTimePicker2.ValueChanged += new System.EventHandler(this.Dtp_ValueChanged);
dateTimePicker2.ShowCheckBox=true;
dateTimePicker2.Checked=false;

the value changed event function

        void Dtp_ValueChanged(object sender, EventArgs e)
        {
            if(((DateTimePicker)sender).ShowCheckBox==true)
            {
                if(((DateTimePicker)sender).Checked==false)
                {
                    ((DateTimePicker)sender).CustomFormat = " ";
                    ((DateTimePicker)sender).Format = DateTimePickerFormat.Custom;
                }
                else
                {
                    ((DateTimePicker)sender).Format = DateTimePickerFormat.Short;
                }
            }
            else
            {
                ((DateTimePicker)sender).Format = DateTimePickerFormat.Short;
            }
        }

When unchecked enter image description here

When checked enter image description here

"Input string was not in a correct format."

Please change your code like below.

  int QuestionID;

  bool IsIntValue = Int32.TryParse("YOUR-VARIABLE", out QuestionID);

  if (IsIntValue)
  {
      // YOUR CODE HERE  
  }

Hope i will be help.

Is there a way to add/remove several classes in one single instruction with classList?

Assume that you have an array of classes to being added, you can use ES6 spread syntax:

let classes = ['first', 'second', 'third']; elem.classList.add(...classes);

Clearfix with twitter bootstrap

clearfix should contain the floating elements but in your html you have added clearfix only after floating right that is your pull-right so you should do like this:

<div class="clearfix">
  <div id="sidebar">
    <ul>
      <li>A</li>
      <li>A</li>
      <li>C</li>
      <li>D</li>
      <li>E</li>
      <li>F</li>
      <li>...</li>
      <li>Z</li>
    </ul>
  </div>
  <div id="main">
    <div>
      <div class="pull-right">
        <a>RIGHT</a>
      </div>
    </div>
  <div>MOVED BELOW Z</div>
</div>

see this demo


Happy to know you solved the problem by setting overflow properties. However this is also good idea to clear the float. Where you have floated your elements you could add overflow: hidden; as you have done in your main.

What exactly is a Context in Java?

A Context represents your environment. It represents the state surrounding where you are in your system.

For example, in web programming in Java, you have a Request, and a Response. These are passed to the service method of a Servlet.

A property of the Servlet is the ServletConfig, and within that is a ServletContext.

The ServletContext is used to tell the servlet about the Container that the Servlet is within.

So, the ServletContext represents the servlets environment within its container.

Similarly, in Java EE, you have EBJContexts that elements (like session beans) can access to work with their containers.

Those are two examples of contexts used in Java today.

Edit --

You mention Android.

Look here: http://developer.android.com/reference/android/content/Context.html

You can see how this Context gives you all sorts of information about where the Android app is deployed and what's available to it.