Programs & Examples On #Visual diff

git visual diff between branches

Have a look at git show-branch

There's a lot you can do with core git functionality. It might be good to specify what you'd like to include in your visual diff. Most answers focus on line-by-line diffs of commits, where your example focuses on names of files affected in a given commit.

One visual that seems not to be addressed is how to see the commits that branches contain (whether in common or uniquely).

For this visual, I'm a big fan of git show-branch; it breaks out a well organized table of commits per branch back to the common ancestor. - to try it on a repo with multiple branches with divergences, just type git show-branch and check the output - for a writeup with examples, see Compare Commits Between Git Branches

How to initialize const member variable in a class?

In C++ you cannot initialize any variables directly while the declaration. For this we've to use the concept of constructors.
See this example:-

#include <iostream>

using namespace std;

class A
{
    public:
  const int x;  
  
  A():x(0) //initializing the value of x to 0
  {
      //constructor
  }
};

int main()
{
    A a; //creating object
   cout << "Value of x:- " <<a.x<<endl; 
   
   return 0;
}

Hope it would help you!

Swing JLabel text change on the running application

import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.event.*;
public class Test extends JFrame implements ActionListener
{
    private JLabel label;
    private JTextField field;
    public Test()
    {
        super("The title");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setPreferredSize(new Dimension(400, 90));
        ((JPanel) getContentPane()).setBorder(new EmptyBorder(13, 13, 13, 13) );
        setLayout(new FlowLayout());
        JButton btn = new JButton("Change");
        btn.setActionCommand("myButton");
        btn.addActionListener(this);
        label = new JLabel("flag");
        field = new JTextField(5);
        add(field);
        add(btn);
        add(label);
        pack();
        setLocationRelativeTo(null);
        setVisible(true);
        setResizable(false);
    }
    public void actionPerformed(ActionEvent e)
    {
        if(e.getActionCommand().equals("myButton"))
        {
            label.setText(field.getText());
        }
    }
    public static void main(String[] args)
    {
        new Test();
    }
}

PHP check if date between two dates

If hours matter:

$paymentDate = strtotime(date("Y-m-d H:i:s"));
$contractDateBegin = strtotime("2014-01-22 12:42:00");
$contractDateEnd = strtotime("2014-01-22 12:50:00");

if($paymentDate > $contractDateBegin && $paymentDate < $contractDateEnd) {
   echo "is between";
} else {
    echo "NO GO!";  
}    

Compare two data.frames to find the rows in data.frame 1 that are not present in data.frame 2

Really fast comparison, to get count of differences. Using specific column name.

colname = "CreatedDate" # specify column name
index <- match(colname, names(source_df)) # get index name for column name
sel <- source_df[, index] == target_df[, index] # get differences, gives you dataframe with TRUE and FALSE values
table(sel)["FALSE"] # count of differences
table(sel)["TRUE"] # count of matches

For complete dataframe, do not provide column or index name

sel <- source_df[, ] == target_df[, ] # gives you dataframe with TRUE and FALSE values
table(sel)["FALSE"] # count of differences
table(sel)["TRUE"] # count of matches

How do I code my submit button go to an email address

There are several ways to do an email from HTML. Typically you see people doing a mailto like so:

<a href="mailto:[email protected]">Click to email</a>

But if you are doing it from a button you may want to look into a javascript solution.

OWIN Security - How to Implement OAuth2 Refresh Tokens

Freddy's answer helped me a lot to get this working. For the sake of completeness here's how you could implement hashing of the token:

private string ComputeHash(Guid input)
{
    byte[] source = input.ToByteArray();

    var encoder = new SHA256Managed();
    byte[] encoded = encoder.ComputeHash(source);

    return Convert.ToBase64String(encoded);
}

In CreateAsync:

var guid = Guid.NewGuid();
...
_refreshTokens.TryAdd(ComputeHash(guid), refreshTokenTicket);
context.SetToken(guid.ToString());

ReceiveAsync:

public async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
{
    Guid token;

    if (Guid.TryParse(context.Token, out token))
    {
        AuthenticationTicket ticket;

        if (_refreshTokens.TryRemove(ComputeHash(token), out ticket))
        {
            context.SetTicket(ticket);
        }
    }
}

cannot import name patterns

Seems you are using outdated version of django.. Simply update django and try again.. Following command will update your django version..

pip install --upgrade django

Multiplying Two Columns in SQL Server

select InitialPayment * MonthlyRate as MultiplyingCalculation, InitialPayment - MonthlyRate as SubtractingCalculation from Payment

Write output to a text file in PowerShell

The simplest way is to just redirect the output, like so:

Compare-Object $(Get-Content c:\user\documents\List1.txt) $(Get-Content c:\user\documents\List2.txt) > c:\user\documents\diff_output.txt

> will cause the output file to be overwritten if it already exists.
>> will append new text to the end of the output file if it already exists.

Perl: Use s/ (replace) and return new string

If you have Perl 5.14 or greater, you can use the /r option with the substitution operator to perform non-destructive substitution:

print "bla: ", $myvar =~ s/a/b/r, "\n";

In earlier versions you can achieve the same using a do() block with a temporary lexical variable, e.g.:

print "bla: ", do { (my $tmp = $myvar) =~ s/a/b/; $tmp }, "\n";

Remove background drawable programmatically in Android

Try this code:

imgView.setImageResource(android.R.color.transparent); 

also this one works:

imgView.setImageResource(0); 

but be careful this one doesn't work:

imgView.setImageResource(null); 

Return a "NULL" object if search result not found

In C++, references can't be null. If you want to optionally return null if nothing is found, you need to return a pointer, not a reference:

Attr *getAttribute(const string& attribute_name) const {
   //search collection
   //if found at i
        return &attributes[i];
   //if not found
        return nullptr;
}

Otherwise, if you insist on returning by reference, then you should throw an exception if the attribute isn't found.

(By the way, I'm a little worried about your method being const and returning a non-const attribute. For philosophical reasons, I'd suggest returning const Attr *. If you also may want to modify this attribute, you can overload with a non-const method returning a non-const attribute as well.)

How to parse a CSV in a Bash script?

First prototype using plain old grep and cut:

grep "${VALUE}" inputfile.csv | cut -d, -f"${INDEX}"

If that's fast enough and gives the proper output, you're done.

Passing arguments to "make run"

No. Looking at the syntax from the man page for GNU make

make [ -f makefile ] [ options ] ... [ targets ] ...

you can specify multiple targets, hence 'no' (at least no in the exact way you specified).

How do I access command line arguments in Python?

I highly recommend argparse which comes with Python 2.7 and later.

The argparse module reduces boiler plate code and makes your code more robust, because the module handles all standard use cases (including subcommands), generates the help and usage for you, checks and sanitize the user input - all stuff you have to worry about when you are using sys.argv approach. And it is for free (built-in).

Here a small example:

import argparse

parser = argparse.ArgumentParser("simple_example")
parser.add_argument("counter", help="An integer will be increased by 1 and printed.", type=int)
args = parser.parse_args()
print(args.counter + 1)

and the output for python prog.py -h

usage: simple_example [-h] counter

positional arguments:
  counter     counter will be increased by 1 and printed.

optional arguments:
  -h, --help  show this help message and exit

and for python prog.py 1 as you would expect:

2

How to use CURL via a proxy?

root@APPLICATIOSERVER:/var/www/html# php connectiontest.php
61e23468-949e-4103-8e08-9db09249e8s1 OpenSSL SSL_connect: SSL_ERROR_SYSCALL in connection to 10.172.123.1:80 root@APPLICATIOSERVER:/var/www/html#

Post declaring the proxy settings in the php script file issue has been fixed.

$proxy = '10.172.123.1:80';
curl_setopt($cSession, CURLOPT_PROXY, $proxy); // PROXY details with port

How to search for a file in the CentOS command line

CentOS is Linux, so as in just about all other Unix/Linux systems, you have the find command. To search for files within the current directory:

find -name "filename"

You can also have wildcards inside the quotes, and not just a strict filename. You can also explicitly specify a directory to start searching from as the first argument to find:

find / -name "filename"

will look for "filename" or all the files that match the regex expression in between the quotes, starting from the root directory. You can also use single quotes instead of double quotes, but in most cases you don't need either one, so the above commands will work without any quotes as well. Also, for example, if you're searching for java files and you know they are somewhere in your /home/username, do:

find /home/username -name *.java

There are many more options to the find command and you should do a:

man find

to learn more about it.

One more thing: if you start searching from / and are not root or are not sudo running the command, you might get warnings that you don't have permission to read certain directories. To ignore/remove those, do:

find / -name 'filename' 2>/dev/null

That just redirects the stderr to /dev/null.

Why do I get a C malloc assertion failure?

You are probably overrunning beyond the allocated mem somewhere. then the underlying sw doesn't pick up on it until you call malloc

There may be a guard value clobbered that is being caught by malloc.

edit...added this for bounds checking help

http://www.lrde.epita.fr/~akim/ccmp/doc/bounds-checking.html

What is difference between MVC, MVP & MVVM design pattern in terms of coding c#

MVP:

Advantages:

Presenter will be present in between Model and view.Presenter will fetch data from Model and will do manipulations for data as view wants and give it to view and view is responsible only for rendering.

Disadvantages:

1)We can't use presenter for multiple modules because data is being modified in presenter as desired by one view class.

3)Breaking Clean architecture because data flow should be only outwards but here data is coming back from presenter to View.

MVC:

Advanatages:

Here we have Controller in between view and model.Here data request will be done from controller to view but data will be sent back to view in form of interface but not with controller.So,here controller won't get bloated up because of many transactions.

Disadvantagaes:

Data Manipulation should be done by View as it wants and this will be extra work on UI thread which may effect UI rendering if data processing is more.

MVVM:

After announcing Architectural components,we got access to ViewModel which provided us biggest advantage i.e it's lifecycle aware.So,it won't notify data if view is not available.It is a clean architecture because flow is only in forward mode and data will be notified automatically by LiveData. So,it is Android's recommended architecture.

Even MVVM has a disadvantage. Since it is a lifecycle aware some concepts like alarm or reminder should come outside app.So,in this scenario we can't use MVVM.

Count number of occurrences for each unique value

select time, coalesce(count(case when activities = 3 then 1 end), 0) as count
from MyTable
group by time

SQL Fiddle Example

Output:

|  TIME | COUNT |
-----------------
| 13:00 |     2 |
| 13:15 |     2 |
| 13:30 |     0 |
| 13:45 |     1 |

If you want to count all the activities in one query, you can do:

select time, 
    coalesce(count(case when activities = 1 then 1 end), 0) as count1,
    coalesce(count(case when activities = 2 then 1 end), 0) as count2,
    coalesce(count(case when activities = 3 then 1 end), 0) as count3,
    coalesce(count(case when activities = 4 then 1 end), 0) as count4,
    coalesce(count(case when activities = 5 then 1 end), 0) as count5
from MyTable
group by time

The advantage of this over grouping by activities, is that it will return a count of 0 even if there are no activites of that type for that time segment.

Of course, this will not return rows for time segments with no activities of any type. If you need that, you'll need to use a left join with table that lists all the possible time segments.

AngularJS passing data to $http.get request

Here's a complete example of an HTTP GET request with parameters using angular.js in ASP.NET MVC:

CONTROLLER:

public class AngularController : Controller
{
    public JsonResult GetFullName(string name, string surname)
    {
        System.Diagnostics.Debugger.Break();
        return Json(new { fullName = String.Format("{0} {1}",name,surname) }, JsonRequestBehavior.AllowGet);
    }
}

VIEW:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<script type="text/javascript">
    var myApp = angular.module("app", []);

    myApp.controller('controller', function ($scope, $http) {

        $scope.GetFullName = function (employee) {

            //The url is as follows - ControllerName/ActionName?name=nameValue&surname=surnameValue

            $http.get("/Angular/GetFullName?name=" + $scope.name + "&surname=" + $scope.surname).
            success(function (data, status, headers, config) {
                alert('Your full name is - ' + data.fullName);
            }).
            error(function (data, status, headers, config) {
                alert("An error occurred during the AJAX request");
            });

        }
    });

</script>

<div ng-app="app" ng-controller="controller">

    <input type="text" ng-model="name" />
    <input type="text" ng-model="surname" />
    <input type="button" ng-click="GetFullName()" value="Get Full Name" />
</div>

Showing which files have changed between two revisions

Also keep in mind that git has cheap and easy branching. If I think a merge could be problematic I create a branch for the merge. So if master has the changes I want to merge in and ba is my branch that needs the code from master I might do the following:

git checkout ba
git checkout -b ba-merge
git merge master
.... review new code and fix conflicts....
git commit
git checkout ba
git merge ba-merge
git branch -d ba-merge
git merge master

End result is that I got to try out the merge on a throw-away branch before screwing with my branch. If I get my self tangled up I can just delete the ba-merge branch and start over.

How to set JAVA_HOME in Linux for all users

  1. find /usr/lib/jvm/java-1.x.x-openjdk
  2. vim /etc/profile

    Prepend sudo if logged in as not-privileged user, ie. sudo vim

  3. Press 'i' to get in insert mode
  4. add:

    export JAVA_HOME="path that you found"
    
    export PATH=$JAVA_HOME/bin:$PATH
    
  5. logout and login again, reboot, or use source /etc/profile to apply changes immediately in your current shell

WebView showing ERR_CLEARTEXT_NOT_PERMITTED although site is HTTPS

When you call "https://darkorbit.com/" your server figures that it's missing "www" so it redirects the call to "http://www.darkorbit.com/" and then to "https://www.darkorbit.com/", your WebView call is blocked at the first redirection as it's a "http" call. You can call "https://www.darkorbit.com/" instead and it will solve the issue.

How to set label size in Bootstrap

if you have

<span class="label label-default">New</span>

just add the style="font-size:XXpx;", ej.

<span class="label label-default" style="font-size:15px;">New</span>

SQL Server Profiler - How to filter trace to only display events from one database?

Create a new template and check DBname. Use that template for your tracefile.

JavaScript: Upload file

Unless you're trying to upload the file using ajax, just submit the form to /upload/image.

<form enctype="multipart/form-data" action="/upload/image" method="post">
    <input id="image-file" type="file" />
</form>

If you do want to upload the image in the background (e.g. without submitting the whole form), you can use ajax:

Error during installing HAXM, VT-X not working

I had the same issue. Enabling the Data Execution Prevention for all programs and services helped. I tried using the method Alex suggested above -

Go to MyPC / right click / Advanced System Settings / Advanced / In Performance click SETTINGS / Data Execution Prevention and enable DEP for all programs and services.

But I found the Data Execution Prevention page was all disabled and said "To use these settings, you must be a computer administrator and you must use the bcdedit.exe file."

This site explains how to enable DEP from cmd. http://www.thewindowsclub.com/disable-data-execution-prevention

What does the question mark operator mean in Ruby?

It's a convention in Ruby that methods that return boolean values end in a question mark. There's no more significance to it than that.

Generate random 5 characters string

I`ve aways use this:

<?php function fRand($len) {
    $str = '';
    $a = "abcdefghijklmnopqrstuvwxyz0123456789";
    $b = str_split($a);
    for ($i=1; $i <= $len ; $i++) { 
        $str .= $b[rand(0,strlen($a)-1)];
    }
    return $str;
} ?>

When you call it, sets the lenght of string.

<?php echo fRand([LENGHT]); ?>

You can also change the possible characters in the string $a.

What is the proof of of (N–1) + (N–2) + (N–3) + ... + 1= N*(N–1)/2

Sum of arithmetical progression

(A1+AN)/2*N = (1 + (N-1))/2*(N-1) = N*(N-1)/2

How to redirect output of systemd service to a file

If you have a newer distro with a newer systemd (systemd version 236 or newer), you can set the values of StandardOutput or StandardError to file:YOUR_ABSPATH_FILENAME.


Long story:

In newer versions of systemd there is a relatively new option (the github request is from 2016 ish and the enhancement is merged/closed 2017 ish) where you can set the values of StandardOutput or StandardError to file:YOUR_ABSPATH_FILENAME. The file:path option is documented in the most recent systemd.exec man page.

This new feature is relatively new and so is not available for older distros like centos-7 (or any centos before that).

How do I 'git diff' on a certain directory?

Provide a path (myfolder in this case) and just run:

git diff myfolder/

Add new attribute (element) to JSON object using JavaScript

A JSON object is simply a javascript object, so with Javascript being a prototype based language, all you have to do is address it using the dot notation.

mything.NewField = 'foo';

Convert a hexadecimal string to an integer efficiently in C?

For larger Hex strings like in the example I needed to use strtoul.

MySQL does not start when upgrading OSX to Yosemite or El Capitan

Long story short you need to create a launch file. So, from Terminal:

sudo vi /Library/LaunchDaemons/com.mysql.mysql.plist

(If you are not familiar with vi, then press i to start inserting text)

This should be the content of your file:

<?xml version="1.0" encoding="UTF-8"?> 
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
  <dict>
    <key>KeepAlive</key>
    <true />
    <key>Label</key>
    <string>com.mysql.mysqld</string>
    <key>ProgramArguments</key>
    <array>
      <string>/usr/local/mysql/bin/mysqld_safe</string>
      <string>--user=mysql</string>
    </array>
  </dict>
</plist>

press esc then : wq!enter

Then you need to give the file the right permissions and set it to load on startup.

sudo chown root:wheel /Library/LaunchDaemons/com.mysql.mysql.plist 
sudo chmod 644 /Library/LaunchDaemons/com.mysql.mysql.plist 
sudo launchctl load -w /Library/LaunchDaemons/com.mysql.mysql.plist

And that is it.

Parse XML using JavaScript

The following will parse an XML string into an XML document in all major browsers, including Internet Explorer 6. Once you have that, you can use the usual DOM traversal methods/properties such as childNodes and getElementsByTagName() to get the nodes you want.

var parseXml;
if (typeof window.DOMParser != "undefined") {
    parseXml = function(xmlStr) {
        return ( new window.DOMParser() ).parseFromString(xmlStr, "text/xml");
    };
} else if (typeof window.ActiveXObject != "undefined" &&
       new window.ActiveXObject("Microsoft.XMLDOM")) {
    parseXml = function(xmlStr) {
        var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async = "false";
        xmlDoc.loadXML(xmlStr);
        return xmlDoc;
    };
} else {
    throw new Error("No XML parser found");
}

Example usage:

var xml = parseXml("<foo>Stuff</foo>");
alert(xml.documentElement.nodeName);

Which I got from https://stackoverflow.com/a/8412989/1232175.

Is there an equivalent to e.PageX position for 'touchstart' event as there is for click event?

Check Safari developer reference on Touch class.

According to this, pageX/Y should be available - maybe you should check spelling? make sure it's pageX and not PageX

Installing and Running MongoDB on OSX

Mac Installation:

  1. Install brew

    ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
    
  2. Update and verify you are good with

    brew update
    brew doctor
    
  3. Install mongodb with

    brew install mongodb
    
  4. Create folder for mongo data files:

    mkdir -p /data/db
    
  5. Set permissions

    sudo chown -R `id -un` /data/db
    
  6. Open another terminal window & run and keep running a mongo server/daemon

    mongod
    
  7. Return to previous terminal and run a mongodb shell to access data

    mongo
    

To quit each of these later:

  1. The Shell:

    quit()
    
  2. The Server

    ctrl-c
    

How do I simulate a hover with a touch in touch enabled browsers?

Try this:

<script>
document.addEventListener("touchstart", function(){}, true);
</script>

And in your CSS:

element:hover, element:active {
-webkit-tap-highlight-color: rgba(0,0,0,0);
-webkit-user-select: none;
-webkit-touch-callout: none /*only to disable context menu on long press*/
}

With this code you don't need an extra .hover class!

Export MySQL data to Excel in PHP

try this code

data.php

    <table border="1">
<tr>
    <th>NO.</th>
    <th>NAME</th>
    <th>Major</th>
</tr>
<?php
//connection to mysql
mysql_connect("localhost", "root", ""); //server , username , password
mysql_select_db("codelution");

//query get data
$sql = mysql_query("SELECT * FROM student ORDER BY id ASC");
$no = 1;
while($data = mysql_fetch_assoc($sql)){
    echo '
    <tr>
        <td>'.$no.'</td>
        <td>'.$data['name'].'</td>
        <td>'.$data['major'].'</td>
    </tr>
    ';
    $no++;
}
?>

code for excel file

export.php

<?php
// The function header by sending raw excel
header("Content-type: application/vnd-ms-excel");
// Defines the name of the export file "codelution-export.xls"
header("Content-Disposition: attachment; filename=codelution-export.xls");
// Add data table
include 'data.php';
?>

if mysqli version

$sql="SELECT * FROM user_details";
$result=mysqli_query($conn,$sql);
if(mysqli_num_rows($result) > 0)
{
    $no = 1;
            while($data = mysqli_fetch_assoc($result))
            {echo '
    <tr>
        <<td>'.$no.'</td>
        <td>'.$data['name'].'</td>
        <td>'.$data['major'].'</td>

    </tr>
    ';
    $no++;

http://codelution.com/development/web/easy-ways-to-export-data-from-mysql-to-excel-with-php/

How to declare local variables in postgresql?

Postgresql historically doesn't support procedural code at the command level - only within functions. However, in Postgresql 9, support has been added to execute an inline code block that effectively supports something like this, although the syntax is perhaps a bit odd, and there are many restrictions compared to what you can do with SQL Server. Notably, the inline code block can't return a result set, so can't be used for what you outline above.

In general, if you want to write some procedural code and have it return a result, you need to put it inside a function. For example:

CREATE OR REPLACE FUNCTION somefuncname() RETURNS int LANGUAGE plpgsql AS $$
DECLARE
  one int;
  two int;
BEGIN
  one := 1;
  two := 2;
  RETURN one + two;
END
$$;
SELECT somefuncname();

The PostgreSQL wire protocol doesn't, as far as I know, allow for things like a command returning multiple result sets. So you can't simply map T-SQL batches or stored procedures to PostgreSQL functions.

Upload files from Java client to a HTTP server

Here is how you could do it with Java 11's java.net.http package:

    var fileA = new File("a.pdf");
    var fileB = new File("b.pdf");

    var mimeMultipartData = MimeMultipartData.newBuilder()
            .withCharset(StandardCharsets.UTF_8)
            .addFile("file1", fileA.toPath(), Files.probeContentType(fileA.toPath()))
            .addFile("file2", fileB.toPath(), Files.probeContentType(fileB.toPath()))
            .build();

    var request = HttpRequest.newBuilder()
            .header("Content-Type", mimeMultipartData.getContentType())
            .POST(mimeMultipartData.getBodyPublisher())
            .uri(URI.create("http://somehost/upload"))
            .build();

    var httpClient = HttpClient.newBuilder().build();
    var response = httpClient.send(request, BodyHandlers.ofString());

With the following MimeMultipartData:

public class MimeMultipartData {

    public static class Builder {

        private String boundary;
        private Charset charset = StandardCharsets.UTF_8;
        private List<MimedFile> files = new ArrayList<MimedFile>();
        private Map<String, String> texts = new LinkedHashMap<>();

        private Builder() {
            this.boundary = new BigInteger(128, new Random()).toString();
        }

        public Builder withCharset(Charset charset) {
            this.charset = charset;
            return this;
        }

        public Builder withBoundary(String boundary) {
            this.boundary = boundary;
            return this;
        }

        public Builder addFile(String name, Path path, String mimeType) {
            this.files.add(new MimedFile(name, path, mimeType));
            return this;
        }

        public Builder addText(String name, String text) {
            texts.put(name, text);
            return this;
        }

        public MimeMultipartData build() throws IOException {
            MimeMultipartData mimeMultipartData = new MimeMultipartData();
            mimeMultipartData.boundary = boundary;

            var newline = "\r\n".getBytes(charset);
            var byteArrayOutputStream = new ByteArrayOutputStream();
            for (var f : files) {
                byteArrayOutputStream.write(("--" + boundary).getBytes(charset)); 
                byteArrayOutputStream.write(newline);
                byteArrayOutputStream.write(("Content-Disposition: form-data; name=\"" + f.name + "\"; filename=\"" + f.path.getFileName() + "\"").getBytes(charset));
                byteArrayOutputStream.write(newline);
                byteArrayOutputStream.write(("Content-Type: " + f.mimeType).getBytes(charset));
                byteArrayOutputStream.write(newline);
                byteArrayOutputStream.write(newline);
                byteArrayOutputStream.write(Files.readAllBytes(f.path));
                byteArrayOutputStream.write(newline);
            }
            for (var entry: texts.entrySet()) {
                byteArrayOutputStream.write(("--" + boundary).getBytes(charset));
                byteArrayOutputStream.write(newline);
                byteArrayOutputStream.write(("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"").getBytes(charset));
                byteArrayOutputStream.write(newline);
                byteArrayOutputStream.write(newline);
                byteArrayOutputStream.write(entry.getValue().getBytes(charset));
                byteArrayOutputStream.write(newline);
            }
            byteArrayOutputStream.write(("--" + boundary + "--").getBytes(charset));

            mimeMultipartData.bodyPublisher = BodyPublishers.ofByteArray(byteArrayOutputStream.toByteArray());
            return mimeMultipartData;
        }

        public class MimedFile {

            public final String name;
            public final Path path;
            public final String mimeType;

            public MimedFile(String name, Path path, String mimeType) {
                this.name = name;
                this.path = path;
                this.mimeType = mimeType;
            }
        }
    }

    private String boundary;
    private BodyPublisher bodyPublisher;

    private MimeMultipartData() {
    }

    public static Builder newBuilder() {
        return new Builder();
    }

    public BodyPublisher getBodyPublisher() throws IOException {
        return bodyPublisher;
    }

    public String getContentType() {
        return "multipart/form-data; boundary=" + boundary;
    }

}

Weird behavior of the != XPath operator

If $AccountNumber or $Balance is a node-set, then this behavior could easily happen. It's not because and is being treated as or.

For example, if $AccountNumber referred to nodes with the values 12345 and 66 and $Balance referred to nodes with the values 55 and 0, then $AccountNumber != '12345' would be true (because 66 is not equal to 12345) and $Balance != '0' would be true (because 55 is not equal to 0).

I'd suggest trying this instead:

<xsl:when test="not($AccountNumber = '12345' or $Balance = '0')">

$AccountNumber = '12345' or $Balance = '0' will be true any time there is an $AccountNumber with the value 12345 or there is a $Balance with the value 0, and if you apply not() to that, you will get a false result.

How to use sed to remove the last n lines of a file

From the sed one-liners:

# delete the last 10 lines of a file
sed -e :a -e '$d;N;2,10ba' -e 'P;D'   # method 1
sed -n -e :a -e '1,10!{P;N;D;};N;ba'  # method 2

Seems to be what you are looing for.

Excel select a value from a cell having row number calculated

You could use the INDIRECT function. This takes a string and converts it into a range

More info here

=INDIRECT("K"&A2)

But it's preferable to use INDEX as it is less volatile.

=INDEX(K:K,A2)

This returns a value or the reference to a value from within a table or range

More info here

Put either function into cell B2 and fill down.

How can I make a multipart/form-data POST request using Java?

Here's a solution that does not require any libraries.

This routine transmits every file in the directory d:/data/mpf10 to urlToConnect


String boundary = Long.toHexString(System.currentTimeMillis());
URLConnection connection = new URL(urlToConnect).openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
PrintWriter writer = null;
try {
    writer = new PrintWriter(new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));
    File dir = new File("d:/data/mpf10");
    for (File file : dir.listFiles()) {
        if (file.isDirectory()) {
            continue;
        }
        writer.println("--" + boundary);
        writer.println("Content-Disposition: form-data; name=\"" + file.getName() + "\"; filename=\"" + file.getName() + "\"");
        writer.println("Content-Type: text/plain; charset=UTF-8");
        writer.println();
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
            for (String line; (line = reader.readLine()) != null;) {
                writer.println(line);
            }
        } finally {
            if (reader != null) {
                reader.close();
            }
        }
    }
    writer.println("--" + boundary + "--");
} finally {
    if (writer != null) writer.close();
}
// Connection is lazily executed whenever you request any status.
int responseCode = ((HttpURLConnection) connection).getResponseCode();
// Handle response

pandas convert some columns into rows

pd.wide_to_long

You can add a prefix to your year columns and then feed directly to pd.wide_to_long. I won't pretend this is efficient, but it may in certain situations be more convenient than pd.melt, e.g. when your columns already have an appropriate prefix.

df.columns = np.hstack((df.columns[:2], df.columns[2:].map(lambda x: f'Value{x}')))

res = pd.wide_to_long(df, stubnames=['Value'], i='name', j='Date').reset_index()\
        .sort_values(['location', 'name'])

print(res)

   name        Date location  Value
0  test    Jan-2010        A     12
2  test    Feb-2010        A     20
4  test  March-2010        A     30
1   foo    Jan-2010        B     18
3   foo    Feb-2010        B     20
5   foo  March-2010        B     25

JUnit: how to avoid "no runnable methods" in test utils classes

  1. If this is your base test class for example AbstractTest and all your tests extends this then define this class as abstract
  2. If it is Util class then better remove *Test from the class rename it is MyTestUtil or Utils etc.

Ionic 2: Cordova is not available. Make sure to include cordova.js or run in a device/simulator (running in emulator)

This is quite late but anyone going through the same problem might benefit from this answer.First try to add browser by running below command ionic platform add browser and then run command ionic run browser.

which is the difference between ionic serve and ionic run browser?

Ionic serve - runs your app as a website (meaning it doesn't have any Cordova capabilities). Ionic run browser - runs your app in the Cordova browser platform, which will inject cordova.js and any plugins that have browser capabilities

You can refer this link to know more difference between ionic serve and ionic run browser command

Update

From Ionic 3 this command has been changed. Use the command below instead;

ionic cordova platform add browser

ionic cordova run browser

You can find out which version of ionic you are using by running: ionic --version

How to see PL/SQL Stored Function body in Oracle

If is a package then you can get the source for that with:

    select text from all_source where name = 'PADCAMPAIGN' 
    and type = 'PACKAGE BODY'
    order by line;

Oracle doesn't store the source for a sub-program separately, so you need to look through the package source for it.

Note: I've assumed you didn't use double-quotes when creating that package, but if you did , then use

    select text from all_source where name = 'pAdCampaign' 
    and type = 'PACKAGE BODY'
    order by line;

Stacked Bar Plot in R

I'm obviosly not a very good R coder, but if you wanted to do this with ggplot2:

data<- rbind(c(480, 780, 431, 295, 670, 360,  190),
             c(720, 350, 377, 255, 340, 615,  345),
             c(460, 480, 179, 560,  60, 735, 1260),
             c(220, 240, 876, 789, 820, 100,   75))

a <- cbind(data[, 1], 1, c(1:4))
b <- cbind(data[, 2], 2, c(1:4))
c <- cbind(data[, 3], 3, c(1:4))
d <- cbind(data[, 4], 4, c(1:4))
e <- cbind(data[, 5], 5, c(1:4))
f <- cbind(data[, 6], 6, c(1:4))
g <- cbind(data[, 7], 7, c(1:4))

data           <- as.data.frame(rbind(a, b, c, d, e, f, g))
colnames(data) <-c("Time", "Type", "Group")
data$Type      <- factor(data$Type, labels = c("A", "B", "C", "D", "E", "F", "G"))

library(ggplot2)

ggplot(data = data, aes(x = Type, y = Time, fill = Group)) + 
       geom_bar(stat = "identity") +
       opts(legend.position = "none")

enter image description here

Number of rows affected by an UPDATE in PL/SQL

For those who want the results from a plain command, the solution could be:

begin
  DBMS_OUTPUT.PUT_LINE(TO_Char(SQL%ROWCOUNT)||' rows affected.');
end;

The basic problem is that SQL%ROWCOUNT is a PL/SQL variable (or function), and cannot be directly accessed from an SQL command. By using a noname PL/SQL block, this can be achieved.

... If anyone has a solution to use it in a SELECT Command, I would be interested.

How does setTimeout work in Node.JS?

setTimeout is a kind of Thread, it holds a operation for a given time and execute.

setTimeout(function,time_in_mills);

in here the first argument should be a function type; as an example if you want to print your name after 3 seconds, your code should be something like below.

setTimeout(function(){console.log('your name')},3000);

Key point to remember is, what ever you want to do by using the setTimeout method, do it inside a function. If you want to call some other method by parsing some parameters, your code should look like below:

setTimeout(function(){yourOtherMethod(parameter);},3000);

Android Intent Cannot resolve constructor

Same Error was coming with my code in Activity but not in Fragment. Showing constructor error for different line like new Intent( From.this, To.class) and new ArrayList<> etc.

Fixed using closing Android Studio and moving the repository to other location and opening the the project once again. Fixed the problem.

Seems like Android Studio building problem.

How to remove a row from JTable?

The correct way to apply a filter to a JTable is through the RowFilter interface added to a TableRowSorter. Using this interface, the view of a model can be changed without changing the underlying model. This strategy preserves the Model-View-Controller paradigm, whereas removing the rows you wish hidden from the model itself breaks the paradigm by confusing your separation of concerns.

What is the meaning of prepended double colon "::"?

:: is the scope resolution operator. It's used to specify the scope of something.

For example, :: alone is the global scope, outside all other namespaces.

some::thing can be interpreted in any of the following ways:

  • some is a namespace (in the global scope, or an outer scope than the current one) and thing is a type, a function, an object or a nested namespace;
  • some is a class available in the current scope and thing is a member object, function or type of the some class;
  • in a class member function, some can be a base type of the current type (or the current type itself) and thing is then one member of this class, a type, function or object.

You can also have nested scope, as in some::thing::bad. Here each name could be a type, an object or a namespace. In addition, the last one, bad, could also be a function. The others could not, since functions can't expose anything within their internal scope.

So, back to your example, ::thing can be only something in the global scope: a type, a function, an object or a namespace.

The way you use it suggests (used in a pointer declaration) that it's a type in the global scope.

I hope this answer is complete and correct enough to help you understand scope resolution.

What are the differences between a pointer variable and a reference variable in C++?

Actually, a reference is not really like a pointer.

A compiler keeps "references" to variables, associating a name with a memory address; that's its job to translate any variable name to a memory address when compiling.

When you create a reference, you only tell the compiler that you assign another name to the pointer variable; that's why references cannot "point to null", because a variable cannot be, and not be.

Pointers are variables; they contain the address of some other variable, or can be null. The important thing is that a pointer has a value, while a reference only has a variable that it is referencing.

Now some explanation of real code:

int a = 0;
int& b = a;

Here you are not creating another variable that points to a; you are just adding another name to the memory content holding the value of a. This memory now has two names, a and b, and it can be addressed using either name.

void increment(int& n)
{
    n = n + 1;
}

int a;
increment(a);

When calling a function, the compiler usually generates memory spaces for the arguments to be copied to. The function signature defines the spaces that should be created and gives the name that should be used for these spaces. Declaring a parameter as a reference just tells the compiler to use the input variable memory space instead of allocating a new memory space during the method call. It may seem strange to say that your function will be directly manipulating a variable declared in the calling scope, but remember that when executing compiled code, there is no more scope; there is just plain flat memory, and your function code could manipulate any variables.

Now there may be some cases where your compiler may not be able to know the reference when compiling, like when using an extern variable. So a reference may or may not be implemented as a pointer in the underlying code. But in the examples I gave you, it will most likely not be implemented with a pointer.

jquery $(this).id return Undefined

Hiya demo http://jsfiddle.net/LYTbc/

this is a reference to the DOM element, so you can wrap it directly.

attr api: http://api.jquery.com/attr/

The .attr() method gets the attribute value for only the first element in the matched set.

have a nice one, cheers!

code

$(document).ready(function () {
    $(".inputs").click(function () {
         alert(this.id);

        alert(" or " + $(this).attr("id"));

    });

});?

Inserting created_at data with Laravel

You can manually set this using Laravel, just remember to add 'created_at' to your $fillable array:

protected $fillable = ['name', 'created_at']; 

Connect HTML page with SQL server using javascript

Before The execution of following code, I assume you have created a database and a table (with columns Name (varchar), Age(INT) and Address(varchar)) inside that database. Also please update your SQL Server name , UserID, password, DBname and table name in the code below.

In the code. I have used VBScript and embedded it in HTML. Try it out!

<!DOCTYPE html>
<html>
<head>
<script type="text/vbscript">
<!--    

Sub Submit_onclick()
Dim Connection
Dim ConnString
Dim Recordset

Set connection=CreateObject("ADODB.Connection")
Set Recordset=CreateObject("ADODB.Recordset")
ConnString="DRIVER={SQL Server};SERVER=*YourSQLserverNameHere*;UID=*YourUserIdHere*;PWD=*YourpasswordHere*;DATABASE=*YourDBNameHere*"
Connection.Open ConnString

dim form1
Set form1 = document.Register

Name1 = form1.Name.value
Age1 = form1.Age.Value
Add1 = form1.address.value

connection.execute("INSERT INTO [*YourTableName*] VALUES ('"&Name1 &"'," &Age1 &",'"&Add1 &"')")

End Sub

//-->
</script>
</head>
<body>

<h2>Please Fill details</h2><br>
<p>
<form name="Register">
<pre>
<font face="Times New Roman" size="3">Please enter the log in credentials:<br>
Name:   <input type="text" name="Name">
Age:        <input type="text" name="Age">
Address:        <input type="text" name="address">
<input type="button" id ="Submit" value="submit" /><font></form> 
</p>
</pre>
</body>
</html>

Class constructor type in typescript?

I am not sure if this was possible in TypeScript when the question was originally asked, but my preferred solution is with generics:

class Zoo<T extends Animal> {
    constructor(public readonly AnimalClass: new () => T) {
    }
}

This way variables penguin and lion infer concrete type Penguin or Lion even in the TypeScript intellisense.

const penguinZoo = new Zoo(Penguin);
const penguin = new penguinZoo.AnimalClass(); // `penguin` is of `Penguin` type.

const lionZoo = new Zoo(Lion);
const lion = new lionZoo.AnimalClass(); // `lion` is `Lion` type.

How to generate JAXB classes from XSD?

1) You can use standard java utility xjc - ([your java home dir]\bin\xjc.exe). But you need to create .bat (or .sh) script for using it.

e.g. generate.bat:

[your java home dir]\bin\xjc.exe %1 %2 %3

e.g. test-scheme.xsd:

<?xml version="1.0"?>
<xs:schema version="1.0"
           xmlns:xs="http://www.w3.org/2001/XMLSchema"
           elementFormDefault="qualified" 
           targetNamespace="http://myprojects.net/xsd/TestScheme"
           xmlns="http://myprojects.net/xsd/TestScheme">
    <xs:element name="employee" type="PersonInfoType"/>

    <xs:complexType name="PersonInfoType">
        <xs:sequence>
            <xs:element name="firstname" type="xs:string"/>
            <xs:element name="lastname" type="xs:string"/>
        </xs:sequence>
    </xs:complexType>
</xs:schema>

Run .bat file with parameters: generate.bat test-scheme.xsd -d [your src dir]

For more info use this documentation - http://docs.oracle.com/javaee/5/tutorial/doc/bnazg.html

and this - http://docs.oracle.com/javase/6/docs/technotes/tools/share/xjc.html

2) JAXB (xjc utility) is installed together with JDK6 by default.

SQL Server stored procedure Nullable parameter

It looks like you're passing in Null for every argument except for PropertyValueID and DropDownOptionID, right? I don't think any of your IF statements will fire if only these two values are not-null. In short, I think you have a logic error.

Other than that, I would suggest two things...

First, instead of testing for NULL, use this kind syntax on your if statements (it's safer)...

    ELSE IF ISNULL(@UnitValue, 0) != 0 AND ISNULL(@UnitOfMeasureID, 0) = 0

Second, add a meaningful PRINT statement before each UPDATE. That way, when you run the sproc in MSSQL, you can look at the messages and see how far it's actually getting.

How do I set the default Java installation/runtime (Windows)?

Stacked by this issue and have resolved it in 2020, in Windows 10. I'm using Java 8 RE and 14.1 JDK and it worked well until Eclipse upgrade to version 2020-09. After that I can't run Eclipse because it needed to use Java 11 or newer and it found only 8 version. It was because of order of environment variables of "Path":

environment variables setting

I suppose C:\Program Files (x86)\Common Files\Oracle\Java\javapath is path to link to installed JRE exe files (in my case Java 8) and the issue was resolved by move down this link after %JAVA_HOME%, what leads to Java 14.1/bin folder.

EV setting after edit

It seems that order of environment variables affects order of searched folders while executable file is requested. Thanks for your comment or better explanation.

Select2 open dropdown on focus

Working Code for v4.0+ *(including 4.0.7)

The following code will open the menu on the initial focus, but won't get stuck in an infinite loop when the selection re-focuses after the menu closes.

// on first focus (bubbles up to document), open the menu
$(document).on('focus', '.select2-selection.select2-selection--single', function (e) {
  $(this).closest(".select2-container").siblings('select:enabled').select2('open');
});

// steal focus during close - only capture once and stop propogation
$('select.select2').on('select2:closing', function (e) {
  $(e.target).data("select2").$selection.one('focus focusin', function (e) {
    e.stopPropagation();
  });
});

Explanation

Prevent Infinite Focus Loop

Note: The focus event is fired twice

  1. Once when tabbing into the field
  2. Again when tabbing with an open dropdown to restore focus

focus menu states

We can prevent an infinite loop by looking for differences between the types of focus events. Since we only want to open the menu on the initial focus to the control, we have to somehow distinguish between the following raised events:

event timeline

Doing so it a cross browser friendly way is hard, because browsers send different information along with different events and also Select2 has had many minor changes to their internal firing of events, which interrupt previous flows.

One way that seems to work is to attach an event handler during the closing event for the menu and use it to capture the impending focus event and prevent it from bubbling up the DOM. Then, using a delegated listener, we'll call the actual focus -> open code only when the focus event bubbles all the way up to the document

Prevent Opening Disabled Selects

As noted in this github issue #4025 - Dropdown does not open on tab focus, we should check to make sure we only call 'open' on :enabled select elements like this:

$(this).siblings('select:enabled').select2('open');

Select2 DOM traversal

We have to traverse the DOM a little bit, so here's a map of the HTML structure generated by Select2

Select2 DOM

Source Code on GitHub

Here are some of the relevant code sections in play:

.on('mousedown' ... .trigger('toggle')
.on('toggle' ... .toggleDropdown()
.toggleDropdown ... .open()
.on('focus' ... .trigger('focus'
.on('close' ... $selection.focus()

It used to be the case that opening select2 fired twice, but it was fixed in Issue #3503 and that should prevent some jank

PR #5357 appears to be what broke the previous focus code that was working in 4.05

Working Demo in jsFiddle & Stack Snippets:

_x000D_
_x000D_
$('.select2').select2({});_x000D_
_x000D_
// on first focus (bubbles up to document), open the menu_x000D_
$(document).on('focus', '.select2-selection.select2-selection--single', function (e) {_x000D_
  $(this).closest(".select2-container").siblings('select:enabled').select2('open');_x000D_
});_x000D_
_x000D_
// steal focus during close - only capture once and stop propogation_x000D_
$('select.select2').on('select2:closing', function (e) {_x000D_
  $(e.target).data("select2").$selection.one('focus focusin', function (e) {_x000D_
    e.stopPropagation();_x000D_
  });_x000D_
});
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.7/css/select2.css" rel="stylesheet"/>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.7/js/select2.js"></script>_x000D_
_x000D_
<select class="select2" style="width:200px" >_x000D_
  <option value="1">Apple</option>_x000D_
  <option value="2">Banana</option>_x000D_
  <option value="3">Carrot</option>_x000D_
  <option value="4">Donut</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Tested on Chrome, FF, Edge, IE11

Editor does not contain a main type in Eclipse

I just had this exact same problem. This will sound crazy but if someone sees this try this before drastic measures. delete method signature:

public static void main(String args[])

(Not the body of your main just method declaration)

Save your project then re-write the method's header back onto its respective body. Save again and re-run. That worked for me but if it doesn't work try again but clean project right before re-running.

I don't know how this fixed it but it did. Worth a shot before recreating your whole project right?

Uncaught ReferenceError: $ is not defined

2 issues.

Looks like your jQuery was not loaded properly.

You generally see this error

Uncaught ReferenceError:$ is not defined

when jQuery was not properly included on your page.

Try using jQuery from CDN and it should solve your problem

Replace

<script src="JS/jquery-1.10.1.min.js"></script>

with the one from cdn

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>

NOTE: if you test from file system, you need to add the http: to the above URL or it will fail

Next your script file is before the HTML . So need to contain the code in DOM Ready handler.

$(function() {
    $('#slider').cycle({ 
        fx:     'scrollHorz', 
        speed:  'fast', 
        next:   '#next', 
        prev:   '#prev' 
    });
});

As far as I know 'Slider' was referenced when I created the div Id.

No it is not. If your script was included just before the body , then you may not enclose it in the Ready handler. But in your case it is present in the head. So when the script starts running that particular element is still not present in the DOM

Check Fiddle

python for increment inner loop

for a in range(1):

    for b in range(3):
        a = b*2
        print(a)

As per your question, you want to iterate the outer loop with help of the inner loop.

  1. In outer loop, we are iterating the inner loop 1 time.
  2. In the inner loop, we are iterating the 3 digits which are in the multiple of 2, starting from 0.

    Output:
    0
    2
    4
    

npx command not found

if you are using Linux system, use sudo command

sudo npm i -g npx

Return outside function error in Python

You can only return from inside a function and not from a loop.

It seems like your return should be outside the while loop, and your complete code should be inside a function.

def func():
    N = int(input("enter a positive integer:"))
    counter = 1
    while (N > 0):
        counter = counter * N
        N -= 1
    return counter  # de-indent this 4 spaces to the left.

print func()

And if those codes are not inside a function, then you don't need a return at all. Just print the value of counter outside the while loop.

How can I check for "undefined" in JavaScript?

I personally use

myVar === undefined

Warning: Please note that === is used over == and that myVar has been previously declared (not defined).


I do not like typeof myVar === "undefined". I think it is long winded and unnecessary. (I can get the same done in less code.)

Now some people will keel over in pain when they read this, screaming: "Wait! WAAITTT!!! undefined can be redefined!"

Cool. I know this. Then again, most variables in Javascript can be redefined. Should you never use any built-in identifier that can be redefined?

If you follow this rule, good for you: you aren't a hypocrite.

The thing is, in order to do lots of real work in JS, developers need to rely on redefinable identifiers to be what they are. I don't hear people telling me that I shouldn't use setTimeout because someone can

window.setTimeout = function () {
    alert("Got you now!");
};

Bottom line, the "it can be redefined" argument to not use a raw === undefined is bogus.

(If you are still scared of undefined being redefined, why are you blindly integrating untested library code into your code base? Or even simpler: a linting tool.)


Also, like the typeof approach, this technique can "detect" undeclared variables:

if (window.someVar === undefined) {
    doSomething();
}

But both these techniques leak in their abstraction. I urge you not to use this or even

if (typeof myVar !== "undefined") {
    doSomething();
}

Consider:

var iAmUndefined;

To catch whether or not that variable is declared or not, you may need to resort to the in operator. (In many cases, you can simply read the code O_o).

if ("myVar" in window) {
    doSomething();
}

But wait! There's more! What if some prototype chain magic is happening…? Now even the superior in operator does not suffice. (Okay, I'm done here about this part except to say that for 99% of the time, === undefined (and ****cough**** typeof) works just fine. If you really care, you can read about this subject on its own.)

How to create a function in SQL Server

I can give a small hack, you can use T-SQL function. Try this:

SELECT ID, PARSENAME(WebsiteName, 2)
FROM dbo.YourTable .....

How to call loading function with React useEffect only once

useMountEffect hook

Running a function only once after component mounts is such a common pattern that it justifies a hook of it's own that hides implementation details.

const useMountEffect = (fun) => useEffect(fun, [])

Use it in any functional component.

function MyComponent() {
    useMountEffect(function) // function will run only once after it has mounted. 
    return <div>...</div>;
}

About the useMountEffect hook

When using useEffect with a second array argument, React will run the callback after mounting (initial render) and after values in the array have changed. Since we pass an empty array, it will run only after mounting.

How to make a input field readonly with JavaScript?

You can get the input element and then set its readOnly property to true as follows:

document.getElementById('InputFieldID').readOnly = true;

Specifically, this is what you want:

<script type="text/javascript">
  function onLoadBody() {
    document.getElementById('control_EMAIL').readOnly = true;
  } 
</script>

Call this onLoadBody() function on body tag like:

<body onload="onLoadBody">

View Demo: jsfiddle.

How to import set of icons into Android Studio project

For custom images you created yourself, you can do without the plugin:

Right click on res folder, selecting New > Image Asset. browse image file. Select the largest image you have.

It will create all densities for you. Make sure you select an original image, not an asset studio image with an alpha, or you will semi-transpartent it twice.

How can I use a custom font in Java?

Here is how I did it!

//create the font

try {
    //create the font to use. Specify the size!
    Font customFont = Font.createFont(Font.TRUETYPE_FONT, new File("Fonts\\custom_font.ttf")).deriveFont(12f);
    GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
    //register the font
    ge.registerFont(customFont);
} catch (IOException e) {
    e.printStackTrace();
} catch(FontFormatException e) {
    e.printStackTrace();
}

//use the font
yourSwingComponent.setFont(customFont);

Convert float64 column to int64 in Pandas

This seems to be a little buggy in Pandas 0.23.4?

If there are np.nan values then this will throw an error as expected:

df['col'] = df['col'].astype(np.int64)

But doesn't change any values from float to int as I would expect if "ignore" is used:

df['col'] = df['col'].astype(np.int64,errors='ignore') 

It worked if I first converted np.nan:

df['col'] = df['col'].fillna(0).astype(np.int64)
df['col'] = df['col'].astype(np.int64)

Now I can't figure out how to get null values back in place of the zeroes since this will convert everything back to float again:

df['col']  = df['col'].replace(0,np.nan)

Why is Thread.Sleep so harmful

Sleep is used in cases where independent program(s) that you have no control over may sometimes use a commonly used resource (say, a file), that your program needs to access when it runs, and when the resource is in use by these other programs your program is blocked from using it. In this case, where you access the resource in your code, you put your access of the resource in a try-catch (to catch the exception when you can't access the resource), and you put this in a while loop. If the resource is free, the sleep never gets called. But if the resource is blocked, then you sleep for an appropriate amount of time, and attempt to access the resource again (this why you're looping). However, bear in mind that you must put some kind of limiter on the loop, so it's not a potentially infinite loop. You can set your limiting condition to be N number of attempts (this is what I usually use), or check the system clock, add a fixed amount of time to get a time limit, and quit attempting access if you hit the time limit.

Create Word Document using PHP in Linux

PHPWord can generate Word documents in docx format. It can also use an existing .docx file as a template - template variables can be added to the document in the format ${varname}

It has an LGPL license and the examples that came with the code worked nicely for me.

Detecting iOS / Android Operating system

Using the cordova-device-plugin, you can detect

device.platform

will be "Android" for android, and "windows" for windows. Works on device, and when simulating on browser. Here is a toast that will display the device values:

    window.plugins.toast.showLongTop(
    'Cordova:     ' + device.cordova + '\n' +
    'Model:       ' + device.model + '\n' +
    'Platform:    ' + device.platform + '\n' +
    'UUID:        ' + '\n' +
                      device.uuid + '\n' +
    'Version:     ' + device.version + '\n' +
    'Manufacturer ' + device.manufacturer + '\n' +
    'isVirtual    ' + device.isVirtual + '\n' +
    'Serial       ' + device.serial);

How to start new activity on button click

Intent iinent= new Intent(Homeactivity.this,secondactivity.class);
startActivity(iinent);

jQuery function to open link in new window

Button click event only.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
        <script language="javascript" type="text/javascript">
            $(document).ready(function () {
                $("#btnext").click(function () {                    
                    window.open("HTMLPage.htm", "PopupWindow", "width=600,height=600,scrollbars=yes,resizable=no");
                });
            });
</script>

Inline Form nested within Horizontal Form in Bootstrap 3

Another option is to put all of the fields that you want on a single line within a single form-group.

See demo here

<form class="form-horizontal">
    <div class="form-group">
        <label for="name" class="col-xs-2 control-label">Name</label>
        <div class="col-xs-10">
            <input type="text" class="form-control col-sm-10" name="name" placeholder="name"/>
        </div>
    </div>

    <div class="form-group">
        <label for="birthday" class="col-xs-3 col-sm-2 control-label">Birthday</label>
        <div class="col-xs-3">
            <input type="text" class="form-control" placeholder="year"/>
        </div>
        <div class="col-xs-3">
            <input type="text" class="form-control" placeholder="month"/>
        </div>
        <div class="col-xs-3">
            <input type="text" class="form-control" placeholder="day"/>
        </div>    
    </div>
</form>

Dart SDK is not configured

I followed the following steps to solve this problem:

First, Go to: File->Settings->Language & Framework->Flutter

There under the: 'flutter SDK path', put in the location where you have installed Flutter Mine was at: C:\src\flutter

Click Apply then OK and the android studio will refresh. The problem will be solved.

Concatenate a list of pandas dataframes together

If the dataframes DO NOT all have the same columns try the following:

df = pd.DataFrame.from_dict(map(dict,df_list))

"INSERT IGNORE" vs "INSERT ... ON DUPLICATE KEY UPDATE"

ON DUPLICATE KEY UPDATE is not really in the standard. It's about as standard as REPLACE is. See SQL MERGE.

Essentially both commands are alternative-syntax versions of standard commands.

Set angular scope variable in markup

ngInit can help to initialize variables.

<div ng-app='app'>
    <div ng-controller="MyController" ng-init="myVar='test'">
        {{myVar}}
    </div>
</div>

jsfiddle example

LINQ: Select where object does not contain items from list

In general, you're looking for the "Except" extension.

var rejectStatus = GenerateRejectStatuses();
var fullList = GenerateFullList();
var rejectList = fullList.Where(i => rejectStatus.Contains(i.Status));
var filteredList = fullList.Except(rejectList);

In this example, GenerateRegectStatuses() should be the list of statuses you wish to reject (or in more concrete terms based on your example, a List<int> of IDs)

jQuery - prevent default, then continue default

I would just do:

 $('#submiteButtonID').click(function(e){
     e.preventDefault();
     //do your stuff.
     $('#formId').submit();
 });

Call preventDefault at first and use submit() function later, if you just need to submit the form

Removing double quotes from variables in batch file creates problems with CMD environment

You have an extra double quote at the end, which is adding it back to the end of the string (after removing both quotes from the string).

Input:

set widget="a very useful item"
set widget
set widget=%widget:"=%
set widget

Output:

widget="a very useful item"
widget=a very useful item

Note: To replace Double Quotes " with Single Quotes ' do the following:

set widget=%widget:"='%

Note: To replace the word "World" (not case sensitive) with BobB do the following:

set widget="Hello World!"
set widget=%widget:world=BobB%
set widget

Output:

widget="Hello BobB!"

As far as your initial question goes (save the following code to a batch file .cmd or .bat and run):

@ECHO OFF
ECHO %0
SET BathFileAndPath=%~0
ECHO %BathFileAndPath%
ECHO "%BathFileAndPath%"
ECHO %~0
ECHO %0
PAUSE

Output:

"C:\Users\Test\Documents\Batch Files\Remove Quotes.cmd"
C:\Users\Test\Documents\Batch Files\Remove Quotes.cmd
"C:\Users\Test\Documents\Batch Files\Remove Quotes.cmd"
C:\Users\Test\Documents\Batch Files\Remove Quotes.cmd
"C:\Users\Test\Documents\Batch Files\Remove Quotes.cmd"
Press any key to continue . . .

%0 is the Script Name and Path.
%1 is the first command line argument, and so on.

How do I break out of a loop in Scala?

I got a situation like the code below

 for(id<-0 to 99) {
    try {
      var symbol = ctx.read("$.stocks[" + id + "].symbol").toString
      var name = ctx.read("$.stocks[" + id + "].name").toString
      stocklist(symbol) = name
    }catch {
      case ex: com.jayway.jsonpath.PathNotFoundException=>{break}
    }
  }

I am using a java lib and the mechanism is that ctx.read throw a Exception when it can find nothing. I was trapped in the situation that :I have to break the loop when a Exception was thrown, but scala.util.control.Breaks.break using Exception to break the loop ,and it was in the catch block thus it was caught.

I got ugly way to solve this: do the loop for the first time and get the count of the real length. and use it for the second loop.

take out break from Scala is not that good,when you are using some java libs.

Swift convert unix time to date and time

To get the date to show as the current time zone I used the following.

if let timeResult = (jsonResult["dt"] as? Double) {
     let date = NSDate(timeIntervalSince1970: timeResult)
     let dateFormatter = NSDateFormatter()
     dateFormatter.timeStyle = NSDateFormatterStyle.MediumStyle //Set time style
     dateFormatter.dateStyle = NSDateFormatterStyle.MediumStyle //Set date style
     dateFormatter.timeZone = NSTimeZone()
     let localDate = dateFormatter.stringFromDate(date)
}

Swift 3.0 Version

if let timeResult = (jsonResult["dt"] as? Double) {
    let date = Date(timeIntervalSince1970: timeResult)
    let dateFormatter = DateFormatter()
    dateFormatter.timeStyle = DateFormatter.Style.medium //Set time style
    dateFormatter.dateStyle = DateFormatter.Style.medium //Set date style
    dateFormatter.timeZone = self.timeZone
    let localDate = dateFormatter.string(from: date)                     
}

Swift 5

if let timeResult = (jsonResult["dt"] as? Double) {
    let date = Date(timeIntervalSince1970: timeResult)
    let dateFormatter = DateFormatter()
    dateFormatter.timeStyle = DateFormatter.Style.medium //Set time style
    dateFormatter.dateStyle = DateFormatter.Style.medium //Set date style
    dateFormatter.timeZone = .current
    let localDate = dateFormatter.string(from: date)                                
}

Keystore type: which one to use?

If you are using Java 8 or newer you should definitely choose PKCS12, the default since Java 9 (JEP 229).

The advantages compared to JKS and JCEKS are:

  • Secret keys, private keys and certificates can be stored
  • PKCS12 is a standard format, it can be read by other programs and libraries1
  • Improved security: JKS and JCEKS are pretty insecure. This can be seen by the number of tools for brute forcing passwords of these keystore types, especially popular among Android developers.2, 3

1 There is JDK-8202837, which has been fixed in Java 11

2 The iteration count for PBE used by all keystore types (including PKCS12) used to be rather weak (CVE-2017-10356), however this has been fixed in 9.0.1, 8u151, 7u161, and 6u171

3 For further reading:

How do write IF ELSE statement in a MySQL query

you must write it in SQL not it C/PHP style

IF( action = 2 AND state = 0, 1, 0 ) AS state

for use in query

IF ( action = 2 AND state = 0 ) THEN SET state = 1

for use in stored procedures or functions

C# Double - ToString() formatting with two decimal places but no rounding

I use the following:

double x = Math.Truncate(myDoubleValue * 100) / 100;

For instance:

If the number is 50.947563 and you use the following, the following will happen:

- Math.Truncate(50.947563 * 100) / 100;
- Math.Truncate(5094.7563) / 100;
- 5094 / 100
- 50.94

And there's your answer truncated, now to format the string simply do the following:

string s = string.Format("{0:N2}%", x); // No fear of rounding and takes the default number format

Change Twitter Bootstrap Tooltip content on click

You can just change the data-original-title using the following code:

$(element).attr('data-original-title', newValue);

How to get SLF4J "Hello World" working with log4j?

I had the same problem. I called my own custom logger in the log4j.properties file from code when using log4j api directly. If you are using the slf4j api calls, you are probably using the default root logger so you must configure that to be associated with an appender in the log4j.properties:


    # Set root logger level to DEBUG and its only appender to A1.
    log4j.rootLogger=DEBUG, A1

    # A1 is set to be a ConsoleAppender.
    log4j.appender.A1=org.apache.log4j.ConsoleAppender

Is there a method that tells my program to quit?

In Python 3 there is an exit() function:

elif choice == "q":
    exit()

Available text color classes in Bootstrap

You can use text classes:

.text-primary
.text-secondary
.text-success
.text-danger
.text-warning
.text-info
.text-light
.text-dark
.text-muted
.text-white

use text classes in any tag where needed.

<p class="text-primary">.text-primary</p>
<p class="text-secondary">.text-secondary</p>
<p class="text-success">.text-success</p>
<p class="text-danger">.text-danger</p>
<p class="text-warning">.text-warning</p>
<p class="text-info">.text-info</p>
<p class="text-light bg-dark">.text-light</p>
<p class="text-dark">.text-dark</p>
<p class="text-muted">.text-muted</p>
<p class="text-white bg-dark">.text-white</p>

You can add your own classes or modify above classes as your requirement.

'Java' is not recognized as an internal or external command

You need to configure your environment variables, JAVA_HOME and PATH.

JAVA_HOME must contain the path to java, and you should add %JAVA_HOME%\bin to PATH

Alternatively, you can simply add to your PATH the whole path to the bin folder, without the JAVA_HOME variable, however, this makes a little more annoying when you need to have more than one java version on your machine (that way you only need to change JAVA_HOME and don't even bother with PATH)

how to overcome ERROR 1045 (28000): Access denied for user 'ODBC'@'localhost' (using password: NO) permanently

I tried this and it worked:

C:\cd MySQL installed path\MySQL -uyourusername -pyourpassword

Is there a Boolean data type in Microsoft SQL Server like there is in MySQL?

You could use the BIT datatype to represent boolean data. A BIT field's value is either 1, 0, or null.

std::unique_lock<std::mutex> or std::lock_guard<std::mutex>?

They are not really same mutexes, lock_guard<muType> has nearly the same as std::mutex, with a difference that it's lifetime ends at the end of the scope (D-tor called) so a clear definition about these two mutexes :

lock_guard<muType> has a mechanism for owning a mutex for the duration of a scoped block.

And

unique_lock<muType> is a wrapper allowing deferred locking, time-constrained attempts at locking, recursive locking, transfer of lock ownership, and use with condition variables.

Here is an example implemetation :

#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <functional>
#include <chrono>

using namespace std::chrono;

class Product{

   public:

       Product(int data):mdata(data){
       }

       virtual~Product(){
       }

       bool isReady(){
       return flag;
       }

       void showData(){

        std::cout<<mdata<<std::endl;
       }

       void read(){

         std::this_thread::sleep_for(milliseconds(2000));

         std::lock_guard<std::mutex> guard(mmutex);

         flag = true;

         std::cout<<"Data is ready"<<std::endl;

         cvar.notify_one();

       }

       void task(){

       std::unique_lock<std::mutex> lock(mmutex);

       cvar.wait(lock, [&, this]() mutable throw() -> bool{ return this->isReady(); });

       mdata+=1;

       }

   protected:

    std::condition_variable cvar;
    std::mutex mmutex;
    int mdata;
    bool flag = false;

};

int main(){

     int a = 0;
     Product product(a);

     std::thread reading(product.read, &product);
     std::thread setting(product.task, &product);

     reading.join();
     setting.join();


     product.showData();
    return 0;
}

In this example, i used the unique_lock<muType> with condition variable

The property 'Id' is part of the object's key information and cannot be modified

Try

contact.ContactType = differentContactType;

or

contact.ContactTypeId = 3;

You are trying to set the Id of the ContactType (of the Contact) to 3.

How to link an image and target a new window

you can do like this

<a href="http://www.w3c.org/" target="_blank">W3C Home Page</a>

find this page

http://www.corelangs.com/html/links/new-window.html

goreb

How to remove old Docker containers

For anyone interested, I took the example from qkrijger and turned it into a clear all (stop and remove all)

docker stop `docker ps --no-trunc -aq` ; docker rm `docker ps --no-trunc -aq`

How to add a footer to the UITableView?

Initially I was just trying the method:

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section

but after using this along with:

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section

problem was solved. Sample Program-

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 30.0f;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *sampleView = [[UIView alloc] init];
    sampleView.frame = CGRectMake(SCREEN_WIDTH/2, 5, 60, 4);
    sampleView.backgroundColor = [UIColor blackColor];
    return sampleView;
}

and include UITableViewDelegate protocol.

@interface TestViewController : UIViewController <UITableViewDelegate>

Importing class from another file

Your problem is basically that you never specified the right path to the file.

Try instead, from your main script:

from folder.file import Klasa

Or, with from folder import file:

from folder import file
k = file.Klasa()

Or again:

import folder.file as myModule
k = myModule.Klasa()

Properties file in python (similar to Java Properties)

Lightbend has released the Typesafe Config library, which parses properties files and also some JSON-based extensions. Lightbend's library is only for the JVM, but it seems to be widely adopted and there are now ports in many languages, including Python: https://github.com/chimpler/pyhocon

How to create a timer using tkinter?

The root.after(ms, func) is the method you need to use. Just call it once before the mainloop starts and reschedule it inside the bound function every time it is called. Here is an example:

from tkinter import *
import time


def update_clock():
    timer_label.config(text=time.strftime('%H:%M:%S',time.localtime()),
                  font='Times 25')  # change the text of the time_label according to the current time
    root.after(100, update_clock)  # reschedule update_clock function to update time_label every 100 ms

root = Tk()  # create the root window
timer_label = Label(root, justify='center')  # create the label for timer
timer_label.pack()  # show the timer_label using pack geometry manager
root.after(0, update_clock)  # schedule update_clock function first call
root.mainloop()  # start the root window mainloop

only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices

I believe your problem is this: in your while loop, n is divided by 2, but never cast as an integer again, so it becomes a float at some point. It is then added onto y, which is then a float too, and that gives you the warning.

nodejs send html file to client

Try your code like this:

var app = express();
app.get('/test', function(req, res) {
    res.sendFile('views/test.html', {root: __dirname })
});
  1. Use res.sendFile instead of reading the file manually so express can handle setting the content-type properly for you.

  2. You don't need the app.engine line, as that is handled internally by express.

How to use and style new AlertDialog from appCompat 22.1 and above

If you want to use the new android.support.v7.app.AlertDialog and have different colors for the buttons and also have a custom layout then have a look at my https://gist.github.com/JoachimR/6bfbc175d5c8116d411e

@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {

    View v = inflater.inflate(R.layout.custom_layout, null);

    initDialogUi(v);

    final AlertDialog d = new AlertDialog.Builder(activity, R.style.AppCompatAlertDialogStyle)
            .setTitle(getString(R.string.some_dialog_title))
            .setCancelable(true)
            .setPositiveButton(activity.getString(R.string.some_dialog_title_btn_positive),
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            doSomething();
                            dismiss();
                        }
                    })
            .setNegativeButton(activity.getString(R.string.some_dialog_title_btn_negative),
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dismiss();
                        }
                    })
            .setView(v)
            .create();

    // change color of positive button         
    d.setOnShowListener(new DialogInterface.OnShowListener() {
        @Override
        public void onShow(DialogInterface dialog) {
            Button b = d.getButton(DialogInterface.BUTTON_POSITIVE);
            b.setTextColor(getResources().getColor(R.color.colorPrimary));
        }
    });

    return d;
}

enter image description here

What is the purpose of meshgrid in Python / NumPy?

Basic Idea

Given possible x values, xs, (think of them as the tick-marks on the x-axis of a plot) and possible y values, ys, meshgrid generates the corresponding set of (x, y) grid points---analogous to set((x, y) for x in xs for y in yx). For example, if xs=[1,2,3] and ys=[4,5,6], we'd get the set of coordinates {(1,4), (2,4), (3,4), (1,5), (2,5), (3,5), (1,6), (2,6), (3,6)}.

Form of the Return Value

However, the representation that meshgrid returns is different from the above expression in two ways:

First, meshgrid lays out the grid points in a 2d array: rows correspond to different y-values, columns correspond to different x-values---as in list(list((x, y) for x in xs) for y in ys), which would give the following array:

   [[(1,4), (2,4), (3,4)],
    [(1,5), (2,5), (3,5)],
    [(1,6), (2,6), (3,6)]]

Second, meshgrid returns the x and y coordinates separately (i.e. in two different numpy 2d arrays):

   xcoords, ycoords = (
       array([[1, 2, 3],
              [1, 2, 3],
              [1, 2, 3]]),
       array([[4, 4, 4],
              [5, 5, 5],
              [6, 6, 6]]))
   # same thing using np.meshgrid:
   xcoords, ycoords = np.meshgrid([1,2,3], [4,5,6])
   # same thing without meshgrid:
   xcoords = np.array([xs] * len(ys)
   ycoords = np.array([ys] * len(xs)).T

Note, np.meshgrid can also generate grids for higher dimensions. Given xs, ys, and zs, you'd get back xcoords, ycoords, zcoords as 3d arrays. meshgrid also supports reverse ordering of the dimensions as well as sparse representation of the result.

Applications

Why would we want this form of output?

Apply a function at every point on a grid: One motivation is that binary operators like (+, -, *, /, **) are overloaded for numpy arrays as elementwise operations. This means that if I have a function def f(x, y): return (x - y) ** 2 that works on two scalars, I can also apply it on two numpy arrays to get an array of elementwise results: e.g. f(xcoords, ycoords) or f(*np.meshgrid(xs, ys)) gives the following on the above example:

array([[ 9,  4,  1],
       [16,  9,  4],
       [25, 16,  9]])

Higher dimensional outer product: I'm not sure how efficient this is, but you can get high-dimensional outer products this way: np.prod(np.meshgrid([1,2,3], [1,2], [1,2,3,4]), axis=0).

Contour plots in matplotlib: I came across meshgrid when investigating drawing contour plots with matplotlib for plotting decision boundaries. For this, you generate a grid with meshgrid, evaluate the function at each grid point (e.g. as shown above), and then pass the xcoords, ycoords, and computed f-values (i.e. zcoords) into the contourf function.

How to return an array from an AJAX call?

@Xeon06, nice but just as a fyi for those that read this thread and tried like me... when returning the array from php => json_encode($theArray). converts to a string which to me isn't easy to manipulate esp for soft js users like myself.

Inside js, you are trying to get the array values and/or keys of the array u r better off using JSON.parse as in var jsArray = JSON.parse(data) where data is return array from php. the json encoded string is converted to js object that can now be manipulated easily.

e.g. foo={one:1, two:2, three:3} - gotten after JSON.parse

for (key in foo){ console.log("foo["+ key +"]="+ foo[key]) } - prints to ur firebug console. voila!

How to write text in ipython notebook?

Simply Enter Esc and type m it will convert to text cell.

setup script exited with error: command 'x86_64-linux-gnu-gcc' failed with exit status 1

$ sudo apt-get install gcc
$ sudo apt-get install python-dateutil python-docutils python-feedparser python-gdata python-jinja2 python-ldap python-libxslt1 python-lxml python-mako python-mock python-openid python-psycopg2 python-psutil python-pybabel python-pychart python-pydot python-pyparsing python-reportlab python-simplejson python-tz python-unittest2 python-vatnumber python-vobject python-webdav python-werkzeug python-xlwt python-yaml python-zsi

OR TRY THIS:

$ sudo apt-get install libxml2-dev libxslt1-dev

Angular 2 Checkbox Two Way Data Binding

You can remove .selected from saveUsername in your checkbox input since saveUsername is a boolean. Instead of [(ngModel)] use [checked]="saveUsername" (change)="saveUsername = !saveUsername"

Edit: Correct Solution:

<input
  type="checkbox"
  [checked]="saveUsername"
  (change)="saveUsername = !saveUsername"/>

Update: Like @newman noticed when ngModel is used in a form it won't work. However, you should use [ngModelOptions] attribute like (tested in Angular 7):

<input
  type="checkbox"
  [(ngModel)]="saveUsername"
  [ngModelOptions]="{standalone: true}"/> `

I also created an example at Stackblitz: https://stackblitz.com/edit/angular-abelrm

PHP If Statement with Multiple Conditions

It will be good to use array and compare each value 1 by 1 in loop. Its give advantage to change the length of your tests array. Write a function taking 2 parameters, 1 is test array and other one is the value to be tested.

$test_array = ('test1','test2', 'test3','test4');
for($i = 0; $i < count($test_array); $i++){
   if($test_value == $test_array[$i]){
       $ret_val = true;
       break;
   }
   else{
       $ret_val = false;
   }
}

Casting a number to a string in TypeScript

window.location.hash is a string, so do this:

var page_number: number = 3;
window.location.hash = String(page_number); 

Return background color of selected cell

If you are looking at a Table, a Pivot Table, or something with conditional formatting, you can try:

ActiveCell.DisplayFormat.Interior.Color

This also seems to work just fine on regular cells.

Handling null values in Freemarker

I think it works the other way

<#if object.attribute??>
   Do whatever you want....
</#if>

If object.attribute is NOT NULL, then the content will be printed.

Calculate percentage saved between two numbers?

This is function with inverted option

It will return:

  • 'change' - string that you can use for css class in your template
  • 'result' - plain result
  • 'formatted' - formatted result

function getPercentageChange( $oldNumber , $newNumber , $format = true , $invert = false ){

    $value      = $newNumber - $oldNumber;

    $change     = '';
    $sign       = '';

    $result     = 0.00;

    if ( $invert ) {
         if ( $value > 0 ) {
        //  going UP
            $change             = 'up';
            $sign               = '+';
            if ( $oldNumber > 0 ) {
                $result         = ($newNumber / $oldNumber) * 100;
            } else {
                $result     = 100.00;
            }

        }elseif ( $value < 0 ) {        
        //  going DOWN
            $change             = 'down';
            //$value                = abs($value);
            $result             = ($oldNumber / $newNumber) * 100;
            $result             = abs($result);
            $sign               = '-';

        }else {
        //  no changes
        }

    }else{

        if ( $newNumber > $oldNumber ) {

            //  increase
            $change             = 'up';

            if ( $oldNumber > 0 ) {

                $result = ( ( $newNumber / $oldNumber ) - 1 )* 100;

            }else{
                $result = 100.00;
            }

            $sign               = '+';

        }elseif ( $oldNumber > $newNumber ) {

            //  decrease
            $change             = 'down';

            if ( $oldNumber > 0 ) {

                $result = ( ( $newNumber / $oldNumber ) - 1 )* 100;

            } else {
                $result = 100.00;
            }

            $sign               = '-';

        }else{

            //  no change

        }

        $result = abs($result);

    }

    $result_formatted       = number_format($result, 2);

    if ( $invert ) {
        if ( $change == 'up' ) {
            $change = 'down';
        }elseif ( $change == 'down' ) {
            $change = 'up';
        }else{
            //
        }

        if ( $sign == '+' ) {
            $sign = '-';
        }elseif ( $sign == '-' ) {
            $sign = '+';
        }else{
            //
        }
    }
    if ( $format ) {
        $formatted          = '<span class="going '.$change.'">'.$sign.''.$result_formatted.' %</span>';
    } else{
        $formatted          = $result_formatted;
    }

    return array( 'change' => $change , 'result' => $result , 'formatted' => $formatted );
}

Differences between action and actionListener

As BalusC indicated, the actionListener by default swallows exceptions, but in JSF 2.0 there is a little more to this. Namely, it doesn't just swallows and logs, but actually publishes the exception.

This happens through a call like this:

context.getApplication().publishEvent(context, ExceptionQueuedEvent.class,                                                          
    new ExceptionQueuedEventContext(context, exception, source, phaseId)
);

The default listener for this event is the ExceptionHandler which for Mojarra is set to com.sun.faces.context.ExceptionHandlerImpl. This implementation will basically rethrow any exception, except when it concerns an AbortProcessingException, which is logged. ActionListeners wrap the exception that is thrown by the client code in such an AbortProcessingException which explains why these are always logged.

This ExceptionHandler can be replaced however in faces-config.xml with a custom implementation:

<exception-handlerfactory>
   com.foo.myExceptionHandler
</exception-handlerfactory>

Instead of listening globally, a single bean can also listen to these events. The following is a proof of concept of this:

@ManagedBean
@RequestScoped
public class MyBean {

    public void actionMethod(ActionEvent event) {

        FacesContext.getCurrentInstance().getApplication().subscribeToEvent(ExceptionQueuedEvent.class, new SystemEventListener() {

        @Override
        public void processEvent(SystemEvent event) throws AbortProcessingException {
            ExceptionQueuedEventContext content = (ExceptionQueuedEventContext)event.getSource();
            throw new RuntimeException(content.getException());
        }

        @Override
        public boolean isListenerForSource(Object source) {
            return true;
        }
        });

        throw new RuntimeException("test");
    }

}

(note, this is not how one should normally code listeners, this is only for demonstration purposes!)

Calling this from a Facelet like this:

<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core">
    <h:body>
        <h:form>
            <h:commandButton value="test" actionListener="#{myBean.actionMethod}"/>
        </h:form>
    </h:body>
</html>

Will result in an error page being displayed.

Get viewport/window height in ReactJS

Answers by @speckledcarp and @Jamesl are both brilliant. In my case, however, I needed a component whose height could extend the full window height, conditional at render time.... but calling a HOC within render() re-renders the entire subtree. BAAAD.

Plus, I wasn't interested in getting the values as props but simply wanted a parent div that would occupy the entire screen height (or width, or both).

So I wrote a Parent component providing a full height (and/or width) div. Boom.

A use case:

class MyPage extends React.Component {
  render() {
    const { data, ...rest } = this.props

    return data ? (
      // My app uses templates which misbehave badly if you manually mess around with the container height, so leave the height alone here.
      <div>Yay! render a page with some data. </div>
    ) : (
      <FullArea vertical>
        // You're now in a full height div, so containers will vertically justify properly
        <GridContainer justify="center" alignItems="center" style={{ height: "inherit" }}>
          <GridItem xs={12} sm={6}>
            Page loading!
          </GridItem>
        </GridContainer>
      </FullArea>
    )

Here's the component:

import React, { Component } from 'react'
import PropTypes from 'prop-types'

class FullArea extends Component {
  constructor(props) {
    super(props)
    this.state = {
      width: 0,
      height: 0,
    }
    this.getStyles = this.getStyles.bind(this)
    this.updateWindowDimensions = this.updateWindowDimensions.bind(this)
  }

  componentDidMount() {
    this.updateWindowDimensions()
    window.addEventListener('resize', this.updateWindowDimensions)
  }

  componentWillUnmount() {
    window.removeEventListener('resize', this.updateWindowDimensions)
  }

  getStyles(vertical, horizontal) {
    const styles = {}
    if (vertical) {
      styles.height = `${this.state.height}px`
    }
    if (horizontal) {
      styles.width = `${this.state.width}px`
    }
    return styles
  }

  updateWindowDimensions() {
    this.setState({ width: window.innerWidth, height: window.innerHeight })
  }

  render() {
    const { vertical, horizontal } = this.props
    return (
      <div style={this.getStyles(vertical, horizontal)} >
        {this.props.children}
      </div>
    )
  }
}

FullArea.defaultProps = {
  horizontal: false,
  vertical: false,
}

FullArea.propTypes = {
  horizontal: PropTypes.bool,
  vertical: PropTypes.bool,
}

export default FullArea

JQuery Calculate Day Difference in 2 date textboxes

$("#edate").change(function(){

   var edate = new Date($('#edate').val());
   var sdate = new Date($('#sdate').val());
   
   days = (edate- sdate) / (1000 * 60 * 60 * 24);
   days=days+1;
   alert (days);
   $("#nod").val(days);
});

Where is Android Studio layout preview?

I had the same issue and resolved by editing the t file in src>main>res>layout. You can choose between Test and Design mode at the bottom of editor.

Quite simple if we know where to look for !!! spend few hours figuring it out!!!

MVC Calling a view from a different controller

To directly answer your question if you want to return a view that belongs to another controller you simply have to specify the name of the view and its folder name.

public class CommentsController : Controller
{
    public ActionResult Index()
    { 
        return View("../Articles/Index", model );
    }
}

and

public class ArticlesController : Controller
{
    public ActionResult Index()
    { 
        return View();
    }
}

Also, you're talking about using a read and write method from one controller in another. I think you should directly access those methods through a model rather than calling into another controller as the other controller probably returns html.

Unable to create Android Virtual Device

For Ubuntu and running android-studio run to install the packages (these are not installed by default):

android update sdk

What are the various "Build action" settings in Visual Studio project properties and what do they do?

From the documentation:

The BuildAction property indicates what Visual Studio does with a file when a build is executed. BuildAction can have one of several values:

None - The file is not included in the project output group and is not compiled in the build process. An example is a text file that contains documentation, such as a Readme file.

Compile - The file is compiled into the build output. This setting is used for code files.

Content - The file is not compiled, but is included in the Content output group. For example, this setting is the default value for an .htm or other kind of Web file.

Embedded Resource - This file is embedded in the main project build output as a DLL or executable. It is typically used for resource files.

Difference between signature versions - V1 (Jar Signature) and V2 (Full APK Signature) while generating a signed APK in Android Studio?

According to this link: signature help

APK Signature Scheme v2 offers:

  1. Faster app install times
  2. More protection against unauthorized alterations to APK files.

Android 7.0 introduces APK Signature Scheme v2, a new app-signing scheme that offers faster app install times and more protection against unauthorized alterations to APK files. By default, Android Studio 2.2 and the Android Plugin for Gradle 2.2 sign your app using both APK Signature Scheme v2 and the traditional signing scheme, which uses JAR signing.

It is recommended to use APK Signature Scheme v2 but is not mandatory.

Although we recommend applying APK Signature Scheme v2 to your app, this new scheme is not mandatory. If your app doesn't build properly when using APK Signature Scheme v2, you can disable the new scheme.

How to call another controller Action From a controller in Mvc

Dleh's answer is correct and explain how to get an instance of another controller without missing dependencies set up for IoC

However, we now need to call the method from this other controller.
Full answer would be :

var controller = DependencyResolver.Current.GetService<ControllerB>();
controller.ControllerContext = new ControllerContext(this.Request.RequestContext, controller);

//Call your method
ActionInvoker.InvokeAction(controller.ControllerContext, "MethodNameFromControllerB_ToCall");

history.replaceState() example?

look at the example

window.history.replaceState({
    foo: 'bar'
}, 'Nice URL Title', '/nice_url');

window.onpopstate = function (e) {
    if (typeof e.state == "object" && e.state.foo == "bar") {
        alert("Blah blah blah");
    }
};

window.history.go(-1);

and search location.hash;

how do I create an array in jquery?

Some thoughts:

  • jQuery is a JavaScript library, not a language. So, JavaScript arrays look something like this:

    var someNumbers = [1, 2, 3, 4, 5];
    
  • { pageNo: $(this).text(), sortBy: $("#sortBy").val()} is a map of key to value. If you want an array of the keys or values, you can do something like this:

    var keys = [];
    var values = [];
    
    var object = { pageNo: $(this).text(), sortBy: $("#sortBy").val()};
    $.each(object, function(key, value) {
        keys.push(key);
        values.push(value);
    });
    
  • objects in JavaScript are incredibly flexible. If you want to create an object {foo: 1}, all of the following work:

    var obj = {foo: 1};
    
    var obj = {};
    obj['foo'] = 1;
    
    var obj = {};
    obj.foo = 1;
    

To wrap up, do you want this?

var data = {};
// either way of changing data will work:
data.pageNo = $(this).text();
data['sortBy'] = $("#sortBy").val();

$("#results").load("jquery-routing.php", data);

How do I create a SQL table under a different schema?

Try running CREATE TABLE [schemaname].[tableName]; GO;

This assumes the schemaname exists in your database. Please use CREATE SCHEMA [schemaname] if you need to create a schema as well.

EDIT: updated to note SQL Server 11.03 requiring this be the only statement in the batch.

How to display an IFRAME inside a jQuery UI dialog

There are multiple ways you can do this but I am not sure which one is the best practice. The first approach is you can append an iFrame in the dialog container on the fly with your given link:

$("#dialog").append($("<iframe />").attr("src", "your link")).dialog({dialogoptions});

Another would be to load the content of your external link into the dialog container using ajax.

$("#dialog").load("yourajaxhandleraddress.htm").dialog({dialogoptions});

Both works fine but depends on the external content.

Auto-size dynamic text to fill fixed size container

I have found a way to prevent the use of loops to shrink the text. It adjusts the font-size by multiplying it for the rate between container's width and content width. So if the container's width is 1/3 of the content, the font-size will be reduced by 1/3 and will container's width. To scale up, I have used a while loop, until content is bigger than container.

function fitText(outputSelector){
    // max font size in pixels
    const maxFontSize = 50;
    // get the DOM output element by its selector
    let outputDiv = document.getElementById(outputSelector);
    // get element's width
    let width = outputDiv.clientWidth;
    // get content's width
    let contentWidth = outputDiv.scrollWidth;
    // get fontSize
    let fontSize = parseInt(window.getComputedStyle(outputDiv, null).getPropertyValue('font-size'),10);
    // if content's width is bigger than elements width - overflow
    if (contentWidth > width){
        fontSize = Math.ceil(fontSize * width/contentWidth,10);
        fontSize =  fontSize > maxFontSize  ? fontSize = maxFontSize  : fontSize - 1;
        outputDiv.style.fontSize = fontSize+'px';   
    }else{
        // content is smaller than width... let's resize in 1 px until it fits 
        while (contentWidth === width && fontSize < maxFontSize){
            fontSize = Math.ceil(fontSize) + 1;
            fontSize = fontSize > maxFontSize  ? fontSize = maxFontSize  : fontSize;
            outputDiv.style.fontSize = fontSize+'px';   
            // update widths
            width = outputDiv.clientWidth;
            contentWidth = outputDiv.scrollWidth;
            if (contentWidth > width){
                outputDiv.style.fontSize = fontSize-1+'px'; 
            }
        }
    }
}

This code is part of a test that I have uploaded to Github https://github.com/ricardobrg/fitText/

Why do we need to install gulp globally and locally?

Technically you don't need to install it globally if the node_modules folder in your local installation is in your PATH. Generally this isn't a good idea.

Alternatively if npm test references gulp then you can just type npm test and it'll run the local gulp.

I've never installed gulp globally -- I think it's bad form.

What is your single most favorite command-line trick using Bash?

I'm new to programming on a mac, and I miss being able to launch gui programs from bash...so I have to create functions like this:

function macvim
{
/Applications/MacVim.app/Contents/MacOS/Vim "$@" -gp &
}

Sort array by firstname (alphabetically) in Javascript

A generalized function can be written like below

    function getSortedData(data, prop, isAsc) {
        return data.sort((a, b) => (a[prop] < b[prop] ? -1 : 1) * (isAsc ? 1 : -1));
   }

you can pass the below parameters

  1. The data which you want to sort
  2. The property in the data by it should be sorted
  3. The last parameter is of boolean type. It checks if you want to sort by ascending or by descending

Why isn't textarea an input[type="textarea"]?

It was a limitation of the technology at the time it was created. My answer copied over from Programmers.SE:

From one of the original HTML drafts:

NOTE: In the initial design for forms, multi-line text fields were supported by the Input element with TYPE=TEXT. Unfortunately, this causes problems for fields with long text values. SGML's default (Reference Quantity Set) limits the length of attribute literals to only 240 characters. The HTML 2.0 SGML declaration increases the limit to 1024 characters.

Transport security has blocked a cleartext HTTP

Like many have noted, this is a feature issue that comes with iOS 9.0. They have added a thing called App Transport Security, and I too was annoyed when it broke my Apps.

You can bandage it with the NSAllowsArbitraryLoads key to YES under NSAppTransportSecurity dictionary in your .plist file, but ultimately you will need to re-write the code that forms your URLs to form the HTTPS:// prefix.

Apple has re-written the NSUrlConnection class in iOS 9.0. You can read about it in NSURLConnection.

Else, you may have to back out of iOS 9.0 until you have time to implement the correct solution.

Split array into chunks

Well, a nice function for this would be:

function chunk(arr,times){
    if(times===null){var times = 10} //Fallback for users wanting to use the default of ten
   var tempArray = Array() //Array to be populated with chunks
    for(i=0;i<arr.length/times;i++){
     tempArray[i] = Array() //Sub-Arrays        //Repeats for each chunk         
   for(j=0;j<times;j++){
        if(!(arr[i*times+j]===undefined)){tempArray[i][j] = arr[i*times+j]//Populate Sub-  Arrays with chunks
    }
     else{
       j = times //Stop loop
       i = arr.length/times //Stop loop
  }
    }
     }
   return tempArray //Return the populated and chunked array
   }

Usage would be:

chunk(array,sizeOfChunks)

I commented it so you could understand what was going on.

(The formatting is a bit off, I programmed this on mobile)

Regular expressions in C: examples?

While the answer above is good, I recommend using PCRE2. This means you can literally use all the regex examples out there now and not have to translate from some ancient regex.

I made an answer for this already, but I think it can help here too..

Regex In C To Search For Credit Card Numbers

// YOU MUST SPECIFY THE UNIT WIDTH BEFORE THE INCLUDE OF THE pcre.h

#define PCRE2_CODE_UNIT_WIDTH 8
#include <stdio.h>
#include <string.h>
#include <pcre2.h>
#include <stdbool.h>

int main(){

bool Debug = true;
bool Found = false;
pcre2_code *re;
PCRE2_SPTR pattern;
PCRE2_SPTR subject;
int errornumber;
int i;
int rc;
PCRE2_SIZE erroroffset;
PCRE2_SIZE *ovector;
size_t subject_length;
pcre2_match_data *match_data;


char * RegexStr = "(?:\\D|^)(5[1-5][0-9]{2}(?:\\ |\\-|)[0-9]{4}(?:\\ |\\-|)[0-9]{4}(?:\\ |\\-|)[0-9]{4})(?:\\D|$)";
char * source = "5111 2222 3333 4444";

pattern = (PCRE2_SPTR)RegexStr;// <<<<< This is where you pass your REGEX 
subject = (PCRE2_SPTR)source;// <<<<< This is where you pass your bufer that will be checked. 
subject_length = strlen((char *)subject);




  re = pcre2_compile(
  pattern,               /* the pattern */
  PCRE2_ZERO_TERMINATED, /* indicates pattern is zero-terminated */
  0,                     /* default options */
  &errornumber,          /* for error number */
  &erroroffset,          /* for error offset */
  NULL);                 /* use default compile context */

/* Compilation failed: print the error message and exit. */
if (re == NULL)
  {
  PCRE2_UCHAR buffer[256];
  pcre2_get_error_message(errornumber, buffer, sizeof(buffer));
  printf("PCRE2 compilation failed at offset %d: %s\n", (int)erroroffset,buffer);
  return 1;
  }


match_data = pcre2_match_data_create_from_pattern(re, NULL);

rc = pcre2_match(
  re,
  subject,              /* the subject string */
  subject_length,       /* the length of the subject */
  0,                    /* start at offset 0 in the subject */
  0,                    /* default options */
  match_data,           /* block for storing the result */
  NULL);

if (rc < 0)
  {
  switch(rc)
    {
    case PCRE2_ERROR_NOMATCH: //printf("No match\n"); //
    pcre2_match_data_free(match_data);
    pcre2_code_free(re);
    Found = 0;
    return Found;
    //  break;
    /*
    Handle other special cases if you like
    */
    default: printf("Matching error %d\n", rc); //break;
    }
  pcre2_match_data_free(match_data);   /* Release memory used for the match */
  pcre2_code_free(re);
  Found = 0;                /* data and the compiled pattern. */
  return Found;
  }


if (Debug){
ovector = pcre2_get_ovector_pointer(match_data);
printf("Match succeeded at offset %d\n", (int)ovector[0]);

if (rc == 0)
  printf("ovector was not big enough for all the captured substrings\n");


if (ovector[0] > ovector[1])
  {
  printf("\\K was used in an assertion to set the match start after its end.\n"
    "From end to start the match was: %.*s\n", (int)(ovector[0] - ovector[1]),
      (char *)(subject + ovector[1]));
  printf("Run abandoned\n");
  pcre2_match_data_free(match_data);
  pcre2_code_free(re);
  return 0;
}

for (i = 0; i < rc; i++)
  {
  PCRE2_SPTR substring_start = subject + ovector[2*i];
  size_t substring_length = ovector[2*i+1] - ovector[2*i];
  printf("%2d: %.*s\n", i, (int)substring_length, (char *)substring_start);
  }
}

else{
  if(rc > 0){
    Found = true;

    } 
} 
pcre2_match_data_free(match_data);
pcre2_code_free(re);
return Found;

}

Install PCRE using:

wget https://ftp.pcre.org/pub/pcre/pcre2-10.31.zip
make 
sudo make install 
sudo ldconfig

Compile using :

gcc foo.c -lpcre2-8 -o foo

Check my answer for more details.

Android Button click go to another xml page

Write below code in your MainActivity.java file instead of your code.

public class MainActivity extends Activity implements OnClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button mBtn1 = (Button) findViewById(R.id.mBtn1);
        mBtn1.setOnClickListener(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

    @Override
    public void onClick(View v) {
        Log.i("clicks","You Clicked B1");
        Intent i=new Intent(MainActivity.this, MainActivity2.class);
        startActivity(i);
    }
}

And Declare MainActivity2 into your Androidmanifest.xml file using below code.

<activity
    android:name=".MainActivity2"
    android:label="@string/title_activity_main">
</activity>

Convert textbox text to integer

int num = int.Parse(textBox.Text);

try this. It worked for me

Git: How configure KDiff3 as merge tool and diff tool

For Mac users

Here is @Joseph's accepted answer, but with the default Mac install path location of kdiff3

(Note that you can copy and paste this and run it in one go)

git config --global --add merge.tool kdiff3 
git config --global --add mergetool.kdiff3.path  "/Applications/kdiff3.app/Contents/MacOS/kdiff3" 
git config --global --add mergetool.kdiff3.trustExitCode false

git config --global --add diff.guitool kdiff3
git config --global --add difftool.kdiff3.path "/Applications/kdiff3.app/Contents/MacOS/kdiff3"
git config --global --add difftool.kdiff3.trustExitCode false

disable textbox using jquery?

I would've done it slightly different

 <input type="radio" value="1" name="userradiobtn" id="userradiobtn" />   
 <input type="radio" value="2" name="userradiobtn" id="userradiobtn" />    
 <input type="radio" value="3" name="userradiobtn" id="userradiobtn" class="disablebox"/>   
 <input type="checkbox" value="4" name="chkbox" id="chkbox" class="showbox"/>    
 <input type="text" name="usertxtbox" id="usertxtbox" class="showbox" />   

Notice class attribute

 $(document).ready(function() {      
    $('.disablebox').click(function() {
        $('.showbox').attr("disabled", true);           
    });
});

This way should you need to add more radio buttons you don't need to worry about changing the javascript

Show/Hide Multiple Divs with Jquery

simple but stupid approach:

$('#showall').click(function(){
    $('div[id^=div]').show();
});

$('#showdiv1').click(function(){
    $('#div1').show();
    $('div[id^=div]').not('#div1').show();
});

as for better one - add common class to all div's, and use some attribute in buttons with id of target divs

NumPy ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

try this=> numpy.array(yourvariable) followed by the command to compare, whatever you wish to.

How do I render a Word document (.doc, .docx) in the browser using JavaScript?

No browsers currently have the code necessary to render Word Documents, and as far as I know, there are no client-side libraries that currently exist for rendering them either.

However, if you only need to display the Word Document, but don't need to edit it, you can use Google Documents' Viewer via an <iframe> to display a remotely hosted .doc/.docx.

<iframe src="https://docs.google.com/gview?url=http://remote.url.tld/path/to/document.doc&embedded=true"></iframe>

Solution adapted from "How to display a word document using fancybox".

Example:

JSFiddle

However, if you'd rather have native support, in most, if not all browsers, I'd recommend resaving the .doc/.docx as a PDF file Those can also be independently rendered using PDF.js by Mozilla.

Edit:

Huge thanks to fatbotdesigns for posting the Microsoft Office 365 viewer in the comments.

<iframe src='https://view.officeapps.live.com/op/embed.aspx?src=http://remote.url.tld/path/to/document.doc' width='1366px' height='623px' frameborder='0'>This is an embedded <a target='_blank' href='http://office.com'>Microsoft Office</a> document, powered by <a target='_blank' href='http://office.com/webapps'>Office Online</a>.</iframe>

One more important caveat to keep in mind, as pointed out by lightswitch05, is that this will upload your document to a third-party server. If this is unacceptable, then this method of display isn't the proper course of action.

Live Examples:

Google Docs Viewer

Microsoft Office Viewer

Why do we check up to the square root of a prime number to determine if it is prime?

Let n be non-prime. Therefore, it has at least two integer factors greater than 1. Let f be the smallest of n's such factors. Suppose f > sqrt n. Then n/f is an integer LTE sqrt n, thus smaller than f. Therefore, f cannot be n's smallest factor. Reductio ad absurdum; n's smallest factor must be LTE sqrt n.

How to make Python speak

This is what you are looking for. A complete TTS solution for the Mac. You can use this standalone or as a co-location Mac server for web apps:

http://wolfpaulus.com/jounal/mac/ttsserver/

How to parse this string in Java?

...
String str = "bla!/bla/bla/"

String parts[] = str.split("/");

//To get fist "bla!"
String dir1 = parts[0];

Open Jquery modal dialog on click event

Try this

    $(function() {

$('#clickMe').click(function(event) {
    var mytext = $('#myText').val();


    $('<div id="dialog">'+mytext+'</div>').appendTo('body');        
    event.preventDefault();

        $("#dialog").dialog({                   
            width: 600,
            modal: true,
            close: function(event, ui) {
                $("#dialog").remove();
                }
            });
    }); //close click
});

And in HTML

<h3 id="clickMe">Open dialog</h3>
<textarea cols="0" rows="0" id="myText" style="display:none">Some hidden text display none</textarea>

How to create EditText accepts Alphabets only in android?

EditText state = (EditText) findViewById(R.id.txtState);


                Pattern ps = Pattern.compile("^[a-zA-Z ]+$");
                Matcher ms = ps.matcher(state.getText().toString());
                boolean bs = ms.matches();
                if (bs == false) {
                    if (ErrorMessage.contains("invalid"))
                        ErrorMessage = ErrorMessage + "state,";
                    else
                        ErrorMessage = ErrorMessage + "invalid state,";

                }

Get all table names of a particular database by SQL query?

Simply get all improtanat information with this below SQL in Mysql

    SELECT t.TABLE_NAME , t.ENGINE , t.TABLE_ROWS ,t.AVG_ROW_LENGTH, 
t.INDEX_LENGTH FROM 
INFORMATION_SCHEMA.TABLES as t where t.TABLE_SCHEMA = 'YOURTABLENAMEHERE' 
order by t.TABLE_NAME ASC limit 10000;

How to generate random number with the specific length in python

To get a random 3-digit number:

from random import randint
randint(100, 999)  # randint is inclusive at both ends

(assuming you really meant three digits, rather than "up to three digits".)

To use an arbitrary number of digits:

from random import randint

def random_with_N_digits(n):
    range_start = 10**(n-1)
    range_end = (10**n)-1
    return randint(range_start, range_end)

print random_with_N_digits(2)
print random_with_N_digits(3)
print random_with_N_digits(4)

Output:

33
124
5127

How to clear PermGen space Error in tomcat

@AndreSmiley 's code of line worked for me.

only modification required is.

-XX:MaxPermSize=256m

"m" means MB.

Actually my application is kinda huge so i was advised to make it 1024m for performance.

Check if record exists from controller in Rails

business = Business.where(:user_id => current_user.id).first
if business.nil?
# no business found
else
# business.ceo = "me"
end

Comparing Class Types in Java

Check Class.java source code for equals()

public boolean equals(Object obj) {
  return this == obj;
}

Link a .css on another folder

I dont get it clearly, do you want to link an external css as the structure of files you defined above? If yes then just use the link tag :

    <link rel="stylesheet" type="text/css" href="file.css">

so basically for files that are under your website folder (folder containing your index) you directly call it. For each successive folder use the "/" for example in your case :

    <link rel="stylesheet" type="text/css" href="Fonts/Font1/file name">
    <link rel="stylesheet" type="text/css" href="Fonts/Font2/file name">

How can I iterate over the elements in Hashmap?

You should not map score to player. You should map player (or his name) to score:

Map<Player, Integer> player2score = new HashMap<Player, Integer>();

Then add players to map: int score = .... Player player = new Player(); player.setName("John"); // etc. player2score.put(player, score);

In this case the task is trivial:

int score = player2score.get(player);

Android RecyclerView addition & removal of items

  public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
private Context context;
private List<cardview_widgets> list;

public MyAdapter(Context context, List<cardview_widgets> list) {
    this.context = context;
    this.list = list;
}

@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
    View view = LayoutInflater.from(this.context).inflate(R.layout.fragment1_one_item,
            viewGroup, false);
    return new MyViewHolder(view);
}

public static class MyViewHolder extends RecyclerView.ViewHolder {
    TextView txtValue;
    TextView txtCategory;
    ImageView imgInorEx;
    ImageView imgCategory;
    TextView txtDate;

    public MyViewHolder(@NonNull View itemView) {
        super(itemView);
        txtValue= itemView.findViewById(R.id.id_values);
        txtCategory= itemView.findViewById(R.id.id_category);
        imgInorEx= itemView.findViewById(R.id.id_inorex);
        imgCategory= itemView.findViewById(R.id.id_imgcategory);
        txtDate= itemView.findViewById(R.id.id_date);
    }
}

@NonNull
@Override
public void onBindViewHolder(@NonNull final MyViewHolder myViewHolder, int i) {

    myViewHolder.txtValue.setText(String.valueOf(list.get(i).getValuee()));
    myViewHolder.txtCategory.setText(list.get(i).getCategory());
    myViewHolder.imgInorEx.setBackgroundColor(list.get(i).getImg_inorex());
    myViewHolder.imgCategory.setImageResource(list.get(i).getImg_category());
    myViewHolder.txtDate.setText(list.get(i).getDate());
    myViewHolder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            list.remove(myViewHolder.getAdapterPosition());
            notifyDataSetChanged();
            return false;
        }
    });
}

@Override
public int getItemCount() {
    return list.size();
}}      

i hope this help you.

Reset C int array to zero : the fastest way?

From memset():

memset(myarray, 0, sizeof(myarray));

You can use sizeof(myarray) if the size of myarray is known at compile-time. Otherwise, if you are using a dynamically-sized array, such as obtained via malloc or new, you will need to keep track of the length.

How to view DLL functions?

Use the free DLL Export Viewer, it is very easy to use.

Highlight text similar to grep, but don't filter out text

You can do it using only grep by:

  1. reading the file line by line
  2. matching a pattern in each line and highlighting pattern by grep
  3. if there is no match, echo the line as is

which gives you the following:

while read line ; do (echo $line | grep PATTERN) || echo $line  ; done < inputfile

Unable to create a constant value of type Only primitive types or enumeration types are supported in this context

This cannot work because ppCombined is a collection of objects in memory and you cannot join a set of data in the database with another set of data that is in memory. You can try instead to extract the filtered items personProtocol of the ppCombined collection in memory after you have retrieved the other properties from the database:

var persons = db.Favorites
    .Where(f => f.userId == userId)
    .Join(db.Person, f => f.personId, p => p.personId, (f, p) =>
        new // anonymous object
        {
            personId = p.personId,
            addressId = p.addressId,   
            favoriteId = f.favoriteId,
        })
    .AsEnumerable() // database query ends here, the rest is a query in memory
    .Select(x =>
        new PersonDTO
        {
            personId = x.personId,
            addressId = x.addressId,   
            favoriteId = x.favoriteId,
            personProtocol = ppCombined
                .Where(p => p.personId == x.personId)
                .Select(p => new PersonProtocol
                {
                    personProtocolId = p.personProtocolId,
                    activateDt = p.activateDt,
                    personId = p.personId
                })
                .ToList()
        });

Set output of a command as a variable (with pipes)

I find myself a tad amazed at the lack of what I consider the best answer to this question anywhere on the internet. I struggled for many years to find the answer. Many answers online come close, but none really answer it. The real answer is

(cmd & echo.) >2 & (set /p =)<2

The "secret sauce" being the "closely guarded coveted secret" that "echo." sends a CR/LF (ENTER/new line/0x0D0A). Otherwise, what I am doing here is redirecting the output of the first command to the standard error stream. I then redirect the standard error stream into the standard input stream for the "set /p =" command.

Example:

(echo foo & echo.) >2 & (set /p bar=)<2

DOM element to corresponding vue.js component

Since in Vue 2.0, no solution seems available, a clean solution that I found is to create a vue-id attribute, and also set it on the template. Then on created and beforeDestroy lifecycle these instances are updated on the global object.

Basically:

created: function() {
    this._id = generateUid();
    globalRepo[this._id] = this;
},

beforeDestroy: function() {
    delete globalRepo[this._id]
},

data: function() {
    return {
        vueId: this._id
    }
}

Is there a good Valgrind substitute for Windows?

You can take a look to the article Design and Implementation of an In-Game Memory Profiler in the book "Game Programming Gems 8".

It shows how to implement a low overhead semi-intrusive real-time memory profiler, source code provided in the CD-ROM.

enter image description here

Easiest way to open a download window without navigating away from the page

I've been looking for a good way to use javascript to initiate the download of a file, just as this question suggests. However these answers not been helpful. I then did some xbrowser testing and have found that an iframe works best on all modern browsers IE>8.

downloadUrl = "http://example.com/download/file.zip";
var downloadFrame = document.createElement("iframe"); 
downloadFrame.setAttribute('src',downloadUrl);
downloadFrame.setAttribute('class',"screenReaderText"); 
document.body.appendChild(downloadFrame); 

class="screenReaderText" is my class to style content that is present but not viewable.

css:

.screenReaderText { 
  border: 0; 
  clip: rect(0 0 0 0); 
  height: 1px; 
  margin: -1px; 
  overflow: hidden; 
  padding: 0; 
  position: absolute; 
  width: 1px; 
}

same as .visuallyHidden in html5boilerplate

I prefer this to the javascript window.open method because if the link is broken the iframe method simply doesn't do anything as opposed to redirecting to a blank page saying the file could not be opened.

window.open(downloadUrl, 'download_window', 'toolbar=0,location=no,directories=0,status=0,scrollbars=0,resizeable=0,width=1,height=1,top=0,left=0');
window.focus();

Remove characters except digits from string using Python?

Not a one liner but very simple:

buffer = ""
some_str = "aas30dsa20"

for char in some_str:
    if not char.isdigit():
        buffer += char

print( buffer )

Create thumbnail image

This is the code I'm using. Also works for .NET Core > 2.0 using System.Drawing.Common NuGet.

https://www.nuget.org/packages/System.Drawing.Common/

using System;
using System.Drawing;

class Program
{
    static void Main()
    {
        const string input = "C:\\background1.png";
        const string output = "C:\\thumbnail.png";

        // Load image.
        Image image = Image.FromFile(input);

        // Compute thumbnail size.
        Size thumbnailSize = GetThumbnailSize(image);

        // Get thumbnail.
        Image thumbnail = image.GetThumbnailImage(thumbnailSize.Width,
            thumbnailSize.Height, null, IntPtr.Zero);

        // Save thumbnail.
        thumbnail.Save(output);
    }

    static Size GetThumbnailSize(Image original)
    {
        // Maximum size of any dimension.
        const int maxPixels = 40;

        // Width and height.
        int originalWidth = original.Width;
        int originalHeight = original.Height;

        // Return original size if image is smaller than maxPixels
        if (originalWidth <= maxPixels || originalHeight <= maxPixels)
        {
            return new Size(originalWidth, originalHeight);
        }   

        // Compute best factor to scale entire image based on larger dimension.
        double factor;
        if (originalWidth > originalHeight)
        {
            factor = (double)maxPixels / originalWidth;
        }
        else
        {
            factor = (double)maxPixels / originalHeight;
        }

        // Return thumbnail size.
        return new Size((int)(originalWidth * factor), (int)(originalHeight * factor));
    }
}

Source:

https://www.dotnetperls.com/getthumbnailimage

Customize list item bullets using CSS

I just found a solution that I think works really well and gets around all of the pitfalls of custom symbols. The main problem with the li:before solution is that if list-items are longer than one line will not indent properly after the first line of text. By using text-indent with a negative padding we can circumvent that problem and have all the lines aligned properly:

ul{
    padding-left: 0; // remove default padding
}

li{
    list-style-type: none;  // remove default styles
    padding-left: 1.2em;    
    text-indent:-1.2em;     // remove padding on first line
}

li::before{
    margin-right:     0.5em; 
    width:            0.7em; // margin-right and width must add up to the negative indent-value set above
    height:           0.7em;

    display:          inline-block;
    vertical-align:   middle;
    border-radius: 50%;
    background-color: orange;
    content:          ' '
}

How to drop columns using Rails migration

For older versions of Rails

ruby script/generate migration RemoveFieldNameFromTableName field_name:datatype

For Rails 3 and up

rails generate migration RemoveFieldNameFromTableName field_name:datatype

Socket File "/var/pgsql_socket/.s.PGSQL.5432" Missing In Mountain Lion (OS X Server)

File permissions are restrictive on the Postgres db owned by the Mac OS. These permissions are reset after reboot, or restart of Postgres: e.g. serveradmin start postgres.

So, temporarily reset the permissions or ownership:

sudo chmod o+rwx /var/pgsql_socket/.s.PGSQL.5432
sudo chown "webUser"  /var/pgsql_socket/.s.PGSQL.5432

Permissions resetting is not secure, so install a version of the db that you own for a solution.

Undefined reference to pthread_create in Linux

In Anjuta, go to the Build menu, then Configure Project. In the Configure Options box, add:

LDFLAGS='-lpthread'

Hope it'll help somebody too...

How to roundup a number to the closest ten?

the second argument in ROUNDUP, eg =ROUNDUP(12345.6789,3) refers to the negative of the base-10 column with that power of 10, that you want rounded up. eg 1000 = 10^3, so to round up to the next highest 1000, use ,-3)

=ROUNDUP(12345.6789,-4) = 20,000
=ROUNDUP(12345.6789,-3) = 13,000
=ROUNDUP(12345.6789,-2) = 12,400
=ROUNDUP(12345.6789,-1) = 12,350
=ROUNDUP(12345.6789,0) = 12,346
=ROUNDUP(12345.6789,1) = 12,345.7
=ROUNDUP(12345.6789,2) = 12,345.68
=ROUNDUP(12345.6789,3) = 12,345.679

So, to answer your question: if your value is in A1, use =ROUNDUP(A1,-1)

UL has margin on the left

The <ul> element has browser inherent padding & margin by default. In your case, Use

#footer ul {
    margin: 0; /* To remove default bottom margin */ 
    padding: 0; /* To remove default left padding */
}

or a CSS browser reset ( https://cssreset.com/ ) to deal with this.

Print empty line?

Python's print function adds a newline character to its input. If you give it no input it will just print a newline character

print()

Will print an empty line. If you want to have an extra line after some text you're printing, you can a newline to your text

my_str = "hello world"
print(my_str + "\n")

If you're doing this a lot, you can also tell print to add 2 newlines instead of just one by changing the end= parameter (by default end="\n")

print("hello world", end="\n\n")

But you probably don't need this last method, the two before are much clearer.

How to replace all double quotes to single quotes using jquery?

You can also use replaceAll(search, replaceWith) [MDN].

Then, make sure you have a string by wrapping one type of quotes by a different type:

 'a "b" c'.replaceAll('"', "'")
 // result: "a 'b' c"
    
 'a "b" c'.replaceAll(`"`, `'`)
 // result: "a 'b' c"

 // Using RegEx. You MUST use a global RegEx(Meaning it'll match all occurrences).
 'a "b" c'.replaceAll(/\"/g, "'")
 // result: "a 'b' c"

Important(!) if you choose regex:

when using a regexp you have to set the global ("g") flag; otherwise, it will throw a TypeError: "replaceAll must be called with a global RegExp".

Android Studio doesn't start, fails saying components not installed

If are you using Linux, I noticed that the Android Studio cannot be run with JDK 8. You have to download open Jdk 7 and press alt + shift + t and type:

sudo apt-get install openjdk-7-jre 

When u have downloaded jdk 7 go to terminal then go to android-studio/bin then type

sudo sh ./studio.sh 

Excel: Can I create a Conditional Formula based on the Color of a Cell?

You can use this function (I found it here: http://excelribbon.tips.net/T010780_Colors_in_an_IF_Function.html):

Function GetFillColor(Rng As Range) As Long
    GetFillColor = Rng.Interior.ColorIndex
End Function

Here is an explanation, how to create user-defined functions: http://www.wikihow.com/Create-a-User-Defined-Function-in-Microsoft-Excel

In your worksheet, you can use the following: =GetFillColor(B5)

Open fancybox from function

The answers seems a bit over complicated. I hope I didn't misunderstand the question.

If you simply want to open a fancy box from a click to an "A" tag. Just set your html to

<a id="my_fancybox" href="#contentdiv">click me</a>

The contents of your box will be inside of a div with id "contentdiv" and in your javascript you can initialize fancybox like this:

$('#my_fancybox').fancybox({
    'autoScale': true,
    'transitionIn': 'elastic',
    'transitionOut': 'elastic',
    'speedIn': 500,
    'speedOut': 300,
    'autoDimensions': true,
    'centerOnScroll': true,
});

This will show a fancybox containing "contentdiv" when your anchor tag is clicked.

mailto link with HTML body

Thunderbird supports html-body: mailto:[email protected]?subject=Me&html-body=<b>ME</b>

How to make MySQL table primary key auto increment with some prefix

I know it is late but I just want to share on what I have done for this. I'm not allowed to add another table or trigger so I need to generate it in a single query upon insert. For your case, can you try this query.

CREATE TABLE YOURTABLE(
IDNUMBER VARCHAR(7) NOT NULL PRIMARY KEY,
ENAME VARCHAR(30) not null
);

Perform a select and use this select query and save to the parameter @IDNUMBER

(SELECT IFNULL
     (CONCAT('LHPL',LPAD(
       (SUBSTRING_INDEX
        (MAX(`IDNUMBER`), 'LHPL',-1) + 1), 5, '0')), 'LHPL001')
    AS 'IDNUMBER' FROM YOURTABLE ORDER BY `IDNUMBER` ASC)

And then Insert query will be :

INSERT INTO YOURTABLE(IDNUMBER, ENAME) VALUES 
(@IDNUMBER, 'EMPLOYEE NAME');

The result will be the same as the other answer but the difference is, you will not need to create another table or trigger. I hope that I can help someone that have a same case as mine.

Why is HttpContext.Current null?

try to implement Application_AuthenticateRequest instead of Application_Start.

this method has an instance for HttpContext.Current, unlike Application_Start (which fires very soon in app lifecycle, soon enough to not hold a HttpContext.Current object yet).

hope that helps.

How can I find the dimensions of a matrix in Python?

If you are using NumPy arrays, shape can be used. For example

  >>> a = numpy.array([[[1,2,3],[1,2,3]],[[12,3,4],[2,1,3]]])
  >>> a
  array([[[ 1,  2,  3],
         [ 1,  2,  3]],

         [[12,  3,  4],
         [ 2,  1,  3]]])
 >>> a.shape
 (2, 2, 3)

How to get string objects instead of Unicode from JSON?

This is late to the game, but I built this recursive caster. It works for my needs and I think it's relatively complete. It may help you.

def _parseJSON(self, obj):
    newobj = {}

    for key, value in obj.iteritems():
        key = str(key)

        if isinstance(value, dict):
            newobj[key] = self._parseJSON(value)
        elif isinstance(value, list):
            if key not in newobj:
                newobj[key] = []
                for i in value:
                    newobj[key].append(self._parseJSON(i))
        elif isinstance(value, unicode):
            val = str(value)
            if val.isdigit():
                val = int(val)
            else:
                try:
                    val = float(val)
                except ValueError:
                    val = str(val)
            newobj[key] = val

    return newobj

Just pass it a JSON object like so:

obj = json.loads(content, parse_float=float, parse_int=int)
obj = _parseJSON(obj)

I have it as a private member of a class, but you can repurpose the method as you see fit.

Concatenating Column Values into a Comma-Separated List

DECLARE @CarList nvarchar(max);
SET @CarList = N'';
SELECT @CarList+=CarName+N','
FROM dbo.CARS;
SELECT LEFT(@CarList,LEN(@CarList)-1);

Thanks are due to whoever on SO showed me the use of accumulating data during a query.

Is there a way to check if a file is in use?

Aside from working 3-liners and just for reference: If you want the full blown information - there is a little project on Microsoft Dev Center:

https://code.msdn.microsoft.com/windowsapps/How-to-know-the-process-704839f4

From the Introduction:

The C# sample code developed in .NET Framework 4.0 would help in finding out which is the process that is having a lock on a file. RmStartSession function which is included in rstrtmgr.dll has been used to create a restart manager session and according to the return result a new instance of Win32Exception object is created. After registering the resources to a Restart Manager session via RmRegisterRescources function, RmGetList function is invoked to check what are the applications are using a particular file by enumerating the RM_PROCESS_INFO array.

It works by connecting to the "Restart Manager Session".

The Restart Manager uses the list of resources registered with the session to determine which applications and services must be shut down and restarted. Resources can be identified by filenames, service short names, or RM_UNIQUE_PROCESS structures that describe running applications.

It might be a little overengineered for your particular needs... But if that is what you want, go ahead and grab the vs-project.

Python 3.4.0 with MySQL database

sudo apt-get install python3-dev
sudo apt-get install libmysqlclient-dev
sudo apt-get install zlib1g-dev
sudo pip3 install mysqlclient

that worked for me!

How to pass ArrayList of Objects from one to another activity using Intent in android?

You must need to also implement Parcelable interface and must add writeToParcel method to your Questions class with Parcel argument in Constructor in addition to Serializable. otherwise app will crash.

Pull request vs Merge request

GitLab 12.1 (July 2019) introduces a difference:

"Merge Requests for Confidential Issues"

When discussing, planning and resolving confidential issues, such as security vulnerabilities, it can be particularly challenging for open source projects to remain efficient since the Git repository is public.

https://about.gitlab.com/images/12_1/mr-confidential.png

As of 12.1, it is now possible for confidential issues in a public project to be resolved within a streamlined workflow using the Create confidential merge request button, which helps you create a merge request in a private fork of the project.

See "Confidential issues" from issue 58583.

A similar feature exists in GitHub, but involves the creation of a special private fork, called "maintainer security advisory".


GitLab 13.5 (Oct. 2020) will add reviewers, which was already available for GitHub before.

Android Studio update -Error:Could not run build action using Gradle distribution

Try updating gradle dependency to 2.4. For that you need to go to File -> Project Structure -> Project -> Gradle version.

There you need to change from 2.2.1 to 2.4. Wait for new gradle version to be downloaded.

And you are ready to go.