Programs & Examples On #Pushpin

MVC If statement in View

You only need to prefix an if statement with @ if you're not already inside a razor code block.

Edit: You have a couple of things wrong with your code right now.

You're declaring nmb, but never actually doing anything with the value. So you need figure out what that's supposed to actually be doing. In order to fix your code, you need to make a couple of tiny changes:

@if (ViewBag.Articles != null)
{
    int nmb = 0;
    foreach (var item in ViewBag.Articles)
    {
        if (nmb % 3 == 0)
        {
            @:<div class="row"> 
        }

        <a href="@Url.Action("Article", "Programming", new { id = item.id })">
            <div class="tasks">
                <div class="col-md-4">
                    <div class="task important">
                        <h4>@item.Title</h4>
                        <div class="tmeta">
                            <i class="icon-calendar"></i>
                                @item.DateAdded - Pregleda:@item.Click
                            <i class="icon-pushpin"></i> Authorrr
                        </div>
                    </div>
                </div>
            </div>
        </a>
        if (nmb % 3 == 0)
        {
            @:</div>
        }
    }
}

The important part here is the @:. It's a short-hand of <text></text>, which is used to force the razor engine to render text.

One other thing, the HTML standard specifies that a tags can only contain inline elements, and right now, you're putting a div, which is a block-level element, inside an a.

Subtracting two lists in Python

Python 2.7 and 3.2 added the collections.Counter class, which is a dictionary subclass that maps elements to the number of occurrences of the element. This can be used as a multiset. You can do something like this:

from collections import Counter
a = Counter([0, 1, 2, 1, 0])
b = Counter([0, 1, 1])
c = a - b  # ignores items in b missing in a

print(list(c.elements()))  # -> [0, 2]

As well, if you want to check that every element in b is in a:

# a[key] returns 0 if key not in a, instead of raising an exception
assert all(a[key] >= b[key] for key in b)

But since you are stuck with 2.5, you could try importing it and define your own version if that fails. That way you will be sure to get the latest version if it is available, and fall back to a working version if not. You will also benefit from speed improvements if if gets converted to a C implementation in the future.

try:
   from collections import Counter
except ImportError:
    class Counter(dict):
       ...

You can find the current Python source here.

Send file using POST from a Python script

Chris Atlee's poster library works really well for this (particularly the convenience function poster.encode.multipart_encode()). As a bonus, it supports streaming of large files without loading an entire file into memory. See also Python issue 3244.

Writing an Excel file in EPPlus

It's best if you worked with DataSets and/or DataTables. Once you have that, ideally straight from your stored procedure with proper column names for headers, you can use the following method:

ws.Cells.LoadFromDataTable(<DATATABLE HERE>, true, OfficeOpenXml.Table.TableStyles.Light8);

.. which will produce a beautiful excelsheet with a nice table!

Now to serve your file, assuming you have an ExcelPackage object as in your code above called pck..

Response.Clear();

Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("Content-Disposition", "attachment;filename=" + sFilename);

Response.BinaryWrite(pck.GetAsByteArray());
Response.End();

Hibernate Query By Example and Projections

The problem seems to happen when you have an alias the same name as the objects property. Hibernate seems to pick up the alias and use it in the sql. I found this documented here and here, and I believe it to be a bug in Hibernate, although I am not sure that the Hibernate team agrees.

Either way, I have found a simple work around that works in my case. Your mileage may vary. The details are below, I tried to simplify the code for this sample so I apologize for any errors or typo's:

Criteria criteria = session.createCriteria(MyClass.class)
    .setProjection(Projections.projectionList()
        .add(Projections.property("sectionHeader"), "sectionHeader")
        .add(Projections.property("subSectionHeader"), "subSectionHeader")
        .add(Projections.property("sectionNumber"), "sectionNumber"))
    .add(Restrictions.ilike("sectionHeader", sectionHeaderVar)) // <- Problem!
    .setResultTransformer(Transformers.aliasToBean(MyDTO.class));

Would produce this sql:

select
    this_.SECTION_HEADER as y1_,
    this_.SUB_SECTION_HEADER as y2_,
    this_.SECTION_NUMBER as y3_,
from
    MY_TABLE this_ 
where
    ( lower(y1_) like ? ) 

Which was causing an error: java.sql.SQLException: ORA-00904: "Y1_": invalid identifier

But, when I changed my restriction to use "this", like so:

Criteria criteria = session.createCriteria(MyClass.class)
    .setProjection(Projections.projectionList()
        .add(Projections.property("sectionHeader"), "sectionHeader")
        .add(Projections.property("subSectionHeader"), "subSectionHeader")
        .add(Projections.property("sectionNumber"), "sectionNumber"))
    .add(Restrictions.ilike("this.sectionHeader", sectionHeaderVar)) // <- Problem Solved!
    .setResultTransformer(Transformers.aliasToBean(MyDTO.class));

It produced the following sql and my problem was solved.

select
    this_.SECTION_HEADER as y1_,
    this_.SUB_SECTION_HEADER as y2_,
    this_.SECTION_NUMBER as y3_,
from
    MY_TABLE this_ 
where
    ( lower(this_.SECTION_HEADER) like ? ) 

Thats, it! A pretty simple fix to a painful problem. I don't know how this fix would translate to the query by example problem, but it may get you closer.

SQL Server Insert Example

I hope this will help you

Create table :

create table users (id int,first_name varchar(10),last_name varchar(10));

Insert values into the table :

insert into users (id,first_name,last_name) values(1,'Abhishek','Anand');

Drop a temporary table if it exists

What you asked for is:

IF OBJECT_ID('tempdb..##CLIENTS_KEYWORD') IS NOT NULL
    BEGIN
       DROP TABLE ##CLIENTS_KEYWORD

       CREATE TABLE ##CLIENTS_KEYWORD(client_id int)

    END
ELSE
   CREATE TABLE ##CLIENTS_KEYWORD(client_id int) 

IF OBJECT_ID('tempdb..##TEMP_CLIENTS_KEYWORD') IS NOT NULL
    BEGIN
       DROP TABLE ##TEMP_CLIENTS_KEYWORD

       CREATE TABLE ##TEMP_CLIENTS_KEYWORD(client_id int)

    END
ELSE
   CREATE TABLE ##TEMP_CLIENTS_KEYWORD(client_id int) 

Since you're always going to create the table, regardless of whether the table is deleted or not; a slightly optimised solution is:

IF OBJECT_ID('tempdb..##CLIENTS_KEYWORD') IS NOT NULL
   DROP TABLE ##CLIENTS_KEYWORD

CREATE TABLE ##CLIENTS_KEYWORD(client_id int) 

IF OBJECT_ID('tempdb..##TEMP_CLIENTS_KEYWORD') IS NOT NULL
   DROP TABLE ##TEMP_CLIENTS_KEYWORD

CREATE TABLE ##TEMP_CLIENTS_KEYWORD(client_id int) 

How to multiply all integers inside list

The simplest way to me is:

map((2).__mul__, [1, 2, 3])

Could not reliably determine the server's fully qualified domain name

Another option is to ensure that the full qualified host name (FQDN) is listed in /etc/hosts. This worked for me on Ubuntu v11.10 without having to change the default Apache configuration.

urllib2 and json

Example - sending some data encoded as JSON as a POST data:

import json
import urllib2
data = json.dumps([1, 2, 3])
f = urllib2.urlopen(url, data)
response = f.read()
f.close()

How to automatically insert a blank row after a group of data

This won't work if the data is not sequential (1 2 3 4 but 5 7 3 1 5) as in that case you can't sort it.

Here is how I solve that issue for me:

Column A initial data that needs to contain 5 rows between each number - 5 4 6 8 9

Column B - 1 2 3 4 5 (final number represents the number of empty rows that you need to be between numbers in column A) copy-paste 1-5 in column B as long as you have numbers in column A.

Jump to D column, in D1 type 1. In D2 type this formula - =IF(B2=1,1+D1,D1) Drag it to the same length as column B.

Back to Column C - at C1 cell type this formula - =IF(B1=1,INDIRECT("a"&(D1)),""). Drag it down and we done. Now in column C we have same sequence of numbers as in column A distributed separately by 4 rows.

How to make certain text not selectable with CSS

The CSS below stops users from being able to select text.

-webkit-user-select: none; /* Safari */        
-moz-user-select: none; /* Firefox */
-ms-user-select: none; /* IE10+/Edge */
user-select: none; /* Standard */

To target IE9 downwards the html attribute unselectable must be used instead:

<p unselectable="on">Test Text</p>

How to ping multiple servers and return IP address and Hostnames using batch script?

Try this

$servers = Get-Content test.txt

$reg=""

foreach ($server in $servers) 

{

$reg=$reg+$server+"`t"+([System.Net.Dns]::GetHostAddresses($server) | foreach {echo $_.IPAddressToString})+"`n"

 }
$reg >reg.csv

How to convert WebResponse.GetResponseStream return into a string?

You can create a StreamReader around the stream, then call StreamReader.ReadToEnd().

StreamReader responseReader = new StreamReader(request.GetResponse().GetResponseStream());
var responseData = responseReader.ReadToEnd();

undefined reference to 'std::cout'

Yes, using g++ command worked for me:

g++ my_source_code.cpp

How do I install the OpenSSL libraries on Ubuntu?

Another way to install openssl library from source code on Ubuntu, follows steps below, here WORKDIR is your working directory:

sudo apt-get install pkg-config
cd WORKDIR
git clone https://github.com/openssl/openssl.git
cd openssl
./config
make
sudo make install
# Open file /etc/ld.so.conf, add a new line: "/usr/local/lib" at EOF
sudo ldconfig

HTML5 File API read as text and binary

Note in 2018: readAsBinaryString is outdated. For use cases where previously you'd have used it, these days you'd use readAsArrayBuffer (or in some cases, readAsDataURL) instead.


readAsBinaryString says that the data must be represented as a binary string, where:

...every byte is represented by an integer in the range [0..255].

JavaScript originally didn't have a "binary" type (until ECMAScript 5's WebGL support of Typed Array* (details below) -- it has been superseded by ECMAScript 2015's ArrayBuffer) and so they went with a String with the guarantee that no character stored in the String would be outside the range 0..255. (They could have gone with an array of Numbers instead, but they didn't; perhaps large Strings are more memory-efficient than large arrays of Numbers, since Numbers are floating-point.)

If you're reading a file that's mostly text in a western script (mostly English, for instance), then that string is going to look a lot like text. If you read a file with Unicode characters in it, you should notice a difference, since JavaScript strings are UTF-16** (details below) and so some characters will have values above 255, whereas a "binary string" according to the File API spec wouldn't have any values above 255 (you'd have two individual "characters" for the two bytes of the Unicode code point).

If you're reading a file that's not text at all (an image, perhaps), you'll probably still get a very similar result between readAsText and readAsBinaryString, but with readAsBinaryString you know that there won't be any attempt to interpret multi-byte sequences as characters. You don't know that if you use readAsText, because readAsText will use an encoding determination to try to figure out what the file's encoding is and then map it to JavaScript's UTF-16 strings.

You can see the effect if you create a file and store it in something other than ASCII or UTF-8. (In Windows you can do this via Notepad; the "Save As" as an encoding drop-down with "Unicode" on it, by which looking at the data they seem to mean UTF-16; I'm sure Mac OS and *nix editors have a similar feature.) Here's a page that dumps the result of reading a file both ways:

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title>Show File Data</title>
<style type='text/css'>
body {
    font-family: sans-serif;
}
</style>
<script type='text/javascript'>

    function loadFile() {
        var input, file, fr;

        if (typeof window.FileReader !== 'function') {
            bodyAppend("p", "The file API isn't supported on this browser yet.");
            return;
        }

        input = document.getElementById('fileinput');
        if (!input) {
            bodyAppend("p", "Um, couldn't find the fileinput element.");
        }
        else if (!input.files) {
            bodyAppend("p", "This browser doesn't seem to support the `files` property of file inputs.");
        }
        else if (!input.files[0]) {
            bodyAppend("p", "Please select a file before clicking 'Load'");
        }
        else {
            file = input.files[0];
            fr = new FileReader();
            fr.onload = receivedText;
            fr.readAsText(file);
        }

        function receivedText() {
            showResult(fr, "Text");

            fr = new FileReader();
            fr.onload = receivedBinary;
            fr.readAsBinaryString(file);
        }

        function receivedBinary() {
            showResult(fr, "Binary");
        }
    }

    function showResult(fr, label) {
        var markup, result, n, aByte, byteStr;

        markup = [];
        result = fr.result;
        for (n = 0; n < result.length; ++n) {
            aByte = result.charCodeAt(n);
            byteStr = aByte.toString(16);
            if (byteStr.length < 2) {
                byteStr = "0" + byteStr;
            }
            markup.push(byteStr);
        }
        bodyAppend("p", label + " (" + result.length + "):");
        bodyAppend("pre", markup.join(" "));
    }

    function bodyAppend(tagName, innerHTML) {
        var elm;

        elm = document.createElement(tagName);
        elm.innerHTML = innerHTML;
        document.body.appendChild(elm);
    }

</script>
</head>
<body>
<form action='#' onsubmit="return false;">
<input type='file' id='fileinput'>
<input type='button' id='btnLoad' value='Load' onclick='loadFile();'>
</form>
</body>
</html>

If I use that with a "Testing 1 2 3" file stored in UTF-16, here are the results I get:

Text (13):

54 65 73 74 69 6e 67 20 31 20 32 20 33

Binary (28):

ff fe 54 00 65 00 73 00 74 00 69 00 6e 00 67 00 20 00 31 00 20 00 32 00 20 00 33 00

As you can see, readAsText interpreted the characters and so I got 13 (the length of "Testing 1 2 3"), and readAsBinaryString didn't, and so I got 28 (the two-byte BOM plus two bytes for each character).


* XMLHttpRequest.response with responseType = "arraybuffer" is supported in HTML 5.

** "JavaScript strings are UTF-16" may seem like an odd statement; aren't they just Unicode? No, a JavaScript string is a series of UTF-16 code units; you see surrogate pairs as two individual JavaScript "characters" even though, in fact, the surrogate pair as a whole is just one character. See the link for details.

XPath: difference between dot and text()

There is big difference between dot (".") and text() :-

  • The dot (".") in XPath is called the "context item expression" because it refers to the context item. This could be match with a node (such as an element, attribute, or text node) or an atomic value (such as a string, number, or boolean). While text() refers to match only element text which is in string form.

  • The dot (".") notation is the current node in the DOM. This is going to be an object of type Node while Using the XPath function text() to get the text for an element only gets the text up to the first inner element. If the text you are looking for is after the inner element you must use the current node to search for the string and not the XPath text() function.

For an example :-

<a href="something.html">
  <img src="filename.gif">
  link
</a>

Here if you want to find anchor a element by using text link, you need to use dot ("."). Because if you use //a[contains(.,'link')] it finds the anchor a element but if you use //a[contains(text(),'link')] the text() function does not seem to find it.

Hope it will help you..:)

Detecting input change in jQuery?

If you've got HTML5:

  • oninput (fires only when a change actually happens, but does so immediately)

Otherwise you need to check for all these events which might indicate a change to the input element's value:

  • onchange
  • onkeyup (not keydown or keypress as the input's value won't have the new keystroke in it yet)
  • onpaste (when supported)

and maybe:

  • onmouseup (I'm not sure about this one)

How to prevent the "Confirm Form Resubmission" dialog?

I was having this problem and added this JavaScript to the bottom of my page (read it at https://www.webtrickshome.com/faq/how-to-stop-form-resubmission-on-page-refresh) and it seemed to work. It seems much simpler a solution. Any drawbacks?

<script>
if ( window.history.replaceState ) {
  window.history.replaceState( null, null, window.location.href );
}
</script>

Thanks,

doug

Unable to load script from assets index.android.bundle on windows

I have spent half a day figuring this issue...

If you are using the API target version Above 28.0.0 then you may face this issue.

Just add this line

android:usesCleartextTraffic="true"

in your Manifest Application block.

Manifest Application block code.

 <application
        ....
        android:usesCleartextTraffic="true"
.../>

Node.js request CERT_HAS_EXPIRED

Here is a more concise way to achieve the "less insecure" method proposed by CoolAJ86

request({
  url: url,
  agentOptions: {
    rejectUnauthorized: false
  }
}, function (err, resp, body) {
  // ...
});

How to call execl() in C with the proper arguments?

execl("/home/vlc", 
  "/home/vlc", "/home/my movies/the movie i want to see.mkv", 
  (char*) NULL);

You need to specify all arguments, included argv[0] which isn't taken from the executable.

Also make sure the final NULL gets cast to char*.

Details are here: http://pubs.opengroup.org/onlinepubs/9699919799/functions/exec.html

How to install Cmake C compiler and CXX compiler

Those errors :

"CMake Error: CMAKE_C_COMPILER not set, after EnableLanguage

CMake Error: CMAKE_CXX_COMPILER not set, after EnableLanguage"

means you haven't installed mingw32-base.

Go to http://sourceforge.net/projects/mingw/files/latest/download?source=files

and then make sure you select "mingw32-base"

Make sure you set up environment variables correctly in PATH section. "C:\MinGW\bin"

After that open CMake and Select Installation --> Delete Cache.

And click configure button again. I solved the problem this way, hope you solve the problem.

Batch command to move files to a new directory

Something like this might help:

SET Today=%Date:~10,4%%Date:~4,2%%Date:~7,2%
mkdir C:\Test\Backup-%Today%
move C:\Test\Log\*.* C:\Test\Backup-%Today%\
SET Today=

The important part is the first line. It takes the output of the internal DATE value and parses it into an environmental variable named Today, in the format CCYYMMDD, as in '20110407`.

The %Date:~10,4% says to extract a *substring of the Date environmental variable 'Thu 04/07/2011' (built in - type echo %Date% at a command prompt) starting at position 10 for 4 characters (2011). It then concatenates another substring of Date: starting at position 4 for 2 chars (04), and then concats two additional characters starting at position 7 (07).

*The substring value starting points are 0-based.

You may need to adjust these values depending on the date format in your locale, but this should give you a starting point.

MySQL 8.0 - Client does not support authentication protocol requested by server; consider upgrading MySQL client

I just run into this problem too, with all the MySQL re-config mentioned above the error still appears. It turns out that I misspelled the database name.

So be sure you're connecting with the right database name especially the case.

else & elif statements not working in Python

elif and else must immediately follow the end of the if block, or Python will assume that the block has closed without them.

if 1:
    pass
             <--- this line must be indented at the same level as the `pass`
else:
    pass

In your code, the interpreter finishes the if block when the indentation, so the elif and the else aren't associated with it. They are thus being understood as standalone statements, which doesn't make sense.


In general, try to follow the style guidelines, which include removing excessive whitespace.

Abstraction vs Encapsulation in Java

In simple words: You do abstraction when deciding what to implement. You do encapsulation when hiding something that you have implemented.

Using G++ to compile multiple .cpp and .h files

You can use several g++ commands and then link, but the easiest is to use a traditional Makefile or some other build system: like Scons (which are often easier to set up than Makefiles).

Failed to load ApplicationContext from Unit Test: FileNotFound

Try with the relative path using *

  @ContextConfiguration(locations = {
"classpath*:spring/applicationContext.xml",
"classpath*:spring/applicationContext-jpa.xml",
"classpath*:spring/applicationContext-security.xml" })

If not look if your xml are really on resources/spring/.

Finally try just on without location

 @ContextConfiguration({"classpath*:spring/applicationContext.xml"})

The other error that you´re showing is because you have this tag duplicated on applicationContext.xml and applicationContext-security.xml

 Duplicate <global-method-security>

Groovy String to Date

Try this:

def date = Date.parse("E MMM dd H:m:s z yyyy", dateStr)

Here are the patterns to format the dates

Getting min and max Dates from a pandas dataframe

'Date' is your index so you want to do,

print (df.index.min())
print (df.index.max())

2014-03-13 00:00:00
2014-03-31 00:00:00

Create zip file and ignore directory structure

Alternatively, you could create a temporary symbolic link to your file:

ln -s /data/to/zip/data.txt data.txt
zip /dir/to/file/newZip !$
rm !$

This works also for a directory.

Can't find bundle for base name

If you are using IntelliJ IDE just right click on resources package and go to new and then select Resource Boundle it automatically create a .properties file for you. This did work for me .

How to import multiple .csv files at once?

Using plyr::ldply there is roughly a 50% speed increase by enabling the .parallel option while reading 400 csv files roughly 30-40 MB each. Example includes a text progress bar.

library(plyr)
library(data.table)
library(doSNOW)

csv.list <- list.files(path="t:/data", pattern=".csv$", full.names=TRUE)

cl <- makeCluster(4)
registerDoSNOW(cl)

pb <- txtProgressBar(max=length(csv.list), style=3)
pbu <- function(i) setTxtProgressBar(pb, i)
dt <- setDT(ldply(csv.list, fread, .parallel=TRUE, .paropts=list(.options.snow=list(progress=pbu))))

stopCluster(cl)

Set value for particular cell in pandas DataFrame using index

From version 0.21.1 you can also use .at method. There are some differences compared to .loc as mentioned here - pandas .at versus .loc, but it's faster on single value replacement

How to round an average to 2 decimal places in PostgreSQL?

Error:function round(double precision, integer) does not exist

Solution: You need to addtype cast then it will work

Ex: round(extract(second from job_end_time_t)::integer,0)

What is the correct SQL type to store a .Net Timespan with values > 24:00:00?

If you don't have to store more than 24 hours you can just store time, since SQL Server 2008 and later the mapping is

time (SQL Server) <-> TimeSpan(.NET)

No conversions needed if you only need to store 24 hours or less.

Source: http://msdn.microsoft.com/en-us/library/cc716729(v=vs.110).aspx

But, if you want to store more than 24h, you are going to need to store it in ticks, retrieve the data and then convert to TimeSpan. For example

int timeData = yourContext.yourTable.FirstOrDefault();
TimeSpan ts = TimeSpan.FromMilliseconds(timeData);

How to force the browser to reload cached CSS and JavaScript files

Here is a pure JavaScript solution

(function(){

    // Match this timestamp with the release of your code
    var lastVersioning = Date.UTC(2014, 11, 20, 2, 15, 10);
 
    var lastCacheDateTime = localStorage.getItem('lastCacheDatetime');

    if(lastCacheDateTime){
        if(lastVersioning > lastCacheDateTime){
            var reload = true;
        }
    }

    localStorage.setItem('lastCacheDatetime', Date.now());

    if(reload){
        location.reload(true);
    }

})();

The above will look for the last time the user visited your site. If the last visit was before you released new code, it uses location.reload(true) to force page refresh from server.

I usually have this as the very first script within the <head> so it's evaluated before any other content loads. If a reload needs to occurs, it's hardly noticeable to the user.

I am using local storage to store the last visit timestamp on the browser, but you can add cookies to the mix if you're looking to support older versions of IE.

isolating a sub-string in a string before a symbol in SQL Server 2008

This can achieve using two SQL functions- SUBSTRING and CHARINDEX

You can read strings to a variable as shown in the above answers, or can add it to a SELECT statement as below:

SELECT SUBSTRING('Net Operating Loss - 2007' ,0, CHARINDEX('-','Net Operating Loss - 2007'))

Use of *args and **kwargs

One case where *args and **kwargs are useful is when writing wrapper functions (such as decorators) that need to be able accept arbitrary arguments to pass through to the function being wrapped. For example, a simple decorator that prints the arguments and return value of the function being wrapped:

def mydecorator( f ):
   @functools.wraps( f )
   def wrapper( *args, **kwargs ):
      print "Calling f", args, kwargs
      v = f( *args, **kwargs )
      print "f returned", v
      return v
   return wrapper

PHPMyAdmin Default login password

If it was installed with plesk (not sure if it's just that, or on the phpmyadmin side: It changes the root user to admin.

Error creating bean with name 'entityManagerFactory

This sounds like a ClassLoader conflict. I'd bet you have the javax.persistence api 1.x on the classpath somewhere, whereas Spring is trying to access ValidationMode, which was only introduced in JPA 2.0.

Since you use Maven, do mvn dependency:tree, find the artifact:

<dependency>
    <groupId>javax.persistence</groupId>
    <artifactId>persistence-api</artifactId>
    <version>1.0</version>
</dependency>

And remove it from your setup. (See Excluding Dependencies)

AFAIK there is no such general distribution for JPA 2, but you can use this Hibernate-specific version:

<dependency>
    <groupId>org.hibernate.javax.persistence</groupId>
    <artifactId>hibernate-jpa-2.0-api</artifactId>
    <version>1.0.1.Final</version>
</dependency>

OK, since that doesn't work, you still seem to have some JPA-1 version in there somewhere. In a test method, add this code:

System.out.println(EntityManager.class.getProtectionDomain()
                                      .getCodeSource()
                                      .getLocation());

See where that points you and get rid of that artifact.


Ahh, now I finally see the problem. Get rid of this:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jpa</artifactId>
    <version>2.0.8</version>
</dependency>

and replace it with

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-orm</artifactId>
    <version>3.2.5.RELEASE</version>
</dependency>

On a different note, you should set all test libraries (spring-test, easymock etc.) to

<scope>test</scope>

How to compare two tables column by column in oracle

SELECT *
  FROM (SELECT   table_name, COUNT (*) cnt
            FROM all_tab_columns
           WHERE owner IN ('OWNER_A')
        GROUP BY table_name) x,
       (SELECT   table_name, COUNT (*) cnt
            FROM all_tab_columns
           WHERE owner IN ('OWNER_B')
        GROUP BY table_name) y
 WHERE x.table_name = y.table_name AND x.cnt <> y.cnt;

How to uninstall an older PHP version from centOS7

Subscribing to the IUS Community Project Repository

cd ~
curl 'https://setup.ius.io/' -o setup-ius.sh

Run the script:

sudo bash setup-ius.sh

Upgrading mod_php with Apache

This section describes the upgrade process for a system using Apache as the web server and mod_php to execute PHP code. If, instead, you are running Nginx and PHP-FPM, skip ahead to the next section.

Begin by removing existing PHP packages. Press y and hit Enter to continue when prompted.

sudo yum remove php-cli mod_php php-common

Install the new PHP 7 packages from IUS. Again, press y and Enter when prompted.

sudo yum install mod_php70u php70u-cli php70u-mysqlnd

Finally, restart Apache to load the new version of mod_php:

sudo apachectl restart

You can check on the status of Apache, which is managed by the httpd systemd unit, using systemctl:

systemctl status httpd

How to detect online/offline event cross-browser?

The best way which works now on all Major Browsers is the following Script:

(function () {
    var displayOnlineStatus = document.getElementById("online-status"),
        isOnline = function () {
            displayOnlineStatus.innerHTML = "Online";
            displayOnlineStatus.className = "online";
        },
        isOffline = function () {
            displayOnlineStatus.innerHTML = "Offline";
            displayOnlineStatus.className = "offline";
        };

    if (window.addEventListener) {
        /*
            Works well in Firefox and Opera with the 
            Work Offline option in the File menu.
            Pulling the ethernet cable doesn't seem to trigger it.
            Later Google Chrome and Safari seem to trigger it well
        */
        window.addEventListener("online", isOnline, false);
        window.addEventListener("offline", isOffline, false);
    }
    else {
        /*
            Works in IE with the Work Offline option in the 
            File menu and pulling the ethernet cable
        */
        document.body.ononline = isOnline;
        document.body.onoffline = isOffline;
    }
})();

Source: http://robertnyman.com/html5/offline/online-offline-events.html

Why XML-Serializable class need a parameterless constructor

First of all, this what is written in documentation. I think it is one of your class fields, not the main one - and how you want deserialiser to construct it back w/o parameterless construction ?

I think there is a workaround to make constructor private.

How to make a edittext box in a dialog

Simplest of all would be.

  • Create xml layout file for dialog . Add whatever view you want like EditText , ListView , Spinner etc.

    Inflate this view and set this to AlertDialog

Lets start with Layout file first.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal"
    android:orientation="vertical">


    <EditText
        android:id="@+id/etComments"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="top"
        android:hint="Enter comments(Optional)"
        android:inputType="textMultiLine"
        android:lines="8"
        android:maxLines="3"
        android:minLines="6"
        android:scrollbars="vertical" />

</LinearLayout>

final View view = layoutInflater.inflate(R.layout.xml_file_created_above, null);
AlertDialog alertDialog = new AlertDialog.Builder(ct).create();
alertDialog.setTitle("Your Title Here");
alertDialog.setIcon("Icon id here");
alertDialog.setCancelable(false);
Constant.alertDialog.setMessage("Your Message Here");


final EditText etComments = (EditText) view.findViewById(R.id.etComments);

alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK", new OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {

    }
});


alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "Cancel", new OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        alertDialog.dismiss()
    }
});


alertDialog.setView(view);
alertDialog.show();

Python constructor and default value

I would try:

self.wordList = list(wordList)

to force it to make a copy instead of referencing the same object.

Create a nonclustered non-unique index within the CREATE TABLE statement with SQL Server

TLDR:

CREATE TABLE MyTable(
    a int NOT NULL
    ,b smallint NOT NULL index IX_indexName nonclustered
    ,c smallint NOT NULL
    ,d smallint NOT NULL
    ,e smallint NOT NULL
)

Details

As per T-SQL CREATE TABLE documentation, in 2014 the column definition supports defining an index:

<column_definition> ::=  
column_name <data_type>  
    ...
    [ <column_index> ]  

and <column_index> grammar is defined as:

<column_index> ::=   
 INDEX index_name [ CLUSTERED | NONCLUSTERED ]  
    [ WITH ( <index_option> [ ,... n ] ) ]  
    [ ON { partition_scheme_name (column_name )   
         | filegroup_name  
         | default   
         }  
    ]   
    [ FILESTREAM_ON { filestream_filegroup_name | partition_scheme_name | "NULL" } ]  
  

So a lot of what you can do as a separate statement can be done inline. I noticed include is not an option in this grammar so some things are not possible.

CREATE TABLE MyTable(
    a int NOT NULL
    ,b smallint NOT NULL index IX_indexName nonclustered
    ,c smallint NOT NULL
    ,d smallint NOT NULL
    ,e smallint NOT NULL
)

You can also have inline indexes defined as another line after columns, but within the create table statement, and this allows multiple columns in the index, but still no include clause:

< table_index > ::=   
{  
    {  
      INDEX index_name [ CLUSTERED | NONCLUSTERED ]   
         (column_name [ ASC | DESC ] [ ,... n ] )   
    | INDEX index_name CLUSTERED COLUMNSTORE  
    | INDEX index_name [ NONCLUSTERED ] COLUMNSTORE (column_name [ ,... n ] )  
    }  
    [ WITH ( <index_option> [ ,... n ] ) ]   
    [ ON { partition_scheme_name (column_name )   
         | filegroup_name  
         | default   
         }  
    ]   
    [ FILESTREAM_ON { filestream_filegroup_name | partition_scheme_name | "NULL" } ]  
  
}   

For example here we add an index on both columns c and d:

CREATE TABLE MyTable(
    a int NOT NULL
    ,b smallint NOT NULL index IX_MyTable_b nonclustered
    ,c smallint NOT NULL
    ,d smallint NOT NULL
    ,e smallint NOT NULL

    ,index IX_MyTable_c_d nonclustered (c,d)
)

SMTP Connect() failed. Message was not sent.Mailer error: SMTP Connect() failed

If it works on your localhost but not on your web host:

Some hosting sites block certain outbound SMTP ports. Commenting out the line $mail->IsSMTP(); as noted in the accepted answer may make it work, but it is simply disabling your SMTP configuration, and using the hosting site's email config.

If you are using GoDaddy, there is no way to send mail using a different SMTP. I was using SiteGround, and found that they were allowing SMTP access from ports 25 and 465 only, with an SSL encryption type, so I would look up documentation for your host and go from there.

Android Button click go to another xml page

Change your FirstyActivity to:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button btn_go=(Button)findViewById(R.id.YOUR_BUTTON_ID);
            btn_go.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                  Log.i("clicks","You Clicked B1");
              Intent i=new Intent(
                     MainActivity.this,
                     MainActivity2.class);
              startActivity(i);
            }
        }
    });

}

Hope it will help you.

AngularJS routing without the hash '#'

If you enabled html5mode as others have said, and create an .htaccess file with the following contents (adjust for your needs):

RewriteEngine   On
RewriteBase     /
RewriteCond     %{REQUEST_URI} !^(/index\.php|/img|/js|/css|/robots\.txt|/favicon\.ico)
RewriteCond     %{REQUEST_FILENAME} !-f
RewriteCond     %{REQUEST_FILENAME} !-d
RewriteRule     ./index.html [L]

Users will be directed to the your app when they enter a proper route, and your app will read the route and bring them to the correct "page" within it.

EDIT: Just make sure not to have any file or directory names conflict with your routes.

How to check the installed version of React-Native

First, make sure npm is installed on your system. Use: [sudo] npm install npm -g to download and install it.

Fixing Xcode 9 issue: "iPhone is busy: Preparing debugger support for iPhone"

  1. Click on Window menu
  2. Select Device and Simulators
  3. Select your device
  4. Click on + button at bottom left corner
  5. Click Next
  6. Click Done

$.focus() not working

Pro tip. If you want to turn on focus from the dev console then just open the console as a separate window from the options tab. The latest Firefox and Chrome supports this feature.

Java: Best way to iterate through a Collection (here ArrayList)

The first option is better performance wise (As ArrayList implement RandomAccess interface). As per the java doc, a List implementation should implement RandomAccess interface if, for typical instances of the class, this loop:

 for (int i=0, n=list.size(); i < n; i++)
     list.get(i);

runs faster than this loop:

 for (Iterator i=list.iterator(); i.hasNext(); )
     i.next();

I hope it helps. First option would be slow for sequential access lists.

SQL Server Output Clause into a scalar variable

Way later but still worth mentioning is that you can also use variables to output values in the SET clause of an UPDATE or in the fields of a SELECT;

DECLARE @val1 int;
DECLARE @val2 int;
UPDATE [dbo].[PortalCounters_TEST]
SET @val1 = NextNum, @val2 = NextNum = NextNum + 1
WHERE [Condition] = 'unique value'
SELECT @val1, @val2

In the example above @val1 has the before value and @val2 has the after value although I suspect any changes from a trigger would not be in val2 so you'd have to go with the output table in that case. For anything but the simplest case, I think the output table will be more readable in your code as well.

One place this is very helpful is if you want to turn a column into a comma-separated list;

DECLARE @list varchar(max) = '';
DECLARE @comma varchar(2) = '';
SELECT @list = @list + @comma + County, @comma = ', ' FROM County
print @list

Convert java.util.date default format to Timestamp in Java

You can use the Calendar class to convert Date

public long getDifference()
{
    SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd kk:mm:ss z yyyy");
    Date d = sdf.parse("Mon May 27 11:46:15 IST 2013");

    Calendar c = Calendar.getInstance();
    c.setTime(d);
    long time = c.getTimeInMillis();
    long curr = System.currentTimeMillis();
    long diff = curr - time;    //Time difference in milliseconds
    return diff/1000;
}

How do I use su to execute the rest of the bash script as that user?

The trick is to use "sudo" command instead of "su"

You may need to add this

username1 ALL=(username2) NOPASSWD: /path/to/svn

to your /etc/sudoers file

and change your script to:

sudo -u username2 -H sh -c "cd /home/$USERNAME/$PROJECT; svn update" 

Where username2 is the user you want to run the SVN command as and username1 is the user running the script.

If you need multiple users to run this script, use a %groupname instead of the username1

css3 text-shadow in IE9

Try CSS Generator.

You can choose values and see the results online. Then you get the code in the clipboard.
This is one example of generated code:

text-shadow: 1px 1px 2px #a8aaad;
filter: dropshadow(color=#a8aaad, offx=1, offy=1);

Generate random numbers with a given (numerical) distribution

Here is a more effective way of doing this:

Just call the following function with your 'weights' array (assuming the indices as the corresponding items) and the no. of samples needed. This function can be easily modified to handle ordered pair.

Returns indexes (or items) sampled/picked (with replacement) using their respective probabilities:

def resample(weights, n):
    beta = 0

    # Caveat: Assign max weight to max*2 for best results
    max_w = max(weights)*2

    # Pick an item uniformly at random, to start with
    current_item = random.randint(0,n-1)
    result = []

    for i in range(n):
        beta += random.uniform(0,max_w)

        while weights[current_item] < beta:
            beta -= weights[current_item]
            current_item = (current_item + 1) % n   # cyclic
        else:
            result.append(current_item)
    return result

A short note on the concept used in the while loop. We reduce the current item's weight from cumulative beta, which is a cumulative value constructed uniformly at random, and increment current index in order to find the item, the weight of which matches the value of beta.

HTML img tag: title attribute vs. alt attribute?

The ALT attribute is for the visually impaired user that would use a screen reader. If the ALT is missing from ANY image tag, the entire url for the image will be read. If the images are for part of the design of the site, they should still have the ALT but they can be left empty so the url doesn't have to be read for every part of the site.

Convert comma separated string of ints to int array

I have found a simple solution which worked for me.

String.Join(",",str.Split(','));

css padding is not working in outlook

Make sure to throw on the !important for Outlook especially.

td {
border-collapse: separate;
padding: 15 !important
}

I also wanted borders, so might not work for someone who doesn't.

How to extract year and month from date in PostgreSQL without using to_char() function?

1st Option

date_trunc('month', timestamp_column)::date

It will maintain the date format with all months starting at day one.

Example:

2016-08-01
2016-09-01
2016-10-01
2016-11-01
2016-12-01
2017-01-01

2nd Option

to_char(timestamp_column, 'YYYY-MM')

This solution proposed by @yairchu worked fine in my case. I really wanted to discard 'day' info.

How to extract epoch from LocalDate and LocalDateTime?

The classes LocalDate and LocalDateTime do not contain information about the timezone or time offset, and seconds since epoch would be ambigious without this information. However, the objects have several methods to convert them into date/time objects with timezones by passing a ZoneId instance.

LocalDate

LocalDate date = ...;
ZoneId zoneId = ZoneId.systemDefault(); // or: ZoneId.of("Europe/Oslo");
long epoch = date.atStartOfDay(zoneId).toEpochSecond();

LocalDateTime

LocalDateTime time = ...;
ZoneId zoneId = ZoneId.systemDefault(); // or: ZoneId.of("Europe/Oslo");
long epoch = time.atZone(zoneId).toEpochSecond();

selecting rows with id from another table

You can use a subquery:

SELECT *
FROM terms
WHERE id IN (SELECT term_id FROM terms_relation WHERE taxonomy='categ');

and if you need to show all columns from both tables:

SELECT t.*, tr.*
FROM terms t, terms_relation tr
WHERE t.id = tr.term_id
AND tr.taxonomy='categ'

How to Select Min and Max date values in Linq Query

If you are looking for the oldest date (minimum value), you'd sort and then take the first item returned. Sorry for the C#:

var min = myData.OrderBy( cv => cv.Date1 ).First();

The above will return the entire object. If you just want the date returned:

var min = myData.Min( cv => cv.Date1 );

Regarding which direction to go, re: Linq to Sql vs Linq to Entities, there really isn't much choice these days. Linq to Sql is no longer being developed; Linq to Entities (Entity Framework) is the recommended path by Microsoft these days.

From Microsoft Entity Framework 4 in Action (MEAP release) by Manning Press:

What about the future of LINQ to SQL?

It's not a secret that LINQ to SQL is included in the Framework 4.0 for compatibility reasons. Microsoft has clearly stated that Entity Framework is the recommended technology for data access. In the future it will be strongly improved and tightly integrated with other technologies while LINQ to SQL will only be maintained and little evolved.

Dataframe to Excel sheet

From your above needs, you will need to use both Python (to export pandas data frame) and VBA (to delete existing worksheet content and copy/paste external data).

With Python: use the to_csv or to_excel methods. I recommend the to_csv method which performs better with larger datasets.

# DF TO EXCEL
from pandas import ExcelWriter

writer = ExcelWriter('PythonExport.xlsx')
yourdf.to_excel(writer,'Sheet5')
writer.save()

# DF TO CSV
yourdf.to_csv('PythonExport.csv', sep=',')

With VBA: copy and paste source to destination ranges.

Fortunately, in VBA you can call Python scripts using Shell (assuming your OS is Windows).

Sub DataFrameImport()
  'RUN PYTHON TO EXPORT DATA FRAME
  Shell "C:\pathTo\python.exe fullpathOfPythonScript.py", vbNormalFocus

  'CLEAR EXISTING CONTENT
  ThisWorkbook.Worksheets(5).Cells.Clear

  'COPY AND PASTE TO WORKBOOK
  Workbooks("PythonExport").Worksheets(1).Cells.Copy
  ThisWorkbook.Worksheets(5).Range("A1").Select
  ThisWorkbook.Worksheets(5).Paste
End Sub

Alternatively, you can do vice versa: run a macro (ClearExistingContent) with Python. Be sure your Excel file is a macro-enabled (.xlsm) one with a saved macro to delete Sheet 5 content only. Note: macros cannot be saved with csv files.

import os
import win32com.client
from pandas import ExcelWriter

if os.path.exists("C:\Full Location\To\excelsheet.xlsm"):
  xlApp=win32com.client.Dispatch("Excel.Application")
  wb = xlApp.Workbooks.Open(Filename="C:\Full Location\To\excelsheet.xlsm")

  # MACRO TO CLEAR SHEET 5 CONTENT
  xlApp.Run("ClearExistingContent")
  wb.Save() 
  xlApp.Quit()
  del xl

  # WRITE IN DATA FRAME TO SHEET 5
  writer = ExcelWriter('C:\Full Location\To\excelsheet.xlsm')
  yourdf.to_excel(writer,'Sheet5')
  writer.save() 

Android Studio Google JAR file causing GC overhead limit exceeded error

4g is a bit overkill, if you do not want to change buildGradle you can use FILE -> Invalid caches / restart.

Thats work fine for me ...

Preferred way to create a Scala list

Uhmm.. these seem too complex to me. May I propose

def listTestD = (0 to 3).toList

or

def listTestE = for (i <- (0 to 3).toList) yield i

Calculate RSA key fingerprint

If your SSH agent is running, it is

ssh-add -l

to list RSA fingerprints of all identities, or -L for listing public keys.

If your agent is not running, try:

ssh-agent sh -c 'ssh-add; ssh-add -l'

And for your public keys:

ssh-agent sh -c 'ssh-add; ssh-add -L'

If you get the message: 'The agent has no identities.', then you have to generate your RSA key by ssh-keygen first.

Error in eval(expr, envir, enclos) : object not found

Don't know why @Janos deleted his answer, but it's correct: your data frame Train doesn't have a column named pre. When you pass a formula and a data frame to a model-fitting function, the names in the formula have to refer to columns in the data frame. Your Train has columns called residual.sugar, total.sulfur, alcohol and quality. You need to change either your formula or your data frame so they're consistent with each other.

And just to clarify: Pre is an object containing a formula. That formula contains a reference to the variable pre. It's the latter that has to be consistent with the data frame.

Floating elements within a div, floats outside of div. Why?

W3Schools recommendation:

put overflow: auto on parent element and it will "color" whole background including elements margins. Also floating elements will stay inside of border.

http://www.w3schools.com/css/tryit.asp?filename=trycss_layout_clearfix

Downloading a Google font and setting up an offline site that uses it

3 steps:

  1. Download your custom font on Goole Fonts and down load .css file ex: Download http://fonts.googleapis.com/css?family=Open+Sans:400italic,600italic,400,600,300 and save as example.css
  2. Open file you download (example.css). Now you must download all font-face file and save them on fonts directory.
  3. Edit example.css: replace all font-face file to your .css download

Ex:

_x000D_
_x000D_
@font-face {_x000D_
  font-family: 'Open Sans';_x000D_
  font-style: italic;_x000D_
  font-weight: 400;_x000D_
  src: local('Open Sans Italic'), local('OpenSans-Italic'), url(http://fonts.gstatic.com/s/opensans/v14/xjAJXh38I15wypJXxuGMBvZraR2Tg8w2lzm7kLNL0-w.woff2) format('woff2');_x000D_
  unicode-range: U+0460-052F, U+20B4, U+2DE0-2DFF, U+A640-A69F;_x000D_
}
_x000D_
_x000D_
_x000D_

Look at src: -> url. Download http://fonts.gstatic.com/s/opensans/v14/xjAJXh38I15wypJXxuGMBvZraR2Tg8w2lzm7kLNL0-w.woff2 and save to fonts directory. After that change url to all your downloaded file. Now it will be look like

_x000D_
_x000D_
@font-face {_x000D_
  font-family: 'Open Sans';_x000D_
  font-style: italic;_x000D_
  font-weight: 400;_x000D_
  src: local('Open Sans Italic'), local('OpenSans-Italic'), url(fonts/xjAJXh38I15wypJXxuGMBvZraR2Tg8w2lzm7kLNL0-w.woff2) format('woff2');_x000D_
  unicode-range: U+0460-052F, U+20B4, U+2DE0-2DFF, U+A640-A69F;_x000D_
}
_x000D_
_x000D_
_x000D_

** Download all fonts contain .css file Hope it will help u

How to get the nvidia driver version from the command line?

Windows version:

cd \Program Files\NVIDIA Corporation\NVSMI

nvidia-smi

Split string, convert ToList<int>() in one line

Joze's way also need LINQ, ToList() is in System.Linq namespace.

You can convert Array to List without Linq by passing the array to List constructor:

List<int> numbers = new List<int>( Array.ConvertAll(sNumbers.Split(','), int.Parse) );

Commit only part of a file in Git

git gui provides this functionality under the diff view. Just right click the line(s) you're interested in and you should see a "stage this line to commit" menu item.

What are .NumberFormat Options In Excel VBA?

The .NET Library EPPlus implements a conversation from the string definition to the built in number. See class ExcelNumberFormat:

internal static int GetFromBuildIdFromFormat(string format)
{
    switch (format)
    {
        case "General":
            return 0;
        case "0":
            return 1;
        case "0.00":
            return 2;
        case "#,##0":
            return 3;
        case "#,##0.00":
            return 4;
        case "0%":
            return 9;
        case "0.00%":
            return 10;
        case "0.00E+00":
            return 11;
        case "# ?/?":
            return 12;
        case "# ??/??":
            return 13;
        case "mm-dd-yy":
            return 14;
        case "d-mmm-yy":
            return 15;
        case "d-mmm":
            return 16;
        case "mmm-yy":
            return 17;
        case "h:mm AM/PM":
            return 18;
        case "h:mm:ss AM/PM":
            return 19;
        case "h:mm":
            return 20;
        case "h:mm:ss":
            return 21;
        case "m/d/yy h:mm":
            return 22;
        case "#,##0 ;(#,##0)":
            return 37;
        case "#,##0 ;[Red](#,##0)":
            return 38;
        case "#,##0.00;(#,##0.00)":
            return 39;
        case "#,##0.00;[Red](#,#)":
            return 40;
        case "mm:ss":
            return 45;
        case "[h]:mm:ss":
            return 46;
        case "mmss.0":
            return 47;
        case "##0.0":
            return 48;
        case "@":
            return 49;
        default:
            return int.MinValue;
    }
}

When you use one of these formats, Excel will automatically identify them as a standard format.

How to compare two strings are equal in value, what is the best method?

string1.equals(string2) is the way.

It returns true if string1 is equals to string2 in value. Else, it will return false.

equals reference

PHP executable not found. Install PHP 7 and add it to your PATH or set the php.executablePath setting

For those who are using xampp:

File -> Preferences -> Settings

"php.validate.executablePath": "C:\\xampp\\php\\php.exe",
"php.executablePath": "C:\\xampp\\php\\php.exe"

Short description of the scoping rules?

Actually, a concise rule for Python Scope resolution, from Learning Python, 3rd. Ed.. (These rules are specific to variable names, not attributes. If you reference it without a period, these rules apply.)

LEGB Rule

  • Local — Names assigned in any way within a function (def or lambda), and not declared global in that function

  • Enclosing-function — Names assigned in the local scope of any and all statically enclosing functions (def or lambda), from inner to outer

  • Global (module) — Names assigned at the top-level of a module file, or by executing a global statement in a def within the file

  • Built-in (Python) — Names preassigned in the built-in names module: open, range, SyntaxError, etc

So, in the case of

code1
class Foo:
    code2
    def spam():
        code3
        for code4:
            code5
            x()

The for loop does not have its own namespace. In LEGB order, the scopes would be

  • L: Local in def spam (in code3, code4, and code5)
  • E: Any enclosing functions (if the whole example were in another def)
  • G: Were there any x declared globally in the module (in code1)?
  • B: Any builtin x in Python.

x will never be found in code2 (even in cases where you might expect it would, see Antti's answer or here).

Changing Fonts Size in Matlab Plots

It's possible to change default fonts, both for the axes and for other text, by adding the following lines to the startup.m file.

% Change default axes fonts.
set(0,'DefaultAxesFontName', 'Times New Roman')
set(0,'DefaultAxesFontSize', 14)

% Change default text fonts.
set(0,'DefaultTextFontname', 'Times New Roman')
set(0,'DefaultTextFontSize', 14)

If you don't know if you have a startup.m file, run

which startup

to find its location. If Matlab says there isn't one, run

userpath

to know where it should be placed.

How to place a div below another div?

You have set #slider as absolute, which means that it "is positioned relative to the nearest positioned ancestor" (confusing, right?). Meanwhile, #content div is placed relative, which means "relative to its normal position". So the position of the 2 divs is not related.

You can read about CSS positioning here

If you set both to relative, the divs will be one after the other, as shown here:

#slider {
    position:relative;
    left:0;
    height:400px;

    border-style:solid;
    border-width:5px;
}
#slider img {
    width:100%;
}

#content {
    position:relative;
}

#content #text {
    position:relative;
    width:950px;
    height:215px;
    color:red;
}

http://jsfiddle.net/uorgj4e1/

What is the difference between '/' and '//' when used for division?

In Python 3.x, 5 / 2 will return 2.5 and 5 // 2 will return 2. The former is floating point division, and the latter is floor division, sometimes also called integer division.

In Python 2.2 or later in the 2.x line, there is no difference for integers unless you perform a from __future__ import division, which causes Python 2.x to adopt the 3.x behavior.

Regardless of the future import, 5.0 // 2 will return 2.0 since that's the floor division result of the operation.

You can find a detailed description at https://docs.python.org/whatsnew/2.2.html#pep-238-changing-the-division-operator

How to dismiss keyboard iOS programmatically when pressing return

For a group of UITextViews inside a ViewController:

Swift 3.0

for view in view.subviews {
    if view is UITextField {
        view.resignFirstResponder()
    }
}

Objective-C

// hide keyboard before dismiss
for (UIView *view in [self.view subviews]) {
    if ([view isKindOfClass:[UITextField class]]) {
        // no need to cast
        [view resignFirstResponder];
    }
}

Chart.js v2 - hiding grid lines

Please refer to the official documentation:

https://www.chartjs.org/docs/latest/axes/styling.html#grid-line-configuration

Below code changes would hide the gridLines:

        gridLines: {
            display:false
        }

enter image description here

Current date and time - Default in MVC razor

You could initialize ReturnDate on the model before sending it to the view.

In the controller:

[HttpGet]
public ActionResult SomeAction()
{
    var viewModel = new MyActionViewModel
    {
        ReturnDate = System.DateTime.Now
    };

    return View(viewModel);
}

Difference between .keystore file and .jks file

Ultimately, .keystore and .jks are just file extensions: it's up to you to name your files sensibly. Some application use a keystore file stored in $HOME/.keystore: it's usually implied that it's a JKS file, since JKS is the default keystore type in the Sun/Oracle Java security provider. Not everyone uses the .jks extension for JKS files, because it's implied as the default. I'd recommend using the extension, just to remember which type to specify (if you need).

In Java, the word keystore can have either of the following meanings, depending on the context:

When talking about the file and storage, this is not really a storage facility for key/value pairs (there are plenty or other formats for this). Rather, it's a container to store cryptographic keys and certificates (I believe some of them can also store passwords). Generally, these files are encrypted and password-protected so as not to let this data available to unauthorized parties.

Java uses its KeyStore class and related API to make use of a keystore (whether it's file based or not). JKS is a Java-specific file format, but the API can also be used with other file types, typically PKCS#12. When you want to load a keystore, you must specify its keystore type. The conventional extensions would be:

  • .jks for type "JKS",
  • .p12 or .pfx for type "PKCS12" (the specification name is PKCS#12, but the # is not used in the Java keystore type name).

In addition, BouncyCastle also provides its implementations, in particular BKS (typically using the .bks extension), which is frequently used for Android applications.

How do I inject a controller into another controller in AngularJS

There is no need to import/Inject your controller in JS. You can just inject your controller/nested controller through your HTML.It's worked for me. Like :

<div ng-controller="TestCtrl1">
    <div ng-controller="TestCtrl2">
      <!-- your code--> 
    </div> 
</div>

How to limit the maximum value of a numeric field in a Django model?

from django.db import models
from django.core.validators import MinValueValidator, MaxValueValidator

size = models.IntegerField(validators=[MinValueValidator(0),
                                       MaxValueValidator(5)])

Can scrapy be used to scrape dynamic content from websites that are using AJAX?

yes, Scrapy can scrap dynamic websites, website that are rendered through javaScript.

There are Two approaches to scrapy these kind of websites.

First,

you can use splash to render Javascript code and then parse the rendered HTML. you can find the doc and project here Scrapy splash, git

Second,

As everyone is stating, by monitoring the network calls, yes, you can find the api call that fetch the data and mock that call in your scrapy spider might help you to get desired data.

Explain ggplot2 warning: "Removed k rows containing missing values"

Even if your data falls within your specified limits (e.g. c(0, 335)), adding a geom_jitter() statement could push some points outside those limits, producing the same error message.

library(ggplot2)

range(mtcars$hp)
#> [1]  52 335

# No jitter -- no error message
ggplot(mtcars, aes(mpg, hp)) + 
    geom_point() +
    scale_y_continuous(limits=c(0,335))


# Jitter is too large -- this generates the error message
ggplot(mtcars, aes(mpg, hp)) + 
    geom_point() +
    geom_jitter(position = position_jitter(w = 0.2, h = 0.2)) +
    scale_y_continuous(limits=c(0,335))
#> Warning: Removed 1 rows containing missing values (geom_point).

Created on 2020-08-24 by the reprex package (v0.3.0)

How can I put the current running linux process in background?

Suspend the process with CTRL+Z then use the command bg to resume it in background. For example:

sleep 60
^Z  #Suspend character shown after hitting CTRL+Z
[1]+  Stopped  sleep 60  #Message showing stopped process info
bg  #Resume current job (last job stopped)

More about job control and bg usage in bash manual page:

JOB CONTROL
Typing the suspend character (typically ^Z, Control-Z) while a process is running causes that process to be stopped and returns control to bash. [...] The user may then manipulate the state of this job, using the bg command to continue it in the background, [...]. A ^Z takes effect immediately, and has the additional side effect of causing pending output and typeahead to be discarded.

bg [jobspec ...]
Resume each suspended job jobspec in the background, as if it had been started with &. If jobspec is not present, the shell's notion of the current job is used.

EDIT

To start a process where you can even kill the terminal and it still carries on running

nohup [command] [-args] > [filename] 2>&1 &

e.g.

nohup /home/edheal/myprog -arg1 -arg2 > /home/edheal/output.txt 2>&1 &

To just ignore the output (not very wise) change the filename to /dev/null

To get the error message set to a different file change the &1 to a filename.

In addition: You can use the jobs command to see an indexed list of those backgrounded processes. And you can kill a backgrounded process by running kill %1 or kill %2 with the number being the index of the process.

MetadataException when using Entity Framework Entity Connection

I had this problem when moving my .edmx database first model from one project to another.

I simply did the following:

  1. Deleted the connection strings in the app.config or web.config
  2. Deleted the 'Model.edmx'
  3. Re-added the model to the project.

Showing line numbers in IPython/Jupyter Notebooks

You can also find Toggle Line Numbers under View on the top toolbar of the Jupyter notebook in your browser. This adds/removes the lines numbers in all notebook cells.

For me, Esc+l only added/removed the line numbers of the active cell.

What is the difference between String and string in C#?

String (capital S) is a class in the .NET framework in the System namespace. The fully qualified name is System.String. Whereas, the lower case string is an alias of System.String.

string str1= "Hello";
String str2 = "World!";
            
Console.WriteLine(str1.GetType().FullName); // System.String
Console.WriteLine(str2.GetType().FullName); // System.String

Equivalent of typedef in C#

No, there's no true equivalent of typedef. You can use 'using' directives within one file, e.g.

using CustomerList = System.Collections.Generic.List<Customer>;

but that will only impact that source file. In C and C++, my experience is that typedef is usually used within .h files which are included widely - so a single typedef can be used over a whole project. That ability does not exist in C#, because there's no #include functionality in C# that would allow you to include the using directives from one file in another.

Fortunately, the example you give does have a fix - implicit method group conversion. You can change your event subscription line to just:

gcInt.MyEvent += gcInt_MyEvent;

:)

iPhone and WireShark

You can proceed as follow:

  1. Install Charles Web Proxy.
  2. Disable SSL proxying (uncheck the flag in Proxy->Proxy Settings...->SSL
  3. Connect your iDevice to the Charles proxy, as explained here
  4. Sniff the packets via Wireshark or Charles

jQuery get the name of a select option

Using name on a select option is not valid.

Other have suggested the data- attribute, an alternative is a lookup table

Here the "this" refers to the select so no need to "find" the option

_x000D_
_x000D_
var names = ["", "acoustic", "jazz", "acoustic_jazz", "party", "acoustic_party", "jazz_party", "acoustic_jazz_party"];_x000D_
_x000D_
$(function() {_x000D_
  $('#band_type_choices').on('change', function() {_x000D_
    $('.checkboxlist').hide();_x000D_
    var idx = this.selectedIndex;_x000D_
    if (idx > 0) $('#checkboxlist_' + names[idx]).show();_x000D_
  });_x000D_
});
_x000D_
.checkboxlist { display:none }
_x000D_
Choose acoustic to see the corresponding div_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<select id="band_type_choices">_x000D_
  <option vlaue="0"></option>_x000D_
  <option value="100" name="acoustic">Acoustic</option>_x000D_
  <option value="0" name="jazz">Jazz/Easy Listening</option>_x000D_
  <option value="0" name="acoustic_jazz">Acoustic + Jazz/Easy Listening</option>_x000D_
  <option value="0" name="party">Party</option>_x000D_
  <option value="0" name="acoustic_party">Acoustic + Party</option>_x000D_
  <option value="0" name="jazz_party">Jazz/Easy Listening + Party</option>_x000D_
  <option value="0" name="acoustic_jazz_party">Acoustic + Jazz/Easy Listening + Party</option>_x000D_
</select>_x000D_
<div class="checkboxlist" id="checkboxlist_acoustic">_x000D_
  <input type="checkbox" class="checkbox keys" name="keys" value="100" />Keys<br>_x000D_
  <input type="checkbox" class="checkbox acou_guit" name="acou_guit" value="100" />Acoustic Guitar<br>_x000D_
  <input type="checkbox" class="checkbox drums" name="drums" value="100" />Drums<br>_x000D_
  <input type="checkbox" class="checkbox alt_sax" name="alt_sax" value="100" />Alto Sax<br>_x000D_
  <input type="checkbox" class="checkbox ten_sax" name="ten_sax" value="100" />Tenor Sax<br>_x000D_
  <input type="checkbox" class="checkbox clarinet" name="clarinet" value="100" />Clarinet<br>_x000D_
  <input type="checkbox" class="checkbox trombone" name="trombone" value="100" />Trombone<br>_x000D_
  <input type="checkbox" class="checkbox trumpet" name="trumpet" value="100" />Trumpet<br>_x000D_
  <input type="checkbox" class="checkbox flute" name="flute" value="100" />Flute<br>_x000D_
  <input type="checkbox" class="checkbox cello" name="cello" value="100" />Cello<br>_x000D_
  <input type="checkbox" class="checkbox violin" name="violin" value="100" />Violin<br>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to trim a file extension from a String in JavaScript?

Though it's pretty late, I will add another approach to get the filename without extension using plain old JS-

path.replace(path.substr(path.lastIndexOf('.')), '')

Rollback to an old Git commit in a public repo

Let's say you work on a project and after a day or so. You notice one feature is still giving you errors. But you do not know what change you made that caused the error. So you have to fish previous working commits. To revert to a specific commit:

git checkout 8a0fe5191b7dfc6a81833bfb61220d7204e6b0a9 .

Ok, so that commit works for you. No more error. You pinpointed the issue. Now you can go back to latest commit:

git checkout 792d9294f652d753514dc2033a04d742decb82a5 .

And checkout a specific file before it caused the error (in my case I use example Gemfile.lock):

git checkout 8a0fe5191b7dfc6a81833bfb61220d7204e6b0a9 -- /projects/myproject/Gemfile.lock

And this is one way to handle errors you created in commits without realizing the errors until later.

How to scroll to bottom in a ScrollView on activity startup

This is the best way of doing this.

scrollView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            scrollView.post(new Runnable() {
                @Override
                public void run() {
                    scrollView.fullScroll(View.FOCUS_DOWN);
                }
            });
        }
});

How to implement an android:background that doesn't stretch?

Simply using ImageButton instead of Button fixes the problem.

<ImageButton android:layout_width="30dp"
             android:layout_height="30dp"
             android:src="@drawable/bgimage" />

and you can set

android:background="@null"

to remove button background if you want.

Quick Fix !! :-)

How can I remove a key from a Python dictionary?

You can use exception handling if you want to be very verbose:

try: 
    del dict[key]

except KeyError: pass

This is slower, however, than the pop() method, if the key doesn't exist.

my_dict.pop('key', None)

It won't matter for a few keys, but if you're doing this repeatedly, then the latter method is a better bet.

The fastest approach is this:

if 'key' in dict: 
    del myDict['key']

But this method is dangerous because if 'key' is removed in between the two lines, a KeyError will be raised.

Firefox and SSL: sec_error_unknown_issuer

Firefox is more stringent than other browsers and will require proper installation of an intermediate server certificate. This can be supplied by the cert authority the certificate was purchased from. the intermediate cert is typically installed in the same location as the server cert and requires the proper entry in the httpd.conf file.

while many are chastising Firefox for it's (generally) exclusive 'flagging' of this, it's actually demonstrating a higher level of security standards.

How to set up default schema name in JPA configuration?

For those who uses last versions of spring boot will help this:

.properties:

spring.jpa.properties.hibernate.default_schema=<name of your schema>

.yml:

spring:
    jpa:
        properties:
            hibernate:
                default_schema: <name of your schema>

Is the ternary operator faster than an "if" condition in Java

Try to use switch case statement but normally it's not the performance bottleneck.

In-place type conversion of a NumPy array

Use this:

In [105]: a
Out[105]: 
array([[15, 30, 88, 31, 33],
       [53, 38, 54, 47, 56],
       [67,  2, 74, 10, 16],
       [86, 33, 15, 51, 32],
       [32, 47, 76, 15, 81]], dtype=int32)

In [106]: float32(a)
Out[106]: 
array([[ 15.,  30.,  88.,  31.,  33.],
       [ 53.,  38.,  54.,  47.,  56.],
       [ 67.,   2.,  74.,  10.,  16.],
       [ 86.,  33.,  15.,  51.,  32.],
       [ 32.,  47.,  76.,  15.,  81.]], dtype=float32)

Convert integer to binary in C#

I know this answer would look similar to most of the answers already here, but I noticed just about none of them uses a for-loop. This code works, and can be considered simple, in the sense it will work without any special functions, like a ToString() with parameters, and is not too long as well. Maybe some prefer for-loops instead of just while-loop, this may be suitable for them.

public static string ByteConvert (int num)
{
    int[] p = new int[8];
    string pa = "";
    for (int ii = 0; ii<= 7;ii = ii +1)
    {
        p[7-ii] = num%2;
        num = num/2;
    }
    for (int ii = 0;ii <= 7; ii = ii + 1)
    {
        pa += p[ii].ToString();
    }
    return pa;
}

Defining a `required` field in Bootstrap

Update 2018

Since the original answer HTML5 validation is now supported in all modern browsers. Now the easiest way to make a field required is simply using the required attibute.

<input type="email" class="form-control" id="exampleInputEmail1" required>

or in compliant HTML5:

<input type="email" class="form-control" id="exampleInputEmail1" required="true">

Read more on Bootstrap 4 validation


In Bootstrap 3, you can apply a "validation state" class to the parent element: http://getbootstrap.com/css/#forms-control-validation

For example has-error will show a red border around the input. However, this will have no impact on the actual validation of the field. You'd need to add some additional client (javascript) or server logic to make the field required.

Demo: http://bootply.com/90564


Fastest way to remove non-numeric characters from a VARCHAR in SQL Server

I would recommend enforcing a strict format for phone numbers in the database. I use the following format. (Assuming US phone numbers)

Database: 5555555555x555

Display: (555) 555-5555 ext 555

Input: 10 digits or more digits embedded in any string. (Regex replacing removes all non-numeric characters)

Stop handler.postDelayed()

You can define a boolean and change it to false when you want to stop handler. Like this..

boolean stop = false;

handler.postDelayed(new Runnable() {
    @Override
    public void run() {

        //do your work here..

        if (!stop) {
            handler.postDelayed(this, delay);
        }
    }
}, delay);

Swap two items in List<T>

Maybe someone will think of a clever way to do this, but you shouldn't. Swapping two items in a list is inherently side-effect laden but LINQ operations should be side-effect free. Thus, just use a simple extension method:

static class IListExtensions {
    public static void Swap<T>(
        this IList<T> list,
        int firstIndex,
        int secondIndex
    ) {
        Contract.Requires(list != null);
        Contract.Requires(firstIndex >= 0 && firstIndex < list.Count);
        Contract.Requires(secondIndex >= 0 && secondIndex < list.Count);
        if (firstIndex == secondIndex) {
            return;
        }
        T temp = list[firstIndex];
        list[firstIndex] = list[secondIndex];
        list[secondIndex] = temp;
    }
}

How to 'grep' a continuous stream?

This one command workes for me (Suse):

mail-srv:/var/log # tail -f /var/log/mail.info |grep --line-buffered LOGIN  >> logins_to_mail

collecting logins to mail service

How to output to the console in C++/Windows

If you're using Visual Studio, it should work just fine!

Here's a code example:

#include <iostream>

using namespace std;

int main (int) {
    cout << "This will print to the console!" << endl;
}

Make sure you chose a Win32 console application when creating a new project. Still you can redirect the output of your project to a file by using the console switch (>>). This will actually redirect the console pipe away from the stdout to your file. (for example, myprog.exe >> myfile.txt).

I wish I'm not mistaken!

PHP code to get selected text of a combo box

Put whatever you want to send to PHP in the value attribute.

  <select id="cmbMake" name="Make" >
     <option value="">Select Manufacturer</option>
     <option value="--Any--">--Any--</option>
     <option value="Toyota">Toyota</option>
     <option value="Nissan">Nissan</option>
  </select>

You can also omit the value attribute. It defaults to using the text.

If you don't want to change the HTML, you can put an array in your PHP to translate the values:

$makes = array(2 => 'Toyota',
               3 => 'Nissan');

$maker = $makes[$_POST['Make']];

DLL load failed error when importing cv2

(base) C:\WINDOWS\system32>conda install C:\Users\Todd\Downloads\opencv3-3.1.0-py35_0.tar.bz2

I ran this command from anaconda terminal after I downloaded the version from https://anaconda.org/menpo/opencv3/files

This is the only way I could get cv2 to work and I tried everything for two days.

Using jQuery To Get Size of Viewport

Please note that CSS3 viewport units (vh,vw) wouldn't play well on iOS When you scroll the page, viewport size is somehow recalculated and your size of element which uses viewport units also increases. So, actually some javascript is required.

Javascript: best Singleton pattern

Extending the above post by Tom, if you need a class type declaration and access the singleton instance using a variable, the code below might be of help. I like this notation as the code is little self guiding.

function SingletonClass(){
    if ( arguments.callee.instance )
        return arguments.callee.instance;
    arguments.callee.instance = this;
}


SingletonClass.getInstance = function() {
    var singletonClass = new SingletonClass();
    return singletonClass;
};

To access the singleton, you would

var singleTon = SingletonClass.getInstance();

Java Spring - How to use classpath to specify a file location?

looks like you have maven project and so resources are in classpath by

go for

getClass().getResource("classpath:storedProcedures.sql")

How To Define a JPA Repository Query with a Join

You are experiencing this issue for two reasons.

  • The JPQL Query is not valid.
  • You have not created an association between your entities that the underlying JPQL query can utilize.

When performing a join in JPQL you must ensure that an underlying association between the entities attempting to be joined exists. In your example, you are missing an association between the User and Area entities. In order to create this association we must add an Area field within the User class and establish the appropriate JPA Mapping. I have attached the source for User below. (Please note I moved the mappings to the fields)

User.java

@Entity
@Table(name="user")
public class User {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="iduser")
    private Long idUser;

    @Column(name="user_name")
    private String userName;

    @OneToOne()
    @JoinColumn(name="idarea")
    private Area area;

    public Long getIdUser() {
        return idUser;
    }

    public void setIdUser(Long idUser) {
        this.idUser = idUser;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public Area getArea() {
        return area;
    }

    public void setArea(Area area) {
        this.area = area;
    }
}

Once this relationship is established you can reference the area object in your @Query declaration. The query specified in your @Query annotation must follow proper syntax, which means you should omit the on clause. See the following:

@Query("select u.userName from User u inner join u.area ar where ar.idArea = :idArea")

While looking over your question I also made the relationship between the User and Area entities bidirectional. Here is the source for the Area entity to establish the bidirectional relationship.

Area.java

@Entity
@Table(name = "area")
public class Area {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="idarea")
    private Long idArea;

    @Column(name="area_name")
    private String areaName;

    @OneToOne(fetch=FetchType.LAZY, mappedBy="area")
    private User user;

    public Long getIdArea() {
        return idArea;
    }

    public void setIdArea(Long idArea) {
        this.idArea = idArea;
    }

    public String getAreaName() {
        return areaName;
    }

    public void setAreaName(String areaName) {
        this.areaName = areaName;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }
}

Setting the default page for ASP.NET (Visual Studio) server configuration

If you are running against IIS rather than the VS webdev server, ensure that Index.aspx is one of your default files and that directory browsing is turned off.

How to write new line character to a file in Java

Split the string in to string array and write using above method (I assume your text contains \n to get new line)

String[] test = test.split("\n");

and the inside a loop

bufferedWriter.write(test[i]);
bufferedWriter.newline();

How to use ArrayList's get() method

Would this help?

final List<String> l = new ArrayList<String>();
for (int i = 0; i < 10; i++) l.add("Number " + i);
for (int i = 0; i < 10; i++) System.out.println(l.get(i));

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

Just adding on to carlpett's answer. For a much useful view of the files, you could pipe the output to ls.

find . -maxdepth 1 -type f|ls -lt|less

Shows the most recently modified files in a list format, quite useful when you have downloaded a lot of files, and want to see a non-cluttered version of the recent ones.

Starting a node.js server

Run cmd and then run node server.js. In your example, you are trying to use the REPL to run your command, which is not going to work. The ellipsis is node.js expecting more tokens before closing the current scope (you can type code in and run it on the fly here)

SQL string value spanning multiple lines in query

SQL Server allows the following (be careful to use single quotes instead of double)

UPDATE User
SET UserId = 12345
   , Name = 'J Doe'
   , Location = 'USA'
   , Bio='my bio
spans 
multiple
lines!'
WHERE UserId = 12345

.NET Global exception handler in console application

I just inherited an old VB.NET console application and needed to set up a Global Exception Handler. Since this question mentions VB.NET a few times and is tagged with VB.NET, but all the other answers here are in C#, I thought I would add the exact syntax for a VB.NET application as well.

Public Sub Main()
    REM Set up Global Unhandled Exception Handler.
    AddHandler System.AppDomain.CurrentDomain.UnhandledException, AddressOf MyUnhandledExceptionEvent

    REM Do other stuff
End Sub

Public Sub MyUnhandledExceptionEvent(ByVal sender As Object, ByVal e As UnhandledExceptionEventArgs)
    REM Log Exception here and do whatever else is needed
End Sub

I used the REM comment marker instead of the single quote here because Stack Overflow seemed to handle the syntax highlighting a bit better with REM.

Are there benefits of passing by pointer over passing by reference in C++?

Allen Holub's "Enough Rope to Shoot Yourself in the Foot" lists the following 2 rules:

120. Reference arguments should always be `const`
121. Never use references as outputs, use pointers

He lists several reasons why references were added to C++:

  • they are necessary to define copy constructors
  • they are necessary for operator overloads
  • const references allow you to have pass-by-value semantics while avoiding a copy

His main point is that references should not be used as 'output' parameters because at the call site there's no indication of whether the parameter is a reference or a value parameter. So his rule is to only use const references as arguments.

Personally, I think this is a good rule of thumb as it makes it more clear when a parameter is an output parameter or not. However, while I personally agree with this in general, I do allow myself to be swayed by the opinions of others on my team if they argue for output parameters as references (some developers like them immensely).

React - How to get parameter value from query string?

React router from v4 onwards no longer gives you the query params directly in its location object. The reason being

There are a number of popular packages that do query string parsing/stringifying slightly differently, and each of these differences might be the "correct" way for some users and "incorrect" for others. If React Router picked the "right" one, it would only be right for some people. Then, it would need to add a way for other users to substitute in their preferred query parsing package. There is no internal use of the search string by React Router that requires it to parse the key-value pairs, so it doesn't have a need to pick which one of these should be "right".

Having included that, It would just make more sense to just parse location.search in your view components that are expecting a query object.

You can do this generically by overriding the withRouter from react-router like

customWithRouter.js

import { compose, withPropsOnChange } from 'recompose';
import { withRouter } from 'react-router';
import queryString from 'query-string';

const propsWithQuery = withPropsOnChange(
    ['location', 'match'],
    ({ location, match }) => {
        return {
            location: {
                ...location,
                query: queryString.parse(location.search)
            },
            match
        };
    }
);

export default compose(withRouter, propsWithQuery)

How do I check if a string is unicode or ascii?

How to tell if an object is a unicode string or a byte string

You can use type or isinstance.

In Python 2:

>>> type(u'abc')  # Python 2 unicode string literal
<type 'unicode'>
>>> type('abc')   # Python 2 byte string literal
<type 'str'>

In Python 2, str is just a sequence of bytes. Python doesn't know what its encoding is. The unicode type is the safer way to store text. If you want to understand this more, I recommend http://farmdev.com/talks/unicode/.

In Python 3:

>>> type('abc')   # Python 3 unicode string literal
<class 'str'>
>>> type(b'abc')  # Python 3 byte string literal
<class 'bytes'>

In Python 3, str is like Python 2's unicode, and is used to store text. What was called str in Python 2 is called bytes in Python 3.


How to tell if a byte string is valid utf-8 or ascii

You can call decode. If it raises a UnicodeDecodeError exception, it wasn't valid.

>>> u_umlaut = b'\xc3\x9c'   # UTF-8 representation of the letter 'Ü'
>>> u_umlaut.decode('utf-8')
u'\xdc'
>>> u_umlaut.decode('ascii')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128)

What does 'const static' mean in C and C++?

It has uses in both C and C++.

As you guessed, the static part limits its scope to that compilation unit. It also provides for static initialization. const just tells the compiler to not let anybody modify it. This variable is either put in the data or bss segment depending on the architecture, and might be in memory marked read-only.

All that is how C treats these variables (or how C++ treats namespace variables). In C++, a member marked static is shared by all instances of a given class. Whether it's private or not doesn't affect the fact that one variable is shared by multiple instances. Having const on there will warn you if any code would try to modify that.

If it was strictly private, then each instance of the class would get its own version (optimizer notwithstanding).

How to convert integer into date object python?

I would suggest the following simple approach for conversion:

from datetime import datetime, timedelta
s = "20120213"
# you could also import date instead of datetime and use that.
date = datetime(year=int(s[0:4]), month=int(s[4:6]), day=int(s[6:8]))

For adding/subtracting an arbitary amount of days (seconds work too btw.), you could do the following:

date += timedelta(days=10)
date -= timedelta(days=5)

And convert back using:

s = date.strftime("%Y%m%d")

To convert the integer to a string safely, use:

s = "{0:-08d}".format(i)

This ensures that your string is eight charecters long and left-padded with zeroes, even if the year is smaller than 1000 (negative years could become funny though).

Further reference: datetime objects, timedelta objects

Download text/csv content as files from server in Angular

Most of the references on the web about this issue point out to the fact that you cannot download files via ajax call 'out of the box'. I have seen (hackish) solutions that involve iframes and also solutions like @dcodesmith's that work and are perfectly viable.

Here's another solution I found that works in Angular and is very straighforward.

In the view, wrap the csv download button with <a> tag the following way :

<a target="_self" ng-href="{{csv_link}}">
  <button>download csv</button>
</a>

(Notice the target="_self there, it's crucial to disable Angular's routing inside the ng-app more about it here)

Inside youre controller you can define csv_link the following way :

$scope.csv_link = '/orders' + $window.location.search;

(the $window.location.search is optional and onlt if you want to pass additionaly search query to your server)

Now everytime you click the button, it should start downloading.

How to Configure SSL for Amazon S3 bucket

If you really need it, consider redirections.

For example, on request to assets.my-domain.example.com/path/to/file you could perform a 301 or 302 redirection to my-bucket-name.s3.amazonaws.com/path/to/file or s3.amazonaws.com/my-bucket-name/path/to/file (please remember that in the first case my-bucket-name cannot contain any dots, otherwise it won't match *.s3.amazonaws.com, s3.amazonaws.com stated in S3 certificate).

Not tested, but I believe it would work. I see few gotchas, however.

The first one is pretty obvious, an additional request to get this redirection. And I doubt you could use redirection server provided by your domain name registrar — you'd have to upload proper certificate there somehow — so you have to use your own server for this.

The second one is that you can have urls with your domain name in page source code, but when for example user opens the pic in separate tab, then address bar will display the target url.

Unable to find valid certification path to requested target - error even after cert imported

Solution when migrating from JDK 8 to JDK 10

JDK 10

root@c339504909345:/opt/jdk-minimal/jre/lib/security #  keytool -cacerts -list
Enter keystore password:
Keystore type: JKS
Keystore provider: SUN

Your keystore contains 80 entries

JDK 8

root@c39596768075:/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/security/cacerts #  keytool -cacerts -list
Enter keystore password:
Keystore type: JKS
Keystore provider: SUN

Your keystore contains 151 entries

Steps to fix

  • I deleted the JDK 10 cert and replaced it with the JDK 8
  • Since I'm building Docker Images, I could quickly do that using Multi-stage builds
    • I'm building a minimal JRE using jlink as /opt/jdk/bin/jlink \ --module-path /opt/jdk/jmods...

So, here's the different paths and the sequence of the commands...

# Java 8
COPY --from=marcellodesales-springboot-builder-jdk8 /usr/lib/jvm/java-8-openjdk-amd64/jre/lib/security/cacerts /etc/ssl/certs/java/cacerts

# Java 10
RUN rm -f /opt/jdk-minimal/jre/lib/security/cacerts
RUN ln -s /etc/ssl/certs/java/cacerts /opt/jdk-minimal/jre/lib/security/cacerts

Java String to SHA1

It is not printing correctly because you need to use Base64 encoding. With Java 8 you can encode using Base64 encoder class.

public static String toSHA1(byte[] convertme) throws NoSuchAlgorithmException {
    MessageDigest md = MessageDigest.getInstance("SHA-1");
    return Base64.getEncoder().encodeToString(md.digest(convertme));
}

Result

This will give you your expected output of 5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8

How to update a git clone --mirror?

See here: Git doesn't clone all branches on subsequent clones?

If you really want this by pulling branches instead of push --mirror, you can have a look here:

"fetch --all" in a git bare repository doesn't synchronize local branches to the remote ones

This answer provides detailed steps on how to achieve that relatively easily:

What is the difference between a pandas Series and a single-column DataFrame?

Quoting the Pandas docs

pandas.DataFrame(data=None, index=None, columns=None, dtype=None, copy=False)

Two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). Arithmetic operations align on both row and column labels. Can be thought of as a dict-like container for Series objects. The primary pandas data structure.

So, the Series is the data structure for a single column of a DataFrame, not only conceptually, but literally, i.e. the data in a DataFrame is actually stored in memory as a collection of Series.

Analogously: We need both lists and matrices, because matrices are built with lists. Single row matricies, while equivalent to lists in functionality still cannot exist without the list(s) they're composed of.

They both have extremely similar APIs, but you'll find that DataFrame methods always cater to the possibility that you have more than one column. And, of course, you can always add another Series (or equivalent object) to a DataFrame, while adding a Series to another Series involves creating a DataFrame.

Java: Add elements to arraylist with FOR loop where element name has increasing number

I assume Answer as an Integer data type so in this case, you can easily use Scanner class for adding the multiple elements(say 50).

private static final Scanner obj = new Scanner(System.in);
private static ArrayList<Integer> arrayList = new ArrayList<Integer>(50);
public static void main(String...S){
for (int i=0;i<50;i++) {
  /*Using Scanner class object to take input.*/
  arrayList.add(obj.nextInt());
}
 /*You can also check the elements of your ArrayList.*/
for (int i=0;i<50;i++) {
 /*Using get function for fetching the value present at index 'i'.*/
 System.out.print(arrayList.get(i)+" ");
}}

This is a simple and easy method for adding multiple values in an ArrayList using for loop. As in the above code, I presume the Answer as Integer it could be String, Double, Long et Cetra. So, in that case, you can use next(), nextDouble(), and nextLong() respectively.

Explode PHP string by new line

Best Practice

As mentioned in the comment to the first answer, the best practice is to use the PHP constant PHP_EOL which represents the current system's EOL (End Of Line).

$skuList = explode(PHP_EOL, $_POST['skuList']);

PHP provides a lot of other very useful constants that you can use to make your code system independent, see this link to find useful and system independent directory constants.

Warning

These constants make your page system independent, but you might run into problems when moving from one system to another when you use the constants with data stored on another system. The new system's constants might be different from the previous system's and the stored data might not work anymore. So completely parse your data before storing it to remove any system dependent parts.

UPDATE

Andreas' comment made me realize that the 'Best Practice' solution I present here does not apply to the described use-case: the server's EOL (PHP) does not have anything to do with the EOL the browser (any OS) is using, but that (the browser) is where the string is coming from.

So please use the solution from @Alin_Purcaru (three down) to cover all your bases (and upvote his answer):

$skuList = preg_split('/\r\n|\r|\n/', $_POST['skuList']);

Pass PDO prepared statement to variables

You could do $stmt->queryString to obtain the SQL query used in the statement. If you want to save the entire $stmt variable (I can't see why), you could just copy it. It is an instance of PDOStatement so there is apparently no advantage in storing it.

How to split a dos path into its components in Python

I can't actually contribute a real answer to this one (as I came here hoping to find one myself), but to me the number of differing approaches and all the caveats mentioned is the surest indicator that Python's os.path module desperately needs this as a built-in function.

Is there a Boolean data type in Microsoft SQL Server like there is in MySQL?

Use the BIT datatype to represent boolean data. A BIT field's value is either 1,0 or NULL.

create table <tablename> (
    <columnName> bit
)

Unless you want a threeway boolean you should add NOT NULL DEFAULT 0 like so:

create table <tablename> (
    <columnName> bit not null default 0
)

How to use "Share image using" sharing Intent to share images in android?

SuperM answer worked for me but with Uri.fromFile() instead of Uri.parse().

With Uri.parse(), it worked only with Whatsapp.

This is my code:

sharingIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(mFile));

Output of Uri.parse():
/storage/emulated/0/Android/data/application_package/Files/17072015_0927.jpg

Output of Uri.fromFile:
file:///storage/emulated/0/Android/data/application_package/Files/17072015_0927.jpg

Best way to replace multiple characters in a string?

>>> a = '&#'
>>> print a.replace('&', r'\&')
\&#
>>> print a.replace('#', r'\#')
&\#
>>> 

You want to use a 'raw' string (denoted by the 'r' prefixing the replacement string), since raw strings to not treat the backslash specially.

Declare a variable in DB2 SQL

I'm coming from a SQL Server background also and spent the past 2 weeks figuring out how to run scripts like this in IBM Data Studio. Hope it helps.

CREATE VARIABLE v_lookupid INTEGER DEFAULT (4815162342); --where 4815162342 is your variable data 
  SELECT * FROM DB1.PERSON WHERE PERSON_ID = v_lookupid;
  SELECT * FROM DB1.PERSON_DATA WHERE PERSON_ID = v_lookupid;
  SELECT * FROM DB1.PERSON_HIST WHERE PERSON_ID = v_lookupid;
DROP VARIABLE v_lookupid; 

Can I use GDB to debug a running process?

If one want to attach a process, this process must have the same owner. The root is able to attach to any process.

Check if number is decimal

If you are working with form validation. Then in this case form send string. I used following code to check either form input is a decimal number or not. I hope this will work for you too.

function is_decimal($input = '') {

    $alphabets = str_split($input);
    $find = array('0','1','2','3','4','5','6','7','8','9','.'); // Please note: All intiger numbers are decimal. If you want to check numbers without point "." then you can remove '.' from array. 

    foreach ($alphabets as $key => $alphabet) {
        if (!in_array($alphabet, $find)) {
            return false;
        }
    }

    // Check if user has enter "." point more then once.
    if (substr_count($input, ".") > 1) {
        return false;
    }

    return true;
}

javascript: detect scroll end

if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight)
{
//your code here
}

I too searched it and even after checking all comments here and more, this is the solution to check if reached the bottom or not.

DB2 SQL error: SQLCODE: -206, SQLSTATE: 42703

That only means that an undefined column or parameter name was detected. The errror that DB2 gives should point what that may be:

DB2 SQL Error: SQLCODE=-206, SQLSTATE=42703, SQLERRMC=[THE_UNDEFINED_COLUMN_OR_PARAMETER_NAME], DRIVER=4.8.87

Double check your table definition. Maybe you just missed adding something.

I also tried google-ing this problem and saw this:

http://www.coderanch.com/t/515475/JDBC/databases/sql-insert-statement-giving-sqlcode

C++ String Concatenation operator<<

You can combine strings using stream string like that:

#include <iostream>
#include <sstream>
using namespace std;
int main()
{
    string name = "Bill";
    stringstream ss;
    ss << "Your name is: " << name;
    string info = ss.str();
    cout << info << endl;
    return 0;
}

Java 8 lambda get and remove element from list

As others have suggested, this might be a use case for loops and iterables. In my opinion, this is the simplest approach. If you want to modify the list in-place, it cannot be considered "real" functional programming anyway. But you could use Collectors.partitioningBy() in order to get a new list with elements which satisfy your condition, and a new list of those which don't. Of course with this approach, if you have multiple elements satisfying the condition, all of those will be in that list and not only the first.

jQuery append() vs appendChild()

The JavaScript appendchild method can be use to append an item to another element. The jQuery Append element does the same work but certainly in less number of lines:

Let us take an example to Append an item in a list:

a) With JavaScript

var n= document.createElement("LI");                 // Create a <li> node
var tn = document.createTextNode("JavaScript");      // Create a text node
n.appendChild(tn);                                   // Append the text to <li>
document.getElementById("myList").appendChild(n);  

b) With jQuery

$("#myList").append("<li>jQuery</li>")

How do I find my host and username on mysql?

The default username is root. You can reset the root password if you do not know it: http://dev.mysql.com/doc/refman/5.0/en/resetting-permissions.html. You should not, however, use the root account from PHP, set up a limited permission user to do that: http://dev.mysql.com/doc/refman/5.1/en/adding-users.html

If MySql is running on the same computer as your webserver, you can just use "localhost" as the host

Scrollview can host only one direct child

Wrap all the children inside of another LinearLayout with wrap_content for both the width and the height as well as the vertical orientation.

Append String in Swift

let firstname = "paresh"
let lastname = "hirpara"
let itsme = "\(firstname) \(lastname)"

Converting a float to a string without rounding it

I know this is too late but for those who are coming here for the first time, I'd like to post a solution. I have a float value index and a string imgfile and I had the same problem as you. This is how I fixed the issue

index = 1.0
imgfile = 'data/2.jpg'
out = '%.1f,%s' % (index,imgfile)
print out

The output is

1.0,data/2.jpg

You may modify this formatting example as per your convenience.

Sort Java Collection

Implement the Comparable interface on your customObject.

Using Excel as front end to Access database (with VBA)

Just skip the excel part - the excel user forms are just a poor man's version of the way more robust Access forms. Also Access VBA is identical to Excel VBA - you just have to learn Access' object model. With a simple application you won't need to write much VBA anyways because in Access you can wire things together quite easily.

What does mvn install in maven exactly do

Have you looked at any of the Maven docs, for example, the maven install plugin docs?

Nutshell version: it will build the project and install it in your local repository.

Only get hash value using md5sum (without filename)

Another way:

md5=$(md5sum ${my_iso_file} | sed '/ .*//' )

Nginx sites-enabled, sites-available: Cannot create soft-link between config files in Ubuntu 12.04

My site configuration file is example.conf in sites-available folder So you can create a symbolic link as

ln -s /etc/nginx/sites-available/example.conf /etc/nginx/sites-enabled/

How to read a line from the console in C?

You might need to use a character by character (getc()) loop to ensure you have no buffer overflows and don't truncate the input.

How to display svg icons(.svg files) in UI using React Component?

if you have .svg or an image locally. first you have to install the loader needed for svg and file-loader for images. Then you have to import your icon or image first for example:

import logo from './logos/myLogo.svg' ;
import image from './images/myimage.png';

const temp = (
     <div>
         <img src={logo} />
         <img src={image} />
     </div>
);

ReactDOM.render(temp,document.getElementByID("app"));

Happy Coding :")

resources from react website and worked for me after many searches: https://create-react-app.dev/docs/adding-images-fonts-and-files/

Check if a JavaScript string is a URL

One function that I have been using to validate a URL "string" is:

var matcher = /^(?:\w+:)?\/\/([^\s\.]+\.\S{2}|localhost[\:?\d]*)\S*$/;

function isUrl(string){
  return matcher.test(string);
}

This function will return a boolean whether the string is a URL.

Examples:

isUrl("https://google.com");     // true
isUrl("http://google.com");      // true
isUrl("http://google.de");       // true
isUrl("//google.de");            // true
isUrl("google.de");              // false
isUrl("http://google.com");      // true
isUrl("http://localhost");       // true
isUrl("https://sdfasd");         // false

jQuery disable a link

This works for links that have the onclick attribute set inline. This also allows you to later remove the "return false" in order to enable it.

        //disable all links matching class
        $('.yourLinkClass').each(function(index) {
            var link = $(this);
            var OnClickValue = link.attr("onclick");
            link.attr("onclick", "return false; " + OnClickValue);
        });

        //enable all edit links
        $('.yourLinkClass').each(function (index) {
            var link = $(this);
            var OnClickValue = link.attr("onclick");
            link.attr("onclick", OnClickValue.replace("return false; ", ""));
        });

Android: Storing username and password?

These are ranked in order of difficulty to break your hidden info.

  1. Store in cleartext

  2. Store encrypted using a symmetric key

  3. Using the Android Keystore

  4. Store encrypted using asymmetric keys

source: Where is the best place to store a password in your Android app

The Keystore itself is encrypted using the user’s own lockscreen pin/password, hence, when the device screen is locked the Keystore is unavailable. Keep this in mind if you have a background service that could need to access your application secrets.

source: Simple use the Android Keystore to store passwords and other sensitive information

What is a magic number, and why is it bad?

Magic Number Vs. Symbolic Constant: When to replace?

Magic: Unknown semantic

Symbolic Constant -> Provides both correct semantic and correct context for use

Semantic: The meaning or purpose of a thing.

"Create a constant, name it after the meaning, and replace the number with it." -- Martin Fowler

First, magic numbers are not just numbers. Any basic value can be "magic". Basic values are manifest entities such as integers, reals, doubles, floats, dates, strings, booleans, characters, and so on. The issue is not the data type, but the "magic" aspect of the value as it appears in our code text.

What do we mean by "magic"? To be precise: By "magic", we intend to point to the semantics (meaning or purpose) of the value in the context of our code; that it is unknown, unknowable, unclear, or confusing. This is the notion of "magic". A basic value is not magic when its semantic meaning or purpose-of-being-there is quickly and easily known, clear, and understood (not confusing) from the surround context without special helper words (e.g. symbolic constant).

Therefore, we identify magic numbers by measuring the ability of a code reader to know, be clear, and understand the meaning and purpose of a basic value from its surrounding context. The less known, less clear, and more confused the reader is, the more "magic" the basic value is.

Helpful Definitions

  • confuse: cause (someone) to become bewildered or perplexed.
  • bewildered: cause (someone) to become perplexed and confused.
  • perplexed: completely baffled; very puzzled.
  • baffled: totally bewilder or perplex.
  • puzzled: unable to understand; perplexed.
  • understand: perceive the intended meaning of (words, a language, or speaker).
  • meaning: what is meant by a word, text, concept, or action.
  • meant: intend to convey, indicate, or refer to (a particular thing or notion); signify.
  • signify: be an indication of.
  • indication: a sign or piece of information that indicates something.
  • indicate: point out; show.
  • sign: an object, quality, or event whose presence or occurrence indicates the probable presence or occurrence of something else.

Basics

We have two scenarios for our magic basic values. Only the second is of primary importance for programmers and code:

  1. A lone basic value (e.g. number) from which its meaning is unknown, unknowable, unclear or confusing.
  2. A basic value (e.g. number) in context, but its meaning remains unknown, unknowable, unclear or confusing.

An overarching dependency of "magic" is how the lone basic value (e.g. number) has no commonly known semantic (like Pi), but has a locally known semantic (e.g. your program), which is not entirely clear from context or could be abused in good or bad context(s).

The semantics of most programming languages will not allow us to use lone basic values, except (perhaps) as data (i.e. tables of data). When we encounter "magic numbers", we generally do so in a context. Therefore, the answer to

"Do I replace this magic number with a symbolic constant?"

is:

"How quickly can you assess and understand the semantic meaning of the number (its purpose for being there) in its context?"

Kind of Magic, but not quite

With this thought in mind, we can quickly see how a number like Pi (3.14159) is not a "magic number" when placed in proper context (e.g. 2 x 3.14159 x radius or 2*Pi*r). Here, the number 3.14159 is mentally recognized Pi without the symbolic constant identifier.

Still, we generally replace 3.14159 with a symbolic constant identifier like Pi because of the length and complexity of the number. The aspects of length and complexity of Pi (coupled with a need for accuracy) usually means the symbolic identifier or constant is less prone to error. Recognition of "Pi" as a name is a simply a convenient bonus, but is not the primary reason for having the constant.

Meanwhile: Back at the Ranch

Laying aside common constants like Pi, let's focus primarily on numbers with special meanings, but which those meanings are constrained to the universe of our software system. Such a number might be "2" (as a basic integer value).

If I use the number 2 by itself, my first question might be: What does "2" mean? The meaning of "2" by itself is unknown and unknowable without context, leaving its use unclear and confusing. Even though having just "2" in our software will not happen because of language semantics, we do want to see that "2" by itself carries no special semantics or obvious purpose being alone.

Let's put our lone "2" in a context of: padding := 2, where the context is a "GUI Container". In this context the meaning of 2 (as pixels or other graphical unit) offers us a quick guess of its semantics (meaning and purpose). We might stop here and say that 2 is okay in this context and there is nothing else we need to know. However, perhaps in our software universe this is not the whole story. There is more to it, but "padding = 2" as a context cannot reveal it.

Let's further pretend that 2 as pixel padding in our program is of the "default_padding" variety throughout our system. Therefore, writing the instruction padding = 2 is not good enough. The notion of "default" is not revealed. Only when I write: padding = default_padding as a context and then elsewhere: default_padding = 2 do I fully realize a better and fuller meaning (semantic and purpose) of 2 in our system.

The example above is pretty good because "2" by itself could be anything. Only when we limit the range and domain of understanding to "my program" where 2 is the default_padding in the GUI UX parts of "my program", do we finally make sense of "2" in its proper context. Here "2" is a "magic" number, which is factored out to a symbolic constant default_padding within the context of the GUI UX of "my program" in order to make it use as default_padding quickly understood in the greater context of the enclosing code.

Thus, any basic value, whose meaning (semantic and purpose) cannot be sufficiently and quickly understood is a good candidate for a symbolic constant in the place of the basic value (e.g. magic number).

Going Further

Numbers on a scale might have semantics as well. For example, pretend we are making a D&D game, where we have the notion of a monster. Our monster object has a feature called life_force, which is an integer. The numbers have meanings that are not knowable or clear without words to supply meaning. Thus, we begin by arbitrarily saying:

  • full_life_force: INTEGER = 10 -- Very alive (and unhurt)
  • minimum_life_force: INTEGER = 1 -- Barely alive (very hurt)
  • dead: INTEGER = 0 -- Dead
  • undead: INTEGER = -1 -- Min undead (almost dead)
  • zombie: INTEGER = -10 -- Max undead (very undead)

From the symbolic constants above, we start to get a mental picture of the aliveness, deadness, and "undeadness" (and possible ramifications or consequences) for our monsters in our D&D game. Without these words (symbolic constants), we are left with just the numbers ranging from -10 .. 10. Just the range without the words leaves us in a place of possibly great confusion and potentially with errors in our game if different parts of the game have dependencies on what that range of numbers means to various operations like attack_elves or seek_magic_healing_potion.

Therefore, when searching for and considering replacement of "magic numbers" we want to ask very purpose-filled questions about the numbers within the context of our software and even how the numbers interact semantically with each other.

Conclusion

Let's review what questions we ought to ask:

You might have a magic number if ...

  1. Can the basic value have a special meaning or purpose in your softwares universe?
  2. Can the special meaning or purpose likely be unknown, unknowable, unclear, or confusing, even in its proper context?
  3. Can a proper basic value be improperly used with bad consequences in the wrong context?
  4. Can an improper basic value be properly used with bad consequences in the right context?
  5. Does the basic value have a semantic or purpose relationships with other basic values in specific contexts?
  6. Can a basic value exist in more than one place in our code with different semantics in each, thereby causing our reader a confusion?

Examine stand-alone manifest constant basic values in your code text. Ask each question slowly and thoughtfully about each instance of such a value. Consider the strength of your answer. Many times, the answer is not black and white, but has shades of misunderstood meaning and purpose, speed of learning, and speed of comprehension. There is also a need to see how it connects to the software machine around it.

In the end, the answer to replacement is answer the measure (in your mind) of the strength or weakness of the reader to make the connection (e.g. "get it"). The more quickly they understand meaning and purpose, the less "magic" you have.

CONCLUSION: Replace basic values with symbolic constants only when the magic is large enough to cause difficult to detect bugs arising from confusions.

Error - is not marked as serializable

You need to add a Serializable attribute to the class which you want to serialize.

[Serializable]
public class OrgPermission

How to Add Date Picker To VBA UserForm

You could try the "Microsoft Date and Time Picker Control". To use it, in the Toolbox, you right-click and choose "Additional Controls...". Then you check "Microsoft Date and Time Picker Control 6.0" and OK. You will have a new control in the Toolbox to do what you need.

I just found some printscreen of this on : http://www.logicwurks.com/CodeExamplePages/EDatePickerControl.html Forget the procedures, just check the printscreens.

How do I know if jQuery has an Ajax request pending?

We have to utilize $.ajax.abort() method to abort request if the request is active. This promise object uses readyState property to check whether the request is active or not.

HTML

<h3>Cancel Ajax Request on Demand</h3>
<div id="test"></div>
<input type="button" id="btnCancel" value="Click to Cancel the Ajax Request" />

JS Code

//Initial Message
var ajaxRequestVariable;
$("#test").html("Please wait while request is being processed..");

//Event handler for Cancel Button
$("#btnCancel").on("click", function(){
if (ajaxRequestVariable !== undefined)

if (ajaxRequestVariable.readyState > 0 && ajaxRequestVariable.readyState < 4)
{
  ajaxRequestVariable.abort();
  $("#test").html("Ajax Request Cancelled.");
}
});

//Ajax Process Starts
ajaxRequestVariable = $.ajax({
            method: "POST",
            url: '/echo/json/',
            contentType: "application/json",
            cache: false,
            dataType: "json",
            data: {
        json: JSON.encode({
         data:
             [
                            {"prop1":"prop1Value"},
                    {"prop1":"prop2Value"}
                  ]         
        }),
        delay: 11
    },

            success: function (response) {
            $("#test").show();
            $("#test").html("Request is completed");           
            },
            error: function (error) {

            },
            complete: function () {

            }
        });

Storing Python dictionaries

Minimal example, writing directly to a file:

import json
json.dump(data, open(filename, 'wb'))
data = json.load(open(filename))

or safely opening / closing:

import json
with open(filename, 'wb') as outfile:
    json.dump(data, outfile)
with open(filename) as infile:
    data = json.load(infile)

If you want to save it in a string instead of a file:

import json
json_str = json.dumps(data)
data = json.loads(json_str)

is python capable of running on multiple cores?

I converted the script to Python3 and ran it on my Raspberry Pi 3B+:

import time
import threading

def t():
        with open('/dev/urandom', 'rb') as f:
                for x in range(100):
                        f.read(4 * 65535)

if __name__ == '__main__':
    start_time = time.time()
    t()
    t()
    t()
    t()
    print("Sequential run time: %.2f seconds" % (time.time() - start_time))

    start_time = time.time()
    t1 = threading.Thread(target=t)
    t2 = threading.Thread(target=t)
    t3 = threading.Thread(target=t)
    t4 = threading.Thread(target=t)
    t1.start()
    t2.start()
    t3.start()
    t4.start()
    t1.join()
    t2.join()
    t3.join()
    t4.join()
    print("Parallel run time: %.2f seconds" % (time.time() - start_time))

python3 t.py

Sequential run time: 2.10 seconds
Parallel run time: 1.41 seconds

For me, running parallel was quicker.

WPF: Create a dialog / prompt

Great answer of Josh, all credit to him, I slightly modified it to this however:

MyDialog Xaml

    <StackPanel Margin="5,5,5,5">
        <TextBlock Name="TitleTextBox" Margin="0,0,0,10" />
        <TextBox Name="InputTextBox" Padding="3,3,3,3" />
        <Grid Margin="0,10,0,0">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*"/>
                <ColumnDefinition Width="*"/>
            </Grid.ColumnDefinitions>
            <Button Name="BtnOk" Content="OK" Grid.Column="0" Margin="0,0,5,0" Padding="8" Click="BtnOk_Click" />
            <Button Name="BtnCancel" Content="Cancel" Grid.Column="1" Margin="5,0,0,0" Padding="8" Click="BtnCancel_Click" />
        </Grid>
    </StackPanel>

MyDialog Code Behind

    public MyDialog()
    {
        InitializeComponent();
    }

    public MyDialog(string title,string input)
    {
        InitializeComponent();
        TitleText = title;
        InputText = input;
    }

    public string TitleText
    {
        get { return TitleTextBox.Text; }
        set { TitleTextBox.Text = value; }
    }

    public string InputText
    {
        get { return InputTextBox.Text; }
        set { InputTextBox.Text = value; }
    }

    public bool Canceled { get; set; }

    private void BtnCancel_Click(object sender, System.Windows.RoutedEventArgs e)
    {
        Canceled = true;
        Close();
    }

    private void BtnOk_Click(object sender, System.Windows.RoutedEventArgs e)
    {
        Canceled = false;
        Close();
    }

And call it somewhere else

var dialog = new MyDialog("test", "hello");
dialog.Show();
dialog.Closing += (sender,e) =>
{
    var d = sender as MyDialog;
    if(!d.Canceled)
        MessageBox.Show(d.InputText);
}

Lollipop : draw behind statusBar with its color set to transparent

@Cody Toombs's answer lead to an issue that brings the layout behind the navigation bar. So what I found is using this solution given by @Kriti

here is the Kotlin code snippet for the same:

if (Build.VERSION.SDK_INT >= 19 && Build.VERSION.SDK_INT < 21) {
    setWindowFlag(this, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, true)
}

if (Build.VERSION.SDK_INT >= 19) {
    window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
}

if (Build.VERSION.SDK_INT >= 21) {
    setWindowFlag(this, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, false)
    getWindow().setStatusBarColor(Color.TRANSPARENT)
}

private fun setWindowFlag(activity: Activity, bits: Int, on: Boolean) {

    val win: Window = activity.getWindow()

    val winParams: WindowManager.LayoutParams = win.getAttributes()
    if (on) {
        winParams.flags = winParams.flags or bits
    } else {
        winParams.flags = winParams.flags and bits.inv()
    }
    win.setAttributes(winParams)
}

You also need to add

android:fitsSystemWindows="false"

root view of your layout.

JUnit Eclipse Plugin?

You do not need to install or update any software for the JUnit. it is the part of Java Development tools and comes with almost most of the latest versions in Eclipse.

Go to your project. Right click onto that->Select buildpath->add library->select JUnit from the list ->select the version you want to work with-> done

build you project again to see the errors gone:)

How can I resolve "Your requirements could not be resolved to an installable set of packages" error?

Run this command:

composer install --ignore-platform-reqs

or

composer update --ignore-platform-reqs

Why can't I call a public method in another class?

It sounds like you're not instantiating your class. That's the primary reason I get the "an object reference is required" error.

MyClass myClass = new MyClass();

once you've added that line you can then call your method

myClass.myMethod();

Also, are all of your classes in the same namespace? When I was first learning c# this was a common tripping point for me.

php hide ALL errors

Use PHP error handling functions to handle errors. How you do it depends on your needs. This system will intercept all errors and forward it however you want it Or supress it if you ask it to do so

http://php.net/manual/en/book.errorfunc.php

Why both no-cache and no-store should be used in HTTP response?

no-store should not be necessary in normal situations, and can harm both speed and usability. It is intended for use where the HTTP response contains information so sensitive it should never be written to a disk cache at all, regardless of the negative effects that creates for the user.

How it works:

  • Normally, even if a user agent such as a browser determines that a response shouldn't be cached, it may still store it to the disk cache for reasons internal to the user agent. This version may be utilised for features like "view source", "back", "page info", and so on, where the user hasn't necessarily requested the page again, but the browser doesn't consider it a new page view and it would make sense to serve the same version the user is currently viewing.

  • Using no-store will prevent that response being stored, but this may impact the browser's ability to give "view source", "back", "page info" and so on without making a new, separate request for the server, which is undesirable. In other words, the user may try viewing the source and if the browser didn't keep it in memory, they'll either be told this isn't possible, or it will cause a new request to the server. Therefore, no-store should only be used when the impeded user experience of these features not working properly or quickly is outweighed by the importance of ensuring content is not stored in the cache.

My current understanding is that it is just for intermediate cache server. Even if "no-cache" is in response, intermediate cache server can still save the content to non-volatile storage.

This is incorrect. Intermediate cache servers compatible with HTTP 1.1 will obey the no-cache and must-revalidate instructions, ensuring that content is not cached. Using these instructions will ensure that the response is not cached by any intermediate cache, and that all subsequent requests are sent back to the origin server.

If the intermediate cache server does not support HTTP 1.1, then you will need to use Pragma: no-cache and hope for the best. Note that if it doesn't support HTTP 1.1 then no-store is irrelevant anyway.

Distinct in Linq based on only one field of the table

data.Select(x=>x.Name).Distinct().Select(x => new SelectListItem { Text = x });

Waiting for HOME ('android.process.acore') to be launched

This problem occurs because while creating the AVD manager in the "Create new Android virtual device(AVD)" dialog window ,"Snapshot" was marked as "Enabled" by me.

Solution:

Create a new AVD manager with the "Enabled" checkbox not checked and then try running the project with the newly created AVD manager as "Target" , the problem will not occur anymore

SQL ORDER BY date problem

I wanted to edit several events in descendant chonologic order, and I just made a :

select 
TO_CHAR(startdate,'YYYYMMDD') dateorder,
TO_CHAR(startdate,'DD/MM/YYYY') startdate,
...
from ...
...
order by dateorder desc

and it works for me. But surely not adapted for every case... Just hope it'll help someone !

Ineligible Devices section appeared in Xcode 6.x.x

I set my "iOS Deployment Target" in "Project" and "Targets" from 7.1 to 8.0 and restarted Xcode (with "Quit") and it worked.

angular.min.js.map not found, what is it exactly?

Monkey is right, according to the link given by monkey

Basically it's a way to map a combined/minified file back to an unbuilt state. When you build for production, along with minifying and combining your JavaScript files, you generate a source map which holds information about your original files. When you query a certain line and column number in your generated JavaScript you can do a lookup in the source map which returns the original location.

I am not sure if it is angular's fault that no map files were generated. But you can turn off source map files by unchecking this option in chrome console setting

enter image description here

Filename too long in Git for Windows

The better solution is enable the longpath parameter from Git.

git config --system core.longpaths true

But a workaround that works is remove the node_modules folder from Git:

$ git rm -r --cached node_modules
$ vi .gitignore

Add node_modules in a new row inside the .gitignore file. After doing this, push your modifications:

$ git add .gitignore
$ git commit -m "node_modules removed"
$ git push

How to pretty-print a numpy.array without scientific notation and with given precision?

The numpy arrays have the method round(precision) which return a new numpy array with elements rounded accordingly.

import numpy as np

x = np.random.random([5,5])
print(x.round(3))

gdb: "No symbol table is loaded"

Whenever gcc on the compilation machine and gdb on the testing machine have differing versions, you may be facing debuginfo format incompatibility.

To fix that, try downgrading the debuginfo format:

gcc -gdwarf-3 ...
gcc -gdwarf-2 ...
gcc -gstabs ...
gcc -gstabs+ ...
gcc -gcoff ...
gcc -gxcoff ...
gcc -gxcoff+ ...

Or match gdb to the gcc you're using.

Already defined in .obj - no double inclusions

You probably don't want to do this:

#include "client.cpp"

A *.cpp file will have been compiled by the compiler as part of your build. By including it in other files, it will be compiled again (and again!) in every file in which you include it.

Now here's the thing: You are guarding it with #ifndef SOCKET_CLIENT_CLASS, however, each file that has #include "client.cpp" is built independently and as such will find SOCKET_CLIENT_CLASS not yet defined. Therefore it's contents will be included, not #ifdef'd out.

If it contains any definitions at all (rather than just declarations) then these definitions will be repeated in every file where it's included.

Appending a line to a file only if it does not already exist

use awk

awk 'FNR==NR && /configs.*projectname\.conf/{f=1;next}f==0;END{ if(!f) { print "your line"}} ' file file

How to get the entire document HTML as a string?

document.documentElement.innerHTML

Showing all errors and warnings

Straight from the php.ini file:

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Error handling and logging ;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

; This directive informs PHP of which errors, warnings and notices you would like
; it to take action for. The recommended way of setting values for this
; directive is through the use of the error level constants and bitwise
; operators. The error level constants are below here for convenience as well as
; some common settings and their meanings.
; By default, PHP is set to take action on all errors, notices and warnings EXCEPT
; those related to E_NOTICE and E_STRICT, which together cover best practices and
; recommended coding standards in PHP. For performance reasons, this is the
; recommend error reporting setting. Your production server shouldn't be wasting
; resources complaining about best practices and coding standards. That's what
; development servers and development settings are for.
; Note: The php.ini-development file has this setting as E_ALL. This
; means it pretty much reports everything which is exactly what you want during
; development and early testing.
;
; Error Level Constants:
; E_ALL             - All errors and warnings (includes E_STRICT as of PHP 5.4.0)
; E_ERROR           - fatal run-time errors
; E_RECOVERABLE_ERROR  - almost fatal run-time errors
; E_WARNING         - run-time warnings (non-fatal errors)
; E_PARSE           - compile-time parse errors
; E_NOTICE          - run-time notices (these are warnings which often result
;                     from a bug in your code, but it's possible that it was
;                     intentional (e.g., using an uninitialized variable and
;                     relying on the fact it is automatically initialized to an
;                     empty string)
; E_STRICT          - run-time notices, enable to have PHP suggest changes
;                     to your code which will ensure the best interoperability
;                     and forward compatibility of your code
; E_CORE_ERROR      - fatal errors that occur during PHP's initial startup
; E_CORE_WARNING    - warnings (non-fatal errors) that occur during PHP's
;                     initial startup
; E_COMPILE_ERROR   - fatal compile-time errors
; E_COMPILE_WARNING - compile-time warnings (non-fatal errors)
; E_USER_ERROR      - user-generated error message
; E_USER_WARNING    - user-generated warning message
; E_USER_NOTICE     - user-generated notice message
; E_DEPRECATED      - warn about code that will not work in future versions
;                     of PHP
; E_USER_DEPRECATED - user-generated deprecation warnings
;
; Common Values:
;   E_ALL (Show all errors, warnings and notices including coding standards.)
;   E_ALL & ~E_NOTICE  (Show all errors, except for notices)
;   E_ALL & ~E_NOTICE & ~E_STRICT  (Show all errors, except for notices and coding standards warnings.)
;   E_COMPILE_ERROR|E_RECOVERABLE_ERROR|E_ERROR|E_CORE_ERROR  (Show only errors)
; Default Value: E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED
; Development Value: E_ALL
; Production Value: E_ALL & ~E_DEPRECATED & ~E_STRICT
; http://php.net/error-reporting
error_reporting = E_ALL & ~E_DEPRECATED & ~E_STRICT

For pure development I go for:

error_reporting = E_ALL ^ E_NOTICE ^ E_WARNING

Also don't forget to put display_errors to on

display_errors = On

After that, restart your server for Apache on Ubuntu:

sudo /etc/init.d/apache2 restart

jQuery: checking if the value of a field is null (empty)

that depends on what kind of information are you passing to the conditional..

sometimes your result will be null or undefined or '' or 0, for my simple validation i use this if.

( $('#id').val() == '0' || $('#id').val() == '' || $('#id').val() == 'undefined' || $('#id').val() == null )

NOTE: null != 'null'

PHP find difference between two datetimes

I collected many topics to make universal function with many outputs (years, months, days, hours, minutes, seconds) with string or parse to int and direction +- if you need to know what side is direction of the difference.

Use example:



    $date1='2016-05-27 02:00:00';
    $format='Y-m-d H:i:s';

    echo timeDifference($date1, $format, '2017-08-30 00:01:59', $format); 
    #1 years 3 months 2 days 22 hours 1 minutes 59 seconds (string)

    echo timeDifference($date1, $format, '2017-08-30 00:01:59', $format,false, '%a days %h hours');
    #459 days 22 hours (string)

    echo timeDifference('2016-05-27 00:00:00', $format, '2017-08-30 00:01:59', $format,true, '%d days -> %H:%I:%S', true);
    #-3 days -> 00:01:59 (string)

    echo timeDifference($date1, $format, '2016-05-27 00:05:51', $format, false, 'seconds');
    #9 (string)

    echo timeDifference($date1, $format, '2016-05-27 07:00:00', $format, false, 'hours');
    #5 (string)

    echo timeDifference($date1, $format, '2016-05-27 07:00:00', $format, true, 'hours');
    #-5 (string)

    echo timeDifference($date1, $format, '2016-05-27 07:00:00', $format, true, 'hours',true);
    #-5 (int)

Function



    function timeDifference($date1_pm_checked, $date1_format,$date2, $date2_format, $plus_minus=false, $return='all', $parseInt=false)
    {
        $strtotime1=strtotime($date1_pm_checked);
        $strtotime2=strtotime($date2);
        $date1 = new DateTime(date($date1_format, $strtotime1));
        $date2 = new DateTime(date($date2_format, $strtotime2));
        $interval=$date1->diff($date2);

        $plus_minus=(empty($plus_minus)) ? '' : ( ($strtotime1 > $strtotime2) ? '+' : '-'); # +/-/no_sign before value 

        switch($return)
        {
            case 'y';
            case 'year';
            case 'years';
                $elapsed = $interval->format($plus_minus.'%y');
                break;

            case 'm';
            case 'month';
            case 'months';
                $elapsed = $interval->format($plus_minus.'%m');
                break;

            case 'a';
            case 'day';
            case 'days';
                $elapsed = $interval->format($plus_minus.'%a');
                break;

            case 'd';
                $elapsed = $interval->format($plus_minus.'%d');
                break;

            case 'h';       
            case 'hour';        
            case 'hours';       
                $elapsed = $interval->format($plus_minus.'%h');
                break;

            case 'i';
            case 'minute';
            case 'minutes';
                $elapsed = $interval->format($plus_minus.'%i');
                break;

            case 's';
            case 'second';
            case 'seconds';
                $elapsed = $interval->format($plus_minus.'%s');
                break;

            case 'all':
                $parseInt=false;
                $elapsed = $plus_minus.$interval->format('%y years %m months %d days %h hours %i minutes %s seconds');
                break;

            default:
                $parseInt=false;
                $elapsed = $plus_minus.$interval->format($return);
        }

        if($parseInt)
            return (int) $elapsed;
        else
            return $elapsed;

    }

Android Studio build fails with "Task '' not found in root project 'MyProject'."

I got this error when switching from one Git branch to another, and then trying to run "Clean Project". I used ack to search for the Task name, and found it in a .iml file.

My solution was to regenerate the project's .iml file by clicking (in the main menu) Tools > Android > Sync Project with Gradle Files. (Thanks to this answer.)

How do I view an older version of an SVN file?

To directly answer the question of how to "get a copy of that file":

svn cat -r 666 file > file_r666

then you can view the newly created file_r666 with any viewer or comparison program, e.g.

kompare file_r666 file

nicely shows the differences.

I posted the answer because the accepted answer's commands do actually not give a copy of the file and because svn cat -r 666 file | vim does not work with my system (Vim: Error reading input, exiting...)

What does Java option -Xmx stand for?

see here: Java Tool Doc, it says,

-Xmxn
Specify the maximum size, in bytes, of the memory allocation pool. This value must a multiple of 1024 greater than 2MB. Append the letter k or K to indicate kilobytes, or m or M to indicate megabytes. The default value is 64MB. The upper limit for this value will be approximately 4000m on Solaris 7 and Solaris 8 SPARC platforms and 2000m on Solaris 2.6 and x86 platforms, minus overhead amounts. Examples:

           -Xmx83886080
           -Xmx81920k
           -Xmx80m

So, in simple words, you are setting Java heap memory to a maximum of 1024 MB from the available memory, not more.

Notice there is NO SPACE between -Xmx and 1024m

It does not matter if you use uppercase or lowercase. For example: "-Xmx10G" and "-Xmx10g" do the exact same thing.