Programs & Examples On #Opencalais

Disabling Log4J Output in Java

Change level to what you want. (I am using Log4j2, version 2.6.2). This is simplest way, change to <Root level="off">

For example: File log4j2.xml
Development environment

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
        </Console>
        <Console name="SimpleConsole" target="SYSTEM_OUT">
            <PatternLayout pattern="%msg%n"/>
        </Console>
    </Appenders>
    <Loggers>
        <Root level="error">
            <AppenderRef ref="Console"/>
        </Root>
    </Loggers>
    <Loggers>
        <Root level="info">
            <AppenderRef ref="SimpleConsole"/>
        </Root>
    </Loggers>
</Configuration>

Production environment

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
        </Console>
        <Console name="SimpleConsole" target="SYSTEM_OUT">
            <PatternLayout pattern="%msg%n"/>
        </Console>
    </Appenders>
    <Loggers>
        <Root level="off">
            <AppenderRef ref="Console"/>
        </Root>
    </Loggers>
    <Loggers>
        <Root level="off">
            <AppenderRef ref="SimpleConsole"/>
        </Root>
    </Loggers>
</Configuration>

How to wait until an element exists?

You can listen to DOMNodeInserted or DOMSubtreeModified events which fire whenever a new element is added to the DOM.

There is also LiveQuery jQuery plugin which would detect when a new element is created:

$("#future_element").livequery(function(){
    //element created
});

How to secure the ASP.NET_SessionId cookie?

Going with Marcel's solution above to secure Forms Authentication cookie you should also update "authentication" config element to use SSL

<authentication mode="Forms">
   <forms ...  requireSSL="true" />
</authentication>

Other wise authentication cookie will not be https

See: http://msdn.microsoft.com/en-us/library/vstudio/1d3t3c61(v=vs.100).aspx

View's getWidth() and getHeight() returns 0

The basic problem is, that you have to wait for the drawing phase for the actual measurements (especially with dynamic values like wrap_content or match_parent), but usually this phase hasn't been finished up to onResume(). So you need a workaround for waiting for this phase. There a are different possible solutions to this:

1. Listen to Draw/Layout Events: ViewTreeObserver

A ViewTreeObserver gets fired for different drawing events. Usually the OnGlobalLayoutListener is what you want for getting the measurement, so the code in the listener will be called after the layout phase, so the measurements are ready:

view.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                view.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                view.getHeight(); //height is ready
            }
        });

Note: The listener will be immediately removed because otherwise it will fire on every layout event. If you have to support apps SDK Lvl < 16 use this to unregister the listener:

public void removeGlobalOnLayoutListener (ViewTreeObserver.OnGlobalLayoutListener victim)


2. Add a runnable to the layout queue: View.post()

Not very well known and my favourite solution. Basically just use the View's post method with your own runnable. This basically queues your code after the view's measure, layout, etc. as stated by Romain Guy:

The UI event queue will process events in order. After setContentView() is invoked, the event queue will contain a message asking for a relayout, so anything you post to the queue will happen after the layout pass

Example:

final View view=//smth;
...
view.post(new Runnable() {
            @Override
            public void run() {
                view.getHeight(); //height is ready
            }
        });

The advantage over ViewTreeObserver:

  • your code is only executed once and you don't have to disable the Observer after execution which can be a hassle
  • less verbose syntax

References:


3. Overwrite Views's onLayout Method

This is only practical in certain situation when the logic can be encapsulated in the view itself, otherwise this is a quite verbose and cumbersome syntax.

view = new View(this) {
    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        view.getHeight(); //height is ready
    }
};

Also mind, that onLayout will be called many times, so be considerate what you do in the method, or disable your code after the first time


4. Check if has been through layout phase

If you have code that is executing multiple times while creating the ui you could use the following support v4 lib method:

View viewYouNeedHeightFrom = ...
...
if(ViewCompat.isLaidOut(viewYouNeedHeightFrom)) {
   viewYouNeedHeightFrom.getHeight();
}

Returns true if view has been through at least one layout since it was last attached to or detached from a window.

Additional: Getting staticly defined measurements

If it suffices to just get the statically defined height/width, you can just do this with:

But mind you, that this might be different to the actual width/height after drawing. The javadoc describes the difference in more detail:

The size of a view is expressed with a width and a height. A view actually possess two pairs of width and height values.

The first pair is known as measured width and measured height. These dimensions define how big a view wants to be within its parent (see Layout for more details.) The measured dimensions can be obtained by calling getMeasuredWidth() and getMeasuredHeight().

The second pair is simply known as width and height, or sometimes drawing width and drawing height. These dimensions define the actual size of the view on screen, at drawing time and after layout. These values may, but do not have to, be different from the measured width and height. The width and height can be obtained by calling getWidth() and getHeight().

How can I copy a file on Unix using C?

sprintf( cmd, "/bin/cp -p \'%s\' \'%s\'", old, new);

system( cmd);

Add some error checks...

Otherwise, open both and loop on read/write, but probably not what you want.

...

UPDATE to address valid security concerns:

Rather than using "system()", do a fork/wait, and call execv() or execl() in the child.

execl( "/bin/cp", "-p", old, new);

Postgresql - unable to drop database because of some auto connections to DB

If no potential impact on other services on your machine, simply service postgresql restart

Set QLineEdit to accept only numbers

If you're using QT Creator 5.6 you can do that like this:

#include <QIntValidator>

ui->myLineEditName->setValidator( new QIntValidator);

I recomend you put that line after ui->setupUi(this);

I hope this helps.

Forgot Oracle username and password, how to retrieve?

if you are on Windows

  1. Start the Oracle service if it is not started (most probably it starts automatically when Windows starts)
  2. Start CMD.exe
  3. in the cmd (black window) type: sqlplus / as sysdba

Now you are logged with SYS user and you can do anything you want (query DBA_USERS to find out your username, or change any user password). You can not see the old password, you can only change it.

Print values for multiple variables on the same line from within a for-loop

As an additional note, there is no need for the for loop because of R's vectorization.

This:

P <- 243.51
t <- 31 / 365
n <- 365

for (r in seq(0.15, 0.22, by = 0.01))    
     A <- P * ((1 + (r/ n))^ (n * t))
     interest <- A - P
}

is equivalent to:

P <- 243.51
t <- 31 / 365
n <- 365
r <- seq(0.15, 0.22, by = 0.01)
A <- P * ((1 + (r/ n))^ (n * t))
interest <- A - P

Because r is a vector, the expression above containing it is performed for all values of the vector.

How to redraw DataTable with new data

I was having same issue, and the solution was working but with some alerts and warnings so here is full solution, the key was to check for existing DataTable object or not, if yes just clear the table and add jsonData, if not just create new.

            var table;
            if ($.fn.dataTable.isDataTable('#example')) {
                table = $('#example').DataTable();
                table.clear();
                table.rows.add(jsonData).draw();
            }
            else {
                table = $('#example').DataTable({
                    "data": jsonData,
                    "deferRender": true,
                    "pageLength": 25,
                    "retrieve": true,

Versions

  • JQuery: 3.3.1
  • DataTable: 1.10.20

Reading an image file in C/C++

Check out Intel Open CV library ...

Error: Could not create the Java Virtual Machine Mac OSX Mavericks

There can be one more reason for such behavior - you delete current working directory.

For example:

# in terminal #1
cd /home/user/myJavaApp

# in terminal #2
rm -rf /home/user/myJavaApp

# in terminal #1
java -jar myJar.jar

Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.

How do you declare an object array in Java?

Like this

Vehicle[] car = new Vehicle[10];

How to check if a file exists in Documents folder?

Swift 3:

let documentsURL = try! FileManager().url(for: .documentDirectory,
                                          in: .userDomainMask,
                                          appropriateFor: nil,
                                          create: true)

... gives you a file URL of the documents directory. The following checks if there's a file named foo.html:

let fooURL = documentsURL.appendingPathComponent("foo.html")
let fileExists = FileManager().fileExists(atPath: fooURL.path)

Objective-C:

NSString* documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];

NSString* foofile = [documentsPath stringByAppendingPathComponent:@"foo.html"];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:foofile];

Changing date format in R

This is really easy using package lubridate. All you have to do is tell R what format your date is already in. It then converts it into the standard format

nzd$date <- dmy(nzd$date)

that's it.

INSTALL_FAILED_UPDATE_INCOMPATIBLE when I try to install compiled .apk on device

you just run adb uninstall {{package_name}}. That's it. Now you try the build.

How do I toggle an element's class in pure JavaScript?

Here is a code for IE >= 9 by using split(" ") on the className :

function toggleClass(element, className) {
    var arrayClass = element.className.split(" ");
    var index = arrayClass.indexOf(className);

    if (index === -1) {
        if (element.className !== "") {
            element.className += ' '
        }
        element.className += className;
    } else {
        arrayClass.splice(index, 1);
        element.className = "";
        for (var i = 0; i < arrayClass.length; i++) {
            element.className += arrayClass[i];
            if (i < arrayClass.length - 1) {
                element.className += " ";
            }
        }
    }
}

SQL Server - Create a copy of a database table and place it in the same database?

You need to write SSIS to copy the table and its data, constraints and triggers. We have in our organization a software called Kal Admin by kalrom Systems that has a free version for downloading (I think that the copy tables feature is optional)

Filling a List with all enum values in Java

List<Something> result = new ArrayList<Something>(all);

EnumSet is a Java Collection, as it implements the Set interface:

public interface Set<E> extends Collection<E> 

So anything you can do with a Collection you can do with an EnumSet.

Url decode UTF-8 in Python

You can achieve an expected result with requests library as well:

import requests

url = "http://www.mywebsite.org/Data%20Set.zip"

print(f"Before: {url}")
print(f"After:  {requests.utils.unquote(url)}")

Output:

$ python3 test_url_unquote.py

Before: http://www.mywebsite.org/Data%20Set.zip
After:  http://www.mywebsite.org/Data Set.zip

Might be handy if you are already using requests, without using another library for this job.

Using python's mock patch.object to change the return value of a method called within another method

Let me clarify what you're talking about: you want to test Foo in a testcase, which calls external method uses_some_other_method. Instead of calling the actual method, you want to mock the return value.

class Foo:
    def method_1():
       results = uses_some_other_method()
    def method_n():
       results = uses_some_other_method()

Suppose the above code is in foo.py and uses_some_other_method is defined in module bar.py. Here is the unittest:

import unittest
import mock

from foo import Foo


class TestFoo(unittest.TestCase):

    def setup(self):
        self.foo = Foo()

    @mock.patch('foo.uses_some_other_method')
    def test_method_1(self, mock_method):
        mock_method.return_value = 3
        self.foo.method_1(*args, **kwargs)

        mock_method.assert_called_with(*args, **kwargs)

If you want to change the return value every time you passed in different arguments, mock provides side_effect.

Angular @ViewChild() error: Expected 2 arguments, but got 1

That also resolved my issue.

@ViewChild('map', {static: false}) googleMap;

php get values from json encode

json_decode will return the same array that was originally encoded. For instanse, if you

$array = json_decode($json, true);
echo $array['countryId'];

OR

$obj= json_decode($json);

echo $obj->countryId;

These both will echo 84. I think json_encode and json_decode function names are self-explanatory...

Best way to require all files from a directory in ruby?

I'm a few years late to the party, but I kind of like this one-line solution I used to get rails to include everything in app/workers/concerns:

Dir[ Rails.root.join *%w(app workers concerns *) ].each{ |f| require f }

VBA for clear value in specific range of cell and protected cell from being wash away formula

Try this

Sheets("your sheetname").range("A5:X50").Value = ""

You can also use

ActiveSheet.range

How to Resize image in Swift?

See my blog post, Resize image in swift and objective C, for further details.

Image resize function in swift as below.

func resizeImage(image: UIImage, targetSize: CGSize) -> UIImage {
    let size = image.size

    let widthRatio  = targetSize.width  / size.width
    let heightRatio = targetSize.height / size.height

    // Figure out what our orientation is, and use that to form the rectangle
    var newSize: CGSize
    if(widthRatio > heightRatio) {
        newSize = CGSizeMake(size.width * heightRatio, size.height * heightRatio)
    } else {
        newSize = CGSizeMake(size.width * widthRatio,  size.height * widthRatio)
    }

    // This is the rect that we've calculated out and this is what is actually used below
    let rect = CGRectMake(0, 0, newSize.width, newSize.height)

    // Actually do the resizing to the rect using the ImageContext stuff
    UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
    image.drawInRect(rect)
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return newImage
}

Use the above function and resize image with 200*200 as below code

self.resizeImage(UIImage(named: "yourImageName")!, targetSize: CGSizeMake(200.0, 200.0))

swift3 updated

 func resizeImage(image: UIImage, targetSize: CGSize) -> UIImage {
    let size = image.size

    let widthRatio  = targetSize.width  / size.width
    let heightRatio = targetSize.height / size.height

    // Figure out what our orientation is, and use that to form the rectangle
    var newSize: CGSize
    if(widthRatio > heightRatio) {
        newSize = CGSize(width: size.width * heightRatio, height: size.height * heightRatio)
    } else {
        newSize = CGSize(width: size.width * widthRatio,  height: size.height * widthRatio)
    }

    // This is the rect that we've calculated out and this is what is actually used below
    let rect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height)

    // Actually do the resizing to the rect using the ImageContext stuff
    UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
    image.draw(in: rect)
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return newImage!
}

How to install "make" in ubuntu?

I have no idea what linux distribution "ubuntu centOS" is. Ubuntu and CentOS are two different distributions.

To answer the question in the header: To install make in ubuntu you have to install build-essentials

sudo apt-get install build-essential

How do I determine scrollHeight?

Correct ways in jQuery are -

  • $('#test').prop('scrollHeight') OR
  • $('#test')[0].scrollHeight OR
  • $('#test').get(0).scrollHeight

Joining Multiple Tables - Oracle

While former answer is absolutely correct, I prefer using the JOIN ON syntax to be sure that I know how do I join and on what fields. It would look something like this:

SELECT bc.firstname, bc.lastname, b.title, TO_CHAR(bo.orderdate, 'MM/DD/YYYY') "Order         Date", p.publishername
FROM books b
JOIN book_customer bc ON bc.costumer_id = b.book_id
LEFT JOIN book_order bo ON bo.book_id = b.book_id
(etc.)
WHERE b.publishername = 'PRINTING IS US';

This syntax seperates completely the WHERE clause from the JOIN clause, making the statement more readable and easier for you to debug.

java.lang.OutOfMemoryError: bitmap size exceeds VM budget - Android

This explanation might help: http://code.google.com/p/android/issues/detail?id=8488#c80

"Fast Tips:

1) NEVER call System.gc() yourself. This has been propagated as a fix here, and it doesn't work. Do not do it. If you noticed in my explanation, before getting an OutOfMemoryError, the JVM already runs a garbage collection so there is no reason to do one again (its slowing your program down). Doing one at the end of your activity is just covering up the problem. It may causes the bitmap to be put on the finalizer queue faster, but there is no reason you couldn't have simply called recycle on each bitmap instead.

2) Always call recycle() on bitmaps you don't need anymore. At the very least, in the onDestroy of your activity go through and recycle all the bitmaps you were using. Also, if you want the bitmap instances to be collected from the dalvik heap faster, it doesn't hurt to clear any references to the bitmap.

3) Calling recycle() and then System.gc() still might not remove the bitmap from the Dalvik heap. DO NOT BE CONCERNED about this. recycle() did its job and freed the native memory, it will just take some time to go through the steps I outlined earlier to actually remove the bitmap from the Dalvik heap. This is NOT a big deal because the large chunk of native memory is already free!

4) Always assume there is a bug in the framework last. Dalvik is doing exactly what its supposed to do. It may not be what you expect or what you want, but its how it works. "

Insert Multiple Rows Into Temp Table With SQL Server 2012

Yes, SQL Server 2012 supports multiple inserts - that feature was introduced in SQL Server 2008.

That makes me wonder if you have Management Studio 2012, but you're really connected to a SQL Server 2005 instance ...

What version of the SQL Server engine do you get from SELECT @@VERSION ??

How to replace sql field value

Try this query it ll change the records ends with .com

 UPDATE tablename SET email = replace(email, '.com', '.org') WHERE  email LIKE '%.com';

Turning multi-line string into single comma-separated

$ awk -v ORS=, '{print $2}' data.txt | sed 's/,$//'
+12.0,+15.5,+9.0,+13.5

$ cat data.txt | tr -s ' ' | cut -d ' ' -f 2 | tr '\n' ',' | sed 's/,$//'
+12.0,+15.5,+9.0,+13.5

How to revert multiple git commits?

git reset --hard a
git reset --mixed d
git commit

That will act as a revert for all of them at once. Give a good commit message.

How to run Linux commands in Java?

The suggested solutions could be optimized using commons.io, handling the error stream, and using Exceptions. I would suggest to wrap like this for use in Java 8 or later:

public static List<String> execute(final String command) throws ExecutionFailedException, InterruptedException, IOException {
    try {
        return execute(command, 0, null, false);
    } catch (ExecutionTimeoutException e) { return null; } /* Impossible case! */
}

public static List<String> execute(final String command, final long timeout, final TimeUnit timeUnit) throws ExecutionFailedException, ExecutionTimeoutException, InterruptedException, IOException {
    return execute(command, 0, null, true);
}

public static List<String> execute(final String command, final long timeout, final TimeUnit timeUnit, boolean destroyOnTimeout) throws ExecutionFailedException, ExecutionTimeoutException, InterruptedException, IOException {
    Process process = new ProcessBuilder().command("bash", "-c", command).start();
    if(timeUnit != null) {
        if(process.waitFor(timeout, timeUnit)) {
            if(process.exitValue() == 0) {
                return IOUtils.readLines(process.getInputStream(), StandardCharsets.UTF_8);
            } else {
                throw new ExecutionFailedException("Execution failed: " + command, process.exitValue(), IOUtils.readLines(process.getInputStream(), StandardCharsets.UTF_8));
            }
        } else {
            if(destroyOnTimeout) process.destroy();
            throw new ExecutionTimeoutException("Execution timed out: " + command);
        }
    } else {
        if(process.waitFor() == 0) {
            return IOUtils.readLines(process.getInputStream(), StandardCharsets.UTF_8);
        } else {
            throw new ExecutionFailedException("Execution failed: " + command, process.exitValue(), IOUtils.readLines(process.getInputStream(), StandardCharsets.UTF_8));
        }
    }
}

public static class ExecutionFailedException extends Exception {

    private static final long serialVersionUID = 1951044996696304510L;

    private final int exitCode;
    private final List<String> errorOutput;

    public ExecutionFailedException(final String message, final int exitCode, final List<String> errorOutput) {
        super(message);
        this.exitCode = exitCode;
        this.errorOutput = errorOutput;
    }

    public int getExitCode() {
        return this.exitCode;
    }

    public List<String> getErrorOutput() {
        return this.errorOutput;
    }

}

public static class ExecutionTimeoutException extends Exception {

    private static final long serialVersionUID = 4428595769718054862L;

    public ExecutionTimeoutException(final String message) {
        super(message);
    }

}

Fatal error: Namespace declaration statement has to be the very first statement in the script in

File | Remove BOM in PhpStorm fixed this problem in both cases that I encountered it.

How to Set/Update State of StatefulWidget from other StatefulWidget in Flutter?

1.On Child Widget : add parameter Function paramter

class ChildWidget extends StatefulWidget {
  final Function() notifyParent;
  ChildWidget({Key key, @required this.notifyParent}) : super(key: key);
}

2.On Parent Widget : create a Function for the child to callback

refresh() {
  setState(() {});
}

3.On Parent Widget : pass parentFunction to Child Widget

new ChildWidget( notifyParent: refresh );  

4.On Child Widget : call the Parent Function

  widget.notifyParent();

How to wrap text in LaTeX tables?

I like the simplicity of tabulary package:

\usepackage{tabulary}
...
\begin{tabulary}{\linewidth}{LCL}
    \hline
    Short sentences      & \#  & Long sentences                                                 \\
    \hline
    This is short.       & 173 & This is much loooooooonger, because there are many more words.  \\
    This is not shorter. & 317 & This is still loooooooonger, because there are many more words. \\
    \hline
\end{tabulary} 

In the example, you arrange the whole width of the table with respect to \textwidth. E.g 0.4 of it. Then the rest is automatically done by the package.

Most of the example is taken from http://en.wikibooks.org/wiki/LaTeX/Tables .

android - how to convert int to string and place it in a EditText?

Use +, the string concatenation operator:

ed = (EditText) findViewById (R.id.box);
int x = 10;
ed.setText(""+x);

or use String.valueOf(int):

ed.setText(String.valueOf(x));

or use Integer.toString(int):

ed.setText(Integer.toString(x));

Python Pandas merge only certain columns

You could merge the sub-DataFrame (with just those columns):

df2[list('xab')]  # df2 but only with columns x, a, and b

df1.merge(df2[list('xab')])

How do I check if an element is really visible with JavaScript?

Try element.getBoundingClientRect(). It will return an object with properties

  • bottom
  • top
  • right
  • left
  • width -- browser dependent
  • height -- browser dependent

Check that the width and height of the element's BoundingClientRect are not zero which is the value of hidden or non-visible elements. If the values are greater than zero the element should be visible in the body. Then check if the bottom property is less than screen.height which would imply that the element is withing the viewport. (Technically you would also have to account for the top of the browser window including the searchbar, buttons, etc.)

What is difference between functional and imperative programming languages?

Here is the difference:

Imperative:

  • Start
  • Turn on your shoes size 9 1/2.
  • Make room in your pocket to keep an array[7] of keys.
  • Put the keys in the room for the keys in the pocket.
  • Enter garage.
  • Open garage.
  • Enter Car.

... and so on and on ...

  • Put the milk in the refrigerator.
  • Stop.

Declarative, whereof functional is a subcategory:

  • Milk is a healthy drink, unless you have problems digesting lactose.
  • Usually, one stores milk in a refrigerator.
  • A refrigerator is a box that keeps the things in it cool.
  • A store is a place where items are sold.
  • By "selling" we mean the exchange of things for money.
  • Also, the exchange of money for things is called "buying".

... and so on and on ...

  • Make sure we have milk in the refrigerator (when we need it - for lazy functional languages).

Summary: In imperative languages you tell the computer how to change bits, bytes and words in it's memory and in what order. In functional ones, we tell the computer what things, actions etc. are. For example, we say that the factorial of 0 is 1, and the factorial of every other natural number is the product of that number and the factorial of its predecessor. We don't say: To compute the factorial of n, reserve a memory region and store 1 there, then multiply the number in that memory region with the numbers 2 to n and store the result at the same place, and at the end, the memory region will contain the factorial.

Remove the legend on a matplotlib figure

As of matplotlib v1.4.0rc4, a remove method has been added to the legend object.

Usage:

ax.get_legend().remove()

or

legend = ax.legend(...)
...
legend.remove()

See here for the commit where this was introduced.

How to find the last field using 'cut'

Adding an approach to this old question just for the fun of it:

$ cat input.file # file containing input that needs to be processed
a;b;c;d;e
1;2;3;4;5
no delimiter here
124;adsf;15454
foo;bar;is;null;info

$ cat tmp.sh # showing off the script to do the job
#!/bin/bash
delim=';'
while read -r line; do  
    while [[ "$line" =~ "$delim" ]]; do
        line=$(cut -d"$delim" -f 2- <<<"$line")
    done
    echo "$line"
done < input.file

$ ./tmp.sh # output of above script/processed input file
e
5
no delimiter here
15454
info

Besides bash, only cut is used. Well, and echo, I guess.

Android WebView, how to handle redirects in app instead of opening a browser

You will have to set your custom WebviewClient overriding shouldOverrideUrlLoading method for your webview before loading the url.

mWebView.setWebViewClient(new WebViewClient()
        {
            @SuppressWarnings("deprecation")
            @Override
            public boolean shouldOverrideUrlLoading(WebView webView, String url)
            {
                return shouldOverrideUrlLoading(url);
            }

            @TargetApi(Build.VERSION_CODES.N)
            @Override
            public boolean shouldOverrideUrlLoading(WebView webView, WebResourceRequest request)
            {
                Uri uri = request.getUrl();
                return shouldOverrideUrlLoading(uri.toString());
            }

            private boolean shouldOverrideUrlLoading(final String url)
            {
                Log.i(TAG, "shouldOverrideUrlLoading() URL : " + url);

                // Here put your code

                return true; // Returning True means that application wants to leave the current WebView and handle the url itself, otherwise return false.
            }
        });

Checkout the example code for handling redirect urls and open PDF without download, in webview. https://gist.github.com/ashishdas09/014a408f9f37504eb2608d98abf49500

How to start anonymous thread class

Leaving this here for future reference, but its an answer too.

new Thread(() -> whatever()).start();

I can’t find the Android keytool

One thing that wasn't mentioned here (but kept me from running keytool altogether) was that you need to run the Command Prompt as Administrator.

Just wanted to share it...

Socket.IO - how do I get a list of connected sockets/clients?

I think we can access the socket object from the server, and you can assign the nickname, and point its socket id,

io.sockets.on('connection',function(socket){ 
    io.sockets.sockets['nickname'] = socket.id;
    client.on("chat", function(data) {      
        var sock_id = io.sockets.sockets['nickname']
        io.sockets.sockets[sock_id].emit("private", "message");
    });    
});

On disconnect please remove the nickname from io.sockets.sockets.

How to debug SSL handshake using cURL?

I have used this command to troubleshoot client certificate negotiation:

openssl s_client -connect www.test.com:443 -prexit

The output will probably contain "Acceptable client certificate CA names" and a list of CA certificates from the server, or possibly "No client certificate CA names sent", if the server doesn't always require client certificates.

Android studio - Failed to find target android-18

Check the local.properties file in your Studio Project. Chances are that the property sdk.dir points to the wrong folder if you had set/configured a previous android sdk from pre-studio era. This was the solution in my case.

What's the best visual merge tool for Git?

You can install ECMerge diff/merge tool on your Linux, Mac or Windows. It is pre-configured in Git, so just using git mergetool will do the job.

How to Validate Google reCaptcha on Form Submit

One issue I came up with that prevented these two files from working correctly was with my php.ini file for the website. Make sure this property is properly set, as follows:

allow_url_fopen = 

How does an SSL certificate chain bundle work?

You need to use the openssl pkcs12 -export -chain -in server.crt -CAfile ...

See https://www.openssl.org/docs/apps/pkcs12.html

CSS align images and text on same line

vertical-align: text-bottom;

Tested, this worked for me perfectly, just apply this to the image.

VBA Check if variable is empty

To check if a Variant is Null, you need to do it like:

Isnull(myvar) = True

or

Not Isnull(myvar)

:: (double colon) operator in Java 8

:: is a new operator included in Java 8 that is used to refer a method of an existing class. You can refer static methods and non-static methods of a class.

For referring static methods, the syntax is:

ClassName :: methodName 

For referring non-static methods, the syntax is

objRef :: methodName

And

ClassName :: methodName

The only prerequisite for referring a method is that method exists in a functional interface, which must be compatible with the method reference.

Method references, when evaluated, create an instance of the functional interface.

Found on: http://www.speakingcs.com/2014/08/method-references-in-java-8.html

Resize image in the wiki of GitHub using Markdown

Almost 5 years after only the direct HTML formatting works for images on GitHub and other markdown options still prevent images from loading when specifying some custom sizes even with the wrong dimensions. I prefer to specify the desired width and get the height calculated automatically, for example,

_x000D_
_x000D_
<img src="https://github.com/your_image.png" alt="Your image title" width="250"/>
_x000D_
_x000D_
_x000D_

How to restart Jenkins manually?

To restart Jenkins manually, you can use either of the following commands (by entering their URL in a browser):

(jenkins_url)/safeRestart - Allows all running jobs to complete. New jobs will remain in the queue to run after the restart is complete.

(jenkins_url)/restart - Forces a restart without waiting for builds to complete.

Git Symlinks in Windows

The most recent version of git scm (testet 2.11.1) allows to enable symbolic links. But you have to clone the repository with the symlinks again git clone -c core.symlinks=true <URL>. You need to run this command with administrator rights. It is also possible to create symlinks on Windows with mklink. Check out the wiki.

enter image description here

Disable Chrome strict MIME type checking

Another solution when a file pretends another extension

I use php inside of var.js file with this .htaccess.

<Files var.js>
    AddType application/x-httpd-php .js
</Files>

Then I write php code in the .js file

<?php
// This is a `.js` file but works with php
echo "var js_variable = '$php_variable';";

When I got the MIME type warning on Chrome, I fixed it by adding a Content-Type header line in the .js(but php) file.

<?php
header('Content-Type: application/javascript');        // <- Add this line
// This is a `.js` file but works with php
...

A browser won't execute .js file because apache sends the Content-Type header of the file as application/x-httpd-php that is defined in .htaccess. That's a security reason. But apache won't execute php as far as htaccess commands the impersonation, it's necessary. So we need to overwrite apache's Content-Type header with the php function header(). I guess that apache stops sending its own header when php sends it instead of apache before.

Why am I getting "Cannot Connect to Server - A network-related or instance-specific error"?

Verify the account you are using to create a session for the SQL Server instance.

See

How to get input text value on click in ReactJS

There are two ways to go about doing this.

  1. Create a state in the constructor that contains the text input. Attach an onChange event to the input box that updates state each time. Then onClick you could just alert the state object.

  2. handleClick: function() { alert(this.refs.myInput.value); },

Custom Input[type="submit"] style not working with jquerymobile button

jQuery Mobile >= 1.4

Create a custom class, e.g. .custom-btn. Note that to override jQM styles without using !important, CSS hierarchy should be respected. .ui-btn.custom-class or .ui-input-btn.custom-class.

.ui-input-btn.custom-btn {
   border:1px solid red;
   text-decoration:none;
   font-family:helvetica;
   color:red;
   background:url(img.png) repeat-x;
}

Add a data-wrapper-class to input. The custom class will be added to input wrapping div.

<input type="button" data-wrapper-class="custom-btn">

Demo


jQuery Mobile <= 1.3

Input button is wrapped by a DIV with class ui-btn. You need to select that div and the input[type="submit"]. Using !important is essential to override Jquery Mobile styles.

Demo

div.ui-btn, input[type="submit"] {
 border:1px solid red !important;
 text-decoration:none !important;
 font-family:helvetica !important;
 color:red !important;
 background:url(../images/btn_hover.png) repeat-x !important;
}

image.onload event and browser cache

I have met the same issue today. After trying various method, I realize that just put the code of sizing inside $(window).load(function() {}) instead of document.ready would solve part of issue (if you are not ajaxing the page).

Where is the documentation for the values() method of Enum?

The method is implicitly defined (i.e. generated by the compiler).

From the JLS:

In addition, if E is the name of an enum type, then that type has the following implicitly declared static methods:

/**
* Returns an array containing the constants of this enum 
* type, in the order they're declared.  This method may be
* used to iterate over the constants as follows:
*
*    for(E c : E.values())
*        System.out.println(c);
*
* @return an array containing the constants of this enum 
* type, in the order they're declared
*/
public static E[] values();

/**
* Returns the enum constant of this type with the specified
* name.
* The string must match exactly an identifier used to declare
* an enum constant in this type.  (Extraneous whitespace 
* characters are not permitted.)
* 
* @return the enum constant with the specified name
* @throws IllegalArgumentException if this enum type has no
* constant with the specified name
*/
public static E valueOf(String name);

Difference between arguments and parameters in Java

The term parameter refers to any declaration within the parentheses following the method/function name in a method/function declaration or definition; the term argument refers to any expression within the parentheses of a method/function call. i.e.

  1. parameter used in function/method definition.
  2. arguments used in function/method call.

Please have a look at the below example for better understanding:

package com.stackoverflow.works;

public class ArithmeticOperations {

    public static int add(int x, int y) { //x, y are parameters here
        return x + y;
    }

    public static void main(String[] args) {
        int x = 10;
        int y = 20;
        int sum = add(x, y); //x, y are arguments here
        System.out.println("SUM IS: " +sum);
    }

}

Thank you!

matplotlib does not show my drawings although I call pyplot.show()

For me the problem happens if I simply create an empty matplotlibrc file under ~/.matplotlib on macOS. Adding "backend: macosx" in it fixes the problem.

I think it is a bug: if backend is not specified in my matplotlibrc it should take the default value.

Search and replace a line in a file in Python

I guess something like this should do it. It basically writes the content to a new file and replaces the old file with the new file:

from tempfile import mkstemp
from shutil import move, copymode
from os import fdopen, remove

def replace(file_path, pattern, subst):
    #Create temp file
    fh, abs_path = mkstemp()
    with fdopen(fh,'w') as new_file:
        with open(file_path) as old_file:
            for line in old_file:
                new_file.write(line.replace(pattern, subst))
    #Copy the file permissions from the old file to the new file
    copymode(file_path, abs_path)
    #Remove original file
    remove(file_path)
    #Move new file
    move(abs_path, file_path)

htaccess redirect to https://www

BAD SOLUTION AND WHY!

Don't ever use the solution below because when you are using their code that is something like:

RewriteCond %{HTTPS} off
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule .* https://www.example.com%{REQUEST_URI} [L,R=301]

The browser goes to:

http://example.com

Then redirects to:

https://example.com

Then redirects to:

https://www.example.com

This is too much request to the server.

Most of the answers even accepted one has this problem.


BEST SOLUTION AND THE ANSWER

This code has an [OR] condition to prevent dual changes at url!

RewriteEngine on
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule (.*) https://www.example.com%{REQUEST_URI} [R=301,L]

SQL Server - INNER JOIN WITH DISTINCT

Try this:

select distinct a.FirstName, a.LastName, v.District
from AddTbl a 
  inner join ValTbl v
  on a.LastName = v.LastName
order by a.FirstName;

Or this (it does the same, but the syntax is different):

select distinct a.FirstName, a.LastName, v.District
from AddTbl a, ValTbl v
where a.LastName = v.LastName
order by a.FirstName;

How do I add a newline using printf?

Try this:

printf '\n%s\n' 'I want this on a new line!'

That allows you to separate the formatting from the actual text. You can use multiple placeholders and multiple arguments.

quantity=38; price=142.15; description='advanced widget'
$ printf '%8d%10.2f  %s\n' "$quantity" "$price" "$description"
      38    142.15  advanced widget

Can’t delete docker image with dependent child images

Expanding on the answer provided by @Nguyen - this function can be added to your .bashrc etc and then called from the commandline to help clean up any image has dependent child images errors...

You can run the function as yourself, and if a docker ps fails, then it will run the docker command with sudo and prompt you for your password.

Does NOT delete images for any running containers!

docker_rmi_dependants ()                                                                                                                                                         
{ 
  DOCKER=docker
  [ docker ps >/dev/null 2>&1 ] || DOCKER="sudo docker"

  echo "Docker: ${DOCKER}"

  for n in $(${DOCKER} images | awk '$2 == "<none>" {print $3}');
  do  
    echo "ImageID: $n";
    ${DOCKER} inspect --format='{{.Id}} {{.Parent}}' $(${DOCKER} images --filter since=$n -q);
  done;

  ${DOCKER} rmi $(${DOCKER} images | awk '$2 == "<none>" {print $3}')
}

I also have this in my .bashrc file...

docker_rm_dangling ()  
{ 
  DOCKER=docker
  [ docker ps >/dev/null 2>&1 ] || DOCKER="sudo docker"

  echo "Docker: ${DOCKER}"

  ${DOCKER} images -f dangling=true 2>&1 > /dev/null && YES=$?;                                                                                                                  
  if [ $YES -eq 1 ]; then
    read -t 30 -p "Press ENTER to remove, or CTRL-C to quit.";
    ${DOCKER} rmi $(${DOCKER} images -f dangling=true -q);
  else
    echo "Nothing to do... all groovy!";
  fi  
}

Works with:

$ docker --version 
Docker version 17.05.0-ce, build 89658be

How does one use glide to download an image into a bitmap?

This is what worked for me: https://github.com/bumptech/glide/wiki/Custom-targets#overriding-default-behavior

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.transition.Transition;
import com.bumptech.glide.request.target.BitmapImageViewTarget;

...

Glide.with(yourFragment)
  .load("yourUrl")
  .asBitmap()
  .into(new BitmapImageViewTarget(yourImageView) {
    @Override
    public void onResourceReady(Bitmap bitmap, Transition<? super Bitmap> anim) {
        super.onResourceReady(bitmap, anim);
        Palette.generateAsync(bitmap, new Palette.PaletteAsyncListener() {  
            @Override
            public void onGenerated(Palette palette) {
                // Here's your generated palette
                Palette.Swatch swatch = palette.getDarkVibrantSwatch();
                int color = palette.getDarkVibrantColor(swatch.getTitleTextColor());
            }
        });
    }
});

Sniff HTTP packets for GET and POST requests from an application

Put http.request.method == "POST" in the display filter of wireshark to only show POST requests. Click on the packet, then expand the Hypertext Transfer Protocol field. The POST data will be right there on top.

Could not find an implementation of the query pattern

For those of you (like me) that wasted too much time from this error:

I had received the same error: "Could not find implementation of query Pattern for source type 'DbSet'" but the solution for me was fixing a mistake at the DbContext level.

When I created my context I had this:

public class ContactContext : DbContext
    {
        public ContactContext() : base() { }

        public DbSet Contacts { get; set; }
    }

And my Repository (I was following a Repository pattern in ASP.NET guide) looked like this:

public Contact FindById(int id)
    {       
        var contact = from c in _db.Contacts where c.Id == id select c;
        return contact;
    }

My issue came from the initial setup of my DbContext, when I used DbSet as a generic instead of the type.

I changed public DbSet Contacts { get; set; } to public DbSet<Contact> Contacts { get; set; } and suddenly the query was recognized.


This is probably what k.m says in his answer, but since he mentioned IEnumerable<t> and not DbSet<<YourDomainObject>> I had to dig around in the code for a couple hours to find the line that caused this headache.

python location on mac osx

This one will solve all your problems not only for Mac but works on every basic shell -> Linux also:

If you have a Mac and you've installed python3 like most of us do :) (with brew install - ofc)

your file is located in:

/usr/local/Cellar/python/3.6.4_4/bin/python3

How do you know? -> you can run this on every basic shell Run:

which python3

You should get:

/usr/local/bin/python3

Now this is a symbolic link, how do you know? Run:

ls -al /usr/local/bin/python3 

and you'll get:

/usr/local/bin/python3 -> /usr/local/Cellar/python/3.6.4_4/bin/python3

which means that your

/usr/local/bin/python3 

is actually pointing to:

/usr/local/Cellar/python/3.6.4_4/bin/python3

If, for some reason, your

/usr/local/bin/python3 

is not pointing to the place you want, which in our case:

/usr/local/Cellar/python/3.6.4_4/bin/python3

just backup it:

cp /usr/local/bin/python3{,.orig} 

and run:

rm -rf /usr/local/bin/python3

now create a new symbolic link:

ln -s /usr/local/Cellar/python/3.6.4_4/bin/python3 /usr/local/bin/python3 

and now your

/usr/local/bin/python3

is pointing to

/usr/local/Cellar/python/3.6.4_4/bin/python3 

Check it out by running:

ls -al /usr/local/bin/python3

Removing character in list of strings

A faster way is to join the list, replace 8 and split the new string:

mylist = [("aaaa8"),("bb8"),("ccc8"),("dddddd8")]
mylist = ' '.join(mylist).replace('8','').split()
print mylist

Compare every item to every other item in ArrayList

In some cases this is the best way because your code may have change something and j=i+1 won't check that.

for (int i = 0; i < list.size(); i++){  
    for (int j = 0; j < list.size(); j++) {
                if(i == j) {
               //to do code here
                    continue;
                }

}

}

determine DB2 text string length

Mostly we write below statement select * from table where length(ltrim(rtrim(field)))=10;

SimpleDateFormat parse loses timezone

OP's solution to his problem, as he says, has dubious output. That code still shows confusion about representations of time. To clear up this confusion, and make code that won't lead to wrong times, consider this extension of what he did:

public static void _testDateFormatting() {
    SimpleDateFormat sdfGMT1 = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
    sdfGMT1.setTimeZone(TimeZone.getTimeZone("GMT"));
    SimpleDateFormat sdfGMT2 = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss z");
    sdfGMT2.setTimeZone(TimeZone.getTimeZone("GMT"));

    SimpleDateFormat sdfLocal1 = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
    SimpleDateFormat sdfLocal2 = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss z");

    try {
        Date d = new Date();
        String s1 = d.toString();
        String s2 = sdfLocal1.format(d);
        // Store s3 or s4 in database.
        String s3 = sdfGMT1.format(d);
        String s4 = sdfGMT2.format(d);
        // Retrieve s3 or s4 from database, using LOCAL sdf.
        String s5 = sdfLocal1.parse(s3).toString();
        //EXCEPTION String s6 = sdfLocal2.parse(s3).toString();
        String s7 = sdfLocal1.parse(s4).toString();
        String s8 = sdfLocal2.parse(s4).toString();
        // Retrieve s3 from database, using GMT sdf.
        // Note that this is the SAME sdf that created s3.
        Date d2 = sdfGMT1.parse(s3);
        String s9 = d2.toString();
        String s10 = sdfGMT1.format(d2);
        String s11 = sdfLocal2.format(d2);
    } catch (Exception e) {
        e.printStackTrace();
    }       
}

examining values in a debugger:

s1  "Mon Sep 07 06:11:53 EDT 2015" (id=831698113128)    
s2  "2015.09.07 06:11:53" (id=831698114048) 
s3  "2015.09.07 10:11:53" (id=831698114968) 
s4  "2015.09.07 10:11:53 GMT+00:00" (id=831698116112)   
s5  "Mon Sep 07 10:11:53 EDT 2015" (id=831698116944)    
s6  -- omitted, gave parse exception    
s7  "Mon Sep 07 10:11:53 EDT 2015" (id=831698118680)    
s8  "Mon Sep 07 06:11:53 EDT 2015" (id=831698119584)    
s9  "Mon Sep 07 06:11:53 EDT 2015" (id=831698120392)    
s10 "2015.09.07 10:11:53" (id=831698121312) 
s11 "2015.09.07 06:11:53 EDT" (id=831698122256) 

sdf2 and sdfLocal2 include time zone, so we can see what is really going on. s1 & s2 are at 06:11:53 in zone EDT. s3 & s4 are at 10:11:53 in zone GMT -- equivalent to the original EDT time. Imagine we save s3 or s4 in a data base, where we are using GMT for consistency, so we can have times from anywhere in the world, without storing different time zones.

s5 parses the GMT time, but treats it as a local time. So it says "10:11:53" -- the GMT time -- but thinks it is 10:11:53 in local time. Not good.

s7 parses the GMT time, but ignores the GMT in the string, so still treats it as a local time.

s8 works, because now we include GMT in the string, and the local zone parser uses it to convert from one time zone to another.

Now suppose you don't want to store the zone, you want to be able to parse s3, but display it as a local time. The answer is to parse using the same time zone it was stored in -- so use the same sdf as it was created in, sdfGMT1. s9, s10, & s11 are all representations of the original time. They are all "correct". That is, d2 == d1. Then it is only a question of how you want to DISPLAY it. If you want to display what is stored in DB -- GMT time -- then you need to format it using a GMT sdf. Ths is s10.

So here is the final solution, if you don't want to explicitly store with " GMT" in the string, and want to display in GMT format:

public static void _testDateFormatting() {
    SimpleDateFormat sdfGMT1 = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
    sdfGMT1.setTimeZone(TimeZone.getTimeZone("GMT"));

    try {
        Date d = new Date();
        String s3 = sdfGMT1.format(d);
        // Store s3 in DB.
        // ...
        // Retrieve s3 from database, using GMT sdf.
        Date d2 = sdfGMT1.parse(s3);
        String s10 = sdfGMT1.format(d2);
    } catch (Exception e) {
        e.printStackTrace();
    }       
}

Spring @PropertySource using YAML

From Spring Boot 1.4, you can use the new @SpringBootTest annotation to achieve this more easily (and to simplify your integration test setup in general) by bootstrapping your integration tests using Spring Boot support.

Details on the Spring Blog.

As far as I can tell, this means you get all the benefits of Spring Boot's externalized config goodness just like in your production code, including automatically picking up YAML config from the classpath.

By default, this annotation will

... first attempt to load @Configuration from any inner-classes, and if that fails, it will search for your primary @SpringBootApplication class.

but you can specify other configuration classes if required.

For this particular case, you can combine @SpringBootTest with @ActiveProfiles( "test" ) and Spring will pick up your YAML config, provided it follows the normal Boot naming standards (i.e. application-test.yml).

@RunWith( SpringRunner.class )
@SpringBootTest
@ActiveProfiles( "test" )
public class SpringBootITest {

    @Value("${db.username}")
    private String username;

    @Autowired
    private MyBean myBean;

    ...

}

Note: SpringRunner.class is the new name for SpringJUnit4ClassRunner.class

Comparison of Android Web Service and Networking libraries: OKHTTP, Retrofit and Volley

Retrofit 1.9.0 vs. RoboSpice

I am using both in my app.

Robospice works faster than Retrofit whenever I parse the nested JSON class. Because Spice Manger will do everything for you. In Retrofit you need to create GsonConverter and deserialize it.

I created two fragments in the same activity and called the same time with two same kind of URLs.

09-23 20:12:32.830  16002-16002/com.urbanpro.seeker E/RETROFIT?   RestAdapter Init
09-23 20:12:32.833  16002-16002/com.urbanpro.seeker E/RETROFIT? calling the method
09-23 20:12:32.837  16002-16002/com.urbanpro.seeker E/ROBOSPICE? initialzig spice manager
09-23 20:12:32.860  16002-16002/com.urbanpro.seeker E/ROBOSPICE? Executing the method
09-23 20:12:33.537  16002-16002/com.urbanpro.seeker E/ROBOSPICE? on SUcceess
09-23 20:12:33.553  16002-16002/com.urbanpro.seeker E/ROBOSPICE? gettting the all contents
09-23 20:12:33.601  16002-21819/com.urbanpro.seeker E/RETROFIT? deseriazation starts
09-23 20:12:33.603  16002-21819/com.urbanpro.seeker E/RETROFIT? deseriazation ends

apache and httpd running but I can't see my website

There are several possibilities.

  • firewall, iptables configuration
  • apache listen address / port

More information is needed about your configuration. What distro are you using? Can you connect via 127.0.0.1?

If the issue is with the firewall/iptables, you can add the following lines to /etc/sysconfig/iptables:

-A INPUT -p tcp -m tcp --dport 80 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 443 -j ACCEPT

(Second line is only needed for https)

Make sure this is above any lines that would globally restrict access, like the following:

-A INPUT -j REJECT --reject-with icmp-host-prohibited

Tested on CentOS 6.3

And finally

service iptables restart

Can I set subject/content of email using mailto:?

<a href="mailto:[email protected]?subject=Feedback for 
webdevelopersnotes.com&body=The Tips and Tricks section is great
&[email protected]
&[email protected]">Send me an email</a>

you can use this code to set subject, body, cc, bcc

Landscape printing from HTML

I tried Denis's answer and hit some problems (portrait pages didn't print properly after going after landscape pages), so here is my solution:

_x000D_
_x000D_
body {_x000D_
  margin: 0;_x000D_
  background: #CCCCCC;_x000D_
}_x000D_
_x000D_
div.page {_x000D_
  margin: 10px auto;_x000D_
  border: solid 1px black;_x000D_
  display: block;_x000D_
  page-break-after: always;_x000D_
  width: 209mm;_x000D_
  height: 296mm;_x000D_
  overflow: hidden;_x000D_
  background: white;_x000D_
}_x000D_
_x000D_
div.landscape-parent {_x000D_
  width: 296mm;_x000D_
  height: 209mm;_x000D_
}_x000D_
_x000D_
div.landscape {_x000D_
  width: 296mm;_x000D_
  height: 209mm;_x000D_
}_x000D_
_x000D_
div.content {_x000D_
  padding: 10mm;_x000D_
}_x000D_
_x000D_
body,_x000D_
div,_x000D_
td {_x000D_
  font-size: 13px;_x000D_
  font-family: Verdana;_x000D_
}_x000D_
_x000D_
@media print {_x000D_
  body {_x000D_
    background: none;_x000D_
  }_x000D_
  div.page {_x000D_
    width: 209mm;_x000D_
    height: 296mm;_x000D_
  }_x000D_
  div.landscape {_x000D_
    transform: rotate(270deg) translate(-296mm, 0);_x000D_
    transform-origin: 0 0;_x000D_
  }_x000D_
  div.portrait,_x000D_
  div.landscape,_x000D_
  div.page {_x000D_
    margin: 0;_x000D_
    padding: 0;_x000D_
    border: none;_x000D_
    background: none;_x000D_
  }_x000D_
}
_x000D_
<div class="page">_x000D_
  <div class="content">_x000D_
    First page in Portrait mode_x000D_
  </div>_x000D_
</div>_x000D_
<div class="page landscape-parent">_x000D_
  <div class="landscape">_x000D_
    <div class="content">_x000D_
      Second page in Landscape mode (correctly shows horizontally in browser and prints rotated in printer)_x000D_
    </div>_x000D_
  </div>_x000D_
</div>_x000D_
<div class="page">_x000D_
  <div class="content">_x000D_
    Third page in Portrait mode_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

JSON character encoding - is UTF-8 well-supported by browsers or should I use numeric escape sequences?

I had a problem there. When I JSON encode a string with a character like "é", every browsers will return the same "é", except IE which will return "\u00e9".

Then with PHP json_decode(), it will fail if it find "é", so for Firefox, Opera, Safari and Chrome, I've to call utf8_encode() before json_decode().

Note : with my tests, IE and Firefox are using their native JSON object, others browsers are using json2.js.

Concatenate two slices in Go

I think it's important to point out and to know that if the destination slice (the slice you append to) has sufficient capacity, the append will happen "in-place", by reslicing the destination (reslicing to increase its length in order to be able to accommodate the appendable elements).

This means that if the destination was created by slicing a bigger array or slice which has additional elements beyond the length of the resulting slice, they may get overwritten.

To demonstrate, see this example:

a := [10]int{1, 2}
fmt.Printf("a: %v\n", a)

x, y := a[:2], []int{3, 4}
fmt.Printf("x: %v, y: %v\n", x, y)
fmt.Printf("cap(x): %v\n", cap(x))

x = append(x, y...)
fmt.Printf("x: %v\n", x)

fmt.Printf("a: %v\n", a)

Output (try it on the Go Playground):

a: [1 2 0 0 0 0 0 0 0 0]
x: [1 2], y: [3 4]
cap(x): 10
x: [1 2 3 4]
a: [1 2 3 4 0 0 0 0 0 0]

We created a "backing" array a with length 10. Then we create the x destination slice by slicing this a array, y slice is created using the composite literal []int{3, 4}. Now when we append y to x, the result is the expected [1 2 3 4], but what may be surprising is that the backing array a also changed, because capacity of x is 10 which is sufficient to append y to it, so x is resliced which will also use the same a backing array, and append() will copy elements of y into there.

If you want to avoid this, you may use a full slice expression which has the form

a[low : high : max]

which constructs a slice and also controls the resulting slice's capacity by setting it to max - low.

See the modified example (the only difference is that we create x like this: x = a[:2:2]:

a := [10]int{1, 2}
fmt.Printf("a: %v\n", a)

x, y := a[:2:2], []int{3, 4}
fmt.Printf("x: %v, y: %v\n", x, y)
fmt.Printf("cap(x): %v\n", cap(x))

x = append(x, y...)
fmt.Printf("x: %v\n", x)

fmt.Printf("a: %v\n", a)

Output (try it on the Go Playground)

a: [1 2 0 0 0 0 0 0 0 0]
x: [1 2], y: [3 4]
cap(x): 2
x: [1 2 3 4]
a: [1 2 0 0 0 0 0 0 0 0]

As you can see, we get the same x result but the backing array a did not change, because capacity of x was "only" 2 (thanks to the full slice expression a[:2:2]). So to do the append, a new backing array is allocated that can store the elements of both x and y, which is distinct from a.

Select first occurring element after another element

Just hit on this when trying to solve this type of thing my self.

I did a selector that deals with the element after being something other than a p.

.here .is.the #selector h4 + * {...}

Hope this helps anyone who finds it :)

Android App Not Install. An existing package by the same name with a conflicting signature is already installed

If you use multiple users at android, verify that the app is uninstalled everywhere.

Increasing nesting function calls limit

Personally I would suggest this is an error as opposed to a setting that needs adjusting. In my code it was because I had a class that had the same name as a library within one of my controllers and it seemed to trip it up.

Output errors and see where this is being triggered.

Error: Generic Array Creation

The following will give you an array of the type you want while preserving type safety.

PCB[] getAll(Class<PCB[]> arrayType) {  
    PCB[] res = arrayType.cast(java.lang.reflect.Array.newInstance(arrayType.getComponentType(), list.size()));  
    for (int i = 0; i < res.length; i++)  {  
        res[i] = list.get(i);  
    }  
    list.clear();  
    return res;  
}

How this works is explained in depth in my answer to the question that Kirk Woll linked as a duplicate.

How to customize the back button on ActionBar

I have checked the question. Here is the steps that I follow. The source code is hosted on GitHub: https://github.com/jiahaoliuliu/sherlockActionBarLab

Override the actual style for the pre-v11 devices.

Copy and paste the follow code in the file styles.xml of the default values folder.

<resources>
    <style name="MyCustomTheme" parent="Theme.Sherlock.Light">
    <item name="homeAsUpIndicator">@drawable/ic_home_up</item>
    </style>
</resources>

Note that the parent could be changed to any Sherlock theme.

Override the actual style for the v11+ devices.

On the same folder where the folder values is, create a new folder called values-v11. Android will automatically look for the content of this folder for devices with API or above.

Create a new file called styles.xml and paste the follow code into the file:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="MyCustomTheme" parent="Theme.Sherlock.Light">
    <item name="android:homeAsUpIndicator">@drawable/ic_home_up</item>
    </style>
</resources>

Note tha the name of the style must be the same as the file in the default values folder and instead of the item homeAsUpIndicator, it is called android:homeAsUpIndicator.

The item issue is because for devices with API 11 or above, Sherlock Action Bar use the default Action Bar which comes with Android, which the key name is android:homeAsUpIndicator. But for the devices with API 10 or lower, Sherlock Action Bar uses its own ActionBar, which the home as up indicator is called simple "homeAsUpIndicator".

Use the new theme in the manifest

Replace the theme for the application/activity in the AndroidManifest file:

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/MyCustomTheme" >

vba error handling in loop

How about:

    For Each oSheet In ActiveWorkbook.Sheets
        If oSheet.ListObjects.Count > 0 Then
          oCmbBox.AddItem oSheet.Name
        End If
    Next oSheet

How to update SQLAlchemy row entry?

There are several ways to UPDATE using sqlalchemy

1) user.no_of_logins += 1
   session.commit()

2) session.query().\
       filter(User.username == form.username.data).\
       update({"no_of_logins": (User.no_of_logins +1)})
   session.commit()

3) conn = engine.connect()
   stmt = User.update().\
       values(no_of_logins=(User.no_of_logins + 1)).\
       where(User.username == form.username.data)
   conn.execute(stmt)

4) setattr(user, 'no_of_logins', user.no_of_logins+1)
   session.commit()

Binding ConverterParameter

The ConverterParameter property can not be bound because it is not a dependency property.

Since Binding is not derived from DependencyObject none of its properties can be dependency properties. As a consequence, a Binding can never be the target object of another Binding.

There is however an alternative solution. You could use a MultiBinding with a multi-value converter instead of a normal Binding:

<Style TargetType="FrameworkElement">
    <Setter Property="Visibility">
        <Setter.Value>
            <MultiBinding Converter="{StaticResource AccessLevelToVisibilityConverter}">
                <Binding Path="Tag" RelativeSource="{RelativeSource Mode=FindAncestor,
                                                     AncestorType=UserControl}"/>
                <Binding Path="Tag" RelativeSource="{RelativeSource Mode=Self}"/>
            </MultiBinding>
        </Setter.Value>
    </Setter>
</Style>

The multi-value converter gets an array of source values as input:

public class AccessLevelToVisibilityConverter : IMultiValueConverter
{
    public object Convert(
        object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        return values.All(v => (v is bool && (bool)v))
            ? Visibility.Visible
            : Visibility.Hidden;
    }

    public object[] ConvertBack(
        object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}

How to run an EXE file in PowerShell with parameters with spaces and quotes

When PowerShell sees a command starting with a string it just evaluates the string, that is, it typically echos it to the screen, for example:

PS> "Hello World"
Hello World

If you want PowerShell to interpret the string as a command name then use the call operator (&) like so:

PS> & 'C:\Program Files\IIS\Microsoft Web Deploy\msdeploy.exe'

After that you probably only need to quote parameter/argument pairs that contain spaces and/or quotation chars. When you invoke an EXE file like this with complex command line arguments it is usually very helpful to have a tool that will show you how PowerShell sends the arguments to the EXE file. The PowerShell Community Extensions has such a tool. It is called echoargs. You just replace the EXE file with echoargs - leaving all the arguments in place, and it will show you how the EXE file will receive the arguments, for example:

PS> echoargs -verb:sync -source:dbfullsql="Data Source=mysource;Integrated Security=false;User ID=sa;Pwd=sapass!;Database=mydb;" -dest:dbfullsql="Data Source=.\mydestsource;Integrated Security=false;User ID=sa;Pwd=sapass!;Database=mydb;",computername=10.10.10.10,username=administrator,password=adminpass

Arg 0 is <-verb:sync>
Arg 1 is <-source:dbfullsql=Data>
Arg 2 is <Source=mysource;Integrated>
Arg 3 is <Security=false;User>
Arg 4 is <ID=sa;Pwd=sapass!;Database=mydb;>
Arg 5 is <-dest:dbfullsql=Data>
Arg 6 is <Source=.\mydestsource;Integrated>
Arg 7 is <Security=false;User>
Arg 8 is <ID=sa;Pwd=sapass!;Database=mydb; computername=10.10.10.10 username=administrator password=adminpass>

Using echoargs you can experiment until you get it right, for example:

PS> echoargs -verb:sync "-source:dbfullsql=Data Source=mysource;Integrated Security=false;User ID=sa;Pwd=sapass!;Database=mydb;"
Arg 0 is <-verb:sync>
Arg 1 is <-source:dbfullsql=Data Source=mysource;Integrated Security=false;User ID=sa;Pwd=sapass!;Database=mydb;>

It turns out I was trying too hard before to maintain the double quotes around the connection string. Apparently that isn't necessary because even cmd.exe will strip those out.

BTW, hats off to the PowerShell team. They were quite helpful in showing me the specific incantation of single & double quotes to get the desired result - if you needed to keep the internal double quotes in place. :-) They also realize this is an area of pain, but they are driven by the number of folks are affected by a particular issue. If this is an area of pain for you, then please vote up this PowerShell bug submission.

For more information on how PowerShell parses, check out my Effective PowerShell blog series - specifically item 10 - "Understanding PowerShell Parsing Modes"

UPDATE 4/4/2012: This situation gets much easier to handle in PowerShell V3. See this blog post for details.

Is there a "goto" statement in bash?

It indeed may be useful for some debug or demonstration needs.

I found that Bob Copeland solution http://bobcopeland.com/blog/2012/10/goto-in-bash/ elegant:

#!/bin/bash
# include this boilerplate
function jumpto
{
    label=$1
    cmd=$(sed -n "/$label:/{:a;n;p;ba};" $0 | grep -v ':$')
    eval "$cmd"
    exit
}

start=${1:-"start"}

jumpto $start

start:
# your script goes here...
x=100
jumpto foo

mid:
x=101
echo "This is not printed!"

foo:
x=${x:-10}
echo x is $x

results in:

$ ./test.sh
x is 100
$ ./test.sh foo
x is 10
$ ./test.sh mid
This is not printed!
x is 101

java.sql.SQLException: Missing IN or OUT parameter at index:: 1

In your INSERT statements:

INSERT INTO employee(hans,germany) values(?,?)

You've got your values where your field names belong. Change it to be:

INSERT INTO employee(emp_name,emp_address) values(?,?)

If you were to run that statement from a SQL prompt, it would look like this:

INSERT INTO employee(emp_name,emp_address) values('hans','germany');

Note that you'd need to put single quotes around the string/varchar values.

Additionally, you are also not adding any parameters to your prepared statement. That is what's actually causing the error you're seeing. Try this:

PreparedStatement ps = con.prepareStatement(inserting); 
ps.setString(1, "hans");
ps.setString(2, "germany");
ps.execute();

Also (according to Oracle), you can use "execute" for any SQL statement. Using "executeUpdate" would also be valid in this situation, which would return an integer to indicate the number of rows affected.

How do I automatically resize an image for a mobile site?

You can use the following css to resize the image for mobile view

object-fit: scale-down; max-width: 100%

Twitter bootstrap hide element on small devices

<div class="small hidden-xs">
    Some Content Here
</div>

This also works for elements not necessarily used in a grid /small column. When it is rendered on larger screens the font-size will be smaller than your default text font-size.

This answer satisfies the question in the OP title (which is how I found this Q/A).

Accessing a matrix element in the "Mat" object (not the CvMat object) in OpenCV C++

On the documentation:

http://docs.opencv.org/2.4/modules/core/doc/basic_structures.html#mat

It says:

(...) if you know the matrix element type, e.g. it is float, then you can use at<>() method

That is, you can use:

Mat M(100, 100, CV_64F);
cout << M.at<double>(0,0);

Maybe it is easier to use the Mat_ class. It is a template wrapper for Mat. Mat_ has the operator() overloaded in order to access the elements.

Can't get Gulp to run: cannot find module 'gulp-util'

In most of the cases, deleting all the node packages and then installing them again, solve the problem.

But In my case node_modules folder has not write permission.

How to show multiline text in a table cell

I added only <br> inside the <td> and it works good, break the line!

Turn off textarea resizing

this will do your job

  textarea{
        resize:none;
    }

enter image description here

Constants in Objective-C

I use a singleton class, so that I can mock the class and change the constants if necessary for testing. The constants class looks like this:

#import <Foundation/Foundation.h>

@interface iCode_Framework : NSObject

@property (readonly, nonatomic) unsigned int iBufCapacity;
@property (readonly, nonatomic) unsigned int iPort;
@property (readonly, nonatomic) NSString * urlStr;

@end

#import "iCode_Framework.h"

static iCode_Framework * instance;

@implementation iCode_Framework

@dynamic iBufCapacity;
@dynamic iPort;
@dynamic urlStr;

- (unsigned int)iBufCapacity
{
    return 1024u;
};

- (unsigned int)iPort
{
    return 1978u;
};

- (NSString *)urlStr
{
    return @"localhost";
};

+ (void)initialize
{
    if (!instance) {
        instance = [[super allocWithZone:NULL] init];
    }
}

+ (id)allocWithZone:(NSZone * const)notUsed
{
    return instance;
}

@end

And it is used like this (note the use of a shorthand for the constants c - it saves typing [[Constants alloc] init] every time):

#import "iCode_FrameworkTests.h"
#import "iCode_Framework.h"

static iCode_Framework * c; // Shorthand

@implementation iCode_FrameworkTests

+ (void)initialize
{
    c  = [[iCode_Framework alloc] init]; // Used like normal class; easy to mock!
}

- (void)testSingleton
{
    STAssertNotNil(c, nil);
    STAssertEqualObjects(c, [iCode_Framework alloc], nil);
    STAssertEquals(c.iBufCapacity, 1024u, nil);
}

@end

How to check if the key pressed was an arrow key in Java KeyListener?

public void keyPressed(KeyEvent e) {
    if (e.getKeyCode() == KeyEvent.VK_RIGHT ) {
            //Right arrow key code
    } else if (e.getKeyCode() == KeyEvent.VK_LEFT ) {
            //Left arrow key code
    } else if (e.getKeyCode() == KeyEvent.VK_UP ) {
            //Up arrow key code
    } else if (e.getKeyCode() == KeyEvent.VK_DOWN ) {
            //Down arrow key code
    }

    repaint();
}

The KeyEvent codes are all a part of the API: http://docs.oracle.com/javase/7/docs/api/java/awt/event/KeyEvent.html

How can I convert a .jar to an .exe?

If your program is "publicly available non-commercial in nature" and has "a publicly available Web site that meets the basic quality standards", then you can try and get a free license of Excelsior. If its not then it's expensive, but still a viable option.

Program: https://www.excelsiorjet.com

As a side note: Here's a study of all existing Jar to EXE programs, which is a bit depressing - https://www.excelsior-usa.com/articles/java-to-exe.html

How to Round to the nearest whole number in C#

You have the Math.Round function that does exactly what you want.

Math.Round(1.1) results with 1
Math.Round(1.8) will result with 2.... and so one.

react-router - pass props to handler component

React-router v4 alpha

now there is a new way, to do this, although very similar to the previous method.

import { Match, Link, Miss } from 'react-router';
import Homepage from './containers/Homepage';

const route = {
    exactly: true,
    pattern: '/',
    title: `${siteTitle} - homepage`,
    component: Homepage
  }

<Match { ...route } render={(props) => <route.component {...props} />} />

P.S. This works only in alpha version, and were removed after the v4 alpha release. In v4 latest, is once again , with the path and exact props.

react-lego an example app contains code that does exactly this in routes.js on its react-router-4 branch

Is an entity body allowed for an HTTP DELETE request?

It appears to me that RFC 2616 does not specify this.

From section 4.3:

The presence of a message-body in a request is signaled by the inclusion of a Content-Length or Transfer-Encoding header field in the request's message-headers. A message-body MUST NOT be included in a request if the specification of the request method (section 5.1.1) does not allow sending an entity-body in requests. A server SHOULD read and forward a message-body on any request; if the request method does not include defined semantics for an entity-body, then the message-body SHOULD be ignored when handling the request.

And section 9.7:

The DELETE method requests that the origin server delete the resource identified by the Request-URI. This method MAY be overridden by human intervention (or other means) on the origin server. The client cannot be guaranteed that the operation has been carried out, even if the status code returned from the origin server indicates that the action has been completed successfully. However, the server SHOULD NOT indicate success unless, at the time the response is given, it intends to delete the resource or move it to an inaccessible location.

A successful response SHOULD be 200 (OK) if the response includes an entity describing the status, 202 (Accepted) if the action has not yet been enacted, or 204 (No Content) if the action has been enacted but the response does not include an entity.

If the request passes through a cache and the Request-URI identifies one or more currently cached entities, those entries SHOULD be treated as stale. Responses to this method are not cacheable.c

So it's not explicitly allowed or disallowed, and there's a chance that a proxy along the way might remove the message body (although it SHOULD read and forward it).

Alternative to iFrames with HTML5

You can use object and embed, like so:

<object data="http://www.web-source.net" width="600" height="400">
    <embed src="http://www.web-source.net" width="600" height="400"> </embed>
    Error: Embedded data could not be displayed.
</object>

Which isn't new, but still works. I'm not sure if it has the same functionality though.

Python: Importing urllib.quote

This is how I handle this, without using exceptions.

import sys
if sys.version_info.major > 2:  # Python 3 or later
    from urllib.parse import quote
else:  # Python 2
    from urllib import quote

How to check in Javascript if one element is contained within another

I came across a wonderful piece of code to check whether or not an element is a child of another element. I have to use this because IE doesn't support the .contains element method. Hope this will help others as well.

Below is the function:

function isChildOf(childObject, containerObject) {
  var returnValue = false;
  var currentObject;

  if (typeof containerObject === 'string') {
    containerObject = document.getElementById(containerObject);
  }
  if (typeof childObject === 'string') {
    childObject = document.getElementById(childObject);
  }

  currentObject = childObject.parentNode;

  while (currentObject !== undefined) {
    if (currentObject === document.body) {
      break;
    }

    if (currentObject.id == containerObject.id) {
      returnValue = true;
      break;
    }

    // Move up the hierarchy
    currentObject = currentObject.parentNode;
  }

  return returnValue;
}

How do you discover model attributes in Rails?

There is a rails plugin called Annotate models, that will generate your model attributes on the top of your model files here is the link:

https://github.com/ctran/annotate_models

to keep the annotation in sync, you can write a task to re-generate annotate models after each deploy.

What is the use of adding a null key or value to a HashMap in Java?

Another example : I use it to group Data by date. But some data don't have date. I can group it with the header "NoDate"

Is there an easy way to attach source in Eclipse?

Another thought for making that easier when using an automated build:

When you create a jar of one of your projects, also create a source files jar:
project.jar
project-src.jar

Instead of going into the build path options dialog to add a source reference to each jar, try the following: add one source reference through the dialog. Edit your .classpath and using the first jar entry as a template, add the source jar files to each of your other jars.

This way you can use Eclipse's navigation aids to their fullest while still using something more standalone to build your projects.

Javascript Confirm popup Yes, No button instead of OK and Cancel

Unfortunately, there is no cross-browser support for opening a confirmation dialog that is not the default OK/Cancel pair. The solution you provided uses VBScript, which is only available in IE.

I would suggest using a Javascript library that can build a DOM-based dialog instead. Try Jquery UI: http://jqueryui.com/

Search File And Find Exact Match And Print Line?

The check has to be like this:

if num == line.split()[0]:

If file.txt has a layout like this:

1 foo
20 bar
30 20

We split up "1 foo" into ['1', 'foo'] and just use the first item, which is the number.

Convert a String of Hex into ASCII in Java

//%%%%%%%%%%%%%%%%%%%%%% HEX to ASCII %%%%%%%%%%%%%%%%%%%%%%
public String convertHexToString(String hex){

 String ascii="";
 String str;

 // Convert hex string to "even" length
 int rmd,length;
 length=hex.length();
 rmd =length % 2;
 if(rmd==1)
 hex = "0"+hex;

  // split into two characters
  for( int i=0; i<hex.length()-1; i+=2 ){

      //split the hex into pairs
      String pair = hex.substring(i, (i + 2));
      //convert hex to decimal
      int dec = Integer.parseInt(pair, 16);
      str=CheckCode(dec);
      ascii=ascii+" "+str;
  }
  return ascii;
}

public String CheckCode(int dec){
  String str;

          //convert the decimal to character
        str = Character.toString((char) dec);

      if(dec<32 || dec>126 && dec<161)
             str="n/a";  
  return str;
}

A Space between Inline-Block List Items

Even if its not inline-block based, this solution might worth consideration (allows nearly same formatting control from upper levels).

ul {
  display: table;
}
ul li {
  display: table-cell;
}

Cleanest way to build an SQL string in Java

I would have a look at Spring JDBC. I use it whenever I need to execute SQLs programatically. Example:

int countOfActorsNamedJoe
    = jdbcTemplate.queryForInt("select count(0) from t_actors where first_name = ?", new Object[]{"Joe"});

It's really great for any kind of sql execution, especially querying; it will help you map resultsets to objects, without adding the complexity of a complete ORM.

Pretty printing XML in Python

I had this problem and solved it like this:

def write_xml_file (self, file, xml_root_element, xml_declaration=False, pretty_print=False, encoding='unicode', indent='\t'):
    pretty_printed_xml = etree.tostring(xml_root_element, xml_declaration=xml_declaration, pretty_print=pretty_print, encoding=encoding)
    if pretty_print: pretty_printed_xml = pretty_printed_xml.replace('  ', indent)
    file.write(pretty_printed_xml)

In my code this method is called like this:

try:
    with open(file_path, 'w') as file:
        file.write('<?xml version="1.0" encoding="utf-8" ?>')

        # create some xml content using etree ...

        xml_parser = XMLParser()
        xml_parser.write_xml_file(file, xml_root, xml_declaration=False, pretty_print=True, encoding='unicode', indent='\t')

except IOError:
    print("Error while writing in log file!")

This works only because etree by default uses two spaces to indent, which I don't find very much emphasizing the indentation and therefore not pretty. I couldn't ind any setting for etree or parameter for any function to change the standard etree indent. I like how easy it is to use etree, but this was really annoying me.

Zooming MKMapView to fit annotation pins?

I use this this code and works fine for me:

-(void)zoomToFitMapAnnotations:(MKMapView*)aMapView
{
    if([aMapView.annotations count] == 0)
        return;

    CLLocationCoordinate2D topLeftCoord;
    topLeftCoord.latitude = -90;
    topLeftCoord.longitude = 180;

    CLLocationCoordinate2D bottomRightCoord;
    bottomRightCoord.latitude = 90;
    bottomRightCoord.longitude = -180;

    for(MapViewAnnotation *annotation in mapView.annotations)
    {
        topLeftCoord.longitude = fmin(topLeftCoord.longitude, annotation.coordinate.longitude);
        topLeftCoord.latitude = fmax(topLeftCoord.latitude, annotation.coordinate.latitude);

        bottomRightCoord.longitude = fmax(bottomRightCoord.longitude, annotation.coordinate.longitude);
        bottomRightCoord.latitude = fmin(bottomRightCoord.latitude, annotation.coordinate.latitude);
    }

    MKCoordinateRegion region;
    region.center.latitude = topLeftCoord.latitude - (topLeftCoord.latitude - bottomRightCoord.latitude) * 0.5;
    region.center.longitude = topLeftCoord.longitude + (bottomRightCoord.longitude - topLeftCoord.longitude) * 0.5;
    region.span.latitudeDelta = fabs(topLeftCoord.latitude - bottomRightCoord.latitude) * 1.1; // Add a little extra space on the sides
    region.span.longitudeDelta = fabs(bottomRightCoord.longitude - topLeftCoord.longitude) * 1.1; // Add a little extra space on the sides

    region = [aMapView regionThatFits:region];
    [mapView setRegion:region animated:YES];
}

Pandas - 'Series' object has no attribute 'colNames' when using apply()

When you use df.apply(), each row of your DataFrame will be passed to your lambda function as a pandas Series. The frame's columns will then be the index of the series and you can access values using series[label].

So this should work:

df['D'] = (df.apply(lambda x: myfunc(x[colNames[0]], x[colNames[1]]), axis=1)) 

How to get the correct range to set the value to a cell?

Use setValue method of Range class to set the value of particular cell.

function storeValue() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  // ss is now the spreadsheet the script is associated with
  var sheet = ss.getSheets()[0]; // sheets are counted starting from 0
  // sheet is the first worksheet in the spreadsheet
  var cell = sheet.getRange("B2"); 
  cell.setValue(100);
}

You can also select a cell using row and column numbers.

var cell = sheet.getRange(2, 3); // here cell is C2

It's also possible to set value of multiple cells at once.

var values = [
  ["2.000", "1,000,000", "$2.99"]
];

var range = sheet.getRange("B2:D2");
range.setValues(values);

Set a cookie to HttpOnly via Javascript

An HttpOnly cookie means that it's not available to scripting languages like JavaScript. So in JavaScript, there's absolutely no API available to get/set the HttpOnly attribute of the cookie, as that would otherwise defeat the meaning of HttpOnly.

Just set it as such on the server side using whatever server side language the server side is using. If JavaScript is absolutely necessary for this, you could consider to just let it send some (ajax) request with e.g. some specific request parameter which triggers the server side language to create an HttpOnly cookie. But, that would still make it easy for hackers to change the HttpOnly by just XSS and still have access to the cookie via JS and thus make the HttpOnly on your cookie completely useless.

WAMP server, localhost is not working

If you have skype installed, close it completely.

If you have sql server installed, go to:

Control panel -> Administrative Tools -> Services

And stop SQL Server Reporting Services

Port 80 must be free now. Click on Wamp icon -> Restart All Services

git status (nothing to commit, working directory clean), however with changes commited

Your local branch doensn't know about the remote branch. If you don't tell git that your local branch (master) is supposed to compare itself to the remote counterpart (origin/master in this case); then git status won't tell you the difference between your branch and the remote one. So you should use:

git branch --set-upstream-to origin/master

or with the short option:

git branch -u origin/master

This options --set-upstream-to (or -u in short) was introduced in git 1.8.0.

Once you have set this option; git status will show you something like:

# Your branch is ahead of 'origin/master' by 1 commit.

Exception : mockito wanted but not invoked, Actually there were zero interactions with this mock

You need to inject mock inside the class you're testing. At the moment you're interacting with the real object, not with the mock one. You can fix the code in a following way:

void testAbc(){
     myClass.myObj = myInteface;
     myClass.abc();
     verify(myInterface).myMethodToBeVerified(new String("a"), new String("b"));
}

although it would be a wiser choice to extract all initialization code into @Before

@Before
void setUp(){
     myClass = new myClass();
     myClass.myObj = myInteface;
}

@Test
void testAbc(){
     myClass.abc();
     verify(myInterface).myMethodToBeVerified(new String("a"), new String("b"));
}

jQuery DatePicker with today as maxDate

For those who dont want to use datepicker method

var alldatepicker=  $("[class$=hasDatepicker]");

alldatepicker.each(function(){

var value=$(this).val();

var today = new Date();

var dd = today.getDate();

var mm = today.getMonth()+1; //January is 0!

var yyyy = today.getFullYear();

if(dd<10) {

    dd='0'+dd

} 
if(mm<10) {

    mm='0'+mm

} 
today = mm+'/'+dd+'/'+yyyy;
if(value!=''){
if(value>today){
alert("Date cannot be greater than current date");
}
}
}); 

Sending emails through SMTP with PHPMailer

Yes, you need OpenSSL to work correctly. My backup testing site worked, my live server didn't. Difference? Live server didn't have OpenSSL within PHP configuration.

What is a reasonable length limit on person "Name" fields?

depending on who is going to be using your database, for example African names will do with varchar(20) for last name and first name separated. however it is different from nation to nation but for the sake saving your database resources and memory, separate last name and first name fields and use varchar(30) think that will work.

Java 8 optional: ifPresent return object orElseThrow exception

Use the map-function instead. It transforms the value inside the optional.

Like this:

private String getStringIfObjectIsPresent(Optional<Object> object) {
    return object.map(() -> {
        String result = "result";
        //some logic with result and return it
        return result;
    }).orElseThrow(MyCustomException::new);
}

How to change the date format from MM/DD/YYYY to YYYY-MM-DD in PL/SQL?

According to the comments, the data-type in the datatable is DATE. So you should simply use: "select date_column from table;"

Now if you execute the select you will get back a date data-type, which should be what you need for the .xsd.

Culture-dependent formating of the date should be done in the GUI (most languages have convenient ways to do so), not in the select-statement.

Alter column, add default constraint

I confirm like the comment from JohnH, never use column types in the your object names! It's confusing. And use brackets if possible.

Try this:

ALTER TABLE [TableName]
ADD  DEFAULT (getutcdate()) FOR [Date]; 

How to properly exit a C# application?

In this case, the most proper way to exit the application in to override onExit() method in App.xaml.cs:

protected override void OnExit(ExitEventArgs e) {
    base.OnExit(e); 
}

Returning a file to View/Download in ASP.NET MVC

Action method needs to return FileResult with either a stream, byte[], or virtual path of the file. You will also need to know the content-type of the file being downloaded. Here is a sample (quick/dirty) utility method. Sample video link How to download files using asp.net core

[Route("api/[controller]")]
public class DownloadController : Controller
{
    [HttpGet]
    public async Task<IActionResult> Download()
    {
        var path = @"C:\Vetrivel\winforms.png";
        var memory = new MemoryStream();
        using (var stream = new FileStream(path, FileMode.Open))
        {
            await stream.CopyToAsync(memory);
        }
        memory.Position = 0;
        var ext = Path.GetExtension(path).ToLowerInvariant();
        return File(memory, GetMimeTypes()[ext], Path.GetFileName(path));
    }

    private Dictionary<string, string> GetMimeTypes()
    {
        return new Dictionary<string, string>
        {
            {".txt", "text/plain"},
            {".pdf", "application/pdf"},
            {".doc", "application/vnd.ms-word"},
            {".docx", "application/vnd.ms-word"},
            {".png", "image/png"},
            {".jpg", "image/jpeg"},
            ...
        };
    }
}

SSRS Query execution failed for dataset

I was also facing the same issue - I checked below things to fix this issue,

  • If you have recently changed pointing database-name in data-source
    then first check that all the store procedures for that report exist on changed database.

  • If there are multiple sub reports on main report then make sure each report individually running perfectly.

  • Also check security panel - user must have access to the databases/ tables/views/functions for that report.

Sometimes, we also need to check dataset1 - store procedure. As if you are trying to show the report with user1 and if this user doesn't have the access(rights) of provided (dataset1 database) database then it will throw the same error as above so must check the user have access of dbreader in SQL Server.

Also, if that store procedure contains some other database (Database2) like

Select * from XYZ inner join Database2..Table1 on ... where...

Then user must have the access of this database too.

Note: you can check log files on this path for more details,

C:\Program Files\Microsoft SQL Server\MSRS11.SQLEXPRESS\Reporting Services

Cannot install Aptana Studio 3.6 on Windows

Install NODE.JS on windows before installing aptana

Try the following link http://blueashes.com/2011/web-development/install-nodejs-on-windows/

Spring + Web MVC: dispatcher-servlet.xml vs. applicationContext.xml (plus shared security)

<mvc:annotation-driven />
<mvc:default-servlet-handler />
<mvc:resources mapping="/resources/**" location="/resources/" />

<context:component-scan base-package="com.tridenthyundai.ains" />

<bean id="multipartResolver"
    class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />

<bean id="messageSource" 
    class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
    <property name="basename" value="/WEB-INF/messages" />
</bean>

<bean id="viewResolver"
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">

    <property name="prefix">
        <value>/WEB-INF/pages/</value>
    </property>
    <property name="suffix">
        <value>.jsp</value>
    </property>
</bean>

Why is my Button text forced to ALL CAPS on Lollipop?

By default, Button in android provides all caps keyword. If you want button text to be in lower case or mixed case you can disable textAllCaps flag using android:textAllCaps="false"

Ansible - Use default if a variable is not defined

If anybody is looking for an option which handles nested variables, there are several such options in this github issue.

In short, you need to use "default" filter for every level of nested vars. For a variable "a.nested.var" it would look like:

- hosts: 'localhost'
  tasks:
    - debug:
        msg: "{{ ((a | default({})).nested | default({}) ).var | default('bar') }}"

or you could set default values of empty dicts for each level of vars, maybe using "combine" filter. Or use "json_query" filter. But the option I chose seems simpler to me if you have only one level of nesting.

history.replaceState() example?

Indeed this is a bug, although intentional for 2 years now. The problem lies with some unclear specs and the complexity when document.title and back/forward are involved.

See bug reference on Webkit and Mozilla. Also Opera on the introduction of History API said it wasn't using the title parameter and probably still doesn't.

Currently the 2nd argument of pushState and replaceState — the title of the history entry — isn't used in Opera's implementation, but may be one day.

Potential solution

The only way I see is to alter the title element and use pushState instead:

document.getElementsByTagName('title')[0].innerHTML = 'bar';
window.history.pushState( {} , 'bar', '/bar' );

How do I add target="_blank" to a link within a specified div?

Bear in mind that doing this is considered bad practice in general by web developers and usability experts. Jakob Nielson has this to say about removing control of the users browsing experience:

Avoid spawning multiple browser windows if at all possible — taking the "Back" button away from users can make their experience so painful that it usually far outweighs whatever benefit you're trying to provide. One common theory in favor of spawning the second window is that it keeps users from leaving your site, but ironically it may have just the opposite effect by preventing them from returning when they want to.

I believe this is the rationale for the target attribute being removed by the W3C from the XHTML 1.1 spec.

If you're dead set on taking this approach, Pim Jager's solution is good.

A nicer, more user friendly idea, would be to append a graphic to all of your external links, indicating to the user that following the link will take them externally.

You could do this with jquery:

$('a[href^="http://"]').each(function() {
    $('<img width="10px" height="10px" src="/images/skin/external.png" alt="External Link" />').appendTo(this)

});

Socket send and receive byte array

Try this, it's working for me.

Sender:

byte[] message = ...
Socket socket = ...
DataOutputStream dOut = new DataOutputStream(socket.getOutputStream());

dOut.writeInt(message.length); // write length of the message
dOut.write(message);           // write the message


Receiver:

Socket socket = ...
DataInputStream dIn = new DataInputStream(socket.getInputStream());

int length = dIn.readInt();                    // read length of incoming message
if(length>0) {
    byte[] message = new byte[length];
    dIn.readFully(message, 0, message.length); // read the message
}

how to get selected row value in the KendoUI

One way is to use the Grid's select() and dataItem() methods.

In single selection case, select() will return a single row which can be passed to dataItem()

var entityGrid = $("#EntitesGrid").data("kendoGrid");
var selectedItem = entityGrid.dataItem(entityGrid.select());
// selectedItem has EntityVersionId and the rest of your model

For multiple row selection select() will return an array of rows. You can then iterate through the array and the individual rows can be passed into the grid's dataItem().

var entityGrid = $("#EntitesGrid").data("kendoGrid");
var rows = entityGrid.select();
rows.each(function(index, row) {
  var selectedItem = entityGrid.dataItem(row);
  // selectedItem has EntityVersionId and the rest of your model
});

Auto height div with overflow and scroll when needed

You can do this just with flexboxes and overflow property.

Even if parent height is computed too.

Please see this answer or JSFiddle for details.

Rename a table in MySQL

ALTER TABLE `group` RENAME `member`

group is keyword so you must have to enclose into group

MySQL said: Documentation #1045 - Access denied for user 'root'@'localhost' (using password: NO)

Step one: Go to... C:\xampp\phpMyAdmin

Step Two: Open the config.inc.php file

Step Three: Locate the following information and change the password.

/* Authentication type and info */
$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = 'ENTER_YOUR_USER_NAME_HERE';
$cfg['Servers'][$i]['password'] = 'ENTER_YOUR_PASS_HERE';
$cfg['Servers'][$i]['extension'] = 'mysqli';
$cfg['Servers'][$i]['AllowNoPassword'] = true;
$cfg['Lang'] = '';

Searching word in vim?

For basic searching:

  • /pattern - search forward for pattern
  • ?pattern - search backward
  • n - repeat forward search
  • N - repeat backward

Some variables you might want to set:

  • :set ignorecase - case insensitive
  • :set smartcase - use case if any caps used
  • :set incsearch - show match as search

Can CSS force a line break after each word in an element?

I faced the same problem, and none of the options here helped me. Some mail services do not support specified styles. Here is my version, which solved the problem and works everywhere I checked:

<table>
    <tr>
        <td width="1">Gargantuan Word</td>
    </tr>
</table>

OR using CSS:

<table>
    <tr>
        <td style="width:1px">Gargantuan Word</td>
    </tr>
</table>

Permission denied (publickey). fatal: The remote end hung up unexpectedly while pushing back to git repository

Googled "Permission denied (publickey). fatal: The remote end hung up unexpectedly", first result an exact SO dupe:

GitHub: Permission denied (publickey). fatal: The remote end hung up unexpectedly which links here in the accepted answer (from the original poster, no less): http://help.github.com/linux-set-up-git/

how to execute php code within javascript

You could use http://phpjs.org/ http://locutus.io/php/ it ports a bunch of PHP functionality to javascript, but if it's just echos, and the script is in a php file, you could do something like this:

alert("<?php echo "asdasda";?>");

don't worry about the shifty-looking use of double-quotes, PHP will render that before the browser sees it.

as for using ajax, the easiest way is to use a library, like jQuery. With that you can do:

$.ajax({
  url: 'test.php',
  success: function(data) {
    $('.result').html(data);
  }
});

and test.php would be:

<?php 
  echo 'asdasda';
?>

it would write the contents of test.php to whatever element has the result class.

spark submit add multiple jars in classpath

In Spark 2.3 you need to just set the --jars option. The file path should be prepended with the scheme though ie file:///<absolute path to the jars> Eg : file:////home/hadoop/spark/externaljsrs/* or file:////home/hadoop/spark/externaljars/abc.jar,file:////home/hadoop/spark/externaljars/def.jar

How to read a file in reverse order?

How about something like this:

import os


def readlines_reverse(filename):
    with open(filename) as qfile:
        qfile.seek(0, os.SEEK_END)
        position = qfile.tell()
        line = ''
        while position >= 0:
            qfile.seek(position)
            next_char = qfile.read(1)
            if next_char == "\n":
                yield line[::-1]
                line = ''
            else:
                line += next_char
            position -= 1
        yield line[::-1]


if __name__ == '__main__':
    for qline in readlines_reverse(raw_input()):
        print qline

Since the file is read character by character in reverse order, it will work even on very large files, as long as individual lines fit into memory.

Elegant way to check for missing packages and install them?

You can simply use the setdiff function to get the packages that aren't installed and then install them. In the sample below, we check if the ggplot2 and Rcpp packages are installed before installing them.

unavailable <- setdiff(c("ggplot2", "Rcpp"), rownames(installed.packages()))
install.packages(unavailable)

In one line, the above can be written as:

install.packages(setdiff(c("ggplot2", "Rcpp"), rownames(installed.packages())))

Parse rfc3339 date strings in Python?

This has already been answered here: How do I translate a ISO 8601 datetime string into a Python datetime object?

d = datetime.datetime.strptime( "2012-10-09T19:00:55Z", "%Y-%m-%dT%H:%M:%SZ" )
d.weekday()

Javascript: Unicode string to hex

how do you get "\u6f22\u5b57" from ?? in JavaScript?

These are JavaScript Unicode escape sequences e.g. \u12AB. To convert them, you could iterate over every code unit in the string, call .toString(16) on it, and go from there.

However, it is more efficient to also use hexadecimal escape sequences e.g. \xAA in the output wherever possible.

Also note that ASCII symbols such as A, b, and - probably don’t need to be escaped.

I’ve written a small JavaScript library that does all this for you, called jsesc. It has lots of options to control the output.

Here’s an online demo of the tool in action: http://mothereff.in/js-escapes#1%E6%BC%A2%E5%AD%97


Your question was tagged as utf-8. Reading the rest of your question, UTF-8 encoding/decoding didn’t seem to be what you wanted here, but in case you ever need it: use utf8.js (online demo).

ActiveRecord OR query

With rails + arel, a more clear way:

# Table name: messages
#
# sender_id:    integer
# recipient_id: integer
# content:      text

class Message < ActiveRecord::Base
  scope :by_participant, ->(user_id) do
    left  = arel_table[:sender_id].eq(user_id)
    right = arel_table[:recipient_id].eq(user_id)

    where(Arel::Nodes::Or.new(left, right))
  end
end

Produces:

$ Message.by_participant(User.first.id).to_sql 
=> SELECT `messages`.* 
     FROM `messages` 
    WHERE `messages`.`sender_id` = 1 
       OR `messages`.`recipient_id` = 1

Android Facebook 4.0 SDK How to get Email, Date of Birth and gender of User

After Login

private void getFbInfo() {
    GraphRequest request = GraphRequest.newMeRequest(
            AccessToken.getCurrentAccessToken(),
            new GraphRequest.GraphJSONObjectCallback() {
                @Override
                public void onCompleted(
                        JSONObject object,
                        GraphResponse response) {
                    try {
                        Log.d(LOG_TAG, "fb json object: " + object);
                        Log.d(LOG_TAG, "fb graph response: " + response);

                        String id = object.getString("id");
                        String first_name = object.getString("first_name");
                        String last_name = object.getString("last_name");
                        String gender = object.getString("gender");
                        String birthday = object.getString("birthday");
                        String image_url = "http://graph.facebook.com/" + id + "/picture?type=large";

                        String email;
                        if (object.has("email")) {
                            email = object.getString("email");
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
    Bundle parameters = new Bundle();
    parameters.putString("fields", "id,first_name,last_name,email,gender,birthday"); // id,first_name,last_name,email,gender,birthday,cover,picture.type(large)
    request.setParameters(parameters);
    request.executeAsync();
}

Array as session variable

Yes, PHP supports arrays as session variables. See this page for an example.

As for your second question: once you set the session variable, it will remain the same until you either change it or unset it. So if the 3rd page doesn't change the session variable, it will stay the same until the 2nd page changes it again.

How to clear mysql screen console in windows?

I had the same issue, and CTRL+L worked for me on Windows 10.

How to convert any date format to yyyy-MM-dd

if (DateTime.TryParse(datetoparser, out dateValue))
{
   string formatedDate = dateValue.ToString("yyyy-MM-dd");
}

Android Location Providers - GPS or Network Provider?

There are 3 location providers in Android.

They are:

gps –> (GPS, AGPS): Name of the GPS location provider. This provider determines location using satellites. Depending on conditions, this provider may take a while to return a location fix. Requires the permission android.permission.ACCESS_FINE_LOCATION.

network –> (AGPS, CellID, WiFi MACID): Name of the network location provider. This provider determines location based on availability of cell tower and WiFi access points. Results are retrieved by means of a network lookup. Requires either of the permissions android.permission.ACCESS_COARSE_LOCATION or android.permission.ACCESS_FINE_LOCATION.

passive –> (CellID, WiFi MACID): A special location provider for receiving locations without actually initiating a location fix. This provider can be used to passively receive location updates when other applications or services request them without actually requesting the locations yourself. This provider will return locations generated by other providers. Requires the permission android.permission.ACCESS_FINE_LOCATION, although if the GPS is not enabled this provider might only return coarse fixes. This is what Android calls these location providers, however, the underlying technologies to make this stuff work is mapped to the specific set of hardware and telco provided capabilities (network service).

The best way is to use the “network” or “passive” provider first, and then fallback on “gps”, and depending on the task, switch between providers. This covers all cases, and provides a lowest common denominator service (in the worst case) and great service (in the best case).

enter image description here

Article Reference : Android Location Providers - gps, network, passive By Nazmul Idris

Code Reference : https://stackoverflow.com/a/3145655/28557

-----------------------Update-----------------------

Now Android have Fused location provider

The Fused Location Provider intelligently manages the underlying location technology and gives you the best location according to your needs. It simplifies ways for apps to get the user’s current location with improved accuracy and lower power usage

Fused location provider provide three ways to fetch location

  1. Last Location: Use when you want to know current location once.
  2. Request Location using Listener: Use when application is on screen / frontend and require continues location.
  3. Request Location using Pending Intent: Use when application in background and require continues location.

References :

Official site : http://developer.android.com/google/play-services/location.html

Fused location provider example: GIT : https://github.com/kpbird/fused-location-provider-example

http://blog.lemberg.co.uk/fused-location-provider

--------------------------------------------------------

How can I increase a scrollbar's width using CSS?

My experience with trying to use CSS to modify the scroll bars is don't. Only IE will let you do this.

List<object>.RemoveAll - How to create an appropriate Predicate

A predicate in T is a delegate that takes in a T and returns a bool. List<T>.RemoveAll will remove all elements in a list where calling the predicate returns true. The easiest way to supply a simple predicate is usually a lambda expression, but you can also use anonymous methods or actual methods.

{
    List<Vehicle> vehicles;
    // Using a lambda
    vehicles.RemoveAll(vehicle => vehicle.EnquiryID == 123);
    // Using an equivalent anonymous method
    vehicles.RemoveAll(delegate(Vehicle vehicle)
    {
        return vehicle.EnquiryID == 123;
    });
    // Using an equivalent actual method
    vehicles.RemoveAll(VehiclePredicate);
}

private static bool VehiclePredicate(Vehicle vehicle)
{
    return vehicle.EnquiryID == 123;
}

How to switch to other branch in Source Tree to commit the code?

Hi I'm also relatively new but I can give you basic help.

  1. To switch to another branch use "Checkout". Just click on your branch and then on the button "checkout" at the top.

UPDATE 12.01.2016:

The bold line is the current branch.

You can also just double click a branch to use checkout.


  1. Your first answer I think depends on the repository you use (like github or bitbucket). Maybe the "Show hosted repository"-Button can help you (Left panel, bottom, right button = database with cog)

And here some helpful links:

Easy Git Guide

Git-flow - Git branching model

Tips on branching with sourcetree

Load and execute external js file in node.js with access to local variables?

Expanding on @Shripad's and @Ivan's answer, I would recommend that you use Node.js's standard module.export functionality.

In your file for constants (e.g. constants.js), you'd write constants like this:

const CONST1 = 1;
module.exports.CONST1 = CONST1;

const CONST2 = 2;
module.exports.CONST2 = CONST2;

Then in the file in which you want to use those constants, write the following code:

const {CONST1 , CONST2} = require('./constants.js');

If you've never seen the const { ... } syntax before: that's destructuring assignment.

Switch case on type c#

The following code works more or less as one would expect a type-switch that only looks at the actual type (e.g. what is returned by GetType()).

public static void TestTypeSwitch()
{
    var ts = new TypeSwitch()
        .Case((int x) => Console.WriteLine("int"))
        .Case((bool x) => Console.WriteLine("bool"))
        .Case((string x) => Console.WriteLine("string"));

    ts.Switch(42);     
    ts.Switch(false);  
    ts.Switch("hello"); 
}

Here is the machinery required to make it work.

public class TypeSwitch
{
    Dictionary<Type, Action<object>> matches = new Dictionary<Type, Action<object>>();
    public TypeSwitch Case<T>(Action<T> action) { matches.Add(typeof(T), (x) => action((T)x)); return this; } 
    public void Switch(object x) { matches[x.GetType()](x); }
}

Change the maximum upload file size

Perhaps this should be a comment to @seanb123 and @Fredrick Gauss commenting on his comment, but for me in Drupal 8.1 with PHP 7 the file I needed to modify was located here:

/etc/php/7.0/apache2/php.ini

I modded probably four other php.ini files, including the one my system called the "Loaded Configuration File" (php -i | grep -i "loaded configuration file") and the one found on the info.php page but none of them helped. The key to discovering the correct path was found on a site from 2012. They said the path "/etc/php5/apache2/php.ini" was deprecated even BACK THEN but it gave me a clue where to find it. For PHP7 it's a little different than in PHP5 but the concept is the same.

Maybe this will help some otherwise helpless schmuck like myself.

That being said, the answer to the OP in my case would be that someone with admin privileges on the box would have to do it.

The site that helped me: http://www.evilbox.ro/linux/remove-ispconfig-maximum-upload-size-of-2m-for-wordpress/

This is also addressed here: Import file size limit in PHPMyAdmin

EDIT: the full text of my note to myself:

In order to change the max upload size, edit upload_max_filesize and [if needed?] post_max_size in /etc/php/7.0/apache2/php.ini (or in older versions: /etc/php5/apache2/php.ini )

/etc/init.d/apache2 restart

EDIT AGAIN: since you're importing big files you may need to change the timeout for processing them. In my case, the file named, "config.default.php" was found at /usr/share/phpmyadmin/libraries/config.default.php with the variable $cfg['ExecTimeLimit'] = 300; I changed mine to 900 for a huge import, for instance. Afterward you need to restart apache

SQL Server Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >=

Try this:

SELECT
    od.Sku,
    od.mf_item_number,
    od.Qty,
    od.Price,
    s.SupplierId,
    s.SupplierName,
    s.DropShipFees,
    si.Price as cost
FROM
    OrderDetails od
    INNER JOIN Supplier s on s.SupplierId = od.Mfr_ID
    INNER JOIN Group_Master gm on gm.Sku = od.Sku
    INNER JOIN Supplier_Item si on si.SKU = od.Sku and si.SupplierId = s.SupplierID
WHERE
    od.invoiceid = '339740'

This will return multiple rows that are identical except for the cost column. Look at the different cost values that are returned and figure out what is causing the different values. Then ask somebody which cost value they want, and add the criteria to the query that will select that cost.

How to use a parameter in ExecStart command line?

To attempt command line arguments directly is not possible.

One alternative might be environment variables (https://superuser.com/questions/728951/systemd-giving-my-service-multiple-arguments).

This is where I found the answer: http://www.freedesktop.org/software/systemd/man/systemctl.html

so sudo systemctl restart myprog -v -- systemctl will think you're trying to set one of its flags, not myprog's flag.

sudo systemctl restart myprog someotheroption -- systemctl will restart myprog and the someotheroption service, if it exists.

PowerShell says "execution of scripts is disabled on this system."

I found this line worked best for one of my Windows Server 2008 R2 servers. A couple of others had no issues without this line in my PowerShell scripts:

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Force -Scope Process

Using UPDATE in stored procedure with optional parameters

One Idea:

UPDATE tbl_ClientNotes
SET ordering=ISNULL(@ordering, ordering), 
    title=ISNULL(@title, title),  
    content=ISNULL(@content, content)
WHERE id=@id

How to increase font size in a plot in R?

Thus, to summarise the existing discussion, adding

cex.lab=1.5, cex.axis=1.5, cex.main=1.5, cex.sub=1.5

to your plot, where 1.5 could be 2, 3, etc. and a value of 1 is the default will increase the font size.

x <- rnorm(100)

cex doesn't change things

hist(x, xlim=range(x),
     xlab= "Variable Lable", ylab="density", main="Title of plot", prob=TRUE)

hist(x, xlim=range(x),
     xlab= "Variable Lable", ylab="density", main="Title of plot", prob=TRUE, 
     cex=1.5)

enter image description here

Add cex.lab=1.5, cex.axis=1.5, cex.main=1.5, cex.sub=1.5

hist(x, xlim=range(x),
     xlab= "Variable Lable", ylab="density", main="Title of plot", prob=TRUE, 
     cex.lab=1.5, cex.axis=1.5, cex.main=1.5, cex.sub=1.5)

enter image description here

How to set Java environment path in Ubuntu

Java is typically installed in /usr/java locate the version you have and then do the following:

Assuming you are using bash (if you are just starting off, i recommend bash over other shells) you can simply type in bash to start it.

Edit your ~/.bashrc file and add the paths as follows:

for eg. vi ~/.bashrc

insert following lines:

export JAVA_HOME=/usr/java/<your version of java>
export PATH=${PATH}:${JAVA_HOME}/bin

after you save the changes, exit and restart your bash or just type in bash to start a new shell

Type in export to ensure paths are right.

Type in java -version to ensure Java is accessible.

How to get all options in a drop-down list by Selenium WebDriver using C#?

To get all options in a drop-down list by Selenium WebDriver C#:

SelectElement TimeZoneSelect = new SelectElement(driver.FindElement(By.Name("time_zone")));
IList<IWebElement> ElementCount = TimeZoneSelect.Options;
int ItemSize = ElementCount.Count;

for (int i = 0; i < ItemSize; i++)
{
    String ItemValue = ElementCount.ElementAt(i).Text;
    Console.WriteLine(ItemValue);
}

Subdomain on different host

sub domain is part of the domain, it's like subletting a room of an apartment. A records has to be setup on the dns for the domain e.g

mydomain.com has IP 123.456.789.999 and hosted with Godaddy. Now to get the sub domain

anothersite.mydomain.com

of which the site is actually on another server then

login to Godaddy and add an A record dnsimple anothersite.mydomain.com and point the IP to the other server 98.22.11.11

And that's it.

Converting of Uri to String

String to Uri

Uri myUri = Uri.parse("https://www.google.com");

Uri to String

Uri uri;
String stringUri = uri.toString();

How to find a Java Memory Leak

You can find out by measuring memory usage size after calling garbage collector multiple times:

Runtime runtime = Runtime.getRuntime();

while(true) {
    ...
    if(System.currentTimeMillis() % 4000 == 0){
        System.gc();
        float usage = (float) (runtime.totalMemory() - runtime.freeMemory()) / 1024 / 1024;
        System.out.println("Used memory: " + usage + "Mb");
    }

}

If the output numbers were equal, there is no memory leak in your application, but if you saw difference between the numbers of memory usage (increasing numbers), there is memory leak in your project. For example:

Used memory: 14.603279Mb
Used memory: 14.737213Mb
Used memory: 14.772224Mb
Used memory: 14.802681Mb
Used memory: 14.840599Mb
Used memory: 14.900841Mb
Used memory: 14.942261Mb
Used memory: 14.976143Mb

Note that sometimes it takes some time to release memory by some actions like streams and sockets. You should not judge by first outputs, You should test it in a specific amount of time.

How to get progress from XMLHttpRequest

If you have access to your apache install and trust third-party code, you can use the apache upload progress module (if you use apache; there's also a nginx upload progress module).

Otherwise, you'd have to write a script that you can hit out of band to request the status of the file (checking the filesize of the tmp file for instance).

There's some work going on in firefox 3 I believe to add upload progress support to the browser, but that's not going to get into all the browsers and be widely adopted for a while (more's the pity).

How do I encode/decode HTML entities in Ruby?

<% str="<h1> Test </h1>" %>

result: &lt; h1 &gt; Test &lt; /h1 &gt;

<%= CGI.unescapeHTML(str).html_safe %>

Errors in SQL Server while importing CSV file despite varchar(MAX) being used for each column

Goto Advanced tab----> data type of column---> Here change data type from DT_STR to DT_TEXT and column width 255. Now you can check it will work perfectly.

Syntax for a single-line Bash infinite while loop

I like to use the semicolons only for the WHILE statement, and the && operator to make the loop do more than one thing...

So I always do it like this

while true ; do echo Launching Spaceship into orbit && sleep 5s && /usr/bin/launch-mechanism && echo Launching in T-5 && sleep 1s && echo T-4 && sleep 1s && echo T-3 && sleep 1s && echo T-2 && sleep 1s && echo T-1 && sleep 1s && echo liftoff ; done

C++ getters/setters coding style

Even though the name is immutable, you may still want to have the option of computing it rather than storing it in a field. (I realize this is unlikely for "name", but let's aim for the general case.) For that reason, even constant fields are best wrapped inside of getters:

class Foo {
    public:
        const std::string& getName() const {return name_;}
    private:
        const std::string& name_;
};

Note that if you were to change getName() to return a computed value, it couldn't return const ref. That's ok, because it won't require any changes to the callers (modulo recompilation.)

How to mount a host directory in a Docker container

Note that in Windows you'll have to provide the absolute path.

Below worked for me.

docker run -t -i -v D:/projects/:/home/chankeypathak/work -p 8888:8888 jupyter/tensorflow-notebook /bin/bash

GetFiles with multiple extensions

The following retrieves the jpg, tiff and bmp files and gives you an IEnumerable<FileInfo> over which you can iterate:

var files = dinfo.GetFiles("*.jpg")
    .Concat(dinfo.GetFiles("*.tiff"))
    .Concat(dinfo.GetFiles("*.bmp"));

If you really need an array, simply stick .ToArray() at the end of this.

Java Refuses to Start - Could not reserve enough space for object heap

You're using a 32-bit OS, so you're going to be seeing limits on the total size due to that. Other answers have covered this in more detail, so I'll avoid repeating their information.

A behaviour that I noticed with our servers recently is that specifying a maximum heap size with -Xmx while not specifying a minimum heap size with -Xms would lead to Java's server VM immediately attempting to allocate all of the memory needed for the maximum heap size. And sure, if the app gets up to that heap size, that's the amount of memory that you'll need. But the chances are, your apps will be starting out with comparitively small heaps and may require the larger heap at some later point. Additionally specifying the minimum heap size will let you start your app start with a smaller heap and gradually grow that heap.

All of this isn't going to help you increase your maximum heap size, but I figured it might help, so...

How do I revert to a previous package in Anaconda?

For the case that you wish to revert a recently installed package that made several changes to dependencies (such as tensorflow), you can "roll back" to an earlier installation state via the following method:

conda list --revisions
conda install --revision [revision number]

The first command shows previous installation revisions (with dependencies) and the second reverts to whichever revision number you specify.

Note that if you wish to (re)install a later revision, you may have to sequentially reinstall all intermediate versions. If you had been at revision 23, reinstalled revision 20 and wish to return, you may have to run each:

conda install --revision 21
conda install --revision 22
conda install --revision 23

How to change default Anaconda python environment

Load your "base" environment -- as OP's py34 -- when you load your terminal/shell.

If you use Bash, put the line:

conda activate py34

in your .bash_profile (or .bashrc):

$ echo 'conda activate py34' >> ~/.bash_profile

Every time you run a new terminal, conda environment py34 will be loaded.

Get properties of a class

Another solution, You can just iterate over the object keys like so, Note: you must use an instantiated object with existing properties:

printTypeNames<T>(obj: T) {
    const objectKeys = Object.keys(obj) as Array<keyof T>;
    for (let key of objectKeys)
    {
       console.log('key:' + key);
    }
}

How Can I Resolve:"can not open 'git-upload-pack' " error in eclipse?

This is a quite old post, but:

  • never oh never disable ssl verify as suggested in some answers

  • if you want to stick with https:

    1. retrieve add your git server certificate (using firefox for example)
    2. add it to your java keystore. See https://stackoverflow.com/a/27928213/5423781

Testing Spring's @RequestBody using Spring MockMVC

The issue is that you are serializing your bean with a custom Gson object while the application is attempting to deserialize your JSON with a Jackson ObjectMapper (within MappingJackson2HttpMessageConverter).

If you open up your server logs, you should see something like

Exception in thread "main" com.fasterxml.jackson.databind.exc.InvalidFormatException: Can not construct instance of java.util.Date from String value '2013-34-10-10:34:31': not a valid representation (error: Failed to parse Date value '2013-34-10-10:34:31': Can not parse date "2013-34-10-10:34:31": not compatible with any of standard forms ("yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", "EEE, dd MMM yyyy HH:mm:ss zzz", "yyyy-MM-dd"))
 at [Source: java.io.StringReader@baea1ed; line: 1, column: 20] (through reference chain: com.spring.Bean["publicationDate"])

among other stack traces.

One solution is to set your Gson date format to one of the above (in the stacktrace).

The alternative is to register your own MappingJackson2HttpMessageConverter by configuring your own ObjectMapper to have the same date format as your Gson.

For vs. while in C programming?

WHILE is more flexible. FOR is more concise in those instances in which it applies.

FOR is great for loops which have a counter of some kind, like

for (int n=0; n<max; ++n)

You can accomplish the same thing with a WHILE, of course, as others have pointed out, but now the initialization, test, and increment are broken across three lines. Possibly three widely-separated lines if the body of the loop is large. This makes it harder for the reader to see what you're doing. After all, while "++n" is a very common third piece of the FOR, it's certainly not the only possibility. I've written many loops where I write "n+=increment" or some more complex expression.

FOR can also work nicely with things other than a counter, of course. Like

for (int n=getFirstElementFromList(); listHasMoreElements(); n=getNextElementFromList())

Etc.

But FOR breaks down when the "next time through the loop" logic gets more complicated. Consider:

initializeList();
while (listHasMoreElements())
{
  n=getCurrentElement();
  int status=processElement(n);
  if (status>0)
  {
    skipElements(status);
    advanceElementPointer();
  }
  else
  {
    n=-status;
    findElement(n);
  }
}

That is, if the process of advancing may be different depending on conditions encountered while processing, a FOR statement is impractical. Yes, sometimes you could make it work with a complicated enough expressions, use of the ternary ?: operator, etc, but that usually makes the code less readable rather than more readable.

In practice, most of my loops are either stepping through an array or structure of some kind, in which case I use a FOR loop; or are reading a file or a result set from a database, in which case I use a WHILE loop ("while (!eof())" or something of that sort).

python: [Errno 10054] An existing connection was forcibly closed by the remote host

For me this problem arised while trying to connect to the SAP Hana database. When I got this error,

OperationalError: Lost connection to HANA server (ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None))

I tried to run the code for connection(mentioned below), which created that error, again and it worked.


    import pyhdb
    connection = pyhdb.connect(host="example.com",port=30015,user="user",password="secret")
    cursor = connection.cursor()
    cursor.execute("SELECT 'Hello Python World' FROM DUMMY")
    cursor.fetchone()
    connection.close()

It was because the server refused to connect. It might require you to wait for a while and try again. Try closing the Hana Studio by logging off and then logging in again. Keep running the code for a number of times.

Removing trailing newline character from fgets() input

 for(int i = 0; i < strlen(Name); i++ )
{
    if(Name[i] == '\n') Name[i] = '\0';
}

You should give it a try. This code basically loop through the string until it finds the '\n'. When it's found the '\n' will be replaced by the null character terminator '\0'

Note that you are comparing characters and not strings in this line, then there's no need to use strcmp():

if(Name[i] == '\n') Name[i] = '\0';

since you will be using single quotes and not double quotes. Here's a link about single vs double quotes if you want to know more

Looping Over Result Sets in MySQL

Use cursors.

A cursor can be thought of like a buffered reader, when reading through a document. If you think of each row as a line in a document, then you would read the next line, perform your operations, and then advance the cursor.