Programs & Examples On #Front controller

The Front Controller Pattern provides a centralized entry point for handling requests in web applications.

What's the difference between getRequestURI and getPathInfo methods in HttpServletRequest?

I will put a small comparison table here (just to have it somewhere):

Servlet is mapped as /test%3F/* and the application is deployed under /app.

http://30thh.loc:8480/app/test%3F/a%3F+b;jsessionid=S%3F+ID?p+1=c+d&p+2=e+f#a

Method              URL-Decoded Result           
----------------------------------------------------
getContextPath()        no      /app
getLocalAddr()                  127.0.0.1
getLocalName()                  30thh.loc
getLocalPort()                  8480
getMethod()                     GET
getPathInfo()           yes     /a?+b
getProtocol()                   HTTP/1.1
getQueryString()        no      p+1=c+d&p+2=e+f
getRequestedSessionId() no      S%3F+ID
getRequestURI()         no      /app/test%3F/a%3F+b;jsessionid=S+ID
getRequestURL()         no      http://30thh.loc:8480/app/test%3F/a%3F+b;jsessionid=S+ID
getScheme()                     http
getServerName()                 30thh.loc
getServerPort()                 8480
getServletPath()        yes     /test?
getParameterNames()     yes     [p 2, p 1]
getParameter("p 1")     yes     c d

In the example above the server is running on the localhost:8480 and the name 30thh.loc was put into OS hosts file.

Comments

  • "+" is handled as space only in the query string

  • Anchor "#a" is not transferred to the server. Only the browser can work with it.

  • If the url-pattern in the servlet mapping does not end with * (for example /test or *.jsp), getPathInfo() returns null.

If Spring MVC is used

  • Method getPathInfo() returns null.

  • Method getServletPath() returns the part between the context path and the session ID. In the example above the value would be /test?/a?+b

  • Be careful with URL encoded parts of @RequestMapping and @RequestParam in Spring. It is buggy (current version 3.2.4) and is usually not working as expected.

Posting JSON data via jQuery to ASP .NET MVC 4 controller action

//simple json object in asp.net mvc

var model = {"Id": "xx", "Name":"Ravi"};
$.ajax({    url: 'test/[ControllerName]',
                        type: "POST",
                        data: model,
                        success: function (res) {
                            if (res != null) {
                                alert("done.");
                            }
                        },
                        error: function (res) {

                        }
                    });


//model in c#
public class MyModel
{
 public string Id {get; set;}
 public string Name {get; set;}
}

//controller in asp.net mvc


public ActionResult test(MyModel model)
{
 //now data in your model 
}

Twitter bootstrap scrollable modal

In case of using .modal {overflow-y: auto;}, would create additional scroll bar on the right of the page, when body is already overflowed.

The work around for this is to remove overflow from the body tag temporarily and set modal overflow-y to auto.

Example:

$('.myModalSelector').on('show.bs.modal', function () {

        // Store initial body overflow value
        _initial_body_overflow = $('body').css('overflow');

        // Let modal be scrollable
        $(this).css('overflow-y', 'auto');
        $('body').css('overflow', 'hidden');


    }).on('hide.bs.modal', function () {

        // Reverse previous initialization
        $(this).css('overflow-y', 'hidden');
        $('body').css('overflow', _initial_body_overflow);
});

C# Timer or Thread.Sleep

class Program
{
    static void Main(string[] args)
    {
        Timer timer = new Timer(new TimerCallback(TimeCallBack),null,1000,50000);
        Console.Read();
        timer.Dispose();
    }

    public static void TimeCallBack(object o)
    {
      curMinute = DateTime.Now.Minute;
      if (lastMinute < curMinute) {
       // do your once-per-minute code here
       lastMinute = curMinute;
    }
}

The code could resemble something like the one above

Mosaic Grid gallery with dynamic sized images

I suggest Freewall. It is a cross-browser and responsive jQuery plugin to help you create many types of grid layouts: flexible layouts, images layouts, nested grid layouts, metro style layouts, pinterest like layouts ... with nice CSS3 animation effects and call back events. Freewall is all-in-one solution for creating dynamic grid layouts for desktop, mobile, and tablet.

Home page and document: also found here.

Nginx: stat() failed (13: permission denied)

I finally found my way through. In short, let's say your username is joe and you hold a website under your personal filesystem /home/joe/path/to/website.

You literally have to tell the system that nginx is your pal.
Place nginx in joe group :

sudo gpasswd -a nginx joe

After that if it still doesn't work, check right access of /home/joe directory. That's probably the reason why nginx can't reach the file because even if he is your friend now you have to open him the door to your house :

sudo chmod g+x /home/joe

That's it. That's literally all you have to do to give nginx access to your local files :)

I don't think there are security concerns with this method because nginx is the high authority and only an admin can change the group. nginx can now read what's in joe directories. It's only a security breach if the holder of the nginx account is different with the user you open directory access from, but in my case I'm the holder of both parties, that is in a local context.

Need to navigate to a folder in command prompt

To access another drive, type the drive's letter, followed by ":".

D:

Then enter:

cd d:\windows\movie

Eclipse - Unable to install breakpoint due to missing line number attributes

I had the same error message in Eclipse 3.4.1, SUN JVM1.6.0_07 connected to Tomcat 6.0 (running in debug-mode on a different machine, Sun JVM1.6.0_16, the debug connection did work correctly).

Window --> Preferences --> Java --> Compiler --> Classfile Generation: "add line number attributes to generated class file" was checked. I did a clean, recompile. I did uncheck it, recompile, check it, recompile. I made sure the project did use the global settings. Still the same message.

I switched to ant build, using

<javac srcdir="./src/java" destdir="./bin" debug="true">

Still, same message.

I didn't find out what caused this message and why it wouldn't go away. Though it seemed to have something to do with the running Tomcat debug session: when disconnected, recompiling solves the issue. But on connecting the debugger to Tomcat or on setting new breakpoints during a connected debug session, it appeared again.

However, it turned out the message was wrong: I was indeed able to debug and set breakpoints, both before and during debugging (javap -l did show line numbers, too). So just ignore it :)

Convert JS Object to form data

You can simply install qs:

npm i qs

Simply import:

import qs from 'qs'

Pass object to qs.stringify():

var item = {
   description: 'Some Item',
   price : '0.00',
   srate : '0.00',
   color : 'red',
   ...
   ...
}

qs.stringify(item)

Convert an array into an ArrayList

As an ArrayList that line would be

import java.util.ArrayList;
...
ArrayList<Card> hand = new ArrayList<Card>();

To use the ArrayList you have do

hand.get(i); //gets the element at position i 
hand.add(obj); //adds the obj to the end of the list
hand.remove(i); //removes the element at position i
hand.add(i, obj); //adds the obj at the specified index
hand.set(i, obj); //overwrites the object at i with the new obj

Also read this http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html

What is the best way to access redux store outside a react component?

You can use store object that is returned from createStore function (which should be already used in your code in app initialization). Than you can use this object to get current state with store.getState() method or store.subscribe(listener) to subscribe to store updates.

You can even save this object to window property to access it from any part of application if you really want it (window.store = store)

More info can be found in the Redux documentation .

Making a Windows shortcut start relative to where the folder is?

I like leoj3n's solution. It can also be used to set a relative "start in" directory, which is what I needed by using start's /D parameter. Without /c or /k in as an argument to cmd, the subsequent start command doesn't run. /c will close the shell immediately after running the command and /k will keep it open (even after the command is done). So if whatever you're running spits to standard out and you need to see it, use /k.

Unfortunately, according to the lnk file specification, the icon is not saved in the shortcut, but rather "encoded using environment variables, which makes it possible to find the icon across machines where the locations vary but are expressed using environment variables." So it's likely that if paths are changing and you're trying to take the icon from the executable you're pointing to, it won't transfer correctly.

How do I restore a dump file from mysqldump?

When we make a dump file with mysqldump, what it contains is a big SQL script for recreating the databse contents. So we restore it by using starting up MySQL’s command-line client:

mysql -uroot -p 

(where root is our admin user name for MySQL), and once connected to the database we need commands to create the database and read the file in to it:

create database new_db;
use new_db;
\. dumpfile.sql

Details will vary according to which options were used when creating the dump file.

How do I measure the execution time of JavaScript code with callbacks?

Surprised no one had mentioned yet the new built in libraries:

Available in Node >= 8.5, and should be in Modern Browers

https://developer.mozilla.org/en-US/docs/Web/API/Performance

https://nodejs.org/docs/latest-v8.x/api/perf_hooks.html#

Node 8.5 ~ 9.x (Firefox, Chrome)

_x000D_
_x000D_
// const { performance } = require('perf_hooks'); // enable for node
const delay = time => new Promise(res=>setTimeout(res,time))
async function doSomeLongRunningProcess(){
  await delay(1000);
}
performance.mark('A');
(async ()=>{
  await doSomeLongRunningProcess();
  performance.mark('B');
  performance.measure('A to B', 'A', 'B');
  const measure = performance.getEntriesByName('A to B')[0];
  // firefox appears to only show second precision.
  console.log(measure.duration);
  // apparently you should clean up...
  performance.clearMarks();
  performance.clearMeasures();         
  // Prints the number of milliseconds between Mark 'A' and Mark 'B'
})();
_x000D_
_x000D_
_x000D_

https://repl.it/@CodyGeisler/NodeJsPerformanceHooks

Node 12.x

https://nodejs.org/docs/latest-v12.x/api/perf_hooks.html

const { PerformanceObserver, performance } = require('perf_hooks');
const delay = time => new Promise(res => setTimeout(res, time))
async function doSomeLongRunningProcess() {
    await delay(1000);
}
const obs = new PerformanceObserver((items) => {
    console.log('PerformanceObserver A to B',items.getEntries()[0].duration);
      // apparently you should clean up...
      performance.clearMarks();
      // performance.clearMeasures(); // Not a function in Node.js 12
});
obs.observe({ entryTypes: ['measure'] });

performance.mark('A');

(async function main(){
    try{
        await performance.timerify(doSomeLongRunningProcess)();
        performance.mark('B');
        performance.measure('A to B', 'A', 'B');
    }catch(e){
        console.log('main() error',e);
    }
})();

Getting the current date in SQL Server?

As you are using SQL Server 2008, go with Martin's answer.

If you find yourself needing to do it in SQL Server 2005 where you don't have access to the Date column type, I'd use:

SELECT DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), 0)

SQLFiddle

What is a simple C or C++ TCP server and client example?

Although many year ago, clsocket seems a really nice small cross-platform (Windows, Linux, Mac OSX): https://github.com/DFHack/clsocket

[Vue warn]: Cannot find element

I get the same error. the solution is to put your script code before the end of body, not in the head section.

how do I loop through a line from a csv file in powershell

A slightly other way of iterating through each column of each line of a CSV-file would be

$path = "d:\scratch\export.csv"
$csv = Import-Csv -path $path

foreach($line in $csv)
{ 
    $properties = $line | Get-Member -MemberType Properties
    for($i=0; $i -lt $properties.Count;$i++)
    {
        $column = $properties[$i]
        $columnvalue = $line | Select -ExpandProperty $column.Name

        # doSomething $column.Name $columnvalue 
        # doSomething $i $columnvalue 
    }
} 

so you have the choice: you can use either $column.Name to get the name of the column, or $i to get the number of the column

How do I install a custom font on an HTML site

If you are using an external style sheet, the code could look something like this:

@font-face { font-family: Junebug; src: url('Junebug.ttf'); } 
.junebug { font-family: Junebug; font-size: 4.2em; }

And should be saved in a separate .css file (eg styles.css). If your .css file is in a location separate from the page code, the actual font file should have the same path as the .css file, NOT the .html or .php web page file. Then the web page needs something like:

<link rel="stylesheet" href="css/styles.css">

in the <head> section of your html page. In this example, the font file should be located in the css folder along with the stylesheet. After this, simply add the class="junebug" inside any tag in your html to use Junebug font in that element.

If you're putting the css in the actual web page, add the style tag in the head of the html like:

<style>
    @font-face { font-family: Junebug; src: url('Junebug.ttf'); } 
</style>

And the actual element style can either be included in the above <style> and called per element by class or id, or you can just declare the style inline with the element. By element I mean <div>, <p>, <h1> or any other element within the html that needs to use the Junebug font. With both of these options, the font file (Junebug.ttf) should be located in the same path as the html page. Of these two options, the best practice would look like:

<style>
    @font-face { font-family: Junebug; src: url('Junebug.ttf'); } 
    .junebug { font-family: Junebug; font-size: 4.2em; }
</style>

and

<h1 class="junebug">This is Junebug</h1>

And the least acceptable way would be:

<style>
    @font-face { font-family: Junebug; src: url('Junebug.ttf'); } 
</style>

and

<h1 style="font-family: Junebug;">This is Junebug</h1>

The reason it's not good to use inline styles is best practice dictates that styles should be kept all in one place so editing is practical. This is also the main reason that I recommend using the very first option of using external style sheets. I hope this helps.

Backporting Python 3 open(encoding="utf-8") to Python 2

If you are using six, you can try this, by which utilizing the latest Python 3 API and can run in both Python 2/3:

import six

if six.PY2:
    # FileNotFoundError is only available since Python 3.3
    FileNotFoundError = IOError
    from io import open

fname = 'index.rst'
try:
    with open(fname, "rt", encoding="utf-8") as f:
        pass
        # do_something_with_f ...
except FileNotFoundError:
    print('Oops.')

And, Python 2 support abandon is just deleting everything related to six.

Java 8 optional: ifPresent return object orElseThrow exception

Two options here:

Replace ifPresent with map and use Function instead of Consumer

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

Use isPresent:

private String getStringIfObjectIsPresent(Optional<Object> object) {
    if (object.isPresent()) {
        String result = "result";
        //some logic with result and return it
        return result;
    } else {
        throw new MyCustomException();
    }
}

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

find /abs/path/ -name '*.js'

Edit: As Brian points out, add -type f if you want only plain files, and not directories, links, etc.

VBA Convert String to Date

Try using Replace to see if it will work for you. The problem as I see it which has been mentioned a few times above is the CDate function is choking on the periods. You can use replace to change them to slashes. To answer your question about a Function in vba that can parse any date format, there is not any you have very limited options.

Dim current as Date, highest as Date, result() as Date 
For Each itemDate in DeliveryDateArray
    Dim tempDate As String
    itemDate = IIf(Trim(itemDate) = "", "0", itemDate) 'Added per OP's request.
    tempDate = Replace(itemDate, ".", "/")
    current = Format(CDate(tempDate),"dd/mm/yyyy")
    if current > highest then 
        highest = current 
    end if 
    ' some more operations an put dates into result array 
Next itemDate 
'After activating final sheet... 
Range("A1").Resize(UBound(result), 1).Value = Application.Transpose(result) 

Drawing a line/path on Google Maps

This worked for me. With the method mentioned here I was able to draw polylines on Google Maps V2. I drew a new line whenever the user location got changed, so the the polyline looks like the path followed by user on map.

Source code at. Github: prasang7/eTaxi-Meter

Please ignore other modules of this project related to distance calculation and User Interface if you are not interested in them.

Adding new column to existing DataFrame in Python pandas

I got the dreaded SettingWithCopyWarning, and it wasn't fixed by using the iloc syntax. My DataFrame was created by read_sql from an ODBC source. Using a suggestion by lowtech above, the following worked for me:

df.insert(len(df.columns), 'e', pd.Series(np.random.randn(sLength),  index=df.index))

This worked fine to insert the column at the end. I don't know if it is the most efficient, but I don't like warning messages. I think there is a better solution, but I can't find it, and I think it depends on some aspect of the index.
Note. That this only works once and will give an error message if trying to overwrite and existing column.
Note As above and from 0.16.0 assign is the best solution. See documentation http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.assign.html#pandas.DataFrame.assign Works well for data flow type where you don't overwrite your intermediate values.

set dropdown value by text using jquery

Here is an simple example:

$("#country_id").change(function(){
    if(this.value.toString() == ""){
        return;
    }
    alert("You just changed country to: " + $("#country_id option:selected").text() + " which carried the value for country_id as: " + this.value.toString());
});

How to choose the id generation strategy when using JPA and Hibernate

Basically, you have two major choices:

  • You can generate the identifier yourself, in which case you can use an assigned identifier.
  • You can use the @GeneratedValue annotation and Hibernate will assign the identifier for you.

For the generated identifiers you have two options:

  • UUID identifiers.
  • Numerical identifiers.

For numerical identifiers you have three options:

  • IDENTITY
  • SEQUENCE
  • TABLE

IDENTITY is only a good choice when you cannot use SEQUENCE (e.g. MySQL) because it disables JDBC batch updates.

SEQUENCE is the preferred option, especially when used with an identifier optimizer like pooled or pooled-lo.

TABLE is to be avoided since it uses a separate transaction to fetch the identifier and row-level locks which scales poorly.

How do I output coloured text to a Linux terminal?

You can use escape sequences, if your terminal supports it. For example:

echo \[\033[32m\]Hello, \[\033[36m\]colourful \[\033[33mworld!\033[0m\]

Getting an Embedded YouTube Video to Auto Play and Loop

All of the answers didn't work for me, I checked the playlist URL and seen that playlist parameter changed to list! So it should be:

&loop=1&list=PLvNxGp1V1dOwpDBl7L3AJIlkKYdNDKUEs

So here is the full code I use make a clean, looping, autoplay video:

<iframe width="100%" height="425" src="https://www.youtube.com/embed/MavEpJETfgI?autoplay=1&showinfo=0&loop=1&list=PLvNxGp1V1dOwpDBl7L3AJIlkKYdNDKUEs&rel=0" frameborder="0" allowfullscreen></iframe>

How to run JUnit tests with Gradle?

testCompile is deprecated. Gradle 7 compatible:

dependencies {
...
   testImplementation 'junit:junit:4.13'
}

and if you use the default folder structure (src/test/java/...) the test section is simply:

test {
    useJUnit()
}

Finally:

gradlew clean test

Alos see: https://docs.gradle.org/current/userguide/java_testing.html

How to declare global variables in Android?

Create this subclass

public class MyApp extends Application {
  String foo;
}

In the AndroidManifest.xml add android:name

Example

<application android:name=".MyApp" 
       android:icon="@drawable/icon" 
       android:label="@string/app_name">

How to remove and clear all localStorage data

It only worked for me in Firefox when accessing it from the window object.

Example...

window.onload = function()
{
 window.localStorage.clear();
}

PHP-FPM and Nginx: 502 Bad Gateway

Don't forget that php-fpm is a service. After installing it, make sure you start it:

# service php-fpm start
# chkconfig php-fpm on

cmake - find_library - custom library location

I've encountered a similar scenario. I solved it by adding in this following code just before find_library():

set(CMAKE_PREFIX_PATH /the/custom/path/to/your/lib/)

then it can find the library location.

jQuery - passing value from one input to another

Get input1 data to send them to input2 immediately

<div>
<label>Input1</label>
 <input type="text" id="input1" value="">
</div>

</br>
<label>Input2</label>
<input type="text" id="input2" value="">

<script type="text/javascript">
        $(document).ready(function () {
            $("#input1").keyup(function () {
                var value = $(this).val();
                $("#input2").val(value);
            });
        });
</script>

Run Command Prompt Commands

Tried @RameshVel solution but I could not pass arguments in my console application. If anyone experiences the same problem here is a solution:

using System.Diagnostics;

Process cmd = new Process();
cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.RedirectStandardInput = true;
cmd.StartInfo.RedirectStandardOutput = true;
cmd.StartInfo.CreateNoWindow = true;
cmd.StartInfo.UseShellExecute = false;
cmd.Start();

cmd.StandardInput.WriteLine("echo Oscar");
cmd.StandardInput.Flush();
cmd.StandardInput.Close();
cmd.WaitForExit();
Console.WriteLine(cmd.StandardOutput.ReadToEnd());

How to reset the state of a Redux store?

Combining the approaches of Dan, Ryan and Rob, to account for keeping the router state and initializing everything else in the state tree, I ended up with this:

const rootReducer = (state, action) => appReducer(action.type === LOGOUT ? {
    ...appReducer({}, {}),
    router: state && state.router || {}
  } : state, action);

How do I open a new window using jQuery?

Those are by no means the same. The first will simply send you to whatever URL you have assigned to window.location.href (in the same window you're currently in). The second makes a GET AJAX request.

Try this page: http://www.codebelt.com/jquery/open-new-browser-window-with-jquery-custom-size/

It gives a great example on how to open a new window*.

If you wish to use raw javascript then this is what you're looking for:

window.open(URL,name,specs,replace)

As seen in http://www.w3schools.com/jsref/met_win_open.asp

how to refresh Select2 dropdown menu after ajax loading different content?

Initialize again select2 by new id or class like below

when the page load

$(".mynames").select2();

call again when came by ajax after success ajax function

$(".names").select2();

set div height using jquery (stretch div height)

The correct way to do this is with good-old CSS:

#content{
    width:100%;
    position:absolute;
    top:35px;
    bottom:35px;
}

And the bonus is that you don't need to attach to the window.onresize event! Everything will adjust as the document reflows. All for the low-low price of four lines of CSS!

Class method decorator with self arguments?

A more concise example might be as follows:

#/usr/bin/env python3
from functools import wraps

def wrapper(method):
    @wraps(method)
    def _impl(self, *method_args, **method_kwargs):
        method_output = method(self, *method_args, **method_kwargs)
        return method_output + "!"
    return _impl

class Foo:
    @wrapper
    def bar(self, word):
        return word

f = Foo()
result = f.bar("kitty")
print(result)

Which will print:

kitty!

Elegant Python function to convert CamelCase to snake_case?

def convert(name):
    return reduce(
        lambda x, y: x + ('_' if y.isupper() else '') + y, 
        name
    ).lower()

And if we need to cover a case with already-un-cameled input:

def convert(name):
    return reduce(
        lambda x, y: x + ('_' if y.isupper() and not x.endswith('_') else '') + y, 
        name
    ).lower()

What is the reason and how to avoid the [FIN, ACK] , [RST] and [RST, ACK]

Here is a rough explanation of the concepts.

[ACK] is the acknowledgement that the previously sent data packet was received.

[FIN] is sent by a host when it wants to terminate the connection; the TCP protocol requires both endpoints to send the termination request (i.e. FIN).

So, suppose

  • host A sends a data packet to host B
  • and then host B wants to close the connection.
  • Host B (depending on timing) can respond with [FIN,ACK] indicating that it received the sent packet and wants to close the session.
  • Host A should then respond with a [FIN,ACK] indicating that it received the termination request (the ACK part) and that it too will close the connection (the FIN part).

However, if host A wants to close the session after sending the packet, it would only send a [FIN] packet (nothing to acknowledge) but host B would respond with [FIN,ACK] (acknowledges the request and responds with FIN).

Finally, some TCP stacks perform half-duplex termination, meaning that they can send [RST] instead of the usual [FIN,ACK]. This happens when the host actively closes the session without processing all the data that was sent to it. Linux is one operating system which does just this.

You can find a more detailed and comprehensive explanation here.

Single line if statement with 2 actions

userType = (user.Type == 0) ? "Admin" : (user.type == 1) ? "User" : "Admin";

should do the trick.

What is the difference between parseInt() and Number()?

If you are looking for performance then probably best results you'll get with bitwise right shift "10">>0. Also multiply ("10" * 1) or not not (~~"10"). All of them are much faster of Number and parseInt. They even have "feature" returning 0 for not number argument. Here are Performance tests.

plot legends without border and with white background

As documented in ?legend you do this like so:

plot(1:10,type = "n")
abline(v=seq(1,10,1), col='grey', lty='dotted')
legend(1, 5, "This legend text should not be disturbed by the dotted grey lines,\nbut the plotted dots should still be visible",box.lwd = 0,box.col = "white",bg = "white")
points(1:10,1:10)

enter image description here

Line breaks are achieved with the new line character \n. Making the points still visible is done simply by changing the order of plotting. Remember that plotting in R is like drawing on a piece of paper: each thing you plot will be placed on top of whatever's currently there.

Note that the legend text is cut off because I made the plot dimensions smaller (windows.options does not exist on all R platforms).

Transposing a 1D NumPy array

You can only transpose a 2D array. You can use numpy.matrix to create a 2D array. This is three years late, but I am just adding to the possible set of solutions:

import numpy as np
m = np.matrix([2, 3])
m.T

Shell script to copy files from one location to another location and rename add the current date to every file

path_src=./folder1
path_dst=./folder2
date=$(date +"%m%d%y")
for file_src in $path_src/*; do
  file_dst="$path_dst/$(basename $file_src | \
    sed "s/^\(.*\)\.\(.*\)/\1$date.\2/")"
  echo mv "$file_src" "$file_dst"
done

Setting up a websocket on Apache?

I struggled to understand the proxy settings for websockets for https therefore let me put clarity here what i realized.

First you need to enable proxy and proxy_wstunnel apache modules and the apache configuration file will look like this.

<IfModule mod_ssl.c>
    <VirtualHost _default_:443>
      ServerName www.example.com
        ServerAdmin webmaster@localhost
        DocumentRoot /var/www/your_project_public_folder

      SSLEngine on
      SSLCertificateFile    /etc/ssl/certs/path_to_your_ssl_certificate
      SSLCertificateKeyFile /etc/ssl/private/path_to_your_ssl_key

      <Directory /var/www/your_project_public_folder>
              Options Indexes FollowSymLinks
              AllowOverride All
              Require all granted
              php_flag display_errors On
      </Directory>
      ProxyRequests Off 
      ProxyPass /wss/  ws://example.com:port_no

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined
    </VirtualHost>
</IfModule>

in your frontend application use the url "wss://example.com/wss/" this is very important mostly if you are stuck with websockets you might be making mistake in the front end url. You probably putting url wrongly like below.

wss://example.com:8080/wss/ -> port no should not be mentioned
ws://example.com/wss/ -> url should start with wss only.
wss://example.com/wss -> url should end with / -> most important

also interesting part is the last /wss/ is same as proxypass value if you writing proxypass /ws/ then in the front end you should write /ws/ in the end of url.

Is there a TRY CATCH command in Bash

bash does not abort the running execution in case something detects an error state (unless you set the -e flag). Programming languages which offer try/catch do this in order to inhibit a "bailing out" because of this special situation (hence typically called "exception").

In the bash, instead, only the command in question will exit with an exit code greater than 0, indicating that error state. You can check for that of course, but since there is no automatic bailing out of anything, a try/catch does not make sense. It is just lacking that context.

You can, however, simulate a bailing out by using sub shells which can terminate at a point you decide:

(
  echo "Do one thing"
  echo "Do another thing"
  if some_condition
  then
    exit 3  # <-- this is our simulated bailing out
  fi
  echo "Do yet another thing"
  echo "And do a last thing"
)   # <-- here we arrive after the simulated bailing out, and $? will be 3 (exit code)
if [ $? = 3 ]
then
  echo "Bail out detected"
fi

Instead of that some_condition with an if you also can just try a command, and in case it fails (has an exit code greater than 0), bail out:

(
  echo "Do one thing"
  echo "Do another thing"
  some_command || exit 3
  echo "Do yet another thing"
  echo "And do a last thing"
)
...

Unfortunately, using this technique you are restricted to 255 different exit codes (1..255) and no decent exception objects can be used.

If you need more information to pass along with your simulated exception, you can use the stdout of the subshells, but that is a bit complicated and maybe another question ;-)

Using the above mentioned -e flag to the shell you can even strip that explicit exit statement:

(
  set -e
  echo "Do one thing"
  echo "Do another thing"
  some_command
  echo "Do yet another thing"
  echo "And do a last thing"
)
...

Efficient way to return a std::vector in c++

In C++11, this is the preferred way:

std::vector<X> f();

That is, return by value.

With C++11, std::vector has move-semantics, which means the local vector declared in your function will be moved on return and in some cases even the move can be elided by the compiler.

How to get info on sent PHP curl request

If you set CURLINFO_HEADER_OUT to true, outgoing headers are available in the array returned by curl_getinfo(), under request_header key:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://foo.com/bar");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "someusername:secretpassword");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);

curl_exec($ch);

$info = curl_getinfo($ch);
print_r($info['request_header']);

This will print:

GET /bar HTTP/1.1
Authorization: Basic c29tZXVzZXJuYW1lOnNlY3JldHBhc3N3b3Jk
Host: foo.com
Accept: */*

Note the auth details are base64-encoded:

echo base64_decode('c29tZXVzZXJuYW1lOnNlY3JldHBhc3N3b3Jk');
// prints: someusername:secretpassword

Also note that username and password need to be percent-encoded to escape any URL reserved characters (/, ?, &, : and so on) they might contain:

curl_setopt($ch, CURLOPT_USERPWD, urlencode($username).':'.urlencode($password));

How should I do integer division in Perl?

you can:

use integer;

it is explained by Michael Ratanapintha or else use manually:

$a=3.7;
$b=2.1;

$c=int(int($a)/int($b));

notice, 'int' is not casting. this is function for converting number to integer form. this is because Perl 5 does not have separate integer division. exception is when you 'use integer'. Then you will lose real division.

Swift - How to hide back button in navigation item?

self.navigationItem.setHidesBackButton(true, animated: false)

Run a controller function whenever a view is opened/shown

I faced at the same problem, and here i leave the reason of this behavior for everyone else with the same issue.

View LifeCycle

In order to improve performance, we've improved Ionic's ability to cache view elements and scope data. Once a controller is initialized, it may persist throughout the app’s life; it’s just hidden and removed from the watch cycle. Since we aren’t rebuilding scope, we’ve added events for which we should listen when entering the watch cycle again.

To see full description and $ionicView events go to: http://ionicframework.com/blog/navigating-the-changes/

Filter Pyspark dataframe column with None value

isNull()/isNotNull() will return the respective rows which have dt_mvmt as Null or !Null.

method_1 = df.filter(df['dt_mvmt'].isNotNull()).count()
method_2 = df.filter(df.dt_mvmt.isNotNull()).count()

Both will return the same result

Find (and kill) process locking port 3000 on Mac

This single command line is easy to remember:

npx kill-port 3000

For a more powerful tool with search:

npx fkill-cli


PS: They use third party javascript packages. npx comes built in with Node.js.

Sources: tweet | github

How to escape double quotes in JSON

For those who would like to use developer powershell. Here are the lines to add to your settings.json:

"terminal.integrated.automationShell.windows": "C:\\Windows\\SysWOW64\\WindowsPowerShell\\v1.0\\powershell.exe",
"terminal.integrated.shellArgs.windows": [
    "-noe",
    "-c",
    " &{Import-Module 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\BuildTools\\Common7\\Tools\\Microsoft.VisualStudio.DevShell.dll'; Enter-VsDevShell b7c50c8d} ",
    ],

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

Oracle, PostgreSQL, SQL Server and many more RDBMS engines have analytic functions called LAG and LEAD that do this very thing.

In SQL Server prior to 2012 you'd need to do the following:

SELECT  value - (
        SELECT  TOP 1 value
        FROM    mytable m2
        WHERE   m2.col1 < m1.col1 OR (m2.col1 = m1.col1 AND m2.pk < m1.pk)
        ORDER BY 
                col1, pk
        )
FROM mytable m1
ORDER BY
      col1, pk

, where COL1 is the column you are ordering by.

Having an index on (COL1, PK) will greatly improve this query.

CSS: image link, change on hover

That could be done with <a> only:

#twitterbird {
 display: block; /* 'convert' <a> to <div> */
 margin-bottom: 10px;
 background-position: center top;
 background-repeat: no-repeat;
 width: 160px;
 height: 160px;
 background-image: url('twitterbird.png');
}
#twitterbird:hover {
 background-image: url('twitterbird_hover.png');
}

Assign a variable inside a Block to a variable outside a Block

You need to use this line of code to resolve your problem:

__block Person *aPerson = nil;

For more details, please refer to this tutorial: Blocks and Variables

Basic Authentication Using JavaScript

EncodedParams variable is redefined as params variable will not work. You need to have same predefined call to variable, otherwise it looks possible with a little more work. Cheers! json is not used to its full capabilities in php there are better ways to call json which I don't recall at the moment.

How can I hide/show a div when a button is clicked?

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Show and hide div with JavaScript</title>
<script>

    var button_beg = '<button id="button" onclick="showhide()">', button_end = '</button>';
    var show_button = 'Show', hide_button = 'Hide';
    function showhide() {
        var div = document.getElementById( "hide_show" );
        var showhide = document.getElementById( "showhide" );
        if ( div.style.display !== "none" ) {
            div.style.display = "none";
            button = show_button;
            showhide.innerHTML = button_beg + button + button_end;
        } else {
            div.style.display = "block";
            button = hide_button;
            showhide.innerHTML = button_beg + button + button_end;
        }
    }
    function setup_button( status ) {
        if ( status == 'show' ) {
            button = hide_button;
        } else {
            button = show_button;
        }
        var showhide = document.getElementById( "showhide" );
        showhide.innerHTML = button_beg + button + button_end;
    }
    window.onload = function () {
        setup_button( 'hide' );
        showhide(); // if setup_button is set to 'show' comment this line
    }
</script>
</head>
<body>
    <div id="showhide"></div>
    <div id="hide_show">
        <p>This div will be show and hide on button click</p>
    </div>
</body>
</html>

Splitting on first occurrence

For me the better approach is that:

s.split('mango', 1)[-1]

...because if happens that occurrence is not in the string you'll get "IndexError: list index out of range".

Therefore -1 will not get any harm cause number of occurrences is already set to one.

Callback functions in C++

There is also the C way of doing callbacks: function pointers

//Define a type for the callback signature,
//it is not necessary, but makes life easier

//Function pointer called CallbackType that takes a float
//and returns an int
typedef int (*CallbackType)(float);  


void DoWork(CallbackType callback)
{
  float variable = 0.0f;

  //Do calculations

  //Call the callback with the variable, and retrieve the
  //result
  int result = callback(variable);

  //Do something with the result
}

int SomeCallback(float variable)
{
  int result;

  //Interpret variable

  return result;
}

int main(int argc, char ** argv)
{
  //Pass in SomeCallback to the DoWork
  DoWork(&SomeCallback);
}

Now if you want to pass in class methods as callbacks, the declarations to those function pointers have more complex declarations, example:

//Declaration:
typedef int (ClassName::*CallbackType)(float);

//This method performs work using an object instance
void DoWorkObject(CallbackType callback)
{
  //Class instance to invoke it through
  ClassName objectInstance;

  //Invocation
  int result = (objectInstance.*callback)(1.0f);
}

//This method performs work using an object pointer
void DoWorkPointer(CallbackType callback)
{
  //Class pointer to invoke it through
  ClassName * pointerInstance;

  //Invocation
  int result = (pointerInstance->*callback)(1.0f);
}

int main(int argc, char ** argv)
{
  //Pass in SomeCallback to the DoWork
  DoWorkObject(&ClassName::Method);
  DoWorkPointer(&ClassName::Method);
}

String isNullOrEmpty in Java?

You can add one

public static boolean isNullOrBlank(String param) { 
    return param == null || param.trim().length() == 0;
}

I have

public static boolean isSet(String param) { 
    // doesn't ignore spaces, but does save an object creation.
    return param != null && param.length() != 0; 
}

ResourceDictionary in a separate assembly

I'm working with .NET 4.5 and couldn't get this working... I was using WPF Custom Control Library. This worked for me in the end...

<ResourceDictionary Source="/MyAssembly;component/mytheme.xaml" />

source: http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/11a42336-8d87-4656-91a3-275413d3cc19

Python NLTK: SyntaxError: Non-ASCII character '\xc3' in file (Sentiment Analysis -NLP)

Add the following to the top of your file # coding=utf-8

If you go to the link in the error you can seen the reason why:

Defining the Encoding

Python will default to ASCII as standard encoding if no other encoding hints are given. To define a source code encoding, a magic comment must be placed into the source files either as first or second line in the file, such as: # coding=

Declare a constant array

From Effective Go:

Constants in Go are just that—constant. They are created at compile time, even when defined as locals in functions, and can only be numbers, characters (runes), strings or booleans. Because of the compile-time restriction, the expressions that define them must be constant expressions, evaluatable by the compiler. For instance, 1<<3 is a constant expression, while math.Sin(math.Pi/4) is not because the function call to math.Sin needs to happen at run time.

Slices and arrays are always evaluated during runtime:

var TestSlice = []float32 {.03, .02}
var TestArray = [2]float32 {.03, .02}
var TestArray2 = [...]float32 {.03, .02}

[...] tells the compiler to figure out the length of the array itself. Slices wrap arrays and are easier to work with in most cases. Instead of using constants, just make the variables unaccessible to other packages by using a lower case first letter:

var ThisIsPublic = [2]float32 {.03, .02}
var thisIsPrivate = [2]float32 {.03, .02}

thisIsPrivate is available only in the package it is defined. If you need read access from outside, you can write a simple getter function (see Getters in golang).

Good tutorial for using HTML5 History API (Pushstate?)

Here is a great screen-cast on the topic by Ryan Bates of railscasts. At the end he simply disables the ajax functionality if the history.pushState method is not available:

http://railscasts.com/episodes/246-ajax-history-state

Disable double-tap "zoom" option in browser on touch devices

I just wanted to answer my question properly as some people do not read the comments below an answer. So here it is:

(function($) {
  $.fn.nodoubletapzoom = function() {
      $(this).bind('touchstart', function preventZoom(e) {
        var t2 = e.timeStamp
          , t1 = $(this).data('lastTouch') || t2
          , dt = t2 - t1
          , fingers = e.originalEvent.touches.length;
        $(this).data('lastTouch', t2);
        if (!dt || dt > 500 || fingers > 1) return; // not double-tap

        e.preventDefault(); // double tap - prevent the zoom
        // also synthesize click events we just swallowed up
        $(this).trigger('click').trigger('click');
      });
  };
})(jQuery);

I did not write this, i just modified it. I found the iOS-only version here: https://gist.github.com/2047491 (thanks Kablam)

How to find column names for all tables in all databases in SQL Server

Try this:

select 
    o.name,c.name 
    from sys.columns            c
        inner join sys.objects  o on c.object_id=o.object_id
    order by o.name,c.column_id

With resulting column names this would be:

select 
     o.name as [Table], c.name as [Column]
     from sys.columns            c
         inner join sys.objects  o on c.object_id=o.object_id
     --where c.name = 'column you want to find'
     order by o.name,c.name

Or for more detail:

SELECT
    s.name as ColumnName
        ,sh.name+'.'+o.name AS ObjectName
        ,o.type_desc AS ObjectType
        ,CASE
             WHEN t.name IN ('char','varchar') THEN t.name+'('+CASE WHEN s.max_length<0 then 'MAX' ELSE CONVERT(varchar(10),s.max_length) END+')'
             WHEN t.name IN ('nvarchar','nchar') THEN t.name+'('+CASE WHEN s.max_length<0 then 'MAX' ELSE CONVERT(varchar(10),s.max_length/2) END+')'
            WHEN t.name IN ('numeric') THEN t.name+'('+CONVERT(varchar(10),s.precision)+','+CONVERT(varchar(10),s.scale)+')'
             ELSE t.name
         END AS DataType

        ,CASE
             WHEN s.is_nullable=1 THEN 'NULL'
            ELSE 'NOT NULL'
        END AS Nullable
        ,CASE
             WHEN ic.column_id IS NULL THEN ''
             ELSE ' identity('+ISNULL(CONVERT(varchar(10),ic.seed_value),'')+','+ISNULL(CONVERT(varchar(10),ic.increment_value),'')+')='+ISNULL(CONVERT(varchar(10),ic.last_value),'null')
         END
        +CASE
             WHEN sc.column_id IS NULL THEN ''
             ELSE ' computed('+ISNULL(sc.definition,'')+')'
         END
        +CASE
             WHEN cc.object_id IS NULL THEN ''
             ELSE ' check('+ISNULL(cc.definition,'')+')'
         END
            AS MiscInfo
    FROM sys.columns                           s
        INNER JOIN sys.types                   t ON s.system_type_id=t.user_type_id and t.is_user_defined=0
        INNER JOIN sys.objects                 o ON s.object_id=o.object_id
        INNER JOIN sys.schemas                sh on o.schema_id=sh.schema_id
        LEFT OUTER JOIN sys.identity_columns  ic ON s.object_id=ic.object_id AND s.column_id=ic.column_id
        LEFT OUTER JOIN sys.computed_columns  sc ON s.object_id=sc.object_id AND s.column_id=sc.column_id
        LEFT OUTER JOIN sys.check_constraints cc ON s.object_id=cc.parent_object_id AND s.column_id=cc.parent_column_id
    ORDER BY sh.name+'.'+o.name,s.column_id

EDIT
Here is a basic example to get all columns in all databases:

DECLARE @SQL varchar(max)
SET @SQL=''
SELECT @SQL=@SQL+'UNION
select 
'''+d.name+'.''+sh.name+''.''+o.name,c.name,c.column_id
from '+d.name+'.sys.columns            c
    inner join '+d.name+'.sys.objects  o on c.object_id=o.object_id
    INNER JOIN '+d.name+'.sys.schemas  sh on o.schema_id=sh.schema_id
'
FROM sys.databases d
SELECT @SQL=RIGHT(@SQL,LEN(@SQL)-5)+'order by 1,3'
--print @SQL
EXEC (@SQL)

EDIT SQL Server 2000 version

DECLARE @SQL varchar(8000)
SET @SQL=''
SELECT @SQL=@SQL+'UNION
select 
'''+d.name+'.''+sh.name+''.''+o.name,c.name,c.colid
from '+d.name+'..syscolumns            c
    inner join sysobjects  o on c.id=o.id
    INNER JOIN sysusers  sh on o.uid=sh.uid
'
FROM master.dbo.sysdatabases d
SELECT @SQL=RIGHT(@SQL,LEN(@SQL)-5)+'order by 1,3'
--print @SQL
EXEC (@SQL)

EDIT
Based on some comments, here is a version using sp_MSforeachdb:

sp_MSforeachdb 'select 
    ''?'' AS DatabaseName, o.name AS TableName,c.name AS ColumnName
    from sys.columns            c
        inner join ?.sys.objects  o on c.object_id=o.object_id
    --WHERE ''?'' NOT IN (''master'',''msdb'',''tempdb'',''model'')
    order by o.name,c.column_id'

Android change SDK version in Eclipse? Unable to resolve target android-x

If you're using eclipse you can open default.properties file in your workspace and change the project target to the new sdk (target=android-8 for 2.2). I accidentally selected the 1.5 sdk for my version and didn't catch it until much later, but updating that and restarting eclipse seemed to have done the trick.

Add Facebook Share button to static HTML page

 <div class="fb_share">
     <a name="fb_share" type="box_count" share_url="<?php the_permalink() ?>"
       href="http://www.facebook.com/sharer.php">Partilhar</a>
     <script src="http://static.ak.fbcdn.net/connect.php/js/FB.Share" type="text/javascript"></script> </div> <?php }  }

 add_action('thesis_hook_byline_item','fb_share');

Can I call an overloaded constructor from another constructor of the same class in C#?

If you mean if you can do ctor chaining in C#, the answer is yes. The question has already been asked.

However it seems from the comments, it seems what you really intend to ask is 'Can I call an overloaded constructor from within another constructor with pre/post processing?'
Although C# doesn't have the syntax to do this, you could do this with a common initialization function (like you would do in C++ which doesn't support ctor chaining)

class A
{
  //ctor chaining
  public A() : this(0)
  {  
      Console.WriteLine("default ctor"); 
  }

  public A(int i)
  {  
      Init(i); 
  }

  // what you want
  public A(string s)
  {  
      Console.WriteLine("string ctor overload" );
      Console.WriteLine("pre-processing" );
      Init(Int32.Parse(s));
      Console.WriteLine("post-processing" );
  }

   private void Init(int i)
   {
      Console.WriteLine("int ctor {0}", i);
   }
}

How to install OpenSSL for Python

SSL development libraries have to be installed

CentOS:

$ yum install openssl-devel libffi-devel

Ubuntu:

$ apt-get install libssl-dev libffi-dev

OS X (with Homebrew installed):

$ brew install openssl

Removing Conda environment

To remove complete conda environment :

conda remove --name YOUR_CONDA_ENV_NAME --all

How to add a new row to an empty numpy array

The way to "start" the array that you want is:

arr = np.empty((0,3), int)

Which is an empty array but it has the proper dimensionality.

>>> arr
array([], shape=(0, 3), dtype=int64)

Then be sure to append along axis 0:

arr = np.append(arr, np.array([[1,2,3]]), axis=0)
arr = np.append(arr, np.array([[4,5,6]]), axis=0)

But, @jonrsharpe is right. In fact, if you're going to be appending in a loop, it would be much faster to append to a list as in your first example, then convert to a numpy array at the end, since you're really not using numpy as intended during the loop:

In [210]: %%timeit
   .....: l = []
   .....: for i in xrange(1000):
   .....:     l.append([3*i+1,3*i+2,3*i+3])
   .....: l = np.asarray(l)
   .....: 
1000 loops, best of 3: 1.18 ms per loop

In [211]: %%timeit
   .....: a = np.empty((0,3), int)
   .....: for i in xrange(1000):
   .....:     a = np.append(a, 3*i+np.array([[1,2,3]]), 0)
   .....: 
100 loops, best of 3: 18.5 ms per loop

In [214]: np.allclose(a, l)
Out[214]: True

The numpythonic way to do it depends on your application, but it would be more like:

In [220]: timeit n = np.arange(1,3001).reshape(1000,3)
100000 loops, best of 3: 5.93 µs per loop

In [221]: np.allclose(a, n)
Out[221]: True

Git fetch remote branch

The easiest way to do it, at least for me:

git fetch origin <branchName> # Will fetch the branch locally
git checkout <branchName> # To move to that branch

Why does JavaScript only work after opening developer tools in IE once?

It sounds like you might have some debugging code in your javascript.

The experience you're describing is typical of code which contain console.log() or any of the other console functionality.

The console object is only activated when the Dev Toolbar is opened. Prior to that, calling the console object will result in it being reported as undefined. After the toolbar has been opened, the console will exist (even if the toolbar is subsequently closed), so your console calls will then work.

There are a few solutions to this:

The most obvious one is to go through your code removing references to console. You shouldn't be leaving stuff like that in production code anyway.

If you want to keep the console references, you could wrap them in an if() statement, or some other conditional which checks whether the console object exists before trying to call it.

MySQL Like multiple values

The (a,b,c) list only works with in. For like, you have to use or:

WHERE interests LIKE '%sports%' OR interests LIKE '%pub%'

How to empty a list?

lst *= 0

has the same effect as

lst[:] = []

It's a little simpler and maybe easier to remember. Other than that there's not much to say

The efficiency seems to be about the same

What does "|=" mean? (pipe equal operator)

It's a shortening for this:

notification.defaults = notification.defaults | Notification.DEFAULT_SOUND;

And | is a bit-wise OR.

Java - How to access an ArrayList of another class?

You can do the following:

  public class Numbers {
    private int number1 = 50;
    private int number2 = 100;
    private List<Integer> list;

    public Numbers() {
      list = new ArrayList<Integer>();
      list.add(number1);
      list.add(number2);
    }

    int getNumber(int pos)
    {
      return list.get(pos);
    }
  }

  public class Test {
    private Numbers numbers;

    public Test(){
      numbers = new Numbers();
      int number1 = numbers.getNumber(0);
      int number2 = numbers.getNumber(1);
    }
  }

An Iframe I need to refresh every 30 seconds (but not the whole page)

Let's assume that your iframe id= myIframe

here is the code:

<script>
window.setInterval("reloadIFrame();", 30000);
function reloadIFrame() {
 document.getElementById("myIframe").src="YOUR_PAGE_URL_HERE";
}
</script>

How can I check for Python version in a program that uses new language features?

Have a wrapper around your program that does the following.

import sys

req_version = (2,5)
cur_version = sys.version_info

if cur_version >= req_version:
   import myApp
   myApp.run()
else:
   print "Your Python interpreter is too old. Please consider upgrading."

You can also consider using sys.version(), if you plan to encounter people who are using pre-2.0 Python interpreters, but then you have some regular expressions to do.

And there might be more elegant ways to do this.

How to override maven property in command line?

See Introduction to the POM

finalName is created as:

<build>
    <finalName>${project.artifactId}-${project.version}</finalName>
</build>

One of the solutions is to add own property:

<properties>
    <finalName>${project.artifactId}-${project.version}</finalName>
</properties>
<build>
    <finalName>${finalName}</finalName>
 </build>

And now try:

mvn -DfinalName=build clean package

How to fix "The ConnectionString property has not been initialized"

The connection string is not in AppSettings.

What you're looking for is in:

System.Configuration.ConfigurationManager.ConnectionStrings["MyDB"]...

Tool to generate JSON schema from JSON data

You might be looking for this:

http://www.jsonschema.net

It is an online tool that can automatically generate JSON schema from JSON string. And you can edit the schema easily.

How to open local file on Jupyter?

I do not know if it's what you were looking for, but it sounds to me something like this.

This is for linux (ubuntu) but maybe it also works on mac:

If the file is a pdf called 'book.pdf' and is located in your downloads, then

import subprocess

path='/home/user/Downloads/book.pdf'
subprocess.call(['evince', path])

where evince is the program that open pdfs in ubuntu

SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 81

If you are getting this error when you run stuffs on automated cluster and you are downloading the stable version of the google chrome every time then you can use the below shell script to download the compatible version of the chrome driver dynamically every time even if the stable version of the chrome gets updated.

%sh
#downloading compatible chrome driver version
#getting the current chrome browser version
**chromeVersion=$(google-chrome --product-version)**
#getting the major version value from the full version
**chromeMajorVersion=${chromeVersion%%.*}**
# setting the base url for getting the release url for the chrome driver
**baseDriverLatestReleaseURL=https://chromedriver.storage.googleapis.com/LATEST_RELEASE_**
#creating the latest release driver url based on the major version of the chrome
**latestDriverReleaseURL=$baseDriverLatestReleaseURL$chromeMajorVersion**
**echo $latestDriverReleaseURL**
#file name of the file that gets downloaded which would contain the full version of the chrome driver to download
**latestDriverVersionFileName="LATEST_RELEASE_"$chromeMajorVersion**
#downloading the file that would contain the full release version compatible with the major release of the chrome browser version
**wget $latestDriverReleaseURL** 
#reading the file to get the version of the chrome driver that we should download
**latestFullDriverVersion=$(cat $latestDriverVersionFileName)**
**echo $latestFullDriverVersion**
#creating the final URL by passing the compatible version of the chrome driver that we should download
**finalURL="https://chromedriver.storage.googleapis.com/"$latestFullDriverVersion"/chromedriver_linux64.zip"**
**echo $finalURL**
**wget $finalURL**

I was able to get the compatible version of chrome browser and chrome driver using the above approach when running scheduled job on the databricks environment and it worked like a charm without any issues.

Hope it helps others in one way or other.

HTML-5 date field shows as "mm/dd/yyyy" in Chrome, even when valid date is set

I was having the same problem, with a value like 2016-08-8, then I solved adding a zero to have two digits days, and it works. Tested in chrome, firefox, and Edge

today:function(){
   var today = new Date();
   var d = (today.getDate() < 10 ? '0' : '' )+ today.getDate();
   var m = ((today.getMonth() + 1) < 10 ? '0' :'') + (today.getMonth() + 1);
   var y = today.getFullYear();
   var x = String(y+"-"+m+"-"+d); 
   return x;
}

How to install XCODE in windows 7 platform?

X-code is primarily made for OS-X or iPhone development on Mac systems. Versions for Windows are not available. However this might help!

There is no way to get Xcode on Windows; however you can use a different SDK like Corona instead although it will not use Objective-C (I believe it uses Lua). I have however heard that it is horrible to use.

Source: classroomm.com

System.drawing namespace not found under console application

For,Adding System.Drawing Follow some steps: Firstly, right click on the solution and click on add Reference. Secondly, Select the .NET Folder. And then double click on the Using.System.Drawing;

Stop on first error

Maybe you want set -e:

www.davidpashley.com/articles/writing-robust-shell-scripts.html#id2382181:

This tells bash that it should exit the script if any statement returns a non-true return value. The benefit of using -e is that it prevents errors snowballing into serious issues when they could have been caught earlier. Again, for readability you may want to use set -o errexit.

Java command not found on Linux

  1. Execute: vi ~/.bashrc OR vi ~/.bash_profile

(if above command will not allow to update the .bashrc file then you can open this file in notepad by writing command at terminal i.e. "leafpad ~/.bashrc")

  1. add line : export JAVA_HOME=/usr/java/jre1.6.0_24
  2. save the file (by using shift + Z + Z)
  3. source ~/.bashrc OR source ~/.bash_profile
  4. Execute : echo $JAVA_HOME (Output should print the path)

how to get the one entry from hashmap without iterating

Get values, convert it to an array, get array's first element:

map.values().toArray()[0]

W.

Associating existing Eclipse project with existing SVN repository

I came across the same issue. I checked out using Tortoise client and then tried to import the projects in Eclipse using import wizard. Eclipse did not recognize the svn location. I tried share option as mentioned in the above posts and it tried to commit these projects into SVN. But my issue was a version mismatch. I selected svn 1.8 version in eclipse (I was using 1.7 in eclipse and 1.8.8 in tortoise) and then re imported the projects. It resolved with no issues.

How to execute Ant build in command line

is it still actual?

As I can see you wrote <target depends="build-subprojects,build-project" name="build"/>, then you wrote <target name="build-subprojects"/> (it does nothing). Could it be a reason? Does this <echo message="${ant.project.name}: ${ant.file}"/> print appropriate message? If no then target is not running. Take a look at the next link http://www.sqaforums.com/showflat.php?Number=623277

What is Java String interning?

http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#intern()

Basically doing String.intern() on a series of strings will ensure that all strings having same contents share same memory. So if you have list of names where 'john' appears 1000 times, by interning you ensure only one 'john' is actually allocated memory.

This can be useful to reduce memory requirements of your program. But be aware that the cache is maintained by JVM in permanent memory pool which is usually limited in size compared to heap so you should not use intern if you don't have too many duplicate values.


More on memory constraints of using intern()

On one hand, it is true that you can remove String duplicates by internalizing them. The problem is that the internalized strings go to the Permanent Generation, which is an area of the JVM that is reserved for non-user objects, like Classes, Methods and other internal JVM objects. The size of this area is limited, and is usually much smaller than the heap. Calling intern() on a String has the effect of moving it out from the heap into the permanent generation, and you risk running out of PermGen space.

-- From: http://www.codeinstructions.com/2009/01/busting-javalangstringintern-myths.html


From JDK 7 (I mean in HotSpot), something has changed.

In JDK 7, interned strings are no longer allocated in the permanent generation of the Java heap, but are instead allocated in the main part of the Java heap (known as the young and old generations), along with the other objects created by the application. This change will result in more data residing in the main Java heap, and less data in the permanent generation, and thus may require heap sizes to be adjusted. Most applications will see only relatively small differences in heap usage due to this change, but larger applications that load many classes or make heavy use of the String.intern() method will see more significant differences.

-- From Java SE 7 Features and Enhancements

Update: Interned strings are stored in main heap from Java 7 onwards. http://www.oracle.com/technetwork/java/javase/jdk7-relnotes-418459.html#jdk7changes

Convert DateTime to a specified Format

Easy peasy:

var date = DateTime.Parse("14/11/2011"); // may need some Culture help here
Console.Write(date.ToString("yyyy-MM-dd"));

Take a look at DateTime.ToString() method, Custom Date and Time Format Strings and Standard Date and Time Format Strings

string customFormattedDateTimeString = DateTime.Now.ToString("yyyy-MM-dd");

In git, what is the difference between merge --squash and rebase?

Merge commits: retains all of the commits in your branch and interleaves them with commits on the base branchenter image description here

Merge Squash: retains the changes but omits the individual commits from history enter image description here

Rebase: This moves the entire feature branch to begin on the tip of the master branch, effectively incorporating all of the new commits in master

enter image description here

More on here

SOAP-ERROR: Parsing WSDL: Couldn't load from <URL>

As mentioned in earlier responses, this error can occur when interacting with a SOAP service over an HTTPS connection, and an issue is identified with the connection. The issue may be on the remote end (invalid cert) or on the client (in case of missing CA or PEM files). See http://php.net/manual/en/context.ssl.php for all possible SSL context settings. In my case, setting the path to my local certificate resolved the issue:

$context = ['ssl' => [
    'local_cert' => '/path/to/pem/file',
]];

$params = [
    'soap_version' => SOAP_1_2, 
    'trace' => 1, 
    'exceptions' => 1, 
    'connection_timeout' => 180, 
    'stream_context' => stream_context_create($context), 
    'cache_wsdl' => WSDL_CACHE_NONE, // eliminate possible issue from cached wsdl
];

$client = new SoapClient('https://remoteservice/wsdl', $params);

Function to clear the console in R and RStudio

You can combine the following two commands

cat("\014"); 
cat(rep("\n", 50))

How to parse a text file with C#

You could do something like:

using (TextReader rdr = OpenYourFile()) {
    string line;
    while ((line = rdr.ReadLine()) != null) {
        string[] fields = line.Split('\t'); // THIS LINE DOES THE MAGIC
        int theInt = Convert.ToInt32(fields[1]);
    }
}

The reason you didn't find relevant result when searching for 'formatting' is that the operation you are performing is called 'parsing'.

How to set proxy for wget?

For all users of the system via the /etc/wgetrc or for the user only with the ~/.wgetrc file:

use_proxy=yes
http_proxy=127.0.0.1:8080
https_proxy=127.0.0.1:8080

or via -e options placed after the URL:

wget ... -e use_proxy=yes -e http_proxy=127.0.0.1:8080 ...

java.lang.IllegalStateException: Cannot (forward | sendRedirect | create session) after response has been committed

You should add return statement while you are forwarding or redirecting the flow.

Example:

if forwardind,

    request.getRequestDispatcher("/abs.jsp").forward(request, response);
    return;

if redirecting,

    response.sendRedirect(roundTripURI);
    return;

if (select count(column) from table) > 0 then

Edit:

The oracle tag was not on the question when this answer was offered, and apparently it doesn't work with oracle, but it does work with at least postgres and mysql

No, just use the value directly:

begin
  if (select count(*) from table) > 0 then
     update table
  end if;
end;

Note there is no need for an "else".

Edited

You can simply do it all within the update statement (ie no if construct):

update table
set ...
where ...
and exists (select 'x' from table where ...)

How to render a PDF file in Android

I finally was able to modify butelo's code to open any PDF file in the Android filesystem using pdf.js. The code can be found on my GitHub

What I did was modified the pdffile.js to read HTML argument file like this:

var url = getURLParameter('file');

function getURLParameter(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null}

So what you need to do is just append the file path after the index.html like this:

Uri path = Uri.parse(Environment.getExternalStorageDirectory().toString() + "/data/test.pdf");
webView.loadUrl("file:///android_asset/pdfviewer/index.html?file=" + path);

Update the path variable to point to a valid PDF in the Adroid filesystem.

How can I change the text inside my <span> with jQuery?

This will be used to change the Html content inside the span

 $('#abc span').html('goes inside the span');

if you want to change the text inside the span, you can use:

 $('#abc span').text('goes inside the span');

How do I change Bootstrap 3's glyphicons to white?

You can just create your own .white class and add it to the glyphicon element.

.white, .white a {
  color: #fff;
}
<i class="glyphicon glyphicon-home white"></i>

How to avoid the "Windows Defender SmartScreen prevented an unrecognized app from starting warning"

UPDATE: Another writeup here: How to add publisher in Installshield 2018 (might be better).


I am not too well informed about this issue, but please see if this answer to another question tells you anything useful (and let us know so I can evolve a better answer here): How to pass the Windows Defender SmartScreen Protection? That question relates to BitRock - a non-MSI installer technology, but the overall issue seems to be the same.

Extract from one of the links pointed to in my answer above: "...a certificate just isn't enough anymore to gain trust... SmartScreen is reputation based, not unlike the way StackOverflow works... SmartScreen trusts installers that don't cause problems. Windows machines send telemetry back to Redmond about installed programs and how much trouble they cause. If you get enough thumbs-up then SmartScreen stops blocking your installer automatically. This takes time and lots of installs to get sufficient thumbs. There is no way to find out how far along you got."

Honestly this is all news to me at this point, so do get back to us with any information you dig up yourself.


The actual dialog text you have marked above definitely relates to the Zone.Identifier alternate data stream with a value of 3 that is added to any file that is downloaded from the Internet (see linked answer above for more details).


I was not able to mark this question as a duplicate of the previous one, since it doesn't have an accepted answer. Let's leave both question open for now? (one question is for MSI, one is for non-MSI).

CSS horizontal centering of a fixed div?

It is possible to horisontally center the div this way:

html:

<div class="container">
    <div class="inner">content</div>
</div>

css:

.container {
    left: 0;
    right: 0;
    bottom: 0; /* or top: 0, or any needed value */
    position: fixed;
    z-index: 1000; /* or even higher to prevent guarantee overlapping */
}

.inner {
    max-width: 600px; /* just for example */
    margin: 0 auto;
}

Using this way you will have always your inner block centered, in addition it can be easily turned to true responsive (in the example it will be just fluid on smaller screens), therefore no limitation in as in the question example and in the chosen answer.

Notepad++ change text color?

You can Change it from:

Menu Settings -> Style Configurator

See on screenshot:

enter image description here

MySQL fails on: mysql "ERROR 1524 (HY000): Plugin 'auth_socket' is not loaded"

In case someone lands here after making the same mistake I did:

  1. Switched to plugin="mysql_native_password" temporarily. Performed my tasks.
  2. Attempted to switch back to the "auth_socket" plugin, but incorrectly referenced it as plugin="auth_socket" which resulted in mysql "ERROR 1524 (HY000): Plugin 'auth_socket' is not loaded"
  3. Lacking a way to login to fix this mistake, I was forced to have to stop mysql and use mysql_safe to bypass authentication in order to switch to the appropriate plugin plugin="unix_socket"

Hopefully this saves someone some time if they receive the original poster's error message, but the true cause was flubbing the plugin name, not actually lacking the existence of the "auth_socket" plugin itself, which according to the MariaDB documentation:

In MariaDB 10.4.3 and later, the unix_socket authentication plugin is installed by default, and it is used by the 'root'@'localhost' user account by default.

Check if value is zero or not null in python

You can check if it can be converted to decimal. If yes, then its a number

from decimal import Decimal

def is_number(value):
    try:
        value = Decimal(value)
        return True
    except:
        return False

print is_number(None)   // False
print is_number(0)      // True
print is_number(2.3)    // True
print is_number('2.3')  // True (caveat!)

JWT (JSON Web Token) library for Java

JJWT aims to be the easiest to use and understand JWT library for the JVM and Android:

https://github.com/jwtk/jjwt

How to write "Html.BeginForm" in Razor

The following code works fine:

@using (Html.BeginForm("Upload", "Upload", FormMethod.Post, 
                                      new { enctype = "multipart/form-data" }))
{
    @Html.ValidationSummary(true)
    <fieldset>
        Select a file <input type="file" name="file" />
        <input type="submit" value="Upload" />
    </fieldset>
}

and generates as expected:

<form action="/Upload/Upload" enctype="multipart/form-data" method="post">    
    <fieldset>
        Select a file <input type="file" name="file" />
        <input type="submit" value="Upload" />
    </fieldset>
</form>

On the other hand if you are writing this code inside the context of other server side construct such as an if or foreach you should remove the @ before the using. For example:

@if (SomeCondition)
{
    using (Html.BeginForm("Upload", "Upload", FormMethod.Post, 
                                      new { enctype = "multipart/form-data" }))
    {
        @Html.ValidationSummary(true)
        <fieldset>
            Select a file <input type="file" name="file" />
            <input type="submit" value="Upload" />
        </fieldset>
    }
}

As far as your server side code is concerned, here's how to proceed:

[HttpPost]
public ActionResult Upload(HttpPostedFileBase file) 
{
    if (file != null && file.ContentLength > 0) 
    {
        var fileName = Path.GetFileName(file.FileName);
        var path = Path.Combine(Server.MapPath("~/content/pics"), fileName);
        file.SaveAs(path);
    }
    return RedirectToAction("Upload");
}

How can I read Chrome Cache files?

The JPEXS Free Flash Decompiler has Java code to do this at in the source tree for both Chrome and Firefox (no support for Firefox's more recent cache2 though).

change cursor to finger pointer

Solution via pure CSS as mentioned in answer marked as the best is not suitable for this situation.

The example in this topic does not have normal static href attribute, it is calling of JS only, so it will not do anything without JS.

So it is good to switch on pointer with JS only. So, solution

onMouseOver="this.style.cursor='pointer'"

as mentioned above (but I can not comment there) is the best one in this case. (But yes, generaly, for normal links not demanding JS, it is better to work with pure CSS without JS.)

Stop UIWebView from "bouncing" vertically?

Brad's method worked for me. If you use it you might want to make it a little safer.

id scrollView = [yourWebView.subviews objectAtIndex:0];
if( [scrollView respondsToSelector:@selector(setAllowsRubberBanding:)] )
{
    [scrollView performSelector:@selector(setAllowsRubberBanding:) withObject:NO];
}

If apple changes something then the bounce will come back - but at least your app won't crash.

Can I hide the HTML5 number input’s spin box?

I needed this to work

/* Chrome, Safari, Edge, Opera */
input[type=number]::-webkit-outer-spin-button,
input[type=number]::-webkit-inner-spin-button
  -webkit-appearance: none
  appearance: none
  margin: 0

/* Firefox */
input[type=number]
  -moz-appearance: textfield

The extra line of appearance: none was key to me.

How to change onClick handler dynamically?

Use .onclick (all lowercase). Like so:

document.getElementById("foo").onclick = function () {
  alert('foo'); // do your stuff
  return false; // <-- to suppress the default link behaviour
};

Actually, you'll probably find yourself way better off using some good library (I recommend jQuery for several reasons) to get you up and running, and writing clean javascript.

Cross-browser (in)compatibilities are a right hell to deal with for anyone - let alone someone who's just starting.

Handling JSON Post Request in Go

Please use json.Decoder instead of json.Unmarshal.

func test(rw http.ResponseWriter, req *http.Request) {
    decoder := json.NewDecoder(req.Body)
    var t test_struct
    err := decoder.Decode(&t)
    if err != nil {
        panic(err)
    }
    log.Println(t.Test)
}

Make an image width 100% of parent div, but not bigger than its own width

If the image is smaller than parent...

.img_100 {
  width: 100%;
}

Dealing with float precision in Javascript

You could do something like this:

> +(Math.floor(y/x)*x).toFixed(15);
1.2

Can you display HTML5 <video> as a full screen background?

Just a comment on this - I've used HTML5 video for a full-screen background and it works a treat - but make sure to use either Height:100% and width:auto or the other way around - to ensure you keep aspect ratio.

As for Ipads -you can (apparently) do this, by having a hidden and then forcing the click event to fire, and having the function of the click event kick off the Load/Play().

P.s - this shouldn't require any plugins and can be done with minimal JS - If you're targeting any mobile device (I would assume you might be..) staying away from any such framework is the way forward.

Calculate MD5 checksum for a file

I know this question was already answered, but this is what I use:

using (FileStream fStream = File.OpenRead(filename)) {
    return GetHash<MD5>(fStream)
}

Where GetHash:

public static String GetHash<T>(Stream stream) where T : HashAlgorithm {
    StringBuilder sb = new StringBuilder();

    MethodInfo create = typeof(T).GetMethod("Create", new Type[] {});
    using (T crypt = (T) create.Invoke(null, null)) {
        byte[] hashBytes = crypt.ComputeHash(stream);
        foreach (byte bt in hashBytes) {
            sb.Append(bt.ToString("x2"));
        }
    }
    return sb.ToString();
}

Probably not the best way, but it can be handy.

How to convert int[] to Integer[] in Java?

Not sure why you need a Double in your map. In terms of what you're trying to do, you have an int[] and you just want counts of how many times each sequence occurs? Why would this required a Double anyway?

What I would do is to create a wrapper for the int array with a proper .equals and .hashCode methods to account for the fact that int[] object itself doesn't consider the data in it's version of these methods.

public class IntArrayWrapper {
    private int values[];

    public IntArrayWrapper(int[] values) {
        super();
        this.values = values;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + Arrays.hashCode(values);
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        IntArrayWrapper other = (IntArrayWrapper) obj;
        if (!Arrays.equals(values, other.values))
            return false;
        return true;
    }

}

And then use google guava's multiset, which is meant exactly for the purpose of counting occurances, as long as the element type you put in it has proper .equals and .hashCode methods.

List<int[]> list = ...;
HashMultiset<IntArrayWrapper> multiset = HashMultiset.create();
for (int values[] : list) {
    multiset.add(new IntArrayWrapper(values));
}

Then, to get the count for any particular combination:

int cnt = multiset.count(new IntArrayWrapper(new int[] { 0, 1, 2, 3 }));

Python "extend" for a dictionary

As others have mentioned, a.update(b) for some dicts a and b will achieve the result you've asked for in your question. However, I want to point out that many times I have seen the extend method of mapping/set objects desire that in the syntax a.extend(b), a's values should NOT be overwritten by b's values. a.update(b) overwrites a's values, and so isn't a good choice for extend.

Note that some languages call this method defaults or inject, as it can be thought of as a way of injecting b's values (which might be a set of default values) in to a dictionary without overwriting values that might already exist.

Of course, you could simple note that a.extend(b) is nearly the same as b.update(a); a=b. To remove the assignment, you could do it thus:

def extend(a,b):
    """Create a new dictionary with a's properties extended by b,
    without overwriting.

    >>> extend({'a':1,'b':2},{'b':3,'c':4})
    {'a': 1, 'c': 4, 'b': 2}
    """
    return dict(b,**a)

Thanks to Tom Leys for that smart idea using a side-effect-less dict constructor for extend.

Can you target an elements parent element using event.target?

function getParent(event)
{
   return event.target.parentNode;
}

Examples: 1. document.body.addEventListener("click", getParent, false); returns the parent element of the current element that you have clicked.

  1. If you want to use inside any function then pass your event and call the function like this : function yourFunction(event){ var parentElement = getParent(event); }

pandas how to check dtype for all columns in a dataframe?

To go one step further, I assume you want to do something with these dtypes. df.dtypes.to_dict() comes in handy.

my_type = 'float64' #<---

dtypes = dataframe.dtypes.to_dict()

for col_nam, typ in dtypes.items():
    if (typ != my_type): #<---
        raise ValueError(f"Yikes - `dataframe['{col_name}'].dtype == {typ}` not {my_type}")

You'll find that Pandas did a really good job comparing NumPy classes and user-provided strings. For example: even things like 'double' == dataframe['col_name'].dtype will succeed when .dtype==np.float64.

Failed to find target with hash string 'android-25'

I got same exception while running gradle build for my android project.

Caused by: java.lang.IllegalStateException: Failed to find target with hash string 'android-27'

This issue related to android SDK version enable for your Android Studio. Please find the solution of this problem from attached screen. enter image description here

Mount current directory as a volume in Docker on Windows 10

  1. Open Settings on Docker Desktop (Docker for Windows).
  2. Select Shared Drives.
  3. Select the drive that you want to use inside your containers (e.g., C).
  4. Click Apply. You may be asked to provide user credentials. Enabling drives for containers on Windows

  5. The command below should now work on PowerShell (command prompt does not support ${PWD}):

    docker run --rm -v ${PWD}:/data alpine ls /data

IMPORTANT: if/when you change your Windows domain password, the mount will stop working silently, that is, -v will work but the container will not see your host folders and files. Solution: go back to Settings, uncheck the shared drives, Apply, check them again, Apply, and enter the new password when prompted.

Loading context in Spring using web.xml

You can also load the context while defining the servlet itself (WebApplicationContext)

  <servlet>
    <servlet-name>admin</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>
                /WEB-INF/spring/*.xml
            </param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>admin</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

rather than (ApplicationContext)

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationContext*.xml</param-value>
</context-param>

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

or can do both together.

Drawback of just using WebApplicationContext is that it will load context only for this particular Spring entry point (DispatcherServlet) where as with above mentioned methods context will be loaded for multiple entry points (Eg. Webservice Servlet, REST servlet etc)

Context loaded by ContextLoaderListener will infact be a parent context to that loaded specifically for DisplacherServlet . So basically you can load all your business service, data access or repository beans in application context and separate out your controller, view resolver beans to WebApplicationContext.

How to change the current URL in javascript?

Your example wasn't working because you are trying to add 1 to a string that looks like this: "1.html". That will just get you this "1.html1" which is not what you want. You have to isolate the numeric part of the string and then convert it to an actual number before you can do math on it. After getting it to an actual number, you can then increase its value and then combine it back with the rest of the string.

You can use a custom replace function like this to isolate the various pieces of the original URL and replace the number with an incremented number:

function nextImage() {
    return(window.location.href.replace(/(\d+)(\.html)$/, function(str, p1, p2) {
        return((Number(p1) + 1) + p2);
    }));
}

You can then call it like this:

window.location.href = nextImage();

Demo here: http://jsfiddle.net/jfriend00/3VPEq/

This will work for any URL that ends in some series of digits followed by .html and if you needed a slightly different URL form, you could just tweak the regular expression.

Determine on iPhone if user has enabled push notifications

Below you'll find a complete example that covers both iOS8 and iOS7 (and lower versions). Please note that prior to iOS8 you can't distinguish between "remote notifications disabled" and "only View in lockscreen enabled".

BOOL remoteNotificationsEnabled = false, noneEnabled,alertsEnabled, badgesEnabled, soundsEnabled;

if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerUserNotificationSettings:)]) {
    // iOS8+
    remoteNotificationsEnabled = [UIApplication sharedApplication].isRegisteredForRemoteNotifications;

    UIUserNotificationSettings *userNotificationSettings = [UIApplication sharedApplication].currentUserNotificationSettings;

    noneEnabled = userNotificationSettings.types == UIUserNotificationTypeNone;
    alertsEnabled = userNotificationSettings.types & UIUserNotificationTypeAlert;
    badgesEnabled = userNotificationSettings.types & UIUserNotificationTypeBadge;
    soundsEnabled = userNotificationSettings.types & UIUserNotificationTypeSound;

} else {
    // iOS7 and below
    UIRemoteNotificationType enabledRemoteNotificationTypes = [UIApplication sharedApplication].enabledRemoteNotificationTypes;

    noneEnabled = enabledRemoteNotificationTypes == UIRemoteNotificationTypeNone;
    alertsEnabled = enabledRemoteNotificationTypes & UIRemoteNotificationTypeAlert;
    badgesEnabled = enabledRemoteNotificationTypes & UIRemoteNotificationTypeBadge;
    soundsEnabled = enabledRemoteNotificationTypes & UIRemoteNotificationTypeSound;
}

if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerUserNotificationSettings:)]) {
    NSLog(@"Remote notifications enabled: %@", remoteNotificationsEnabled ? @"YES" : @"NO");
}

NSLog(@"Notification type status:");
NSLog(@"  None: %@", noneEnabled ? @"enabled" : @"disabled");
NSLog(@"  Alerts: %@", alertsEnabled ? @"enabled" : @"disabled");
NSLog(@"  Badges: %@", badgesEnabled ? @"enabled" : @"disabled");
NSLog(@"  Sounds: %@", soundsEnabled ? @"enabled" : @"disabled");

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" >

How does spring.jpa.hibernate.ddl-auto property exactly work in Spring?

For the record, the spring.jpa.hibernate.ddl-auto property is Spring Data JPA specific and is their way to specify a value that will eventually be passed to Hibernate under the property it knows, hibernate.hbm2ddl.auto.

The values create, create-drop, validate, and update basically influence how the schema tool management will manipulate the database schema at startup.

For example, the update operation will query the JDBC driver's API to get the database metadata and then Hibernate compares the object model it creates based on reading your annotated classes or HBM XML mappings and will attempt to adjust the schema on-the-fly.

The update operation for example will attempt to add new columns, constraints, etc but will never remove a column or constraint that may have existed previously but no longer does as part of the object model from a prior run.

Typically in test case scenarios, you'll likely use create-drop so that you create your schema, your test case adds some mock data, you run your tests, and then during the test case cleanup, the schema objects are dropped, leaving an empty database.

In development, it's often common to see developers use update to automatically modify the schema to add new additions upon restart. But again understand, this does not remove a column or constraint that may exist from previous executions that is no longer necessary.

In production, it's often highly recommended you use none or simply don't specify this property. That is because it's common practice for DBAs to review migration scripts for database changes, particularly if your database is shared across multiple services and applications.

make div's height expand with its content

as an alternative way you can also try this that may be usefull in some situations

display:table;

jsFiddle

Get AVG ignoring Null or Zero values

In Case of not considering '0' or 'NULL' in average function. Simply use

AVG(NULLIF(your_column_name,0))

Python script header


I'd suggest 3 things in the beginning of your script:

First, as already being said use environment:

#!/usr/bin/env python

Second, set your encoding:

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

Third, set some doc string:

"""This is a awesome
    python script!"""

And for sure I would use " " (4 spaces) for ident.
Final header will look like:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""This is a awesome
        python script!"""


Best wishes and happy coding.

Unbalanced calls to begin/end appearance transitions for <UITabBarController: 0x197870>

I had the same error. I have a tab bar with 3 items and I was unconsciously trying to call the root view controller of item 1 in the item 2 of my tab bar using performSegueWithIdentifier.

What happens is that it calls the view controller and goes back to the root view controller of item 2 after a few seconds and logs that error.

Apparently, you cannot call the root view controller of an item to another item.

So instead of performSegueWithIdentifier

I used [self.parentViewController.tabBarController setSelectedIndex:0];

Hope this helps someone.

How do I hide anchor text without hiding the anchor?

You can put an image into ::before pseudoelement and set the same dimensions for as is the image + add overflow:hidden, like:

li a::before{
  content:url('img');
  width:20px;
  height:10px
}

a {
  overflow:hidden;
  width:20px;
  height:10px
}

retrieve links from web page using python and BeautifulSoup

just for getting the links, without B.soup and regex:

import urllib2
url="http://www.somewhere.com"
page=urllib2.urlopen(url)
data=page.read().split("</a>")
tag="<a href=\""
endtag="\">"
for item in data:
    if "<a href" in item:
        try:
            ind = item.index(tag)
            item=item[ind+len(tag):]
            end=item.index(endtag)
        except: pass
        else:
            print item[:end]

for more complex operations, of course BSoup is still preferred.

Relative path to absolute path in C#?

string exactPath = Path.GetFullPath(yourRelativePath);

works

Modifying CSS class property values on the fly with JavaScript / jQuery

This may be late to the discussion, but I needed something like what is being talked about here, but didn't find anything that really did what I wanted, and did it easily. What I needed was to hide and show numerous elements without explicitly visiting each element individually to update them in some way that changed the display style to and from hidden. So I came up with the following:

<style>
  /* The bulk of the css rules should go here or in an external css file */
  /* None of these rules will be changed, but may be overridden */
  .aclass { display: inline-block; width: 50px; height: 30px; }
</style>
<style id="style">
  /* Only the rules to be changed should go in this style */
  .bclass { display: inline-block; }
</style>
<script>
  //
  // This is a helper function that returns the named style as an object.
  // This could also be done in other ways.
  // 
  function setStyle() { return document.getElementById( 'style' ); }
</script>
<div id="d1" class="aclass" style="background-color: green;">
  Hi
</div>
<!-- The element to be shown and hidden --> 
<div id="d2" class="aclass bclass" style="background-color: yellow;">
  there
</div>
<div id="d3" class="aclass" style="background-color: lightblue;">
  sailor
</div>
<hr />
<!-- These buttons demonstrate hiding and showing the d3 dive element -->
<button onclick="setStyle().innerHTML = '.bclass { display: none; }';">
  Hide
</button>&nbsp;&nbsp;
<button onclick="setStyle().innerHTML = '.bclass { display: inline-block; }';">
  Show
</button>

By toggling the bclass rule in the embedded and named stylesheet, which comes after the any other relevant style sheets, in this case one with the aclass rule, I could update the just the display css rule in one place and have it override the aclass rule, which also had it's own display rule.

The beauty of this technique is that it is so simple, effectively one line that does the actual work, it doesn't require any libraries, such as JQuery or plug-ins, and the real work of updating all of the places where the change applies is performed by the browser's css core functionality, not in JavaScript. Also, it works in IE 9 and above, Chrome, Safari, Opera, and all of the other browsers that MicroSoft Edge could emulate, for desktop and tablet/phones devices.

Call Python function from JavaScript code

Typically you would accomplish this using an ajax request that looks like

var xhr = new XMLHttpRequest();
xhr.open("GET", "pythoncode.py?text=" + text, true);
xhr.responseType = "JSON";
xhr.onload = function(e) {
  var arrOfStrings = JSON.parse(xhr.response);
}
xhr.send();

How to call servlet through a JSP page

You could use <jsp:include> for this.

<jsp:include page="/servletURL" />

It's however usually the other way round. You call the servlet which in turn forwards to the JSP to display the results. Create a Servlet which does something like following in doGet() method.

request.setAttribute("result", "This is the result of the servlet call");
request.getRequestDispatcher("/WEB-INF/result.jsp").forward(request, response);

and in /WEB-INF/result.jsp

<p>The result is ${result}</p>

Now call the Servlet by the URL which matches its <url-pattern> in web.xml, e.g. http://example.com/contextname/servletURL.

Do note that the JSP file is explicitly placed in /WEB-INF folder. This will prevent the user from opening the JSP file individually. The user can only call the servlet in order to open the JSP file.


If your actual question is "How to submit a form to a servlet?" then you just have to specify the servlet URL in the HTML form action.

<form action="servletURL" method="post">

Its doPost() method will then be called.


See also:

Use CSS to make a span not clickable

CSS relates to visual styling and not behaviour, so the answer is no really.

You could however either use javascript to modify the behaviour or change the styling of the span in question so that it doesn't have the pointy finger, underline, etc. Styling it like that will still leave it clickable.

Even better, change your markup so that it reflects what you want it to do.

'Operation is not valid due to the current state of the object' error during postback

I didn't apply paging on my gridview and it extends to more than 600 records (with checkbox, buttons, etc.) and the value of 2001 didn't work. You may increase the value, say 10000 and test.

<appSettings>
<add key="aspnet:MaxHttpCollectionKeys" value="10000" />
</appSettings>

How to get rid of "Unnamed: 0" column in a pandas DataFrame?

This is usually caused by your CSV having been saved along with an (unnamed) index (RangeIndex).

(The fix would actually need to be done when saving the DataFrame, but this isn't always an option.)

Workaround: read_csv with index_col=[0] argument

IMO, the simplest solution would be to read the unnamed column as the index. Specify an index_col=[0] argument to pd.read_csv, this reads in the first column as the index. (Note the square brackets).

df = pd.DataFrame('x', index=range(5), columns=list('abc'))
df

   a  b  c
0  x  x  x
1  x  x  x
2  x  x  x
3  x  x  x
4  x  x  x

# Save DataFrame to CSV.
df.to_csv('file.csv')

<!- ->

pd.read_csv('file.csv')

   Unnamed: 0  a  b  c
0           0  x  x  x
1           1  x  x  x
2           2  x  x  x
3           3  x  x  x
4           4  x  x  x

# Now try this again, with the extra argument.
pd.read_csv('file.csv', index_col=[0])

   a  b  c
0  x  x  x
1  x  x  x
2  x  x  x
3  x  x  x
4  x  x  x

Note
You could have avoided this in the first place by using index=False if the output CSV was created in pandas, if your DataFrame does not have an index to begin with:

df.to_csv('file.csv', index=False)

But as mentioned above, this isn't always an option.


Stopgap Solution: Filtering with str.match

If you cannot modify the code to read/write the CSV file, you can just remove the column by filtering with str.match:

df 

   Unnamed: 0  a  b  c
0           0  x  x  x
1           1  x  x  x
2           2  x  x  x
3           3  x  x  x
4           4  x  x  x

df.columns
# Index(['Unnamed: 0', 'a', 'b', 'c'], dtype='object')

df.columns.str.match('Unnamed')
# array([ True, False, False, False])

df.loc[:, ~df.columns.str.match('Unnamed')]
 
   a  b  c
0  x  x  x
1  x  x  x
2  x  x  x
3  x  x  x
4  x  x  x

Searching in a ArrayList with custom objects for certain strings

Probably something like:

ArrayList<DataPoint> myList = new ArrayList<DataPoint>();
//Fill up myList with your Data Points

//Traversal
for(DataPoint myPoint : myList) {
    if(myPoint.getName() != null && myPoint.getName().equals("Michael Hoffmann")) {
        //Process data do whatever you want
        System.out.println("Found it!");
     }
}

Android Closing Activity Programmatically

you can use finishAffinity(); to close all the activity..

What is Dependency Injection?

The best definition I've found so far is one by James Shore:

"Dependency Injection" is a 25-dollar term for a 5-cent concept. [...] Dependency injection means giving an object its instance variables. [...].

There is an article by Martin Fowler that may prove useful, too.

Dependency injection is basically providing the objects that an object needs (its dependencies) instead of having it construct them itself. It's a very useful technique for testing, since it allows dependencies to be mocked or stubbed out.

Dependencies can be injected into objects by many means (such as constructor injection or setter injection). One can even use specialized dependency injection frameworks (e.g. Spring) to do that, but they certainly aren't required. You don't need those frameworks to have dependency injection. Instantiating and passing objects (dependencies) explicitly is just as good an injection as injection by framework.

Remove scrollbar from iframe

This is a last resort, but worth mentioning - you can use the ::-webkit-scrollbar pseudo-element on the iframe's parent to get rid of those famous 90's scroll bars.

::-webkit-scrollbar {
    width: 0px;
    height: 0px;
}

Edit: though it's relatively supported, ::-webkit-scrollbar may not suit all browsers. use with caution :)

How to manually include external aar package using new Gradle Android Build System

You can reference an aar file from a repository. A maven is an option, but there is a simpler solution: put the aar file in your libs directory and add a directory repository.

    repositories {
      mavenCentral()
      flatDir {
        dirs 'libs'
      }
    }

Then reference the library in the dependency section:

  dependencies {
        implementation 'com.actionbarsherlock:actionbarsherlock:4.4.0@aar'
}

You can check out Min'an blog post for more info.

Ignore <br> with CSS?

Yes you can ignore this <br>. You may need this especially in case of responsive design where you need to remove breaks for mobile devices.

HTML

<h2>

  Where ever you go <br class="break"> i am there.

</h2>

CSS for mobile example

/* Resize the browser window to check */

@media (max-width: 640px) 
{
  .break {display: none;}
}

Check out this Codepen:
https://codepen.io/fluidbrush/pen/pojGQyM

Div not expanding even with content inside

Putting a <br clear="all" /> after the last floated div worked the best for me. Thanks to Brent Fiare & Paul Waite for the info that floated divs will not expand the height of the parent div! This has been driving me nuts! ;-}

Mocking a class: Mock() or patch()?

mock.patch is a very very different critter than mock.Mock. patch replaces the class with a mock object and lets you work with the mock instance. Take a look at this snippet:

>>> class MyClass(object):
...   def __init__(self):
...     print 'Created MyClass@{0}'.format(id(self))
... 
>>> def create_instance():
...   return MyClass()
... 
>>> x = create_instance()
Created MyClass@4299548304
>>> 
>>> @mock.patch('__main__.MyClass')
... def create_instance2(MyClass):
...   MyClass.return_value = 'foo'
...   return create_instance()
... 
>>> i = create_instance2()
>>> i
'foo'
>>> def create_instance():
...   print MyClass
...   return MyClass()
...
>>> create_instance2()
<mock.Mock object at 0x100505d90>
'foo'
>>> create_instance()
<class '__main__.MyClass'>
Created MyClass@4300234128
<__main__.MyClass object at 0x100505d90>

patch replaces MyClass in a way that allows you to control the usage of the class in functions that you call. Once you patch a class, references to the class are completely replaced by the mock instance.

mock.patch is usually used when you are testing something that creates a new instance of a class inside of the test. mock.Mock instances are clearer and are preferred. If your self.sut.something method created an instance of MyClass instead of receiving an instance as a parameter, then mock.patch would be appropriate here.

Python: For each list element apply a function across the list

You can do this using list comprehensions and min() (Python 3.0 code):

>>> nums = [1,2,3,4,5]
>>> [(x,y) for x in nums for y in nums]
[(1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (2, 1), (2, 2), (2, 3), (2, 4), (2, 5), (3, 1), (3, 2), (3, 3), (3, 4), (3, 5), (4, 1), (4, 2), (4, 3), (4, 4), (4, 5), (5, 1), (5, 2), (5, 3), (5, 4), (5, 5)]
>>> min(_, key=lambda pair: pair[0]/pair[1])
(1, 5)

Note that to run this on Python 2.5 you'll need to either make one of the arguments a float, or do from __future__ import division so that 1/5 correctly equals 0.2 instead of 0.

How to determine an object's class?

Any use of any of the methods suggested is considered a code smell which is based in a bad OO design.

If your design is good, you should not find yourself needing to use getClass() or instanceof.

Any of the suggested methods will do, but just something to keep in mind, design-wise.

How to change sender name (not email address) when using the linux mail command for autosending mail?

You can use the "-r" option to set the sender address:

mail -r [email protected] -s ...

In case you also want to include your real name in the from-field, you can use the following format

mail -r "[email protected] (My Name)" -s "My Subject" ...

Html code as IFRAME source rather than a URL

use html5's new attribute srcdoc (srcdoc-polyfill) Docs

<iframe srcdoc="<html><body>Hello, <b>world</b>.</body></html>"></iframe>

Browser support - Tested in the following browsers:

Microsoft Internet Explorer
6, 7, 8, 9, 10, 11
Microsoft Edge
13, 14
Safari
4, 5.0, 5.1 ,6, 6.2, 7.1, 8, 9.1, 10
Google Chrome
14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24.0.1312.5 (beta), 25.0.1364.5 (dev), 55
Opera
11.1, 11.5, 11.6, 12.10, 12.11 (beta) , 42
Mozilla FireFox
3.0, 3.6, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18 (beta), 50

How to develop Desktop Apps using HTML/CSS/JavaScript?

It seems the solutions for HTML/JS/CSS desktop apps are in no short supply.

One solution I have just come across is TideSDK: http://www.tidesdk.org/, which seems very promising, looking at the documentation.

You can develop with Python, PHP or Ruby, and package it for Mac, Windows or Linux.

How to 'bulk update' with Django?

IT returns number of objects are updated in table.

update_counts = ModelClass.objects.filter(name='bar').update(name="foo")

You can refer this link to get more information on bulk update and create. Bulk update and Create

C++ - Hold the console window open?

hey first of all to include c++ functions you should use

include<iostream.h> instead of stdio .h

and to hold the output screen there is a simple command getch();
here, is an example:
   #include<iostream.h>
   #include<conio.h>
   void main()  \\or int main(); if you want
  {
    cout<<"c# is more advanced than c++";
    getch();
  }

thank you

Sending files using POST with HttpURLConnection

I have no idea why the HttpURLConnection class does not provide any means to send files without having to compose the file wrapper manually. Here's what I ended up doing, but if someone knows a better solution, please let me know.

Input data:

Bitmap bitmap = myView.getBitmap();

Static stuff:

String attachmentName = "bitmap";
String attachmentFileName = "bitmap.bmp";
String crlf = "\r\n";
String twoHyphens = "--";
String boundary =  "*****";

Setup the request:

HttpURLConnection httpUrlConnection = null;
URL url = new URL("http://example.com/server.cgi");
httpUrlConnection = (HttpURLConnection) url.openConnection();
httpUrlConnection.setUseCaches(false);
httpUrlConnection.setDoOutput(true);

httpUrlConnection.setRequestMethod("POST");
httpUrlConnection.setRequestProperty("Connection", "Keep-Alive");
httpUrlConnection.setRequestProperty("Cache-Control", "no-cache");
httpUrlConnection.setRequestProperty(
    "Content-Type", "multipart/form-data;boundary=" + this.boundary);

Start content wrapper:

DataOutputStream request = new DataOutputStream(
    httpUrlConnection.getOutputStream());

request.writeBytes(this.twoHyphens + this.boundary + this.crlf);
request.writeBytes("Content-Disposition: form-data; name=\"" +
    this.attachmentName + "\";filename=\"" + 
    this.attachmentFileName + "\"" + this.crlf);
request.writeBytes(this.crlf);

Convert Bitmap to ByteBuffer:

//I want to send only 8 bit black & white bitmaps
byte[] pixels = new byte[bitmap.getWidth() * bitmap.getHeight()];
for (int i = 0; i < bitmap.getWidth(); ++i) {
    for (int j = 0; j < bitmap.getHeight(); ++j) {
        //we're interested only in the MSB of the first byte, 
        //since the other 3 bytes are identical for B&W images
        pixels[i + j] = (byte) ((bitmap.getPixel(i, j) & 0x80) >> 7);
    }
}

request.write(pixels);

End content wrapper:

request.writeBytes(this.crlf);
request.writeBytes(this.twoHyphens + this.boundary + 
    this.twoHyphens + this.crlf);

Flush output buffer:

request.flush();
request.close();

Get response:

InputStream responseStream = new 
    BufferedInputStream(httpUrlConnection.getInputStream());

BufferedReader responseStreamReader = 
    new BufferedReader(new InputStreamReader(responseStream));

String line = "";
StringBuilder stringBuilder = new StringBuilder();

while ((line = responseStreamReader.readLine()) != null) {
    stringBuilder.append(line).append("\n");
}
responseStreamReader.close();

String response = stringBuilder.toString();

Close response stream:

responseStream.close();

Close the connection:

httpUrlConnection.disconnect();

PS: Of course I had to wrap the request in private class AsyncUploadBitmaps extends AsyncTask<Bitmap, Void, String>, in order to make the Android platform happy, because it doesn't like to have network requests on the main thread.

Opposite of append in jquery

You could use remove(). More information on jQuery remove().

$(this).children("ul").remove();

Note that this will remove all ul elements that are children.

How to execute multiple commands in a single line

Googling gives me this:


Command A & Command B

Execute Command A, then execute Command B (no evaluation of anything)


Command A | Command B

Execute Command A, and redirect all its output into the input of Command B


Command A && Command B

Execute Command A, evaluate the errorlevel after running and if the exit code (errorlevel) is 0, only then execute Command B


Command A || Command B

Execute Command A, evaluate the exit code of this command and if it's anything but 0, only then execute Command B


How to change the background color of the options menu?

The style attribute for the menu background is android:panelFullBackground.

Despite what the documentation says, it needs to be a resource (e.g. @android:color/black or @drawable/my_drawable), it will crash if you use a color value directly.

This will also get rid of the item borders that I was unable to change or remove using primalpop's solution.

As for the text color, I haven't found any way to set it through styles in 2.2 and I'm sure I've tried everything (which is how I discovered the menu background attribute). You would need to use primalpop's solution for that.

MySQL SELECT WHERE datetime matches day (and not necessarily time)

NEVER EVER use a selector like DATE(datecolumns) = '2012-12-24' - it is a performance killer:

  • it will calculate DATE() for all rows, including those, that don't match
  • it will make it impossible to use an index for the query

It is much faster to use

SELECT * FROM tablename 
WHERE columname BETWEEN '2012-12-25 00:00:00' AND '2012-12-25 23:59:59'

as this will allow index use without calculation.

EDIT

As pointed out by Used_By_Already, in the time since the inital answer in 2012, there have emerged versions of MySQL, where using '23:59:59' as a day end is no longer safe. An updated version should read

SELECT * FROM tablename 
WHERE columname >='2012-12-25 00:00:00'
AND columname <'2012-12-26 00:00:00'

The gist of the answer, i.e. the avoidance of a selector on a calculated expression, of course still stands.

Is there any way to delete local commits in Mercurial?

In addition to Samaursa's excelent answer, you can use the evolve extension's prune as a safe and recoverable version of strip that will allow you to go back in case you do anything wrong.

I have these alias on my .hgrc:

 # Prunes all draft changesets on the current repository
 reset-tree = prune -r "outgoing() and not obsolete()"
 # *STRIPS* all draft changesets on current repository. This deletes history.
 force-reset-tree = strip 'roots(outgoing())'

Note that prune also has --keep, just like strip, to keep the working directory intact allowing you to recommit the files.

Difference between break and continue statement

A break statement results in the termination of the statement to which it applies (switch, for, do, or while).

A continue statement is used to end the current loop iteration and return control to the loop statement.

How to get full REST request body using Jersey?

It does seem you would have to use a MessageBodyReader here. Here's an example, using jdom:

import org.jdom.Document;
import javax.ws.rs.ext.MessageBodyReader;
import javax.ws.rs.ext.Provider;
import javax.ws.rs.ext.MediaType;
import javax.ws.rs.ext.MultivaluedMap;
import java.lang.reflect.Type;
import java.lang.annotation.Annotation;
import java.io.InputStream;

@Provider // this annotation is necessary!
@ConsumeMime("application/xml") // this is a hint to the system to only consume xml mime types
public class XMLMessageBodyReader implements MessageBodyReader<Document> {
  private SAXBuilder builder = new SAXBuilder();

  public boolean isReadable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) {
    // check if we're requesting a jdom Document
    return Document.class.isAssignableFrom(type);
  }

  public Document readFrom(Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) {
    try {
      return builder.build(entityStream);
    }
    catch (Exception e) {
      // handle error somehow
    }
  } 
}

Add this class to the list of resources your jersey deployment will process (usually configured via web.xml, I think). You can then use this reader in one of your regular resource classes like this:

@Path("/somepath") @POST
public void handleXMLData(Document doc) {
  // do something with the document
}

I haven't verified that this works exactly as typed, but that's the gist of it. More reading here:

How to grep and replace

This works best for me on OS X:

grep -r -l 'searchtext' . | sort | uniq | xargs perl -e "s/matchtext/replacetext/" -pi

Source: http://www.praj.com.au/post/23691181208/grep-replace-text-string-in-files

angular js unknown provider

Yet another possibility.

I had unknown Provider <- <- nameOfMyService. The error was caused by the following syntax:

module.factory(['', function() { ... }]);

Angular was looking for the '' dependency.

Detecting scroll direction

Simple way to catch all scroll events (touch and wheel)

window.onscroll = function(e) {
  // print "false" if direction is down and "true" if up
  console.log(this.oldScroll > this.scrollY);
  this.oldScroll = this.scrollY;
}

Display help message with python argparse when script is called without any arguments

This isn't good (also, because intercepts all errors), but:

def _error(parser):
    def wrapper(interceptor):
        parser.print_help()

        sys.exit(-1)

    return wrapper

def _args_get(args=sys.argv[1:]):
    parser = argparser.ArgumentParser()

    parser.error = _error(parser)

    parser.add_argument(...)
    ...

Here is definition of the error function of the ArgumentParser class:

https://github.com/python/cpython/blob/276eb67c29d05a93fbc22eea5470282e73700d20/Lib/argparse.py#L2374

. As you see, following signature, it takes two arguments. However, functions outside the class nothing knows about first argument: self, because, roughly speaking, this is parameter for the class. (I know, that you know...) Thereby, just pass own self and message in _error(...) can't (

def _error(self, message):
    self.print_help()

    sys.exit(-1)

def _args_get(args=sys.argv[1:]):
    parser = argparser.ArgumentParser()

    parser.error = _error
    ...
...

will output:

...
"AttributeError: 'str' object has no attribute 'print_help'"

). You can pass parser (self) in _error function, by calling it:

def _error(self, message):
    self.print_help()

    sys.exit(-1)

def _args_get(args=sys.argv[1:]):
    parser = argparser.ArgumentParser()

    parser.error = _error(parser)
    ...
...

, but you don't want exit the program, right now. Then return it:

def _error(parser):
    def wrapper():
        parser.print_help()

        sys.exit(-1)

    return wrapper
...

. Nonetheless, parser doesn't know, that it has been modified, thus when an error occurs, it will send cause of it (by the way, its localized translation). Well, then intercept it:

def _error(parser):
    def wrapper(interceptor):
        parser.print_help()

        sys.exit(-1)

    return wrapper
...

. Now, when error occurs and parser will send cause of it, you'll intercept it, look at this, and... throw out.

MySQL: How to allow remote connection to mysql

I had to this challenge when working on a Java Project with MySQL server as the database.

Here's how I did it:

First, confirm that your MySQL server configuration to allow for remote connections. Use your preferred text editor to open the MySQL server configuration file:

sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf

Scroll down to the bind-address line and ensure that is either commented out or replaced with 0.0.0.0 (to allow all remote connections) or replaced with Ip-Addresses that you want remote connections from.

Once you make the necessary changes, save and exit the configuration file. Apply the changes made to the MySQL config file by restarting the MySQL service:

sudo systemctl restart mysql

Next, log into the MySQL server console on the server it was installed:

mysql -u root -p

Enter your mysql user password

Check the hosts that the user you want has access to already. In my case the user is root:

SELECT host FROM mysql.user WHERE user = "root";

This gave me this output:

+-----------+
| host      |
+-----------+
| localhost |
+-----------+

Next, I ran the command below to grant the root user remote access to the database named my_database:

USE my_database;
GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'my-password';

Note: % grants a user remote access from all hosts on a network. You can specify the Ip-Address of the individual hosts that you want to grant the user access from using the command - GRANT ALL PRIVILEGES ON *.* TO 'root'@'Ip-Address' IDENTIFIED BY 'my-password';

Afterwhich I checked the hosts that the user now has access to. In my case the user is root:

SELECT host FROM mysql.user WHERE user = "root";

This gave me this output:

+-----------+
| host      |
+-----------+
| %         |
| localhost |
+-----------+

Finally, you can try connecting to the MySQL server from another server using the command:

mysql -u username -h mysql-server-ip-address -p

Where u represents user, h represents mysql-server-ip-address and p represents password. So in my case it was:

mysql -u root -h 34.69.261.158 -p

Enter your mysql user password

You should get this output depending on your MySQL server version:

Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 4
Server version: 5.7.31 MySQL Community Server (GPL)

Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> 

Resources: How to Allow Remote Connections to MySQL

That's all.

I hope this helps

com.microsoft.sqlserver.jdbc.SQLServerDriver not found error

public static final String URL = "jdbc:sqlserver://localhost:1433;databaseName=dbName";
public static final String USERNAME = "xxxx";
public static final String PASSWORD = "xxxx";

/**
 *  This method
    @param args     command line argument
*/
public static void main(String[] args)
{
   try
   {
        Connection connection;
        DriverManager.registerDriver(new com.microsoft.sqlserver.jdbc.SQLServerDriver());   
        connection = DriverManager.getConnection(MainDriver.URL,MainDriver.USERNAME,
                        MainDriver.PASSWORD);
        String query ="select * from employee";
        Statement statement = connection.createStatement();
        ResultSet resultSet = statement.executeQuery(query);
        while(resultSet.next())
        {
            System.out.print("First Name: " + resultSet.getString("first_name"));
            System.out.println("  Last Name: " + resultSet.getString("last_name"));                
        }
   }catch(Exception ex)
   {
        ex.printStackTrace();
   }
}

How do you append to an already existing string?

teststr=$'test1\n'
teststr+=$'test2\n'
echo "$teststr"

Center a position:fixed element

Just add:

left: calc(-50vw + 50%);
right: calc(-50vw + 50%);
margin-left: auto;
margin-right: auto;

Start redis-server with config file

To start redis with a config file all you need to do is specifiy the config file as an argument:

redis-server /root/config/redis.rb

Instead of using and killing PID's I would suggest creating an init script for your service

I would suggest taking a look at the Installing Redis more properly section of http://redis.io/topics/quickstart. It will walk you through setting up an init script with redis so you can just do something like service redis_server start and service redis_server stop to control your server.

I am not sure exactly what distro you are using, that article describes instructions for a Debian based distro. If you are are using a RHEL/Fedora distro let me know, I can provide you with instructions for the last couple of steps, the config file and most of the other steps will be the same.

Is there a way to detach matplotlib plots so that the computation can continue?

I also wanted my plots to display run the rest of the code (and then keep on displaying) even if there is an error (I sometimes use plots for debugging). I coded up this little hack so that any plots inside this with statement behave as such.

This is probably a bit too non-standard and not advisable for production code. There is probably a lot of hidden "gotchas" in this code.

from contextlib import contextmanager

@contextmanager
def keep_plots_open(keep_show_open_on_exit=True, even_when_error=True):
    '''
    To continue excecuting code when plt.show() is called
    and keep the plot on displaying before this contex manager exits
    (even if an error caused the exit).
    '''
    import matplotlib.pyplot
    show_original = matplotlib.pyplot.show
    def show_replacement(*args, **kwargs):
        kwargs['block'] = False
        show_original(*args, **kwargs)
    matplotlib.pyplot.show = show_replacement

    pylab_exists = True
    try:
        import pylab
    except ImportError: 
        pylab_exists = False
    if pylab_exists:
        pylab.show = show_replacement

    try:
        yield
    except Exception, err:
        if keep_show_open_on_exit and even_when_error:
            print "*********************************************"
            print "Error early edition while waiting for show():" 
            print "*********************************************"
            import traceback
            print traceback.format_exc()
            show_original()
            print "*********************************************"
            raise
    finally:
        matplotlib.pyplot.show = show_original
        if pylab_exists:
            pylab.show = show_original
    if keep_show_open_on_exit:
        show_original()

# ***********************
# Running example
# ***********************
import pylab as pl
import time
if __name__ == '__main__':
    with keep_plots_open():
        pl.figure('a')
        pl.plot([1,2,3], [4,5,6])     
        pl.plot([3,2,1], [4,5,6])
        pl.show()

        pl.figure('b')
        pl.plot([1,2,3], [4,5,6])
        pl.show()

        time.sleep(1)
        print '...'
        time.sleep(1)
        print '...'
        time.sleep(1)
        print '...'
        this_will_surely_cause_an_error

If/when I implement a proper "keep the plots open (even if an error occurs) and allow new plots to be shown", I would want the script to properly exit if no user interference tells it otherwise (for batch execution purposes).

I may use something like a time-out-question "End of script! \nPress p if you want the plotting output to be paused (you have 5 seconds): " from https://stackoverflow.com/questions/26704840/corner-cases-for-my-wait-for-user-input-interruption-implementation.

When tracing out variables in the console, How to create a new line?

console.log('Hello, \n' + 
            'Text under your Header\n' + 
            '-------------------------\n' + 
            'More Text\n' +
            'Moree Text\n' +
            'Moooooer Text\n' );

This works great for me for text only, and easy on the eye.

How do I copy the contents of one ArrayList into another?

You can use such trick:

myObject = new ArrayList<Object>(myTempObject);

or use

myObject = (ArrayList<Object>)myTempObject.clone();

You can get some information about clone() method here

But you should remember, that all these ways will give you a copy of your List, not all of its elements. So if you change one of the elements in your copied List, it will also be changed in your original List.

How to show full column content in a Spark Dataframe?

results.show(false) will show you the full column content.

Show method by default limit to 20, and adding a number before false will show more rows.

WAMP shows error 'MSVCR100.dll' is missing when install

I encountered this problem when my operating system was in French, and I was installing Wampserver in English.

I am pretty sure that Microsoft Redistributable packages were installed since I was already working with Visual Studio. I think the issue may have been because of changes in path names with different languages. However, when I installed wampserver in French, everything worked perfectly.

What does the "~" (tilde/squiggle/twiddle) CSS selector mean?

The ~ selector is in fact the General sibling combinator (renamed to Subsequent-sibling combinator in selectors Level 4):

The general sibling combinator is made of the "tilde" (U+007E, ~) character that separates two sequences of simple selectors. The elements represented by the two sequences share the same parent in the document tree and the element represented by the first sequence precedes (not necessarily immediately) the element represented by the second one.

Consider the following example:

_x000D_
_x000D_
.a ~ .b {_x000D_
  background-color: powderblue;_x000D_
}
_x000D_
<ul>_x000D_
  <li class="b">1st</li>_x000D_
  <li class="a">2nd</li>_x000D_
  <li>3rd</li>_x000D_
  <li class="b">4th</li>_x000D_
  <li class="b">5th</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

.a ~ .b matches the 4th and 5th list item because they:

  • Are .b elements
  • Are siblings of .a
  • Appear after .a in HTML source order.

Likewise, .check:checked ~ .content matches all .content elements that are siblings of .check:checked and appear after it.

Jquery href click - how can I fire up an event?

It doesn't because the href value is not sign_up.It is #sign_up. Try like below, You need to add "#" to indicate the id of the href value.

$('a[href="#sign_up"]').click(function(){
  alert('Sign new href executed.'); 
}); 

DEMO: http://jsfiddle.net/pnGbP/

curl_init() function not working

This answer is for https request:

Curl doesn't have built-in root certificates (like most modern browser do). You need to explicitly point it to a cacert.pem file:

  curl_setopt($ch, CURLOPT_CAINFO, '/path/to/cert/file/cacert.pem');

Without this, curl cannot verify the certificate sent back via ssl. This same root certificate file can be used every time you use SSL in curl.

You can get the cacert.pem file here: http://curl.haxx.se/docs/caextract.html

Reference PHP cURL Not Working with HTTPS

JBoss debugging in Eclipse

VonC mentioned in his answer how to remote debug from Eclipse.

I would like to add that the JAVA_OPTS settings are already in run.conf.bat. You just have to uncomment them:

in JBOSS_HOME\bin\run.conf.bat on Windows:

rem # Sample JPDA settings for remote socket debugging
set "JAVA_OPTS=%JAVA_OPTS% -Xrunjdwp:transport=dt_socket,address=8787,server=y,suspend=n"

The Linux version is similar and is located at JBOSS_HOME/bin/run.conf

Detecting superfluous #includes in C/C++?

It's not automatic, but doxygen will produce dependency diagrams for #included files. You will have to go through them visually, but they can be very useful for getting a picture of what is using what.

How to use Class<T> in Java?

Just to throw in another example, the generic version of Class (Class<T>) allows one to write generic functions such as the one below.

public static <T extends Enum<T>>Optional<T> optionalFromString(
        @NotNull Class<T> clazz,
        String name
) {
    return Optional<T> opt = Optional.ofNullable(name)
            .map(String::trim)
            .filter(StringUtils::isNotBlank)
            .map(String::toUpperCase)
            .flatMap(n -> {
                try {
                    return Optional.of(Enum.valueOf(clazz, n));
                } catch (Exception e) {
                    return Optional.empty();
                }
            });
}

How do I export (and then import) a Subversion repository?

You can also use svnsync. This only requires read-only access on the source repository

more at svnbook

Custom Cell Row Height setting in storyboard is not responding

If you use UITableViewController, implement this method:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;

In the function of a row you can choose Height. For example,

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
       return 100;
    } 
    else {
       return 60;
    }
}

In this exemple, the first row height is 100 pixels, and the others are 60 pixels.

I hope this one can help you.