Programs & Examples On #Convex hull

Convex-hull of a set of points X in a Euclidean space is the convex set with smallest area that contains all points of X.

How to tell whether a point is to the right or left side of a line

Here's a version, again using the cross product logic, written in Clojure.

(defn is-left? [line point]
  (let [[[x1 y1] [x2 y2]] (sort line)
        [x-pt y-pt] point]
    (> (* (- x2 x1) (- y-pt y1)) (* (- y2 y1) (- x-pt x1)))))

Example usage:

(is-left? [[-3 -1] [3 1]] [0 10])
true

Which is to say that the point (0, 10) is to the left of the line determined by (-3, -1) and (3, 1).

NOTE: This implementation solves a problem that none of the others (so far) does! Order matters when giving the points that determine the line. I.e., it's a "directed line", in a certain sense. So with the above code, this invocation also produces the result of true:

(is-left? [[3 1] [-3 -1]] [0 10])
true

That's because of this snippet of code:

(sort line)

Finally, as with the other cross product based solutions, this solution returns a boolean, and does not give a third result for collinearity. But it will give a result that makes sense, e.g.:

(is-left? [[1 1] [3 1]] [10 1])
false

Call a Javascript function every 5 seconds continuously

Good working example here: http://jsfiddle.net/MrTest/t4NXD/62/

Plus:

  • has nice fade in / fade out animation
  • will pause on :hover
  • will prevent running multiple actions (finish run animation before starting second)
  • will prevent going broken when in the tab ( browser stops scripts in the tabs)

Tested and working!

javascript: get a function's variable's value within another function

Your nameContent scope is only inside first function. You'll never get it's value that way.

var nameContent; // now it's global!
function first(){
    nameContent = document.getElementById('full_name').value;
}

function second() {
    first(); 
    y=nameContent; 
    alert(y);
}
second();

String's Maximum length in Java - calling length() method

Considering the String class' length method returns an int, the maximum length that would be returned by the method would be Integer.MAX_VALUE, which is 2^31 - 1 (or approximately 2 billion.)

In terms of lengths and indexing of arrays, (such as char[], which is probably the way the internal data representation is implemented for Strings), Chapter 10: Arrays of The Java Language Specification, Java SE 7 Edition says the following:

The variables contained in an array have no names; instead they are referenced by array access expressions that use nonnegative integer index values. These variables are called the components of the array. If an array has n components, we say n is the length of the array; the components of the array are referenced using integer indices from 0 to n - 1, inclusive.

Furthermore, the indexing must be by int values, as mentioned in Section 10.4:

Arrays must be indexed by int values;

Therefore, it appears that the limit is indeed 2^31 - 1, as that is the maximum value for a nonnegative int value.

However, there probably are going to be other limitations, such as the maximum allocatable size for an array.

Provide an image for WhatsApp link sharing

Following actions helped in my case.

Putting image under the same host.

<meta property="og:url" content="https://www.same-host.com/whatsapp-image.png" />

Passing needed image to WhatsApp specifically by detecting its user agent by leading substring, example

WhatsApp/2.18.380 A

Waiting few seconds before actually pushing send button, so WhatsApp will have time to retrieve image and description from og metadata.

How can I uninstall npm modules in Node.js?

I just install stylus by default under my home dir, so I just use npm uninstall stylus to detach it, or you can try npm rm <package_name> out.

Can you call ko.applyBindings to bind a partial view?

I've managed to bind a custom model to an element at runtime. The code is here: http://jsfiddle.net/ZiglioNZ/tzD4T/457/

The interesting bit is that I apply the data-bind attribute to an element I didn't define:

    var handle = slider.slider().find(".ui-slider-handle").first();
    $(handle).attr("data-bind", "tooltip: viewModel.value");
    ko.applyBindings(viewModel.value, $(handle)[0]);

How to use ng-repeat for dictionaries in AngularJs?

You can use

<li ng-repeat="(name, age) in items">{{name}}: {{age}}</li>

See ngRepeat documentation. Example: http://jsfiddle.net/WRtqV/1/

How to use registerReceiver method?

The whole code if somebody need it.

void alarm(Context context, Calendar calendar) {
    AlarmManager alarmManager = (AlarmManager)context.getSystemService(ALARM_SERVICE);

    final String SOME_ACTION = "com.android.mytabs.MytabsActivity.AlarmReceiver";
    IntentFilter intentFilter = new IntentFilter(SOME_ACTION);

    AlarmReceiver mReceiver = new AlarmReceiver();
    context.registerReceiver(mReceiver, intentFilter);

    Intent anotherIntent = new Intent(SOME_ACTION);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, anotherIntent, 0);
    alramManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);

    Toast.makeText(context, "Added", Toast.LENGTH_LONG).show();
}

class AlarmReceiver extends BroadcastReceiver {     
    @Override
    public void onReceive(Context context, Intent arg1) {
        Toast.makeText(context, "Started", Toast.LENGTH_LONG).show();
    }
}

Add vertical scroll bar to panel

Try this instead for 'only' scrolling vertical.
(auto scroll needs to be false before it will accept changes)

mypanel.AutoScroll = false;
mypanel.HorizontalScroll.Enabled = false;
mypanel.HorizontalScroll.Visible = false;
mypanel.HorizontalScroll.Maximum = 0;
mypanel.AutoScroll = true;

How to add subject alernative name to ssl certs?

Both IP and DNS can be specified with the keytool additional argument -ext SAN=dns:abc.com,ip:1.1.1.1

Example:

keytool -genkeypair -keystore <keystore> -dname "CN=test, OU=Unknown, O=Unknown, L=Unknown, ST=Unknown, C=Unknown" -keypass <keypwd> -storepass <storepass> -keyalg RSA -alias unknown -ext SAN=dns:test.abc.com,ip:1.1.1.1

Fast check for NaN in NumPy

  1. use .any()

    if numpy.isnan(myarray).any()

  2. numpy.isfinite maybe better than isnan for checking

    if not np.isfinite(prop).all()

Implementing a HashMap in C

The primary goal of a hashmap is to store a data set and provide near constant time lookups on it using a unique key. There are two common styles of hashmap implementation:

  • Separate chaining: one with an array of buckets (linked lists)
  • Open addressing: a single array allocated with extra space so index collisions may be resolved by placing the entry in an adjacent slot.

Separate chaining is preferable if the hashmap may have a poor hash function, it is not desirable to pre-allocate storage for potentially unused slots, or entries may have variable size. This type of hashmap may continue to function relatively efficiently even when the load factor exceeds 1.0. Obviously, there is extra memory required in each entry to store linked list pointers.

Hashmaps using open addressing have potential performance advantages when the load factor is kept below a certain threshold (generally about 0.7) and a reasonably good hash function is used. This is because they avoid potential cache misses and many small memory allocations associated with a linked list, and perform all operations in a contiguous, pre-allocated array. Iteration through all elements is also cheaper. The catch is hashmaps using open addressing must be reallocated to a larger size and rehashed to maintain an ideal load factor, or they face a significant performance penalty. It is impossible for their load factor to exceed 1.0.

Some key performance metrics to evaluate when creating a hashmap would include:

  • Maximum load factor
  • Average collision count on insertion
  • Distribution of collisions: uneven distribution (clustering) could indicate a poor hash function.
  • Relative time for various operations: put, get, remove of existing and non-existing entries.

Here is a flexible hashmap implementation I made. I used open addressing and linear probing for collision resolution.

https://github.com/DavidLeeds/hashmap

Change x axes scale in matplotlib

This is not so much an answer to your original question as to one of the queries you had in the body of your question.

A little preamble, so that my naming doesn't seem strange:

import matplotlib
from matplotlib import rc
from matplotlib.figure import Figure
ax = self.figure.add_subplot( 111 )

As has been mentioned you can use ticklabel_format to specify that matplotlib should use scientific notation for large or small values:

ax.ticklabel_format(style='sci',scilimits=(-3,4),axis='both')

You can affect the way that this is displayed using the flags in rcParams (from matplotlib import rcParams) or by setting them directly. I haven't found a more elegant way of changing between '1e' and 'x10^' scientific notation than:

ax.xaxis.major.formatter._useMathText = True

This should give you the more Matlab-esc, and indeed arguably better appearance. I think the following should do the same:

rc('text', usetex=True)

What is difference between Implicit wait and Explicit wait in Selenium WebDriver?

Differences:

1) Implicit wait is set for the entire duration of the webDriver object. Suppose , you want to wait for a certain duration, let's say 5 seconds before each element or a lot of elements on the webpage load. Now, you wouldn't want to write the same code again and again. Hence, implicit wait. However, if you want to wait for only one element, use explicit.

2) You not only need web element to show up but also to be clickable or to satisfy certain other property of web elements. Such kind of flexibility can be provided by explicit wait only. Specially helpful if dynamic data is being loaded on webpage. You can wait for that element to be developed (not just show up on DOM) using explicit wait.

Access Enum value using EL with JSTL

So to get my problem fully resolved I needed to do the following:

<% pageContext.setAttribute("old", Status.OLD); %>

Then I was able to do:

<c:when test="${someModel.status == old}"/>...</c:when>

which worked as expected.

Populating a database in a Laravel migration file

This should do what you want.

public function up()
{
    DB::table('user')->insert(array('username'=>'dude', 'password'=>'z19pers!'));
}

How to display the current time and date in C#

label1.Text = DateTime.Now.ToLongTimeString();//its for current date

label1.Text = DateTime.Now.ToLongDateString();//its for current time

How to fix java.net.SocketException: Broken pipe?

SocketException: Broken pipe, is caused by the 'other end' (The client or the server) closing the connection while your code is either reading from or writing to the connection.

This is a very common exception in client/server applications that receive traffic from clients or servers outside of the application control. For example, the client is a browser. If the browser makes an Ajax call, and/or the user simply closes the page or browser, then this can effectively kill all communication unexpectedly. Basically, you will see this error any time the other end terminates their application, and you were not anticipating it.

If you experience this Exception in your application, then it means you should check your code where the IO (Input/Output) occurs and wrap it with a try/catch block to catch this IOException. It is then, up to you to decide how you want to handle this semi-valid situation.

In your case, the earliest place where you still have control is the call to HttpMethodDirector.executeWithRetry - So ensure that call is wrapped with the try/catch block, and handle it how you see fit.

I would strongly advise against logging SocketException-Broken Pipe specific errors at anything other than debug/trace levels. Else, this can be used as a form of DOS (Denial Of Service) attack by filling up the logs. Try and harden and negative-test your application for this common scenario.

How can I make a list of installed packages in a certain virtualenv?

list out the installed packages in the virtualenv

step 1:

workon envname

step 2:

pip freeze

it will display the all installed packages and installed packages and versions

How do I set up Eclipse/EGit with GitHub?

In Eclipse, go to Help -> Install New Software -> Add -> Name: any name like egit; Location: http://download.eclipse.org/egit/updates -> Okay. Now Search for egit in Work with and select all the check boxes and press Next till finish.

File -> Import -> search Git and select "Projects from Git" -> Clone URI. In the URI, paste the HTTPS URL of the repository (the one with .git extension). -> Next ->It will show all the branches "Next" -> Local Destination "Next" -> "Import as a general project" -> Next till finish.

You can refer to this Youtube tutorial: https://www.youtube.com/watch?v=ptK9-CNms98

Creating a config file in PHP

Here is my way.

    <?php

    define('DEBUG',0);

    define('PRODUCTION',1);



    #development_mode : DEBUG / PRODUCTION

    $development_mode = PRODUCTION;



    #Website root path for links

    $app_path = 'http://192.168.0.234/dealer/';



    #User interface files path

    $ui_path = 'ui/';

    #Image gallery path

    $gallery_path = 'ui/gallery/';


    $mysqlserver = "localhost";
    $mysqluser = "root";
    $mysqlpass = "";
    $mysqldb = "dealer_plus";

   ?>

Any doubts please comment

What is the best way to ensure only one instance of a Bash script is running?

i found this in procmail package dependencies:

apt install liblockfile-bin

To run: dotlockfile -l file.lock

file.lock will be created.

To unlock: dotlockfile -u file.lock

Use this to list this package files / command: dpkg-query -L liblockfile-bin

How do I iterate through the files in a directory in Java?

For Java 7+, there is also https://docs.oracle.com/javase/7/docs/api/java/nio/file/DirectoryStream.html

Example taken from the Javadoc:

List<Path> listSourceFiles(Path dir) throws IOException {
   List<Path> result = new ArrayList<>();
   try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, "*.{c,h,cpp,hpp,java}")) {
       for (Path entry: stream) {
           result.add(entry);
       }
   } catch (DirectoryIteratorException ex) {
       // I/O error encounted during the iteration, the cause is an IOException
       throw ex.getCause();
   }
   return result;
}

How to add a footer to the UITableView?

Swift 2.1.1 below works:

func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let v = UIView()
        v.backgroundColor = UIColor.RGB(53, 60, 62)
        return v
    }

    func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 80
    }

If use self.theTable.tableFooterView = tableFooter there is a space between last row and tableFooterView.

Seaborn plots not showing up

To tell from the style of your code snippet, I suppose you were using IPython rather than Jupyter Notebook.

In this issue on GitHub, it was made clear by a member of IPython in 2016 that the display of charts would only work when "only work when it's a Jupyter kernel". Thus, the %matplotlib inline would not work.

I was just having the same issue and suggest you use Jupyter Notebook for the visualization.

Confusing "duplicate identifier" Typescript error message

In my case I got the error as

node_modules/@types/es6-promise/index.d.ts(11,15): error TS2300: Duplicate identifier 'Promise'.

And I had @types/es6-promise on my package.json but my tsconfig was already with target: "es6". So I guess there was a conflict with Promise when compiling.

Removing @types/es6-promise from my package.json file solved the issue.

"This operation requires IIS integrated pipeline mode."

GitHub solution solved the problem for me by adding

  • Global.asax.cs: Set AntiForgeryConfig.SuppressXFrameOptionsHeader = true; in Application_Start:
  • Manually add the X-Frame-Options header in Application_BeginRequest

VBA EXCEL To Prompt User Response to Select Folder and Return the Path as String Variable

Consider:

Function GetFolder() As String
    Dim fldr As FileDialog
    Dim sItem As String
    Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
    With fldr
        .Title = "Select a Folder"
        .AllowMultiSelect = False
        .InitialFileName = Application.DefaultFilePath
        If .Show <> -1 Then GoTo NextCode
        sItem = .SelectedItems(1)
    End With
NextCode:
    GetFolder = sItem
    Set fldr = Nothing
End Function

This code was adapted from Ozgrid

and as jkf points out, from Mr Excel

Indentation shortcuts in Visual Studio

Visual studio’s smart indenting does automatically indenting, but we can select a block or all the code for indentation.

  1. Select all the code: Ctrl+a

  2. Use either of the two ways to indentation the code:

    • Shift+Tab,

    • Ctrl+k+f.

How to completely uninstall python 2.7.13 on Ubuntu 16.04

This is what I have after doing purge of all the python versions and reinstalling only 3.6.

root@esp32:/# python
Python 3.6.0b2 (default, Oct 11 2016, 05:27:10) 
[GCC 6.2.0 20161005] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 
root@esp32:/# python3
Python 3.8.0 (default, Dec 15 2019, 14:19:02) 
[GCC 6.2.0 20161005] on linux
Type "help", "copyright", "credits" or "license" for more information.

Also the pip and pip3 commands are totally f up:

root@esp32:/# pip
Traceback (most recent call last):
  File "/usr/local/bin/pip", line 7, in <module>
    from pip._internal.cli.main import main
  File "/usr/local/lib/python3.5/dist-packages/pip/_internal/cli/main.py", line 60
    sys.stderr.write(f"ERROR: {exc}")
                                   ^
SyntaxError: invalid syntax

root@esp32:/# pip3
Traceback (most recent call last):
  File "/usr/local/bin/pip3", line 7, in <module>
    from pip._internal.cli.main import main
  File "/usr/local/lib/python3.5/dist-packages/pip/_internal/cli/main.py", line 60
    sys.stderr.write(f"ERROR: {exc}")
                                   ^
SyntaxError: invalid syntax

I am totally noob at Linux, I just wanted to update Python from 2.x to 3.x so that Platformio could upgrade and now I messed up everything it seems.

Array String Declaration

You are not initializing your String[]. You either need to initialize it using the exact array size, as suggested by @Tr?nSiLong, or use a List<String> and then convert to a String[] (in case you do not know the length):

String[] title = {
        "Abundance",
        "Anxiety",
        "Bruxism",
        "Discipline",
        "Drug Addiction"
    };
String urlbase = "http://www.somewhere.com/data/";
String imgSel = "/logo.png";
List<String> mStrings = new ArrayList<String>();

for(int i=0;i<title.length;i++) {
    mStrings.add(urlbase + title[i].toLowerCase() + imgSel);

    System.out.println(mStrings[i]);
}

String[] strings = new String[mStrings.size()];
strings = mStrings.toArray(strings);//now strings is the resulting array

DataTables warning: Requested unknown parameter '0' from the data source for row '0'

You're using an array of objects. Can you use a two dimensional array instead?

http://www.datatables.net/examples/data_sources/js_array.html

See this jsfiddle: http://jsfiddle.net/QhYse/

I used an array like this and it worked fine:

var data = [
    ["UpdateBootProfile","PASS","00:00:00",[]] ,
    ["NRB Boot","PASS","00:00:50.5000000",[{"TestName":"TOTAL_TURN_ON_TIME","Result":"PASS","Value":"50.5","LowerLimit":"NaN","UpperLimit":"NaN","ComparisonType":"nctLOG","Units":"SECONDS"}]] ,
    ["NvMgrCommit","PASS","00:00:00",[]] ,
    ["SyncNvToEFS","PASS","00:00:01.2500000",[]]
];

Edit to include array of objects

There's a possible solution from this question: jQuery DataTables fnrender with objects

This jsfiddle http://jsfiddle.net/j2C7j/ uses an array of objects. To not get the error I had to pad it with 3 blank values - less than optimal, I know. You may find a better way with fnRender, please post if you do.

var data = [
   ["","","", {"Name":"UpdateBootProfile","Result":"PASS","ExecutionTime":"00:00:00","Measurement":[]} ]

];

$(function() {
        var testsTable = $('#tests').dataTable({
                bJQueryUI: true,
                aaData: data,
                aoColumns: [
                        { mData: 'Name', "fnRender": function( oObj ) { return oObj.aData[3].Name}},
                        { mData: 'Result' ,"fnRender": function( oObj ) { return oObj.aData[3].Result }},
                        { mData: 'ExecutionTime',"fnRender": function( oObj ) { return oObj.aData[3].ExecutionTime } }
                ]
        });
});

invalid use of non-static member function

You shall pass a this pointer to tell the function which object to work on because it relies on that as opposed to a static member function.

How can I change the color of my prompt in zsh (different from normal text)?

Try my favorite: put in

~/.zshrc

this line:

PROMPT='%F{240}%n%F{red}@%F{green}%m:%F{141}%d$ %F{reset}'

don't forget

source ~/.zshrc

to test the changes

you can change the colors/color codes, of course :-)

How to get the scroll bar with CSS overflow on iOS

Apply this code in your css

::-webkit-scrollbar{

    -webkit-appearance: none;
    width: 7px;

}

::-webkit-scrollbar-thumb {

    border-radius: 4px;
    background-color: rgba(0,0,0,.5); 
    -webkit-box-shadow: 0 0 1px rgba(255,255,255,.5);
}

How can I convert integer into float in Java?

You just need to transfer the first value to float, before it gets involved in further computations:

float z = x * 1.0 / y;

How do I do an initial push to a remote repository with Git?

I am aware there are existing answers which solves the problem. For those who are new to git, As of 02/11/2021, The default branch in git is "main" not "master" branch, The command will be

git push -u origin main

How to upload files on server folder using jsp

Below code is working on my live server as well as in my own Lapy.

Note:

Please Create data folder in WebContent and put in any single image or any file(jsp or html file).

Add jar files

commons-collections-3.1.jar
commons-fileupload-1.2.2.jar
commons-io-2.1.jar
commons-logging-1.0.4.jar

upload.jsp

    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
       pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>File Upload</title>
</head>
<body>
<form method="post" action="UploadServlet" enctype="multipart/form-data">
Select file to upload:
<input type="file" name="dataFile" id="fileChooser"/><br/><br/>
<input type="submit" value="Upload" />
</form>
</body>
</html>

UploadServlet.java

package com.servlet;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * Servlet implementation class UploadServlet
 */
public class UploadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    private static final String DATA_DIRECTORY = "data";
    private static final int MAX_MEMORY_SIZE = 1024 * 1024 * 2;
    private static final int MAX_REQUEST_SIZE = 1024 * 1024;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // Check that we have a file upload request
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);

        if (!isMultipart) {
            return;
        }

        // Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory();

        // Sets the size threshold beyond which files are written directly to
        // disk.
        factory.setSizeThreshold(MAX_MEMORY_SIZE);

        // Sets the directory used to temporarily store files that are larger
        // than the configured size threshold. We use temporary directory for
        // java
        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

        // constructs the folder where uploaded file will be stored
        String uploadFolder = getServletContext().getRealPath("")
                + File.separator + DATA_DIRECTORY;

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        // Set overall request size constraint
        upload.setSizeMax(MAX_REQUEST_SIZE);

        try {
            // Parse the request
            List items = upload.parseRequest(request);
            Iterator iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();

                if (!item.isFormField()) {
                    String fileName = new File(item.getName()).getName();
                    String filePath = uploadFolder + File.separator + fileName;
                    File uploadedFile = new File(filePath);
                    System.out.println(filePath);
                    // saves the file to upload directory
                    item.write(uploadedFile);
                }
            }

            // displays done.jsp page after upload finished
            getServletContext().getRequestDispatcher("/done.jsp").forward(
                    request, response);

        } catch (FileUploadException ex) {
            throw new ServletException(ex);
        } catch (Exception ex) {
            throw new ServletException(ex);
        }

    }

}

web.xml

  <servlet>
    <description></description>
    <display-name>UploadServlet</display-name>
    <servlet-name>UploadServlet</servlet-name>
    <servlet-class>com.servlet.UploadServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>UploadServlet</servlet-name>
    <url-pattern>/UploadServlet</url-pattern>
  </servlet-mapping>

done.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
   pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Upload Done</title>
</head>
<body>
<h3>Your file has been uploaded!</h3>
</body>
</html>

How do I edit SSIS package files?

Adding to what b_levitt said, you can get the SSDT-BI plugin for Visual Studio 2013 here: http://www.microsoft.com/en-us/download/details.aspx?id=42313

Changing Fonts Size in Matlab Plots

Jonas's answer is good, but I had to modify it slightly to get every piece of text on the screen to change:

set(gca,'FontSize',30,'fontWeight','bold')

set(findall(gcf,'type','text'),'FontSize',30,'fontWeight','bold')

align 3 images in same row with equal spaces?

I assumed the first DIV is #content :

<div id="content">
   <img src="@Url.Content("~/images/image1.bmp")" alt="" />
   <img src="@Url.Content("~/images/image2.bmp")" alt="" />
   <img src="@Url.Content("~/images/image3.bmp")" alt="" />
</div>

And CSS :

#content{
         width: 700px;
         display: block;
         height: auto;
     }
     #content > img{
        float: left; width: 200px;
        height: 200px;
        margin: 5px 8px;
     }

How to impose maxlength on textArea in HTML using JavaScript

I know you want to avoid jQuery, but as the solution requires JavaScript, this solution (using jQuery 1.4) is the most consise and robust.

Inspired by, but an improvement over Dana Woodman's answer:

Changes from that answer are: Simplified and more generic, using jQuery.live and also not setting val if length is OK (leads to working arrow-keys in IE, and noticable speedup in IE):

// Get all textareas that have a "maxlength" property. Now, and when later adding HTML using jQuery-scripting:
$('textarea[maxlength]').live('keyup blur', function() {
    // Store the maxlength and value of the field.
    var maxlength = $(this).attr('maxlength');
    var val = $(this).val();

    // Trim the field if it has content over the maxlength.
    if (val.length > maxlength) {
        $(this).val(val.slice(0, maxlength));
    }
});

EDIT: Updated version for jQuery 1.7+, using on instead of live

// Get all textareas that have a "maxlength" property. Now, and when later adding HTML using jQuery-scripting:
$('textarea[maxlength]').on('keyup blur', function() {
    // Store the maxlength and value of the field.
    var maxlength = $(this).attr('maxlength');
    var val = $(this).val();

    // Trim the field if it has content over the maxlength.
    if (val.length > maxlength) {
        $(this).val(val.slice(0, maxlength));
    }
});

What is the maximum number of characters that nvarchar(MAX) will hold?

From char and varchar (Transact-SQL)

varchar [ ( n | max ) ]

Variable-length, non-Unicode character data. n can be a value from 1 through 8,000. max indicates that the maximum storage size is 2^31-1 bytes. The storage size is the actual length of data entered + 2 bytes. The data entered can be 0 characters in length. The ISO synonyms for varchar are char varying or character varying.

How to check postgres user and password?

You may change the pg_hba.conf and then reload the postgresql. something in the pg_hba.conf may be like below:

# "local" is for Unix domain socket connections only
local   all             all                                     trust
# IPv4 local connections:
host    all             all             127.0.0.1/32            trust

then you change your user to postgresql, you may login successfully.

su postgresql

How to save .xlsx data to file as a blob

Here's my implementation using the fetch api. The server endpoint sends a stream of bytes and the client receives a byte array and creates a blob out of it. A .xlsx file will then be generated.

return fetch(fullUrlEndpoint, options)
  .then((res) => {
    if (!res.ok) {
      const responseStatusText = res.statusText
      const errorMessage = `${responseStatusText}`
      throw new Error(errorMessage);
    }
    return res.arrayBuffer();
  })
    .then((ab) => {
      // BE endpoint sends a readable stream of bytes
      const byteArray = new Uint8Array(ab);
      const a = window.document.createElement('a');
      a.href = window.URL.createObjectURL(
        new Blob([byteArray], {
          type:
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        }),
      );
      a.download = `${fileName}.XLSX`;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
    })
    .catch(error => {
      throw new Error('Error occurred:' + error);
    });

how to fix Cannot call sendRedirect() after the response has been committed?

The root cause of IllegalStateException exception is a java servlet is attempting to write to the output stream (response) after the response has been committed.

It is always better to ensure that no content is added to the response after the forward or redirect is done to avoid IllegalStateException. It can be done by including a ‘return’ statement immediately next to the forward or redirect statement.

JAVA 7 OFFICIAL LINK

ADDITIONAL INFO

How to disable mouse scroll wheel scaling with Google Maps API

Daniel's code does the job (thanks a heap!). But I wanted to disable zooming completely. I found I had to use all four of these options to do so:

{
  zoom: 14,                        // Set the zoom level manually
  zoomControl: false,
  scaleControl: false,
  scrollwheel: false,
  disableDoubleClickZoom: true,
  ...
}

See: MapOptions object specification

Python Selenium Chrome Webdriver

You need to specify the path where your chromedriver is located.

  1. Download chromedriver for your desired platform from here.

  2. Place chromedriver on your system path, or where your code is.

  3. If not using a system path, link your chromedriver.exe (For non-Windows users, it's just called chromedriver):

    browser = webdriver.Chrome(executable_path=r"C:\path\to\chromedriver.exe")
    

    (Set executable_path to the location where your chromedriver is located.)

    If you've placed chromedriver on your System Path, you can shortcut by just doing the following:

    browser = webdriver.Chrome()

  4. If you're running on a Unix-based operating system, you may need to update the permissions of chromedriver after downloading it in order to make it executable:

    chmod +x chromedriver

  5. That's all. If you're still experiencing issues, more info can be found on this other StackOverflow article: Can't use chrome driver for Selenium

Add a new line to a text file in MS-DOS

echo "text to echo" > file.txt

How to display an error message in an ASP.NET Web Application

Roughly you can do it like that :

try
{
    //do something
}
catch (Exception ex)
{
    string script = "<script>alert('" + ex.Message + "');</script>";
    if (!Page.IsStartupScriptRegistered("myErrorScript"))
    {
         Page.ClientScript.RegisterStartupScript("myErrorScript", script);
    }
}

But I recommend you to define your custom Exception and throw it anywhere you need. At your page catch this custom exception and register your message box script.

Set cellpadding and cellspacing in CSS?

I suggest this and all the cells for the particular table are effected.

table.tbl_classname td, th {
    padding: 5px 5px 5px 4px;
 }

@font-face src: local - How to use the local font if the user already has it?

I haven’t actually done anything with font-face, so take this with a pinch of salt, but I don’t think there’s any way for the browser to definitively tell if a given web font installed on a user’s machine or not.

The user could, for example, have a different font with the same name installed on their machine. The only way to definitively tell would be to compare the font files to see if they’re identical. And the browser couldn’t do that without downloading your web font first.

Does Firefox download the font when you actually use it in a font declaration? (e.g. h1 { font: 'DejaVu Serif';)?

Create an empty object in JavaScript with {} or new Object()?

Yes, There is a difference, they're not the same. It's true that you'll get the same results but the engine works in a different way for both of them. One of them is an object literal, and the other one is a constructor, two different ways of creating an object in javascript.

var objectA = {} //This is an object literal

var objectB = new Object() //This is the object constructor

In JS everything is an object, but you should be aware about the following thing with new Object(): It can receive a parameter, and depending on that parameter, it will create a string, a number, or just an empty object.

For example: new Object(1), will return a Number. new Object("hello") will return a string, it means that the object constructor can delegate -depending on the parameter- the object creation to other constructors like string, number, etc... It's highly important to keep this in mind when you're managing dynamic data to create objects..

Many authors recommend not to use the object constructor when you can use a certain literal notation instead, where you will be sure that what you're creating is what you're expecting to have in your code.

I suggest you to do a further reading on the differences between literal notation and constructors on javascript to find more details.

SQL JOIN vs IN performance?

Funny you mention that, I did a blog post on this very subject.

See Oracle vs MySQL vs SQL Server: Aggregation vs Joins

Short answer: you have to test it and individual databases vary a lot.

What's the net::ERR_HTTP2_PROTOCOL_ERROR about?

For my situation this error was caused by having circular references in json sent from the server when using an ORM for parent/child relationships. So the quick and easy solution was

JsonConvert.SerializeObject(myObject, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore })

The better solution is to create DTOs that do not contain the references on both sides (parent/child).

Date only from TextBoxFor()

The DisplayFormat attribute did not work for me in either form upon initial load. I created an EditorTemplate instead:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.DateTime>" %>
<%@ Import Namespace="System.Web.Mvc.Html" %>
<%=
    Html.TextBox("", Model.ToShortDateString(), new { @class = "date-range" }) %>

How do I list all cron jobs for all users?

I like the simple one-liner answer above:

for user in $(cut -f1 -d: /etc/passwd); do crontab -u $user -l; done

But Solaris which does not have the -u flag and does not print the user it's checking, you can modify it like so:

for user in $(cut -f1 -d: /etc/passwd); do echo User:$user; crontab -l $user 2>&1 | grep -v crontab; done

You will get a list of users without the errors thrown by crontab when an account is not allowed to use cron etc. Be aware that in Solaris, roles can be in /etc/passwd too (see /etc/user_attr).

lvalue required as left operand of assignment error when using C++

To assign, you should use p=p+1; instead of p+1=p;

int main()
{

   int x[3]={4,5,6};
   int *p=x;
   p=p+1; /*You just needed to switch the terms around*/
   cout<<p<<endl;
   getch();
}

Returning multiple values from a C++ function

rather than returning multiple values,just return one of them and make a reference of others in the required function for eg:

int divide(int a,int b,int quo,int &rem)

How to get the selected date value while using Bootstrap Datepicker?

For bootstrap datepicker you can use:

$("#inputWithDatePicer").data('datepicker').getFormattedDate('yyyy-mm-dd');

SQL Inner join more than two tables

A possible solution:

SELECT Company.Company_Id,Company.Company_Name,
    Invoice_Details.Invoice_No, Product_Details.Price
  FROM Company inner join Invoice_Details
    ON Company.Company_Id=Invoice_Details.Company_Id
 INNER JOIN Product_Details
        ON Invoice_Details.Invoice_No= Product_Details.Invoice_No
 WHERE Price='60000';

-- tets changes

How can I style the border and title bar of a window in WPF?

If someone says you can't because only Windows can control the non-client area, they're wrong!

That's just a half-truth because Windows lets you specify the dimensions of the non-client area. The fact is, this is possible only throughout the Windows' kernel methods, and you're in .NET, not C/C++. Anyway, don't worry! P/Invoke was meant just for such things! Indeed, the whole of the Windows Form UI and Console application Std-I/O methods are offered using system calls. Hence, you'd have only to perform the right system calls to set the non-client area up, as documented in MSDN.

However, this is a really hard solution I came up with a lot of time ago. Luckily, as of .NET 4.5, you can use the WindowChrome class to adjust the non-client area like you want. Here you can get to start with.

In order to make things simpler and cleaner, I'll redirect you here, a guide to change the window border dimensions to whatever you want. By setting it to 0, you'll be able to implement your custom window border in place of the system's one.

I'm sorry for not posting a clear example, but later I will for sure.

what is the use of "response.setContentType("text/html")" in servlet

response.setContentType("text/html");

Above code would be include in "HTTP response" to inform the browser about the format of the response, so that the browser can interpret it.

How to always show the vertical scrollbar in a browser?

_x000D_
_x000D_
// Nothing to show here
_x000D_
body {_x000D_
  height: 150vh;_x000D_
}_x000D_
_x000D_
::-webkit-scrollbar {_x000D_
  width: 15px;_x000D_
}_x000D_
_x000D_
::-webkit-scrollbar-thumb {_x000D_
  background: rgba(0, 0, 0, .6);_x000D_
}_x000D_
_x000D_
/* Of course you can style it even more */
_x000D_
<h1 style="margin: 0;position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%);font-family: Helvetica, Arial, sans-serif;">Scroll</h1>
_x000D_
_x000D_
_x000D_

How do the post increment (i++) and pre increment (++i) operators work in Java?

Pre-increment means that the variable is incremented BEFORE it's evaluated in the expression. Post-increment means that the variable is incremented AFTER it has been evaluated for use in the expression.

Therefore, look carefully and you'll see that all three assignments are arithmetically equivalent.

Changing navigation title programmatically

Swift 3

I created an outlet for the navigation title bar item that comes with the navigation bar (from the Object Browser) in the storyboard. Then I sued the line below:

navigationBarTitleItem.title = "Hello Bar"

How to remove undefined and null values from an object using lodash?

I like using _.pickBy, because you have full control over what you are removing:

var person = {"name":"bill","age":21,"sex":undefined,"height":null};

var cleanPerson = _.pickBy(person, function(value, key) {
  return !(value === undefined || value === null);
});

Source: https://www.codegrepper.com/?search_term=lodash+remove+undefined+values+from+object

Show a div with Fancybox

I use approach with appending "singleton" link for element you want to show in fancybox. This is code, what I use with some minor edits:

function showElementInPopUp(elementId) {
    var fancyboxAnchorElementId = "fancyboxTriggerFor_" + elementId;
    if ($("#"+fancyboxAnchorElementId).length == 0) {
        $("body").append("<a id='" + fancyboxAnchorElementId + "' href='#" + elementId+ "' style='display:none;'></a>");
        $("#"+fancyboxAnchorElementId).fancybox();
    }

    $("#" + fancyboxAnchorElementId).click();
}

Additional explanation: If you show fancybox with "content" option, it will duplicate DOM, which is inside elements. Sometimes this is not OK. In my case I needed to have the same elements, because they were used in form.

PHP header(Location: ...): Force URL change in address bar

Well, if the server sends a correct redirection header, the browser redirects and therefore "changes the url". It might be a browser issue, then. I don't know if it has anything to do with it, but you should not send a relative url in the location header ("HTTP/1.1 requires an absolute URI as argument to » Location: including the scheme, hostname and absolute path, but some clients accept relative URIs. ", http://php.net/manual/en/function.header.php), and "location" must be capitalized, like:

header('Location: http://myhost.com/mypage.php');

How to set recurring schedule for xlsm file using Windows Task Scheduler

Better to use a as you indicated

  1. Create a simple vbs, which is a text file with a .vbs extension (see sample code below)
  2. Use the Task Scheduler to run the vbs
  3. Use the vbs to open the workbook at the scheduled time and then either:
    • use the Private Sub Workbook_Open() event in the ThisWorkbook module to run code when the file is opened
    • more robustly (as macros may be disabled on open), use Application.Run in the vbs to run the macro

See this example of the later approach at Running Excel on Windows Task Scheduler

sample vbs

Dim ObjExcel, ObjWB
Set ObjExcel = CreateObject("excel.application")
'vbs opens a file specified by the path below
Set ObjWB = ObjExcel.Workbooks.Open("C:\temp\rod.xlsm")
'either use the Workbook Open event (if macros are enabled), or Application.Run

ObjWB.Close False
ObjExcel.Quit
Set ObjExcel = Nothing

Unable to execute dex: Multiple dex files define Lcom/myapp/R$array;

I had two related but not identical guava libraries in the /libs directory, after I removed one, the problem went away.

Prevent browser caching of AJAX call result

If you are using .net ASP MVC, disable the caching on the controller action by adding the following attribute on the end point function:

[OutputCacheAttribute(VaryByParam = "*", Duration = 0, NoStore = true)]

git - Server host key not cached

Had the same issue, and forget to connect to SSH on port where is actuall repository, not just general SSH port, then the host key is different!

How do I delete everything in Redis?

Heads up that FLUSHALL may be overkill. FLUSHDB is the one to flush a database only. FLUSHALL will wipe out the entire server. As in every database on the server. Since the question was about flushing a database I think this is an important enough distinction to merit a separate answer.

Background color on input type=button :hover state sticks in IE

There might be a fix to <input type="button"> - but if there is, I don't know it.

Otherwise, a good option seems to be to replace it with a carefully styled a element.

Example: http://jsfiddle.net/Uka5v/

.button {
    background-color: #E3E1B8; 
    padding: 2px 4px;
    font: 13px sans-serif;
    text-decoration: none;
    border: 1px solid #000;
    border-color: #aaa #444 #444 #aaa;
    color: #000
}

Upsides include that the a element will style consistently between different (older) versions of Internet Explorer without any extra work, and I think my link looks nicer than that button :)

How do I get into a non-password protected Java keystore or change the password?

Getting into a non-password protected Java keystore and changing the password can be done with a help of Java programming language itself.

That article contains the code for that:

thetechawesomeness.ideasmatter.info

How to concatenate items in a list to a single string?

We can specify how we have to join the string. Instead of '-', we can use ' '

sentence = ['this','is','a','sentence']
s=(" ".join(sentence))
print(s)

PHP: Split a string in to an array foreach char

You can access a string using [], as you do for arrays:

$stringLength = strlen($str);
for ($i = 0; $i < $stringLength; $i++)
    $char = $str[$i];

Jquery Open in new Tab (_blank)

Setting links on the page woud require a combination of @Ravi and @ncksllvn's answers:

// Find link in $(".product-item") and set "target" attribute to "_blank".
$(this).find("a").attr("target", "_blank");

For opening the page in another window, see this question: jQuery click _blank And see this reference for window.open options for customization.

Update:

You would need something along:

$(document).ready(function() {
  $(".product-item").click(function() {
    var productLink = $(this).find("a");

    productLink.attr("target", "_blank");
    window.open(productLink.attr("href"));

    return false;
  });
});

Note the usage of .attr():

$element.attr("attribute_name")                   // Get value of attribute.
$element.attr("attribute_name", attribute_value)  // Set value of attribute.

Get the current cell in Excel VB

I realize this doesn't directly apply from the title of the question, However some ways to deal with a variable range could be to select the range each time the code runs -- especially if you are interested in a user-selected range. If you are interested in that option, you can use the Application.InputBox (official documentation page here). One of the optional variables is 'type'. If the type is set equal to 8, the InputBox also has an excel-style range selection option. An example of how to use it in code would be:

Dim rng as Range
Set rng = Application.InputBox(Prompt:= "Please select a range", Type:=8)

Note:

If you assign the InputBox value to a none-range variable (without the Set keyword), instead of the ranges, the values from the ranges will be assigned, as in the code below (although selecting multiple ranges in this situation may require the values to be assigned to a variant):

Dim str as String
str = Application.InputBox(Prompt:= "Please select a range", Type:=8)

Get pandas.read_csv to read empty values as empty string instead of nan

I added a ticket to add an option of some sort here:

https://github.com/pydata/pandas/issues/1450

In the meantime, result.fillna('') should do what you want

EDIT: in the development version (to be 0.8.0 final) if you specify an empty list of na_values, empty strings will stay empty strings in the result

ImportError: DLL load failed: %1 is not a valid Win32 application. But the DLL's are there

For me the problem was that I was using different versions of Python in the same Eclipse project. My setup was not consistent with the Project Properties and the Run Configuration Python versions.

In Project > Properties > PyDev, I had the Interpreter set to Python2.7.11.

In Run Configurations > Interpreter, I was using the Default Interpreter. Changing it to Python 2.7.11 fixed the problem.

Locking a file in Python

The other solutions cite a lot of external code bases. If you would prefer to do it yourself, here is some code for a cross-platform solution that uses the respective file locking tools on Linux / DOS systems.

try:
    # Posix based file locking (Linux, Ubuntu, MacOS, etc.)
    #   Only allows locking on writable files, might cause
    #   strange results for reading.
    import fcntl, os
    def lock_file(f):
        if f.writable(): fcntl.lockf(f, fcntl.LOCK_EX)
    def unlock_file(f):
        if f.writable(): fcntl.lockf(f, fcntl.LOCK_UN)
except ModuleNotFoundError:
    # Windows file locking
    import msvcrt, os
    def file_size(f):
        return os.path.getsize( os.path.realpath(f.name) )
    def lock_file(f):
        msvcrt.locking(f.fileno(), msvcrt.LK_RLCK, file_size(f))
    def unlock_file(f):
        msvcrt.locking(f.fileno(), msvcrt.LK_UNLCK, file_size(f))


# Class for ensuring that all file operations are atomic, treat
# initialization like a standard call to 'open' that happens to be atomic.
# This file opener *must* be used in a "with" block.
class AtomicOpen:
    # Open the file with arguments provided by user. Then acquire
    # a lock on that file object (WARNING: Advisory locking).
    def __init__(self, path, *args, **kwargs):
        # Open the file and acquire a lock on the file before operating
        self.file = open(path,*args, **kwargs)
        # Lock the opened file
        lock_file(self.file)

    # Return the opened file object (knowing a lock has been obtained).
    def __enter__(self, *args, **kwargs): return self.file

    # Unlock the file and close the file object.
    def __exit__(self, exc_type=None, exc_value=None, traceback=None):        
        # Flush to make sure all buffered contents are written to file.
        self.file.flush()
        os.fsync(self.file.fileno())
        # Release the lock on the file.
        unlock_file(self.file)
        self.file.close()
        # Handle exceptions that may have come up during execution, by
        # default any exceptions are raised to the user.
        if (exc_type != None): return False
        else:                  return True        

Now, AtomicOpen can be used in a with block where one would normally use an open statement.

WARNINGS:

  • If running on Windows and Python crashes before exit is called, I'm not sure what the lock behavior would be.
  • The locking provided here is advisory, not absolute. All potentially competing processes must use the "AtomicOpen" class.
  • As of (Nov 9th, 2020) this code only locks writable files on Posix systems. At some point after the posting and before this date, it became illegal to use the fcntl.lock on read-only files.

TypeError: 'dict_keys' object does not support indexing

Clearly you're passing in d.keys() to your shuffle function. Probably this was written with python2.x (when d.keys() returned a list). With python3.x, d.keys() returns a dict_keys object which behaves a lot more like a set than a list. As such, it can't be indexed.

The solution is to pass list(d.keys()) (or simply list(d)) to shuffle.

Running JAR file on Windows 10

How do I run an executable JAR file? If you have a jar file called Example.jar, follow these rules:

Open a notepad.exe.
Write : java -jar Example.jar.
Save it with the extension .bat.
Copy it to the directory which has the .jar file.
Double click it to run your .jar file.

Join a list of items with different types as string in Python

map function in python can be used. It takes two arguments. First argument is the function which has to be used for each element of the list. Second argument is the iterable.

a = [1, 2, 3]   
map(str, a)  
['1', '2', '3']

After converting the list into string you can use simple join function to combine list into a single string

a = map(str, a)    
''.join(a)      
'123'

jQuery onclick toggle class name

you can use toggleClass() to toggle class it is really handy.

case:1

<div id='mydiv' class="class1"></div>

$('#mydiv').toggleClass('class1 class2');

output: <div id='mydiv' class="class2"></div>

case:2

<div id='mydiv' class="class2"></div>

$('#mydiv').toggleClass('class1 class2');

output: <div id='mydiv' class="class1"></div>

case:3

<div id='mydiv' class="class1 class2 class3"></div>

$('#mydiv').toggleClass('class1 class2');

output: <div id='mydiv' class="class3"></div>

Load image from url

Based on this answer i write my own loader.

With Loading effect and Appear effect :

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;

import java.io.InputStream;

/**
 * Created by Sergey Shustikov ([email protected]) at 2015.
 */
public class DownloadImageTask extends AsyncTask<String, Void, Bitmap>
{
    public static final int ANIMATION_DURATION = 250;
    private final ImageView mDestination, mFakeForError;
    private final String mUrl;
    private final ProgressBar mProgressBar;
    private Animation.AnimationListener mOutAnimationListener = new Animation.AnimationListener()
    {
        @Override
        public void onAnimationStart(Animation animation)
        {

        }

        @Override
        public void onAnimationEnd(Animation animation)
        {
            mProgressBar.setVisibility(View.GONE);
        }

        @Override
        public void onAnimationRepeat(Animation animation)
        {

        }
    };
    private Animation.AnimationListener mInAnimationListener = new Animation.AnimationListener()
    {
        @Override
        public void onAnimationStart(Animation animation)
        {
            if (isBitmapSet)
                mDestination.setVisibility(View.VISIBLE);
            else
                mFakeForError.setVisibility(View.VISIBLE);
        }

        @Override
        public void onAnimationEnd(Animation animation)
        {

        }

        @Override
        public void onAnimationRepeat(Animation animation)
        {

        }
    };
    private boolean isBitmapSet;

    public DownloadImageTask(Context context, ImageView destination, String url)
    {
        mDestination = destination;
        mUrl = url;
        ViewGroup parent = (ViewGroup) destination.getParent();
        mFakeForError = new ImageView(context);
        destination.setVisibility(View.GONE);
        FrameLayout layout = new FrameLayout(context);
        mProgressBar = new ProgressBar(context);
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        params.gravity = Gravity.CENTER;
        mProgressBar.setLayoutParams(params);
        FrameLayout.LayoutParams copy = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        copy.gravity = Gravity.CENTER;
        copy.width = dpToPx(48);
        copy.height = dpToPx(48);
        mFakeForError.setLayoutParams(copy);
        mFakeForError.setVisibility(View.GONE);
        mFakeForError.setImageResource(android.R.drawable.ic_menu_close_clear_cancel);
        layout.addView(mProgressBar);
        layout.addView(mFakeForError);
        mProgressBar.setIndeterminate(true);
        parent.addView(layout, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
    }

    protected Bitmap doInBackground(String... urls)
    {
        String urlDisplay = mUrl;
        Bitmap bitmap = null;
        try {
            InputStream in = new java.net.URL(urlDisplay).openStream();
            bitmap = BitmapFactory.decodeStream(in);
        } catch (Exception e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        return bitmap;
    }

    protected void onPostExecute(Bitmap result)
    {
        AlphaAnimation in = new AlphaAnimation(0f, 1f);
        AlphaAnimation out = new AlphaAnimation(1f, 0f);
        in.setDuration(ANIMATION_DURATION * 2);
        out.setDuration(ANIMATION_DURATION);
        out.setAnimationListener(mOutAnimationListener);
        in.setAnimationListener(mInAnimationListener);
        in.setStartOffset(ANIMATION_DURATION);
        if (result != null) {
            mDestination.setImageBitmap(result);
            isBitmapSet = true;
            mDestination.startAnimation(in);
        } else {
            mFakeForError.startAnimation(in);
        }
        mProgressBar.startAnimation(out);
    }
    public int dpToPx(int dp) {
        DisplayMetrics displayMetrics = mDestination.getContext().getResources().getDisplayMetrics();
        int px = Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
        return px;
    }
}

Add permission

<uses-permission android:name="android.permission.INTERNET"/>

And execute :

 new DownloadImageTask(context, imageViewToLoad, urlToImage).execute();

Fill remaining vertical space with CSS using display:flex

Here is the codepen demo showing the solution:

Important highlights:

  • all containers from html, body, ... .container, should have the height set to 100%
  • introducing flex to ANY of the flex items will trigger calculation of the items sizes based on flex distribution:
    • if only one cell is set to flex, for example: flex: 1 then this flex item will occupy the remaining of the space
    • if there are more than one with the flex property, the calculation will be more complicated. For example, if the item 1 is set to flex: 1 and the item 2 is se to flex: 2 then the item 2 will take twice more of the remaining space
  • Main Size Property

How to use NSURLConnection to connect with SSL for an untrusted cert?

You have to use NSURLConnectionDelegate to allow HTTPS connections and there are new callbacks with iOS8.

Deprecated:

connection:canAuthenticateAgainstProtectionSpace:
connection:didCancelAuthenticationChallenge:
connection:didReceiveAuthenticationChallenge:

Instead those, you need to declare:

connectionShouldUseCredentialStorage: - Sent to determine whether the URL loader should use the credential storage for authenticating the connection.

connection:willSendRequestForAuthenticationChallenge: - Tells the delegate that the connection will send a request for an authentication challenge.

With willSendRequestForAuthenticationChallenge you can use challenge like you did with the deprecated methods, for example:

// Trusting and not trusting connection to host: Self-signed certificate
[challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
[challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];

"android.view.WindowManager$BadTokenException: Unable to add window" on buider.show()

android.view.WindowManager$BadTokenException: Unable to add window"

Problem :

This exception occurs when the app is trying to notify the user from the background thread (AsyncTask) by opening a Dialog.

If you are trying to modify the UI from background thread (usually from onPostExecute() of AsyncTask) and if the activity enters finishing stage i.e.) explicitly calling finish(), user pressing home or back button or activity clean up made by Android then you get this error.

Reason :

The reason for this exception is that, as the exception message says, the activity has finished but you are trying to display a dialog with a context of the finished activity. Since there is no window for the dialog to display the android runtime throws this exception.

Solution:

Use isFinishing() method which is called by Android to check whether this activity is in the process of finishing: be it explicit finish() call or activity clean up made by Android. By using this method it is very easy to avoid opening dialog from background thread when activity is finishing.

Also maintain a weak reference for the activity (and not a strong reference so that activity can be destroyed once not needed) and check if the activity is not finishing before performing any UI using this activity reference (i.e. showing a dialog).

eg.

private class chkSubscription extends AsyncTask<String, Void, String>{

  private final WeakReference<login> loginActivityWeakRef;

  public chkSubscription (login loginActivity) {
    super();
    this.loginActivityWeakRef= new WeakReference<login >(loginActivity)
  }

  protected String doInBackground(String... params) {
    //web service call
  }

  protected void onPostExecute(String result) {
    if(page.contains("error")) //when not subscribed
    {
      if (loginActivityWeakRef.get() != null && !loginActivityWeakRef.get().isFinishing()) {
        AlertDialog.Builder builder = new AlertDialog.Builder(login.this);
        builder.setCancelable(true);
        builder.setMessage(sucObject);
        builder.setInverseBackgroundForced(true);

        builder.setNeutralButton("Ok",new DialogInterface.OnClickListener() {
          public void onClick(DialogInterface dialog, int whichButton){
            dialog.dismiss();
          }
        });

        builder.show();
      }
    }
  }
}

Update :

Window Tokens:

As its name implies, a window token is a special type of Binder token that the window manager uses to uniquely identify a window in the system. Window tokens are important for security because they make it impossible for malicious applications to draw on top of the windows of other applications. The window manager protects against this by requiring applications to pass their application's window token as part of each request to add or remove a window. If the tokens don't match, the window manager rejects the request and throws a BadTokenException. Without window tokens, this necessary identification step wouldn't be possible and the window manager wouldn't be able to protect itself from malicious applications.

 A real-world scenario:

When an application starts up for the first time, the ActivityManagerService creates a special kind of window token called an application window token, which uniquely identifies the application's top-level container window. The activity manager gives this token to both the application and the window manager, and the application sends the token to the window manager each time it wants to add a new window to the screen. This ensures secure interaction between the application and the window manager (by making it impossible to add windows on top of other applications), and also makes it easy for the activity manager to make direct requests to the window manager.

Is it ok to scrape data from Google results?

Google disallows automated access in their TOS, so if you accept their terms you would break them.

That said, I know of no lawsuit from Google against a scraper. Even Microsoft scraped Google, they powered their search engine Bing with it. They got caught in 2011 red handed :)

There are two options to scrape Google results:

1) Use their API

UPDATE 2020: Google has reprecated previous APIs (again) and has new prices and new limits. Now (https://developers.google.com/custom-search/v1/overview) you can query up to 10k results per day at 1,500 USD per month, more than that is not permitted and the results are not what they display in normal searches.

  • You can issue around 40 requests per hour You are limited to what they give you, it's not really useful if you want to track ranking positions or what a real user would see. That's something you are not allowed to gather.

  • If you want a higher amount of API requests you need to pay.

  • 60 requests per hour cost 2000 USD per year, more queries require a custom deal.

2) Scrape the normal result pages

  • Here comes the tricky part. It is possible to scrape the normal result pages. Google does not allow it.
  • If you scrape at a rate higher than 8 (updated from 15) keyword requests per hour you risk detection, higher than 10/h (updated from 20) will get you blocked from my experience.
  • By using multiple IPs you can up the rate, so with 100 IP addresses you can scrape up to 1000 requests per hour. (24k a day) (updated)
  • There is an open source search engine scraper written in PHP at http://scraping.compunect.com It allows to reliable scrape Google, parses the results properly and manages IP addresses, delays, etc. So if you can use PHP it's a nice kickstart, otherwise the code will still be useful to learn how it is done.

3) Alternatively use a scraping service (updated)

  • Recently a customer of mine had a huge search engine scraping requirement but it was not 'ongoing', it's more like one huge refresh per month.
    In this case I could not find a self-made solution that's 'economic'.
    I used the service at http://scraping.services instead. They also provide open source code and so far it's running well (several thousand resultpages per hour during the refreshes)
  • The downside is that such a service means that your solution is "bound" to one professional supplier, the upside is that it was a lot cheaper than the other options I evaluated (and faster in our case)
  • One option to reduce the dependency on one company is to make two approaches at the same time. Using the scraping service as primary source of data and falling back to a proxy based solution like described at 2) when required.

Convert Mercurial project to Git

This would be better as a comment, sorry I do not have commenting permissions.

@mar10 comment was the missing piece I needed to do this.

Note that '/path/to/old/mercurial_repo' must be a path on the file system (not a URL), so you have to clone the original repository before. – mar10 Dec 27 '13 at 16:30

This comment was in regards to the answer that solved this for me, https://stackoverflow.com/a/10710294/2148757 which is the same answer as the one marked correct here, https://stackoverflow.com/a/16037861/2148757

This moved our hg project to git with the commit history intact.

How to determine the current language of a wordpress page when using polylang?

I use something like this:

<?php 

$lang = get_bloginfo("language"); 

if ($lang == 'fr-FR') : ?>

   <p>Bienvenue!</p>

<?php endif; ?>

Attempt to write a readonly database - Django w/ SELinux error

You can change acls without touching the ownership and permissions of file/directory.

Use the following commands:

setfacl -m u:www-data:rwx /home/user/website
setfacl -m u:www-data:rw /home/user/website/db.sqlite3

Check if all checkboxes are selected

$('.abc[checked!=true]').length == 0

What's the difference between the Window.Loaded and Window.ContentRendered events

If you're using data binding, then you need to use the ContentRendered event.

For the code below, the Header is NULL when the Loaded event is raised. However, Header gets its value when the ContentRendered event is raised.

<MenuItem Header="{Binding NewGame_Name}" Command="{Binding NewGameCommand}" />

JavaScript load a page on button click

Simple code to redirect page

<!-- html button designing and calling the event in javascript -->
<input id="btntest" type="button" value="Check" 
       onclick="window.location.href = 'http://www.google.com'" />

Maven Installation OSX Error Unsupported major.minor version 51.0

Do this in your .profile -

export JAVA_HOME=`/usr/libexec/java_home`

(backticks make sure to execute the command and place its value in JAVA_HOME)

Uncaught TypeError: Cannot assign to read only property

When you use Object.defineProperties, by default writable is set to false, so _year and edition are actually read only properties.

Explicitly set them to writable: true:

_year: {
    value: 2004,
    writable: true
},

edition: {
    value: 1,
    writable: true
},

Check out MDN for this method.

writable
true if and only if the value associated with the property may be changed with an assignment operator.
Defaults to false.

How to select a single child element using jQuery?

I think what you want to do is this:

$(this).children('img').eq(0);

this will give you a jquery object containing the first img element, whereas

$(this).children('img')[0];

will give you the img element itself.

Restoring Nuget References?

You need to Enable NuGet package restore at the VS solution level for the restore missing package to work.

enter image description here

CSS transition fade on hover

This will do the trick

.gallery-item
{
  opacity:1;
}

.gallery-item:hover
{
  opacity:0;
  transition: opacity .2s ease-out;
  -moz-transition: opacity .2s ease-out;
  -webkit-transition: opacity .2s ease-out;
  -o-transition: opacity .2s ease-out;
}

How to check the maximum number of allowed connections to an Oracle database?

Note: this only answers part of the question.

If you just want to know the maximum number of sessions allowed, then you can execute in sqlplus, as sysdba:

SQL> show parameter sessions

This gives you an output like:

    NAME                                 TYPE        VALUE
------------------------------------ ----------- ------------------------------
java_max_sessionspace_size           integer     0
java_soft_sessionspace_limit         integer     0
license_max_sessions                 integer     0
license_sessions_warning             integer     0
sessions                             integer     248
shared_server_sessions               integer

The sessions parameter is the one what you want.

How to add a ScrollBar to a Stackpanel

If you mean, you want to scroll through multiple items in your stackpanel, try putting a grid around it. By definition, a stackpanel has infinite length.

So try something like this:

   <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
        <StackPanel Width="311">
              <TextBlock Text="{Binding A}" TextWrapping="Wrap" Style="{StaticResource PhoneTextExtraLargeStyle}" FontStretch="Condensed" FontSize="28" />
              <TextBlock Text="{Binding B}" TextWrapping="Wrap" Margin="12,-6,12,0" Style="{StaticResource PhoneTextSubtleStyle}"/>
        </StackPanel>
    </Grid>

You could even make this work with a ScrollViewer

Constraint Layout Vertical Align Center

You can easily center multiple things by creating a chain. It works both vertically and horizontally

Link to official documentation about chains

Edit to answer comment :

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
    <TextView
        android:id="@+id/first_score"
        android:layout_width="60dp"
        android:layout_height="wrap_content"
        android:text="10"
        app:layout_constraintEnd_toStartOf="@+id/second_score"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@+id/second_score"
        app:layout_constraintBottom_toTopOf="@+id/subtitle"
        app:layout_constraintHorizontal_chainStyle="spread"
        app:layout_constraintVertical_chainStyle="packed"
        android:gravity="center"
        />
    <TextView
        android:id="@+id/subtitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Subtitle"
        app:layout_constraintTop_toBottomOf="@+id/first_score"
        app:layout_constraintBottom_toBottomOf="@+id/second_score"
        app:layout_constraintStart_toStartOf="@id/first_score"
        app:layout_constraintEnd_toEndOf="@id/first_score"
        />
    <TextView
        android:id="@+id/second_score"
        android:layout_width="60dp"
        android:layout_height="120sp"
        android:text="243"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/thrid_score"
        app:layout_constraintStart_toEndOf="@id/first_score"
        app:layout_constraintTop_toTopOf="parent"
        android:gravity="center"
        />
    <TextView
        android:id="@+id/thrid_score"
        android:layout_width="60dp"
        android:layout_height="wrap_content"
        android:text="3200"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@id/second_score"
        app:layout_constraintTop_toTopOf="@id/second_score"
        app:layout_constraintBottom_toBottomOf="@id/second_score"
        android:gravity="center"
        />
</android.support.constraint.ConstraintLayout>

This code gives this result

You have the horizontal chain : first_score <=> second_score <=> third_score. second_score is centered vertically. The other scores are centered vertically according to it.

You can definitely create a vertical chain first_score <=> subtitle and center it according to second_score

PHP filesize MB/KB conversion

Here is a sample:

<?php
// Snippet from PHP Share: http://www.phpshare.org

    function formatSizeUnits($bytes)
    {
        if ($bytes >= 1073741824)
        {
            $bytes = number_format($bytes / 1073741824, 2) . ' GB';
        }
        elseif ($bytes >= 1048576)
        {
            $bytes = number_format($bytes / 1048576, 2) . ' MB';
        }
        elseif ($bytes >= 1024)
        {
            $bytes = number_format($bytes / 1024, 2) . ' KB';
        }
        elseif ($bytes > 1)
        {
            $bytes = $bytes . ' bytes';
        }
        elseif ($bytes == 1)
        {
            $bytes = $bytes . ' byte';
        }
        else
        {
            $bytes = '0 bytes';
        }

        return $bytes;
}
?>

PHP is_numeric or preg_match 0-9 validation

is_numeric checks more:

Finds whether the given variable is numeric. Numeric strings consist of optional sign, any number of digits, optional decimal part and optional exponential part. Thus +0123.45e6 is a valid numeric value. Hexadecimal notation (0xFF) is allowed too but only without sign, decimal and exponential part.

How to install a package inside virtualenv?

Sharing a personal case if it helps. It is that a virtual environment was previously arranged. Its path can be displayed by

echo $VIRTUAL_ENV

Make sure that the it is writable to the current user. If not, using

sudo ipython

would certainly clear off the warning message.

In anaconda, if $VIRTUAL_ENV is independently arranged, one can simply delete this folder or rename it, and then restart the shell. Anaconda will recover to its default setup.

Interface extends another interface but implements its methods

An interface defines behavior. For example, a Vehicle interface might define the move() method.

A Car is a Vehicle, but has additional behavior. For example, the Car interface might define the startEngine() method. Since a Car is also a Vehicle, the Car interface extends the Vehicle interface, and thus defines two methods: move() (inherited) and startEngine().

The Car interface doesn't have any method implementation. If you create a class (Volkswagen) that implements Car, it will have to provide implementations for all the methods of its interface: move() and startEngine().

An interface may not implement any other interface. It can only extend it.

Why can't decimal numbers be represented exactly in binary?

If you make a big enough number with floating point (as it can do exponents), then you'll end up with inexactness in front of the decimal point, too. So I don't think your question is entirely valid because the premise is wrong; it's not the case that shifting by 10 will always create more precision, because at some point the floating point number will have to use exponents to represent the largeness of the number and will lose some precision that way as well.

Can local storage ever be considered secure?

WebCrypto

The concerns with cryptography in client-side (browser) javascript are detailed below. All but one of these concerns does not apply to the WebCrypto API, which is now reasonably well supported.

For an offline app, you must still design and implement a secure keystore.

Aside: If you are using Node.js, use the builtin crypto API.

Native-Javascript Cryptography (pre-WebCrypto)

I presume the primary concern is someone with physical access to the computer reading the localStorage for your site, and you want cryptography to help prevent that access.

If someone has physical access you are also open to attacks other and worse than reading. These include (but are not limited to): keyloggers, offline script modification, local script injection, browser cache poisoning, and DNS redirects. Those attacks only work if the user uses the machine after it has been compromised. Nevertheless, physical access in such a scenario means you have bigger problems.

So keep in mind that the limited scenario where local crypto is valuable would be if the machine is stolen.

There are libraries that do implement the desired functionality, e.g. Stanford Javascript Crypto Library. There are inherent weaknesses, though (as referred to in the link from @ircmaxell's answer):

  1. Lack of entropy / random number generation;
  2. Lack of a secure keystore i.e. the private key must be password-protected if stored locally, or stored on the server (which bars offline access);
  3. Lack of secure-erase;
  4. Lack of timing characteristics.

Each of these weaknesses corresponds with a category of cryptographic compromise. In other words, while you may have "crypto" by name, it will be well below the rigour one aspires to in practice.

All that being said, the actuarial assessment is not as trivial as "Javascript crypto is weak, do not use it". This is not an endorsement, strictly a caveat and it requires you to completely understand the exposure of the above weaknesses, the frequency and cost of the vectors you face, and your capacity for mitigation or insurance in the event of failure: Javascript crypto, in spite of its weaknesses, may reduce your exposure but only against thieves with limited technical capacity. However, you should presume Javascript crypto has no value against a determined and capable attacker who is targeting that information. Some would consider it misleading to call the data "encrypted" when so many weaknesses are known to be inherent to the implementation. In other words, you can marginally decrease your technical exposure but you increase your financial exposure from disclosure. Each situation is different, of course - and the analysis of reducing the technical exposure to financial exposure is non-trivial. Here is an illustrative analogy: Some banks require weak passwords, in spite of the inherent risk, because their exposure to losses from weak passwords is less than the end-user costs of supporting strong passwords.

If you read the last paragraph and thought "Some guy on the Internet named Brian says I can use Javascript crypto", do not use Javascript crypto.

For the use case described in the question it would seem to make more sense for users to encrypt their local partition or home directory and use a strong password. That type of security is generally well tested, widely trusted, and commonly available.

How can I delete all of my Git stashes at once?

There are two ways to delete a stash:

  1. If you no longer need a particular stash, you can delete it with: $ git stash drop <stash_id>.
  2. You can delete all of your stashes from the repo with: $ git stash clear.

Use both of them with caution, it maybe is difficult to revert the once deleted stashes.

Here is the reference article.

Adding Permissions in AndroidManifest.xml in Android Studio?

Put these two line in your AndroidMainfest

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 

Draw text in OpenGL ES

I've written a tutorial that expands on the answer posted by JVitela. Basically, it uses the same idea, but instead of rendering each string to a texture, it renders all characters from a font file to a texture and uses that to allow for full dynamic text rendering with no further slowdowns (once the initialization is complete).

The main advantage of my method, compared to the various font atlas generators, is that you can ship small font files (.ttf .otf) with your project instead of having to ship large bitmaps for every font variation and size. It can generate perfect quality fonts at any resolution using only a font file :)

The tutorial includes full code that can be used in any project :)

Javascript get object key name

ECMAscript edition 5 also offers you the neat methods Object.keys() and Object.getOwnPropertyNames().

So

Object.keys( buttons );  // ['button1', 'button2'];

Downloading all maven dependencies to a directory NOT in repository?

The maven dependency plugin can potentially solve your problem.

If you have a pom with all your project dependencies specified, all you would need to do is run

mvn dependency:copy-dependencies

and you will find the target/dependencies folder filled with all the dependencies, including transitive.

Adding Gustavo's answer from below: To download the dependency sources, you can use

mvn dependency:copy-dependencies -Dclassifier=sources

(via Apache Maven Dependency Plugin doc).

jQuery selector for the label of a checkbox

Thanks Kip, for those who may be looking to achieve the same using $(this) whilst iterating or associating within a function:

$("label[for="+$(this).attr("id")+"]").addClass( "orienSel" );

I looked for a while whilst working this project but couldn't find a good example so I hope this helps others who may be looking to resolve the same issue.

In the example above, my objective was to hide the radio inputs and style the labels to provide a slicker user experience (changing the orientation of the flowchart).

You can see an example here

If you like the example, here is the css:

.orientation {      position: absolute; top: -9999px;   left: -9999px;}
    .orienlabel{background:#1a97d4 url('http://www.ifreight.solutions/process.html/images/icons/flowChart.png') no-repeat 2px 5px; background-size: 40px auto;color:#fff; width:50px;height:50px;display:inline-block; border-radius:50%;color:transparent;cursor:pointer;}
    .orR{   background-position: 9px -57px;}
    .orT{   background-position: 2px -120px;}
    .orB{   background-position: 6px -177px;}

    .orienSel {background-color:#323232;}

and the relevant part of the JavaScript:

function changeHandler() {
    $(".orienSel").removeClass( "orienSel" );
    if(this.checked) {
        $("label[for="+$(this).attr("id")+"]").addClass( "orienSel" );
    }
};

An alternate root to the original question, given the label follows the input, you could go with a pure css solution and avoid using JavaScript altogether...:

input[type=checkbox]:checked+label {}

How can I find all *.js file in directory recursively in Linux?

Use find on the command line:

find /my/directory -name '*.js'

How to bind a List<string> to a DataGridView control?

Try this:

IList<String> list_string= new List<String>();
DataGridView.DataSource = list_string.Select(x => new { Value = x }).ToList();
dgvSelectedNode.Show();

I hope this helps.

Regular expression to extract numbers from a string

if you know for sure that there are only going to be 2 places where you have a list of digits in your string and that is the only thing you are going to pull out then you should be able to simply use

\d+

move_uploaded_file gives "failed to open stream: Permission denied" error

Just change the permission of tmp_file_upload to 755 Following is the command chmod -R 755 tmp_file_upload

Is Django for the frontend or backend?

Neither.

Django is a framework, not a language. Python is the language in which Django is written.

Django is a collection of Python libs allowing you to quickly and efficiently create a quality Web application, and is suitable for both frontend and backend.

However, Django is pretty famous for its "Django admin", an auto generated backend that allows you to manage your website in a blink for a lot of simple use cases without having to code much.

More precisely, for the front end, Django helps you with data selection, formatting, and display. It features URL management, a templating language, authentication mechanisms, cache hooks, and various navigation tools such as paginators.

For the backend, Django comes with an ORM that lets you manipulate your data source with ease, forms (an HTML independent implementation) to process user input and validate data and signals, and an implementation of the observer pattern. Plus a tons of use-case specific nifty little tools.

For the rest of the backend work Django doesn't help with, you just use regular Python. Business logic is a pretty broad term.

You probably want to know as well that Django comes with the concept of apps, a self contained pluggable Django library that solves a problem. The Django community is huge, and so there are numerous apps that do specific business logic that vanilla Django doesn't.

Named colors in matplotlib

Matplotlib uses a dictionary from its colors.py module.

To print the names use:

# python2:

import matplotlib
for name, hex in matplotlib.colors.cnames.iteritems():
    print(name, hex)

# python3:

import matplotlib
for name, hex in matplotlib.colors.cnames.items():
    print(name, hex)

This is the complete dictionary:

cnames = {
'aliceblue':            '#F0F8FF',
'antiquewhite':         '#FAEBD7',
'aqua':                 '#00FFFF',
'aquamarine':           '#7FFFD4',
'azure':                '#F0FFFF',
'beige':                '#F5F5DC',
'bisque':               '#FFE4C4',
'black':                '#000000',
'blanchedalmond':       '#FFEBCD',
'blue':                 '#0000FF',
'blueviolet':           '#8A2BE2',
'brown':                '#A52A2A',
'burlywood':            '#DEB887',
'cadetblue':            '#5F9EA0',
'chartreuse':           '#7FFF00',
'chocolate':            '#D2691E',
'coral':                '#FF7F50',
'cornflowerblue':       '#6495ED',
'cornsilk':             '#FFF8DC',
'crimson':              '#DC143C',
'cyan':                 '#00FFFF',
'darkblue':             '#00008B',
'darkcyan':             '#008B8B',
'darkgoldenrod':        '#B8860B',
'darkgray':             '#A9A9A9',
'darkgreen':            '#006400',
'darkkhaki':            '#BDB76B',
'darkmagenta':          '#8B008B',
'darkolivegreen':       '#556B2F',
'darkorange':           '#FF8C00',
'darkorchid':           '#9932CC',
'darkred':              '#8B0000',
'darksalmon':           '#E9967A',
'darkseagreen':         '#8FBC8F',
'darkslateblue':        '#483D8B',
'darkslategray':        '#2F4F4F',
'darkturquoise':        '#00CED1',
'darkviolet':           '#9400D3',
'deeppink':             '#FF1493',
'deepskyblue':          '#00BFFF',
'dimgray':              '#696969',
'dodgerblue':           '#1E90FF',
'firebrick':            '#B22222',
'floralwhite':          '#FFFAF0',
'forestgreen':          '#228B22',
'fuchsia':              '#FF00FF',
'gainsboro':            '#DCDCDC',
'ghostwhite':           '#F8F8FF',
'gold':                 '#FFD700',
'goldenrod':            '#DAA520',
'gray':                 '#808080',
'green':                '#008000',
'greenyellow':          '#ADFF2F',
'honeydew':             '#F0FFF0',
'hotpink':              '#FF69B4',
'indianred':            '#CD5C5C',
'indigo':               '#4B0082',
'ivory':                '#FFFFF0',
'khaki':                '#F0E68C',
'lavender':             '#E6E6FA',
'lavenderblush':        '#FFF0F5',
'lawngreen':            '#7CFC00',
'lemonchiffon':         '#FFFACD',
'lightblue':            '#ADD8E6',
'lightcoral':           '#F08080',
'lightcyan':            '#E0FFFF',
'lightgoldenrodyellow': '#FAFAD2',
'lightgreen':           '#90EE90',
'lightgray':            '#D3D3D3',
'lightpink':            '#FFB6C1',
'lightsalmon':          '#FFA07A',
'lightseagreen':        '#20B2AA',
'lightskyblue':         '#87CEFA',
'lightslategray':       '#778899',
'lightsteelblue':       '#B0C4DE',
'lightyellow':          '#FFFFE0',
'lime':                 '#00FF00',
'limegreen':            '#32CD32',
'linen':                '#FAF0E6',
'magenta':              '#FF00FF',
'maroon':               '#800000',
'mediumaquamarine':     '#66CDAA',
'mediumblue':           '#0000CD',
'mediumorchid':         '#BA55D3',
'mediumpurple':         '#9370DB',
'mediumseagreen':       '#3CB371',
'mediumslateblue':      '#7B68EE',
'mediumspringgreen':    '#00FA9A',
'mediumturquoise':      '#48D1CC',
'mediumvioletred':      '#C71585',
'midnightblue':         '#191970',
'mintcream':            '#F5FFFA',
'mistyrose':            '#FFE4E1',
'moccasin':             '#FFE4B5',
'navajowhite':          '#FFDEAD',
'navy':                 '#000080',
'oldlace':              '#FDF5E6',
'olive':                '#808000',
'olivedrab':            '#6B8E23',
'orange':               '#FFA500',
'orangered':            '#FF4500',
'orchid':               '#DA70D6',
'palegoldenrod':        '#EEE8AA',
'palegreen':            '#98FB98',
'paleturquoise':        '#AFEEEE',
'palevioletred':        '#DB7093',
'papayawhip':           '#FFEFD5',
'peachpuff':            '#FFDAB9',
'peru':                 '#CD853F',
'pink':                 '#FFC0CB',
'plum':                 '#DDA0DD',
'powderblue':           '#B0E0E6',
'purple':               '#800080',
'red':                  '#FF0000',
'rosybrown':            '#BC8F8F',
'royalblue':            '#4169E1',
'saddlebrown':          '#8B4513',
'salmon':               '#FA8072',
'sandybrown':           '#FAA460',
'seagreen':             '#2E8B57',
'seashell':             '#FFF5EE',
'sienna':               '#A0522D',
'silver':               '#C0C0C0',
'skyblue':              '#87CEEB',
'slateblue':            '#6A5ACD',
'slategray':            '#708090',
'snow':                 '#FFFAFA',
'springgreen':          '#00FF7F',
'steelblue':            '#4682B4',
'tan':                  '#D2B48C',
'teal':                 '#008080',
'thistle':              '#D8BFD8',
'tomato':               '#FF6347',
'turquoise':            '#40E0D0',
'violet':               '#EE82EE',
'wheat':                '#F5DEB3',
'white':                '#FFFFFF',
'whitesmoke':           '#F5F5F5',
'yellow':               '#FFFF00',
'yellowgreen':          '#9ACD32'}

You could plot them like this:

import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib.colors as colors
import math


fig = plt.figure()
ax = fig.add_subplot(111)

ratio = 1.0 / 3.0
count = math.ceil(math.sqrt(len(colors.cnames)))
x_count = count * ratio
y_count = count / ratio
x = 0
y = 0
w = 1 / x_count
h = 1 / y_count

for c in colors.cnames:
    pos = (x / x_count, y / y_count)
    ax.add_patch(patches.Rectangle(pos, w, h, color=c))
    ax.annotate(c, xy=pos)
    if y >= y_count-1:
        x += 1
        y = 0
    else:
        y += 1

plt.show()

How to get Node.JS Express to listen only on localhost?

Thanks for the info, think I see the problem. This is a bug in hive-go that only shows up when you add a host. The last lines of it are:

app.listen(3001);
console.log("... port %d in %s mode", app.address().port, app.settings.env);

When you add the host on the first line, it is crashing when it calls app.address().port.

The problem is the potentially asynchronous nature of .listen(). Really it should be doing that console.log call inside a callback passed to listen. When you add the host, it tries to do a DNS lookup, which is async. So when that line tries to fetch the address, there isn't one yet because the DNS request is running, so it crashes.

Try this:

app.listen(3001, 'localhost', function() {
  console.log("... port %d in %s mode", app.address().port, app.settings.env);
});

How to search in array of object in mongodb

The right way is:

db.users.find({awards: {$elemMatch: {award:'National Medal', year:1975}}})

$elemMatch allows you to match more than one component within the same array element.

Without $elemMatch mongo will look for users with National Medal in some year and some award in 1975s, but not for users with National Medal in 1975.

See MongoDB $elemMatch Documentation for more info. See Read Operations Documentation for more information about querying documents with arrays.

How to round up with excel VBA round()?

Try the RoundUp function:

Dim i As Double

i = Application.WorksheetFunction.RoundUp(Cells(1, 1).Value * Cells(1, 2).Value, 2)

How do I resize a Google Map with JavaScript after it has loaded?

This is best it will do the Job done. It will re-size your Map. No need to inspect element anymore to re-size your Map. What it does it will automatically trigger re-size event .

    google.maps.event.addListener(map, "idle", function()
        {
            google.maps.event.trigger(map, 'resize');
        });

        map_array[Next].setZoom( map.getZoom() - 1 );
    map_array[Next].setZoom( map.getZoom() + 1 );

Convert pyQt UI to python

For pyqt5 you can use

pyuic5 xyz.ui > xyz.py 

or

pyuic5 xyz.ui -o xyz.py

Print array to a file

However op needs to write array as it is on file I have landed this page to find out a solution where I can write a array to file and than can easily read later using php again.

I have found solution my self by using json_encode so anyone else is looking for the same here is the code:

file_put_contents('array.tmp', json_encode($array));

than read

$array = file_get_contents('array.tmp');
$array = json_decode($array,true);

Return outside function error in Python

As already explained by the other contributers, you could print out the counter and then replace the return with a break statement.

N = int(input("enter a positive integer:"))
counter = 1
while (N > 0):
    counter = counter * N
    N = N - 1
    print(counter)
    break

Is there a macro to conditionally copy rows to another worksheet?

This works: The way it's set up I called it from the immediate pane, but you can easily create a sub() that will call MoveData once for each month, then just invoke the sub.

You may want to add logic to sort your monthly data after it's all been copied

Public Sub MoveData(MonthNumber As Integer, SheetName As String)

Dim sharePoint As Worksheet
Dim Month As Worksheet
Dim spRange As Range
Dim cell As Range

Set sharePoint = Sheets("Sharepoint")
Set Month = Sheets(SheetName)
Set spRange = sharePoint.Range("A2")
Set spRange = sharePoint.Range("A2:" & spRange.End(xlDown).Address)
For Each cell In spRange
    If Format(cell.Value, "MM") = MonthNumber Then
        copyRowTo sharePoint.Range(cell.Row & ":" & cell.Row), Month
    End If
Next cell

End Sub

Sub copyRowTo(rng As Range, ws As Worksheet)
    Dim newRange As Range
    Set newRange = ws.Range("A1")
    If newRange.Offset(1).Value <> "" Then
        Set newRange = newRange.End(xlDown).Offset(1)
        Else
        Set newRange = newRange.Offset(1)
    End If
    rng.Copy
    newRange.PasteSpecial (xlPasteAll)
End Sub

Maven: best way of linking custom external JAR to my project?

If the external jar is created by a Maven project only then you can copy the entire project on your system and run a

mvn install

in the project directory. This will add the jar into .m2 directory which is local maven repository.

Now you can add the

<dependency>
     <groupId>copy-from-the=maven-pom-of-existing-project</groupId>
     <artifactId>copy-from-the=maven-pom-of-existing-project</artifactId>
     <version>copy-from-the=maven-pom-of-existing-project</version>
</dependency>

This will ensure that you

mvn exec:java 

works. If you use suggested here

<scope>system</scope>

Then you will have to add classes individually while using executing through command line.

You can add the external jars by the following command described here

mvn install:install-file -Dfile=<path-to-file> -DgroupId=<group-id> \
-DartifactId=<artifact-id> -Dversion=<version> -Dpackaging=<packaging>

Why does Firebug say toFixed() is not a function?

That is because Low is a string.

.toFixed() only works with a number.


Try doing:

Low = parseFloat(Low).toFixed(..);

sql server convert date to string MM/DD/YYYY

That task should be done by the next layer up in your software stack. SQL is a data repository, not a presentation system

You can do it with

CONVERT(VARCHAR(10), fmdate(), 101)

But you shouldn't

Iterating over Numpy matrix rows to apply a function each?

Use numpy.apply_along_axis(). Assuming your matrix is 2D, you can use like:

import numpy as np
mymatrix = np.matrix([[11,12,13],
                      [21,22,23],
                      [31,32,33]])
def myfunction( x ):
    return sum(x)

print np.apply_along_axis( myfunction, axis=1, arr=mymatrix )
#[36 66 96]

C# How to determine if a number is a multiple of another?

bool isMultiple = a % b == 0;

This will be true if a is a multiple of b

How to create a new object instance from a Type

If this is for something that will be called a lot in an application instance, it's a lot faster to compile and cache dynamic code instead of using the activator or ConstructorInfo.Invoke(). Two easy options for dynamic compilation are compiled Linq Expressions or some simple IL opcodes and DynamicMethod. Either way, the difference is huge when you start getting into tight loops or multiple calls.

How to get the last character of a string in a shell?

For portability you can say "${s#"${s%?}"}":

#!/bin/sh
m=bzzzM n=bzzzN
for s in \
    'vv'  'w'   ''    'uu  ' ' uu ' '  uu' / \
    'ab?' 'a?b' '?ab' 'ab??' 'a??b' '??ab' / \
    'cd#' 'c#d' '#cd' 'cd##' 'c##d' '##cd' / \
    'ef%' 'e%f' '%ef' 'ef%%' 'e%%f' '%%ef' / \
    'gh*' 'g*h' '*gh' 'gh**' 'g**h' '**gh' / \
    'ij"' 'i"j' '"ij' "ij'"  "i'j"  "'ij"  / \
    'kl{' 'k{l' '{kl' 'kl{}' 'k{}l' '{}kl' / \
    'mn$' 'm$n' '$mn' 'mn$$' 'm$$n' '$$mn' /
do  case $s in
    (/) printf '\n' ;;
    (*) printf '.%s. ' "${s#"${s%?}"}" ;;
    esac
done

Output:

.v. .w. .. . . . . .u. 
.?. .b. .b. .?. .b. .b. 
.#. .d. .d. .#. .d. .d. 
.%. .f. .f. .%. .f. .f. 
.*. .h. .h. .*. .h. .h. 
.". .j. .j. .'. .j. .j. 
.{. .l. .l. .}. .l. .l. 
.$. .n. .n. .$. .n. .n. 

How to hide columns in HTML table?

<!doctype html>
<html lang="en">
<head>
<style id="myStyleSheet">
...
</style>

var column = 3;
var styleSheet = document.getElementById("myStyleSheet").sheet;
var rule = "table  tr td:nth-child("+ column +"),table th:nth-child("+ column +") 
{display: none}";
styleSheet.insertRule(rule);

How to list all files in a directory and its subdirectories in hadoop hdfs

Now, one can use Spark to do the same and its way faster than other approaches (such as Hadoop MR). Here is the code snippet.

def traverseDirectory(filePath:String,recursiveTraverse:Boolean,filePaths:ListBuffer[String]) {
    val files = FileSystem.get( sparkContext.hadoopConfiguration ).listStatus(new Path(filePath))
            files.foreach { fileStatus => {
                if(!fileStatus.isDirectory() && fileStatus.getPath().getName().endsWith(".xml")) {                
                    filePaths+=fileStatus.getPath().toString()      
                }
                else if(fileStatus.isDirectory()) {
                    traverseDirectory(fileStatus.getPath().toString(), recursiveTraverse, filePaths)
                }
            }
    }   
}

Is it ok to use `any?` to check if an array is not empty?

any? isn't the same as not empty? in some cases.

>> [nil, 1].any?
=> true
>> [nil, nil].any?
=> false

From the documentation:

If the block is not given, Ruby adds an implicit block of {|obj| obj} (that is any? will return true if at least one of the collection members is not false or nil).

How to copy a file to a remote server in Python using SCP or SSH?

Reached the same problem, but instead of "hacking" or emulating command line:

Found this answer here.

from paramiko import SSHClient
from scp import SCPClient

ssh = SSHClient()
ssh.load_system_host_keys()
ssh.connect('example.com')

with SCPClient(ssh.get_transport()) as scp:
    scp.put('test.txt', 'test2.txt')
    scp.get('test2.txt')

How do I tell if an object is a Promise?

const isPromise = (value) => {
  return !!(
    value &&
    value.then &&
    typeof value.then === 'function' &&
    value?.constructor?.name === 'Promise'
  )
}

As for me - this check is better, try it out

How can I get a side-by-side diff when I do "git diff"?

Try git difftool

Use git difftool instead of git diff. You'll never go back.

UPDATE to add an example usage:

Here is a link to another stackoverflow that talks about git difftool: How do I view 'git diff' output with my preferred diff tool/ viewer?

For newer versions of git, the difftool command supports many external diff tools out-of-the-box. For example vimdiff is auto supported and can be opened from the command line by:

cd /path/to/git/repo
git difftool --tool=vimdiff

Other supported external diff tools are listed via git difftool --tool-help here is an example output:

'git difftool --tool=<tool>' may be set to one of the following:
        araxis
        kompare
        vimdiff
        vimdiff2

The following tools are valid, but not currently available:
        bc3
        codecompare
        deltawalker
        diffuse
        ecmerge
        emerge
        gvimdiff
        gvimdiff2
        kdiff3
        meld
        opendiff
        tkdiff
        xxdiff

what is Promotional and Feature graphic in Android Market/Play Store?

Promo graphic

The promo graphic is used for promotions on older versions of the Android OS (earlier than 4.0). This image is not required to submit an update for your Store Listing.

Requirements

  • JPG or 24-bit PNG (no alpha)
  • Dimensions: 180px by 120px

https://support.google.com/googleplay/android-developer/answer/1078870

How do I run a spring boot executable jar in a Production environment?

My Spring boot application has two initializers. One for development and another for production. For development, I use the main method like this:

@SpringBootApplication
public class MyAppInitializer {

    public static void main(String[] args) {
        SpringApplication.run(MyAppInitializer .class, args);
    }

}

My Initializer for production environment extends the SpringBootServletInitializer and looks like this:

@SpringBootApplication
public class MyAppInitializerServlet extends SpringBootServletInitializer{
    private static final Logger log = Logger
            .getLogger(SpringBootServletInitializer.class);
    @Override
    protected SpringApplicationBuilder configure(
            SpringApplicationBuilder builder) {
        log.trace("Initializing the application");
        return builder.sources(MyAppInitializerServlet .class);
    }

}

I use gradle and my build.gradle file applies 'WAR' plugin. When I run it in the development environment, I use bootrun task. Where as when I want to deploy it to production, I use assemble task to generate the WAR and deploy.

I can run like a normal spring application in production without discounting the advantages provided by the inbuilt tomcat while developing. Hope this helps.

jQuery checkbox onChange

$('input[type=checkbox]').change(function () {
    alert('changed');
});

ERROR 1064 (42000): You have an error in your SQL syntax;

It is varchar and not var_char

CREATE DATABASE IF NOT EXISTS courses;

USE courses;

CREATE TABLE IF NOT EXISTS teachers(
    id INT(10) UNSIGNED PRIMARY KEY NOT NULL AUTO_INCREMENT,
    name VARCHAR(50) NOT NULL,
    addr VARCHAR(255) NOT NULL,
    phone INT NOT NULL
);

You should use a SQL tool to visualize possbile errors like MySQL Workbench.

Multiple files upload in Codeigniter

_x000D_
_x000D_
<?php

if(isset($_FILES[$input_name]) && is_array($_FILES[$input_name]['name'])){
            $image_path = array();          
            $count = count($_FILES[$input_name]['name']);   
            for($key =0; $key <$count; $key++){     
                $_FILES['file']['name']     = $_FILES[$input_name]['name'][$key]; 
                $_FILES['file']['type']     = $_FILES[$input_name]['type'][$key]; 
                $_FILES['file']['tmp_name'] = $_FILES[$input_name]['tmp_name'][$key]; 
                $_FILES['file']['error']     = $_FILES[$input_name]['error'][$key]; 
                $_FILES['file']['size']     = $_FILES[$input_name]['size'][$key]; 
                    
                $config['file_name'] = $_FILES[$input_name]['name'][$key];                      
                $this->upload->initialize($config); 
                
                if($this->upload->do_upload('file')) {
                    $data = $this->upload->data();
                    $image_path[$key] = $path ."$data[file_name]";                  
                }else{
                    $error =  $this->upload->display_errors();
                $this->session->set_flashdata('msg_error',"image upload! ".$error);
                }   
            }
            return json_encode($image_path);
        }
    
    
   ?>
_x000D_
_x000D_
_x000D_

DLL load failed error when importing cv2

I had the same issue when installing opencv 2.4.13 on Anaconda3 (Python 3.6)... I managed to fix this issue by reverting to Anaconda2 (Python 2.7)

Failure [INSTALL_FAILED_ALREADY_EXISTS] when I tried to update my application

If you install the application on your device via adb install you should look for the reinstall option which should be -r. So if you do adb install -r you should be able to install without uninstalling before.

Check if a number is int or float

What you can do too is usingtype() Example:

if type(inNumber) == int : print "This number is an int"
elif type(inNumber) == float : print "This number is a float"

CURL to pass SSL certifcate and password

I went through this when trying to get a clientcert and private key out of a keystore.

The link above posted by welsh was great, but there was an extra step on my redhat distribution. If curl is built with NSS ( run curl --version to see if you see NSS listed) then you need to import the keys into an NSS keystore. I went through a bunch of convoluted steps, so this may not be the cleanest way, but it got things working

So export the keys into .p12

keytool -importkeystore -srckeystore $jksfile -destkeystore $p12file \
        -srcstoretype JKS -deststoretype PKCS12 \
        -srcstorepass $jkspassword -deststorepass $p12password  
        -srcalias $myalias -destalias $myalias \
        -srckeypass $keypass -destkeypass $keypass -noprompt

And generate the pem file that holds only the key

 echo making ${fileroot}.key.pem
 openssl pkcs12 -in $p12 -out ${fileroot}.key.pem  \
         -passin pass:$p12password  \
         -passout pass:$p12password  -nocerts
  • Make an empty keystore:
mkdir ~/nss
chmod 700 ~/nss
certutil -N -d ~/nss
  • Import the keys into the keystore
pks12util -i <mykeys>.p12 -d ~/nss -W <password for cert >

Now curl should work.

curl --insecure --cert <client cert alias>:<password for cert> \
     --key ${fileroot}.key.pem  <URL>

As I mentioned, there may be other ways to do this, but at least this was repeatable for me. If curl is compiled with NSS support, I was not able to get it to pull the client cert from a file.

Merge two rows in SQL

if one row has value in field1 column and other rows have null value then this Query might work.

SELECT
  FK,
  MAX(Field1) as Field1,
  MAX(Field2) as Field2
FROM 
(
select FK,ISNULL(Field1,'') as Field1,ISNULL(Field2,'') as Field2 from table1
)
tbl
GROUP BY FK

Convert a JSON string to object in Java ME?

Just make a Json object in java with the following Json String.In your case

{name:"MyNode", width:200, height:100}

if the above is your Json string , just create a Json Object with it.

JsonString ="{name:"MyNode", width:200, height:100}";
JSONObject yourJsonObject = new JSONObject(JsonString);
System.out.println("name=" + yourJsonObject.getString("name"));
System.out.println("width=" + yourJsonObject.getString("width"));

How to put a List<class> into a JSONObject and then read that object?

You could use a JSON serializer/deserializer like flexjson to do the conversion for you.

Extracting text from a PDF file using PDFMiner in python?

Here is a working example of extracting text from a PDF file using the current version of PDFMiner(September 2016)

from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfpage import PDFPage
from io import StringIO

def convert_pdf_to_txt(path):
    rsrcmgr = PDFResourceManager()
    retstr = StringIO()
    codec = 'utf-8'
    laparams = LAParams()
    device = TextConverter(rsrcmgr, retstr, codec=codec, laparams=laparams)
    fp = open(path, 'rb')
    interpreter = PDFPageInterpreter(rsrcmgr, device)
    password = ""
    maxpages = 0
    caching = True
    pagenos=set()

    for page in PDFPage.get_pages(fp, pagenos, maxpages=maxpages, password=password,caching=caching, check_extractable=True):
        interpreter.process_page(page)

    text = retstr.getvalue()

    fp.close()
    device.close()
    retstr.close()
    return text

PDFMiner's structure changed recently, so this should work for extracting text from the PDF files.

Edit : Still working as of the June 7th of 2018. Verified in Python Version 3.x

Edit: The solution works with Python 3.7 at October 3, 2019. I used the Python library pdfminer.six, released on November 2018.

Generate preview image from Video file?

I recommend php-ffmpeg library.

Extracting image

You can extract a frame at any timecode using the FFMpeg\Media\Video::frame method.

This code returns a FFMpeg\Media\Frame instance corresponding to the second 42. You can pass any FFMpeg\Coordinate\TimeCode as argument, see dedicated documentation below for more information.

$frame = $video->frame(FFMpeg\Coordinate\TimeCode::fromSeconds(42));
$frame->save('image.jpg');

If you want to extract multiple images from the video, you can use the following filter:

$video
    ->filters()
    ->extractMultipleFrames(FFMpeg\Filters\Video\ExtractMultipleFramesFilter::FRAMERATE_EVERY_10SEC, '/path/to/destination/folder/')
    ->synchronize();

$video
    ->save(new FFMpeg\Format\Video\X264(), '/path/to/new/file');

By default, this will save the frames as jpg images.

You are able to override this using setFrameFileType to save the frames in another format:

$frameFileType = 'jpg'; // either 'jpg', 'jpeg' or 'png'
$filter = new ExtractMultipleFramesFilter($frameRate, $destinationFolder);
$filter->setFrameFileType($frameFileType);

$video->addFilter($filter);

Python dict how to create key or append an element to key?

Here are the various ways to do this so you can compare how it looks and choose what you like. I've ordered them in a way that I think is most "pythonic", and commented the pros and cons that might not be obvious at first glance:

Using collections.defaultdict:

import collections
dict_x = collections.defaultdict(list)

...

dict_x[key].append(value)

Pros: Probably best performance. Cons: Not available in Python 2.4.x.

Using dict().setdefault():

dict_x = {}

...

dict_x.setdefault(key, []).append(value)

Cons: Inefficient creation of unused list()s.

Using try ... except:

dict_x = {}

...

try:
    values = dict_x[key]
except KeyError:
    values = dict_x[key] = []
values.append(value)

Or:

try:
    dict_x[key].append(value)
except KeyError:
    dict_x[key] = [value]

No WebApplicationContext found: no ContextLoaderListener registered?

You'll have to have a ContextLoaderListener in your web.xml - It loads your configuration files.

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

You need to understand the difference between Web application context and root application context .

In the web MVC framework, each DispatcherServlet has its own WebApplicationContext, which inherits all the beans already defined in the root WebApplicationContext. These inherited beans defined can be overridden in the servlet-specific scope, and new scope-specific beans can be defined local to a given servlet instance.

The dispatcher servlet's application context is a web application context which is only applicable for the Web classes . You cannot use these for your middle tier layers . These need a global app context using ContextLoaderListener .

Read the spring reference here for spring mvc .

How do I find the index of a character within a string in C?

What about:

char *string = "qwerty";
char *e = string;
int idx = 0;
while (*e++ != 'e') idx++;

copying to e to preserve the original string, I suppose if you don't care you could just operate over *string

Class 'DOMDocument' not found

For Centos 7 and php 7.1:
yum install php71w-xml
apachectl restart

Apache Proxy: No protocol handler was valid

This can happen if you don't have mod_proxy_http enabled

sudo a2enmod proxy_http

For me to get my https based load balancer working, i had to enable the following:

sudo a2enmod ssl
sudo a2enmod proxy
sudo a2enmod proxy_balancer
sudo a2enmod proxy_http

Where is the syntax for TypeScript comments documented?

Update November 2020

A website is now online with all the TSDoc syntax available (and that's awesome): https://tsdoc.org/


For reference, old answer:

The right syntax is now the one used by TSDoc. It will allow you to have your comments understood by Visual Studio Code or other documentation tools.

A good overview of the syntax is available here and especially here. The precise spec should be "soon" written up.

Another file worth checking out is this one where you will see useful standard tags.

Note: you should not use JSDoc, as explained on TSDoc main page: Why can't JSDoc be the standard? Unfortunately, the JSDoc grammar is not rigorously specified but rather inferred from the behavior of a particular implementation. The majority of the standard JSDoc tags are preoccupied with providing type annotations for plain JavaScript, which is an irrelevant concern for a strongly-typed language such as TypeScript. TSDoc addresses these limitations while also tackling a more sophisticated set of goals.

Check Postgres access for a user

For all users on a specific database, do the following:

# psql
\c your_database
select grantee, table_catalog, privilege_type, table_schema, table_name from information_schema.table_privileges order by grantee, table_schema, table_name;

Jinja2 template variable if None Object set a default value

According to docs you can just do:

{{ p|default('', true) }}

Cause None casts to False in boolean context.


Update: As lindes mentioned, it works only for simple data types.

jQuery Change event on an <input> element - any way to retain previous value?

Every DOM element has an attribute called defaultValue. You can use that to get the default value if you just want to compare the first changing of data.

Execute action when back bar button of UINavigationController is pressed

If you want to have back button with back arrow you can use an image and code below

backArrow.png arrow1 [email protected] arrow2 [email protected] arrow3

override func viewDidLoad() {
    super.viewDidLoad()
    let customBackButton = UIBarButtonItem(image: UIImage(named: "backArrow") , style: .plain, target: self, action: #selector(backAction(sender:)))
    customBackButton.imageInsets = UIEdgeInsets(top: 2, left: -8, bottom: 0, right: 0)
    navigationItem.leftBarButtonItem = customBackButton
}

func backAction(sender: UIBarButtonItem) {
    // custom actions here
    navigationController?.popViewController(animated: true)
}

How to send email to multiple recipients with addresses stored in Excel?

ToAddress = "[email protected]"
ToAddress1 = "[email protected]"
ToAddress2 = "[email protected]"
MessageSubject = "It works!."
Set ol = CreateObject("Outlook.Application")
Set newMail = ol.CreateItem(olMailItem)
newMail.Subject = MessageSubject
newMail.RecipIents.Add(ToAddress)
newMail.RecipIents.Add(ToAddress1)
newMail.RecipIents.Add(ToAddress2)
newMail.Send

Convert time span value to format "hh:mm Am/Pm" using C#

You cannot add AM / PM to a TimeSpan. You'll anyway have to associate the TimaSpan value with DateTime if you want to display the time in 12-hour clock format.

TimeSpan is not intended to use with a 12-hour clock format, because we are talking about a time interval here.

As it says in the documentation;

A TimeSpan object represents a time interval (duration of time or elapsed time) that is measured as a positive or negative number of days, hours, minutes, seconds, and fractions of a second. The TimeSpan structure can also be used to represent the time of day, but only if the time is unrelated to a particular date. Otherwise, the DateTime or DateTimeOffset structure should be used instead.

Also Microsoft Docs describes as follows;

A TimeSpan value can be represented as [-]d.hh:mm:ss.ff, where the optional minus sign indicates a negative time interval, the d component is days, hh is hours as measured on a 24-hour clock, mm is minutes, ss is seconds, and ff is fractions of a second.

So in this case, you can display using AM/PM as follows.

TimeSpan storedTime = new TimeSpan(03,00,00);
string displayValue = new DateTime().Add(storedTime).ToString("hh:mm tt");


Side note :
Also should note that the TimeOfDay property of DateTime is a TimeSpan, where it represents

a time interval that represents the fraction of the day that has elapsed since midnight.

Send values from one form to another form

Form1 Code :

private void button1_Click(object sender, EventArgs e)
{
            Form2 f2 = new Form2();
            f2.ShowDialog();
            MessageBox.Show("Form1 Message :"+Form2.t.Text); //can put label also in form 1 to show the value got from form2
}

Form2 Code :

        public Form2()
        {
            InitializeComponent();
            t = textBox1;                        //Initialize with static textbox
        }
        public static TextBox t=new TextBox();   //make static to get the same value as inserted
        private void button1_Click(object sender, EventArgs e)
        {

            this.Close();

        }

It Works!

How to publish a Web Service from Visual Studio into IIS?

If using Visual Studio 2010 you can right-click on the project for the service, and select properties. Then select the Web tab. Under the Servers section you can configure the URL. There is also a button to create the virtual directory.

Android camera intent

It took me some hours to get this working. The code it's almost a copy-paste from developer.android.com, with a minor difference.

Request this permission on the AndroidManifest.xml:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

On your Activity, start by defining this:

static final int REQUEST_IMAGE_CAPTURE = 1;
private Bitmap mImageBitmap;
private String mCurrentPhotoPath;
private ImageView mImageView;

Then fire this Intent in an onClick:

Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (cameraIntent.resolveActivity(getPackageManager()) != null) {
    // Create the File where the photo should go
    File photoFile = null;
    try {
        photoFile = createImageFile();
    } catch (IOException ex) {
        // Error occurred while creating the File
        Log.i(TAG, "IOException");
    }
    // Continue only if the File was successfully created
    if (photoFile != null) {
        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
        startActivityForResult(cameraIntent, REQUEST_IMAGE_CAPTURE);
    }
}

Add the following support method:

private File createImageFile() throws IOException {
    // Create an image file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";
    File storageDir = Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_PICTURES);
    File image = File.createTempFile(
            imageFileName,  // prefix
            ".jpg",         // suffix
            storageDir      // directory
    );

    // Save a file: path for use with ACTION_VIEW intents
    mCurrentPhotoPath = "file:" + image.getAbsolutePath();
    return image;
}

Then receive the result:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
        try {
            mImageBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.parse(mCurrentPhotoPath));
            mImageView.setImageBitmap(mImageBitmap);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

What made it work is the MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.parse(mCurrentPhotoPath)), which is different from the code from developer.android.com. The original code gave me a FileNotFoundException.

Add to Array jQuery

You are right. This has nothing to do with jQuery though.

var myArray = [];
myArray.push("foo");
// myArray now contains "foo" at index 0.

ggplot2 plot without axes, legends, etc

I didn't find this solution here. It removes all of it using the cowplot package:

library(cowplot)

p + theme_nothing() +
theme(legend.position="none") +
scale_x_continuous(expand=c(0,0)) +
scale_y_continuous(expand=c(0,0)) +
labs(x = NULL, y = NULL)

Just noticed that the same thing can be accomplished using theme.void() like this:

p + theme_void() +
theme(legend.position="none") +
scale_x_continuous(expand=c(0,0)) +
scale_y_continuous(expand=c(0,0)) +
labs(x = NULL, y = NULL)

How to get name of calling function/method in PHP?

My favourite way, in one line!

debug_backtrace()[1]['function'];

You can use it like this:

echo 'The calling function: ' . debug_backtrace()[1]['function'];

Note that this is only compatible with versions of PHP released within the last year. But it's a good idea to keep your PHP up to date anyway for security reasons.

Pass multiple optional parameters to a C# function

Use a parameter array with the params modifier:

public static int AddUp(params int[] values)
{
    int sum = 0;
    foreach (int value in values)
    {
        sum += value;
    }
    return sum;
}

If you want to make sure there's at least one value (rather than a possibly empty array) then specify that separately:

public static int AddUp(int firstValue, params int[] values)

(Set sum to firstValue to start with in the implementation.)

Note that you should also check the array reference for nullity in the normal way. Within the method, the parameter is a perfectly ordinary array. The parameter array modifier only makes a difference when you call the method. Basically the compiler turns:

int x = AddUp(4, 5, 6);

into something like:

int[] tmp = new int[] { 4, 5, 6 };
int x = AddUp(tmp);

You can call it with a perfectly normal array though - so the latter syntax is valid in source code as well.

What does the 'standalone' directive mean in XML?

standalone describes if the current XML document depends on an external markup declaration.

W3C describes its purpose in "Extensible Markup Language (XML) 1.0 (Fifth Edition)":

How to show git log history (i.e., all the related commits) for a sub directory of a git repo?

From directory foo/, use

  git log -- A

You need the '--' to separate <path>.. from the <since>..<until> refspecs.

# Show changes for src/nvfs
$ git log --oneline -- src/nvfs
d6f6b3b Changes for Mac OS X
803fcc3 Initial Commit

# Show all changes (one additional commit besides in src/nvfs).
$ git log --oneline
d6f6b3b Changes for Mac OS X
96cbb79 gitignore
803fcc3 Initial Commit

Warning: Cannot modify header information - headers already sent by ERROR

This typically occurs when there is unintended output from the script before you start the session. With your current code, you could try to use output buffering to solve it.

try adding a call to the ob_start(); function at the very top of your script and ob_end_flush(); at the very end of the document.

Find difference between timestamps in seconds in PostgreSQL

SELECT (cast(timestamp_1 as bigint) - cast(timestamp_2 as bigint)) FROM table;

In case if someone is having an issue using extract.

Angular2 - Http POST request parameters

I was having problems with every approach using multiple parameters, but it works quite well with single object

api:

    [HttpPut]
    [Route("addfeeratevalue")]
    public object AddFeeRateValue(MyValeObject val)

angular:

var o = {ID:rateId, AMOUNT_TO: amountTo, VALUE: value};
return this.http.put('/api/ctrl/mymethod', JSON.stringify(o), this.getPutHeaders());


private getPutHeaders(){
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    return new RequestOptions({
        headers: headers
        , withCredentials: true // optional when using windows auth
    });
}

Coerce multiple columns to factors at once

and, for completeness and with regards to this question asking about changing string columns only, there's mutate_if:

data <- cbind(stringVar = sample(c("foo","bar"),10,replace=TRUE),
              data.frame(matrix(sample(1:40), 10, 10, dimnames = list(1:10, LETTERS[1:10]))),stringsAsFactors=FALSE)     

factoredData = data %>% mutate_if(is.character,funs(factor(.)))

Split string to equal length substrings in Java

Here's the regex one-liner version:

System.out.println(Arrays.toString(
    "Thequickbrownfoxjumps".split("(?<=\\G.{4})")
));

\G is a zero-width assertion that matches the position where the previous match ended. If there was no previous match, it matches the beginning of the input, the same as \A. The enclosing lookbehind matches the position that's four characters along from the end of the last match.

Both lookbehind and \G are advanced regex features, not supported by all flavors. Furthermore, \G is not implemented consistently across the flavors that do support it. This trick will work (for example) in Java, Perl, .NET and JGSoft, but not in PHP (PCRE), Ruby 1.9+ or TextMate (both Oniguruma). JavaScript's /y (sticky flag) isn't as flexible as \G, and couldn't be used this way even if JS did support lookbehind.

I should mention that I don't necessarily recommend this solution if you have other options. The non-regex solutions in the other answers may be longer, but they're also self-documenting; this one's just about the opposite of that. ;)

Also, this doesn't work in Android, which doesn't support the use of \G in lookbehinds.

how to make jni.h be found?

Use the following code:

make -I/usr/lib/jvm/jdk*/include

where jdk* is the directory name of your jdk installation (e.g. jdk1.7.0).

And there wouldn't be a system-wide solution since the directory name would be different with different builds of JDK downloaded and installed. If you desire an automated solution, please include all commands in a single script and run the said script in Terminal.

Suppress InsecureRequestWarning: Unverified HTTPS request is being made in Python2.6

Warning message

~/venv/lib/python3.4/site-packages/urllib3/connectionpool.py:857: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings InsecureRequestWarning)

In Debian 8 this steps works

  1. In python3 code
import urllib3
urllib3.disable_warnings()
  1. Install two packages on Debian

libssl1.0.0_1.0.2l-1_bpo8+1_amd64.deb

libssl-dev_1.0.2l-1_bpo8+1_amd64.deb

debian mirror

To build dependencies with new library

  1. Create new venv for python project
python3 -m venv .venv
source .venv/bin/activate

Clean Install modules under python project inside virtual environment by

python3 -m pip install -e .

How to iterate over a TreeMap?

Just to point out the generic way to iterate over any map:

 private <K, V> void iterateOverMap(Map<K, V> map) {
    for (Map.Entry<K, V> entry : map.entrySet()) {
        System.out.println("key ->" + entry.getKey() + ", value->" + entry.getValue());
    }
    }

Difference between IsNullOrEmpty and IsNullOrWhiteSpace in C#

string.isNullOrWhiteSpace(text) should be used in most cases as it also includes a blank string.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace Rextester
{
    public class Program
    {
        public static void Main(string[] args)
        {
            //Your code goes here
            var str = "";

            Console.WriteLine(string.IsNullOrWhiteSpace(str));              

        }
    }
}

It returns True!

How to center text vertically with a large font-awesome icon?

a flexbox option - font awesome 4.7 and below

FA 4.x Hosted URL - https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css

_x000D_
_x000D_
div {_x000D_
  display: inline-flex; /* make element size relative to content */_x000D_
  align-items: center; /* vertical alignment of items */_x000D_
  line-height: 40px; /* vertically size by height, line-height or padding */_x000D_
  padding: 0px 10px; /* horizontal with padding-l/r */_x000D_
  border: 1px solid #ccc;_x000D_
}_x000D_
_x000D_
/* unnecessary styling below, ignore */_x000D_
body {display: flex;justify-content: center;align-items: center;height: 100vh;}div i {margin-right: 10px;}div {background-color: hsla(0, 0%, 87%, 0.5);}div:hover {background-color: hsla(34, 100%, 52%, 0.5);cursor: pointer;}
_x000D_
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>_x000D_
<div>_x000D_
    <i class='fa fa-2x fa-camera'></i>_x000D_
    hello world_x000D_
</div>
_x000D_
_x000D_
_x000D_

fiddle

http://jsfiddle.net/Hastig/V7DLm/180/


using flex and font awesome 5

FA 5.x Hosted URL - https://use.fontawesome.com/releases/v5.0.8/js/all.js

_x000D_
_x000D_
div {_x000D_
  display: inline-flex; /* make element size relative to content */_x000D_
  align-items: center; /* vertical alignment of items */_x000D_
  padding: 3px 10px; /* horizontal vertical position with padding */_x000D_
  border: 1px solid #ccc;_x000D_
}_x000D_
.svg-inline--fa { /* target all FA icons */_x000D_
  padding-right: 10px;_x000D_
}_x000D_
.icon-camera .svg-inline--fa { /* target specific icon */_x000D_
  font-size: 50px;_x000D_
}_x000D_
/* unnecessary styling below, ignore */_x000D_
body {display: flex;justify-content: center;align-items: center;height: 100vh; flex-direction: column;}div{margin: 10px 0;}div {background-color: hsla(0, 0%, 87%, 0.5);}div:hover {background-color: hsla(212, 100%, 63%, 1);cursor: pointer;}
_x000D_
<script src="https://use.fontawesome.com/releases/v5.0.8/js/all.js"></script>_x000D_
<div class="icon-camera">_x000D_
    <i class='fas fa-camera'></i>_x000D_
    hello world_x000D_
</div>_x000D_
<div class="icon-clock">_x000D_
    <i class='fas fa-clock'></i>_x000D_
    hello world_x000D_
</div>
_x000D_
_x000D_
_x000D_

fiddle

https://jsfiddle.net/3bpjvof2/

Directing print output to a .txt file

Give print a file keyword argument, where the value of the argument is a file stream. We can create a file stream using the open function:

print("Hello stackoverflow!", file=open("output.txt", "a"))
print("I have a question.", file=open("output.txt", "a"))

From the Python documentation about print:

The file argument must be an object with a write(string) method; if it is not present or None, sys.stdout will be used.

And the documentation for open:

Open file and return a corresponding file object. If the file cannot be opened, an OSError is raised.

The "a" as the second argument of open means "append" - in other words, the existing contents of the file won't be overwritten. If you want the file to be overwritten instead, use "w".


Opening a file with open many times isn't ideal for performance, however. You should ideally open it once and name it, then pass that variable to print's file option. You must remember to close the file afterwards!

f = open("output.txt", "a")
print("Hello stackoverflow!", file=f)
print("I have a question.", file=f)
f.close()

There's also a syntactic shortcut for this, which is the with block. This will close your file at the end of the block for you:

with open("output.txt", "a") as f:
    print("Hello stackoverflow!", file=f)
    print("I have a question.", file=f)