Programs & Examples On #Post redirect get

Post/Redirect/Get (PRG) is a web development design pattern that prevents some duplicate form submissions, creating a more intuitive interface for user agents (users). PRG implements bookmarks and the refresh button in a predictable way that does not create duplicate form submissions.

Asp.net MVC ModelState.Clear

Update:

  • This is not a bug.
  • Please stop returning View() from a POST action. Use PRG instead and redirect to a GET if the action is a success.
  • If you are returning a View() from a POST action, do it for form validation, and do it the way MVC is designed using the built in helpers. If you do it this way then you shouldn't need to use .Clear()
  • If you're using this action to return ajax for a SPA, use a web api controller and forget about ModelState since you shouldn't be using it anyway.

Old answer:

ModelState in MVC is used primarily to describe the state of a model object largely with relation to whether that object is valid or not. This tutorial should explain a lot.

Generally you should not need to clear the ModelState as it is maintained by the MVC engine for you. Clearing it manually might cause undesired results when trying to adhere to MVC validation best practises.

It seems that you are trying to set a default value for the title. This should be done when the model object is instantiated (domain layer somewhere or in the object itself - parameterless ctor), on the get action such that it goes down to the page the 1st time or completely on the client (via ajax or something) so that it appears as if the user entered it and it comes back with the posted forms collection. Some how your approach of adding this value on the receiving of a forms collection (in the POST action // Edit) is causing this bizarre behaviour that might result in a .Clear() appearing to work for you. Trust me - you don't want to be using the clear. Try one of the other ideas.

How to hide html source & disable right click and text copy?

$(document).ready(function() { 
 `$(document).bind("contextmenu copy paste cut drag drop ",function(e {`return false;`});`

How to get data from observable in angular2

this.myService.getConfig().subscribe(
  (res) => console.log(res),
  (err) => console.log(err),
  () => console.log('done!')
);

How to fix error "ERROR: Command errored out with exit status 1: python." when trying to install django-heroku using pip

You need to add the package containing the executable pg_config.

A prior answer should have details you need: pg_config executable not found

Tool to monitor HTTP, TCP, etc. Web Service traffic

I tried Fiddler with its reverse proxy ability which is mentioned by @marxidad and it seems to be working fine, since Fiddler is a familiar UI for me and has the ability to show request/responses in various formats (i.e. Raw, XML, Hex), I accept it as an answer to this question. One thing though. I use WCF and I got the following exception with reverse proxy thing:

The message with To 'http://localhost:8000/path/to/service' cannot be processed at the receiver, due to an AddressFilter mismatch at the EndpointDispatcher. Check that the sender and receiver's EndpointAddresses agree

I have figured out (thanks Google, erm.. I mean Live Search :p) that this is because my endpoint addresses on server and client differs by port number. If you get the same exception consult to the following MSDN forum message:

http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2302537&SiteID=1

which recommends to use clientVia Endpoint Behavior explained in following MSDN article:

http://msdn.microsoft.com/en-us/magazine/cc163412.aspx

DateTime format to SQL format using C#

Why not skip the string altogether :

SqlDateTime myDateTime = DateTime.Now;

Setting width to wrap_content for TextView through code

A little update on this post: if you are using ktx within your Android project, there is a little helper method that makes updating LayoutParams a lot easier.

If you want to update e.g. only the width you can do that with the following line in Kotlin.

tv.updateLayoutParams { width = WRAP_CONTENT }

Side-by-side plots with ggplot2

You can use the following multiplot function from Winston Chang's R cookbook

multiplot(plot1, plot2, cols=2)

multiplot <- function(..., plotlist=NULL, cols) {
    require(grid)

    # Make a list from the ... arguments and plotlist
    plots <- c(list(...), plotlist)

    numPlots = length(plots)

    # Make the panel
    plotCols = cols                          # Number of columns of plots
    plotRows = ceiling(numPlots/plotCols) # Number of rows needed, calculated from # of cols

    # Set up the page
    grid.newpage()
    pushViewport(viewport(layout = grid.layout(plotRows, plotCols)))
    vplayout <- function(x, y)
        viewport(layout.pos.row = x, layout.pos.col = y)

    # Make each plot, in the correct location
    for (i in 1:numPlots) {
        curRow = ceiling(i/plotCols)
        curCol = (i-1) %% plotCols + 1
        print(plots[[i]], vp = vplayout(curRow, curCol ))
    }

}

How to join two sets in one line without using "|"

Suppose you have 2 lists

 A = [1,2,3,4]
 B = [3,4,5,6]

so you can find A Union B as follow

 union = set(A).union(set(B))

also if you want to find intersection and non-intersection you do that as follow

 intersection = set(A).intersection(set(B))
 non_intersection = union - intersection

How to compare two List<String> to each other?

If you want to check that the elements inside the list are equal and in the same order, you can use SequenceEqual:

if (a1.SequenceEqual(a2))

See it working online: ideone

How to find an object in an ArrayList by property

Following with Oleg answer, if you want to find ALL objects in a List filtered by a property, you could do something like:

//Search into a generic list ALL items with a generic property
public final class SearchTools {
       public static <T> List<T> findByProperty(Collection<T> col, Predicate<T> filter) {
           List<T> filteredList = (List<T>) col.stream().filter(filter).collect(Collectors.toList());
           return filteredList;
     }

//Search in the list "listItems" ALL items of type "Item" with the specific property "iD_item=itemID"
public static final class ItemTools {
         public static List<Item> findByItemID(Collection<Item> listItems, String itemID) {
             return SearchTools.findByProperty(listItems, item -> itemID.equals(item.getiD_Item()));
         }
     }
}

and similarly if you want to filter ALL items in a HashMap with a certain Property

//Search into a MAP ALL items with a given property
public final class SearchTools {
       public static <T> HashMap<String,T> filterByProperty(HashMap<String,T> completeMap, Predicate<? super Map.Entry<String,T>> filter) {
           HashMap<String,T> filteredList = (HashMap<String,T>) completeMap.entrySet().stream()
                                .filter(filter)
                                .collect(Collectors.toMap(map -> map.getKey(), map -> map.getValue()));
           return filteredList;
     }

     //Search into the MAP ALL items with specific properties
public static final class ItemTools {

        public static HashMap<String,Item> filterByParentID(HashMap<String,Item> mapItems, String parentID) {
            return SearchTools.filterByProperty(mapItems, mapItem -> parentID.equals(mapItem.getValue().getiD_Parent()));
        }

        public static HashMap<String,Item> filterBySciName(HashMap<String,Item> mapItems, String sciName) {
            return SearchTools.filterByProperty(mapItems, mapItem -> sciName.equals(mapItem.getValue().getSciName()));
        }
    }

Nginx 403 error: directory index of [folder] is forbidden

Here is the config that works:

server {
    server_name www.mysite2.name;
    return 301 $scheme://mysite2.name$request_uri;
}
server {
    #This config is based on https://github.com/daylerees/laravel-website-configs/blob/6db24701073dbe34d2d58fea3a3c6b3c0cd5685b/nginx.conf
    server_name mysite2.name;

     # The location of our project's public directory.
    root /usr/share/nginx/mysite2/live/public/;

     # Point index to the Laravel front controller.
    index           index.php;

    location / {
        # URLs to attempt, including pretty ones.
        try_files   $uri $uri/ /index.php?$query_string;
    }

    # Remove trailing slash to please routing system.
    if (!-d $request_filename) {
            rewrite     ^/(.+)/$ /$1 permanent;
    }

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    location ~ \.php$ {
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
    #   # NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini
    #   # With php5-fpm:
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_param                   SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }

}

Then the only output in the browser was a Laravel error: “Whoops, looks like something went wrong.”

Do NOT run chmod -R 777 app/storage (note). Making something world-writable is bad security.

chmod -R 755 app/storage works and is more secure.

curl_exec() always returns false

This happened to me yesterday and in my case was because I was following a PDF manual to develop some module to communicate with an API and while copying the link directly from the manual, for some odd reason, the hyphen from the copied link was in a different encoding and hence the curl_exec() was always returning false because it was unable to communicate with the server.

It took me a couple hours to finally understand the diference in the characters bellow:

https://www.e-example.com/api
https://www.e-example.com/api

Every time I tried to access the link directly from a browser it converted to something likehttps://www.xn--eexample-0m3d.com/api.

It may seem to you that they are equal but if you check the encoding of the hyphens here you'll see that the first hyphen is a unicode characters U+2010 and the other is a U+002D.

Hope this helps someone.

Merge two dataframes by index

Use merge, which is inner join by default:

pd.merge(df1, df2, left_index=True, right_index=True)

Or join, which is left join by default:

df1.join(df2)

Or concat, which is outer join by default:

pd.concat([df1, df2], axis=1)

Samples:

df1 = pd.DataFrame({'a':range(6),
                    'b':[5,3,6,9,2,4]}, index=list('abcdef'))

print (df1)
   a  b
a  0  5
b  1  3
c  2  6
d  3  9
e  4  2
f  5  4

df2 = pd.DataFrame({'c':range(4),
                    'd':[10,20,30, 40]}, index=list('abhi'))

print (df2)
   c   d
a  0  10
b  1  20
h  2  30
i  3  40

#default inner join
df3 = pd.merge(df1, df2, left_index=True, right_index=True)
print (df3)
   a  b  c   d
a  0  5  0  10
b  1  3  1  20

#default left join
df4 = df1.join(df2)
print (df4)
   a  b    c     d
a  0  5  0.0  10.0
b  1  3  1.0  20.0
c  2  6  NaN   NaN
d  3  9  NaN   NaN
e  4  2  NaN   NaN
f  5  4  NaN   NaN

#default outer join
df5 = pd.concat([df1, df2], axis=1)
print (df5)
     a    b    c     d
a  0.0  5.0  0.0  10.0
b  1.0  3.0  1.0  20.0
c  2.0  6.0  NaN   NaN
d  3.0  9.0  NaN   NaN
e  4.0  2.0  NaN   NaN
f  5.0  4.0  NaN   NaN
h  NaN  NaN  2.0  30.0
i  NaN  NaN  3.0  40.0

how to use ng-option to set default value of select element

<select id="itemDescFormId" name="itemDescFormId" size="1" ng-model="prop" ng-change="update()">
    <option value="">English(EN)</option>
    <option value="23">Corsican(CO)</option>
    <option value="43">French(FR)</option>
    <option value="16">German(GR)</option>

Just add option with empty value. It will work.

DEMO Plnkr

How do I get a file's directory using the File object?

File directory = new File("Enter any 
                directory name or file name");
boolean isDirectory = directory.isDirectory();
if (isDirectory) {
  // It returns true if directory is a directory.
  System.out.println("the name you have entered 
         is a directory  : "  +    directory);  
  //It returns the absolutepath of a directory.
  System.out.println("the path is "  + 
              directory.getAbsolutePath());
} else {
  // It returns false if directory is a file.
  System.out.println("the name you have
   entered is a file  : " +   directory);
  //It returns the absolute path of a file.
  System.out.println("the path is "  +  
            file.getParent());
}

No Application Encryption Key Has Been Specified

You can generate Application Encryption Key using this command:

php artisan key:generate

Then, create a cache file for faster configuration loading using this command:

php artisan config:cache

Or, serve the application on the PHP development server using this command:

php artisan serve

That's it!

Evaluate list.contains string in JSTL

You need to use the fn:contains() or fn:containsIgnoreCase() function.

<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>

...

 <c:if test="${not fn:containsIgnoreCase(mylist, 'apple')}">
        <p>Doesn't contain 'apple'</p>
    </c:if>

or

<c:if test="${not fn:contains(mylist, 'Apple')}">
            <p>Contains 'Apple'</p>
        </c:if>

Note: This will work like mylist.toString().contains("apple") and if this is not what you are looking for better use a other approach.

How to reset a select element with jQuery

$('#baba').prop('selectedIndex',-1);

What is a regex to match ONLY an empty string?

I believe Python is the only widely used language that doesn't support \z in this way (yet). There are Python bindings for Russ Cox / Google's super fast re2 C++ library that can be "dropped in" as a replacement for the bundled re.

There's an excellent discussion (with workarounds) for this at Perl Compatible Regular Expression (PCRE) in Python, here on SO.

python
Python 2.7.11 (default, Jan 16 2016, 01:14:05) 
[GCC 4.2.1 Compatible FreeBSD Clang 3.4.1 on freebsd10
Type "help", "copyright", "credits" or "license" for more information.
>>> import re2 as re
>>> 
>>> re.match(r'\A\z', "")
<re2.Match object at 0x805d97170>

@tchrist's answer is worth the read.

What's the quickest way to multiply multiple cells by another number?

  1. Enter the multiplier in a cell
  2. Copy that cell to the clipboard
  3. Select the range you want to multiply by the multiplier
  4. (Excel 2003 or earlier) Choose Edit | Paste Special | Multiply

    (Excel 2007 or later) Click on the Paste down arrow | Paste Special | Multiply

Passing variables to the next middleware using next() in Express.js

Attach your variable to the req object, not res.

Instead of

res.somevariable = variable1;

Have:

req.somevariable = variable1;

As others have pointed out, res.locals is the recommended way of passing data through middleware.

Seeing if data is normally distributed in R

The Anderson-Darling test is also be useful.

library(nortest)
ad.test(data)

HTML embed autoplay="false", but still plays automatically

the below codes helped me with the same problem. Let me know if it helped.

<!DOCTYPE html>
<html>
<body>


<audio controls>

<source src="YOUR AUDIO FILE" type="audio/mpeg">
Your browser does not support the audio element.
</audio>



</body>
</html>

Deleting a file in VBA

set a reference to the Scripting.Runtime library and then use the FileSystemObject:

Dim fso as New FileSystemObject, aFile as File

if (fso.FileExists("PathToFile")) then
    aFile = fso.GetFile("PathToFile")
    aFile.Delete
End if

Call a stored procedure with parameter in c#

public void myfunction(){
        try
        {
            sqlcon.Open();
            SqlCommand cmd = new SqlCommand("sp_laba", sqlcon);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.ExecuteNonQuery();
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        finally
        {
            sqlcon.Close();
        }
}

Moment.js with Vuejs

vue-moment

very nice plugin for vue project and works very smoothly with the components and existing code. Enjoy the moments...

// in your main.js
Vue.use(require('vue-moment'));
// and use in component
{{'2019-10-03 14:02:22' | moment("calendar")}}
// or like this
{{created_at | moment("calendar")}}

C# Telnet Library

I doubt very much a telnet library will ever be part of the .Net BCL, although you do have almost full socket support so it wouldnt be too hard to emulate a telnet client, Telnet in its general implementation is a legacy and dying technology that where exists generally sits behind a nice new modern facade. In terms of Unix/Linux variants you'll find that out the box its SSH and enabling telnet is generally considered poor practice.

You could check out: http://granados.sourceforge.net/ - SSH Library for .Net http://www.tamirgal.com/home/dev.aspx?Item=SharpSsh

You'll still need to put in place your own wrapper to handle events for feeding in input in a scripted manner.

Creating a very simple linked list

A Linked List, at its core is a bunch of Nodes linked together.

So, you need to start with a simple Node class:

public class Node {
    public Node next;
    public Object data;
}

Then your linked list will have as a member one node representing the head (start) of the list:

public class LinkedList {
    private Node head;
}

Then you need to add functionality to the list by adding methods. They usually involve some sort of traversal along all of the nodes.

public void printAllNodes() {
    Node current = head;
    while (current != null) 
    {
        Console.WriteLine(current.data);
        current = current.next;
    }
}

Also, inserting new data is another common operation:

public void Add(Object data) {
    Node toAdd = new Node();
    toAdd.data = data;
    Node current = head;
    // traverse all nodes (see the print all nodes method for an example)
    current.next = toAdd;
}

This should provide a good starting point.

How can I bind a background color in WPF/XAML?

You assigned a string "Red". Your Background property should be of type Color:

using System.Windows;
using System.ComponentModel;

namespace TestBackground88238
{
    public partial class Window1 : Window, INotifyPropertyChanged
    {

        #region ViewModelProperty: Background
        private Color _background;
        public Color Background
        {
            get
            {
                return _background;
            }

            set
            {
                _background = value;
                OnPropertyChanged("Background");
            }
        }
        #endregion

        //...//
}

Then you can use the binding to the SolidColorBrush like this:

public Window1()
{
    InitializeComponent();
    DataContext = this;

    Background = Colors.Red;
    Message = "This is the title, the background should be " + Background.toString() + ".";

}

not 100% sure about the .toString() method on Color-Object. It might tell you it is a Color-Class, but you will figur this out ;)

Get current directory name (without full path) in a Bash script

You can use a combination of pwd and basename. E.g.

#!/bin/bash

CURRENT=`pwd`
BASENAME=`basename "$CURRENT"`

echo "$BASENAME"

exit;

How to read a file without newlines?

def getText():
    file=open("ex1.txt","r");

    names=file.read().split("\n");
    for x,word in enumerate(names):
        if(len(word)>=20):
            return 0;
            print "length of ",word,"is over 20"
            break;
        if(x==20):
            return 0;
            break;
    else:
        return names;


def show(names):
    for word in names:
        len_set=len(set(word))
        print word," ",len_set


for i in range(1):

    names=getText();
    if(names!=0):
        show(names);
    else:
        break;

How to rename a directory/folder on GitHub website?

Go into your directory and click on 'Settings' next to the little cog. There is a field to rename your directory.

How can I switch to a tag/branch in hg?

Once you have cloned the repo, you have everything: you can then hg up branchname or hg up tagname to update your working copy.

UP: hg up is a shortcut of hg update, which also has hg checkout alias for people with git habits.

How to sync with a remote Git repository?

For Linux:

git add * 
git commit -a --message "Initial Push All"
git push -u origin --all

Getting URL parameter in java and extract a specific text from that URL

My solution mayble not good

        String url = "https://www.youtube.com/watch?param=test&v=XcHJMiSy_1c&lis=test";
        int start = url.indexOf("v=")+2;
        // int start = url.indexOf("list=")+5; **5 is length of ("list=")**
        int end = url.indexOf("&", start);

        end = (end == -1 ? url.length() : end); 

        System.out.println(url.substring(start, end));
        // result: XcHJMiSy_1c

work fine with:

  • https://www.youtube.com/watch?param=test&v=XcHJMiSy_1c&lis=test
  • https://www.youtube.com/watch?v=XcHJMiSy_1c

Best practices for circular shift (rotate) operations in C++

another suggestion

template<class T>
inline T rotl(T x, unsigned char moves){
    unsigned char temp;
    __asm{
        mov temp, CL
        mov CL, moves
        rol x, CL
        mov CL, temp
    };
    return x;
}

Android ImageView Animation

Inside the element put:

android:repeatCount="infinite"

Convert Swift string to array

You can also create an extension:

var strArray = "Hello, playground".Letterize()

extension String {
    func Letterize() -> [String] {
        return map(self) { String($0) }
    }
}

The application has stopped unexpectedly: How to Debug?

I'm an Eclipse/Android beginner as well, but hopefully my simple debugging process can help...

You set breakpoints in Eclipse by right-clicking next to the line you want to break at and selecting "Toggle Breakpoint". From there you'll want to select "Debug" rather than the standard "Run", which will allow you to step through and so on. Use the filters provided by LogCat (referenced in your tutorial) so you can target the messages you want rather than wading through all the output. That will (hopefully) go a long way in helping you make sense of your errors.

As for other good tutorials, I was searching around for a few myself, but didn't manage to find any gems yet.

Pip Install not installing into correct directory?

This is what worked for me on Windows. The cause being multiple python installations

  1. update path with correct python
  2. uninstall pip using python -m pip uninstall pip setuptools
  3. restart windows didn't work until a restart

How to use JavaScript regex over multiple lines?

[\\w\\s]*

This one was beyond helpful for me, especially for matching multiple things that include new lines, every single other answer ended up just grouping all of the matches together.

How to set-up a favicon?

With the introduction of (i|android|windows)phones, things have changed, and to get a correct and complete solution that works on any device is really time-consuming.

You can have a peek at https://realfavicongenerator.net/favicon_compatibility or http://caniuse.com/#search=favicon to get an idea on the best way to get something that works on any device.

You should have a look at http://realfavicongenerator.net/ to automate a large part of this work, and probably at https://github.com/audreyr/favicon-cheat-sheet to understand how it works (even if this latter resource hasn't been updated in a loooong time).

One complete solution requires to add to you header the following (with the corresponding pictures and files, of course) :

<link rel="shortcut icon" href="favicon.ico">
<link rel="apple-touch-icon" sizes="57x57" href="apple-touch-icon-57x57.png">
<link rel="apple-touch-icon" sizes="114x114" href="apple-touch-icon-114x114.png">
<link rel="apple-touch-icon" sizes="72x72" href="apple-touch-icon-72x72.png">
<link rel="apple-touch-icon" sizes="144x144" href="apple-touch-icon-144x144.png">
<link rel="apple-touch-icon" sizes="60x60" href="apple-touch-icon-60x60.png">
<link rel="apple-touch-icon" sizes="120x120" href="apple-touch-icon-120x120.png">
<link rel="apple-touch-icon" sizes="76x76" href="apple-touch-icon-76x76.png">
<link rel="apple-touch-icon" sizes="152x152" href="apple-touch-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="apple-touch-icon-180x180.png">
<link rel="icon" type="image/png" href="favicon-192x192.png" sizes="192x192">
<link rel="icon" type="image/png" href="favicon-160x160.png" sizes="160x160">
<link rel="icon" type="image/png" href="favicon-96x96.png" sizes="96x96">
<link rel="icon" type="image/png" href="favicon-16x16.png" sizes="16x16">
<link rel="icon" type="image/png" href="favicon-32x32.png" sizes="32x32">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="mstile-144x144.png">
<meta name="msapplication-config" content="browserconfig.xml">

In June 2016, RealFaviconGenerator claimed that the following 5 lines of code were supporting as many devices as the previous 18 lines:

<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
<link rel="icon" type="image/png" href="/favicon-32x32.png" sizes="32x32">
<link rel="icon" type="image/png" href="/favicon-16x16.png" sizes="16x16">
<link rel="manifest" href="/manifest.json">
<link rel="mask-icon" href="/safari-pinned-tab.svg" color="#5bbad5">
<meta name="theme-color" content="#ffffff">

Looping over arrays, printing both index and value

You would find the array keys with "${!foo[@]}" (reference), so:

for i in "${!foo[@]}"; do 
  printf "%s\t%s\n" "$i" "${foo[$i]}"
done

Which means that indices will be in $i while the elements themselves have to be accessed via ${foo[$i]}

Total number of items defined in an enum

A nifty trick I saw in a C answer to this question, just add a last element to the enum and use it to tell how many elements are in the enum:

enum MyType {
  Type1,
  Type2,
  Type3,
  NumberOfTypes
}

In the case where you're defining a start value other than 0, you can use NumberOfTypes - Type1 to ascertain the number of elements.

I'm unsure if this method would be faster than using Enum, and I'm also not sure if it would be considered the proper way to do this, since we have Enum to ascertain this information for us.

How to fully clean bin and obj folders within Visual Studio?

I store my finished VS projects by saving only source code.

I delete BIN, DEBUG, RELEASE, OBJ, ARM and .vs folders from all projects.

This reduces the size of the project considerably. The project

must be rebuilt when pulled out of storage.

Search input with an icon Bootstrap 4

Here is an input box with a search icon on the right.

  <div class="input-group">
      <input class="form-control py-2 border-right-0 border" type="search" placeholder="Search">
      <div class="input-group-append">
          <div class="input-group-text" id="btnGroupAddon2"><i class="fa fa-search"></i></div>
      </div>
  </div>

Here is an input box with a search icon on the left.

  <div class="input-group">
      <div class="input-group-prepend">
          <div class="input-group-text" id="btnGroupAddon2"><i class="fa fa-search"></i></div>
      </div>
      <input class="form-control py-2 border-right-0 border" type="search" placeholder="Search">
  </div>

pass JSON to HTTP POST Request

I feel

var x = request.post({
       uri: config.uri,
       json: reqData
    });

Defining like this will be the effective way of writing your code. And application/json should be automatically added. There is no need to specifically declare it.

android adb turn on wifi via adb

You should start the WiFi activity from adb then simulate inputs:

adb shell am start -a android.intent.action.MAIN -n com.android.settings/.wifi.WifiSettings
adb shell input keyevent 20 && adb shell input keyevent 23

Here is the list of adb inputs: #7789826

I'm not sure if those keyevents are the right one for your case, but I think it will do. It simulated a "down" to select the first checkbox, then an "enter".

How is Java platform-independent when it needs a JVM to run?

Typically, the compiled code is the exact set of instructions the CPU requires to "execute" the program. In Java, the compiled code is an exact set of instructions for a "virtual CPU" which is required to work the same on every physical machine.

So, in a sense, the designers of the Java language decided that the language and the compiled code was going to be platform independent, but since the code eventually has to run on a physical platform, they opted to put all the platform dependent code in the JVM.

This requirement for a JVM is in contrast to your Turbo C example. With Turbo C, the compiler will produce platform dependent code, and there is no need for a JVM work-alike because the compiled Turbo C program can be executed by the CPU directly.

With Java, the CPU executes the JVM, which is platform dependent. This running JVM then executes the Java bytecode which is platform independent, provided that you have a JVM available for it to execute upon. You might say that writing Java code, you don't program for the code to be executed on the physical machine, you write the code to be executed on the Java Virtual Machine.

The only way that all this Java bytecode works on all Java virtual machines is that a rather strict standard has been written for how Java virtual machines work. This means that no matter what physical platform you are using, the part where the Java bytecode interfaces with the JVM is guaranteed to work only one way. Since all the JVMs work exactly the same, the same code works exactly the same everywhere without recompiling. If you can't pass the tests to make sure it's the same, you're not allowed to call your virtual machine a "Java virtual machine".

Of course, there are ways that you can break the portability of a Java program. You could write a program that looks for files only found on one operating system (cmd.exe for example). You could use JNI, which effectively allows you to put compiled C or C++ code into a class. You could use conventions that only work for a certain operating system (like assuming ":" separates directories). But you are guaranteed to never have to recompile your program for a different machine unless you're doing something really special (like JNI).

How to round 0.745 to 0.75 using BigDecimal.ROUND_HALF_UP?

Use BigDecimal.valueOf(double d) instead of new BigDecimal(double d). The last one has precision errors by float and double.

HTML.ActionLink vs Url.Action in ASP.NET Razor

<p>
    @Html.ActionLink("Create New", "Create")
</p>
@using (Html.BeginForm("Index", "Company", FormMethod.Get))
{
    <p>
        Find by Name: @Html.TextBox("SearchString", ViewBag.CurrentFilter as string)
        <input type="submit" value="Search" />
        <input type="button" value="Clear" onclick="location.href='@Url.Action("Index","Company")'"/>
    </p>
}

In the above example you can see that If I specifically need a button to do some action, I have to do it with @Url.Action whereas if I just want a link I will use @Html.ActionLink. The point is when you have to use some element(HTML) with action url is used.

How do I change button size in Python?

I've always used .place() for my tkinter widgets. place syntax

You can specify the size of it just by changing the keyword arguments!

Of course, you will have to call .place() again if you want to change it.

Works in python 3.8.2, if you're wondering.

How to change current working directory using a batch file

Just use cd /d %root% to switch driver letters and change directories.

Alternatively, use pushd %root% to switch drive letters when changing directories as well as storing the previous directory on a stack so you can use popd to switch back.

Note that pushd will also allow you to change directories to a network share. It will actually map a network drive for you, then unmap it when you execute the popd for that directory.

Make column fixed position in bootstrap

Updated for Bootstrap 4

Bootstrap 4 now includes a position-fixed class for this purpose so there is no need for additional CSS...

<div class="container">
    <div class="row">
        <div class="col-lg-3">
            <div class="position-fixed">
                Fixed content
            </div>
        </div>
        <div class="col-lg-9">
            Normal scrollable content
        </div>
    </div>
</div>

https://www.codeply.com/go/yOF9csaptw

MySQL LIMIT on DELETE statement

the delete query only allows for modifiers after the DELETE 'command' to tell the database what/how do handle things.

see this page

Expand a div to fill the remaining width

The solution to this is actually very easy, but not at all obvious. You have to trigger something called a "block formatting context" (BFC), which interacts with floats in a specific way.

Just take that second div, remove the float, and give it overflow:hidden instead. Any overflow value other than visible makes the block it's set on become a BFC. BFCs don't allow descendant floats to escape them, nor do they allow sibling/ancestor floats to intrude into them. The net effect here is that the floated div will do its thing, then the second div will be an ordinary block, taking up all available width except that occupied by the float.

This should work across all current browsers, though you may have to trigger hasLayout in IE6 and 7. I can't recall.

Demos:

CSS3 selector :first-of-type with class name?

No, it's not possible using just one selector. The :first-of-type pseudo-class selects the first element of its type (div, p, etc). Using a class selector (or a type selector) with that pseudo-class means to select an element if it has the given class (or is of the given type) and is the first of its type among its siblings.

Unfortunately, CSS doesn't provide a :first-of-class selector that only chooses the first occurrence of a class. As a workaround, you can use something like this:

.myclass1 { color: red; }
.myclass1 ~ .myclass1 { color: /* default, or inherited from parent div */; }

Explanations and illustrations for the workaround are given here and here.

Qt - reading from a text file

You have to replace string line

QString line = in.readLine();

into while:

QFile file("/home/hamad/lesson11.txt");
if(!file.open(QIODevice::ReadOnly)) {
    QMessageBox::information(0, "error", file.errorString());
}

QTextStream in(&file);

while(!in.atEnd()) {
    QString line = in.readLine();    
    QStringList fields = line.split(",");    
    model->appendRow(fields);    
}

file.close();

Unable to find the requested .Net Framework Data Provider. It may not be installed. - when following mvc3 asp.net tutorial

I had the same issue. I checked the version of System.Data.SqlServerCe in C:\Windows\assembly. It was 3.5.1.0. So I installed version 4.0.0 from below link (x86) and works fine.

http://www.microsoft.com/download/en/details.aspx?id=17876

Displaying a Table in Django from Database

If you want to table do following steps:-

views.py:

def view_info(request):
    objs=Model_name.objects.all()
    ............
    return render(request,'template_name',{'objs':obj})

.html page

 {% for item in objs %}
    <tr> 
         <td>{{ item.field1 }}</td>
         <td>{{ item.field2 }}</td>
         <td>{{ item.field3 }}</td>
         <td>{{ item.field4 }}</td>
    </tr>
       {% endfor %}

Call asynchronous method in constructor?

You can also do just like this:

Task.Run(() => this.FunctionAsync()).Wait();

Note: Be careful about thread blocking!

How can I change the default Django date template format?

In order to change date format in the views.py and then assign it to template.

# get the object details 
home = Home.objects.get(home_id=homeid)

# get the start date
_startDate = home.home_startdate.strftime('%m/%d/%Y')

# assign it to template 
return render_to_response('showme.html' 
                                        {'home_startdate':_startDate},   
                                         context_instance=RequestContext(request) )  

how to destroy an object in java?

Short Answer - E

Answer isE given that the rest are plainly wrong, but ..

Long Answer - It isn't that simple; it depends ...

Simple fact is, the garbage collector may never decide to garbage collection every single object that is a viable candidate for collection, not unless memory pressure is extremely high. And then there is the fact that Java is just as susceptible to memory leaks as any other language, they are just harder to cause, and thus harder to find when you do cause them!

The following article has many good details on how memory management works and doesn't work and what gets take up by what. How generational Garbage Collectors work and Thanks for the Memory ( Understanding How the JVM uses Native Memory on Windows and Linux )

If you read the links, I think you will get the idea that memory management in Java isn't as simple as a multiple choice question.

AngularJS ng-click stopPropagation

In case that you're using a directive like me this is how it works when you need the two data way binding for example after updating an attribute in any model or collection:

angular.module('yourApp').directive('setSurveyInEditionMode', setSurveyInEditionMode)

function setSurveyInEditionMode() {
  return {
    restrict: 'A',
    link: function(scope, element, $attributes) {
      element.on('click', function(event){
        event.stopPropagation();
        // In order to work with stopPropagation and two data way binding
        // if you don't use scope.$apply in my case the model is not updated in the view when I click on the element that has my directive
        scope.$apply(function () {
          scope.mySurvey.inEditionMode = true;
          console.log('inside the directive')
        });
      });
    }
  }
}

Now, you can easily use it in any button, link, div, etc. like so:

<button set-survey-in-edition-mode >Edit survey</button>

Possible reason for NGINX 499 error codes

Client closed the connection doesn't mean it's a browser issue!? Not at all!

You can find 499 errors in a log file if you have a LB (load balancer) in front of your webserver (nginx) either AWS or haproxy (custom). That said the LB will act as a client to nginx.

If you run haproxy default values for:

    timeout client  60000
    timeout server  60000

That would mean that LB will time out after 60000ms if there is no respond from nginx. Time outs might happen for busy websites or scripts that need more time for execution. You'll need to find timeout that will work for you. For example extend it to:

    timeout client  180s
    timeout server  180s

And you will be probably set.

Depending on your setup you might see a 504 gateway timeout error in your browser which indicates that something is wrong with php-fpm but that will not be the case with 499 errors in your log files.

Extracting a parameter from a URL in WordPress

In the call back function, use the $request parameter

$parameters = $request->get_params();
echo $parameters['ppc'];

How can I add a username and password to Jenkins?

Assuming you have Manage Jenkins > Configure Global Security > Enable Security and Jenkins Own User Database checked you would go to:

  • Manage Jenkins > Manage Users > Create User

How do I filter an array with TypeScript in Angular 2?

To filter an array irrespective of the property type (i.e. for all property types), we can create a custom filter pipe

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({ name: "filter" })
export class ManualFilterPipe implements PipeTransform {
  transform(itemList: any, searchKeyword: string) {
    if (!itemList)
      return [];
    if (!searchKeyword)
      return itemList;
    let filteredList = [];
    if (itemList.length > 0) {
      searchKeyword = searchKeyword.toLowerCase();
      itemList.forEach(item => {
        //Object.values(item) => gives the list of all the property values of the 'item' object
        let propValueList = Object.values(item);
        for(let i=0;i<propValueList.length;i++)
        {
          if (propValueList[i]) {
            if (propValueList[i].toString().toLowerCase().indexOf(searchKeyword) > -1)
            {
              filteredList.push(item);
              break;
            }
          }
        }
      });
    }
    return filteredList;
  }
}

//Usage

//<tr *ngFor="let company of companyList | filter: searchKeyword"></tr>

Don't forget to import the pipe in the app module

We might need to customize the logic to filer with dates.

What is the difference between smoke testing and sanity testing?

Sanity testing

Sanity testing is the subset of regression testing and it is performed when we do not have enough time for doing testing.

Sanity testing is the surface level testing where QA engineer verifies that all the menus, functions, commands available in the product and project are working fine.


Example

For example, in a project there are 5 modules: Login Page, Home Page, User's Details Page, New User Creation and Task Creation.

Suppose we have a bug in the login page: the login page's username field accepts usernames which are shorter than 6 alphanumeric characters, and this is against the requirements, as in the requirements it is specified that the username should be at least 6 alphanumeric characters.

Now the bug is reported by the testing team to the developer team to fix it. After the developing team fixes the bug and passes the app to the testing team, the testing team also checks the other modules of the application in order to verify that the bug fix does not affect the functionality of the other modules. But keep one point always in mind: the testing team only checks the extreme functionality of the modules, it does not go deep to test the details because of the short time.


Sanity testing is performed after the build has cleared the smoke tests and has been accepted by QA team for further testing. Sanity testing checks the major functionality with finer details.

Sanity testing is performed when the development team needs to know quickly the state of the product after they have done changes in the code, or there is some controlled code changed in a feature to fix any critical issue, and stringent release time-frame does not allow complete regression testing.


Smoke testing

Smoke Testing is performed after a software build to ascertain that the critical functionalities of the program are working fine. It is executed "before" any detailed functional or regression tests are executed on the software build.

The purpose is to reject a badly broken application, so that the QA team does not waste time installing and testing the software application.

In smoke testing, the test cases chosen cover the most important functionalities or components of the system. The objective is not to perform exhaustive testing, but to verify that the critical functionalities of the system are working fine. For example, typical smoke tests would be:

  • verify that the application launches successfully,
  • Check that the GUI is responsive

Set background color in PHP?

just insert the following line and use any color you like

    echo "<body style='background-color:pink'>";

Round button with text and icon in flutter

You can achieve that by using a FlatButton that contains a Column (for showing a text below the icon) or a Row (for text next to the icon), and then having an Icon Widget and a Text widget as children.

Here's an example:

class MyPage extends StatelessWidget {

  @override
  Widget build(BuildContext context) =>
      Scaffold(
        appBar: AppBar(
          title: Text("Hello world"),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              FlatButton(
                onPressed: () => {},
                color: Colors.orange,
                padding: EdgeInsets.all(10.0),
                child: Column( // Replace with a Row for horizontal icon + text
                  children: <Widget>[
                    Icon(Icons.add),
                    Text("Add")
                  ],
                ),
              ),
            ],
          ),
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: () => {},
          tooltip: 'Increment',
          child: Icon(Icons.add),
        ),
      );
}

This will produce the following:

Result

Location of the mongodb database on mac

Thanks @Mark, I keep forgetting this again and again. After installing MongoDB with Homebrew:

  • The databases are stored in the /usr/local/var/mongodb/ directory
  • The mongod.conf file is here: /usr/local/etc/mongod.conf
  • The mongo logs can be found at /usr/local/var/log/mongodb/
  • The mongo binaries are here: /usr/local/Cellar/mongodb/[version]/bin

Completely removing phpMyAdmin

If your system is using dpkg and apt (debian, ubuntu, etc), try running the following commands in that order (be careful with the sudo rm commands):

sudo apt-get -f install
sudo dpkg -P phpmyadmin  
sudo rm -vf /etc/apache2/conf.d/phpmyadmin.conf
sudo rm -vfR /usr/share/phpmyadmin
sudo service apache2 restart

Populate data table from data reader

If you're trying to load a DataTable, then leverage the SqlDataAdapter instead:

DataTable dt = new DataTable();

using (SqlConnection c = new SqlConnection(cString))
using (SqlDataAdapter sda = new SqlDataAdapter(sql, c))
{
    sda.SelectCommand.CommandType = CommandType.StoredProcedure;
    sda.SelectCommand.Parameters.AddWithValue("@parm1", val1);
    ...

    sda.Fill(dt);
}

You don't even need to define the columns. Just create the DataTable and Fill it.

Here, cString is your connection string and sql is the stored procedure command.

Center the content inside a column in Bootstrap 4

<div class="container">
    <div class="row justify-content-center">
        <div class="col-3 text-center">
            Center text goes here
        </div>
    </div>
</div>

I have used justify-content-center class instead of mx-auto as in this answer.

check at https://jsfiddle.net/sarfarazk/4fsp4ywh/

How to implement history.back() in angular.js

For me, my problem was I needed to navigate back and then transition to another state. So using $window.history.back() didn't work because for some reason the transition happened before history.back() occured so I had to wrap my transition in a timeout function like so.

$window.history.back();
setTimeout(function() {
  $state.transitionTo("tab.jobs"); }, 100);

This fixed my issue.

Unbound classpath container in Eclipse

I got the Similar issue while importing the project.

The issue is you select "Use an execution environment JRE" and which is lower then the libraries used in the projects being imported.

There are two ways to resolve this issue:

1.While first time importing the project:

in JRE tab select "USE project specific JRE" instead of "Use an execution environment JRE".

2.Delete the Project from your work space and import again. This time:

select "Check out as a project in the workspace" instead of "Check out as a project configured using the new Project Wizard"

how to draw smooth curve through N points using javascript HTML5 canvas?

If you want to determine the equation of the curve through n points then the following code will give you the coefficients of the polynomial of degree n-1 and save these coefficients to the coefficients[] array (starting from the constant term). The x coordinates do not have to be in order. This is an example of a Lagrange polynomial.

var xPoints=[2,4,3,6,7,10]; //example coordinates
var yPoints=[2,5,-2,0,2,8];
var coefficients=[];
for (var m=0; m<xPoints.length; m++) coefficients[m]=0;
    for (var m=0; m<xPoints.length; m++) {
        var newCoefficients=[];
        for (var nc=0; nc<xPoints.length; nc++) newCoefficients[nc]=0;
        if (m>0) {
            newCoefficients[0]=-xPoints[0]/(xPoints[m]-xPoints[0]);
            newCoefficients[1]=1/(xPoints[m]-xPoints[0]);
    } else {
        newCoefficients[0]=-xPoints[1]/(xPoints[m]-xPoints[1]);
        newCoefficients[1]=1/(xPoints[m]-xPoints[1]);
    }
    var startIndex=1; 
    if (m==0) startIndex=2; 
    for (var n=startIndex; n<xPoints.length; n++) {
        if (m==n) continue;
        for (var nc=xPoints.length-1; nc>=1; nc--) {
        newCoefficients[nc]=newCoefficients[nc]*(-xPoints[n]/(xPoints[m]-xPoints[n]))+newCoefficients[nc-1]/(xPoints[m]-xPoints[n]);
        }
        newCoefficients[0]=newCoefficients[0]*(-xPoints[n]/(xPoints[m]-xPoints[n]));
    }    
    for (var nc=0; nc<xPoints.length; nc++) coefficients[nc]+=yPoints[m]*newCoefficients[nc];
}

Passing an integer by reference in Python

Not exactly passing a value directly, but using it as if it was passed.

x = 7
def my_method():
    nonlocal x
    x += 1
my_method()
print(x) # 8

Caveats:

  • nonlocal was introduced in python 3
  • If the enclosing scope is the global one, use global instead of nonlocal.

Can I add a custom attribute to an HTML tag?

You can add, but then you have to write a line of JavaScript code too,

document.createElement('tag');

to make sure everything fall in place. I mean Internet Explorer :)

Xcode build failure "Undefined symbols for architecture x86_64"

If you're getting this error when trying to link to a C file, first double check the function names for typos. Next double check that you are not trying to call a C function from a C++ / Objective-C++ environment without using the extern C {} construct. I was tearing my hair out because I had a class that was in a .mm file which was trying to call C functions. It doesn't work because in C++, the symbols are mangled. You can actually see the concrete symbols generated using the nm tool. Terminal to the path of the .o files, and run nm -g on the file that is calling the symbol and the one that should have the symbol, and you should see if they match up or not, which can provide clues for the error.

nm -g file.o

You can inspect the C++ symbols demangled with this:

nm -gC file.o

Save text file UTF-8 encoded with VBA

I found the answer on the web:

Dim fsT As Object
Set fsT = CreateObject("ADODB.Stream")
fsT.Type = 2 'Specify stream type - we want To save text/string data.
fsT.Charset = "utf-8" 'Specify charset For the source text data.
fsT.Open 'Open the stream And write binary data To the object
fsT.WriteText "special characters: äöüß"
fsT.SaveToFile sFileName, 2 'Save binary data To disk

Certainly not as I expected...

Standard Android menu icons, for example refresh

You can get the icons from the android sdk they are in this folder

$android-sdk\platforms\android-xx\data\res

CSS I want a div to be on top of everything

z-index property enables you to take your control at front. the bigger number you set the upper your element you get.

position property should be relative because position of html-element should be position relatively against other controls in all dimensions.

element.style {
   position:relative;
   z-index:1000; //change your number as per elements lies on your page.
}

Playing Sound In Hidden Tag

_x000D_
_x000D_
audio { display:none;}
_x000D_
<audio autoplay="true" src="https://upload.wikimedia.org/wikipedia/commons/c/c8/Example.ogg">
_x000D_
_x000D_
_x000D_

Managing jQuery plugin dependency in webpack

In your webpack.config.js file add below:

 var webpack = require("webpack");
 plugins: [
    new webpack.ProvidePlugin({
        $: "jquery",
        jQuery: "jquery"
    })
 ],

Install jQuery using npm:

$ npm i jquery --save

In app.js file add below lines:

import $ from 'jquery';
window.jQuery = $;
window.$ = $;

This worked for me. :)

Can someone give an example of cosine similarity, in a very simple, graphical way?

Simple JAVA code to calculate cosine similarity

/**
   * Method to calculate cosine similarity of vectors
   * 1 - exactly similar (angle between them is 0)
   * 0 - orthogonal vectors (angle between them is 90)
   * @param vector1 - vector in the form [a1, a2, a3, ..... an]
   * @param vector2 - vector in the form [b1, b2, b3, ..... bn]
   * @return - the cosine similarity of vectors (ranges from 0 to 1)
   */
  private double cosineSimilarity(List<Double> vector1, List<Double> vector2) {

    double dotProduct = 0.0;
    double normA = 0.0;
    double normB = 0.0;
    for (int i = 0; i < vector1.size(); i++) {
      dotProduct += vector1.get(i) * vector2.get(i);
      normA += Math.pow(vector1.get(i), 2);
      normB += Math.pow(vector2.get(i), 2);
    }
    return dotProduct / (Math.sqrt(normA) * Math.sqrt(normB));
  }

Android Studio emulator does not come with Play Store for API 23

Now there's no need to side load any packages of execute any scripts to get the Play Store on the emulator. Starting from Android Studio 2.4 now you can create an AVD that has Play Store pre-installed on it. Currently it is supported only on the AVDs running Android 7.0 (API 24) system images.

Official Source

AVD with Play Store

Note: Compatible devices are denoted by the new Play Store column.

What is "android:allowBackup"?

This is not explicitly mentioned, but based on the following docs, I think it is implied that an app needs to declare and implement a BackupAgent in order for data backup to work, even in the case when allowBackup is set to true (which is the default value).

http://developer.android.com/reference/android/R.attr.html#allowBackup http://developer.android.com/reference/android/app/backup/BackupManager.html http://developer.android.com/guide/topics/data/backup.html

Conda update failed: SSL error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed

Conda needs to know where to find you SSL certificate store.

conda config --set ssl_verify <pathToYourFile>.crt

No need to disable SSL verification.

This command add a line to your $HOME/.condarc file or %USERPROFILE%\.condarc file on Windows that looks like:

ssl_verify: <pathToYourFile>.crt

If you leave your organization's network, you can just comment out that line in .condarc with a # and uncomment when you return.

If it still doesn't work, make sure that you are using the latest version of curl, checking both the conda-forge and anaconda channels.

C#: easiest way to populate a ListBox from a List

You can also use the AddRange method

listBox1.Items.AddRange(myList.ToArray());

How to create checkbox inside dropdown?

Here is a simple dropdown checklist:

_x000D_
_x000D_
var checkList = document.getElementById('list1');
checkList.getElementsByClassName('anchor')[0].onclick = function(evt) {
  if (checkList.classList.contains('visible'))
    checkList.classList.remove('visible');
  else
    checkList.classList.add('visible');
}
_x000D_
.dropdown-check-list {
  display: inline-block;
}

.dropdown-check-list .anchor {
  position: relative;
  cursor: pointer;
  display: inline-block;
  padding: 5px 50px 5px 10px;
  border: 1px solid #ccc;
}

.dropdown-check-list .anchor:after {
  position: absolute;
  content: "";
  border-left: 2px solid black;
  border-top: 2px solid black;
  padding: 5px;
  right: 10px;
  top: 20%;
  -moz-transform: rotate(-135deg);
  -ms-transform: rotate(-135deg);
  -o-transform: rotate(-135deg);
  -webkit-transform: rotate(-135deg);
  transform: rotate(-135deg);
}

.dropdown-check-list .anchor:active:after {
  right: 8px;
  top: 21%;
}

.dropdown-check-list ul.items {
  padding: 2px;
  display: none;
  margin: 0;
  border: 1px solid #ccc;
  border-top: none;
}

.dropdown-check-list ul.items li {
  list-style: none;
}

.dropdown-check-list.visible .anchor {
  color: #0094ff;
}

.dropdown-check-list.visible .items {
  display: block;
}
_x000D_
<div id="list1" class="dropdown-check-list" tabindex="100">
  <span class="anchor">Select Fruits</span>
  <ul class="items">
    <li><input type="checkbox" />Apple </li>
    <li><input type="checkbox" />Orange</li>
    <li><input type="checkbox" />Grapes </li>
    <li><input type="checkbox" />Berry </li>
    <li><input type="checkbox" />Mango </li>
    <li><input type="checkbox" />Banana </li>
    <li><input type="checkbox" />Tomato</li>
  </ul>
</div>
_x000D_
_x000D_
_x000D_

How to write a test which expects an Error to be thrown in Jasmine?

In my case the function throwing error was async so I followed here:

await expectAsync(asyncFunction()).toBeRejected();
await expectAsync(asyncFunction()).toBeRejectedWithError(...);

Get Date Object In UTC format in Java

A Date doesn't have any time zone. What you're seeing is only the formatting of the date by the Date.toString() method, which uses your local timezone, always, to transform the timezone-agnostic date into a String that you can understand.

If you want to display the timezone-agnostic date as a string using the UTC timezone, then use a SimpleDateFormat with the UTC timezone (as you're already doing in your question).

In other terms, the timezone is not a property of the date. It's a property of the format used to transform the date into a string.

JavaScript CSS how to add and remove multiple CSS classes to an element

In modern browsers, the classList API is supported.

This allows for a (vanilla) JavaScript function like this:

var addClasses;

addClasses = function (selector, classArray) {
    'use strict';

    var className, element, elements, i, j, lengthI, lengthJ;

    elements = document.querySelectorAll(selector);

    // Loop through the elements
    for (i = 0, lengthI = elements.length; i < lengthI; i += 1) {
        element = elements[i];

        // Loop through the array of classes to add one class at a time
        for (j = 0, lengthJ = classArray.length; j < lengthJ; j += 1) {
            className = classArray[j];

            element.classList.add(className);
        }
    }
};

Modern browsers (not IE) support passing multiple arguments to the classList::add function, which would remove the need for the nested loop, simplifying the function a bit:

var addClasses;

addClasses = function (selector, classArray) {
    'use strict';

    var classList, className, element, elements, i, j, lengthI, lengthJ;

    elements = document.querySelectorAll(selector);

    // Loop through the elements
    for (i = 0, lengthI = elements.length; i < lengthI; i += 1) {
        element = elements[i];
        classList = element.classList;

        // Pass the array of classes as multiple arguments to classList::add
        classList.add.apply(classList, classArray);
    }
};

Usage

addClasses('.button', ['large', 'primary']);

Functional version

var addClassesToElement, addClassesToSelection;

addClassesToElement = function (element, classArray) {
    'use strict';

    classArray.forEach(function (className) {
       element.classList.add(className);
    });
};

addClassesToSelection = function (selector, classArray) {
    'use strict';

    // Use Array::forEach on NodeList to iterate over results.
    // Okay, since we’re not trying to modify the NodeList.
    Array.prototype.forEach.call(document.querySelectorAll(selector), function (element) {
        addClassesToElement(element, classArray)
    });
};

// Usage
addClassesToSelection('.button', ['button', 'button--primary', 'button--large'])

The classList::add function will prevent multiple instances of the same CSS class as opposed to some of the previous answers.

Resources on the classList API:

how to place last div into right top corner of parent div? (css)

_x000D_
_x000D_
.block1 {_x000D_
    color: red;_x000D_
    width: 100px;_x000D_
    border: 1px solid green;_x000D_
    position: relative;_x000D_
}_x000D_
_x000D_
.block2 {_x000D_
    color: blue;_x000D_
    width: 70px;_x000D_
    border: 2px solid black;_x000D_
    position: absolute;_x000D_
    top: 0px;_x000D_
    right: 0px;_x000D_
}
_x000D_
<div class='block1'>_x000D_
  <p>text</p>_x000D_
  <p>text2</p>_x000D_
  <div class='block2'>block2</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Should do it. Assuming you don't need it to flow.

How to write a cursor inside a stored procedure in SQL Server 2008

What's wrong with just simply using a single, simple UPDATE statement??

UPDATE dbo.Coupon
SET NoofUses = (SELECT COUNT(*) FROM dbo.CouponUse WHERE Couponid = dbo.Coupon.ID)

That's all that's needed ! No messy and complicated cursor, no looping, no RBAR (row-by-agonizing-row) processing ..... just a nice, simple, clean set-based SQL statement.

How to turn off Wifi via ADB?

Using "svc" through ADB (rooted required):

Enable:

adb shell su -c 'svc wifi enable'

Disable:

adb shell su -c 'svc wifi disable'

Using Key Events through ADB:

adb shell am start -a android.intent.action.MAIN -n com.android.settings/.wifi.WifiSettings
adb shell input keyevent 20 & adb shell input keyevent 23

The first line launch "wifi.WifiSettings" activity which open the WiFi Settings page. The second line simulate key presses.

I tested those two lines on a Droid X. But Key Events above probably need to edit in other devices because of different Settings layout.

More info about "keyevents" here.

Which to use <div class="name"> or <div id="name">?

ID provides a unique indentifier for the element, in case you want to manipulate it in JavaScript. The class attribute can be used to treat a group of HTML elements the same, particularly in regards to fonts, colors and other style properties...

What is the alternative for ~ (user's home directory) on Windows command prompt?

You're going to be disappointed: %userprofile%

You can use other terminals, though. Powershell, which I believe you can get on XP and later (and comes preinstalled with Win7), allows you to use ~ for home directory.

How can I remove a pytz timezone from a datetime object?

To remove a timezone (tzinfo) from a datetime object:

# dt_tz is a datetime.datetime object
dt = dt_tz.replace(tzinfo=None)

If you are using a library like arrow, then you can remove timezone by simply converting an arrow object to to a datetime object, then doing the same thing as the example above.

# <Arrow [2014-10-09T10:56:09.347444-07:00]>
arrowObj = arrow.get('2014-10-09T10:56:09.347444-07:00')

# datetime.datetime(2014, 10, 9, 10, 56, 9, 347444, tzinfo=tzoffset(None, -25200))
tmpDatetime = arrowObj.datetime

# datetime.datetime(2014, 10, 9, 10, 56, 9, 347444)
tmpDatetime = tmpDatetime.replace(tzinfo=None)

Why would you do this? One example is that mysql does not support timezones with its DATETIME type. So using ORM's like sqlalchemy will simply remove the timezone when you give it a datetime.datetime object to insert into the database. The solution is to convert your datetime.datetime object to UTC (so everything in your database is UTC since it can't specify timezone) then either insert it into the database (where the timezone is removed anyway) or remove it yourself. Also note that you cannot compare datetime.datetime objects where one is timezone aware and another is timezone naive.

##############################################################################
# MySQL example! where MySQL doesn't support timezones with its DATETIME type!
##############################################################################

arrowObj = arrow.get('2014-10-09T10:56:09.347444-07:00')

arrowDt = arrowObj.to("utc").datetime

# inserts datetime.datetime(2014, 10, 9, 17, 56, 9, 347444, tzinfo=tzutc())
insertIntoMysqlDatabase(arrowDt)

# returns datetime.datetime(2014, 10, 9, 17, 56, 9, 347444)
dbDatetimeNoTz = getFromMysqlDatabase()

# cannot compare timzeone aware and timezone naive
dbDatetimeNoTz == arrowDt # False, or TypeError on python versions before 3.3

# compare datetimes that are both aware or both naive work however
dbDatetimeNoTz == arrowDt.replace(tzinfo=None) # True

Print in Landscape format

you cannot set this in javascript, you have to do this with html/css:

<style type="text/css" media="print">
  @page { size: landscape; }
</style>

EDIT: See this Question and the accepted answer for more information on browser support: Is @Page { size:landscape} obsolete?

SQL server ignore case in a where expression

I found another solution elsewhere; that is, to use

upper(@yourString)

but everyone here is saying that, in SQL Server, it doesn't matter because it's ignoring case anyway? I'm pretty sure our database is case-sensitive.

'Access denied for user 'root'@'localhost' (using password: NO)'

Use mysql -u root -p It will ask for password, insert password and enter.

Which @NotNull Java annotation should I use?

If you are building your application using Spring Framework I would suggest using javax.validation.constraints.NotNull comming from Beans Validation packaged in following dependency:

    <dependency>
        <groupId>javax.validation</groupId>
        <artifactId>validation-api</artifactId>
        <version>1.1.0.Final</version>
    </dependency>

The main advantage of this annotation is that Spring provides support for both method parameters and class fields annotated with javax.validation.constraints.NotNull. All you need to do to enable support is:

  1. supply the api jar for beans validation and jar with implementation of validator of jsr-303/jsr-349 annotations (which comes with Hibernate Validator 5.x dependency):

    <dependency>
        <groupId>javax.validation</groupId>
        <artifactId>validation-api</artifactId>
        <version>1.1.0.Final</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>5.4.1.Final</version>
    </dependency>
    
  2. provide MethodValidationPostProcessor to spring's context

      @Configuration
      @ValidationConfig
      public class ValidationConfig implements MyService {
    
            @Bean
            public MethodValidationPostProcessor providePostProcessor() {
                  return new MethodValidationPostProcessor()
            }
      }
    
  3. finally you annotate your classes with Spring's org.springframework.validation.annotation.Validated and validation will be automatically handled by Spring.

Example:

@Service
@Validated
public class MyServiceImpl implements MyService {

  @Override
  public Something doSomething(@NotNull String myParameter) {
        // No need to do something like assert myParameter != null  
  }
}

When you try calling method doSomething and pass null as the parameter value, spring (by means of HibernateValidator) will throw ConstraintViolationException. No need for manuall work here.

You can also validate return values.

Another important benefit of javax.validation.constraints.NotNull comming for Beans Validation Framework is that at the moment it is still developed and new features are planned for new version 2.0.

What about @Nullable? There is nothing like that in Beans Validation 1.1. Well, I could arguee that if you decide to use @NotNull than everything which is NOT annotated with @NonNull is effectively "nullable", so the @Nullable annotation is useless.

When to use malloc for char pointers

malloc is for allocating memory on the free-store. If you have a string literal that you do not want to modify the following is ok:

char *literal = "foo";

However, if you want to be able to modify it, use it as a buffer to hold a line of input and so on, use malloc:

char *buf = (char*) malloc(BUFSIZE); /* define BUFSIZE before */
// ...
free(buf);

How do I serialize a Python dictionary into a string, and then back to a dictionary?

It depends on what you're wanting to use it for. If you're just trying to save it, you should use pickle (or, if you’re using CPython 2.x, cPickle, which is faster).

>>> import pickle
>>> pickle.dumps({'foo': 'bar'})
b'\x80\x03}q\x00X\x03\x00\x00\x00fooq\x01X\x03\x00\x00\x00barq\x02s.'
>>> pickle.loads(_)
{'foo': 'bar'}

If you want it to be readable, you could use json:

>>> import json
>>> json.dumps({'foo': 'bar'})
'{"foo": "bar"}'
>>> json.loads(_)
{'foo': 'bar'}

json is, however, very limited in what it will support, while pickle can be used for arbitrary objects (if it doesn't work automatically, the class can define __getstate__ to specify precisely how it should be pickled).

>>> pickle.dumps(object())
b'\x80\x03cbuiltins\nobject\nq\x00)\x81q\x01.'
>>> json.dumps(object())
Traceback (most recent call last):
  ...
TypeError: <object object at 0x7fa0348230c0> is not JSON serializable

How to add smooth scrolling to Bootstrap's scroll spy function

$("#YOUR-BUTTON").on('click', function(e) {
   e.preventDefault();
   $('html, body').animate({
        scrollTop: $("#YOUR-TARGET").offset().top
     }, 300);
});

Download multiple files with a single action

HTTP does not support more than one file download at once.

There are two solutions:

  • Open x amount of windows to initiate the file downloads (this would be done with JavaScript)
  • preferred solution create a script to zip the files

Excel VBA - select multiple columns not in sequential order

Some of the code looks a bit complex to me. This is very simple code to select only the used rows in two discontiguous columns D and H. It presumes the columns are of unequal length and thus more flexible vs if the columns were of equal length.

As you most likely surmised 4=column D and 8=column H

Dim dlastRow As Long
Dim hlastRow As Long

dlastRow = ActiveSheet.Cells(Rows.Count, 4).End(xlUp).Row
hlastRow = ActiveSheet.Cells(Rows.Count, 8).End(xlUp).Row
Range("D2:D" & dlastRow & ",H2:H" & hlastRow).Select

Hope you find useful - DON'T FORGET THAT COMMA BEFORE THE SECOND COLUMN, AS I DID, OR IT WILL BOMB!!

How to change the minSdkVersion of a project?

Set the min SDK version in your project's AndroidManifest.xml file and in the toolbar search for "Sync Projects with Gradle Files" icon. It works for me.

Also look for your project's build.gradle file and update the min sdk version.

JavaScript OR (||) variable assignment explanation

It will evaluate X and, if X is not null, the empty string, or 0 (logical false), then it will assign it to z. If X is null, the empty string, or 0 (logical false), then it will assign y to z.

var x = '';
var y = 'bob';
var z = x || y;
alert(z);

Will output 'bob';

How to use [DllImport("")] in C#?

You can't declare an extern local method inside of a method, or any other method with an attribute. Move your DLL import into the class:

using System.Runtime.InteropServices;


public class WindowHandling
{
    [DllImport("User32.dll")]
    public static extern int SetForegroundWindow(IntPtr point);

    public void ActivateTargetApplication(string processName, List<string> barcodesList)
    {
        Process p = Process.Start("notepad++.exe");
        p.WaitForInputIdle();
        IntPtr h = p.MainWindowHandle;
        SetForegroundWindow(h);
        SendKeys.SendWait("k");
        IntPtr processFoundWindow = p.MainWindowHandle;
    }
}

Create a root password for PHPMyAdmin

PHPMyAdmin is telling you that your MySQL service is missing a root password. You can change it by accessing the MySQL command line interface. mysqladmin -u root password newpass

http://www.howtoforge.com/setting-changing-resetting-mysql-root-passwords

Return row number(s) for a particular value in a column in a dataframe

Use which(mydata_2$height_chad1 == 2585)

Short example

df <- data.frame(x = c(1,1,2,3,4,5,6,3),
                 y = c(5,4,6,7,8,3,2,4))
df
  x y
1 1 5
2 1 4
3 2 6
4 3 7
5 4 8
6 5 3
7 6 2
8 3 4

which(df$x == 3)
[1] 4 8

length(which(df$x == 3))
[1] 2

count(df, vars = "x")
  x freq
1 1    2
2 2    1
3 3    2
4 4    1
5 5    1
6 6    1

df[which(df$x == 3),]
  x y
4 3 7
8 3 4

As Matt Weller pointed out, you can use the length function. The count function in plyr can be used to return the count of each unique column value.

How do I completely rename an Xcode project (i.e. inclusive of folders)?

XCode 11.0+.

It's really simple now. Just go to Project Navigator left panel of the XCode window.
Press Enter to make it active for rename, just like you change the folder name.
enter image description here

Just change the new name here, and XCode will ask you for renaming other pieces of stuff.

enter image description here.

Tap on Rename here and you are done.
If you are confused about your root folder name that why it's not changed, well it's just a folder. just renamed it with a new name.
enter image description here

Case Statement Equivalent in R

If you got factor then you could change levels by standard method:

df <- data.frame(name = c('cow','pig','eagle','pigeon'), 
             stringsAsFactors = FALSE)
df$type <- factor(df$name) # First step: copy vector and make it factor
# Change levels:
levels(df$type) <- list(
    animal = c("cow", "pig"),
    bird = c("eagle", "pigeon")
)
df
#     name   type
# 1    cow animal
# 2    pig animal
# 3  eagle   bird
# 4 pigeon   bird

You could write simple function as a wrapper:

changelevels <- function(f, ...) {
    f <- as.factor(f)
    levels(f) <- list(...)
    f
}

df <- data.frame(name = c('cow','pig','eagle','pigeon'), 
                 stringsAsFactors = TRUE)

df$type <- changelevels(df$name, animal=c("cow", "pig"), bird=c("eagle", "pigeon"))

How to list only files and not directories of a directory Bash?

  • carlpett's find-based answer (find . -maxdepth 1 -type f) works in principle, but is not quite the same as using ls: you get a potentially unsorted list of filenames all prefixed with ./, and you lose the ability to apply ls's many options;
    also find invariably finds hidden items too, whereas ls' behavior depends on the presence or absence of the -a or -A options.

    • An improvement, suggested by Alex Hall in a comment on the question is to combine shell globbing with find:

          find * -maxdepth 0 -type f  # find -L * ... includes symlinks to files
      
      • However, while this addresses the prefix problem and gives you alphabetically sorted output, you still have neither (inline) control over inclusion of hidden items nor access to ls's many other sorting / output-format options.
  • Hans Roggeman's ls + grep answer is pragmatic, but locks you into using long (-l) output format.


To address these limitations I wrote the fls (filtering ls) utility,

  • a utility that provides the output flexibility of ls while also providing type-filtering capability,
  • simply by placing type-filtering characters such as f for files, d for directories, and l for symlinks before a list of ls arguments (run fls --help or fls --man to learn more).

Examples:

fls f        # list all files in current dir.
fls d -tA ~  #  list dirs. in home dir., including hidden ones, most recent first
fls f^l /usr/local/bin/c* # List matches that are files, but not (^) symlinks (l)

Installation

Supported platforms

  • When installing from the npm registry: Linux and macOS
  • When installing manually: any Unix-like platform with Bash

From the npm registry

Note: Even if you don't use Node.js, its package manager, npm, works across platforms and is easy to install; try
curl -L https://git.io/n-install | bash

With Node.js installed, install as follows:

[sudo] npm install fls -g

Note:

  • Whether you need sudo depends on how you installed Node.js / io.js and whether you've changed permissions later; if you get an EACCES error, try again with sudo.

  • The -g ensures global installation and is needed to put fls in your system's $PATH.

Manual installation

  • Download this bash script as fls.
  • Make it executable with chmod +x fls.
  • Move it or symlink it to a folder in your $PATH, such as /usr/local/bin (macOS) or /usr/bin (Linux).

How to convert a Title to a URL slug in jQuery?

For people already using lodash

Most of these example are really good and cover a lot of cases. But if you 'know' that you only have English text, here's my version that's super easy to read :)

_.words(_.toLower(text)).join('-')

Date format in the json output using spring boot

If you have Jackson integeration with your application to serialize your bean to JSON format, then you can use Jackson anotation @JsonFormat to format your date to specified format.
In your case if you need your date into yyyy-MM-dd format you need to specify @JsonFormat above your field on which you want to apply this format.

For Example :

public class Subject {

     private String uid;
     private String number;
     private String initials;

     @JsonFormat(pattern="yyyy-MM-dd")
     private Date dateOfBirth;  

     //Other Code  

}  

From Docs :

annotation used for configuring details of how values of properties are to be serialized.

More Reference Doc

Hope this helps.

Pagination on a list using ng-repeat

If you have not too much data, you can definitely do pagination by just storing all the data in the browser and filtering what's visible at a certain time.

Here's a simple pagination example: http://jsfiddle.net/2ZzZB/56/

That example was on the list of fiddles on the angular.js github wiki, which should be helpful: https://github.com/angular/angular.js/wiki/JsFiddle-Examples

EDIT: http://jsfiddle.net/2ZzZB/16/ to http://jsfiddle.net/2ZzZB/56/ (won't show "1/4.5" if there is 45 results)

Random record from MongoDB

Do a count of all records, generate a random number between 0 and the count, and then do:

db.yourCollection.find().limit(-1).skip(yourRandomNumber).next()

Convert ndarray from float64 to integer

There's also a really useful discussion about converting the array in place, In-place type conversion of a NumPy array. If you're concerned about copying your array (which is whatastype() does) definitely check out the link.

Get remote registry value

If you need user's SID and browse remote HKEY_USERS folder, you can follow this script :

<# Replace following domain.name with yours and userAccountName with remote username #>
$userLogin = New-Object System.Security.Principal.NTAccount(“domain.name“,”userAccountName“)
$userSID = $userLogin.Translate([System.Security.Principal.SecurityIdentifier])

<# We will open HKEY_USERS and with accurate user’s SID from remoteComputer #>
$remoteRegistry = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey(‘Users’,”remoteComputer“)

<# We will then retrieve LocalName value from Control Panel / International subkeys #>

$key = $userSID.value+”\Control Panel\International”
$openKey = $remoteRegistry.OpenSubKey($key)

<# We can now retrieve any values #>

$localName = $openKey.GetValue(‘LocaleName’)

Source : http://techsultan.com/how-to-browse-remote-registry-in-powershell/

Update a column value, replacing part of a string

UPDATE yourtable
SET url = REPLACE(url, 'http://domain1.com/images/', 'http://domain2.com/otherfolder/')
WHERE url LIKE ('http://domain1.com/images/%');

relevant docs: http://dev.mysql.com/doc/refman/5.5/en/string-functions.html#function_replace

How to align 3 divs (left/center/right) inside another div?

Using Bootstrap 3 I create 3 divs of equal width (in 12 column layout 4 columns for each div). This way you can keep your central zone centered even if left/right sections have different widths (if they don't overflow their columns' space).

HTML:

<div id="container">
  <div id="left" class="col col-xs-4 text-left">Left</div>
  <div id="center" class="col col-xs-4 text-center">Center</div>
  <div id="right" class="col col-xs-4 text-right">Right</div>
</div>

CSS:

#container {
  border: 1px solid #aaa;
  margin: 10px;
  padding: 10px;
  height: 100px;
}
.col {
  border: 1px solid #07f;
  padding: 0;
}

CodePen

To create that structure without libraries I copied some rules from Bootstrap CSS.

HTML:

<div id="container">
  <div id="left" class="col">Left</div>
  <div id="center" class="col">Center</div>
  <div id="right" class="col">Right</div>
</div>

CSS:

* {
  box-sizing: border-box;
}
#container {
  border: 1px solid #aaa;
  margin: 10px;
  padding: 10px;
  height: 100px;
}
.col {
  float: left;
  width: 33.33333333%;
  border: 1px solid #07f;
  padding: 0;
}
#left {
  text-align: left;
}
#center {
  text-align: center;
}
#right {
  text-align: right;
}

CopePen

Add one year in current date PYTHON

AGSM's answer shows a convenient way of solving this problem using the python-dateutil package. But what if you don't want to install that package? You could solve the problem in vanilla Python like this:

from datetime import date

def add_years(d, years):
    """Return a date that's `years` years after the date (or datetime)
    object `d`. Return the same calendar date (month and day) in the
    destination year, if it exists, otherwise use the following day
    (thus changing February 29 to March 1).

    """
    try:
        return d.replace(year = d.year + years)
    except ValueError:
        return d + (date(d.year + years, 1, 1) - date(d.year, 1, 1))

If you want the other possibility (changing February 29 to February 28) then the last line should be changed to:

        return d + (date(d.year + years, 3, 1) - date(d.year, 3, 1))

How to access SVG elements with Javascript

If you are using an <img> tag for the SVG, then you cannot manipulate its contents (as far as I know).

As the accepted answer shows, using <object> is an option.

I needed this recently and used gulp-inject during my gulp build to inject the contents of an SVG file directly into the HTML document as an <svg> element, which is then very easy to work with using CSS selectors and querySelector/getElementBy*.

How can I make a menubar fixed on the top while scrolling

The postition:absolute; tag positions the element relative to it's immediate parent. I noticed that even in the examples, there isn't room for scrolling, and when i tried it out, it didn't work. Therefore, to pull off the facebook floating menu, the position:fixed; tag should be used instead. It displaces/keeps the element at the given/specified location, and the rest of the page can scroll smoothly - even with the responsive ones.

Please see CSS postion attribute documentation when you can :)

grep a file, but show several surrounding lines?

grep astring myfile -A 5 -B 5

That will grep "myfile" for "astring", and show 5 lines before and after each match

Zip folder in C#

There is a ZipPackage class in the System.IO.Packaging namespace which is built into .NET 3, 3.5, and 4.0.

http://msdn.microsoft.com/en-us/library/system.io.packaging.zippackage.aspx

Here is an example how to use it. http://www.codeproject.com/KB/files/ZipUnZipTool.aspx?display=Print

How to get the server path to the web directory in Symfony2 from inside the controller?

UPDATE: Since 2.8 this no longer works because assetic is no longer included by default. Although if you're using assetic this will work.

You can use the variable %assetic.write_to%.

$this->getParameter('assetic.write_to');

Since your assets depend on this variable to be dumped to your web directory, it's safe to assume and use to locate your web folder.

http://symfony.com/doc/current/reference/configuration/assetic.html

no match for ‘operator<<’ in ‘std::operator

Obviously, the standard library provided operator does not know what to do with your user defined type mystruct. It only works for predefined data types. To be able to use it for your own data type, You need to overload operator << to take your user defined data type.

How to append one file to another in Linux from the shell?

cat file2 >> file1

The >> operator appends the output to the named file or creates the named file if it does not exist.

cat file1 file2 > file3

This concatenates two or more files to one. You can have as many source files as you need. For example,

cat *.txt >> newfile.txt

Update 20130902
In the comments eumiro suggests "don't try cat file1 file2 > file1." The reason this might not result in the expected outcome is that the file receiving the redirect is prepared before the command to the left of the > is executed. In this case, first file1 is truncated to zero length and opened for output, then the cat command attempts to concatenate the now zero-length file plus the contents of file2 into file1. The result is that the original contents of file1 are lost and in its place is a copy of file2 which probably isn't what was expected.

Update 20160919
In the comments tpartee suggests linking to backing information/sources. For an authoritative reference, I direct the kind reader to the sh man page at linuxcommand.org which states:

Before a command is executed, its input and output may be redirected using a special notation interpreted by the shell.

While that does tell the reader what they need to know it is easy to miss if you aren't looking for it and parsing the statement word by word. The most important word here being 'before'. The redirection is completed (or fails) before the command is executed.

In the example case of cat file1 file2 > file1 the shell performs the redirection first so that the I/O handles are in place in the environment in which the command will be executed before it is executed.

A friendlier version in which the redirection precedence is covered at length can be found at Ian Allen's web site in the form of Linux courseware. His I/O Redirection Notes page has much to say on the topic, including the observation that redirection works even without a command. Passing this to the shell:

$ >out

...creates an empty file named out. The shell first sets up the I/O redirection, then looks for a command, finds none, and completes the operation.

Get timezone from DateTime

No.

A developer is responsible for keeping track of time-zone information associated with a DateTime value via some external mechanism.

A quote from an excellent article here. A must read for every .Net developer.

So my advice is to write a little wrapper class that suits your needs.

How to fetch FetchType.LAZY associations with JPA and Hibernate in a Spring Controller

I think you need OpenSessionInViewFilter to keep your session open during view rendering (but it is not too good practice).

How do I create a crontab through a script

In Ubuntu and many other distros, you can just put a file into the /etc/cron.d directory containing a single line with a valid crontab entry. No need to add a line to an existing file.

If you just need something to run daily, just put a file into /etc/cron.daily. Likewise, you can also drop files into /etc/cron.hourly, /etc/cron.monthly, and /etc/cron.weekly.

C# guid and SQL uniqueidentifier

// Create Instance of Connection and Command Object
SqlConnection myConnection = new SqlConnection(GentEFONRFFConnection);
myConnection.Open();
SqlCommand myCommand = new SqlCommand("your Procedure Name", myConnection);
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.Parameters.Add("@orgid", SqlDbType.UniqueIdentifier).Value = orgid;
myCommand.Parameters.Add("@statid", SqlDbType.UniqueIdentifier).Value = statid;
myCommand.Parameters.Add("@read", SqlDbType.Bit).Value = read;
myCommand.Parameters.Add("@write", SqlDbType.Bit).Value = write;
// Mark the Command as a SPROC

myCommand.ExecuteNonQuery();

myCommand.Dispose();
myConnection.Close();

java.util.Date and getYear()

Java 8 LocalDate class is another option to get the year from a java.util.Date,

int year = LocalDate.parse(new SimpleDateFormat("yyyy-MM-dd").format(date)).getYear();

Another option is,

int year = Integer.parseInt(new SimpleDateFormat("yyyy").format(date));

iPhone app could not be installed at this time

I have had the same issue after fiddling around with certificates (argh).

The problem became apparent as I followed the comment of @Duraiamuthan.H, I installed on a device. The device reported 0xe8008016 (Entitlements) see SO here

The initial reason was, that the testflight target used the App store distribution certificate, not the Team certificate. I fixed that and the application was installing on the device over Xcode and then it also worked with testflight.

Get difference between two lists

I wanted something that would take two lists and could do what diff in bash does. Since this question pops up first when you search for "python diff two lists" and is not very specific, I will post what I came up with.

Using SequenceMather from difflib you can compare two lists like diff does. None of the other answers will tell you the position where the difference occurs, but this one does. Some answers give the difference in only one direction. Some reorder the elements. Some don't handle duplicates. But this solution gives you a true difference between two lists:

a = 'A quick fox jumps the lazy dog'.split()
b = 'A quick brown mouse jumps over the dog'.split()

from difflib import SequenceMatcher

for tag, i, j, k, l in SequenceMatcher(None, a, b).get_opcodes():
  if tag == 'equal': print('both have', a[i:j])
  if tag in ('delete', 'replace'): print('  1st has', a[i:j])
  if tag in ('insert', 'replace'): print('  2nd has', b[k:l])

This outputs:

both have ['A', 'quick']
  1st has ['fox']
  2nd has ['brown', 'mouse']
both have ['jumps']
  2nd has ['over']
both have ['the']
  1st has ['lazy']
both have ['dog']

Of course, if your application makes the same assumptions the other answers make, you will benefit from them the most. But if you are looking for a true diff functionality, then this is the only way to go.

For example, none of the other answers could handle:

a = [1,2,3,4,5]
b = [5,4,3,2,1]

But this one does:

  2nd has [5, 4, 3, 2]
both have [1]
  1st has [2, 3, 4, 5]

Python: Pandas pd.read_excel giving ImportError: Install xlrd >= 0.9.0 for Excel support

You need to install the "xlrd" lib

For Linux (Ubuntu and Derivates):

Installing via pip: python -m pip install --user xlrd

Install system-wide via a Linux package manager: *sudo apt-get install python-xlrd

Windows:

Installing via pip: *pip install xlrd

Download the files: https://pypi.org/project/xlrd/

Converting Stream to String and back...what are we missing?

a UTF8 MemoryStream to String conversion:

var res = Encoding.UTF8.GetString(stream.GetBuffer(), 0 , (int)stream.Length)

Include another JSP file

1.<a href="index.jsp?p=products">Products</a> when user clicks on Products link,you can directly call products.jsp.

I mean u can maintain name of the JSP file same as parameter Value.

<%
 if(request.getParameter("p")!=null)
 { 
   String contextPath="includes/";
   String p = request.getParameter("p");
   p=p+".jsp";
   p=contextPath+p;

%>    

<%@include file="<%=p%>" %>

<% 
 }
%>

or

2.you can maintain external resource file with key,value pairs. like below

products : products.jsp

customer : customers.jsp

you can programatically retrieve the name of JSP file from properies file.

this way you can easily change the name of JSP file

How can I set the PATH variable for javac so I can manually compile my .java works?

You don't need to do any complex command-line stuff or edit any system code. You simply have to open Computer, showing all of your disks and open properties. From there, go to Advanced System Settings and click Environment Variables. Scroll down in the lower list box and edit Path. Do not erase anything already there. Put a ; after it and then type in your path. To test, open command prompt and do "javac", it should list around 20 programs. You would be finished at that point.

By the way, the command to compile is javac -g not just javac.

Happy coding!

PHP 5 disable strict standards error

The default value of error_reporting flag is E_ALL & ~E_NOTICE if not set in php.ini. But in some installation (particularly installations targeting development environments) has E_ALL | E_STRICT set as value of this flag (this is the recommended value during development). In some cases, specially when you'll want to run some open source projects, that was developed prior to PHP 5.3 era and not yet updated with best practices defined by PHP 5.3, in your development environment, you'll probably run into getting some messages like you are getting. The best way to cope up on this situation, is to set only E_ALL as the value of error_reporting flag, either in php.ini or in code (probably in a front-controller like index.php in web-root as follows:

if(defined('E_STRICT')){
    error_reporting(E_ALL);
}

Returning null in a method whose signature says return int?

Do you realy want to return null ? Something you can do, is maybe initialise savedkey with 0 value and return 0 as a null value. It can be more simple.

C++ equivalent of Java's toString?

As an extension to what John said, if you want to extract the string representation and store it in a std::string do this:

#include <sstream>    
// ...
// Suppose a class A
A a;
std::stringstream sstream;
sstream << a;
std::string s = sstream.str(); // or you could use sstream >> s but that would skip out whitespace

std::stringstream is located in the <sstream> header.

Retrieve specific commit from a remote Git repository

This works best:

git fetch origin specific_commit
git checkout -b temp FETCH_HEAD

name "temp" whatever you want...this branch might be orphaned though

How do you see the entire command history in interactive Python?

Code for printing the entire history:

Python 3

One-liner (quick copy and paste):

import readline; print('\n'.join([str(readline.get_history_item(i + 1)) for i in range(readline.get_current_history_length())]))

(Or longer version...)

import readline
for i in range(readline.get_current_history_length()):
    print (readline.get_history_item(i + 1))

Python 2

One-liner (quick copy and paste):

import readline; print '\n'.join([str(readline.get_history_item(i + 1)) for i in range(readline.get_current_history_length())])

(Or longer version...)

import readline
for i in range(readline.get_current_history_length()):
    print readline.get_history_item(i + 1)

Note: get_history_item() is indexed from 1 to n.

Get user info via Google API

If you only want to fetch the Google user id, name and picture for a visitor of your web app - here is my pure PHP service side solution for the year 2020 with no external libraries used -

If you read the Using OAuth 2.0 for Web Server Applications guide by Google (and beware, Google likes to change links to its own documentation), then you have to perform only 2 steps:

  1. Present the visitor a web page asking for the consent to share her name with your web app
  2. Then take the "code" passed by the above web page to your web app and fetch a token (actually 2) from Google.

One of the returned tokens is called "id_token" and contains the user id, name and photo of the visitor.

Here is the PHP code of a web game by me. Initially I was using Javascript SDK, but then I have noticed that fake user data could be passed to my web game, when using client side SDK only (especially the user id, which is important for my game), so I have switched to using PHP on the server side:

<?php

const APP_ID       = '1234567890-abcdefghijklmnop.apps.googleusercontent.com';
const APP_SECRET   = 'abcdefghijklmnopq';

const REDIRECT_URI = 'https://the/url/of/this/PHP/script/';
const LOCATION     = 'Location: https://accounts.google.com/o/oauth2/v2/auth?';
const TOKEN_URL    = 'https://oauth2.googleapis.com/token';
const ERROR        = 'error';
const CODE         = 'code';
const STATE        = 'state';
const ID_TOKEN     = 'id_token';

# use a "random" string based on the current date as protection against CSRF
$CSRF_PROTECTION   = md5(date('m.d.y'));

if (isset($_REQUEST[ERROR]) && $_REQUEST[ERROR]) {
    exit($_REQUEST[ERROR]);
}

if (isset($_REQUEST[CODE]) && $_REQUEST[CODE] && $CSRF_PROTECTION == $_REQUEST[STATE]) {
    $tokenRequest = [
        'code'          => $_REQUEST[CODE],
        'client_id'     => APP_ID,
        'client_secret' => APP_SECRET,
        'redirect_uri'  => REDIRECT_URI,
        'grant_type'    => 'authorization_code',
    ];

    $postContext = stream_context_create([
        'http' => [
            'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
            'method'  => 'POST',
            'content' => http_build_query($tokenRequest)
        ]
    ]);

    # Step #2: send POST request to token URL and decode the returned JWT id_token
    $tokenResult = json_decode(file_get_contents(TOKEN_URL, false, $postContext), true);
    error_log(print_r($tokenResult, true));
    $id_token    = $tokenResult[ID_TOKEN];
    # Beware - the following code does not verify the JWT signature! 
    $userResult  = json_decode(base64_decode(str_replace('_', '/', str_replace('-', '+', explode('.', $id_token)[1]))), true);

    $user_id     = $userResult['sub'];
    $given_name  = $userResult['given_name'];
    $family_name = $userResult['family_name'];
    $photo       = $userResult['picture'];

    if ($user_id != NULL && $given_name != NULL) {
        # print your web app or game here, based on $user_id etc.
        exit();
    }
}

$userConsent = [
    'client_id'     => APP_ID,
    'redirect_uri'  => REDIRECT_URI,
    'response_type' => 'code',
    'scope'         => 'profile',
    'state'         => $CSRF_PROTECTION,
];

# Step #1: redirect user to a the Google page asking for user consent
header(LOCATION . http_build_query($userConsent));

?>

You could use a PHP library to add additional security by verifying the JWT signature. For my purposes it was unnecessary, because I trust that Google will not betray my little web game by sending fake visitor data.

Also, if you want to get more personal data of the visitor, then you need a third step:

const USER_INFO    = 'https://www.googleapis.com/oauth2/v3/userinfo?access_token=';
const ACCESS_TOKEN = 'access_token'; 

# Step #3: send GET request to user info URL
$access_token = $tokenResult[ACCESS_TOKEN];
$userResult = json_decode(file_get_contents(USER_INFO . $access_token), true);

Or you could get more permissions on behalf of the user - see the long list at the OAuth 2.0 Scopes for Google APIs doc.

Finally, the APP_ID and APP_SECRET constants used in my code - you get it from the Google API console:

screenshot

How to use an output parameter in Java?

As a workaround a generic "ObjectHolder" can be used. See code example below.

The sample output is:

name: John Doe
dob:1953-12-17
name: Jim Miller
dob:1947-04-18

so the Person parameter has been modified since it's wrapped in the Holder which is passed by value - the generic param inside is a reference where the contents can be modified - so actually a different person is returned and the original stays as is.

/**
 * show work around for missing call by reference in java
 */
public class OutparamTest {

 /**
  * a test class to be used as parameter
  */
 public static class Person {
   public String name;
     public String dob;
     public void show() {
      System.out.println("name: "+name+"\ndob:"+dob);
   }
 }

 /**
  * ObjectHolder (Generic ParameterWrapper)
  */
 public static class ObjectHolder<T> {
    public ObjectHolder(T param) {
     this.param=param;
    }
    public T param;
 }

 /**
  * ObjectHolder is substitute for missing "out" parameter
  */
 public static void setPersonData(ObjectHolder<Person> personHolder,String name,String dob) {
    // Holder needs to be dereferenced to get access to content
    personHolder.param=new Person();
    personHolder.param.name=name;
    personHolder.param.dob=dob;
 } 

  /**
   * show how it works
   */
  public static void main(String args[]) {
    Person jim=new Person();
    jim.name="Jim Miller";
    jim.dob="1947-04-18";
    ObjectHolder<Person> testPersonHolder=new ObjectHolder(jim);
    // modify the testPersonHolder person content by actually creating and returning
    // a new Person in the "out parameter"
    setPersonData(testPersonHolder,"John Doe","1953-12-17");
    testPersonHolder.param.show();
    jim.show();
  }
}

Setting "checked" for a checkbox with jQuery

You can do

$('.myCheckbox').attr('checked',true) //Standards compliant

or

$("form #mycheckbox").attr('checked', true)

If you have custom code in the onclick event for the checkbox that you want to fire, use this one instead:

$("#mycheckbox").click();

You can uncheck by removing the attribute entirely:

$('.myCheckbox').removeAttr('checked')

You can check all checkboxes like this:

$(".myCheckbox").each(function(){
    $("#mycheckbox").click()
});

How to only get file name with Linux 'find'?

I've found a solution (on makandracards page), that gives just the newest file name:

ls -1tr * | tail -1

(thanks goes to Arne Hartherz)

I used it for cp:

cp $(ls -1tr * | tail -1) /tmp/

How can I use custom fonts on a website?

CSS lets you use custom fonts, downloadable fonts on your website. You can download the font of your preference, let’s say myfont.ttf, and upload it to your remote server where your blog or website is hosted.

@font-face {
    font-family: myfont;
    src: url('myfont.ttf');
}

Default value in Doctrine

I struggled with the same problem. I wanted to have the default value from the database into the entities (automatically). Guess what, I did it :)

<?php
/**
 * Created by JetBrains PhpStorm.
 * User: Steffen
 * Date: 27-6-13
 * Time: 15:36
 * To change this template use File | Settings | File Templates.
 */

require_once 'bootstrap.php';

$em->getConfiguration()->setMetadataDriverImpl(
    new \Doctrine\ORM\Mapping\Driver\DatabaseDriver(
        $em->getConnection()->getSchemaManager()
    )
);

$driver = new \Doctrine\ORM\Mapping\Driver\DatabaseDriver($em->getConnection()->getSchemaManager());
$driver->setNamespace('Models\\');

$em->getConfiguration()->setMetadataDriverImpl($driver);

$cmf = new \Doctrine\ORM\Tools\DisconnectedClassMetadataFactory();
$cmf->setEntityManager($em);
$metadata = $cmf->getAllMetadata();

// Little hack to have default values for your entities...
foreach ($metadata as $k => $t)
{
    foreach ($t->getFieldNames() as $fieldName)
    {
        $correctFieldName = \Doctrine\Common\Util\Inflector::tableize($fieldName);

        $columns = $tan = $em->getConnection()->getSchemaManager()->listTableColumns($t->getTableName());
        foreach ($columns as $column)
        {
            if ($column->getName() == $correctFieldName)
            {
                // We skip DateTime, because this needs to be a DateTime object.
                if ($column->getType() != 'DateTime')
                {
                    $metadata[$k]->fieldMappings[$fieldName]['default'] = $column->getDefault();
                }
                break;
            }
        }
    }
}

// GENERATE PHP ENTITIES!
$entityGenerator = new \Doctrine\ORM\Tools\EntityGenerator();
$entityGenerator->setGenerateAnnotations(true);
$entityGenerator->setGenerateStubMethods(true);
$entityGenerator->setRegenerateEntityIfExists(true);
$entityGenerator->setUpdateEntityIfExists(false);
$entityGenerator->generate($metadata, __DIR__);

echo "Entities created";

Can I set a breakpoint on 'memory access' in GDB?

I just tried the following:

 $ cat gdbtest.c
 int abc = 43;

 int main()
 {
   abc = 10;
 }
 $ gcc -g -o gdbtest gdbtest.c
 $ gdb gdbtest
 ...
 (gdb) watch abc
 Hardware watchpoint 1: abc
 (gdb) r
 Starting program: /home/mweerden/gdbtest 
 ...

 Old value = 43
 New value = 10
 main () at gdbtest.c:6
 6       }
 (gdb) quit

So it seems possible, but you do appear to need some hardware support.

Sending Arguments To Background Worker?

You can pass multiple arguments like this.

List<object> arguments = new List<object>();
arguments.Add("first");      //argument 1
arguments.Add(new Object()); //argument 2
// ...
arguments.Add(10);           //argument n

backgroundWorker.RunWorkerAsync(arguments);

private void worker_DoWork(object sender, DoWorkEventArgs e) 
{
  List<object> genericlist = e.Argument as List<object>;
  //extract your multiple arguments from 
  //this list and cast them and use them. 
}

Java - Check if JTextField is empty or not

To Check JTextFiled is empty or not condition:

if( (billnotf.getText().length()==0)||(billtabtf.getText().length()==0))

How to start new line with space for next line in Html.fromHtml for text view in android

use <br/> tag

Example:

<string name="copyright"><b>@</b> 2014 <br/>
Corporation.<br/>
<i>All rights reserved.</i></string>

Fatal error: unexpectedly found nil while unwrapping an Optional values

Nil Coalescing Operator can be used as well.

rowName = rowName != nil ?rowName!.stringFromCamelCase():""

How can I install a .ipa file to my iPhone simulator

You can't. If it was downloaded via the iTunes store it was built for a different processor and won't work in the simulator.

String.format() to format double in java

If you want to format it with manually set symbols, use this:

DecimalFormatSymbols decimalFormatSymbols = new DecimalFormatSymbols();
decimalFormatSymbols.setDecimalSeparator('.');
decimalFormatSymbols.setGroupingSeparator(',');
DecimalFormat decimalFormat = new DecimalFormat("#,##0.00", decimalFormatSymbols);
System.out.println(decimalFormat.format(1237516.2548)); //1,237,516.25

Locale-based formatting is preferred, though.

How to find all occurrences of a substring?

You can use re.finditer() for non-overlapping matches.

>>> import re
>>> aString = 'this is a string where the substring "is" is repeated several times'
>>> print [(a.start(), a.end()) for a in list(re.finditer('is', aString))]
[(2, 4), (5, 7), (38, 40), (42, 44)]

but won't work for:

In [1]: aString="ababa"

In [2]: print [(a.start(), a.end()) for a in list(re.finditer('aba', aString))]
Output: [(0, 3)]

why are there two different kinds of for loops in java?

The for-each loop was introduced in Java 1.5 and is used with collections (and to be pedantic, arrays, and anything implementing the Iterable<E> interface ... which the article notes):

http://download.oracle.com/javase/1,5.0/docs/guide/language/foreach.html

jQuery change method on input type="file"

As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live(). Refer: http://api.jquery.com/on/

$('#imageFile').on("change", function(){ uploadFile(); });

How to convert the system date format to dd/mm/yy in SQL Server 2008 R2?

The query below will result in dd/mm/yy format.

select  LEFT(convert(varchar(10), @date, 103),6) + Right(Year(@date)+ 1,2)

Is there a MessageBox equivalent in WPF?

You can use this:

MessageBoxResult result = MessageBox.Show("Do you want to close this window?",
                                          "Confirmation",
                                          MessageBoxButton.YesNo,
                                          MessageBoxImage.Question);
if (result == MessageBoxResult.Yes)
{
    Application.Current.Shutdown();
}

For more information, visit MessageBox in WPF.

How to capture multiple repeated groups?

I think you need something like this....

b="HELLO,THERE,WORLD"
re.findall('[\w]+',b)

Which in Python3 will return

['HELLO', 'THERE', 'WORLD']

How does the vim "write with sudo" trick work?

This also works well:

:w !sudo sh -c "cat > %"

This is inspired by the comment of @Nathan Long.

NOTICE:

" must be used instead of ' because we want % to be expanded before passing to shell.

undefined offset PHP error

How to reproduce this error in PHP:

Create an empty array and ask for the value given a key like this:

php> $foobar = array();

php> echo gettype($foobar);
array

php> echo $foobar[0];

PHP Notice:  Undefined offset: 0 in 
/usr/local/lib/python2.7/dist-packages/phpsh/phpsh.php(578) : 
eval()'d code on line 1

What happened?

You asked an array to give you the value given a key that it does not contain. It will give you the value NULL then put the above error in the errorlog.

It looked for your key in the array, and found undefined.

How to make the error not happen?

Ask if the key exists first before you go asking for its value.

php> echo array_key_exists(0, $foobar) == false;
1

If the key exists, then get the value, if it doesn't exist, no need to query for its value.

Entity Framework and Connection Pooling

Below code helped my object to be refreshed with fresh database values. The Entry(object).Reload() command forces the object to recall database values

GM_MEMBERS member = DatabaseObjectContext.GM_MEMBERS.FirstOrDefault(p => p.Username == username && p.ApplicationName == this.ApplicationName);
DatabaseObjectContext.Entry(member).Reload();

php mysqli_connect: authentication method unknown to the client [caching_sha2_password]

I think it is not useful to configure the mysql server without caching_sha2_password encryption, we have to find a way to publish, send or obtain secure information through the network. As you see in the code below I dont use variable $db_name, and Im using a user in mysql server with standar configuration password. Just create a Standar user password and config all privilages. it works, but how i said without segurity.

<?php
$db_name="db";
$mysql_username="root";
$mysql_password="****";
$server_name="localhost";
$conn=mysqli_connect($server_name,$mysql_username,$mysql_password);

if ($conn) {
    echo "connetion success";
}
else{
    echo mysqli_error($conn);
}

?>

BASH Syntax error near unexpected token 'done'

I have exactly the same issue as above, and took me the whole day to discover that it doesn't like my newline approach. Instead I reused the same code with semi-colon approach instead. For example my initial code using the newline (which threw the same error as yours):

Y=1
while test "$Y" -le "20"
do
        echo "Number $Y"
        Y=$[Y+1]
done

And using code with semicolon approach with worked wonder:

Y=1 ; while test "$Y" -le "20"; do echo "Number $Y"; Y=$[Y+1] ; done

I notice the same problem occurs for other commands as well using the newline approach, so I think I am gonna stick to using semicolon for my future code.

How to get the list of files in a directory in a shell script?

Here's another way of listing files inside a directory (using a different tool, not as efficient as some of the other answers).

cd "search_dir"
for [ z in `echo *` ]; do
    echo "$z"
done

echo * Outputs all files of the current directory. The for loop iterates over each file name and prints to stdout.

Additionally, If looking for directories inside the directory then place this inside the for loop:

if [ test -d $z ]; then
    echo "$z is a directory"
fi

test -d checks if the file is a directory.

CakePHP 3.0 installation: intl extension missing from system

For those who get Package not found error try sudo apt-get install php7-intl then run composer install in your project directory.

What do 'real', 'user' and 'sys' mean in the output of time(1)?

Minimal runnable POSIX C examples

To make things more concrete, I want to exemplify a few extreme cases of time with some minimal C test programs.

All programs can be compiled and run with:

gcc -ggdb3 -o main.out -pthread -std=c99 -pedantic-errors -Wall -Wextra main.c
time ./main.out

and have been tested in Ubuntu 18.10, GCC 8.2.0, glibc 2.28, Linux kernel 4.18, ThinkPad P51 laptop, Intel Core i7-7820HQ CPU (4 cores / 8 threads), 2x Samsung M471A2K43BB1-CRC RAM (2x 16GiB).

sleep

Non-busy sleep does not count in either user or sys, only real.

For example, a program that sleeps for a second:

#define _XOPEN_SOURCE 700
#include <stdlib.h>
#include <unistd.h>

int main(void) {
    sleep(1);
    return EXIT_SUCCESS;
}

GitHub upstream.

outputs something like:

real    0m1.003s
user    0m0.001s
sys     0m0.003s

The same holds for programs blocked on IO becoming available.

For example, the following program waits for the user to enter a character and press enter:

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

int main(void) {
    printf("%c\n", getchar());
    return EXIT_SUCCESS;
}

GitHub upstream.

And if you wait for about one second, it outputs just like the sleep example something like:

real    0m1.003s
user    0m0.001s
sys     0m0.003s

For this reason time can help you distinguish between CPU and IO bound programs: What do the terms "CPU bound" and "I/O bound" mean?

Multiple threads

The following example does niters iterations of useless purely CPU-bound work on nthreads threads:

#define _XOPEN_SOURCE 700
#include <assert.h>
#include <inttypes.h>
#include <pthread.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

uint64_t niters;

void* my_thread(void *arg) {
    uint64_t *argument, i, result;
    argument = (uint64_t *)arg;
    result = *argument;
    for (i = 0; i < niters; ++i) {
        result = (result * result) - (3 * result) + 1;
    }
    *argument = result;
    return NULL;
}

int main(int argc, char **argv) {
    size_t nthreads;
    pthread_t *threads;
    uint64_t rc, i, *thread_args;

    /* CLI args. */
    if (argc > 1) {
        niters = strtoll(argv[1], NULL, 0);
    } else {
        niters = 1000000000;
    }
    if (argc > 2) {
        nthreads = strtoll(argv[2], NULL, 0);
    } else {
        nthreads = 1;
    }
    threads = malloc(nthreads * sizeof(*threads));
    thread_args = malloc(nthreads * sizeof(*thread_args));

    /* Create all threads */
    for (i = 0; i < nthreads; ++i) {
        thread_args[i] = i;
        rc = pthread_create(
            &threads[i],
            NULL,
            my_thread,
            (void*)&thread_args[i]
        );
        assert(rc == 0);
    }

    /* Wait for all threads to complete */
    for (i = 0; i < nthreads; ++i) {
        rc = pthread_join(threads[i], NULL);
        assert(rc == 0);
        printf("%" PRIu64 " %" PRIu64 "\n", i, thread_args[i]);
    }

    free(threads);
    free(thread_args);
    return EXIT_SUCCESS;
}

GitHub upstream + plot code.

Then we plot wall, user and sys as a function of the number of threads for a fixed 10^10 iterations on my 8 hyperthread CPU:

enter image description here

Plot data.

From the graph, we see that:

  • for a CPU intensive single core application, wall and user are about the same

  • for 2 cores, user is about 2x wall, which means that the user time is counted across all threads.

    user basically doubled, and while wall stayed the same.

  • this continues up to 8 threads, which matches my number of hyperthreads in my computer.

    After 8, wall starts to increase as well, because we don't have any extra CPUs to put more work in a given amount of time!

    The ratio plateaus at this point.

Note that this graph is only so clear and simple because the work is purely CPU-bound: if it were memory bound, then we would get a fall in performance much earlier with less cores because the memory accesses would be a bottleneck as shown at What do the terms "CPU bound" and "I/O bound" mean?

Quickly checking that wall < user is a simple way to determine that a program is multithreaded, and the closer that ratio is to the number of cores, the more effective the parallelization is, e.g.:

Sys heavy work with sendfile

The heaviest sys workload I could come up with was to use the sendfile, which does a file copy operation on kernel space: Copy a file in a sane, safe and efficient way

So I imagined that this in-kernel memcpy will be a CPU intensive operation.

First I initialize a large 10GiB random file with:

dd if=/dev/urandom of=sendfile.in.tmp bs=1K count=10M

Then run the code:

#define _GNU_SOURCE
#include <assert.h>
#include <fcntl.h>
#include <stdlib.h>
#include <sys/sendfile.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

int main(int argc, char **argv) {
    char *source_path, *dest_path;
    int source, dest;
    struct stat stat_source;
    if (argc > 1) {
        source_path = argv[1];
    } else {
        source_path = "sendfile.in.tmp";
    }
    if (argc > 2) {
        dest_path = argv[2];
    } else {
        dest_path = "sendfile.out.tmp";
    }
    source = open(source_path, O_RDONLY);
    assert(source != -1);
    dest = open(dest_path, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
    assert(dest != -1);
    assert(fstat(source, &stat_source) != -1);
    assert(sendfile(dest, source, 0, stat_source.st_size) != -1);
    assert(close(source) != -1);
    assert(close(dest) != -1);
    return EXIT_SUCCESS;
}

GitHub upstream.

which gives basically mostly system time as expected:

real    0m2.175s
user    0m0.001s
sys     0m1.476s

I was also curious to see if time would distinguish between syscalls of different processes, so I tried:

time ./sendfile.out sendfile.in1.tmp sendfile.out1.tmp &
time ./sendfile.out sendfile.in2.tmp sendfile.out2.tmp &

And the result was:

real    0m3.651s
user    0m0.000s
sys     0m1.516s

real    0m4.948s
user    0m0.000s
sys     0m1.562s

The sys time is about the same for both as for a single process, but the wall time is larger because the processes are competing for disk read access likely.

So it seems that it does in fact account for which process started a given kernel work.

Bash source code

When you do just time <cmd> on Ubuntu, it use the Bash keyword as can be seen from:

type time

which outputs:

time is a shell keyword

So we grep source in the Bash 4.19 source code for the output string:

git grep '"user\b'

which leads us to execute_cmd.c function time_command, which uses:

  • gettimeofday() and getrusage() if both are available
  • times() otherwise

all of which are Linux system calls and POSIX functions.

GNU Coreutils source code

If we call it as:

/usr/bin/time

then it uses the GNU Coreutils implementation.

This one is a bit more complex, but the relevant source seems to be at resuse.c and it does:

  • a non-POSIX BSD wait3 call if that is available
  • times and gettimeofday otherwise

Inserting a PDF file in LaTeX

There is an option without additional packages that works under pdflatex

Adapt this code

\begin{figure}[h]
    \centering
    \includegraphics[width=\ScaleIfNeeded]{figuras/diagrama-spearman.pdf}
    \caption{Schematical view of Spearman's theory.}
\end{figure}

"diagrama-spearman.pdf" is a plot generated with TikZ and this is the code (it is another .tex file different from the .tex file where I want to insert a pdf)

\documentclass[border=3mm]{standalone}
\usepackage[applemac]{inputenc}
\usepackage[protrusion=true,expansion=true]{microtype}
\usepackage[bb=lucida,bbscaled=1,cal=boondoxo]{mathalfa}
\usepackage[stdmathitalics=true,math-style=iso,lucidasmallscale=true,romanfamily=bright]{lucimatx}
\usepackage{tikz}
\usetikzlibrary{intersections}
\newcommand{\at}{\makeatletter @\makeatother}

\begin{document}

\begin{tikzpicture}
\tikzset{venn circle/.style={draw,circle,minimum width=5cm,fill=#1,opacity=1}}
\node [venn circle = none, name path=A] (A) at (45:2cm) { };
\node [venn circle = none, name path=B] (B) at (135:2cm) { };
\node [venn circle = none, name path=C] (C) at (225:2cm) { };
\node [venn circle = none, name path=D] (D) at (315:2cm) { };
\node[above right] at (barycentric cs:A=1) {logical}; 
\node[above left] at (barycentric cs:B=1) {mechanical}; 
\node[below left] at (barycentric cs:C=1) {spatial}; 
\node[below right] at (barycentric cs:D=1) {arithmetical}; 
\node at (0,0) {G};    
\end{tikzpicture}

\end{document} 

This is the diagram I included

enter image description here

How to Use -confirm in PowerShell

For when you want a 1-liner

while( -not ( ($choice= (Read-Host "May I continue?")) -match "y|n")){ "Y or N ?"}

correct way to define class variables in Python

Neither way is necessarily correct or incorrect, they are just two different kinds of class elements:

  • Elements outside the __init__ method are static elements; they belong to the class.
  • Elements inside the __init__ method are elements of the object (self); they don't belong to the class.

You'll see it more clearly with some code:

class MyClass:
    static_elem = 123

    def __init__(self):
        self.object_elem = 456

c1 = MyClass()
c2 = MyClass()

# Initial values of both elements
>>> print c1.static_elem, c1.object_elem 
123 456
>>> print c2.static_elem, c2.object_elem
123 456

# Nothing new so far ...

# Let's try changing the static element
MyClass.static_elem = 999

>>> print c1.static_elem, c1.object_elem
999 456
>>> print c2.static_elem, c2.object_elem
999 456

# Now, let's try changing the object element
c1.object_elem = 888

>>> print c1.static_elem, c1.object_elem
999 888
>>> print c2.static_elem, c2.object_elem
999 456

As you can see, when we changed the class element, it changed for both objects. But, when we changed the object element, the other object remained unchanged.

Reading HTML content from a UIWebView

Note that the NSString stringWithContentsOfURL will report a totally different user-agent string than the UIWebView making the same request. So if your server is user-agent aware, and sending back different html depending on who is asking for it, you may not get correct results this way.

Also note that the @"document.body.innerHTML" mentioned above will only display what is in the body tag. If you use @"document.all[0].innerHTML" you will get both head and body. Which is still not the complete contents of the UIWebView, since it will not get back the !doctype or html tags, but it is a lot closer.

What does "export" do in shell programming?

it makes the assignment visible to subprocesses.

$ foo=bar
$ bash -c 'echo $foo'

$ export foo
$ bash -c 'echo $foo'
bar

Change input text border color without changing its height

Set a transparent border and then change it:

.default{
border: 2px solid transparent;
}

.new{
border: 2px solid red;
}

"An exception occurred while processing your request. Additionally, another exception occurred while executing the custom error page..."

You can use Oracle.ManagedDataAccess.dll instead (download from Oracle), include that dll in you project bin dir, add reference to that dll in the project. In code, "using Oracle.MangedDataAccess.Client". Deploy project to server as usual. No need install Oracle Client on server. No need to add assembly info in web.config.

how to make a jquery "$.post" request synchronous

jQuery < 1.8

May I suggest that you use $.ajax() instead of $.post() as it's much more customizable.

If you are calling $.post(), e.g., like this:

$.post( url, data, success, dataType );

You could turn it into its $.ajax() equivalent:

$.ajax({
  type: 'POST',
  url: url,
  data: data,
  success: success,
  dataType: dataType,
  async:false
});

Please note the async:false at the end of the $.ajax() parameter object.

Here you have a full detail of the $.ajax() parameters: jQuery.ajax() – jQuery API Documentation.


jQuery >=1.8 "async:false" deprecation notice

jQuery >=1.8 won't block the UI during the http request, so we have to use a workaround to stop user interaction as long as the request is processed. For example:

  • use a plugin e.g. BlockUI;
  • manually add an overlay before calling $.ajax(), and then remove it when the AJAX .done() callback is called.

Please have a look at this answer for an example.

jQuery.ajax handling continue responses: "success:" vs ".done"?

success has been the traditional name of the success callback in jQuery, defined as an option in the ajax call. However, since the implementation of $.Deferreds and more sophisticated callbacks, done is the preferred way to implement success callbacks, as it can be called on any deferred.

For example, success:

$.ajax({
  url: '/',
  success: function(data) {}
});

For example, done:

$.ajax({url: '/'}).done(function(data) {});

The nice thing about done is that the return value of $.ajax is now a deferred promise that can be bound to anywhere else in your application. So let's say you want to make this ajax call from a few different places. Rather than passing in your success function as an option to the function that makes this ajax call, you can just have the function return $.ajax itself and bind your callbacks with done, fail, then, or whatever. Note that always is a callback that will run whether the request succeeds or fails. done will only be triggered on success.

For example:

function xhr_get(url) {

  return $.ajax({
    url: url,
    type: 'get',
    dataType: 'json',
    beforeSend: showLoadingImgFn
  })
  .always(function() {
    // remove loading image maybe
  })
  .fail(function() {
    // handle request failures
  });

}

xhr_get('/index').done(function(data) {
  // do stuff with index data
});

xhr_get('/id').done(function(data) {
  // do stuff with id data
});

An important benefit of this in terms of maintainability is that you've wrapped your ajax mechanism in an application-specific function. If you decide you need your $.ajax call to operate differently in the future, or you use a different ajax method, or you move away from jQuery, you only have to change the xhr_get definition (being sure to return a promise or at least a done method, in the case of the example above). All the other references throughout the app can remain the same.

There are many more (much cooler) things you can do with $.Deferred, one of which is to use pipe to trigger a failure on an error reported by the server, even when the $.ajax request itself succeeds. For example:

function xhr_get(url) {

  return $.ajax({
    url: url,
    type: 'get',
    dataType: 'json'
  })
  .pipe(function(data) {
    return data.responseCode != 200 ?
      $.Deferred().reject( data ) :
      data;
  })
  .fail(function(data) {
    if ( data.responseCode )
      console.log( data.responseCode );
  });
}

xhr_get('/index').done(function(data) {
  // will not run if json returned from ajax has responseCode other than 200
});

Read more about $.Deferred here: http://api.jquery.com/category/deferred-object/

NOTE: As of jQuery 1.8, pipe has been deprecated in favor of using then in exactly the same way.

Add leading zeroes to number in Java?

Another option is to use DecimalFormat to format your numeric String. Here is one other way to do the job without having to use String.format if you are stuck in the pre 1.5 world:

static String intToString(int num, int digits) {
    assert digits > 0 : "Invalid number of digits";

    // create variable length array of zeros
    char[] zeros = new char[digits];
    Arrays.fill(zeros, '0');
    // format number as String
    DecimalFormat df = new DecimalFormat(String.valueOf(zeros));

    return df.format(num);
}

HTML5 form validation pattern alphanumeric with spaces?

How about adding a space in the pattern attribute like pattern="[a-zA-Z0-9 ]+". If you want to support any kind of space try pattern="[a-zA-Z0-9\s]+"

Import data.sql MySQL Docker Container

You can import database afterwards:

docker exec -i mysql-container mysql -uuser -ppassword name_db < data.sql

ASP.NET Web API - PUT & DELETE Verbs Not Allowed - IIS 8

Just a quick update for anyone else who might run into this issue. As of today, changing the %userprofile%\documents\iisexpress\config\applicationhost.config does NOT work any longer (this was working fine until now, not sure if this is due to a Windows update). After hours of frustration, I changed the web.config to add these handlers to system.webserver to get it to work:

<handlers>
        <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
        <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
        <remove name="ExtensionlessUrlHandler-Integrated-4.0" />

        <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
        <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
        <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>

Generate random 5 characters string

works fine in PHP (php 5.4.4)

$seed = str_split('abcdefghijklmnopqrstuvwxyz');
$rand = array_rand($seed, 5);
$convert = array_map(function($n){
    global $seed;
    return $seed[$n];
},$rand);

$var = implode('',$convert);
echo $var;

Live Demo

Difference between Statement and PreparedStatement

PreparedStatement is a very good defense (but not foolproof) in preventing SQL injection attacks. Binding parameter values is a good way to guarding against "little Bobby Tables" making an unwanted visit.

how to parse JSON file with GSON

just parse as an array:

Review[] reviews = new Gson().fromJson(jsonString, Review[].class);

then if you need you can also create a list in this way:

List<Review> asList = Arrays.asList(reviews);

P.S. your json string should be look like this:

[
    {
        "reviewerID": "A2SUAM1J3GNN3B1",
        "asin": "0000013714",
        "reviewerName": "J. McDonald",
        "helpful": [2, 3],
        "reviewText": "I bought this for my husband who plays the piano.",
        "overall": 5.0,
        "summary": "Heavenly Highway Hymns",
        "unixReviewTime": 1252800000,
        "reviewTime": "09 13, 2009"
    },
    {
        "reviewerID": "A2SUAM1J3GNN3B2",
        "asin": "0000013714",
        "reviewerName": "J. McDonald",
        "helpful": [2, 3],
        "reviewText": "I bought this for my husband who plays the piano.",
        "overall": 5.0,
        "summary": "Heavenly Highway Hymns",
        "unixReviewTime": 1252800000,
        "reviewTime": "09 13, 2009"
    },

    [...]
]

What is an NP-complete in computer science?

What is NP?

NP is the set of all decision problems (questions with a yes-or-no answer) for which the 'yes'-answers can be verified in polynomial time (O(nk) where n is the problem size, and k is a constant) by a deterministic Turing machine. Polynomial time is sometimes used as the definition of fast or quickly.

What is P?

P is the set of all decision problems which can be solved in polynomial time by a deterministic Turing machine. Since they can be solved in polynomial time, they can also be verified in polynomial time. Therefore P is a subset of NP.

What is NP-Complete?

A problem x that is in NP is also in NP-Complete if and only if every other problem in NP can be quickly (ie. in polynomial time) transformed into x.

In other words:

  1. x is in NP, and
  2. Every problem in NP is reducible to x

So, what makes NP-Complete so interesting is that if any one of the NP-Complete problems was to be solved quickly, then all NP problems can be solved quickly.

See also the post What's "P=NP?", and why is it such a famous question?

What is NP-Hard?

NP-Hard are problems that are at least as hard as the hardest problems in NP. Note that NP-Complete problems are also NP-hard. However not all NP-hard problems are NP (or even a decision problem), despite having NP as a prefix. That is the NP in NP-hard does not mean non-deterministic polynomial time. Yes, this is confusing, but its usage is entrenched and unlikely to change.

Add up a column of numbers at the Unix shell

I would use "du" instead.

$ cat files.txt | xargs du -c | tail -1
4480    total

If you just want the number:

cat files.txt | xargs du -c | tail -1 | awk '{print $1}'