Programs & Examples On #Client templates

get basic SQL Server table structure information

For total columns information use below syntax : Use "DBName" go Exec SP_Columns "TableName"

For total table information use below syntax : Use "DBName" go Exec SP_help "Table Name"

how to find seconds since 1970 in java

The answer you want, "1317427200", is achieved if your reference months are January and October. If so, the dates you are looking for are 1970-JAN-01 and 2011-OCT-01, correct?

Then the problem are these numbers you are using for your months.

See, if you check the Calendar API documentation or even the constants provided in there ("Calendar.JANUARY", "Calendar.FEBRUARY" and so on), you'll discover that months start at 0 (being January).

So checking your code, you are passing february and november, which would result in "1317510000".

Best regards.

Show special characters in Unix while using 'less' Command

You can do that with cat and that pipe the output to less:

cat -e yourFile | less

This excerpt from man cat explains what -e means:

   -e     equivalent to -vE

   -E, --show-ends
          display $ at end of each line

   -v, --show-nonprinting
          use ^ and M- notation, except for LFD and TAB

How can I resize an image dynamically with CSS as the browser width/height changes?

window.onresize = function(){
    var img = document.getElementById('fullsize');
    img.style.width = "100%";
};

In IE onresize event gets fired on every pixel change (width or height) so there could be performance issue. Delay image resizing for few milliseconds by using javascript's window.setTimeout().

http://mbccs.blogspot.com/2007/11/fixing-window-resize-event-in-ie.html

Is it bad to have my virtualenv directory inside my git repository?

I used to do the same until I started using libraries that are compiled differently depending on the environment such as PyCrypto. My PyCrypto mac wouldn't work on Cygwin wouldn't work on Ubuntu.

It becomes an utter nightmare to manage the repository.

Either way I found it easier to manage the pip freeze & a requirements file than having it all in git. It's cleaner too since you get to avoid the commit spam for thousands of files as those libraries get updated...

Save each sheet in a workbook to separate CSV files

Please look into Von Pookie's answer, all credits to him/her.

 Sub asdf()
Dim ws As Worksheet, newWb As Workbook

Application.ScreenUpdating = False
For Each ws In Sheets(Array("EID Upload", "Wages with Locals Upload", "Wages without Local Upload"))
   ws.Copy
   Set newWb = ActiveWorkbook
   With newWb
      .SaveAs ws.Name, xlCSV
      .Close (False)
   End With
Next ws
Application.ScreenUpdating = True

End Sub

How to calculate the bounding box for a given lat/lng location?

I suggest to approximate locally the Earth surface as a sphere with radius given by the WGS84 ellipsoid at the given latitude. I suspect that the exact computation of latMin and latMax would require elliptic functions and would not yield an appreciable increase in accuracy (WGS84 is itself an approximation).

My implementation follows (It's written in Python; I have not tested it):

# degrees to radians
def deg2rad(degrees):
    return math.pi*degrees/180.0
# radians to degrees
def rad2deg(radians):
    return 180.0*radians/math.pi

# Semi-axes of WGS-84 geoidal reference
WGS84_a = 6378137.0  # Major semiaxis [m]
WGS84_b = 6356752.3  # Minor semiaxis [m]

# Earth radius at a given latitude, according to the WGS-84 ellipsoid [m]
def WGS84EarthRadius(lat):
    # http://en.wikipedia.org/wiki/Earth_radius
    An = WGS84_a*WGS84_a * math.cos(lat)
    Bn = WGS84_b*WGS84_b * math.sin(lat)
    Ad = WGS84_a * math.cos(lat)
    Bd = WGS84_b * math.sin(lat)
    return math.sqrt( (An*An + Bn*Bn)/(Ad*Ad + Bd*Bd) )

# Bounding box surrounding the point at given coordinates,
# assuming local approximation of Earth surface as a sphere
# of radius given by WGS84
def boundingBox(latitudeInDegrees, longitudeInDegrees, halfSideInKm):
    lat = deg2rad(latitudeInDegrees)
    lon = deg2rad(longitudeInDegrees)
    halfSide = 1000*halfSideInKm

    # Radius of Earth at given latitude
    radius = WGS84EarthRadius(lat)
    # Radius of the parallel at given latitude
    pradius = radius*math.cos(lat)

    latMin = lat - halfSide/radius
    latMax = lat + halfSide/radius
    lonMin = lon - halfSide/pradius
    lonMax = lon + halfSide/pradius

    return (rad2deg(latMin), rad2deg(lonMin), rad2deg(latMax), rad2deg(lonMax))

EDIT: The following code converts (degrees, primes, seconds) to degrees + fractions of a degree, and vice versa (not tested):

def dps2deg(degrees, primes, seconds):
    return degrees + primes/60.0 + seconds/3600.0

def deg2dps(degrees):
    intdeg = math.floor(degrees)
    primes = (degrees - intdeg)*60.0
    intpri = math.floor(primes)
    seconds = (primes - intpri)*60.0
    intsec = round(seconds)
    return (int(intdeg), int(intpri), int(intsec))

Writing a list to a file with Python

You can also use the print function if you're on python3 as follows.

f = open("myfile.txt","wb")
print(mylist, file=f)

Create a pointer to two-dimensional array

You can always avoid fiddling around with the compiler by declaring the array as linear and doing the (row,col) to array index calculation by yourself.

static uint8_t l_matrix[200];

void test(int row, int col, uint8_t val)

{

   uint8_t* matrix_ptr = l_matrix;
   matrix_ptr [col+y*row] = val; // to assign a value

}

this is what the compiler would have done anyway.

How to make a HTML list appear horizontally instead of vertically using CSS only?

Using display: inline-flex

_x000D_
_x000D_
#menu ul {_x000D_
  list-style: none;_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
  display: inline-flex_x000D_
}
_x000D_
<div id="menu">_x000D_
  <ul>_x000D_
    <li>1 menu item</li>_x000D_
    <li>2 menu item</li>_x000D_
    <li>3 menu item</li>_x000D_
  </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Using display: inline-block

_x000D_
_x000D_
#menu ul {_x000D_
  list-style: none;_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
}_x000D_
_x000D_
#menu li {_x000D_
  display: inline-block;_x000D_
}
_x000D_
<div id="menu">_x000D_
  <ul>_x000D_
    <li>1 menu item</li>_x000D_
    <li>2 menu item</li>_x000D_
    <li>3 menu item</li>_x000D_
  </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Turn on torch/flash on iPhone

Here's a shorter version you can now use to turn the light on or off:

AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
if ([device hasTorch]) {
    [device lockForConfiguration:nil];
    [device setTorchMode:AVCaptureTorchModeOn];  // use AVCaptureTorchModeOff to turn off
    [device unlockForConfiguration];
}

UPDATE: (March 2015)

With iOS 6.0 and later, you can control the brightness or level of the torch using the following method:

- (void)setTorchToLevel:(float)torchLevel
{
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    if ([device hasTorch]) {
        [device lockForConfiguration:nil];
        if (torchLevel <= 0.0) {
            [device setTorchMode:AVCaptureTorchModeOff];
        }
        else {
            if (torchLevel >= 1.0)
                torchLevel = AVCaptureMaxAvailableTorchLevel;
            BOOL success = [device setTorchModeOnWithLevel:torchLevel   error:nil];
        }
        [device unlockForConfiguration];
    }
}

You may also want to monitor the return value (success) from setTorchModeOnWithLevel:. You may get a failure if you try to set the level too high and the torch is overheating. In that case setting the level to AVCaptureMaxAvailableTorchLevel will set the level to the highest level that is allowed given the temperature of the torch.

Simple C example of doing an HTTP POST and consuming the response

Handle added.
Added Host header.
Added linux / windows support, tested (XP,WIN7).
WARNING: ERROR : "segmentation fault" if no host,path or port as argument.

#include <stdio.h> /* printf, sprintf */
#include <stdlib.h> /* exit, atoi, malloc, free */
#include <unistd.h> /* read, write, close */
#include <string.h> /* memcpy, memset */
#ifdef __linux__ 
    #include <sys/socket.h> /* socket, connect */
    #include <netdb.h> /* struct hostent, gethostbyname */
    #include <netinet/in.h> /* struct sockaddr_in, struct sockaddr */
#elif _WIN32
    #include <winsock2.h>
    #include <ws2tcpip.h>
    #include <windows.h>
    #pragma comment(lib,"ws2_32.lib") //Winsock Library

#else

#endif

void error(const char *msg) { perror(msg); exit(0); }

int main(int argc,char *argv[])
{

    int i;
    struct hostent *server;
    struct sockaddr_in serv_addr;
    int bytes, sent, received, total, message_size;
    char *message, response[4096];
    int portno = atoi(argv[2])>0?atoi(argv[2]):80;
    char *host = strlen(argv[1])>0?argv[1]:"localhost";
    char *path = strlen(argv[4])>0?argv[4]:"/";
    if (argc < 5) { puts("Parameters: <host> <port> <method> <path> [<data> [<headers>]]"); exit(0); }
    /* How big is the message? */
    message_size=0;
    if(!strcmp(argv[3],"GET"))
    {
                printf("Process 1\n");
        message_size+=strlen("%s %s%s%s HTTP/1.0\r\nHost: %s\r\n");        /* method         */
        message_size+=strlen(argv[3]);                         /* path           */
        message_size+=strlen(path);                         /* headers        */
        if(argc>5)
            message_size+=strlen(argv[5]);                     /* query string   */
        for(i=6;i<argc;i++)                                    /* headers        */
            message_size+=strlen(argv[i])+strlen("\r\n");
        message_size+=strlen("\r\n");                          /* blank line     */
    }
    else
    {
                printf("Process 2\n");
        message_size+=strlen("%s %s HTTP/1.0\r\nHost: %s\r\n");
        message_size+=strlen(argv[3]);                         /* method         */
        message_size+=strlen(path);                            /* path           */
        for(i=6;i<argc;i++)                                    /* headers        */
            message_size+=strlen(argv[i])+strlen("\r\n");
        if(argc>5)
            message_size+=strlen("Content-Length: %d\r\n")+10; /* content length */
        message_size+=strlen("\r\n");                          /* blank line     */
        if(argc>5)
            message_size+=strlen(argv[5]);                     /* body           */
    }
            printf("Allocating...\n");
    /* allocate space for the message */
    message=malloc(message_size);

    /* fill in the parameters */
    if(!strcmp(argv[3],"GET"))
    {
        if(argc>5)
            sprintf(message,"%s %s%s%s HTTP/1.0\r\nHost: %s\r\n",
                strlen(argv[3])>0?argv[3]:"GET",               /* method         */
                path,                                          /* path           */
                strlen(argv[5])>0?"?":"",                      /* ?              */
                strlen(argv[5])>0?argv[5]:"",host);            /* query string   */
        else
            sprintf(message,"%s %s HTTP/1.0\r\nHost: %s\r\n",
                strlen(argv[3])>0?argv[3]:"GET",               /* method         */
                path,host);                                    /* path           */
        for(i=6;i<argc;i++)                                    /* headers        */
            {strcat(message,argv[i]);strcat(message,"\r\n");}
        strcat(message,"\r\n");                                /* blank line     */
    }
    else
    {
        sprintf(message,"%s %s HTTP/1.0\r\nHost: %s\r\n",
            strlen(argv[3])>0?argv[3]:"POST",                  /* method         */
            path,host);                                        /* path           */
        for(i=6;i<argc;i++)                                    /* headers        */
            {strcat(message,argv[i]);strcat(message,"\r\n");}
        if(argc>5)
            sprintf(message+strlen(message),"Content-Length: %d\r\n",(int)strlen(argv[5]));
        strcat(message,"\r\n");                                /* blank line     */
        if(argc>5)
            strcat(message,argv[5]);                           /* body           */
    }
    printf("Processed\n");
    /* What are we going to send? */
    printf("Request:\n%s\n",message);
        /* lookup the ip address */

    total = strlen(message);
    /* create the socket */
    #ifdef _WIN32
WSADATA wsa;
SOCKET s;

printf("\nInitialising Winsock...");
if (WSAStartup(MAKEWORD(2,2),&wsa) != 0)
{
    printf("Failed. Error Code : %d",WSAGetLastError());
    return 1;
}

printf("Initialised.\n");

//Create a socket
if((s = socket(AF_INET , SOCK_STREAM , 0 )) == INVALID_SOCKET)
{
    printf("Could not create socket : %d" , WSAGetLastError());
}

printf("Socket created.\n");

server = gethostbyname(host);
serv_addr.sin_addr.s_addr = inet_addr(server->h_addr);
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(portno);
memset(&serv_addr,0,sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(portno);
memcpy(&serv_addr.sin_addr.s_addr,server->h_addr,server->h_length);
//Connect to remote server
if (connect(s , (struct sockaddr *)&serv_addr , sizeof(serv_addr)) < 0)
{
    printf("connect failed with error code : %d" , WSAGetLastError());
    return 1;
}

puts("Connected");
if( send(s , message , strlen(message) , 0) < 0)
{
    printf("Send failed with error code : %d" , WSAGetLastError());
    return 1;
}
puts("Data Send\n");

//Receive a reply from the server
if((received = recv(s , response , 2000 , 0)) == SOCKET_ERROR)
{
    printf("recv failed with error code : %d" , WSAGetLastError());
}

puts("Reply received\n");

//Add a NULL terminating character to make it a proper string before printing
response[received] = '\0';
puts(response);

closesocket(s);
WSACleanup();
    #endif
    #ifdef __linux__ 
    int sockfd;
    server = gethostbyname(host);
    if (server == NULL) error("ERROR, no such host");
        sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (sockfd < 0) error("ERROR opening socket");
        /* fill in the structure */
        memset(&serv_addr,0,sizeof(serv_addr));
        serv_addr.sin_family = AF_INET;
        serv_addr.sin_port = htons(portno);
        memcpy(&serv_addr.sin_addr.s_addr,server->h_addr,server->h_length);
                /* connect the socket */
        if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0)
            error("ERROR connecting");
                /* send the request */

    sent = 0;
    do {
        bytes = write(sockfd,message+sent,total-sent);
        if (bytes < 0)
            error("ERROR writing message to socket");
        if (bytes == 0)
            break;
        sent+=bytes;
    } while (sent < total);
    /* receive the response */
    memset(response, 0, sizeof(response));
    total = sizeof(response)-1;
    received = 0;
    printf("Response: \n");
    do {
       printf("%s", response);
       memset(response, 0, sizeof(response));
       bytes = recv(sockfd, response, 1024, 0);
        if (bytes < 0)
           printf("ERROR reading response from socket");
       if (bytes == 0)
           break;
       received+=bytes;
    } while (1);

    if (received == total)
        error("ERROR storing complete response from socket");

    /* close the socket */
    close(sockfd);
    #endif


    free(message);

    return 0;
}

"SetPropertiesRule" warning message when starting Tomcat from Eclipse

I respect all the solutions given here.

But what I came to know after reading all these, we haven't observed that on which folder the struts.xml file or any configuration file which is necessary for the web application.

My SOULUTION IS:

  1. copy the struts.xml file to the src folder of our project.
  2. click "file-->save all" in eclipse and go click "project-->clean".
  3. restart the server.

Hope the problem solved.

How to find out if an item is present in a std::vector?

You can use std::find from <algorithm>:

#include <vector>
vector<int> vec; 
//can have other data types instead of int but must same datatype as item 
std::find(vec.begin(), vec.end(), item) != vec.end()

This returns a bool (true if present, false otherwise). With your example:

#include <algorithm>
#include <vector>

if ( std::find(vec.begin(), vec.end(), item) != vec.end() )
   do_this();
else
   do_that();

printf a variable in C

Your printf needs a format string:

printf("%d\n", x);

This reference page gives details on how to use printf and related functions.

How can I convert a stack trace to a string?

Without java.io.* it can be done like this.

String trace = e.toString() + "\n";                     

for (StackTraceElement e1 : e.getStackTrace()) {
    trace += "\t at " + e1.toString() + "\n";
}   

And then the trace variable holds your stack trace. Output also holds the initial cause, the output is identical to printStackTrace()

Example, printStackTrace() yields:

java.io.FileNotFoundException: / (Is a directory)
    at java.io.FileOutputStream.open0(Native Method)
    at java.io.FileOutputStream.open(FileOutputStream.java:270)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:213)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:101)
    at Test.main(Test.java:9)

The trace String holds, when printed to stdout

java.io.FileNotFoundException: / (Is a directory)
     at java.io.FileOutputStream.open0(Native Method)
     at java.io.FileOutputStream.open(FileOutputStream.java:270)
     at java.io.FileOutputStream.<init>(FileOutputStream.java:213)
     at java.io.FileOutputStream.<init>(FileOutputStream.java:101)
     at Test.main(Test.java:9)

Connecting to SQL Server Express - What is my server name?

You should be able to see it in the Services panel. Look for a servicename like Sql Server (MSSQLSERVER). The name in the parentheses is your instance name.

How to use OUTPUT parameter in Stored Procedure

SqlCommand yourCommand = new SqlCommand();
yourCommand.Connection = yourSqlConn;
yourCommand.Parameters.Add("@yourParam");
yourCommand.Parameters["@yourParam"].Direction = ParameterDirection.Output;

// execute your query successfully

int yourResult = yourCommand.Parameters["@yourParam"].Value;

How to update Ruby to 1.9.x on Mac?

Dan Benjamin's Hivelogic article Installing Ruby, RubyGems, and Rails on Snow Leopard is the recommended place to go although the article is for 1.8, so here's a Ruby 1.9-specific install on Snow Leopard. Watch out for the 64-bit thing... either go all 64-bit 'fat' (as is - for example - Apache on OS X, which can cause problems with 32-bit libraries) or check any gems you're likely to use to make sure they're okay for 64-bit.

If statements for Checkboxes

I simplification for Science_Fiction's answer I think is to use the exclusive or function so you can just have:

if(checkbox1.checked ^ checkbox2.checked)
{
//do stuff
}

That is assuming you want to do the same thing for both situations.

How can I retrieve a table from stored procedure to a datatable?

Explaining if any one want to send some parameters while calling stored procedure as below,

using (SqlConnection con = new SqlConnection(connetionString))
            {
                using (var command = new SqlCommand(storedProcName, con))
                {
                    foreach (var item in sqlParams)
                    {
                        item.Direction = ParameterDirection.Input;
                        item.DbType = DbType.String;
                        command.Parameters.Add(item);
                    }
                    command.CommandType = CommandType.StoredProcedure;
                    using (var adapter = new SqlDataAdapter(command))
                    {
                        adapter.Fill(dt);
                    }
                }
            }

Checking password match while typing

$(function() {
    $("#txtConfirmPassword").keyup(function() {
        var password = $("#txtNewPassword").val();
        $("#divCheckPasswordMatch").html(password == $(this).val()
            ? "Passwords match."
            : "Passwords do not match!"
        );
    });
});?

Demo here

Joining pandas dataframes by column names

you need to make county_ID as index for the right frame:

frame_2.join ( frame_1.set_index( [ 'county_ID' ], verify_integrity=True ),
               on=[ 'countyid' ], how='left' )

for your information, in pandas left join breaks when the right frame has non unique values on the joining column. see this bug.

so you need to verify integrity before joining by , verify_integrity=True

cannot download, $GOPATH not set

This problem occured to me in raspberry pi. I had logged in through VNC client The problem persisted despite setting and exporting the GOPATH. Then Ran the "go get" command without sudo and it worked perfectly.

SQLException : String or binary data would be truncated

In our own case I increase the sql table allowable character or field size which is less than the total characters posted from the front end. Hence that resolve the issue.

Lowercase and Uppercase with jQuery

I think you want to lowercase the checked value? Try:

var jIsHasKids = $('#chkIsHasKids:checked').val().toLowerCase();

or you want to check it, then get its value as lowercase:

var jIsHasKids = $('#chkIsHasKids').attr("checked", true).val().toLowerCase();

Doctrine 2: Update query with query builder

Let's say there is an administrator dashboard where users are listed with their id printed as a data attribute so it can be retrieved at some point via JavaScript.

An update could be executed this way …

class UserRepository extends \Doctrine\ORM\EntityRepository
{
    public function updateUserStatus($userId, $newStatus)
    {
        return $this->createQueryBuilder('u')
            ->update()
            ->set('u.isActive', '?1')
            ->setParameter(1, $qb->expr()->literal($newStatus))
            ->where('u.id = ?2')
            ->setParameter(2, $qb->expr()->literal($userId))
            ->getQuery()
            ->getSingleScalarResult()
        ;
    }

AJAX action handling:

# Post datas may be:
# handled with a specific custom formType — OR — retrieved from request object
$userId = (int)$request->request->get('userId');
$newStatus = (int)$request->request->get('newStatus');
$em = $this->getDoctrine()->getManager();
$r = $em->getRepository('NAMESPACE\User')
        ->updateUserStatus($userId, $newStatus);
if ( !empty($r) ){
    # Row updated
}

Working example using Doctrine 2.5 (on top of Symfony3).

Where are my postgres *.conf files?

On Mac (Postgres installed using brew) :

/usr/local/Cellar/postgresql/9.3.3>bin/postgres -D /usr/local/var/postgres/

wamp server mysql user id and password

Simply goto MySql Console.

If using Wamp:

  1. Click on Wamp icon just beside o'clock.
  2. In MySql section click on MySql Console.
  3. Press enter (means no password) twice.
  4. mysql commands preview like this : mysql>
  5. SET PASSWORD FOR 'root'@'localhost' = PASSWORD('secret');

That's it. This set your root password to secret

In order to set user privilege to default one:

SET PASSWORD FOR 'root'@'localhost' = PASSWORD('');

Works like a charm!

Find the number of employees in each department - SQL Oracle

A request to list "Number of employees in each department" or "Display how many people work in each department" is the same as "For each department, list the number of employees", this must include departments with no employees. In the sample database, Operations has 0 employees. So a LEFT OUTER JOIN should be used.

SELECT dept.name, COUNT(emp.empno) AS count
FROM dept
LEFT OUTER JOIN emp ON emp.deptno = dept.deptno
GROUP BY dept.name;

Gradle Sync failed could not find constraint-layout:1.0.0-alpha2

I used com.android.support.constraint:constraint-layout:1.0.0-alpha2 with classpath 'com.android.tools.build:gradle:2.1.0', it worked like charm.

What's the u prefix in a Python string?

All strings meant for humans should use u"".

I found that the following mindset helps a lot when dealing with Python strings: All Python manifest strings should use the u"" syntax. The "" syntax is for byte arrays, only.

Before the bashing begins, let me explain. Most Python programs start out with using "" for strings. But then they need to support documentation off the Internet, so they start using "".decode and all of a sudden they are getting exceptions everywhere about decoding this and that - all because of the use of "" for strings. In this case, Unicode does act like a virus and will wreak havoc.

But, if you follow my rule, you won't have this infection (because you will already be infected).

Function not defined javascript

There are a couple of things to check:

  • In FireBug, see if there are any loading errors that would indicate that your script is badly formatted and the functions do not get registered.
  • You can also try typing "proceedToSecond" into the FireBug console to see if the function gets defined
  • One thing you may try is removing the space around the @type attribute to the script tag: it should be <script type="text/javascript"> instead of <script type = "text/javascript">

"Could not find a version that satisfies the requirement opencv-python"

We were getting the same error.For us, it solved by upgrading pip version (also discussed in FAQ of OpenCV GitHub). Earlier we had pip-7.1.0, post upgrading it to "pip-9.0.2", it successfully installed.

pip install --upgrade pip
pip install opencv-python

How to print table using Javascript?

Here is your code in a jsfiddle example. I have tested it and it looks fine.

http://jsfiddle.net/dimshik/9DbEP/4/

I used a simple table, maybe you are missing some CSS on your new page that was created with JavaScript.

<table border="1" cellpadding="3" id="printTable">
    <tbody><tr>
        <th>First Name</th>
        <th>Last Name</th>      
        <th>Points</th>
    </tr>
    <tr>
        <td>Jill</td>
        <td>Smith</td>      
        <td>50</td>
    </tr>
    <tr>
        <td>Eve</td>
        <td>Jackson</td>        
        <td>94</td>
    </tr>
    <tr>
        <td>John</td>
        <td>Doe</td>        
        <td>80</td>
    </tr>
    <tr>
        <td>Adam</td>
        <td>Johnson</td>        
        <td>67</td>
    </tr>
</tbody></table>

Modifying Objects within stream in Java8 while iterating

This might be a little late. But here is one of the usage. This to get the count of the number of files.

Create a pointer to memory (a new obj in this case) and have the property of the object modified. Java 8 stream doesn't allow to modify the pointer itself and hence if you declare just count as a variable and try to increment within the stream it will never work and throw a compiler exception in the first place

Path path = Paths.get("/Users/XXXX/static/test.txt");



Count c = new Count();
            c.setCount(0);
            Files.lines(path).forEach(item -> {
                c.setCount(c.getCount()+1);
                System.out.println(item);});
            System.out.println("line count,"+c);

public static class Count{
        private int count;

        public int getCount() {
            return count;
        }

        public void setCount(int count) {
            this.count = count;
        }

        @Override
        public String toString() {
            return "Count [count=" + count + "]";
        }



    }

Download all stock symbol list of a market

There does not seem to be a straight-forward way provided by Google or Yahoo finance portals to download the full list of tickers. One possible 'brute force' way to get it is to query their APIs for every possible combinations of letters and save only those that return valid results. As silly as it may seem there are people who actually do it (ie. check this: http://investexcel.net/all-yahoo-finance-stock-tickers/).

You can download lists of symbols from exchanges directly or 3rd party websites as suggested by @Eugene S and @Capn Sparrow, however if you intend to use it to fetch data from Google or Yahoo, you have to sometimes use prefixes or suffixes to make sure that you're getting the correct data. This is because some symbols may repeat between exchanges, so Google and Yahoo prepend or append exchange codes to the tickers in order to distinguish between them. Here's an example:

Company:  Vodafone
------------------
LSE symbol:    VOD
 in Google:    LON:VOD
 in Yahoo:     VOD.L
NASDAQ symbol: VOD
 in Google:    NASDAQ:VOD
 in Yahoo:     VOD

How to repair COMException error 80040154?

To find the DLL, go to your 64-bit machine and open the registry. Find the key called HKEY_CLASSES_ROOT\CLSID\{681EF637-F129-4AE9-94BB-618937E3F6B6}\InprocServer32. This key will have the filename of the DLL as its default value.

If you solved the problem on your 64-bit machine by recompiling your project for x86, then you'll need to look in the 32-bit portion of the registry instead of in the normal place. This is HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Classes\CLSID\{681EF637-F129-4AE9-94BB-618937E3F6B6}\InprocServer32.

If the DLL is built for 32 bits then you can use it directly on your 32-bit machine. If it's built for 64 bits then you'll have to contact the vendor and get a 32-bit version from them.

When you have the DLL, register it by running c:\windows\system32\regsvr32.exe.

How can I replace a regex substring match in Javascript?

var str   = 'asd-0.testing';
var regex = /(asd-)\d(\.\w+)/;
str = str.replace(regex, "$11$2");
console.log(str);

Or if you're sure there won't be any other digits in the string:

var str   = 'asd-0.testing';
var regex = /\d/;
str = str.replace(regex, "1");
console.log(str);

How to set default font family for entire Android app

READ UPDATES BELOW

I had the same issue with embedding a new font and finally got it to work with extending the TextView and set the typefont inside.

public class YourTextView extends TextView {

    public YourTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    public YourTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public YourTextView(Context context) {
        super(context);
        init();
    }

    private void init() {
        Typeface tf = Typeface.createFromAsset(context.getAssets(),
            "fonts/helveticaneue.ttf");
        setTypeface(tf);
    }
}

You have to change the TextView Elements later to from to in every element. And if you use the UI-Creator in Eclipse, sometimes he doesn't show the TextViews right. Was the only thing which work for me...

UPDATE

Nowadays I'm using reflection to change typefaces in whole application without extending TextViews. Check out this SO post

UPDATE 2

Starting with API Level 26 and available in 'support library' you can use

android:fontFamily="@font/embeddedfont"

Further information: Fonts in XML

UITextView that expands to text using auto layout

I've found it's not entirely uncommon in situations where you may still need isScrollEnabled set to true to allow a reasonable UI interaction. A simple case for this is when you want to allow an auto expanding text view but still limit it's maximum height to something reasonable in a UITableView.

Here's a subclass of UITextView I've come up with that allows auto expansion with auto layout but that you could still constrain to a maximum height and which will manage whether the view is scrollable depending on the height. By default the view will expand indefinitely if you have your constraints setup that way.

import UIKit

class FlexibleTextView: UITextView {
    // limit the height of expansion per intrinsicContentSize
    var maxHeight: CGFloat = 0.0
    private let placeholderTextView: UITextView = {
        let tv = UITextView()

        tv.translatesAutoresizingMaskIntoConstraints = false
        tv.backgroundColor = .clear
        tv.isScrollEnabled = false
        tv.textColor = .disabledTextColor
        tv.isUserInteractionEnabled = false
        return tv
    }()
    var placeholder: String? {
        get {
            return placeholderTextView.text
        }
        set {
            placeholderTextView.text = newValue
        }
    }

    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        isScrollEnabled = false
        autoresizingMask = [.flexibleWidth, .flexibleHeight]
        NotificationCenter.default.addObserver(self, selector: #selector(UITextInputDelegate.textDidChange(_:)), name: Notification.Name.UITextViewTextDidChange, object: self)
        placeholderTextView.font = font
        addSubview(placeholderTextView)

        NSLayoutConstraint.activate([
            placeholderTextView.leadingAnchor.constraint(equalTo: leadingAnchor),
            placeholderTextView.trailingAnchor.constraint(equalTo: trailingAnchor),
            placeholderTextView.topAnchor.constraint(equalTo: topAnchor),
            placeholderTextView.bottomAnchor.constraint(equalTo: bottomAnchor),
        ])
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override var text: String! {
        didSet {
            invalidateIntrinsicContentSize()
            placeholderTextView.isHidden = !text.isEmpty
        }
    }

    override var font: UIFont? {
        didSet {
            placeholderTextView.font = font
            invalidateIntrinsicContentSize()
        }
    }

    override var contentInset: UIEdgeInsets {
        didSet {
            placeholderTextView.contentInset = contentInset
        }
    }

    override var intrinsicContentSize: CGSize {
        var size = super.intrinsicContentSize

        if size.height == UIViewNoIntrinsicMetric {
            // force layout
            layoutManager.glyphRange(for: textContainer)
            size.height = layoutManager.usedRect(for: textContainer).height + textContainerInset.top + textContainerInset.bottom
        }

        if maxHeight > 0.0 && size.height > maxHeight {
            size.height = maxHeight

            if !isScrollEnabled {
                isScrollEnabled = true
            }
        } else if isScrollEnabled {
            isScrollEnabled = false
        }

        return size
    }

    @objc private func textDidChange(_ note: Notification) {
        // needed incase isScrollEnabled is set to true which stops automatically calling invalidateIntrinsicContentSize()
        invalidateIntrinsicContentSize()
        placeholderTextView.isHidden = !text.isEmpty
    }
}

As a bonus there's support for including placeholder text similar to UILabel.

Java: how to import a jar file from command line

you can try to export as "Runnable jar" in eclipse. I have also problems, when i export as "jar", but i have never problems when i export as "Runnable jar".

How to read a Parquet file into Pandas DataFrame?

Update: since the time I answered this there has been a lot of work on this look at Apache Arrow for a better read and write of parquet. Also: http://wesmckinney.com/blog/python-parquet-multithreading/

There is a python parquet reader that works relatively well: https://github.com/jcrobak/parquet-python

It will create python objects and then you will have to move them to a Pandas DataFrame so the process will be slower than pd.read_csv for example.

overlay opaque div over youtube iframe

I spent a day messing with CSS before I found anataliocs tip. Add wmode=transparent as a parameter to the YouTube URL:

<iframe title=<your frame title goes here> 
    src="http://www.youtube.com/embed/K3j9taoTd0E?wmode=transparent"  
    scrolling="no" 
    frameborder="0" 
    width="640" 
    height="390" 
    style="border:none;">
</iframe>

This allows the iframe to inherit the z-index of its container so your opaque <div> would be in front of the iframe.

How to remove "onclick" with JQuery?

I know this is quite old, but when a lost stranger finds this question looking for an answer (like I did) then this is the best way to do it, instead of using removeAttr():

$element.prop("onclick", null);

Citing jQuerys official doku:

"Removing an inline onclick event handler using .removeAttr() doesn't achieve the desired effect in Internet Explorer 6, 7, or 8. To avoid potential problems, use .prop() instead"

Iterate over a Javascript associative array in sorted order

I really like @luke-schafer's prototype idea, but also hear what he is saying about the issues with prototypes. What about using a simple function?

_x000D_
_x000D_
function sortKeysAndDo( obj, worker ) {_x000D_
  var keys = Object.keys(obj);_x000D_
  keys.sort();_x000D_
  for (var i = 0; i < keys.length; i++) {_x000D_
     worker(keys[i], obj[keys[i]]);_x000D_
  }_x000D_
}_x000D_
_x000D_
function show( key, value ) {_x000D_
  document.write( key + ' : ' + value +'<br>' );_x000D_
}_x000D_
_x000D_
var a = new Array();_x000D_
a['b'] = 1;_x000D_
a['z'] = 1;_x000D_
a['a'] = 1;_x000D_
_x000D_
sortKeysAndDo( a, show);_x000D_
_x000D_
var my_object = { 'c': 3, 'a': 1, 'b': 2 };_x000D_
_x000D_
sortKeysAndDo( my_object, show);
_x000D_
_x000D_
_x000D_

This seems to eliminate the issues with prototypes and still provide a sorted iterator for objects. I am not really a JavaScript guru, though, so I'd love to know if this solution has hidden flaws I missed.

java.lang.NoClassDefFoundError: org/json/JSONObject

Please add the following dependency http://mvnrepository.com/artifact/org.json/json/20080701

<dependency>
   <groupId>org.json</groupId>
   <artifactId>json</artifactId>
   <version>20080701</version>
</dependency>

SQL: parse the first, middle and last name from a fullname field

If you are trying to parse apart a human name in PHP, I recommend Keith Beckman's nameparse.php script.

Copy in case site goes down:

<?
/*
Name:   nameparse.php
Version: 0.2a
Date:   030507
First:  030407
License:    GNU General Public License v2
Bugs:   If one of the words in the middle name is Ben (or St., for that matter),
        or any other possible last-name prefix, the name MUST be entered in
        last-name-first format. If the last-name parsing routines get ahold
        of any prefix, they tie up the rest of the name up to the suffix. i.e.:

        William Ben Carey   would yield 'Ben Carey' as the last name, while,
        Carey, William Ben  would yield 'Carey' as last and 'Ben' as middle.

        This is a problem inherent in the prefix-parsing routines algorithm,
        and probably will not be fixed. It's not my fault that there's some
        odd overlap between various languages. Just don't name your kids
        'Something Ben Something', and you should be alright.

*/

function    norm_str($string) {
    return  trim(strtolower(
        str_replace('.','',$string)));
    }

function    in_array_norm($needle,$haystack) {
    return  in_array(norm_str($needle),$haystack);
    }

function    parse_name($fullname) {
    $titles         =   array('dr','miss','mr','mrs','ms','judge');
    $prefices       =   array('ben','bin','da','dal','de','del','der','de','e',
                            'la','le','san','st','ste','van','vel','von');
    $suffices       =   array('esq','esquire','jr','sr','2','ii','iii','iv');

    $pieces         =   explode(',',preg_replace('/\s+/',' ',trim($fullname)));
    $n_pieces       =   count($pieces);

    switch($n_pieces) {
        case    1:  // array(title first middles last suffix)
            $subp   =   explode(' ',trim($pieces[0]));
            $n_subp =   count($subp);
            for($i = 0; $i < $n_subp; $i++) {
                $curr               =   trim($subp[$i]);
                $next               =   trim($subp[$i+1]);

                if($i == 0 && in_array_norm($curr,$titles)) {
                    $out['title']   =   $curr;
                    continue;
                    }

                if(!$out['first']) {
                    $out['first']   =   $curr;
                    continue;
                    }

                if($i == $n_subp-2 && $next && in_array_norm($next,$suffices)) {
                    if($out['last']) {
                        $out['last']    .=  " $curr";
                        }
                    else {
                        $out['last']    =   $curr;
                        }
                    $out['suffix']      =   $next;
                    break;
                    }

                if($i == $n_subp-1) {
                    if($out['last']) {
                        $out['last']    .=  " $curr";
                        }
                    else {
                        $out['last']    =   $curr;
                        }
                    continue;
                    }

                if(in_array_norm($curr,$prefices)) {
                    if($out['last']) {
                        $out['last']    .=  " $curr";
                        }
                    else {
                        $out['last']    =   $curr;
                        }
                    continue;
                    }

                if($next == 'y' || $next == 'Y') {
                    if($out['last']) {
                        $out['last']    .=  " $curr";
                        }
                    else {
                        $out['last']    =   $curr;
                        }
                    continue;
                    }

                if($out['last']) {
                    $out['last']    .=  " $curr";
                    continue;
                    }

                if($out['middle']) {
                    $out['middle']      .=  " $curr";
                    }
                else {
                    $out['middle']      =   $curr;
                    }
                }
            break;
        case    2:
                switch(in_array_norm($pieces[1],$suffices)) {
                    case    TRUE: // array(title first middles last,suffix)
                        $subp   =   explode(' ',trim($pieces[0]));
                        $n_subp =   count($subp);
                        for($i = 0; $i < $n_subp; $i++) {
                            $curr               =   trim($subp[$i]);
                            $next               =   trim($subp[$i+1]);

                            if($i == 0 && in_array_norm($curr,$titles)) {
                                $out['title']   =   $curr;
                                continue;
                                }

                            if(!$out['first']) {
                                $out['first']   =   $curr;
                                continue;
                                }

                            if($i == $n_subp-1) {
                                if($out['last']) {
                                    $out['last']    .=  " $curr";
                                    }
                                else {
                                    $out['last']    =   $curr;
                                    }
                                continue;
                                }

                            if(in_array_norm($curr,$prefices)) {
                                if($out['last']) {
                                    $out['last']    .=  " $curr";
                                    }
                                else {
                                    $out['last']    =   $curr;
                                    }
                                continue;
                                }

                            if($next == 'y' || $next == 'Y') {
                                if($out['last']) {
                                    $out['last']    .=  " $curr";
                                    }
                                else {
                                    $out['last']    =   $curr;
                                    }
                                continue;
                                }

                            if($out['last']) {
                                $out['last']    .=  " $curr";
                                continue;
                                }

                            if($out['middle']) {
                                $out['middle']      .=  " $curr";
                                }
                            else {
                                $out['middle']      =   $curr;
                                }
                            }                       
                        $out['suffix']  =   trim($pieces[1]);
                        break;
                    case    FALSE: // array(last,title first middles suffix)
                        $subp   =   explode(' ',trim($pieces[1]));
                        $n_subp =   count($subp);
                        for($i = 0; $i < $n_subp; $i++) {
                            $curr               =   trim($subp[$i]);
                            $next               =   trim($subp[$i+1]);

                            if($i == 0 && in_array_norm($curr,$titles)) {
                                $out['title']   =   $curr;
                                continue;
                                }

                            if(!$out['first']) {
                                $out['first']   =   $curr;
                                continue;
                                }

                        if($i == $n_subp-2 && $next &&
                            in_array_norm($next,$suffices)) {
                            if($out['middle']) {
                                $out['middle']  .=  " $curr";
                                }
                            else {
                                $out['middle']  =   $curr;
                                }
                            $out['suffix']      =   $next;
                            break;
                            }

                        if($i == $n_subp-1 && in_array_norm($curr,$suffices)) {
                            $out['suffix']      =   $curr;
                            continue;
                            }

                        if($out['middle']) {
                            $out['middle']      .=  " $curr";
                            }
                        else {
                            $out['middle']      =   $curr;
                            }
                        }
                        $out['last']    =   $pieces[0];
                        break;
                    }
            unset($pieces);
            break;
        case    3:  // array(last,title first middles,suffix)
            $subp   =   explode(' ',trim($pieces[1]));
            $n_subp =   count($subp);
            for($i = 0; $i < $n_subp; $i++) {
                $curr               =   trim($subp[$i]);
                $next               =   trim($subp[$i+1]);
                if($i == 0 && in_array_norm($curr,$titles)) {
                    $out['title']   =   $curr;
                    continue;
                    }

                if(!$out['first']) {
                    $out['first']   =   $curr;
                    continue;
                    }

                if($out['middle']) {
                    $out['middle']      .=  " $curr";
                    }
                else {
                    $out['middle']      =   $curr;
                    }
                }

            $out['last']                =   trim($pieces[0]);
            $out['suffix']              =   trim($pieces[2]);
            break;
        default:    // unparseable
            unset($pieces);
            break;
        }

    return $out;
    }


?>

jQuery Button.click() event is triggered twice

Strange behaviour which I was experienced also. So for me "return false" did the trick.

        $( '#selector' ).on( 'click', function() {
            //code
            return false;
        });

MS Access DB Engine (32-bit) with Office 64-bit

I hate to answer my own questions, but I did finally find a solution that actually works (using socket communication between services may fix the problem, but it creates even more problems). Since our database is legacy, it merely required Microsoft.ACE.OLEDB.12.0 in the connection string. It turns out that this was also included in Office 2007 (and MSDE 2007), where there is only a 32-bit version available. So, instead of installing MSDE 2010 32-bit, we install MSDE 2007, and it works just fine. Other applications can then install 64-bit MSDE 2010 (or 64-bit Office 2010), and it does not conflict with our application.

Thus far, it appears this is an acceptable solution for all Windows OS environments.

How to send/receive SOAP request and response using C#?

The urls are different.

  • http://localhost/AccountSvc/DataInquiry.asmx

vs.

  • /acctinqsvc/portfolioinquiry.asmx

Resolve this issue first, as if the web server cannot resolve the URL you are attempting to POST to, you won't even begin to process the actions described by your request.

You should only need to create the WebRequest to the ASMX root URL, ie: http://localhost/AccountSvc/DataInquiry.asmx, and specify the desired method/operation in the SOAPAction header.

The SOAPAction header values are different.

  • http://localhost/AccountSvc/DataInquiry.asmx/ + methodName

vs.

  • http://tempuri.org/GetMyName

You should be able to determine the correct SOAPAction by going to the correct ASMX URL and appending ?wsdl

There should be a <soap:operation> tag underneath the <wsdl:operation> tag that matches the operation you are attempting to execute, which appears to be GetMyName.

There is no XML declaration in the request body that includes your SOAP XML.

You specify text/xml in the ContentType of your HttpRequest and no charset. Perhaps these default to us-ascii, but there's no telling if you aren't specifying them!

The SoapUI created XML includes an XML declaration that specifies an encoding of utf-8, which also matches the Content-Type provided to the HTTP request which is: text/xml; charset=utf-8

Hope that helps!

Why would you use Expression<Func<T>> rather than Func<T>?

I'd like to add some notes about the differences between Func<T> and Expression<Func<T>>:

  • Func<T> is just a normal old-school MulticastDelegate;
  • Expression<Func<T>> is a representation of lambda expression in form of expression tree;
  • expression tree can be constructed through lambda expression syntax or through the API syntax;
  • expression tree can be compiled to a delegate Func<T>;
  • the inverse conversion is theoretically possible, but it's a kind of decompiling, there is no builtin functionality for that as it's not a straightforward process;
  • expression tree can be observed/translated/modified through the ExpressionVisitor;
  • the extension methods for IEnumerable operate with Func<T>;
  • the extension methods for IQueryable operate with Expression<Func<T>>.

There's an article which describes the details with code samples:
LINQ: Func<T> vs. Expression<Func<T>>.

Hope it will be helpful.

Requery a subform from another form?

All your controls are belong to us!

Fionnuala answered this correctly but skimmers like me would find it easy to miss the point.

You don't refresh the subFORM you refresh the subform CONTROL. In fact, if you check with allforms() the subForm isn't even loaded as far as access is concerned.

On the main form look at the label the subform wizard provided or select the subform by clicking once or on the border around it and look at the "caption" in the "Other" tab in properties. That's the name you use for requerying, not the name of the form that appears in the navigation panel.

In my case I had a subform called frmInvProdSub and I tried for many hours to figure out why Access didn't think it existed. I gave up, deleted the form and re-created it. The very last step is telling it what you want to call the control so I called it frmInvProdSub and finished the wizard. Then I tried and voila, it worked!

When I looked at the form name in the navigation window I realized I'd forgotten to put "Sub" in the name! That's when it clicked. The CONTROL is called frmInvProdSub, not the form and using the control name works.

Of course if both names are identical then you didn't have this problem lol.

Best way to load module/class from lib folder in Rails 3?

As of Rails 5, it is recommended to put the lib folder under app directory or instead create other meaningful name spaces for the folder as services , presenters, features etc and put it under app directory for auto loading by rails.

Please check this GitHub Discussion Link as well.

Apply style to cells of first row

This should do the work:

.category_table tr:first-child td {
    vertical-align: top;
}

Is there shorthand for returning a default value if None in Python?

You could use the or operator:

return x or "default"

Note that this also returns "default" if x is any falsy value, including an empty list, 0, empty string, or even datetime.time(0) (midnight).

How to export MySQL database with triggers and procedures?

mysqldump will backup by default all the triggers but NOT the stored procedures/functions. There are 2 mysqldump parameters that control this behavior:

  • --routines – FALSE by default
  • --triggers – TRUE by default

so in mysqldump command , add --routines like :

mysqldump <other mysqldump options> --routines > outputfile.sql

See the MySQL documentation about mysqldump arguments.

Indenting code in Sublime text 2?

Select everything, or whatever you want to re-indent and do Alt+ E+L+R. This is really quick and painless.

How SID is different from Service name in Oracle tnsnames.ora

I know this is ancient however when dealing with finicky tools, uses, users or symptoms re: sid & service naming one can add a little flex to your tnsnames entries as like:

mySID, mySID.whereever.com =
(DESCRIPTION =
  (ADDRESS_LIST =
    (ADDRESS = (PROTOCOL = TCP)(HOST = myHostname)(PORT = 1521))
  )
  (CONNECT_DATA =
    (SERVICE_NAME = mySID.whereever.com)
    (SID = mySID)
    (SERVER = DEDICATED)
  )
)

I just thought I'd leave this here as it's mildly relevant to the question and can be helpful when attempting to weave around some less than clear idiosyncrasies of oracle networking.

HTTP test server accepting GET/POST requests

Just set one up yourself. Copy this snippet to your webserver.


echo "<pre>";
print_r($_POST);
echo "</pre>";

Just post what you want to that page. Done.

PostgreSQL delete all content

For small tables DELETE is often faster and needs less aggressive locking (for heavy concurrent load):

DELETE FROM tbl;

With no WHERE condition.

For medium or bigger tables, go with TRUNCATE tbl, like @Greg posted.

Best way to compare dates in Android

You could try this

Calendar today = Calendar.getInstance (); 
today.add(Calendar.DAY_OF_YEAR, 0); 
today.set(Calendar.HOUR_OF_DAY, hrs); 
today.set(Calendar.MINUTE, mins ); 
today.set(Calendar.SECOND, 0); 

and you could use today.getTime() to retrieve value and compare.

Bootstrap fullscreen layout with 100% height

Here's an answer using the latest Bootstrap 4.0.0. This layout is easier using the flexbox and sizing utility classes that are all provided in Bootstrap 4. This layout is possible with very little extra CSS.

#mmenu_screen > .row {
    min-height: 100vh;
}

.flex-fill {
    flex:1 1 auto;
}

<div id="mmenu_screen" class="container-fluid main_container d-flex">
    <div class="row flex-fill">
        <div class="col-sm-6 h-100">
            <div class="row h-50">
                <div class="col-sm-12" id="mmenu_screen--book">
                    <!-- Button for booking -->
                    Booking
                </div>
            </div>
            <div class="row h-50">
                <div class="col-sm-12" id="mmenu_screen--information">
                    <!-- Button for information -->
                    Info
                </div>
            </div>
        </div>
        <div class="col-sm-6 mmenu_screen--direktaction flex-fill">
            <!-- Button for direktaction -->
            Action
        </div>
    </div>
</div>

Demo

The flex-fill and vh-100 classes are included in Bootstrap 4.1 (and later)

Does swift have a trim method on String?

Don't forget to import Foundation or UIKit.

import Foundation
let trimmedString = "   aaa  "".trimmingCharacters(in: .whitespaces)
print(trimmedString)

Result:

"aaa"

Otherwise you'll get:

error: value of type 'String' has no member 'trimmingCharacters'
    return self.trimmingCharacters(in: .whitespaces)

How to Call VBA Function from Excel Cells?

The issue you have encountered is that UDFs cannot modify the Excel environment, they can only return a value to the calling cell.

There are several alternatives

  1. For the sample given you don't actually need VBA. This formula will work
    ='C:\Users\UserName\Desktop\[TestSample.xlsx]Sheet1'!$B$2

  2. Use a rather messy work around: See this answer

  3. You can use ExecuteExcel4Macro or OLEDB

Access Controller method from another controller in Laravel 5

Try creating a new PrintReportController object in SubmitPerformanceController and calling getPrintReport method directly.

For example lets say I have a function called "Test" in SubmitPerformanceController then I can do something like this:

public function test() { 
  $prc = new PrintReportController();
  $prc->getPrintReport();
 }

Laravel 5 – Remove Public from URL

Create A .htaccess file in your root DIR and paste the below code. That's it :P

_x000D_
_x000D_
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ ^$1 [N]

RewriteCond %{REQUEST_URI} (\.\w+$) [NC]
RewriteRule ^(.*)$ public/$1 

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ server.php
_x000D_
_x000D_
_x000D_

What's the difference between INNER JOIN, LEFT JOIN, RIGHT JOIN and FULL JOIN?

An SQL JOIN clause is used to combine rows from two or more tables, based on a common field between them.

There are different types of joins available in SQL:

INNER JOIN: returns rows when there is a match in both tables.

LEFT JOIN: returns all rows from the left table, even if there are no matches in the right table.

RIGHT JOIN: returns all rows from the right table, even if there are no matches in the left table.

FULL JOIN: It combines the results of both left and right outer joins.

The joined table will contain all records from both the tables and fill in NULLs for missing matches on either side.

SELF JOIN: is used to join a table to itself as if the table were two tables, temporarily renaming at least one table in the SQL statement.

CARTESIAN JOIN: returns the Cartesian product of the sets of records from the two or more joined tables.

WE can take each first four joins in Details :

We have two tables with the following values.

TableA

id  firstName                  lastName
.......................................
1   arun                        prasanth                 
2   ann                         antony                   
3   sruthy                      abc                      
6   new                         abc                                           

TableB

id2 age Place
................
1   24  kerala
2   24  usa
3   25  ekm
5   24  chennai

....................................................................

INNER JOIN

Note :it gives the intersection of the two tables, i.e. rows they have common in TableA and TableB

Syntax

SELECT table1.column1, table2.column2...
  FROM table1
 INNER JOIN table2
    ON table1.common_field = table2.common_field;

Apply it in our sample table :

SELECT TableA.firstName,TableA.lastName,TableB.age,TableB.Place
  FROM TableA
 INNER JOIN TableB
    ON TableA.id = TableB.id2;

Result Will Be

firstName       lastName       age  Place
..............................................
arun            prasanth        24  kerala
ann             antony          24  usa
sruthy          abc             25  ekm

LEFT JOIN

Note : will give all selected rows in TableA, plus any common selected rows in TableB.

Syntax

SELECT table1.column1, table2.column2...
  FROM table1
  LEFT JOIN table2
    ON table1.common_field = table2.common_field;

Apply it in our sample table :

SELECT TableA.firstName,TableA.lastName,TableB.age,TableB.Place
  FROM TableA
  LEFT JOIN TableB
    ON TableA.id = TableB.id2;

Result

firstName                   lastName                    age   Place
...............................................................................
arun                        prasanth                    24    kerala
ann                         antony                      24    usa
sruthy                      abc                         25    ekm
new                         abc                         NULL  NULL

RIGHT JOIN

Note : will give all selected rows in TableB, plus any common selected rows in TableA.

Syntax

SELECT table1.column1, table2.column2...
  FROM table1
 RIGHT JOIN table2
    ON table1.common_field = table2.common_field;

Apply it in our sample table :

SELECT TableA.firstName,TableA.lastName,TableB.age,TableB.Place
  FROM TableA
 RIGHT JOIN TableB
    ON TableA.id = TableB.id2;

Result

firstName                   lastName                    age     Place
...............................................................................
arun                        prasanth                    24     kerala
ann                         antony                      24     usa
sruthy                      abc                         25     ekm
NULL                        NULL                        24     chennai

FULL JOIN

Note :It will return all selected values from both tables.

Syntax

SELECT table1.column1, table2.column2...
  FROM table1
  FULL JOIN table2
    ON table1.common_field = table2.common_field;

Apply it in our sample table :

SELECT TableA.firstName,TableA.lastName,TableB.age,TableB.Place
  FROM TableA
  FULL JOIN TableB
    ON TableA.id = TableB.id2;

Result

firstName                   lastName                    age    Place
...............................................................................
arun                        prasanth                    24    kerala
ann                         antony                      24    usa
sruthy                      abc                         25    ekm
new                         abc                         NULL  NULL
NULL                        NULL                        24    chennai

Interesting Fact

For INNER joins the order doesn't matter

For (LEFT, RIGHT or FULL) OUTER joins,the order matter

Better to go check this Link it will give you interesting details about join order

What is a Python equivalent of PHP's var_dump()?

I use self-written Printer class, but dir() is also good for outputting the instance fields/values.

class Printer:

       def __init__ (self, PrintableClass):
           for name in dir(PrintableClass):
               value = getattr(PrintableClass,name)
               if  '_' not in str(name).join(str(value)):
                    print '  .%s: %r' % (name, value)

The sample of usage:

Printer(MyClass)

Find commit by hash SHA in Git

Just use the following command

git show a2c25061

or (the exact equivalent):

git log -p -1 a2c25061

Open Sublime Text from Terminal in macOS

Close Sublime. Run this command. It will uninstall it. You won't lose your prefs. Then run it again. It will automatically bind subl.

brew install Caskroom/cask/sublime-text

Use Excel VBA to click on a button in Internet Explorer, when the button has no "name" associated

IE.Document.getElementById("dgTime").getElementsByTagName("a")(0).Click

EDIT: to loop through the collection (items should appear in the same order as they are in the source document)

Dim links, link 

Set links = IE.Document.getElementById("dgTime").getElementsByTagName("a")

'For Each loop
For Each link in links
    link.Click
Next link

'For Next loop
Dim n, i
n = links.length
For i = 0 to n-1 Step 2
    links(i).click
Next I

Java out.println() how is this possible?

You will have to create an object out first. More about this here:

    // write to stdout
    out = System.out;
    out.println("Test 1");
    out.close();

Change SQLite database mode to read-write

I solved this by changing owner from root to me on all files on /db dir.

Just do ls -l on that folder, if any of the filer is owned by root just change it to you, using: sudo chown user file

How to pass an object from one activity to another on Android

You could also write the object's data into temporary Strings and ints, and pass them to the activity. Of course that way, you get the data transported, but not the object itself.

But if you just want to display them, and not use the object in another method or something like that, it should be enough. I did it the same way to just display data from one object in another activity.

String fName_temp   = yourObject.getFname();
String lName_temp   = yourObject.getLname();
String age_temp     = yourObject.getAge();
String address_temp = yourObject.getAddress();

Intent i = new Intent(this, ToClass.class);
i.putExtra("fname", fName_temp);
i.putExtra("lname", lName_temp);
i.putExtra("age", age_temp);
i.putExtra("address", address_temp);

startActivity(i);

You could also pass them in directly instead of the temp ivars, but this way it's clearer, in my opinion. Additionally, you can set the temp ivars to null so that they get cleaned by the GarbageCollector sooner.

Good luck!

On a side note: override toString() instead of writing your own print method.

As mentioned in the comments below, this is how you get your data back in another activity:

String fName = getIntent().getExtras().getInt("fname");

How to return the output of stored procedure into a variable in sql server

That depends on the nature of the information you want to return.

If it is a single integer value, you can use the return statement

 create proc myproc
 as 
 begin
     return 1
 end
 go
 declare @i int
 exec @i = myproc

If you have a non integer value, or a number of scalar values, you can use output parameters

create proc myproc
  @a int output,
  @b varchar(50) output
as
begin
  select @a = 1, @b='hello'
end
go
declare @i int, @j varchar(50)
exec myproc @i output, @j output

If you want to return a dataset, you can use insert exec

create proc myproc
as 
begin
     select name from sysobjects
end
go

declare @t table (name varchar(100))
insert @t (name)
exec myproc

You can even return a cursor but that's just horrid so I shan't give an example :)

Change the encoding of a file in Visual Studio Code

So here's how to do that:

In the bottom bar of VSCode, you'll see the label UTF-8. Click it. A popup opens. Click Save with encoding. You can now pick a new encoding for that file.

Alternatively, you can change the setting globally in Workspace/User settings using the setting "files.encoding": "utf8". If using the graphical settings page in VSCode, simply search for encoding. Do note however that this only applies to newly created files.

Can I open a dropdownlist using jQuery

You can easily simulate a click on an element, but a click on a <select> won’t open up the dropdown.

Using multiple selects can be problematic. Perhaps you should consider radio buttons inside a container element which you can expand and contract as needed.

Await operator can only be used within an Async method

You can only use await in an async method, and Main cannot be async.

You'll have to use your own async-compatible context, call Wait on the returned Task in the Main method, or just ignore the returned Task and just block on the call to Read. Note that Wait will wrap any exceptions in an AggregateException.

If you want a good intro, see my async/await intro post.

How to develop Android app completely using python?

To answer your first question: yes it is feasible to develop an android application in pure python, in order to achieve this I suggest you use BeeWare, which is just a suite of python tools, that work together very well and they enable you to develop platform native applications in python.

checkout this video by the creator of BeeWare that perfectly explains and demonstrates it's application

How it works

Android's preferred language of implementation is Java - so if you want to write an Android application in Python, you need to have a way to run your Python code on a Java Virtual Machine. This is what VOC does. VOC is a transpiler - it takes Python source code, compiles it to CPython Bytecode, and then transpiles that bytecode into Java-compatible bytecode. The end result is that your Python source code files are compiled directly to a Java .class file, which can be packaged into an Android application.

VOC also allows you to access native Java objects as if they were Python objects, implement Java interfaces with Python classes, and subclass Java classes with Python classes. Using this, you can write an Android application directly against the native Android APIs.

Once you've written your native Android application, you can use Briefcase to package your Python code as an Android application.

Briefcase is a tool for converting a Python project into a standalone native application. You can package projects for:

  • Mac
  • Windows
  • Linux
  • iPhone/iPad
  • Android
  • AppleTV
  • tvOS.

You can check This native Android Tic Tac Toe app written in Python, using the BeeWare suite. on GitHub

in addition to the BeeWare tools, you'll need to have a JDK and Android SDK installed to test run your application.

and to answer your second question: a good environment can be anything you are comfortable with be it a text editor and a command line, or an IDE, if you're looking for a good python IDE I would suggest you try Pycharm, it has a community edition which is free, and it has a similar environment as android studio, due to to the fact that were made by the same company.

I hope this has been helpful

How to get a variable name as a string in PHP?

You could use get_defined_vars() to find the name of a variable that has the same value as the one you're trying to find the name of. Obviously this will not always work, since different variables often have the same values, but it's the only way I can think of to do this.

Edit: get_defined_vars() doesn't seem to be working correctly, it returns 'var' because $var is used in the function itself. $GLOBALS seems to work so I've changed it to that.

function print_var_name($var) {
    foreach($GLOBALS as $var_name => $value) {
        if ($value === $var) {
            return $var_name;
        }
    }

    return false;
}

Edit: to be clear, there is no good way to do this in PHP, which is probably because you shouldn't have to do it. There are probably better ways of doing what you're trying to do.

How to add a local repo and treat it as a remote repo

It appears that your format is incorrect:

If you want to share a locally created repository, or you want to take contributions from someone elses repository - if you want to interact in any way with a new repository, it's generally easiest to add it as a remote. You do that by running git remote add [alias] [url]. That adds [url] under a local remote named [alias].

#example
$ git remote
$ git remote add github [email protected]:schacon/hw.git
$ git remote -v

http://gitref.org/remotes/#remote

How to return part of string before a certain character?

In General a function to return string after substring is

_x000D_
_x000D_
function getStringAfterSubstring(parentString, substring) {_x000D_
    return parentString.substring(parentString.indexOf(substring) + substring.length)_x000D_
}_x000D_
_x000D_
function getStringBeforeSubstring(parentString, substring) {_x000D_
    return parentString.substring(0, parentString.indexOf(substring))_x000D_
}_x000D_
console.log(getStringAfterSubstring('abcxyz123uvw', '123'))_x000D_
console.log(getStringBeforeSubstring('abcxyz123uvw', '123'))
_x000D_
_x000D_
_x000D_

'No database provider has been configured for this DbContext' on SignInManager.PasswordSignInAsync

I could resolve it by overriding Configuration in MyContext through adding connection string to the DbContextOptionsBuilder:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
            IConfigurationRoot configuration = new ConfigurationBuilder()
               .SetBasePath(Directory.GetCurrentDirectory())
               .AddJsonFile("appsettings.json")
               .Build();
            var connectionString = configuration.GetConnectionString("DbCoreConnectionString");
            optionsBuilder.UseSqlServer(connectionString);
        }
    }

TypeError: 'str' does not support the buffer interface

There is an easier solution to this problem.

You just need to add a t to the mode so it becomes wt. This causes Python to open the file as a text file and not binary. Then everything will just work.

The complete program becomes this:

plaintext = input("Please enter the text you want to compress")
filename = input("Please enter the desired filename")
with gzip.open(filename + ".gz", "wt") as outfile:
    outfile.write(plaintext)

Copy table without copying data

Try

CREATE TABLE foo LIKE bar;

so the keys and indexes are copied over as, well.

Documentation

Disable a textbox using CSS

you can disable via css:

pointer-events: none; 

Doesn't work everywhere though.

Starting iPhone app development in Linux?

It seems to be true so far. The only SDK available from Apple only targets the macOS environment. I've been upset about that, but I'm looking into buying a mac now, just to do iPhone development. I really dislike what they are doing, and I hope a good SDK come out for other environments, such as Linux and Windows.

Obstacles regarding the SDK:

The iPhone SDK and free software: not a match

Apple's recently released a software development kit (SDK) for the iPhone, but if you were hoping to port or develop original open source software with it, the news isn't good. Code signing and nondisclosure conditions make free software a no-go.

The SDK itself is a free download, with which you can write programs and run them on a software simulator. But in order to actually release software you've written, you must enroll in the iPhone Developer Program -- a step separate from downloading the SDK, and one that requires Apple's approval.

I think it's rather elitist for them to think only macOS users are good enough to write programs for their phone, and the fact you need to buy a $100 license if you want to publish your stuff, really makes it more difficult for the hobbyist programmer. Though, if that's what you need to do, I'm planning on jumping through their hoops; I'd really like to get some stuff developed on my iPhone.

Liquibase lock - reasons?

In postgres 12 I needed to use this command:

UPDATE DATABASECHANGELOGLOCK SET LOCKED=false, LOCKGRANTED=null, LOCKEDBY=null where ID=1;

How to access global variables

I create a file dif.go that contains your code:

package dif

import (
    "time"
)

var StartTime = time.Now()

Outside the folder I create my main.go, it is ok!

package main

import (
    dif "./dif"
    "fmt"
)

func main() {
    fmt.Println(dif.StartTime)
}

Outputs:

2016-01-27 21:56:47.729019925 +0800 CST

Files directory structure:

folder
  main.go
  dif
    dif.go

It works!

How to place the cursor (auto focus) in text box when a page gets loaded without javascript support?

Ya its possible to do without support of javascript..
We can use html5 auto focus attribute
For Example:

<input type="text" name="name" autofocus="autofocus" id="xax" />

If use it (autofocus="autofocus") in text field means that text field get focused when page gets loaded.. For more details:
http://www.hscripts.com/tutorials/html5/autofocus-attribute.html

Javascript (+) sign concatenates instead of giving sum of variables

Care must be taken that i is an integer type of variable. In javaScript we don't specify the datatype during declaration of variables, but our initialisation can guarantee that our variable is of a specific datatype.

It is a good practice to initialize variables of declaration:

  • In case of integers, var num = 0;
  • In case of strings, var str = "";

Even if your i variable is integer, + operator can perform concatenation instead of addition.

In your problem's case, you have supposed that i = 1, in order to get 2 in addition with 1 try using (i-1+2). Use of ()-parenthesis will not be necessary.

- (minus operator) cannot be misunderstood and you will not get unexpected result/s.

WiX tricks and tips

Using the Msi Diagnostic logging to get detailed failure Information

msiexec /i Package.msi /l*v c:\Package.log

Where

Package.msi
is the name of your package and
c:\Package.log
is where you want the output of the log

Msi Error Codes

Wix Intro Video
Oh and Random Wix intro video featuring "Mr. WiX" Rob Mensching is "conceptual big picture" helpful.

WebDriverException: unknown error: DevToolsActivePort file doesn't exist while trying to initiate Chrome Browser

update capabilities in conf.js as

exports.config = {
  seleniumAddress: 'http://localhost:4444/wd/hub',
  specs: ['todo-spec.js'],
  capabilities: {
    browserName: 'chrome',
    chromeOptions: {
      args: ['--disable-gpu', '--no-sandbox', '--disable-extensions', '--disable-dev-shm-usage']
    }
  },

};

C++ vector of char array

You need

char test[] = "abcde";  // This will add a terminating \0 character to the array
std::vector<std::string> v;
v.push_back(test);

Of if you meant to make a vector of character instead of a vector of strings,

std::vector<char> v(test, test + sizeof(test)/sizeof(*test));

The expression sizeof(test)/sizeof(*test) is for calculating the number of elements in the array test.

"Expected BEGIN_OBJECT but was STRING at line 1 column 1"

if your json format and variables are okay then check your database queries...even if data is saved in db correctly the actual problem might be in there...recheck your queries and try again.. Hope it helps

How to stop C++ console application from exiting immediately?

I just do this:

//clear buffer, wait for input to close program
std::cin.clear(); std::cin.ignore(INT_MAX, '\n');
std::cin.get();
return 0;

Note: clearing the cin buffer and such is only necessary if you've used cin at some point earlier in your program. Also using std::numeric_limits::max() is probably better then INT_MAX, but it's a bit wordy and usually unnecessary.

Java integer to byte array

How about:

public static final byte[] intToByteArray(int value) {
    return new byte[] {
            (byte)(value >>> 24),
            (byte)(value >>> 16),
            (byte)(value >>> 8),
            (byte)value};
}

The idea is not mine. I've taken it from some post on dzone.com.

How can I get just the first row in a result set AFTER ordering?

An alternative way:

SELECT ...
FROM bla
WHERE finalDate = (SELECT MAX(finalDate) FROM bla) AND
      rownum = 1

When is null or undefined used in JavaScript?

I find that some of these answers are vague and complicated, I find the best way to figure out these things for sure is to just open up the console and test it yourself.

var x;

x == null            // true
x == undefined       // true
x === null           // false
x === undefined      // true

var y = null;

y == null            // true
y == undefined       // true
y === null           // true
y === undefined      // false

typeof x             // 'undefined'
typeof y             // 'object'

var z = {abc: null};

z.abc == null        // true
z.abc == undefined   // true
z.abc === null       // true
z.abc === undefined  // false

z.xyz == null        // true
z.xyz == undefined   // true
z.xyz === null       // false
z.xyz === undefined  // true

null = 1;            // throws error: invalid left hand assignment
undefined = 1;       // works fine: this can cause some problems

So this is definitely one of the more subtle nuances of JavaScript. As you can see, you can override the value of undefined, making it somewhat unreliable compared to null. Using the == operator, you can reliably use null and undefined interchangeably as far as I can tell. However, because of the advantage that null cannot be redefined, I might would use it when using ==.

For example, variable != null will ALWAYS return false if variable is equal to either null or undefined, whereas variable != undefined will return false if variable is equal to either null or undefined UNLESS undefined is reassigned beforehand.

You can reliably use the === operator to differentiate between undefined and null, if you need to make sure that a value is actually undefined (rather than null).

According to the ECMAScript 5 spec:

  • Both Null and Undefined are two of the six built in types.

4.3.9 undefined value

primitive value used when a variable has not been assigned a value

4.3.11 null value

primitive value that represents the intentional absence of any object value

Download image from the site in .NET/C#

Also possible to use DownloadData method

    private byte[] GetImage(string iconPath)
    {
        using (WebClient client = new WebClient())
        {
            byte[] pic = client.DownloadData(iconPath);
            //string checkPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) +@"\1.png";
            //File.WriteAllBytes(checkPath, pic);
            return pic;
        }
    }

IntelliJ IDEA generating serialVersionUID

In addition you can add live template that will do the work.

To do it press Ctrl+Alt+S -> "Live Templates" section -> other (or w/e you wish)

And then create a new one with a definition like this:

private static final long serialVersionUID = 1L;
$END$

Then select definition scope and save it as 'serial'

Now you can type serialTAB in class body.

PostgreSQL - query from bash script as database user 'postgres'

Try this one:

#!/bin/bash
psql -U postgres -d database_name -c "SELECT c_defaults  FROM user_info WHERE c_uid = 'testuser'"

Or using su:

#!/bin/bash
su -c "psql -d database_name -c \"SELECT c_defaults  FROM user_info WHERE c_uid = 'testuser'\"" postgres

And also sudo:

#!/bin/bash
sudo -u postgres -H -- psql -d database_name -c "SELECT c_defaults  FROM user_info WHERE c_uid = 'testuser'"

How to truncate float values?

n = 1.923328437452
str(n)[:4]

Chrome not rendering SVG referenced via <img> tag

I came here because I had a similar problem, the image was not being rendered. What I found out was that the content type header of my testing server wasn't correct. I fixed it by adding the following to my .htaccess file:

AddType image/svg+xml svg svgz
AddEncoding gzip svgz

Find all files with name containing string

Use find:

find . -maxdepth 1 -name "*string*" -print

It will find all files in the current directory (delete maxdepth 1 if you want it recursive) containing "string" and will print it on the screen.

If you want to avoid file containing ':', you can type:

find . -maxdepth 1 -name "*string*" ! -name "*:*" -print

If you want to use grep (but I think it's not necessary as far as you don't want to check file content) you can use:

ls | grep touch

But, I repeat, find is a better and cleaner solution for your task.

How can I make an entire HTML form "readonly"?

You add html invisible layer over the form. For instance

<div class="coverContainer">
<form></form>
</div>

and style:

.coverContainer{
    width: 100%;
    height: 100%;
    z-index: 100;
    background: rgba(0,0,0,0);
    position: absolute;
}

Ofcourse user can hide this layer in web browser.

C# declare empty string array

Your syntax is wrong:

string[] arr = new string[]{};

or

string[] arr = new string[0];

Fastest way to download a GitHub project

Another faster way of downloading a GitHub project would be to use the clone functionality with the --depth argument as:

git clone --depth=1 [email protected]:organization/your-repo.git

to perform a shallow clone.

How can I make the computer beep in C#?

In .Net 2.0, you can use Console.Beep().

// Default beep
Console.Beep();

You can also specify the frequency and length of the beep in milliseconds.

// Beep at 5000 Hz for 1 second
Console.Beep(5000, 1000);

For more information refer http://msdn.microsoft.com/en-us/library/8hftfeyw%28v=vs.110%29.aspx

Invalid postback or callback argument. Event validation is enabled using '<pages enableEventValidation="true"/>'

Four minutes ago I received the same error. Then I have researched during one half hour like you. In all forums they are generally saying "add page enableEvent..=false or true". Any solution proposed didn't resolved my problems until I found it. The problem is unfortunately an ASP.NET button. I removed it two seconds ago. I tried to replace with "imagebutton", but it was also unacceptable (because it gave the same error).

Finally I have replaced with LinkButton. it seems to be working!

Groovy String to Date

Googling around for Groovy ways to "cast" a String to a Date, I came across this article: http://www.goodercode.com/wp/intercept-method-calls-groovy-type-conversion/

The author uses Groovy metaMethods to allow dynamically extending the behavior of any class' asType method. Here is the code from the website.

class Convert {
    private from
    private to

    private Convert(clazz) { from = clazz }
    static def from(clazz) {
        new Convert(clazz)
    }

    def to(clazz) {
        to = clazz
        return this
    }

    def using(closure) {
        def originalAsType = from.metaClass.getMetaMethod('asType', [] as Class[])
        from.metaClass.asType = { Class clazz ->
            if( clazz == to ) {
                closure.setProperty('value', delegate)
                closure(delegate)
            } else {
                originalAsType.doMethodInvoke(delegate, clazz)
            }
        }
    }
}

They provide a Convert class that wraps the Groovy complexity, making it trivial to add custom as-based type conversion from any type to any other:

Convert.from( String ).to( Date ).using { new java.text.SimpleDateFormat('MM-dd-yyyy').parse(value) }

def christmas = '12-25-2010' as Date

It's a convenient and powerful solution, but I wouldn't recommend it to someone who isn't familiar with the tradeoffs and pitfalls of tinkering with metaClasses.

adding multiple event listeners to one element

_x000D_
_x000D_
document.getElementById('first').addEventListener('touchstart',myFunction);_x000D_
_x000D_
document.getElementById('first').addEventListener('click',myFunction);_x000D_
    _x000D_
function myFunction(e){_x000D_
  e.preventDefault();e.stopPropagation()_x000D_
  do_something();_x000D_
}    
_x000D_
_x000D_
_x000D_

You should be using e.stopPropagation() because if not, your function will fired twice on mobile

Loop Through Each HTML Table Column and Get the Data using jQuery

try this

    $("#mprDetailDataTable tr:gt(0)").each(function () {
        var this_row = $(this);
        var productId = $.trim(this_row.find('td:eq(0)').html());//td:eq(0) means first td of this row
        var product = $.trim(this_row.find('td:eq(1)').html())
        var Quantity = $.trim(this_row.find('td:eq(2)').html())
    });

Convert nullable bool? to bool

If you're going to use the bool? in an if statement, I find the easiest thing to do is to compare against either true or false.

bool? b = ...;

if (b == true) { Debug.WriteLine("true"; }
if (b == false) { Debug.WriteLine("false"; }
if (b != true) { Debug.WriteLine("false or null"; }
if (b != false) { Debug.WriteLine("true or null"; }

Of course, you can also compare against null as well.

bool? b = ...;

if (b == null) { Debug.WriteLine("null"; }
if (b != null) { Debug.WriteLine("true or false"; }
if (b.HasValue) { Debug.WriteLine("true or false"; }
//HasValue and != null will ALWAYS return the same value, so use whatever you like.

If you're going to convert it to a bool to pass on to other parts of the application, then the Null Coalesce operator is what you want.

bool? b = ...;
bool b2 = b ?? true; // null becomes true
b2 = b ?? false; // null becomes false

If you've already checked for null, and you just want the value, then access the Value property.

bool? b = ...;
if(b == null)
    throw new ArgumentNullException();
else
    SomeFunc(b.Value);

Laravel back button

You can use javascript for this provblem. It's retrieve link from browser history.

_x000D_
_x000D_
<script>_x000D_
function goBack() {_x000D_
  window.history.back();_x000D_
}_x000D_
</script>
_x000D_
<button onclick="goBack()">Go Back</button>
_x000D_
_x000D_
_x000D_

'Source code does not match the bytecode' when debugging on a device

Android Studio takes source version equal to Target Version in your application. Compilation performed with source version equal to above mentioned Compile Version. So, take care that in your project Compile Version == Target Version (adjust module's build.gradle file).

how to add background image to activity?

We can easily place the background image in PercentFrameLayout using the ImageView. We have to set the scaleType attribute value="fitXY" and in the foreground we can also display other view's like textview or button.

 <android.support.percent.PercentFrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        >
        <ImageView
            android:src="@drawable/logo"
            android:id="@+id/im1"
            android:scaleType="fitXY"
            android:layout_height="match_parent"
            android:layout_width="match_parent"/>
<EditText android:layout_gravity="center_horizontal"
        android:hint="Enter Username"
        android:id="@+id/et1"
        android:layout_height="wrap_content"
        app:layout_widthPercent="50%"
        app:layout_marginTopPercent="30%"
        />
<Button
    android:layout_gravity="center_horizontal"
    android:text="Login"
    android:id="@+id/b1"
    android:layout_height="wrap_content"
    app:layout_widthPercent="50%"
    app:layout_marginTopPercent="40%"/>
</android.support.percent.PercentFrameLayout>

Get a list of resources from classpath directory

The most robust mechanism for listing all resources in the classpath is currently to use this pattern with ClassGraph, because it handles the widest possible array of classpath specification mechanisms, including the new JPMS module system. (I am the author of ClassGraph.)

List<String> resourceNames;
try (ScanResult scanResult = new ClassGraph().whitelistPaths("x/y/z").scan()) {
    resourceNames = scanResult.getAllResources().getNames();
}

How do I parse JSON with Objective-C?

With the perspective of the OS X v10.7 and iOS 5 launches, probably the first thing to recommend now is NSJSONSerialization, Apple's supplied JSON parser. Use third-party options only as a fallback if you find that class unavailable at runtime.

So, for example:

NSData *returnedData = ...JSON data, probably from a web request...

// probably check here that returnedData isn't nil; attempting
// NSJSONSerialization with nil data raises an exception, and who
// knows how your third-party library intends to react?

if(NSClassFromString(@"NSJSONSerialization"))
{
    NSError *error = nil;
    id object = [NSJSONSerialization
                      JSONObjectWithData:returnedData
                      options:0
                      error:&error];

    if(error) { /* JSON was malformed, act appropriately here */ }

    // the originating poster wants to deal with dictionaries;
    // assuming you do too then something like this is the first
    // validation step:
    if([object isKindOfClass:[NSDictionary class]])
    {
        NSDictionary *results = object;
        /* proceed with results as you like; the assignment to
        an explicit NSDictionary * is artificial step to get 
        compile-time checking from here on down (and better autocompletion
        when editing). You could have just made object an NSDictionary *
        in the first place but stylistically you might prefer to keep
        the question of type open until it's confirmed */
    }
    else
    {
        /* there's no guarantee that the outermost object in a JSON
        packet will be a dictionary; if we get here then it wasn't,
        so 'object' shouldn't be treated as an NSDictionary; probably
        you need to report a suitable error condition */
    }
}
else
{
    // the user is using iOS 4; we'll need to use a third-party solution.
    // If you don't intend to support iOS 4 then get rid of this entire
    // conditional and just jump straight to
    // NSError *error = nil;
    // [NSJSONSerialization JSONObjectWithData:...
}

https connection using CURL from command line

Simple solution

That's my everyday script:

curl --insecure -v https://www.google.com 2>&1 | awk 'BEGIN { cert=0 } /^\* Server certificate:/ { cert=1 } /^\*/ { if (cert) print }'

Output:

* Server certificate:
*    subject: C=US; ST=California; L=Mountain View; O=Google Inc; CN=www.google.com
*    start date: 2016-01-07 11:34:33 GMT
*    expire date: 2016-04-06 00:00:00 GMT
*    issuer: C=US; O=Google Inc; CN=Google Internet Authority G2
*    SSL certificate verify ok.
* Server GFE/2.0 is not blacklisted
* Connection #0 to host www.google.com left intact

JavaScript - Get Browser Height

I prefer the way I just figured out... No JS... 100% HTML & CSS:

(Will center it perfectly in the middle, regardless of the content size.

HTML FILE

<html><head>
<link href="jane.css" rel="stylesheet" />
</head>
<body>
<table id="container">
<tr>
<td id="centerpiece">
123
</td></tr></table>
</body></html>

CSS FILE

#container{
    border:0;
    width:100%;
    height:100%;
}
#centerpiece{
    vertical-align:middle;
    text-align:center;
}

for centering images / div's held within the td, you may wish to try margin:auto; and specify a div dimension instead. -Though, saying that... the 'text-align' property will align much more than just a simple text element.

What is the simplest way to get indented XML with line breaks from XmlDocument?

As adapted from Erika Ehrli's blog, this should do it:

XmlDocument doc = new XmlDocument();
doc.LoadXml("<item><name>wrench</name></item>");
// Save the document to a file and auto-indent the output.
using (XmlTextWriter writer = new XmlTextWriter("data.xml", null)) {
    writer.Formatting = Formatting.Indented;
    doc.Save(writer);
}

Resize image proportionally with MaxHeight and MaxWidth constraints

Working Solution :

For Resize image with size lower then 100Kb

WriteableBitmap bitmap = new WriteableBitmap(140,140);
bitmap.SetSource(dlg.File.OpenRead());
image1.Source = bitmap;

Image img = new Image();
img.Source = bitmap;
WriteableBitmap i;

do
{
    ScaleTransform st = new ScaleTransform();
    st.ScaleX = 0.3;
    st.ScaleY = 0.3;
    i = new WriteableBitmap(img, st);
    img.Source = i;
} while (i.Pixels.Length / 1024 > 100);

More Reference at http://net4attack.blogspot.com/

How do I manage conflicts with git submodules?

I struggled a bit with the answers on this question and didn't have much luck with the answers in a similar SO post either. So this is what worked for me - bearing in mind that in my case, the submodule was maintained by a different team, so the conflict came from different submodule versions in master and my local branch of the project I was working on:

  1. Run git status - make a note of the submodule folder with conflicts
  2. Reset the submodule to the version that was last committed in the current branch:

    git reset HEAD path/to/submodule

  3. At this point, you have a conflict-free version of your submodule which you can now update to the latest version in the submodule's repository:

    cd path/to/submodule
    git submodule foreach git pull origin SUBMODULE-BRANCH-NAME
  4. And now you can commit that and get back to work.

How to store images in mysql database using php

I found the answer, For those who are looking for the same thing here is how I did it. You should not consider uploading images to the database instead you can store the name of the uploaded file in your database and then retrieve the file name and use it where ever you want to display the image.

HTML CODE

<input type="file" name="imageUpload" id="imageUpload">

PHP CODE

if(isset($_POST['submit'])) {

    //Process the image that is uploaded by the user

    $target_dir = "uploads/";
    $target_file = $target_dir . basename($_FILES["imageUpload"]["name"]);
    $uploadOk = 1;
    $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);

    if (move_uploaded_file($_FILES["imageUpload"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["imageUpload"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }

    $image=basename( $_FILES["imageUpload"]["name"],".jpg"); // used to store the filename in a variable

    //storind the data in your database
    $query= "INSERT INTO items VALUES ('$id','$title','$description','$price','$value','$contact','$image')";
    mysql_query($query);

    require('heading.php');
    echo "Your add has been submited, you will be redirected to your account page in 3 seconds....";
    header( "Refresh:3; url=account.php", true, 303);
}

CODE TO DISPLAY THE IMAGE

while($row = mysql_fetch_row($result)) {
    echo "<tr>";
    echo "<td><img src='uploads/$row[6].jpg' height='150px' width='300px'></td>";
    echo "</tr>\n";
}

How can I have Github on my own server?

If you must have GitHub, there is the enterprise version as already mentioned.

If you want to look for alternatives for running a central git server for your company, you can try Gitolite.

https://github.com/sitaramc/gitolite
https://github.com/sitaramc/gitolite/wiki/

Understanding __getitem__ method

The magic method __getitem__ is basically used for accessing list items, dictionary entries, array elements etc. It is very useful for a quick lookup of instance attributes.

Here I am showing this with an example class Person that can be instantiated by 'name', 'age', and 'dob' (date of birth). The __getitem__ method is written in a way that one can access the indexed instance attributes, such as first or last name, day, month or year of the dob, etc.

import copy

# Constants that can be used to index date of birth's Date-Month-Year
D = 0; M = 1; Y = -1

class Person(object):
    def __init__(self, name, age, dob):
        self.name = name
        self.age = age
        self.dob = dob

    def __getitem__(self, indx):
        print ("Calling __getitem__")
        p = copy.copy(self)

        p.name = p.name.split(" ")[indx]
        p.dob = p.dob[indx] # or, p.dob = p.dob.__getitem__(indx)
        return p

Suppose one user input is as follows:

p = Person(name = 'Jonab Gutu', age = 20, dob=(1, 1, 1999))

With the help of __getitem__ method, the user can access the indexed attributes. e.g.,

print p[0].name # print first (or last) name
print p[Y].dob  # print (Date or Month or ) Year of the 'date of birth'

C++ catching all exceptions

  1. Can you run your JNI-using Java application from a console window (launch it from a java command line) to see if there is any report of what may have been detected before the JVM was crashed. When running directly as a Java window application, you may be missing messages that would appear if you ran from a console window instead.

  2. Secondly, can you stub your JNI DLL implementation to show that methods in your DLL are being entered from JNI, you are returning properly, etc?

  3. Just in case the problem is with an incorrect use of one of the JNI-interface methods from the C++ code, have you verified that some simple JNI examples compile and work with your setup? I'm thinking in particular of using the JNI-interface methods for converting parameters to native C++ formats and turning function results into Java types. It is useful to stub those to make sure that the data conversions are working and you are not going haywire in the COM-like calls into the JNI interface.

  4. There are other things to check, but it is hard to suggest any without knowing more about what your native Java methods are and what the JNI implementation of them is trying to do. It is not clear that catching an exception from the C++ code level is related to your problem. (You can use the JNI interface to rethrow the exception as a Java one, but it is not clear from what you provide that this is going to help.)

Switching a DIV background image with jQuery

I did mine using regular expressions, since I wanted to preserve a relative path and not use add the addClass function. I just wanted to make it convoluted, lol.

$(".travelinfo-btn").click(
            function() {
                $("html, body").animate({scrollTop: $(this).offset().top}, 200);
                var bgImg = $(this).css('background-image')
                var bgPath = bgImg.substr(0, bgImg.lastIndexOf('/')+1)
                if(bgImg.match(/collapse/)) {
                    $(this).stop().css('background-image', bgImg.replace(/collapse/,'expand'));
                    $(this).next(".travelinfo-item").stop().slideToggle(400);
                } else {
                    $(this).stop().css('background-image', bgImg.replace(/expand/,'collapse'));
                    $(this).next(".travelinfo-item").stop().slideToggle(400);
                }
            }
        );

How to convert a private key to an RSA private key?

To Convert BEGIN OPENSSH PRIVATE KEY to BEGIN RSA PRIVATE KEY:

ssh-keygen -p -m PEM -f ~/.ssh/id_rsa

How do I share a global variable between c files?

using extern <variable type> <variable name> in a header or another C file.

Disable clipboard prompt in Excel VBA on workbook close

I have hit this problem in the past - from the look of it if you don't actually need the clipboard at the point that you exit, so you can use the same simple solution I had. Just clear the clipboard. :)

ActiveCell.Copy

Sort matrix according to first column in R

Be aware that if you want to have values in the reverse order, you can easily do so:

> example = matrix(c(1,1,1,4,3,3,2,349,393,392,459,49,32,94), ncol = 2)
> example[order(example[,1], decreasing = TRUE),]
     [,1] [,2]
[1,]    4  459
[2,]    3   49
[3,]    3   32
[4,]    2   94
[5,]    1  349
[6,]    1  393
[7,]    1  392

mysqld_safe Directory '/var/run/mysqld' for UNIX socket file don't exists

When I used the code mysqld_safe --skip-grant-tables & but I get the error:

mysqld_safe Directory '/var/run/mysqld' for UNIX socket file don't exists.

$ systemctl stop  mysql.service
$ ps -eaf|grep mysql
$ mysqld_safe --skip-grant-tables &

I solved:

$ mkdir -p /var/run/mysqld
$ chown mysql:mysql /var/run/mysqld

Now I use the same code mysqld_safe --skip-grant-tables & and get

mysqld_safe Starting mysqld daemon with databases from /var/lib/mysql

If I use $ mysql -u root I'll get :

Server version: 5.7.18-0ubuntu0.16.04.1 (Ubuntu)

Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>

Now time to change password:

mysql> use mysql
mysql> describe user;

Reading table information for completion of table and column names You can turn off this feature to get a quicker startup with -A

Database changed

mysql> FLUSH PRIVILEGES;
mysql> SET PASSWORD FOR root@'localhost' = PASSWORD('newpwd');

or If you have a mysql root account that can connect from everywhere, you should also do:

UPDATE mysql.user SET Password=PASSWORD('newpwd') WHERE User='root';

Alternate Method:

   USE mysql
   UPDATE user SET Password = PASSWORD('newpwd')
   WHERE Host = 'localhost' AND User = 'root';

And if you have a root account that can access from everywhere:

 USE mysql
 UPDATE user SET Password = PASSWORD('newpwd')
 WHERE Host = '%' AND User = 'root';`enter code here

now need to quit from mysql and stop/start

FLUSH PRIVILEGES;
sudo /etc/init.d/mysql stop
sudo /etc/init.d/mysql start

now again ` mysql -u root -p' and use the new password to get

mysql>

HTML 5 video recording and storing a stream

The followin example shows how to capture and process video frames in HTML5:

_x000D_
_x000D_
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Capturing & Processing Video in HTML5</title>
</head>
<body>
    <div>
        <h2>Camera Preview</h2>
        <video id="cameraPreview" width="240" height="180" autoplay></video>
        <p>
            <button id="startButton" onclick="startCapture();">Start Capture</button>
            <button id="stopButton" onclick="stopCapture();">Stop Capture</button>
        </p>
    </div>

    <div>
        <h2>Processing Preview</h2>
        <canvas id="processingPreview" width="240" height="180"></canvas>
    </div>

    <div>
        <h2>Recording Preview</h2>
        <video id="recordingPreview" width="240" height="180" autoplay controls></video>
        <p>
            <a id="downloadButton">Download</a>
        </p>
    </div>

    <script>

    const ROI_X = 250;
    const ROI_Y = 150;
    const ROI_WIDTH = 240;
    const ROI_HEIGHT = 180;
    
    const FPS = 25;
    
    let cameraStream = null;
    let processingStream = null;
    let mediaRecorder = null;
    let mediaChunks = null;
    let processingPreviewIntervalId = null;

    function processFrame() {
        let cameraPreview = document.getElementById("cameraPreview");
        
        processingPreview
            .getContext('2d')
            .drawImage(cameraPreview, ROI_X, ROI_Y, ROI_WIDTH, ROI_HEIGHT, 0, 0, ROI_WIDTH, ROI_HEIGHT);
    }
    
    function generateRecordingPreview() {
        let mediaBlob = new Blob(mediaChunks, { type: "video/webm" });
        let mediaBlobUrl = URL.createObjectURL(mediaBlob);
        
        let recordingPreview = document.getElementById("recordingPreview");
        recordingPreview.src = mediaBlobUrl;

        let downloadButton = document.getElementById("downloadButton");
        downloadButton.href = mediaBlobUrl;
        downloadButton.download = "RecordedVideo.webm";
    }
        
    function startCapture() {
        const constraints = { video: true, audio: false };
        navigator.mediaDevices.getUserMedia(constraints)
        .then((stream) => {
            cameraStream = stream;
            
            let processingPreview = document.getElementById("processingPreview");
            processingStream = processingPreview.captureStream(FPS);
            
            mediaRecorder = new MediaRecorder(processingStream);
            mediaChunks = []
            
            mediaRecorder.ondataavailable = function(event) {
                mediaChunks.push(event.data);
                if(mediaRecorder.state == "inactive") {
                    generateRecordingPreview();
                }
            };
            
            mediaRecorder.start();
            
            let cameraPreview = document.getElementById("cameraPreview");
            cameraPreview.srcObject = stream;
        
            processingPreviewIntervalId = setInterval(processFrame, 1000 / FPS);
        })
        .catch((err) => {
            alert("No media device found!");
        });
    };
    
    function stopCapture() {
        if(cameraStream != null) {
            cameraStream.getTracks().forEach(function(track) {
                track.stop();
            });
        }
        
        if(processingStream != null) {
            processingStream.getTracks().forEach(function(track) {
                track.stop();
            });
        }
        
        if(mediaRecorder != null) {
            if(mediaRecorder.state == "recording") {
                mediaRecorder.stop();
            }
        }
        
        if(processingPreviewIntervalId != null) {
            clearInterval(processingPreviewIntervalId);
            processingPreviewIntervalId = null;
        }
    };
    </script>
</body>
</html>
_x000D_
_x000D_
_x000D_

How to force a html5 form validation without submitting it via jQuery

To check all the required fields of form without using submit button you can use below function.

You have to assign required attribute to the controls.

  $("#btnSave").click(function () {
    $(":input[required]").each(function () {                     
        var myForm = $('#form1');
        if (!$myForm[0].checkValidity()) 
          {                
            $(myForm).submit();              
          }
        });
  });

Best practice to validate null and empty collection in Java

If you use Spring frameworks, then you can use CollectionUtils to check against both Collections (List, Array) and Map etc.

if(CollectionUtils.isEmpty(...)) {...}

How do I use installed packages in PyCharm?

Download anaconda https://anaconda.org/

once done installing anaconda...

Go into Settings -> Project Settings -> Project Interpreter.

Then navigate to the "Paths" tab and search for /anaconda/bin/python

click apply

enter image description here

Client to send SOAP request and receive response

I got this simple solution here:

Sending SOAP request and receiving response in .NET 4.0 C# without using the WSDL or proxy classes:

class Program
    {
        /// <summary>
        /// Execute a Soap WebService call
        /// </summary>
        public static void Execute()
        {
            HttpWebRequest request = CreateWebRequest();
            XmlDocument soapEnvelopeXml = new XmlDocument();
            soapEnvelopeXml.LoadXml(@"<?xml version=""1.0"" encoding=""utf-8""?>
                <soap:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"">
                  <soap:Body>
                    <HelloWorld xmlns=""http://tempuri.org/"" />
                  </soap:Body>
                </soap:Envelope>");

            using (Stream stream = request.GetRequestStream())
            {
                soapEnvelopeXml.Save(stream);
            }

            using (WebResponse response = request.GetResponse())
            {
                using (StreamReader rd = new StreamReader(response.GetResponseStream()))
                {
                    string soapResult = rd.ReadToEnd();
                    Console.WriteLine(soapResult);
                }
            }
        }
        /// <summary>
        /// Create a soap webrequest to [Url]
        /// </summary>
        /// <returns></returns>
        public static HttpWebRequest CreateWebRequest()
        {
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(@"http://localhost:56405/WebService1.asmx?op=HelloWorld");
            webRequest.Headers.Add(@"SOAP:Action");
            webRequest.ContentType = "text/xml;charset=\"utf-8\"";
            webRequest.Accept = "text/xml";
            webRequest.Method = "POST";
            return webRequest;
        }

        static void Main(string[] args)
        {
            Execute();
        }
    }

Programmatically go back to the previous fragment in the backstack

By adding fragment_tran.addToBackStack(null) on last fragment, I am able to do come back on last fragment.

adding new fragment:

view.findViewById(R.id.changepass).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
            transaction.replace(R.id.container, new ChangePassword());
            transaction.addToBackStack(null);
            transaction.commit();
        }
    });

Passing an array using an HTML form hidden element

Either serialize:

$postvalue=array("a","b","c");
<input type="hidden" name="result" value="<?php echo serialize($postvalue); ?>">

on receive: unserialize($_POST['result'])

Or implode:

$postvalue=array("a","b","c");
<input type="hidden" name="result" value="<?php echo implode(',', $postvalue); ?>">

On receive: explode(',', $_POST['result'])

LINQ query on a DataTable

you can try this, but you must be sure the type of values for each Column

List<MyClass> result = myDataTable.AsEnumerable().Select(x=> new MyClass(){
     Property1 = (string)x.Field<string>("ColumnName1"),
     Property2 = (int)x.Field<int>("ColumnName2"),
     Property3 = (bool)x.Field<bool>("ColumnName3"),    
});

Trigger function when date is selected with jQuery UI datepicker

Use the following code:

$(document).ready(function() {
    $('.date-pick').datepicker( {
     onSelect: function(date) {
        alert(date)
     },
    selectWeek: true,
    inline: true,
    startDate: '01/01/2000',
    firstDay: 1,
  });
});

You can adjust the parameters yourself :-)

Display current path in terminal only

If you just want to get the information of current directory, you can type:

pwd

and you don't need to use the Nautilus, or you can use a teamviewer software to remote connect to the computer, you can get everything you want.

How to remove application from app listings on Android Developer Console

There is strictly no service provided yet from Google Store to delete/remove production app and also you can't change production build for best test.

Convert Datetime column from UTC to local time in select statement

Here's a simpler one that takes dst in to account

CREATE FUNCTION [dbo].[UtcToLocal] 
(
    @p_utcDatetime DATETIME 
)
RETURNS DATETIME
AS
BEGIN
    RETURN DATEADD(MINUTE, DATEDIFF(MINUTE, GETUTCDATE(), @p_utcDatetime), GETDATE())
END

Hide particular div onload and then show div after click

At first if you want to hide div element with id = "abc" on load and then toggle between hide and show using a button with id = "btn" then,

$(document).ready(function() {
 $("#abc").hide(); 
  $("#btn").click(function() {
     $("#abc").toggle();
  });
});

Select and display only duplicate records in MySQL

Get a list of all duplicate rows from table:

Select * from TABLE1 where PRIMARY_KEY_COLUMN NOT IN ( SELECT PRIMARY_KEY_COLUMN
FROM TABLE1 
GROUP BY DUP_COLUMN_NAME having (count(*) >= 1))

How can I write data attributes using Angular?

About access

<ol class="viewer-nav">
    <li *ngFor="let section of sections" 
        [attr.data-sectionvalue]="section.value"
        (click)="get_data($event)">
        {{ section.text }}
    </li>  
</ol>

And

get_data(event) {
   console.log(event.target.dataset.sectionvalue)
}

MySQL: How to allow remote connection to mysql

Just F.Y.I I pulled my hair out with this problem for hours.. finally I call my hosting provider and found that in my case using a cloud server that in the control panel for 1and1 they have a secondary firewall that you have to clone and add port 3306. Once added I got straight in..

How to get the size of a range in Excel

The overall dimensions of a range are in its Width and Height properties.

Dim r As Range
Set r = ActiveSheet.Range("A4:H12")

Debug.Print r.Width
Debug.Print r.Height

How to know installed Oracle Client is 32 bit or 64 bit?

For Unix

grep "ARCHITECTURE" $ORACLE_HOME/inventory/ContentsXML/oraclehomeproperties.xml

And the output is:

<PROPERTY NAME="ARCHITECTURE" VAL="64"/> 

For Windows

findstr "ARCHITECTURE" %ORACLE_HOME%\inventory\ContentsXML\oraclehomeproperties.xml

And the output can be:

<PROPERTY NAME="ARCHITECTURE" VAL="64"/>

Intellisense and code suggestion not working in Visual Studio 2012 Ultimate RC

I've just had this happen to me - and (while it was not instantly obvious) it was due to Resharper (R#) being disabled during a licensing issue.

Enabling Resharper fixed this for me!

How to sum up an array of integers in C#

Yes there is. With .NET 3.5:

int sum = arr.Sum();
Console.WriteLine(sum);

If you're not using .NET 3.5 you could do this:

int sum = 0;
Array.ForEach(arr, delegate(int i) { sum += i; });
Console.WriteLine(sum);

How do you format the day of the month to say "11th", "21st" or "23rd" (ordinal indicator)?

The following method can be used to get the formatted string of the date which is passed in to it. It'll format the date to say 1st,2nd,3rd,4th .. using SimpleDateFormat in Java. eg:- 1st of September 2015

public String getFormattedDate(Date date){
            Calendar cal=Calendar.getInstance();
            cal.setTime(date);
            //2nd of march 2015
            int day=cal.get(Calendar.DATE);

            switch (day % 10) {
            case 1:  
                return new SimpleDateFormat("d'st' 'of' MMMM yyyy").format(date);
            case 2:  
                return new SimpleDateFormat("d'nd' 'of' MMMM yyyy").format(date);
            case 3:  
                return new SimpleDateFormat("d'rd' 'of' MMMM yyyy").format(date);
            default: 
                return new SimpleDateFormat("d'th' 'of' MMMM yyyy").format(date);
        }

How to bind inverse boolean properties in WPF?

.Net Core Solution

Handles null situation and does not throw an exception, but returns true if no value is presented; otherwise takes the inputted Boolean and reverses it.

public class BooleanToReverseConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
     => !(bool?) value ?? true;

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
     => !(value as bool?);
}

Xaml

IsEnabled="{Binding IsSuccess Converter={StaticResource BooleanToReverseConverter}}"

App.Xaml I like to put all my converter statics in the app.xaml file so I don't have to redeclare them throughout the windows/pages/controls of the project.

<Application.Resources>
    <converters:BooleanToReverseConverter x:Key="BooleanToReverseConverter"/>
    <local:FauxVM x:Key="VM" />
</Application.Resources>

To be clear converters: is the namespace to the actual class implementation (xmlns:converters="clr-namespace:ProvingGround.Converters").

Facebook Oauth Logout

For Python developers that want to log user out straight from the backend

At the moment I'm writing this, the trick with m.facebook.com no longer works (at least for me) and user is redirected to the mobile FB login page which obviously is not good for UX.

Fortunately, FB PHP SDK has a semi-documented solution (in case the link doesn't lead to getLogoutUrl() function, just search look for it on that page). This is also mentioned in at least one other on StackOverflow: Facebook php SDK getLogoutUrl() problem.

BTW I've just noticed that Zach Greenberg got it right in this question, but I'm adding my answer as a summary for Python developers.

How to execute a command prompt command from python

Taking some inspiration from Daren Thomas's answer (and edit), try this:

proc = subprocess.Popen('dir C:\\', shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
out, err = proc.communicate()

out will now contain the text output.

They key nugget here is that the subprocess module already provides you shell integration with shell=True, so you don't need to call cmd.exe directly.

As a reminder, if you're in Python 3, this is going to be bytes, so you may want to do out.decode() to convert to a string.

Create Directory When Writing To File In Node.js

With node-fs-extra you can do it easily.

Install it

npm install --save fs-extra

Then use the outputFile method. Its documentation says:

Almost the same as writeFile (i.e. it overwrites), except that if the parent directory does not exist, it's created.

You can use it in three ways:

Callback style

const fse = require('fs-extra');

fse.outputFile('tmp/test.txt', 'Hey there!', err => {
  if(err) {
    console.log(err);
  } else {
    console.log('The file was saved!');
  }
})

Using Promises

If you use promises, and I hope so, this is the code:

fse.outputFile('tmp/test.txt', 'Hey there!')
   .then(() => {
       console.log('The file was saved!');
   })
   .catch(err => {
       console.error(err)
   });

Sync version

If you want a sync version, just use this code:

fse.outputFileSync('tmp/test.txt', 'Hey there!')

For a complete reference, check the outputFile documentation and all node-fs-extra supported methods.

How to Generate unique file names in C#

DateTime.Now.Ticks is not safe, Guid.NewGuid() is too ugly, if you need something clean and almost safe (it's not 100% safe for example if you call it 1,000,000 times in 1ms), try:

Math.Abs(Guid.NewGuid().GetHashCode())

By safe I mean safe to be unique when you call it so many times in very short period few ms of time.

How can I render HTML from another file in a React component?

It is common to have components that are only rendering from props. Like this:

class Template extends React.Component{
  render (){
    return <div>this.props.something</div>
  }
}

Then in your upper level component where you have the logic you just import the Template component and pass the needed props. All your logic stays in the higher level component, and the Template only renders. This is a possible way to achieve 'templates' like in Angular.

There is no way to have .jsx file with jsx only and use it in React because jsx is not really html but markup for a virtual DOM, which React manages.

Python - converting a string of numbers into a list of int

number_string = '0, 0, 0, 11, 0, 0, 0, 0, 0, 19, 0, 9, 0, 0, 0, 0, 0, 0, 11'

number_string = number_string.split(',')

number_string = [int(i) for i in number_string]

How can I merge the columns from two tables into one output?

I had a similar problem with a small difference: some a.category_id are not in b and some b.category_id are not in a.
To solve this problem just adapt the excelent answer from beny23 to

select a.col1, b.col2, a.col3, b.col4, a.category_id 
from items_a a
LEFT OUTER JOIN
items_b b 
on a.category_id = b.category_id

Hope this helps someone.
Regards.

Waiting till the async task finish its work

Although optimally it would be nice if your code can run parallel, it can be the case you're simply using a thread so you do not block the UI thread, even if your app's usage flow will have to wait for it.

You've got pretty much 2 options here;

  1. You can execute the code you want waiting, in the AsyncTask itself. If it has to do with updating the UI(thread), you can use the onPostExecute method. This gets called automatically when your background work is done.

  2. If you for some reason are forced to do it in the Activity/Fragment/Whatever, you can also just make yourself a custom listener, which you broadcast from your AsyncTask. By using this, you can have a callback method in your Activity/Fragment/Whatever which only gets called when you want it: aka when your AsyncTask is done with whatever you had to wait for.

Linq filter List<string> where it contains a string value from another List<string>

Try the following:

var filteredFileSet = fileList.Where(item => filterList.Contains(item));

When you iterate over filteredFileSet (See LINQ Execution) it will consist of a set of IEnumberable values. This is based on the Where Operator checking to ensure that items within the fileList data set are contained within the filterList set.

As fileList is an IEnumerable set of string values, you can pass the 'item' value directly into the Contains method.

What is the size of an enum in C?

Taken from the current C Standard (C99): http://www.open-std.org/JTC1/SC22/WG14/www/docs/n1256.pdf

6.7.2.2 Enumeration specifiers
[...]
Constraints
The expression that defines the value of an enumeration constant shall be an integer constant expression that has a value representable as an int.
[...]
Each enumerated type shall be compatible with char, a signed integer type, or an unsigned integer type. The choice of type is implementation-defined, but shall be capable of representing the values of all the members of the enumeration.

Not that compilers are any good at following the standard, but essentially: If your enum holds anything else than an int, you're in deep "unsupported behavior that may come back biting you in a year or two" territory.

Update: The latest publicly available draft of the C Standard (C11): http://www.open-std.org/JTC1/SC22/WG14/www/docs/n1570.pdf contains the same clauses. Hence, this answer still holds for C11.

AngularJS $http-post - convert binary to excel file and download

This is how you do it:

  1. Forget IE8/IE9, it is not worth the effort and does not pay the money back.
  2. You need to use the right HTTP header,use Accept to 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' and also you need to put responseType to 'arraybuffer'(ArrayBuffer but set with lowercase).
  3. HTML5 saveAs is used to save the actual data to your wanted format. Note it will still work without adding type in this case.
$http({
    url: 'your/webservice',
    method: 'POST',
    responseType: 'arraybuffer',
    data: json, //this is your json data string
    headers: {
        'Content-type': 'application/json',
        'Accept': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    }
}).success(function(data){
    var blob = new Blob([data], {
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    });
    saveAs(blob, 'File_Name_With_Some_Unique_Id_Time' + '.xlsx');
}).error(function(){
    //Some error log
});

Tip! Don't mix " and ', stick to always use ', in a professional environment you will have to pass js validation for example jshint, same goes for using === and not ==, and so on, but that is another topic :)

I would put the save excel in another service, so you have clean structure and the post is in a proper service of its own. I can make a JS fiddle for you, if you don't get my example working. Then I would also need some json data from you that you use for a full example.

Happy coding.. Eduardo

Split long commands in multiple lines through Windows batch file

The rule for the caret is:

A caret at the line end, appends the next line, the first character of the appended line will be escaped.

You can use the caret multiple times, but the complete line must not exceed the maximum line length of ~8192 characters (Windows XP, Windows Vista, and Windows 7).

echo Test1
echo one ^
two ^
three ^
four^
*
--- Output ---
Test1
one two three four*

echo Test2
echo one & echo two
--- Output ---
Test2
one
two

echo Test3
echo one & ^
echo two
--- Output ---
Test3
one
two

echo Test4
echo one ^
& echo two
--- Output ---
Test4
one & echo two

To suppress the escaping of the next character you can use a redirection.

The redirection has to be just before the caret. But there exist one curiosity with redirection before the caret.

If you place a token at the caret the token is removed.

echo Test5
echo one <nul ^
& echo two
--- Output ---
Test5
one
two


echo Test6
echo one <nul ThisTokenIsLost^
& echo two
--- Output ---
Test6
one
two

And it is also possible to embed line feeds into the string:

setlocal EnableDelayedExpansion
set text=This creates ^

a line feed
echo Test7: %text%
echo Test8: !text!
--- Output ---
Test7: This creates
Test8: This creates
a line feed

The empty line is important for the success. This works only with delayed expansion, else the rest of the line is ignored after the line feed.

It works, because the caret at the line end ignores the next line feed and escapes the next character, even if the next character is also a line feed (carriage returns are always ignored in this phase).

Combine two columns and add into one new column

You don't need to store the column to reference it that way. Try this:

To set up:

CREATE TABLE tbl
  (zipcode text NOT NULL, city text NOT NULL, state text NOT NULL);
INSERT INTO tbl VALUES ('10954', 'Nanuet', 'NY');

We can see we have "the right stuff":

\pset border 2
SELECT * FROM tbl;
+---------+--------+-------+
| zipcode |  city  | state |
+---------+--------+-------+
| 10954   | Nanuet | NY    |
+---------+--------+-------+

Now add a function with the desired "column name" which takes the record type of the table as its only parameter:

CREATE FUNCTION combined(rec tbl)
  RETURNS text
  LANGUAGE SQL
AS $$
  SELECT $1.zipcode || ' - ' || $1.city || ', ' || $1.state;
$$;

This creates a function which can be used as if it were a column of the table, as long as the table name or alias is specified, like this:

SELECT *, tbl.combined FROM tbl;

Which displays like this:

+---------+--------+-------+--------------------+
| zipcode |  city  | state |      combined      |
+---------+--------+-------+--------------------+
| 10954   | Nanuet | NY    | 10954 - Nanuet, NY |
+---------+--------+-------+--------------------+

This works because PostgreSQL checks first for an actual column, but if one is not found, and the identifier is qualified with a relation name or alias, it looks for a function like the above, and runs it with the row as its argument, returning the result as if it were a column. You can even index on such a "generated column" if you want to do so.

Because you're not using extra space in each row for the duplicated data, or firing triggers on all inserts and updates, this can often be faster than the alternatives.

What's the difference between HEAD, working tree and index, in Git?

The difference between HEAD (current branch or last committed state on current branch), index (aka. staging area) and working tree (the state of files in checkout) is described in "The Three States" section of the "1.3 Git Basics" chapter of Pro Git book by Scott Chacon (Creative Commons licensed).

Here is the image illustrating it from this chapter:

Local Operations - working directory vs. staging area (index) vs git repository (HEAD)

In the above image "working directory" is the same as "working tree", the "staging area" is an alternate name for git "index", and HEAD points to currently checked out branch, which tip points to last commit in the "git directory (repository)"

Note that git commit -a would stage changes and commit in one step.

.gitignore and "The following untracked working tree files would be overwritten by checkout"

In my case, the problem was with the submodules. master was merged with another branch which added a new submodule to the project. The branch I was trying to checkout didn't have it, that's why git was complaining about untracked files and none of the other suggested solutions worked for me. I forced the checkout to my new branch, and pulled master.

  • git checkout -f my_branch
  • git pull origin master
  • git submodule update --init

String concatenation with Groovy

def my_string = "some string"
println "here: " + my_string 

Not quite sure why the answer above needs to go into benchmarks, string buffers, tests, etc.

How do I show a running clock in Excel?

See the below code (taken from this post)

Put this code in a Module in VBA (Developer Tab -> Visual Basic)

Dim TimerActive As Boolean
Sub StartTimer()
    Start_Timer
End Sub
Private Sub Start_Timer()
    TimerActive = True
    Application.OnTime Now() + TimeValue("00:01:00"), "Timer"
End Sub
Private Sub Stop_Timer()
    TimerActive = False
End Sub
Private Sub Timer()
    If TimerActive Then
        ActiveSheet.Cells(1, 1).Value = Time
        Application.OnTime Now() + TimeValue("00:01:00"), "Timer"
    End If
End Sub

You can invoke the "StartTimer" function when the workbook opens and have it repeat every minute by adding the below code to your workbooks Visual Basic "This.Workbook" class in the Visual Basic editor.

Private Sub Workbook_Open()
    Module1.StartTimer
End Sub

Now, every time 1 minute passes the Timer procedure will be invoked, and set cell A1 equal to the current time.

Python: avoiding pylint warnings about too many arguments

I came across the same nagging error, which I realized has something to do with a cool feature PyCharm automatically detects...just add the @staticmethod decorator, and it will automatically remove that error where the method is used

Laravel csrf token mismatch for ajax POST Request

The best way to solve this problem "X-CSRF-TOKEN" is to add the following code to your main layout, and continue making your ajax calls normally:

In header

<meta name="csrf-token" content="{{ csrf_token() }}" />

In script

<script type="text/javascript">
$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});
</script>

Multi value Dictionary

Here is an implementation of a single key to multi value map in C# which uses a set based key type:

https://github.com/ColmBhandal/CsharpExtras/blob/master/CsharpExtras/Dictionary/MultiValueMapImpl.cs

The dictionary behaves like a regular dictionary from the key type onto a set of the value type, but also provides functionality to directly add a single value of the value type, and in the background handles the creation of an underlying set and/or addition to that set.

Current date and time - Default in MVC razor

Before you return your model from the controller, set your ReturnDate property to DateTime.Now()

myModel.ReturnDate = DateTime.Now()

return View(myModel)

Your view is not the right place to set values on properties so the controller is the better place for this.

You could even have it so that the getter on ReturnDate returns the current date/time.

private DateTime _returnDate = DateTime.MinValue;
public DateTime ReturnDate{
   get{
     return (_returnDate == DateTime.MinValue)? DateTime.Now() : _returnDate;
   }
   set{_returnDate = value;}
}

How to get the current time in Google spreadsheet using script editor?

Use the Date object provided by javascript. It's not unique or special to Google's scripting environment.

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".

JPA Query.getResultList() - use in a generic way

I had the same problem and a simple solution that I found was:

List<Object[]> results = query.getResultList();
for (Object[] result: results) {
    SomeClass something = (SomeClass)result[1];
    something.doSomething;
}

I know this is defenitly not the most elegant solution nor is it best practice but it works, at least for me.

How do I import a pre-existing Java project into Eclipse and get up and running?

In the menu go to : - File - Import - as the filter select 'Existing Projects into Workspace' - click next - browse to the project directory at 'select root directory' - click on 'finish'

How to copy and paste code without rich text formatting?

If you're pasting into Word you can use the Paste Special command.

How to store token in Local or Session Storage in Angular 2?

import { Injectable,OpaqueToken } from '@angular/core'; export const localStorage = new OpaqueToken('localStorage');

Place these lines in the top of the file, it should resolve the issue.

How to get a web page's source code from Java

URL yahoo = new URL("http://www.yahoo.com/");
BufferedReader in = new BufferedReader(
            new InputStreamReader(
            yahoo.openStream()));

String inputLine;

while ((inputLine = in.readLine()) != null)
    System.out.println(inputLine);

in.close();

Where Sticky Notes are saved in Windows 10 1607

If at all you can't find .snt folder and above mentioned answers don't work for you. you can simply take plum.sqlite file and read it online or sqlite editor.

for online you can refer to http://inloop.github.io/sqlite-viewer/ link and browse the url as C:\Users\YOURUSERNAME\AppData\Local\Packages\Microsoft.MicrosoftStickyNotes_8wekyb3d8bbwe\LocalState

and pick sql lite file and execute it. Post executing select Note and you will find all rows corresponding to each sticky notes you have lost. Select the Text column and copy content, you will find all your data there.

ENJOY !!!! enter image description here

Formula to convert date to number

The Excel number for a modern date is most easily calculated as the number of days since 12/30/1899 on the Gregorian calendar.

Excel treats the mythical date 01/00/1900 (i.e., 12/31/1899) as corresponding to 0, and incorrectly treats year 1900 as a leap year. So for dates before 03/01/1900, the Excel number is effectively the number of days after 12/31/1899.

However, Excel will not format any number below 0 (-1 gives you ##########) and so this only matters for "01/00/1900" to 02/28/1900, making it easier to just use the 12/30/1899 date as a base.

A complete function in DB2 SQL that accounts for the leap year 1900 error:

SELECT
   DAYS(INPUT_DATE)                 
   - DAYS(DATE('1899-12-30'))
   - CASE                       
        WHEN INPUT_DATE < DATE('1900-03-01')  
           THEN 1               
           ELSE 0               
     END

scale Image in an UIButton to AspectFit?

For Xamarin.iOS (C#):

    myButton.VerticalAlignment = UIControlContentVerticalAlignment.Fill;
    myButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Fill;
    myButton.ImageView.ContentMode = UIViewContentMode.ScaleAspectFit;

How can I pass arguments to anonymous functions in JavaScript?

Your specific case can simply be corrected to be working:

<script type="text/javascript">
  var myButton = document.getElementById("myButton");
  var myMessage = "it's working";
  myButton.onclick = function() { alert(myMessage); };
</script>

This example will work because the anonymous function created and assigned as a handler to element will have access to variables defined in the context where it was created.

For the record, a handler (that you assign through setting onxxx property) expects single argument to take that is event object being passed by the DOM, and you cannot force passing other argument in there

Disable EditText blinking cursor

You can use following code for enabling and disabling edit text cursor by programmatically.

To Enable cursor

    editText.requestFocus();
    editText.setCursorVisible(true);

To Disable cursor

    editText.setCursorVisible(false);

Using XML enable disable cursor

   android:cursorVisible="false/true"
   android:focusable="false/true"

To make edit_text Selectable to (copy/cut/paste/select/select all)

   editText.setTextIsSelectable(true);

To focus on touch mode write following lines in XML

  android:focusableInTouchMode="true"
  android:clickable="true"
  android:focusable="true" 

programmatically

  editText.requestFocusFromTouch();

To clear focus on touch mode

  editText.clearFocus()

Python List & for-each access (Find/Replace in built-in list)

Python is not Java, nor C/C++ -- you need to stop thinking that way to really utilize the power of Python.

Python does not have pass-by-value, nor pass-by-reference, but instead uses pass-by-name (or pass-by-object) -- in other words, nearly everything is bound to a name that you can then use (the two obvious exceptions being tuple- and list-indexing).

When you do spam = "green", you have bound the name spam to the string object "green"; if you then do eggs = spam you have not copied anything, you have not made reference pointers; you have simply bound another name, eggs, to the same object ("green" in this case). If you then bind spam to something else (spam = 3.14159) eggs will still be bound to "green".

When a for-loop executes, it takes the name you give it, and binds it in turn to each object in the iterable while running the loop; when you call a function, it takes the names in the function header and binds them to the arguments passed; reassigning a name is actually rebinding a name (it can take a while to absorb this -- it did for me, anyway).

With for-loops utilizing lists, there are two basic ways to assign back to the list:

for i, item in enumerate(some_list):
    some_list[i] = process(item)

or

new_list = []
for item in some_list:
    new_list.append(process(item))
some_list[:] = new_list

Notice the [:] on that last some_list -- it is causing a mutation of some_list's elements (setting the entire thing to new_list's elements) instead of rebinding the name some_list to new_list. Is this important? It depends! If you have other names besides some_list bound to the same list object, and you want them to see the updates, then you need to use the slicing method; if you don't, or if you do not want them to see the updates, then rebind -- some_list = new_list.

"call to undefined function" error when calling class method

you need to call the function like this

$this->assign()

instead of just assign()

How to resolve the "ADB server didn't ACK" error?

On my end, I used Resource Monitor to see which application was still listening to port 5037 after all the Eclipse and adb restart were unsuccessful for me.

Start > All Programs > Accessories > System Tools >
Resource Monitor > Network > Listening Ports

This eventually showed that java.exe was listening to port 5037, hence, preventing adb from doing so. I killed java.exe, immediately start adb (with adb start-server) and received a confirmation that adb was able to start:

android-sdks\platform-tools>adb start-server
* daemon not running. starting it now on port 5037 *
* daemon started successfully *

Why Anaconda does not recognize conda command?

Try setting the file path using (for anaconda3)...

export PATH=~/anaconda3/bin:$PATH

Then check whether it worked with...

conda --version

This worked for me when 'conda' was returning 'command not found'.

Get a list of URLs from a site

I didn't mean to answer my own question but I just thought about running a sitemap generator. First one I found http://www.xml-sitemaps.com has a nice text output. Perfect for my needs.

Error using eclipse for Android - No resource found that matches the given name

If you are an iPhone Developer don't just add your picture (by right clicking then add file...like we do in iPhone). You have to copy and paste the picture in your drawable folder.

CSS "and" and "or"

The :not pseudo-class is not supported by IE. I'd got for something like this instead:

.registration_form_right input[type="text"],
.registration_form_right input[type="password"],
.registration_form_right input[type="submit"],
.registration_form_right input[type="button"] {
  ...
}

Some duplication there, but it's a small price to pay for higher compatibility.