Programs & Examples On #Aspwizard

Configure hibernate (using JPA) to store Y/N for type Boolean instead of 0/1

The only way I've figured out how to do this is to have two properties for my class. One as the boolean for the programming API which is not included in the mapping. It's getter and setter reference a private char variable which is Y/N. I then have another protected property which is included in the hibernate mapping and it's getters and setters reference the private char variable directly.

EDIT: As has been pointed out there are other solutions that are directly built into Hibernate. I'm leaving this answer because it can work in situations where you're working with a legacy field that doesn't play nice with the built in options. On top of that there are no serious negative consequences to this approach.

No WebApplicationContext found: no ContextLoaderListener registered?

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

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

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

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

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

Read the spring reference here for spring mvc .

Save PHP array to MySQL?

There is no good way to store an array into a single field.

You need to examine your relational data and make the appropriate changes to your schema. See example below for a reference to this approach.

If you must save the array into a single field then the serialize() and unserialize() functions will do the trick. But you cannot perform queries on the actual content.

As an alternative to the serialization function there is also json_encode() and json_decode().

Consider the following array

$a = array(
    1 => array(
        'a' => 1,
        'b' => 2,
        'c' => 3
    ),
    2 => array(
        'a' => 1,
        'b' => 2,
        'c' => 3
    ),
);

To save it in the database you need to create a table like this

$c = mysql_connect($server, $username, $password);
mysql_select_db('test');
$r = mysql_query(
    'DROP TABLE IF EXISTS test');
$r = mysql_query(
    'CREATE TABLE test (
      id INTEGER UNSIGNED NOT NULL,
      a INTEGER UNSIGNED NOT NULL,
      b INTEGER UNSIGNED NOT NULL,
      c INTEGER UNSIGNED NOT NULL,
      PRIMARY KEY (id)
    )');

To work with the records you can perform queries such as these (and yes this is an example, beware!)

function getTest() {
    $ret = array();
    $c = connect();
    $query = 'SELECT * FROM test';
    $r = mysql_query($query,$c);
    while ($o = mysql_fetch_array($r,MYSQL_ASSOC)) {
        $ret[array_shift($o)] = $o;
    }
    mysql_close($c);
    return $ret;
}
function putTest($t) {
    $c = connect();
    foreach ($t as $k => $v) {
        $query = "INSERT INTO test (id,".
                implode(',',array_keys($v)).
                ") VALUES ($k,".
                implode(',',$v).
            ")";
        $r = mysql_query($query,$c);
    }
    mysql_close($c);
}

putTest($a);
$b = getTest();

The connect() function returns a mysql connection resource

function connect() {
    $c = mysql_connect($server, $username, $password);
    mysql_select_db('test');
    return $c;
}

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

HTML5 Boilerplate has a nice pre-made code for console problems fixing:

// Avoid `console` errors in browsers that lack a console.
(function() {
    var method;
    var noop = function () {};
    var methods = [
        'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
        'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
        'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
        'timeStamp', 'trace', 'warn'
    ];
    var length = methods.length;
    var console = (window.console = window.console || {});

    while (length--) {
        method = methods[length];

        // Only stub undefined methods.
        if (!console[method]) {
            console[method] = noop;
        }
    }
}());

As @plus- pointed in comments, latest version is available on their GitHub page

When to use reinterpret_cast?

First you have some data in a specific type like int here:

int x = 0x7fffffff://==nan in binary representation

Then you want to access the same variable as an other type like float: You can decide between

float y = reinterpret_cast<float&>(x);

//this could only be used in cpp, looks like a function with template-parameters

or

float y = *(float*)&(x);

//this could be used in c and cpp

BRIEF: it means that the same memory is used as a different type. So you could convert binary representations of floats as int type like above to floats. 0x80000000 is -0 for example (the mantissa and exponent are null but the sign, the msb, is one. This also works for doubles and long doubles.

OPTIMIZE: I think reinterpret_cast would be optimized in many compilers, while the c-casting is made by pointerarithmetic (the value must be copied to the memory, cause pointers couldn't point to cpu- registers).

NOTE: In both cases you should save the casted value in a variable before cast! This macro could help:

#define asvar(x) ({decltype(x) __tmp__ = (x); __tmp__; })

How do I flush the PRINT buffer in TSQL?

Another better option is to not depend on PRINT or RAISERROR and just load your "print" statements into a ##Temp table in TempDB or a permanent table in your database which will give you visibility to the data immediately via a SELECT statement from another window. This works the best for me. Using a permanent table then also serves as a log to what happened in the past. The print statements are handy for errors, but using the log table you can also determine the exact point of failure based on the last logged value for that particular execution (assuming you track the overall execution start time in your log table.)

Android ListView with different layouts for each row

If we need to show different type of view in list-view then its good to use getViewTypeCount() and getItemViewType() in adapter instead of toggling a view VIEW.GONE and VIEW.VISIBLE can be very expensive task inside getView() which will affect the list scroll.

Please check this one for use of getViewTypeCount() and getItemViewType() in Adapter.

Link : the-use-of-getviewtypecount

Removing Duplicate Values from ArrayList

Without a loop, No! Since ArrayList is indexed by order rather than by key, you can not found the target element without iterate the whole list.

A good practice of programming is to choose proper data structure to suit your scenario. So if Set suits your scenario the most, the discussion of implementing it with List and trying to find the fastest way of using an improper data structure makes no sense.

Create a user with all privileges in Oracle

There are 2 differences:

2 methods creating a user and granting some privileges to him

create user userName identified by password;
grant connect to userName;

and

grant connect to userName identified by password;

do exactly the same. It creates a user and grants him the connect role.

different outcome

resource is a role in oracle, which gives you the right to create objects (tables, procedures, some more but no views!). ALL PRIVILEGES grants a lot more of system privileges.

To grant a user all privileges run you first snippet or

grant all privileges to userName identified by password;

Text file with 0D 0D 0A line breaks

Just saying, this is also the value (kind of...) that is returned from php upon:

<?php var_dump(urlencode(PHP_EOL)); ?> 
    // Prints: string '%0D%0A' (length=6)-- used in 5.4.24 at least

Text blinking jQuery

This code will effectively make the element(s) blink without touching the layout (like fadeIn().fadeOut() will do) by just acting on the opacity ; There you go, blinking text ; usable for both good and evil :)

setInterval(function() {
  $('.blink').animate({ opacity: 1 }, 400).animate({ opacity: 0 }, 600);
}, 800);

PostgreSQL naming conventions

There isn't really a formal manual, because there's no single style or standard.

So long as you understand the rules of identifier naming you can use whatever you like.

In practice, I find it easier to use lower_case_underscore_separated_identifiers because it isn't necessary to "Double Quote" them everywhere to preserve case, spaces, etc.

If you wanted to name your tables and functions "@MyA??! ""betty"" Shard$42" you'd be free to do that, though it'd be pain to type everywhere.

The main things to understand are:

  • Unless double-quoted, identifiers are case-folded to lower-case, so MyTable, MYTABLE and mytable are all the same thing, but "MYTABLE" and "MyTable" are different;

  • Unless double-quoted:

    SQL identifiers and key words must begin with a letter (a-z, but also letters with diacritical marks and non-Latin letters) or an underscore (_). Subsequent characters in an identifier or key word can be letters, underscores, digits (0-9), or dollar signs ($).

  • You must double-quote keywords if you wish to use them as identifiers.

In practice I strongly recommend that you do not use keywords as identifiers. At least avoid reserved words. Just because you can name a table "with" doesn't mean you should.

Convert String To date in PHP

$d="05/Feb/2010:14:00:01";
$dr= date_create_from_format('d/M/Y:H:i:s', $d);
echo $dr->format('Y-m-d H:i:s');

here you get date string, give format specifier in ->format() according to format needed

Moving from JDK 1.7 to JDK 1.8 on Ubuntu

Just use these command lines:

sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update
sudo apt-get install oracle-java8-installer

If needed, you can also follow this Ubuntu tutorial.

How can you detect the version of a browser?

Here is the java version for somemone who whould like to do it on server side using the String returned by HttpServletRequest.getHeader("User-Agent");

It is working on the 70 different browser configuration I used for testing.

public static String decodeBrowser(String userAgent) {
    userAgent= userAgent.toLowerCase();
    String name = "unknown";
    String version = "0.0";
    Matcher userAgentMatcher = USER_AGENT_MATCHING_PATTERN.matcher(userAgent);
    if (userAgentMatcher.find()) {
      name = userAgentMatcher.group(1);
      version = userAgentMatcher.group(2);
      if ("trident".equals(name)) {
        name = "msie";
        Matcher tridentVersionMatcher = TRIDENT_MATCHING_PATTERN.matcher(userAgent);
        if (tridentVersionMatcher.find()) {
          version = tridentVersionMatcher.group(1);
        }
      }
    }
    return name + " " + version;
  }

  private static final Pattern USER_AGENT_MATCHING_PATTERN=Pattern.compile("(opera|chrome|safari|firefox|msie|trident(?=\\/))\\/?\\s*([\\d\\.]+)");
  private static final Pattern TRIDENT_MATCHING_PATTERN=Pattern.compile("\\brv[ :]+(\\d+(\\.\\d+)?)");

Can I underline text in an Android layout?

Just use the attribute in string resource file e.g.

<string name="example"><u>Example</u></string>

Query a parameter (postgresql.conf setting) like "max_connections"

You can use SHOW:

SHOW max_connections;

This returns the currently effective setting. Be aware that it can differ from the setting in postgresql.conf as there are a multiple ways to set run-time parameters in PostgreSQL. To reset the "original" setting from postgresql.conf in your current session:

RESET max_connections;

However, not applicable to this particular setting. The manual:

This parameter can only be set at server start.

To see all settings:

SHOW ALL;

There is also pg_settings:

The view pg_settings provides access to run-time parameters of the server. It is essentially an alternative interface to the SHOW and SET commands. It also provides access to some facts about each parameter that are not directly available from SHOW, such as minimum and maximum values.

For your original request:

SELECT *
FROM   pg_settings
WHERE  name = 'max_connections';

Finally, there is current_setting(), which can be nested in DML statements:

SELECT current_setting('max_connections');

Related:

How to add a scrollbar to an HTML5 table?

use this table into a DIV

<div class="tbl_container">
<table> .... </table>
</div>


.tbl_container{ overflow:auto; width: 500px;height: 200px; }

and beside this if you want to make it more beautiful and attractive use the jscollpane to customized your scrollbar..

Where are the recorded macros stored in Notepad++?

On Vista with virtualization on, the file is here. Note that the AppData folder is hidden. Either show hidden folders, or go straight to it by typing %AppData% in the address bar of Windows Explorer.

C:\Users\[user]\AppData\Roaming\Notepad++\shortcuts.xml

ReflectionException: Class ClassName does not exist - Laravel

I have the same problem with a class. I tried composer dump-autoload and php artisan config:clear but it did not solve my problem.

Then I decided to read my code to find the problem and I found the problem. The problem in my case was a missing comma in my class. See my Model code:

{
    protected
    $fillable = ['agente_id', 'matter_id', 'amendment_id', 'tipo_id'];

    public
    $rules = [
        'agente_id' => 'required', // <= See the comma
        'tipo_id' => 'required'
    ];

    public
    $niceNames = [
        'agente_id' => 'Membro', // <= This comma is missing on my code
        'tipo_id' => 'Membro'
    ];
}

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

The BitmapFactory.decode* methods, discussed in the Load Large Bitmaps Efficiently lesson, should not be executed on the main UI thread if the source data is read from disk or a network location (or really any source other than memory). The time this data takes to load is unpredictable and depends on a variety of factors (speed of reading from disk or network, size of image, power of CPU, etc.). If one of these tasks blocks the UI thread, the system flags your application as non-responsive and the user has the option of closing it (see Designing for Responsiveness for more information).

How do I pipe or redirect the output of curl -v?

The following worked for me:

Put your curl statement in a script named abc.sh

Now run:

sh abc.sh 1>stdout_output 2>stderr_output

You will get your curl's results in stdout_output and the progress info in stderr_output.

Disabling Controls in Bootstrap

try

$('#xxx').attr('disabled', true);

How to check if X server is running?

I often need to run an X command on a server that is running many X servers, so the ps based answers do not work. Naturally, $DISPLAY has to be set appropriately. To check that that is valid, use xset q in some fragment like:

if ! xset q &>/dev/null; then
    echo "No X server at \$DISPLAY [$DISPLAY]" >&2
    exit 1
fi

EDIT

Some people find that xset can pause for a annoying amount of time before deciding that $DISPLAY is not pointing at a valid X server (often when tcp/ip is the transport). The fix of course is to use timeout to keep the pause amenable, 1 second say.

if ! timeout 1s xset q &>/dev/null; then
    ?

Difference between classification and clustering in data mining?

enter image description here

Classification- A data-set can have different groups/ classes. red, green and black. Classification will try to find rules that divides them in different classes.

Custering- if a data-set is not having any class and you want to put them in some class/grouping, you do clustering. The purple circles above.

If classification rules are not good, you will have mis-classification in testing or ur rules are not correct enough.
if clustering is not good, you will have lot of outliers ie. data points not able to fall in any cluster.

getting the error: expected identifier or ‘(’ before ‘{’ token

you need to place the opening brace after main , not before it

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

int main(void)
{

CSS change button style after click

It is possible to do with CSS only by selecting active and focus pseudo element of the button.

button:active{
    background:olive;
}

button:focus{
    background:olive;
}

See codepen: http://codepen.io/fennefoss/pen/Bpqdqx

You could also write a simple jQuery click function which changes the background color.

HTML:

<button class="js-click">Click me!</button>

CSS:

button {
  background: none;
}

JavaScript:

  $( ".js-click" ).click(function() {
    $( ".js-click" ).css('background', 'green');
  });

Check out this codepen: http://codepen.io/fennefoss/pen/pRxrVG

How to read input with multiple lines in Java

Look into BufferedReader. If that isn't general/high-level enough, I recommend reading the I/O tutorial.

How to pick just one item from a generator?

I believe the only way is to get a list from the iterator then get the element you want from that list.

l = list(myfunct())
l[4]

How can I print a quotation mark in C?

This one also works:

printf("%c\n", printf("Here, I print some double quotes: "));

But if you plan to use it in an interview, make sure you can explain what it does.

EDIT: Following Eric Postpischil's comment, here's a version that doesn't rely on ASCII:

printf("%c\n", printf("%*s", '"', "Printing quotes: "));

The output isn't as nice, and it still isn't 100% portable (will break on some hypothetical encoding schemes), but it should work on EBCDIC.

What does `dword ptr` mean?

It is a 32bit declaration. If you type at the top of an assembly file the statement [bits 32], then you don't need to type DWORD PTR. So for example:

[bits 32]
.
.
and  [ebp-4], 0

Meaning of *& and **& in C++

*& signifies the receiving the pointer by reference. It means it is an alias for the passing parameter. So, it affects the passing parameter.

#include <iostream>
using namespace std;

void foo(int *ptr)
{
    ptr = new int(50);    // Modifying the pointer to point to a different location
    cout << "In foo:\t" << *ptr << "\n"; 
    delete ptr ;
}

void bar(int *& ptr)
{
    ptr = new int(80);    // Modifying the pointer to point to a different location
    cout << "In bar:\t" << *ptr << "\n"; 
    // Deleting the pointer will result the actual passed parameter dangling
}
int main()
{
    int temp = 100 ;
    int *p = &temp ;

    cout << "Before foo:\t" << *p << "\n";
    foo(p) ;
    cout << "After foo:\t" << *p << "\n";

    cout << "Before bar:\t" << *p << "\n";
    bar(p) ;
    cout << "After bar:\t" << *p << "\n";

    delete p;

    return 0;
}

Output:

Before foo: 100
In foo: 50
After foo:  100
Before bar: 100
In bar: 80
After bar:  80

How can I delete all Git branches which have been merged?

Based on some of these answers I made my own Bash script to do it too!

It uses git branch --merged and git branch -d to delete the branches that have been merged and prompts you for each of the branches before deleting.

merged_branches(){
  local current_branch=$(git rev-parse --abbrev-ref HEAD)
  for branch in $(git branch --merged | cut -c3-)
    do
      echo "Branch $branch is already merged into $current_branch."
      echo "Would you like to delete it? [Y]es/[N]o "
      read REPLY
      if [[ $REPLY =~ ^[Yy] ]]; then
        git branch -d $branch
      fi
  done
}

REACT - toggle class onclick

Use state. Reacts docs are here.

class MyComponent extends Component {
    constructor(props) {
        super(props);
        this.addActiveClass= this.addActiveClass.bind(this);
        this.state = {
            active: false,
        };
    }
    toggleClass() {
        const currentState = this.state.active;
        this.setState({ active: !currentState });
    };

    render() {
        return (
            <div 
                className={this.state.active ? 'your_className': null} 
                onClick={this.toggleClass} 
            >
                <p>{this.props.text}</p>
            </div>
        )
  }
}

class Test extends Component {
    render() {
        return (
            <div>
                <MyComponent text={'1'} />
                <MyComponent text={'2'} />
            </div>
        );
    }
}

Json.net serialize/deserialize derived types?

Use this JsonKnownTypes, it's very similar way to use, it just add discriminator to json:

[JsonConverter(typeof(JsonKnownTypeConverter<BaseClass>))]
[JsonKnownType(typeof(Base), "base")]
[JsonKnownType(typeof(Derived), "derived")]
public class Base
{
    public string Name;
}
public class Derived : Base
{
    public string Something;
}

Now when you serialize object in json will be add "$type" with "base" and "derived" value and it will be use for deserialize

Serialized list example:

[
    {"Name":"some name", "$type":"base"},
    {"Name":"some name", "Something":"something", "$type":"derived"}
]

JPA: How to get entity based on field value other than ID?

Write a custom method like this:

public Object findByYourField(Class entityClass, String yourFieldValue)
{
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Object> criteriaQuery = criteriaBuilder.createQuery(entityClass);
    Root<Object> root = criteriaQuery.from(entityClass);
    criteriaQuery.select(root);

    ParameterExpression<String> params = criteriaBuilder.parameter(String.class);
    criteriaQuery.where(criteriaBuilder.equal(root.get("yourField"), params));

    TypedQuery<Object> query = entityManager.createQuery(criteriaQuery);
    query.setParameter(params, yourFieldValue);

    List<Object> queryResult = query.getResultList();

    Object returnObject = null;

    if (CollectionUtils.isNotEmpty(queryResult)) {
        returnObject = queryResult.get(0);
    }

    return returnObject;
}

Using Spring RestTemplate in generic method with generic parameter

I feel like there's a much easier way to do this... Just define a class with the type parameters that you want. e.g.:


final class MyClassWrappedByResponse extends ResponseWrapper<MyClass> {
    private static final long serialVersionUID = 1L;
}

Now change your code above to this and it should work:

public ResponseWrapper<MyClass> makeRequest(URI uri) {
    ResponseEntity<MyClassWrappedByResponse> response = template.exchange(
        uri,
        HttpMethod.POST,
        null,
        MyClassWrappedByResponse.class
    return response;
}

Program to find largest and smallest among 5 numbers without using array

You can do something like this:

int min_num = INT_MAX;  //  2^31-1
int max_num = INT_MIN;  // -2^31
int input;
while (!std::cin.eof()) {
    std::cin >> input;
    min_num = min(input, min_num);
    max_num = max(input, max_num);
}
cout << "min: " << min_num; 
cout << "max: " << max_num;

This reads numbers from standard input until eof (it does not care how many you have - 5 or 1,000,000).

How to copy a file along with directory structure/path using python?

take a look at shutil. shutil.copyfile(src, dst) will copy a file to another file.

Note that shutil.copyfile will not create directories that do not already exist. for that, use os.makedirs

'any' vs 'Object'

Adding to Alex's answer and simplifying it:

Objects are more strict with their use and hence gives the programmer more compile time "evaluation" power and hence in a lot of cases provide more "checking capability" and coould prevent any leaks, whereas any is a more generic term and a lot of compile time checks might hence be ignored.

Android emulator: How to monitor network traffic?

I would suggest you use Wireshark.

Steps:

  1. Install Wireshark.
  2. Select the network connection that you are using for the calls(for eg, select the Wifi if you are using it)
  3. There will be many requests and responses, close extra applications.
  4. Usually the requests are in green color, once you spot your request, copy the destination address and use the filter on top by typing ip.dst==52.187.182.185 by putting the destination address.

You can make use of other filtering techniques mentioned here to get specific traffic.

INSERT INTO TABLE from comma separated varchar-list

Sql Server does not (on my knowledge) have in-build Split function. Split function in general on all platforms would have comma-separated string value to be split into individual strings. In sql server, the main objective or necessary of the Split function is to convert a comma-separated string value (‘abc,cde,fgh’) into a temp table with each string as rows.

The below Split function is Table-valued function which would help us splitting comma-separated (or any other delimiter value) string to individual string.

CREATE FUNCTION dbo.Split(@String varchar(8000), @Delimiter char(1))       
returns @temptable TABLE (items varchar(8000))       
as       
begin       
    declare @idx int       
    declare @slice varchar(8000)       

    select @idx = 1       
        if len(@String)<1 or @String is null  return       

    while @idx!= 0       
    begin       
        set @idx = charindex(@Delimiter,@String)       
        if @idx!=0       
            set @slice = left(@String,@idx - 1)       
        else       
            set @slice = @String       

        if(len(@slice)>0)  
            insert into @temptable(Items) values(@slice)       

        set @String = right(@String,len(@String) - @idx)       
        if len(@String) = 0 break       
    end   
return       
end  

select top 10 * from dbo.split('Chennai,Bangalore,Mumbai',',')

the complete can be found at follownig link http://www.logiclabz.com/sql-server/split-function-in-sql-server-to-break-comma-separated-strings-into-table.aspx

Laravel Migration Change to Make a Column Nullable

For Laravel 4.2, Unnawut's answer above is the best one. But if you are using table prefix, then you need to alter your code a little.

function up()
{
    $table_prefix = DB::getTablePrefix();
    DB::statement('ALTER TABLE `' . $table_prefix . 'throttle` MODIFY `user_id` INTEGER UNSIGNED NULL;');
}

And to make sure you can still rollback your migration, we'll do the down() as well.

function down()
{
    $table_prefix = DB::getTablePrefix();
    DB::statement('ALTER TABLE `' . $table_prefix . 'throttle` MODIFY `user_id` INTEGER UNSIGNED NOT NULL;');
}

Exec : display stdout "live"

Don't use exec. Use spawn which is an EventEmmiter object. Then you can listen to stdout/stderr events (spawn.stdout.on('data',callback..)) as they happen.

From NodeJS documentation:

var spawn = require('child_process').spawn,
    ls    = spawn('ls', ['-lh', '/usr']);

ls.stdout.on('data', function (data) {
  console.log('stdout: ' + data.toString());
});

ls.stderr.on('data', function (data) {
  console.log('stderr: ' + data.toString());
});

ls.on('exit', function (code) {
  console.log('child process exited with code ' + code.toString());
});

exec buffers the output and usually returns it when the command has finished executing.

How to convert a string to integer in C?

There is strtol which is better IMO. Also I have taken a liking in strtonum, so use it if you have it (but remember it's not portable):

long long
     strtonum(const char *nptr, long long minval, long long maxval,
     const char **errstr);

You might also be interested in strtoumax and strtoimax which are standard functions in C99. For example you could say:

uintmax_t num = strtoumax(s, NULL, 10);
if (num == UINTMAX_MAX && errno == ERANGE)
    /* Could not convert. */

Anyway, stay away from atoi:

The call atoi(str) shall be equivalent to:

(int) strtol(str, (char **)NULL, 10)

except that the handling of errors may differ. If the value cannot be represented, the behavior is undefined.

Best way to find os name and version in Unix/Linux platform

With quotes:

cat /etc/*-release | grep "PRETTY_NAME" | sed 's/PRETTY_NAME=//g'

gives output as:

"CentOS Linux 7 (Core)"

Without quotes:

cat /etc/*-release | grep "PRETTY_NAME" | sed 's/PRETTY_NAME=//g' | sed 's/"//g'

gives output as:

CentOS Linux 7 (Core)

python filter list of dictionaries based on key value

You can try a list comp

>>> exampleSet = [{'type':'type1'},{'type':'type2'},{'type':'type2'}, {'type':'type3'}]
>>> keyValList = ['type2','type3']
>>> expectedResult = [d for d in exampleSet if d['type'] in keyValList]
>>> expectedResult
[{'type': 'type2'}, {'type': 'type2'}, {'type': 'type3'}]

Another way is by using filter

>>> list(filter(lambda d: d['type'] in keyValList, exampleSet))
[{'type': 'type2'}, {'type': 'type2'}, {'type': 'type3'}]

How can I find where I will be redirected using cURL?

To make cURL follow a redirect, use:

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

Erm... I don't think you're actually executing the curl... Try:

curl_exec($ch);

...after setting the options, and before the curl_getinfo() call.

EDIT: If you just want to find out where a page redirects to, I'd use the advice here, and just use Curl to grab the headers and extract the Location: header from them:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
if (preg_match('~Location: (.*)~i', $result, $match)) {
   $location = trim($match[1]);
}

MongoDB: Combine data from multiple collections into one..how?

If there is no bulk insert into mongodb, we loop all objects in the small_collection and insert them one by one into the big_collection:

db.small_collection.find().forEach(function(obj){ 
   db.big_collection.insert(obj)
});

Jackson with JSON: Unrecognized field, not marked as ignorable

This may be a very late response, but just changing the POJO to this should solve the json string provided in the problem (since, the input string is not in your control as you said):

public class Wrapper {
    private List<Student> wrapper;
    //getters & setters here
}

ASP.NET Core 1.0 on IIS error 502.5

For me it was that the connectionString in Startup.cs was null in:

services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

and it was null because the application was not looking into appsettings.json for the connection string.

Had to change Program.cs to:

public static void Main(string[] args)
{
    BuildWebHost(args).Run();
}

public static IWebHost BuildWebHost(string[] args) =>
     WebHost.CreateDefaultBuilder(args)
     .ConfigureAppConfiguration((context, builder) => builder.SetBasePath(context.HostingEnvironment.ContentRootPath)
     .AddJsonFile("appsettings.json").Build())
     .UseStartup<Startup>().Build();

How do I unlock a SQLite database?

I ran into this same problem on Mac OS X 10.5.7 running Python scripts from a terminal session. Even though I had stopped the scripts and the terminal window was sitting at the command prompt, it would give this error the next time it ran. The solution was to close the terminal window and then open it up again. Doesn't make sense to me, but it worked.

How to check if an object is defined?

If a class type is not defined, you'll get a compiler error if you try to use the class, so in that sense you should have to check.

If you have an instance, and you want to ensure it's not null, simply check for null:

if (value != null)
{
    // it's not null. 
}

How to select the first row of each group?

This is a exact same of zero323's answer but in SQL query way.

Assuming that dataframe is created and registered as

df.createOrReplaceTempView("table")
//+----+--------+----------+
//|Hour|Category|TotalValue|
//+----+--------+----------+
//|0   |cat26   |30.9      |
//|0   |cat13   |22.1      |
//|0   |cat95   |19.6      |
//|0   |cat105  |1.3       |
//|1   |cat67   |28.5      |
//|1   |cat4    |26.8      |
//|1   |cat13   |12.6      |
//|1   |cat23   |5.3       |
//|2   |cat56   |39.6      |
//|2   |cat40   |29.7      |
//|2   |cat187  |27.9      |
//|2   |cat68   |9.8       |
//|3   |cat8    |35.6      |
//+----+--------+----------+

Window function :

sqlContext.sql("select Hour, Category, TotalValue from (select *, row_number() OVER (PARTITION BY Hour ORDER BY TotalValue DESC) as rn  FROM table) tmp where rn = 1").show(false)
//+----+--------+----------+
//|Hour|Category|TotalValue|
//+----+--------+----------+
//|1   |cat67   |28.5      |
//|3   |cat8    |35.6      |
//|2   |cat56   |39.6      |
//|0   |cat26   |30.9      |
//+----+--------+----------+

Plain SQL aggregation followed by join:

sqlContext.sql("select Hour, first(Category) as Category, first(TotalValue) as TotalValue from " +
  "(select Hour, Category, TotalValue from table tmp1 " +
  "join " +
  "(select Hour as max_hour, max(TotalValue) as max_value from table group by Hour) tmp2 " +
  "on " +
  "tmp1.Hour = tmp2.max_hour and tmp1.TotalValue = tmp2.max_value) tmp3 " +
  "group by tmp3.Hour")
  .show(false)
//+----+--------+----------+
//|Hour|Category|TotalValue|
//+----+--------+----------+
//|1   |cat67   |28.5      |
//|3   |cat8    |35.6      |
//|2   |cat56   |39.6      |
//|0   |cat26   |30.9      |
//+----+--------+----------+

Using ordering over structs:

sqlContext.sql("select Hour, vs.Category, vs.TotalValue from (select Hour, max(struct(TotalValue, Category)) as vs from table group by Hour)").show(false)
//+----+--------+----------+
//|Hour|Category|TotalValue|
//+----+--------+----------+
//|1   |cat67   |28.5      |
//|3   |cat8    |35.6      |
//|2   |cat56   |39.6      |
//|0   |cat26   |30.9      |
//+----+--------+----------+

DataSets way and don't dos are same as in original answer

How to enable zoom controls and pinch zoom in a WebView?

Check if you don't have a ScrollView wrapping your Webview.

In my case that was the problem. It seems ScrollView gets in the way of the pinch gesture.

To fix it, just take your Webview outside the ScrollView.

pip installs packages successfully, but executables not found from command line

On Windows, you need to add the path %USERPROFILE%\AppData\Roaming\Python\Scripts to your path.

How to use new PasswordEncoder from Spring Security

Here is the implementation of BCrypt which is working for me.

in spring-security.xml

<authentication-manager >
    <authentication-provider ref="authProvider"></authentication-provider>  
    </authentication-manager>
<beans:bean id="authProvider" class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
  <beans:property name="userDetailsService" ref="userDetailsServiceImpl" />
  <beans:property name="passwordEncoder" ref="encoder" />
</beans:bean>
<!-- For hashing and salting user passwords -->
    <beans:bean id="encoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"/>

In java class

PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
String hashedPassword = passwordEncoder.encode(yourpassword);

For more detailed example of spring security Click Here

Hope this will help.

Thanks

Python Pandas User Warning: Sorting because non-concatenation axis is not aligned

jezrael's answer is good, but did not answer a question I had: Will getting the "sort" flag wrong mess up my data in any way? The answer is apparently "no", you are fine either way.

from pandas import DataFrame, concat

a = DataFrame([{'a':1,      'c':2,'d':3      }])
b = DataFrame([{'a':4,'b':5,      'd':6,'e':7}])

>>> concat([a,b],sort=False)
   a    c  d    b    e
0  1  2.0  3  NaN  NaN
0  4  NaN  6  5.0  7.0

>>> concat([a,b],sort=True)
   a    b    c  d    e
0  1  NaN  2.0  3  NaN
0  4  5.0  NaN  6  7.0

Can grep show only words that match search pattern?

$ grep -w

Excerpt from grep man page:

-w: Select only those lines containing matches that form whole words. The test is that the matching substring must either be at the beginning of the line, or preceded by a non-word constituent character.

SSLHandshakeException: No subject alternative names present

Thanks,Bruno for giving me heads up on Common Name and Subject Alternative Name. As we figured out certificate was generated with CN with DNS name of network and asked for regeneration of new certificate with Subject Alternative Name entry i.e. san=ip:10.0.0.1. which is the actual solution.

But, we managed to find out a workaround with which we can able to run on development phase. Just add a static block in the class from which we are making ssl connection.

static {
    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier()
        {
            public boolean verify(String hostname, SSLSession session)
            {
                // ip address of the service URL(like.23.28.244.244)
                if (hostname.equals("23.28.244.244"))
                    return true;
                return false;
            }
        });
}

If you happen to be using Java 8, there is a much slicker way of achieving the same result:

static {
    HttpsURLConnection.setDefaultHostnameVerifier((hostname, session) -> hostname.equals("127.0.0.1"));
}

MySQL - length() vs char_length()

varchar(10) will store 10 characters, which may be more than 10 bytes. In indexes, it will allocate the maximium length of the field - so if you are using UTF8-mb4, it will allocate 40 bytes for the 10 character field.

org.hibernate.MappingException: Could not determine type for: java.util.Set

Had this issue just today and discovered that I inadvertently left off the @ManyToMany annotation above the @JoinTable annotation.

How do I make a relative reference to another workbook in Excel?

easier & shorter via indirect: INDIRECT("'..\..\..\..\Supply\SU\SU.ods'#$Data.$A$2:$AC$200")

however indirect() has performance drawbacks if lot of links in workbook

I miss construct like: ['../Data.ods']#Sheet1.A1 in LibreOffice. The intention is here: if I create a bunch of master workbooks and depending report workbooks in limited subtree of directories in source file system, I can zip whole directory subtree with complete package of workbooks and send it to other cooperating person per Email or so. It will be saved in some other absolute pazth on target system, but linkage works again in new absolute path because it was coded relatively to subtree root.

How to set limits for axes in ggplot2 R plots?

Quick note: if you're also using coord_flip() to flip the x and the y axis, you won't be able to set range limits using coord_cartesian() because those two functions are exclusive (see here).

Fortunately, this is an easy fix; set your limits within coord_flip() like so:

p + coord_flip(ylim = c(3,5), xlim = c(100, 400))

This just alters the visible range (i.e. doesn't remove data points).

Rails server says port already used, how to kill that process?

If you are on windows machine follow these steps.

c:/project/
cd tmp
c:/project/tmp
cd pids
c:/project/tmp/pids
dir

There you will a file called server.pid

delete it.

c:/project/tmp/pid> del *.pid

Thats it.

EDIT: Please refer this

How to disable back swipe gesture in UINavigationController on iOS 7

My method. One gesture recognizer to rule them all:

class DisabledGestureViewController: UIViewController: UIGestureRecognizerDelegate {
    override func viewDidLoad() {
        super.viewDidLoad()
        navigationController!.interactivePopGestureRecognizer!.delegate = self
    }

    func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool {
        // Prevent going back to the previous view
        return !(navigationController!.topViewController is DisabledGestureViewController)
    }
}

Important: don't reset the delegate anywhere in the navigation stack: navigationController!.interactivePopGestureRecognizer!.delegate = nil

What's the difference between utf8_general_ci and utf8_unicode_ci?

In brief words:

If you need better sorting order - use utf8_unicode_ci (this is the preferred method),

but if you utterly interested in performance - use utf8_general_ci, but know that it is a little outdated.

The differences in terms of performance are very slight.

How to flush route table in windows?

You can open a command prompt and do a

route print

and see your current routing table.

You can modify it by

route add    d.d.d.d mask m.m.m.m g.g.g.g 
route delete d.d.d.d mask m.m.m.m g.g.g.g 
route change d.d.d.d mask m.m.m.m g.g.g.g

these seem to work

I run a ping d.d.d.d -t change the route and it changes. (my test involved routing to a dead route and the ping stopped)

How to print VARCHAR(MAX) using Print Statement?

Came across this question and wanted something more simple... Try the following:

SELECT [processing-instruction(x)]=@Script FOR XML PATH(''),TYPE

Can I save input from form to .txt in HTML, using JAVASCRIPT/jQuery, and then use it?

Or this will work too the same way but without a save as choice:

<!DOCTYPE html>
<html>
<head>


<script type='text/javascript'>//<![CDATA[
window.onload=function(){
(function () {
var textFile = null,
  makeTextFile = function (text) {
    var data = new Blob([text], {type: 'text/plain'});

    // If we are replacing a previously generated file we need to
    // manually revoke the object URL to avoid memory leaks.
    if (textFile !== null) {
      window.URL.revokeObjectURL(textFile);
    }

    textFile = window.URL.createObjectURL(data);

    return textFile;
  };


  var create = document.getElementById('create'),
    textbox = document.getElementById('textbox');

  create.addEventListener('click', function () {
    var link = document.getElementById('downloadlink');
    link.href = makeTextFile(textbox.value);
    link.style.display = 'block';
  }, false);
})();

}//]]> 

</script>


</head>

<body>
  <textarea id="textbox">Type something here</textarea> <button id="create">Create file</button> <a download="info.txt" id="downloadlink" style="display: none">Download</a>


  <script>
  // tell the embed parent frame the height of the content
  if (window.parent && window.parent.parent){
    window.parent.parent.postMessage(["resultsFrame", {
      height: document.body.getBoundingClientRect().height,
      slug: "qm5AG"
    }], "*")
  }
</script>

</body>

</html>

Sniffing/logging your own Android Bluetooth traffic

Android 4.4 (Kit Kat) does have a new sniffing capability for Bluetooth. You should give it a try.

If you don’t own a sniffing device however, you aren’t necessarily out of luck. In many cases we can obtain positive results with a new feature introduced in Android 4.4: the ability to capture all Bluetooth HCI packets and save them to a file.

When the Analyst has finished populating the capture file by running the application being tested, he can pull the file generated by Android into the external storage of the device and analyze it (with Wireshark, for example).

Once this setting is activated, Android will save the packet capture to /sdcard/btsnoop_hci.log to be pulled by the analyst and inspected.

Type the following in case /sdcard/ is not the right path on your particular device:

adb shell echo \$EXTERNAL_STORAGE

We can then open a shell and pull the file: $adb pull /sdcard/btsnoop_hci.log and inspect it with Wireshark, just like a PCAP collected by sniffing WiFi traffic for example, so it is very simple and well supported:

screenshot of wireshark capture using Android HCI Snoop

[source]

You can enable this by going to Settings->Developer Options, then checking the box next to "Bluetooth HCI Snoop Log."

Undefined symbols for architecture i386

A bit late to the party but might be valuable to someone with this error..

I just straight copied a bunch of files into an Xcode project, if you forget to add them to your projects Build Phases you will get the error "Undefined symbols for architecture i386". So add your implementation files to Compile Sources, and Xib files to Copy Bundle Resources.

The error was telling me that there was no link to my classes simply because they weren't included in the Compile Sources, quite obvious really but may save someone a headache.

How to copy a file from one directory to another using PHP?

copy will do this. Please check the php-manual. Simple Google search should answer your last two questions ;)

jQuery ajax post file field

This should help. How can I upload files asynchronously?

As the post suggest I recommend a plugin located here http://malsup.com/jquery/form/#code-samples

BackgroundWorker vs background Thread

I want to point out one behavior of BackgroundWorker class that wasn't mentioned yet. You can make a normal Thread to run in background by setting the Thread.IsBackground property.

Background threads are identical to foreground threads, except that background threads do not prevent a process from terminating. [1]

You can test this behavoir by calling the following method in the constructor of your form window.

void TestBackgroundThread()
{
    var thread = new Thread((ThreadStart)delegate()
    {
        long count = 0;
        while (true)
        {
            count++;
            Debug.WriteLine("Thread loop count: " + count);
        }
    });

    // Choose one option:
    thread.IsBackground = true; // <--- This will make the thread run in background
    thread.IsBackground = false; // <--- This will delay program termination

    thread.Start();
}

When the IsBackground property is set to true and you close the window, then your application will terminate normaly.

But when the IsBackground property is set to false (by default) and you close the window, then just the window will disapear but the process will still keep running.

The BackgroundWorker class utilize a Thread that runs in the background.

How to align form at the center of the page in html/css

I would just use table and not the form. Its done by using margin.

table {
  margin: 0 auto;
}

also try using something like

table td {
    padding-bottom: 5px;
}

instead of <br />

and also your input should end with /> e.g:

<input type="password" name="cpwd" />

Windows Explorer "Command Prompt Here"

On vista and windows 7:

  • Alt+d -> it will put focus on the address bar of the explorer window
  • and then, type the name of any program you would launch using WIN+r
  • hit Enter

The program will start with its current directory set to that of the explorer instance. e.g.:python, ghci, powershell, cmd, etc...

Show loading image while $.ajax is performed

The "image" people generally show during an ajax call is an animated gif. Since there is no way to determine the percent complete of the ajax request, the animated gifs used are indeterminate spinners. This is just an image repeating over and over like a ball of circles of varying sizes. A good site to create your own custom indeterminate spinner is http://ajaxload.info/

PHP Get Highest Value from Array

Here a solution inside an exercise:

function high($sentence)
{
    $alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'ñ', 'o', 'p', 'q', 'r', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
    $alphabet = array_flip($alphabet);

    $words = explode(" ", $sentence);

    foreach ($words as $word) {
        $letters = str_split($word);
        $points = 0;
        foreach ($letters as $letter)
            $points += $alphabet[$letter];
        $score[$word] = $points;
    }

    $value = max($score);
    $key = array_search($value, $score);

    return $key;
}

echo high("what time are we climbing up the volcano");

How do I use HTML as the view engine in Express?

No view engine is necessary, if you want to use angular with simple plain html file. Here's how to do it: In your route.js file:

router.get('/', (req, res) => {
   res.sendFile('index.html', {
     root: 'yourPathToIndexDirectory'
   });
});

How to do multiline shell script in Ansible

Ansible uses YAML syntax in its playbooks. YAML has a number of block operators:

  • The > is a folding block operator. That is, it joins multiple lines together by spaces. The following syntax:

    key: >
      This text
      has multiple
      lines
    

    Would assign the value This text has multiple lines\n to key.

  • The | character is a literal block operator. This is probably what you want for multi-line shell scripts. The following syntax:

    key: |
      This text
      has multiple
      lines
    

    Would assign the value This text\nhas multiple\nlines\n to key.

You can use this for multiline shell scripts like this:

- name: iterate user groups
  shell: |
    groupmod -o -g {{ item['guid'] }} {{ item['username'] }} 
    do_some_stuff_here
    and_some_other_stuff
  with_items: "{{ users }}"

There is one caveat: Ansible does some janky manipulation of arguments to the shell command, so while the above will generally work as expected, the following won't:

- shell: |
    cat <<EOF
    This is a test.
    EOF

Ansible will actually render that text with leading spaces, which means the shell will never find the string EOF at the beginning of a line. You can avoid Ansible's unhelpful heuristics by using the cmd parameter like this:

- shell:
    cmd: |
      cat <<EOF
      This is a test.
      EOF

Call to undefined function oci_connect()

I installed WAMPServer 2.5 (32-bit) and also encountered an oci_connect error. I also had Oracle 11g client (32-bit) installed. The common fix I read in other posts was to alter the php.ini file in your C:\wamp\bin\php\php5.5.12 directory, however this never worked for me. Maybe I misunderstood, but I found that if you alter the php.ini file in the C:\wamp\bin\apache\apache2.4.9 directory instead, you will get the results you want. The only thing I altered in the apache php.ini file was remove the semicolon to extension=php_oci8_11g.dll in order to enable it. I then restarted all the services and it now works! I hope this works for you.

bootstrap datepicker setDate format dd/mm/yyyy

I have some problems with jquery mobile 1.4.5. For example it seems accepting format change only passing from "option". And there are some refresh problem with the calendar using "option". For all that have the same problems I can suggest this code:

$( "#mydatepicker" ).datepicker( "option", "dateFormat", "dd/mm/yy" );
$( "#mydatepicker" ).datepicker( "setDate", new Date());    
$('.ui-datepicker-calendar').hide();

bundle install returns "Could not locate Gemfile"

I had this problem on Ubuntu 18.04. I updated the gem

sudo gem install rails
sudo gem install jekyll
sudo gem install jekyll bundler
cd ~/desiredFolder
jekyll new <foldername>
cd <foldername> OR 
bundle init
bundle install
bundle add jekyll
bundle exec jekyll serve

All worked and goto your browser just go to http://127.0.0.1:4000/ and it really should be running

Is it possible to run one logrotate check manually?

You may want to run it in verbose + force mode.

logrotate -vf /etc/logrotate.conf

PHP script to loop through all of the files in a directory?

You can use this code to loop through a directory recursively:

$path = "/home/myhome";
$rdi = new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::KEY_AS_PATHNAME);
foreach (new RecursiveIteratorIterator($rdi, RecursiveIteratorIterator::SELF_FIRST) as $file => $info) {
    echo $file."\n";
}

How do I start PowerShell from Windows Explorer?

Just to add in the reverse as a trick, at a PowerShell prompt you can do:

ii .

or

start .

to open a Windows Explorer window in your current directory.

Setting Elastic search limit to "unlimited"

Another approach is to first do a searchType: 'count', then and then do a normal search with size set to results.count.

The advantage here is it avoids depending on a magic number for UPPER_BOUND as suggested in this similar SO question, and avoids the extra overhead of building too large of a priority queue that Shay Banon describes here. It also lets you keep your results sorted, unlike scan.

The biggest disadvantage is that it requires two requests. Depending on your circumstance, this may be acceptable.

Append integer to beginning of list in Python

Another way of doing the same,

list[0:0] = [a]

How to SELECT a dropdown list item by value programmatically

ddl.SetSelectedValue("2");

With a handy extension:

public static class WebExtensions
{

    /// <summary>
    /// Selects the item in the list control that contains the specified value, if it exists.
    /// </summary>
    /// <param name="dropDownList"></param>
    /// <param name="selectedValue">The value of the item in the list control to select</param>
    /// <returns>Returns true if the value exists in the list control, false otherwise</returns>
    public static Boolean SetSelectedValue(this DropDownList dropDownList, String selectedValue)
    {
        ListItem selectedListItem = dropDownList.Items.FindByValue(selectedValue);

        if (selectedListItem != null)
        {
            selectedListItem.Selected = true;
            return true;
        }
        else
            return false;
    }
}

Note: Any code is released into the public domain. No attribution required.

How can I create numbered map markers in Google Maps V3?

It's quite feasible to generate labeled icons server-side, if you have some programming skills. You'll need the GD library at the server, in addition to PHP. Been working well for me for several years now, but admittedly tricky to get the icon images in synch.

I do that via AJAX by sending the few parameters to define the blank icon and the text and color as well as bgcolor to be applied. Here's my PHP:

header("Content-type: image/png");
//$img_url = "./icons/gen_icon5.php?blank=7&text=BB";

function do_icon ($icon, $text, $color) {
$im = imagecreatefrompng($icon);
imageAlphaBlending($im, true);
imageSaveAlpha($im, true);

$len = strlen($text);
$p1 = ($len <= 2)? 1:2 ;
$p2 = ($len <= 2)? 3:2 ;
$px = (imagesx($im) - 7 * $len) / 2 + $p1;
$font = 'arial.ttf';
$contrast = ($color)? imagecolorallocate($im, 255, 255, 255): imagecolorallocate($im, 0, 0, 0); // white on dark?

imagestring($im, $p2, $px, 3, $text, $contrast);    // imagestring  ( $image, $font, $x, $y, $string, $color)

imagepng($im);
imagedestroy($im);
}
$icons =   array("black.png", "blue.png", "green.png", "red.png", "white.png", "yellow.png", "gray.png", "lt_blue.png", "orange.png");      // 1/9/09
$light =   array( TRUE,         TRUE,       FALSE,       FALSE,     FALSE,      FALSE,      FALSE,          FALSE,      FALSE);     // white text?

$the_icon = $icons[$_GET['blank']];             // 0 thru 8 (note: total 9)
$the_text = substr($_GET['text'], 0, 3);        // enforce 2-char limit
do_icon ($the_icon, $the_text,$light[$_GET['blank']] ); 

It's invoked client-side via something like the following: var image_file = "./our_icons/gen_icon.php?blank=" + escape(icons[color]) + "&text=" + iconStr;

How to install the Six module in Python2.7

here's what six is:

pip search six
six                       - Python 2 and 3 compatibility utilities

to install:

pip install six

though if you did install python-dateutil from pip six should have been set as a dependency.

N.B.: to install pip run easy_install pip from command line.

Docker error cannot delete docker container, conflict: unable to remove repository reference

If you have multiples docker containers launched, use this

$ docker rm $(docker ps -aq)

It will remove all the current dockers listed in the "ps -aq" command.

Source : aaam on https://github.com/docker/docker/issues/12487

Extract year from date

if all your dates are the same width, you can put the dates in a vector and use substring

Date
a <- c("01/01/2009", "01/01/2010" , "01/01/2011")
substring(a,7,10) #This takes string and only keeps the characters beginning in position 7 to position 10

output

[1] "2009" "2010" "2011"

Can anyone explain python's relative imports?

If you are going to call relative.py directly and i.e. if you really want to import from a top level module you have to explicitly add it to the sys.path list.
Here is how it should work:

# Add this line to the beginning of relative.py file
import sys
sys.path.append('..')

# Now you can do imports from one directory top cause it is in the sys.path
import parent

# And even like this:
from parent import Parent

If you think the above can cause some kind of inconsistency you can use this instead:

sys.path.append(sys.path[0] + "/..")

sys.path[0] refers to the path that the entry point was ran from.

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

From the documentation:

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

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

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

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

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

How to make all controls resize accordingly proportionally when window is maximized?

Well, it's fairly simple to do.

On the window resize event handler, calculate how much the window has grown/shrunk, and use that fraction to adjust 1) Height, 2) Width, 3) Canvas.Top, 4) Canvas.Left properties of all the child controls inside the canvas.

Here's the code:

private void window1_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            myCanvas.Width = e.NewSize.Width;
            myCanvas.Height = e.NewSize.Height;

            double xChange = 1, yChange = 1;

            if (e.PreviousSize.Width != 0)
            xChange = (e.NewSize.Width/e.PreviousSize.Width);

            if (e.PreviousSize.Height != 0)
            yChange = (e.NewSize.Height / e.PreviousSize.Height);

            foreach (FrameworkElement fe in myCanvas.Children )
            {   
                /*because I didn't want to resize the grid I'm having inside the canvas in this particular instance. (doing that from xaml) */            
                if (fe is Grid == false)
                {
                    fe.Height = fe.ActualHeight * yChange;
                    fe.Width = fe.ActualWidth * xChange;

                    Canvas.SetTop(fe, Canvas.GetTop(fe) * yChange);
                    Canvas.SetLeft(fe, Canvas.GetLeft(fe) * xChange);

                }
            }
        }

Using SED with wildcard

The asterisk (*) means "zero or more of the previous item".

If you want to match any single character use

sed -i 's/string-./string-0/g' file.txt

If you want to match any string (i.e. any single character zero or more times) use

sed -i 's/string-.*/string-0/g' file.txt

Eclipse Bug: Unhandled event loop exception No more handles

Happens with Eclipse Mars.2 Release (4.5.2) and Multimon TaskBar 2.1 on a dual monitor setup, too. It disappears if MM TaskBar is un-loaded.

UPDATE

Still the same with Oxygen.2 Release (4.7.2).

Event on a disabled input

OR do this with jQuery and CSS!

$('input.disabled').attr('ignore','true').css({
    'pointer-events':'none',
     'color': 'gray'
});

This way you make the element look disabled and no pointer events will fire, yet it allows propagation and if submitted you can use the attribute 'ignore' to ignore it.

An unhandled exception was generated during the execution of the current web request

As far as I understand, you have more than one form tag in your web page that causes the problem. Make sure you have only one server-side form tag for each page.

Run a single migration file

This are the steps to run again this migration file "20150927161307_create_users.rb"

  1. Run the console mode. (rails c)
  2. Copy and past the class which is in that file to the console.

    class CreateUsers < ActiveRecord::Migration
      def change
        create_table :users do |t|
          t.string :name
          t.string :email
          t.timestamps null: false   end
        end
      end
    end
    
  3. Create an instance of the class CreateUsers: c1 = CreateUsers.new

  4. Execute the method change of that instance: c1.change

How do I specify C:\Program Files without a space in it for programs that can't handle spaces in file paths?

Use the following notations:

  • For "C:\Program Files", use "C:\PROGRA~1"
  • For "C:\Program Files (x86)", use "C:\PROGRA~2"

Thanks @lit for your ideal answer in below comment:

Use the environment variables %ProgramFiles% and %ProgramFiles(x86)%

:

Sys.WebForms.PageRequestManagerServerErrorException: An unknown error occurred while processing the request on the server."

I had this issue when I upgraded my project to 4.5 framework and the GridView had Empty Data Template. Something changed and the following statement which previously was returning the Empty Data Template was now returning the Header Row.

GridViewRow dr = (GridViewRow)this.grdViewRoleMembership.Controls[0].Controls[0];

I changed it to below and the error went away and the GridView started working as expected.

GridViewRow dr = (GridViewRow)this.grdViewRoleMembership.Controls[0].Controls[1];

I hope this helps someone.

What is the most efficient string concatenation method in python?

For python 3.8.6/3.9, I had to do some dirty hacks, because perfplot was giving out some errors. Here assume that x[0] is a a and x[1] is b: Performance

The plot is nearly same for large data. For small data, Performance 2

Taken by perfplot and this is the code, large data == range(8), small data == range(4).

import perfplot

from random import choice
from string import ascii_lowercase as letters

def generate_random(x):
    data = ''.join(choice(letters) for i in range(x))
    sata = ''.join(choice(letters) for i in range(x))
    return [data,sata]

def fstring_func(x):
    return [ord(i) for i in f'{x[0]}{x[1]}']

def format_func(x):
    return [ord(i) for i in "{}{}".format(x[0], x[1])]

def replace_func(x):
    return [ord(i) for i in "|~".replace('|', x[0]).replace('~', x[1])]

def join_func(x):
    return [ord(i) for i in "".join([x[0], x[1]])]

perfplot.show(
    setup=lambda n: generate_random(n),
    kernels=[
        fstring_func,
        format_func,
        replace_func,
        join_func,
    ],
    n_range=[int(k ** 2.5) for k in range(4)],
)

When medium data is there, and 4 strings are there x[0], x[1], x[2], x[3] instead of 2 string:

def generate_random(x):
    a =  ''.join(choice(letters) for i in range(x))
    b =  ''.join(choice(letters) for i in range(x))
    c =  ''.join(choice(letters) for i in range(x))
    d =  ''.join(choice(letters) for i in range(x))
    return [a,b,c,d]

Performance 3 Better to stick with fstrings

Use space as a delimiter with cut command

You can't do it easily with cut if the data has for example multiple spaces. I have found it useful to normalize input for easier processing. One trick is to use sed for normalization as below.

echo -e "foor\t \t bar" | sed 's:\s\+:\t:g' | cut -f2  #bar

Why should I use core.autocrlf=true in Git?

I am a .NET developer, and have used Git and Visual Studio for years. My strong recommendation is set line endings to true. And do it as early as you can in the lifetime of your Repository.

That being said, I HATE that Git changes my line endings. A source control should only save and retrieve the work I do, it should NOT modify it. Ever. But it does.

What will happen if you don't have every developer set to true, is ONE developer eventually will set to true. This will begin to change the line endings of all of your files to LF in your repo. And when users set to false check those out, Visual Studio will warn you, and ask you to change them. You will have 2 things happen very quickly. One, you will get more and more of those warnings, the bigger your team the more you get. The second, and worse thing, is that it will show that every line of every modified file was changed(because the line endings of every line will be changed by the true guy). Eventually you won't be able to track changes in your repo reliably anymore. It is MUCH easier and cleaner to make everyone keep to true, than to try to keep everyone false. As horrible as it is to live with the fact that your trusted source control is doing something it should not. Ever.

How can I use pointers in Java?

You can use addresses and pointers using the Unsafe class. However as the name suggests, these methods are UNSAFE and generally a bad idea. Incorrect usage can result in your JVM randomly dying (actually the same problem get using pointers incorrectly in C/C++)

While you may be used to pointers and think you need them (because you don't know how to code any other way), you will find that you don't and you will be better off for it.

How to break a while loop from an if condition inside the while loop?

An "if" is not a loop. Just use the break inside the "if" and it will break out of the "while".

If you ever need to use genuine nested loops, Java has the concept of a labeled break. You can put a label before a loop, and then use the name of the label is the argument to break. It will break outside of the labeled loop.

C# - How to add an Excel Worksheet programmatically - Office XP / 2003

You need to add a COM reference in your project to the "Microsoft Excel 11.0 Object Library" - or whatever version is appropriate.

This code works for me:

private void AddWorksheetToExcelWorkbook(string fullFilename,string worksheetName)
{
    Microsoft.Office.Interop.Excel.Application xlApp = null;
    Workbook xlWorkbook = null;
    Sheets xlSheets = null;
    Worksheet xlNewSheet = null;

    try {
        xlApp = new Microsoft.Office.Interop.Excel.Application();

        if (xlApp == null)
            return;

        // Uncomment the line below if you want to see what's happening in Excel
        // xlApp.Visible = true;

        xlWorkbook = xlApp.Workbooks.Open(fullFilename, 0, false, 5, "", "",
                false, XlPlatform.xlWindows, "",
                true, false, 0, true, false, false);

        xlSheets = xlWorkbook.Sheets as Sheets;

        // The first argument below inserts the new worksheet as the first one
        xlNewSheet = (Worksheet)xlSheets.Add(xlSheets[1], Type.Missing, Type.Missing, Type.Missing);
        xlNewSheet.Name = worksheetName;

        xlWorkbook.Save();
        xlWorkbook.Close(Type.Missing,Type.Missing,Type.Missing);
        xlApp.Quit();
    }
    finally {
        Marshal.ReleaseComObject(xlNewSheet);
        Marshal.ReleaseComObject(xlSheets);
        Marshal.ReleaseComObject(xlWorkbook);
        Marshal.ReleaseComObject(xlApp);
        xlApp = null;
    }
}

Note that you want to be very careful about properly cleaning up and releasing your COM object references. Included in that StackOverflow question is a useful rule of thumb: "Never use 2 dots with COM objects". In your code; you're going to have real trouble with that. My demo code above does NOT properly clean up the Excel app, but it's a start!

Some other links that I found useful when looking into this question:

According to MSDN

To use COM interop, you must have administrator or Power User security permissions.

Hope that helps.

initialize a const array in a class initializer in C++

How about emulating a const array via an accessor function? It's non-static (as you requested), and it doesn't require stl or any other library:

class a {
    int privateB[2];
public:
    a(int b0,b1) { privateB[0]=b0; privateB[1]=b1; }
    int b(const int idx) { return privateB[idx]; }
}

Because a::privateB is private, it is effectively constant outside a::, and you can access it similar to an array, e.g.

a aobj(2,3);    // initialize "constant array" b[]
n = aobj.b(1);  // read b[1] (write impossible from here)

If you are willing to use a pair of classes, you could additionally protect privateB from member functions. This could be done by inheriting a; but I think I prefer John Harrison's comp.lang.c++ post using a const class.

How can jQuery deferred be used?

You can use a deferred object to make a fluid design that works well in webkit browsers. Webkit browsers will fire resize event for each pixel the window is resized, unlike FF and IE which fire the event only once for each resize. As a result, you have no control over the order in which the functions bound to your window resize event will execute. Something like this solves the problem:

var resizeQueue = new $.Deferred(); //new is optional but it sure is descriptive
resizeQueue.resolve();

function resizeAlgorithm() {
//some resize code here
}

$(window).resize(function() {
    resizeQueue.done(resizeAlgorithm);
});

This will serialize the execution of your code so that it executes as you intended it to. Beware of pitfalls when passing object methods as callbacks to a deferred. Once such method is executed as a callback to deferred, the 'this' reference will be overwritten with reference to the deferred object and will no longer refer to the object the method belongs to.

Fatal error: iostream: No such file or directory in compiling C program using GCC

Seems like you posted a new question after you realized that you were dealing with a simpler problem related to size_t. I am glad that you did.

Anyways, You have a .c source file, and most of the code looks as per C standards, except that #include <iostream> and using namespace std;

C equivalent for the built-in functions of C++ standard #include<iostream> can be availed through #include<stdio.h>

  1. Replace #include <iostream> with #include <stdio.h>, delete using namespace std;
  2. With #include <iostream> taken off, you would need a C standard alternative for cout << endl;, which can be done by printf("\n"); or putchar('\n');
    Out of the two options, printf("\n"); works the faster as I observed.

    When used printf("\n"); in the code above in place of cout<<endl;

    $ time ./thread.exe
    1 2 3 4 5 6 7 8 9 10
    
    real    0m0.031s
    user    0m0.030s
    sys     0m0.030s
    

    When used putchar('\n'); in the code above in place of cout<<endl;

    $ time ./thread.exe
    1 2 3 4 5 6 7 8 9 10
    
    real    0m0.047s
    user    0m0.030s
    sys     0m0.030s
    

Compiled with Cygwin gcc (GCC) 4.8.3 version. results averaged over 10 samples. (Took me 15 mins)

Move entire line up and down in Vim

Move a line up: ddkP

Move a line down: ddp

How does Java deal with multiple conditions inside a single IF statement

Is Java smart enough to skip checking bool2 and bool2 if bool1 was evaluated to false?

Its not a matter of being smart, its a requirement specified in the language. Otherwise you couldn't write expressions like.

if(s != null && s.length() > 0)

or

if(s == null || s.length() == 0)

BTW if you use & and | it will always evaluate both sides of the expression.

AngularJS: how to enable $locationProvider.html5Mode with deeplinking

This was the best solution I found after more time than I care to admit. Basically, add target="_self" to each link that you need to insure a page reload.

http://blog.panjiesw.com/posts/2013/09/angularjs-normal-links-with-html5mode/

Is there a way for non-root processes to bind to "privileged" ports on Linux?

TLDR: For "the answer" (as I see it), jump down to the >>TLDR<< part in this answer.

OK, I've figured it out (for real this time), the answer to this question, and this answer of mine is also a way of apologizing for promoting another answer (both here and on twitter) that I thought was "the best", but after trying it, discovered that I was mistaken about that. Learn from my mistake kids: don't promote something until you've actually tried it yourself!

Again, I reviewed all the answers here. I've tried some of them (and chose not to try others because I simply didn't like the solutions). I thought that the solution was to use systemd with its Capabilities= and CapabilitiesBindingSet= settings. After wrestling with this for some time, I discovered that this is not the solution because:

Capabilities are intended to restrict root processes!

As the OP wisely stated, it is always best to avoid that (for all your daemons if possible!).

You cannot use the Capabilities related options with User= and Group= in systemd unit files, because capabilities are ALWAYS reset when execev (or whatever the function is) is called. In other words, when systemd forks and drops its perms, the capabilities are reset. There is no way around this, and all that binding logic in the kernel is basic around uid=0, not capabilities. This means that it is unlikely that Capabilities will ever be the right answer to this question (at least any time soon). Incidentally, setcap, as others have mentioned, is not a solution. It didn't work for me, it doesn't work nicely with scripts, and those are reset anyways whenever the file changes.

In my meager defense, I did state (in the comment I've now deleted), that James' iptables suggestion (which the OP also mentions), was the "2nd best solution". :-P

>>TLDR<<

The solution is to combine systemd with on-the-fly iptables commands, like this (taken from DNSChain):

[Unit]
Description=dnschain
After=network.target
Wants=namecoin.service

[Service]
ExecStart=/usr/local/bin/dnschain
Environment=DNSCHAIN_SYSD_VER=0.0.1
PermissionsStartOnly=true
ExecStartPre=/sbin/sysctl -w net.ipv4.ip_forward=1
ExecStartPre=-/sbin/iptables -D INPUT -p udp --dport 5333 -j ACCEPT
ExecStartPre=-/sbin/iptables -t nat -D PREROUTING -p udp --dport 53 -j REDIRECT --to-ports 5333
ExecStartPre=/sbin/iptables -A INPUT -p udp --dport 5333 -j ACCEPT
ExecStartPre=/sbin/iptables -t nat -A PREROUTING -p udp --dport 53 -j REDIRECT --to-ports 5333
ExecStopPost=/sbin/iptables -D INPUT -p udp --dport 5333 -j ACCEPT
ExecStopPost=/sbin/iptables -t nat -D PREROUTING -p udp --dport 53 -j REDIRECT --to-ports 5333
User=dns
Group=dns
Restart=always
RestartSec=5
WorkingDirectory=/home/dns
PrivateTmp=true
NoNewPrivileges=true
ReadOnlyDirectories=/etc

# Unfortunately, capabilities are basically worthless because they're designed to restrict root daemons. Instead, we use iptables to listen on privileged ports.
# Capabilities=cap_net_bind_service+pei
# SecureBits=keep-caps

[Install]
WantedBy=multi-user.target

Here we accomplish the following:

  • The daemon listens on 5333, but connections are successfully accepted on 53 thanks to iptables
  • We can include the commands in the unit file itself, and thus we save people headaches. systemd cleans up the firewall rules for us, making sure to remove them when the daemon isn't running.
  • We never run as root, and we make privilege escalation impossible (at least systemd claims to), supposedly even if the daemon is compromised and sets uid=0.

iptables is still, unfortunately, quite an ugly and difficult-to-use utility. If the daemon is listening on eth0:0 instead of eth0, for example, the commands are slightly different.

angular 2 sort and filter

This is my sort. It will do number sort , string sort and date sort .

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

@Pipe({
  name: 'sortPipe'
 })

export class SortPipe implements PipeTransform {

    transform(array: Array<string>, key: string): Array<string> {

        console.log("Entered in pipe*******  "+ key);


        if(key === undefined || key == '' ){
            return array;
        }

        var arr = key.split("-");
        var keyString = arr[0];   // string or column name to sort(name or age or date)
        var sortOrder = arr[1];   // asc or desc order
        var byVal = 1;


        array.sort((a: any, b: any) => {

            if(keyString === 'date' ){

                let left    = Number(new Date(a[keyString]));
                let right   = Number(new Date(b[keyString]));

                return (sortOrder === "asc") ? right - left : left - right;
            }
            else if(keyString === 'name'){

                if(a[keyString] < b[keyString]) {
                    return (sortOrder === "asc" ) ? -1*byVal : 1*byVal;
                } else if (a[keyString] > b[keyString]) {
                    return (sortOrder === "asc" ) ? 1*byVal : -1*byVal;
                } else {
                    return 0;
                }  
            }
            else if(keyString === 'age'){
                return (sortOrder === "asc") ? a[keyString] - b[keyString] : b[keyString] - a[keyString];
            }

        });

        return array;

  }

}

Check if file is already open

On Windows I found the answer https://stackoverflow.com/a/13706972/3014879 using

fileIsLocked = !file.renameTo(file)

most useful, as it avoids false positives when processing write protected (or readonly) files.

DropDownList in MVC 4 with Razor

@{
List<SelectListItem> listItems= new List<SelectListItem>();
listItems.Add(new SelectListItem
    {
      Text = "One",
      Value = "1"
    });
listItems.Add(new SelectListItem
    {
        Text = "Two",
        Value = "2",
    });
listItems.Add(new SelectListItem
    {
        Text = "Three",
        Value = "3"
    });
listItems.Add(new SelectListItem
{
   Text = "Four",
   Value = "4"
});
listItems.Add(new SelectListItem
{
   Text = "Five",
   Value = "5"
});
}
@Html.DropDownList("DDlDemo",new SelectList(listItems,"Value","Text"))

Refer:- Create drop down list in MVC 4 razor example

SyntaxError: Cannot use import statement outside a module

I ran into the same issue and it's even worse: I needed both "import" and "require"

  1. Some newer ES6 modules works only with import.
  2. Some CommonJS works with require.

Here is what worked for me:

  1. Turn your js file into .mjs as suggested in other answers

  2. "require" is not defined with ES6 module, so you can define it this way:

    import { createRequire } from 'module'
    const require = createRequire(import.meta.url);
    

    Now 'require' can be used in the usual way.

  3. Use import for ES6 modules and require for commonJS.

Some useful links: node.js's own documentation. difference between import and require. Mozilla has some nice documentation about import

How can I echo the whole content of a .html file in PHP?

You should use readfile():

readfile("/path/to/file");

This will read the file and send it to the browser in one command. This is essentially the same as:

echo file_get_contents("/path/to/file");

except that file_get_contents() may cause the script to crash for large files, while readfile() won't.

How do I clone a specific Git branch?

To clone a branch without fetching other branches:

mkdir $BRANCH
cd $BRANCH
git init
git remote add -t $BRANCH -f origin $REMOTE_REPO
git checkout $BRANCH

Java: String - add character n-times

Here is a simple way..

for(int i=0;i<n;i++)
{
  yourString = yourString + "what you want to append continiously";
}

What is this: [Ljava.lang.Object;?

[Ljava.lang.Object; is the name for Object[].class, the java.lang.Class representing the class of array of Object.

The naming scheme is documented in Class.getName():

If this class object represents a reference type that is not an array type then the binary name of the class is returned, as specified by the Java Language Specification (§13.1).

If this class object represents a primitive type or void, then the name returned is the Java language keyword corresponding to the primitive type or void.

If this class object represents a class of arrays, then the internal form of the name consists of the name of the element type preceded by one or more '[' characters representing the depth of the array nesting. The encoding of element type names is as follows:

Element Type        Encoding
boolean             Z
byte                B
char                C
double              D
float               F
int                 I
long                J
short               S 
class or interface  Lclassname;

Yours is the last on that list. Here are some examples:

// xxxxx varies
System.out.println(new int[0][0][7]); // [[[I@xxxxx
System.out.println(new String[4][2]); // [[Ljava.lang.String;@xxxxx
System.out.println(new boolean[256]); // [Z@xxxxx

The reason why the toString() method on arrays returns String in this format is because arrays do not @Override the method inherited from Object, which is specified as follows:

The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:

getClass().getName() + '@' + Integer.toHexString(hashCode())

Note: you can not rely on the toString() of any arbitrary object to follow the above specification, since they can (and usually do) @Override it to return something else. The more reliable way of inspecting the type of an arbitrary object is to invoke getClass() on it (a final method inherited from Object) and then reflecting on the returned Class object. Ideally, though, the API should've been designed such that reflection is not necessary (see Effective Java 2nd Edition, Item 53: Prefer interfaces to reflection).


On a more "useful" toString for arrays

java.util.Arrays provides toString overloads for primitive arrays and Object[]. There is also deepToString that you may want to use for nested arrays.

Here are some examples:

int[] nums = { 1, 2, 3 };

System.out.println(nums);
// [I@xxxxx

System.out.println(Arrays.toString(nums));
// [1, 2, 3]

int[][] table = {
        { 1, },
        { 2, 3, },
        { 4, 5, 6, },
};

System.out.println(Arrays.toString(table));
// [[I@xxxxx, [I@yyyyy, [I@zzzzz]

System.out.println(Arrays.deepToString(table));
// [[1], [2, 3], [4, 5, 6]]

There are also Arrays.equals and Arrays.deepEquals that perform array equality comparison by their elements, among many other array-related utility methods.

Related questions

Passing javascript variable to html textbox

Pass the variable to the form element like this

your form element

<input type="text" id="mytext">

javascript

var test = "Hello";
document.getElementById("mytext").value = test;//Now you get the js variable inside your form element

Using LIKE in an Oracle IN clause

No, you cannot do this. The values in the IN clause must be exact matches. You could modify the select thusly:

SELECT *
  FROM tbl
 WHERE my_col LIKE %val1%
    OR my_col LIKE %val2%
    OR my_col LIKE %val3%
 ...

If the val1, val2, val3... are similar enough, you might be able to use regular expressions in the REGEXP_LIKE operator.

How can I pass a parameter to a Java Thread?

To create a thread you normally create your own implementation of Runnable. Pass the parameters to the thread in the constructor of this class.

class MyThread implements Runnable{
   private int a;
   private String b;
   private double c;

   public MyThread(int a, String b, double c){
      this.a = a;
      this.b = b;
      this.c = c;
   }

   public void run(){
      doSomething(a, b, c);
   }
}

How to find MAC address of an Android device programmatically

private fun getMac(): String? =
        try {
            NetworkInterface.getNetworkInterfaces()
                    .toList()
                    .find { networkInterface -> networkInterface.name.equals("wlan0", ignoreCase = true) }
                    ?.hardwareAddress
                    ?.joinToString(separator = ":") { byte -> "%02X".format(byte) }
        } catch (ex: Exception) {
            ex.printStackTrace()
            null
        }

error LNK2019: unresolved external symbol _main referenced in function ___tmainCRTStartup

if you have _tmain function in your projects you need to include <tchar.h>.

Unable to specify the compiler with CMake

Using with FILEPATH option might work:

set(CMAKE_CXX_COMPILER:FILEPATH C:/MinGW/bin/gcc.exe)

Eclipse - "Workspace in use or cannot be created, chose a different one."

An additional reason could be that you're pointing to a workspace on a drive that no longer exists, thinking that you're choosing the valid one. For instance, for me the workspace used to exist on the F drive, but now it is on my D drive. Even though I don't have the F drive anymore it is still listed as a workspace I once used during Eclipse startup. When I choose this old workspace Eclipse complains that the workspace is "in use", which is very strange.

How can javascript upload a blob?

2019 Update

This updates the answers with the latest Fetch API and doesn't need jQuery.

Disclaimer: doesn't work on IE, Opera Mini and older browsers. See caniuse.

Basic Fetch

It could be as simple as:

  fetch(`https://example.com/upload.php`, {method:"POST", body:blobData})
                .then(response => console.log(response.text()))

Fetch with Error Handling

After adding error handling, it could look like:

fetch(`https://example.com/upload.php`, {method:"POST", body:blobData})
            .then(response => {
                if (response.ok) return response;
                else throw Error(`Server returned ${response.status}: ${response.statusText}`)
            })
            .then(response => console.log(response.text()))
            .catch(err => {
                alert(err);
            });

PHP Code

This is the server-side code in upload.php.

<?php    
    // gets entire POST body
    $data = file_get_contents('php://input');
    // write the data out to the file
    $fp = fopen("path/to/file", "wb");

    fwrite($fp, $data);
    fclose($fp);
?>

In Visual Studio C++, what are the memory allocation representations?

There's actually quite a bit of useful information added to debug allocations. This table is more complete:

http://www.nobugs.org/developer/win32/debug_crt_heap.html#table

Address  Offset After HeapAlloc() After malloc() During free() After HeapFree() Comments
0x00320FD8  -40    0x01090009    0x01090009     0x01090009    0x0109005A     Win32 heap info
0x00320FDC  -36    0x01090009    0x00180700     0x01090009    0x00180400     Win32 heap info
0x00320FE0  -32    0xBAADF00D    0x00320798     0xDDDDDDDD    0x00320448     Ptr to next CRT heap block (allocated earlier in time)
0x00320FE4  -28    0xBAADF00D    0x00000000     0xDDDDDDDD    0x00320448     Ptr to prev CRT heap block (allocated later in time)
0x00320FE8  -24    0xBAADF00D    0x00000000     0xDDDDDDDD    0xFEEEFEEE     Filename of malloc() call
0x00320FEC  -20    0xBAADF00D    0x00000000     0xDDDDDDDD    0xFEEEFEEE     Line number of malloc() call
0x00320FF0  -16    0xBAADF00D    0x00000008     0xDDDDDDDD    0xFEEEFEEE     Number of bytes to malloc()
0x00320FF4  -12    0xBAADF00D    0x00000001     0xDDDDDDDD    0xFEEEFEEE     Type (0=Freed, 1=Normal, 2=CRT use, etc)
0x00320FF8  -8     0xBAADF00D    0x00000031     0xDDDDDDDD    0xFEEEFEEE     Request #, increases from 0
0x00320FFC  -4     0xBAADF00D    0xFDFDFDFD     0xDDDDDDDD    0xFEEEFEEE     No mans land
0x00321000  +0     0xBAADF00D    0xCDCDCDCD     0xDDDDDDDD    0xFEEEFEEE     The 8 bytes you wanted
0x00321004  +4     0xBAADF00D    0xCDCDCDCD     0xDDDDDDDD    0xFEEEFEEE     The 8 bytes you wanted
0x00321008  +8     0xBAADF00D    0xFDFDFDFD     0xDDDDDDDD    0xFEEEFEEE     No mans land
0x0032100C  +12    0xBAADF00D    0xBAADF00D     0xDDDDDDDD    0xFEEEFEEE     Win32 heap allocations are rounded up to 16 bytes
0x00321010  +16    0xABABABAB    0xABABABAB     0xABABABAB    0xFEEEFEEE     Win32 heap bookkeeping
0x00321014  +20    0xABABABAB    0xABABABAB     0xABABABAB    0xFEEEFEEE     Win32 heap bookkeeping
0x00321018  +24    0x00000010    0x00000010     0x00000010    0xFEEEFEEE     Win32 heap bookkeeping
0x0032101C  +28    0x00000000    0x00000000     0x00000000    0xFEEEFEEE     Win32 heap bookkeeping
0x00321020  +32    0x00090051    0x00090051     0x00090051    0xFEEEFEEE     Win32 heap bookkeeping
0x00321024  +36    0xFEEE0400    0xFEEE0400     0xFEEE0400    0xFEEEFEEE     Win32 heap bookkeeping
0x00321028  +40    0x00320400    0x00320400     0x00320400    0xFEEEFEEE     Win32 heap bookkeeping
0x0032102C  +44    0x00320400    0x00320400     0x00320400    0xFEEEFEEE     Win32 heap bookkeeping

How do I connect to my existing Git repository using Visual Studio Code?

  1. Open Vs Code
  2. Go to view
  3. Click on terminal to open a terminal in VS Code
  4. Copy the link for your existing repository from your GitHub page.
  5. Type “git clone” and paste the link in addition i.e “git clone https://github.com/...”
  6. This will open the repository in your Vs Code Editor.

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

If you want to assign dynamic bitmap image to bitmap variables

Example for kotlin

backgroundImage = Glide.with(applicationContext).asBitmap().load(PresignedUrl().getUrl(items!![position].img)).into(100, 100).get();

The above answers did not work for me

.asBitmap should be before the .load("http://....")

Hashing with SHA1 Algorithm in C#

This is what I went with. For those of you who want to optimize, check out https://stackoverflow.com/a/624379/991863.

    public static string Hash(string stringToHash)
    {
        using (var sha1 = new SHA1Managed())
        {
            return BitConverter.ToString(sha1.ComputeHash(Encoding.UTF8.GetBytes(stringToHash)));
        }
    }

How do I fix this "TypeError: 'str' object is not callable" error?

this part :

"Your new price is: $"(float(price)

asks python to call this string:

"Your new price is: $"

just like you would a function: function( some_args) which will ALWAYS trigger the error:

TypeError: 'str' object is not callable

Maven fails to find local artifact

Catch all. When solutions mentioned here don't work(happend in my case), simply delete all contents from '.m2' folder/directory, and do mvn clean install.

What does @@variable mean in Ruby?

@ and @@ in modules also work differently when a class extends or includes that module.

So given

module A
    @a = 'module'
    @@a = 'module'

    def get1
        @a          
    end     

    def get2
        @@a         
    end     

    def set1(a) 
        @a = a      
    end     

    def set2(a) 
        @@a = a     
    end     

    def self.set1(a)
        @a = a      
    end     

    def self.set2(a)
        @@a = a     
    end     
end 

Then you get the outputs below shown as comments

class X
    extend A

    puts get1.inspect # nil
    puts get2.inspect # "module"

    @a = 'class' 
    @@a = 'class' 

    puts get1.inspect # "class"
    puts get2.inspect # "module"

    set1('set')
    set2('set')

    puts get1.inspect # "set" 
    puts get2.inspect # "set" 

    A.set1('sset')
    A.set2('sset')

    puts get1.inspect # "set" 
    puts get2.inspect # "sset"
end 

class Y
    include A

    def doit
        puts get1.inspect # nil
        puts get2.inspect # "module"

        @a = 'class'
        @@a = 'class'

        puts get1.inspect # "class"
        puts get2.inspect # "class"

        set1('set')
        set2('set')

        puts get1.inspect # "set"
        puts get2.inspect # "set"

        A.set1('sset')
        A.set2('sset')

        puts get1.inspect # "set"
        puts get2.inspect # "sset"
    end
end

Y.new.doit

So use @@ in modules for variables you want common to all their uses, and use @ in modules for variables you want separate for every use context.

How can I delete (not disable) ActiveX add-ons in Internet Explorer (7 and 8 Beta 2)?

You could unregister the control with

regsvr32 /u badboy.ocx

at the command line. Though i would suggest testing these things in a vmware.

Stored procedure or function expects parameter which is not supplied

Your stored procedure expects 5 parameters as input

@userID int, 
@userName varchar(50), 
@password nvarchar(50), 
@emailAddress nvarchar(50), 
@preferenceName varchar(20) 

So you should add all 5 parameters to this SP call:

    cmd.CommandText = "SHOWuser";
    cmd.Parameters.AddWithValue("@userID",userID);
    cmd.Parameters.AddWithValue("@userName", userName);
    cmd.Parameters.AddWithValue("@password", password);
    cmd.Parameters.AddWithValue("@emailAddress", emailAddress);
    cmd.Parameters.AddWithValue("@preferenceName", preferences);
    dbcon.Open();

PS: It's not clear what these parameter are for. You don't use these parameters in your SP body so your SP should looks like:

ALTER PROCEDURE [dbo].[SHOWuser] AS BEGIN ..... END

SSIS Excel Import Forcing Incorrect Column Type

You can also alter the registry to look at more values than just the first 8 rows. I have used this method and works quite well.

http://support.microsoft.com/kb/281517

Understanding MongoDB BSON Document size limit

To post a clarification answer here for those who get directed here by Google.

The document size includes everything in the document including the subdocuments, nested objects etc.

So a document of:

{
  "_id": {},
  "na": [1, 2, 3],
  "naa": [
    { "w": 1, "v": 2, "b": [1, 2, 3] },
    { "w": 5, "b": 2, "h": [{ "d": 5, "g": 7 }, {}] }
  ]
}

Has a maximum size of 16 MB.

Subdocuments and nested objects are all counted towards the size of the document.

How do I return multiple values from a function?

For small projects I find it easiest to work with tuples. When that gets too hard to manage (and not before) I start grouping things into logical structures, however I think your suggested use of dictionaries and ReturnValue objects is wrong (or too simplistic).

Returning a dictionary with keys "y0", "y1", "y2", etc. doesn't offer any advantage over tuples. Returning a ReturnValue instance with properties .y0, .y1, .y2, etc. doesn't offer any advantage over tuples either. You need to start naming things if you want to get anywhere, and you can do that using tuples anyway:

def get_image_data(filename):
    [snip]
    return size, (format, version, compression), (width,height)

size, type, dimensions = get_image_data(x)

IMHO, the only good technique beyond tuples is to return real objects with proper methods and properties, like you get from re.match() or open(file).

What is the difference between char array and char pointer in C?

char p[3] = "hello" ? should be char p[6] = "hello" remember there is a '\0' char in the end of a "string" in C.

anyway, array in C is just a pointer to the first object of an adjust objects in the memory. the only different s are in semantics. while you can change the value of a pointer to point to a different location in the memory an array, after created, will always point to the same location.
also when using array the "new" and "delete" is automatically done for you.

is it possible to update UIButton title/text programmatically?

Do you have the button specified as an IBOutlet in your view controller class, and is it connected properly as an outlet in Interface Builder (ctrl drag from new referencing outlet to file owner and select your UIButton object)? That's usually the problem I have when I see these symptoms.


Edit: While it's not the case here, something like this can also happen if you set an attributed title to the button, then you try to change the title and not the attributed title.

Java foreach loop: for (Integer i : list) { ... }

Sometimes it's just better to use an iterator.

(Allegedly, "85%" of the requests for an index in the posh for loop is for implementing a String join method (which you can easily do without).)

Does Java have something like C#'s ref and out keywords?

Like many others, I needed to convert a C# project to Java. I did not find a complete solution on the web regarding out and ref modifiers. But, I was able to take the information I found, and expand upon it to create my own classes to fulfill the requirements. I wanted to make a distinction between ref and out parameters for code clarity. With the below classes, it is possible. May this information save others time and effort.

An example is included in the code below.

//*******************************************************************************************
//XOUT CLASS
//*******************************************************************************************
public class XOUT<T>
{
    public XOBJ<T> Obj = null;

    public XOUT(T value)
    {
        Obj = new XOBJ<T>(value);
    }

    public XOUT()
    {
      Obj = new XOBJ<T>();
    }

    public XOUT<T> Out()
    {
        return(this);
    }

    public XREF<T> Ref()
    {
        return(Obj.Ref());
    }
};

//*******************************************************************************************
//XREF CLASS
//*******************************************************************************************

public class XREF<T>
{
    public XOBJ<T> Obj = null;

    public XREF(T value)
    {
        Obj = new XOBJ<T>(value);
    }

    public XREF()
    {
      Obj = new XOBJ<T>();
    }

    public XOUT<T> Out()
    {
        return(Obj.Out());
    }

    public XREF<T> Ref()
    {
        return(this);
    }
};

//*******************************************************************************************
//XOBJ CLASS
//*******************************************************************************************
/**
 *
 * @author jsimms
 */
/*
    XOBJ is the base object that houses the value. XREF and XOUT are classes that
    internally use XOBJ. The classes XOBJ, XREF, and XOUT have methods that allow
    the object to be used as XREF or XOUT parameter; This is important, because
    objects of these types are interchangeable.

    See Method:
       XXX.Ref()
       XXX.Out()

    The below example shows how to use XOBJ, XREF, and XOUT;
    //
    // Reference parameter example
    //
    void AddToTotal(int a, XREF<Integer> Total)
    {
       Total.Obj.Value += a;
    }

    //
    // out parameter example
    //
    void Add(int a, int b, XOUT<Integer> ParmOut)
    {
       ParmOut.Obj.Value = a+b;
    }

    //
    // XOBJ example
    //
    int XObjTest()
    {
       XOBJ<Integer> Total = new XOBJ<>(0);
       Add(1, 2, Total.Out());    // Example of using out parameter
       AddToTotal(1,Total.Ref()); // Example of using ref parameter
       return(Total.Value);
    }
*/


public class XOBJ<T> {

    public T Value;

    public  XOBJ() {

    }

    public XOBJ(T value) {
        this.Value = value;
    }

    //
    // Method: Ref()
    // Purpose: returns a Reference Parameter object using the XOBJ value
    //
    public XREF<T> Ref()
    {
        XREF<T> ref = new XREF<T>();
        ref.Obj = this;
        return(ref);
    }

    //
    // Method: Out()
    // Purpose: returns an Out Parameter Object using the XOBJ value
    //
    public XOUT<T> Out()
    {
        XOUT<T> out = new XOUT<T>();
        out.Obj = this;
        return(out);
    }

    //
    // Method get()
    // Purpose: returns the value
    // Note: Because this is combersome to edit in the code,
    // the Value object has been made public
    //
    public T get() {
        return Value;
    }

    //
    // Method get()
    // Purpose: sets the value
    // Note: Because this is combersome to edit in the code,
    // the Value object has been made public
    //
    public void set(T anotherValue) {
        Value = anotherValue;
    }

    @Override
    public String toString() {
        return Value.toString();
    }

    @Override
    public boolean equals(Object obj) {
        return Value.equals(obj);
    }

    @Override
    public int hashCode() {
        return Value.hashCode();
    }
}

Difference between Encapsulation and Abstraction

Abstraction

In Java, abstraction means hiding the information to the real world. It establishes the contract between the party to tell about “what should we do to make use of the service”.

Example, In API development, only abstracted information of the service has been revealed to the world rather the actual implementation. Interface in java can help achieve this concept very well.

Interface provides contract between the parties, example, producer and consumer. Producer produces the goods without letting know the consumer how the product is being made. But, through interface, Producer let all consumer know what product can buy. With the help of abstraction, producer can markets the product to their consumers.

Encapsulation:

Encapsulation is one level down of abstraction. Same product company try shielding information from each other production group. Example, if a company produce wine and chocolate, encapsulation helps shielding information how each product Is being made from each other.

  1. If I have individual package one for wine and another one for chocolate, and if all the classes are declared in the package as default access modifier, we are giving package level encapsulation for all classes.
  2. Within a package, if we declare each class filed (member field) as private and having a public method to access those fields, this way giving class level encapsulation to those fields

find path of current folder - cmd

2015-03-30: Edited - Missing information has been added

To retrieve the current directory you can use the dynamic %cd% variable that holds the current active directory

set "curpath=%cd%"

This generates a value with a ending backslash for the root directory, and without a backslash for the rest of directories. You can force and ending backslash for any directory with

for %%a in ("%cd%\") do set "curpath=%%~fa"

Or you can use another dynamic variable: %__CD__% that will return the current active directory with an ending backslash.

Also, remember the %cd% variable can have a value directly assigned. In this case, the value returned will not be the current directory, but the assigned value. You can prevent this with a reference to the current directory

for %%a in (".\") do set "curpath=%%~fa"

Up to windows XP, the %__CD__% variable has the same behaviour. It can be overwritten by the user, but at least from windows 7 (i can't test it on Vista), any change to the %__CD__% is allowed but when the variable is read, the changed value is ignored and the correct current active directory is retrieved (note: the changed value is still visible using the set command).

BUT all the previous codes will return the current active directory, not the directory where the batch file is stored.

set "curpath=%~dp0"

It will return the directory where the batch file is stored, with an ending backslash.

BUT this will fail if in the batch file the shift command has been used

shift
echo %~dp0

As the arguments to the batch file has been shifted, the %0 reference to the current batch file is lost.

To prevent this, you can retrieve the reference to the batch file before any shifting, or change the syntax to shift /1 to ensure the shift operation will start at the first argument, not affecting the reference to the batch file. If you can not use any of this options, you can retrieve the reference to the current batch file in a call to a subroutine

@echo off
    setlocal enableextensions

    rem Destroy batch file reference
    shift
    echo batch folder is "%~dp0"

    rem Call the subroutine to get the batch folder 
    call :getBatchFolder batchFolder
    echo batch folder is "%batchFolder%"

    exit /b

:getBatchFolder returnVar
    set "%~1=%~dp0" & exit /b

This approach can also be necessary if when invoked the batch file name is quoted and a full reference is not used (read here).

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'demoRestController'

Your DemoApplication class is in the com.ag.digital.demo.boot package and your LoginBean class is in the com.ag.digital.demo.bean package. By default components (classes annotated with @Component) are found if they are in the same package or a sub-package of your main application class DemoApplication. This means that LoginBean isn't being found so dependency injection fails.

There are a couple of ways to solve your problem:

  1. Move LoginBean into com.ag.digital.demo.boot or a sub-package.
  2. Configure the packages that are scanned for components using the scanBasePackages attribute of @SpringBootApplication that should be on DemoApplication.

A few of other things that aren't causing a problem, but are not quite right with the code you've posted:

  • @Service is a specialisation of @Component so you don't need both on LoginBean
  • Similarly, @RestController is a specialisation of @Component so you don't need both on DemoRestController
  • DemoRestController is an unusual place for @EnableAutoConfiguration. That annotation is typically found on your main application class (DemoApplication) either directly or via @SpringBootApplication which is a combination of @ComponentScan, @Configuration, and @EnableAutoConfiguration.

How to solve maven 2.6 resource plugin dependency?

I had exactly the same error. My network is an internal one of a company. The proxy has been disabled from the IT team so for that we do not have to enable any proxy settings. I have commented the proxy setting in settings.xml file from the below mentioned locations C:\Users\vijay.singh.m2\settings.xml This fixed the same issue for me

pandas get column average/mean

You can use either of the two statements below:

numpy.mean(df['col_name'])
# or
df['col_name'].mean()

Android Studio Run/Debug configuration error: Module not specified

This issue also may happen when you just installed new Android studio and importing some project, in the new Android studio only the latest sdk is downloaded(for example currently the latest is 30) and if your project target sdk is 29 you will not see your module in run configuring dialog.

So download the sdk that your app is targeted, then run Sync project with gradle files.

enter image description here

Write a number with two decimal places SQL Server

This will allow total 10 digits with 2 values after the decimal. It means that it can accomodate the value value before decimal upto 8 digits and 2 after decimal.

To validate, put the value in the following query.

DECLARE vtest  number(10,2);
BEGIN
SELECT 10.008 INTO vtest FROM dual;
dbms_output.put_line(vtest);
END;

wget/curl large file from google drive

JULY 2020 - Windows users batch file solution

I would like to add a simple batch file solution for windows users, as I found only linux solutions and it took me several days to learn all this stuff for creating a solution for windows. So to save this work from others that may need it, here it is.

Tools you need

  1. wget for windows (small 5KB exe program, no need installation) Download it from here. https://eternallybored.org/misc/wget/

  2. jrepl for windows (small 117KB batch file program, no need installation) This tool is similar to linux sed tool. Download it from here: https://www.dostips.com/forum/viewtopic.php?t=6044

Assuming

%filename% - the file name you want the the download will be saved to.
%fileid% = google file id (as already was explained here before)

Batch code for downloading small file from google drive

wget -O "%filename%" "https://docs.google.com/uc?export=download&id=%fileid%"        

Batch code for downloading large file from google drive

set cookieFile="cookie.txt"
set confirmFile="confirm.txt"
   
REM downlaod cooky and message with request for confirmation
wget --quiet --save-cookies "%cookieFile%" --keep-session-cookies --no-check-certificate "https://docs.google.com/uc?export=download&id=%fileid%" -O "%confirmFile%"
   
REM extract confirmation key from message saved in confirm file and keep in variable resVar
jrepl ".*confirm=([0-9A-Za-z_]+).*" "$1" /F "%confirmFile%" /A /rtn resVar
   
REM when jrepl writes to variable, it adds carriage return (CR) (0x0D) and a line feed (LF) (0x0A), so remove these two last characters
set confirmKey=%resVar:~0,-2%
   
REM download the file using cookie and confirmation key
wget --load-cookies "%cookieFile%" -O "%filename%" "https://docs.google.com/uc?export=download&id=%fileid%&confirm=%confirmKey%"
   
REM clear temporary files 
del %cookieFile%
del %confirmFile%

not finding android sdk (Unity)

  1. Delete android sdk "tools" folder : [Your Android SDK root]/tools -> tools

  2. Download SDK Tools: http://dl-ssl.google.com/android/repository/tools_r25.2.5-windows.zip

  3. Extract that to Android SDK root

  4. Build your project

After that it didn't work for me yet, I had to

  1. Go to the Java archives (http://www.oracle.com/technetwork/java/javase/downloads/java-archive-javase8-2177648.html)

  2. Search for the jdk-8u131 release.

  3. Accept the Licence Agreement,make an account and download the release.

  4. Install it and define it as JDK path in Unity.

source : https://www.reddit.com/r/Unity3D/comments/77azfb/i_cant_get_unity_to_build_run_my_game/

Relationship between hashCode and equals method in Java

See JavaDoc of java.lang.Object

In hashCode() it says:

If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.

(Emphasis by me).

If you only override equals() and not hashCode() your class violates this contract.

This is also said in the JavaDoc of the equals() method:

Note that it is generally necessary to override the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes.

git: Your branch is ahead by X commits

Then when I do a git status it tells me that my branch is ahead by X commits (presumably the same number of commits that I have made).

My experience is in a team environment with many branches. We work in our own feature branches (in local clones) and it was one of those that git status showed I was 11 commits ahead. My working assumption, like the question's author, was that +11 was from commits of my own.

It turned out that I had pulled in changes from the common develop branch into my feature branch many weeks earlier -- but forgot! When I revisited my local feature branch today and did a git pull origin develop the number jumped to +41 commits ahead. Much work had been done in develop and so my local feature branch was even further ahead of the feature branch on the origin repository.

So, if you get this message, think back to any pulls/merges you might have done from other branches (of your own, or others) you have access to. The message just signals you need to git push those pulled changes back to the origin repo ('tracking branch') from your local repo to get things sync'd up.

log4j:WARN No appenders could be found for logger in web.xml

I had the same problem . Same configuration settings and same warning message . What worked for me was : Changing the order of the entries .

  • I put the entries for the log configuration [ the context param and the listener ] on the top of the file [ before the entry for the applicationContext.xml ] and it worked .

The Order matters , i guess .

How should I deal with "package 'xxx' is not available (for R version x.y.z)" warning?

1. You can't spell

The first thing to test is have you spelled the name of the package correctly? Package names are case sensitive in R.


2. You didn't look in the right repository

Next, you should check to see if the package is available. Type

setRepositories()

See also ?setRepositories.

To see which repositories R will look in for your package, and optionally select some additional ones. At the very least, you will usually want CRAN to be selected, and CRAN (extras) if you use Windows, and the Bioc* repositories if you do any [gen/prote/metabol/transcript]omics biological analyses.

To permanently change this, add a line like setRepositories(ind = c(1:6, 8)) to your Rprofile.site file.


3. The package is not in the repositories you selected

Return all the available packages using

ap <- available.packages()

See also Names of R's available packages, ?available.packages.

Since this is a large matrix, you may wish to use the data viewer to examine it. Alternatively, you can quickly check to see if the package is available by testing against the row names.

View(ap)
"foobarbaz" %in% rownames(ap)

Alternatively, the list of available packages can be seen in a browser for CRAN, CRAN (extras), Bioconductor, R-forge, RForge, and github.

Another possible warnings message you may get when interacting with CRAN mirrors is:

Warning: unable to access index for repository

Which may indicate the selected CRAN repository is currently be unavailable. You can select a different mirror with chooseCRANmirror() and try the installation again.


There are several reasons why a package may not be available.


4. You don't want a package

Perhaps you don't really want a package. It is common to be confused about the difference between a package and a library, or a package and a dataset.

A package is a standardized collection of material extending R, e.g. providing code, data, or documentation. A library is a place (directory) where R knows to find packages it can use

To see available datasets, type

data()

5. R or Bioconductor is out of date

It may have a dependency on a more recent version of R (or one of the packages that it imports/depends upon does). Look at

ap["foobarbaz", "Depends"]

and consider updating your R installation to the current version. On Windows, this is most easily done via the installr package.

library(installr)
updateR()

(Of course, you may need to install.packages("installr") first.)

Equivalently for Bioconductor packages, you may need to update your Bioconductor installation.

source("http://bioconductor.org/biocLite.R")
biocLite("BiocUpgrade")

6. The package is out of date

It may have been archived (if it is no longer maintained and no longer passes R CMD check tests).

In this case, you can load an old version of the package using install_version()

library(remotes)
install_version("foobarbaz", "0.1.2")

An alternative is to install from the github CRAN mirror.

library(remotes)
install_github("cran/foobarbaz")

7. There is no Windows/OS X/Linux binary

It may not have a Windows binary due to requiring additional software that CRAN does not have. Additionally, some packages are available only via the sources for some or all platforms. In this case, there may be a version in the CRAN (extras) repository (see setRepositories above).

If the package requires compiling code (e.g. C, C++, FORTRAN) then on Windows install Rtools or on OS X install the developer tools accompanying XCode, and install the source version of the package via:

install.packages("foobarbaz", type = "source")

# Or equivalently, for Bioconductor packages:
source("http://bioconductor.org/biocLite.R")
biocLite("foobarbaz", type = "source")

On CRAN, you can tell if you'll need special tools to build the package from source by looking at the NeedsCompilation flag in the description.


8. The package is on github/Bitbucket/Gitorious

It may have a repository on Github/Bitbucket/Gitorious. These packages require the remotes package to install.

library(remotes)
install_github("packageauthor/foobarbaz")
install_bitbucket("packageauthor/foobarbaz")
install_gitorious("packageauthor/foobarbaz")

(As with installr, you may need to install.packages("remotes") first.)


9. There is no source version of the package

Although the binary version of your package is available, the source version is not. You can turn off this check by setting

options(install.packages.check.source = "no")

as described in this SO answer by imanuelc and the Details section of ?install.packages.


10. The package is in a non-standard repository

Your package is in a non-standard repository (e.g. Rbbg). Assuming that it is reasonably compliant with CRAN standards, you can still download it using install.packages; you just have to specify the repository URL.

install.packages("Rbbg", repos = "http://r.findata.org")

RHIPE on the other hand isn't in a CRAN-like repository and has its own installation instructions.

How to create permanent PowerShell Aliases

UPDATED - January 2021

It's possible to store in a profile.ps1 file any PowerShell code to be executed each time PowerShell starts. There are at least 6 different paths where to store the code depending on which user has to execute it. We will consider only 2 of them: the "all users" and the "only your user" paths (follow the previous link for further options).

To answer your question, you only have to create a profile.ps1 file containing the code you want to be executed, that is:

New-Alias Goto Set-Location

and save it in the proper path:

  • "$Home\Documents" (usually C:\Users<yourname>\Documents): Only your user will execute the code. This is the reccomanded place.
    You can quickly find your profile location by running echo $profile in PowerShell
  • $PsHome (C:\Windows\System32\WindowsPowerShell\v1.0): Every user will execute the code.

IMPORTANT: Remember you need to restart your PowerShell instances to apply the changes.

TIPS

  • If both paths contain a profile.ps1 file, the all-users one is executed first, then the user-specific one. This means the user-specific commands will overwrite variables in case of duplicates or conflicts.

  • Always put the code in the user-specific profile if there is no need to extend its execution to every user. This is safer because you don't pollute other users' space (usually, you don't want to do that).
    Another advantage is that you don't need administrator rights to add the file to your user-space (you do for anything in C:\Windows\System32).

  • If you really need to execute the profile code for every user, mind that the $PsHome path is different for 32bit and 64bit instances of PowerShell. You should consider both environments if you want to always execute the profile code.
    The paths are:

    • C:\Windows\System32\WindowsPowerShell\v1.0 for the 64bit environment
    • C:\Windows\SysWow64\WindowsPowerShell\v1.0 for the 32bit one (Yeah I know, the folder naming is counterintuitive, but it's correct).

Re-enabling window.alert in Chrome

I can see that this only for actually turning the dialogs back on. But if you are a web dev and you would like to see a way to possibly have some form of notification when these are off...in the case that you are using native alerts/confirms for validation or whatever. Check this solution to detect and notify the user https://stackoverflow.com/a/23697435/1248536

How do I enable TODO/FIXME/XXX task tags in Eclipse?

There are apparently distributions or custom builds in which the ability to set Task Tags for non-Java files is not present. This post mentions that ColdFusion Builder (built on Eclipse) does not let you set non-Java Task Tags, but the beta version of CF Builder 2 does. (I know the OP wasn't using CF Builder, but I am, and I was wondering about this question myself ... because he didn't see the ability to set non-Java tags, I thought others might be in the same position.)

Calling a php function by onclick event

Use this html code it will surely help you

<input type="button" value="NEXT"  onclick="document.write('<?php //call a function here ex- 'fun();' ?>');" />

one limitation is that it is taking more time to run so wait for few seconds it will work

Executing a batch script on Windows shutdown

You can create a local computer policy on Windows. See the TechNet at http://technet.microsoft.com/en-us/magazine/dd630947

  1. Run gpedit.msc to open the Group Policy Editor,
  2. Navigate to Computer Configuration | Windows Settings | Scripts (Startup/Shutdown).

enter image description here

Get AVG ignoring Null or Zero values

NULL is already ignored so you can use NULLIF to turn 0 to NULL. Also you don't need DISTINCT and your WHERE on ActualTime is not sargable.

SELECT AVG(cast(NULLIF(a.SecurityW, 0) AS BIGINT)) AS Average1,
       AVG(cast(NULLIF(a.TransferW, 0) AS BIGINT)) AS Average2,
       AVG(cast(NULLIF(a.StaffW, 0) AS BIGINT))    AS Average3
FROM   Table1 a
WHERE  a.ActualTime >= '20130401'
       AND a.ActualTime < '20130501' 

PS I have no idea what Table2 b is in the original query for as there is no join condition for it so have omitted it from my answer.

Cannot attach the file *.mdf as database

Just change database name from web.config project level file and then update database.

connectionString = Data Source =(LocalDb)\MSSQLLocalDB;AttachDbFilename="|DataDirectory|\aspnet-Project name-20180413070506.mdf";Initial Catalog="aspnet--20180413070506";Integrated

Change the bold digit to some other number:

connectionString = Data Source==(LocalDb)\MSSQLLocalDB;AttachDbFilename="|DataDirectory|\aspnet-Project name-20180413070507.mdf";Initial Catalog="aspnet--20180413070507";Integrated

Switch statement for greater-than/less-than

What exactly are you doing in //do stuff?

You may be able to do something like:

(scrollLeft < 1000) ? //do stuff
: (scrollLeft > 1000 && scrollLeft < 2000) ? //do stuff
: (scrollLeft > 2000) ? //do stuff
: //etc. 

How to make a SIMPLE C++ Makefile

I used friedmud's answer. I looked into this for a while, and it seems to be a good way to get started. This solution also has a well defined method of adding compiler flags. I answered again, because I made changes to make it work in my environment, Ubuntu and g++. More working examples are the best teacher, sometimes.

appname := myapp

CXX := g++
CXXFLAGS := -Wall -g

srcfiles := $(shell find . -maxdepth 1 -name "*.cpp")
objects  := $(patsubst %.cpp, %.o, $(srcfiles))

all: $(appname)

$(appname): $(objects)
    $(CXX) $(CXXFLAGS) $(LDFLAGS) -o $(appname) $(objects) $(LDLIBS)

depend: .depend

.depend: $(srcfiles)
    rm -f ./.depend
    $(CXX) $(CXXFLAGS) -MM $^>>./.depend;

clean:
    rm -f $(objects)

dist-clean: clean
    rm -f *~ .depend

include .depend

Makefiles seem to be very complex. I was using one, but it was generating an error related to not linking in g++ libraries. This configuration solved that problem.

Make a URL-encoded POST request using `http.NewRequest(...)`

URL-encoded payload must be provided on the body parameter of the http.NewRequest(method, urlStr string, body io.Reader) method, as a type that implements io.Reader interface.

Based on the sample code:

package main

import (
    "fmt"
    "net/http"
    "net/url"
    "strconv"
    "strings"
)

func main() {
    apiUrl := "https://api.com"
    resource := "/user/"
    data := url.Values{}
    data.Set("name", "foo")
    data.Set("surname", "bar")

    u, _ := url.ParseRequestURI(apiUrl)
    u.Path = resource
    urlStr := u.String() // "https://api.com/user/"

    client := &http.Client{}
    r, _ := http.NewRequest(http.MethodPost, urlStr, strings.NewReader(data.Encode())) // URL-encoded payload
    r.Header.Add("Authorization", "auth_token=\"XXXXXXX\"")
    r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
    r.Header.Add("Content-Length", strconv.Itoa(len(data.Encode())))

    resp, _ := client.Do(r)
    fmt.Println(resp.Status)
}

resp.Status is 200 OK this way.

wampserver doesn't go green - stays orange

I have had this issue before and it turned out that Skype was interferring with port 80. So you may have to look at your system to see if you have another application utilizing this port.

Anyway under Skype, to change this setting it was: Tools->Options->Advanced->Connection->Use port 80 and 443 as alternatives for incoming connections. Untick this, restart Skype, restart wamp.

Related question

Installing and Running MongoDB on OSX

Problem here is you are trying to open a mongo shell without starting a mongo db which is listening to port 127.0.0.1:27017(deafault for mongo db) thats what the error is all about:

Error: couldn't connect to server 127.0.0.1:27017 at src/mongo/shell/mongo.js:145 exception: connect failed

The easiest solution is to open the terminal and type

$ mongod --dbpath ~/data/db

Note: dbpath here is "Users/user" where data/db directories are created

i.e., you need to create directory data and sub directory db in your user folder. For e.g say `

/Users/johnny/data

After mongo db is up. Open another terminal in new window and type

$ mongo

it will open mongo shell with your mongo db connection opened in another terminal.

git checkout tag, git pull fails in branch

In order to just download updates:

git fetch origin master

However, this just updates a reference called origin/master. The best way to update your local master would be the checkout/merge mentioned in another comment. If you can guarantee that your local master has not diverged from the main trunk that origin/master is on, you could use git update-ref to map your current master to the new point, but that's probably not the best solution to be using on a regular basis...

Undefined or null for AngularJS

lodash provides a shorthand method to check if undefined or null: _.isNil(yourVariable)

Python - How to concatenate to a string in a for loop?

This should work:

endstring = ''.join(list)

performSelector may cause a leak because its selector is unknown

As a workaround until the compiler allows overriding the warning, you can use the runtime

objc_msgSend(_controller, NSSelectorFromString(@"someMethod"));

instead of

[_controller performSelector:NSSelectorFromString(@"someMethod")];

You'll have to

#import <objc/message.h>

Import an Excel worksheet into Access using VBA

Pass the sheet name with the Range parameter of the DoCmd.TransferSpreadsheet Method. See the box titled "Worksheets in the Range Parameter" near the bottom of that page.

This code imports from a sheet named "temp" in a workbook named "temp.xls", and stores the data in a table named "tblFromExcel".

Dim strXls As String
strXls = CurrentProject.Path & Chr(92) & "temp.xls"
DoCmd.TransferSpreadsheet acImport, , "tblFromExcel", _
    strXls, True, "temp!"

what is the use of $this->uri->segment(3) in codeigniter pagination

In your code $this->uri->segment(3) refers to the pagination offset which you use in your query. According to your $config['base_url'] = base_url().'index.php/papplicant/viewdeletedrecords/' ;, $this->uri->segment(3) i.e segment 3 refers to the offset. The first segment is the controller, second is the method, there after comes the parameters sent to the controllers as segments.

How to cast from List<Double> to double[] in Java?

You can convert to a Double[] by calling frameList.toArray(new Double[frameList.size()]), but you'll need to iterate the list/array to convert to double[]

Programmatically Hide/Show Android Soft Keyboard

Did you try InputMethodManager.SHOW_IMPLICIT in first window.

and for hiding in second window use InputMethodManager.HIDE_IMPLICIT_ONLY

EDIT :

If its still not working then probably you are putting it at the wrong place. Override onFinishInflate() and show/hide there.

@override
public void onFinishInflate() {
     /* code to show keyboard on startup */
    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.showSoftInput(mUserNameEdit, InputMethodManager.SHOW_IMPLICIT);
}

Disabling Log4J Output in Java

If you want to turn off logging programmatically then use

List<Logger> loggers = Collections.<Logger>list(LogManager.getCurrentLoggers());
loggers.add(LogManager.getRootLogger());
for ( Logger logger : loggers ) {
    logger.setLevel(Level.OFF);
}

mysqli_real_connect(): (HY000/2002): No such file or directory

First of all, make sure the mysql service is running:

ps elf|grep mysql

you will see an output like this if is running:

4 S root      9642     1  0  80   0 -  2859 do_wai 23:08 pts/0    00:00:00 /bin/sh /usr/bin/mysqld_safe --datadir=/var/lib/mysql --pid-file=/var/lib/mysql/tomcat-machine.local.pid
4 S mysql     9716  9642  0  80   0 - 200986 poll_s 23:08 pts/0   00:00:00 /usr/sbin/mysqld --basedir=/usr --datadir=/var/lib/mysql --plugin-dir=/usr/lib64/mysql/plugin --user=mysql --log-error=/var/lib/mysql/tomcat-machine.local.err --pid-file=/var/lib/mysql/tomcat-machine.local.pid

then change localhost to 127.0.0.1 in config.inc.php

$cfg['Servers'][$i]['host'] = '127.0.0.1';

The default password for "root" user is empty "" do not type anything for the password

If it does not allow empty password you need to edit config.inc.php again and change:

$cfg['Servers'][$i]['AllowNoPassword'] = true;

The problem is a combination of config settings and MySQL not running. This was what helped me to fix this error.

How do I get a list of locked users in an Oracle database?

select username,
       account_status 
  from dba_users 
 where lock_date is not null;

This will actually give you the list of locked users.

How do I get a platform-dependent new line character?

Avoid appending strings using String + String etc, use StringBuilder instead.

String separator = System.getProperty( "line.separator" );
StringBuilder lines = new StringBuilder( line1 );
lines.append( separator );
lines.append( line2 );
lines.append( separator );
String result = lines.toString( );

OpenMP set_num_threads() is not working

According to the GCC manual for omp_get_num_threads:

In a sequential section of the program omp_get_num_threads returns 1

So this:

cout<<"sum="<<sum<<endl;
cout<<"threads="<<omp_get_num_threads()<<endl;

Should be changed to something like:

#pragma omp parallel
{
    cout<<"sum="<<sum<<endl;
    cout<<"threads="<<omp_get_num_threads()<<endl;
}

The code I use follows Hristo's advice of disabling dynamic teams, too.

Can Rails Routing Helpers (i.e. mymodel_path(model)) be Used in Models?

Any logic having to do with what is displayed in the view should be delegated to a helper method, as methods in the model are strictly for handling data.

Here is what you could do:

# In the helper...

def link_to_thing(text, thing)
  (thing.url?) ? link_to(text, thing_path(thing)) : link_to(text, thing.url)
end

# In the view...

<%= link_to_thing("text", @thing) %>

File size exceeds configured limit (2560000), code insight features not available

Changing the above options form Help menu didn't work for me. You have edit idea.properties file and change to some large no.

MAC: /Applications/<Android studio>.app/Contents/bin[Open App contents] 

Idea.max.intellisense.filesize=999999 

WINDOWS: IDE_HOME\bin\idea.properties

Getting text from td cells with jQuery

$(".field-group_name").each(function() {
        console.log($(this).text());
    });

How to get memory usage at runtime using C++?

David Robert Nadeau has put a good self contained multi-platform C function to get the process resident set size (physical memory use) in his website:

/*
 * Author:  David Robert Nadeau
 * Site:    http://NadeauSoftware.com/
 * License: Creative Commons Attribution 3.0 Unported License
 *          http://creativecommons.org/licenses/by/3.0/deed.en_US
 */

#if defined(_WIN32)
#include <windows.h>
#include <psapi.h>

#elif defined(__unix__) || defined(__unix) || defined(unix) || (defined(__APPLE__) && defined(__MACH__))
#include <unistd.h>
#include <sys/resource.h>

#if defined(__APPLE__) && defined(__MACH__)
#include <mach/mach.h>

#elif (defined(_AIX) || defined(__TOS__AIX__)) || (defined(__sun__) || defined(__sun) || defined(sun) && (defined(__SVR4) || defined(__svr4__)))
#include <fcntl.h>
#include <procfs.h>

#elif defined(__linux__) || defined(__linux) || defined(linux) || defined(__gnu_linux__)
#include <stdio.h>

#endif

#else
#error "Cannot define getPeakRSS( ) or getCurrentRSS( ) for an unknown OS."
#endif





/**
 * Returns the peak (maximum so far) resident set size (physical
 * memory use) measured in bytes, or zero if the value cannot be
 * determined on this OS.
 */
size_t getPeakRSS( )
{
#if defined(_WIN32)
    /* Windows -------------------------------------------------- */
    PROCESS_MEMORY_COUNTERS info;
    GetProcessMemoryInfo( GetCurrentProcess( ), &info, sizeof(info) );
    return (size_t)info.PeakWorkingSetSize;

#elif (defined(_AIX) || defined(__TOS__AIX__)) || (defined(__sun__) || defined(__sun) || defined(sun) && (defined(__SVR4) || defined(__svr4__)))
    /* AIX and Solaris ------------------------------------------ */
    struct psinfo psinfo;
    int fd = -1;
    if ( (fd = open( "/proc/self/psinfo", O_RDONLY )) == -1 )
        return (size_t)0L;      /* Can't open? */
    if ( read( fd, &psinfo, sizeof(psinfo) ) != sizeof(psinfo) )
    {
        close( fd );
        return (size_t)0L;      /* Can't read? */
    }
    close( fd );
    return (size_t)(psinfo.pr_rssize * 1024L);

#elif defined(__unix__) || defined(__unix) || defined(unix) || (defined(__APPLE__) && defined(__MACH__))
    /* BSD, Linux, and OSX -------------------------------------- */
    struct rusage rusage;
    getrusage( RUSAGE_SELF, &rusage );
#if defined(__APPLE__) && defined(__MACH__)
    return (size_t)rusage.ru_maxrss;
#else
    return (size_t)(rusage.ru_maxrss * 1024L);
#endif

#else
    /* Unknown OS ----------------------------------------------- */
    return (size_t)0L;          /* Unsupported. */
#endif
}





/**
 * Returns the current resident set size (physical memory use) measured
 * in bytes, or zero if the value cannot be determined on this OS.
 */
size_t getCurrentRSS( )
{
#if defined(_WIN32)
    /* Windows -------------------------------------------------- */
    PROCESS_MEMORY_COUNTERS info;
    GetProcessMemoryInfo( GetCurrentProcess( ), &info, sizeof(info) );
    return (size_t)info.WorkingSetSize;

#elif defined(__APPLE__) && defined(__MACH__)
    /* OSX ------------------------------------------------------ */
    struct mach_task_basic_info info;
    mach_msg_type_number_t infoCount = MACH_TASK_BASIC_INFO_COUNT;
    if ( task_info( mach_task_self( ), MACH_TASK_BASIC_INFO,
        (task_info_t)&info, &infoCount ) != KERN_SUCCESS )
        return (size_t)0L;      /* Can't access? */
    return (size_t)info.resident_size;

#elif defined(__linux__) || defined(__linux) || defined(linux) || defined(__gnu_linux__)
    /* Linux ---------------------------------------------------- */
    long rss = 0L;
    FILE* fp = NULL;
    if ( (fp = fopen( "/proc/self/statm", "r" )) == NULL )
        return (size_t)0L;      /* Can't open? */
    if ( fscanf( fp, "%*s%ld", &rss ) != 1 )
    {
        fclose( fp );
        return (size_t)0L;      /* Can't read? */
    }
    fclose( fp );
    return (size_t)rss * (size_t)sysconf( _SC_PAGESIZE);

#else
    /* AIX, BSD, Solaris, and Unknown OS ------------------------ */
    return (size_t)0L;          /* Unsupported. */
#endif
}

Usage

size_t currentSize = getCurrentRSS( );
size_t peakSize    = getPeakRSS( );

For more discussion, check the web site, it also provides a function to get the physical memory size of a system.

How to store an array into mysql?

If you just store the data in a database as you would if you were manually putting it into an array

"INSERT INTO database_name.database_table (`array`)
    VALUES
    ('One,Two,Three,Four')";

Then when you are pulling from the database, use the explode() function

$sql = mysql_query("SELECT * FROM database_name.database_table");
$numrows = mysql_num_rows($sql);
if($numrows != 0){
    while($rows = mysql_fetch_assoc($sql)){
        $array_from_db = $rows['array'];
    }
}else{
    echo "No rows found!".mysql_error();
}
$array = explode(",",$array_from_db);
foreach($array as $varchar){
    echo $varchar."<br/>";
}

Like so!

CSS flexbox not working in IE10

IE10 has uses the old syntax. So:

display: -ms-flexbox; /* will work on IE10 */
display: flex; /* is new syntax, will not work on IE10 */

see css-tricks.com/snippets/css/a-guide-to-flexbox:

(tweener) means an odd unofficial syntax from [2012] (e.g. display: flexbox;)

How to update all MySQL table rows at the same time?

Just add parameters, split by comma:

UPDATE tablename SET column1 = "value1", column2 = "value2" ....

see the link also MySQL UPDATE

Use Fieldset Legend with bootstrap

I had a different approach , used bootstrap panel to show it little more rich. Just to help someone and improve the answer.

_x000D_
_x000D_
.text-on-pannel {_x000D_
  background: #fff none repeat scroll 0 0;_x000D_
  height: auto;_x000D_
  margin-left: 20px;_x000D_
  padding: 3px 5px;_x000D_
  position: absolute;_x000D_
  margin-top: -47px;_x000D_
  border: 1px solid #337ab7;_x000D_
  border-radius: 8px;_x000D_
}_x000D_
_x000D_
.panel {_x000D_
  /* for text on pannel */_x000D_
  margin-top: 27px !important;_x000D_
}_x000D_
_x000D_
.panel-body {_x000D_
  padding-top: 30px !important;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />_x000D_
<div class="container">_x000D_
  <div class="panel panel-primary">_x000D_
    <div class="panel-body">_x000D_
      <h3 class="text-on-pannel text-primary"><strong class="text-uppercase"> Title </strong></h3>_x000D_
      <p> Your Code </p>_x000D_
    </div>_x000D_
  </div>_x000D_
  <div>
_x000D_
_x000D_
_x000D_

This will give below look. enter image description here

Note: We need to change the styles in order to use different header size.

Prevent WebView from displaying "web page not available"

Finally, I solved this. (It works till now..)

My solution is like this...

  1. Prepare the layout to show when an error occurred instead of Web Page (a dirty 'page not found message') The layout has one button, "RELOAD" with some guide messages.

  2. If an error occurred, Remember using boolean and show the layout we prepare.

  3. If user click "RELOAD" button, set mbErrorOccured to false. And Set mbReloadPressed to true.
  4. if mbErrorOccured is false and mbReloadPressed is true, it means webview loaded page successfully. 'Cause if error occurred again, mbErrorOccured will be set true on onReceivedError(...)

Here is my full source. Check this out.

public class MyWebViewActivity extends ActionBarActivity implements OnClickListener {

    private final String TAG = MyWebViewActivity.class.getSimpleName();
    private WebView mWebView = null;
    private final String URL = "http://www.google.com";
    private LinearLayout mlLayoutRequestError = null;
    private Handler mhErrorLayoutHide = null;

    private boolean mbErrorOccured = false;
    private boolean mbReloadPressed = false;

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_webview);

        ((Button) findViewById(R.id.btnRetry)).setOnClickListener(this);
        mlLayoutRequestError = (LinearLayout) findViewById(R.id.lLayoutRequestError);
        mhErrorLayoutHide = getErrorLayoutHideHandler();

        mWebView = (WebView) findViewById(R.id.webviewMain);
        mWebView.setWebViewClient(new MyWebViewClient());
        WebSettings settings = mWebView.getSettings();
        settings.setJavaScriptEnabled(true);
        mWebView.setWebChromeClient(getChromeClient());
        mWebView.loadUrl(URL);
    }

    @Override
    public boolean onSupportNavigateUp() {
        return super.onSupportNavigateUp();
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();

        if (id == R.id.btnRetry) {
            if (!mbErrorOccured) {
                return;
            }

            mbReloadPressed = true;
            mWebView.reload();
            mbErrorOccured = false;
        }
    }

    @Override
    public void onBackPressed() {
        if (mWebView.canGoBack()) {
            mWebView.goBack();
            return;
        }
        else {
            finish();
        }

        super.onBackPressed();
    }

    class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            return super.shouldOverrideUrlLoading(view, url);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onLoadResource(WebView view, String url) {
            super.onLoadResource(view, url);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            if (mbErrorOccured == false && mbReloadPressed) {
                hideErrorLayout();
                mbReloadPressed = false;
            }

            super.onPageFinished(view, url);
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            mbErrorOccured = true;
            showErrorLayout();
            super.onReceivedError(view, errorCode, description, failingUrl);
        }
    }

    private WebChromeClient getChromeClient() {
        final ProgressDialog progressDialog = new ProgressDialog(MyWebViewActivity.this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setCancelable(false);

        return new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
            }
        };
    }

    private void showErrorLayout() {
        mlLayoutRequestError.setVisibility(View.VISIBLE);
    }

    private void hideErrorLayout() {
        mhErrorLayoutHide.sendEmptyMessageDelayed(10000, 200);
    }

    private Handler getErrorLayoutHideHandler() {
        return new Handler() {
            @Override
            public void handleMessage(Message msg) {
                mlLayoutRequestError.setVisibility(View.GONE);
                super.handleMessage(msg);
            }
        };
    }
}

Addition:Here is layout....

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/rLayoutWithWebView"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<WebView
    android:id="@+id/webviewMain"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

<LinearLayout
    android:id="@+id/lLayoutRequestError"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_centerInParent="true"
    android:background="@color/white"
    android:gravity="center"
    android:orientation="vertical"
    android:visibility="gone" >

    <Button
        android:id="@+id/btnRetry"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:minWidth="120dp"
        android:text="RELOAD"
        android:textSize="20dp"
        android:textStyle="bold" />
</LinearLayout>

How can I properly handle 404 in ASP.NET MVC?

Quick Answer / TL;DR

enter image description here

For the lazy people out there:

Install-Package MagicalUnicornMvcErrorToolkit -Version 1.0

Then remove this line from global.asax

GlobalFilters.Filters.Add(new HandleErrorAttribute());

And this is only for IIS7+ and IIS Express.

If you're using Cassini .. well .. um .. er.. awkward ... awkward


Long, explained answer

I know this has been answered. But the answer is REALLY SIMPLE (cheers to David Fowler and Damian Edwards for really answering this).

There is no need to do anything custom.

For ASP.NET MVC3, all the bits and pieces are there.

Step 1 -> Update your web.config in TWO spots.

<system.web>
    <customErrors mode="On" defaultRedirect="/ServerError">
      <error statusCode="404" redirect="/NotFound" />
    </customErrors>

and

<system.webServer>
    <httpErrors errorMode="Custom">
      <remove statusCode="404" subStatusCode="-1" />
      <error statusCode="404" path="/NotFound" responseMode="ExecuteURL" />
      <remove statusCode="500" subStatusCode="-1" />
      <error statusCode="500" path="/ServerError" responseMode="ExecuteURL" />
    </httpErrors>    

...
<system.webServer>
...
</system.web>

Now take careful note of the ROUTES I've decided to use. You can use anything, but my routes are

  • /NotFound <- for a 404 not found, error page.
  • /ServerError <- for any other error, include errors that happen in my code. this is a 500 Internal Server Error

See how the first section in <system.web> only has one custom entry? The statusCode="404" entry? I've only listed one status code because all other errors, including the 500 Server Error (ie. those pesky error that happens when your code has a bug and crashes the user's request) .. all the other errors are handled by the setting defaultRedirect="/ServerError" .. which says, if you are not a 404 page not found, then please goto the route /ServerError.

Ok. that's out of the way.. now to my routes listed in global.asax

Step 2 - Creating the routes in Global.asax

Here's my full route section..

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    routes.IgnoreRoute("{*favicon}", new {favicon = @"(.*/)?favicon.ico(/.*)?"});

    routes.MapRoute(
        "Error - 404",
        "NotFound",
        new { controller = "Error", action = "NotFound" }
        );

    routes.MapRoute(
        "Error - 500",
        "ServerError",
        new { controller = "Error", action = "ServerError"}
        );

    routes.MapRoute(
        "Default", // Route name
        "{controller}/{action}/{id}", // URL with parameters
        new {controller = "Home", action = "Index", id = UrlParameter.Optional}
        );
}

That lists two ignore routes -> axd's and favicons (ooo! bonus ignore route, for you!) Then (and the order is IMPERATIVE HERE), I have my two explicit error handling routes .. followed by any other routes. In this case, the default one. Of course, I have more, but that's special to my web site. Just make sure the error routes are at the top of the list. Order is imperative.

Finally, while we are inside our global.asax file, we do NOT globally register the HandleError attribute. No, no, no sir. Nadda. Nope. Nien. Negative. Noooooooooo...

Remove this line from global.asax

GlobalFilters.Filters.Add(new HandleErrorAttribute());

Step 3 - Create the controller with the action methods

Now .. we add a controller with two action methods ...

public class ErrorController : Controller
{
    public ActionResult NotFound()
    {
        Response.StatusCode = (int)HttpStatusCode.NotFound;
        return View();
    }

    public ActionResult ServerError()
    {
        Response.StatusCode = (int)HttpStatusCode.InternalServerError;

        // Todo: Pass the exception into the view model, which you can make.
        //       That's an exercise, dear reader, for -you-.
        //       In case u want to pass it to the view, if you're admin, etc.
        // if (User.IsAdmin) // <-- I just made that up :) U get the idea...
        // {
        //     var exception = Server.GetLastError();
        //     // etc..
        // }

        return View();
    }

    // Shhh .. secret test method .. ooOOooOooOOOooohhhhhhhh
    public ActionResult ThrowError()
    {
        throw new NotImplementedException("Pew ^ Pew");
    }
}

Ok, lets check this out. First of all, there is NO [HandleError] attribute here. Why? Because the built in ASP.NET framework is already handling errors AND we have specified all the shit we need to do to handle an error :) It's in this method!

Next, I have the two action methods. Nothing tough there. If u wish to show any exception info, then u can use Server.GetLastError() to get that info.

Bonus WTF: Yes, I made a third action method, to test error handling.

Step 4 - Create the Views

And finally, create two views. Put em in the normal view spot, for this controller.

enter image description here

Bonus comments

  • You don't need an Application_Error(object sender, EventArgs e)
  • The above steps all work 100% perfectly with Elmah. Elmah fraking wroxs!

And that, my friends, should be it.

Now, congrats for reading this much and have a Unicorn as a prize!

enter image description here