Programs & Examples On #Buildbot

Buildbot is an open-source framework for automating software build, test, and release processes.

Aborting a stash pop in Git

Simple one-liner

I have always used

git reset --merge

I can't remember it ever failing.

sweet-alert display HTML code in text

As of 2018, the accepted answer is out-of-date:

Sweetalert is maintained, and you can solve the original question's issue with use of the content option.

OpenSSL: unable to verify the first certificate for Experian URL

Adding additional information to emboss's answer.

To put it simply, there is an incorrect cert in your certificate chain.

For example, your certificate authority will have most likely given you 3 files.

  • your_domain_name.crt
  • DigiCertCA.crt # (Or whatever the name of your certificate authority is)
  • TrustedRoot.crt

You most likely combined all of these files into one bundle.

-----BEGIN CERTIFICATE----- 
(Your Primary SSL certificate: your_domain_name.crt) 
-----END CERTIFICATE----- 
-----BEGIN CERTIFICATE----- 
(Your Intermediate certificate: DigiCertCA.crt) 
-----END CERTIFICATE----- 
-----BEGIN CERTIFICATE----- 
(Your Root certificate: TrustedRoot.crt) 
-----END CERTIFICATE-----

If you create the bundle, but use an old, or an incorrect version of your Intermediate Cert (DigiCertCA.crt in my example), you will get the exact symptoms you are describing.

Redownload all certs from your certificate authority and make a fresh bundle.

What is the easiest way to clear a database from the CLI with manage.py in Django?

I think Django docs explicitly mention that if the intent is to start from an empty DB again (which seems to be OP's intent), then just drop and re-create the database and re-run migrate (instead of using flush):

If you would rather start from an empty database and re-run all migrations, you should drop and recreate the database and then run migrate instead.

So for OP's case, we just need to:

  1. Drop the database from MySQL
  2. Recreate the database
  3. Run python manage.py migrate

Fastest way of finding differences between two files in unix?

You could try..

comm -13 <(sort file1) <(sort file2) > file3

or

grep -Fxvf file1 file2 > file3

or

diff file1 file2 | grep "<" | sed 's/^<//g'  > file3

or

join -v 2 <(sort file1) <(sort file2) > file3

How to copy and paste worksheets between Excel workbooks?

This code copies and pastes all sheets (not cell values) from one source workbook to a destination workbook:

Private Sub copypastesheets()

Dim wbSource, wbDestination As Object
Dim nbSheets As Integer

Set wbSource = Workbooks("your_source_workbook_name")
Set wbDestination = Workbooks("your_destination_workbook_name")
nbSheets = wbDestination.Sheets.Count - 1

For Each sheetItem In wbSource.Sheets

    nbSheets = nbSheets + 1
    sheetItem.Copy after:=wbDestination.Sheets(nbSheets)

Next sheetItem


End Sub

package javax.mail and javax.mail.internet do not exist

It might be that you do not have the necessary .jar files that give you access to the Java Mail API. These can be downloaded from here.

How to grep a string in a directory and all its subdirectories?

If your grep supports -R, do:

grep -R 'string' dir/

If not, then use find:

find dir/ -type f -exec grep -H 'string' {} +

How to get the index of a maximum element in a NumPy array along one axis

argmax() will only return the first occurrence for each row. http://docs.scipy.org/doc/numpy/reference/generated/numpy.argmax.html

If you ever need to do this for a shaped array, this works better than unravel:

import numpy as np
a = np.array([[1,2,3], [4,3,1]])  # Can be of any shape
indices = np.where(a == a.max())

You can also change your conditions:

indices = np.where(a >= 1.5)

The above gives you results in the form that you asked for. Alternatively, you can convert to a list of x,y coordinates by:

x_y_coords =  zip(indices[0], indices[1])

How to change the background color on a Java panel?

You could call:


getContentPane().setBackground(Color.black);

Or add a JPanel to the JFrame your using. Then add your components to the JPanel. This will allow you to call


setBackground(Color.black);

on the JPanel to set the background color.

How to use SQL Select statement with IF EXISTS sub query?

Use CASE:

SELECT 
  TABEL1.Id, 
  CASE WHEN EXISTS (SELECT Id FROM TABLE2 WHERE TABLE2.ID = TABLE1.ID)
       THEN 'TRUE' 
       ELSE 'FALSE'
  END AS NewFiled  
FROM TABLE1

If TABLE2.ID is Unique or a Primary Key, you could also use this:

SELECT 
  TABEL1.Id, 
  CASE WHEN TABLE2.ID IS NOT NULL
       THEN 'TRUE' 
       ELSE 'FALSE'
  END AS NewFiled  
FROM TABLE1
  LEFT JOIN Table2
    ON TABLE2.ID = TABLE1.ID

Remove a file from a Git repository without deleting it from the local filesystem

If you want to just untrack a file and not delete from local and remote repo then use this command:

git update-index --assume-unchanged  file_name_with_path

Rethrowing exceptions in Java without losing the stack trace

In Java is almost the same:

try
{
   ...
}
catch (Exception e)
{
   if (e instanceof FooException)
     throw e;
}

Simple timeout in java

    @Singleton
    @AccessTimeout(value=120000)
    public class StatusSingletonBean {
      private String status;
    
      @Lock(LockType.WRITE)
      public void setStatus(String new Status) {
        status = newStatus;
      }
      @Lock(LockType.WRITE)
      @AccessTimeout(value=360000)
      public void doTediousOperation {
        //...
      }
    }
    //The following singleton has a default access timeout value of 60 seconds, specified //using the TimeUnit.SECONDS constant:
    @Singleton
    @AccessTimeout(value=60, timeUnit=SECONDS) 
    public class StatusSingletonBean { 
    //... 
    }  
    //The Java EE 6 Tutorial

//https://docs.oracle.com/javaee/6/tutorial/doc/gipvi.html

Updating version numbers of modules in a multi-module Maven project

The best way is, since you intend to bundle your modules together, you can specify <dependencyManagement> tag in outer most pom.xml (parent module) direct under <project> tag. It controls the version and group name. In your individual module, you just need to specify the <artifactId> tag in your pom.xml. It will take the version from parent file.

Best practice: PHP Magic Methods __set and __get

I am now returning to setters and getters but I am also putting the getters and setters in the magic methos __get and __set. This way I have a default behavior when I do this

$class->var;

This will just call the getter I have set in the __get. Normally I will just use the getter directly but there are still some instances where this is just simpler.

How to unnest a nested list

the first case can also be easily done as:

A=A[0]

Convert array of JSON object strings to array of JS objects

var json = jQuery.parseJSON(s); //If you have jQuery.

Since the comment looks cluttered, please use the parse function after enclosing those square brackets inside the quotes.

var s=['{"Select":"11","PhotoCount":"12"}','{"Select":"21","PhotoCount":"22"}'];

Change the above code to

var s='[{"Select":"11","PhotoCount":"12"},{"Select":"21","PhotoCount":"22"}]';

Eg:

$(document).ready(function() {
    var s= '[{"Select":"11","PhotoCount":"12"},{"Select":"21","PhotoCount":"22"}]';

    s = jQuery.parseJSON(s);

    alert( s[0]["Select"] );
});

And then use the parse function. It'll surely work.

EDIT :Extremely sorry that I gave the wrong function name. it's jQuery.parseJSON

Jquery

The json api

Edit (30 April 2020):

Editing since I got an upvote for this answer. There's a browser native function available instead of JQuery (for nonJQuery users), JSON.parse("<json string here>")

how to use html2canvas and jspdf to export to pdf in a proper and simple way

I have made a jsfiddle for you.

 <canvas id="canvas" width="480" height="320"></canvas> 
      <button id="download">Download Pdf</button>

'

        html2canvas($("#canvas"), {
            onrendered: function(canvas) {         
                var imgData = canvas.toDataURL(
                    'image/png');              
                var doc = new jsPDF('p', 'mm');
                doc.addImage(imgData, 'PNG', 10, 10);
                doc.save('sample-file.pdf');
            }
        });

jsfiddle: http://jsfiddle.net/rpaul/p4s5k59s/5/

Tested in Chrome38, IE11 and Firefox 33. Seems to have issues with Safari. However, Andrew got it working in Safari 8 on Mac OSx by switching to JPEG from PNG. For details, see his comment below.

Illegal string offset Warning PHP

i think the only reason for this message is because target Array is actually an array like string etc (JSON -> {"host": "127.0.0.1"}) variable

Doctrine - How to print out the real sql, not just the prepared statement?

You can check the query executed by your app if you log all the queries in mysql:

http://dev.mysql.com/doc/refman/5.1/en/query-log.html

there will be more queries not only the one that you are looking for but you can grep for it.

but usually ->getSql(); works

Edit:

to view all the mysql queries I use

sudo vim /etc/mysql/my.cnf 

and add those 2 lines:

general_log = on
general_log_file = /tmp/mysql.log

and restart mysql

CSV in Python adding an extra carriage return, on Windows

In Python 3 (I haven't tried this in Python 2), you can also simply do

with open('output.csv','w',newline='') as f:
    writer=csv.writer(f)
    writer.writerow(mystuff)
    ...

as per documentation.

More on this in the doc's footnote:

If newline='' is not specified, newlines embedded inside quoted fields will not be interpreted correctly, and on platforms that use \r\n linendings on write an extra \r will be added. It should always be safe to specify newline='', since the csv module does its own (universal) newline handling.

Jquery submit form

Try this :

$('#form1').submit();

or

document.form1.submit();

#if DEBUG vs. Conditional("DEBUG")

With the first example, SetPrivateValue won't exist in the build if DEBUG is not defined, with the second example, calls to SetPrivateValue won't exist in the build if DEBUG is not defined.

With the first example, you'll have to wrap any calls to SetPrivateValue with #if DEBUG as well.

With the second example, the calls to SetPrivateValue will be omitted, but be aware that SetPrivateValue itself will still be compiled. This is useful if you're building a library, so an application referencing your library can still use your function (if the condition is met).

If you want to omit the calls and save the space of the callee, you could use a combination of the two techniques:

[System.Diagnostics.Conditional("DEBUG")]
public void SetPrivateValue(int value){
    #if DEBUG
    // method body here
    #endif
}

How do I get the max and min values from a set of numbers entered?

I tried to optimize solution by handling user input exceptions.

public class Solution {
    private static Integer TERMINATION_VALUE = 0;
    public static void main(String[] args) {
        Integer value = null;
        Integer minimum = Integer.MAX_VALUE;
        Integer maximum = Integer.MIN_VALUE;
        Scanner scanner = new Scanner(System.in);
        while (value != TERMINATION_VALUE) {
            Boolean inputValid = Boolean.TRUE;
            try {
                System.out.print("Enter a value: ");
                value = scanner.nextInt();
            } catch (InputMismatchException e) {
                System.out.println("Value must be greater or equal to " + Integer.MIN_VALUE + " and less or equals to " + Integer.MAX_VALUE );
                inputValid = Boolean.FALSE;
                scanner.next();
            }
            if(Boolean.TRUE.equals(inputValid)){
                minimum = Math.min(minimum, value);
                maximum = Math.max(maximum, value);
            }
        }
        if(TERMINATION_VALUE.equals(minimum) || TERMINATION_VALUE.equals(maximum)){
            System.out.println("There is not any valid input.");
        } else{
            System.out.println("Minimum: " + minimum);
            System.out.println("Maximum: " + maximum);
        }
        scanner.close();
    }
}

Add ... if string is too long PHP

This will return a given string with ellipsis based on WORD count instead of characters:

<?php
/**
*    Return an elipsis given a string and a number of words
*/
function elipsis ($text, $words = 30) {
    // Check if string has more than X words
    if (str_word_count($text) > $words) {

        // Extract first X words from string
        preg_match("/(?:[^\s,\.;\?\!]+(?:[\s,\.;\?\!]+|$)){0,$words}/", $text, $matches);
        $text = trim($matches[0]);

        // Let's check if it ends in a comma or a dot.
        if (substr($text, -1) == ',') {
            // If it's a comma, let's remove it and add a ellipsis
            $text = rtrim($text, ',');
            $text .= '...';
        } else if (substr($text, -1) == '.') {
            // If it's a dot, let's remove it and add a ellipsis (optional)
            $text = rtrim($text, '.');
            $text .= '...';
        } else {
            // Doesn't end in dot or comma, just adding ellipsis here
            $text .= '...';
        }
    }
    // Returns "ellipsed" text, or just the string, if it's less than X words wide.
    return $text;
}

$description = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quibusdam ut placeat consequuntur pariatur iure eum ducimus quasi perferendis, laborum obcaecati iusto ullam expedita excepturi debitis nisi deserunt fugiat velit assumenda. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Incidunt, blanditiis nostrum. Nostrum cumque non rerum ducimus voluptas officia tempore modi, nulla nisi illum, voluptates dolor sapiente ut iusto earum. Esse? Lorem ipsum dolor sit amet, consectetur adipisicing elit. A eligendi perspiciatis natus autem. Necessitatibus eligendi doloribus corporis quia, quas laboriosam. Beatae repellat dolor alias. Perferendis, distinctio, laudantium? Dolorum, veniam, amet!';

echo elipsis($description, 30);
?>

SQL Error: ORA-00936: missing expression

In the above query when we are trying to combine two or more tables it is necessary to use joins and specify the alias name for description and date (that means, the table from which you are fetching the description and date values)

SELECT DISTINCT Description, Date as treatmentDate  
FROM doothey.Patient P  
INNER JOIN doothey.Account A ON P.PatientID = A.PatientID  
INNER JOIN doothey.AccountLine AL ON A.AccountNo = AL.AccountNo  
INNER JOIN doothey.Item I ON AL.ItemNo = I.ItemNo  
WHERE p.FamilyName = 'Stange' AND p.GivenName = 'Jessie';

Twitter Bootstrap Multilevel Dropdown Menu

This example is from http://bootsnipp.com/snippets/featured/multi-level-dropdown-menu-bs3

Works for me in Bootstrap v3.1.1.

HTML

<div class="container">
<div class="row">
    <h2>Multi level dropdown menu in Bootstrap 3</h2>
    <hr>
    <div class="dropdown">
        <a id="dLabel" role="button" data-toggle="dropdown" class="btn btn-primary" data-target="#" href="/page.html">
            Dropdown <span class="caret"></span>
        </a>
        <ul class="dropdown-menu multi-level" role="menu" aria-labelledby="dropdownMenu">
          <li><a href="#">Some action</a></li>
          <li><a href="#">Some other action</a></li>
          <li class="divider"></li>
          <li class="dropdown-submenu">
            <a tabindex="-1" href="#">Hover me for more options</a>
            <ul class="dropdown-menu">
              <li><a tabindex="-1" href="#">Second level</a></li>
              <li class="dropdown-submenu">
                <a href="#">Even More..</a>
                <ul class="dropdown-menu">
                    <li><a href="#">3rd level</a></li>
                    <li><a href="#">3rd level</a></li>
                </ul>
              </li>
              <li><a href="#">Second level</a></li>
              <li><a href="#">Second level</a></li>
            </ul>
          </li>
        </ul>
    </div>
</div>

CSS

.dropdown-submenu {
position: relative;
}

.dropdown-submenu>.dropdown-menu {
top: 0;
left: 100%;
margin-top: -6px;
margin-left: -1px;
-webkit-border-radius: 0 6px 6px 6px;
-moz-border-radius: 0 6px 6px;
border-radius: 0 6px 6px 6px;
}

.dropdown-submenu:hover>.dropdown-menu {
display: block;
}

.dropdown-submenu>a:after {
display: block;
content: " ";
float: right;
width: 0;
height: 0;
border-color: transparent;
border-style: solid;
border-width: 5px 0 5px 5px;
border-left-color: #ccc;
margin-top: 5px;
margin-right: -10px;
}

.dropdown-submenu:hover>a:after {
border-left-color: #fff;
}

.dropdown-submenu.pull-left {
float: none;
}

.dropdown-submenu.pull-left>.dropdown-menu {
left: -100%;
margin-left: 10px;
-webkit-border-radius: 6px 0 6px 6px;
-moz-border-radius: 6px 0 6px 6px;
border-radius: 6px 0 6px 6px;
}

How do I install SciPy on 64 bit Windows?

You can either download a scientific Python distribution. One of the ones mentioned here: https://scipy.org/install.html

Or pip install from a whl file here if the above is not an option for you.

http://www.lfd.uci.edu/~gohlke/pythonlibs/#scipy

"No such file or directory" error when executing a binary

Old question, but hopefully this'll help someone else.

In my case I was using a toolchain on Ubuntu 12.04 that was built on Ubuntu 10.04 (requires GCC 4.1 to build). As most of the libraries have moved to multiarch dirs, it couldn't find ld.so. So, make a symlink for it.

Check required path:

$ readelf -a arm-linux-gnueabi-gcc | grep interpreter:
      [Requesting program interpreter: /lib/ld-linux-x86-64.so.2]

Create symlink:

$ sudo ln -s /lib/x86_64-linux-gnu/ld-linux-x86-64.so.2 /lib/ld-linux-x86-64.so.2

If you're on 32bit, it'll be i386-linux-gnu and not x86_64-linux-gnu.

Why do we not have a virtual constructor in C++?

Although the concept of virtual constructors does not fit in well since object type is pre-requisite for object creation, its not completly over-ruled.

GOF's 'factory method' design pattern makes use of the 'concept' of virtual constructor, which is handly in certain design situations.

Error: Cannot find module '../lib/utils/unsupported.js' while using Ionic

I followed the previous answers and reinstalled node. But I got this error.

Warning: The post-install step did not complete successfully You can try again using brew postinstall node

So I ran this command

sudo chown -R $(whoami):admin /usr/local/lib/node_modules/

Then ran

brew postinstall node

How can I delete derived data in Xcode 8?

Steps For Delete DerivedData:

  1. Open Finder
  2. From menu click on Go > Go to Folder
  3. Enter ~/Library/Developer/Xcode/DerivedData in textfield
  4. Click on Go button
  5. You will see the folders of your Xcode projects
  6. Delete the folders of projects, which you don't need.

Comparing two hashmaps for equal values and same key sets?

Simply use :

mapA.equals(mapB);

Compares the specified object with this map for equality. Returns true if the given object is also a map and the two maps represent the same mappings

How is a JavaScript hash map implemented?

Here is an easy and convenient way of using something similar to the Java map:

var map= {
    'map_name_1': map_value_1,
    'map_name_2': map_value_2,
    'map_name_3': map_value_3,
    'map_name_4': map_value_4
    }

And to get the value:

alert( map['map_name_1'] );    // fives the value of map_value_1

......  etc  .....

How to get the current branch name in Git?

You can just type in command line (console) on Linux, in the repository directory:

$ git status

and you will see some text, among which something similar to:

...
On branch master
...

which means you are currently on master branch. If you are editing any file at that moment and it is located in the same local repository (local directory containing the files that are under Git version control management), you are editing file in this branch.

Is JavaScript guaranteed to be single-threaded?

JavaScript/ECMAScript is designed to live within a host environment. That is, JavaScript doesn't actually do anything unless the host environment decides to parse and execute a given script, and provide environment objects that let JavaScript actually be useful (such as the DOM in browsers).

I think a given function or script block will execute line-by-line and that is guaranteed for JavaScript. However, perhaps a host environment could execute multiple scripts at the same time. Or, a host environment could always provide an object that provides multi-threading. setTimeout and setInterval are examples, or at least pseudo-examples, of a host environment providing a way to do some concurrency (even if it's not exactly concurrency).

How to set border's thickness in percentages?

You can also use

border-left: 9vw solid #F5E5D6;
border-right: 9vw solid #F5E5D6;     

OR

border: 9vw solid #F5E5D6;

How do I see if Wi-Fi is connected on Android?

Try out this method.

public boolean isInternetConnected() {
    ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    boolean ret = true;
    if (conMgr != null) {
        NetworkInfo i = conMgr.getActiveNetworkInfo();

        if (i != null) {
            if (!i.isConnected()) {
                ret = false;
            }

            if (!i.isAvailable()) {
                ret = false;
            }
        }

        if (i == null)
            ret = false;
    } else
        ret = false;
    return ret;
}

This method will help to find internet connection available or not.

Dictionary text file

For an English dictionary .txt file, you can use Custom Dictionary.

You can also generate a list aspell or wordlist with own settings.

Also you can take a look at http://wordlist.sourceforge.net/

Only english words: http://www.math.sjsu.edu/~foster/dictionary.txt

Is Tomcat running?

Here are my two cents.

I have multiple tomcat instances running on different ports for my cluster setup. I use the following command to check each processes running on different ports.

/sbin/fuser 8080/tcp

Replace the port number as per your need.

And to kill the process use -k in the above command.

  • This is much faster than the ps -ef way or any other commands where you call a command and call another grep on top of it.
  • Works well with multiple installations of tomcat ,Or any other server that uses a port as a matter of fact running on the same server.

The equivalent command on BSD operating systems is fstat

Python, how to read bytes from file and save it?

Use the open function to open the file. The open function returns a file object, which you can use the read and write to files:

file_input = open('input.txt') #opens a file in reading mode
file_output = open('output.txt') #opens a file in writing mode

data = file_input.read(1024) #read 1024 bytes from the input file
file_output.write(data) #write the data to the output file

A simple scenario using wait() and notify() in java

Example for wait() and notifyall() in Threading.

A synchronized static array list is used as resource and wait() method is called if the array list is empty. notify() method is invoked once a element is added for the array list.

public class PrinterResource extends Thread{

//resource
public static List<String> arrayList = new ArrayList<String>();

public void addElement(String a){
    //System.out.println("Add element method "+this.getName());
    synchronized (arrayList) {
        arrayList.add(a);
        arrayList.notifyAll();
    }
}

public void removeElement(){
    //System.out.println("Remove element method  "+this.getName());
    synchronized (arrayList) {
        if(arrayList.size() == 0){
            try {
                arrayList.wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }else{
            arrayList.remove(0);
        }
    }
}

public void run(){
    System.out.println("Thread name -- "+this.getName());
    if(!this.getName().equalsIgnoreCase("p4")){
        this.removeElement();
    }
    this.addElement("threads");

}

public static void main(String[] args) {
    PrinterResource p1 = new PrinterResource();
    p1.setName("p1");
    p1.start();

    PrinterResource p2 = new PrinterResource();
    p2.setName("p2");
    p2.start();


    PrinterResource p3 = new PrinterResource();
    p3.setName("p3");
    p3.start();


    PrinterResource p4 = new PrinterResource();
    p4.setName("p4");
    p4.start();     

    try{
        p1.join();
        p2.join();
        p3.join();
        p4.join();
    }catch(InterruptedException e){
        e.printStackTrace();
    }
    System.out.println("Final size of arraylist  "+arrayList.size());
   }
}

How to set the context path of a web application in Tomcat 7.0

In Tomcat 9.0, I only have to change the following in the server.xml

<Context docBase="web" path="/web" reloadable="true" source="org.eclipse.jst.jee.server:web"/>

to

<Context docBase="web" path="" reloadable="true" source="org.eclipse.jst.jee.server:web"/>

Test credit card numbers for use with PayPal sandbox

It turns out, after messing around with all of the settings in the test business account, that one (or more) of the fraud related settings in the payment receiving preferences / security settings screens were causing the test payments to fail (without any useful error).

Show image using file_get_contents

you can do like this :

<?php
    $file = 'your_images.jpg';

    header('Content-Type: image/jpeg');
    header('Content-Length: ' . filesize($file));
    echo file_get_contents($file);
?>

Convert DataSet to List

Use the code below:

using Newtonsoft.Json;
string JSONString = string.Empty;
JSONString = JsonConvert.SerializeObject(ds.Tables[0]);

How to round the corners of a button

You may want to check out my library called DCKit. It's written on the latest version of Swift.

You'd be able to make a rounded corner button/text field from the Interface builder directly:

DCKit: rounded button

It also has many other cool features, such as text fields with validation, controls with borders, dashed borders, circle and hairline views etc.

How to represent a DateTime in Excel

You can set date time values to a cell in XlsIO using one of these options

sheet.Range["A1"].Value2 = DateTime.Now;
sheet.Range["A1"].NumberFormat = "dd/mm/yyyy";

sheet.Range["A2"].DateTime = DateTime.Now;
sheet.Range["A2"].NumberFormat = "[$-409]d-mmm-yy;@";

You can find more information here.

How to add Tomcat Server in eclipse

There are different eclipse plugins available to manage Tomcat server and create war file.

For example you can use tomcatPlugin. It permits to start/stop and build the war simply. You can read this tutorial.

How can I convert tabs to spaces in every file of a directory?

Converting tabs to space in just in ".lua" files [tabs -> 2 spaces]

find . -iname "*.lua" -exec sed -i "s#\t#  #g" '{}' \;

How do you get centered content using Twitter Bootstrap?

My preferred method for centering blocks of information while maintaining responsiveness (mobile compatibility) is to place two empty span1 divs before and after the content you wish to center.

<div class="row-fluid">

    <div class="span1">
    </div>

        <div class="span10">
          <div class="hero-unit">
            <h1>Reading Resources</h1>
            <p>Read here...</p>
          </div>
        </div><!--/span-->

    <div class="span1">
    </div>

</div><!--/row-->

HTTP redirect: 301 (permanent) vs. 302 (temporary)

301 redirects are cached indefinitely (at least by some browsers).

This means, if you set up a 301, visit that page, you not only get redirected, but that redirection gets cached.

When you visit that page again, your Browser* doesn't even bother to request that URL, it just goes to the cached redirection target.

The only way to undo a 301 for a visitor with that redirection in Cache, is re-redirecting back to the original URL**. In that case, the Browser will notice the loop, and finally really request the entered URL.

Obviously, that's not an option if you decided to 301 to facebook or any other resource you're not fully under control.

Unfortunately, many Hosting Providers offer a feature in their Admin Interface simply called "Redirection", which does a 301 redirect. If you're using this to temporarily redirect your domain to facebook as a coming soon page, you're basically screwed.

*at least Chrome and Firefox, according to How long do browsers cache HTTP 301s?. Just tried it with Chrome 45. Edit: Safari 7.0.6 on Mac also caches, a browser restart didn't help (Link says that on Safari 5 on Windows it does help.)

**I tried javascript window.location = '', because it would be the solution which could be applied in most cases - it doesn't work. It results in an undetected infinite Loop. However, php header('Location: new.url') does break the loop

Bottom Line: only use 301s if you're absolutely sure you're never going to use that URL again. Usually never on the root dir (example.com/)

Adding an image to a PDF using iTextSharp and scale it properly

Personally, I use something close from fubo's solution and it works well:

image.ScaleToFit(document.PageSize);
image.SetAbsolutePosition(0,0);

How to use the PI constant in C++

Values like M_PI, M_PI_2, M_PI_4, etc are not standard C++ so a constexpr seems a better solution. Different const expressions can be formulated that calculate the same pi and it concerns me whether they (all) provide me the full accuracy. The C++ standard does not explicitly mention how to calculate pi. Therefore, I tend to fall back to defining pi manually. I would like to share the solution below which supports all kind of fractions of pi in full accuracy.

#include <ratio>
#include <iostream>

template<typename RATIO>
constexpr double dpipart()
{
    long double const pi = 3.14159265358979323846264338327950288419716939937510582097494459230781640628620899863;
    return static_cast<double>(pi * RATIO::num / RATIO::den);
}

int main()
{
    std::cout << dpipart<std::ratio<-1, 6>>() << std::endl;
}

How do I test if a string is empty in Objective-C?

Very useful post, to add NSDictionary support as well one small change

static inline BOOL isEmpty(id thing) {
    return thing == nil
    || [thing isKindOfClass:[NSNull class]]
    || ([thing respondsToSelector:@selector(length)]
        && ![thing respondsToSelector:@selector(count)]
        && [(NSData *)thing length] == 0)
    || ([thing respondsToSelector:@selector(count)]
        && [thing count] == 0);
}

How to get selected path and name of the file opened with file dialog?

Try this

Sub Demo()
    Dim lngCount As Long
    Dim cl As Range

    Set cl = ActiveCell
    ' Open the file dialog
    With Application.FileDialog(msoFileDialogOpen)
        .AllowMultiSelect = True
        .Show
        ' Display paths of each file selected
        For lngCount = 1 To .SelectedItems.Count
            ' Add Hyperlinks
            cl.Worksheet.Hyperlinks.Add _
                Anchor:=cl, Address:=.SelectedItems(lngCount), _
                TextToDisplay:=.SelectedItems(lngCount)
            ' Add file name
            'cl.Offset(0, 1) = _
            '    Mid(.SelectedItems(lngCount), InStrRev(.SelectedItems(lngCount), "\") + 1)
            ' Add file as formula
            cl.Offset(0, 1).FormulaR1C1 = _
                 "=TRIM(RIGHT(SUBSTITUTE(RC[-1],""\"",REPT("" "",99)),99))"


            Set cl = cl.Offset(1, 0)
        Next lngCount
    End With
End Sub

Viewing full version tree in git

There is a very good answer to the same question.
Adding following lines to "~/.gitconfig":

[alias]
lg1 = log --graph --abbrev-commit --decorate --date=relative --format=format:'%C(bold blue)%h%C(reset) - %C(bold green)(%ar)%C(reset) %C(white)%s%C(reset) %C(dim white)- %an%C(reset)%C(bold yellow)%d%C(reset)' --all
lg2 = log --graph --abbrev-commit --decorate --format=format:'%C(bold blue)%h%C(reset) - %C(bold cyan)%aD%C(reset) %C(bold green)(%ar)%C(reset)%C(bold yellow)%d%C(reset)%n''          %C(white)%s%C(reset) %C(dim white)- %an%C(reset)' --all
lg = !"git lg1"

CodeIgniter: Create new helper?

Some code that allows you to use CI instance inside the helper:

function yourHelperFunction(){
    $ci=& get_instance();
    $ci->load->database(); 

    $sql = "select * from table"; 
    $query = $ci->db->query($sql);
    $row = $query->result();
}

What's an Aggregate Root?

Aggregate is where you protect your invariants and force consistency by limiting its access thought aggregate root. Do not forget, aggregate should design upon your project business rules and invariants, not database relationship. you should not inject any repository and no queries are not allowed.

Why is there no multiple inheritance in Java, but implementing multiple interfaces is allowed?

Take for example the case where Class A has a getSomething method and class B has a getSomething method and class C extends A and B. What would happen if someone called C.getSomething? There is no way to determine which method to call.

Interfaces basically just specify what methods a implementing class needs to contain. A class that implements multiple interfaces just means that class has to implement the methods from all those interfaces. Whci would not lead to any issues as described above.

Formatting Decimal places in R

You can format a number, say x, up to decimal places as you wish. Here x is a number with many decimal places. Suppose we wish to show up to 8 decimal places of this number:

x = 1111111234.6547389758965789345
y = formatC(x, digits = 8, format = "f")
# [1] "1111111234.65473890"

Here format="f" gives floating numbers in the usual decimal places say, xxx.xxx, and digits specifies the number of digits. By contrast, if you wanted to get an integer to display you would use format="d" (much like sprintf).

Make content horizontally scroll inside a div

It may be something like this in HTML:

<div class="container-outer">
   <div class="container-inner">
      <!-- Your images over here -->
   </div>
</div>

With this stylesheet:

.container-outer { overflow: scroll; width: 500px; height: 210px; }
.container-inner { width: 10000px; }

You can even create an intelligent script to calculate the inner container width, like this one:

$(document).ready(function() {
   var container_width = SINGLE_IMAGE_WIDTH * $(".container-inner a").length;
   $(".container-inner").css("width", container_width);
});

How to create a string with format?

Success to try it:

 var letters:NSString = "abcdefghijkl"
        var strRendom = NSMutableString.stringWithCapacity(strlength)
        for var i=0; i<strlength; i++ {
            let rndString = Int(arc4random() % 12)
            //let strlk = NSString(format: <#NSString#>, <#CVarArg[]#>)
            let strlk = NSString(format: "%c", letters.characterAtIndex(rndString))
            strRendom.appendString(String(strlk))
        }

Export table from database to csv file

And when you want all tables for some reason ?

You can generate these commands in SSMS:

SELECT 
CONCAT('sqlcmd -S ',
'Your(local?)SERVERhere'
,' -d',
'YourDB'
,' -E -s, -W -Q "SELECT * FROM ',
TABLE_NAME,
'" >',
TABLE_NAME,
'.csv') FROM INFORMATION_SCHEMA.TABLES

And get again rows like this

sqlcmd -S ... -d... -E -s, -W -Q "SELECT * FROM table1" >table1.csv
sqlcmd -S ... -d... -E -s, -W -Q "SELECT * FROM table2" >table2.csv
...

There is also option to use better TAB as delimiter, but it would need a strange Unicode character - using Alt+9 in CMD, it came like this ? (Unicode CB25), but works only by copy/paste to command line not in batch.

use a javascript array to fill up a drop down select box

This is a part from a REST-Service I´ve written recently.

var select = $("#productSelect")
for (var prop in data) {
    var option = document.createElement('option');
    option.innerHTML = data[prop].ProduktName
    option.value = data[prop].ProduktName;
    select.append(option)
}

The reason why im posting this is because appendChild() wasn´t working in my case so I decided to put up another possibility that works aswell.

Uses of Action delegate in C#

I use it when I am dealing with Illegal Cross Thread Calls For example:

DataRow dr = GetRow();
this.Invoke(new Action(() => {
   txtFname.Text = dr["Fname"].ToString();
   txtLname.Text = dr["Lname"].ToString(); 
   txtMI.Text = dr["MI"].ToString();
   txtSSN.Text = dr["SSN"].ToString();
   txtSSN.ButtonsRight["OpenDialog"].Visible = true;
   txtSSN.ButtonsRight["ListSSN"].Visible = true;
   txtSSN.Focus();
}));

I must give credit to Reed Copsey SO user 65358 for the solution. My full question with answers is SO Question 2587930

Resolving IP Address from hostname with PowerShell

Working one liner if you want a single result from the collection:

$ipAddy = [System.Net.Dns]::GetHostAddresses("yahoo.com")[0].IPAddressToString; 

hth

syntax error near unexpected token `('

Since you've got both the shell that you're typing into and the shell that sudo -s runs, you need to quote or escape twice. (EDITED fixed quoting)

sudo -su db2inst1 '/opt/ibm/db2/V9.7/bin/db2 force application \(1995\)'

or

sudo -su db2inst1 /opt/ibm/db2/V9.7/bin/db2 force application \\\(1995\\\)

Out of curiosity, why do you need -s? Can't you just do this:

sudo -u db2inst1 /opt/ibm/db2/V9.7/bin/db2 force application \(1995\)

Can't ignore UserInterfaceState.xcuserstate

Had a friend show me this amazing site https://www.gitignore.io/. Enter the IDE of your choice or other options and it will automatically generate a gitignore file consisting of useful ignores, one of which is the xcuserstate. You can preview the gitignore file before downloading.

Angular.js and HTML5 date input value -- how to get Firefox to show a readable date value in a date input?

If using Angular Material Design, you can use the datepicker component there and this will work in Firefox, IE etc.

https://material.angularjs.org/latest/demo/datepicker

Fair warning though - personal experience is that there are problems with this, and seemingly it is being re-worked at present. See here:

https://github.com/angular/material/issues/4856

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

if the full message is:

kernel panic - not syncing: Attempted to kill inint !
PId: 1, comm: init not tainted 2.6.32.-279-5.2.e16.x86_64 #1

then you should have disabled selinux and after that you have rebooted the system.

The easier way is to use a live OS and re-enable it

vim /etc/selinux/config
    ...
    SELINUX=enforcing
    ...

Second choice is to disable selinux in the kernel arguments by adding selinux=0

vim /boot/grub/grub.conf
    ...
    kernel /boot/vmlinuz-2.4.20-selinux-2003040709 ro root=/dev/hda1 nousb selinux=0
    ...

source kernel panic - not syncing: Attempted to kill inint !

Getting a link to go to a specific section on another page

You can simply use

 <a href="directry/filename.html#section5" >click me</a>

to link to a section/id of another page by

How can I align the columns of tables in Bash?

Below code has been tested and does exactly what is requested in the original question.

Parameters: %30s Column of 30 char and text right align. %10d integer notation, %10s will also work. Added clarification included on code comments.

stringarray[0]="a very long string.........."
# 28Char (max length for this column)
numberarray[0]=1122324333
# 10digits (max length for this column)
anotherfield[0]="anotherfield"
# 12Char (max length for this column)
stringarray[1]="a smaller string....."
numberarray[1]=123124343
anotherfield[1]="anotherfield"

printf "%30s %10d %13s" "${stringarray[0]}" ${numberarray[0]} "${anotherfield[0]}"
printf "\n"
printf "%30s %10d %13s" "${stringarray[1]}" ${numberarray[1]} "${anotherfield[1]}"
# a var string with spaces has to be quoted
printf "\n Next line will fail \n"      
printf "%30s %10d %13s" ${stringarray[0]} ${numberarray[0]} "${anotherfield[0]}"



  a very long string.......... 1122324333  anotherfield
         a smaller string.....  123124343  anotherfield

Android Studio: Unable to start the daemon process

I think it's wrong JAVA_HOME make this error. when i get error i try all the way,but it don't work for me. i try delete c:.gradle and Compiler Android studio but it's still don't work. i Re-install the system it work, when update system i get the error again. I try Compiler JAVA_HOME user environment and system environment: enter image description here

when i use cmd input java:

enter image description here

when cmd.exe show the masage it mean it's work, try to runing Android Studio, it will fix the error. enter image description here

Insert/Update Many to Many Entity Framework . How do I do it?

Try this one for Updating:

[HttpPost]
public ActionResult Edit(Models.MathClass mathClassModel)
{
    //get current entry from db (db is context)
    var item = db.Entry<Models.MathClass>(mathClassModel);

    //change item state to modified
    item.State = System.Data.Entity.EntityState.Modified;

    //load existing items for ManyToMany collection
    item.Collection(i => i.Students).Load();

    //clear Student items          
    mathClassModel.Students.Clear();

    //add Toner items
    foreach (var studentId in mathClassModel.SelectedStudents)
    {
        var student = db.Student.Find(int.Parse(studentId));
        mathClassModel.Students.Add(student);
    }                

    if (ModelState.IsValid)
    {
       db.SaveChanges();
       return RedirectToAction("Index");
    }

    return View(mathClassModel);
}

SyntaxError: cannot assign to operator

in python only work

a=4
b=3

i=a+b

which i is new operator

TERM environment variable not set

Using a terminal command i.e. "clear", in a script called from cron (no terminal) will trigger this error message. In your particular script, the smbmount command expects a terminal in which case the work-arounds above are appropriate.

Connection Java-MySql : Public Key Retrieval is not allowed

For DBeaver users:

  1. Right click your connection, choose "Edit Connection"

  2. On the "Connection settings" screen (main screen) click on "Edit Driver Settings"

  3. Click on "Connection properties"

  4. Right click the "user properties" area and choose "Add new property"

  5. Add two properties: "useSSL" and "allowPublicKeyRetrieval"

  6. Set their values to "false" and "true" by double clicking on the "value" column

Android: How to get a custom View's height and width?

Don't try to get them inside its constructor. Try Call them in onDraw() method.

What is the difference between a web API and a web service?

In the context of ASP.Net a Web API is a Controller whose base class is ApiController and does not use Views. A Web Service is a class derived from WebService and has automatic WSDL generation. By default it is a SOAP api, but you can also use JSON by adding a ScriptServiceAttribute.

Android Studio: Plugin with id 'android-library' not found

Add the below to the build.gradle project module:

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.3'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Convert JSON format to CSV format for MS Excel

I created a JsFiddle here based on the answer given by Zachary. It provides a more accessible user interface and also escapes double quotes within strings properly.

How to sort 2 dimensional array by column value?

Nothing special, just saving the cost it takes to return a value at certain index from an array.

function sortByCol(arr, colIndex){
    arr.sort(sortFunction)
    function sortFunction(a, b) {
        a = a[colIndex]
        b = b[colIndex]
        return (a === b) ? 0 : (a < b) ? -1 : 1
    }
}
// Usage
var a = [[12, 'AAA'], [58, 'BBB'], [28, 'CCC'],[18, 'DDD']]
sortByCol(a, 0)
console.log(JSON.stringify(a))
// "[[12,"AAA"],[18,"DDD"],[28,"CCC"],[58,"BBB"]]"

Error: expected type-specifier before 'ClassName'

First of all, let's try to make your code a little simpler:

// No need to create a circle unless it is clearly necessary to
// demonstrate the problem

// Your Rect2f defines a default constructor, so let's use it for simplicity.
shared_ptr<Shape> rect(new Rect2f());

Okay, so now we see that the parentheses are clearly balanced. What else could it be? Let's check the following code snippet's error:

int main() {
    delete new T();
}

This may seem like weird usage, and it is, but I really hate memory leaks. However, the output does seem useful:

In function 'int main()':
Line 2: error: expected type-specifier before 'T'

Aha! Now we're just left with the error about the parentheses. I can't find what causes that; however, I think you are forgetting to include the file that defines Rect2f.

How do I save and restore multiple variables in python?

The following approach seems simple and can be used with variables of different size:

import hickle as hkl
# write variables to filename [a,b,c can be of any size]
hkl.dump([a,b,c], filename)

# load variables from filename
a,b,c = hkl.load(filename)

How to uninstall pip on OSX?

Since pip is a package, pip uninstall pip Will do it.
EDIT: If that does not work, try sudo -H pip uninstall pip.

Checking if a double (or float) is NaN in C++

There is also a header-only library present in Boost that have neat tools to deal with floating point datatypes

#include <boost/math/special_functions/fpclassify.hpp>

You get the following functions:

template <class T> bool isfinite(T z);
template <class T> bool isinf(T t);
template <class T> bool isnan(T t);
template <class T> bool isnormal(T t);

If you have time then have a look at whole Math toolkit from Boost, it has many useful tools and is growing quickly.

Also when dealing with floating and non-floating points it might be a good idea to look at the Numeric Conversions.

How to remove item from list in C#?

You don't specify what kind of list, but the generic List can use either the RemoveAt(index) method, or the Remove(obj) method:

// Remove(obj)
var item = resultList.Single(x => x.Id == 2);
resultList.Remove(item);

// RemoveAt(index)
resultList.RemoveAt(1);

How to program a delay in Swift 3

After a lot of research, I finally figured this one out.

DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) { // Change `2.0` to the desired number of seconds.
   // Code you want to be delayed
}

This creates the desired "wait" effect in Swift 3 and Swift 4.

Inspired by a part of this answer.

Test for array of string type in TypeScript

there is a little problem here because the

if (typeof item !== 'string') {
    return false
}

will not stop the foreach. So the function will return true even if the array does contain none string values.

This seems to wok for me:

function isStringArray(value: any): value is number[] {
  if (Object.prototype.toString.call(value) === '[object Array]') {
     if (value.length < 1) {
       return false;
     } else {
       return value.every((d: any) => typeof d === 'string');
     }
  }
  return false;
}

Greetings, Hans

Jboss server error : Failed to start service jboss.deployment.unit."jbpm-console.war"

try staring jboss with ./standalone.sh -c standalone-full.xml or any other alternative that allows you to start with the full profile

Fetching distinct values on a column using Spark DataFrame

This solution demonstrates how to transform data with Spark native functions which are better than UDFs. It also demonstrates how dropDuplicates which is more suitable than distinct for certain queries.

Suppose you have this DataFrame:

+-------+-------------+
|country|    continent|
+-------+-------------+
|  china|         asia|
| brazil|south america|
| france|       europe|
|  china|         asia|
+-------+-------------+

Here's how to take all the distinct countries and run a transformation:

df
  .select("country")
  .distinct
  .withColumn("country", concat(col("country"), lit(" is fun!")))
  .show()
+--------------+
|       country|
+--------------+
|brazil is fun!|
|france is fun!|
| china is fun!|
+--------------+

You can use dropDuplicates instead of distinct if you don't want to lose the continent information:

df
  .dropDuplicates("country")
  .withColumn("description", concat(col("country"), lit(" is a country in "), col("continent")))
  .show(false)
+-------+-------------+------------------------------------+
|country|continent    |description                         |
+-------+-------------+------------------------------------+
|brazil |south america|brazil is a country in south america|
|france |europe       |france is a country in europe       |
|china  |asia         |china is a country in asia          |
+-------+-------------+------------------------------------+

See here for more information about filtering DataFrames and here for more information on dropping duplicates.

Ultimately, you'll want to wrap your transformation logic in custom transformations that can be chained with the Dataset#transform method.

Eliminate space before \begin{itemize}

I'm very happy with the paralist package. Besides adding the option to eliminate the space it also adds other nice things like compact versions of the itemize, enumerate and describe environments.

TypeError: 'NoneType' object is not iterable in Python

Explanation of error: 'NoneType' object is not iterable

In python2, NoneType is the type of None. In Python3 NoneType is the class of None, for example:

>>> print(type(None))     #Python2
<type 'NoneType'>         #In Python2 the type of None is the 'NoneType' type.

>>> print(type(None))     #Python3
<class 'NoneType'>        #In Python3, the type of None is the 'NoneType' class.

Iterating over a variable that has value None fails:

for a in None:
    print("k")     #TypeError: 'NoneType' object is not iterable

Python methods return NoneType if they don't return a value:

def foo():
    print("k")
a, b = foo()      #TypeError: 'NoneType' object is not iterable

You need to check your looping constructs for NoneType like this:

a = None 
print(a is None)              #prints True
print(a is not None)          #prints False
print(a == None)              #prints True
print(a != None)              #prints False
print(isinstance(a, object))  #prints True
print(isinstance(a, str))     #prints False

Guido says only use is to check for None because is is more robust to identity checking. Don't use equality operations because those can spit bubble-up implementationitis of their own. Python's Coding Style Guidelines - PEP-008

NoneTypes are Sneaky, and can sneak in from lambdas:

import sys
b = lambda x : sys.stdout.write("k") 
for a in b(10): 
    pass            #TypeError: 'NoneType' object is not iterable 

NoneType is not a valid keyword:

a = NoneType     #NameError: name 'NoneType' is not defined

Concatenation of None and a string:

bar = "something"
foo = None
print foo + bar    #TypeError: cannot concatenate 'str' and 'NoneType' objects

What's going on here?

Python's interpreter converted your code to pyc bytecode. The Python virtual machine processed the bytecode, it encountered a looping construct which said iterate over a variable containing None. The operation was performed by invoking the __iter__ method on the None.

None has no __iter__ method defined, so Python's virtual machine tells you what it sees: that NoneType has no __iter__ method.

This is why Python's duck-typing ideology is considered bad. The programmer does something completely reasonable with a variable and at runtime it gets contaminated by None, the python virtual machine attempts to soldier on, and pukes up a bunch of unrelated nonsense all over the carpet.

Java or C++ doesn't have these problems because such a program wouldn't be allowed to compile since you haven't defined what to do when None occurs. Python gives the programmer lots of rope to hang himself by allowing you to do lots of things that should cannot be expected to work under exceptional circumstances. Python is a yes-man, saying yes-sir when it out to be stopping you from harming yourself, like Java and C++ does.

"Auth Failed" error with EGit and GitHub

For you who, like me, already did setup you ssh-keys but still get the errors:

Make sure you did setup a push remote. It worked for me when I got both the Cannot get remote repository refs-problems ("... Passphrase for..." and "Auth fail" in the "Push..." dialog).

Provided that you already:

  1. Setup your SSH keys with Github (Window > Preferences > General > Network Connections > SSH2)

  2. Setup your local repository (you can follow this guide for that)

  3. Created a Github repository (same guide)

... here's how you do it:

  • Go to the Git Repositories view (Window > Show View > Other > Git Repositories)
  • Expand your Repository and right click Remotes --> "Create Remote"
  • "Remote Name": origin, "Configure push": checked --> click "OK"
  • Click the "Change..." button
  • Paste your git URI and select protocol ssh --> click "Finish"
  • Now, click "Save and Push" and NOW you should get a password prompt --> enter the public key passphrase here (provided that you DID (and you should) setup a passphrase to your public key) --> click "OK"
  • Now you should get a confirmation window saying "Pushed to YourRepository - origin" --> click "OK"
  • Push to upstream, but this time use "Configured remote repository" as your Destination Git repository
  • Go get yourself a well earned cup of coffee!

MySQL compare now() (only date, not time) with a datetime field

Use DATE(NOW()) to compare dates

DATE(NOW()) will give you the date part of current date and DATE(duedate) will give you the date part of the due date. then you can easily compare the dates

So you can compare it like

DATE(NOW()) = DATE(duedate)

OR

DATE(duedate) = CURDATE() 

See here

DBCC CHECKIDENT Sets Identity to 0

Change statement to

  DBCC CHECKIDENT('TableName', RESEED, 1)

This will start from 2 (or 1 when you recreate table), but it will never be 0.

Where can I download mysql jdbc jar from?

Go to http://dev.mysql.com/downloads/connector/j and with in the dropdown select "Platform Independent" then it will show you the options to download tar.gz file or zip file.

Download zip file and extract it, with in that you will find mysql-connector-XXX.jar file

If you are using maven then you can add the dependency from the link http://mvnrepository.com/artifact/mysql/mysql-connector-java

Select the version you want to use and add the dependency in your pom.xml file

SQL: How to get the id of values I just INSERTed?

Ms SQL Server: this is good solution even if you inserting more rows:

 Declare @tblInsertedId table (Id int not null)

 INSERT INTO Test ([Title], [Text])
 OUTPUT inserted.Id INTO @tblInsertedId (Id)
 SELECT [Title], [Text] FROM AnotherTable

 select Id from @tblInsertedId 

Using Linq to group a list of objects into a new grouped list of list of objects

For type

public class KeyValue
{
    public string KeyCol { get; set; }
    public string ValueCol { get; set; }
}

collection

var wordList = new Model.DTO.KeyValue[] {
    new Model.DTO.KeyValue {KeyCol="key1", ValueCol="value1" },
    new Model.DTO.KeyValue {KeyCol="key2", ValueCol="value1" },
    new Model.DTO.KeyValue {KeyCol="key3", ValueCol="value2" },
    new Model.DTO.KeyValue {KeyCol="key4", ValueCol="value2" },
    new Model.DTO.KeyValue {KeyCol="key5", ValueCol="value3" },
    new Model.DTO.KeyValue {KeyCol="key6", ValueCol="value4" }
};

our linq query look like below

var query =from m in wordList group m.KeyCol by m.ValueCol into g
select new { Name = g.Key, KeyCols = g.ToList() };

or for array instead of list like below

var query =from m in wordList group m.KeyCol by m.ValueCol into g
select new { Name = g.Key, KeyCols = g.ToList().ToArray<string>() };

Split comma separated column data into additional columns

split_part() does what you want in one step:

SELECT split_part(col, ',', 1) AS col1
     , split_part(col, ',', 2) AS col2
     , split_part(col, ',', 3) AS col3
     , split_part(col, ',', 4) AS col4
FROM   tbl;

Add as many lines as you have items in col (the possible maximum). Columns exceeding data items will be empty strings ('').

Command copy exited with code 4 when building - Visual Studio restart solves it

I faced the same issue in case of XCOPY after build is done. In my case the issue was happening because of READ-ONLY permissions set on folders.

I added attrib -R command before XCOPY and it solved the issue.

Hope it helps someone!

Is there an alternative to string.Replace that is case-insensitive?

From MSDN
$0 - "Substitutes the last substring matched by group number number (decimal)."

In .NET Regular expressions group 0 is always the entire match. For a literal $ you need to

string value = Regex.Replace("%PolicyAmount%", "%PolicyAmount%", @"$$0", RegexOptions.IgnoreCase);

SyntaxError of Non-ASCII character

You should define source code encoding, add this to the top of your script:

# -*- coding: utf-8 -*-

The reason why it works differently in console and in the IDE is, likely, because of different default encodings set. You can check it by running:

import sys
print sys.getdefaultencoding()

Also see:

global variable for all controller and views

using middlwares

1- create middlware with any name

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\View;

class GlobalData
{
    public function handle($request, Closure $next)
    {
        // edit this section and share what do you want
        $site_settings = Setting::all();
        View::share('site_settings', $site_settings);
        return $next($request);
    }
}

2- register your middleware in Kernal.php

protected $routeMiddleware = [
 .
 ...
 'globaldata' => GlobalData::class,
 ]

3-now group your routes with globaldata middleware

Route::group(['middleware' => ['globaldata']], function () {
//  add routes that need to site_settings
}

Is there a way to access the "previous row" value in a SELECT statement?

select t2.col from (
select col,MAX(ID) id from 
(
select ROW_NUMBER() over(PARTITION by col order by col) id ,col from testtab t1) as t1
group by col) as t2

MacOSX homebrew mysql root password

  1. go to apple icon --> system preferences
  2. open Mysql
  3. in instances you will see "initialize Database"
  4. click on that
  5. you will be asked to set password for root --> set a strong password there
  6. use that password to login in mysql from next time

Hope this helps.

How to make a <div> appear in front of regular text/tables

You can use the stacking index of the div to make it appear on top of anything else. Make it a larger value that other elements and it well be on top of others.

use z-index property. See Specifying the stack level: the 'z-index' property and

Elaborate description of Stacking Contexts

Something like

#divOnTop { z-index: 1000; }

<div id="divOnTop">I am on top</div>

What you have to look out for will be IE6. In IE 6 some elements like <select> will be placed on top of an element with z-index value higher than the <select>. You can have a workaround for this by placing an <iframe> behind the div.

See this Internet Explorer z-index bug?

PHP header() redirect with POST variables

If you don't want to use sessions, the only thing you can do is POST to the same page. Which IMO is the best solution anyway.

// form.php

<?php

    if (!empty($_POST['submit'])) {
        // validate

        if ($allGood) {
            // put data into database or whatever needs to be done

            header('Location: nextpage.php');
            exit;
        }
    }

?>

<form action="form.php">
    <input name="foo" value="<?php if (!empty($_POST['foo'])) echo htmlentities($_POST['foo']); ?>">
    ...
</form>

This can be made more elegant, but you get the idea...

Image vs zImage vs uImage

What is the difference between them?

Image: the generic Linux kernel binary image file.

zImage: a compressed version of the Linux kernel image that is self-extracting.

uImage: an image file that has a U-Boot wrapper (installed by the mkimage utility) that includes the OS type and loader information.
A very common practice (e.g. the typical Linux kernel Makefile) is to use a zImage file. Since a zImage file is self-extracting (i.e. needs no external decompressors), the wrapper would indicate that this kernel is "not compressed" even though it actually is.


Note that the author/maintainer of U-Boot considers the (widespread) use of using a zImage inside a uImage questionable:

Actually it's pretty stupid to use a zImage inside an uImage. It is much better to use normal (uncompressed) kernel image, compress it using just gzip, and use this as poayload for mkimage. This way U-Boot does the uncompresiong instead of including yet another uncompressor with each kernel image.

(quoted from https://lists.yoctoproject.org/pipermail/yocto/2013-October/016778.html)


Which type of kernel image do I have to use?

You could choose whatever you want to program for.
For economy of storage, you should probably chose a compressed image over the uncompressed one.
Beware that executing the kernel (presumably the Linux kernel) involves more than just loading the kernel image into memory. Depending on the architecture (e.g. ARM) and the Linux kernel version (e.g. with or without DTB), there are registers and memory buffers that may have to be prepared for the kernel. In one instance there was also hardware initialization that U-Boot performed that had to be replicated.

ADDENDUM

I know that u-boot needs a kernel in uImage format.

That is accurate for all versions of U-Boot which only have the bootm command.
But more recent versions of U-Boot could also have the bootz command that can boot a zImage.

This view is not constrained vertically. At runtime it will jump to the left unless you add a vertical constraint

for example I have this

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"

use RelativeLayout layout like this

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

Can I escape html special chars in javascript?

You can encode every character in your string:

function encode(e){return e.replace(/[^]/g,function(e){return"&#"+e.charCodeAt(0)+";"})}

Or just target the main characters to worry about (&, inebreaks, <, >, " and ') like:

_x000D_
_x000D_
function encode(r){_x000D_
return r.replace(/[\x26\x0A\<>'"]/g,function(r){return"&#"+r.charCodeAt(0)+";"})_x000D_
}_x000D_
_x000D_
test.value=encode('How to encode\nonly html tags &<>\'" nice & fast!');_x000D_
_x000D_
/*************_x000D_
* \x26 is &ampersand (it has to be first),_x000D_
* \x0A is newline,_x000D_
*************/
_x000D_
<textarea id=test rows="9" cols="55">&#119;&#119;&#119;&#46;&#87;&#72;&#65;&#75;&#46;&#99;&#111;&#109;</textarea>
_x000D_
_x000D_
_x000D_

C# DateTime.ParseExact

It's probably the same problem with cultures as presented in this related SO-thread: Why can't DateTime.ParseExact() parse "9/1/2009" using "M/d/yyyy"

You already specified the culture, so try escaping the slashes.

Modify table: How to change 'Allow Nulls' attribute from not null to allow null

For MySQL, MariaDB

ALTER TABLE [table name] MODIFY COLUMN [column name] [data type] NULL

Use MODIFY COLUMN instead of ALTER COLUMN.

How to pass parameters in GET requests with jQuery

The data property allows you to send in a string. On your server side code, accept it as a string argument name "myVar" and then you can parse it out.

$.ajax({
    url: "ajax.aspx",
    data: [myVar = {id: 4, email: 'emailaddress', myArray: [1, 2, 3]}];
    success: function(response) {
    //Do Something
    },
    error: function(xhr) {
    //Do Something to handle error
    }
});

Reload activity in Android

in some cases it's the best practice in other it's not a good idea it's context driven if you chose to do so using the following is the best way to pass from an activity to her sons :

    Intent i = new Intent(myCurrentActivityName.this,activityIWishToRun.class);    
    startActivityForResult(i, GlobalDataStore.STATIC_INTEGER_VALUE);

the thing is whenever you finish() from activityIWishToRun you return to your a living activity

How to use group by with union in t-sql

with UnionTable as  
(
    SELECT a.id, a.time FROM dbo.a
    UNION
    SELECT b.id, b.time FROM dbo.b
) SELECT id FROM UnionTable GROUP BY id

What is code coverage and how do YOU measure it?

Code coverage basically tells you how much of your code is covered under tests. For example, if you have 90% code coverage, it means 10% of the code is not covered under tests.

I know you might be thinking that if 90% of the code is covered, it's good enough, but you have to look from a different angle. What is stopping you from getting 100% code coverage?

A good example will be this:

if(customer.IsOldCustomer()) 
{
}
else 
{
}

Now, in the code above, there are two paths/branches. If you are always hitting the "YES" branch, you are not covering the "else" part and it will be shown in the Code Coverage results. This is good because now you know that what is not covered and you can write a test to cover the "else" part. If there was no code coverage, you are just sitting on a time bomb, waiting to explode.

NCover is a good tool to measure code coverage.

How to iterate through table in Lua?

If you want to refer to a nested table by multiple keys you can just assign them to separate keys. The tables are not duplicated, and still reference the same values.

arr = {}
apples = {'a', "red", 5 }
arr.apples = apples
arr[1] = apples

This code block lets you iterate through all the key-value pairs in a table (http://lua-users.org/wiki/TablesTutorial):

for k,v in pairs(t) do
 print(k,v)
end

How to initialize List<String> object in Java?

Just in case, any one still lingering around this question. Because, i see one or two new users again asking the same question and everyone telling then , No you can't do that, Dear Prudence, Apart from all the answers given here, I would like to provide additional Information - Yes you can actually do, List list = new List(); But at the cost of writing implementations of all the methods of Interfaces. The notion is not simply List list = new List(); but

List<Integer> list = new List<Integer>(){

        @Override
        public int size() {
            // TODO Auto-generated method stub
            return 0;
        }

        @Override
        public boolean isEmpty() {
            // TODO Auto-generated method stub
            return false;
        }

        @Override
        public boolean contains(Object o) {
            // TODO Auto-generated method stub
            return false;
        }

..... and So on (Cant write all methods.)

This is an example of Anonymous class. Its correct when someone states , No you cant instantiate an interface, and that's right. But you can never say , You CANT write List list = new List(); but, evidently you can do that and that's a hard statement to make that You can't do.

how to change class name of an element by jquery

$('.IsBestAnswer').removeClass('IsBestAnswer').addClass('bestanswer');

Your code has two problems:

  1. The selector .IsBestAnswe does not match what you thought
  2. It's addClass(), not addclass().

Also, I'm not sure whether you want to replace the class or add it. The above will replace, but remove the .removeClass('IsBestAnswer') part to add only:

$('.IsBestAnswer').addClass('bestanswer');

You should decide whether to use camelCase or all-lowercase in your CSS classes too (e.g. bestAnswer vs. bestanswer).

How to vertically align label and input in Bootstrap 3?

I'm sure you've found your answer by now, but for those who are still looking for an answer:

When input-lg is used, margins mismatch unless you use form-group-lg in addition to form-group class. Its example is in docs:

<form class="form-horizontal">
  <div class="form-group form-group-lg">
    <label class="col-sm-2 control-label" for="formGroupInputLarge">Large label</label>
    <div class="col-sm-10">
      <input class="form-control" type="text" id="formGroupInputLarge" placeholder="Large input">
    </div>
  </div>
  <div class="form-group form-group-sm">
    <label class="col-sm-2 control-label" for="formGroupInputSmall">Small label</label>
    <div class="col-sm-10">
      <input class="form-control" type="text" id="formGroupInputSmall" placeholder="Small input">
    </div>
  </div>
</form>

How to enable copy paste from between host machine and virtual machine in vmware, virtual machine is ubuntu

here is another solution I started using after being fed up with the copy and paste issue:

  1. Download MRemote (for pc). this is an alternative to remote desktop manager. You can use remote desktop manager if you like.
  2. Change the VMNet settings to NAT or add another VMNet and set it to NAT.
  3. Configure the vm ip address with an ip in the same network as you host machine. if you want to keep networks separated use a second vmnet and set it's ip address in the same network as the host. that's what I use.
  4. Enable RDP connections on the guest (I only use windows guests)
  5. Create a batch file with this command. add your guest machines:

vmrun start D:\VM\MySuperVM1\vm1.vmx nogui vmrun start D:\VM\MySuperVM2\vm2.vmx nogui

save the file to startmyvms.cmd

create another batch file and add your vms

vmrun stop D:\VM\MySuperVM1\vm1.vmx nogui vmrun stop D:\VM\MySuperVM2\vm2.vmx nogui

save the file to stopmyvms.cmd

  1. Open Mremote go to tools => External tools Add external tool => filename will be the startmyvms.cmd file Add external tool => filename will be the stopmyvms.cmd file So to start working with your vms:

  2. Create you connections to your VMs in mremote

Now to work with your vm 1. You open mremote 2. You go to tools => external tools 3. You click the startmyvms tool when you're done 1. You go to tools => external tools 2. You click the stopmyvms external tool

you could add the vmrun start on the connection setting => external tool before connection and add the vmrun stop in the connection settings => external tool after

Voilà !

PHP Warning: POST Content-Length of 8978294 bytes exceeds the limit of 8388608 bytes in Unknown on line 0

From the XAMPP panel, click on the ADMIN button on the Apache site. Then choose to edit php.ini And add the missing post_max_size to a value you are comfortable with.

post_max_size = 100M

JavaScript: Check if mouse button down?

I know this is an old post, but I thought the tracking of mouse button using mouse up/down felt a bit clunky, so I found an alternative that may appeal to some.

<style>
    div.myDiv:active {
        cursor: default;
    }
</style>

<script>
    function handleMove( div ) {
        var style = getComputedStyle( div );
        if (style.getPropertyValue('cursor') == 'default')
        {
            // You're down and moving here!
        }
    }
</script>

<div class='myDiv' onmousemove='handleMove(this);'>Click and drag me!</div>

The :active selector handles the mouse click much better than mouse up/down, you just need a way of reading that state in the onmousemove event. For that I needed to cheat and relied on the fact that the default cursor is "auto" and I just change it to "default", which is what auto selects by default.

You can use anything in the object that is returned by getComputedStyle that you can use as a flag without upsetting the look of your page e.g. border-color.

I would have liked to set my own user defined style in the :active section, but I couldn't get that to work. It would be better if it's possible.

Matching a Forward Slash with a regex

You can also work around special JS handling of the forward slash by enclosing it in a character group, like so:

const start = /[/]/g;
"/dev/null".match(start)     // => ["/", "/"]

const word = /[/](\w+)/ig;
"/dev/null".match(word)      // => ["/dev", "/null"]

How to store Java Date to Mysql datetime with JPA

Are you perhaps using java.sql.Date? While that has millisecond granularity as a Java class (it is a subclass of java.util.Date, bad design decision), it will be interpreted by the JDBC driver as a date without a time component. You have to use java.sql.Timestamp instead.

Java regex to extract text between tags

Try this:

Pattern p = Pattern.compile(?<=\\<(any_tag)\\>)(\\s*.*\\s*)(?=\\<\\/(any_tag)\\>);
Matcher m = p.matcher(anyString);

For example:

String str = "<TR> <TD>1Q Ene</TD> <TD>3.08%</TD> </TR>";
Pattern p = Pattern.compile("(?<=\\<TD\\>)(\\s*.*\\s*)(?=\\<\\/TD\\>)");
Matcher m = p.matcher(str);
while(m.find()){
   Log.e("Regex"," Regex result: " + m.group())       
}

Output:

10 Ene

3.08%

Python: create dictionary using dict() with integer keys?

a = dict(one=1, two=2, three=3)

Providing keyword arguments as in this example only works for keys that are valid Python identifiers. Otherwise, any valid keys can be used.

How to change letter spacing in a Textview?

As android doesn't support such a thing, you can do it manually with FontCreator. It has good options for font modifying. I used this tool to build a custom font, even if it takes some times but you can always use it in your projects.

'0000-00-00 00:00:00' can not be represented as java.sql.Timestamp error

I believe this is help full for who are getting this below Exception on to pumping data through logstash Error: logstash.inputs.jdbc - Exception when executing JDBC query {:exception=>#}

Answer:jdbc:mysql://localhost:3306/database_name?zeroDateTimeBehavior=convertToNull"

or if you are working with mysql

How to symbolicate crash log Xcode?

Make sure that your Xcode application name doesn't contain any spaces. This was the reason it didn't work for me. So /Applications/Xcode.app works, while /Applications/Xcode 6.1.1.app doesn't work.

How to create an empty array in Swift?

Compatible with: Xcode 6.0.1+

You can create an empty array by specifying the Element type of your array in the declaration.

For example:

// Shortened forms are preferred
var emptyDoubles: [Double] = []

// The full type name is also allowed
var emptyFloats: Array<Float> = Array()

Example from the apple developer page (Array):

Hope this helps anyone stumbling onto this page.

Complex nesting of partials and templates

UPDATE: Check out AngularUI's new project to address this problem


For subsections it's as easy as leveraging strings in ng-include:

<ul id="subNav">
  <li><a ng-click="subPage='section1/subpage1.htm'">Sub Page 1</a></li>
  <li><a ng-click="subPage='section1/subpage2.htm'">Sub Page 2</a></li>
  <li><a ng-click="subPage='section1/subpage3.htm'">Sub Page 3</a></li>
</ul>
<ng-include src="subPage"></ng-include>

Or you can create an object in case you have links to sub pages all over the place:

$scope.pages = { page1: 'section1/subpage1.htm', ... };
<ul id="subNav">
  <li><a ng-click="subPage='page1'">Sub Page 1</a></li>
  <li><a ng-click="subPage='page2'">Sub Page 2</a></li>
  <li><a ng-click="subPage='page3'">Sub Page 3</a></li>
</ul>
<ng-include src="pages[subPage]"></ng-include>

Or you can even use $routeParams

$routeProvider.when('/home', ...);
$routeProvider.when('/home/:tab', ...);
$scope.params = $routeParams;
<ul id="subNav">
  <li><a href="#/home/tab1">Sub Page 1</a></li>
  <li><a href="#/home/tab2">Sub Page 2</a></li>
  <li><a href="#/home/tab3">Sub Page 3</a></li>
</ul>
<ng-include src=" '/home/' + tab + '.html' "></ng-include>

You can also put an ng-controller at the top-most level of each partial

How to add an image in Tkinter?

Python 3.3.1 [MSC v.1600 32 bit (Intel)] on win32 14.May.2013

This worked for me, by following the code above

from tkinter import *
from PIL import ImageTk, Image
import os

root = Tk()
img = ImageTk.PhotoImage(Image.open("True1.gif"))
panel = Label(root, image = img)
panel.pack(side = "bottom", fill = "both", expand = "yes")
root.mainloop()

How do I concatenate two strings in Java?

Out of the box you have 3 ways to inject the value of a variable into a String as you try to achieve:

1. The simplest way

You can simply use the operator + between a String and any object or primitive type, it will automatically concatenate the String and

  1. In case of an object, the value of String.valueOf(obj) corresponding to the String "null" if obj is null otherwise the value of obj.toString().
  2. In case of a primitive type, the equivalent of String.valueOf(<primitive-type>).

Example with a non null object:

Integer theNumber = 42;
System.out.println("Your number is " + theNumber + "!");

Output:

Your number is 42!

Example with a null object:

Integer theNumber = null;
System.out.println("Your number is " + theNumber + "!");

Output:

Your number is null!

Example with a primitive type:

int theNumber = 42;
System.out.println("Your number is " + theNumber + "!");

Output:

Your number is 42!

2. The explicit way and potentially the most efficient one

You can use StringBuilder (or StringBuffer the thread-safe outdated counterpart) to build your String using the append methods.

Example:

int theNumber = 42;
StringBuilder buffer = new StringBuilder()
    .append("Your number is ").append(theNumber).append('!');
System.out.println(buffer.toString()); // or simply System.out.println(buffer)

Output:

Your number is 42!

Behind the scene, this is actually how recent java compilers convert all the String concatenations done with the operator +, the only difference with the previous way is that you have the full control.

Indeed, the compilers will use the default constructor so the default capacity (16) as they have no idea what would be the final length of the String to build, which means that if the final length is greater than 16, the capacity will be necessarily extended which has price in term of performances.

So if you know in advance that the size of your final String will be greater than 16, it will be much more efficient to use this approach to provide a better initial capacity. For instance, in our example we create a String whose length is greater than 16, so for better performances it should be rewritten as next:

Example optimized :

int theNumber = 42;
StringBuilder buffer = new StringBuilder(18)
    .append("Your number is ").append(theNumber).append('!');
System.out.println(buffer)

Output:

Your number is 42!

3. The most readable way

You can use the methods String.format(locale, format, args) or String.format(format, args) that both rely on a Formatter to build your String. This allows you to specify the format of your final String by using place holders that will be replaced by the value of the arguments.

Example:

int theNumber = 42;
System.out.println(String.format("Your number is %d!", theNumber));
// Or if we need to print only we can use printf
System.out.printf("Your number is still %d with printf!%n", theNumber);

Output:

Your number is 42!
Your number is still 42 with printf!

The most interesting aspect with this approach is the fact that we have a clear idea of what will be the final String because it is much more easy to read so it is much more easy to maintain.

How to check a string starts with numeric number?

Sorry I didn't see your Java tag, was reading question only. I'll leave my other answers here anyway since I've typed them out.

Java

String myString = "9Hello World!";
if ( Character.isDigit(myString.charAt(0)) )
{
    System.out.println("String begins with a digit");
}

C++:

string myString = "2Hello World!";

if (isdigit( myString[0]) )
{
    printf("String begins with a digit");
}

Regular expression:

\b[0-9]

Some proof my regex works: Unless my test data is wrong? alt text

Python: Get HTTP headers from urllib2.urlopen call?

urllib2.urlopen does an HTTP GET (or POST if you supply a data argument), not an HTTP HEAD (if it did the latter, you couldn't do readlines or other accesses to the page body, of course).

Toolbar Navigation Hamburger Icon missing

Just Add the following in your onCreate method,

if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setHomeButtonEnabled(true);
        }

        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, mDrawer, mToolbar, R.string.home_navigation_drawer_open, R.string.home_navigation_drawer_close) {

            public void onDrawerClosed(View view) {
                super.onDrawerClosed(view);
                invalidateOptionsMenu();
            }

            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                invalidateOptionsMenu();
            }

            @Override
            public void onDrawerSlide(View drawerView, float slideOffset) {
                super.onDrawerSlide(drawerView, slideOffset);
            }
        };
        mDrawer.addDrawerListener(toggle);
        toggle.syncState();

and In strings.xml,

<string name="home_navigation_drawer_open">Open navigation drawer</string>
<string name="home_navigation_drawer_close">Close navigation drawer</string>

How to use parameters with HttpPost

To set parameters to your HttpPostRequest you can use BasicNameValuePair, something like this :

    HttpClient httpclient;
    HttpPost httpPost;
    ArrayList<NameValuePair> postParameters;
    httpclient = new DefaultHttpClient();
    httpPost = new HttpPost("your login link");


    postParameters = new ArrayList<NameValuePair>();
    postParameters.add(new BasicNameValuePair("param1", "param1_value"));
    postParameters.add(new BasicNameValuePair("param2", "param2_value"));

    httpPost.setEntity(new UrlEncodedFormEntity(postParameters, "UTF-8"));

    HttpResponse response = httpclient.execute(httpPost);

Python Pandas: Get index of rows which column matches certain value

I extended this question that is how to gets the row, columnand value of all matches value?

here is solution:

import pandas as pd
import numpy as np


def search_coordinate(df_data: pd.DataFrame, search_set: set) -> list:
    nda_values = df_data.values
    tuple_index = np.where(np.isin(nda_values, [e for e in search_set]))
    return [(row, col, nda_values[row][col]) for row, col in zip(tuple_index[0], tuple_index[1])]


if __name__ == '__main__':
    test_datas = [['cat', 'dog', ''],
                  ['goldfish', '', 'kitten'],
                  ['Puppy', 'hamster', 'mouse']
                  ]
    df_data = pd.DataFrame(test_datas)
    print(df_data)
    result_list = search_coordinate(df_data, {'dog', 'Puppy'})
    print(f"\n\n{'row':<4} {'col':<4} {'name':>10}")
    [print(f"{row:<4} {col:<4} {name:>10}") for row, col, name in result_list]

Output:

          0        1       2
0       cat      dog        
1  goldfish           kitten
2     Puppy  hamster   mouse


row  col        name
0    1           dog
2    0         Puppy

Save each sheet in a workbook to separate CSV files

For Mac users like me, there are several gotchas:

You cannot save to any directory you want. Only few of them can receive your saved files. More info there

Here is a working script that you can copy paste in your excel for Mac:

Public Sub SaveWorksheetsAsCsv()

 Dim WS As Excel.Worksheet
 Dim SaveToDirectory As String

 SaveToDirectory = "~/Library/Containers/com.microsoft.Excel/Data/"

 For Each WS In ThisWorkbook.Worksheet
    WS.SaveAs SaveToDirectory & WS.Name & ".csv", xlCSV
 Next

End Sub

is it possible to evenly distribute buttons across the width of an android linearlayout

You can do this by giving both Views a layout_width of 0dp and a layout_weight of 1:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"/>

    <TextView
        android:layout_width="0dp"
        android:text="example text"
        android:layout_height="wrap_content"
        android:layout_weight="1"/>

</LinearLayout>

The way android layout_weight works is that:

  • first, it looks to the size that a View would normally take and reserves this space.
  • second, if the layout is match_parent then it will divide the space that is left in the ratio of the layout_weights. Thus if you gave the Views layout_weight="2" and layout_weight="1",the resultant ratio will be 2 to 1,that is : the first View will get 2/3 of the space that is left and the other view 1/3.

So that's why if you give layout_width a size of 0dp the first step has no added meaning since both Views are not assigned any space. Then only the second point decides the space each View gets, thus giving the Views the space you specified according to the ratio!

To explain why 0dp causes the space to devide equally by providing an example that shows the opposite: The code below would result in something different since example text now has a width that is greater than 0dp because it has wrap_content instead making the free space left to divide less than 100% because the text takes space. The result will be that they do get 50% of the free space left but the text already took some space so the TextView will have well over 50% of the total space.

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"/>

    <TextView
        android:layout_width="wrap_content"
        android:text="example text"
        android:layout_height="wrap_content"
        android:layout_weight="1"/>

</LinearLayout>

How to get distinct values from an array of objects in JavaScript?

my two cents on this function:

var result = [];
for (var len = array.length, i = 0; i < len; ++i) {
  var age = array[i].age;
  if (result.indexOf(age) > -1) continue;
  result.push(age);
}

You can see the result here (Method 8) http://jsperf.com/distinct-values-from-array/3

How to retrieve the LoaderException property?

try
{
  // load the assembly or type
}
catch (Exception ex)
{
  if (ex is System.Reflection.ReflectionTypeLoadException)
  {
    var typeLoadException = ex as ReflectionTypeLoadException;
    var loaderExceptions  = typeLoadException.LoaderExceptions;
  }
}

Convert object to JSON string in C#

Use .net inbuilt class JavaScriptSerializer

  JavaScriptSerializer js = new JavaScriptSerializer();
  string json = js.Serialize(obj);

Checking for an empty file in C++

Seek to the end of the file and check the position:

 fseek(fileDescriptor, 0, SEEK_END);
 if (ftell(fileDescriptor) == 0) {
     // file is empty...
 } else {
     // file is not empty, go back to the beginning:
     fseek(fileDescriptor, 0, SEEK_SET);
 }

If you don't have the file open already, just use the fstat function and check the file size directly.

java.lang.NoClassDefFoundError: org/json/JSONObject

Add json jar to your classpath

or use java -classpath json.jar ClassName

refer this

Convert UTF-8 with BOM to UTF-8 with no BOM in Python

You can use codecs.

import codecs
with open("test.txt",'r') as filehandle:
    content = filehandle.read()
if content[:3] == codecs.BOM_UTF8:
    content = content[3:]
print content.decode("utf-8")

Connecting an input stream to an outputstream

BUFFER_SIZE is the size of chucks to read in. Should be > 1kb and < 10MB.

private static final int BUFFER_SIZE = 2 * 1024 * 1024;
private void copy(InputStream input, OutputStream output) throws IOException {
    try {
        byte[] buffer = new byte[BUFFER_SIZE];
        int bytesRead = input.read(buffer);
        while (bytesRead != -1) {
            output.write(buffer, 0, bytesRead);
            bytesRead = input.read(buffer);
        }
    //If needed, close streams.
    } finally {
        input.close();
        output.close();
    }
}

How to use Javascript to read local text file and read line by line?

Without jQuery:

document.getElementById('file').onchange = function(){

  var file = this.files[0];

  var reader = new FileReader();
  reader.onload = function(progressEvent){
    // Entire file
    console.log(this.result);

    // By lines
    var lines = this.result.split('\n');
    for(var line = 0; line < lines.length; line++){
      console.log(lines[line]);
    }
  };
  reader.readAsText(file);
};

HTML:

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

Remember to put your javascript code after the file field is rendered.

How to add items to array in nodejs

Here is example which can give you some hints to iterate through existing array and add items to new array. I use UnderscoreJS Module to use as my utility file.

You can download from (https://npmjs.org/package/underscore)

$ npm install underscore

Here is small snippet to demonstrate how you can do it.

var _ = require("underscore");
var calendars = [1, "String", {}, 1.1, true],
    newArray = [];

_.each(calendars, function (item, index) {
    newArray.push(item);
});

console.log(newArray);

error: RPC failed; curl transfer closed with outstanding read data remaining

For me, the issue was that the connection closes before the whole clone complete. I used ethernet instead of wifi connection. Then it solves for me

Why am I getting "(304) Not Modified" error on some links when using HttpWebRequest?

This is intended behavior.

When you make an HTTP request, the server normally returns code 200 OK. If you set If-Modified-Since, the server may return 304 Not modified (and the response will not have the content). This is supposed to be your cue that the page has not been modified.

The authors of the class have foolishly decided that 304 should be treated as an error and throw an exception. Now you have to clean up after them by catching the exception every time you try to use If-Modified-Since.

Configure active profile in SpringBoot via Maven

The Maven profile and the Spring profile are two completely different things. Your pom.xml defines spring.profiles.active variable which is available in the build process, but not at runtime. That is why only the default profile is activated.

How to bind Maven profile with Spring?

You need to pass the build variable to your application so that it is available when it is started.

  1. Define a placeholder in your application.properties:

    [email protected]@
    

    The @spring.profiles.active@ variable must match the declared property from the Maven profile.

  2. Enable resource filtering in you pom.xml:

    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
            </resource>
        </resources>
        …
    </build>
    

    When the build is executed, all files in the src/main/resources directory will be processed by Maven and the placeholder in your application.properties will be replaced with the variable you defined in your Maven profile.

For more details you can go to my post where I described this use case.

Remote Connections Mysql Ubuntu

To expose MySQL to anything other than localhost you will have to have the following line

For mysql version 5.6 and below

uncommented in /etc/mysql/my.cnf and assigned to your computers IP address and not loopback

For mysql version 5.7 and above

uncommented in /etc/mysql/mysql.conf.d/mysqld.cnf and assigned to your computers IP address and not loopback

#Replace xxx with your IP Address 
bind-address        = xxx.xxx.xxx.xxx

Or add a bind-address = 0.0.0.0 if you don't want to specify the IP

Then stop and restart MySQL with the new my.cnf entry. Once running go to the terminal and enter the following command.

lsof -i -P | grep :3306

That should come back something like this with your actual IP in the xxx's

mysqld  1046  mysql  10u  IPv4  5203  0t0  TCP  xxx.xxx.xxx.xxx:3306 (LISTEN)

If the above statement returns correctly you will then be able to accept remote users. However for a remote user to connect with the correct priveleges you need to have that user created in both the localhost and '%' as in.

CREATE USER 'myuser'@'localhost' IDENTIFIED BY 'mypass';
CREATE USER 'myuser'@'%' IDENTIFIED BY 'mypass';

then,

GRANT ALL ON *.* TO 'myuser'@'localhost';
GRANT ALL ON *.* TO 'myuser'@'%';

and finally,

FLUSH PRIVILEGES; 
EXIT;

If you don't have the same user created as above, when you logon locally you may inherit base localhost privileges and have access issues. If you want to restrict the access myuser has then you would need to read up on the GRANT statement syntax HERE If you get through all this and still have issues post some additional error output and the my.cnf appropriate lines.

NOTE: If lsof does not return or is not found you can install it HERE based on your Linux distribution. You do not need lsof to make things work, but it is extremely handy when things are not working as expected.

UPDATE: If even after adding/changing the bind-address in my.cnf did not work, then go and change it in the place it was originally declared:

/etc/mysql/mariadb.conf.d/50-server.cnf

How can I tell which button was clicked in a PHP form submit?

All you need to give the name attribute to the each button. And you need to address each button press from the PHP script. But be careful to give each button a unique name. Because the PHP script only take care of the name most of the time

<input type="submit" name="Submit_this" id="This" />

Convert hexadecimal string (hex) to a binary string

BigInteger.toString(radix) will do what you want. Just pass in a radix of 2.

static String hexToBin(String s) {
  return new BigInteger(s, 16).toString(2);
}

How can I create a blank/hardcoded column in a sql query?

Thank you, in PostgreSQL this works for boolean

SELECT
hat,
shoe,
boat,
false as placeholder
FROM
objects

Django DoesNotExist

The solution that i believe is best and optimized is:

try:
   #your code
except "ModelName".DoesNotExist:
   #your code

"[notice] child pid XXXX exit signal Segmentation fault (11)" in apache error.log

Attach gdb to one of the httpd child processes and reload or continue working and wait for a crash and then look at the backtrace. Do something like this:

$ ps -ef|grep httpd
0     681     1   0 10:38pm ??         0:00.45 /Applications/MAMP/Library/bin/httpd -k start
501   690   681   0 10:38pm ??         0:00.02 /Applications/MAMP/Library/bin/httpd -k start

...

Now attach gdb to one of the child processes, in this case PID 690 (columns are UID, PID, PPID, ...)

$ sudo gdb
(gdb) attach 690
Attaching to process 690.
Reading symbols for shared libraries . done
Reading symbols for shared libraries ....................... done
0x9568ce29 in accept$NOCANCEL$UNIX2003 ()
(gdb) c
Continuing.

Wait for crash... then:

(gdb) backtrace

Or

(gdb) backtrace full

Should give you some clue what's going on. If you file a bug report you should include the backtrace.

If the crash is hard to reproduce it may be a good idea to configure Apache to only use one child processes for handling requests. The config is something like this:

StartServers 1
MinSpareServers 1
MaxSpareServers 1

jQuery validate: How to add a rule for regular expression validation?

You can use the addMethod()

e.g

$.validator.addMethod('postalCode', function (value) { 
    return /^((\d{5}-\d{4})|(\d{5})|([A-Z]\d[A-Z]\s\d[A-Z]\d))$/.test(value); 
}, 'Please enter a valid US or Canadian postal code.');

good article here https://web.archive.org/web/20130609222116/http://www.randallmorey.com/blog/2008/mar/16/extending-jquery-form-validation-plugin/

Copy a variable's value into another

The reason for this is simple. JavaScript uses refereces, so when you assign b = a you are assigning a reference to b thus when updating a you are also updating b

I found this on stackoverflow and will help prevent things like this in the future by just calling this method if you want to do a deep copy of an object.

function clone(obj) {
    // Handle the 3 simple types, and null or undefined
    if (null == obj || "object" != typeof obj) return obj;

    // Handle Date
    if (obj instanceof Date) {
        var copy = new Date();
        copy.setTime(obj.getTime());
        return copy;
    }

    // Handle Array
    if (obj instanceof Array) {
        var copy = [];
        for (var i = 0, len = obj.length; i < len; i++) {
            copy[i] = clone(obj[i]);
        }
        return copy;
    }

    // Handle Object
    if (obj instanceof Object) {
        var copy = {};
        for (var attr in obj) {
            if (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr]);
        }
        return copy;
    }

    throw new Error("Unable to copy obj! Its type isn't supported.");
}

In C# check that filename is *possibly* valid (not that it exists)

I've had luck using regular expressions as others have shown.

One thing to keep in mind is that Windows at least prohibits some filenames that otherwise containlegal characters. A few come to mind: com, nul, prn.

I don't have it with me now, but I have a regex that takes these filename into consideration. If you want I can post it, otherwise I'm sure you can find it the same way I did: Google.

-Jay

How do I check if a directory exists? "is_dir", "file_exists" or both?

Second variant in question post is not ok, because, if you already have file with the same name, but it is not a directory, !file_exists($dir) will return false, folder will not be created, so error "failed to open stream: No such file or directory" will be occured. In Windows there is a difference between 'file' and 'folder' types, so need to use file_exists() and is_dir() at the same time, for ex.:

if (file_exists('file')) {
    if (!is_dir('file')) { //if file is already present, but it's not a dir
        //do something with file - delete, rename, etc.
        unlink('file'); //for example
        mkdir('file', NEEDED_ACCESS_LEVEL);
    }
} else { //no file exists with this name
    mkdir('file', NEEDED_ACCESS_LEVEL);
}

How to set text color to a text view programmatically

yourTextView.setTextColor(color);

Or, in your case: yourTextView.setTextColor(0xffbdbdbd);

Nginx upstream prematurely closed connection while reading response header from upstream, for large requests

You can increase the timeout in node like so.

app.post('/slow/request', function(req, res){ req.connection.setTimeout(100000); //100 seconds ... }

What exactly is nullptr?

Let me first give you an implementation of unsophisticated nullptr_t

struct nullptr_t 
{
    void operator&() const = delete;  // Can't take address of nullptr

    template<class T>
    inline operator T*() const { return 0; }

    template<class C, class T>
    inline operator T C::*() const { return 0; }
};

nullptr_t nullptr;

nullptr is a subtle example of Return Type Resolver idiom to automatically deduce a null pointer of the correct type depending upon the type of the instance it is assigning to.

int *ptr = nullptr;                // OK
void (C::*method_ptr)() = nullptr; // OK
  • As you can above, when nullptr is being assigned to an integer pointer, a int type instantiation of the templatized conversion function is created. And same goes for method pointers too.
  • This way by leveraging template functionality, we are actually creating the appropriate type of null pointer every time we do, a new type assignment.
  • As nullptr is an integer literal with value zero, you can not able to use its address which we accomplished by deleting & operator.

Why do we need nullptr in the first place?

  • You see traditional NULL has some issue with it as below:

1?? Implicit conversion

char *str = NULL; // Implicit conversion from void * to char *
int i = NULL;     // OK, but `i` is not pointer type

2?? Function calling ambiguity

void func(int) {}
void func(int*){}
void func(bool){}

func(NULL);     // Which one to call?

  • Compilation produces the following error:
error: call to 'func' is ambiguous
    func(NULL);
    ^~~~
note: candidate function void func(bool){}
                              ^
note: candidate function void func(int*){}
                              ^
note: candidate function void func(int){}
                              ^
1 error generated.
compiler exit status 1

3?? Constructor overload

struct String
{
    String(uint32_t)    {   /* size of string */    }
    String(const char*) {       /* string */        }
};

String s1( NULL );
String s2( 5 );

  • In such cases, you need explicit cast (i.e., String s((char*)0)).

Twitter Bootstrap Form File Element Upload Button

No fancy shiz required:

HTML:

<form method="post" action="/api/admin/image" enctype="multipart/form-data">
    <input type="hidden" name="url" value="<%= boxes[i].url %>" />
    <input class="image-file-chosen" type="text" />
    <br />
    <input class="btn image-file-button" value="Choose Image" />
    <input class="image-file hide" type="file" name="image"/> <!-- Hidden -->
    <br />
    <br />
    <input class="btn" type="submit" name="image" value="Upload" />
    <br />
</form>

JS:

$('.image-file-button').each(function() {
      $(this).off('click').on('click', function() {
           $(this).siblings('.image-file').trigger('click');
      });
});
$('.image-file').each(function() {
      $(this).change(function () {
           $(this).siblings('.image-file-chosen').val(this.files[0].name);
      });
});

CAUTION: The three form elements in question MUST be siblings of each other (.image-file-chosen, .image-file-button, .image-file)

Declaring an unsigned int in Java

There are good answers here, but I don’t see any demonstrations of bitwise operations. Like Visser (the currently accepted answer) says, Java signs integers by default (Java 8 has unsigned integers, but I have never used them). Without further ado, let‘s do it...

RFC 868 Example

What happens if you need to write an unsigned integer to IO? Practical example is when you want to output the time according to RFC 868. This requires a 32-bit, big-endian, unsigned integer that encodes the number of seconds since 12:00 A.M. January 1, 1900. How would you encode this?

Make your own unsigned 32-bit integer like this:

Declare a byte array of 4 bytes (32 bits)

Byte my32BitUnsignedInteger[] = new Byte[4] // represents the time (s)

This initializes the array, see Are byte arrays initialised to zero in Java?. Now you have to fill each byte in the array with information in the big-endian order (or little-endian if you want to wreck havoc). Assuming you have a long containing the time (long integers are 64 bits long in Java) called secondsSince1900 (Which only utilizes the first 32 bits worth, and you‘ve handled the fact that Date references 12:00 A.M. January 1, 1970), then you can use the logical AND to extract bits from it and shift those bits into positions (digits) that will not be ignored when coersed into a Byte, and in big-endian order.

my32BitUnsignedInteger[0] = (byte) ((secondsSince1900 & 0x00000000FF000000L) >> 24); // first byte of array contains highest significant bits, then shift these extracted FF bits to first two positions in preparation for coersion to Byte (which only adopts the first 8 bits)
my32BitUnsignedInteger[1] = (byte) ((secondsSince1900 & 0x0000000000FF0000L) >> 16);
my32BitUnsignedInteger[2] = (byte) ((secondsSince1900 & 0x000000000000FF00L) >> 8);
my32BitUnsignedInteger[3] = (byte) ((secondsSince1900 & 0x00000000000000FFL); // no shift needed

Our my32BitUnsignedInteger is now equivalent to an unsigned 32-bit, big-endian integer that adheres to the RCF 868 standard. Yes, the long datatype is signed, but we ignored that fact, because we assumed that the secondsSince1900 only used the lower 32 bits). Because of coersing the long into a byte, all bits higher than 2^7 (first two digits in hex) will be ignored.

Source referenced: Java Network Programming, 4th Edition.

Click button copy to clipboard using jQuery

Even better approach without flash or any other requirements is clipboard.js. All you need to do is add data-clipboard-target="#toCopyElement" on any button, initialize it new Clipboard('.btn'); and it will copy the content of DOM with id toCopyElement to clipboard. This is a snippet that copy the text provided in your question via a link.

One limitation though is that it does not work on safari, but it works on all other browser including mobile browsers as it does not use flash

_x000D_
_x000D_
$(function(){_x000D_
  new Clipboard('.copy-text');_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdn.jsdelivr.net/clipboard.js/1.5.12/clipboard.min.js"></script>_x000D_
_x000D_
<p id="content">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s</p>_x000D_
_x000D_
<a class="copy-text" data-clipboard-target="#content" href="#">copy Text</a>
_x000D_
_x000D_
_x000D_

Update row with data from another row in the same table

UPDATE financialyear
   SET firstsemfrom = dt2.firstsemfrom,
       firstsemto = dt2.firstsemto,
       secondsemfrom = dt2.secondsemfrom,
       secondsemto = dt2.secondsemto
  from financialyear dt2
 WHERE financialyear.financialyearkey = 141
   AND dt2.financialyearkey = 140

Storing Images in PostgreSQL

Update from 10 years later In 2008 the hard drives you would run a database on would have much different characteristics and much higher cost than the disks you would store files on. These days there are much better solutions for storing files that didn't exist 10 years ago and I would revoke this advice and advise readers to look at some of the other answers in this thread.

Original

Don't store in images in the database unless you absolutely have to. I understand that this is not a web application, but if there isn't a shared file location that you can point to save the location of the file in the database.

//linuxserver/images/imagexxx.jpg

then perhaps you can quickly set up a webserver and store the web urls in the database (as well as the local path). While databases can handle LOB's and 3000 images (4-6 Megapixels, assuming 500K an image) 1.5 Gigs isn't a lot of space file systems are much better designed for storing large files than a database is.

database vs. flat files

Difference between database and flat files are given below:

  • Database provide more flexibility whereas flat file provide less flexibility.

  • Database system provide data consistency whereas flat file can not provide data consistency.

  • Database is more secure over flat files.
  • Database support DML and DDL whereas flat files can not support these.

  • Less data redundancy in database whereas more data redundancy in flat files.

Bind service to activity in Android

"If you start an android Service with startService(..) that Service will remain running until you explicitly invoke stopService(..). There are two reasons that a service can be run by the system. If someone calls Context.startService() then the system will retrieve the service (creating it and calling its onCreate() method if needed) and then call its onStartCommand(Intent, int, int) method with the arguments supplied by the client. The service will at this point continue running until Context.stopService() or stopSelf() is called. Note that multiple calls to Context.startService() do not nest (though they do result in multiple corresponding calls to onStartCommand()), so no matter how many times it is started a service will be stopped once Context.stopService() or stopSelf() is called; however, services can use their stopSelf(int) method to ensure the service is not stopped until started intents have been processed.

Clients can also use Context.bindService() to obtain a persistent connection to a service. This likewise creates the service if it is not already running (calling onCreate() while doing so), but does not call onStartCommand(). The client will receive the IBinder object that the service returns from its onBind(Intent) method, allowing the client to then make calls back to the service. The service will remain running as long as the connection is established (whether or not the client retains a reference on the Service's IBinder). Usually the IBinder returned is for a complex interface that has been written in AIDL.

A service can be both started and have connections bound to it. In such a case, the system will keep the service running as long as either it is started or there are one or more connections to it with the Context.BIND_AUTO_CREATE flag. Once neither of these situations hold, the Service's onDestroy() method is called and the service is effectively terminated. All cleanup (stopping threads, unregistering receivers) should be complete upon returning from onDestroy()."

How to get ID of clicked element with jQuery

You just need to remove the hash from the beginning:

$('a.pagerlink').click(function() { 
    var id = $(this).attr('id').substring(1);
    $container.cycle(id); 
    return false; 
}); 

Write a mode method in Java to find the most frequently occurring element in an array

I have recently made a program that computes a few different stats, including mode. While the coding may be rudimentary, it works for any array of ints, and could be modified to be doubles, floats, etc. The modification to the array is based on deleting indexes in the array that are not the final mode value(s). This allows you to show all modes (if there are multiple) as well as have the amount of occurrences (last item in modes array). The code below is the getMode method as well as the deleteValueIndex method needed to run this code

import java.io.File;
import java.util.Scanner;
import java.io.PrintStream;

public static int[] getMode(final int[] array) {           
  int[] numOfVals = new int[array.length];
  int[] valsList = new int[array.length];

  //initialize the numOfVals and valsList

  for(int ix = 0; ix < array.length; ix++) {
     valsList[ix] = array[ix];
  }

  for(int ix = 0; ix < numOfVals.length; ix++) {
     numOfVals[ix] = 1;
  }

  //freq table of items in valsList

  for(int ix = 0; ix < valsList.length - 1; ix++) {
     for(int ix2 = ix + 1; ix2 < valsList.length; ix2++) {
        if(valsList[ix2] == valsList[ix]) {
           numOfVals[ix] += 1;
        }
     }
  }

  //deletes index from valsList and numOfVals if a duplicate is found in valsList

  for(int ix = 0; ix < valsList.length - 1; ix++) {   
     for(int ix2 = ix + 1; ix2 < valsList.length; ix2++) {
        if(valsList[ix2] == valsList[ix]) {
           valsList = deleteValIndex(valsList, ix2);
           numOfVals = deleteValIndex(numOfVals, ix2);
        }
     }
  }

  //finds the highest occurence in numOfVals and sets it to most

  int most = 0;

  for(int ix = 0; ix < valsList.length; ix++) {
     if(numOfVals[ix] > most) {
        most = numOfVals[ix];
     }
  }

  //deletes index from valsList and numOfVals if corresponding index in numOfVals is less than most

  for(int ix = 0; ix < numOfVals.length; ix++) {
     if(numOfVals[ix] < most) {
        valsList = deleteValIndex(valsList, ix);
        numOfVals = deleteValIndex(numOfVals, ix);
        ix--;
     }
  }

  //sets modes equal to valsList, with the last index being most(the highest occurence)

  int[] modes = new int[valsList.length + 1];

  for(int ix = 0; ix < valsList.length; ix++) {
     modes[ix] = valsList[ix];
  }

  modes[modes.length - 1] = most;

  return modes;

}

public static int[] deleteValIndex(int[] array, final int index) {   
  int[] temp = new int[array.length - 1];
  int tempix = 0;

  //checks if index is in array

  if(index >= array.length) {
     System.out.println("I'm sorry, there are not that many items in this list.");
     return array;
  }

  //deletes index if in array

  for(int ix = 0; ix < array.length; ix++) {
     if(ix != index) {
        temp[tempix] = array[ix];
        tempix++;
     }
  }
  return temp;
}

Pandas: create two new columns in a dataframe with values calculated from a pre-existing column

The top answer is flawed in my opinion. Hopefully, no one is mass importing all of pandas into their namespace with from pandas import *. Also, the map method should be reserved for those times when passing it a dictionary or Series. It can take a function but this is what apply is used for.

So, if you must use the above approach, I would write it like this

df["A1"], df["A2"] = zip(*df["a"].apply(calculate))

There's actually no reason to use zip here. You can simply do this:

df["A1"], df["A2"] = calculate(df['a'])

This second method is also much faster on larger DataFrames

df = pd.DataFrame({'a': [1,2,3] * 100000, 'b': [2,3,4] * 100000})

DataFrame created with 300,000 rows

%timeit df["A1"], df["A2"] = calculate(df['a'])
2.65 ms ± 92.4 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

%timeit df["A1"], df["A2"] = zip(*df["a"].apply(calculate))
159 ms ± 5.24 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

60x faster than zip


In general, avoid using apply

Apply is generally not much faster than iterating over a Python list. Let's test the performance of a for-loop to do the same thing as above

%%timeit
A1, A2 = [], []
for val in df['a']:
    A1.append(val**2)
    A2.append(val**3)

df['A1'] = A1
df['A2'] = A2

298 ms ± 7.14 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

So this is twice as slow which isn't a terrible performance regression, but if we cythonize the above, we get much better performance. Assuming, you are using ipython:

%load_ext cython

%%cython
cpdef power(vals):
    A1, A2 = [], []
    cdef double val
    for val in vals:
        A1.append(val**2)
        A2.append(val**3)

    return A1, A2

%timeit df['A1'], df['A2'] = power(df['a'])
72.7 ms ± 2.16 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

Directly assigning without apply

You can get even greater speed improvements if you use the direct vectorized operations.

%timeit df['A1'], df['A2'] = df['a'] ** 2, df['a'] ** 3
5.13 ms ± 320 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

This takes advantage of NumPy's extremely fast vectorized operations instead of our loops. We now have a 30x speedup over the original.


The simplest speed test with apply

The above example should clearly show how slow apply can be, but just so its extra clear let's look at the most basic example. Let's square a Series of 10 million numbers with and without apply

s = pd.Series(np.random.rand(10000000))

%timeit s.apply(calc)
3.3 s ± 57.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

Without apply is 50x faster

%timeit s ** 2
66 ms ± 2 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

What is the best way to programmatically detect porn images?

This was written in 2000, not sure if the state of the art in porn detection has advanced at all, but I doubt it.

http://www.dansdata.com/pornsweeper.htm

PORNsweeper seems to have some ability to distinguish pictures of people from pictures of things that aren't people, as long as the pictures are in colour. It is less successful at distinguishing dirty pictures of people from clean ones.

With the default, medium sensitivity, if Human Resources sends around a picture of the new chap in Accounts, you've got about a 50% chance of getting it. If your sister sends you a picture of her six-month-old, it's similarly likely to be detained.

It's only fair to point out amusing errors, like calling the Mona Lisa porn, if they're representative of the behaviour of the software. If the makers admit that their algorithmic image recogniser will drop the ball 15% of the time, then making fun of it when it does exactly that is silly.

But PORNsweeper only seems to live up to its stated specifications in one department - detection of actual porn. It's half-way decent at detecting porn, but it's bad at detecting clean pictures. And I wouldn't be surprised if no major leaps were made in this area in the near future.

Android dependency has different version for the compile and runtime

In my case, I was having two different versions of the below implementation in two different modules, So i changed both implementation to versions ie : 6.0.2 and it worked. You may also need to write dependency resolution see the accepted answer.

app module

implementation 'com.karumi:dexter:5.0.0'

commons module

implementation 'com.karumi:dexter:6.0.2'

Python requests library how to pass Authorization header with single token

Requests natively supports basic auth only with user-pass params, not with tokens.

You could, if you wanted, add the following class to have requests support token based basic authentication:

import requests
from base64 import b64encode

class BasicAuthToken(requests.auth.AuthBase):
    def __init__(self, token):
        self.token = token
    def __call__(self, r):
        authstr = 'Basic ' + b64encode(('token:' + self.token).encode('utf-8')).decode('utf-8')
        r.headers['Authorization'] = authstr
        return r

Then, to use it run the following request :

r = requests.get(url, auth=BasicAuthToken(api_token))

An alternative would be to formulate a custom header instead, just as was suggested by other users here.

Dark theme in Netbeans 7 or 8

There is no more plugin in netbeans 12. In case someone comes to this page. Tools->Options->Appearance->Look and feel->Flatlaf Dark

enter image description here

What does %s and %d mean in printf in the C language?

%s is for string %d is for decimal (or int) %c is for character

It appears to be chewing through an array of characters, and printing out whatever string exists starting at each subsequent position. The strings will stop at the first null in each case.

The commas are just separating the arguments to a function that takes a variable number of args; this number corresponds to the number of % args in the format descriptor at the front.

Sending websocket ping/pong frame from browser

There is no Javascript API to send ping frames or receive pong frames. This is either supported by your browser, or not. There is also no API to enable, configure or detect whether the browser supports and is using ping/pong frames. There was discussion about creating a Javascript ping/pong API for this. There is a possibility that pings may be configurable/detectable in the future, but it is unlikely that Javascript will be able to directly send and receive ping/pong frames.

However, if you control both the client and server code, then you can easily add ping/pong support at a higher level. You will need some sort of message type header/metadata in your message if you don't have that already, but that's pretty simple. Unless you are planning on sending pings hundreds of times per second or have thousands of simultaneous clients, the overhead is going to be pretty minimal to do it yourself.

How to push a docker image to a private repository

There are two options:

  1. Go into the hub, and create the repository first, and mark it as private. Then when you push to that repo, it will be private. This is the most common approach.

  2. log into your docker hub account, and go to your global settings. There is a setting that allows you to set what your default visability is for the repositories that you push. By default it is set to public, but if you change it to private, all of your repositories that you push will be marked as private by default. It is important to note that you will need to have enough private repos available on your account, or else the repo will be locked until you upgrade your plan.

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

You can also create shapes directly inside the item tag, in case you want to add some more details to your view, like this:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true">
        <shape>
            <solid android:color="#81ba73" />
            <corners android:radius="6dp" />
        </shape>
        <ripple android:color="#c62828"/>
    </item>
    <item android:state_enabled="false">
        <shape>
            <solid android:color="#788e73" />
            <corners android:radius="6dp" />
        </shape>
    </item>
    <item>
        <shape>
            <solid android:color="#add8a3" />
            <corners android:radius="6dp" />
        </shape>
    </item>
</selector>

Beware that Android will cycle through the items from top to bottom, therefore, you must place the item without condition on the bottom of the list (so it acts like a default/fallback).

SQL to add column and comment in table in single command

You can use below query to update or create comment on already created table.

SYNTAX:

COMMENT ON COLUMN TableName.ColumnName IS 'comment text';

Example:

COMMENT ON COLUMN TAB_SAMBANGI.MY_COLUMN IS 'This is a comment on my column...';

What's the difference between a 302 and a 307 redirect?

EXPECTED for 302: redirect uses same request method POST on NEW_URL

CLIENT POST OLD_URL -> SERVER 302 NEW_URL -> CLIENT POST NEW_URL

ACTUAL for 302, 303: redirect changes request method from POST to GET on NEW_URL

CLIENT POST OLD_URL -> SERVER 302 NEW_URL -> CLIENT GET NEW_URL (redirect uses GET)
CLIENT POST OLD_URL -> SERVER 303 NEW_URL -> CLIENT GET NEW_URL (redirect uses GET)

ACTUAL for 307: redirect uses same request method POST on NEW_URL

CLIENT POST OLD_URL -> SERVER 307 NEW_URL -> CLIENT POST NEW_URL

How can I pass arguments to anonymous functions in JavaScript?

Your specific case can simply be corrected to be working:

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

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

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

importing jar libraries into android-studio

Android Studio 1.0.1 doesn't make it any clearer, but it does make it somehow easier. Here's what worked for me:

1) Using explorer, create an 'external_libs' folder (any other name is fine) inside the Project/app/src folder, where 'Project' is the name of your project

2) Copy your jar file into this 'external_libs' folder

3) In Android Studio, go to File -> Project Structure -> Dependencies -> Add -> File Dependency and navigate to your jar file, which should be under 'src/external_libs'

3) Select your jar file and click 'Ok'

Now, check your build.gradle (Module.app) script, where you'll see the jar already added under 'dependencies'

How to make the webpack dev server run on port 80 and on 0.0.0.0 to make it publicly accessible?

For me: changing the listen host worked:

.listen(3000, 'localhost', function (err, result) {
        if (err) {
            console.log(err);
        }
        console.log('Listening at localhost:3000');
    });

was changed to :

.listen(3000, '0.0.0.0', function (err, result) {
        if (err) {
            console.log(err);
        }
        console.log('Listening at localhost:3000');
    });

and the server started listening on 0.0.0.0

How to increment a datetime by one day?

date = datetime.datetime(2003,8,1,12,4,5)
for i in range(5): 
    date += datetime.timedelta(days=1)
    print(date) 

What is HEAD in Git?

In addition to all definitions, the thing that stuck in my mind was, when you make a commit, GIT creates a commit object within the repository. Commit objects should have a parent ( or multiple parents if it is a merge commit). Now, how does git know the parent of the current commit? So HEAD is a pointer to the (reference of the) last commit which will become the parent of the current commit.

Check if Variable is Empty - Angular 2

Angular 4 empty data if else

if(this.data == 0)
{
alert("Null data");
}
else
{
//some logic
}

Convert java.util.Date to String

Try this,

import java.text.ParseException;
import java.text.SimpleDateFormat;

public class Date
{
    public static void main(String[] args) 
    {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String strDate = "2013-05-14 17:07:21";
        try
        {
           java.util.Date dt = sdf.parse(strDate);         
           System.out.println(sdf.format(dt));
        }
        catch (ParseException pe)
        {
            pe.printStackTrace();
        }
    }
}

Output:

2013-05-14 17:07:21

For more on date and time formatting in java refer links below

Oracle Help Centre

Date time example in java