Programs & Examples On #Realloc

C library function for reallocating a dynamically allocated memory region.

how to set mongod --dbpath

sudo mongod --dbpath ~/data

This made it work for me.

C free(): invalid pointer

You can't call free on the pointers returned from strsep. Those are not individually allocated strings, but just pointers into the string s that you've already allocated. When you're done with s altogether, you should free it, but you do not have to do that with the return values of strsep.

error: Libtool library used but 'LIBTOOL' is undefined

In my case on macOS I solved it with:

brew link libtool

Mongodb service won't start

I verified permissions but all was good (mongod:mongod). As I'm working on a large project and from a similar issue in our dev environment where we had a script consuming all available disk space, I could see in the error messages that mongod needs at least 3.7Gb free disk space to run..

I checked my own disk space only to see that less than 2Gb was remaining. After moving / erasing some data I can successfully start mongod again.

Hope this helps ;-)

Unable to create/open lock file: /data/mongod.lock errno:13 Permission denied

I got the same issue when I ran mongod command after installing it on Windows10. I stopped the mongodb service and started it again. Working like a charm

Command to stop mongodb service (in windows): net stop mongodb

Command to start mongodb server: mongod --dbpath PATH_TO_DATA_FOLDER

Couldn't connect to server 127.0.0.1:27017

For future reference,Follow these steps to avoid similar errors:

1.Download MondoDB https://www.mongodb.com/

2.Open a terminal and cd into your downloads folder or whatever folder youve saved your mondodb download(Ensure you extract your mongodb folder before you cd into it)

cd Downloads

3.Move mongodb to your usr/local path

sudo mv mongodb-osx-... /usr/local/mongodb

4.cd into your local folder

cd /usr/local/mongodb

5.make a new directory

sudo mkdir -p /data/db

6.cd into the new directory just created above

cd /data/db

7.give mongo permisions

sudo chown YourMacUserName /data/db

8.Then go/open your .bash_profile

To do so,follow these steps:

In your a new terminal

1.cd 2.pwd 3.ls -l

Check if the .bash_profile appears on your list of files on your terminal

if not create the -bash_profile

Creating .bash_profile:

In your terminal

touch .bash_profile

//skip this step if you already have a .bash_profile

Step8:

Next in your terminal:

open .bash_profile

And in your bash file that pops open add the following:

MONGO_PATH=/usr/local/mongodb
export PATH=$PATH:$MONGO_PATH/bin

And then save.(File Save or command S/CMD+S)

Step9:back in your terminal:

source .bash_profile

Now open two terminals.One will for your mondo daemon the other for your mongo.

Terminal 1: in your terminal type:mongod

mongodb

Output: Mongod Terminal

Terminal 2:

mongo

Output: Mongo terminal

Also make sure you dont make the following typo error when starting your mongod in your terminal: This is incorrect

mongo d

gives off the following error: Failed to connect to 127.0.0.1:27017, in(checking socket for error after poll), reason: Connection refused

This is Correct:

mongod

(There should be no space between the words mongo and d..mondod

Finally always keep in mind that you have to run mondod before you run mongo on your terminals.

Performance differences between ArrayList and LinkedList

ArrayList: The ArrayList class extends AbstractList and implements the List interface and RandomAccess (marker interface). ArrayList supports dynamic arrays that can grow as needed. It gives us first iteration over elements.

LinkedList: A LinkedList is ordered by index position, like ArrayList, except that the elements are doubly-linked to one another. This linkage gives you new methods (beyond what you get from the List interface) for adding and removing from the beginning or end, which makes it an easy choice for implementing a stack or queue. Keep in mind that a LinkedList may iterate more slowly than an ArrayList, but it's a good choice when you need fast insertion and deletion. As of Java 5, the LinkedList class has been enhanced to implement the java.util.Queue interface. As such, it now supports the common queue methods: peek (), poll (), and offer ().

Why are elementwise additions much faster in separate loops than in a combined loop?

OK, the right answer definitely has to do something with the CPU cache. But to use the cache argument can be quite difficult, especially without data.

There are many answers, that led to a lot of discussion, but let's face it: Cache issues can be very complex and are not one dimensional. They depend heavily on the size of the data, so my question was unfair: It turned out to be at a very interesting point in the cache graph.

@Mysticial's answer convinced a lot of people (including me), probably because it was the only one that seemed to rely on facts, but it was only one "data point" of the truth.

That's why I combined his test (using a continuous vs. separate allocation) and @James' Answer's advice.

The graphs below shows, that most of the answers and especially the majority of comments to the question and answers can be considered completely wrong or true depending on the exact scenario and parameters used.

Note that my initial question was at n = 100.000. This point (by accident) exhibits special behavior:

  1. It possesses the greatest discrepancy between the one and two loop'ed version (almost a factor of three)

  2. It is the only point, where one-loop (namely with continuous allocation) beats the two-loop version. (This made Mysticial's answer possible, at all.)

The result using initialized data:

Enter image description here

The result using uninitialized data (this is what Mysticial tested):

Enter image description here

And this is a hard-to-explain one: Initialized data, that is allocated once and reused for every following test case of different vector size:

Enter image description here

Proposal

Every low-level performance related question on Stack Overflow should be required to provide MFLOPS information for the whole range of cache relevant data sizes! It's a waste of everybody's time to think of answers and especially discuss them with others without this information.

New to MongoDB Can not run command mongo

Also check if you have installed the Mongo as a windows service and if its running. That's also important. There might port conflict because of that.

Mongod complains that there is no /data/db folder

MongoDB can be confusing regarding the dbPath folder.

When you run mongod without dbpath then the default path is /data/db

However when you start it as a service, e.g. systemctl start mongod then it reads on configuration file, typially /etc/mongod.cfg and in this config file the defaults are

Platform Package Manager Default storage.dbPath
RHEL / CentOS and Amazon yum /var/lib/mongo
SUSE zypper /var/lib/mongo
Ubuntu and Debian apt /var/lib/mongodb
macOS brew /usr/local/var/mongodb

So, by accident your MongoDB tries to access different data folders depending on how you start the service.

What is the use of a private static variable in Java?

Static variables are those variables which are common for all the instances of a class..if one instance changes it.. then value of static variable would be updated for all other instances

unable to start mongodb local server

I've faced the same issue. Though the mongodb service is not running, the log showed address already in use message.

 $netstat -tulpn | grep :27017 

returns nothing

On further analysis found that the issue was due to lock file. The service is running fine, after deleting the lock file and restarting it.

$grep "dbpath" /etc/mongodb.conf

dbpath =/var/lib/mongodb

$ls /var/lib/mongodb/mongod.lock

$service mongod start

Converting an integer to binary in C

You need to initialise bin, e.g.

bin = malloc(1);
bin[0] = '\0';

or use calloc:

bin = calloc(1, 1);

You also have a bug here:

 bin = (char *)realloc(bin, sizeof(char) * (sizeof(bin)+1));

this needs to be:

 bin = (char *)realloc(bin, sizeof(char) * (strlen(bin)+1));

(i.e. use strlen, not sizeof).

And you should increase the size before calling strcat.

And you're not freeing bin, so you have a memory leak.

And you need to convert 0, 1 to '0', '1'.

And you can't strcat a char to a string.

So apart from that, it's close, but the code should probably be more like this (warning, untested !):

int int_to_bin(int k)
{
   char *bin;
   int tmp;

   bin = calloc(1, 1);
   while (k > 0)
   {
      bin = realloc(bin, strlen(bin) + 2);
      bin[strlen(bin) - 1] = (k % 2) + '0';
      bin[strlen(bin)] = '\0';
      k = k / 2;
   }
   tmp = atoi(bin);
   free(bin);
   return tmp;
}

How to read from stdin with fgets()?

If you want to concatenate the input, then replace printf("%s\n", buffer); with strcat(big_buffer, buffer);. Also create and initialize the big buffer at the beginning: char *big_buffer = new char[BIG_BUFFERSIZE]; big_buffer[0] = '\0';. You should also prevent a buffer overrun by verifying the current buffer length plus the new buffer length does not exceed the limit: if ((strlen(big_buffer) + strlen(buffer)) < BIG_BUFFERSIZE). The modified program would look like this:

#include <stdio.h>
#include <string.h>

#define BUFFERSIZE 10
#define BIG_BUFFERSIZE 1024

int main (int argc, char *argv[])
{
    char buffer[BUFFERSIZE];
    char *big_buffer = new char[BIG_BUFFERSIZE];
    big_buffer[0] = '\0';
    printf("Enter a message: \n");
    while(fgets(buffer, BUFFERSIZE , stdin) != NULL)
    {
        if ((strlen(big_buffer) + strlen(buffer)) < BIG_BUFFERSIZE)
        {
            strcat(big_buffer, buffer);
        }
    }
    return 0;
}

C read file line by line

const char *readLine(FILE *file, char* line) {

    if (file == NULL) {
        printf("Error: file pointer is null.");
        exit(1);
    }

    int maximumLineLength = 128;
    char *lineBuffer = (char *)malloc(sizeof(char) * maximumLineLength);

    if (lineBuffer == NULL) {
        printf("Error allocating memory for line buffer.");
        exit(1);
    }

    char ch = getc(file);
    int count = 0;

    while ((ch != '\n') && (ch != EOF)) {
        if (count == maximumLineLength) {
            maximumLineLength += 128;
            lineBuffer = realloc(lineBuffer, maximumLineLength);
            if (lineBuffer == NULL) {
                printf("Error reallocating space for line buffer.");
                exit(1);
            }
        }
        lineBuffer[count] = ch;
        count++;

        ch = getc(file);
    }

    lineBuffer[count] = '\0';
    char line[count + 1];
    strncpy(line, lineBuffer, (count + 1));
    free(lineBuffer);
    return line;

}


char linebuffer[256];
while (!feof(myFile)) {
    const char *line = readLine(myFile, linebuffer);
    printf("%s\n", line);
}

note that the 'line' variable is declared in calling function and then passed, so your readLine function fills predefined buffer and just returns it. This is the way most of C libraries work.

There are other ways, which I'm aware of:

  • defining the char line[] as static (static char line[MAX_LINE_LENGTH] -> it will hold it's value AFTER returning from the function). -> bad, the function is not reentrant, and race condition can occur -> if you call it twice from two threads, it will overwrite it's results
  • malloc()ing the char line[], and freeing it in calling functions -> too many expensive mallocs, and, delegating the responsibility to free the buffer to another function (the most elegant solution is to call malloc and free on any buffers in same function)

btw, 'explicit' casting from char* to const char* is redundant.

btw2, there is no need to malloc() the lineBuffer, just define it char lineBuffer[128], so you don't need to free it

btw3 do not use 'dynamic sized stack arrays' (defining the array as char arrayName[some_nonconstant_variable]), if you don't exactly know what are you doing, it works only in C99.

MySQL server has gone away - in exactly 60 seconds

In our case, the culprit was the global (not "local") MySQL variable "wait_timeout".

Compare the results of the following queries:

SHOW VARIABLES LIKE '%wait%';

to

SHOW GLOBAL VARIABLES WHERE Variable_name LIKE '%wait%';

In our case the first query showed a wait_timeout of 28800, but the 2nd query showed a value of 10 (seconds).

We verified that changing the global variable fixed the problem. Here is a simple PHP script that reproduced our condition:

<?php    
$db = mysqli_connect('host', 'user', 'password', 'database');

sleep(10); // number of seconds to sleep

// MySQL server has gone away?
$obj = mysqli_query($db, 'SELECT * FROM some_table');

$results = mysqli_fetch_object($obj);

print_r($results);

As soon as the sleep time exceeded the global wait_timeout value, we would get the error: "Warning: mysqli_query(): MySQL server has gone away".

To change the value, we had to edit the setting in our Amazon RDS dashboard.

How do you implement a class in C?

C Interfaces and Implementations: Techniques for Creating Reusable Software, David R. Hanson

http://www.informit.com/store/product.aspx?isbn=0201498413

This book does an excellent job of covering your question. It's in the Addison Wesley Professional Computing series.

The basic paradigm is something like this:

/* for data structure foo */

FOO *myfoo;
myfoo = foo_create(...);
foo_something(myfoo, ...);
myfoo = foo_append(myfoo, ...);
foo_delete(myfoo);

How can I create a dynamically sized array of structs?

If you want to dynamically allocate arrays, you can use malloc from stdlib.h.

If you want to allocate an array of 100 elements using your words struct, try the following:

words* array = (words*)malloc(sizeof(words) * 100);

The size of the memory that you want to allocate is passed into malloc and then it will return a pointer of type void (void*). In most cases you'll probably want to cast it to the pointer type you desire, which in this case is words*.

The sizeof keyword is used here to find out the size of the words struct, then that size is multiplied by the number of elements you want to allocate.

Once you are done, be sure to use free() to free up the heap memory you used in order to prevent memory leaks:

free(array);

If you want to change the size of the allocated array, you can try to use realloc as others have mentioned, but keep in mind that if you do many reallocs you may end up fragmenting the memory. If you want to dynamically resize the array in order to keep a low memory footprint for your program, it may be better to not do too many reallocs.

How to use the COLLATE in a JOIN in SQL Server?

Correct syntax looks like this. See MSDN.

SELECT *
  FROM [FAEB].[dbo].[ExportaComisiones] AS f
  JOIN [zCredifiel].[dbo].[optPerson] AS p

  ON p.vTreasuryId COLLATE Latin1_General_CI_AS = f.RFC COLLATE Latin1_General_CI_AS 

Minimum and maximum date

To augment T.J.'s answer, exceeding the min/max values generates an Invalid Date.

_x000D_
_x000D_
let maxDate = new Date(8640000000000000);_x000D_
let minDate = new Date(-8640000000000000);_x000D_
_x000D_
console.log(new Date(maxDate.getTime()).toString());_x000D_
console.log(new Date(maxDate.getTime() - 1).toString());_x000D_
console.log(new Date(maxDate.getTime() + 1).toString()); // Invalid Date_x000D_
_x000D_
console.log(new Date(minDate.getTime()).toString());_x000D_
console.log(new Date(minDate.getTime() + 1).toString());_x000D_
console.log(new Date(minDate.getTime() - 1).toString()); // Invalid Date
_x000D_
_x000D_
_x000D_

Deleting rows with MySQL LEFT JOIN

DELETE FROM deadline where ID IN (
    SELECT d.ID FROM `deadline` d LEFT JOIN `job` ON deadline.job_id = job.job_id WHERE `status` =  'szamlazva' OR `status` = 'szamlazhato' OR `status` = 'fizetve' OR `status` = 'szallitva' OR `status` = 'storno');

I am not sure if that kind of sub query works in MySQL, but try it. I am assuming you have an ID column in your deadline table.

Angular, content type is not being sent with $http

You need to include a body with the request. Angular removes the content-type header otherwise.

Add data: '' to the argument to $http.

How to lookup JNDI resources on WebLogic?

java is the root JNDI namespace for resources. What the original snippet of code means is that the container the application was initially deployed in did not apply any additional namespaces to the JNDI context you retrieved (as an example, Tomcat automatically adds all resources to the namespace comp/env, so you would have to do dataSource = (javax.sql.DataSource) context.lookup("java:comp/env/jdbc/myDataSource"); if the resource reference name is jdbc/myDataSource).

To avoid having to change your legacy code I think if you register the datasource with the name myDataSource (remove the jdbc/) you should be fine. Let me know if that works.

BigDecimal to string

By using below method you can convert java.math.BigDecimal to String.

   BigDecimal bigDecimal = new BigDecimal("10.0001");
   String bigDecimalString = String.valueOf(bigDecimal.doubleValue());
   System.out.println("bigDecimal value in String: "+bigDecimalString);

Output:
bigDecimal value in String: 10.0001

Filter by process/PID in Wireshark

In some cases you can not filter by process id. For example, in my case i needed to sniff traffic from one process. But I found in its config target machine IP-address, added filter ip.dst==someip and voila. It won't work in any case, but for some it's useful.

PySpark: multiple conditions in when clause

It should be:

$when(((tdata.Age == "" ) & (tdata.Survived == "0")), mean_age_0)

How to "properly" create a custom object in JavaScript?

I use this pattern fairly frequently - I've found that it gives me a pretty huge amount of flexibility when I need it. In use it's rather similar to Java-style classes.

var Foo = function()
{

    var privateStaticMethod = function() {};
    var privateStaticVariable = "foo";

    var constructor = function Foo(foo, bar)
    {
        var privateMethod = function() {};
        this.publicMethod = function() {};
    };

    constructor.publicStaticMethod = function() {};

    return constructor;
}();

This uses an anonymous function that is called upon creation, returning a new constructor function. Because the anonymous function is called only once, you can create private static variables in it (they're inside the closure, visible to the other members of the class). The constructor function is basically a standard Javascript object - you define private attributes inside of it, and public attributes are attached to the this variable.

Basically, this approach combines the Crockfordian approach with standard Javascript objects to create a more powerful class.

You can use it just like you would any other Javascript object:

Foo.publicStaticMethod(); //calling a static method
var test = new Foo();     //instantiation
test.publicMethod();      //calling a method

How do I get 'date-1' formatted as mm-dd-yyyy using PowerShell?

    Windows PowerShell
    Copyright (C) 2014 Microsoft Corporation. All rights reserved.

    PS C:\Windows\system32> **$dte = Get-Date**
    PS C:\Windows\system32> **$PastDueDate = $dte.AddDays(-45).Date**
    PS C:\Windows\system32> **$PastDueDate**

    Sunday, March 1, 2020 12:00:00 AM

   PS C:\Windows\system32> **$NewDateFormat = Get-Date $PastDueDate -Format MMddyyyy**
   PS C:\Windows\system32> **$NewDateFormat 03012020**

There're few additional methods available as well e.g.: $dte.AddDays(-45).Day

Are PHP short tags acceptable to use?

Let's face it. PHP is ugly as hell without short tags.

You can enable them in a .htaccess file if you can't get to the php.ini:

php_flag short_open_tag on

WAMP Server doesn't load localhost

Solution(s) for this, found in the official wampserver.com forums:

SOLUTION #1:

This problem is caused by Windows (7) in combination with any software that also uses port 80 (like Skype or IIS (which is installed on most developer machines)). A video solution can be found here (34.500+ views, damn, this seems to be a big thing ! EDIT: The video now has ~60.000 views ;) )

To make it short: open command line tool, type "netstat -aon" and look for any lines that end of ":80". Note thatPID on the right side. This is the process id of the software which currently usesport 80. Press AltGr + Ctrl + Del to get into the Taskmanager. Switch to the tab where you can see all services currently running, ordered by PID. Search for that PID you just notices and stop that thing (right click). To prevent this in future, you should config the software's port settings (skype can do that).

SOLUTION #2:

left click the wamp icon in the taskbar, go to apache > httpd.conf and edit this file: change "listen to port .... 80" to 8080. Restart. Done !

SOLUTION #3:

Port 80 blocked by "Microsoft Web Deployment Service", simply deinstall this, more info here

By the way, it's not Microsoft's fault, it's a stupid usage of ports by most WAMP stacks.

IMPORTANT: you have to use localhost or 127.0.0.1 now with port 8080, this means 127.0.0.1:8080 or localhost:8080.

Exit Shell Script Based on Process Exit Code

In Bash this is easy. Just tie them together with &&:

command1 && command2 && command3

You can also use the nested if construct:

if command1
   then
       if command2
           then
               do_something
           else
               exit
       fi
   else
       exit
fi

ERROR: ld.so: object LD_PRELOAD cannot be preloaded: ignored

If you want to make sure that the library is loaded if and only if the program lunar-calendar-gtk is launched, you can apply this:

You set the environment variable per command by prefixing the command with it:

$ LD_PRELOAD="liblunar-calendar-preload.so" printenv "LD_PRELOAD"
liblunar-calendar-preload.so
$ printenv "LD_PRELOAD"
$

You can then choose to put this in a shell script and make lunar-calendar-gtk a symlink to this shell script, replaceing the original referencee. This effectively makes sure that the library is loaded everytime the original application is executed.

You will have to rename the original lunar-calendar-gtk to something else, which might not be too intriguing as it possibly may cause issues with uninstallation and upgrading. However, I found it useful with a former version of Skype.

How to convert 1 to true or 0 to false upon model fetch

Assigning Comparison to property value

JavaScript

You could assign the comparison of the property to "1"

obj["isChecked"] = (obj["isChecked"]==="1");

This only evaluates for a String value of "1" though. Other variables evaulate to false like an actual typeof number would be false. (i.e. obj["isChecked"]=1)

If you wanted to be indiscrimate about "1" or 1, you could use:

obj["isChecked"] = (obj["isChecked"]=="1");

Example Outputs

console.log(obj["isChecked"]==="1"); // true
console.log(obj["isChecked"]===1); // false
console.log(obj["isChecked"]==1); // true
console.log(obj["isChecked"]==="0"); // false
console.log(obj["isChecked"]==="Elephant"); // false

PHP

Same concept in PHP

$obj["isChecked"] = ($obj["isChecked"] == "1");

The same operator limitations as stated above for JavaScript apply.

Double Not

The 'double not' also works. It's confusing when people first read it but it works in both languages for integer/number type values. It however does not work in JavaScript for string type values as they always evaluate to true:

JavaScript

!!"1"; //true
!!"0"; //true
!!1; //true
!!0; //false
!!parseInt("0",10); // false

PHP

echo !!"1"; //true
echo !!"0"; //false
echo !!1; //true
echo !!0; //false

How to do case insensitive string comparison?

Suppose we want to find the string variable needle in the string variable haystack. There are three gotchas:

  1. Internationalized applications should avoid string.toUpperCase and string.toLowerCase. Use a regular expression which ignores case instead. For example, var needleRegExp = new RegExp(needle, "i"); followed by needleRegExp.test(haystack).
  2. In general, you might not know the value of needle. Be careful that needle does not contain any regular expression special characters. Escape these using needle.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");.
  3. In other cases, if you want to precisely match needle and haystack, just ignoring case, make sure to add "^" at the start and "$" at the end of your regular expression constructor.

Taking points (1) and (2) into consideration, an example would be:

var haystack = "A. BAIL. Of. Hay.";
var needle = "bail.";
var needleRegExp = new RegExp(needle.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"), "i");
var result = needleRegExp.test(haystack);
if (result) {
    // Your code here
}

jQuery Combobox/select autocomplete?

jQuery 1.8.1 has an example of this under autocomplete. It's very easy to implement.

pip is not able to install packages correctly: Permission denied error

It looks like you're having a permissions error, based on this message in your output: error: could not create '/lib/python2.7/site-packages/lxml': Permission denied.

One thing you can try is doing a user install of the package with pip install lxml --user. For more information on how that works, check out this StackOverflow answer. (Thanks to Ishaan Taylor for the suggestion)

You can also run pip install as a superuser with sudo pip install lxml but it is not generally a good idea because it can cause issues with your system-level packages.

Non-resolvable parent POM using Maven 3.0.3 and relativePath notation

You need to check your relative path, based on depth of your modules from parent if module is just below parent then in module put relative path as: ../pom.xml

if its 2 level down then ../../pom.xml

What is this: [Ljava.lang.Object;?

If you are here because of the Liquibase error saying:

Caused By: Precondition Error
...
Can't detect type of array [Ljava.lang.Short

and you are using

not {
  indexExists()
}

precondition multiple times, then you are facing an old bug: https://liquibase.jira.com/browse/CORE-1342

We can try to execute an above check using bare sqlCheck(Postgres):

SELECT COUNT(i.relname)
FROM
    pg_class t,
    pg_class i,
    pg_index ix
WHERE
    t.oid = ix.indrelid
    and i.oid = ix.indexrelid
    and t.relkind = 'r'
    and t.relname = 'tableName'
    and i.relname = 'indexName';

where tableName - is an index table name and indexName - is an index name

How to access the services from RESTful API in my angularjs page?

Welcome to the wonderful world of Angular !!

I am very new to angularJS. I am searching for accessing services from RESTful API but I didn't get any idea. please help me to do that. Thank you

There are two (very big) hurdles to writing your first Angular scripts, if you're currently using 'GET' services.

First, your services must implement the "Access-Control-Allow-Origin" property, otherwise the services will work a treat when called from, say, a web browser, but fail miserably when called from Angular.

So, you'll need to add a few lines to your web.config file:

<configuration>
  ... 
  <system.webServer>
    <httpErrors errorMode="Detailed"/>
    <validation validateIntegratedModeConfiguration="false"/>
    <!-- We need the following 6 lines, to let AngularJS call our REST web services -->
    <httpProtocol>
        <customHeaders>
            <add name="Access-Control-Allow-Origin" value="*"/>
            <add name="Access-Control-Allow-Headers" value="Content-Type"/>
        </customHeaders>
    </httpProtocol>
  </system.webServer>
  ... 
</configuration>

Next, you need to add a little bit of code to your HTML file, to force Angular to call 'GET' web services:

// Make sure AngularJS calls our WCF Service as a "GET", rather than as an "OPTION"
var myApp = angular.module('myApp', []);
myApp.config(['$httpProvider', function ($httpProvider) {
    $httpProvider.defaults.useXDomain = true;
    delete $httpProvider.defaults.headers.common['X-Requested-With'];
}]);

Once you have these fixes in place, actually calling a RESTful API is really straightforward.

function YourAngularController($scope, $http) 
{
    $http.get('http://www.iNorthwind.com/Service1.svc/getAllCustomers')
        .success(function (data) {
        //  
        //  Do something with the data !
        //  
    });
}

You can find a really clear walkthrough of these steps on this webpage:

Using Angular, with JSON data

Good luck !

Mike

Base 64 encode and decode example code

Answer from 2021 in kotlin

Encode :

        val data: String = "Hello"
        val dataByteArray: ByteArray = data.toByteArray()
        val dataInBase64: String = Base64Utils.encode(dataByteArray)

Decode :

        val dataInBase64: String = "..."
        val dataByteArray: ByteArray = Base64Utils.decode(dataInBase64)
        val data: String = dataByteArray.toString()

How to open child forms positioned within MDI parent in VB.NET?

See this page for the solution! https://msdn.microsoft.com/en-us/library/7aw8zc76(v=vs.110).aspx

I was able to implement the Child form inside the parent.

In the Example below Form2 should change to the name of your child form. NewMDIChild.MdiParent=me is the main form since the control that opens (shows) the child form is the parent or Me.

NewMDIChild.Show() is your child form since you associated your child form with Dim NewMDIChild As New Form2()

Protected Sub MDIChildNew_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuItem2.Click
   Dim NewMDIChild As New Form2()
   'Set the Parent Form of the Child window.
   NewMDIChild.MdiParent = Me
   'Display the new form.
   NewMDIChild.Show()
End Sub

Simple and it works.

How to dynamically change a web page's title?

Using the document.title is how you would accomplish it in JavaScript, but how is this supposed to assist with SEO? Bots don't generally execute javascript code as they traverse through pages.

Spring profiles and testing

@EnableConfigurationProperties needs to be there (you also can annotate your test class), the application-localtest.yml from test/resources will be loaded. A sample with jUnit5

@ExtendWith(SpringExtension.class)
@EnableConfigurationProperties
@ContextConfiguration(classes = {YourClasses}, initializers = ConfigFileApplicationContextInitializer.class)
@ActiveProfiles(profiles = "localtest")
class TestActiveProfile {

    @Test
    void testActiveProfile(){

    }
}

Why does using from __future__ import print_function breaks Python2-style print?

First of all, from __future__ import print_function needs to be the first line of code in your script (aside from some exceptions mentioned below). Second of all, as other answers have said, you have to use print as a function now. That's the whole point of from __future__ import print_function; to bring the print function from Python 3 into Python 2.6+.

from __future__ import print_function

import sys, os, time

for x in range(0,10):
    print(x, sep=' ', end='')  # No need for sep here, but okay :)
    time.sleep(1)

__future__ statements need to be near the top of the file because they change fundamental things about the language, and so the compiler needs to know about them from the beginning. From the documentation:

A future statement is recognized and treated specially at compile time: Changes to the semantics of core constructs are often implemented by generating different code. It may even be the case that a new feature introduces new incompatible syntax (such as a new reserved word), in which case the compiler may need to parse the module differently. Such decisions cannot be pushed off until runtime.

The documentation also mentions that the only things that can precede a __future__ statement are the module docstring, comments, blank lines, and other future statements.

MySQL - force not to use cache for testing speed of query

Try using the SQL_NO_CACHE (MySQL 5.7) option in your query. (MySQL 5.6 users click HERE )

eg.

SELECT SQL_NO_CACHE * FROM TABLE

This will stop MySQL caching the results, however be aware that other OS and disk caches may also impact performance. These are harder to get around.

How to uncheck a radio button?

Use this

$("input[name='nameOfYourRadioButton']").attr("checked", false);

How to give environmental variable path for file appender in configuration file in log4j

java -DLOG_DIR=${LOG_DIR} -jar myjar.jar "param1" "param2" ==> in cmd line if you have "value="${LOG_DIR}/log/clientProject/project-error.log" in xml

How to escape strings in SQL Server using PHP?

After struggling with this for hours, I've come up with a solution that feels almost the best.

Chaos' answer of converting values to hexstring doesn't work with every datatype, specifically with datetime columns.

I use PHP's PDO::quote(), but as it comes with PHP, PDO::quote() is not supported for MS SQL Server and returns FALSE. The solution for it to work was to download some Microsoft bundles:

After that you can connect in PHP with PDO using a DSN like the following example:

sqlsrv:Server=192.168.0.25; Database=My_Database;

Using the UID and PWD parameters in the DSN didn't worked, so username and password are passed as the second and third parameters on the PDO constructor when creating the connection. Now you can use PHP's PDO::quote(). Enjoy.

How to use a variable for a key in a JavaScript object literal?

With ECMAScript 2015 you are now able to do it directly in object declaration with the brackets notation: 

var obj = {
  [key]: value
}

Where key can be any sort of expression (e.g. a variable) returning a value.

So here your code would look like:

<something>.stop().animate({
  [thetop]: 10
}, 10)

Where thetop will be evaluated before being used as key.

How to call a function after a div is ready?

You can use recursion here to do this. For example:

jQuery(document).ready(checkContainer);

function checkContainer () {
  if($('#divIDer').is(':visible'))){ //if the container is visible on the page
    createGrid();  //Adds a grid to the html
  } else {
    setTimeout(checkContainer, 50); //wait 50 ms, then try again
  }
}

Basically, this function will check to make sure that the element exists and is visible. If it is, it will run your createGrid() function. If not, it will wait 50ms and try again.

Note:: Ideally, you would just use the callback function of your AJAX call to know when the container was appended, but this is a brute force, standalone approach. :)

Telegram Bot - how to get a group chat id?

After mid-2018:
1:) Invite @getidsbot or @RawDataBot to your group and get your group id from the chat id field.

Message
 + message_id: 338
 + from
 ?  + id: *****
 ?  + is_bot: false
 ?  + first_name: ???
 ?  + username: ******
 ?  + language_code: en
 + chat
 ?  + id: -1001118554477    // This is Your Group id
 ?  + title: Test Group
 ?  + type: supergroup
 + date: 1544948900
 + text: A

2:) use an unofficial Messenger like Plus Messenger and see your group id in group/channel info.

Before mid-2018: (don't Use)
1: Goto (https://web.telegram.org)
2: Goto your Gorup and Find your link of Gorup(https://web.telegram.org/#/im?p=g154513121)
3: Copy That number after g and put a (-) Before That -154513121
4: Send Your Message to Gorup bot.sendMessage(-154513121, "Hi")
I Tested Now and Work like a Charm

Plot Normal distribution with Matplotlib

Note: This solution is using pylab, not matplotlib.pyplot

You may try using hist to put your data info along with the fitted curve as below:

import numpy as np
import scipy.stats as stats
import pylab as pl

h = sorted([186, 176, 158, 180, 186, 168, 168, 164, 178, 170, 189, 195, 172,
     187, 180, 186, 185, 168, 179, 178, 183, 179, 170, 175, 186, 159,
     161, 178, 175, 185, 175, 162, 173, 172, 177, 175, 172, 177, 180])  #sorted

fit = stats.norm.pdf(h, np.mean(h), np.std(h))  #this is a fitting indeed

pl.plot(h,fit,'-o')

pl.hist(h,normed=True)      #use this to draw histogram of your data

pl.show()                   #use may also need add this 

enter image description here

How can I access and process nested objects, arrays or JSON?

var ourStorage = {


"desk":    {
    "drawer": "stapler"
  },
"cabinet": {
    "top drawer": { 
      "folder1": "a file",
      "folder2": "secrets"
    },
    "bottom drawer": "soda"
  }
};
ourStorage.cabinet["top drawer"].folder2; // Outputs -> "secrets"

or

//parent.subParent.subsubParent["almost there"]["final property"]

Basically, use a dot between each descendant that unfolds underneath it and when you have object names made out of two strings, you must use the ["obj Name"] notation. Otherwise, just a dot would suffice;

Source: https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/accessing-nested-objects

to add to this, accessing nested Arrays would happen like so:

var ourPets = [
  {
    animalType: "cat",
    names: [
      "Meowzer",
      "Fluffy",
      "Kit-Cat"
    ]
  },
  {
    animalType: "dog",
    names: [
      "Spot",
      "Bowser",
      "Frankie"
    ]
  }
];
ourPets[0].names[1]; // Outputs "Fluffy"
ourPets[1].names[0]; // Outputs "Spot"

Source: https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/accessing-nested-arrays/

Another more useful document depicting the situation above: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Basics#Bracket_notation

Property access via dot walking: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors#Dot_notation

How to convert a color integer to a hex String in Android?

If you use Integer.toHexString you will end-up with missed zeros when you convert colors like 0xFF000123. Here is my kotlin based solution which doesn't require neither android specific classes nor java. So you could use it in multiplatform project as well:

    fun Int.toRgbString(): String =
        "#${red.toStringComponent()}${green.toStringComponent()}${blue.toStringComponent()}".toUpperCase()

    fun Int.toArgbString(): String =
        "#${alpha.toStringComponent()}${red.toStringComponent()}${green.toStringComponent()}${blue.toStringComponent()}".toUpperCase()

    private fun Int.toStringComponent(): String =
        this.toString(16).let { if (it.length == 1) "0${it}" else it }

    inline val Int.alpha: Int
        get() = (this shr 24) and 0xFF

    inline val Int.red: Int
        get() = (this shr 16) and 0xFF

    inline val Int.green: Int
        get() = (this shr 8) and 0xFF

    inline val Int.blue: Int
        get() = this and 0xFF

Java 11 package javax.xml.bind does not exist

According to the release-notes, Java 11 removed the Java EE modules:

java.xml.bind (JAXB) - REMOVED
  • Java 8 - OK
  • Java 9 - DEPRECATED
  • Java 10 - DEPRECATED
  • Java 11 - REMOVED

See JEP 320 for more info.

You can fix the issue by using alternate versions of the Java EE technologies. Simply add Maven dependencies that contain the classes you need:

<dependency>
  <groupId>javax.xml.bind</groupId>
  <artifactId>jaxb-api</artifactId>
  <version>2.3.0</version>
</dependency>
<dependency>
  <groupId>com.sun.xml.bind</groupId>
  <artifactId>jaxb-core</artifactId>
  <version>2.3.0</version>
</dependency>
<dependency>
  <groupId>com.sun.xml.bind</groupId>
  <artifactId>jaxb-impl</artifactId>
  <version>2.3.0</version>
</dependency>

Jakarta EE 8 update (Mar 2020)

Instead of using old JAXB modules you can fix the issue by using Jakarta XML Binding from Jakarta EE 8:

<dependency>
  <groupId>jakarta.xml.bind</groupId>
  <artifactId>jakarta.xml.bind-api</artifactId>
  <version>2.3.3</version>
</dependency>
<dependency>
  <groupId>com.sun.xml.bind</groupId>
  <artifactId>jaxb-impl</artifactId>
  <version>2.3.3</version>
  <scope>runtime</scope>
</dependency>

Jakarta EE 9 update (Nov 2020)

Use latest release of Eclipse Implementation of JAXB 3.0.0:

<dependency>
  <groupId>jakarta.xml.bind</groupId>
  <artifactId>jakarta.xml.bind-api</artifactId>
  <version>3.0.0</version>
</dependency>
<dependency>
  <groupId>com.sun.xml.bind</groupId>
  <artifactId>jaxb-impl</artifactId>
  <version>3.0.0</version>
  <scope>runtime</scope>
</dependency>

Note: Jakarta EE 9 adopts new API package namespace jakarta.xml.bind.*, so update import statements:

javax.xml.bind -> jakarta.xml.bind

Error 5 : Access Denied when starting windows service

Click the Start menu and choose Run or use the keyboard shortcut of Win+R.

In the dialog box, type lusrmgr.msc. When this application opens, click Users in the left-hand panel and then right click Administrator in the right-hand panel. Click Properties in the menu.

In the Administrator Properties dialog, choose the Member Of tab, then click the Add... button at the lower right. From the next dialog, choose Advanced...

Another dialog will appear. From there click Find Now on the right. A list of search results will appear at the bottom of the dialog. Select Network Services from this list and click OK on each of the open dialogs.

Favicon not showing up in Google Chrome

Upload your favicon.ico to the root directory of your website and that should work with Chrome. Some browsers disregard the meta tag and just use /favicon.ico

Go figure?.....

How to mark-up phone numbers?

Mobile Safari (iPhone & iPod Touch) use the tel: scheme.

How do I dial a phone number from a webpage on iPhone?

Gradient of n colors ranging from color 1 and color 2

Just to expand on the previous answer colorRampPalettecan handle more than two colors.

So for a more expanded "heat map" type look you can....

colfunc<-colorRampPalette(c("red","yellow","springgreen","royalblue"))
plot(rep(1,50),col=(colfunc(50)), pch=19,cex=2)

The resulting image:

enter image description here

Add new item in existing array in c#.net

 Array.Resize(ref youur_array_name, your_array_name.Length + 1);
 your_array_name[your_array_name.Length - 1] = "new item";

Several ports (8005, 8080, 8009) required by Tomcat Server at localhost are already in use

The problem often arises when Apache Tomcat fails to terminate, properly, even though a shutdown instruction was sent. In my case, using Tomcat 8, this happens with annoying regularity. Luckily, you can use Windows PowerShell and the netstat command to create a simple script to kill the process.

The following PowerShell script will parse the output from netstat to find any process that is listening on 127.0.0.1:8005, extract its PID and then kill that process:

netstat -a -o -n `
 | select -skip 4 `
 | % {$a = $_ -split ' {3,}'; New-Object 'PSObject' -Property @{Original=$_;Fields=$a}} `
 | ? {$_.Fields[1] -match '127\.0\.0\.1\:8005$'} `
 | % {Write-Host "Killing PID" $_.Fields[4] "..."; taskkill /F /PID $_.Fields[4] }

If your server.xml configures Tomcat to use a different port or IP, edit the regular expression on the script's fourth line accordingly.

Finally, I should point out that the situation is better on Linux because you can instruct Tomcat to save its PID to a file at startup-time and use a switch to force the shutdown, later - the shutdown script for 'nix systems already features the ability to kill the process and the sleuth-work with netstat is not required.

How to sort an array of objects in Java?

You have two ways to do that, both use the Arrays utility class

  1. Implement a Comparator and pass your array along with the comparator to the sort method which take it as second parameter.
  2. Implement the Comparable interface in the class your objects are from and pass your array to the sort method which takes only one parameter.

Example

class Book implements Comparable<Book> {
    public String name, id, author, publisher;
    public Book(String name, String id, String author, String publisher) {
        this.name = name;
        this.id = id;
        this.author = author;
        this.publisher = publisher;
    }
    public String toString() {
        return ("(" + name + ", " + id + ", " + author + ", " + publisher + ")");
    }
    @Override
    public int compareTo(Book o) {
        // usually toString should not be used,
        // instead one of the attributes or more in a comparator chain
        return toString().compareTo(o.toString());
    }
}

@Test
public void sortBooks() {
    Book[] books = {
            new Book("foo", "1", "author1", "pub1"),
            new Book("bar", "2", "author2", "pub2")
    };

    // 1. sort using Comparable
    Arrays.sort(books);
    System.out.println(Arrays.asList(books));

    // 2. sort using comparator: sort by id
    Arrays.sort(books, new Comparator<Book>() {
        @Override
        public int compare(Book o1, Book o2) {
            return o1.id.compareTo(o2.id);
        }
    });
    System.out.println(Arrays.asList(books));
}

Output

[(bar, 2, author2, pub2), (foo, 1, author1, pub1)]
[(foo, 1, author1, pub1), (bar, 2, author2, pub2)]

Python handling socket.error: [Errno 104] Connection reset by peer

There is a way to catch the error directly in the except clause with ConnectionResetError, better to isolate the right error. This example also catches the timeout.

from urllib.request import urlopen 
from socket import timeout

url = "http://......"
try: 
    string = urlopen(url, timeout=5).read()
except ConnectionResetError:
    print("==> ConnectionResetError")
    pass
except timeout: 
    print("==> Timeout")
    pass

CSS transition shorthand with multiple properties?

Syntax:

transition: <property> || <duration> || <timing-function> || <delay> [, ...];

Note that the duration must come before the delay, if the latter is specified.

Individual transitions combined in shorthand declarations:

-webkit-transition: height 0.3s ease-out, opacity 0.3s ease 0.5s;
-moz-transition: height 0.3s ease-out, opacity 0.3s ease 0.5s;
-o-transition: height 0.3s ease-out, opacity 0.3s ease 0.5s;
transition: height 0.3s ease-out, opacity 0.3s ease 0.5s;

Or just transition them all:

-webkit-transition: all 0.3s ease-out;
-moz-transition: all 0.3s ease-out;
-o-transition: all 0.3s ease-out;
transition: all 0.3s ease-out;

Here is a straightforward example. Here is another one with the delay property.


Edit: previously listed here were the compatibilities and known issues regarding transition. Removed for readability.

Bottom-line: just use it. The nature of this property is non-breaking for all applications and compatibility is now well above 94% globally.

If you still want to be sure, refer to http://caniuse.com/css-transitions

Simplest way to wait some asynchronous tasks complete, in Javascript?

I see you are using mongoose so you are talking about server-side JavaScript. In that case I advice looking at async module and use async.parallel(...). You will find this module really helpful - it was developed to solve the problem you are struggling with. Your code may look like this

var async = require('async');

var calls = [];

['aaa','bbb','ccc'].forEach(function(name){
    calls.push(function(callback) {
        conn.collection(name).drop(function(err) {
            if (err)
                return callback(err);
            console.log('dropped');
            callback(null, name);
        });
    }
)});

async.parallel(calls, function(err, result) {
    /* this code will run after all calls finished the job or
       when any of the calls passes an error */
    if (err)
        return console.log(err);
    console.log(result);
});

JSON.parse vs. eval()

You are more vulnerable to attacks if using eval: JSON is a subset of Javascript and json.parse just parses JSON whereas eval would leave the door open to all JS expressions.

contenteditable change events

I have modified lawwantsin 's answer like so and this works for me. I use the keyup event instead of keypress which works great.

$('#editor').on('focus', function() {
  before = $(this).html();
}).on('blur keyup paste', function() { 
  if (before != $(this).html()) { $(this).trigger('change'); }
});

$('#editor').on('change', function() {alert('changed')});

How do I run a batch file from my Java Application?

ProcessBuilder is the Java 5/6 way to run external processes.

Android: How to rotate a bitmap on a center point

Look at the sample from Google called Lunar Lander, the ship image there is rotated dynamically.

Lunar Lander code sample

How to iterate through table in Lua?

To iterate over all the key-value pairs in a table you can use pairs:

for k, v in pairs(arr) do
  print(k, v[1], v[2], v[3])
end

outputs:

pears   2   p   green
apples  0   a   red
oranges 1   o   orange

Edit: Note that Lua doesn't guarantee any iteration order for the associative part of the table. If you want to access the items in a specific order, retrieve the keys from arr and sort it. Then access arr through the sorted keys:

local ordered_keys = {}

for k in pairs(arr) do
    table.insert(ordered_keys, k)
end

table.sort(ordered_keys)
for i = 1, #ordered_keys do
    local k, v = ordered_keys[i], arr[ ordered_keys[i] ]
    print(k, v[1], v[2], v[3])
end

outputs:

  apples  a   red     5
  oranges o   orange  12
  pears   p   green   7

Could not find a base address that matches scheme https for the endpoint with binding WebHttpBinding. Registered base address schemes are [http]

I solved the issue by adding https binding in my IIS websites and adding 443 SSL port and selecting a self signed certificate in binding.

enter image description here

How to delete all files older than 3 days when "Argument list too long"?

To delete all files and directories within the current directory:

find . -mtime +3 | xargs rm -Rf

Or alternatively, more in line with the OP's original command:

find . -mtime +3 -exec rm -Rf -- {} \;

How to increase Java heap space for a tomcat app

  • Open the server tab in eclipse
  • right click open
  • click on open lauch configuration
  • Go to arguments
  • Here you can add in VM arguments after endorsed

    -Xms64m -Xmx256m
    

How to detect the swipe left or Right in Android?

I want to add on to the accepted answer which works partially, but is missing the time variable, that makes it perfect.

Simplest left to right swipe detector with a time variable:

In your activity class add following attributes:

private float x1,x2;
private long startClickTime;
static final int MIN_DISTANCE = 150;
static final int MAX_SWIPE_TIME = 200;

and override onTouchEvent () method:

    @Override
    public boolean onTouchEvent(MotionEvent event)
    {
        switch(event.getAction())
        {
            case MotionEvent.ACTION_DOWN:
                startClickTime = Calendar.getInstance().getTimeInMillis();
                x1 = event.getX();
                break;
            case MotionEvent.ACTION_UP:
                long clickDuration = Calendar.getInstance().getTimeInMillis() - startClickTime;
                x2 = event.getX();
                float deltaX = x2 - x1;
                if (Math.abs(deltaX) > MIN_DISTANCE && clickDuration < MAX_SWIPE_TIME)
                {
                    Toast.makeText(this, "left2right swipe", Toast.LENGTH_SHORT).show ();
                }
                else
                {
                    // consider as something else - a screen tap for example
                }
                break;
        }
        return super.onTouchEvent(event);
    }

Trigger Change event when the Input value changed programmatically?

If someone is using react, following will be useful:

https://stackoverflow.com/a/62111884/1015678

const valueSetter = Object.getOwnPropertyDescriptor(this.textInputRef, 'value').set;
const prototype = Object.getPrototypeOf(this.textInputRef);
const prototypeValueSetter = Object.getOwnPropertyDescriptor(prototype, 'value').set;
if (valueSetter && valueSetter !== prototypeValueSetter) {
    prototypeValueSetter.call(this.textInputRef, 'new value');
} else {
    valueSetter.call(this.textInputRef, 'new value');
}
this.textInputRef.dispatchEvent(new Event('input', { bubbles: true }));

How would I stop a while loop after n amount of time?

I want to share the one I am using:

import time
# provide a waiting-time list:
lst = [1,2,7,4,5,6,4,3]
# set the timeout limit
timeLimit = 4

for i in lst:
    timeCheck = time.time()
    while True:
        time.sleep(i)
        if time.time() <= timeCheck + timeLimit:
            print ([i,'looks ok'])
            break
        else:
            print ([i,'too long'])
            break

Then you will get:

[1, 'looks ok']
[2, 'looks ok']
[7, 'too long']
[4, 'looks ok']
[5, 'too long']
[6, 'too long']
[4, 'looks ok']
[3, 'looks ok']

PHP json_encode encoding numbers as strings

try $arr = array('var1' => 100, 'var2' => 200);
$json = json_encode( $arr, JSON_NUMERIC_CHECK);

But it just work on PHP 5.3.3. Look at this PHP json_encode change log http://php.net/manual/en/function.json-encode.php#refsect1-function.json-encode-changelog

Quickly reading very large tables as dataframes

This was previously asked on R-Help, so that's worth reviewing.

One suggestion there was to use readChar() and then do string manipulation on the result with strsplit() and substr(). You can see the logic involved in readChar is much less than read.table.

I don't know if memory is an issue here, but you might also want to take a look at the HadoopStreaming package. This uses Hadoop, which is a MapReduce framework designed for dealing with large data sets. For this, you would use the hsTableReader function. This is an example (but it has a learning curve to learn Hadoop):

str <- "key1\t3.9\nkey1\t8.9\nkey1\t1.2\nkey1\t3.9\nkey1\t8.9\nkey1\t1.2\nkey2\t9.9\nkey2\"
cat(str)
cols = list(key='',val=0)
con <- textConnection(str, open = "r")
hsTableReader(con,cols,chunkSize=6,FUN=print,ignoreKey=TRUE)
close(con)

The basic idea here is to break the data import into chunks. You could even go so far as to use one of the parallel frameworks (e.g. snow) and run the data import in parallel by segmenting the file, but most likely for large data sets that won't help since you will run into memory constraints, which is why map-reduce is a better approach.

How can I get npm start at a different directory?

Below Command where project is a folder which contains package.json file

npm run --prefix project ${COMMAND}

is working as well. Useful in Docker based applications.

How can I create basic timestamps or dates? (Python 3.4)

>>> import time
>>> print(time.strftime('%a %H:%M:%S'))
Mon 06:23:14

Warning: Found conflicts between different versions of the same dependent assembly

This happened to me too. One dll was referenced twice: once directly (in references) and once indirectly (referenced by another referenced project). I removed direct reference, cleaned & rebuilt solution. Problem fixed.

Regex to remove letters, symbols except numbers

Use /[^0-9.,]+/ if you want floats.

Setting format and value in input type="date"

new Date().toISOString().split('T')[0];

Adding a JAR to an Eclipse Java library

You might also consider using a build tool like Maven to manage your dependencies. It is very easy to setup and helps manage those dependencies automatically in eclipse. Definitely worth the effort if you have a large project with a lot of external dependencies.

Passing null arguments to C# methods

You can use 2 ways: int? or Nullable, both have the same behavior. You could to make a mix without problems but is better choice one to make code cleanest.

Option 1 (With ?):

private void Example(int? arg1, int? arg2)
    {
        if (arg1.HasValue)
        {
            //do something
        }
        if (arg1.HasValue)
        {
            //do something else
        }
    }

Option 2 (With Nullable):

private void Example(Nullable<int> arg1, Nullable<int> arg2)
    {
        if (arg1.HasValue)
        {
            //do something
        }
        if (arg1.HasValue)
        {
            //do something else
        }
    }

From C#4.0 comes a new way to do the same with more flexibility, in this case the framework offers optional parameters with default values, of this way you can set a default value if the method is called without all parameters.

Option 3 (With default values)

private void Example(int arg1 = 0, int arg2 = 1)
    {
        //do something else
    }

Reading a file character by character in C

I think the most significant problem is that you're incrementing code as you read stuff in, and then returning the final value of code, i.e. you'll be returning a pointer to the end of the string. You probably want to make a copy of code before the loop, and return that instead.

Also, C strings need to be null-terminated. You need to make sure that you place a '\0' directly after the final character that you read in.

Note: You could just use fgets() to get the entire line in one hit.

Can I use multiple versions of jQuery on the same page?

You can have as many different jQuery versions on your page as you want.

Use jQuery.noConflict():

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>
<script>
    var $i = jQuery.noConflict();
    alert($i.fn.jquery);
</script> 

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
    var $j = jQuery.noConflict();
    alert($j.fn.jquery);
</script> 

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>
    var $k = jQuery.noConflict();
    alert($k.fn.jquery);
</script> 

DEMO | Source

What is the difference between call and apply?

Follows an extract from Closure: The Definitive Guide by Michael Bolin. It might look a bit lengthy, but it's saturated with a lot of insight. From "Appendix B. Frequently Misunderstood JavaScript Concepts":


What this Refers to When a Function is Called

When calling a function of the form foo.bar.baz(), the object foo.bar is referred to as the receiver. When the function is called, it is the receiver that is used as the value for this:

var obj = {};
obj.value = 10;
/** @param {...number} additionalValues */
obj.addValues = function(additionalValues) {
  for (var i = 0; i < arguments.length; i++) {
    this.value += arguments[i];
  }
  return this.value;
};
// Evaluates to 30 because obj is used as the value for 'this' when
// obj.addValues() is called, so obj.value becomes 10 + 20.
obj.addValues(20);

If there is no explicit receiver when a function is called, then the global object becomes the receiver. As explained in "goog.global" on page 47, window is the global object when JavaScript is executed in a web browser. This leads to some surprising behavior:

var f = obj.addValues;
// Evaluates to NaN because window is used as the value for 'this' when
// f() is called. Because and window.value is undefined, adding a number to
// it results in NaN.
f(20);
// This also has the unintentional side effect of adding a value to window:
alert(window.value); // Alerts NaN

Even though obj.addValues and f refer to the same function, they behave differently when called because the value of the receiver is different in each call. For this reason, when calling a function that refers to this, it is important to ensure that this will have the correct value when it is called. To be clear, if this were not referenced in the function body, then the behavior of f(20) and obj.addValues(20) would be the same.

Because functions are first-class objects in JavaScript, they can have their own methods. All functions have the methods call() and apply() which make it possible to redefine the receiver (i.e., the object that this refers to) when calling the function. The method signatures are as follows:

/**
* @param {*=} receiver to substitute for 'this'
* @param {...} parameters to use as arguments to the function
*/
Function.prototype.call;
/**
* @param {*=} receiver to substitute for 'this'
* @param {Array} parameters to use as arguments to the function
*/
Function.prototype.apply;

Note that the only difference between call() and apply() is that call() receives the function parameters as individual arguments, whereas apply() receives them as a single array:

// When f is called with obj as its receiver, it behaves the same as calling
// obj.addValues(). Both of the following increase obj.value by 60:
f.call(obj, 10, 20, 30);
f.apply(obj, [10, 20, 30]);

The following calls are equivalent, as f and obj.addValues refer to the same function:

obj.addValues.call(obj, 10, 20, 30);
obj.addValues.apply(obj, [10, 20, 30]);

However, since neither call() nor apply() uses the value of its own receiver to substitute for the receiver argument when it is unspecified, the following will not work:

// Both statements evaluate to NaN
obj.addValues.call(undefined, 10, 20, 30);
obj.addValues.apply(undefined, [10, 20, 30]);

The value of this can never be null or undefined when a function is called. When null or undefined is supplied as the receiver to call() or apply(), the global object is used as the value for receiver instead. Therefore, the previous code has the same undesirable side effect of adding a property named value to the global object.

It may be helpful to think of a function as having no knowledge of the variable to which it is assigned. This helps reinforce the idea that the value of this will be bound when the function is called rather than when it is defined.


End of extract.

How to stop/terminate a python script from running?

you can also use the Activity Monitor to stop the py process

How to convert QString to std::string?

 QString data;
   data.toStdString().c_str();

could even throw exception on VS2017 compiler in xstring

 ~basic_string() _NOEXCEPT
        {   // destroy the string
        _Tidy_deallocate();
        }

the right way ( secure - no exception) is how is explained above from Artyom

 QString qs;

    // Either this if you use UTF-8 anywhere
    std::string utf8_text = qs.toUtf8().constData();

    // or this if you're on Windows :-)
    std::string current_locale_text = qs.toLocal8Bit().constData();

What is the difference between atan and atan2 in C++?

The actual values are in radians but to interpret them in degrees it will be:

  • atan = gives angle value between -90 and 90
  • atan2 = gives angle value between -180 and 180

For my work which involves computation of various angles such as heading and bearing in navigation, atan2 in most cases does the job.

jQuery UI Accordion Expand/Collapse All

A lot of these seem to be overcomplicated. I achieved what I wanted with just the following:

$(".ui-accordion-content").show();

JSFiddle

Center text in div?

Adding line height helps too.

text-align: center;
line-height: 18px; /* for example. */

Can you delete multiple branches in one command with Git?

git branch  | cut -c3- | egrep "^3.2" | xargs git branch -D
  ^                ^                ^         ^ 
  |                |                |         |--- create arguments
  |                |                |              from standard input
  |                |                |
  |                |                |---your regexp 
  |                |
  |                |--- skip asterisk 
  |--- list all 
       local
       branches

EDIT:

A safer version (suggested by Jakub Narebski and Jefromi), as git branch output is not meant to be used in scripting:

git for-each-ref --format="%(refname:short)" refs/heads/3.2\* | xargs git branch -D

... or the xargs-free:

git branch -D `git for-each-ref --format="%(refname:short)" refs/heads/3.2\*`

error: passing xxx as 'this' argument of xxx discards qualifiers

Let's me give a more detail example. As to the below struct:

struct Count{
    uint32_t c;

    Count(uint32_t i=0):c(i){}

    uint32_t getCount(){
        return c;
    }

    uint32_t add(const Count& count){
        uint32_t total = c + count.getCount();
        return total;
    }
};

enter image description here

As you see the above, the IDE(CLion), will give tips Non-const function 'getCount' is called on the const object. In the method add count is declared as const object, but the method getCount is not const method, so count.getCount() may change the members in count.

Compile error as below(core message in my compiler):

error: passing 'const xy_stl::Count' as 'this' argument discards qualifiers [-fpermissive]

To solve the above problem, you can:

  1. change the method uint32_t getCount(){...} to uint32_t getCount() const {...}. So count.getCount() won't change the members in count.

or

  1. change uint32_t add(const Count& count){...} to uint32_t add(Count& count){...}. So count don't care about changing members in it.

As to you problem, objects in the std::set are stored as const StudentT, but the method getId and getName are not const, so you give the above error.

You can also see this question Meaning of 'const' last in a function declaration of a class? for more detail.

ERROR 1067 (42000): Invalid default value for 'created_at'

Try and run the following command:

ALTER TABLE `investments` 
MODIFY created_at TIMESTAMP 
DEFAULT CURRENT_TIMESTAMP 
NOT NULL;

and

ALTER TABLE `investments` 
MODIFY updated_at TIMESTAMP 
DEFAULT CURRENT_TIMESTAMP 
NOT NULL;

The reason you are getting this error is because you are not setting a default value for the created_at and updated_at fields. MySQL is not accepting your command since the values for these columns cannot be null.

How to fix the height of a <div> element?

You can try max-height: 70px; See if that works.

Concatenating strings in C, which method is more efficient?

Here's some madness for you, I actually went and measured it. Bloody hell, imagine that. I think I got some meaningful results.

I used a dual core P4, running Windows, using mingw gcc 4.4, building with "gcc foo.c -o foo.exe -std=c99 -Wall -O2".

I tested method 1 and method 2 from the original post. Initially kept the malloc outside the benchmark loop. Method 1 was 48 times faster than method 2. Bizarrely, removing -O2 from the build command made the resulting exe 30% faster (haven't investigated why yet).

Then I added a malloc and free inside the loop. That slowed down method 1 by a factor of 4.4. Method 2 slowed down by a factor of 1.1.

So, malloc + strlen + free DO NOT dominate the profile enough to make avoiding sprintf worth while.

Here's the code I used (apart from the loops were implemented with < instead of != but that broke the HTML rendering of this post):

void a(char *first, char *second, char *both)
{
    for (int i = 0; i != 1000000 * 48; i++)
    {
        strcpy(both, first);
        strcat(both, " ");
        strcat(both, second);
    }
}

void b(char *first, char *second, char *both)
{
    for (int i = 0; i != 1000000 * 1; i++)
        sprintf(both, "%s %s", first, second);
}

int main(void)
{
    char* first= "First";
    char* second = "Second";
    char* both = (char*) malloc((strlen(first) + strlen(second) + 2) * sizeof(char));

    // Takes 3.7 sec with optimisations, 2.7 sec WITHOUT optimisations!
    a(first, second, both);

    // Takes 3.7 sec with or without optimisations
    //b(first, second, both);

    return 0;
}

Add number of days to a date

You could use the DateTime class built in PHP. It has a method called "add", and how it is used is thoroughly demonstrated in the manual: http://www.php.net/manual/en/datetime.add.php

It however requires PHP 5.3.0.

Connect with SSH through a proxy

This is how I solved it, hoping to help others later.

My system is debian 10, and minimal installation.

I also have the same problem like this.

git clone [email protected]:nothing/nothing.git
Cloning into 'nothing'...
nc: invalid option -- 'x'
nc -h for help
ssh_exchange_identification: Connection closed by remote host
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

Or

git clone [email protected]:nothing/nothing.git
Cloning into 'nothing'...
/usr/bin/nc: invalid option -- 'X'
nc -h for help
ssh_exchange_identification: Connection closed by remote host
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

So, I know the nc has different versions like openbsd-netcat and GNU-netcat, you can change the nc in debian to the openbsd version, but I choose to change the software like corkscrew, because the names of the two versions of nc in system are same, and many people don’t understand it well. My approach is as follows.

sudo apt install corkscrew

Then.

vim ~/.ssh/config

Change this file like this.

Host github.com
    User git
    ProxyCommand corkscrew 192.168.1.22 8118 %h %p

192.168.1.22 and 8118 is my proxy server's address and port, you should change it according to your server address.

It's work fine.

Thanks @han.

What causes a java.lang.StackOverflowError

Stack Overflow exceptions can occur when a thread stack continues to grow in size until reaching the maximum limit.

Adjusting the Stack Sizes (Xss and Xmso) options...

I suggest you see this link: http://www-01.ibm.com/support/docview.wss?uid=swg21162896 There are many possible causes to a StackOverflowError, as you can see in the link....

How do I install the babel-polyfill library?

If your package.json looks something like the following:

  ...
  "devDependencies": {
    "babel": "^6.5.2",
    "babel-eslint": "^6.0.4",
    "babel-polyfill": "^6.8.0",
    "babel-preset-es2015": "^6.6.0",
    "babelify": "^7.3.0",
  ...

And you get the Cannot find module 'babel/polyfill' error message, then you probably just need to change your import statement FROM:

import "babel/polyfill";

TO:

import "babel-polyfill";

And make sure it comes before any other import statement (not necessarily at the entry point of your application).

Reference: https://babeljs.io/docs/usage/polyfill/

Android button onClickListener

easy:

launching activity (onclick handler)

 Intent myIntent = new Intent(CurrentActivity.this, NextActivity.class);
 myIntent.putExtra("key", value); //Optional parameters
 CurrentActivity.this.startActivity(myIntent);

on the new activity:

@Override
protected void onCreate(Bundle savedInstanceState) {
Intent intent = getIntent();
String value = intent.getStringExtra("key"); //if it's a string you stored.

and add your new activity in the AndroidManifest.xml:

<activity android:label="@string/app_name" android:name="NextActivity"/>

No visible cause for "Unexpected token ILLEGAL"

why you looking for this problem into your code? Even, if it's copypasted.

If you can see, what exactly happening after save file in synced folder - you will see something like ***** at the end of file. It's not related to your code at all.

Solution.

If you are using nginx in vagrant box - add to server config:

sendfile off;

If you are using apache in vagrant box - add to server config:

EnableSendfile Off;

Source of problem: VirtualBox Bug

regular expression to validate datetime format (MM/DD/YYYY)

It's long, but great:

new RegExp(/(?=\d)^(?:(?!(?:10\D(?:0?[5-9]|1[0-4])\D(?:1582))|(?:0?9\D(?:0?[3-9]|1[0-3])\D(?:1752)))((?:0?[13578]|1[02])|(?:0?[469]|11)(?!\/31)(?!-31)(?!\.31)|(?:0?2(?=.?(?:(?:29.(?!000[04]|(?:(?:1[^0-6]|[2468][^048]|[3579][^26])00))(?:(?:(?:\d\d)(?:[02468][048]|[13579][26])(?!\x20BC))|(?:00(?:42|3[0369]|2[147]|1[258]|09)\x20BC))))))|(?:0?2(?=.(?:(?:\d\D)|(?:[01]\d)|(?:2[0-8])))))([-.\/])(0?[1-9]|[12]\d|3[01])\2(?!0000)((?=(?:00(?:4[0-5]|[0-3]?\d)\x20BC)|(?:\d{4}(?!\x20BC)))\d{4}(?:\x20BC)?)(?:$|(?=\x20\d)\x20))?((?:(?:0?[1-9]|1[012])(?::[0-5]\d){0,2}(?:\x20[aApP][mM]))|(?:[01]\d|2[0-3])(?::[0-5]\d){1,2})?$/);

C++11 introduced a standardized memory model. What does it mean? And how is it going to affect C++ programming?

This is now a multiple-year old question, but being very popular, it's worth mentioning a fantastic resource for learning about the C++11 memory model. I see no point in summing up his talk in order to make this yet another full answer, but given this is the guy who actually wrote the standard, I think it's well worth watching the talk.

Herb Sutter has a three hour long talk about the C++11 memory model titled "atomic<> Weapons", available on the Channel9 site - part 1 and part 2. The talk is pretty technical, and covers the following topics:

  1. Optimizations, Races, and the Memory Model
  2. Ordering – What: Acquire and Release
  3. Ordering – How: Mutexes, Atomics, and/or Fences
  4. Other Restrictions on Compilers and Hardware
  5. Code Gen & Performance: x86/x64, IA64, POWER, ARM
  6. Relaxed Atomics

The talk doesn't elaborate on the API, but rather on the reasoning, background, under the hood and behind the scenes (did you know relaxed semantics were added to the standard only because POWER and ARM do not support synchronized load efficiently?).

Xamarin 2.0 vs Appcelerator Titanium vs PhoneGap

Overview

As reported by Tim Anderson

Cross-platform development is a big deal, and will continue to be so until a day comes when everyone uses the same platform. Android? HTML? WebKit? iOS? Windows? Xamarin? Titanum? PhoneGap? Corona? ecc.

Sometimes I hear it said that there are essentially two approaches to cross-platform mobile apps. You can either use an embedded browser control and write a web app wrapped as a native app, as in Adobe PhoneGap/Cordova or the similar approach taken by Sencha, or you can use a cross-platform tool that creates native apps, such as Xamarin Studio, Appcelerator Titanium, or Embarcardero FireMonkey.

Within the second category though, there is diversity. In particular, they vary concerning the extent to which they abstract the user interface.

Here is the trade-off. If you design your cross-platform framework you can have your application work almost the same way on every platform. If you are sharing the UI design across all platforms, it is hard to make your design feel equally right in all cases. It might be better to take the approach adopted by most games, using a design that is distinctive to your app and make a virtue of its consistency across platforms, even though it does not have the native look and feel on any platform.

edit Xamarin v3 in 2014 started offering choice of Xamarin.Forms as well as pure native that still follows the philosophy mentioned here (took liberty of inline edit because such a great answer)

Xamarin Studio on the other hand makes no attempt to provide a shared GUI framework:

We don’t try to provide a user interface abstraction layer that works across all the platforms. We think that’s a bad approach that leads to lowest common denominator user interfaces. (Nat Friedman to Tim Anderson)

This is right; but the downside is the effort involved in maintaining two or more user interface designs for your app.

Comparison about PhoneGap and Titanium it's well reported in Kevin Whinnery blog.

PhoneGap

The purpose of PhoneGap is to allow HTML-based web applications to be deployed and installed as native applications. PhoneGap web applications are wrapped in a native application shell, and can be installed via the native app stores for multiple platforms. Additionally, PhoneGap strives to provide a common native API set which is typically unavailable to web applications, such as basic camera access, device contacts, and sensors not already exposed in the browser.

To develop PhoneGap applications, developers will create HTML, CSS, and JavaScript files in a local directory, much like developing a static website. Approaching native-quality UI performance in the browser is a non-trivial task - Sencha employs a large team of web programming experts dedicated full-time to solving this problem. Even so, on most platforms, in most browsers today, reaching native-quality UI performance and responsiveness is simply not possible, even with a framework as advanced as Sencha Touch. Is the browser already “good enough” though? It depends on your requirements and sensibilities, but it is unquestionably less good than native UI. Sometimes much worse, depending on the browser.

PhoneGap is not as truly cross-platform as one might believe, not all features are equally supported on all platforms.

  • Javascript is not an application scale programming language, too many global scope interactions, different libraries don't often co-exist nicely. We spent many hours trying to get knockout.js and jQuery.mobile play well together, and we still have problems.

  • Fragmented landscape for frameworks and libraries. Too many choices, and too many are not mature enough.

  • Strangely enough, for the needs of our app, decent performance could be achieved (not with jQuery.Mobile, though). We tried jqMobi (not very mature, but fast).

  • Very limited capability for interaction with other apps or cdevice capabilities, and this would not be cross-platform anyway, as there aren't any standards in HTML5 except for a few, like geolocation, camera and local databases.

by Karl Waclawek

Appcelerator Titanium

The goal of Titanium Mobile is to provide a high level, cross-platform JavaScript runtime and API for mobile development (today we support iOS, Android and Windows Phone. Titanium actually has more in common with MacRuby/Hot Cocoa, PHP, or node.js than it does with PhoneGap, Adobe AIR, Corona, or Rhomobile. Titanium is built on two assertions about mobile development: - There is a core of mobile development APIs which can be normalized across platforms. These areas should be targeted for code reuse. - There are platform-specific APIs, UI conventions, and features which developers should incorporate when developing for that platform. Platform-specific code should exist for these use cases to provide the best possible experience.

So for those reasons, Titanium is not an attempt at “write once, run everywhere”. Same as Xamarin.

Titanium are going to do a further step in the direction similar to that of Xamarin. In practice, they will do two layers of different depths: the layer Titanium (in JS), which gives you a bee JS-of-Titanium. If you want to go more low-level, have created an additional layer (called Hyperloop), where (always with JS) to call you back directly to native APIs of SO

Xamarin (+ MVVMCross)

AZDevelop.net

Xamarin (originally a division of Novell) in the last 18 months has brought to market its own IDE and snap-in for Visual Studio. The underlining premise of Mono is to create disparate mobile applications using C# while maintaining native UI development strategies.

In addition to creating a visual design platform to develop native applications, they have integrated testing suites, incorporated native library support and a Nuget style component store. Recently they provided iOS visual design through their IDE freeing the developer from opening XCode. In Visual Studio all three platforms are now supported and a cloud testing suite is on the horizon.

From the get go, Xamarin has provided a rich Android visual design experience. I have yet to download or open Eclipse or any other IDE besides Xamarin. What is truly amazing is that I am able to use LINQ to work with collections as well as create custom delegates and events that free me from objective-C and Java limitations. Many of the libraries I have been spoiled with, like Newtonsoft JSON.Net, work perfectly in all three environments.

In my opinion there are several HUGE advantages including

  • native performance
  • easier to read code (IMO)
  • testability
  • shared code between client and server
  • support (although Xam could do better on bugzilla)

Upgrade for me is use Xamarin and MVVMCross combined. It's still quite a new framework, but it's born from experience of several other frameworks (such as MvvmLight and monocross) and it's now been used in at several released cross platform projects.

Conclusion

My choice after knowing all these framwework, was to select development tool based on product needs. In general, however if you start to use a tool with which you feel comfortable (even if it requires a higher initial overhead) after you'll use it forever.

I chose Xamarin + MVVMCross and I must say to be happy with this choice. I'm not afraid of approach Native SDK for software updates or seeing limited functionality of a system or the most trivial thing a feature graphics. Write code fairly structured (DDD + SOA) is very useful to have a core project shared with native C# views implementation.

References and links

Load and execute external js file in node.js with access to local variables?

If you are writing code for Node, using Node modules as described by Ivan is without a doubt the way to go.

However, if you need to load JavaScript that has already been written and isn't aware of node, the vm module is the way to go (and definitely preferable to eval).

For example, here is my execfile module, which evaluates the script at path in either context or the global context:

var vm = require("vm");
var fs = require("fs");
module.exports = function(path, context) {
  var data = fs.readFileSync(path);
  vm.runInNewContext(data, context, path);
}

Also note: modules loaded with require(…) don't have access to the global context.

XXHDPI and XXXHDPI dimensions in dp for images and icons in android

You can use a vector. Instead of worry about different screen sizes you only need to create an .svg file and import it to your project using Vector Asset Studio.

Generating an MD5 checksum of a file

I'm clearly not adding anything fundamentally new, but added this answer before I was up to commenting status, plus the code regions make things more clear -- anyway, specifically to answer @Nemo's question from Omnifarious's answer:

I happened to be thinking about checksums a bit (came here looking for suggestions on block sizes, specifically), and have found that this method may be faster than you'd expect. Taking the fastest (but pretty typical) timeit.timeit or /usr/bin/time result from each of several methods of checksumming a file of approx. 11MB:

$ ./sum_methods.py
crc32_mmap(filename) 0.0241742134094
crc32_read(filename) 0.0219960212708
subprocess.check_output(['cksum', filename]) 0.0553209781647
md5sum_mmap(filename) 0.0286180973053
md5sum_read(filename) 0.0311000347137
subprocess.check_output(['md5sum', filename]) 0.0332629680634
$ time md5sum /tmp/test.data.300k
d3fe3d5d4c2460b5daacc30c6efbc77f  /tmp/test.data.300k

real    0m0.043s
user    0m0.032s
sys     0m0.010s
$ stat -c '%s' /tmp/test.data.300k
11890400

So, looks like both Python and /usr/bin/md5sum take about 30ms for an 11MB file. The relevant md5sum function (md5sum_read in the above listing) is pretty similar to Omnifarious's:

import hashlib
def md5sum(filename, blocksize=65536):
    hash = hashlib.md5()
    with open(filename, "rb") as f:
        for block in iter(lambda: f.read(blocksize), b""):
            hash.update(block)
    return hash.hexdigest()

Granted, these are from single runs (the mmap ones are always a smidge faster when at least a few dozen runs are made), and mine's usually got an extra f.read(blocksize) after the buffer is exhausted, but it's reasonably repeatable and shows that md5sum on the command line is not necessarily faster than a Python implementation...

EDIT: Sorry for the long delay, haven't looked at this in some time, but to answer @EdRandall's question, I'll write down an Adler32 implementation. However, I haven't run the benchmarks for it. It's basically the same as the CRC32 would have been: instead of the init, update, and digest calls, everything is a zlib.adler32() call:

import zlib
def adler32sum(filename, blocksize=65536):
    checksum = zlib.adler32("")
    with open(filename, "rb") as f:
        for block in iter(lambda: f.read(blocksize), b""):
            checksum = zlib.adler32(block, checksum)
    return checksum & 0xffffffff

Note that this must start off with the empty string, as Adler sums do indeed differ when starting from zero versus their sum for "", which is 1 -- CRC can start with 0 instead. The AND-ing is needed to make it a 32-bit unsigned integer, which ensures it returns the same value across Python versions.

HTML Tags in Javascript Alert() method

No, you can use only some escape sequences - \n for example (maybe only this one).

How do you get the file size in C#?

If you have already a file path as input, this is the code you need:

long length = new System.IO.FileInfo(path).Length;

How do you truncate all tables in a database using TSQL?

It is a little late but it might help someone. I created a procedure sometimes back which does the following using T-SQL:

  1. Store all constraints in a Temporary table
  2. Drop All Constraints
  3. Truncate all tables with exception of some tables, which does not need truncation
  4. Recreate all Constraints.

I have listed it on my blog here

Drawing a dot on HTML5 canvas

This should do the job

//get a reference to the canvas
var ctx = $('#canvas')[0].getContext("2d");

//draw a dot
ctx.beginPath();
ctx.arc(20, 20, 10, 0, Math.PI*2, true);
ctx.closePath();
ctx.fill();

Gradle Build Android Project "Could not resolve all dependencies" error

compileSdkVersion 17
targetSdkVersion 17

change the compile version from 18 to 17

compile "com.android.support:support-v4:17.0.+"
compile "com.android.support:appcompat-v7:17.0.+"

No content to map due to end-of-input jackson parser

I could fix this error. In my case, the problem was at client side. By mistake I did not close the stream that I was writing to server. I closed stream and it worked fine. Even the error sounds like server was not able to identify the end-of-input.

OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
out.write(jsonstring.getBytes());
out.close() ; //This is what I did

Select records from today, this week, this month php mysql

Everybody seems to refer to date being a column in the table.
I dont think this is good practice. The word date might just be a keyword in some coding language (maybe Oracle) so please change the columnname date to maybe JDate.
So will the following work better:

SELECT * FROM jokes WHERE JDate >= CURRENT_DATE() ORDER BY JScore DESC;

So we have a table called Jokes with columns JScore and JDate.

MySQL query String contains

Quite simple actually:

mysql_query("
SELECT *
FROM `table`
WHERE `column` LIKE '%{$needle}%'
");

The % is a wildcard for any characters set (none, one or many). Do note that this can get slow on very large datasets so if your database grows you'll need to use fulltext indices.

Using gdb to single-step assembly code outside specified executable causes error "cannot find bounds of current function"

You can use stepi or nexti (which can be abbreviated to si or ni) to step through your machine code.

How to set default font family in React Native?

Add

"rnpm": {
  "assets": [
 "./assets/fonts/"
  ]
}

in package.json then run react-native link

How to execute powershell commands from a batch file?

This is what the code would look like in a batch file(tested, works):

powershell -Command "& {set-location 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings'; set-location ZoneMap\Domains; new-item SERVERNAME; set-location SERVERNAME; new-itemproperty . -Name http -Value 2 -Type DWORD;}"

Based on the information from:

http://dmitrysotnikov.wordpress.com/2008/06/27/powershell-script-in-a-bat-file/

PHP Header redirect not working

If I understand correctly, something has already sent out from header.php (maybe some HTML) so the headers have been set. You may need to recheck your header.php file for any part that may output HTML or spaces before your first

EDIT: I am now sure that it is caused from header.php since you have those HTML output. You can fix this by remove the "include('header.php');" line and copy the following code to your file instead.

include('class.user.php');
include('class.Connection.php');

        $date = date('Y-m-j');

Load content of a div on another page

Yes, see "Loading Page Fragments" on http://api.jquery.com/load/.

In short, you add the selector after the URL. For example:

$('#result').load('ajax/test.html #container');

Does mobile Google Chrome support browser extensions?

Just use a different browser. Follow the steps given below to install Chrome extensions on your Android device.

Step 1: Open Google Play Store and download Yandex Browser. Install the browser on your phone.

Step 2: In the URL box of your new browser, open 'chrome.google.com/webstore’ by entering the same in the URL address.

Step 3: Look for the Chrome extension that you want and once you have it, tap on 'Add to Chrome.’

The added Chrome extension will now be automatically added to the Yandex browser.

How do I delete rows in a data frame?

Delete Dan from employee.data - No need to manage a new data.frame.

employee.data <- subset(employee.data, name!="Dan")

How to Lock the data in a cell in excel using vba

Sub LockCells()

Range("A1:A1").Select

Selection.Locked = True

Selection.FormulaHidden = False

ActiveSheet.Protect DrawingObjects:=False, Contents:=True, Scenarios:= False, AllowFormattingCells:=True, AllowFormattingColumns:=True, AllowFormattingRows:=True, AllowInsertingColumns:=True, AllowInsertingRows:=True, AllowInsertingHyperlinks:=True, AllowDeletingColumns:=True, AllowDeletingRows:=True, AllowSorting:=True, AllowFiltering:=True, AllowUsingPivotTables:=True

End Sub

newline in <td title="">

Using &#xA; Works in Chrome to create separate lines in a tooltip.

import an array in python

Another option is numpy.genfromtxt, e.g:

import numpy as np
data = np.genfromtxt("myfile.dat",delimiter=",")

This will make data a numpy array with as many rows and columns as are in your file

How to use npm with node.exe?

I've just installed 64 bit Node.js v0.12.0 for Windows 8.1 from here. It's about 8MB and since it's an MSI you just double click to launch. It will automatically set up your environment paths etc.

Then to get the command line it's just [Win-Key]+[S] for search and then enter "node.js" as your search phrase.

Choose the Node.js Command Prompt entry NOT the Node.js entry.

Both will given you a command prompt but only the former will actually work. npm is built into that download so then just npm -whatever at prompt.

How do you calculate log base 2 in Java for integers?

Some cases just worked when I used Math.log10:

public static double log2(int n)
{
    return (Math.log10(n) / Math.log10(2));
}

Keyboard shortcuts with jQuery

I recently wrote a standalone library for this. It does not require jQuery, but you can use it with jQuery no problem. It's called Mousetrap.

You can check it out at http://craig.is/killing/mice

Kill some processes by .exe file name

You can use Process.GetProcesses() to get the currently running processes, then Process.Kill() to kill a process.

What's the difference between window.location= and window.location.replace()?

window.location adds an item to your history in that you can (or should be able to) click "Back" and go back to the current page.

window.location.replace replaces the current history item so you can't go back to it.

See window.location:

assign(url): Load the document at the provided URL.

replace(url):Replace the current document with the one at the provided URL. The difference from the assign() method is that after using replace() the current page will not be saved in session history, meaning the user won't be able to use the Back button to navigate to it.

Oh and generally speaking:

window.location.href = url;

is favoured over:

window.location = url;

Error: Unexpected value 'undefined' imported by the module

The issue is that there is at least one import for which source file is missing.

For example I got the same error when I was using

       import { AppRoutingModule } from './app-routing.module';

But the file './app-routing.module' was not there in given path.

I removed this import and error went away.

Java: Calling a super method which calls an overridden method

During my research for a similar case, I have been ending up by checking the stack trace in the subclass method to find out from where the call is coming from. There are probably smarter ways to do so, but it works out for me and it's a dynamic approach.

public void method2(){
        Exception ex=new Exception();
        StackTraceElement[] ste=ex.getStackTrace();
        if(ste[1].getClassName().equals(this.getClass().getSuperclass().getName())){
            super.method2();
        }
        else{
            //subclass method2 code
        }
}

I think the question to have a solution for the case is reasonable. There are of course ways to solve the issue with different method names or even different parameter types, like already mentioned in the thread, but in my case I dindn't like to confuse by different method names.

Delete cookie by name?

I'm not really sure if that was the situation with Roundcube version from May '12, but for current one the answer is that you can't delete roundcube_sessauth cookie from JavaScript, as it is marked as HttpOnly. And this means it's not accessible from JS client side code and can be removed only by server side script or by direct user action (via some browser mechanics like integrated debugger or some plugin).

MySQL INNER JOIN select only one row from second table

There are two problems with your query:

  1. Every table and subquery needs a name, so you have to name the subquery INNER JOIN (SELECT ...) AS p ON ....
  2. The subquery as you have it only returns one row period, but you actually want one row for each user. For that you need one query to get the max date and then self-join back to get the whole row.

Assuming there are no ties for payments.date, try:

    SELECT u.*, p.* 
    FROM (
        SELECT MAX(p.date) AS date, p.user_id 
        FROM payments AS p
        GROUP BY p.user_id
    ) AS latestP
    INNER JOIN users AS u ON latestP.user_id = u.id
    INNER JOIN payments AS p ON p.user_id = u.id AND p.date = latestP.date
    WHERE u.package = 1

Installing Java 7 (Oracle) in Debian via apt-get

Managed to get answer after do some google..

echo "deb http://ppa.launchpad.net/webupd8team/java/ubuntu precise main" | tee -a /etc/apt/sources.list
echo "deb-src http://ppa.launchpad.net/webupd8team/java/ubuntu precise main" | tee -a /etc/apt/sources.list
apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys EEA14886
apt-get update
# Java 7
apt-get install oracle-java7-installer
# For Java 8 command is:
apt-get install oracle-java8-installer

Why does SSL handshake give 'Could not generate DH keypair' exception?

The problem is the prime size. The maximum-acceptable size that Java accepts is 1024 bits. This is a known issue (see JDK-6521495).

The bug report that I linked to mentions a workaround using BouncyCastle's JCE implementation. Hopefully that should work for you.

UPDATE

This was reported as bug JDK-7044060 and fixed recently.

Note, however, that the limit was only raised to 2048 bit. For sizes > 2048 bit, there is JDK-8072452 - Remove the maximum prime size of DH Keys; the fix appears to be for 9.

Android java.lang.NoClassDefFoundError

I've run into this problem a few times opening old projects that include other Android libraries. What works for me is to:

move Android to the top in the Order and Export tab and deselecting it.

Yes, this really makes the difference. Maybe it's time for me to ditch ADT for Android Studio!

How do I clone a single branch in Git?

For the newbies like me, just run the code below

git clone https://gitlab.com/repo/repo.git --branch <name of branch> --single-branch

Getting IPV4 address from a sockaddr structure

Once sockaddr cast to sockaddr_in, it becomes this:

struct sockaddr_in {
    u_short     sin_family;
    u_short     sin_port;
    struct      in_addr sin_addr;
    char        sin_zero[8];
};

TypeScript enum to object array

If you are using ES8

For this case only it will work perfectly fine. It will give you value array of the given enum.

enum Colors {
  WHITE = 0,
  BLACK = 1,
  BLUE = 3
}

const colorValueArray = Object.values(Colors); //[ 'WHITE', 'BLACK', 'BLUE', 0, 1, 3 ]

You will get colorValueArray like this [ 'WHITE', 'BLACK', 'BLUE', 0, 1, 3 ]. All the keys will be in first half of the array and all the values in second half.

Even this kind of enum will work fine

enum Operation {
    READ,
    WRITE,
    EXECUTE
}

But this solution will not work for Heterogeneous enums like this

enum BooleanLikeHeterogeneousEnum {
  No = 0,
  Yes = "YES",
}

How to import local packages without gopath

Run:

go mod init yellow

Then create a file yellow.go:

package yellow

func Mix(s string) string {
   return s + "Yellow"
}

Then create a file orange/orange.go:

package main
import "yellow"

func main() {
   s := yellow.Mix("Red")
   println(s)
}

Then build:

go build

https://golang.org/doc/code.html

Python: How to keep repeating a program until a specific input is obtained?

Easier way:

#required_number = 18

required_number=input("Insert a number: ")
while required_number != 18
    print("Oops! Something is wrong")
    required_number=input("Try again: ")
if required_number == '18'
    print("That's right!")

#continue the code

How can I find the number of arguments of a Python function?

inspect.getargspec() to meet your needs

from inspect import getargspec

def func(a, b):
    pass
print len(getargspec(func).args)

How to set the value of a hidden field from a controller in mvc

Please find code for respected region.

Controller

ViewBag.hdnFlag= Session["hdnFlag"];

View

<input type="hidden" value="@ViewBag.hdnFlag" id="hdnFlag" />

JavaScript

var hdnFlagVal = $("#hdnFlag").val();

Why doesn't "System.out.println" work in Android?

I dont having fancy IDE to use LogCat as I use a mobile IDE.

I had to use various other methods and I have the classes and utilties for you to use if you need.

  1. class jav.android.Msg. Has a collection of static methods. A: methods for printing android TOASTS. B: methods for popping up a dialog box. Each method requires a valid Context. You can set the default context.

  2. A more ambitious way, An Android Console. You instantiate a handle to the console in your app, which fires up the console(if it is installed), and you can write to the console. I recently updated the console to implement reading input from the console. Which doesnt return until the input is recieved, like a regular console. A: Download and install Android Console( get it from me) B: A java file is shipped with it(jav.android.console.IConsole). Place it at the appropriate directory. It contains the methods to operate Android Console. C: Call the constructor which completes the initialization. D: read<*> and write the console. There is still work to do. Namely, since OnServiceConnected is not called immediately, You cannot use IConsole in the same function you instantiated it.

  3. Before creating Android Console, I created Console Dialog, which was a dialog operating in the same app to resemble a console. Pro: no need to wait on OnServiceConnected to use it. Con: When app crashes, you dont get the message that crashed the app.

Since Android Console is a seperate app in a seperate process, if your app crashes, you definately get to see the error. Furthermore IConsole sets an uncaught exception handler in your app incase you are not keen in exception handling. It pretty much prints the stack traces and exception messages to Android Console. Finally, if Android Console crashes, it sends its stacktrace and exceptions to you and you can choose an app to read it. Actually, AndroidConsole is not required to crash.

Edit Extras I noticed that my while APK Builder has no LogCat; AIDE does. Then I realized a pro of using my Android Console anyhow.

  1. Android Console is design to take up only a portion of the screen, so you can see both your app, and data emitted from your app to the console. This is not possible with AIDE. So I I want to touch the screen and see coordinates, Android Console makes this easy.

  2. Android Console is designed to pop up when you write to it.

  3. Android Console will hide when you backpress.

Get started with Latex on Linux

LaTeX comes with most Linux distributions in the form of the teTeX distribution. Find all packages with 'teTeX' in the name and install them.

  • Most editors such as vim or emacs come with TeX editing modes. You can also get WYSIWIG-ish front-ends (technically WYSIWYM), of which perhaps the best known is LyX.

  • The best quick intro to LaTeX is Oetiker's 'The not so short intro to LaTeX'

  • LaTeX works like a compiler. You compile the LaTeX document (which can include other files), which generates a file called a .dvi (device independent). This can be post-processed to various formats (including PDF) with various post-processors.

  • To do PDF, use dvips and use the flag -PPDF (IIRC - I don't have a makefile to hand) to produce a PS with font rendering set up for conversion to pdf. PDF conversion can then be done with ps2pdf or distiller (if you have this).

  • The best format for including graphics in this environment is eps (Encapsulated Postscript) although not all software produces well-behaved postscript. Photographs in jpeg or other formats can be included using various mechanisms.

what is Array.any? for javascript

I believe this to be the cleanest and readable option:

var empty = [];
empty.some(x => x); //returns false

How to restore the permissions of files and directories within git if they have been modified?

I use git from cygwin on Windows, the git apply solution doesn't work for me. Here is my solution, run chmod on every file to reset its permissions.

#!/bin/bash
IFS=$'\n'
for c in `git diff -p |sed -n '/diff --git/{N;s/diff --git//g;s/\n/ /g;s# a/.* b/##g;s/old mode //g;s/\(.*\) 100\(.*\)/chmod \2 \1/g;p}'`
do
        eval $c
done
unset IFS

Finding an item in a List<> using C#

item = objects.Find(obj => obj.property==myValue);

Passing A List Of Objects Into An MVC Controller Method Using jQuery Ajax

Using NickW's suggestion, I was able to get this working using things = JSON.stringify({ 'things': things }); Here is the complete code.

$(document).ready(function () {
    var things = [
        { id: 1, color: 'yellow' },
        { id: 2, color: 'blue' },
        { id: 3, color: 'red' }
    ];      

    things = JSON.stringify({ 'things': things });

    $.ajax({
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        type: 'POST',
        url: '/Home/PassThings',
        data: things,
        success: function () {          
            $('#result').html('"PassThings()" successfully called.');
        },
        failure: function (response) {          
            $('#result').html(response);
        }
    }); 
});


public void PassThings(List<Thing> things)
{
    var t = things;
}

public class Thing
{
    public int Id { get; set; }
    public string Color { get; set; }
}

There are two things I learned from this:

  1. The contentType and dataType settings are absolutely necessary in the ajax() function. It won't work if they are missing. I found this out after much trial and error.

  2. To pass in an array of objects to an MVC controller method, simply use the JSON.stringify({ 'things': things }) format.

I hope this helps someone else!

Didn't find class "com.google.firebase.provider.FirebaseInitProvider"?

Just override the following method in your application class.

public class YourApplication extends Application {

    @Override
    protected void attachBaseContext(Context context) {
        super.attachBaseContext(context);
        MultiDex.install(this);
    }
    @Override
    public void onCreate() {
        super.onCreate();
        Realm.init(this); //initialize other plugins 

    }
}

Explain the concept of a stack frame in a nutshell

If you understand stack very well then you will understand how memory works in program and if you understand how memory works in program you will understand how function store in program and if you understand how function store in program you will understand how recursive function works and if you understand how recursive function works you will understand how compiler works and if you understand how compiler works your mind will works as compiler and you will debug any program very easily

Let me explain how stack works:

First you have to know how functions are represented in stack :

Heap stores dynamically allocated values.
Stack stores automatic allocation and deletion values.

enter image description here

Let's understand with example :

def hello(x):
    if x==1:
        return "op"
    else:
        u=1
        e=12
        s=hello(x-1)
        e+=1
        print(s)
        print(x)
        u+=1
    return e

hello(4)

Now understand parts of this program :

enter image description here

Now let's see what is stack and what are stack parts:

enter image description here

Allocation of the stack :

Remember one thing: if any function's return condition gets satisfied, no matter it has loaded the local variables or not, it will immediately return from stack with it's stack frame. It means that whenever any recursive function get base condition satisfied and we put a return after base condition, the base condition will not wait to load local variables which are located in the “else” part of program. It will immediately return the current frame from the stack following which the next frame is now in the activation record.

See this in practice:

enter image description here

Deallocation of the block:

So now whenever a function encounters return statement, it delete the current frame from the stack.

While returning from the stack, values will returned in reverse of the original order in which they were allocated in stack.

enter image description here

How to view DLL functions?

Without telling us what language this dll/assembly is from, we can only guess.

So how about .NET Reflector

What uses are there for "placement new"?

I've used it to create objects based on memory containing messages received from the network.

Laravel - Eloquent or Fluent random row

tl;dr: It's nowadays implemented into Laravel, see "edit 3" below.


Sadly, as of today there are some caveats with the ->orderBy(DB::raw('RAND()')) proposed solution:

  • It isn't DB-agnostic. e.g. SQLite and PostgreSQL use RANDOM()
  • Even worse, this solution isn't applicable anymore since this change:

    $direction = strtolower($direction) == 'asc' ? 'asc' : 'desc';


edit: Now you can use the orderByRaw() method: ->orderByRaw('RAND()'). However this is still not DB-agnostic.

FWIW, CodeIgniter implements a special RANDOM sorting direction, which is replaced with the correct grammar when building query. Also it seems to be fairly easy to implement. Looks like we have a candidate for improving Laravel :)

update: here is the issue about this on GitHub, and my pending pull request.


edit 2: Let's cut the chase. Since Laravel 5.1.18 you can add macros to the query builder:

use Illuminate\Database\Query\Builder;

Builder::macro('orderByRandom', function () {

    $randomFunctions = [
        'mysql'  => 'RAND()',
        'pgsql'  => 'RANDOM()',
        'sqlite' => 'RANDOM()',
        'sqlsrv' => 'NEWID()',
    ];

    $driver = $this->getConnection()->getDriverName();

    return $this->orderByRaw($randomFunctions[$driver]);
});

Usage:

User::where('active', 1)->orderByRandom()->limit(10)->get();

DB::table('users')->where('active', 1)->orderByRandom()->limit(10)->get();


edit 3: Finally! Since Laravel 5.2.33 (changelog, PR #13642) you can use the native method inRandomOrder():

User::where('active', 1)->inRandomOrder()->limit(10)->get();

DB::table('users')->where('active', 1)->inRandomOrder()->limit(10)->get();

Using jquery to delete all elements with a given id

if you want to remove all elements with matching ID parts, for example:

<span id='myID_123'>
<span id='myID_456'>
<span id='myID_789'>

try this:

$("span[id*=myID]").remove();

don't forget the '*' - this will remove them all at once - cheers

Working Demo

Update query using Subquery in Sql Server

Here is a nice explanation of update operation with some examples. Although it is Postgres site, but the SQL queries are valid for the other DBs, too. The following examples are intuitive to understand.

-- Update contact names in an accounts table to match the currently assigned salesmen:

UPDATE accounts SET (contact_first_name, contact_last_name) =
    (SELECT first_name, last_name FROM salesmen
     WHERE salesmen.id = accounts.sales_id);

-- A similar result could be accomplished with a join:

UPDATE accounts SET contact_first_name = first_name,
                    contact_last_name = last_name
  FROM salesmen WHERE salesmen.id = accounts.sales_id;

However, the second query may give unexpected results if salesmen.id is not a unique key, whereas the first query is guaranteed to raise an error if there are multiple id matches. Also, if there is no match for a particular accounts.sales_id entry, the first query will set the corresponding name fields to NULL, whereas the second query will not update that row at all.

Hence for the given example, the most reliable query is like the following.

UPDATE tempDataView SET (marks) =
    (SELECT marks FROM tempData
     WHERE tempDataView.Name = tempData.Name);

how to call url of any other website in php

Depending on what you mean, either redirect or use curl.

best OCR (Optical character recognition) example in android

Like you I also faced many problems implementing OCR in Android, but after much Googling I found the solution, and it surely is the best example of OCR.

Let me explain using step-by-step guidance.

First, download the source code from https://github.com/rmtheis/tess-two.

Import all three projects. After importing you will get an error. To solve the error you have to create a res folder in the tess-two project

enter image description here

First, just create res folder in tess-two by tess-two->RightClick->new Folder->Name it "res"

After doing this in all three project the error should be gone.

Now download the source code from https://github.com/rmtheis/android-ocr, here you will get best example.

Now you just need to import it into your workspace, but first you have to download android-ndk from this site:

http://developer.android.com/tools/sdk/ndk/index.html i have windows 7 - 32 bit PC so I have download http://dl.google.com/android/ndk/android-ndk-r9-windows-x86.zip this file

Now extract it suppose I have extract it into E:\Software\android-ndk-r9 so I will set this path on Environment Variable

Right Click on MyComputer->Property->Advance-System-Settings->Advance->Environment Variable-> find PATH on second below Box and set like path like below picture

enter image description here

done it

Now open cmd and go to on D:\Android Workspace\tess-two like below

enter image description here

If you have successfully set up environment variable of NDK then just type ndk-build just like above picture than enter you will not get any kind of error and all file will be compiled successfully:

Now download other source code also from https://github.com/rmtheis/tess-two , and extract and import it and give it name OCRTest, like in my PC which is in D:\Android Workspace\OCRTest

enter image description here

Import test-two in this and run OCRTest and run it; you will get the best example of OCR.

Is there a way to create and run javascript in Chrome?

if you don't want to create an explicitly a js file but still want to test your javascript code, you can use snippets to run your JS code.

Follow the steps here:

  1. Open Dev Tools
  2. Go to Sources Tab
  3. Under Sources tab go to snippets, + New snippet
  4. Past your JS code in the editor then run command + enter in Mac. You should see the output in console if you are using console.log or similar to test. You can edit the current web page that you have open or run scripts, load more javascript files. (Just note: this snippets are not stored on as a js file, unless you explicitly did, on your computer so if you remove chrome you will lose all your snippets);
  5. You also have a option to save as your snippet if you right click on your snippet.

code javascript using snippets in dev tools

Way to ng-repeat defined number of times instead of repeating over array?

If n is not too high, another option could be to use split('') with a string of n characters :

<div ng-controller="MainCtrl">
<div ng-repeat="a in 'abcdefgh'.split('')">{{$index}}</div>
</div>

How can I load Partial view inside the view?

If you do it with a @Html.ActionLink() then loading the PartialView is handled as a normal request when clicking a anchor-element, i.e. load new page with the reponse of the PartialViewResult method.
If you want to load it immedialty, then you use @Html.RenderPartial("_LoadView") or @Html.RenderAction("Load").
If you want to do it upon userinteraction (i.e. clicking a link) then you need to use AJAX --> @Ajax.ActionLink()

Get the last non-empty cell in a column in Google Sheets

Although the question is already answered, there is an eloquent way to do it.

Use just the column name to denote last non-empty row of that column.

For example:

If your data is in A1:A100 and you want to be able to add some more data to column A, say it can be A1:A105 or even A1:A1234 later, you can use this range:

A1:A

Sample

So to get last non-empty value in a range, we will use 2 functions:

  • COUNTA
  • INDEX

The answer is =INDEX(B3:B,COUNTA(B3:B)).

Here is the explanation:

COUNTA(range) returns number of values in a range, we can use this to get the count of rows.

INDEX(range, row, col) returns the value in a range at position row and col (col=1 if not specified)

Examples:

INDEX(A1:C5,1,1) = A1
INDEX(A1:C5,1) = A1 # implicitly states that col = 1
INDEX(A1:C5,1,2) = A2
INDEX(A1:C5,2,1) = B1
INDEX(A1:C5,2,2) = B2
INDEX(A1:C5,3,1) = C1
INDEX(A1:C5,3,2) = C2

For the picture above, our range will be B3:B. So we will count how many values are there in range B3:B by COUNTA(B3:B) first. In the left side, it will produce 8 since there are 8 values while it will produce 9 in the right side. We also know that the last value is in the 1st column of the range B3:B so the col parameter of INDEX must be 1 and the row parameter should be COUNTA(B3:B).

PS: please upvote @bloodymurderlive's answer since he wrote it first, I'm just explaining it here.

html 5 audio tag width

Set it the same way you'd set the width of any other HTML element, with CSS:

audio { width: 200px; }

Note that audio is an inline element by default in Firefox, so you might also want to set it to display: block. Here's an example.

nginx - nginx: [emerg] bind() to [::]:80 failed (98: Address already in use)

i fixed this by running sudo apachectl stop - turns out apache was running in the background and prevented nginx from starting on the desired port.

On ubuntu run sudo /etc/init.d/apache2 stop

Sql connection-string for localhost server

Using the default instance (i.e., MSSQLSERVER, use the DOT (.))

<add name="CONNECTION_STRING_NAME" connectionString="Data Source=.;Initial Catalog=DATABASE_NAME;Integrated Security=True;" />

What is VanillaJS?

VanillaJS is a term for library/framework free javascript.

Its sometimes ironically referred to as a library, as a joke for people who could be seen as mindlessly using different frameworks, especially jQuery.

Some people have gone so far to release this library, usually with an empty or comment-only js file.

Best way to represent a Grid or Table in AngularJS with Bootstrap 3?

TrNgGrid is working great so far. Here are the reasons I prefer it to ng-grid and moved to this component

  • It makes table elements so it can be bootswatched and use all the power of bootstrap .css (ng-grid uses jQuery UI themes).

  • Simple, well documented grid options.

  • Server size paging works

How to change title of Activity in Android?

There's a faster way, just use

YourActivity.setTitle("New Title");

You can also find it inside the onCreate() with this, for example:

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        this.setTitle("My Title");
    }

By the way, what you simply cannot do is call setTitle() in a static way without passing any Activity object.

Disable future dates after today in Jquery Ui Datepicker

Change maxDate to current date

maxDate: new Date()

It will set current date as maximum value.

MS SQL Date Only Without Time

DATEADD(d, 0, DATEDIFF(d, 0, [tstamp]))

Edit: While this will remove the time portion of your datetime, it will also make the condition non SARGable. If that's important for this query, an indexed view or a between clause is more appropriate.

Convert int to ASCII and back in Python

Use hex(id)[2:] and int(urlpart, 16). There are other options. base32 encoding your id could work as well, but I don't know that there's any library that does base32 encoding built into Python.

Apparently a base32 encoder was introduced in Python 2.4 with the base64 module. You might try using b32encode and b32decode. You should give True for both the casefold and map01 options to b32decode in case people write down your shortened URLs.

Actually, I take that back. I still think base32 encoding is a good idea, but that module is not useful for the case of URL shortening. You could look at the implementation in the module and make your own for this specific case. :-)

Delete with "Join" in Oracle sql Query

Based on the answer I linked to in my comment above, this should work:

delete from
(
select pf.* From PRODUCTFILTERS pf 
where pf.id>=200 
And pf.rowid in 
  (
     Select rowid from PRODUCTFILTERS 
     inner join PRODUCTS on PRODUCTFILTERS.PRODUCTID = PRODUCTS.ID 
     And PRODUCTS.NAME= 'Mark'
  )
); 

or

delete from PRODUCTFILTERS where rowid in
(
select pf.rowid From PRODUCTFILTERS pf 
where pf.id>=200 
And pf.rowid in 
  (
     Select PRODUCTFILTERS.rowid from PRODUCTFILTERS 
     inner join PRODUCTS on PRODUCTFILTERS.PRODUCTID = PRODUCTS.ID 
     And PRODUCTS.NAME= 'Mark'
  )
); 

tsconfig.json: Build:No inputs were found in config file

add .ts file location in 'include' tag then compile work fine. ex.

"include": [
"wwwroot/**/*" ]

Delete default value of an input text on click

Here is a jQuery solution. I always let the default value reappear when a user clears the input field.

<input name="Email" value="What's your programming question ? be specific." type="text" id="Email" value="[email protected]" />

<script>
$("#Email").blur(
    function (){
        if ($(this).val() == "")
            $(this).val($(this).prop("defaultValue"));
        }
).focus(
    function (){
        if ($(this).val() == $(this).prop("defaultValue"))
            $(this).val("");
    }
);
</script>

C# - How to get Program Files (x86) on Windows 64 bit

The function below will return the x86 Program Files directory in all of these three Windows configurations:

  • 32 bit Windows
  • 32 bit program running on 64 bit Windows
  • 64 bit program running on 64 bit windows

 

static string ProgramFilesx86()
{
    if( 8 == IntPtr.Size 
        || (!String.IsNullOrEmpty(Environment.GetEnvironmentVariable("PROCESSOR_ARCHITEW6432"))))
    {
        return Environment.GetEnvironmentVariable("ProgramFiles(x86)");
    }

    return Environment.GetEnvironmentVariable("ProgramFiles");
}

How Best to Compare Two Collections in Java and Act on Them?

You can use Java 8 streams, for example

set1.stream().filter(s -> set2.contains(s)).collect(Collectors.toSet());

or Sets class from Guava:

Set<String> intersection = Sets.intersection(set1, set2);
Set<String> difference = Sets.difference(set1, set2);
Set<String> symmetricDifference = Sets.symmetricDifference(set1, set2);
Set<String> union = Sets.union(set1, set2);

TextView bold via xml file?

Example:

use: android:textStyle="bold"

 <TextView
    android:id="@+id/txtVelocidade"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_above="@+id/txtlatitude"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="34dp"
    android:textStyle="bold"
    android:text="Aguardando GPS"
    android:textAppearance="?android:attr/textAppearanceLarge" />

Set session variable in laravel

You can try

 Session::put('variable_Name', "Your Data Save Successfully !");  
 Session::get('variable_Name');

Response.Redirect with POST instead of Get?

Copy-pasteable code based on Pavlo Neyman's method

RedirectPost(string url, T bodyPayload) and GetPostData() are for those who just want to dump some strongly typed data in the source page and fetch it back in the target one. The data must be serializeable by NewtonSoft Json.NET and you need to reference the library of course.

Just copy-paste into your page(s) or better yet base class for your pages and use it anywhere in you application.

My heart goes out to all of you who still have to use Web Forms in 2019 for whatever reason.

        protected void RedirectPost(string url, IEnumerable<KeyValuePair<string,string>> fields)
        {
            Response.Clear();

            const string template =
@"<html>
<body onload='document.forms[""form""].submit()'>
<form name='form' action='{0}' method='post'>
{1}
</form>
</body>
</html>";

            var fieldsSection = string.Join(
                    Environment.NewLine,
                    fields.Select(x => $"<input type='hidden' name='{HttpUtility.UrlEncode(x.Key)}' value='{HttpUtility.UrlEncode(x.Value)}'>")
                );

            var html = string.Format(template, HttpUtility.UrlEncode(url), fieldsSection);

            Response.Write(html);

            Response.End();
        }

        private const string JsonDataFieldName = "_jsonData";

        protected void RedirectPost<T>(string url, T bodyPayload)
        {
            var json = JsonConvert.SerializeObject(bodyPayload, Formatting.Indented);
            //explicit type declaration to prevent recursion
            IEnumerable<KeyValuePair<string, string>> postFields = new List<KeyValuePair<string, string>>()
                {new KeyValuePair<string, string>(JsonDataFieldName, json)};

            RedirectPost(url, postFields);

        }

        protected T GetPostData<T>() where T: class 
        {
            var urlEncodedFieldData = Request.Params[JsonDataFieldName];
            if (string.IsNullOrEmpty(urlEncodedFieldData))
            {
                return null;// default(T);
            }

            var fieldData = HttpUtility.UrlDecode(urlEncodedFieldData);

            var result = JsonConvert.DeserializeObject<T>(fieldData);
            return result;
        }

What is the difference between Sprint and Iteration in Scrum and length of each Sprint?

  1. Sprint is just the term for an iteration.
  2. You can change the Sprint length to be anything you want, but likely you'll want to try to find an amount of time that "works well" (which may mean any number of things for your team) and end up sticking with it over time.

Problems with jQuery getJSON using local files in Chrome

This code worked fine with sheet.jsonlocally with browser-sync as the local server. -But when on my remote server I got a 404 for the sheet.json file using Chrome. It worked fine in Safari and Firefox. -Changed the name sheet.json to sheet.JSON. Then it worked on the remote server. Anyone else have this experience?

getthejason = function(){
var dataurl = 'data/sheet.JSON';
var xhr = new XMLHttpRequest();
xhr.open('GET', dataurl, true);
xhr.responseType = 'text';
xhr.send();
console.log('getthejason!');

xhr.onload = function() {
.....
}

How to create a number picker dialog?

To show NumberPicker in AlertDialog use this code :

final AlertDialog.Builder d = new AlertDialog.Builder(context);
LayoutInflater inflater = this.getLayoutInflater();
View dialogView = inflater.inflate(R.layout.number_picker_dialog, null);
d.setTitle("Title");
d.setMessage("Message");
d.setView(dialogView);
final NumberPicker numberPicker = (NumberPicker) dialogView.findViewById(R.id.dialog_number_picker);
numberPicker.setMaxValue(50);
numberPicker.setMinValue(1);
numberPicker.setWrapSelectorWheel(false);
numberPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
    @Override
    public void onValueChange(NumberPicker numberPicker, int i, int i1) {
        Log.d(TAG, "onValueChange: ");
    }
});
d.setPositiveButton("Done", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialogInterface, int i) {
        Log.d(TAG, "onClick: " + numberPicker.getValue());
    }
});
d.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialogInterface, int i) {
    }
});
AlertDialog alertDialog = d.create();
alertDialog.show();

number_picker_dialog.xml

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:gravity="center_horizontal">

<NumberPicker
    android:id="@+id/dialog_number_picker"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>
</LinearLayout>

How to use MD5 in javascript to transmit a password

I would suggest you to use CryptoJS in this case.

Basically CryptoJS is a growing collection of standard and secure cryptographic algorithms implemented in JavaScript using best practices and patterns. They are fast, and they have a consistent and simple interface.

So In case you want calculate hash(MD5) of your password string then do as follows :

<script src="http://crypto-js.googlecode.com/svn/tags/3.0.2/build/rollups/md5.js"></script>
<script>
    var passhash = CryptoJS.MD5(password).toString();

    $.post(
      'includes/login.php', 
      { user: username, pass: passhash },
      onLogin, 
      'json' );
</script>

So this script will post hash of your password string to the server.

For further info and support on other hash calculating algorithms you can visit at:

http://code.google.com/p/crypto-js/

How can get the text of a div tag using only javascript (no jQuery)

You'll probably want to try textContent instead of innerHTML.

Given innerHTML will return DOM content as a String and not exclusively the "text" in the div. It's fine if you know that your div contains only text but not suitable if every use case. For those cases, you'll probably have to use textContent instead of innerHTML

For example, considering the following markup:

<div id="test">
  Some <span class="foo">sample</span> text.
</div>

You'll get the following result:

var node = document.getElementById('test'),

htmlContent = node.innerHTML,
// htmlContent = "Some <span class="foo">sample</span> text."

textContent = node.textContent;
// textContent = "Some sample text."

See MDN for more details:

How to retrieve form values from HTTPPOST, dictionary or?

If you want to get the form data directly from Http request, without any model bindings or FormCollection you can use this:

[HttpPost] 
public ActionResult SubmitAction() {

    // This will return an string array of all keys in the form.
    // NOTE: you specify the keys in form by the name attributes e.g:
    // <input name="this is the key" value="some value" type="test" />
    var keys = Request.Form.AllKeys;

    // This will return the value for the keys.
    var value1 = Request.Form.Get(keys[0]);
    var value2 = Request.Form.Get(keys[1]);
}

What is the `data-target` attribute in Bootstrap 3?

The toggle tells Bootstrap what to do and the target tells Bootstrap which element is going to open. So whenever a link like that is clicked, a modal with an id of “basicModal” will appear.

MVC - Set selected value of SelectList

Use LINQ and add the condition on the "selected" as a question mark condition.

    var listSiteId = (from site in db.GetSiteId().ToList()
                                      select new SelectListItem
                                      {
                                          Value = site.SITEID,
                                          Text = site.NAME,
                                          Selected = (dimension.DISPLAYVALUE == site.SITEID) ? true : false,
                                      }).ToList();
                    ViewBag.SiteId = listSiteId;

Highlight Bash/shell code in Markdown files

Bitbucket uses CodeMirror for syntax highlighting. For Bash or shell you can use sh, bash, or zsh. More information can be found at Configuring syntax highlighting for file extensions and Code mirror language modes.

Error handling in Bash

Use a trap!

tempfiles=( )
cleanup() {
  rm -f "${tempfiles[@]}"
}
trap cleanup 0

error() {
  local parent_lineno="$1"
  local message="$2"
  local code="${3:-1}"
  if [[ -n "$message" ]] ; then
    echo "Error on or near line ${parent_lineno}: ${message}; exiting with status ${code}"
  else
    echo "Error on or near line ${parent_lineno}; exiting with status ${code}"
  fi
  exit "${code}"
}
trap 'error ${LINENO}' ERR

...then, whenever you create a temporary file:

temp_foo="$(mktemp -t foobar.XXXXXX)"
tempfiles+=( "$temp_foo" )

and $temp_foo will be deleted on exit, and the current line number will be printed. (set -e will likewise give you exit-on-error behavior, though it comes with serious caveats and weakens code's predictability and portability).

You can either let the trap call error for you (in which case it uses the default exit code of 1 and no message) or call it yourself and provide explicit values; for instance:

error ${LINENO} "the foobar failed" 2

will exit with status 2, and give an explicit message.

How to reload page the page with pagination in Angular 2?

This should technically be achievable using window.location.reload():

HTML:

<button (click)="refresh()">Refresh</button>

TS:

refresh(): void {
    window.location.reload();
}

Update:

Here is a basic StackBlitz example showing the refresh in action. Notice the URL on "/hello" path is retained when window.location.reload() is executed.

What exactly does the Access-Control-Allow-Credentials header do?

By default, CORS does not include cookies on cross-origin requests. This is different from other cross-origin techniques such as JSON-P. JSON-P always includes cookies with the request, and this behavior can lead to a class of vulnerabilities called cross-site request forgery, or CSRF.

In order to reduce the chance of CSRF vulnerabilities in CORS, CORS requires both the server and the client to acknowledge that it is ok to include cookies on requests. Doing this makes cookies an active decision, rather than something that happens passively without any control.

The client code must set the withCredentials property on the XMLHttpRequest to true in order to give permission.

However, this header alone is not enough. The server must respond with the Access-Control-Allow-Credentials header. Responding with this header to true means that the server allows cookies (or other user credentials) to be included on cross-origin requests.

You also need to make sure your browser isn't blocking third-party cookies if you want cross-origin credentialed requests to work.

Note that regardless of whether you are making same-origin or cross-origin requests, you need to protect your site from CSRF (especially if your request includes cookies).

How do I apply a CSS class to Html.ActionLink in ASP.NET MVC?

In C# it also works with a null as the 4th parameter.

@Html.ActionLink( "Front Page", "Index", "Home", null, new { @class = "MenuButtons" })

Oracle SQL - REGEXP_LIKE contains characters other than a-z or A-Z

if you want that not contains any of a-z and A-Z:

SELECT * FROM mytable WHERE NOT REGEXP_LIKE(column_1, '[A-Za-z]')

something like:

"98763045098" or "!%436%$7%$*#"

or other languages like persian, arabic and ... like this:

"???? ????"

Easy way to add drop down menu with 1 - 100 without doing 100 different options?

As everyone else has said, there isn't one in html; however, you could use PUG/Jade. In fact I do this often.

It would look something like this:

select
  - var i = 1
  while i <= 100
    option=i++

This would produce: screenshot of htmltojade.org

How to get next/previous record in MySQL?

I was attempting to do something similar to this, but I needed the results ordered by date since I can't rely on the ID field as a sortable column. Here's the solution I came up with.

First we find out the index of the desired record in the table, when it's sorted as we want:

SELECT row
FROM 
(SELECT @rownum:=@rownum+1 row, a.* 
FROM articles a, (SELECT @rownum:=0) r
ORDER BY date, id) as article_with_rows
WHERE id = 50;

Then decrement the result by 2 put it in the limit statement. For example the above returned 21 for me so I run:

SELECT * 
FROM articles
ORDER BY date, id
LIMIT 19, 3

Gives you your primary record along with it's next and previous records given your stated order.

I tried to do it as a single database call, but couldn't get the LIMIT statement to take a variable as one of it's parameters.

How to implement __iter__(self) for a container object (Python)

I normally would use a generator function. Each time you use a yield statement, it will add an item to the sequence.

The following will create an iterator that yields five, and then every item in some_list.

def __iter__(self):
   yield 5
   yield from some_list

Pre-3.3, yield from didn't exist, so you would have to do:

def __iter__(self):
   yield 5
   for x in some_list:
      yield x

How to validate array in Laravel?

Little bit more complex data, mix of @Laran's and @Nisal Gunawardana's answers

[ 
   {  
       "foodItemsList":[
    {
       "id":7,
       "price":240,
       "quantity":1
                },
               { 
                "id":8,
                "quantity":1
               }],
        "price":340,
        "customer_id":1
   },
   {   
      "foodItemsList":[
    {
       "id":7,
       "quantity":1
    },
    { 
        "id":8,
        "quantity":1
    }],
    "customer_id":2
   }
]

The validation rule will be

 return [
            '*.customer_id' => 'required|numeric|exists:customers,id',
            '*.foodItemsList.*.id' => 'required|exists:food_items,id',
            '*.foodItemsList.*.quantity' => 'required|numeric',
        ];

How to revert a "git rm -r ."?

Get list commit

git log  --oneline

For example, Stable commit has hash: 45ff319c360cd7bd5442c0fbbe14202d20ccdf81

git reset --hard 45ff319c360cd7bd5442c0fbbe14202d20ccdf81
git push -ff origin master

How to prevent rm from reporting that a file was not found?

I had same issue for cshell. The only solution I had was to create a dummy file that matched pattern before "rm" in my script.

How to manually trigger click event in ReactJS?

In a functional component this principle also works, it's just a slightly different syntax and way of thinking.

const UploadsWindow = () => {
  // will hold a reference for our real input file
  let inputFile = '';

  // function to trigger our input file click
  const uploadClick = e => {
    e.preventDefault();
    inputFile.click();
    return false;
  };

  return (
    <>
      <input
        type="file"
        name="fileUpload"
        ref={input => {
          // assigns a reference so we can trigger it later
          inputFile = input;
        }}
        multiple
      />

      <a href="#" className="btn" onClick={uploadClick}>
        Add or Drag Attachments Here
      </a>
    </>
  )

}

Connect to Oracle DB using sqlplus

sqlplus username/password@database

Eg:

sqlplus hr/hr@orcl

jQuery hasClass() - check for more than one class

Works for me:

 if ( $("element").hasClass( "class1") || $("element").hasClass("class2") ) {

 //do something here

 }

How to check empty DataTable

You can also simply write

 if (dt.Rows.Count == 0)
     {
         //DataTable does not contain records
     }        

How to show empty data message in Datatables

If you want to customize the message that being shown on empty table use this:

$('#example').dataTable( {
    "oLanguage": {
        "sEmptyTable":     "My Custom Message On Empty Table"
    }
} );

Since Datatable 1.10 you can do the following:

$('#example').DataTable( {
    "language": {
        "emptyTable":     "My Custom Message On Empty Table"
    }
} );

For the complete availble datatables custom messages for the table take a look at the following link reference/option/language

SSLHandshakeException: No subject alternative names present

Unlike some browsers, Java follows the HTTPS specification strictly when it comes to the server identity verification (RFC 2818, Section 3.1) and IP addresses.

When using a host name, it's possible to fall back to the Common Name in the Subject DN of the server certificate, instead of using the Subject Alternative Name.

When using an IP address, there must be a Subject Alternative Name entry (of type IP address, not DNS name) in the certificate.

You'll find more details about the specification and how to generate such a certificate in this answer.

Can't operator == be applied to generic types in C#?

I wrote the following function looking at the latest msdn. It can easily compare two objects x and y:

static bool IsLessThan(T x, T y) 
{
    return ((IComparable)(x)).CompareTo(y) <= 0;
}

VBA Copy Sheet to End of Workbook (with Hidden Worksheets)

Answer : I found this and wants to share it with you.

Sub Copier4()
   Dim x As Integer

   For x = 1 To ActiveWorkbook.Sheets.Count
      'Loop through each of the sheets in the workbook
      'by using x as the sheet index number.
      ActiveWorkbook.Sheets(x).Copy _
         After:=ActiveWorkbook.Sheets(ActiveWorkbook.Sheets.Count)
         'Puts all copies after the last existing sheet.
   Next
End Sub

But the question, can we use it with following code to rename the sheets, if yes, how can we do so?

Sub CreateSheetsFromAList()
Dim MyCell As Range, MyRange As Range
Set MyRange = Sheets("Summary").Range("A10")
Set MyRange = Range(MyRange, MyRange.End(xlDown))
For Each MyCell In MyRange
Sheets.Add After:=Sheets(Sheets.Count) 'creates a new worksheet
Sheets(Sheets.Count).Name = MyCell.Value ' renames the new worksheet
Next MyCell
End Sub

Android: how to handle button click

#1 I use the last one frequently when having buttons on the layout which are not generated (but static obviously).

If you use it in practice and in a business application, pay extra attention here, because when you use source obfuscater like ProGuard, you'll need to mark these methods in your activity as to not be obfuscated.

For archiving some kind of compile-time-security with this approach, have a look at Android Lint (example).


#2 Pros and cons for all methods are almost the same and the lesson should be:

Use what ever is most appropriate or feels most intuitive to you.

If you have to assign the same OnClickListener to multiple button instances, save it in the class-scope (#1). If you need a simple listener for a Button, make an anonymous implementation:

button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        // Take action.
    }
});

I tend to not implement the OnClickListener in the activity, this gets a little confusing from time to time (especially when you implement multiple other event-handlers and nobody knows what this is all doing).