Programs & Examples On #Emblems

How to create a Java cron job

If you are using unix, you need to write a shellscript to run you java batch first.

After that, in unix, you run this command "crontab -e" to edit crontab script. In order to configure crontab, please refer to this article http://www.thegeekstuff.com/2009/06/15-practical-crontab-examples/

Save your crontab setting. Then wait for the time to come, program will run automatically.

Passing arguments to require (when loading module)

Yes. In your login module, just export a single function that takes the db as its argument. For example:

module.exports = function(db) {
  ...
};

How to add 'ON DELETE CASCADE' in ALTER TABLE statement

If you want to change a foreign key without dropping it you can do:

ALTER TABLE child_table_name  WITH CHECK ADD FOREIGN KEY(child_column_name)
REFERENCES parent_table_name (parent_column_name) ON DELETE CASCADE

How do I format a string using a dictionary in python-3.x?

print("{latitude} {longitude}".format(**geopoint))

What is the difference between tinyint, smallint, mediumint, bigint and int in MySQL?

Data type Range Storage

bigint  -2^63 (-9,223,372,036,854,775,808) to 2^63-1 (9,223,372,036,854,775,807)    8 Bytes
int -2^31 (-2,147,483,648) to 2^31-1 (2,147,483,647)    4 Bytes
smallint    -2^15 (-32,768) to 2^15-1 (32,767)  2 Bytes
tinyint 0 to 255    1 Byte

Example

The following example creates a table using the bigint, int, smallint, and tinyint data types. Values are inserted into each column and returned in the SELECT statement.

CREATE TABLE dbo.MyTable
(
  MyBigIntColumn bigint
 ,MyIntColumn  int
 ,MySmallIntColumn smallint
 ,MyTinyIntColumn tinyint
);

GO

INSERT INTO dbo.MyTable VALUES (9223372036854775807, 214483647,32767,255);
 GO
SELECT MyBigIntColumn, MyIntColumn, MySmallIntColumn, MyTinyIntColumn
FROM dbo.MyTable;

How to check how many letters are in a string in java?

A)

String str = "a string";
int length = str.length( ); // length == 8

http://download.oracle.com/javase/7/docs/api/java/lang/String.html#length%28%29

edit

If you want to count the number of a specific type of characters in a String, then a simple method is to iterate through the String checking each index against your test case.

int charCount = 0;
char temp;

for( int i = 0; i < str.length( ); i++ )
{
    temp = str.charAt( i );

    if( temp.TestCase )
        charCount++;
}

where TestCase can be isLetter( ), isDigit( ), etc.

Or if you just want to count everything but spaces, then do a check in the if like temp != ' '

B)

String str = "a string";
char atPos0 = str.charAt( 0 ); // atPos0 == 'a'

http://download.oracle.com/javase/7/docs/api/java/lang/String.html#charAt%28int%29

Using Python String Formatting with Lists

The same as @neobot's answer but a little more modern and succinct.

>>> l = range(5)
>>> " & ".join(["{}"]*len(l)).format(*l)
'0 & 1 & 2 & 3 & 4'

Override body style for content in an iframe

Perhaps it's changed now, but I have used a separate stylesheet with this element:

.feedEkList iframe
{
max-width: 435px!important;
width: 435px!important;
height: 320px!important;
}

to successfully style embedded youtube iframes...see the blog posts on this page.

Why do we use $rootScope.$broadcast in AngularJS?

Passing data !!!

I wonder why no one mention that $broadcast accept a parameter where you can pass an Object that will be received by $on using a callback function

Example:

// the object to transfert
var myObject = {
    status : 10
}

$rootScope.$broadcast('status_updated', myObject);
$scope.$on('status_updated', function(event, obj){
    console.log(obj.status); // 10
})

How to programmatically add controls to a form in VB.NET

You can get your Button1 location and than increase the Y value every time you click on it.

Public Class Form1
    Dim BtnCoordinate As Point
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim btn As Button = New Button
        BtnCoordinate.Y += Button1.Location.Y + 4
        With btn
            .Location = New Point(BtnCoordinate)
            .Text = TextBox1.Text
            .ForeColor = Color.Black
        End With
        Me.Controls.Add(btn)
        Me.StartPosition = FormStartPosition.CenterScreen
    End Sub

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Button1Coordinate = Button1.Location
    End Sub
End Class

JavaScript naming conventions

I follow Douglas Crockford's code conventions for JavaScript. I also use his JSLint tool to validate following those conventions.

Hide Button After Click (With Existing Form on Page)

Change the button to :

<button onclick="getElementById('hidden-div').style.display = 'block'; this.style.display = 'none'">Check Availability</button>

FIDDLE

Or even better, use a proper event handler by identifying the button :

<button id="show_button">Check Availability</button>

and a script

<script type="text/javascript">
    var button = document.getElementById('show_button')
    button.addEventListener('click',hideshow,false);

    function hideshow() {
        document.getElementById('hidden-div').style.display = 'block'; 
        this.style.display = 'none'
    }   
</script>

FIDDLE

Virtualhost For Wildcard Subdomain and Static Subdomain

<VirtualHost *:80>
  DocumentRoot /var/www/app1
  ServerName app1.example.com
</VirtualHost>

<VirtualHost *:80>
  DocumentRoot /var/www/example
  ServerName example.com
</VirtualHost>

<VirtualHost *:80>
  DocumentRoot /var/www/wildcard
  ServerName other.example.com
  ServerAlias *.example.com
</VirtualHost>

Should work. The first entry will become the default if you don't get an explicit match. So if you had app.otherexample.com point to it, it would be caught be app1.example.com.

How to generate a random int in C?

Despite all the people suggestion rand() here, you don't want to use rand() unless you have to! The random numbers that rand() produces are often very bad. To quote from the Linux man page:

The versions of rand() and srand() in the Linux C Library use the same random number generator as random(3) and srandom(3), so the lower-order bits should be as random as the higher-order bits. However, on older rand() implementations, and on current implementations on different systems, the lower-order bits are much less random than the higher-order bits. Do not use this function in applications intended to be portable when good randomness is needed. (Use random(3) instead.)

Regarding portability, random() is also defined by the POSIX standard for quite some time now. rand() is older, it appeared already in the first POSIX.1 spec (IEEE Std 1003.1-1988), whereas random() first appeared in POSIX.1-2001 (IEEE Std 1003.1-2001), yet the current POSIX standard is already POSIX.1-2008 (IEEE Std 1003.1-2008), which received an update just a year ago (IEEE Std 1003.1-2008, 2016 Edition). So I would consider random() to be very portable.

POSIX.1-2001 also introduced the lrand48() and mrand48() functions, see here:

This family of functions shall generate pseudo-random numbers using a linear congruential algorithm and 48-bit integer arithmetic.

And pretty good pseudo random source is the arc4random() function that is available on many systems. Not part of any official standard, appeared in BSD around 1997 but you can find it on systems like Linux and macOS/iOS.

Using arrays or std::vectors in C++, what's the performance gap?

The performance difference between the two is very much implementation dependent - if you compare a badly implemented std::vector to an optimal array implementation, the array would win, but turn it around and the vector would win...

As long as you compare apples with apples (either both the array and the vector have a fixed number of elements, or both get resized dynamically) I would think that the performance difference is negligible as long as you follow got STL coding practise. Don't forget that using standard C++ containers also allows you to make use of the pre-rolled algorithms that are part of the standard C++ library and most of them are likely to be better performing than the average implementation of the same algorithm you build yourself.

That said, IMHO the vector wins in a debug scenario with a debug STL as most STL implementations with a proper debug mode can at least highlight/cathc the typical mistakes made by people when working with standard containers.

Oh, and don't forget that the array and the vector share the same memory layout so you can use vectors to pass data to legacy C or C++ code that expects basic arrays. Keep in mind that most bets are off in that scenario, though, and you're dealing with raw memory again.

vertical align middle in <div>

Use the translateY CSS property to vertically center your text in it's container

<style>
.centertext{

    position: relative;
    top: 50%;
    transform: translateY(40%);

}
</style>

And then apply it to your containing DIV

  <div class="centertext">
        <font style="color:white; font-size:20px;">   Your Text Here </font>
  </div>

Adjust the translateY percentage to suit your needs. Hope this helps

How do I get an apk file from an Android device?

On unix systems, you can try this function:

function android_pull_apk() {
    if [ -z "$1" ]; then
        echo "You must pass a package to this function!"
        echo "Ex.: android_pull_apk \"com.android.contacts\""
        return 1
    fi

    if [ -z "$(adb shell pm list packages | grep $1)" ]; then
        echo "You are typed a invalid package!"
        return 1
    fi

    apk_path="`adb shell pm path $1 | sed -e 's/package://g' | tr '\n' ' ' | tr -d '[:space:]'`"
    apk_name="`adb shell basename ${apk_path} | tr '\n' ' ' | tr -d '[:space:]'`"

    destination="$HOME/Documents/Android/APKs"
    mkdir -p "$destination"

    adb pull ${apk_path} ${destination}
    echo -e "\nAPK saved in \"$destination/$apk_name\""
}
  • Example: android_pull_apk com.android.contacts
  • Note: To identify the package: adb shell pm list packages

Returning http 200 OK with error within response body

Even if I want to return a business logic error as HTTP code there is no such acceptable HTTP error code for that errors rather than using HTTP 200 because it will misrepresent the actual error.

So, HTTP 200 will be good for business logic errors. But all errors which are covered by HTTP error codes should use them.

Basically HTTP 200 means what server correctly processes user request (in case of there is no seats on the plane it is no matter because user request was correctly processed, it can even return just a number of seats available on the plane, so there will be no business logic errors at all or that business logic can be on client side. Business logic error is an abstract meaning, but HTTP error is more definite).

How to convert C# nullable int to int

Like this,

if(v1.HasValue)
   v2=v1.Value

How to obtain Certificate Signing Request

Follow these steps to create CSR (Code Signing Identity):

  1. On your Mac, go to the folder 'Applications' ? 'Utilities' and open 'Keychain Access.'

    enter image description here

  2. Go to 'Keychain Access' ? Certificate Assistant ? Request a Certificate from a Certificate Authority. ?

    enter image description here

  3. Fill out the information in the Certificate Information window as specified below and click "Continue."
    • In the User Email Address field, enter the email address to identify with this certificate
    • In the Common Name field, enter your name
    • In the Request group, click the "Saved to disk" option ?

    enter image description here

  4. Save the file to your hard drive.

    enter image description here


Use this CSR (.certSigningRequest) file to create project/application certificates and profiles, in Apple developer account.

How to delete a folder with files using Java

My basic recursive version, working with older versions of JDK:

public static void deleteFile(File element) {
    if (element.isDirectory()) {
        for (File sub : element.listFiles()) {
            deleteFile(sub);
        }
    }
    element.delete();
}

C++ initial value of reference to non-const must be an lvalue

When you pass a pointer by a non-const reference, you are telling the compiler that you are going to modify that pointer's value. Your code does not do that, but the compiler thinks that it does, or plans to do it in the future.

To fix this error, either declare x constant

// This tells the compiler that you are not planning to modify the pointer
// passed by reference
void test(float * const &x){
    *x = 1000;
}

or make a variable to which you assign a pointer to nKByte before calling test:

float nKByte = 100.0;
// If "test()" decides to modify `x`, the modification will be reflected in nKBytePtr
float *nKBytePtr = &nKByte;
test(nKBytePtr);

JPA Native Query select and cast object

First of all create a model POJO

import javax.persistence.*;
@Entity
@Table(name = "sys_std_user")
public class StdUser {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "class_id")
    public int classId;
    @Column(name = "user_name")
    public String userName;
    //getter,setter
}

Controller

import com.example.demo.models.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import java.util.List;

@RestController
public class HomeController {
    @PersistenceUnit
    private EntityManagerFactory emf;

    @GetMapping("/")
    public List<StdUser> actionIndex() {
        EntityManager em = emf.createEntityManager(); // Without parameter
        List<StdUser> arr_cust = (List<StdUser>)em
                .createQuery("SELECT c FROM StdUser c")
                .getResultList();
        return arr_cust;
    }

    @GetMapping("/paramter")
    public List actionJoin() {
        int id = 3;
        String userName = "Suresh Shrestha";
        EntityManager em = emf.createEntityManager(); // With parameter
        List arr_cust = em
                .createQuery("SELECT c FROM StdUser c WHERE c.classId = :Id ANd c.userName = :UserName")
                .setParameter("Id",id)
                .setParameter("UserName",userName)
                .getResultList();
        return arr_cust;
    }
}

Why does the html input with type "number" allow the letter 'e' to be entered in the field?

To hide both letter e and minus sign - just go for:

onkeydown="return event.keyCode !== 69 && event.keyCode !== 189"

How to find Current open Cursors in Oracle

Here's how to find open cursors that have been parsed. You need to be logged in as a user with access to v$open_cursor and v$session.

COLUMN USER_NAME FORMAT A15

SELECT s.machine, oc.user_name, oc.sql_text, count(1) 
FROM v$open_cursor oc, v$session s
WHERE oc.sid = s.sid
GROUP BY user_name, sql_text, machine
HAVING COUNT(1) > 2
ORDER BY count(1) DESC
;

If gives you part of the SQL text so it can be useful for identifying leaky applications. If a cursor has not been parsed, then it does not appear here. Note that Oralce will sometimes keep things open longer than you do.

Send FormData and String Data Together Through JQuery AJAX?

I always use this.It send form data using ajax

$(document).on("submit", "form", function(event)
{
    event.preventDefault();

    var url=$(this).attr("action");
    $.ajax({
        url: url,
        type: 'POST',            
        data: new FormData(this),
        processData: false,
        contentType: false,
        success: function (data, status)
        {

        }
    });
});

Passing string parameter in JavaScript function

Change your code to

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

How to Delete a topic in apache kafka

Deletion of a topic has been supported since 0.8.2.x version. You have to enable topic deletion (setting delete.topic.enable to true) on all brokers first.

Note: Ever since 1.0.x, the functionality being stable, delete.topic.enable is by default true.

Follow this step by step process for manual deletion of topics

  1. Stop Kafka server
  2. Delete the topic directory, on each broker (as defined in the logs.dirs and log.dir properties) with rm -rf command
  3. Connect to Zookeeper instance: zookeeper-shell.sh host:port
  4. From within the Zookeeper instance:
    1. List the topics using: ls /brokers/topics
    2. Remove the topic folder from ZooKeeper using: rmr /brokers/topics/yourtopic
    3. Exit the Zookeeper instance (Ctrl+C)
  5. Restart Kafka server
  6. Confirm if it was deleted or not by using this command kafka-topics.sh --list --zookeeper host:port

Send PHP variable to javascript function

A great option is to use jQuery/AJAX. Look at these examples and try them out on your server. In this example, in FILE1.php, note that it is passing a blank value. You can pass a value if you wish, which might look something like this (assuming javascript vars called username and password:

data: 'username='+username+'&password='+password,

In the FILE2.php example, you would retrieve those values like this:

$uname = $_POST['username'];
$pword = $_POST['password'];

Then do your MySQL lookup and return the values thus:

echo 'You are logged in';

This would deliver the message You are logged in to the success function in FILE1.php, and the message string would be stored in the variable called "data". Therefore, the alert(data); line in the success function would alert that message. Of course, you can echo anything that you like, even large amounts of HTML, such as entire table structures.

Here is another good example to review.

The approach is to create your form, and then use jQuery to detect the button press and submit the data to a secondary PHP file via AJAX. The above examples show how to do that.

The secondary PHP file receives the variables (if any are sent) and returns a response (whatever you choose to send). That response then appears in the Success: section of your AJAX call as "data" (in these examples).

The jQuery/AJAX code is javascript, so you have two options: you can place it within <script type="text/javascript"></script> tags within your main PHP document, or you can <?php include "my_javascript_stuff.js"; ?> at the bottom of your PHP document. If you are using jQuery, don't forget to include the jQuery library as in the examples given.

In your case, it sounds like you can pretty much mirror the first example I suggested, sending no data and receiving the response in the AJAX success function. Whatever you need to do with that data, though, you must do inside the success function. Seems a bit weird at first, but it works.

What does principal end of an association means in 1:1 relationship in Entity framework

In one-to-one relation one end must be principal and second end must be dependent. Principal end is the one which will be inserted first and which can exist without the dependent one. Dependent end is the one which must be inserted after the principal because it has foreign key to the principal.

In case of entity framework FK in dependent must also be its PK so in your case you should use:

public class Boo
{
    [Key, ForeignKey("Foo")]
    public string BooId{get;set;}
    public Foo Foo{get;set;}
}

Or fluent mapping

modelBuilder.Entity<Foo>()
            .HasOptional(f => f.Boo)
            .WithRequired(s => s.Foo);

Testing whether a value is odd or even

I prefer using a bit test:

if(i & 1)
{
    // ODD
}
else
{
    // EVEN
}

This tests whether the first bit is on which signifies an odd number.

Catching nullpointerexception in Java

NullPointerException is a run-time exception which is not recommended to catch it, but instead avoid it:

if(someVariable != null) someVariable.doSomething();
else
{
    // do something else
}

How do I get length of list of lists in Java?

count of the contained lists in the outmost list

int count = data.size();

lambda to get the count of the contained inner lists

int count = data.stream().collect( summingInt(l -> l.size()) );

How do you change the value inside of a textfield flutter?

step 1) Declare TextEditingController.

step 2) supply controller to the TextField.

step 3) user controller's text property to change the value of the textField.

follow this official solution to the problem

How to drop a PostgreSQL database if there are active connections to it?

In Linux command Prompt, I would first stop all postgresql processes that are running by tying this command sudo /etc/init.d/postgresql restart

type the command bg to check if other postgresql processes are still running

then followed by dropdb dbname to drop the database

sudo /etc/init.d/postgresql restart
bg
dropdb dbname

This works for me on linux command prompt

Getting Python error "from: can't read /var/mail/Bio"

for Mac OS just go to applications and just run these Scripts Install Certificates.command and Update Shell Profile.command, now it will work.

Show spinner GIF during an $http request in AngularJS?

Adding onto @Adam's answer,

Use ng-show as suggested, however, in your case you want the functionality to have multiple requests and await all of them before the loader is hidden.

<span ng-show="pendingRequests > 0">
    <img src="http://www.nasa.gov/multimedia/videogallery/ajax-loader.gif" style="height:20px;"/>
</span>

And then in your controller:

$scope.pendingRequests++;

let url = '/whatever_Your_URL_Is'
$http.get(url)
  .then(function(response) {
      $scope.pendingRequests--;
})

AndroidStudio gradle proxy

in gradle.properties file (project root directory)

You must set proxy for http and https

systemProp.http.proxyHost=www.somehost.org
systemProp.http.proxyPort=8080
systemProp.http.proxyUser=user
systemProp.http.proxyPassword=password
systemProp.http.nonProxyHosts=localhost
systemProp.http.auth.ntlm.domain=domain

systemProp.https.proxyHost=www.somehost.org
systemProp.https.proxyPort=8080
systemProp.https.proxyUser=user
systemProp.https.proxyPassword=password
systemProp.https.nonProxyHosts=localhost
systemProp.https.auth.ntlm.domain=domain

if you set proxy from File -> Settings ->HTTP Proxy(Under IDE Settings) it only define http proxy and does not set https proxy

How to prevent ENTER keypress to submit a web form?

To prevent form submit when pressing enter in a textarea or input field, check the submit event to find what type of element sent the event.

Example 1

HTML

<button type="submit" form="my-form">Submit</button>
<form id="my-form">
...
</form>

jQuery

$(document).on('submit', 'form', function(e) {
    if (e.delegateTarget.activeElement.type!=="submit") {
        e.preventDefault();
    }
});

A better solution is if you don't have a submit button and you fire the event with a normal button. It is better because in the first examlple 2 submit events are fired, but in the second example only 1 submit event is fired.

Example 2

HTML

<button type="button" onclick="$('#my-form').submit();">Submit</button>
<form id="my-form">
...
</form>

jQuery

$(document).on('submit', 'form', function(e) {
    if (e.delegateTarget.activeElement.localName!=="button") {
        e.preventDefault();
    }
});

What's the difference between event.stopPropagation and event.preventDefault?

event.preventDefault(); Stops the default action of an element from happening.

event.stopPropagation(); Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.

For example, if there is a link with a click method attached inside of a DIV or FORM that also has a click method attached, it will prevent the DIV or FORM click method from firing.

How do I share a global variable between c files?

file 1:

int x = 50;

file 2:

extern int x;

printf("%d", x);

PowerShell script to return versions of .NET Framework on a machine?

Refer to the page Script for finding which .NET versions are installed on remote workstations.

The script there might be useful to find the .NET version for multiple machines on a network.

How can I add C++11 support to Code::Blocks compiler?

  1. Go to Toolbar -> Settings -> Compiler
  2. In the Selected compiler drop-down menu, make sure GNU GCC Compiler is selected
  3. Below that, select the compiler settings tab and then the compiler flags tab underneath
  4. In the list below, make sure the box for "Have g++ follow the C++11 ISO C++ language standard [-std=c++11]" is checked
  5. Click OK to save

Is it bad practice to use break to exit a loop in Java?

Using break, just as practically any other language feature, can be a bad practice, within a specific context, where you are clearly misusing it. But some very important idioms cannot be coded without it, or at least would result in far less readable code. In those cases, break is the way to go.

In other words, don't listen to any blanket, unqualified advice—about break or anything else. It is not once that I've seen code totally emaciated just to literally enforce a "good practice".

Regarding your concern about performance overhead, there is absolutely none. At the bytecode level there are no explicit loop constructs anyway: all flow control is implemented in terms of conditional jumps.

How do I read the first line of a file using cat?

cat alone may not be possible, but if you don't want to use head this works:

 cat <file> | awk 'NR == 1'

Setting up PostgreSQL ODBC on Windows

First you download ODBC driver psqlodbc_09_01_0200-x64.zip then you installed it.After that go to START->Program->Administrative tools then you select Data Source ODBC then you double click on the same after that you select PostgreSQL 30 then you select configure then you provide proper details such as db name user Id host name password of the same database in this way you will configured your DSN connection.After That you will check SSL should be allow .

Then you go on next tab system DSN then you select ADD tabthen select postgreSQL_ANSI_64X ODBC after you that you have created PostgreSQL ODBC connection.

Get the Query Executed in Laravel 3/4

To get the last executed query in laravel,We will use DB::getQueryLog() function of laravel it return all executed queries. To get last query we will use end() function which return last executed query.

$student = DB::table('student')->get();
$query = DB::getQueryLog();
$lastQuery = end($query);
print_r($lastQuery);

I have taken reference from http://www.tutsway.com/how-to-get-the-last-executed-query-in-laravel.php.

How to get the parents of a Python class?

Use bases if you just want to get the parents, use __mro__ (as pointed out by @naught101) for getting the method resolution order (so to know in which order the init's were executed).

Bases (and first getting the class for an existing object):

>>> some_object = "some_text"
>>> some_object.__class__.__bases__
(object,)

For mro in recent Python versions:

>>> some_object = "some_text"
>>> some_object.__class__.__mro__
(str, object)

Obviously, when you already have a class definition, you can just call __mro__ on that directly:

>>> class A(): pass
>>> A.__mro__
(__main__.A, object)

Initializing data.frames()

I always just convert a matrix:

x <- as.data.frame(matrix(nrow = 100, ncol = 10))

SQL is null and = null

It's important to note, that NULL doesn't equal NULL.

NULL is not a value, and therefore cannot be compared to another value.

where x is null checks whether x is a null value.

where x = null is checking whether x equals NULL, which will never be true

How to make CSS width to fill parent?

So after research the following is discovered:

For a div#bar setting display:block; width: auto; causes the equivalent of outerWidth:100%;

For a table#bar you need to wrap it in a div with the rules stated below. So your structure becomes:

<div id="foo">
 <div id="barWrap" style="border....">
  <table id="bar" style="width: 100%; border: 0; padding: 0; margin: 0;">

This way the table takes up the parent div 100%, and #barWrap is used to add borders/margin/padding to the #bar table. Note that you will need to set the background of the whole thing in #barWrap and have #bar's background be transparent or the same as #barWrap.

For textarea#bar and input#bar you need to do the same thing as table#bar, the down side is that by removing the borders you stop native widget rendering of the input/textarea and the #barWrap's borders will look a bit different than everything else, so you will probably have to style all your inputs this way.

How to get std::vector pointer to the raw data?

&something gives you the address of the std::vector object, not the address of the data it holds. &something.begin() gives you the address of the iterator returned by begin() (as the compiler warns, this is not technically allowed because something.begin() is an rvalue expression, so its address cannot be taken).

Assuming the container has at least one element in it, you need to get the address of the initial element of the container, which you can get via

  • &something[0] or &something.front() (the address of the element at index 0), or

  • &*something.begin() (the address of the element pointed to by the iterator returned by begin()).

In C++11, a new member function was added to std::vector: data(). This member function returns the address of the initial element in the container, just like &something.front(). The advantage of this member function is that it is okay to call it even if the container is empty.

How do I move an existing Git submodule within a Git repository?

The most modern answer, taken from Valloric's comment above:

  1. Upgrade to Git 1.9.3 (or 2.18 if the submodule contains nested submodules)
  2. git mv old/submod new/submod
  3. Afterwards the .gitmodules and the submodule directory are already staged for a commit (you can verify this with git status.)
  4. Commit the changes with git commitand you're good to go!

Done!

Angularjs $http post file and form data

You can also upload using HTML5. You can use this AJAX uploader.

The JS code is basically:

  $scope.doPhotoUpload = function () {
    // ..
    var myUploader = new uploader(document.getElementById('file_upload_element_id'), options);
    myUploader.send();
    // ..
  }

Which reads from an HTML input element

<input id="file_upload_element_id" type="file" onchange="angular.element(this).scope().doPhotoUpload()">

There are no primary or candidate keys in the referenced table that match the referencing column list in the foreign key

Foreign keys work by joining a column to a unique key in another table, and that unique key must be defined as some form of unique index, be it the primary key, or some other unique index.

At the moment, the only unique index you have is a compound one on ISBN, Title which is your primary key.

There are a number of options open to you, depending on exactly what BookTitle holds and the relationship of the data within it.

I would hazard a guess that the ISBN is unique for each row in BookTitle. ON the assumption this is the case, then change your primary key to be only on ISBN, and change BookCopy so that instead of Title you have ISBN and join on that.

If you need to keep your primary key as ISBN, Title then you either need to store the ISBN in BookCopy as well as the Title, and foreign key on both columns, OR you need to create a unique index on BookTitle(Title) as a distinct index.

More generally, you need to make sure that the column or columns you have in your REFERENCES clause match exactly a unique index in the parent table: in your case it fails because you do not have a single unique index on Title alone.

Byte Array and Int conversion in Java

You can also use BigInteger for variable length bytes. You can convert it to Long, Integer or Short, whichever suits your needs.

new BigInteger(bytes).intValue();

or to denote polarity:

new BigInteger(1, bytes).intValue();

To get bytes back just:

new BigInteger(bytes).toByteArray()

How to assign the output of a Bash command to a variable?

You can also do way more complex commands, just to round out the examples above. So, say I want to get the number of processes running on the system and store it in the ${NUM_PROCS} variable.

All you have to so is generate the command pipeline and stuff it's output (the process count) into the variable.

It looks something like this:

NUM_PROCS=$(ps -e | sed 1d | wc -l)

I hope that helps add some handy information to this discussion.

insert multiple rows into DB2 database

UPDATE - Even less wordy version

INSERT INTO tableName (col1, col2, col3, col4, col5) 
VALUES ('val1', 'val2', 'val3', 'val4', 'val5'),
       ('val1', 'val2', 'val3', 'val4', 'val5'),
       ('val1', 'val2', 'val3', 'val4', 'val5'),
       ('val1', 'val2', 'val3', 'val4', 'val5')

The following also works for DB2 and is slightly less wordy

INSERT INTO tableName (col1, col2, col3, col4, col5) 
VALUES ('val1', 'val2', 'val3', 'val4', 'val5') UNION ALL
VALUES ('val1', 'val2', 'val3', 'val4', 'val5') UNION ALL
VALUES ('val1', 'val2', 'val3', 'val4', 'val5') UNION ALL
VALUES ('val1', 'val2', 'val3', 'val4', 'val5')

How to filter specific apps for ACTION_SEND intent (and set a different text for each app)

This solution shows a list of applications in a ListView dialog that resembles the chooser:

screenshot

It is up to you to:

  1. obtain the list of relevant application packages
  2. given a package name, invoke the relevant intent

The adapter class:

import java.util.List;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.drawable.Drawable;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

public class ChooserArrayAdapter extends ArrayAdapter<String> {
    PackageManager mPm;
    int mTextViewResourceId;
    List<String> mPackages;

    public ChooserArrayAdapter(Context context, int resource, int textViewResourceId, List<String> packages) {
        super(context, resource, textViewResourceId, packages);
        mPm = context.getPackageManager();
        mTextViewResourceId = textViewResourceId;
        mPackages = packages;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        String pkg = mPackages.get(position);
        View view = super.getView(position, convertView, parent);

        try {
            ApplicationInfo ai = mPm.getApplicationInfo(pkg, 0);

            CharSequence appName = mPm.getApplicationLabel(ai);
            Drawable appIcon = mPm.getApplicationIcon(pkg);

            TextView textView = (TextView) view.findViewById(mTextViewResourceId);
            textView.setText(appName);
            textView.setCompoundDrawablesWithIntrinsicBounds(appIcon, null, null, null);
            textView.setCompoundDrawablePadding((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 12, getContext().getResources().getDisplayMetrics()));
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }

        return view;
    }

}

and its usage:

    void doXxxButton() {
        final List<String> packages = ...;
        if (packages.size() > 1) {
            ArrayAdapter<String> adapter = new ChooserArrayAdapter(MyActivity.this, android.R.layout.select_dialog_item, android.R.id.text1, packages);

            new AlertDialog.Builder(MyActivity.this)
            .setTitle(R.string.app_list_title)
            .setAdapter(adapter, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int item ) {
                    invokeApplication(packages.get(item));
                }
            })
            .show();
        } else if (packages.size() == 1) {
            invokeApplication(packages.get(0));
        }
    }

    void invokeApplication(String packageName) {
        // given a package name, create an intent and fill it with data
        ...
        startActivityForResult(intent, rq);
    }

Double precision - decimal places

A double holds 53 binary digits accurately, which is ~15.9545898 decimal digits. The debugger can show as many digits as it pleases to be more accurate to the binary value. Or it might take fewer digits and binary, such as 0.1 takes 1 digit in base 10, but infinite in base 2.

This is odd, so I'll show an extreme example. If we make a super simple floating point value that holds only 3 binary digits of accuracy, and no mantissa or sign (so range is 0-0.875), our options are:

binary - decimal
000    - 0.000
001    - 0.125
010    - 0.250
011    - 0.375
100    - 0.500
101    - 0.625
110    - 0.750
111    - 0.875

But if you do the numbers, this format is only accurate to 0.903089987 decimal digits. Not even 1 digit is accurate. As is easy to see, since there's no value that begins with 0.4?? nor 0.9??, and yet to display the full accuracy, we require 3 decimal digits.

tl;dr: The debugger shows you the value of the floating point variable to some arbitrary precision (19 digits in your case), which doesn't necessarily correlate with the accuracy of the floating point format (17 digits in your case).

Jquery select this + class

Use $(this).find(), or pass this in context, using jQuery context with selector.

Using $(this).find()

$(".class").click(function(){
     $(this).find(".subclass").css("visibility","visible");
});

Using this in context, $( selector, context ), it will internally call find function, so better to use find on first place.

$(".class").click(function(){
     $(".subclass", this).css("visibility","visible");
});

Why can't I reference my class library?

After confirming the same version of asp.net was being used. I removed the project. cleaned the solution and re-added the project. this is what worked for me.

For homebrew mysql installs, where's my.cnf?

On your shell type my_print_defaults --help

At the bottom of the result, you should be able to see the file from which the server reads the configurations. It prints something like this:

Default options are read from the following files in the given order:
/etc/my.cnf /etc/mysql/my.cnf /usr/local/etc/my.cnf ~/.my.cnf

Log4j: How to configure simplest possible file logging?

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false">

   <appender name="fileAppender" class="org.apache.log4j.RollingFileAppender">
      <param name="Threshold" value="INFO" />
      <param name="File" value="sample.log"/>
      <layout class="org.apache.log4j.PatternLayout">
         <param name="ConversionPattern" value="%d %-5p  [%c{1}] %m %n" />
      </layout>
   </appender>

  <root> 
    <priority value ="debug" /> 
    <appender-ref ref="fileAppender" /> 
  </root> 

</log4j:configuration>

Log4j can be a bit confusing. So lets try to understand what is going on in this file: In log4j you have two basic constructs appenders and loggers.

Appenders define how and where things are appended. Will it be logged to a file, to the console, to a database, etc.? In this case you are specifying that log statements directed to fileAppender will be put in the file sample.log using the pattern specified in the layout tags. You could just as easily create a appender for the console or the database. Where the console appender would specify things like the layout on the screen and the database appender would have connection details and table names.

Loggers respond to logging events as they bubble up. If an event catches the interest of a specific logger it will invoke its attached appenders. In the example below you have only one logger the root logger - which responds to all logging events by default. In addition to the root logger you can specify more specific loggers that respond to events from specific packages. These loggers can have their own appenders specified using the appender-ref tags or will otherwise inherit the appenders from the root logger. Using more specific loggers allows you to fine tune the logging level on specific packages or to direct certain packages to other appenders.

So what this file is saying is:

  1. Create a fileAppender that logs to file sample.log
  2. Attach that appender to the root logger.
  3. The root logger will respond to any events at least as detailed as 'debug' level
  4. The appender is configured to only log events that are at least as detailed as 'info'

The net out is that if you have a logger.debug("blah blah") in your code it will get ignored. A logger.info("Blah blah"); will output to sample.log.

The snippet below could be added to the file above with the log4j tags. This logger would inherit the appenders from <root> but would limit the all logging events from the package org.springframework to those logged at level info or above.

  <!-- Example Package level Logger -->
    <logger name="org.springframework">
        <level value="info"/>
    </logger>   

Check if all values of array are equal

If you're already using underscore.js, then here's another option using _.uniq:

function allEqual(arr) {
    return _.uniq(arr).length === 1;
}

_.uniq returns a duplicate-free version of the array. If all the values are the same, then the length will be 1.

As mentioned in the comments, given that you may expect an empty array to return true, then you should also check for that case:

function allEqual(arr) {
    return arr.length === 0 || _.uniq(arr).length === 1;
}

What is the equivalent of ngShow and ngHide in Angular 2+?

If you are using Bootstrap is as simple as this:

<div [class.hidden]="myBooleanValue"></div>

How to export a Vagrant virtual machine to transfer it

My hard drive in my Mac was making beeping noises in the middle of a project so I decided to install a SSD. I needed to move my project from one disk to another. A few things to consider:

  • I'm vagrant w/ virtualbox on a Mac
  • I'm using git

This is what worked for me:

1.) Copy your ~/.vagrant.d directory to your new machine.
2.) Copy your ~/VirtualBox\ VMs directory to your new machine. 
3.) In VirtualBox add the machines one by one using **Machine** >> **Add**
4.) Run `vagrant box list` to see if vagrant acknowledges your machines. 
5.) `git clone my_project`
6.) `vagrant up`

I had a few problems with VB Guest additions.

enter image description here

I fixed them with this solution.

T-SQL STOP or ABORT command in SQL Server

Try running this as a TSQL Script

SELECT 1
RETURN
SELECT 2
SELECT 3

The return ends the execution.

RETURN (Transact-SQL)

Exits unconditionally from a query or procedure. RETURN is immediate and complete and can be used at any point to exit from a procedure, batch, or statement block. Statements that follow RETURN are not executed.

Sending data back to the Main Activity in Android

All these answers are explaining the scenario of your second activity needs to be finish after sending the data.

But in case if you don't want to finish the second activity and want to send the data back in to first then for that you can use BroadCastReceiver.

In Second Activity -

Intent intent = new Intent("data");
intent.putExtra("some_data", true);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);

In First Activity-

private BroadcastReceiver tempReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        // do some action
    }
};

Register the receiver in onCreate()-

 LocalBroadcastManager.getInstance(this).registerReceiver(tempReceiver,new IntentFilter("data"));

Unregister it in onDestroy()

How to count number of records per day?

select DateAdded, count(CustID)
from Responses
WHERE DateAdded >=dateadd(day,datediff(day,0,GetDate())- 7,0)
GROUP BY DateAdded

Flatten List in LINQ

With query syntax:

var values =
from inner in outer
from value in inner
select value;

In Angular, how to add Validator to FormControl after control is created?

If you are using reactiveFormModule and have formGroup defined like this:

public exampleForm = new FormGroup({
        name: new FormControl('Test name', [Validators.required, Validators.minLength(3)]),
        email: new FormControl('[email protected]', [Validators.required, Validators.maxLength(50)]),
        age: new FormControl(45, [Validators.min(18), Validators.max(65)])
});

than you are able to add a new validator (and keep old ones) to FormControl with this approach:

this.exampleForm.get('age').setValidators([
        Validators.pattern('^[0-9]*$'),
        this.exampleForm.get('age').validator
]);
this.exampleForm.get('email').setValidators([
        Validators.email,
        this.exampleForm.get('email').validator
]);

FormControl.validator returns a compose validator containing all previously defined validators.

get current page from url

The class you need is System.Uri

Dim url As System.Uri = Request.UrlReferrer 
Debug.WriteLine(url.AbsoluteUri)   ' => http://www.mysite.com/default.aspx
Debug.WriteLine(url.AbsolutePath)  ' => /default.aspx
Debug.WriteLine(url.Host)          ' => http:/www.mysite.com
Debug.WriteLine(url.Port)          ' => 80
Debug.WriteLine(url.IsLoopback)    ' => False

http://www.devx.com/vb2themax/Tip/18709

replace special characters in a string python

You need to call replace on z and not on str, since you want to replace characters located in the string variable z

removeSpecialChars = z.replace("!@#$%^&*()[]{};:,./<>?\|`~-=_+", " ")

But this will not work, as replace looks for a substring, you will most likely need to use regular expression module re with the sub function:

import re
removeSpecialChars = re.sub("[!@#$%^&*()[]{};:,./<>?\|`~-=_+]", " ", z)

Don't forget the [], which indicates that this is a set of characters to be replaced.

Null vs. False vs. 0 in PHP

Well, I can't remember enough from my PHP days to answer the "===" part, but for most C-style languages, NULL should be used in the context of pointer values, false as a boolean, and zero as a numeric value such as an int. '\0' is the customary value for a character context. I usually also prefer to use 0.0 for floats and doubles.

So.. the quick answer is: context.

How do I add a library path in cmake?

The simplest way of doing this would be to add

include_directories(${CMAKE_SOURCE_DIR}/inc)
link_directories(${CMAKE_SOURCE_DIR}/lib)

add_executable(foo ${FOO_SRCS})
target_link_libraries(foo bar) # libbar.so is found in ${CMAKE_SOURCE_DIR}/lib

The modern CMake version that doesn't add the -I and -L flags to every compiler invocation would be to use imported libraries:

add_library(bar SHARED IMPORTED) # or STATIC instead of SHARED
set_target_properties(bar PROPERTIES
  IMPORTED_LOCATION "${CMAKE_SOURCE_DIR}/lib/libbar.so"
  INTERFACE_INCLUDE_DIRECTORIES "${CMAKE_SOURCE_DIR}/include/libbar"
)

set(FOO_SRCS "foo.cpp")
add_executable(foo ${FOO_SRCS})
target_link_libraries(foo bar) # also adds the required include path

If setting the INTERFACE_INCLUDE_DIRECTORIES doesn't add the path, older versions of CMake also allow you to use target_include_directories(bar PUBLIC /path/to/include). However, this no longer works with CMake 3.6 or newer.

SELECT INTO a table variable in T-SQL

You could try using temporary tables...if you are not doing it from an application. (It may be ok to run this manually)

SELECT name, location INTO #userData FROM myTable
INNER JOIN otherTable ON ...
WHERE age>30

You skip the effort to declare the table that way... Helps for adhoc queries...This creates a local temp table which wont be visible to other sessions unless you are in the same session. Maybe a problem if you are running query from an app.

if you require it to running on an app, use variables declared this way :

DECLARE @userData TABLE(
    name varchar(30) NOT NULL,
    oldlocation varchar(30) NOT NULL
);

INSERT INTO @userData
SELECT name, location FROM myTable
INNER JOIN otherTable ON ...
WHERE age > 30;

Edit: as many of you mentioned updated visibility to session from connection. Creating temp tables is not an option for web applications, as sessions can be reused, stick to temp variables in those cases

How do I toggle an ng-show in AngularJS based on a boolean?

It's worth noting that if you have a button in Controller A and the element you want to show in Controller B, you may need to use dot notation to access the scope variable across controllers.

For example, this will not work:

<div ng-controller="ControllerA">
  <a ng-click="isReplyFormOpen = !isReplyFormOpen">Reply</a>

  <div ng-controller="ControllerB">
    <div ng-show="isReplyFormOpen" id="replyForm">
    </div>
  </div>

</div>

To solve this, create a global variable (ie. in Controller A or your main Controller):

.controller('ControllerA', function ($scope) {
  $scope.global = {};
}

Then add a 'global' prefix to your click and show variables:

<div ng-controller="ControllerA">
  <a ng-click="global.isReplyFormOpen = !global.isReplyFormOpen">Reply</a>

  <div ng-controller="ControllerB">
    <div ng-show="global.isReplyFormOpen" id="replyForm">
    </div>
  </div>

</div>

For more detail, check out the Nested States & Nested Views in the Angular-UI documentation, watch a video, or read understanding scopes.

How to uninstall / completely remove Oracle 11g (client)?

Assuming a Windows installation, do please refer to this:

http://www.oracle-base.com/articles/misc/ManualOracleUninstall.php

  • Uninstall all Oracle components using the Oracle Universal Installer (OUI).
  • Run regedit.exe and delete the HKEY_LOCAL_MACHINE\SOFTWARE\ORACLE key. This contains registry entires for all Oracle products.
  • Delete any references to Oracle services left behind in the following part of the registry: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Ora* It should be pretty obvious which ones relate to Oracle.
  • Reboot your machine.
  • Delete the "C:\Oracle" directory, or whatever directory is your ORACLE_BASE.
  • Delete the "C:\Program Files\Oracle" directory.
  • Empty the contents of your "C:\temp" directory.
  • Empty your recycle bin.

Calling additional attention to some great comments that were left here:

  • Be careful when following anything listed here (above or below), as doing so may remove or damage any other Oracle-installed products.
  • For 64-bit Windows (x64), you need also to delete the HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\ORACLE key from the registry.
  • Clean-up by removing any related shortcuts that were installed to the Start Menu.
  • Clean-up environment variables:
    • Consider removing %ORACLE_HOME%.
    • Remove any paths no longer needed from %PATH%.

This set of instructions happens to match an almost identical process that I had reverse-engineered myself over the years after a few messed-up Oracle installs, and has almost always met the need.

Note that even if the OUI is no longer available or doesn't work, simply following the remaining steps should still be sufficient.

(Revision #7 reverted as to not misquote the original source, and to not remove credit to the other comments that contributed to the answer. Further edits are appreciated (and then please remove this comment), if a way can be found to maintain these considerations.)

Define a fixed-size list in Java

Create an array of size 100. If you need the List interface, then call Arrays.asList on it. It'll return a fixed-size list backed by the array.

Multiple queries executed in java in single statement

Why dont you try and write a Stored Procedure for this?

You can get the Result Set out and in the same Stored Procedure you can Insert what you want.

The only thing is you might not get the newly inserted rows in the Result Set if you Insert after the Select.

how to check redis instance version?

$ redis-server --version

gives you the version.

Make an image width 100% of parent div, but not bigger than its own width

You should set the max width and if you want you can also set some padding on one of the sides. In my case the max-width: 100% was good but the image was right next to the end of the screen.

  max-width: 100%;
  padding-right: 30px;
  /*add more paddings if needed*/

Checking if sys.argv[x] is defined

Pretty close to what the originator was trying to do. Here is a function I use:

def get_arg(index):
    try:
        sys.argv[index]
    except IndexError:
        return ''
    else:
        return sys.argv[index]

So a usage would be something like:

if __name__ == "__main__":
    banner(get_arg(1),get_arg(2))

How can I give eclipse more memory than 512M?

You can copy this to your eclipse.ini file to have 1024M:

-clean -showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256m
-vmargs
-Xms512m
-Xmx1024m
-XX:PermSize=128m
-XX:MaxPermSize=256m 

How to access child's state in React?

Now You can access the InputField's state which is the child of FormEditor .

Basically whenever there is a change in the state of the input field(child) we are getting the value from the event object and then passing this value to the Parent where in the state in the Parent is set.

On button click we are just printing the state of the Input fields.

The key point here is that we are using the props to get the Input Field's id/value and also to call the functions which are set as attributes on the Input Field while we generate the reusable child Input fields.

class InputField extends React.Component{
  handleChange = (event)=> {
    const val = event.target.value;
    this.props.onChange(this.props.id , val);
  }

  render() {
    return(
      <div>
        <input type="text" onChange={this.handleChange} value={this.props.value}/>
        <br/><br/>
      </div>
    );
  }
}       


class FormEditorParent extends React.Component {
  state = {};
  handleFieldChange = (inputFieldId , inputFieldValue) => {
    this.setState({[inputFieldId]:inputFieldValue});
  }
  //on Button click simply get the state of the input field
  handleClick = ()=>{
    console.log(JSON.stringify(this.state));
  }

  render() {
    const fields = this.props.fields.map(field => (
      <InputField
        key={field}
        id={field}
        onChange={this.handleFieldChange}
        value={this.state[field]}
      />
    ));

    return (
      <div>
        <div>
          <button onClick={this.handleClick}>Click Me</button>
        </div>
        <div>
          {fields}
        </div>
      </div>
    );
  }
}

const App = () => {
  const fields = ["field1", "field2", "anotherField"];
  return <FormEditorParent fields={fields} />;
};

ReactDOM.render(<App/>, mountNode);

JQuery to load Javascript file dynamically

I realize I am a little late here, (5 years or so), but I think there is a better answer than the accepted one as follows:

$("#addComment").click(function() {
    if(typeof TinyMCE === "undefined") {
        $.ajax({
            url: "tinymce.js",
            dataType: "script",
            cache: true,
            success: function() {
                TinyMCE.init();
            }
        });
    }
});

The getScript() function actually prevents browser caching. If you run a trace you will see the script is loaded with a URL that includes a timestamp parameter:

http://www.yoursite.com/js/tinymce.js?_=1399055841840

If a user clicks the #addComment link multiple times, tinymce.js will be re-loaded from a differently timestampped URL. This defeats the purpose of browser caching.

===

Alternatively, in the getScript() documentation there is a some sample code that demonstrates how to enable caching by creating a custom cachedScript() function as follows:

jQuery.cachedScript = function( url, options ) {

    // Allow user to set any option except for dataType, cache, and url
    options = $.extend( options || {}, {
        dataType: "script",
        cache: true,
        url: url
    });

    // Use $.ajax() since it is more flexible than $.getScript
    // Return the jqXHR object so we can chain callbacks
    return jQuery.ajax( options );
};

// Usage
$.cachedScript( "ajax/test.js" ).done(function( script, textStatus ) {
    console.log( textStatus );
});

===

Or, if you want to disable caching globally, you can do so using ajaxSetup() as follows:

$.ajaxSetup({
    cache: true
});

Python read in string from file and split it into values

>>> [[int(i) for i in line.strip().split(',')] for line in open('input.txt').readlines()]
[[995957, 16833579], [995959, 16777241], [995960, 16829368], [995961, 50431654]]

Bug? #1146 - Table 'xxx.xxxxx' doesn't exist

if you are modifying mysql bin->data dir's and after that, your database import will not works

so you need to close wamp and after that start wamp

now database import will work fine

Detecting value change of input[type=text] in jQuery

Description

You can do this using jQuery's .bind() method. Check out the jsFiddle.

Sample

Html

<input id="myTextBox" type="text"/>

jQuery

$("#myTextBox").bind("change paste keyup", function() {
   alert($(this).val()); 
});

More Information

How to check if a variable is an integer or a string?

In my opinion you have two options:

  • Just try to convert it to an int, but catch the exception:

    try:
        value = int(value)
    except ValueError:
        pass  # it was a string, not an int.
    

    This is the Ask Forgiveness approach.

  • Explicitly test if there are only digits in the string:

    value.isdigit()
    

    str.isdigit() returns True only if all characters in the string are digits (0-9).

    The unicode / Python 3 str type equivalent is unicode.isdecimal() / str.isdecimal(); only Unicode decimals can be converted to integers, as not all digits have an actual integer value (U+00B2 SUPERSCRIPT 2 is a digit, but not a decimal, for example).

    This is often called the Ask Permission approach, or Look Before You Leap.

The latter will not detect all valid int() values, as whitespace and + and - are also allowed in int() values. The first form will happily accept ' +10 ' as a number, the latter won't.

If your expect that the user normally will input an integer, use the first form. It is easier (and faster) to ask for forgiveness rather than for permission in that case.

How to parse JSON array in jQuery?

Your data is a string of '[{}]' at that point in time, you can eval it like so:

function(data) {
    data = eval( '(' + data + ')' )
}

However this method is far from secure, this will be a bit more work but the best practice is to parse it with Crockford's JSON parser: https://github.com/douglascrockford/JSON-js

Another method would be $.getJSON and you'll need to set the dataType to json for a pure jQuery reliant method.

Java8: HashMap<X, Y> to HashMap<X, Z> using Stream / Map-Reduce / Collector

If you don't mind using 3rd party libraries, my cyclops-react lib has extensions for all JDK Collection types, including Map. We can just transform the map directly using the 'map' operator (by default map acts on the values in the map).

   MapX<String,Integer> y = MapX.fromMap(HashMaps.of("hello","1"))
                                .map(Integer::parseInt);

bimap can be used to transform the keys and values at the same time

  MapX<String,Integer> y = MapX.fromMap(HashMaps.of("hello","1"))
                               .bimap(this::newKey,Integer::parseInt);

Difference between Iterator and Listiterator?

There are two differences:

  1. We can use Iterator to traverse Set and List and also Map type of Objects. While a ListIterator can be used to traverse for List-type Objects, but not for Set-type of Objects.

    That is, we can get a Iterator object by using Set and List, see here:

    By using Iterator we can retrieve the elements from Collection Object in forward direction only.

    Methods in Iterator:

    1. hasNext()
    2. next()
    3. remove()
    Iterator iterator = Set.iterator();
    Iterator iterator = List.iterator();
  2. But we get ListIterator object only from the List interface, see here:

    where as a ListIterator allows you to traverse in either directions (Both forward and backward). So it has two more methods like hasPrevious() and previous() other than those of Iterator. Also, we can get indexes of the next or previous elements (using nextIndex() and previousIndex() respectively )

    Methods in ListIterator:

    1. hasNext()
    2. next()
    3. previous()
    4. hasPrevious()
    5. remove()
    6. nextIndex()
    7. previousIndex()
    ListIterator listiterator = List.listIterator();

    i.e., we can't get ListIterator object from Set interface.

Reference : - What is the difference between Iterator and ListIterator ?

What's the difference between <b> and <strong>, <i> and <em>?

<i>, <b>, <em> and <strong> tags are traditionally representational. But they have been given new semantic meaning in HTML5.

<i> and <b> was used for font style in HTML4. <i> was used for italic and <b> for bold. In HTML5 <i> tag has new semantic meaning of 'alternate voice or mood' and <b> tag has the meaning of stylistically offset.

Example uses of <i> tag are - taxonomic designation, technical term, idiomatic phrase from another language, transliteration, a thought, ship names in western texts. Such as -

<p><i>I hope this works</i>, he thought.</p>

Example uses of <b> tag are keywords in a document extract, product names in a review, actionable words in an interactive text driven software, article lead.

The following example paragraph is stylistically offset from the paragraphs that follow it.

<p><b class="lead">The event takes place this upcoming Saturday, and over 3,000 people have already registered.</b></p>

<em> and <strong> had the meaning of emphasis and strong emphasis in HTML4. But in HTML5 <em> means stressed emphasis and <strong> means strong importance.

In the following example there should be a linguistic change while reading the word before ...

<p>Make sure to sign up <em>before</em> the day of the event, September 16, 2016</p>

In the same example we can use the <strong> tag as follows ..

<p>Make sure to sign up <em>before</em> the day of the event, <strong>September 16, 2016</strong></p>

to give importance on the event date.

MDN Ref:

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/b

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/i

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/em

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/strong

What is the method for converting radians to degrees?

This works well enough for me :)

// deg2rad * degrees = radians
#define deg2rad (3.14159265/180.0)
// rad2deg * radians = degrees
#define rad2deg (180/3.14159265)

How do I get the SQLSRV extension to work with PHP, since MSSQL is deprecated?

Quoting http://php.net/manual/en/intro.mssql.php:

The MSSQL extension is not available anymore on Windows with PHP 5.3 or later. SQLSRV, an alternative driver for MS SQL is available from Microsoft: » http://msdn.microsoft.com/en-us/sqlserver/ff657782.aspx.

Once you downloaded that, follow the instructions at this page:

In a nutshell:

Put the driver file in your PHP extension directory.
Modify the php.ini file to include the driver. For example:

extension=php_sqlsrv_53_nts_vc9.dll  

Restart the Web server.

See Also (copied from that page)

The PHP Manual for the SQLSRV extension is located at http://php.net/manual/en/sqlsrv.installation.php and offers the following for Installation:

The SQLSRV extension is enabled by adding appropriate DLL file to your PHP extension directory and the corresponding entry to the php.ini file. The SQLSRV download comes with several driver files. Which driver file you use will depend on 3 factors: the PHP version you are using, whether you are using thread-safe or non-thread-safe PHP, and whether your PHP installation was compiled with the VC6 or VC9 compiler. For example, if you are running PHP 5.3, you are using non-thread-safe PHP, and your PHP installation was compiled with the VC9 compiler, you should use the php_sqlsrv_53_nts_vc9.dll file. (You should use a non-thread-safe version compiled with the VC9 compiler if you are using IIS as your web server). If you are running PHP 5.2, you are using thread-safe PHP, and your PHP installation was compiled with the VC6 compiler, you should use the php_sqlsrv_52_ts_vc6.dll file.

The drivers can also be used with PDO.

How to make canvas responsive

You can have a responsive canvas in 3 short and simple steps:

  1. Remove the width and height attributes from your <canvas>.

    <canvas id="responsive-canvas"></canvas>
    
  2. Using CSS, set the width of your canvas to 100%.

    #responsive-canvas {
      width: 100%;
    }
    
  3. Using JavaScript, set the height to some ratio of the width.

    var canvas = document.getElementById('responsive-canvas');
    var heightRatio = 1.5;
    canvas.height = canvas.width * heightRatio;
    

Define an alias in fish shell

To properly load functions from ~/.config/fish/functions

You may set only ONE function inside file and name file the same as function name + add .fish extension.

This way changing file contents reload functions in opened terminals (note some delay may occur ~1-5s)

That way if you edit either by commandline

function name; function_content; end

then

funcsave name

you have user defined functions in console and custom made in the same order.

How to create a checkbox with a clickable label?

In Angular material label with checkbox

<mat-checkbox>Check me!</mat-checkbox>

How to upload a file and JSON data in Postman?

If you need like Upload file in multipart using form data and send json data(Dto object) in same POST Request

Get yor JSON object as String in Controller and make it Deserialize by adding this line

ContactDto contactDto  = new ObjectMapper().readValue(yourJSONString, ContactDto.class);

Instant run in Android Studio 2.0 (how to turn off)

I tried all above but nothing helps, at last i just figured out that under setting >> apps, device still has an entry for uninstalled application as disabled, i just uninstalled from there and it starts working.

:) might be useful for someone

Why is Thread.Sleep so harmful

I would like to answer this question from a coding-politics perspective, which may or may not be helpful to anyone. But particularly when you're dealing with tools that are intended for 9-5 corporate programmers, people who write documentation tend to use words like "should not" and "never" to mean "don't do this unless you really know what you're doing and why".

A couple of my other favorites in the C# world are that they tell you to "never call lock(this)" or "never call GC.Collect()". These two are forcefully declared in many blogs and official documentation, and IMO are complete misinformation. On some level this misinformation serves its purpose, in that it keeps the beginners away from doing things they don't understand before fully researching the alternatives, but at the same time, it makes it difficult to find REAL information via search-engines that all seem to point to articles telling you not to do something while offering no answer to the question "why not?"

Politically, it boils down to what people consider "good design" or "bad design". Official documentation should not be dictating the design of my application. If there's truly a technical reason that you shouldn't call sleep(), then IMO the documentation should state that it is totally okay to call it under specific scenarios, but maybe offer some alternative solutions that are scenario independent or more appropriate for the other scenarios.

Clearly calling "sleep()" is useful in many situations when deadlines are clearly defined in real-world-time terms, however, there are more sophisticated systems for waiting on and signalling threads that should be considered and understood before you start throwing sleep() into your code, and throwing unnecessary sleep() statements in your code is generally considered a beginners' tactic.

How do I get the current date in JavaScript?

This is good to get formatted date

_x000D_
_x000D_
let date = new Date().toLocaleDateString("en", {year:"numeric", day:"2-digit", month:"2-digit"});_x000D_
console.log(date);
_x000D_
_x000D_
_x000D_

XCOPY switch to create specified directory if it doesn't exist?

I hate the PostBuild step, it allows for too much stuff to happen outside of the build tool's purview. I believe that its better to let MSBuild manage the copy process, and do the updating. You can edit the .csproj file like this:

  <Target Name="AfterBuild" Inputs="$(TargetPath)\**">
    <Copy SourceFiles="$(TargetPath)\**" DestinationFiles="$(SolutionDir)Prism4Demo.Shell\$(OutDir)Modules\**" OverwriteReadOnlyFiles="true"></Copy>
  </Target>

VBA changing active workbook

Use ThisWorkbook which will refer to the original workbook which holds the code.

Alternatively at code start

Dim Wb As Workbook
Set Wb = ActiveWorkbook

sample code that activates all open books before returning to ThisWorkbook

Sub Test()
Dim Wb As Workbook
Dim Wb2 As Workbook
Set Wb = ThisWorkbook
For Each Wb2 In Application.Workbooks
    Wb2.Activate
Next
Wb.Activate
End Sub

How can I reverse a list in Python?

list_data = [1,2,3,4,5]
l = len(list_data)
i=l+1
rev_data = []
while l>0:
  j=i-l
  l-=1
  rev_data.append(list_data[-j])
print "After Rev:- %s" %rev_data 

How to stop a thread created by implementing runnable interface?

How to stop a thread created by implementing runnable interface?

There are many ways that you can stop a thread but all of them take specific code to do so. A typical way to stop a thread is to have a volatile boolean shutdown field that the thread checks every so often:

  // set this to true to stop the thread
  volatile boolean shutdown = false;
  ...
  public void run() {
      while (!shutdown) {
          // continue processing
      }
  }

You can also interrupt the thread which causes sleep(), wait(), and some other methods to throw InterruptedException. You also should test for the thread interrupt flag with something like:

  public void run() {
      while (!Thread.currentThread().isInterrupted()) {
          // continue processing
          try {
              Thread.sleep(1000);
          } catch (InterruptedException e) {
              // good practice
              Thread.currentThread().interrupt();
              return;
          }
      }
  }

Note that that interrupting a thread with interrupt() will not necessarily cause it to throw an exception immediately. Only if you are in a method that is interruptible will the InterruptedException be thrown.

If you want to add a shutdown() method to your class which implements Runnable, you should define your own class like:

public class MyRunnable implements Runnable {
    private volatile boolean shutdown;
    public void run() {
        while (!shutdown) {
            ...
        }
    }
    public void shutdown() {
        shutdown = true;
    }
}

How can I make Bootstrap 4 columns all the same height?

You just have to use class="row-eq-height" with your class="row" to get equal height columns for previous bootstrap versions.

but with bootstrap 4 this comes natively.

check this link --http://getbootstrap.com.vn/examples/equal-height-columns/

How do you automatically set text box to Uppercase?

try

<input type="text" class="normal" 
       style="text-transform:uppercase" 
       name="Name" size="20" maxlength="20"> 
 <img src="../images/tickmark.gif" border="0"/>

Instead of image put style tag on input because you are writing on input not on image

Spring Data JPA and Exists query

It's gotten a lot easier these days!

@Repository
public interface PageRepository extends JpaRepository<Page, UUID> {

    Boolean existsByName(String name); //Checks if there are any records by name
    Boolean existsBy(); // Checks if there are any records whatsoever

}

Detect enter press in JTextField

public void keyReleased(KeyEvent e)
{
    int key=e.getKeyCode();
    if(e.getSource()==textField)
    {
        if(key==KeyEvent.VK_ENTER)
        { 
            Toolkit.getDefaultToolkit().beep();
            textField_1.requestFocusInWindow();                     
        }
    }

To write logic for 'Enter press' in JTextField, it is better to keep logic inside the keyReleased() block instead of keyTyped() & keyPressed().

Serializing list to JSON

You can use pure Python to do it:

import json
list = [1, 2, (3, 4)] # Note that the 3rd element is a tuple (3, 4)
json.dumps(list) # '[1, 2, [3, 4]]'

Prevent linebreak after </div>

I don't think I've seen this version:

<div class="label">My Label:<span class="text">My text</span></div>

How do I fix a compilation error for unhandled exception on call to Thread.sleep()?

You can get rid of the first line. You don't need import java.lang.*;

Just change your 5th line to:

public static void main(String [] args) throws Exception

Insert data using Entity Framework model

var context = new DatabaseEntities();

var t = new test //Make sure you have a table called test in DB
{
    ID = Guid.NewGuid(),
    name = "blah",
};

context.test.Add(t);
context.SaveChanges();

Should do it

Converting from a string to boolean in Python?

def str2bool(str):
  if isinstance(str, basestring) and str.lower() in ['0','false','no']:
    return False
  else:
    return bool(str)

idea: check if you want the string to be evaluated to False; otherwise bool() returns True for any non-empty string.

How to export collection to CSV in MongoDB?

Also, you are not allowed spaces between comma separated field names.

BAD: -f firstname, lastname

GOOD: -f firstname,lastname

json_encode/json_decode - returns stdClass instead of Array in PHP

Take a closer look at the second parameter of json_decode($json, $assoc, $depth) at https://secure.php.net/json_decode

Print JSON parsed object?

If you want to debug why not use console debug

window.console.debug(jsonObject);

How to know if two arrays have the same values

What about this? ES 2017 i suppose:

_x000D_
_x000D_
const array1 = [1, 3, 5];_x000D_
const array2 = [1, 5, 3];_x000D_
_x000D_
const isEqual = (array1.length === array2.length) && (array1.every(val => array2.includes(val)));_x000D_
console.log(isEqual);
_x000D_
_x000D_
_x000D_

1st condition checks if both arrays have same length and 2nd condition checks if 1st array is a subset of the 2nd array. Combining these 2 conditions should then result in comparison of all items of the 2 arrays irrespective of the ordering of elements.

The above code will only work if both arrays have non-duplicate items.

Put Excel-VBA code in module or sheet?

In my experience it's best to put as much code as you can into well-named modules, and only put as much code as you need to into the actual worksheet objects.

Example: Any code that uses worksheet events like Worksheet_SelectionChange or Worksheet_Calculate.

Adding a background image to a <div> element

<div class="foo">Foo Bar</div>

and in your CSS file:

.foo {
    background-image: url("images/foo.png");
}

getColor(int id) deprecated on Android 6.0 Marshmallow (API 23)

Starting from Android Support Library 23,
a new getColor() method has been added to ContextCompat.

Its description from the official JavaDoc:

Returns a color associated with a particular resource ID

Starting in M, the returned color will be styled for the specified Context's theme.


So, just call:

ContextCompat.getColor(context, R.color.your_color);

You can check the ContextCompat.getColor() source code on GitHub.

Can't accept license agreement Android SDK Platform 24

The simplest way to solve this issue is to accept the licenses using the following command:

Windows OS:

C:\Users\{your-username}\AppData\Local\Android\sdk\tools\bin\sdkmanager --licenses

You will be presented with disclaimers. In order to continue your development efforts, you need to answer 'y' to all disclaimers.

Is there a Newline constant defined in Java like Environment.Newline in C#?

As of Java 7:

System.lineSeparator()

Java API : System.lineSeparator

Returns the system-dependent line separator string. It always returns the same value - the initial value of the system property line.separator. On UNIX systems, it returns "\n"; on Microsoft Windows systems it returns "\r\n".

How to handle Pop-up in Selenium WebDriver using Java

       //get the main handle and remove it
       //whatever remains is the child pop up window handle

       String mainHandle = driver.getWindowHandle();
       Set<String> allHandles = driver.getWindowHandles();
       Iterator<String> iter = allHandles.iterator();
       allHandles.remove(mainHandle);
       String childHandle=iter.next();

JBoss vs Tomcat again

I have also read that for some servers one for example needs only annotate persistence contexts, but in some servers, the injection should be done manually.

How to write hello world in assembler under Windows?

To get an .exe with NASM'compiler and Visual Studio's linker this code works fine:

global WinMain
extern ExitProcess  ; external functions in system libraries 
extern MessageBoxA

section .data 
title:  db 'Win64', 0
msg:    db 'Hello world!', 0

section .text
WinMain:
    sub rsp, 28h  
    mov rcx, 0       ; hWnd = HWND_DESKTOP
    lea rdx,[msg]    ; LPCSTR lpText
    lea r8,[title]   ; LPCSTR lpCaption
    mov r9d, 0       ; uType = MB_OK
    call MessageBoxA
    add rsp, 28h  

    mov  ecx,eax
    call ExitProcess

    hlt     ; never here

If this code is saved on e.g. "test64.asm", then to compile:

nasm -f win64 test64.asm

Produces "test64.obj" Then to link from command prompt:

path_to_link\link.exe test64.obj /subsystem:windows /entry:WinMain  /libpath:path_to_libs /nodefaultlib kernel32.lib user32.lib /largeaddressaware:no

where path_to_link could be C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin or wherever is your link.exe program in your machine, path_to_libs could be C:\Program Files (x86)\Windows Kits\8.1\Lib\winv6.3\um\x64 or wherever are your libraries (in this case both kernel32.lib and user32.lib are on the same place, otherwise use one option for each path you need) and the /largeaddressaware:no option is necessary to avoid linker's complain about addresses to long (for user32.lib in this case). Also, as it is done here, if Visual's linker is invoked from command prompt, it is necessary to setup the environment previously (run once vcvarsall.bat and/or see MS C++ 2010 and mspdb100.dll).

How to convert R Markdown to PDF?

I think you really need pandoc, which great software was designed and built just for this task :) Besides pdf, you could convert your md file to e.g. docx or odt among others.

Well, installing an up-to-date version of Pandoc might be challanging on Linux (as you would need the entire haskell-platform?to build from the sources), but really easy on Windows/Mac with only a few megabytes of download.

If you have the brewed/knitted markdown file you can just call pandoc in e.g bash or with the system function within R. A POC demo of that latter is implemented in the ?andoc.convert function of my little package (which you must be terribly bored of as I try to point your attention there at every opportunity).

How do I reference a cell within excel named range?

I've been willing to use something like this in a sheet where all lines are identical and usually refer to other cells in the same line - but as the formulas get complex, the references to other columns get hard to read. I tried the trick given in other answers, with for example column A named as "Sales" I can refers to it as INDEX(Sales;row()) but I found it a bit too long for my tastes.

However, in this particular case, I found that using Sales alone works just as well - Excel (2010 here) just gets the corresponding row automatically.

It appears to work with other ranges too; for example let's say I have values in A2:A11 which I name Sales, I can just use =Sales*0.21 in B2:11 and it will use the same row value, giving out ten different results.


I also found a nice trick on this page: named ranges can also be relative. Going back to your original question, if your value "Age" is in column A and assuming you're using that value in formulas in the same line, you can define Age as being $A2 instead of $A$2, so that when used in B5 or C5 for example, it will actually refer to $A5. (The Name Manager always show the reference relative to the cell currently selected)

erlative named range

Register comdlg32.dll gets Regsvr32: DllRegisterServer entry point was not found

comdlg32.dll is not a COM DLL and cannot be registered.

One way to confirm this for yourself is to run this command:

dumpbin /exports comdlg32.dll

You'll see that comdlg32.dll doesn't contain a DllRegisterServer method. Hence RegSvr32.exe won't work.

That's your answer.


ComDlg32.dll is a a system component. (exists in both c:\windows\system32 and c:\windows\syswow64) Trying to replace it or override any registration with an older version could corrupt the rest of Windows.


I can help more, but I need to know what MSComDlg.CommonDialog is. What does it do and how is it supposed to work? And what version of ComDlg32.dll are you trying to register (and where did you get it)?

In C/C++ what's the simplest way to reverse the order of bits in a byte?

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int i;
    unsigned char rev = 0x70 ; // 0b01110000
    unsigned char tmp = 0;

    for(i=0;i<8;i++)
    {
    tmp |= ( ((rev & (1<<i))?1:0) << (7-i));
    }
    rev = tmp;

    printf("%x", rev);       //0b00001110 binary value of given number
    return 0;
}

Why there is this "clear" class before footer?

A class in HTML means that in order to set attributes to it in CSS, you simply need to add a period in front of it.
For example, the CSS code of that html code may be:

.clear {     height: 50px;     width: 25px; } 

Also, if you, as suggested by abiessu, are attempting to add the CSS clear: both; attribute to the div to prevent anything from floating to the left or right of this div, you can use this CSS code:

.clear {     clear: both; } 

CSS scale height to match width - possibly with a formfactor

For this, you will need to utilise JavaScript, or rely on the somewhat supported calc() CSS expression.

window.addEventListener("resize", function(e) {
    var mapElement = document.getElementById("map");
    mapElement.style.height = mapElement.offsetWidth * 1.72;
});

Or using CSS calc (see support here: http://caniuse.com/calc)

#map {
    width: 100%;
    height: calc(100vw * 1.72)
}

How do I verify that a string only contains letters, numbers, underscores and dashes?

[Edit] There's another solution not mentioned yet, and it seems to outperform the others given so far in most cases.

Use string.translate to replace all valid characters in the string, and see if we have any invalid ones left over. This is pretty fast as it uses the underlying C function to do the work, with very little python bytecode involved.

Obviously performance isn't everything - going for the most readable solutions is probably the best approach when not in a performance critical codepath, but just to see how the solutions stack up, here's a performance comparison of all the methods proposed so far. check_trans is the one using the string.translate method.

Test code:

import string, re, timeit

pat = re.compile('[\w-]*$')
pat_inv = re.compile ('[^\w-]')
allowed_chars=string.ascii_letters + string.digits + '_-'
allowed_set = set(allowed_chars)
trans_table = string.maketrans('','')

def check_set_diff(s):
    return not set(s) - allowed_set

def check_set_all(s):
    return all(x in allowed_set for x in s)

def check_set_subset(s):
    return set(s).issubset(allowed_set)

def check_re_match(s):
    return pat.match(s)

def check_re_inverse(s): # Search for non-matching character.
    return not pat_inv.search(s)

def check_trans(s):
    return not s.translate(trans_table,allowed_chars)

test_long_almost_valid='a_very_long_string_that_is_mostly_valid_except_for_last_char'*99 + '!'
test_long_valid='a_very_long_string_that_is_completely_valid_' * 99
test_short_valid='short_valid_string'
test_short_invalid='/$%$%&'
test_long_invalid='/$%$%&' * 99
test_empty=''

def main():
    funcs = sorted(f for f in globals() if f.startswith('check_'))
    tests = sorted(f for f in globals() if f.startswith('test_'))
    for test in tests:
        print "Test %-15s (length = %d):" % (test, len(globals()[test]))
        for func in funcs:
            print "  %-20s : %.3f" % (func, 
                   timeit.Timer('%s(%s)' % (func, test), 'from __main__ import pat,allowed_set,%s' % ','.join(funcs+tests)).timeit(10000))
        print

if __name__=='__main__': main()

The results on my system are:

Test test_empty      (length = 0):
  check_re_inverse     : 0.042
  check_re_match       : 0.030
  check_set_all        : 0.027
  check_set_diff       : 0.029
  check_set_subset     : 0.029
  check_trans          : 0.014

Test test_long_almost_valid (length = 5941):
  check_re_inverse     : 2.690
  check_re_match       : 3.037
  check_set_all        : 18.860
  check_set_diff       : 2.905
  check_set_subset     : 2.903
  check_trans          : 0.182

Test test_long_invalid (length = 594):
  check_re_inverse     : 0.017
  check_re_match       : 0.015
  check_set_all        : 0.044
  check_set_diff       : 0.311
  check_set_subset     : 0.308
  check_trans          : 0.034

Test test_long_valid (length = 4356):
  check_re_inverse     : 1.890
  check_re_match       : 1.010
  check_set_all        : 14.411
  check_set_diff       : 2.101
  check_set_subset     : 2.333
  check_trans          : 0.140

Test test_short_invalid (length = 6):
  check_re_inverse     : 0.017
  check_re_match       : 0.019
  check_set_all        : 0.044
  check_set_diff       : 0.032
  check_set_subset     : 0.037
  check_trans          : 0.015

Test test_short_valid (length = 18):
  check_re_inverse     : 0.125
  check_re_match       : 0.066
  check_set_all        : 0.104
  check_set_diff       : 0.051
  check_set_subset     : 0.046
  check_trans          : 0.017

The translate approach seems best in most cases, dramatically so with long valid strings, but is beaten out by regexes in test_long_invalid (Presumably because the regex can bail out immediately, but translate always has to scan the whole string). The set approaches are usually worst, beating regexes only for the empty string case.

Using all(x in allowed_set for x in s) performs well if it bails out early, but can be bad if it has to iterate through every character. isSubSet and set difference are comparable, and are consistently proportional to the length of the string regardless of the data.

There's a similar difference between the regex methods matching all valid characters and searching for invalid characters. Matching performs a little better when checking for a long, but fully valid string, but worse for invalid characters near the end of the string.

Center an item with position: relative

You can use calc to position element relative to center. For example if you want to position element 200px right from the center .. you can do this :

#your_element{
    position:absolute;
    left: calc(50% + 200px);
}

Dont forget this

When you use signs + and - you must have one blank space between sign and number, but when you use signs * and / there is no need for blank space.

QtCreator: No valid kits found

Another way to solve this issue (I did it on Ubuntu 16.04 but it might also work for windows and other Ubuntu versions):

While going through the installation steps, when you reach the step where you choose which packages to install via check boxes, instead of just pressing next with the default "Tools" checkbox selected also check the box for the version of QT you would like in addition to the "Tools" box. I usually check the first box which is the latest version of QT.

After doing this you should not see the "no valid kits found" issue described in this thread.

Happy Coding.

How do I get bit-by-bit data from an integer value in C?

If you want the k-th bit of n, then do

(n & ( 1 << k )) >> k

Here we create a mask, apply the mask to n, and then right shift the masked value to get just the bit we want. We could write it out more fully as:

    int mask =  1 << k;
    int masked_n = n & mask;
    int thebit = masked_n >> k;

You can read more about bit-masking here.

Here is a program:

#include <stdio.h>
#include <stdlib.h>

int *get_bits(int n, int bitswanted){
  int *bits = malloc(sizeof(int) * bitswanted);

  int k;
  for(k=0; k<bitswanted; k++){
    int mask =  1 << k;
    int masked_n = n & mask;
    int thebit = masked_n >> k;
    bits[k] = thebit;
  }

  return bits;
}

int main(){
  int n=7;

  int  bitswanted = 5;

  int *bits = get_bits(n, bitswanted);

  printf("%d = ", n);

  int i;
  for(i=bitswanted-1; i>=0;i--){
    printf("%d ", bits[i]);
  }

  printf("\n");
}

Insert into a MySQL table or update if exists

Try this out:

INSERT INTO table (id, name, age) VALUES (1, 'A', 19) ON DUPLICATE KEY UPDATE id = id + 1;

Hope this helps.

How do I pull from a Git repository through an HTTP proxy?

This worked to me.

git config --global http.proxy proxy_user:proxy_passwd@proxy_ip:proxy_port

How do I remove objects from a JavaScript associative array?

Use method splice to completely remove an item from an object array:

Object.prototype.removeItem = function (key, value) {
    if (value == undefined)
        return;

    for (var i in this) {
        if (this[i][key] == value) {
            this.splice(i, 1);
        }
    }
};

var collection = [
    { id: "5f299a5d-7793-47be-a827-bca227dbef95", title: "one" },
    { id: "87353080-8f49-46b9-9281-162a41ddb8df", title: "two" },
    { id: "a1af832c-9028-4690-9793-d623ecc75a95", title: "three" }
];

collection.removeItem("id", "87353080-8f49-46b9-9281-162a41ddb8df");

PHP - include a php file and also send query parameters

Imagine the include as what it is: A copy & paste of the contents of the included PHP file which will then be interpreted. There is no scope change at all, so you can still access $someVar in the included file directly (even though you might consider a class based structure where you pass $someVar as a parameter or refer to a few global variables).

Scatter plot and Color mapping in Python

To add to wflynny's answer above, you can find the available colormaps here

Example:

import matplotlib.cm as cm
plt.scatter(x, y, c=t, cmap=cm.jet)

or alternatively,

plt.scatter(x, y, c=t, cmap='jet')

How to join two tables by multiple columns in SQL?

No, just include the different fields in the "ON" clause of 1 inner join statement:

SELECT * from Evalulation e JOIN Value v ON e.CaseNum = v.CaseNum
    AND e.FileNum = v.FileNum AND e.ActivityNum = v.ActivityNum

Change color of PNG image via CSS?

I found this great codepen example that you insert your hex color value and it returns the needed filter to apply this color to png

CSS filter generator to convert from black to target hex color

for example i needed my png to have the following color #1a9790

then you have to apply the following filter to you png

filter: invert(48%) sepia(13%) saturate(3207%) hue-rotate(130deg) brightness(95%) contrast(80%);

how to align all my li on one line?

I think the NOBR tag might be overkill, and as you said, unreliable.

There are 2 options available depending on how you are displaying the text.

If you are displaying text in a table cell you would do Long Text Here. If you are using a div or a span, you can use the style="white-space: nowrap;"

Convert Unicode to ASCII without errors in Python

As an extension to Ignacio Vazquez-Abrams' answer

>>> u'a?ä'.encode('ascii', 'ignore')
'a'

It is sometimes desirable to remove accents from characters and print the base form. This can be accomplished with

>>> import unicodedata
>>> unicodedata.normalize('NFKD', u'a?ä').encode('ascii', 'ignore')
'aa'

You may also want to translate other characters (such as punctuation) to their nearest equivalents, for instance the RIGHT SINGLE QUOTATION MARK unicode character does not get converted to an ascii APOSTROPHE when encoding.

>>> print u'\u2019'
’
>>> unicodedata.name(u'\u2019')
'RIGHT SINGLE QUOTATION MARK'
>>> u'\u2019'.encode('ascii', 'ignore')
''
# Note we get an empty string back
>>> u'\u2019'.replace(u'\u2019', u'\'').encode('ascii', 'ignore')
"'"

Although there are more efficient ways to accomplish this. See this question for more details Where is Python's "best ASCII for this Unicode" database?

Django: ImproperlyConfigured: The SECRET_KEY setting must not be empty

Let me share m interesting solution!

I put the SECRET_KEY = "***&^%$#" in settings packages init.py file and the error disappeared! it's actually a loading problem!

Hope this quick workaround is useful for some of you!

Calling a PHP function from an HTML form in the same file

Without reloading, using HTML and PHP only it is not possible, but this can be very similar to what you want, but you have to reload:

<?php
    function test() {
        echo $_POST["user"];
    }

    if (isset($_POST[])) { // If it is the first time, it does nothing
        test();
    }
?>

<form action="test.php" method="post">
    <input type="text" name="user" placeholder="enter a text" />
    <input type="submit" value="submit" onclick="test()" />
</form>

SQL Query to concatenate column values from multiple rows in Oracle

There are a few ways depending on what version you have - see the oracle documentation on string aggregation techniques. A very common one is to use LISTAGG:

SELECT pid, LISTAGG(Desc, ' ') WITHIN GROUP (ORDER BY seq) AS description
FROM B GROUP BY pid;

Then join to A to pick out the pids you want.

Note: Out of the box, LISTAGG only works correctly with VARCHAR2 columns.

How to make a section of an image a clickable link

The easiest way is to make the "button image" as a separate image. Then place it over the main image (using "style="position: absolute;". Assign the URL link to "button image". and smile :)

How to use template module with different set of variables?

- name: copy vhosts
  template: src=site-vhost.conf dest=/etc/apache2/sites-enabled/{{ item }}.conf
  with_items:
    - somehost.local
    - otherhost.local
  notify: restart apache

IMPORTANT: Note that an item does not have to be just a string, it can be an object with as many properties as you like, so that way you can pass any number of variables.

In the template I have:

<VirtualHost *:80>
    ServerAdmin [email protected]
    ServerName {{ item }}
    DocumentRoot /vagrant/public


    ErrorLog ${APACHE_LOG_DIR}/error-{{ item }}.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

</VirtualHost>

JavaScript: set dropdown selected item based on option text

You can loop through the select_obj.options. There's a #text method in each of the option object, which you can use to compare to what you want and set the selectedIndex of the select_obj.

Uncaught TypeError: Cannot read property 'toLowerCase' of undefined

your $(this).val() has no scope in your ajax call, because its not in change event function scope

May be you implemented that ajax call in your change event itself first, in that case it works fine. but when u created a function and calling that funciton in change event, scope for $(this).val() is not valid.

simply get the value using id selector instead of

$(#CourseSelect).val()

whole code should be like this:

 $(document).ready(function () 
{
    $("#CourseSelect").change(loadTeachers);
    loadTeachers();
});

function loadTeachers()
{
    $.ajax({ type:'GET', url:'/Manage/getTeachers/' + $(#CourseSelect).val(), dataType:'json', cache:false,
        success:function(data)
        { 
            $('#TeacherSelect').get(0).options.length = 0;    

            $.each(data, function(i, teacher) 
            {
                var option = $('<option />');
                option.val(teacher.employeeId);
                option.text(teacher.name);
                $('#TeacherSelect').append(option);
            });
        }, error:function(){ alert("Error while getting results"); }
    });
}

CodeIgniter PHP Model Access "Unable to locate the model you have specified"

If you are on Linux then make sure your File name must match with the string passed in the load model methods the first argument.

$this->load->model('Order_Model','order_model');

You can use the second argument using that you can call methods from your model and it will work on Linux and windows as well

$result = $this->order_model->get_order_details($orderID);

The model item passed into the dictionary is of type .. but this dictionary requires a model item of type

Observe if the view has the model required:

View

@model IEnumerable<WFAccess.Models.ViewModels.SiteViewModel>

<div class="row">
    <table class="table table-striped table-hover table-width-custom">
        <thead>
            <tr>
....

Controller

[HttpGet]
public ActionResult ListItems()
{
    SiteStore site = new SiteStore();
    site.GetSites();

    IEnumerable<SiteViewModel> sites =
        site.SitesList.Select(s => new SiteViewModel
        {
            Id = s.Id,
            Type = s.Type
        });

    return PartialView("_ListItems", sites);
}

In my case I Use a partial view but runs in normal views

Combination of async function + await + setTimeout

Since Node 7.6, you can combine the functions promisify function from the utils module with setTimeout() .

Node.js

const sleep = require('util').promisify(setTimeout)

Javascript

const sleep = m => new Promise(r => setTimeout(r, m))

Usage

(async () => {
    console.time("Slept for")
    await sleep(3000)
    console.timeEnd("Slept for")
})()

How to get the full path of the file from a file input

You cannot do so - the browser will not allow this because of security concerns. Although there are workarounds, the fact is that you shouldn't count on this working. The following Stack Overflow questions are relevant here:

In addition to these, the new HTML5 specification states that browsers will need to feed a Windows compatible fakepath into the input type="file" field, ostensibly for backward compatibility reasons.

So trying to obtain the path is worse then useless in newer browsers - you'll actually get a fake one instead.

Cannot hide status bar in iOS7

Add method in your view controller.

- (BOOL)prefersStatusBarHidden {
    return YES;
}

Dynamically create Bootstrap alerts box through JavaScript

Try this (see a working example of this code in jsfiddle: http://jsfiddle.net/periklis/7ATLS/1/)

<input type = "button" id = "clickme" value="Click me!"/>
<div id = "alert_placeholder"></div>
<script>
bootstrap_alert = function() {}
bootstrap_alert.warning = function(message) {
            $('#alert_placeholder').html('<div class="alert"><a class="close" data-dismiss="alert">×</a><span>'+message+'</span></div>')
        }

$('#clickme').on('click', function() {
            bootstrap_alert.warning('Your text goes here');
});
</script>?

EDIT: There are now libraries that simplify and streamline this process, such as bootbox.js

SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) symfony2

Countercheck if boostrap/cache/config.php database details are correct. That should give you an hint if they are.

If they are not, then you need to clear the cache using the following steps :

  1. rm -fr bootstrap/cache/*
  2. php artisan optimize

Facebook Javascript SDK Problem: "FB is not defined"

Facebook prefers that you load their SDK asynchronously so that it doesn't block any other scripts that you need for your page but due to the iframe there's a chance that the console tries to call a method on the FB object before the FB object is completely created even though FB is only called in the fbAsyncInit function.
Try loading the javascript synchronously and you shouldn't get the error anymore. To do this you can copy and paste the code that Facebook provides and place it in an external .js file and then include that .js file in a <script> tag in the <head> of your page. If you must load their SDK asynchronously then check for FB to be created first before calling the init function.

Serializing an object as UTF-8 XML in .NET

No, you can use a StringWriter to get rid of the intermediate MemoryStream. However, to force it into XML you need to use a StringWriter which overrides the Encoding property:

public class Utf8StringWriter : StringWriter
{
    public override Encoding Encoding => Encoding.UTF8;
}

Or if you're not using C# 6 yet:

public class Utf8StringWriter : StringWriter
{
    public override Encoding Encoding { get { return Encoding.UTF8; } }
}

Then:

var serializer = new XmlSerializer(typeof(SomeSerializableObject));
string utf8;
using (StringWriter writer = new Utf8StringWriter())
{
    serializer.Serialize(writer, entry);
    utf8 = writer.ToString();
}

Obviously you can make Utf8StringWriter into a more general class which accepts any encoding in its constructor - but in my experience UTF-8 is by far the most commonly required "custom" encoding for a StringWriter :)

Now as Jon Hanna says, this will still be UTF-16 internally, but presumably you're going to pass it to something else at some point, to convert it into binary data... at that point you can use the above string, convert it into UTF-8 bytes, and all will be well - because the XML declaration will specify "utf-8" as the encoding.

EDIT: A short but complete example to show this working:

using System;
using System.Text;
using System.IO;
using System.Xml.Serialization;

public class Test
{    
    public int X { get; set; }

    static void Main()
    {
        Test t = new Test();
        var serializer = new XmlSerializer(typeof(Test));
        string utf8;
        using (StringWriter writer = new Utf8StringWriter())
        {
            serializer.Serialize(writer, t);
            utf8 = writer.ToString();
        }
        Console.WriteLine(utf8);
    }


    public class Utf8StringWriter : StringWriter
    {
        public override Encoding Encoding => Encoding.UTF8;
    }
}

Result:

<?xml version="1.0" encoding="utf-8"?>
<Test xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <X>0</X>
</Test>

Note the declared encoding of "utf-8" which is what we wanted, I believe.

There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key country

If you were using DropDownListFor like this:

@Html.DropDownListFor(m => m.SelectedItemId, Model.MySelectList)

where MySelectList in the model was a property of type SelectList, this error could be thrown if the property was null.

Avoid this by simple initializing it in constructor, like this:

public MyModel()
{
    MySelectList = new SelectList(new List<string>()); // empty list of anything...
}

I know it's not the OP's case, but this might help someone like me which had the same error due to this.

How do you Make A Repeat-Until Loop in C++?

Just use:

do
{
  //enter code here
} while ( !condition );

So what this does is, it moves your 'check for condition' part to the end, since the while is at the end. So it only checks the condition after running the code, just like how you want it

node.js vs. meteor.js what's the difference?

Meteor is a framework built ontop of node.js. It uses node.js to deploy but has several differences.

The key being it uses its own packaging system instead of node's module based system. It makes it easy to make web applications using Node. Node can be used for a variety of things and on its own is terrible at serving up dynamic web content. Meteor's libraries make all of this easy.

How to convert a .eps file to a high quality 1024x1024 .jpg?

Maybe you should try it with -quality 100 -size "1024x1024", because resize often gives results that are ugly to view.

Line break in SSRS expression

Use the vbcrlf for new line in SSSR. e.g.

= First(Fields!SAPName.Value, "DataSet1") & vbcrlf & First(Fields!SAPStreet.Value, "DataSet1") & vbcrlf & First(Fields!SAPCityPostal.Value, "DataSet1") & vbcrlf & First(Fields!SAPCountry.Value, "DataSet1") 

Java, How do I get current index/key in "for each" loop

###################################################
###################################################
###################################################
AVOID THIS
###################################################
###################################################
###################################################

/*for (Song s: songList){
    System.out.println(s + "," + songList.indexOf(s); 
}*/

it is possible in linked list.

you have to make toString() in song class. if you don't it will print out reference of the song.

probably irrelevant for you by now. ^_^

How to use curl to get a GET request exactly same as using Chrome?

If you need to set the user header string in the curl request, you can use the -H option to set user agent like:

curl -H "user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.182 Safari/537.36" http://stackoverflow.com/questions/28760694/how-to-use-curl-to-get-a-get-request-exactly-same-as-using-chrome

Updated user-agent form newest Chrome at 02-22-2021


Using a proxy tool like Charles Proxy really helps make short work of something like what you are asking. Here is what I do, using this SO page as an example (as of July 2015 using Charles version 3.10):

  1. Get Charles Proxy running
  2. Make web request using browser
  3. Find desired request in Charles Proxy
  4. Right click on request in Charles Proxy
  5. Select 'Copy cURL Request'

Copy cURL Request example in Charles 3.10.2

You now have a cURL request you can run in a terminal that will mirror the request your browser made. Here is what my request to this page looked like (with the cookie header removed):

curl -H "Host: stackoverflow.com" -H "Cache-Control: max-age=0" -H "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8" -H "User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.89 Safari/537.36" -H "HTTPS: 1" -H "DNT: 1" -H "Referer: https://www.google.com/" -H "Accept-Language: en-US,en;q=0.8,en-GB;q=0.6,es;q=0.4" -H "If-Modified-Since: Thu, 23 Jul 2015 20:31:28 GMT" --compressed http://stackoverflow.com/questions/28760694/how-to-use-curl-to-get-a-get-request-exactly-same-as-using-chrome

How to query for Xml values and attributes from table in SQL Server?

Actually you're close to your goal, you just need to use nodes() method to split your rows and then get values:

select
    s.SqmId,
    m.c.value('@id', 'varchar(max)') as id,
    m.c.value('@type', 'varchar(max)') as type,
    m.c.value('@unit', 'varchar(max)') as unit,
    m.c.value('@sum', 'varchar(max)') as [sum],
    m.c.value('@count', 'varchar(max)') as [count],
    m.c.value('@minValue', 'varchar(max)') as minValue,
    m.c.value('@maxValue', 'varchar(max)') as maxValue,
    m.c.value('.', 'nvarchar(max)') as Value,
    m.c.value('(text())[1]', 'nvarchar(max)') as Value2
from sqm as s
    outer apply s.data.nodes('Sqm/Metrics/Metric') as m(c)

sql fiddle demo

Basic authentication for REST API using spring restTemplate

You may use spring-boot RestTemplateBuilder

@Bean
RestOperations rest(RestTemplateBuilder restTemplateBuilder) {
    return restTemplateBuilder.basicAuthentication("user", "password").build();
}

See documentation

(before SB 2.1.0 it was #basicAuthorization)

How to use BigInteger?

BigInteger is an immutable class. So whenever you do any arithmetic, you have to reassign the output to a variable.

How to install the Raspberry Pi cross compiler on my Linux host machine?

I could not compile QT5 with any of the (fairly outdated) toolchains from git://github.com/raspberrypi/tools.git. The configure script kept failing with an "could not determine architecture" error and with massive path problems for include directories. What worked for me was using the Linaro toolchain

http://releases.linaro.org/components/toolchain/binaries/4.9-2016.02/arm-linux-gnueabihf/runtime-linaro-gcc4.9-2016.02-arm-linux-gnueabihf.tar.xz

in combination with

https://raw.githubusercontent.com/riscv/riscv-poky/master/scripts/sysroot-relativelinks.py

Failing to fix the symlinks of the sysroot leads to undefined symbol errors as described here: An error building Qt libraries for the raspberry pi This happened to me when I tried the fixQualifiedLibraryPaths script from tools.git. Everthing else is described in detail in http://wiki.qt.io/RaspberryPi2EGLFS . My configure settings were:

./configure -opengl es2 -device linux-rpi3-g++ -device-option CROSS_COMPILE=/usr/local/rasp/gcc-linaro-4.9-2016.02-x86_64_arm-linux-gnueabihf/bin/arm-linux-gnueabihf- -sysroot /usr/local/rasp/sysroot -opensource -confirm-license -optimized-qmake -reduce-exports -release -make libs -prefix /usr/local/qt5pi -hostprefix /usr/local/qt5pi

with /usr/local/rasp/sysroot being the path of my local Raspberry Pi 3 Raspbian (Jessie) system copy and /usr/local/qt5pi being the path of the cross compiled QT that also has to be copied to the device. Be aware that Jessie comes with GCC 4.9.2 when you choose your toolchain.

How to make RatingBar to show five stars

<RatingBar
            android:id="@+id/rating"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            style="?android:attr/ratingBarStyleSmall"
            android:numStars="5"
            android:stepSize="0.1"
            android:isIndicator="true" />

in code

mRatingBar.setRating(int)

How can I check the size of a file in a Windows batch script?

As usual, VBScript is available for you to use.....

Set objFS = CreateObject("Scripting.FileSystemObject")
Set wshArgs = WScript.Arguments
strFile = wshArgs(0)
WScript.Echo objFS.GetFile(strFile).Size & " bytes"

Save as filesize.vbs and enter on the command-line:

C:\test>cscript /nologo filesize.vbs file.txt
79 bytes

Use a for loop (in batch) to get the return result.

R error "sum not meaningful for factors"

The error comes when you try to call sum(x) and x is a factor.

What that means is that one of your columns, though they look like numbers are actually factors (what you are seeing is the text representation)

simple fix, convert to numeric. However, it needs an intermeidate step of converting to character first. Use the following:

family[, 1] <- as.numeric(as.character( family[, 1] ))
family[, 3] <- as.numeric(as.character( family[, 3] ))

For a detailed explanation of why the intermediate as.character step is needed, take a look at this question: How to convert a factor to integer\numeric without loss of information?

Passing an array to a query using a WHERE clause

For MySQLi with an escape function:

$ids = array_map(function($a) use($mysqli) { 
    return is_string($a) ? "'".$mysqli->real_escape_string($a)."'" : $a;
  }, $ids);
$ids = join(',', $ids);  
$result = $mysqli->query("SELECT * FROM galleries WHERE id IN ($ids)");

For PDO with prepared statement:

$qmarks = implode(',', array_fill(0, count($ids), '?'));
$sth = $dbh->prepare("SELECT * FROM galleries WHERE id IN ($qmarks)");
$sth->execute($ids);

Get first day of week in PHP?

<?php
/* PHP 5.3.0 */

date_default_timezone_set('America/Denver'); //Set apprpriate timezone
$start_date = strtotime('2009-12-15'); //Set start date

//Today's date if $start_date is a Sunday, otherwise date of previous Sunday
$today_or_previous_sunday = mktime(0, 0, 0, date('m', $start_date), date('d', $start_date), date('Y', $start_date)) - ((date("w", $start_date) ==0) ? 0 : (86400 * date("w", $start_date)));

//prints 12-13-2009 (month-day-year)
echo date('m-d-Y', $today_or_previous_sunday);

?>

(Note: MM, dd and yyyy in the Question are not standard php date format syntax - I can't be sure what is meant, so I set the $start_date with ISO year-month-day)

Rails 4: List of available datatypes

Rails4 has some added datatypes for Postgres.

For example, railscast #400 names two of them:

Rails 4 has support for native datatypes in Postgres and we’ll show two of these here, although a lot more are supported: array and hstore. We can store arrays in a string-type column and specify the type for hstore.

Besides, you can also use cidr, inet and macaddr. For more information:

https://blog.engineyard.com/2013/new-in-rails-4

How to make an AlertDialog in Flutter?

Simply used this custom dialog class which field you not needed to leave it or make it null so this customization you got easily.

import 'package:flutter/material.dart';

class CustomAlertDialog extends StatelessWidget {
  final Color bgColor;
  final String title;
  final String message;
  final String positiveBtnText;
  final String negativeBtnText;
  final Function onPostivePressed;
  final Function onNegativePressed;
  final double circularBorderRadius;

  CustomAlertDialog({
    this.title,
    this.message,
    this.circularBorderRadius = 15.0,
    this.bgColor = Colors.white,
    this.positiveBtnText,
    this.negativeBtnText,
    this.onPostivePressed,
    this.onNegativePressed,
  })  : assert(bgColor != null),
        assert(circularBorderRadius != null);

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: title != null ? Text(title) : null,
      content: message != null ? Text(message) : null,
      backgroundColor: bgColor,
      shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(circularBorderRadius)),
      actions: <Widget>[
        negativeBtnText != null
            ? FlatButton(
                child: Text(negativeBtnText),
                textColor: Theme.of(context).accentColor,
                onPressed: () {
                  Navigator.of(context).pop();
                  if (onNegativePressed != null) {
                    onNegativePressed();
                  }
                },
              )
            : null,
        positiveBtnText != null
            ? FlatButton(
                child: Text(positiveBtnText),
                textColor: Theme.of(context).accentColor,
                onPressed: () {
                  if (onPostivePressed != null) {
                    onPostivePressed();
                  }
                },
              )
            : null,
      ],
    );
  }
}

Usage:

var dialog = CustomAlertDialog(
  title: "Logout",
  message: "Are you sure, do you want to logout?",
  onPostivePressed: () {},
  positiveBtnText: 'Yes',
  negativeBtnText: 'No');
showDialog(
  context: context,
  builder: (BuildContext context) => dialog);

Output:

enter image description here

Running EXE with parameters

System.Diagnostics.Process.Start("PATH to exe", "Command Line Arguments");

How to add New Column with Value to the Existing DataTable?

Without For loop:

Dim newColumn As New Data.DataColumn("Foo", GetType(System.String))     
newColumn.DefaultValue = "Your DropDownList value" 
table.Columns.Add(newColumn) 

C#:

System.Data.DataColumn newColumn = new System.Data.DataColumn("Foo", typeof(System.String));
newColumn.DefaultValue = "Your DropDownList value";
table.Columns.Add(newColumn);

Two submit buttons in one form

The best way to deal with multiple submit button is using switch case in server script

<form action="demo_form.php" method="get">

Choose your favorite subject:

<button name="subject" type="submit" value="html">HTML</button>
<button name="subject" type="submit" value="css">CSS</button>
<button name="subject" type="submit" value="javascript">Java Script</button>
<button name="subject" type="submit" value="jquery">jQuery</button>

</form>

server code/server script - where you are submitting the form:

demo_form.php

<?php

switch($_REQUEST['subject']) {

    case 'html': //action for html here
                break;

    case 'css': //action for css here
                break;

    case 'javascript': //action for javascript here
                        break;

    case 'jquery': //action for jquery here
                    break;
}

?>

Source: W3Schools.com

Android checkbox style

Perhaps you want something like:

<style name="CustomActivityTheme" parent="@android:style/Theme.Holo">
    <item name="android:checkboxStyle">@style/customCheckBoxStyle</item>
</style>

<style name="customCheckBoxStyle" parent="@android:style/Widget.CompoundButton.CheckBox">
    <item name="android:textColor">@android:color/black</item>
</style>

Note, the textColor item.

PHP server on local machine?

If you have a local machine with the right software: web server with support for PHP, there's no reason why you can't do as you describe.

I'm doing it at the moment with XAMPP on a Windows XP machine, and (at home) with Kubuntu and a LAMP stack.

REST API using POST instead of GET

You can't use the API using POST or GET if they are not build to call using these methods separetly. Like if your API say

/service/function?param1=value1&param2=value2

is accessed by using GET method. Then you can not call it using POST method if it is not specified as POST method by its creator. If you do that you may got 405 Method not allowed status.

Generally in POST method you need to send the content in body with specified format which is described in content-type header for ex. application/json for json data.

And after that the request body gets deserialized at server end. So you need to pass the serialized data from the client and it is decided by the service developer.

But in general terms GET is used when server returns some data to the client and have not any impact on server whereas POST is used to create some resource on server. So generally it should not be same.

How do I download a package from apt-get without installing it?

Try

apt-get -d install <packages>

It is documented in man apt-get.

Just for clarification; the downloaded packages are located in the apt package cache at

/var/cache/apt/archives

ApiNotActivatedMapError for simple html page using google-places-api

Have you tried following the advice on the linked help page? The help page at http://g.co/mapsJSApiErrors says:

ApiNotActivatedMapError

The Google Maps JavaScript API is not activated on your API project. You may need to enable the Google Maps JavaScript API under APIs in the Google Developers Console.

See Obtaining an API key.

So check that the key you are using has Google Maps JavaScript API enabled.

How do I connect to a specific Wi-Fi network in Android programmatically?

Credit to @raji-ramamoorthi & @kenota

The solution which worked for me is combination of above contributors in this thread.

To get ScanResult here is the process.

WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
if (wifi.isWifiEnabled() == false) {
            Toast.makeText(getApplicationContext(), "wifi is disabled..making it enabled", Toast.LENGTH_LONG).show();
            wifi.setWifiEnabled(true);
        }

BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context c, Intent intent) {
                 wifi.getScanResults();
            }
        };

Notice to unregister it on onPause & onStop live this unregisterReceiver(broadcastReceiver);

public void connectWiFi(ScanResult scanResult) {
        try {

            Log.v("rht", "Item clicked, SSID " + scanResult.SSID + " Security : " + scanResult.capabilities);

            String networkSSID = scanResult.SSID;
            String networkPass = "12345678";

            WifiConfiguration conf = new WifiConfiguration();
            conf.SSID = "\"" + networkSSID + "\"";   // Please note the quotes. String should contain ssid in quotes
            conf.status = WifiConfiguration.Status.ENABLED;
            conf.priority = 40;

            if (scanResult.capabilities.toUpperCase().contains("WEP")) {
                Log.v("rht", "Configuring WEP");    
                conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
                conf.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
                conf.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
                conf.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
                conf.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
                conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
                conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
                conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
                conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);

                if (networkPass.matches("^[0-9a-fA-F]+$")) {
                    conf.wepKeys[0] = networkPass;
                } else {
                    conf.wepKeys[0] = "\"".concat(networkPass).concat("\"");
                }

                conf.wepTxKeyIndex = 0;

            } else if (scanResult.capabilities.toUpperCase().contains("WPA")) {
                Log.v("rht", "Configuring WPA");

                conf.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
                conf.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
                conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
                conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
                conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
                conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
                conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
                conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
                conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);

                conf.preSharedKey = "\"" + networkPass + "\"";

            } else {
                Log.v("rht", "Configuring OPEN network");
                conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
                conf.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
                conf.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
                conf.allowedAuthAlgorithms.clear();
                conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
                conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
                conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
                conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
                conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
                conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            }

            WifiManager wifiManager = (WifiManager) WiFiApplicationCore.getAppContext().getSystemService(Context.WIFI_SERVICE);
            int networkId = wifiManager.addNetwork(conf);

            Log.v("rht", "Add result " + networkId);

            List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
            for (WifiConfiguration i : list) {
                if (i.SSID != null && i.SSID.equals("\"" + networkSSID + "\"")) {
                    Log.v("rht", "WifiConfiguration SSID " + i.SSID);

                    boolean isDisconnected = wifiManager.disconnect();
                    Log.v("rht", "isDisconnected : " + isDisconnected);

                    boolean isEnabled = wifiManager.enableNetwork(i.networkId, true);
                    Log.v("rht", "isEnabled : " + isEnabled);

                    boolean isReconnected = wifiManager.reconnect();
                    Log.v("rht", "isReconnected : " + isReconnected);

                    break;
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

Capturing standard out and error with Start-Process

That's how Start-Process was designed for some reason. Here's a way to get it without sending to file:

$pinfo = New-Object System.Diagnostics.ProcessStartInfo
$pinfo.FileName = "ping.exe"
$pinfo.RedirectStandardError = $true
$pinfo.RedirectStandardOutput = $true
$pinfo.UseShellExecute = $false
$pinfo.Arguments = "localhost"
$p = New-Object System.Diagnostics.Process
$p.StartInfo = $pinfo
$p.Start() | Out-Null
$p.WaitForExit()
$stdout = $p.StandardOutput.ReadToEnd()
$stderr = $p.StandardError.ReadToEnd()
Write-Host "stdout: $stdout"
Write-Host "stderr: $stderr"
Write-Host "exit code: " + $p.ExitCode

How do I call a Django function on button click?

The following answer could be helpful for the first part of your question:

Django: How can I call a view function from template?

Difference between the System.Array.CopyTo() and System.Array.Clone()

Both perform shallow copies as @PatrickDesjardins said (despite the many misled souls who think that CopyTo does a deep copy).

However, CopyTo allows you to copy one array to a specified index in the destination array, giving it significantly more flexibility.

Can't fix Unsupported major.minor version 52.0 even after fixing compatibility

I had the same issue. Turned out I used some external jars (apache poi 4.1.2) which were compiled with 1.8. Solved it by changing Java Build Path JRE to 1.8.

How to set session timeout in web.config

If it's not working from web.config, you need to set it from IIS.