Programs & Examples On #Visualsvn server

VisualSVN Server is a commercial and proprietary Subversion server package for Windows operating system.

Working Copy Locked

You can fix it with only one step.

Step 1 : Open terminal and go to your project then fire command "svn cleanup" then "svn update"

SVN Commit failed, access forbidden

As a new user to these two software packages, I experienced the exact same problem. As was also discovered above, my solution was to use the same case letters as is in the Repository path.

Here's a tip that I find helpful: In VisualSVN, you can right click on the path, then click "Copy URL to Clipboard" for pasting in Tortoise to be sure that the path is the identical case.

Uninstalling Android ADT

i got the same problem after clicking update plugins, i tried all the suggestions above and failed , the only thing that worked for my is reinstalling android studio..

Renaming a directory in C#

One already exists. If you cannot get over the "Move" syntax of the System.IO namespace. There is a static class FileSystem within the Microsoft.VisualBasic.FileIO namespace that has both a RenameDirectory and RenameFile already within it.

As mentioned by SLaks, this is just a wrapper for Directory.Move and File.Move.

Scaling an image to fit on canvas

You made the error, for the second call, to set the size of source to the size of the target.
Anyway i bet that you want the same aspect ratio for the scaled image, so you need to compute it :

var hRatio = canvas.width / img.width    ;
var vRatio = canvas.height / img.height  ;
var ratio  = Math.min ( hRatio, vRatio );
ctx.drawImage(img, 0,0, img.width, img.height, 0,0,img.width*ratio, img.height*ratio);

i also suppose you want to center the image, so the code would be :

function drawImageScaled(img, ctx) {
   var canvas = ctx.canvas ;
   var hRatio = canvas.width  / img.width    ;
   var vRatio =  canvas.height / img.height  ;
   var ratio  = Math.min ( hRatio, vRatio );
   var centerShift_x = ( canvas.width - img.width*ratio ) / 2;
   var centerShift_y = ( canvas.height - img.height*ratio ) / 2;  
   ctx.clearRect(0,0,canvas.width, canvas.height);
   ctx.drawImage(img, 0,0, img.width, img.height,
                      centerShift_x,centerShift_y,img.width*ratio, img.height*ratio);  
}

you can see it in a jsbin here : http://jsbin.com/funewofu/1/edit?js,output

Variable that has the path to the current ansible-playbook that is executing?

I was using a playbook like this to test my roles locally:

---
- hosts: localhost
  roles:
     - role: .

but this stopped working with Ansible v2.2.

I debugged the aforementioned solution of

---
- hosts: all
  tasks:
    - name: Find out playbooks path
      shell: pwd
      register: playbook_path_output
    - debug: var=playbook_path_output.stdout

and it produced my home directory and not the "current working directory"

I settled with

---
- hosts: all
  roles:
    - role: '{{playbook_dir}}'

per the solution above.

Google Maps API V3 : How show the direction from a point A to point B (Blue line)?

I'm using a popup to show the map in a new window. I'm using the following url

https://www.google.com/maps?z=15&daddr=LATITUDE,LONGITUDE

HTML snippet

<a target='_blank' href='https://www.google.com/maps?z=15&daddr=${location.latitude},${location.longitude}'>Calculate route</a>

jQuery Validation plugin: disable validation for specified submit buttons

Here is the simplest version, hope it helps someone,

$('#cancel-button').click(function() {
    var $form = $(this).closest('form');
    $form.find('*[data-validation]').attr('data-validation', null);
    $form.get(0).submit();
});

Add regression line equation and R^2 on graph

I've modified Ramnath's post to a) make more generic so it accepts a linear model as a parameter rather than the data frame and b) displays negatives more appropriately.

lm_eqn = function(m) {

  l <- list(a = format(coef(m)[1], digits = 2),
      b = format(abs(coef(m)[2]), digits = 2),
      r2 = format(summary(m)$r.squared, digits = 3));

  if (coef(m)[2] >= 0)  {
    eq <- substitute(italic(y) == a + b %.% italic(x)*","~~italic(r)^2~"="~r2,l)
  } else {
    eq <- substitute(italic(y) == a - b %.% italic(x)*","~~italic(r)^2~"="~r2,l)    
  }

  as.character(as.expression(eq));                 
}

Usage would change to:

p1 = p + geom_text(aes(x = 25, y = 300, label = lm_eqn(lm(y ~ x, df))), parse = TRUE)

How to catch curl errors in PHP

you can generate curl error after its execution

$url = 'http://example.com';

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
if(curl_errno($ch)){
    echo 'Request Error:' . curl_error($ch);
}

and here are curl error code

if someone need more information about curl errors

<?php

    $error_codes=array(
    [1] => 'CURLE_UNSUPPORTED_PROTOCOL',
    [2] => 'CURLE_FAILED_INIT',
    [3] => 'CURLE_URL_MALFORMAT',
    [4] => 'CURLE_URL_MALFORMAT_USER',
    [5] => 'CURLE_COULDNT_RESOLVE_PROXY',
    [6] => 'CURLE_COULDNT_RESOLVE_HOST',
    [7] => 'CURLE_COULDNT_CONNECT',
    [8] => 'CURLE_FTP_WEIRD_SERVER_REPLY',
    [9] => 'CURLE_REMOTE_ACCESS_DENIED',
    [11] => 'CURLE_FTP_WEIRD_PASS_REPLY',
    [13] => 'CURLE_FTP_WEIRD_PASV_REPLY',
    [14]=>'CURLE_FTP_WEIRD_227_FORMAT',
    [15] => 'CURLE_FTP_CANT_GET_HOST',
    [17] => 'CURLE_FTP_COULDNT_SET_TYPE',
    [18] => 'CURLE_PARTIAL_FILE',
    [19] => 'CURLE_FTP_COULDNT_RETR_FILE',
    [21] => 'CURLE_QUOTE_ERROR',
    [22] => 'CURLE_HTTP_RETURNED_ERROR',
    [23] => 'CURLE_WRITE_ERROR',
    [25] => 'CURLE_UPLOAD_FAILED',
    [26] => 'CURLE_READ_ERROR',
    [27] => 'CURLE_OUT_OF_MEMORY',
    [28] => 'CURLE_OPERATION_TIMEDOUT',
    [30] => 'CURLE_FTP_PORT_FAILED',
    [31] => 'CURLE_FTP_COULDNT_USE_REST',
    [33] => 'CURLE_RANGE_ERROR',
    [34] => 'CURLE_HTTP_POST_ERROR',
    [35] => 'CURLE_SSL_CONNECT_ERROR',
    [36] => 'CURLE_BAD_DOWNLOAD_RESUME',
    [37] => 'CURLE_FILE_COULDNT_READ_FILE',
    [38] => 'CURLE_LDAP_CANNOT_BIND',
    [39] => 'CURLE_LDAP_SEARCH_FAILED',
    [41] => 'CURLE_FUNCTION_NOT_FOUND',
    [42] => 'CURLE_ABORTED_BY_CALLBACK',
    [43] => 'CURLE_BAD_FUNCTION_ARGUMENT',
    [45] => 'CURLE_INTERFACE_FAILED',
    [47] => 'CURLE_TOO_MANY_REDIRECTS',
    [48] => 'CURLE_UNKNOWN_TELNET_OPTION',
    [49] => 'CURLE_TELNET_OPTION_SYNTAX',
    [51] => 'CURLE_PEER_FAILED_VERIFICATION',
    [52] => 'CURLE_GOT_NOTHING',
    [53] => 'CURLE_SSL_ENGINE_NOTFOUND',
    [54] => 'CURLE_SSL_ENGINE_SETFAILED',
    [55] => 'CURLE_SEND_ERROR',
    [56] => 'CURLE_RECV_ERROR',
    [58] => 'CURLE_SSL_CERTPROBLEM',
    [59] => 'CURLE_SSL_CIPHER',
    [60] => 'CURLE_SSL_CACERT',
    [61] => 'CURLE_BAD_CONTENT_ENCODING',
    [62] => 'CURLE_LDAP_INVALID_URL',
    [63] => 'CURLE_FILESIZE_EXCEEDED',
    [64] => 'CURLE_USE_SSL_FAILED',
    [65] => 'CURLE_SEND_FAIL_REWIND',
    [66] => 'CURLE_SSL_ENGINE_INITFAILED',
    [67] => 'CURLE_LOGIN_DENIED',
    [68] => 'CURLE_TFTP_NOTFOUND',
    [69] => 'CURLE_TFTP_PERM',
    [70] => 'CURLE_REMOTE_DISK_FULL',
    [71] => 'CURLE_TFTP_ILLEGAL',
    [72] => 'CURLE_TFTP_UNKNOWNID',
    [73] => 'CURLE_REMOTE_FILE_EXISTS',
    [74] => 'CURLE_TFTP_NOSUCHUSER',
    [75] => 'CURLE_CONV_FAILED',
    [76] => 'CURLE_CONV_REQD',
    [77] => 'CURLE_SSL_CACERT_BADFILE',
    [78] => 'CURLE_REMOTE_FILE_NOT_FOUND',
    [79] => 'CURLE_SSH',
    [80] => 'CURLE_SSL_SHUTDOWN_FAILED',
    [81] => 'CURLE_AGAIN',
    [82] => 'CURLE_SSL_CRL_BADFILE',
    [83] => 'CURLE_SSL_ISSUER_ERROR',
    [84] => 'CURLE_FTP_PRET_FAILED',
    [84] => 'CURLE_FTP_PRET_FAILED',
    [85] => 'CURLE_RTSP_CSEQ_ERROR',
    [86] => 'CURLE_RTSP_SESSION_ERROR',
    [87] => 'CURLE_FTP_BAD_FILE_LIST',
    [88] => 'CURLE_CHUNK_FAILED');

    ?>

Checking if output of a command contains a certain string in a shell script

Another option is to check for regular expression match on the command output.

For example:

[[ "$(./somecommand)" =~ "sub string" ]] && echo "Output includes 'sub string'"

Fitting a histogram with python

I was a bit puzzled that norm.fit apparently only worked with the expanded list of sampled values. I tried giving it two lists of numbers, or lists of tuples, but it only appeared to flatten everything and threat the input as individual samples. Since I already have a histogram based on millions of samples, I didn't want to expand this if I didn't have to. Thankfully, the normal distribution is trivial to calculate, so...

# histogram is [(val,count)]
from math import sqrt

def normfit(hist):
    n,s,ss = univar(hist)
    mu = s/n
    var = ss/n-mu*mu
    return (mu, sqrt(var))

def univar(hist):
    n = 0
    s = 0
    ss = 0
    for v,c in hist:
        n += c
        s += c*v
        ss += c*v*v
    return n, s, ss

I'm sure this must be provided by the libraries, but as I couldn't find it anywhere, I'm posting this here instead. Feel free to point to the correct way to do it and downvote me :-)

Hidden features of Windows batch files

You can modify a batch file while it is running. For example you can add a forgotten pause to the end of the file while it's running if you wanted to see the results before the batch file quit.

see Changing a batch file when its running

I personally think of this more as a gotcha than a feature.

CSS3 Box Shadow on Top, Left, and Right Only

#div:before {
 content:"";
 position:absolute;
 width:100%;
 background:#fff;
 height:38px;
 top:1px;
 right:-5px;
}

Correct use of flush() in JPA/Hibernate

Can em.flush() cause any harm when using it within a transaction?

Yes, it may hold locks in the database for a longer duration than necessary.

Generally, When using JPA you delegates the transaction management to the container (a.k.a CMT - using @Transactional annotation on business methods) which means that a transaction is automatically started when entering the method and commited / rolled back at the end. If you let the EntityManager handle the database synchronization, sql statements execution will be only triggered just before the commit, leading to short lived locks in database. Otherwise your manually flushed write operations may retain locks between the manual flush and the automatic commit which can be long according to remaining method execution time.

Notes that some operation automatically triggers a flush : executing a native query against the same session (EM state must be flushed to be reachable by the SQL query), inserting entities using native generated id (generated by the database, so the insert statement must be triggered thus the EM is able to retrieve the generated id and properly manage relationships)

Font Awesome icon inside text input element

Building on allcaps suggestion. Here is the font-awesome background method with the least amount of HTML:

<div class="wrapper"><input></div>

.wrapper {
    position: relative; 
}

input { padding-left: 20px; }

.wrapper:before {
    font-family: 'FontAwesome';
    position: absolute;
    top: 2px;
    left: 3px;
    content: "\f007";
}

Open another application from your own (intent)

For API level 3+, nothing more then one line of code:

Intent intent = context.getPackageManager().getLaunchIntentForPackage("name.of.package");

Return a CATEGORY_INFO launch Intent (apps with no launcher activity, wallpapers for example, often use this to provide some information about app) and, if no find it, returns the CATEGORY_LAUNCH of package, if exists.

How can I copy a file on Unix using C?

Another variant of the copy function using normal POSIX calls and without any loop. Code inspired from the buffer copy variant of the answer of caf. Warning: Using mmap can easily fail on 32 bit systems, on 64 bit system the danger is less likely.

#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <sys/mman.h>

int cp(const char *to, const char *from)
{
  int fd_from = open(from, O_RDONLY);
  if(fd_from < 0)
    return -1;
  struct stat Stat;
  if(fstat(fd_from, &Stat)<0)
    goto out_error;

  void *mem = mmap(NULL, Stat.st_size, PROT_READ, MAP_SHARED, fd_from, 0);
  if(mem == MAP_FAILED)
    goto out_error;

  int fd_to = creat(to, 0666);
  if(fd_to < 0)
    goto out_error;

  ssize_t nwritten = write(fd_to, mem, Stat.st_size);
  if(nwritten < Stat.st_size)
    goto out_error;

  if(close(fd_to) < 0) {
    fd_to = -1;
    goto out_error;
  }
  close(fd_from);

  /* Success! */
  return 0;
}
out_error:;
  int saved_errno = errno;

  close(fd_from);
  if(fd_to >= 0)
    close(fd_to);

  errno = saved_errno;
  return -1;
}

EDIT: Corrected the file creation bug. See comment in http://stackoverflow.com/questions/2180079/how-can-i-copy-a-file-on-unix-using-c/2180157#2180157 answer.

Password hash function for Excel VBA

Here is the MD5 code inserted in an Excel Module with the name "module_md5":

    Private Const BITS_TO_A_BYTE = 8
    Private Const BYTES_TO_A_WORD = 4
    Private Const BITS_TO_A_WORD = 32

    Private m_lOnBits(30)
    Private m_l2Power(30)

    Sub SetUpArrays()
        m_lOnBits(0) = CLng(1)
        m_lOnBits(1) = CLng(3)
        m_lOnBits(2) = CLng(7)
        m_lOnBits(3) = CLng(15)
        m_lOnBits(4) = CLng(31)
        m_lOnBits(5) = CLng(63)
        m_lOnBits(6) = CLng(127)
        m_lOnBits(7) = CLng(255)
        m_lOnBits(8) = CLng(511)
        m_lOnBits(9) = CLng(1023)
        m_lOnBits(10) = CLng(2047)
        m_lOnBits(11) = CLng(4095)
        m_lOnBits(12) = CLng(8191)
        m_lOnBits(13) = CLng(16383)
        m_lOnBits(14) = CLng(32767)
        m_lOnBits(15) = CLng(65535)
        m_lOnBits(16) = CLng(131071)
        m_lOnBits(17) = CLng(262143)
        m_lOnBits(18) = CLng(524287)
        m_lOnBits(19) = CLng(1048575)
        m_lOnBits(20) = CLng(2097151)
        m_lOnBits(21) = CLng(4194303)
        m_lOnBits(22) = CLng(8388607)
        m_lOnBits(23) = CLng(16777215)
        m_lOnBits(24) = CLng(33554431)
        m_lOnBits(25) = CLng(67108863)
        m_lOnBits(26) = CLng(134217727)
        m_lOnBits(27) = CLng(268435455)
        m_lOnBits(28) = CLng(536870911)
        m_lOnBits(29) = CLng(1073741823)
        m_lOnBits(30) = CLng(2147483647)

        m_l2Power(0) = CLng(1)
        m_l2Power(1) = CLng(2)
        m_l2Power(2) = CLng(4)
        m_l2Power(3) = CLng(8)
        m_l2Power(4) = CLng(16)
        m_l2Power(5) = CLng(32)
        m_l2Power(6) = CLng(64)
        m_l2Power(7) = CLng(128)
        m_l2Power(8) = CLng(256)
        m_l2Power(9) = CLng(512)
        m_l2Power(10) = CLng(1024)
        m_l2Power(11) = CLng(2048)
        m_l2Power(12) = CLng(4096)
        m_l2Power(13) = CLng(8192)
        m_l2Power(14) = CLng(16384)
        m_l2Power(15) = CLng(32768)
        m_l2Power(16) = CLng(65536)
        m_l2Power(17) = CLng(131072)
        m_l2Power(18) = CLng(262144)
        m_l2Power(19) = CLng(524288)
        m_l2Power(20) = CLng(1048576)
        m_l2Power(21) = CLng(2097152)
        m_l2Power(22) = CLng(4194304)
        m_l2Power(23) = CLng(8388608)
        m_l2Power(24) = CLng(16777216)
        m_l2Power(25) = CLng(33554432)
        m_l2Power(26) = CLng(67108864)
        m_l2Power(27) = CLng(134217728)
        m_l2Power(28) = CLng(268435456)
        m_l2Power(29) = CLng(536870912)
        m_l2Power(30) = CLng(1073741824)
    End Sub

    Private Function LShift(lValue, iShiftBits)
        If iShiftBits = 0 Then
            LShift = lValue
            Exit Function
        ElseIf iShiftBits = 31 Then
            If lValue And 1 Then
                LShift = &H80000000
            Else
                LShift = 0
            End If
            Exit Function
        ElseIf iShiftBits < 0 Or iShiftBits > 31 Then
            Err.Raise 6
        End If

        If (lValue And m_l2Power(31 - iShiftBits)) Then
            LShift = ((lValue And m_lOnBits(31 - (iShiftBits + 1))) * m_l2Power(iShiftBits)) Or &H80000000
        Else
            LShift = ((lValue And m_lOnBits(31 - iShiftBits)) * m_l2Power(iShiftBits))
        End If
    End Function

    Private Function RShift(lValue, iShiftBits)
        If iShiftBits = 0 Then
            RShift = lValue
            Exit Function
        ElseIf iShiftBits = 31 Then
            If lValue And &H80000000 Then
                RShift = 1
            Else
                RShift = 0
            End If
            Exit Function
        ElseIf iShiftBits < 0 Or iShiftBits > 31 Then
            Err.Raise 6
        End If

        RShift = (lValue And &H7FFFFFFE) \ m_l2Power(iShiftBits)

        If (lValue And &H80000000) Then
            RShift = (RShift Or (&H40000000 \ m_l2Power(iShiftBits - 1)))
        End If
    End Function

    Private Function RotateLeft(lValue, iShiftBits)
        RotateLeft = LShift(lValue, iShiftBits) Or RShift(lValue, (32 - iShiftBits))
    End Function

    Private Function AddUnsigned(lX, lY)
        Dim lX4
        Dim lY4
        Dim lX8
        Dim lY8
        Dim lResult

        lX8 = lX And &H80000000
        lY8 = lY And &H80000000
        lX4 = lX And &H40000000
        lY4 = lY And &H40000000

        lResult = (lX And &H3FFFFFFF) + (lY And &H3FFFFFFF)

        If lX4 And lY4 Then
            lResult = lResult Xor &H80000000 Xor lX8 Xor lY8
        ElseIf lX4 Or lY4 Then
            If lResult And &H40000000 Then
                lResult = lResult Xor &HC0000000 Xor lX8 Xor lY8
            Else
                lResult = lResult Xor &H40000000 Xor lX8 Xor lY8
            End If
        Else
            lResult = lResult Xor lX8 Xor lY8
        End If

        AddUnsigned = lResult
    End Function

    Private Function F(x, y, z)
        F = (x And y) Or ((Not x) And z)
    End Function

    Private Function G(x, y, z)
        G = (x And z) Or (y And (Not z))
    End Function

    Private Function H(x, y, z)
        H = (x Xor y Xor z)
    End Function

    Private Function I(x, y, z)
        I = (y Xor (x Or (Not z)))
    End Function

    Private Sub FF(a, b, c, d, x, s, ac)
        a = AddUnsigned(a, AddUnsigned(AddUnsigned(F(b, c, d), x), ac))
        a = RotateLeft(a, s)
        a = AddUnsigned(a, b)
    End Sub

    Private Sub GG(a, b, c, d, x, s, ac)
        a = AddUnsigned(a, AddUnsigned(AddUnsigned(G(b, c, d), x), ac))
        a = RotateLeft(a, s)
        a = AddUnsigned(a, b)
    End Sub

    Private Sub HH(a, b, c, d, x, s, ac)
        a = AddUnsigned(a, AddUnsigned(AddUnsigned(H(b, c, d), x), ac))
        a = RotateLeft(a, s)
        a = AddUnsigned(a, b)
    End Sub

    Private Sub II(a, b, c, d, x, s, ac)
        a = AddUnsigned(a, AddUnsigned(AddUnsigned(I(b, c, d), x), ac))
        a = RotateLeft(a, s)
        a = AddUnsigned(a, b)
    End Sub

    Private Function ConvertToWordArray(sMessage)
        Dim lMessageLength
        Dim lNumberOfWords
        Dim lWordArray()
        Dim lBytePosition
        Dim lByteCount
        Dim lWordCount

        Const MODULUS_BITS = 512
        Const CONGRUENT_BITS = 448

        lMessageLength = Len(sMessage)

        lNumberOfWords = (((lMessageLength + ((MODULUS_BITS - CONGRUENT_BITS) \ BITS_TO_A_BYTE)) \ (MODULUS_BITS \ BITS_TO_A_BYTE)) + 1) * (MODULUS_BITS \ BITS_TO_A_WORD)
        ReDim lWordArray(lNumberOfWords - 1)

        lBytePosition = 0
        lByteCount = 0
        Do Until lByteCount >= lMessageLength
            lWordCount = lByteCount \ BYTES_TO_A_WORD
            lBytePosition = (lByteCount Mod BYTES_TO_A_WORD) * BITS_TO_A_BYTE
            lWordArray(lWordCount) = lWordArray(lWordCount) Or LShift(Asc(Mid(sMessage, lByteCount + 1, 1)), lBytePosition)
            lByteCount = lByteCount + 1
        Loop

        lWordCount = lByteCount \ BYTES_TO_A_WORD
        lBytePosition = (lByteCount Mod BYTES_TO_A_WORD) * BITS_TO_A_BYTE

        lWordArray(lWordCount) = lWordArray(lWordCount) Or LShift(&H80, lBytePosition)

        lWordArray(lNumberOfWords - 2) = LShift(lMessageLength, 3)
        lWordArray(lNumberOfWords - 1) = RShift(lMessageLength, 29)

        ConvertToWordArray = lWordArray
    End Function

    Private Function WordToHex(lValue)
        Dim lByte
        Dim lCount

        For lCount = 0 To 3
            lByte = RShift(lValue, lCount * BITS_TO_A_BYTE) And m_lOnBits(BITS_TO_A_BYTE - 1)
            WordToHex = WordToHex & Right("0" & Hex(lByte), 2)
        Next
    End Function

    Public Function MD5(sMessage)

        module_md5.SetUpArrays

        Dim x
        Dim k
        Dim AA
        Dim BB
        Dim CC
        Dim DD
        Dim a
        Dim b
        Dim c
        Dim d

        Const S11 = 7
        Const S12 = 12
        Const S13 = 17
        Const S14 = 22
        Const S21 = 5
        Const S22 = 9
        Const S23 = 14
        Const S24 = 20
        Const S31 = 4
        Const S32 = 11
        Const S33 = 16
        Const S34 = 23
        Const S41 = 6
        Const S42 = 10
        Const S43 = 15
        Const S44 = 21

        x = ConvertToWordArray(sMessage)

        a = &H67452301
        b = &HEFCDAB89
        c = &H98BADCFE
        d = &H10325476

        For k = 0 To UBound(x) Step 16
            AA = a
            BB = b
            CC = c
            DD = d

            FF a, b, c, d, x(k + 0), S11, &HD76AA478
            FF d, a, b, c, x(k + 1), S12, &HE8C7B756
            FF c, d, a, b, x(k + 2), S13, &H242070DB
            FF b, c, d, a, x(k + 3), S14, &HC1BDCEEE
            FF a, b, c, d, x(k + 4), S11, &HF57C0FAF
            FF d, a, b, c, x(k + 5), S12, &H4787C62A
            FF c, d, a, b, x(k + 6), S13, &HA8304613
            FF b, c, d, a, x(k + 7), S14, &HFD469501
            FF a, b, c, d, x(k + 8), S11, &H698098D8
            FF d, a, b, c, x(k + 9), S12, &H8B44F7AF
            FF c, d, a, b, x(k + 10), S13, &HFFFF5BB1
            FF b, c, d, a, x(k + 11), S14, &H895CD7BE
            FF a, b, c, d, x(k + 12), S11, &H6B901122
            FF d, a, b, c, x(k + 13), S12, &HFD987193
            FF c, d, a, b, x(k + 14), S13, &HA679438E
            FF b, c, d, a, x(k + 15), S14, &H49B40821

            GG a, b, c, d, x(k + 1), S21, &HF61E2562
            GG d, a, b, c, x(k + 6), S22, &HC040B340
            GG c, d, a, b, x(k + 11), S23, &H265E5A51
            GG b, c, d, a, x(k + 0), S24, &HE9B6C7AA
            GG a, b, c, d, x(k + 5), S21, &HD62F105D
            GG d, a, b, c, x(k + 10), S22, &H2441453
            GG c, d, a, b, x(k + 15), S23, &HD8A1E681
            GG b, c, d, a, x(k + 4), S24, &HE7D3FBC8
            GG a, b, c, d, x(k + 9), S21, &H21E1CDE6
            GG d, a, b, c, x(k + 14), S22, &HC33707D6
            GG c, d, a, b, x(k + 3), S23, &HF4D50D87
            GG b, c, d, a, x(k + 8), S24, &H455A14ED
            GG a, b, c, d, x(k + 13), S21, &HA9E3E905
            GG d, a, b, c, x(k + 2), S22, &HFCEFA3F8
            GG c, d, a, b, x(k + 7), S23, &H676F02D9
            GG b, c, d, a, x(k + 12), S24, &H8D2A4C8A

            HH a, b, c, d, x(k + 5), S31, &HFFFA3942
            HH d, a, b, c, x(k + 8), S32, &H8771F681
            HH c, d, a, b, x(k + 11), S33, &H6D9D6122
            HH b, c, d, a, x(k + 14), S34, &HFDE5380C
            HH a, b, c, d, x(k + 1), S31, &HA4BEEA44
            HH d, a, b, c, x(k + 4), S32, &H4BDECFA9
            HH c, d, a, b, x(k + 7), S33, &HF6BB4B60
            HH b, c, d, a, x(k + 10), S34, &HBEBFBC70
            HH a, b, c, d, x(k + 13), S31, &H289B7EC6
            HH d, a, b, c, x(k + 0), S32, &HEAA127FA
            HH c, d, a, b, x(k + 3), S33, &HD4EF3085
            HH b, c, d, a, x(k + 6), S34, &H4881D05
            HH a, b, c, d, x(k + 9), S31, &HD9D4D039
            HH d, a, b, c, x(k + 12), S32, &HE6DB99E5
            HH c, d, a, b, x(k + 15), S33, &H1FA27CF8
            HH b, c, d, a, x(k + 2), S34, &HC4AC5665

            II a, b, c, d, x(k + 0), S41, &HF4292244
            II d, a, b, c, x(k + 7), S42, &H432AFF97
            II c, d, a, b, x(k + 14), S43, &HAB9423A7
            II b, c, d, a, x(k + 5), S44, &HFC93A039
            II a, b, c, d, x(k + 12), S41, &H655B59C3
            II d, a, b, c, x(k + 3), S42, &H8F0CCC92
            II c, d, a, b, x(k + 10), S43, &HFFEFF47D
            II b, c, d, a, x(k + 1), S44, &H85845DD1
            II a, b, c, d, x(k + 8), S41, &H6FA87E4F
            II d, a, b, c, x(k + 15), S42, &HFE2CE6E0
            II c, d, a, b, x(k + 6), S43, &HA3014314
            II b, c, d, a, x(k + 13), S44, &H4E0811A1
            II a, b, c, d, x(k + 4), S41, &HF7537E82
            II d, a, b, c, x(k + 11), S42, &HBD3AF235
            II c, d, a, b, x(k + 2), S43, &H2AD7D2BB
            II b, c, d, a, x(k + 9), S44, &HEB86D391

            a = AddUnsigned(a, AA)
            b = AddUnsigned(b, BB)
            c = AddUnsigned(c, CC)
            d = AddUnsigned(d, DD)
        Next

        MD5 = LCase(WordToHex(a) & WordToHex(b) & WordToHex(c) & WordToHex(d))
    End Function

How to push both value and key into PHP array

The simple way:

$GET = array();    
$key = 'one=1';
parse_str($key, $GET);

http://php.net/manual/de/function.parse-str.php

How to restrict the selectable date ranges in Bootstrap Datepicker?

The example above can be simplify a bit. Additionally you can put date manually from keyboard instead of selecting it via datepicker only. When clearing the value you need to handle also 'on clearDate' action to remove startDate/endDate boundary:

JS file:

$(".from_date").datepicker({
    format: 'yyyy-mm-dd',
    autoclose: true,
}).on('changeDate', function (selected) {
    var startDate = new Date(selected.date.valueOf());
    $('.to_date').datepicker('setStartDate', startDate);
}).on('clearDate', function (selected) {
    $('.to_date').datepicker('setStartDate', null);
});

$(".to_date").datepicker({
    format: 'yyyy-mm-dd',
    autoclose: true,
}).on('changeDate', function (selected) {
    var endDate = new Date(selected.date.valueOf());
    $('.from_date').datepicker('setEndDate', endDate);
}).on('clearDate', function (selected) {
    $('.from_date').datepicker('setEndDate', null);
});

HTML:

<input class="from_date" placeholder="Select start date" type="text" name="from_date">
<input class="to_date" placeholder="Select end date" type="text" name="to_date">

Invalid use side-effecting operator Insert within a function

There is an exception (I'm using SQL 2014) when you are only using Insert/Update/Delete on Declared-Tables. These Insert/Update/Delete statements cannot contain an OUTPUT statement. The other restriction is that you are not allowed to do a MERGE, even into a Declared-Table. I broke up my Merge statements, that didn't work, into Insert/Update/Delete statements that did work.

The reason I didn't convert it to a stored-procedure is that the table-function was faster (even without the MERGE) than the stored-procedure. This is despite the stored-procedure allowing me to use Temp-Tables that have statistics. I needed the table-function to be very fast, since it is called 20-K times/day. This table function never updates the database.

I also noticed that the NewId() and RAND() SQL functions are not allowed in a function.

Most efficient way to see if an ArrayList contains an object in Java

You could use a Comparator with Java's built-in methods for sorting and binary search. Suppose you have a class like this, where a and b are the fields you want to use for sorting:

class Thing { String a, b, c, d; }

You would define your Comparator:

Comparator<Thing> comparator = new Comparator<Thing>() {
  public int compare(Thing o1, Thing o2) {
    if (o1.a.equals(o2.a)) {
      return o1.b.compareTo(o2.b);
    }
    return o1.a.compareTo(o2.a);
  }
};

Then sort your list:

Collections.sort(list, comparator);

And finally do the binary search:

int i = Collections.binarySearch(list, thingToFind, comparator);

Calculate RSA key fingerprint

$ ssh-add -l 

will also work on Mac OS X v10.8 (Mountain Lion) - v10.10 (Yosemite).

It also supports the option -E to specify the fingerprint format so in case MD5 is needed (it's often used, e.g. by GitHub), just add -E md5 to the command.

Automating running command on Linux from Windows using PuTTY

You can write a TCL script and establish SSH session to that Linux machine and issue commands automatically. Check http://wiki.tcl.tk/11542 for a short tutorial.

Cache an HTTP 'Get' service response in AngularJS?

As AngularJS factories are singletons, you can simply store the result of the http request and retrieve it next time your service is injected into something.

angular.module('myApp', ['ngResource']).factory('myService',
  function($resource) {
    var cache = false;
    return {
      query: function() {
        if(!cache) {
          cache = $resource('http://example.com/api').query();
        }
        return cache;
      }
    };
  }
);

How to use if - else structure in a batch file?

Your syntax is incorrect. You can't use ELSE IF. It appears that you don't really need it anyway. Simply use multiple IF statements:

IF %F%==1 IF %C%==1 (
    ::copying the file c to d
    copy "%sourceFile%" "%destinationFile%"
    )

IF %F%==1 IF %C%==0 (
    ::moving the file c to d
    move "%sourceFile%" "%destinationFile%"
    )

IF %F%==0 IF %C%==1 (
    ::copying a directory c from d, /s:  bos olanlar hariç, /e:bos olanlar dahil
    xcopy "%sourceCopyDirectory%" "%destinationCopyDirectory%" /s/e
    )

IF %F%==0 IF %C%==0 (
    ::moving a directory
    xcopy /E "%sourceMoveDirectory%" "%destinationMoveDirectory%"
    rd /s /q "%sourceMoveDirectory%"
    )

Great batch file reference: http://ss64.com/nt/if.html

Javascript - Get Image height

Well...there are several ways to interpret this question.

The first way and the way I think you mean is to simply alter the display size so all images display the same size. For this, I would actually use CSS and not JavaScript. Simply create a class that has the appropriate width and height values set, and make all <img> tags use this class.

A second way is that you want to preserve the aspect ration of all the images, but scale the display size to a sane value. There is a way to access this in JavaScript, but I'll need a bit to write up a quick code sample.

The third way, and I hope you don't mean this way, is to alter the actual size of the image. This is something you'd have to do on the server side, as not only is JavaScript unable to create images, but it wouldn't make any sense, as the full sized image has already been sent.

Gridview row editing - dynamic binding to a DropDownList

protected void grvSecondaryLocations_RowEditing(object sender, GridViewEditEventArgs e)  
{  
    grvSecondaryLocations.EditIndex = e.NewEditIndex;  

    DropDownList ddlPbx = (DropDownList)(grvSecondaryLocations.Rows[grvSecondaryLocations.EditIndex].FindControl("ddlPBXTypeNS"));
    if (ddlPbx != null)  
    {  
        ddlPbx.DataSource = _pbxTypes;  
        ddlPbx.DataBind();  
    }  

    .... (more stuff)  
}

NSCameraUsageDescription in iOS 10.0 runtime crash?

After iOS 10 you have to define and provide a usage description of all the system’s privacy-sensitive data accessed by your app in Info.plist as below:

Calendar

Key    :  Privacy - Calendars Usage Description    
Value  :  $(PRODUCT_NAME) calendar events

Reminder :

Key    :   Privacy - Reminders Usage Description    
Value  :   $(PRODUCT_NAME) reminder use

Contact :

Key    :   Privacy - Contacts Usage Description     
Value  :  $(PRODUCT_NAME) contact use

Photo :

Key    :  Privacy - Photo Library Usage Description    
Value  :  $(PRODUCT_NAME) photo use

Bluetooth Sharing :

Key    :  Privacy - Bluetooth Peripheral Usage Description     
Value  :  $(PRODUCT_NAME) Bluetooth Peripheral use

Microphone :

Key    :  Privacy - Microphone Usage Description    
Value  :  $(PRODUCT_NAME) microphone use

Camera :

Key    :  Privacy - Camera Usage Description   
Value  :  $(PRODUCT_NAME) camera use

Location :

Key    :  Privacy - Location Always Usage Description   
Value  :  $(PRODUCT_NAME) location use

Key    :  Privacy - Location When In Use Usage Description   
Value  :  $(PRODUCT_NAME) location use

Heath :

Key    :  Privacy - Health Share Usage Description   
Value  :  $(PRODUCT_NAME) heath share use

Key    :  Privacy - Health Update Usage Description   
Value  :  $(PRODUCT_NAME) heath update use

HomeKit :

Key    :  Privacy - HomeKit Usage Description   
Value  :  $(PRODUCT_NAME) home kit use

Media Library :

Key    :  Privacy - Media Library Usage Description   
Value  :  $(PRODUCT_NAME) media library use

Motion :

Key    :  Privacy - Motion Usage Description   
Value  :  $(PRODUCT_NAME) motion use

Speech Recognition :

Key    :  Privacy - Speech Recognition Usage Description   
Value  :  $(PRODUCT_NAME) speech use

SiriKit :

Key    :  Privacy - Siri Usage Description  
Value  :  $(PRODUCT_NAME) siri use

TV Provider :

Key    :  Privacy - TV Provider Usage Description   
Value  :  $(PRODUCT_NAME) tvProvider use

You can get detailed information in this link.

Moment.js transform to date object

moment has updated the js lib as of 06/2018.

var newYork    = moment.tz("2014-06-01 12:00", "America/New_York");
var losAngeles = newYork.clone().tz("America/Los_Angeles");
var london     = newYork.clone().tz("Europe/London");

newYork.format();    // 2014-06-01T12:00:00-04:00
losAngeles.format(); // 2014-06-01T09:00:00-07:00
london.format();     // 2014-06-01T17:00:00+01:00

if you have freedom to use Angular5+, then better use datePipe feature there than the timezone function here. I have to use moment.js because my project limits to Angular2 only.

How to set the matplotlib figure default size in ipython notebook?

If you don't have this ipython_notebook_config.py file, you can create one by following the readme and typing

ipython profile create

Remove an element from a Bash array

Here's a one-line solution with mapfile:

$ mapfile -d $'\0' -t arr < <(printf '%s\0' "${arr[@]}" | grep -Pzv "<regexp>")

Example:

$ arr=("Adam" "Bob" "Claire"$'\n'"Smith" "David" "Eve" "Fred")

$ echo "Size: ${#arr[*]} Contents: ${arr[*]}"

Size: 6 Contents: Adam Bob Claire
Smith David Eve Fred

$ mapfile -d $'\0' -t arr < <(printf '%s\0' "${arr[@]}" | grep -Pzv "^Claire\nSmith$")

$ echo "Size: ${#arr[*]} Contents: ${arr[*]}"

Size: 5 Contents: Adam Bob David Eve Fred

This method allows for great flexibility by modifying/exchanging the grep command and doesn't leave any empty strings in the array.

Reference requirements.txt for the install_requires kwarg in setuptools setup.py file

Most of the other answers above don't work with the current version of pip's API. Here is the correct* way to do it with the current version of pip (6.0.8 at the time of writing, also worked in 7.1.2. You can check your version with pip -V).

from pip.req import parse_requirements
from pip.download import PipSession

install_reqs = parse_requirements(<requirements_path>, session=PipSession())

reqs = [str(ir.req) for ir in install_reqs]

setup(
    ...
    install_requires=reqs
    ....
)

* Correct, in that it is the way to use parse_requirements with the current pip. It still probably isn't the best way to do it, since, as posters above said, pip doesn't really maintain an API.

Cast Double to Integer in Java

double a = 13.34;
int b = (int) a;

System.out.println(b); //prints 13

"Primary Filegroup is Full" in SQL Server 2008 Standard for no apparent reason

I just ran into the same problem. The reason was that the virtual memory file "pagefile.sys" was located on the same drive as our data files for our databases (D: drive). It had doubled in size and filled the disk but windows wasn't picking it up, i.e. it looked like we had 80 GB free when we actually didn't.

Restarting SQL server didn't help, perhaps defragment would give the OS time to free up the pagefile, but we just rebooted the server and voila, the pagefile had shrunk and everything worked fine.

What is interesting is that during the 30 min we were investigating, windows didn't calculate the size of the pagefile.sys at all (80gb). After restart windows did find the pagefile and included it's size in the total disk usage (now 40gb - which is still too big).

Hide the browse button on a input type=file

You may just without making the element hidden, simply make it transparent by making its opacity to 0.

Making the input file hidden will make it STOP working. So DON'T DO THAT..

Here you can find an example for a transparent Browse operation;

Android Studio-No Module

I had a similar issue of my app module disappearing, this was after a large merge (from hell). I found app.iml was missing <component name="FacetManager"> when compared with other projects and before the merge. So I copy and pasted the below under the root <module > element.

Manually editing the .iml files maybe ill advised so proceed at your own risk.

File: project root folder > app > app.iml

Add the following...

  <component name="FacetManager">
    <facet type="android-gradle" name="Android-Gradle">
      <configuration>
        <option name="GRADLE_PROJECT_PATH" value=":app" />
      </configuration>
    </facet>
    <facet type="android" name="Android">
      <configuration>
        <option name="SELECTED_BUILD_VARIANT" value="debug" />
        <option name="SELECTED_TEST_ARTIFACT" value="_android_test_" />
        <option name="ASSEMBLE_TASK_NAME" value="assembleDebug" />
        <option name="COMPILE_JAVA_TASK_NAME" value="compileDebugSources" />
        <afterSyncTasks>
          <task>generateDebugSources</task>
        </afterSyncTasks>
        <option name="ALLOW_USER_CONFIGURATION" value="false" />
        <option name="MANIFEST_FILE_RELATIVE_PATH" value="/src/main/AndroidManifest.xml" />
        <option name="RES_FOLDER_RELATIVE_PATH" value="/src/main/res" />
        <option name="RES_FOLDERS_RELATIVE_PATH" value="file://$MODULE_DIR$/src/main/res;file://$MODULE_DIR$/src/debug/res" />
        <option name="ASSETS_FOLDER_RELATIVE_PATH" value="/src/main/assets" />
      </configuration>
    </facet>
  </component>

Save and load weights in keras

Since this question is quite old, but still comes up in google searches, I thought it would be good to point out the newer (and recommended) way to save Keras models. Instead of saving them using the older h5 format like has been shown before, it is now advised to use the SavedModel format, which is actually a dictionary that contains both the model configuration and the weights.

More information can be found here: https://www.tensorflow.org/guide/keras/save_and_serialize

The snippets to save & load can be found below:

model.fit(test_input, test_target)
# Calling save('my_model') creates a SavedModel folder 'my_model'.
model.save('my_model')

# It can be used to reconstruct the model identically.
reconstructed_model = keras.models.load_model('my_model')

A sample output of this :

enter image description here

HashMap - getting First Key value

Java 8 way of doing,

String firstKey = map.keySet().stream().findFirst().get();

Looping over a list in Python

You may as well use for x in values rather than for x in values[:]; the latter makes an unnecessary copy. Also, of course that code checks for a length of 2 rather than of 3...

The code only prints one item per value of x - and x is iterating over the elements of values, which are the sublists. So it will only print each sublist once.

jQuery hover and class selector

I prefer foxy's answer because we should never use javascript when existing css properties are made for the job.

Don't forget to add display: block ; in .menuItem, so height and width are taken into account.

edit : for better script/look&feel decoupling, if you ever need to change style through jQuery I'd define an additional css class and use $(...).addClass("myclass") and $(...).removeClass("myclass")

How can I reset eclipse to default settings?

Delete the .metadata folder in your workspace.

Add new field to every document in a MongoDB collection

Since MongoDB version 3.2 you can use updateMany():

> db.yourCollection.updateMany({}, {$set:{"someField": "someValue"}})

How to call webmethod in Asp.net C#

I'm not sure why that isn't working, It works fine on my test. But here is an alternative technique that might help.

Instead of calling the method in the AJAX url, just use the page .aspx url, and add the method as a parameter in the data object. Then when it calls page_load, your data will be in the Request.Form variable.

jQuery

jQuery.ajax({
    url: 'AddToCart.aspx',
    type: "POST",
    data: {
        method: 'AddTo_Cart', quantity: total_qty, itemId: itemId
    },
    dataType: "json",
    beforeSend: function () {
        alert("Start!!! ");
    },
    success: function (data) {
        alert("a");
    },
    failure: function (msg) { alert("Sorry!!! "); }
});

C# Page Load:

if (!Page.IsPostBack)
{
    if (Request.Form["method"] == "AddTo_Cart")
    {
        int q, id;
        int.TryParse(Request.Form["quantity"], out q);
        int.TryParse(Request.Form["itemId"], out id);
        AddTo_Cart(q,id);
    }
}

How can I return pivot table output in MySQL?

select t3.name, sum(t3.prod_A) as Prod_A, sum(t3.prod_B) as Prod_B, sum(t3.prod_C) as    Prod_C, sum(t3.prod_D) as Prod_D, sum(t3.prod_E) as Prod_E  
from
(select t2.name as name, 
case when t2.prodid = 1 then t2.counts
else 0 end  prod_A, 

case when t2.prodid = 2 then t2.counts
else 0 end prod_B,

case when t2.prodid = 3 then t2.counts
else 0 end prod_C,

case when t2.prodid = 4 then t2.counts
else 0 end prod_D, 

case when t2.prodid = "5" then t2.counts
else 0 end prod_E

from 
(SELECT partners.name as name, sales.products_id as prodid, count(products.name) as counts
FROM test.sales left outer join test.partners on sales.partners_id = partners.id
left outer join test.products on sales.products_id = products.id 
where sales.partners_id = partners.id and sales.products_id = products.id group by partners.name, prodid) t2) t3

group by t3.name ;

IndexError: too many indices for array

I think the problem is given in the error message, although it is not very easy to spot:

IndexError: too many indices for array
xs  = data[:, col["l1"     ]]

'Too many indices' means you've given too many index values. You've given 2 values as you're expecting data to be a 2D array. Numpy is complaining because data is not 2D (it's either 1D or None).

This is a bit of a guess - I wonder if one of the filenames you pass to loadfile() points to an empty file, or a badly formatted one? If so, you might get an array returned that is either 1D, or even empty (np.array(None) does not throw an Error, so you would never know...). If you want to guard against this failure, you can insert some error checking into your loadfile function.

I highly recommend in your for loop inserting:

print(data)

This will work in Python 2.x or 3.x and might reveal the source of the issue. You might well find it is only one value of your outputs_l1 list (i.e. one file) that is giving the issue.

data.frame rows to a list

If you want to completely abuse the data.frame (as I do) and like to keep the $ functionality, one way is to split you data.frame into one-line data.frames gathered in a list :

> df = data.frame(x=c('a','b','c'), y=3:1)
> df
  x y
1 a 3
2 b 2
3 c 1

# 'convert' into a list of data.frames
ldf = lapply(as.list(1:dim(df)[1]), function(x) df[x[1],])

> ldf
[[1]]
x y
1 a 3    
[[2]]
x y
2 b 2
[[3]]
x y
3 c 1

# and the 'coolest'
> ldf[[2]]$y
[1] 2

It is not only intellectual masturbation, but allows to 'transform' the data.frame into a list of its lines, keeping the $ indexation which can be useful for further use with lapply (assuming the function you pass to lapply uses this $ indexation)

Pass value to iframe from a window

Use the frames collection.

From the link:

var frames = window.frames; // or // var frames = window.parent.frames;
for (var i = 0; i < frames.length; i++) { 
  // do something with each subframe as frames[i]
  frames[i].document.body.style.background = "red";
}

If the iframe has a name you may also do the following:

window.frames['ponies'].number_of_ponies = 7;

You can only do this if the two pages are served from the same domain.

moment.js get current time in milliseconds?

To get the current time's milliseconds, use http://momentjs.com/docs/#/get-set/millisecond/

var timeInMilliseconds = moment().milliseconds();

Redis: Show database size/size for keys

You might find it very useful to sample Redis keys and group them by type. Salvatore has written a tool called redis-sampler that issues about 10000 RANDOMKEY commands followed by a TYPE on retrieved keys. In a matter of seconds, or minutes, you should get a fairly accurate view of the distribution of key types.

I've written an extension (unfortunately not anywhere open-source because it's work related), that adds a bit of introspection of key names via regexs that give you an idea of what kinds of application keys (according to whatever naming structure you're using), are stored in Redis. Combined with the more general output of redis-sampler, this should give you an extremely good idea of what's going on.

How do I collapse sections of code in Visual Studio Code for Windows?

Or, if you want to remove the folding buttons, for extra space:

"editor.folding": false

(add to your settings.json file)

Image is not showing in browser?

I find out the way how to set the image path just remove the "/" before the destination folder as "images/66.jpg" not "/images/66.jpg" And its working fine for me.

How to set password for Redis?

open redis configuration file

sudo nano /etc/redis/redis.conf 

set passphrase

replace

# requirepass foobared

with

requirepass YOURPASSPHRASE

restart redis

redis-server restart

How can I get a user's media from Instagram without authenticating as a user?

I really needed this function but for Wordpress. I fit and it worked perfectly

<script>
    jQuery(function($){
        var name = "caririceara.comcariri";
        $.get("https://images"+~~(Math.random()*33)+"-focus-opensocial.googleusercontent.com/gadgets/proxy?container=none&url=https://www.instagram.com/" + name + "/", function(html) {
            if (html) {
                var regex = /_sharedData = ({.*);<\/script>/m,
                  json = JSON.parse(regex.exec(html)[1]),
                  edges = json.entry_data.ProfilePage[0].graphql.user.edge_owner_to_timeline_media.edges;
              $.each(edges, function(n, edge) {
                   if (n <= 7){
                     var node = edge.node;
                    $('.img_ins').append('<a href="https://instagr.am/p/'+node.shortcode+'" target="_blank"><img src="'+node.thumbnail_src+'" width="150"></a>');
                   }
              });
            }
        });
    }); 
    </script>

'Conda' is not recognized as internal or external command

This problem arose for me when I installed Anaconda multiple times. I was careful to do an uninstall but there are some things that the uninstall process doesn't undo.

In my case, I needed to remove a file Microsoft.PowerShell_profile.ps1 from ~\Documents\WindowsPowerShell\. I identified that this file was the culprit by opening it in a text editor. I saw that it referenced the old installation location C:\Anaconda3\.

How to quickly clear a JavaScript Object?

You can delete the props, but don't delete variables. delete abc; is invalid in ES5 (and throws with use strict).

You can assign it to null to set it for deletion to the GC (it won't if you have other references to properties)

Setting length property on an object does not change anything. (it only, well, sets the property)

Python Image Library fails with message "decoder JPEG not available" - PIL

For those on Mac OS Mountain Lion, I followed the anwser of zeantsoi, but it doesn't work.

I finally ended up with the solution of this post: http://appelfreelance.com/2010/06/libjpeg-pil-snow-leopard-python2-6-_jpeg_resync_to_restart/

Now, I'm happily running my script for jpeg !

add a string prefix to each value in a string column using Pandas

You can use pandas.Series.map :

df['col'].map('str{}'.format)

It will apply the word "str" before all your values.

Recursive Lock (Mutex) vs Non-Recursive Lock (Mutex)

What are non-recursive mutexes good for?

They are absolutely good when you have to make sure the mutex is unlocked before doing something. This is because pthread_mutex_unlock can guarantee that the mutex is unlocked only if it is non-recursive.

pthread_mutex_t      g_mutex;

void foo()
{
    pthread_mutex_lock(&g_mutex);
    // Do something.
    pthread_mutex_unlock(&g_mutex);

    bar();
}

If g_mutex is non-recursive, the code above is guaranteed to call bar() with the mutex unlocked.

Thus eliminating the possibility of a deadlock in case bar() happens to be an unknown external function which may well do something that may result in another thread trying to acquire the same mutex. Such scenarios are not uncommon in applications built on thread pools, and in distributed applications, where an interprocess call may spawn a new thread without the client programmer even realising that. In all such scenarios it's best to invoke the said external functions only after the lock is released.

If g_mutex was recursive, there would be simply no way to make sure it is unlocked before making a call.

How to find the cumulative sum of numbers in a list?

Somewhat hacky, but seems to work:

def cumulative_sum(l):
  y = [0]
  def inc(n):
    y[0] += n
    return y[0]
  return [inc(x) for x in l]

I did think that the inner function would be able to modify the y declared in the outer lexical scope, but that didn't work, so we play some nasty hacks with structure modification instead. It is probably more elegant to use a generator.

Is it possible to set UIView border properties from interface builder?

while this might set the properties, it doesnt actually reflect in IB. So if you're essentially writing code in IB, you might as well then do it in your source code

How to handle ETIMEDOUT error?

This is caused when your request response is not received in given time(by timeout request module option).

Basically to catch that error first, you need to register a handler on error, so the unhandled error won't be thrown anymore: out.on('error', function (err) { /* handle errors here */ }). Some more explanation here.

In the handler you can check if the error is ETIMEDOUT and apply your own logic: if (err.message.code === 'ETIMEDOUT') { /* apply logic */ }.

If you want to request for the file again, I suggest using node-retry or node-backoff modules. It makes things much simpler.

If you want to wait longer, you can set timeout option of request yourself. You can set it to 0 for no timeout.

Is there a "theirs" version of "git merge -s ours"?

I solved my problem using

git checkout -m old
git checkout -b new B
git merge -s ours old

Python Linked List

The following is what I came up with. It's similer to Riccardo C.'s, in this thread, except it prints the numbers in order instead of in reverse. I also made the LinkedList object a Python Iterator in order to print the list out like you would a normal Python list.

class Node:

    def __init__(self, data=None):
        self.data = data
        self.next = None

    def __str__(self):
        return str(self.data)


class LinkedList:

    def __init__(self):
        self.head = None
        self.curr = None
        self.tail = None

    def __iter__(self):
        return self

    def next(self):
        if self.head and not self.curr:
            self.curr = self.head
            return self.curr
        elif self.curr.next:
            self.curr = self.curr.next
            return self.curr
        else:
            raise StopIteration

    def append(self, data):
        n = Node(data)
        if not self.head:
            self.head = n
            self.tail = n
        else:
            self.tail.next = n
            self.tail = self.tail.next


# Add 5 nodes
ll = LinkedList()
for i in range(1, 6):
    ll.append(i)

# print out the list
for n in ll:
    print n

"""
Example output:
$ python linked_list.py
1
2
3
4
5
"""

Postgresql column reference "id" is ambiguous

You need the table name/alias in the SELECT part (maybe (vg.id, name)) :

SELECT (vg.id, name) FROM v_groups vg 
inner join people2v_groups p2vg on vg.id = p2vg.v_group_id
where p2vg.people_id =0;

How do I fire an event when a iframe has finished loading in jQuery?

$("#iFrameId").ready(function (){
    // do something once the iframe is loaded
});

have you tried .ready instead?

Looking for a short & simple example of getters/setters in C#

Simple example

    public  class Simple
    {
        public int Propery { get; set; }
    }

How can I uninstall npm modules in Node.js?

To uninstall a module using npm, you can use:

npm uninstall moduleName

Also, if you want to uninstall and want the change to be reflected in your package.json then you can use the --save flag, like this:

npm uninstall moduleName --save
OR
npm uninstall -S

And if you want to uninstall a module from devDependencies and want the change to be reflected in package.json then you can use -D flag, like this:

npm uninstall moduleName -D

Validating an XML against referenced XSD in C#

A simpler way, if you are using .NET 3.5, is to use XDocument and XmlSchemaSet validation.

XmlSchemaSet schemas = new XmlSchemaSet();
schemas.Add(schemaNamespace, schemaFileName);

XDocument doc = XDocument.Load(filename);
string msg = "";
doc.Validate(schemas, (o, e) => {
    msg += e.Message + Environment.NewLine;
});
Console.WriteLine(msg == "" ? "Document is valid" : "Document invalid: " + msg);

See the MSDN documentation for more assistance.

Ruby/Rails: converting a Date to a UNIX timestamp

The suggested options of using to_utc or utc to fix the local time offset does not work. For me I found using Time.utc() worked correctly and the code involves less steps:

> Time.utc(2016, 12, 25).to_i
=> 1482624000 # correct

vs

> Date.new(2016, 12, 25).to_time.utc.to_i
=> 1482584400 # incorrect

Here is what happens when you call utc after using Date....

> Date.new(2016, 12, 25).to_time
=> 2016-12-25 00:00:00 +1100 # This will use your system's time offset
> Date.new(2016, 12, 25).to_time.utc
=> 2016-12-24 13:00:00 UTC

...so clearly calling to_i is going to give the wrong timestamp.

error: cast from 'void*' to 'int' loses precision

I meet this problem too.

ids[i] = (int) arg; // error occur here => I change this to below.

ids[i] = (uintptr_t) arg;

Then I can continue compiling. Maybe you can try this too.

How to make a redirection on page load in JSF 1.x

Assume that foo.jsp is your jsp file. and following code is the button that you want do redirect.

<h:commandButton value="Redirect" action="#{trial.enter }"/>  

And now we'll check the method for directing in your java (service) class

 public String enter() {
            if (userName.equals("xyz") && password.equals("123")) {
                return "enter";
            } else {
                return null;
            }
        } 

and now this is a part of faces-config.xml file

<managed-bean>
        <managed-bean-name>'class_name'</managed-bean-name>
        <managed-bean-class>'package_name'</managed-bean-class>
        <managed-bean-scope>request</managed-bean-scope>
    </managed-bean>


    <navigation-case>
                <from-outcome>enter</from-outcome>
                <to-view-id>/foo.jsp</to-view-id>
                <redirect />
            </navigation-case>

Uncaught TypeError: Cannot read property 'appendChild' of null

There isn't an element on your page with the id "mainContent" when your callback is being executed.

In the line:

document.getElementById("mainContent").appendChild(p);

the section document.getElementById("mainContent") is returning null

Re-assign host access permission to MySQL user

I haven't had to do this, so take this with a grain of salt and a big helping of "test, test, test".

What happens if (in a safe controlled test environment) you directly modify the Host column in the mysql.user and probably mysql.db tables? (E.g., with an update statement.) I don't think MySQL uses the user's host as part of the password encoding (the PASSWORD function doesn't suggest it does), but you'll have to try it to be sure. You may need to issue a FLUSH PRIVILEGES command (or stop and restart the server).

For some storage engines (MyISAM, for instance), you may also need to check/modify the .frm file any views that user has created. The .frm file stores the definer, including the definer's host. (I have had to do this, when moving databases between hosts where there had been a misconfiguration causing the wrong host to be recorded...)

ASP.NET MVC - Set custom IIdentity or IPrincipal

Here's how I do it.

I decided to use IPrincipal instead of IIdentity because it means I don't have to implement both IIdentity and IPrincipal.

  1. Create the interface

    interface ICustomPrincipal : IPrincipal
    {
        int Id { get; set; }
        string FirstName { get; set; }
        string LastName { get; set; }
    }
    
  2. CustomPrincipal

    public class CustomPrincipal : ICustomPrincipal
    {
        public IIdentity Identity { get; private set; }
        public bool IsInRole(string role) { return false; }
    
        public CustomPrincipal(string email)
        {
            this.Identity = new GenericIdentity(email);
        }
    
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
    
  3. CustomPrincipalSerializeModel - for serializing custom information into userdata field in FormsAuthenticationTicket object.

    public class CustomPrincipalSerializeModel
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
    
  4. LogIn method - setting up a cookie with custom information

    if (Membership.ValidateUser(viewModel.Email, viewModel.Password))
    {
        var user = userRepository.Users.Where(u => u.Email == viewModel.Email).First();
    
        CustomPrincipalSerializeModel serializeModel = new CustomPrincipalSerializeModel();
        serializeModel.Id = user.Id;
        serializeModel.FirstName = user.FirstName;
        serializeModel.LastName = user.LastName;
    
        JavaScriptSerializer serializer = new JavaScriptSerializer();
    
        string userData = serializer.Serialize(serializeModel);
    
        FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
                 1,
                 viewModel.Email,
                 DateTime.Now,
                 DateTime.Now.AddMinutes(15),
                 false,
                 userData);
    
        string encTicket = FormsAuthentication.Encrypt(authTicket);
        HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
        Response.Cookies.Add(faCookie);
    
        return RedirectToAction("Index", "Home");
    }
    
  5. Global.asax.cs - Reading cookie and replacing HttpContext.User object, this is done by overriding PostAuthenticateRequest

    protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
    {
        HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
    
        if (authCookie != null)
        {
            FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
    
            JavaScriptSerializer serializer = new JavaScriptSerializer();
    
            CustomPrincipalSerializeModel serializeModel = serializer.Deserialize<CustomPrincipalSerializeModel>(authTicket.UserData);
    
            CustomPrincipal newUser = new CustomPrincipal(authTicket.Name);
            newUser.Id = serializeModel.Id;
            newUser.FirstName = serializeModel.FirstName;
            newUser.LastName = serializeModel.LastName;
    
            HttpContext.Current.User = newUser;
        }
    }
    
  6. Access in Razor views

    @((User as CustomPrincipal).Id)
    @((User as CustomPrincipal).FirstName)
    @((User as CustomPrincipal).LastName)
    

and in code:

    (User as CustomPrincipal).Id
    (User as CustomPrincipal).FirstName
    (User as CustomPrincipal).LastName

I think the code is self-explanatory. If it isn't, let me know.

Additionally to make the access even easier you can create a base controller and override the returned User object (HttpContext.User):

public class BaseController : Controller
{
    protected virtual new CustomPrincipal User
    {
        get { return HttpContext.User as CustomPrincipal; }
    }
}

and then, for each controller:

public class AccountController : BaseController
{
    // ...
}

which will allow you to access custom fields in code like this:

User.Id
User.FirstName
User.LastName

But this will not work inside views. For that you would need to create a custom WebViewPage implementation:

public abstract class BaseViewPage : WebViewPage
{
    public virtual new CustomPrincipal User
    {
        get { return base.User as CustomPrincipal; }
    }
}

public abstract class BaseViewPage<TModel> : WebViewPage<TModel>
{
    public virtual new CustomPrincipal User
    {
        get { return base.User as CustomPrincipal; }
    }
}

Make it a default page type in Views/web.config:

<pages pageBaseType="Your.Namespace.BaseViewPage">
  <namespaces>
    <add namespace="System.Web.Mvc" />
    <add namespace="System.Web.Mvc.Ajax" />
    <add namespace="System.Web.Mvc.Html" />
    <add namespace="System.Web.Routing" />
  </namespaces>
</pages>

and in views, you can access it like this:

@User.FirstName
@User.LastName

How to add a "open git-bash here..." context menu to the windows explorer?

As, @Shaswat Rungta said: "I think the question is more about how to add it after the installation is over."

On my PC(Windows 7) I think that the command "Git Bash here" disappeard after I installed Visual Studio 2017.

I fixt this by downloading and installing Git again.


NOTE: "When installing Git for Windows the context menu options are not 'on' by default. You will have to select them during the install." – @nbushnell (I did this)

tar: Error is not recoverable: exiting now

Try to get your archive using wget, I had the same issue when I was downloading archive through browser. Than I just copy archive link and in terminal use the command:

wget http://PATH_TO_ARCHIVE

Including a groovy script in another groovy

As of Groovy 2.2 it is possible to declare a base script class with the new @BaseScript AST transform annotation.

Example:

file MainScript.groovy:

abstract class MainScript extends Script {
    def meaningOfLife = 42
}

file test.groovy:

import groovy.transform.BaseScript
@BaseScript MainScript mainScript

println "$meaningOfLife" //works as expected

How to automatically generate unique id in SQL like UID12345678?

The only viable solution in my opinion is to use

  • an ID INT IDENTITY(1,1) column to get SQL Server to handle the automatic increment of your numeric value
  • a computed, persisted column to convert that numeric value to the value you need

So try this:

CREATE TABLE dbo.tblUsers
  (ID INT IDENTITY(1,1) NOT NULL PRIMARY KEY CLUSTERED,
   UserID AS 'UID' + RIGHT('00000000' + CAST(ID AS VARCHAR(8)), 8) PERSISTED,
   .... your other columns here....
  )

Now, every time you insert a row into tblUsers without specifying values for ID or UserID:

INSERT INTO dbo.tblUsersCol1, Col2, ..., ColN)
VALUES (Val1, Val2, ....., ValN)

then SQL Server will automatically and safely increase your ID value, and UserID will contain values like UID00000001, UID00000002,...... and so on - automatically, safely, reliably, no duplicates.

Update: the column UserID is computed - but it still OF COURSE has a data type, as a quick peek into the Object Explorer reveals:

enter image description here

When to create variables (memory management)

In your example number is a primitive, so will be stored as a value.

If you want to use a reference then you should use one of the wrapper types (e.g. Integer)

Java - checking if parseInt throws exception

Check if it is integer parseable

public boolean isInteger(String string) {
    try {
        Integer.valueOf(string);
        return true;
    } catch (NumberFormatException e) {
        return false;
    }
}

or use Scanner

Scanner scanner = new Scanner("Test string: 12.3 dog 12345 cat 1.2E-3");

while (scanner.hasNext()) {
    if (scanner.hasNextDouble()) {
        Double doubleValue = scanner.nextDouble();
    } else {
        String stringValue = scanner.next();
    }
}

or use Regular Expression like

private static Pattern doublePattern = Pattern.compile("-?\\d+(\\.\\d*)?");

public boolean isDouble(String string) {
    return doublePattern.matcher(string).matches();
}

In Flask, What is request.args and how is it used?

It has some interesting behaviour in some cases that is good to be aware of:

from werkzeug.datastructures import MultiDict

d = MultiDict([("ex1", ""), ("ex2", None)])

d.get("ex1", "alternive")
# returns: ''

d.get("ex2", "alternative")
# returns no visible output of any kind
# It is returning literally None, so if you do:
d.get("ex2", "alternative") is None
# it returns: True

d.get("ex3", "alternative")
# returns: 'alternative'

Assigning a variable NaN in python without numpy

You can get NaN from "inf - inf", and you can get "inf" from a number greater than 2e308, so, I generally used:

>>> inf = 9e999
>>> inf
inf
>>> inf - inf
nan

Uncaught TypeError: Cannot read property 'top' of undefined

The problem you are most likely having is that there is a link somewhere in the page to an anchor that does not exist. For instance, let's say you have the following:

<a href="#examples">Skip to examples</a>

There has to be an element in the page with that id, example:

<div id="examples">Here are the examples</div>

So make sure that each one of the links are matched inside the page with it's corresponding anchor.

Reload a DIV without reloading the whole page

The code you're using is also going to include a fadeout effect. Is this what you want to achieve? If not, it might make more sense to just add the following INSIDE "Small.php".

<meta http-equiv="refresh" content="15" >

This adds a refresh every 15seconds to the small.php page which should mean if called by PHP into another page, only that "frame" will reload.

Let us know if it worked/solved your problem!?

-Brad

How to pass datetime from c# to sql correctly?

You've already done it correctly by using a DateTime parameter with the value from the DateTime, so it should already work. Forget about ToString() - since that isn't used here.

If there is a difference, it is most likely to do with different precision between the two environments; maybe choose a rounding (seconds, maybe?) and use that. Also keep in mind UTC/local/unknown (the DB has no concept of the "kind" of date; .NET does).

I have a table and the date-times in it are in the format: 2011-07-01 15:17:33.357

Note that datetimes in the database aren't in any such format; that is just your query-client showing you white lies. It is stored as a number (and even that is an implementation detail), because humans have this odd tendency not to realise that the date you've shown is the same as 40723.6371916281. Stupid humans. By treating it simply as a "datetime" throughout, you shouldn't get any problems.

How to make a Java thread wait for another thread's output?

If you want something quick and dirty, you can just add a Thread.sleep() call within your while loop. If the database library is something you can't change, then there is really no other easy solution. Polling the database until is ready with a wait period won't kill the performance.

while (!dbthread.isReady()) {
  Thread.sleep(250);
}

Hardly something that you could call elegant code, but gets the work done.

In case you can modify the database code, then using a mutex as proposed in other answers is better.

forEach() in React JSX does not output any HTML

You need to pass an array of element to jsx. The problem is that forEach does not return anything (i.e it returns undefined). So it's better to use map because map returns an array:

class QuestionSet extends Component {
render(){ 
    <div className="container">
       <h1>{this.props.question.text}</h1>
       {this.props.question.answers.map((answer, i) => {     
           console.log("Entered");                 
           // Return the element. Also pass key     
           return (<Answer key={answer} answer={answer} />) 
        })}
}

export default QuestionSet;

MySQL: Insert datetime into other datetime field

for MYSQL try this

INSERT INTO table1(myDatetimeField)VALUES(STR_TO_DATE('12-01-2014 00:00:00','%m-%d-%Y %H:%i:%s');

verification-

select * from table1
output- datetime= 2014-12-01 00:00:00

Automatic creation date for Django model form objects?

Well, the above answer is correct, auto_now_add and auto_now would do it, but it would be better to make an abstract class and use it in any model where you require created_at and updated_at fields.

class TimeStampMixin(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        abstract = True

Now anywhere you want to use it you can do a simple inherit and you can use timestamp in any model you make like.

class Posts(TimeStampMixin):
    name = models.CharField(max_length=50)
    ...
    ...

In this way, you can leverage object-oriented reusability, in Django DRY(don't repeat yourself)

Command line to remove an environment variable from the OS level configuration

This has been covered quite a bit, but there's a crucial piece of information that's missing. Hopefully, I can help to clear up how this works and give some relief to weary travellers. :-)

Delete From Current Process

Obviously, everyone knows that you just do this to delete an environment variable from your current process:

set FOO=

Persistent Delete

There are two sets of environment variables, system-wide and user.

Delete User Environment Variable:

reg delete "HKCU\Environment" /v FOO /f

Delete System-Wide Environment Variable:

REG delete "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /F /V FOO

Apply Value Without Rebooting

Here's the magic information that's missing! You're wondering why after you do this, when you launch a new command window, the environment variable is still there. The reason is because explorer.exe has not updated its environment. When one process launches another, the new process inherits the environment from the process that launched it.

There are two ways to fix this without rebooting. The most brute-force way is to kill your explorer.exe process and start it again. You can do that from Task Manager. I don't recommend this method, however.

The other way is by telling explorer.exe that the environment has changed and that it should reread it. This is done by broadcasting a Windows message (WM_SETTINGCHANGE). This can be accomplished with a simple PowerShell script. You could easily write one to do this, but I found one in Update Window Settings After Scripted Changes:

if (-not ("win32.nativemethods" -as [type])) {
    add-type -Namespace Win32 -Name NativeMethods -MemberDefinition @"
        [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        public static extern IntPtr SendMessageTimeout(
            IntPtr hWnd, uint Msg, UIntPtr wParam, string lParam,
            uint fuFlags, uint uTimeout, out UIntPtr lpdwResult);
        "@
}

$HWND_BROADCAST = [intptr]0xffff;
$WM_SETTINGCHANGE = 0x1a;
$result = [uintptr]::zero

[win32.nativemethods]::SendMessageTimeout($HWND_BROADCAST, $WM_SETTINGCHANGE,[uintptr]::Zero, "Environment", 2, 5000, [ref]$result);

Summary

So to delete a user environment variable named "FOO" and have the change reflected in processes you launch afterwards, do the following.

  1. Save the PowerShell script to a file (we'll call it updateenv.ps1).
  2. Do this from the command line: reg delete "HKCU\Environment" /v FOO /f
  3. Run updateenv.ps1.
  4. Close and reopen your command prompt, and you'll see that the environment variable is no longer defined.

Note, you'll probably have to update your PowerShell settings to allow you to run this script, but I'll leave that as a Google-fu exercise for you.

How to find a value in an array of objects in JavaScript?

You can find the object in array with Alasql library:

var data = [ { name : "bob" , dinner : "pizza" }, { name : "john" , dinner : "sushi" },
     { name : "larry", dinner : "hummus" } ];

var res = alasql('SELECT * FROM ? WHERE dinner="sushi"',[data]);

Try this example in jsFiddle.

Android: checkbox listener

You could use this code.

public class MySampleActivity extends Activity {
    CheckBox cb1, cb2, cb3, cb4;
    LinearLayout l1, l2, l3, l4;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        cb1 = (CheckBox) findViewById(R.id.cb1);
        cb2 = (CheckBox) findViewById(R.id.cb2);
        cb3 = (CheckBox) findViewById(R.id.cb3);
        cb4 = (CheckBox) findViewById(R.id.cb4);
        l1 = (LinearLayout) findViewById(R.id.l1);
        l2 = (LinearLayout) findViewById(R.id.l2);
        l3 = (LinearLayout) findViewById(R.id.l3);
        l4 = (LinearLayout) findViewById(R.id.l4);
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        cb1.setOnCheckedChangeListener(new MyCheckedChangeListener(1));
        cb1.setOnCheckedChangeListener(new MyCheckedChangeListener(2));
        cb1.setOnCheckedChangeListener(new MyCheckedChangeListener(3));
        cb1.setOnCheckedChangeListener(new MyCheckedChangeListener(4));
    }

    public class MyCheckedChangeListener implements CompoundButton.OnCheckedChangeListener {
        int position;

        public MyCheckedChangeListener(int position) {
            this.position = position;
        }

        private void changeVisibility(LinearLayout layout, boolean isChecked) {
            if (isChecked) {
                l1.setVisibility(View.VISIBLE);
            } else {
                l1.setVisibility(View.GONE);
            }

        }

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            switch (position) {
                case 1:
                    changeVisibility(l1, isChecked);
                    break;
                case 2:
                    changeVisibility(l2, isChecked);
                    break;
                case 3:
                    changeVisibility(l3, isChecked);
                    break;
                case 4:
                    changeVisibility(l4, isChecked);
                    break;
            }
        }
    }
}

printf, wprintf, %s, %S, %ls, char* and wchar*: Errors not announced by a compiler warning?

Answer A

None of the answers above pointed out why you might not see some of your prints. This is also because here you are dealing with streams (I didn't know this) and stream has something called orientation. Let me cite something from this source:

Narrow and wide orientation

A newly opened stream has no orientation. The first call to any I/O function establishes the orientation.

A wide I/O function makes the stream wide-oriented, a narrow I/O function makes the stream narrow-oriented. Once set, the orientation can only be changed with freopen.

Narrow I/O functions cannot be called on a wide-oriented stream; wide I/O functions cannot be called on a narrow-oriented stream. Wide I/O functions convert between wide and multibyte characters as if by calling mbrtowc and wcrtomb. Unlike the multibyte character strings that are valid in a program, multibyte character sequences in the file may contain embedded nulls and do not have to begin or end in the initial shift state.

So once you use printf() your orientation becomes narrow and from this point on you can't get anything out of wprintf() and you realy don't. Unless you use freeopen() which is intended to be used on files.


Answer B

As it turns out you can use freeopen() like this:

freopen(NULL, "w", stdout);             

To make stream "not defined" again. Try this example:

#include <stdio.h>
#include <wchar.h>
#include <locale.h>

int main(void)
{
    // We set locale which is the same as the enviromental variable "LANG=en_US.UTF-8".
    setlocale(LC_ALL, "en_US.UTF-8");

    // We define array of wide characters. We indicate this on both sides of equal sign
    // with "wchar_t" on the left and "L" on the right.
    wchar_t y[100] = L"€? ???a??p???? e? a??? est??\n";

    // We print header in ASCII characters
    wprintf(L"content-type:text/html; charset:utf-8\n\n");

    // A newly opened stream has no orientation. The first call to any I/O function
    // establishes the orientation: a wide I/O function makes the stream wide-oriented,
    // a narrow I/O function makes the stream narrow-oriented. Once set, we must respect
    // this, so for the time being we are stuck with either printf() or wprintf().

    wprintf(L"%S\n", y);    // Conversion specifier %S is not standardized (!)
    wprintf(L"%ls\n", y);   // Conversion specifier %s with length modifier %l is 
                            // standardized (!)

    // At this point curent orientation of the stream is wide and this is why folowing
    // narrow function won't print anything! Whether we should use wprintf() or printf()
    // is primarily a question of how we want output to be encoded.

    printf("1\n");          // Print narrow string of characters with a narrow function
    printf("%s\n", "2");    // Print narrow string of characters with a narrow function
    printf("%ls\n",L"3");   // Print wide string of characters with a narrow function

    // Now we reset the stream to no orientation.
    freopen(NULL, "w", stdout);

    printf("4\n");          // Print narrow string of characters with a narrow function
    printf("%s\n", "5");    // Print narrow string of characters with a narrow function
    printf("%ls\n",L"6");   // Print wide string of characters with a narrow function

    return 0;
}

postgresql - sql - count of `true` values

probably, the best approach is to use nullif function.

in general

select
    count(nullif(myCol = false, true)),  -- count true values
    count(nullif(myCol = true, true)),   -- count false values
    count(myCol);

or in short

select
    count(nullif(myCol, true)),  -- count false values
    count(nullif(myCol, false)), -- count true values
    count(myCol);

http://www.postgresql.org/docs/9.0/static/functions-conditional.html

PowerShell Remoting giving "Access is Denied" error

Running the command prompt or Powershell ISE as an administrator fixed this for me.

Java JTable setting Column Width

Reading the remark of Kleopatra (her 2nd time she suggested to have a look at javax.swing.JXTable, and now I Am sorry I didn't have a look the first time :) ) I suggest you follow the link

I had this solution for the same problem: (but I suggest you follow the link above) On resize the table, scale the table column widths to the current table total width. to do this I use a global array of ints for the (relative) column widths):

private int[] columnWidths=null;

I use this function to set the table column widths:

public void setColumnWidths(int[] widths){
    int nrCols=table.getModel().getColumnCount();
    if(nrCols==0||widths==null){
        return;
    }
    this.columnWidths=widths.clone();

    //current width of the table:
    int totalWidth=table.getWidth();
    
    int totalWidthRequested=0;
    int nrRequestedWidths=columnWidths.length;
    int defaultWidth=(int)Math.floor((double)totalWidth/(double)nrCols);

    for(int col=0;col<nrCols;col++){
        int width = 0;
        if(columnWidths.length>col){
            width=columnWidths[col];
        }
        totalWidthRequested+=width;
    }
    //Note: for the not defined columns: use the defaultWidth
    if(nrRequestedWidths<nrCols){
        log.fine("Setting column widths: nr of columns do not match column widths requested");
        totalWidthRequested+=((nrCols-nrRequestedWidths)*defaultWidth);
    }
    //calculate the scale for the column width
    double factor=(double)totalWidth/(double)totalWidthRequested;

    for(int col=0;col<nrCols;col++){
        int width = defaultWidth;
        if(columnWidths.length>col){
            //scale the requested width to the current table width
            width=(int)Math.floor(factor*(double)columnWidths[col]);
        }
        table.getColumnModel().getColumn(col).setPreferredWidth(width);
        table.getColumnModel().getColumn(col).setWidth(width);
    }
    
}

When setting the data I call:

    setColumnWidths(this.columnWidths);

and on changing I call the ComponentListener set to the parent of the table (in my case the JScrollPane that is the container of my table):

public void componentResized(ComponentEvent componentEvent) {
    this.setColumnWidths(this.columnWidths);
}

note that the JTable table is also global:

private JTable table;

And here I set the listener:

    scrollPane=new JScrollPane(table);
    scrollPane.addComponentListener(this);

python JSON only get keys in first level

As Karthik mentioned, dct.keys() will work but it will return all the keys in dict_keys type not in list type. So if you want all the keys in a list, then list(dct.keys()) will work.

how to emulate "insert ignore" and "on duplicate key update" (sql merge) with postgresql?

For data import scripts, to replace "IF NOT EXISTS", in a way, there's a slightly awkward formulation that nevertheless works:

DO
$do$
BEGIN
PERFORM id
FROM whatever_table;

IF NOT FOUND THEN
-- INSERT stuff
END IF;
END
$do$;

Autocomplete syntax for HTML or PHP in Notepad++. Not auto-close, autocompelete

Go to:

Settings -> Preferences You will see a dialog box. There click the Backup / Auto-completion tab where you can set the auto complete option :)

Skip first entry in for loop in python?

The best way to skip the first item(s) is:

from itertools import islice
for car in islice(cars, 1, None):
    # do something

islice in this case is invoked with a start-point of 1, and an end point of None, signifying the end of the iterator.

To be able to skip items from the end of an iterable, you need to know its length (always possible for a list, but not necessarily for everything you can iterate on). for example, islice(cars, 1, len(cars)-1) will skip the first and last items in the cars list.

System.drawing namespace not found under console application

  1. Add using System.Drawing;
  2. Go to solution explorer and right click on references and select add reference
  3. Click on assemblies on the left
  4. search for system.drawing
  5. check system.drawing
  6. Click OK
  7. Done

Splitting on last delimiter in Python string?

I just did this for fun

    >>> s = 'a,b,c,d'
    >>> [item[::-1] for item in s[::-1].split(',', 1)][::-1]
    ['a,b,c', 'd']

Caution: Refer to the first comment in below where this answer can go wrong.

phpmyadmin "Not Found" after install on Apache, Ubuntu

It seems like sometime during the second half of 2018 many php packages such as php-mysql and phpmyadmin were removed or changed. I faced that same problem too. So you'll have to download it from another source or find out the new packages

How can I use grep to find a word inside a folder?

grep -nr string my_directory

Additional notes: this satisfies the syntax grep [options] string filename because in Unix-like systems, a directory is a kind of file (there is a term "regular file" to specifically refer to entities that are called just "files" in Windows).

grep -nr string reads the content to search from the standard input, that is why it just waits there for input from you, and stops doing so when you press ^C (it would stop on ^D as well, which is the key combination for end-of-file).

How to have multiple colors in a Windows batch file?

Combining dbenham's bird and syntax with skrebbel's powershell write-host method, it seems that powershell can render complex art more quickly than dbenham's pure batch method (well, after powershell has been primed once, anyway). Minimal massaging of the strings are needed, although I haven't tested this with anything other than the bird. If you want a bright green end-of-transmission character for example, you may be out of luck. :)

This method requires echoing out to a temp file, simply because invoking powershell for each call :c takes forever, and it's much faster to queue the output for one powershell invocation. But it does have the advantage of simplicity and efficiency.

@echo off
setlocal disableDelayedExpansion
set q=^"
echo(
echo(
call :c 0E "                ,      .-;" /n
call :c 0E "             ,  |\    / /  __," /n
call :c 0E "             |\ '.`-.|  |.'.-'" /n
call :c 0E "              \`'-:  `; : /" /n
call :c 0E "               `-._'.  \'|" /n
call :c 0E "              ,_.-=` ` `  ~,_" /n
call :c 0E "               '--,.    "&call :c 0c ".-. "&call :c 0E ",=!q!." /n
call :c 0E "                 /     "&call :c 0c "{ "&call :c 0A "* "&call :c 0c ")"&call :c 0E "`"&call :c 06 ";-."&call :c 0E "}" /n
call :c 0E "                 |      "&call :c 0c "'-' "&call :c 06 "/__ |" /n
call :c 0E "                 /          "&call :c 06 "\_,\|" /n
call :c 0E "                 |          (" /n
call :c 0E "             "&call :c 0c "__ "&call :c 0E "/ '          \" /n
call :c 02 "     /\_    "&call :c 0c "/,'`"&call :c 0E "|     '   "&call :c 0c ".-~!q!~~-." /n
call :c 02 "     |`.\_ "&call :c 0c "|   "&call :c 0E "/  ' ,    "&call :c 0c "/        \" /n
call :c 02 "   _/  `, \"&call :c 0c "|  "&call :c 0E "; ,     . "&call :c 0c "|  ,  '  . |" /n
call :c 02 "   \   `,  "&call :c 0c "|  "&call :c 0E "|  ,  ,   "&call :c 0c "|  :  ;  : |" /n
call :c 02 "   _\  `,  "&call :c 0c "\  "&call :c 0E "|.     ,  "&call :c 0c "|  |  |  | |" /n
call :c 02 "   \`  `.   "&call :c 0c "\ "&call :c 0E "|   '     "&call :c 0A "|"&call :c 0c "\_|-'|_,'\|" /n
call :c 02 "   _\   `,   "&call :c 0A "`"&call :c 0E "\  '  . ' "&call :c 0A "| |  | |  |           "&call :c 02 "__" /n
call :c 02 "   \     `,   "&call :c 0E "| ,  '    "&call :c 0A "|_/'-|_\_/     "&call :c 02 "__ ,-;` /" /n
call :c 02 "    \    `,    "&call :c 0E "\ .  , ' .| | | | |   "&call :c 02 "_/' ` _=`|" /n
call :c 02 "     `\    `,   "&call :c 0E "\     ,  | | | | |"&call :c 02 "_/'   .=!q!  /" /n
call :c 02 "     \`     `,   "&call :c 0E "`\      \/|,| ;"&call :c 02 "/'   .=!q!    |" /n
call :c 02 "      \      `,    "&call :c 0E "`\' ,  | ; "&call :c 02 "/'    =!q!    _/" /n
call :c 02 "       `\     `,  "&call :c 05 ".-!q!!q!-. "&call :c 0E "': "&call :c 02 "/'    =!q!     /" /n
call :c 02 "    jgs _`\    ;"&call :c 05 "_{  '   ; "&call :c 02 "/'    =!q!      /" /n
call :c 02 "       _\`-/__"&call :c 05 ".~  `."&call :c 07 "8"&call :c 05 ".'.!q!`~-. "&call :c 02 "=!q!     _,/" /n
call :c 02 "    __\      "&call :c 05 "{   '-."&call :c 07 "|"&call :c 05 ".'.--~'`}"&call :c 02 "    _/" /n
call :c 02 "    \    .=!q!` "&call :c 05 "}.-~!q!'"&call :c 0D "u"&call :c 05 "'-. '-..'  "&call :c 02 "__/" /n
call :c 02 "   _/  .!q!    "&call :c 05 "{  -'.~('-._,.'"&call :c 02 "\_,/" /n
call :c 02 "  /  .!q!    _/'"&call :c 05 "`--; ;  `.  ;" /n
call :c 02 "   .=!q!  _/'      "&call :c 05 "`-..__,-'" /n
call :c 02 "    __/'" /n

if exist "%temp%\color.psm1" (
    powershell -command "&{set-executionpolicy remotesigned; Import-Module '%temp%\color.psm1'}"
    del "%temp%\color.psm1"
)

echo(

exit /b

:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

:c <color pair> <string> </n>
setlocal enabledelayedexpansion
set "colors=0-black;1-darkblue;2-darkgreen;3-darkcyan;4-darkred;5-darkmagenta;6-darkyellow;7-gray;8-darkgray;9-blue;a-green;b-cyan;c-red;d-magenta;e-yellow;f-white"
set "p=%~1"
set "bg=!colors:*%p:~0,1%-=!"
set bg=%bg:;=&rem.%
set "fg=!colors:*%p:~-1%-=!"
set fg=%fg:;=&rem.%

if not "%~3"=="/n" set "br=-nonewline"
set "str=%~2" & set "str=!str:'=''!"

>>"%temp%\color.psm1" echo write-host '!str!' -foregroundcolor '%fg%' -backgroundcolor '%bg%' %br%
endlocal

Result:

enter image description here

Execution Failed for task :app:compileDebugJavaWithJavac in Android Studio

If all the above didn't work for you try removing cache from .gradle global folder

Try the following

rm -rf ~/.gradle/caches

react-native run-android

If didn't work, the below worked perfectly for me

rm -rf ~/.gradle

react-native run-android

Cross-Domain Cookies

Read Cookie in Web Api

var cookie = actionContext.Request.Headers.GetCookies("newhbsslv1");


                    Logger.Log("Cookie  " + cookie, LoggerLevel.Info);
                    Logger.Log("Cookie count  " + cookie.Count, LoggerLevel.Info);

                    if (cookie != null && cookie.Count > 0)
                    {
                        Logger.Log("Befor For  " , LoggerLevel.Info);
                        foreach (var perCookie in cookie[0].Cookies)
                        {
                            Logger.Log("perCookie  " + perCookie, LoggerLevel.Info);

                            if (perCookie.Name == "newhbsslv1")
                            {
                                strToken = perCookie.Value;
                            }
                        }
                    }

simple Jquery hover enlarge

To create simple hover enlarge plugin, try this. (DEMO)

HTML

     <div id="content">
     <img src="http://www.freevectorgallery.com/wp-content/uploads/2011/10/Vintage-Microphone- 11395-large.jpg" style="width:50%;" />
     </div>

js

        $(function () {
          $('#content img').hover(function () {
          $(this).toggle(function () {
          $(this).width('70%');
                   });
              });
         });

Injecting Mockito mocks into a Spring bean

I developed a solution based on the proposal of Kresimir Nesek. I added a new annotation @EnableMockedBean in order to make the code a bit cleaner and modular.

@EnableMockedBean
@SpringBootApplication
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes=MockedBeanTest.class)
public class MockedBeanTest {

    @MockedBean
    private HelloWorldService helloWorldService;

    @Autowired
    private MiddleComponent middleComponent;

    @Test
    public void helloWorldIsCalledOnlyOnce() {

        middleComponent.getHelloMessage();

        // THEN HelloWorldService is called only once
        verify(helloWorldService, times(1)).getHelloMessage();
    }

}

I have written a post explaining it.

How to sleep the thread in node.js without affecting other threads?

Please consider the deasync module, personally I don't like the Promise way to make all functions async, and keyword async/await anythere. And I think the official node.js should consider to expose the event loop API, this will solve the callback hell simply. Node.js is a framework not a language.

var node = require("deasync");
node.loop = node.runLoopOnce;

var done = 0;
// async call here
db.query("select * from ticket", (error, results, fields)=>{
    done = 1;
});

while (!done)
    node.loop();

// Now, here you go

psql - save results of command to a file

\copy which is a postgres command can work for any user. Don't know if it works for \dt or not, but general syntax is reproduced from the following link Postgres SQL copy syntax

\copy (select * from tempTable limit 100) to 'filenameinquotes' with header delimiter as ','

The above will save the output of the select query in the filename provided as a csv file

EDIT:

For my psql server the following command works this is an older version v8.5

copy (select * from table1) to 'full_path_filename' csv header;

How best to determine if an argument is not sent to the JavaScript function

In ES6 (ES2015) you can use Default parameters

_x000D_
_x000D_
function Test(arg1 = 'Hello', arg2 = 'World!'){_x000D_
  alert(arg1 + ' ' +arg2);_x000D_
}_x000D_
_x000D_
Test('Hello', 'World!'); // Hello World!_x000D_
Test('Hello'); // Hello World!_x000D_
Test(); // Hello World!
_x000D_
_x000D_
_x000D_

How to dynamically create CSS class in JavaScript and apply?

There is a light jQuery plugin which allows to generate CSS declarations: jQuery-injectCSS

In fact, it uses JSS (CSS described by JSON), but it's quite easy to handle in order to generate dynamic css stylesheets.

$.injectCSS({
    "#test": {
        height: 123
    }
});

Drawable-hdpi, Drawable-mdpi, Drawable-ldpi Android

To declare different layouts and bitmaps you'd like to use for the different screens, you must place these alternative resources in separate directories/folders.

This means that if you generate a 200x200 image for xhdpi devices, you should generate the same resource in 150x150 for hdpi, 100x100 for mdpi, and 75x75 for ldpi devices.

Then, place the files in the appropriate drawable resource directory:

MyProject/
    res/
        drawable-xhdpi/
            awesomeimage.png
        drawable-hdpi/
            awesomeimage.png
        drawable-mdpi/
            awesomeimage.png
        drawable-ldpi/
            awesomeimage.png

Any time you reference @drawable/awesomeimage, the system selects the appropriate bitmap based on the screen's density.

What is the best way to detect a mobile device?

To add an extra layer of control I use the HTML5 storage to detect if it is using mobile storage or desktop storage. If the browser does not support storage I have an array of mobile browser names and I compare the user agent with the browsers in the array.

It is pretty simple. Here is the function:

// Used to detect whether the users browser is an mobile browser
function isMobile() {
    ///<summary>Detecting whether the browser is a mobile browser or desktop browser</summary>
    ///<returns>A boolean value indicating whether the browser is a mobile browser or not</returns>

    if (sessionStorage.desktop) // desktop storage 
        return false;
    else if (localStorage.mobile) // mobile storage
        return true;

    // alternative
    mobile = ['iphone','ipad','android','blackberry','nokia','opera mini','windows mobile','windows phone','iemobile','tablet','mobi']; 
    var ua=navigator.userAgent.toLowerCase();
    for (var i in mobile) if (ua.indexOf(mobile[i]) > -1) return true;

    // nothing found.. assume desktop
    return false;
}

jQuery: Adding two attributes via the .attr(); method

the proper way is:

.attr({target:'nw', title:'Opens in a new window'})

Express.js - app.listen vs server.listen

Just for punctuality purpose and extend a bit Tim answer.
From official documentation:

The app returned by express() is in fact a JavaScript Function, DESIGNED TO BE PASSED to Node’s HTTP servers as a callback to handle requests.

This makes it easy to provide both HTTP and HTTPS versions of your app with the same code base, as the app does not inherit from these (it is simply a callback):

http.createServer(app).listen(80);
https.createServer(options, app).listen(443);

The app.listen() method returns an http.Server object and (for HTTP) is a convenience method for the following:

app.listen = function() {
  var server = http.createServer(this);
  return server.listen.apply(server, arguments);
};

Video auto play is not working in Safari and Chrome desktop browser

Chrome does not allow to auto play video with sound on, so make sure to add muted attribute to the video tag like this

<video width="320" height="240"  autoplay muted>
  <source src="video.mp4" type="video/mp4">
</video>

Drawing an image from a data URL to a canvas

function drawDataURIOnCanvas(strDataURI, canvas) {
    "use strict";
    var img = new window.Image();
    img.addEventListener("load", function () {
        canvas.getContext("2d").drawImage(img, 0, 0);
    });
    img.setAttribute("src", strDataURI);
}

jquery can't get data attribute value

Use plain javascript methods

$x10Device = this.dataset("x10");

Android - Package Name convention

Com = commercial application (just like .com, most people register their app as a com app)
First level = always the publishing entity's' name
Second level (optional) = sub-devison, group, or project name
Final level = product name

For example he android launcher (home screen) is Com.Google.android.launcher

MySQL 'create schema' and 'create database' - Is there any difference

Database is a collection of schemas and schema is a collection of tables. But in MySQL they use it the same way.

deleting folder from java

If you use Apache Commons IO it's a one-liner:

FileUtils.deleteDirectory(dir);

See FileUtils.deleteDirectory()


Guava used to support similar functionality:

Files.deleteRecursively(dir);

This has been removed from Guava several releases ago.


While the above version is very simple, it is also pretty dangerous, as it makes a lot of assumptions without telling you. So while it may be safe in most cases, I prefer the "official way" to do it (since Java 7):

public static void deleteFileOrFolder(final Path path) throws IOException {
  Files.walkFileTree(path, new SimpleFileVisitor<Path>(){
    @Override public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs)
      throws IOException {
      Files.delete(file);
      return CONTINUE;
    }

    @Override public FileVisitResult visitFileFailed(final Path file, final IOException e) {
      return handleException(e);
    }

    private FileVisitResult handleException(final IOException e) {
      e.printStackTrace(); // replace with more robust error handling
      return TERMINATE;
    }

    @Override public FileVisitResult postVisitDirectory(final Path dir, final IOException e)
      throws IOException {
      if(e!=null)return handleException(e);
      Files.delete(dir);
      return CONTINUE;
    }
  });
};

Setting PayPal return URL and making it auto return?

Sharing this as I've recently encountered issues similar to this thread

For a long time, my script worked well (basic payment form) and returned the POST variables to my success.php page and the IPN data as POST variables also. However, lately, I noticed the return page (success.php) was no longer receiving any POST vars. I tested in Sandbox and live and I'm pretty sure PayPal have changed something !

The notify_url still receives the correct IPN data allowing me to update DB, but I've not been able to display a success message on my return URL (success.php) page.

Despite trying many combinations to switch options on and off in PayPal website payment preferences and IPN, I've had to make some changes to my script to ensure I can still process a message. I've accomplished this by turning on PDT and Auto Return, after following this excellent guide.

Now it all works fine, but the only issue is the return URL contains all of the PDT variables which is ugly!

You may also find this helpful

Get Last Part of URL PHP

The absolute simplest way to accomplish this, is with basename()

echo basename('http://domain.com/artist/song/music-videos/song-title/9393903');

Which will print

9393903

Of course, if there is a query string at the end it will be included in the returned value, in which case the accepted answer is a better solution.

How to round up a number to nearest 10?

I wanted to round up to the next number in the largest digits place (is there a name for that?), so I made the following function (in php):

//Get the max value to use in a graph scale axis, 
//given the max value in the graph
function getMaxScale($maxVal) {
    $maxInt = ceil($maxVal);
    $numDigits = strlen((string)$maxInt)-1; //this makes 2150->3000 instead of 10000
    $dividend = pow(10,$numDigits);
    $maxScale= ceil($maxInt/ $dividend) * $dividend;
    return $maxScale;
}

What causes "Unable to access jarfile" error?

first I created a variable %JAVA_HOME% :

When you downloaded the file, make sure to check UNBLOCK TAB in file properties as shown above in "maartencls" post .

c:\users\my user\downloads\location of the file\all> java -jar yourfilename.jar

hope this will resolve the issue :)

Epoch vs Iteration when training neural networks

I guess in the context of neural network terminology:

  • Epoch: When your network ends up going over the entire training set (i.e., once for each training instance), it completes one epoch.

In order to define iteration (a.k.a steps), you first need to know about batch size:

  • Batch size: You probably wouldn't like to process the entire training instances all at one forward pass as it is inefficient and needs a huge deal of memory. So what is commonly done is splitting up training instances into subsets (i.e., batches), performing one pass over the selected subset (i.e., batch), and then optimizing the network through backpropagation. The number of training instances within a subset (i.e., batch) is called batch_size.

  • Iteration: (a.k.a training steps) You know that your network has to go over all training instances in one pass in order to complete one epoch. But wait! when you are splitting up your training instances into batches, that means you can only process one batch (a subset of training instances) in one forward pass, so what about the other batches? This is where the term Iteration comes into play:

  • Definition: The number of forward passes (The number of batches that you have created) that your network has to do in order to complete one epoch (i.e., going over all training instances) is called Iteration.

For example, when you have 10000 training instances and you want to do batching with size of 10; you have to do 10000/10 = 1000 iterations to complete 1 epoch.

Hope this could answer your question!

How to check if an array value exists?

You could use the PHP in_array function

if( in_array( "bla" ,$yourarray ) )
{
    echo "has bla";
}

Data at the root level is invalid

For the record:

"Data at the root level is invalid" means that you have attempted to parse something that is not an XML document. It doesn't even start to look like an XML document. It usually means just what you found: you're parsing something like the string "C:\inetpub\wwwroot\mysite\officelist.xml".

Sublime Text 2 Code Formatting

I can't speak for the 2nd or 3rd, but if you install Node first, Sublime-HTMLPrettify works pretty well. You have to setup your own key shortcut once it is installed. One thing I noticed on Windows, you may need to edit your path for Node in the %PATH% variable if it is already long (I think the limit is 1024 for the %PATH% variable, and anything after that is ignored.)

There is a Windows bug, but in the issues there is a fix for it. You'll need to edit the HTMLPrettify.py file - https://github.com/victorporof/Sublime-HTMLPrettify/issues/12

Get the decimal part from a double

It is very simple

       float moveWater =  Mathf.PingPong(theTime * speed, 100) * .015f;
       int    m = (int)(moveWater);
       float decimalPart= moveWater -m ;

       Debug.Log(decimalPart);

How to programmatically set the Image source

Use asp:image

<asp:Image id="Image1" runat="server"
           AlternateText="Image text"
           ImageAlign="left"
           ImageUrl="images/image1.jpg"/>

and codebehind to change image url

Image1.ImageUrl = "/MyProject;component/Images/down.png"; 

How do I add a simple jQuery script to WordPress?

I know what you mean about the tutorials. Here's how I do it:

First you need to write your script. In your theme folder create a folder called something like 'js'. Create a file in that folder for your javascript. E.g. your-script.js. Add your jQuery script to that file (you don't need <script> tags in a .js file).

Here is an example of how your jQuery script (in wp-content/themes/your-theme/js/your-scrript.js) might look:

jQuery(document).ready(function($) {
  $('#nav a').last().addClass('last');
})

Notice that I use jQuery and not $ at the start of the function.

Ok, now open your theme's functions.php file. You'll want to use the wp_enqueue_script() function so that you can add your script whilst also telling WordPress that it relies on jQuery. Here's how to do that:

add_action( 'wp_enqueue_scripts', 'add_my_script' );
function add_my_script() {
    wp_enqueue_script(
        'your-script', // name your script so that you can attach other scripts and de-register, etc.
        get_template_directory_uri() . '/js/your-script.js', // this is the location of your script file
        array('jquery') // this array lists the scripts upon which your script depends
    );
}

Assuming that your theme has wp_head and wp_footer in the right places, this should work. Let me know if you need any more help.

WordPress questions can be asked over at WordPress Answers.

What's the difference between using CGFloat and float?

CGFloat is a regular float on 32-bit systems and a double on 64-bit systems

typedef float CGFloat;// 32-bit
typedef double CGFloat;// 64-bit

So you won't get any performance penalty.

How to allow remote access to my WAMP server for Mobile(Android)

I assume you are using windows. Open the command prompt and type ipconfig and find out your local address (on your pc) it should look something like 192.168.1.13 or 192.168.0.5 where the end digit is the one that changes. It should be next to IPv4 Address.

If your WAMP does not use virtual hosts the next step is to enter that IP address on your phones browser ie http://192.168.1.13 If you have a virtual host then you will need root to edit the hosts file.

If you want to test the responsiveness / mobile design of your website you can change your user agent in chrome or other browsers to mimic a mobile.

See http://googlesystem.blogspot.co.uk/2011/12/changing-user-agent-new-google-chrome.html.

Edit: Chrome dev tools now has a mobile debug tool where you can change the size of the viewport, spoof user agents, connections (4G, 3G etc).

If you get forbidden access then see this question WAMP error: Forbidden You don't have permission to access /phpmyadmin/ on this server. Basically, change the occurrances of deny,allow to allow,deny in the httpd.conf file. You can access this by the WAMP menu.

To eliminate possible causes of the issue for now set your config file to

<Directory />
    Options FollowSymLinks
    AllowOverride All
    Order allow,deny
    Allow from all
    <RequireAll>
        Require all granted
    </RequireAll>
</Directory>

As thatis working for my windows PC, if you have the directory config block as well change that also to allow all.

Config file that fixed the problem:

https://gist.github.com/samvaughton/6790739

Problem was that the /www apache directory config block still had deny set as default and only allowed from localhost.

TypeError: string indices must be integers, not str // working with dict

Actually I think that more general approach to loop through dictionary is to use iteritems():

# get tuples of term, courses
for term, term_courses in courses.iteritems():
    # get tuples of course number, info
    for course, info in term_courses.iteritems():
        # loop through info
        for k, v in info.iteritems():
            print k, v

output:

assistant Peter C.
prereq cs101
...
name Programming a Robotic Car
teacher Sebastian

Or, as Matthias mentioned in comments, if you don't need keys, you can just use itervalues():

for term_courses in courses.itervalues():
    for info in term_courses.itervalues():
        for k, v in info.iteritems():
            print k, v

CSS Selector that applies to elements with two classes

Chain both class selectors (without a space in between):

.foo.bar {
    /* Styles for element(s) with foo AND bar classes */
}

If you still have to deal with ancient browsers like IE6, be aware that it doesn't read chained class selectors correctly: it'll only read the last class selector (.bar in this case) instead, regardless of what other classes you list.

To illustrate how other browsers and IE6 interpret this, consider this CSS:

* {
    color: black;
}

.foo.bar {
    color: red;
}

Output on supported browsers is:

<div class="foo">Hello Foo</div>       <!-- Not selected, black text [1] -->
<div class="foo bar">Hello World</div> <!-- Selected, red text [2] -->
<div class="bar">Hello Bar</div>       <!-- Not selected, black text [3] -->

Output on IE6 is:

<div class="foo">Hello Foo</div>       <!-- Not selected, black text [1] -->
<div class="foo bar">Hello World</div> <!-- Selected, red text [2] -->
<div class="bar">Hello Bar</div>       <!-- Selected, red text [2] -->

Footnotes:

  • Supported browsers:
    1. Not selected as this element only has class foo.
    2. Selected as this element has both classes foo and bar.
    3. Not selected as this element only has class bar.

  • IE6:
    1. Not selected as this element doesn't have class bar.
    2. Selected as this element has class bar, regardless of any other classes listed.

How to store an output of shell script to a variable in Unix?

You need to start the script with a preceding dot, this will put the exported variables in the current environment.

#!/bin/bash
...
export output="SUCCESS"

Then execute it like so

chmod +x /tmp/test.sh
. /tmp/test.sh

When you need the entire output and not just a single value, just put the output in a variable like the other answers indicate

Single-threaded apartment - cannot instantiate ActiveX control

If you used [STAThread] to the main entry of your application and still get the error you may need to make a Thread-Safe call to the control... something like below. In my case with the same problem the following solution worked!

Private void YourFunc(..)
{
    if (this.InvokeRequired)
    {
        Invoke(new MethodInvoker(delegate()
        {
           // Call your method YourFunc(..);
        }));
    }
    else
    {
        ///
    }

memcpy() vs memmove()

Just because memcpy doesn't have to deal with overlapping regions, doesn't mean it doesn't deal with them correctly. The call with overlapping regions produces undefined behavior. Undefined behavior can work entirely as you expect on one platform; that doesn't mean it's correct or valid.

Override valueof() and toString() in Java enum

How about a Java 8 implementation? (null can be replaced by your default Enum)

public static RandomEnum getEnum(String value) {
    return Arrays.stream(RandomEnum.values()).filter(m -> m.value.equals(value)).findAny().orElse(null);
}

Or you could use:

...findAny().orElseThrow(NotFoundException::new);

C++ multiline string literal

Option 1. Using boost library, you can declare the string as below

const boost::string_view helpText = "This is very long help text.\n"
      "Also more text is here\n"
      "And here\n"

// Pass help text here
setHelpText(helpText);

Option 2. If boost is not available in your project, you can use std::string_view() in modern C++.

Matplotlib different size subplots

You can use gridspec and figure:

import numpy as np
import matplotlib.pyplot as plt 
from matplotlib import gridspec

# generate some data
x = np.arange(0, 10, 0.2)
y = np.sin(x)

# plot it
fig = plt.figure(figsize=(8, 6)) 
gs = gridspec.GridSpec(1, 2, width_ratios=[3, 1]) 
ax0 = plt.subplot(gs[0])
ax0.plot(x, y)
ax1 = plt.subplot(gs[1])
ax1.plot(y, x)

plt.tight_layout()
plt.savefig('grid_figure.pdf')

resulting plot

Vertical line using XML drawable

You can use a shape but instead of a line make it rectangle.

android:shape="rectangle">
<stroke
    android:width="5dp"
    android:color="#ff000000"
    android:dashGap="10px"
    android:dashWidth="30px" />

and In your layout use this...

<ImageView
    android:layout_width="7dp"
    android:layout_height="match_parent"
    android:src="@drawable/dashline"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layerType="software"/>

You might have to play with the width, depending on the size of the dashes, to get it into a single line.

Hope this helps Cheers

How to delete all files and folders in a directory?

using System.IO;

string[] filePaths = Directory.GetFiles(@"c:\MyDir\");

foreach (string filePath in filePaths)

File.Delete(filePath);

Setting a windows batch file variable to the day of the week

@ECHO OFF
REM GET DAY OF WEEK VIA DATE TO JULIAN DAY NUMBER CONVERSION
REM ANTONIO PEREZ AYALA
REM GET MONTH, DAY, YEAR VALUES AND ELIMINATE LEFT ZEROS
FOR /F "TOKENS=1-3 DELIMS=/" %%A IN ("%DATE%") DO SET /A MM=10%%A %% 100, DD=10%%B %% 100, YY=%%C
REM CALCULATE JULIAN DAY NUMBER, THEN DAY OF WEEK
IF %MM% LSS 3 SET /A MM+=12, YY-=1
SET /A A=YY/100, B=A/4, C=2-A+B, E=36525*(YY+4716)/100, F=306*(MM+1)/10, JDN=C+DD+E+F-1524
SET /A DOW=(JDN+1)%%7

DOW is 0 for Sunday, 1 for Monday, etc.

Why is quicksort better than mergesort?

All things being equal, I'd expect most people to use whatever is most conveniently available, and that tends to be qsort(3). Other than that quicksort is known to be very fast on arrays, just like mergesort is the common choice for lists.

What I'm wondering is why it's so rare to see radix or bucket sort. They're O(n), at least on linked lists and all it takes is some method of converting the key to an ordinal number. (strings and floats work just fine.)

I'm thinking the reason has to do with how computer science is taught. I even had to demonstrate to my lecturer in Algorithm analysis that it was indeed possible to sort faster than O(n log(n)). (He had the proof that you can't comparison sort faster than O(n log(n)), which is true.)

In other news, floats can be sorted as integers, but you have to turn the negative numbers around afterwards.

Edit: Actually, here's an even more vicious way to sort floats-as-integers: http://www.stereopsis.com/radix.html. Note that the bit-flipping trick can be used regardless of what sorting algorithm you actually use...

Tomcat is not running even though JAVA_HOME path is correct

Remove the 'bin' from JAVA_HOME. That solves the issue.

What is thread Safe in java?

Thread safe simply means that it may be used from multiple threads at the same time without causing problems. This can mean that access to any resources are synchronized, or whatever.

How to continue the code on the next line in VBA

In VBA (and VB.NET) the line terminator (carriage return) is used to signal the end of a statement. To break long statements into several lines, you need to

Use the line-continuation character, which is an underscore (_), at the point at which you want the line to break. The underscore must be immediately preceded by a space and immediately followed by a line terminator (carriage return).

(From How to: Break and Combine Statements in Code)

In other words: Whenever the interpreter encounters the sequence <space>_<line terminator>, it is ignored and parsing continues on the next line. Note, that even when ignored, the line continuation still acts as a token separator, so it cannot be used in the middle of a variable name, for example. You also cannot continue a comment by using a line-continuation character.

To break the statement in your question into several lines you could do the following:

U_matrix(i, j, n + 1) = _
     k * b_xyt(xi, yi, tn) / (4 * hx * hy) * U_matrix(i + 1, j + 1, n) + _
     (k * (a_xyt(xi, yi, tn) / hx ^ 2 + d_xyt(xi, yi, tn) / (2 * hx)))

(Leading whitespaces are ignored.)

A simple explanation of Naive Bayes Classification

Naive Bayes: Naive Bayes comes under supervising machine learning which used to make classifications of data sets. It is used to predict things based on its prior knowledge and independence assumptions.

They call it naive because it’s assumptions (it assumes that all of the features in the dataset are equally important and independent) are really optimistic and rarely true in most real-world applications.

It is classification algorithm which makes the decision for the unknown data set. It is based on Bayes Theorem which describe the probability of an event based on its prior knowledge.

Below diagram shows how naive Bayes works

enter image description here

Formula to predict NB:

enter image description here

How to use Naive Bayes Algorithm ?

Let's take an example of how N.B woks

Step 1: First we find out Likelihood of table which shows the probability of yes or no in below diagram. Step 2: Find the posterior probability of each class.

enter image description here

Problem: Find out the possibility of whether the player plays in Rainy condition?

P(Yes|Rainy) = P(Rainy|Yes) * P(Yes) / P(Rainy)

P(Rainy|Yes) = 2/9 = 0.222
P(Yes) = 9/14 = 0.64
P(Rainy) = 5/14 = 0.36

Now, P(Yes|Rainy) = 0.222*0.64/0.36 = 0.39 which is lower probability which means chances of the match played is low.

For more reference refer these blog.

Refer GitHub Repository Naive-Bayes-Examples

ALTER TABLE DROP COLUMN failed because one or more objects access this column

I had the same problem and this was the script that worked for me with a table with a two part name separated by a period ".".

USE [DATABASENAME] GO ALTER TABLE [TableNamePart1].[TableNamePart2] DROP CONSTRAINT [DF__ TableNamePart1D__ColumnName__5AEE82B9] GO ALTER TABLE [TableNamePart1].[ TableNamePart1] DROP COLUMN [ColumnName] GO

How to return JSON with ASP.NET & jQuery

Try to use this , it works perfectly for me

  // 

   varb = new List<object>();

 // Example 

   varb.Add(new[] { float.Parse(GridView1.Rows[1].Cells[2].Text )});

 // JSON  + Serializ

public string Json()
        {  
            return (new JavaScriptSerializer()).Serialize(varb);
        }


//  Jquery SIDE 

  var datasets = {
            "Products": {
                label: "Products",
                data: <%= getJson() %> 
            }

Press TAB and then ENTER key in Selenium WebDriver

WebElement webElement = driver.findElement(By.xpath(""));

//Enter the xpath or ID.

     webElement.sendKeys("");

//Input the string to pass.

     webElement.sendKeys(Keys.TAB);

//This will enter the string which you want to pass and will press "Tab" button .

Compiling an application for use in highly radioactive environments

Use a cyclic scheduler. This gives you the ability to add regular maintenance times to check the correctness of critical data. The problem most often encountered is corruption of the stack. If your software is cyclical you can reinitialise the stack between cycles. Do not reuse the stacks for interrupt calls, setup a separate stack of each important interrupt call.

Similar to the Watchdog concept is deadline timers. Start a hardware timer before calling a function. If the function does not return before the deadline timer interrupts then reload the stack and try again. If it still fails after 3/5 tries you need reload from ROM.

Split your software into parts and isolate these parts to use separate memory areas and execution times (Especially in a control environment). Example: signal acquisition, prepossessing data, main algorithm and result implementation/transmission. This means a failure in one part will not cause failures through the rest of the program. So while we are repairing the signal acquisition the rest of tasks continues on stale data.

Everything needs CRCs. If you execute out of RAM even your .text needs a CRC. Check the CRCs regularly if you using a cyclical scheduler. Some compilers (not GCC) can generate CRCs for each section and some processors have dedicated hardware to do CRC calculations, but I guess that would fall out side of the scope of your question. Checking CRCs also prompts the ECC controller on the memory to repair single bit errors before it becomes a problem.

Printing chars and their ASCII-code in C

This prints out all ASCII values:

int main()
{
    int i;
    i=0;
    do
    {
        printf("%d %c \n",i,i);
        i++;
    }
    while(i<=255);
    return 0;
}

and this prints out the ASCII value for a given character:

int main()
{
    int e;
    char ch;
    clrscr();
    printf("\n Enter a character : ");
    scanf("%c",&ch);
    e=ch;
    printf("\n The ASCII value of the character is : %d",e);
    getch();
    return 0;
}

How do I check if an element is really visible with JavaScript?

Prototype's Element library is one of the most powerful query libraries in terms of the methods. I recommend you to check out the API.

A few hints:

  1. Checking visibility can be a pain, but you can use the Element.getStyle() method and Element.visible() methods combined into a custom function. With getStyle() you can check the actual computed style.

  2. I don't know exactly what you mean by "underneath" :) If you meant by it has a specific ancestor, for example, a wrapper div, you can use Element.up(cssRule):

    var child = $("myparagraph");
    if(!child.up("mywrapper")){
      // I lost my mom!
    }
    else {
      // I found my mom!
    }
    

    If you want to check the siblings of the child element you can do that too:

    var child = $("myparagraph");
    if(!child.previous("mywrapper")){
      // I lost my bro!
    } 
    else {
      // I found my bro!
    }
    
  3. Again, Element lib can help you if I understand correctly what you mean :) You can check the actual dimensions of the viewport and the offset of your element so you can calculate if your element is "off screen".

Good luck!

I pasted a test case for prototypejs at http://gist.github.com/117125. It seems in your case we simply cannot trust in getStyle() at all. For maximizing the reliability of the isMyElementReallyVisible function you should combine the following:

  • Checking the computed style (dojo has a nice implementation that you can borrow)
  • Checking the viewportoffset (prototype native method)
  • Checking the z-index for the "beneath" problem (under Internet Explorer it may be buggy)

Avoid browser popup blockers

The general rule is that popup blockers will engage if window.open or similar is invoked from javascript that is not invoked by direct user action. That is, you can call window.open in response to a button click without getting hit by the popup blocker, but if you put the same code in a timer event it will be blocked. Depth of call chain is also a factor - some older browsers only look at the immediate caller, newer browsers can backtrack a little to see if the caller's caller was a mouse click etc. Keep it as shallow as you can to avoid the popup blockers.

WooCommerce - get category for product page

Thanks Box. I'm using MyStile Theme and I needed to display the product category name in my search result page. I added this function to my child theme functions.php

Hope it helps others.

/* Post Meta */


if (!function_exists( 'woo_post_meta')) {
    function woo_post_meta( ) {
        global $woo_options;
        global $post;

        $terms = get_the_terms( $post->ID, 'product_cat' );
        foreach ($terms as $term) {
            $product_cat = $term->name;
            break;
        }

?>
<aside class="post-meta">
    <ul>
        <li class="post-category">
            <?php the_category( ', ', $post->ID) ?>
                        <?php echo $product_cat; ?>

        </li>
        <?php the_tags( '<li class="tags">', ', ', '</li>' ); ?>
        <?php if ( isset( $woo_options['woo_post_content'] ) && $woo_options['woo_post_content'] == 'excerpt' ) { ?>
            <li class="comments"><?php comments_popup_link( __( 'Leave a comment', 'woothemes' ), __( '1 Comment', 'woothemes' ), __( '% Comments', 'woothemes' ) ); ?></li>
        <?php } ?>
        <?php edit_post_link( __( 'Edit', 'woothemes' ), '<li class="edit">', '</li>' ); ?>
    </ul>
</aside>
<?php
    }
}


?>

How do I get the file extension of a file in Java?

This is a tested method

public static String getExtension(String fileName) {
    char ch;
    int len;
    if(fileName==null || 
            (len = fileName.length())==0 || 
            (ch = fileName.charAt(len-1))=='/' || ch=='\\' || //in the case of a directory
             ch=='.' ) //in the case of . or ..
        return "";
    int dotInd = fileName.lastIndexOf('.'),
        sepInd = Math.max(fileName.lastIndexOf('/'), fileName.lastIndexOf('\\'));
    if( dotInd<=sepInd )
        return "";
    else
        return fileName.substring(dotInd+1).toLowerCase();
}

And test case:

@Test
public void testGetExtension() {
    assertEquals("", getExtension("C"));
    assertEquals("ext", getExtension("C.ext"));
    assertEquals("ext", getExtension("A/B/C.ext"));
    assertEquals("", getExtension("A/B/C.ext/"));
    assertEquals("", getExtension("A/B/C.ext/.."));
    assertEquals("bin", getExtension("A/B/C.bin"));
    assertEquals("hidden", getExtension(".hidden"));
    assertEquals("dsstore", getExtension("/user/home/.dsstore"));
    assertEquals("", getExtension(".strange."));
    assertEquals("3", getExtension("1.2.3"));
    assertEquals("exe", getExtension("C:\\Program Files (x86)\\java\\bin\\javaw.exe"));
}

Abort Ajax requests using jQuery

If xhr.abort(); causes page reload,

Then you can set onreadystatechange before abort to prevent:

// ? prevent page reload by abort()
xhr.onreadystatechange = null;
// ? may cause page reload
xhr.abort();

Convert int to string?

None of the answers mentioned that the ToString() method can be applied to integer expressions

Debug.Assert((1000*1000).ToString()=="1000000");

even to integer literals

Debug.Assert(256.ToString("X")=="100");

Although integer literals like this are often considered to be bad coding style (magic numbers) there may be cases where this feature is useful...

How to convert a PNG image to a SVG?

potrace does not support PNG as input file, but PNM.
Therefore, first convert from PNG to PNM:

convert file.png file.pnm        # PNG to PNM
potrace file.pnm -s -o file.svg  # PNM to SVG

Explain options

  • potrace -s => Output file is SVG
  • potrace -o file.svg => Write output to file.svg

Example

Input file = 2017.png Input file

convert 2017.png 2017.pnm

Temporary file = 2017.pnm

potrace 2017.pnm -s -o 2017.svg

Output file = 2017.svg Output file

Script

ykarikos proposes a script png2svg.sh that I have improved:

#!/bin/bash

File_png="${1?:Usage: $0 file.png}"

if [[ ! -s "$File_png" ]]; then
  echo >&2 "The first argument ($File_png)"
  echo >&2 "must be a file having a size greater than zero"
  ( set -x ; ls -s "$File_png" )
  exit 1
fi

File="${File_png%.*}"

convert "$File_png" "$File.pnm"        # PNG to PNM
potrace "$File.pnm" -s -o "$File.svg"  # PNM to SVG
rm "$File.pnm"                         # Remove PNM

One-line command

If you want to convert many files, you can also use the following one-line command:

( set -x ; for f_png in *.png ; do f="${f_png%.png}" ; convert "$f_png" "$f.pnm" && potrace "$f.pnm" -s -o "$f.svg" ; done )

See also

See also this good comparison of raster to vector converters on Wikipedia.

What should be the sizeof(int) on a 64-bit machine?

Not really. for backward compatibility it is 32 bits.
If you want 64 bits you have long, size_t or int64_t

Call static method with reflection

As the documentation for MethodInfo.Invoke states, the first argument is ignored for static methods so you can just pass null.

foreach (var tempClass in macroClasses)
{
   // using reflection I will be able to run the method as:
   tempClass.GetMethod("Run").Invoke(null, null);
}

As the comment points out, you may want to ensure the method is static when calling GetMethod:

tempClass.GetMethod("Run", BindingFlags.Public | BindingFlags.Static).Invoke(null, null);

NULL vs nullptr (Why was it replaced?)

One reason: the literal 0 has a bad tendency to acquire the type int, e.g. in perfect argument forwarding or more in general as argument with templated type.

Another reason: readability and clarity of code.

Tomcat startup logs - SEVERE: Error filterStart how to get a stack trace?

I too got the same error and struggled a lot in fixing this issue. Spent quiet a bit time in searching Google and found the following solution and my issue got resolved.

the issue was due to, missing Struts2 Libraries in the deployment path. Most of the folks may put the libraries for compilation and tend to forget to attach required libraries for run-time. So I added the same libraries in the web deployment assembly, and the issue was OFF.

Downloading folders from aws s3, cp or sync?

You've many options to do that, but the best one is using the AWS CLI.

Here's a walk-through:

  1. Download and install AWS CLI in your machine:

  2. Configure AWS CLI:

enter image description here

Make sure you input valid access and secret keys, which you received when you created the account.

  1. Sync the S3 bucket using:

     aws s3 sync s3://yourbucket/yourfolder /local/path
    

In the above command, replace the following fields:

  • yourbucket/yourfolder >> your S3 bucket and the folder that you want to download.
  • /local/path >> path in your local system where you want to download all the files.

Right HTTP status code to wrong input

According to the below scenario ,

Let's say that someone makes a request to your server with data that is in the correct format, but is simply not "good" data. So for example, imagine that someone posted a String value to an API endpoint that expected a String value; but, the value of the string contained data that was blacklisted (ex. preventing people from using "password" as their password). then the status code could be either 400 or 422 ?

Until now, I would have returned a "400 Bad Request", which, according to the w3.org, means:

The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.

This description doesn't quite fit the circumstance; but, if you go by the list of core HTTP status codes defined in the HTTP/1.1 protocol, it's probably your best bet.

Recently, however, Someone from my Dev team pointed out [to me] that popular APIs are starting to use HTTP extensions to get more granular with their error reporting. Specifically, many APIs, like Twitter and Recurly, are using the status code "422 Unprocessable Entity" as defined in the HTTP extension for WebDAV. HTTP status code 422 states:

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.

Going back to our password example from above, this 422 status code feels much more appropriate. The server understands what you're trying to do; and it understands the data that you're submitting; it simply won't let that data be processed.

Android splash screen image sizes to fit all devices

PORTRAIT

LDPI: 200x320px

MDPI: 320x480px

HDPI: 480x800px

XHDPI: 720px1280px

LANDSCAPE

LDPI: 320x200px

MDPI: 480x320px

HDPI: 800x480px

XHDPI: 1280x720px

How do you push a Git tag to a branch using a refspec?

I create the tag like this and then I push it to GitHub:

git tag -a v1.1 -m "Version 1.1 is waiting for review"
git push --tags

Counting objects: 1, done.
Writing objects: 100% (1/1), 180 bytes, done.
Total 1 (delta 0), reused 0 (delta 0)
To [email protected]:neoneye/triangle_draw.git
 * [new tag]         v1.1 -> v1.1

Class Diagrams in VS 2017

  1. Open Visual Studio Installer from the Windows Start menu, or by selecting Tools > Get Tools and Features from the menu bar in Visual Studio.

    Visual Studio Installer opens.

  2. Select the Individual components tab, and then scroll down to the Code tools category.

  3. Select Class Designer and then select Modify.

Visual Studio Installer Window

The Class Designer component starts installing.

For more details, visit this link: How to: Add class diagrams to projects

Create PDF with Java

I prefer outputting my data into XML (using Castor, XStream or JAXB), then transforming it using a XSLT stylesheet into XSL-FO and render that with Apache FOP into PDF. Worked so far for 10-page reports and 400-page manuals. I found this more flexible and stylable than generating PDFs in code using iText.

Pandas: drop a level from a multi-level column index?

As of Pandas 0.24.0, we can now use DataFrame.droplevel():

cols = pd.MultiIndex.from_tuples([("a", "b"), ("a", "c")])
df = pd.DataFrame([[1,2], [3,4]], columns=cols)

df.droplevel(0, axis=1) 

#   b  c
#0  1  2
#1  3  4

This is very useful if you want to keep your DataFrame method-chain rolling.

How to semantically add heading to a list

According to w3.org (note that this link is in the long-expired draft HTML 3.0 spec):

An unordered list typically is a bulleted list of items. HTML 3.0 gives you the ability to customise the bullets, to do without bullets and to wrap list items horizontally or vertically for multicolumn lists.

The opening list tag must be <UL>. It is followed by an optional list header (<LH>caption</LH>) and then by the first list item (<LI>). For example:

<UL>
  <LH>Table Fruit</LH>
  <LI>apples
  <LI>oranges
  <LI>bananas
</UL>

which could be rendered as:

Table Fruit

  • apples
  • oranges
  • bananas

Note: Some legacy documents may include headers or plain text before the first LI element. Implementors of HTML 3.0 user agents are advised to cater for this possibility in order to handle badly formed legacy documents.

Abstract methods in Java

The error message tells the exact reason: "abstract methods cannot have a body".

They can only be defined in abstract classes and interfaces (interface methods are implicitly abstract!) and the idea is, that the subclass implements the method.

Example:

 public abstract class AbstractGreeter {
   public abstract String getHelloMessage();

   public void sayHello() {
     System.out.println(getHelloMessage());
   }
 }

 public class FrenchGreeter extends AbstractGreeter{

   // we must implement the abstract method
   @Override
   public String getHelloMessage() {
     return "bonjour";
   }
 }

How to check if PHP array is associative or sequential?

Modification on the most popular answer.
This takes a little more processing, but is more accurate.

<?php
//$a is a subset of $b
function isSubset($a, $b)
{
    foreach($a =>$v)
        if(array_search($v, $b) === false)
            return false;

    return true;

    //less effecient, clearer implementation. (uses === for comparison)
    //return array_intersect($a, $b) === $a;
}

function isAssoc($arr)
{
    return !isSubset(array_keys($arr), range(0, count($arr) - 1));
}

var_dump(isAssoc(array('a', 'b', 'c'))); // false
var_dump(isAssoc(array(1 => 'a', 0 => 'b', 2 => 'c'))); // false
var_dump(isAssoc(array("0" => 'a', "1" => 'b', "2" => 'c'))); // false 
//(use === in isSubset to get 'true' for above statement)
var_dump(isAssoc(array("a" => 'a', "b" => 'b', "c" => 'c'))); // true
?>

How do I compile the asm generated by GCC?

You can embed the assembly code in a normal C program. Here's a good introduction. Using the appropriate syntax, you can also tell GCC you want to interact with variables declared in C. The program below instructs gcc that:

  • eax shall be foo
  • ebx shall be bar
  • the value in eax shall be stored in foo after the assembly code executed

\n

int main(void)
{
        int foo = 10, bar = 15;
        __asm__ __volatile__("addl  %%ebx,%%eax"
                             :"=a"(foo)
                             :"a"(foo), "b"(bar)
                             );
        printf("foo+bar=%d\n", foo);
        return 0;
}

How to display hidden characters by default (ZERO WIDTH SPACE ie. &#8203)

Not sure what you meant, but you can permanently turn showing whitespaces on and off in Settings -> Editor -> General -> Appearance -> Show whitespaces.

Also, you can set it for a current file only in View -> Active Editor -> Show WhiteSpaces.

Edit:

Had some free time since it looks like a popular issue, I had written a plugin to inspect the code for such abnormalities. It is called Zero Width Characters locator and you're welcome to give it a try.

Javascript Cookie with no expiration date

You can make a cookie never end by setting it to whatever date plus one more than the current year like this :

var d = new Date();    
document.cookie = "username=John Doe; expires=Thu, 18 Dec " + (d.getFullYear() + 1) + " 12:00:00 UTC";

"git checkout <commit id>" is changing branch to "no branch"

This worked best for me when I wanted to check out the code, given the commit ID <commit_id_SHA1>

git fetch origin <commit_id_SHA1>
git checkout -b new_branch FETCH_HEAD

How do I create a comma-separated list from an array in PHP?

A functional solution would go like this:

$fruit = array('apple', 'banana', 'pear', 'grape');
$sep = ','; 

array_reduce(
    $fruits,
    function($fruitsStr, $fruit) use ($sep) {
        return (('' == $fruitsStr) ? $fruit : $fruitsStr . $sep . $fruit);
    },
    ''
);

How to get option text value using AngularJS?

Also you can do like this:

<select class="form-control postType" ng-model="selectedProd">
    <option ng-repeat="product in productList" value="{{product}}">{{product.name}}</option>
</select>

where "selectedProd" will be selected product.

Permission denied error on Github Push

In could able to resolve this issue with giving username and password in below url.

Please replace username and password with your Github credentials:

git remote set-url origin https://<username>:<password>@github.com/<username>/FirstRepository.git

What's the simplest way to extend a numpy array in 2 dimensions?

Another elegant solution to the first question may be the insert command:

p = np.array([[1,2],[3,4]])
p = np.insert(p, 2, values=0, axis=1) # insert values before column 2

Leads to:

array([[1, 2, 0],
       [3, 4, 0]])

insert may be slower than append but allows you to fill the whole row/column with one value easily.

As for the second question, delete has been suggested before:

p = np.delete(p, 2, axis=1)

Which restores the original array again:

array([[1, 2],
       [3, 4]])

Are arrays in PHP copied as value or as reference to new variables, and when passed to functions?

This thread is a bit older but here something I just came across:

Try this code:

$date = new DateTime();
$arr = ['date' => $date];

echo $date->format('Ymd') . '<br>';
mytest($arr);
echo $date->format('Ymd') . '<br>';

function mytest($params = []) {
    if (isset($params['date'])) {
        $params['date']->add(new DateInterval('P1D'));
    }
}

http://codepad.viper-7.com/gwPYMw

Note there is no amp for the $params parameter and still it changes the value of $arr['date']. This doesn't really match with all the other explanations here and what I thought until now.

If I clone the $params['date'] object, the 2nd outputted date stays the same. If I just set it to a string it doesn't effect the output either.

What is the purpose of the "final" keyword in C++11 for functions?

  • It is to prevent a class from being inherited. From Wikipedia:

    C++11 also adds the ability to prevent inheriting from classes or simply preventing overriding methods in derived classes. This is done with the special identifier final. For example:

    struct Base1 final { };
    
    struct Derived1 : Base1 { }; // ill-formed because the class Base1 
                                 // has been marked final
    
  • It is also used to mark a virtual function so as to prevent it from being overridden in the derived classes:

    struct Base2 {
        virtual void f() final;
    };
    
    struct Derived2 : Base2 {
        void f(); // ill-formed because the virtual function Base2::f has 
                  // been marked final
    };
    

Wikipedia further makes an interesting point:

Note that neither override nor final are language keywords. They are technically identifiers; they only gain special meaning when used in those specific contexts. In any other location, they can be valid identifiers.

That means, the following is allowed:

int const final = 0;     // ok
int const override = 1;  // ok

Javascript loop through object array?

Iterations

Method 1: forEach method

messages.forEach(function(message) {
   console.log(message);
}

Method 2: for..of method

for(let message of messages){
   console.log(message);
}

Note: This method might not work with objects, such as:

let obj = { a: 'foo', b: { c: 'bar', d: 'daz' }, e: 'qux' }

Method 2: for..in method

for(let key in messages){
       console.log(messages[key]);
 }

How to check if a line is blank using regex

Here Blank mean what you are meaning.
A line contains full of whitespaces or a line contains nothing.
If you want to match a line which contains nothing then use '/^$/'.

Basic example for sharing text or image with UIActivityViewController in Swift

Share : Text

@IBAction func shareOnlyText(_ sender: UIButton) {
    let text = "This is the text....."
    let textShare = [ text ]
    let activityViewController = UIActivityViewController(activityItems: textShare , applicationActivities: nil)
    activityViewController.popoverPresentationController?.sourceView = self.view 
    self.present(activityViewController, animated: true, completion: nil)
}
}

Share : Image

@IBAction func shareOnlyImage(_ sender: UIButton) {
    let image = UIImage(named: "Product")
    let imageShare = [ image! ]
    let activityViewController = UIActivityViewController(activityItems: imageShare , applicationActivities: nil)
    activityViewController.popoverPresentationController?.sourceView = self.view 
    self.present(activityViewController, animated: true, completion: nil)
 }

Share : Text - Image - URL

   @IBAction func shareAll(_ sender: UIButton) {
    let text = "This is the text...."
    let image = UIImage(named: "Product")
    let myWebsite = NSURL(string:"https://stackoverflow.com/users/4600136/mr-javed-multani?tab=profile")
    let shareAll= [text , image! , myWebsite]
    let activityViewController = UIActivityViewController(activityItems: shareAll, applicationActivities: nil)
    activityViewController.popoverPresentationController?.sourceView = self.view 
    self.present(activityViewController, animated: true, completion: nil)
   }

enter image description here

Will Google Android ever support .NET?

.NET compact framework has been ported to Symbian OS (http://www.redfivelabs.com/). If .NET as a 'closed' platform can be ported to this platform, I can't see any reason why it cannot be done for Android.

Add a column in a table in HIVE QL

You cannot add a column with a default value in Hive. You have the right syntax for adding the column ALTER TABLE test1 ADD COLUMNS (access_count1 int);, you just need to get rid of default sum(max_count). No changes to that files backing your table will happen as a result of adding the column. Hive handles the "missing" data by interpreting NULL as the value for every cell in that column.

So now your have the problem of needing to populate the column. Unfortunately in Hive you essentially need to rewrite the whole table, this time with the column populated. It may be easier to rerun your original query with the new column. Or you could add the column to the table you have now, then select all of its columns plus value for the new column.

You also have the option to always COALESCE the column to your desired default and leave it NULL for now. This option fails when you want NULL to have a meaning distinct from your desired default. It also requires you to depend on always remembering to COALESCE.

If you are very confident in your abilities to deal with the files backing Hive, you could also directly alter them to add your default. In general I would recommend against this because most of the time it will be slower and more dangerous. There might be some case where it makes sense though, so I've included this option for completeness.

sendKeys() in Selenium web driver

I believe Selenium now uses Key.TAB instead of Keys.TAB.

Check list of words in another string

Easiest and Simplest method of solving this problem is using re

import re

search_list = ['one', 'two', 'there']
long_string = 'some one long two phrase three'
if re.compile('|'.join(search_list),re.IGNORECASE).search(long_string): #re.IGNORECASE is used to ignore case
    # Do Something if word is present
else:
    # Do Something else if word is not present

Identify duplicates in a List

java 8 base solution:

List duplicates =    
list.stream().collect(Collectors.groupingBy(Function.identity()))
    .entrySet()
    .stream()
    .filter(e -> e.getValue().size() > 1)
    .map(Map.Entry::getKey)
    .collect(Collectors.toList());

How do I write a compareTo method which compares objects?

A String is an object in Java.

you could compare like so,

if(this.lastName.compareTo(s.getLastName() == 0)//last names are the same

How do we control web page caching, across all browsers?

To complete BalusC -> ANSWER If you are using perl you can use CGI to add HTTP headers.

Using Perl:

Use CGI;    
sub set_new_query() {
        binmode STDOUT, ":utf8";
        die if defined $query;
        $query = CGI->new();
        print $query->header(
                        -expires       => 'Sat, 26 Jul 1997 05:00:00 GMT',
                        -Pragma        => 'no-cache',
                        -Cache_Control => join(', ', qw(
                                            private
                                            no-cache
                                            no-store
                                            must-revalidate
                                            max-age=0
                                            pre-check=0
                                            post-check=0 
                                           ))
        );
    }

Using apache httpd.conf

<FilesMatch "\.(html|htm|js|css|pl)$">
FileETag None
<ifModule mod_headers.c>
Header unset ETag
Header set Cache-Control "max-age=0, no-cache, no-store, must-revalidate"
Header set Pragma "no-cache"
Header set Expires "Wed, 11 Jan 1984 05:00:00 GMT"
</ifModule>

Note: When I tried to use the html META, browsers ignored them and cached the page.

Android Fatal signal 11 (SIGSEGV) at 0x636f7d89 (code=1). How can it be tracked down?

Build fingerprint: 'motorola/harpia/harpia:6.0.1/MPIS24.241-2.50-16/16:user/release-keys' Revision: 'p1b0' ABI: 'arm' pid: 18139, tid: 25935, name: GLThread 2137 >>> com.portable3d.okt.a3dmap1 <<< signal 11 (SIGSEGV), code 2 (SEGV_ACCERR), fault addr 0x7452f000

2 out of 12 phones returned an error, found the problem was in onDrawFrame (), some objects were null, I don’t know why, I just set

if(gears==null) return;.