Programs & Examples On #Iidentity

ASP.NET MVC - Set custom IIdentity or IPrincipal

As an addition to LukeP code for Web Forms users (not MVC) if you want to simplify the access in the code behind of your pages, just add the code below to a base page and derive the base page in all your pages:

Public Overridable Shadows ReadOnly Property User() As CustomPrincipal
    Get
        Return DirectCast(MyBase.User, CustomPrincipal)
    End Get
End Property

So in your code behind you can simply access:

User.FirstName or User.LastName

What I'm missing in a Web Form scenario, is how to obtain the same behaviour in code not tied to the page, for example in httpmodules should I always add a cast in each class or is there a smarter way to obtain this?

Thanks for your answers and thank to LukeP since I used your examples as a base for my custom user (which now has User.Roles, User.Tasks, User.HasPath(int) , User.Settings.Timeout and many other nice things)

Difference between static STATIC_URL and STATIC_ROOT on Django

STATIC_ROOT

The absolute path to the directory where ./manage.py collectstatic will collect static files for deployment. Example: STATIC_ROOT="/var/www/example.com/static/"

now the command ./manage.py collectstatic will copy all the static files(ie in static folder in your apps, static files in all paths) to the directory /var/www/example.com/static/. now you only need to serve this directory on apache or nginx..etc.

STATIC_URL

The URL of which the static files in STATIC_ROOT directory are served(by Apache or nginx..etc). Example: /static/ or http://static.example.com/

If you set STATIC_URL = 'http://static.example.com/', then you must serve the STATIC_ROOT folder (ie "/var/www/example.com/static/") by apache or nginx at url 'http://static.example.com/'(so that you can refer the static file '/var/www/example.com/static/jquery.js' with 'http://static.example.com/jquery.js')

Now in your django-templates, you can refer it by:

{% load static %}
<script src="{% static "jquery.js" %}"></script>

which will render:

<script src="http://static.example.com/jquery.js"></script>

What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?

According to your Code :

String[] name = {"tom", "dick", "harry"};
for(int i = 0; i<=name.length; i++) {
  System.out.print(name[i] +'\n');
}

If You check System.out.print(name.length);

you will get 3;

that mean your name length is 3

your loop is running from 0 to 3 which should be running either "0 to 2" or "1 to 3"

Answer

String[] name = {"tom", "dick", "harry"};
for(int i = 0; i<name.length; i++) {
  System.out.print(name[i] +'\n');
}

jQuery delete all table rows except first

This worked in the following way in my case and working fine

$("#compositeTable").find("tr:gt(1)").remove();

Angular 2.0 router not working on reloading the browser

For those of us struggling through life in IIS: use the following PowerShell code to fix this issue based on the official Angular 2 docs (that someone posted in this thread? http://blog.angular-university.io/angular2-router/)

Import-WebAdministration
# Grab the 404 handler and update it to redirect to index.html.
$redirect = Get-WebConfiguration -filter "/system.WebServer/httperrors/error[@statusCode='404']" -PSPath IIS:\Sites\LIS 
$redirect.path = "/index.html"
$redirect.responseMode = 1
# shove the updated config back into IIS
Set-WebConfiguration -filter "/system.WebServer/httperrors/error[@statusCode='404']" -PSPath IIS:\Sites\LIS -value $redirect

This redirects the 404 to the /index.html file as per the suggestion in the Angular 2 docs (link above).

SQL Update to the SUM of its joined values

I ran into the same issue and found that I could solve it with a Common Table Expression (available in SQL 2005 or later):

;with cte as (
    SELECT PitchID, SUM(Price) somePrice
    FROM BookingPitchExtras
    WHERE [required] = 1 
    GROUP BY PitchID)
UPDATE p SET p.extrasPrice=cte.SomePrice
FROM BookingPitches p INNER JOIN cte ON p.ID=cte.PitchID
WHERE p.BookingID=1

When do you use POST and when do you use GET?

Use GET when you want the URL to reflect the state of the page. This is useful for viewing dynamically generated pages, such as those seen here. A POST should be used in a form to submit data, like when I click the "Post Your Answer" button. It also produces a cleaner URL since it doesn't generate a parameter string after the path.

How to join a slice of strings into a single string?

This is still relevant in 2018.

To String

import strings
stringFiles := strings.Join(fileSlice[:], ",")

Back to Slice again

import strings
fileSlice := strings.Split(stringFiles, ",")

Slide a layout up from bottom of screen

My code to make animation slide up, slide down without XML

private static ObjectAnimator createBottomUpAnimation(View view,
        AnimatorListenerAdapter listener, float distance) {
    ObjectAnimator animator = ObjectAnimator.ofFloat(view, "translationY", -distance);
//        animator.setDuration(???)
    animator.removeAllListeners();
    if (listener != null) {
        animator.addListener(listener);
    }
    return animator;
}

public static ObjectAnimator createTopDownAnimation(View view, AnimatorListenerAdapter listener,
        float distance) {
    view.setTranslationY(-distance);
    ObjectAnimator animator = ObjectAnimator.ofFloat(view, "translationY", 0);
    animator.removeAllListeners();
    if (listener != null) {
        animator.addListener(listener);
    }
    return animator;
}

Using For slide down

createTopDownAnimation(myYellowView, null, myYellowView.getHeight()).start();

For slide up

createBottomUpAnimation(myYellowView, null, myYellowView.getHeight()).start();

enter image description here

How to cast List<Object> to List<MyClass>

You should just iterate over the list and cast all Objects one by one

What do Clustered and Non clustered index actually mean?

Clustered Index

Clustered indexes sort and store the data rows in the table or view based on their key values. These are the columns included in the index definition. There can be only one clustered index per table, because the data rows themselves can be sorted in only one order.

The only time the data rows in a table are stored in sorted order is when the table contains a clustered index. When a table has a clustered index, the table is called a clustered table. If a table has no clustered index, its data rows are stored in an unordered structure called a heap.

Nonclustered

Nonclustered indexes have a structure separate from the data rows. A nonclustered index contains the nonclustered index key values and each key value entry has a pointer to the data row that contains the key value. The pointer from an index row in a nonclustered index to a data row is called a row locator. The structure of the row locator depends on whether the data pages are stored in a heap or a clustered table. For a heap, a row locator is a pointer to the row. For a clustered table, the row locator is the clustered index key.

You can add nonkey columns to the leaf level of the nonclustered index to by-pass existing index key limits, and execute fully covered, indexed, queries. For more information, see Create Indexes with Included Columns. For details about index key limits see Maximum Capacity Specifications for SQL Server.

Reference: https://docs.microsoft.com/en-us/sql/relational-databases/indexes/clustered-and-nonclustered-indexes-described

When to use MyISAM and InnoDB?

Read about Storage Engines.

MyISAM:

The MyISAM storage engine in MySQL.

  • Simpler to design and create, thus better for beginners. No worries about the foreign relationships between tables.
  • Faster than InnoDB on the whole as a result of the simpler structure thus much less costs of server resources. -- Mostly no longer true.
  • Full-text indexing. -- InnoDB has it now
  • Especially good for read-intensive (select) tables. -- Mostly no longer true.
  • Disk footprint is 2x-3x less than InnoDB's. -- As of Version 5.7, this is perhaps the only real advantage of MyISAM.

InnoDB:

The InnoDB storage engine in MySQL.

  • Support for transactions (giving you support for the ACID property).
  • Row-level locking. Having a more fine grained locking-mechanism gives you higher concurrency compared to, for instance, MyISAM.
  • Foreign key constraints. Allowing you to let the database ensure the integrity of the state of the database, and the relationships between tables.
  • InnoDB is more resistant to table corruption than MyISAM.
  • Support for large buffer pool for both data and indexes. MyISAM key buffer is only for indexes.
  • MyISAM is stagnant; all future enhancements will be in InnoDB. This was made abundantly clear with the roll out of Version 8.0.

MyISAM Limitations:

  • No foreign keys and cascading deletes/updates
  • No transactional integrity (ACID compliance)
  • No rollback abilities
  • 4,284,867,296 row limit (2^32) -- This is old default. The configurable limit (for many versions) has been 2**56 bytes.
  • Maximum of 64 indexes per table

InnoDB Limitations:

  • No full text indexing (Below-5.6 mysql version)
  • Cannot be compressed for fast, read-only (5.5.14 introduced ROW_FORMAT=COMPRESSED)
  • You cannot repair an InnoDB table

For brief understanding read below links:

  1. MySQL Engines: InnoDB vs. MyISAM – A Comparison of Pros and Cons
  2. MySQL Engines: MyISAM vs. InnoDB
  3. What are the main differences between InnoDB and MyISAM?
  4. MyISAM versus InnoDB
  5. What's the difference between MyISAM and InnoDB?
  6. MySql: MyISAM vs. Inno DB!

self referential struct definition?

Lets go through basic definition of typedef. typedef use to define an alias to an existing data type either it is user defined or inbuilt.

typedef <data_type> <alias>;

for example

typedef int scores;

scores team1 = 99;

Confusion here is with the self referential structure, due to a member of same data type which is not define earlier. So In standard way you can write your code as :-

//View 1
typedef struct{ bool isParent; struct Cell* child;} Cell;

//View 2
typedef struct{
  bool isParent;
  struct Cell* child;
} Cell;

//Other Available ways, define stucture and create typedef
struct Cell {
  bool isParent;
  struct Cell* child;
};

typedef struct Cell Cell;

But last option increase some extra lines and words with usually we don't want to do (we are so lazy you know ;) ) . So prefer View 2.

WAMP Cannot access on local network 403 Forbidden

For those who may be running WAMP 3.1.4 with Apache 2.4.35 on Windows 10 (64-bit)

If you're having issues with external devices connecting to your localhost, and receiving a 403 Forbidden error, it may be an issue with your httpd.conf and the httpd-vhosts.conf files and the "Require local" line they both have within them.

[Before] httpd-vhosts.conf

<VirtualHost *:80>
 ServerName localhost
 ServerAlias localhost
 DocumentRoot "${INSTALL_DIR}/www"
 <Directory "${INSTALL_DIR}/www/">
   Options +Indexes +Includes +FollowSymLinks +MultiViews
   AllowOverride All
   Require local     <--- This is the offending line.
 </Directory>
</VirtualHost>

[After] httpd-vhosts.conf

<VirtualHost *:80>
 ServerName localhost
 ServerAlias localhost
 DocumentRoot "${INSTALL_DIR}/www"
 <Directory "${INSTALL_DIR}/www/">
   Options +Indexes +Includes +FollowSymLinks +MultiViews
   AllowOverride All
 </Directory>
</VirtualHost>

Additionally, you'll need to update your httpd.conf file as follows:

[Before] httpd.conf

DocumentRoot "${INSTALL_DIR}/www"
<Directory "${INSTALL_DIR}/www/">
#   onlineoffline tag - don't remove

    Require local  #<--- This is the offending line.
</Directory>

[After] httpd.conf

DocumentRoot "${INSTALL_DIR}/www"
<Directory "${INSTALL_DIR}/www/">
#   onlineoffline tag - don't remove

#   Require local
</Directory>

Make sure to restart your WAMP server via (System tray at bottom-right of screen --> left-click WAMP icon --> "Restart all Services").

Then refresh your machine's browser on localhost to ensure you've still got proper connectivity there, and then refresh your other external devices that you were previously attempting to connect.

Disclaimer: If you're in a corporate setting, this is untested from a security perspective; please ensure you're keenly aware of your local development environment's access protocols before implementing any sweeping changes.

Access host database from a docker container

Use host.docker.internal from Docker 18.03 onwards.

Makefile If-Then Else and Loops

You do see for loops alot of the time, but they are usually not needed. Here is an example of how one might perform a for loop without resorting to the shell

LIST_OF_THINGS_TO_DO = do_this do_that 
$(LIST_OF_THINGS_TO_DO): 
       run $@ > [email protected]

SUBDIRS = snafu fubar
$(SUBDIRS):
     cd $@ && $(MAKE)

Create a sample login page using servlet and JSP?

You're comparing the message with the empty string using ==.

First, your comparison is wrong because the message will be null (and not the empty string).

Second, it's wrong because Objects must be compared with equals() and not with ==.

Third, it's wrong because you should avoid scriptlets in JSP, and use the JSP EL, the JSTL, and other custom tags instead:

<c:id test="${!empty message}">
    <c:out value="${message}"/>
</c:if>

Add column with number of days between dates in DataFrame pandas

A list comprehension is your best bet for the most Pythonic (and fastest) way to do this:

[int(i.days) for i in (df.B - df.A)]
  1. i will return the timedelta(e.g. '-58 days')
  2. i.days will return this value as a long integer value(e.g. -58L)
  3. int(i.days) will give you the -58 you seek.

If your columns aren't in datetime format. The shorter syntax would be: df.A = pd.to_datetime(df.A)

How to get a vCard (.vcf file) into Android contacts from website

Just to let you know: I just tried it using a vCard 2.1 file created according to the vCard 2.1 spec. I found that vCard 2.1, despite being an old version, already covered everything I needed, including a base64-encoded photo and international character sets.

It worked perfectly on my unmodified Android 4.1.1 device (Galaxy S3). It also worked on an old iPhone 3GS (iOS 5, via the Evernote app) and a coworker's unmodified old Android 2.1 device. You only need to set the Content-disposition to attachment as suggested above.

A minor problem was that I triggered the VCF download using a QR code, which I scanned with the Microsoft Tag app. That app told me Android couldn't handle the text/x-vcard media type (or just text/vcard, no matter). Once I opened the link in a Web browser (I tried Chrome and the Android default browser), it worked fine.

Find a commit on GitHub given the commit hash

A URL of the form https://github.com/<owner>/<project>/commit/<hash> will show you the changes introduced in that commit. For example here's a recent bugfix I made to one of my projects on GitHub:

https://github.com/jerith666/git-graph/commit/35e32b6a00dec02ae7d7c45c6b7106779a124685

You can also shorten the hash to any unique prefix, like so:

https://github.com/jerith666/git-graph/commit/35e32b


I know you just asked about GitHub, but for completeness: If you have the repository checked out, from the command line, you can achieve basically the same thing with either of these commands (unique prefixes work here too):

git show 35e32b6a00dec02ae7d7c45c6b7106779a124685
git log -p -1 35e32b6a00dec02ae7d7c45c6b7106779a124685

Note: If you shorten the commit hash too far, the command line gives you a helpful disambiguation message, but GitHub will just return a 404.

Can I use Class.newInstance() with constructor arguments?

Assuming you have the following constructor

class MyClass {
    public MyClass(Long l, String s, int i) {

    }
}

You will need to show you intend to use this constructor like so:

Class classToLoad = MyClass.class;

Class[] cArg = new Class[3]; //Our constructor has 3 arguments
cArg[0] = Long.class; //First argument is of *object* type Long
cArg[1] = String.class; //Second argument is of *object* type String
cArg[2] = int.class; //Third argument is of *primitive* type int

Long l = new Long(88);
String s = "text";
int i = 5;

classToLoad.getDeclaredConstructor(cArg).newInstance(l, s, i);

Get device information (such as product, model) from adb command

The correct way to do it would be:

adb -s 123abc12 shell getprop

Which will give you a list of all available properties and their values. Once you know which property you want, you can give the name as an argument to getprop to access its value directly, like this:

adb -s 123abc12 shell getprop ro.product.model

The details in adb devices -l consist of the following three properties: ro.product.name, ro.product.model and ro.product.device.

Note that ADB shell ends lines with \r\n, which depending on your platform might or might not make it more difficult to access the exact value (e.g. instead of Nexus 7 you might get Nexus 7\r).

Javascript geocoding from address to latitude and longitude numbers not working

You're accessing the latitude and longitude incorrectly.

Try

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">

var geocoder = new google.maps.Geocoder();
var address = "new york";

geocoder.geocode( { 'address': address}, function(results, status) {

  if (status == google.maps.GeocoderStatus.OK) {
    var latitude = results[0].geometry.location.lat();
    var longitude = results[0].geometry.location.lng();
    alert(latitude);
  } 
}); 
</script>

What does %~dp0 mean, and how does it work?

Another tip that would help a lot is that to set the current directory to a different drive one would have to use %~d0 first, then cd %~dp0. This will change the directory to the batch file's drive, then change to its folder.

Alternatively, for #oneLinerLovers, as @Omni pointed out in the comments cd /d %~dp0 will change both the drive and directory :)

Hope this helps someone.

List all sequences in a Postgres db 8.1 with SQL

Improvement of the previous answer:

select string_agg('select sequence_name, last_value from ' || relname, chr(13) || 'union' || chr(13) order by relname) 
from pg_class where relkind ='S'

Numpy: Creating a complex array from 2 real ones?

I am python novice so this may not be the most efficient method but, if I understand the intent of the question correctly, steps listed below worked for me.

>>> import numpy as np
>>> Data = np.random.random((100, 100, 1000, 2))
>>> result = np.empty(Data.shape[:-1], dtype=complex)
>>> result.real = Data[...,0]; result.imag = Data[...,1]
>>> print Data[0,0,0,0], Data[0,0,0,1], result[0,0,0]
0.0782889873474 0.156087854837 (0.0782889873474+0.156087854837j)

file_get_contents behind a proxy?

Depending on how the proxy login works stream_context_set_default might help you.

$context  = stream_context_set_default(
  array(
    'http'=>array(
      'header'=>'Authorization: Basic ' . base64_encode('username'.':'.'userpass')
    )
  )
);
$result = file_get_contents('http://..../...');

Convert a hexadecimal string to an integer efficiently in C?

#include "math.h"
#include "stdio.h"
///////////////////////////////////////////////////////////////
//  The bits arg represents the bit say:8,16,32...                                                                                                              
/////////////////////////////////////////////////////////////
volatile long Hex_To_Int(long Hex,char bits)
{
    long Hex_2_Int;
    char byte;
    Hex_2_Int=0;

    for(byte=0;byte<bits;byte++)
    {
        if(Hex&(0x0001<<byte))
            Hex_2_Int+=1*(pow(2,byte));
        else
            Hex_2_Int+=0*(pow(2,byte));
    }

    return Hex_2_Int;
}
///////////////////////////////////////////////////////////////
//                                                                                                                  
/////////////////////////////////////////////////////////////

void main (void)
{
    int Dec;   
    char Hex=0xFA;
    Dec= Hex_To_Int(Hex,8);  //convert an 8-bis hexadecimal value to a number in base 10
    printf("the number is %d",Dec);
}

How to delete object from array inside foreach loop?

foreach($array as $elementKey => $element) {
    foreach($element as $valueKey => $value) {
        if($valueKey == 'id' && $value == 'searched_value'){
            //delete this particular object from the $array
            unset($array[$elementKey]);
        } 
    }
}

Is it possible in Java to access private fields via reflection

Yes it is possible.

You need to use the getDeclaredField method (instead of the getField method), with the name of your private field:

Field privateField = Test.class.getDeclaredField("str");

Additionally, you need to set this Field to be accessible, if you want to access a private field:

privateField.setAccessible(true);

Once that's done, you can use the get method on the Field instance, to access the value of the str field.

Should I use int or Int32

I always use the system types - e.g., Int32 instead of int. I adopted this practice after reading Applied .NET Framework Programming - author Jeffrey Richter makes a good case for using the full type names. Here are the two points that stuck with me:

  1. Type names can vary between .NET languages. For example, in C#, long maps to System.Int64 while in C++ with managed extensions, long maps to Int32. Since languages can be mixed-and-matched while using .NET, you can be sure that using the explicit class name will always be clearer, no matter the reader's preferred language.

  2. Many framework methods have type names as part of their method names:

    BinaryReader br = new BinaryReader( /* ... */ );
    float val = br.ReadSingle();     // OK, but it looks a little odd...
    Single val = br.ReadSingle();    // OK, and is easier to read
    

How do I keep a label centered in WinForms?

I wanted to do something similar, but on a form with a background image, I found that when the text in the label changed the repaints were obvious with this method, so I did the following: * Set the label AutoSize to true and TextAlign to MiddleCenter

Then, each time the text changed (mine was done using a timer) I called the following method:

    private Point GetPosition()
    {
        int y = (this.Height / 2) - (label1.Height / 2);
        int x = (this.Width / 2) - (label1.Width / 2);
        return new Point(x, y);
    }

And set the label's Location property to this return value. This ensured that the label was always in the center of the form when the text changed and the repaints for a full-screen form weren't obvious.

What is the difference between char * const and const char *?

  1. const char* x Here X is basically a character pointer which is pointing to a constant value

  2. char* const x is refer to character pointer which is constant, but the location it is pointing can be change.

  3. const char* const x is combination to 1 and 2, means it is a constant character pointer which is pointing to constant value.

  4. const *char x will cause a compiler error. it can not be declared.

  5. char const * x is equal to point 1.

the rule of thumb is if const is with var name then the pointer will be constant but the pointing location can be changed , else pointer will point to a constant location and pointer can point to another location but the pointing location content can not be change.

How to launch html using Chrome at "--allow-file-access-from-files" mode?

Search for the path of your Chrome executable and then, on your cmd, try :

> "C:\PathTo\Chrome.exe" --allow-file-access-from-files

Source

EDIT : As I see on your question, don't forget that Windows is a little bit similar to Unix, so when you type "chrome ...", cmd will search for Chrome in the PATH, but in general the Chrome folder isn't on the PATH. Also, you don't specify an extension for your executable... So if you move to Chrome's folder, this command will probably work too :

> .\chrome.exe --allow-file-access-from-files

What is cURL in PHP?

cURL is a library that lets you make HTTP requests in PHP. Everything you need to know about it (and most other extensions) can be found in the PHP manual.

In order to use PHP's cURL functions you need to install the » libcurl package. PHP requires that you use libcurl 7.0.2-beta or higher. In PHP 4.2.3, you will need libcurl version 7.9.0 or higher. From PHP 4.3.0, you will need a libcurl version that's 7.9.8 or higher. PHP 5.0.0 requires a libcurl version 7.10.5 or greater.

You can make HTTP requests without cURL, too, though it requires allow_url_fopen to be enabled in your php.ini file.

// Make a HTTP GET request and print it (requires allow_url_fopen to be enabled)
print file_get_contents('http://www.example.com/');

How can I generate a self-signed certificate with SubjectAltName using OpenSSL?

Can someone help me with the exact syntax?

It's a three-step process, and it involves modifying the openssl.cnf file. You might be able to do it with only command line options, but I don't do it that way.

Find your openssl.cnf file. It is likely located in /usr/lib/ssl/openssl.cnf:

$ find /usr/lib -name openssl.cnf
/usr/lib/openssl.cnf
/usr/lib/openssh/openssl.cnf
/usr/lib/ssl/openssl.cnf

On my Debian system, /usr/lib/ssl/openssl.cnf is used by the built-in openssl program. On recent Debian systems it is located at /etc/ssl/openssl.cnf

You can determine which openssl.cnf is being used by adding a spurious XXX to the file and see if openssl chokes.


First, modify the req parameters. Add an alternate_names section to openssl.cnf with the names you want to use. There are no existing alternate_names sections, so it does not matter where you add it.

[ alternate_names ]

DNS.1        = example.com
DNS.2        = www.example.com
DNS.3        = mail.example.com
DNS.4        = ftp.example.com

Next, add the following to the existing [ v3_ca ] section. Search for the exact string [ v3_ca ]:

subjectAltName      = @alternate_names

You might change keyUsage to the following under [ v3_ca ]:

keyUsage = digitalSignature, keyEncipherment

digitalSignature and keyEncipherment are standard fare for a server certificate. Don't worry about nonRepudiation. It's a useless bit thought up by computer science guys/gals who wanted to be lawyers. It means nothing in the legal world.

In the end, the IETF (RFC 5280), browsers and CAs run fast and loose, so it probably does not matter what key usage you provide.


Second, modify the signing parameters. Find this line under the CA_default section:

# Extension copying option: use with caution.
# copy_extensions = copy

And change it to:

# Extension copying option: use with caution.
copy_extensions = copy

This ensures the SANs are copied into the certificate. The other ways to copy the DNS names are broken.


Third, generate your self-signed certificate:

$ openssl genrsa -out private.key 3072
$ openssl req -new -x509 -key private.key -sha256 -out certificate.pem -days 730
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
...

Finally, examine the certificate:

$ openssl x509 -in certificate.pem -text -noout
Certificate:
    Data:
        Version: 3 (0x2)
        Serial Number: 9647297427330319047 (0x85e215e5869042c7)
    Signature Algorithm: sha256WithRSAEncryption
        Issuer: C=US, ST=MD, L=Baltimore, O=Test CA, Limited, CN=Test CA/[email protected]
        Validity
            Not Before: Feb  1 05:23:05 2014 GMT
            Not After : Feb  1 05:23:05 2016 GMT
        Subject: C=US, ST=MD, L=Baltimore, O=Test CA, Limited, CN=Test CA/[email protected]
        Subject Public Key Info:
            Public Key Algorithm: rsaEncryption
                Public-Key: (3072 bit)
                Modulus:
                    00:e2:e9:0e:9a:b8:52:d4:91:cf:ed:33:53:8e:35:
                    ...
                    d6:7d:ed:67:44:c3:65:38:5d:6c:94:e5:98:ab:8c:
                    72:1c:45:92:2c:88:a9:be:0b:f9
                Exponent: 65537 (0x10001)
        X509v3 extensions:
            X509v3 Subject Key Identifier:
                34:66:39:7C:EC:8B:70:80:9E:6F:95:89:DB:B5:B9:B8:D8:F8:AF:A4
            X509v3 Authority Key Identifier:
                keyid:34:66:39:7C:EC:8B:70:80:9E:6F:95:89:DB:B5:B9:B8:D8:F8:AF:A4

            X509v3 Basic Constraints: critical
                CA:FALSE
            X509v3 Key Usage:
                Digital Signature, Non Repudiation, Key Encipherment, Certificate Sign
            X509v3 Subject Alternative Name:
                DNS:example.com, DNS:www.example.com, DNS:mail.example.com, DNS:ftp.example.com
    Signature Algorithm: sha256WithRSAEncryption
         3b:28:fc:e3:b5:43:5a:d2:a0:b8:01:9b:fa:26:47:8e:5c:b7:
         ...
         71:21:b9:1f:fa:30:19:8b:be:d2:19:5a:84:6c:81:82:95:ef:
         8b:0a:bd:65:03:d1

How to return data from PHP to a jQuery ajax call

I figured it out. Need to use echo in PHP instead of return.

<?php 
  $output = some_function();
  echo $output;
?> 

And the jQ:

success: function(data) {
  doSomething(data);
}

How do I UPDATE from a SELECT in SQL Server?

UPDATE from SELECT with INNER JOIN in SQL Database

Since there are too many replies of this post, which are most heavily up-voted, I thought I would provide my suggestion here too. Although the question is very interesting, I have seen in many forum sites and made a solution using INNER JOIN with screenshots.

At first, I have created a table named with schoolold and inserted few records with respect to their column names and execute it.

Then I executed SELECT command to view inserted records.

Then I created a new table named with schoolnew and similarly executed above actions on it.

Then, to view inserted records in it, I execute SELECT command.

Now, Here I want to make some changes in third and fourth row, to complete this action, I execute UPDATE command with INNER JOIN.

To view the changes I execute the SELECT command.

You can see how Third and Fourth records of table schoolold easily replaced with table schoolnew by using INNER JOIN with UPDATE statement.

Append values to query string

You could use the HttpUtility.ParseQueryString method and an UriBuilder which provides a nice way to work with query string parameters without worrying about things like parsing, url encoding, ...:

string longurl = "http://somesite.com/news.php?article=1&lang=en";
var uriBuilder = new UriBuilder(longurl);
var query = HttpUtility.ParseQueryString(uriBuilder.Query);
query["action"] = "login1";
query["attempts"] = "11";
uriBuilder.Query = query.ToString();
longurl = uriBuilder.ToString();
// "http://somesite.com:80/news.php?article=1&lang=en&action=login1&attempts=11"

Reading json files in C++

Essentially javascript and C++ work on two different principles. Javascript creates an "associative array" or hash table, which matches a string key, which is the field name, to a value. C++ lays out structures in memory, so the first 4 bytes are an integer, which is an age, then maybe we have a fixed-wth 32 byte string which represents the "profession".

So javascript will handle things like "age" being 18 in one record and "nineteen" in another. C++ can't. (However C++ is much faster).

So if we want to handle JSON in C++, we have to build the associative array from the ground up. Then we have to tag the values with their types. Is it an integer, a real value (probably return as "double"), boolean, a string? It follows that a JSON C++ class is quite a large chunk of code. Effectively what we are doing is implementing a bit of the javascript engine in C++. We then pass our JSON parser the JSON as a string, and it tokenises it, and gives us functions to query the JSON from C++.

How to create batch file in Windows using "start" with a path and command with spaces

Actually, his example won't work (although at first I thought that it would, too). Based on the help for the Start command, the first parameter is the name of the newly created Command Prompt window, and the second and third should be the path to the application and its parameters, respectively. If you add another "" before path to the app, it should work (at least it did for me). Use something like this:

start "" "c:\path with spaces\app.exe" param1 "param with spaces"

You can change the first argument to be whatever you want the title of the new command prompt to be. If it's a Windows app that is created, then the command prompt won't be displayed, and the title won't matter.

How to remove non-alphanumeric characters?

If you need to support other languages, instead of the typical A-Z, you can use the following:

preg_replace('/[^\p{L}\p{N} ]+/', '', $string);
  • [^\p{L}\p{N} ] defines a negated (It will match a character that is not defined) character class of:
    • \p{L}: a letter from any language.
    • \p{N}: a numeric character in any script.
    • : a space character.
  • + greedily matches the character class between 1 and unlimited times.

This will preserve letters and numbers from other languages and scripts as well as A-Z:

preg_replace('/[^\p{L}\p{N} ]+/', '', 'hello-world'); // helloworld
preg_replace('/[^\p{L}\p{N} ]+/', '', 'abc@~#123-+=öäå'); // abc123öäå
preg_replace('/[^\p{L}\p{N} ]+/', '', '????!@£$%^&*()'); // ????

Note: This is a very old, but still relevant question. I am answering purely to provide supplementary information that may be useful to future visitors.

Static class initializer in PHP

Actually, I use a public static method __init__() on my static classes that require initialization (or at least need to execute some code). Then, in my autoloader, when it loads a class it checks is_callable($class, '__init__'). If it is, it calls that method. Quick, simple and effective...

Adding a Scrollable JTextArea (Java)

  1. Open design view
  2. Right click to textArea
  3. open surround with option
  4. select "...JScrollPane".

Python exit commands - why so many and when should each be used?

Let me give some information on them:

  1. quit() simply raises the SystemExit exception.

    Furthermore, if you print it, it will give a message:

    >>> print (quit)
    Use quit() or Ctrl-Z plus Return to exit
    >>>
    

    This functionality was included to help people who do not know Python. After all, one of the most likely things a newbie will try to exit Python is typing in quit.

    Nevertheless, quit should not be used in production code. This is because it only works if the site module is loaded. Instead, this function should only be used in the interpreter.

  2. exit() is an alias for quit (or vice-versa). They exist together simply to make Python more user-friendly.

    Furthermore, it too gives a message when printed:

    >>> print (exit)
    Use exit() or Ctrl-Z plus Return to exit
    >>>
    

    However, like quit, exit is considered bad to use in production code and should be reserved for use in the interpreter. This is because it too relies on the site module.

  3. sys.exit() also raises the SystemExit exception. This means that it is the same as quit and exit in that respect.

    Unlike those two however, sys.exit is considered good to use in production code. This is because the sys module will always be there.

  4. os._exit() exits the program without calling cleanup handlers, flushing stdio buffers, etc. Thus, it is not a standard way to exit and should only be used in special cases. The most common of these is in the child process(es) created by os.fork.

    Note that, of the four methods given, only this one is unique in what it does.

Summed up, all four methods exit the program. However, the first two are considered bad to use in production code and the last is a non-standard, dirty way that is only used in special scenarios. So, if you want to exit a program normally, go with the third method: sys.exit.


Or, even better in my opinion, you can just do directly what sys.exit does behind the scenes and run:

raise SystemExit

This way, you do not need to import sys first.

However, this choice is simply one on style and is purely up to you.

SQL Server: Make all UPPER case to Proper Case/Title Case

On Server Server 2016 and newer, you can use STRING_SPLIT


with t as (
    select 'GOOFYEAR Tire and Rubber Company' as n
    union all
    select 'THE HAPPY BEAR' as n
    union all
    select 'MONK HOUSE SALES' as n
    union all
    select 'FORUM COMMUNICATIONS' as n
)
select
    n,
    (
        select ' ' + (
            upper(left(value, 1))
            + lower(substring(value, 2, 999))
        )
        from (
            select value
            from string_split(t.n, ' ')
        ) as sq
        for xml path ('')
    ) as title_cased
from t

Example

Generate insert script for selected records?

SELECT 'INSERT SomeOtherDB.dbo.table(column1,column2,etc.)
  SELECT ' + CONVERT(VARCHAR(12), Pk_Id) + ','
       + '''' + REPLACE(ProductName, '''', '''''') + ''','
       + CONVERT(VARCHAR(12), Fk_CompanyId) + ','
       + CONVERT(VARCHAR(12), Price) + ';'
FROM dbo.unspecified_table_name
WHERE Fk_CompanyId = 1;

In C can a long printf statement be broken up into multiple lines?

If you want to break a string literal onto multiple lines, you can concatenate multiple strings together, one on each line, like so:

printf("name: %s\t"
"args: %s\t"
"value %d\t"
"arraysize %d\n", 
sp->name, 
sp->args, 
sp->value, 
sp->arraysize);

Basic authentication with fetch?

If you have a backend server asking for the Basic Auth credentials before the app then this is sufficient, it will re-use that then:

fetch(url, {
  credentials: 'include',
}).then(...);

Why is this jQuery click function not working?

You can use $(function(){ // code }); which is executed when the document is ready to execute the code inside that block.

$(function(){
    $('#clicker').click(function(){
        alert('hey');
        $('.hide_div').hide();
    });
});

How do I find the maximum of 2 numbers?

You could also achieve the same result by using a Conditional Expression:

maxnum = run if run > value else value

a bit more flexible than max but admittedly longer to type.

Charts for Android

SciChart for Android is a relative newcomer, but brings extremely fast high performance real-time charting to the Android platform.

SciChart is a commercial control but available under royalty free distribution / per developer licensing. There is also free licensing available for educational use with some conditions.

Some useful links can be found below:

enter image description here

Disclosure: I am the tech lead on the SciChart project!

how to create a Java Date object of midnight today and midnight tomorrow?

Old fashioned way..

private static Date getDateWithMidnight(){
    long dateInMillis = new Date().getTime();
    return new Date(dateInMillis - dateInMillis%(1000*60*60*24) - TimeZone.getDefault().getOffset(dateInMillis));
}

How can I delay a :hover effect in CSS?

You can use transitions to delay the :hover effect you want, if the effect is CSS-based.

For example

div{
    transition: 0s background-color;
}

div:hover{
    background-color:red;    
    transition-delay:1s;
}

this will delay applying the the hover effects (background-color in this case) for one second.


Demo of delay on both hover on and off:

_x000D_
_x000D_
div{_x000D_
    display:inline-block;_x000D_
    padding:5px;_x000D_
    margin:10px;_x000D_
    border:1px solid #ccc;_x000D_
    transition: 0s background-color;_x000D_
    transition-delay:1s;_x000D_
}_x000D_
div:hover{_x000D_
    background-color:red;_x000D_
}
_x000D_
<div>delayed hover</div>
_x000D_
_x000D_
_x000D_

Demo of delay only on hover on:

_x000D_
_x000D_
div{_x000D_
    display:inline-block;_x000D_
    padding:5px;_x000D_
    margin:10px;_x000D_
    border:1px solid #ccc;_x000D_
    transition: 0s background-color;_x000D_
}_x000D_
div:hover{_x000D_
    background-color:red;    _x000D_
    transition-delay:1s;_x000D_
}
_x000D_
<div>delayed hover</div>
_x000D_
_x000D_
_x000D_


Vendor Specific Extentions for Transitions and W3C CSS3 transitions

How to pip install a package with min and max version range?

An elegant method would be to use the ~= compatible release operator according to PEP 440. In your case this would amount to:

package~=0.5.0

As an example, if the following versions exist, it would choose 0.5.9:

  • 0.5.0
  • 0.5.9
  • 0.6.0

For clarification, each pair is equivalent:

~= 0.5.0
>= 0.5.0, == 0.5.*

~= 0.5
>= 0.5, == 0.*

SQL: How to to SUM two values from different tables

SELECT (SELECT COALESCE(SUM(London), 0) FROM CASH) + (SELECT COALESCE(SUM(London), 0) FROM CHEQUE) as result

'And so on and so forth.

"The COALESCE function basically says "return the first parameter, unless it's null in which case return the second parameter" - It's quite handy in these scenarios." Source

Cannot import keras after installation

Ran to the same issue, Assuming your using anaconda3 and your using a venv with >= python=3.6:

python -m pip install keras
sudo python -m pip install --user tensorflow

C++ - Decimal to binary converting

here a simple converter by using std::string as container. it allows a negative value.

#include <iostream>
#include <string>
#include <limits>

int main()
{
    int x = -14;

    int n = std::numeric_limits<int>::digits - 1;

    std::string s;
    s.reserve(n + 1);

    do
        s.push_back(((x >> n) & 1) + '0');
    while(--n > -1);

    std::cout << s << '\n';
}

When are static variables initialized?

Starting with the code from the other question:

class MyClass {
  private static MyClass myClass = new MyClass();
  private static final Object obj = new Object();
  public MyClass() {
    System.out.println(obj); // will print null once
  }
}

A reference to this class will start initialization. First, the class will be marked as initialized. Then the first static field will be initialized with a new instance of MyClass(). Note that myClass is immediately given a reference to a blank MyClass instance. The space is there, but all values are null. The constructor is now executed and prints obj, which is null.

Now back to initializing the class: obj is made a reference to a new real object, and we're done.

If this was set off by a statement like: MyClass mc = new MyClass(); space for a new MyClass instance is again allocated (and the reference placed in mc). The constructor is again executed and again prints obj, which now is not null.

The real trick here is that when you use new, as in WhatEverItIs weii = new WhatEverItIs( p1, p2 ); weii is immediately given a reference to a bit of nulled memory. The JVM will then go on to initialize values and run the constructor. But if you somehow reference weii before it does so--by referencing it from another thread or or by referencing from the class initialization, for instance--you are looking at a class instance filled with null values.

Predefined type 'System.ValueTuple´2´ is not defined or imported

For .NET 4.6.2 or lower, .NET Core 1.x, and .NET Standard 1.x you need to install the NuGet package System.ValueTuple:

Install-Package "System.ValueTuple"

Or using a package reference in VS 2017:

<PackageReference Include="System.ValueTuple" Version="4.4.0" />

.NET Framework 4.7, .NET Core 2.0, and .NET Standard 2.0 include these types.

What is the equivalent of ngShow and ngHide in Angular 2+?

I find myself in the same situation with the difference than in my case the element was a flex container.If is not your case an easy work around could be

[style.display]="!isLoading ? 'block' : 'none'"

in my case due to the fact that a lot of browsers that we support still need the vendor prefix to avoid problems i went for another easy solution

[class.is-loading]="isLoading"

where then the CSS is simple as

&.is-loading { display: none } 

to leave then the displayed state handled by the default class.

Python Requests package: Handling xml response

requests does not handle parsing XML responses, no. XML responses are much more complex in nature than JSON responses, how you'd serialize XML data into Python structures is not nearly as straightforward.

Python comes with built-in XML parsers. I recommend you use the ElementTree API:

import requests
from xml.etree import ElementTree

response = requests.get(url)

tree = ElementTree.fromstring(response.content)

or, if the response is particularly large, use an incremental approach:

    response = requests.get(url, stream=True)
    # if the server sent a Gzip or Deflate compressed response, decompress
    # as we read the raw stream:
    response.raw.decode_content = True

    events = ElementTree.iterparse(response.raw)
    for event, elem in events:
        # do something with `elem`

The external lxml project builds on the same API to give you more features and power still.

How do I rename a Git repository?

If you meant renaming your repository, go to your repository and click "admin", then rename.

Once you see the red box warning you about some sky-fallingness and other things, go read this question.

"The specified Android SDK Build Tools version (26.0.0) is ignored..."

just clean and make project / rebuilt fixed my issue give a try :-)

How to check if a MySQL query using the legacy API was successful?

This is the first example in the manual page for mysql_query:

$result = mysql_query('SELECT * WHERE 1=1');
if (!$result) {
    die('Invalid query: ' . mysql_error());
}

If you wish to use something other than die, then I'd suggest trigger_error.

Fragment transaction animation: slide in and slide out

There is three way to transaction animation in fragment.

Transitions

So need to use one of the built-in Transitions, use the setTranstion() method:

getSupportFragmentManager()
        .beginTransaction()
        .setTransition( FragmentTransaction.TRANSIT_FRAGMENT_OPEN )
        .show( m_topFragment )
        .commit()

Custom Animations

You can also customize the animation by using the setCustomAnimations() method:

getSupportFragmentManager()
        .beginTransaction()
        .setCustomAnimations( R.anim.slide_up, 0, 0, R.anim.slide_down)
        .show( m_topFragment )
        .commit()

slide_up.xml

<?xml version="1.0" encoding="utf-8"?>
<objectAnimator
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:interpolator="@android:anim/accelerate_decelerate_interpolator"
        android:propertyName="translationY"
        android:valueType="floatType"
        android:valueFrom="1280"
        android:valueTo="0"
        android:duration="@android:integer/config_mediumAnimTime"/>

slide_down.xml

<?xml version="1.0" encoding="utf-8"?>
<objectAnimator
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:interpolator="@android:anim/accelerate_decelerate_interpolator"
        android:propertyName="translationY"
        android:valueType="floatType"
        android:valueFrom="0"
        android:valueTo="1280"
        android:duration="@android:integer/config_mediumAnimTime"/>

Multiple Animations

Finally, It's also possible to kick-off multiple fragment animations in a single transaction. This allows for a pretty cool effect where one fragment is sliding up and the other slides down at the same time:

getSupportFragmentManager()
        .beginTransaction()
        .setCustomAnimations( R.anim.abc_slide_in_top, R.anim.abc_slide_out_top ) // Top Fragment Animation
        .show( m_topFragment )
        .setCustomAnimations( R.anim.abc_slide_in_bottom, R.anim.abc_slide_out_bottom ) // Bottom Fragment Animation
        .show( m_bottomFragment )
        .commit()

To more detail you can visit URL

Note:- You can check animation according to your requirement because above may be have issue.

How to position a DIV in a specific coordinates?

You don't have to use Javascript to do this. Using plain-old css:

div.blah {
  position:absolute;
  top: 0; /*[wherever you want it]*/
  left:0; /*[wherever you want it]*/
}

If you feel you must use javascript, or are trying to do this dynamically Using JQuery, this affects all divs of class "blah":

var blahclass =  $('.blah'); 
blahclass.css('position', 'absolute');
blahclass.css('top', 0); //or wherever you want it
blahclass.css('left', 0); //or wherever you want it

Alternatively, if you must use regular old-javascript you can grab by id

var domElement = document.getElementById('myElement');// don't go to to DOM every time you need it. Instead store in a variable and manipulate.
domElement.style.position = "absolute";
domElement.style.top = 0; //or whatever 
domElement.style.left = 0; // or whatever

Python3: ImportError: No module named '_ctypes' when using Value from module multiprocessing

Installing libffi-dev and re-installing python3.7 fixed the problem for me.

to cleanly build py 3.7 libffi-dev is required or else later stuff will fail

If using RHEL/Fedora:

yum install libffi-devel

or

sudo dnf install libffi-devel

If using Debian/Ubuntu:

sudo apt-get install libffi-dev

What should I do when 'svn cleanup' fails?

$ ls -la .svn
$ rm -f .svn/lock

Then

$ svn update

Hope it helps

Excel concatenation quotes

I was Forming some Programming Logic Used CHAR(34) for Quotes at Excel : A small Part of same I am posting which can be helpfull ,Hopefully

1   Customers
2   Invoices

Formula Used :

=CONCATENATE("listEvents.Add(",D4,",",CHAR(34),E4,CHAR(34),");")

Result :

listEvents.Add(1,"Customers");
listEvents.Add(2,"Invoices");

How can I quantify difference between two images?

Have you seen the Algorithm for finding similar images question? Check it out to see suggestions.

I would suggest a wavelet transformation of your frames (I've written a C extension for that using Haar transformation); then, comparing the indexes of the largest (proportionally) wavelet factors between the two pictures, you should get a numerical similarity approximation.

SQL - How to find the highest number in a column?

You can also use relational algebra. A bit lengthy procedure, but here it is just to understand how MAX() works:

E := pID (Table_Name)
E1 := pID (sID >= ID' ((?ID' E) ? E)) – pID (sID < ID’ ((?ID' E) ? E))

Your answer: Table_Name ? E1

Basically what you do is subtract set of ordered relation(a,b) in which a<b from A where a, b ? A.

For relation algebra symbols see: Relational algebra From Wikipedia

How do I "select Android SDK" in Android Studio?

My problem solved by setting NDK path in Android Studio.

File-> Project Structure->NDK Location.

Rails Active Record find(:all, :order => ) issue

isn't it only :order => 'column1 ASC, column2 DESC'?

Taking multiple inputs from user in python

Split function will split the input data according to whitespace.

data = input().split()
name=data[0]
id=data[1]
marks = list(map(datatype, data[2:]))

name will get first column, id will contain second column and marks will be a list which will contain data from third column to last column.

How do I format date and time on ssrs report?

In SSRS 2016 There is an option under the properties header "Localization" called "Calendar", if you click on this it gives you these 2 options:

  • Gregorian (dd/mm/yyyy)
  • GregorianUSEnglish (MM/dd/yyyy)

This works brilliantly when referencing data from a tables aswell

alternatively if this does not work for you, specify one of these formats under "Number" and in the cell "Format":

dd/MM/yyyy or MM/dd/yyyy

printscreen

How does Java resolve a relative path in new File()?

Only slightly related to the question, but try to wrap your head around this one. So un-intuitive:

import java.nio.file.*;
class Main {
  public static void main(String[] args) {
    Path p1 = Paths.get("/personal/./photos/./readme.txt");
    Path p2 = Paths.get("/personal/index.html");
    Path p3 = p1.relativize(p2);
    System.out.println(p3); //prints  ../../../../index.html  !!
  }
}

MySql sum elements of a column

 select sum(A),sum(B),sum(C) from mytable where id in (1,2,3);

Combining node.js and Python

For communication between node.js and Python server, I would use Unix sockets if both processes run on the same server and TCP/IP sockets otherwise. For marshaling protocol I would take JSON or protocol buffer. If threaded Python shows up to be a bottleneck, consider using Twisted Python, which provides the same event driven concurrency as do node.js.

If you feel adventurous, learn clojure (clojurescript, clojure-py) and you'll get the same language that runs and interoperates with existing code on Java, JavaScript (node.js included), CLR and Python. And you get superb marshalling protocol by simply using clojure data structures.

How to map a composite key with JPA and Hibernate?

Another option is to map is as a Map of composite elements in the ConfPath table.

This mapping would benefit from an index on (ConfPathID,levelStation) though.

public class ConfPath {
    private Map<Long,Time> timeForLevelStation = new HashMap<Long,Time>();

    public Time getTime(long levelStation) {
        return timeForLevelStation.get(levelStation);
    }

    public void putTime(long levelStation, Time newValue) {
        timeForLevelStation.put(levelStation, newValue);
    }
}

public class Time {
    String src;
    String dst;
    long distance;
    long price;

    public long getDistance() {
        return distance;
    }

    public void setDistance(long distance) {
        this.distance = distance;
    }

    public String getDst() {
        return dst;
    }

    public void setDst(String dst) {
        this.dst = dst;
    }

    public long getPrice() {
        return price;
    }

    public void setPrice(long price) {
        this.price = price;
    }

    public String getSrc() {
        return src;
    }

    public void setSrc(String src) {
        this.src = src;
    }
}

Mapping:

<class name="ConfPath" table="ConfPath">
    <id column="ID" name="id">
        <generator class="native"/>
    </id>
    <map cascade="all-delete-orphan" name="values" table="example"
            lazy="extra">
        <key column="ConfPathID"/>
        <map-key type="long" column="levelStation"/>
        <composite-element class="Time">
            <property name="src" column="src" type="string" length="100"/>
            <property name="dst" column="dst" type="string" length="100"/>
            <property name="distance" column="distance"/>
            <property name="price" column="price"/>
        </composite-element>
    </map>
</class>

'tsc command not found' in compiling typescript

Non-admin solution

I do not have admin privileges since this machine was issued by my job.

  • get path of where node modules are being installed and copy to clipboard
    • npm config get prefix | clip
    • don't have clip? just copy output from npm config get prefix
  • add copied path to environment variables
    • my preferred method (Windows)
    • (Ctrl + R), paste rundll32 sysdm.cpl,EditEnvironmentVariables
    • under User Variables, double-click on Path > New > Paste copied path

How do I check if a number is positive or negative in C#?

You just have to compare if the value & its absolute value are equal:

if (value == Math.abs(value))
    return "Positif"
else return "Negatif"

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

A common misunderstanding among starters is that they think that the call of a forward(), sendRedirect(), or sendError() would magically exit and "jump" out of the method block, hereby ignoring the remnant of the code. For example:

protected void doXxx() {
    if (someCondition) {
        sendRedirect();
    }
    forward(); // This is STILL invoked when someCondition is true!
}

This is thus actually not true. They do certainly not behave differently than any other Java methods (expect of System#exit() of course). When the someCondition in above example is true and you're thus calling forward() after sendRedirect() or sendError() on the same request/response, then the chance is big that you will get the exception:

java.lang.IllegalStateException: Cannot forward after response has been committed

If the if statement calls a forward() and you're afterwards calling sendRedirect() or sendError(), then below exception will be thrown:

java.lang.IllegalStateException: Cannot call sendRedirect() after the response has been committed

To fix this, you need either to add a return; statement afterwards

protected void doXxx() {
    if (someCondition) {
        sendRedirect();
        return;
    }
    forward();
}

... or to introduce an else block.

protected void doXxx() {
    if (someCondition) {
        sendRedirect();
    } else {
        forward();
    }
}

To naildown the root cause in your code, just search for any line which calls a forward(), sendRedirect() or sendError() without exiting the method block or skipping the remnant of the code. This can be inside the same servlet before the particular code line, but also in any servlet or filter which was been called before the particular servlet.

In case of sendError(), if your sole purpose is to set the response status, use setStatus() instead.


Another probable cause is that the servlet writes to the response while a forward() will be called, or has been called in the very same method.

protected void doXxx() {
    out.write("some string");
    // ... 
    forward(); // Fail!
}

The response buffer size defaults in most server to 2KB, so if you write more than 2KB to it, then it will be committed and forward() will fail the same way:

java.lang.IllegalStateException: Cannot forward after response has been committed

Solution is obvious, just don't write to the response in the servlet. That's the responsibility of the JSP. You just set a request attribute like so request.setAttribute("data", "some string") and then print it in JSP like so ${data}. See also our Servlets wiki page to learn how to use Servlets the right way.


Another probable cause is that the servlet writes a file download to the response after which e.g. a forward() is called.

protected void doXxx() {
    out.write(bytes);
    // ... 
    forward(); // Fail!
}

This is technically not possible. You need to remove the forward() call. The enduser will stay on the currently opened page. If you actually intend to change the page after a file download, then you need to move the file download logic to page load of the target page.


Yet another probable cause is that the forward(), sendRedirect() or sendError() methods are invoked via Java code embedded in a JSP file in form of old fashioned way <% scriptlets %>, a practice which was officially discouraged since 2001. For example:

<!DOCTYPE html>
<html lang="en">
    <head>
        ... 
    </head>
    <body>
        ...

        <% sendRedirect(); %>
        
        ...
    </body>
</html>

The problem here is that JSP internally immediately writes template text (i.e. HTML code) via out.write("<!DOCTYPE html> ... etc ...") as soon as it's encountered. This is thus essentially the same problem as explained in previous section.

Solution is obvious, just don't write Java code in a JSP file. That's the responsibility of a normal Java class such as a Servlet or a Filter. See also our Servlets wiki page to learn how to use Servlets the right way.


See also:


Unrelated to your concrete problem, your JDBC code is leaking resources. Fix that as well. For hints, see also How often should Connection, Statement and ResultSet be closed in JDBC?

make: *** No rule to make target `all'. Stop

Your makefile should ideally be named makefile, not make. Note that you can call your makefile anything you like, but as you found, you then need the -f option with make to specify the name of the makefile. Using the default name of makefile just makes life easier.

How to prevent http file caching in Apache httpd (MAMP)

Based on the example here: http://drupal.org/node/550488

The following will probably work in .htaccess

 <IfModule mod_expires.c>
   # Enable expirations.
   ExpiresActive On

   # Cache all files for 2 weeks after access (A).
   ExpiresDefault A1209600

  <FilesMatch (\.js|\.html)$>
     ExpiresActive Off
  </FilesMatch>
 </IfModule>

mongodb how to get max value from collections

You can also achieve this through aggregate pipeline.

db.collection.aggregate([{$sort:{age:-1}}, {$limit:1}])

How to apply two CSS classes to a single element

As others have pointed out, you simply delimit them with a space.

However, knowing how the selectors work is also useful.

Consider this piece of HTML...

<div class="a"></div>
<div class="b"></div>
<div class="a b"></div>

Using .a { ... } as a selector will select the first and third. However, if you want to select one which has both a and b, you can use the selector .a.b { ... }. Note that this won't work in IE6, it will simply select .b (the last one).

How to allow only one radio button to be checked?

Give them the same name, and it will work. By definition Radio buttons will only have one choice, while check boxes can have many.

<input type="radio" name="Radio1" />

A column-vector y was passed when a 1d array was expected

use below code:

model = forest.fit(train_fold, train_y.ravel())

if you are still getting slap by error as identical as below ?

Unknown label type: %r" % y

use this code:

y = train_y.ravel()
train_y = np.array(y).astype(int)
model = forest.fit(train_fold, train_y)

laravel throwing MethodNotAllowedHttpException

You are getting that error because you are posting to a GET route.

I would split your routing for validate into a separate GET and POST routes.

New Routes:

Route::post('validate', 'MemberController@validateCredentials');

Route::get('validate', function () {
    return View::make('members/login');
});

Then your controller method could just be

public function validateCredentials()
{
    $email = Input::post('email');
    $password = Input::post('password');
    return "Email: " . $email . " and Password: " . $password;
}

Using Jasmine to spy on a function without an object

My answer differs slightly to @FlavorScape in that I had a single (default export) function in the imported module, I did the following:

import * as functionToTest from 'whatever-lib';

const fooSpy = spyOn(functionToTest, 'default');

Populating a ListView using an ArrayList?

You need to do it through an ArrayAdapter which will adapt your ArrayList (or any other collection) to your items in your layout (ListView, Spinner etc.).

This is what the Android developer guide says:

A ListAdapter that manages a ListView backed by an array of arbitrary objects. By default this class expects that the provided resource id references a single TextView. If you want to use a more complex layout, use the constructors that also takes a field id. That field id should reference a TextView in the larger layout resource.

However the TextView is referenced, it will be filled with the toString() of each object in the array. You can add lists or arrays of custom objects. Override the toString() method of your objects to determine what text will be displayed for the item in the list.

To use something other than TextViews for the array display, for instance ImageViews, or to have some of data besides toString() results fill the views, override getView(int, View, ViewGroup) to return the type of view you want.

So your code should look like:

public class YourActivity extends Activity {

    private ListView lv;

    public void onCreate(Bundle saveInstanceState) {
         setContentView(R.layout.your_layout);

         lv = (ListView) findViewById(R.id.your_list_view_id);

         // Instanciating an array list (you don't need to do this, 
         // you already have yours).
         List<String> your_array_list = new ArrayList<String>();
         your_array_list.add("foo");
         your_array_list.add("bar");

         // This is the array adapter, it takes the context of the activity as a 
         // first parameter, the type of list view as a second parameter and your 
         // array as a third parameter.
         ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
                 this, 
                 android.R.layout.simple_list_item_1,
                 your_array_list );

         lv.setAdapter(arrayAdapter); 
    }
}

How to do a deep comparison between 2 objects with lodash?

Without use of lodash/underscore, I have written this code and is working fine for me for a deep comparison of object1 with object2

function getObjectDiff(a, b) {
    var diffObj = {};
    if (Array.isArray(a)) {
        a.forEach(function(elem, index) {
            if (!Array.isArray(diffObj)) {
                diffObj = [];
            }
            diffObj[index] = getObjectDiff(elem, (b || [])[index]);
        });
    } else if (a != null && typeof a == 'object') {
        Object.keys(a).forEach(function(key) {
            if (Array.isArray(a[key])) {
                var arr = getObjectDiff(a[key], b[key]);
                if (!Array.isArray(arr)) {
                    arr = [];
                }
                arr.forEach(function(elem, index) {
                    if (!Array.isArray(diffObj[key])) {
                        diffObj[key] = [];
                    }
                    diffObj[key][index] = elem;
                });
            } else if (typeof a[key] == 'object') {
                diffObj[key] = getObjectDiff(a[key], b[key]);
            } else if (a[key] != (b || {})[key]) {
                diffObj[key] = a[key];
            } else if (a[key] == (b || {})[key]) {
                delete a[key];
            }
        });
    }
    Object.keys(diffObj).forEach(function(key) {
        if (typeof diffObj[key] == 'object' && JSON.stringify(diffObj[key]) == '{}') {
            delete diffObj[key];
        }
    });
    return diffObj;
}

How to set HttpResponse timeout for Android in Java

public boolean isInternetWorking(){
    try {
        int timeOut = 5000;
        Socket socket = new Socket();
        SocketAddress socketAddress = new InetSocketAddress("8.8.8.8",53);
        socket.connect(socketAddress,timeOut);
        socket.close();
        return true;
    } catch (IOException e) {
        //silent
    }
    return false;
}

Stateless vs Stateful

The adjective Stateful or Stateless refers only to the state of the conversation, it is not in connection with the concept of function which provides the same output for the same input. If so any dynamic web application (with a database behind it) would be a stateful service, which is obviously false. With this in mind if I entrust the task to keep conversational state in the underlying technology (such as a coockie or http session) I'm implementing a stateful service, but if all the necessary information (the context) are passed as parameters I'm implementing a stateless service. It should be noted that even if the passed parameter is an "identifier" of the conversational state (e.g. a ticket or a sessionId) we are still operating under a stateless service, because the conversation is stateless (the ticket is continually passed between client and server), and are the two endpoints to be, so to speak, "stateful".

How to show text on image when hovering?

_x000D_
_x000D_
.container {_x000D_
  position: relative;_x000D_
  width: 50%;_x000D_
}_x000D_
_x000D_
.image {_x000D_
  display: block;_x000D_
  width: 100%;_x000D_
  height: auto;_x000D_
}_x000D_
_x000D_
.overlay {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  bottom: 0;_x000D_
  left: 0;_x000D_
  right: 0;_x000D_
  height: 100%;_x000D_
  width: 100%;_x000D_
  opacity: 0;_x000D_
  transition: .5s ease;_x000D_
  background-color: #008CBA;_x000D_
}_x000D_
_x000D_
.container:hover .overlay {_x000D_
  opacity: 1;_x000D_
}_x000D_
_x000D_
.text {_x000D_
  color: white;_x000D_
  font-size: 20px;_x000D_
  position: absolute;_x000D_
  top: 50%;_x000D_
  left: 50%;_x000D_
  transform: translate(-50%, -50%);_x000D_
  -ms-transform: translate(-50%, -50%);_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head></head>_x000D_
<body>_x000D_
_x000D_
<div class="container">_x000D_
  <img src="http://lorempixel.com/500/500/" alt="Avatar" class="image">_x000D_
  <div class="overlay">_x000D_
    <div class="text">Hello World</div>_x000D_
  </div>_x000D_
</div>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Reference Link W3schools with multiple styles

WAMP error: Forbidden You don't have permission to access /phpmyadmin/ on this server

In my case a WAMP server was installed before on my pc, so when installing the new one some files not overwritten, all you have to do in that case is to go to the C:\ and delete the whole WAMP folder then install it again.

net::ERR_INSECURE_RESPONSE in Chrome

A missing intermediate certificate might be the problem.

You may want to check your https://hostname with curl, openssl or a website like https://www.digicert.com/help/.

No idea why Chrome (possibly) sometimes has problems validating these certs.

How can I debug javascript on Android?

Take a look at jsHybugger. It will allow you to remotely debug your js code for:

  • Android hybrid apps (webview, phonegap, worklight)
  • Web pages which runs in the default android browser (not Chrome, it supports the ADB extension without this tool)

How this works (more details and alternatives on the projects site, this was what I found to be the best way).

  1. Install the jsHybugger APK on your device
  2. Enable USB debugging on you device.
  3. Plug the Android device into your desktop computer via USB
  4. Run the app on the Android device ('jsHybugger')
  5. Enter the target URL and page in the app. Press Start Service and finally Open Browser
    • You'll be presented with a list of installed browsers, choose one.
    • The browser launches.
  6. Back on your desktop computer open Chrome to chrome://inspect/
  7. An inspectors window will appear with the chrome debugging tools linked to the page on the Android device.
  8. debug away!

Again, with Chrome on Android use the ADB extension without jsHybugger. I think this already described in the accepted answer to this question.

The following artifacts could not be resolved: javax.jms:jms:jar:1.1

I also faced the same issue when I started using following maven dependency version for log4j (1.2.15) in my project.

<dependency>
  <groupId>log4j</groupId>
  <artifactId>log4j</artifactId>
  <version>1.2.15</version>
</dependency>

Following error was thrown at me.

The following artifacts could not be resolved: javax.jms:jms:jar:1.1, com.sun.jdmk:jmxtools:jar:1.2.1, com.sun.jmx:jmxri:jar:1.2.1: Could not transfer artifact javax.jms:jms:jar:1.1 from/to java.net (https://maven-repository.dev.java.net/nonav/repository): Cannot access https://maven-repository.dev.java.net/nonav/repository with type legacy using the available connector factories: BasicRepositoryConnectorFactory: Cannot access https://maven-repository.dev.java.net/nonav/repository with type legacy using the available layout factories: Maven2RepositoryLayoutFactory: Unsupported repository layout legacy -> [Help 1]

I started using following log4j (1.2.17) version and it helped me solve this issue without any configurations related fixes.

 <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.17</version>
    </dependency>

RSpec: how to test if a method was called?

To fully comply with RSpec ~> 3.1 syntax and rubocop-rspec's default option for rule RSpec/MessageSpies, here's what you can do with spy:

Message expectations put an example's expectation at the start, before you've invoked the code-under-test. Many developers prefer using an arrange-act-assert (or given-when-then) pattern for structuring tests. Spies are an alternate type of test double that support this pattern by allowing you to expect that a message has been received after the fact, using have_received.

# arrange.
invitation = spy('invitation')

# act.
invitation.deliver("[email protected]")

# assert.
expect(invitation).to have_received(:deliver).with("[email protected]")

If you don't use rubocop-rspec or using non-default option. You may, of course, use RSpec 3 default with expect.

dbl = double("Some Collaborator")
expect(dbl).to receive(:foo).with("[email protected]")

How can I remove 3 characters at the end of a string in php?

<?php echo substr("abcabcabc", 0, -3); ?>

how do I get eclipse to use a different compiler version for Java?

First off, are you setting your desired JRE or your desired JDK?

Even if your Eclipse is set up properly, there might be a wacky project-specific setting somewhere. You can open up a context menu on a given Java project in the Project Explorer and select Properties > Java Compiler to check on that.

If none of that helps, leave a comment and I'll take another look.

Automatic Preferred Max Layout Width is not available on iOS versions prior to 8.0

To Find the problem label(s) in a large storyboard, follow my steps below.

  1. In xCode's Issue Navigator right click on the error and select "Reveal In Log". (Note: @Sam suggests below, look in xCode's report navigator. Also @Rivera notes in the comments that "As of Xcode 6.1.1, clicking on the warning will automatically open and highlight the conflicting label". I haven't tested this).

enter image description here

  1. This will show the error with a code at the end of your storyboard file. Copy the value after .storyboard

enter image description here

  1. Next, reveal your storyboard as source file. enter image description here

  2. Search. You should be able to tell what label it is from here quite easily by looking at the content. enter image description here

Once you find the label the solution that worked for me was to set the "preferred width" to 0.

enter image description here

BTW, you can always quickly get the id of an interface item by selecting the item and looking under the identify inspector. Very handy.

enter image description here

How can I combine hashes in Perl?

Quick Answer (TL;DR)


    %hash1 = (%hash1, %hash2)

    ## or else ...

    @hash1{keys %hash2} = values %hash2;

    ## or with references ...

    $hash_ref1 = { %$hash_ref1, %$hash_ref2 };

Overview

  • Context: Perl 5.x
  • Problem: The user wishes to merge two hashes1 into a single variable

Solution

  • use the syntax above for simple variables
  • use Hash::Merge for complex nested variables

Pitfalls

See also


Footnotes

1 * (aka associative-array, aka dictionary)

Disable copy constructor

You can make the copy constructor private and provide no implementation:

private:
    SymbolIndexer(const SymbolIndexer&);

Or in C++11, explicitly forbid it:

SymbolIndexer(const SymbolIndexer&) = delete;

How to define partitioning of DataFrame?

I was able to do this using RDD. But I don't know if this is an acceptable solution for you. Once you have the DF available as an RDD, you can apply repartitionAndSortWithinPartitions to perform custom repartitioning of data.

Here is a sample I used:

class DatePartitioner(partitions: Int) extends Partitioner {

  override def getPartition(key: Any): Int = {
    val start_time: Long = key.asInstanceOf[Long]
    Objects.hash(Array(start_time)) % partitions
  }

  override def numPartitions: Int = partitions
}

myRDD
  .repartitionAndSortWithinPartitions(new DatePartitioner(24))
  .map { v => v._2 }
  .toDF()
  .write.mode(SaveMode.Overwrite)

How to match all occurrences of a regex

Using scan should do the trick:

string.scan(/regex/)

How to prevent form resubmission when page is refreshed (F5 / CTRL+R)

This form.php sample shows how to use PRG correct (when form is valid or not).

  • It redirects to the same page, only when form is valid and action was performed.
  • Redirection protects form from being resubmitted on page refresh.
  • It uses session to not loose success messages you want to show when form is valid.
  • There are two buttons for testing: "Valid submit", "Invalid submit". Try both and refresh page after that.
<?php
session_start();

function doSelfRedirect()
{
  header('Location:'.$_SERVER['PHP_SELF']);
  exit;
}

function setFlashMessage($msg)
{
  $_SESSION['message'] = $msg;
}

function getFlashMessage()
{
  if (!empty($_SESSION['message'])) {
    $msg = $_SESSION['message'];
    unset($_SESSION['message']);
  } else {
    $msg = null;
  }

  return $msg;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  // Validation primitive example.
  if (empty($_POST['valid'])) {
    $formIsValid = false;
    setFlashMessage('Invalid form submit');
  } else {
    $formIsValid = true;
  }

  if ($formIsValid) {
    // Perform any actions here.
    // ...

    // Cool!
    setFlashMessage('Form is valid. Action performed.');

    // Prevent form resubmission.
    doSelfRedirect();
  }
}
?>
<h1>Hello form</h1>

<?php if ($msg = getFlashMessage()): ?>
  <div><?= $msg ?></div>
<?php endif; ?>

<form method="post">
  <input type="text" name="foo" value="bar"><br><br>
  <button type="submit" name="invalid" value="0">Invalid submit</button>
  <button type="submit" name="valid" value="1">Valid submit</button>
</form>

What is the Eclipse shortcut for "public static void main(String args[])"?

As bmargulies mentioned:

Preferences>Java>Editor>Templates>New...

enter image description here

enter image description here

Now, type psvm then Ctrl + Space on Mac or Windows.

ADB.exe is obsolete and has serious performance problems

17-01-2019

This works for me. Just opened Android SDK Manager Then it showed 4 Updates Available. So I just Updated it and No more above warning.

enter image description here

Run R script from command line

This does not answer the question directly. But someone may end up here because they want to run a oneliner of R from the terminal. For example, if you just want to install some missing packages and quit, this oneliner can be very convenient. I use it a lot when I suddenly find out that I miss some packages, and I want to install them to where I want.

  • To install to the default location:

    R -e 'install.packages(c("package1", "package2"))'
    
  • To install to a location that requires root privileges:

    R -e 'install.packages(c("package1", "package2"), lib="/usr/local/lib/R/site-library")' 
    

Hibernate HQL Query : How to set a Collection as a named parameter of a Query?

Use Query.setParameterList(), Javadoc here.

There are four variants to pick from.

Adding two Java 8 streams, or an extra element to a stream

If you add static imports for Stream.concat and Stream.of, the first example could be written as follows:

Stream<Foo> stream = concat(stream1, concat(stream2, of(element)));

Importing static methods with generic names can result in code that becomes difficult to read and maintain (namespace pollution). So, it might be better to create your own static methods with more meaningful names. However, for demonstration I will stick with this name.

public static <T> Stream<T> concat(Stream<? extends T> lhs, Stream<? extends T> rhs) {
    return Stream.concat(lhs, rhs);
}
public static <T> Stream<T> concat(Stream<? extends T> lhs, T rhs) {
    return Stream.concat(lhs, Stream.of(rhs));
}

With these two static methods (optionally in combination with static imports), the two examples could be written as follows:

Stream<Foo> stream = concat(stream1, concat(stream2, element));

Stream<Foo> stream = concat(
                         concat(stream1.filter(x -> x!=0), stream2).filter(x -> x!=1),
                         element)
                     .filter(x -> x!=2);

The code is now significantly shorter. However, I agree that the readability hasn't improved. So I have another solution.


In a lot of situations, Collectors can be used to extend the functionality of streams. With the two Collectors at the bottom, the two examples could be written as follows:

Stream<Foo> stream = stream1.collect(concat(stream2)).collect(concat(element));

Stream<Foo> stream = stream1
                     .filter(x -> x!=0)
                     .collect(concat(stream2))
                     .filter(x -> x!=1)
                     .collect(concat(element))
                     .filter(x -> x!=2);

The only difference between your desired syntax and the syntax above is, that you have to replace concat(...) with collect(concat(...)). The two static methods can be implemented as follows (optionally used in combination with static imports):

private static <T,A,R,S> Collector<T,?,S> combine(Collector<T,A,R> collector, Function<? super R, ? extends S> function) {
    return Collector.of(
        collector.supplier(),
        collector.accumulator(),
        collector.combiner(),
        collector.finisher().andThen(function));
}
public static <T> Collector<T,?,Stream<T>> concat(Stream<? extends T> other) {
    return combine(Collectors.toList(),
        list -> Stream.concat(list.stream(), other));
}
public static <T> Collector<T,?,Stream<T>> concat(T element) {
    return concat(Stream.of(element));
}

Of course there is a drawback with this solution that should be mentioned. collect is a final operation that consumes all elements of the stream. On top of that, the collector concat creates an intermediate ArrayList each time it is used in the chain. Both operations can have a significant impact on the behaviour of your program. However, if readability is more important than performance, it might still be a very helpful approach.

System.Data.SqlClient.SqlException: Login failed for user

I just ran into this error and it took days to resolve. We were thrown for a loop by the red-herring error message mentioned in the initial question, plus the Windows Event Viewer error log indicated something similar:

Login failed for user '(domain\name-PC)$'. Reason: Could not find a login matching the name provided. [CLIENT: <local machine>]

Neither of these was true, the user had all the necessary permissions in SQL Server.

In our case, the solution was to switch the Application Pool Identity in IIS to NetworkService.

Valid content-type for XML, HTML and XHTML documents

HTML: text/html, full-stop.

XHTML: application/xhtml+xml, or only if following HTML compatbility guidelines, text/html. See the W3 Media Types Note.

XML: text/xml, application/xml (RFC 2376).

There are also many other media types based around XML, for example application/rss+xml or image/svg+xml. It's a safe bet that any unrecognised but registered ending in +xml is XML-based. See the IANA list for registered media types ending in +xml.

(For unregistered x- types, all bets are off, but you'd hope +xml would be respected.)

Error message "unreported exception java.io.IOException; must be caught or declared to be thrown"

Your method showFile() declares that it can throw an IOException. Since this is a checked exception, any call to showFile() method must handle the exception somehow. One option is to wrap the call to showFile() in a try-catch block.

 try {
     showFile();
 }
 catch(IOException e) {
    // Code to handle an IOException here
 }

Yes/No message box using QMessageBox

If you want to make it in python you need check this code in your workbench. also write like this. we created a popup box with python.

msgBox = QMessageBox()
msgBox.setText("The document has been modified.")
msgBox.setInformativeText("Do you want to save your changes?")
msgBox.setStandardButtons(QMessageBox.Save | QMessageBox.Discard | QMessageBox.Cancel)
msgBox.setDefaultButton(QMessageBox.Save)
ret = msgBox.exec_()

How to use Jackson to deserialise an array of objects

For Generic Implementation:

public static <T> List<T> parseJsonArray(String json,
                                         Class<T> classOnWhichArrayIsDefined) 
                                         throws IOException, ClassNotFoundException {
   ObjectMapper mapper = new ObjectMapper();
   Class<T[]> arrayClass = (Class<T[]>) Class.forName("[L" + classOnWhichArrayIsDefined.getName() + ";");
   T[] objects = mapper.readValue(json, arrayClass);
   return Arrays.asList(objects);
}

Command copy exited with code 4 when building - Visual Studio restart solves it

If you are here because your project fails to build on a build server, but builds fine "manually" on a dev machine, and you are doing xcopy only for debugging and to emulate a production environment on a dev machine, then you may want to look at this solution:

https://stackoverflow.com/a/1732478/2279059

You simply turn off post build events on the build server using

msbuild foo.sln /p:PostBuildEvent=

This is not good enough if you have other post build events that also need to run on the build server, and it is not a general solution. However, since there are so many different causes of this problem, there cannot be a general solution. One of the many answers to this question (and its duplicates) will probably help, but be careful with approaches that only somehow circumvent error handling (such as xcopy /C). Those may work for you, particularly also in the build server scenario, but I think this one is more reliable, IF it can be used.

It has also been suggested that with newer versions of Visual Studio, the problem no longer exists, so if you are using an old version, consider updating your build tools.

"The breakpoint will not currently be hit. The source code is different from the original version." What does this mean?

In my case I forgot to include the "stdafx.h" in the header file where I was declaring a template function.

The type initializer for 'Oracle.DataAccess.Client.OracleConnection' threw an exception

This is an old, but still relevant question, and while the answers here are helpful no one answer fully addressed both of the OP's questions.

1. Do I have to install ODP.NET and Oracle client on the computer that I want to run my application?

YES - if you are using ODP.NET, Unmanaged. This is the version that you typically install when you choose "Oracle Data Provider for .NET" in the Oracle Client installer (for example). You Download this from Oracle (just google it: Oracle URLs change often).

But If you are using ODP.NET, Managed (and you probably want to use this one this instead) then No, you only need to install (or deploy) ODP.NET, Managed with the app, not the full Oracle Client. See below for details.

2. If yes, is there other way that I don't have to install them but still can run my application?

Yes, there is at least one way. And it is the Managed port of ODP.NET.

Unfortunately the usual workarounds, including ODBC, Microsoft's Oracle Provider for .NET (yes, that old, deprecated one), and the ODP.NET, Unmanaged DLL all require the Oracle client to be installed. It wasn't until our friends at Oracle gave us a nice little (~5MB) DLL that is also Managed. This means no more having to depoy 32-bit and 64-bit versions to go with 32-bit and 64-bit Oracle clients! And no more issues with assembly binding where you build against 10.0.2.1 (or whatever) but your customers install a range of clients from 9i all the way to 12c, including the 'g' ones in the middle) because you can just ship it with your app, and manage it via nuget.

But if you use ODP.NET, Managed which is available as a nuget package, then you do not need to install the Oracle Client. You only need the ODP.NET, Managed DLL. And if you were previously using the ODP.NET, Unmanaged DLL, it is very easy to switch: simply change all your references to the Managed ODP.NET (.csproj files in csharp, etc.), and then change any using statements, for example: using Oracle.DataAccess.Client becomes using Oracle.ManagedDataAccess.Client and that's it! (Unless you were supposedly using some of the more advanced DB management features in the full client that are exposed in the ODP.NET, Unmanaged, which I have not done myself, so good luck with that..). And also nuke all of those annoying assemblyBindingRedirect nodes from your app.config/web.config files and never sweat that junk again!

References:

Troubleshooting:

That error typically means ODP.NET was found OK, but Oracle client was not found or not installed. This could also occur when the architecture doesn't match (32-bit Oracle client is installed, but trying to use 64-bit Unmanaged ODP.NET, or vice versa). This can also happen due to permissions issues and path issues and other problems with the app domain (your web app or your EXE or whatever) not being able to find the Oracle DLLs to actually communicate with Oracle over the network (the ODP.NET Unmanaged DLLs are basically just wrappers for this that hook into ADO and stuff).

Common solutions I have found to this problem:

App is 64-bit?

  • Install 64-bit Oracle Client (32-bit one wont work)

App is 32-bit?

  • Install 32-bit Oracle Client (64-bit one wont work)

Oracle Client is already installed for the correct architecture?

  • Verify your environment PATH and ORACLE_HOME variables, make sure Oracle can be found (newer versions may use Registry instead)
  • Verify the ORACLE_HOME and settings in the Registry (And remember: Registry is either 32-bit or 64-bit, so make sure you check the one that matches your app!)
  • Verify permissions on the ORACLE_HOME folder. If you don't know where this is, check the Registry. I have seen cases where ASP.NET app worker process was using Network Service user and for some reason installing 32-bit and 64-bit clients side by side resulted in the permissions being removed from the first client for the Authorized Users group.. fixing perms on the home folder fixed this.
  • As always, it is handy to Use SysInternals Process Monitor to find out what file is missing or can't be read.

remove borders around html input

In my case I am using a CSS framework which adds box-shadow, so I had to also add

box-shadow: none;

So the complete snippet is:

border: none; 
border-width: 0; 
box-shadow: none;

How can I do an OrderBy with a dynamic string parameter?

The simplest & the best solution:

mylist.OrderBy(s => s.GetType().GetProperty("PropertyName").GetValue(s));

WAMP 403 Forbidden message on Windows 7

make sure that, the name of the file in the directory c:/wamp/apps/phpmyadmin3.1.3.1/, match the name (or version) in the phpMyAdmin.conf (Alias /phpmyadmin "c:/wamp/apps/phpmyadmin3.1.3.1/" )

Using jQuery to test if an input has focus

There is no :focus, but there is :selected http://docs.jquery.com/Selectors/selected

but if you want to change how things look based on what is selected you should probably be working with the blur events.

http://docs.jquery.com/Events/blur

How can I convert a string to a float in mysql?

mysql> SELECT CAST(4 AS DECIMAL(4,3));
+-------------------------+
| CAST(4 AS DECIMAL(4,3)) |
+-------------------------+
|                   4.000 |
+-------------------------+
1 row in set (0.00 sec)

mysql> SELECT CAST('4.5s' AS DECIMAL(4,3));
+------------------------------+
| CAST('4.5s' AS DECIMAL(4,3)) |
+------------------------------+
|                        4.500 |
+------------------------------+
1 row in set (0.00 sec)

mysql> SELECT CAST('a4.5s' AS DECIMAL(4,3));
+-------------------------------+
| CAST('a4.5s' AS DECIMAL(4,3)) |
+-------------------------------+
|                         0.000 |
+-------------------------------+
1 row in set, 1 warning (0.00 sec)

Makefile - missing separator

You need to precede the lines starting with gcc and rm with a hard tab. Commands in make rules are required to start with a tab (unless they follow a semicolon on the same line). The result should look like this:

PROG = semsearch
all: $(PROG)
%: %.c
        gcc -o $@ $< -lpthread

clean:
        rm $(PROG)

Note that some editors may be configured to insert a sequence of spaces instead of a hard tab. If there are spaces at the start of these lines you'll also see the "missing separator" error. If you do have problems inserting hard tabs, use the semicolon way:

PROG = semsearch
all: $(PROG)
%: %.c ; gcc -o $@ $< -lpthread

clean: ; rm $(PROG)

nvarchar(max) vs NText

The biggest disadvantage of Text (together with NText and Image) is that it will be removed in a future version of SQL Server, as by the documentation. That will effectively make your schema harder to upgrade when that version of SQL Server will be released.

Javascript regular expression password validation having special characters

If you check the length seperately, you can do the following:

var regularExpression  = /^[a-zA-Z]$/;

if (regularExpression.test(newPassword)) {
    alert("password should contain atleast one number and one special character");
    return false;
} 

How to show the "Are you sure you want to navigate away from this page?" when changes committed?

To expand on Keith's already amazing answer:

Custom warning messages

To allow custom warning messages, you can wrap it in a function like this:

function preventNavigation(message) {
    var confirmOnPageExit = function (e) {
        // If we haven't been passed the event get the window.event
        e = e || window.event;

        // For IE6-8 and Firefox prior to version 4
        if (e)
        {
            e.returnValue = message;
        }

        // For Chrome, Safari, IE8+ and Opera 12+
        return message;
    };
    window.onbeforeunload = confirmOnPageExit;
}

Then just call that function with your custom message:

preventNavigation("Baby, please don't go!!!");

Enabling navigation again

To re-enable navigation, all you need to do is set window.onbeforeunload to null. Here it is, wrapped in a neat little function that can be called anywhere:

function enableNavigation() {
    window.onbeforeunload = null;
}

Using jQuery to bind this to form elements

If using jQuery, this can easily be bound to all of the elements of a form like this:

$("#yourForm :input").change(function() {
    preventNavigation("You have not saved the form. Any \
        changes will be lost if you leave this page.");
});

Then to allow the form to be submitted:

$("#yourForm").on("submit", function(event) {
    enableNavigation();
});

Dynamically-modified forms:

preventNavigation() and enableNavigation() can be bound to any other functions as needed, such as dynamically modifying a form, or clicking on a button that sends an AJAX request. I did this by adding a hidden input element to the form:

<input id="dummy_input" type="hidden" />

Then any time I want to prevent the user from navigating away, I trigger the change on that input to make sure that preventNavigation() gets executed:

function somethingThatModifiesAFormDynamically() {

    // Do something that modifies a form

    // ...
    $("#dummy_input").trigger("change");
    // ...
}

Is it safe to use Project Lombok?

Just started using Lombok today. So far I like it, but one drawback I didn't see mentioned was refactoring support.

If you have a class annotated with @Data, it will generate the getters and setters for you based on the field names. If you use one of those getters in another class, then decide the field is poorly named, it will not find usages of those getters and setters and replace the old name with the new name.

I would imagine this would have to be done via an IDE plug-in and not via Lombok.

UPDATE (Jan 22 '13)
After using Lombok for 3 months, I still recommend it for most projects. I did, however, find another drawback that is similar to the one listed above.

If you have a class, say MyCompoundObject.java that has 2 members, both annotated with @Delegate, say myWidgets and myGadgets, when you call myCompoundObject.getThingies() from another class, it's impossible to know if it's delegating to the Widget or Gadget because you can no longer jump to source within the IDE.

Using the Eclipse "Generate Delegate Methods..." provides you with the same functionality, is just as quick and provides source jumping. The downside is it clutters your source with boilerplate code that take the focus off the important stuff.

UPDATE 2 (Feb 26 '13)
After 5 months, we're still using Lombok, but I have some other annoyances. The lack of a declared getter & setter can get annoying at times when you are trying to familiarize yourself with new code.

For example, if I see a method called getDynamicCols() but I don't know what it's about, I have some extra hurdles to jump to determine the purpose of this method. Some of the hurdles are Lombok, some are the lack of a Lombok smart plugin. Hurdles include:

  • Lack of JavaDocs. If I javadoc the field, I would hope the getter and setter would inherit that javadoc through the Lombok compilation step.
  • Jump to method definition jumps me to the class, but not the property that generated the getter. This is a plugin issue.
  • Obviously you are not able to set a breakpoint in a getter/setter unless you generate or code the method.
  • NOTE: This Reference Search is not an issue as I first thought it was. You do need to be using a perspective that enables the Outline view though. Not a problem for most developers. My problem was I am using Mylyn which was filtering my Outline view, so I didn't see the methods. Lack of References search. If I want to see who's calling getDynamicCols(args...), I have to generate or code the setter to be able to search for references.

UPDATE 3 (Mar 7 '13)
Learning to use the various ways of doing things in Eclipse I guess. You can actually set a conditional breakpoint (BP) on a Lombok generated method. Using the Outline view, you can right-click the method to Toggle Method Breakpoint. Then when you hit the BP, you can use the debugging Variables view to see what the generated method named the parameters (usually the same as the field name) and finally, use the Breakpoints view to right-click the BP and select Breakpoint Properties... to add a condition. Nice.

UPDATE 4 (Aug 16 '13)
Netbeans doesn't like it when you update your Lombok dependencies in your Maven pom. The project still compiles, but files get flagged for having compilation errors because it can't see the methods Lombok is creating. Clearing the Netbeans cache resolves the issue. Not sure if there is a "Clean Project" option like there is in Eclipse. Minor issue, but wanted to make it known.

UPDATE 5 (Jan 17 '14)
Lombok doesn't always play nice with Groovy, or at least the groovy-eclipse-compiler. You might have to downgrade your version of the compiler. Maven Groovy and Java + Lombok

UPDATE 6 (Jun 26 '14)
A word of warning. Lombok is slightly addictive and if you work on a project where you can't use it for some reason, it will annoy the piss out of you. You may be better off just never using it at all.

UPDATE 7 (Jul 23 '14)
This is a bit of an interesting update because it directly addresses the safety of adopting Lombok that the OP asked about.

As of v1.14, the @Delegate annotation has been demoted to an Experimental status. The details are documented on their site (Lombok Delegate Docs).

The thing is, if you were using this feature, your backout options are limited. I see the options as:

  • Manually remove @Delegate annotations and generate/handcode the delegate code. This is a little harder if you were using attributes within the annotation.
  • Delombok the files that have the @Delegate annotation and maybe add back in the annotations that you do want.
  • Never update Lombok or maintain a fork (or live with using experiential features).
  • Delombok your entire project and stop using Lombok.

As far as I can tell, Delombok doesn't have an option to remove a subset of annotations; it's all or nothing at least for the context of a single file. I opened a ticket to request this feature with Delombok flags, but I wouldn't expect that in the near future.

UPDATE 8 (Oct 20 '14)
If it's an option for you, Groovy offers most of the same benefits of Lombok, plus a boat load of other features, including @Delegate. If you think you'll have a hard time selling the idea to the powers that be, take a look at the @CompileStatic or @TypeChecked annotation to see if that can help your cause. In fact, the primary focus of the Groovy 2.0 release was static safety.

UPDATE 9 (Sep 1 '15)
Lombok is still being actively maintained and enhanced, which bodes well to the safety level of adoption. The @Builder annotations is one of my favorite new features.

UPDATE 10 (Nov 17 '15)
This may not seem directly related to the OP's question, but worth sharing. If you're looking for tools to help you reduce the amount of boilerplate code you write, you can also check out Google Auto - in particular AutoValue. If you look at their slide deck, the list Lombok as a possible solution to the problem they are trying to solve. The cons they list for Lombok are:

  • The inserted code is invisible (you can't "see" the the methods it generates) [ed note - actually you can, but it just requires a decompiler]
  • The compiler hacks are non-standard and fragile
  • "In our view, your code is no longer really Java"

I'm not sure how much I agree with their evaluation. And given the cons of AutoValue that are documented in the slides, I'll be sticking with Lombok (if Groovy is not an option).

UPDATE 11 (Feb 8 '16)
I found out Spring Roo has some similar annotations. I was a little surprised to find out Roo is still a thing and finding documentation for the annotations is a bit rough. Removal also doesn't look as easy as de-lombok. Lombok seems like the safer choice.

UPDATE 12 (Feb 17 '16)
While trying to come up with justifications for why it's safe to bring in Lombok for the project I'm currently working on, I found a piece of gold that was added with v1.14 - The Configuration System! This is means you can configure a project to dis-allow certain features that your team deems unsafe or undesirable. Better yet, it can also create directory specific config with different settings. This is AWESOME.

UPDATE 13 (Oct 4 '16)
If this kind of thing matters to you, Oliver Gierke felt it was safe to add Lombok to Spring Data Rest.

UPDATE 14 (Sep 26 '17)
As pointed out by @gavenkoa in the comments on the OPs question, JDK9 compiler support isn't yet available (Issue #985). It also sounds like it's not going to be an easy fix for the Lombok team to get around.

UPDATE 15 (Mar 26 '18)
The Lombok changelog indicates as of v1.16.20 "Compiling lombok on JDK1.9 is now possible" even though #985 is still open.

Changes to accommodate JDK9, however, necessitated some breaking changes; all isolated to changes in config defaults. It's a little concerning that they introduced breaking changes, but the version only bumped the "Incremental" version number (going from v1.16.18 to v1.16.20). Since this post was about the safety, if you had a yarn/npm like build system that automatically upgraded to the latest incremental version, you might be in for a rude awakening.

UPDATE 16 (Jan 9 '19)

It seems the JDK9 issues have been resolved and Lombok works with JDK10, and even JDK11 as far as I can tell.

One thing I noticed though that was concerning from a safety aspect is the fact that the change log going from v1.18.2 to v1.18.4 lists two items as BREAKING CHANGE!? I'm not sure how a breaking change happens in a semver "patch" update. Could be an issue if you use a tool that auto-updates patch versions.

Find the day of a week

Use the lubridate package and function wday:

library(lubridate)
df$date <- as.Date(df$date)
wday(df$date, label=TRUE)
[1] Wed   Wed   Thurs
Levels: Sun < Mon < Tues < Wed < Thurs < Fri < Sat

SVN upgrade working copy

If you're getting this error from Netbeans (7.2+) then it means that your separately installed version of Subversion is higher than the version in netbeans. In my case Netbeans (v7.3.1) had SVN v1.7 and I'd just upgraded my SVN to v1.8.

If you look in Tools > Options > Miscellaneous (tab) > Versioning (tab) > Subversion (pane), set the Preferred Client = CLI, then you can set the path the the installed SVN which for me was C:\Program Files\TortoiseSVN\bin.

More can be found on the Netbeans Subversion Clients FAQ.

Can I position an element fixed relative to parent?

With multiple divs I managed to get a fixed-y and absolute-x divs. In my case I needed a div on left and right sides, aligned to a centered 1180px width div.

    <div class="parentdiv" style="
        background: transparent;
        margin: auto;
        width: 100%;
        max-width: 1220px;
        height: 10px;
        text-align: center;">
        <div style="
            position: fixed;
            width: 100%;
            max-width: 1220px;">
            <div style="
                position: absolute;
                background: black;
                height: 20px;
                width: 20px;
                left: 0;">
            </div>
            <div style="
                width: 20px;
                height: 20px;
                background: blue;
                position: absolute;                                           
                right: 0;">
            </div>
        </div>
    </div>

How do I center this form in css?

Normally, if you look up any software issue on stackoverflow, you quickly find a clear answer. But in CSS, even something as simple as "center a form" leads to a long discussion, and lots of failed solutions.

Correction: orfdorf's solution (above) works.

CSS: center element within a <div> element

Set text-align:center; to the parent div, and margin:auto; to the child div.

_x000D_
_x000D_
#parent {_x000D_
    text-align:center;_x000D_
    background-color:blue;_x000D_
    height:400px;_x000D_
    width:600px;_x000D_
}_x000D_
.block {_x000D_
    height:100px;_x000D_
    width:200px;_x000D_
    text-align:left;_x000D_
}_x000D_
.center {_x000D_
    margin:auto;_x000D_
    background-color:green;_x000D_
}_x000D_
.left {_x000D_
    margin:auto auto auto 0;_x000D_
    background-color:red;_x000D_
}_x000D_
.right {_x000D_
    margin:auto 0 auto auto;_x000D_
    background-color:yellow;_x000D_
}
_x000D_
<div id="parent">_x000D_
    <div id="child1" class="block center">_x000D_
        a block to align center and with text aligned left_x000D_
    </div>_x000D_
    <div id="child2" class="block left">_x000D_
        a block to align left and with text aligned left_x000D_
    </div>_x000D_
    <div id="child3" class="block right">_x000D_
        a block to align right and with text aligned left_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

This a good resource to center mostly anything.
http://howtocenterincss.com/

Find rows that have the same value on a column in MySQL

I know this is a very old question but this is more for someone else who might have the same problem and I think this is more accurate to what was wanted.

SELECT * FROM member WHERE email = (Select email From member Where login_id = [email protected]) 

This will return all records that have [email protected] as a login_id value.

How to open remote files in sublime text 3

Base on this.

Step by step:

  • On your local workstation: On Sublime Text 3, open Package Manager (Ctrl-Shift-P on Linux/Win, Cmd-Shift-P on Mac, Install Package), and search for rsub
  • On your local workstation: Add RemoteForward 52698 127.0.0.1:52698 to your .ssh/config file, or -R 52698:localhost:52698 if you prefer command line
  • On your remote server:

    sudo wget -O /usr/local/bin/rsub https://raw.github.com/aurora/rmate/master/rmate
    sudo chmod a+x /usr/local/bin/rsub
    

Just keep your ST3 editor open, and you can easily edit remote files with

rsub myfile.txt

EDIT: if you get "no such file or directory", it's because your /usr/local/bin is not in your PATH. Just add the directory to your path:

echo "export PATH=\"$PATH:/usr/local/bin\"" >> $HOME/.bashrc

Now just log off, log back in, and you'll be all set.

How to discard local changes and pull latest from GitHub repository

If you already committed the changes than you would have to revert changes.

If you didn't commit yet, just do a clean checkout git checkout .

How can I use the apply() function for a single column?

Let me try a complex computation using datetime and considering nulls or empty spaces. I am reducing 30 years on a datetime column and using apply method as well as lambda and converting datetime format. Line if x != '' else x will take care of all empty spaces or nulls accordingly.

df['Date'] = df['Date'].fillna('')
df['Date'] = df['Date'].apply(lambda x : ((datetime.datetime.strptime(str(x), '%m/%d/%Y') - datetime.timedelta(days=30*365)).strftime('%Y%m%d')) if x != '' else x)

"Unicode Error "unicodeescape" codec can't decode bytes... Cannot open text files in Python 3

With Python 3 I had this problem:

 self.path = 'T:\PythonScripts\Projects\Utilities'

produced this error:

 self.path = 'T:\PythonScripts\Projects\Utilities'
            ^
 SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in
 position 25-26: truncated \UXXXXXXXX escape

the fix that worked is:

 self.path = r'T:\PythonScripts\Projects\Utilities'

It seems the '\U' was producing an error and the 'r' preceding the string turns off the eight-character Unicode escape (for a raw string) which was failing. (This is a bit of an over-simplification, but it works if you don't care about unicode)

Hope this helps someone

How do you append to an already existing string?

$ string="test"
$ string="${string}test2"
$ echo $string
testtest2

Parallel foreach with asynchronous lambda

In the accepted answer the ConcurrentBag is not required. Here's an implementation without it:

var tasks = myCollection.Select(GetData).ToList();
await Task.WhenAll(tasks);
var results = tasks.Select(t => t.Result);

Any of the "// some pre stuff" and "// some post stuff" can go into the GetData implementation (or another method that calls GetData)

Aside from being shorter, there's no use of an "async void" lambda, which is an anti pattern.

ssh server connect to host xxx port 22: Connection timed out on linux-ubuntu

If you are on Public Network, Firewall will block all incoming connections by default. check your firewall settings or use private network to SSL

How to load GIF image in Swift?

This is working for me

Podfile:

platform :ios, '9.0'
use_frameworks!

target '<Your Target Name>' do
pod 'SwiftGifOrigin', '~> 1.7.0'
end

Usage:

// An animated UIImage
let jeremyGif = UIImage.gif(name: "jeremy")

// A UIImageView with async loading
let imageView = UIImageView()
imageView.loadGif(name: "jeremy")

// A UIImageView with async loading from asset catalog(from iOS9)
let imageView = UIImageView()
imageView.loadGif(asset: "jeremy")

For more information follow this link: https://github.com/swiftgif/SwiftGif

Create a <ul> and fill it based on a passed array

What are disadvantages of the following solution? Seems to be faster and shorter.

var options = {
    set0: ['Option 1','Option 2'],
    set1: ['First Option','Second Option','Third Option']
};

var list = "<li>" + options.set0.join("</li><li>") + "</li>";
document.getElementById("list").innerHTML = list;

Object creation on the stack/heap?

A)

Object* o;
o = new Object();

`` B)

Object* o = new Object();

I think A and B has no difference. In both the cases o is a pointer to class Object. statement new Object() creates an object of class Object from heap memory. Assignment statement assigns the address of allocated memory to pointer o.

One thing I would like to mention that size of allocated memory from heap is always the sizeof(Object) not sizeof(Object) + sizeof(void *).

How to autowire RestTemplate using annotations

Add the @Configuration annotation in the RestTemplateSOMENAME which extends the RestTemplate class.

@Configuration         
public class RestTemplateClass extends RestTemplate {

}

Then in your controller class you can use the Autowired annotation as follows.

@Autowired   
RestTemplateClass restTemplate;

HTML image not showing in Gmail

I noticed that Google was stripping the src attribute from my img tags. I tried every answer on this page - with no luck.

What finally worked for me was replacing img tags with divs that have background images. For example, instead of:

_x000D_
_x000D_
<img style="height: 24px; width: 24px; display: block;" src="IMAGE SOURCE"/>
_x000D_
_x000D_
_x000D_

I replaced it with:

_x000D_
_x000D_
<div style="height: 24px; width: 24px; display: block; background: url(IMAGE SOURCE); background-size: contain;"></div>
_x000D_
_x000D_
_x000D_

Hope this helps others who spent way too long pulling their hair out over this.

How can I get the current stack trace in Java?

You can use Thread.currentThread().getStackTrace().

That returns an array of StackTraceElements that represent the current stack trace of a program.

How can I undo git reset --hard HEAD~1?

git reflog and back to the last HEAD 6a56624 (HEAD -> master) HEAD@{0}: reset: moving to HEAD~3 1a9bf73 HEAD@{1}: commit: add changes in model generate binary

Change WPF controls from a non-main thread using Dispatcher.Invoke

The first thing is to understand that, the Dispatcher is not designed to run long blocking operation (such as retrieving data from a WebServer...). You can use the Dispatcher when you want to run an operation that will be executed on the UI thread (such as updating the value of a progress bar).

What you can do is to retrieve your data in a background worker and use the ReportProgress method to propagate changes in the UI thread.

If you really need to use the Dispatcher directly, it's pretty simple:

Application.Current.Dispatcher.BeginInvoke(
  DispatcherPriority.Background,
  new Action(() => this.progressBar.Value = 50));

How to move or copy files listed by 'find' command in unix?

Adding to Eric Jablow's answer, here is a possible solution (it worked for me - linux mint 14 /nadia)

find /path/to/search/ -type f -name "glob-to-find-files" | xargs cp -t /target/path/

You can refer to "How can I use xargs to copy files that have spaces and quotes in their names?" as well.

How to add directory to classpath in an application run profile in IntelliJ IDEA?

It appears that IntelliJ 11 has changed the method, and the checked answer no longer works for me. In case anyone else arrives here via a search engine, here's how I solved it in IntelliJ 11:

  1. Go to the Project Structure, click on Modules, and click on your Module
  2. Choose the "Dependencies" tab
  3. Click the "+" button on the right-hand side and select "Jars or directories..."
  4. Add the directory(ies) you want (note you can multi-select) and click OK
  5. In the dialog that comes up, select "classes" and NOT "jar directory"
  6. Make sure you're using that Module in your run target

Note that step 5 seems to be the key difference. If you select "jar directory" it will look exactly the same in the IDE but won't include the path at runtime. There appears to be no way to determine whether you've previously selected "classes" or "jar directory" after the fact.

Defining TypeScript callback type

If you want a generic function you can use the following. Although it doesn't seem to be documented anywhere.

class CallbackTest {
  myCallback: Function;
}   

Video auto play is not working in Safari and Chrome desktop browser

This is because of now chrome is preventing auto play in html5 video, so by default they will not allow auto play. so we can change this settings using chrome flag settings. this is not possible for normal case so i have find another solution. this is working perfect... (add preload="auto")

<video autoplay preload="auto" loop="loop" muted="muted" id="videoBanner" class="videoBanner">
<source src="banner-video.webm" type="video/webm">
<source src="banner-video.mp4" type="video/mp4">
<source src="banner-video.ogg" type="video/ogg">

var herovide = document.getElementById('videoBanner');
       herovide.autoplay=true;
       herovide.load();  

Access Session attribute on jstl

You should definitely avoid using <jsp:...> tags. They're relics from the past and should always be avoided now.

Use the JSTL.

Now, wether you use the JSTL or any other tag library, accessing to a bean property needs your bean to have this property. A property is not a private instance variable. It's an information accessible via a public getter (and setter, if the property is writable). To access the questionPaperID property, you thus need to have a

public SomeType getQuestionPaperID() {
    //...
}

method in your bean.

Once you have that, you can display the value of this property using this code :

<c:out value="${Questions.questionPaperID}" />

or, to specifically target the session scoped attributes (in case of conflicts between scopes) :

<c:out value="${sessionScope.Questions.questionPaperID}" />

Finally, I encourage you to name scope attributes as Java variables : starting with a lowercase letter.

Bootstrap Accordion button toggle "data-parent" not working

Here is a (hopefully) universal patch I developed to fix this problem for BootStrap V3. No special requirements other than plugging in the script.

$(':not(.panel) > [data-toggle="collapse"][data-parent]').click(function() {
    var parent = $(this).data('parent');
    var items = $('[data-toggle="collapse"][data-parent="' + parent + '"]').not(this);
    items.each(function() {
        var target = $(this).data('target') || '#' + $(this).prop('href').split('#')[1];
        $(target).filter('.in').collapse('hide');
    });
});

EDIT: Below is a simplified answer which still meets my needs, and I'm now using a delegated click handler:

$(document.body).on('click', ':not(.panel) > [data-toggle="collapse"][data-parent]', function() {
    var parent = $(this).data('parent');
    var target = $(this).data('target') || $(this).prop('hash');
    $(parent).find('.collapse.in').not(target).collapse('hide');
});

How to create a file in Linux from terminal window?

Depending on what you want the file to contain:

  • touch /path/to/file for an empty file
  • somecommand > /path/to/file for a file containing the output of some command.

      eg: grep --help > randomtext.txt
          echo "This is some text" > randomtext.txt
    
  • nano /path/to/file or vi /path/to/file (or any other editor emacs,gedit etc)
    It either opens the existing one for editing or creates & opens the empty file to enter, if it doesn't exist


Create the file using cat

$ cat > myfile.txt

Now, just type whatever you want in the file:

Hello World!

CTRL-D to save and exit


There are several possible solutions:

Create an empty file

touch file

>file

echo -n > file

printf '' > file

The echo version will work only if your version of echo supports the -n switch to suppress newlines. This is a non-standard addition. The other examples will all work in a POSIX shell.

Create a file containing a newline and nothing else

echo '' > file

printf '\n' > file

This is a valid "text file" because it ends in a newline.

Write text into a file

"$EDITOR" file

echo 'text' > file

cat > file <<END \
text
END

printf 'text\n' > file

These are equivalent. The $EDITOR command assumes that you have an interactive text editor defined in the EDITOR environment variable and that you interactively enter equivalent text. The cat version presumes a literal newline after the \ and after each other line. Other than that these will all work in a POSIX shell.

Of course there are many other methods of writing and creating files, too.

Delete all data in SQL Server database

As an alternative answer, if you Visual Studio SSDT or possibly Red Gate Sql Compare, you could simply run a schema comparison, script it out, drop the old database (possibly make a backup first in case there would be a reason that you will need that data), and then create a new database with the script created by the comparison tool. While on a very small database this may be more work, on a very large database it will be much quicker to simply drop the database then to deal with the different triggers and constraints that may be on the database.

How to remove whitespace from a string in typescript?

Trim just removes the trailing and leading whitespace. Use .replace(/ /g, "") if there are just spaces to be replaced.

this.maintabinfo = this.inner_view_data.replace(/ /g, "").toLowerCase();

What function is to replace a substring from a string in C?

// Here is the code for unicode strings!


int mystrstr(wchar_t *txt1,wchar_t *txt2)
{
    wchar_t *posstr=wcsstr(txt1,txt2);
    if(posstr!=NULL)
    {
        return (posstr-txt1);
    }else
    {
        return -1;
    }
}

// assume: supplied buff is enough to hold generated text
void StringReplace(wchar_t *buff,wchar_t *txt1,wchar_t *txt2)
{
    wchar_t *tmp;
    wchar_t *nextStr;
    int pos;

    tmp=wcsdup(buff);

    pos=mystrstr(tmp,txt1);
    if(pos!=-1)
    {
        buff[0]=0;
        wcsncpy(buff,tmp,pos);
        buff[pos]=0;

        wcscat(buff,txt2);

        nextStr=tmp+pos+wcslen(txt1);

        while(wcslen(nextStr)!=0)
        {
            pos=mystrstr(nextStr,txt1);

            if(pos==-1)
            {
                wcscat(buff,nextStr);
                break;
            }

            wcsncat(buff,nextStr,pos);
            wcscat(buff,txt2);

            nextStr=nextStr+pos+wcslen(txt1);   
        }
    }

    free(tmp);
}

Java - How to create a custom dialog box?

If you don't need much in the way of custom behavior, JOptionPane is a good time saver. It takes care of the placement and localization of OK / Cancel options, and is a quick-and-dirty way to show a custom dialog without needing to define your own classes. Most of the time the "message" parameter in JOptionPane is a String, but you can pass in a JComponent or array of JComponents as well.

Example:

JTextField firstName = new JTextField();
JTextField lastName = new JTextField();
JPasswordField password = new JPasswordField();
final JComponent[] inputs = new JComponent[] {
        new JLabel("First"),
        firstName,
        new JLabel("Last"),
        lastName,
        new JLabel("Password"),
        password
};
int result = JOptionPane.showConfirmDialog(null, inputs, "My custom dialog", JOptionPane.PLAIN_MESSAGE);
if (result == JOptionPane.OK_OPTION) {
    System.out.println("You entered " +
            firstName.getText() + ", " +
            lastName.getText() + ", " +
            password.getText());
} else {
    System.out.println("User canceled / closed the dialog, result = " + result);
}

Simple Random Samples from a Sql database

Select 3000 random records in Netezza:

WITH IDS AS (
     SELECT ID
     FROM MYTABLE;
)

SELECT ID FROM IDS ORDER BY mt_random() LIMIT 3000

Docker-Compose can't connect to Docker Daemon

I had this problem and did not want to mess things up using sudo. When investigating, I tried to get some info :

docker info

Surprinsingly, I had the following error :

Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock: Get http:///var/run/docker.sock/v1.38/info: dial unix /var/run/docker.sock: connect: permission denied

For some reason I did not have enough privileges, the following command solved my problem :

sudo chown $USER /var/run/docker.sock

Et voilà !

How can I remove punctuation from input text in Java?

I don't like to use regex, so here is another simple solution.

public String removePunctuations(String s) {
    String res = "";
    for (Character c : s.toCharArray()) {
        if(Character.isLetterOrDigit(c))
            res += c;
    }
    return res;
}

Note: This will include both Letters and Digits

VB.NET Empty String Array

You don't have to include String twice, and you don't have to use New.
Either of the following will work...

Dim strings() as String = {}
Dim strings as String() = {}

How to use Servlets and Ajax?

Ajax (also AJAX) an acronym for Asynchronous JavaScript and XML) is a group of interrelated web development techniques used on the client-side to create asynchronous web applications. With Ajax, web applications can send data to, and retrieve data from, a server asynchronously Below is example code:

Jsp page java script function to submit data to servlet with two variable firstName and lastName:

function onChangeSubmitCallWebServiceAJAX()
    {
      createXmlHttpRequest();
      var firstName=document.getElementById("firstName").value;
      var lastName=document.getElementById("lastName").value;
      xmlHttp.open("GET","/AJAXServletCallSample/AjaxServlet?firstName="
      +firstName+"&lastName="+lastName,true)
      xmlHttp.onreadystatechange=handleStateChange;
      xmlHttp.send(null);

    }

Servlet to read data send back to jsp in xml format ( You could use text as well. Just you need to change response content to text and render data on javascript function.)

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    String firstName = request.getParameter("firstName");
    String lastName = request.getParameter("lastName");

    response.setContentType("text/xml");
    response.setHeader("Cache-Control", "no-cache");
    response.getWriter().write("<details>");
    response.getWriter().write("<firstName>"+firstName+"</firstName>");
    response.getWriter().write("<lastName>"+lastName+"</lastName>");
    response.getWriter().write("</details>");
}

Exec : display stdout "live"

I have found it helpful to add a custom exec script to my utilities that do this.

utilities.js

const { exec } = require('child_process')

module.exports.exec = (command) => {
  const process = exec(command)

  process.stdout.on('data', (data) => {
    console.log('stdout: ' + data.toString())
  })

  process.stderr.on('data', (data) => {
    console.log('stderr: ' + data.toString())
  })

  process.on('exit', (code) => {
    console.log('child process exited with code ' + code.toString())
  })
}

app.js

const { exec } = require('./utilities.js')

exec('coffee -cw my_file.coffee')

How to list all users in a Linux group?

getent group insert_group_name_here | awk -F ':' '{print $4}' | sed 's|,| |g'

This returns a space separated list of users which I've used in scripts to populate arrays.

for i in $(getent group ftp | awk -F ':' '{print $4}' | sed 's|,| |g')
    do
        userarray+=("$i")
    done

or

userarray+=("$(getent group GROUPNAME | awk -F ':' '{print $4}' | sed 's|,| |g')")

MySQL Workbench: How to keep the connection alive

If you are using a "Standard TCP/IP over SSH" type of connection, under "Preferences"->"Others" there is "SSH KeepAlive" field. It took me quite a while to find it :(

How to read until EOF from cin in C++

Probable simplest and generally efficient:

#include <iostream>
int main()
{
    std::cout << std::cin.rdbuf();
}

If needed, use stream of other types like std::ostringstream as buffer instead of standard output stream here.

How can I update my ADT in Eclipse?

Running as administrator then following other comments fixed the problem for me :)

How to use "not" in xpath?

not() is a function in xpath (as opposed to an operator), so

//a[not(contains(@id, 'xx'))]

How to check if object has any properties in JavaScript?

for (var hasProperties in ad) break;
if (hasProperties)
    ... // ad has properties

If you have to be safe and check for Object prototypes (these are added by certain libraries and not there by default):

var hasProperties = false;
for (var x in ad) {
    if (ad.hasOwnProperty(x)) {
        hasProperties = true;
        break;
    }
}
if (hasProperties)
    ... // ad has properties

Is there a way to check for both `null` and `undefined`?

The simplest way is to use:

import { isNullOrUndefined } from 'util';

and than:

if (!isNullOrUndefined(foo))

How to use export with Python on Linux

import os
import shlex
from subprocess import Popen, PIPE


os.environ.update(key=value)

res = Popen(shlex.split("cmd xxx -xxx"), stdin=PIPE, stdout=PIPE, stderr=PIPE,
            env=os.environ, shell=True).communicate('y\ny\ny\n'.encode('utf8'))
stdout = res[0]
stderr = res[1]

jQuery-- Populate select from json

A solution is to create your own jquery plugin that take the json map and populate the select with it.

(function($) {     
     $.fn.fillValues = function(options) {
         var settings = $.extend({
             datas : null, 
             complete : null,
         }, options);

         this.each( function(){
            var datas = settings.datas;
            if(datas !=null) {
                $(this).empty();
                for(var key in datas){
                    $(this).append('<option value="'+key+'"+>'+datas[key]+'</option>');
                }
            }
            if($.isFunction(settings.complete)){
                settings.complete.call(this);
            }
        });

    }

}(jQuery));

You can call it by doing this :

$("#select").fillValues({datas:your_map,});

The advantages is that anywhere you will face the same problem you just call

 $("....").fillValues({datas:your_map,});

Et voila !

You can add functions in your plugin as you like

How to use particular CSS styles based on screen size / device

Detection is automatic. You must specify what css can be used for each screen resolution:

/* for all screens, use 14px font size */
body {  
    font-size: 14px;    
}
/* responsive, form small screens, use 13px font size */
@media (max-width: 479px) {
    body {
        font-size: 13px;
    }
}

Cleaning up old remote git branches

Here is how to do it with SourceTree (v2.3.1):
1. Click Fetch
2. Check "Prune tracking branches ..."
3. Press OK
4.

enter image description here

Find Nth occurrence of a character in a string

Since the built-in IndexOf function is already optimized for searching a character within a string, an even faster version would be (as extension method):

public static int NthIndexOf(this string input, char value, int n)
{
    if (n <= 0) throw new ArgumentOutOfRangeException("n", n, "n is less than zero.");

    int i = -1;
    do
    {
        i = input.IndexOf(value, i + 1);
        n--;
    }
    while (i != -1 && n > 0);

    return i;
}

Or to search from the end of the string using LastIndexOf:

public static int NthLastIndexOf(this string input, char value, int n)
{
    if (n <= 0) throw new ArgumentOutOfRangeException("n", n, "n is less than zero.");

    int i = input.Length;
    do
    {
        i = input.LastIndexOf(value, i - 1);
        n--;
    }
    while (i != -1 && n > 0);

    return i;
}

Searching for a string instead of a character is as simple as changing the parameter type from char to string and optionally add an overload to specify the StringComparison.

Converting Integer to Long

Oddly enough I found that if you parse from a string it works.

 int i = 0;
 Long l = Long.parseLong(String.valueOf(i));
 int back = Integer.parseInt(String.valueOf(l));

Win.

TypeError: expected str, bytes or os.PathLike object, not _io.BufferedReader

I think it has to do with your second element in storbinary. You are trying to open file, but it is already a pointer to the file you opened in line file = open(local_path,'rb'). So, try to use ftp.storbinary("STOR " + i, file).

MongoDB SELECT COUNT GROUP BY

Mongo shell command that worked for me:

db.getCollection(<collection_name>).aggregate([{"$match": {'<key>': '<value to match>'}}, {"$group": {'_id': {'<group_by_attribute>': "$group_by_attribute"}}}])

Should a RESTful 'PUT' operation return something

Just as an empty Request body is in keeping with the original purpose of a GET request and empty response body is in keeping with the original purpose of a PUT request.

How to display databases in Oracle 11g using SQL*Plus

Oracle does not have a simple database model like MySQL or MS SQL Server. I find the closest thing is to query the tablespaces and the corresponding users within them.

For example, I have a DEV_DB tablespace with all my actual 'databases' within them:

SQL> SELECT TABLESPACE_NAME FROM USER_TABLESPACES;

Resulting in:

SYSTEM
SYSAUX
UNDOTBS1
TEMP
USERS
EXAMPLE
DEV_DB

It is also possible to query the users in all tablespaces:

SQL> select USERNAME, DEFAULT_TABLESPACE from DBA_USERS;

Or within a specific tablespace (using my DEV_DB tablespace as an example):

SQL> select USERNAME, DEFAULT_TABLESPACE from DBA_USERS where DEFAULT_TABLESPACE = 'DEV_DB';

ROLES DEV_DB
DATAWARE DEV_DB
DATAMART DEV_DB
STAGING DEV_DB

CSS3 scrollbar styling on a div

The problem with the css3 scroll bars is that, interaction can only be performed on the content. we can't interact with the scroll bar on touch devices.

What is a good game engine that uses Lua?

Heroes of Might and Magic V used modified Silent Storm engine. I think you can find many good engines listed in wikipedia: Lua-scriptable game engines

Reading numbers from a text file into an array in C

Loop with %c to read the stream character by character instead of %d.

Basic http file downloading and saving to disk in python?

For Python3+ URLopener is deprecated. And when used you will get error as below:

url_opener = urllib.URLopener() AttributeError: module 'urllib' has no attribute 'URLopener'

So, try:

import urllib.request 
urllib.request.urlretrieve(url, filename)

How do I unlock a SQLite database?

If you want to remove a "database is locked" error then follow these steps:

  1. Copy your database file to some other location.
  2. Replace the database with the copied database. This will dereference all processes which were accessing your database file.

Cannot open new Jupyter Notebook [Permission Denied]

You don't have to install or uninstall anything. if you are using python 2 use pip to install and upgrade. But if you want to use python3 then follow the steps below:

sudo apt-get install python3-pip python3-dev

then in terminal use this

pip3 install -U jupyter

final step is to launch jupyter notebook so,in terminal just type

jupyter notebook

all the issues or problems of premissions etc will be resolved.

How to return 2 values from a Java method?

You could implement a generic Pair if you are sure that you just need to return two values:

public class Pair<U, V> {

 /**
     * The first element of this <code>Pair</code>
     */
    private U first;

    /**
     * The second element of this <code>Pair</code>
     */
    private V second;

    /**
     * Constructs a new <code>Pair</code> with the given values.
     * 
     * @param first  the first element
     * @param second the second element
     */
    public Pair(U first, V second) {

        this.first = first;
        this.second = second;
    }

//getter for first and second

and then have the method return that Pair:

public Pair<Object, Object> getSomePair();

If...Then...Else with multiple statements after Then

Multiple statements are to be separated by a new line:

If SkyIsBlue Then
  StartEngines
  Pollute
ElseIf SkyIsRed Then
  StopAttack
  Vent
ElseIf SkyIsYellow Then
  If Sunset Then
    Sleep
  ElseIf Sunrise or IsMorning Then
    Smoke
    GetCoffee
  Else
    Error
  End If
Else
  Joke
  Laugh
End If