Programs & Examples On #Netbeans6.7

It is the version 6.7 of Netbeans IDE for java application development.

How to handle invalid SSL certificates with Apache HttpClient?

Using the InstallCert to generate the jssecacerts file and do -Djavax.net.ssl.trustStore=/path/to/jssecacerts worked great.

How to send only one UDP packet with netcat?

Netcat sends one packet per newline. So you're fine. If you do anything more complex then you might need something else.

I was fooling around with Wireshark when I realized this. Don't know if it helps.

Parse Json string in C#

What you are trying to deserialize to a Dictionary is actually a Javascript object serialized to JSON. In Javascript, you can use this object as an associative array, but really it's an object, as far as the JSON standard is concerned.

So you would have no problem deserializing what you have with a standard JSON serializer (like the .net ones, DataContractJsonSerializer and JavascriptSerializer) to an object (with members called AppName, AnotherAppName, etc), but to actually interpret this as a dictionary you'll need a serializer that goes further than the Json spec, which doesn't have anything about Dictionaries as far as I know.

One such example is the one everybody uses: JSON .net

There is an other solution if you don't want to use an external lib, which is to convert your Javascript object to a list before serializing it to JSON.

var myList = [];
$.each(myObj, function(key, value) { myList.push({Key:key, Value:value}) });

now if you serialize myList to a JSON object, you should be capable of deserializing to a List<KeyValuePair<string, ValueDescription>> with any of the aforementioned serializers. That list would then be quite obvious to convert to a dictionary.

Note: ValueDescription being this class:

public class ValueDescription
{
    public string Description { get; set; }
    public string Value { get; set; }
}

How can I make my flexbox layout take 100% vertical space?

Let me show you another way that works 100%. I will also add some padding for the example.

<div class = "container">
  <div class = "flex-pad-x">
    <div class = "flex-pad-y">
      <div class = "flex-pad-y">
        <div class = "flex-grow-y">
         Content Centered
        </div>
      </div>
    </div>
  </div>
</div>

.container {
  position: fixed;
  top: 0px;
  left: 0px;
  bottom: 0px;
  right: 0px;
  width: 100%;
  height: 100%;
}

  .flex-pad-x {
    padding: 0px 20px;
    height: 100%;
    display: flex;
  }

  .flex-pad-y {
    padding: 20px 0px;
    width: 100%;
    display: flex;
    flex-direction: column;
  }

  .flex-grow-y {
    flex-grow: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
   }

As you can see we can achieve this with a few wrappers for control while utilising the flex-grow & flex-direction attribute.

1: When the parent "flex-direction" is a "row", its child "flex-grow" works horizontally. 2: When the parent "flex-direction" is "columns", its child "flex-grow" works vertically.

Hope this helps

Daniel

How to run 'sudo' command in windows

runas command requires the users to type password. If you don't want to type password and want to just click the UAC dialog, use Start-Process -Verb runas in PowerShell instead of runas command.

see: http://satob.hatenablog.com/entry/2017/06/17/013217

convert double to int

Convert.ToInt32 is the best way to convert

104, 'Connection reset by peer' socket error, or When does closing a socket result in a RST rather than FIN?

Don't use wsgiref for production. Use Apache and mod_wsgi, or something else.

We continue to see these connection resets, sometimes frequently, with wsgiref (the backend used by the werkzeug test server, and possibly others like the Django test server). Our solution was to log the error, retry the call in a loop, and give up after ten failures. httplib2 tries twice, but we needed a few more. They seem to come in bunches as well - adding a 1 second sleep might clear the issue.

We've never seen a connection reset when running through Apache and mod_wsgi. I don't know what they do differently, (maybe they just mask them), but they don't appear.

When we asked the local dev community for help, someone confirmed that they see a lot of connection resets with wsgiref that go away on the production server. There's a bug there, but it is going to be hard to find it.

"No Content-Security-Policy meta tag found." error in my phonegap application

There is an another issue about connection. Some android versions can connect but some cannot. So there is an another solution

in AndroidManifest.xml:

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

Just add 'android:usesCleartextTraffic="true"'

and problem solved finally.

CSS media queries: max-width OR max-height

CSS Media Queries & Logical Operators: A Brief Overview ;)

The quick answer.

Separate rules with commas: @media handheld, (min-width: 650px), (orientation: landscape) { ... }

The long answer.

There's a lot here, but I've tried to make it information dense, not just fluffy writing. It's been a good chance to learn myself! Take the time to systematically read though and I hope it will be helpful.


Media Queries

Media queries essentially are used in web design to create device- or situation-specific browsing experiences; this is done using the @media declaration within a page's CSS. This can be used to display a webpage differently under a large number of circumstances: whether you are on a tablet or TV with different aspect ratios, whether your device has a color or black-and-white screen, or, perhaps most frequently, when a user changes the size of their browser or switches between browsing devices with varying screen sizes (very generally speaking, designing like this is referred to as Responsive Web Design)

Logical Operators

In designing for these situations, there appear to be four Logical Operators that can be used to require more complex combinations of requirements when targeting a variety of devices or viewport sizes.

(Note: If you don't understand the the differences between media rules, media queries, and feature queries, browse the bottom section of this answer first to get a bit better acquainted with the terminology associated with media query syntax

1. AND (and keyword)

Requires that all conditions specified must be met before the styling rules will take effect.

@media screen and (min-width: 700px) and (orientation: landscape) { ... }

The specified styling rules won't go into place unless all of the following evaluate as true:

  • The media type is 'screen' and
  • The viewport is at least 700px wide and
  • Screen orientation is currently landscape.

Note: I believe that used together, these three feature queries make up a single media query.

2. OR (Comma-separated lists)

Rather than an or keyword, comma-separated lists are used in chaining multiple media queries together to form a more complex media rule

@media handheld, (min-width: 650px), (orientation: landscape) { ... }

The specified styling rules will go into effect once any one media query evaluates as true:

  1. The media type is 'handheld' or
  2. The viewport is at least 650px wide or
  3. Screen orientation is currently landscape.

3. NOT (not keyword)

The not keyword can be used to negate a single media query (and NOT a full media rule--meaning that it only negates entries between a set of commas and not the full media rule following the @media declaration).

Similarly, note that the not keyword negates media queries, it cannot be used to negate an individual feature query within a media query.*

@media not screen and (min-resolution: 300dpi), (min-width: 800px) { ... }

The styling specified here will go into effect if

  1. The media type AND min-resolution don't both meet their requirements ('screen' and '300dpi' respectively) or
  2. The viewport is at least 800 pixels wide.

In other words, if the media type is 'screen' and the min-resolution is 300 dpi, the rule will not go into effect unless the min-width of the viewport is at least 800 pixels.

(The not keyword can be a little funky to state. Let me know if I can do better. ;)

4. ONLY (only keyword)

As I understand it, the only keyword is used to prevent older browsers from misinterpreting newer media queries as the earlier-used, narrower media type. When used correctly, older/non-compliant browsers should just ignore the styling altogether.

<link rel="stylesheet" media="only screen and (color)" href="example.css" />

An older / non-compliant browser would just ignore this line of code altogether, I believe as it would read the only keyword and consider it an incorrect media type. (See here and here for more info from smarter people)

FOR MORE INFO

For more info (including more features that can be queried), see: https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Media_queries#Logical_operators


Understanding Media Query Terminology

Note: I needed to learn the following terminology for everything here to make sense, particularly concerning the not keyword. Here it is as I understand it:

A media rule (MDN also seems to call these media statements) includes the term @media with all of its ensuing media queries

@media all and (min-width: 800px)

@media only screen and (max-resolution:800dpi), not print

@media screen and (min-width: 700px), (orientation: landscape)

@media handheld, (min-width: 650px), (min-aspect-ratio: 1/1)

A media query is a set of feature queries. They can be as simple as one feature query or they can use the and keyword to form a more complex query. Media queries can be comma-separated to form more complex media rules (see the or keyword above).

screen (Note: Only one feature query in use here.)

only screen

only screen and (max-resolution:800dpi)

only tv and (device-aspect-ratio: 16/9) and (color)

NOT handheld, (min-width: 650px). (Note the comma: there are two media queries here.)

A feature query is the most basic portion of a media rule and simply concerns a given feature and its status in a given browsing situation.

screen

(min-width: 650px)

(orientation: landscape)

(device-aspect-ratio: 16/9)


Code snippets and information derived from:

CSS media queries by Mozilla Contributors (licensed under CC-BY-SA 2.5). Some code samples were used with minor alterations to (hopefully) increase clarity of explanation.

Catching errors in Angular HttpClient

Following @acdcjunior answer, this is how I implemented it

service:

  get(url, params): Promise<Object> {

            return this.sendRequest(this.baseUrl + url, 'get', null, params)
                .map((res) => {
                    return res as Object
                }).catch((e) => {
                    return Observable.of(e);
                })
                .toPromise();
        }

caller:

this.dataService.get(baseUrl, params)
            .then((object) => {
                if(object['name'] === 'HttpErrorResponse') {
                            this.error = true;
                           //or any handle
                } else {
                    this.myObj = object as MyClass 
                }
           });

Required maven dependencies for Apache POI to work

If you are not using maven, then you will need **

  • poi
  • poi-ooxml
  • xmlbeans
  • dom4j
  • poi-ooxml-schemas
  • stax-api
  • ooxml-schemas

Background images: how to fill whole div if image is small and vice versa

Rather than giving background-size:100%;
We can give background-size:contain;
Check out this for different options avaliable: http://www.css3.info/preview/background-size/

How to convert hex strings to byte values in Java

String str[] = {"aa", "55"};

byte b[] = new byte[str.length];

for (int i = 0; i < str.length; i++) {
    b[i] = (byte) Integer.parseInt(str[i], 16);
}

Integer.parseInt(string, radix) converts a string into an integer, the radix paramter specifies the numeral system.

Use a radix of 16 if the string represents a hexadecimal number.
Use a radix of 2 if the string represents a binary number.
Use a radix of 10 (or omit the radix paramter) if the string represents a decimal number.

For further details check the Java docs: https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt(java.lang.String,%20int)

Genymotion Android emulator - adb access?

Simply do this, with genymotion device running you can open Virtual Box , and see that there is a VM for you device , then go to network Settings of the VM, NAT and do port forwarding of local 5555 to remote 5555 screen attachedVirtual Box Nat Network Port forwarding

iTunes Connect Screenshots Sizes for all iOS (iPhone/iPad/Apple Watch) devices

 1)iPhone X screenshot support in iTunes Connect.October 27, 2017.

 2)You can now upload screenshots for iPhone X. 
  You’ll see a new tab for 5.8-inch displays under Screenshots and App Previews on your iOS app  version information page.

 3)Note that iPhone X screenshots are optional and cannot be used for smaller devices sizes. 
  5.5-inchdisplay screenshots are still required for all apps that run on iPhone.

 4)iPhone X Screenshot Resolutions
  1125 by 2436 (Portrait)
  2436 by 1125 (Landscape)

C# DateTime.ParseExact

It's probably the same problem with cultures as presented in this related SO-thread: Why can't DateTime.ParseExact() parse "9/1/2009" using "M/d/yyyy"

You already specified the culture, so try escaping the slashes.

How to change the URL from "localhost" to something else, on a local system using wampserver?

WINDOWS + WAMP solution

Step 1
Go to C:\wamp\bin\apache\Apache2.2.17\conf\
open httpd.conf file and change
#Include conf/extra/httpd-vhosts.conf
to
Include conf/extra/httpd-vhosts.conf
i.e. uncomment the line so that it can includes the virtual hosts file.

Step 2
Go to C:\wamp\bin\apache\Apache2.2.17\conf\extra
and open httpd-vhosts.conf file and add the following code

<VirtualHost myWebsite.local>
    DocumentRoot "C:/wamp/www/myWebsite/"
    ServerName myWebsite.local
    ServerAlias myWebsite.local
    <Directory "C:/wamp/www/myWebsite/">
        Order allow,deny
        Allow from all
    </Directory>
</VirtualHost>

change myWebsite.local and C:/wamp/www/myWebsite/ as per your requirements.

Step 3
Open hosts file in C:/Windows/System32/drivers/etc/ and add the following line ( Don't delete anything )

127.0.0.1 myWebsite.local

change myWebsite.local as per your name requirements

Step 4
restart your server. That's it


WINDOWS + XAMPP solution

Same steps as that of WAMP just change the paths according to XAMPP which corresponds to path in WAMP

Changing the cursor in WPF sometimes works, sometimes doesn't

Do you need the cursor to be a "wait" cursor only when it's over that particular page/usercontrol? If not, I'd suggest using Mouse.OverrideCursor:

Mouse.OverrideCursor = Cursors.Wait;
try
{
    // do stuff
}
finally
{
    Mouse.OverrideCursor = null;
}

This overrides the cursor for your application rather than just for a part of its UI, so the problem you're describing goes away.

Efficiently test if a port is open on Linux?

ss -tl4 '( sport = :22 )'

2ms is quick enough ?

Add the colon and this works on Linux

Is 'bool' a basic datatype in C++?

C++ does lots of automatic casting for you - that is, if you have a variable of type bool and pass it to something expecting an int, it will make it into an int for you - 0 for false and 1 for true.

I don't have my standard around to see if this is guaranteed, but every compiler I've used does this (so one can assume it will always work).

However, relying on this conversion is a bad idea. Code can stop compiling if a new method is added that overloads the int signature, etc.

Catch browser's "zoom" event in JavaScript

Here is a native way (major frameworks cannot zoom in Chrome, because they dont supports passive event behaviour)


//For Google Chrome
document.addEventListener("mousewheel", event => {
  console.log(`wheel`);
  if(event.ctrlKey == true)
  {
    event.preventDefault();
    if(event.deltaY > 0) {
      console.log('Down');
    }else {
      console.log('Up');
    }
  }
}, { passive: false });

// For Mozilla Firefox
document.addEventListener("DOMMouseScroll", event => {
  console.log(`wheel`);
  if(event.ctrlKey == true)
  {
    event.preventDefault();
    if(event.detail > 0) {
      console.log('Down');
    }else {
      console.log('Up');
    }
  }
}, { passive: false });

MySQL compare now() (only date, not time) with a datetime field

Use DATE(NOW()) to compare dates

DATE(NOW()) will give you the date part of current date and DATE(duedate) will give you the date part of the due date. then you can easily compare the dates

So you can compare it like

DATE(NOW()) = DATE(duedate)

OR

DATE(duedate) = CURDATE() 

See here

PHP syntax question: What does the question mark and colon mean?

It's the ternary form of the if-else operator. The above statement basically reads like this:

if ($add_review) then {
    return FALSE; //$add_review evaluated as True
} else {
    return $arg //$add_review evaluated as False
}

See here for more details on ternary op in PHP: http://www.addedbytes.com/php/ternary-conditionals/

Git Extensions: Win32 error 487: Couldn't reserve space for cygwin's heap, Win32 error 0

I have seen the same error message after upgrading to git1.8.5.2:

Simply make a search for all msys-1.0.dll on your C:\ drive, and make the one used by Git comes first.

For instance, in my case I simply changed the order of:

C:\prgs\Gow\Gow-0.7.0\bin\msys-1.0.dll
C:\prgs\git\PortableGit-1.8.5.2-preview20131230\bin\msys-1.0.dll

By making the Git path C:\prgs\git\PortableGit-1.8.5.2-preview20131230\bin\ come first in my %PATH%, the error message disappeared.

No need to reboot or to even change the DOS session.
Once the %PATH% is updated in that DOS session, the git commands just work.


Note that carmbrester and Sixto Saez both report below (in the comments) having to reboot in order to fix the issue.
Note: First, also removing any msys-1.0.dll, like one in %LOCALAPPDATA%

Plot multiple columns on the same graph in R

Using tidyverse

df %>% tidyr::gather("id", "value", 1:4) %>% 
  ggplot(., aes(Xax, value))+
  geom_point()+
  geom_smooth(method = "lm", se=FALSE, color="black")+
  facet_wrap(~id)

DATA

df<- read.table(text =c("
A       B       C       G       Xax
0.451   0.333   0.034   0.173   0.22        
0.491   0.270   0.033   0.207   0.34    
0.389   0.249   0.084   0.271   0.54    
0.425   0.819   0.077   0.281   0.34
0.457   0.429   0.053   0.386   0.53    
0.436   0.524   0.049   0.249   0.12    
0.423   0.270   0.093   0.279   0.61    
0.463   0.315   0.019   0.204   0.23"), header = T)

How to install mysql-connector via pip

First install setuptools

sudo pip install setuptools

Then install mysql-connector

sudo pip install mysql-connector

If using Python3, then replace pip by pip3

Default instance name of SQL Server Express

When installing SQL Express, you'll usually get a named instance called SQLExpress, which as others have said you can connect to with localhost\SQLExpress.

If you're looking to get a 'default' instance, which doesn't have a name, you can do that as well. If you put MSSQLServer as the name when installing, it will create a default instance which you can connect to by just specifying 'localhost'.

See here for details... MSDN Instance Configuration

How to show code but hide output in RMarkdown?

As @ J_F answered in the comments, using {r echo = T, results = 'hide'}.

I wanted to expand on their answer - there are great resources you can access to determine all possible options for your chunk and output display - I keep a printed copy at my desk!

You can find them either on the RStudio Website under Cheatsheets (look for the R Markdown cheatsheet and R Markdown Reference Guide) or, in RStudio, navigate to the "Help" tab, choose "Cheatsheets", and look for the same documents there.

Finally to set default chunk options, you can run (in your first chunk) something like the following code if you want most chunks to have the same behavior:

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = T,
                      results = "hide")
```

Later, you can modify the behavior of individual chunks like this, which will replace the default value for just the results option.

```{r analysis, results="markup"}
# code here
```

How to format a DateTime in PowerShell

One thing you could do is:

$date.ToString("yyyyMMdd")

IOError: [Errno 22] invalid mode ('r') or filename: 'c:\\Python27\test.txt'

always use 'r' to get a raw string when you want to avoid escape.

test_file=open(r'c:\Python27\test.txt','r')

How to list all the available keyspaces in Cassandra?

The DESCRIBE command is your friend. You can describe one keyspace, list keyspaces, one table or list all tables in keyspace, the cluster and much more. You can get the full idea by typing

HELP DESCRIBE in cqlsh.

Connected to mscluster at 127.0.0.1:9042. [cqlsh 5.0.1 | Cassandra 3.8 | CQL spec 3.4.2 | Native protocol v4] Use HELP for help.

cqlsh> HELP DESCRIBE

    DESCRIBE [cqlsh only]

    (DESC may be used as a shorthand.)

      Outputs information about the connected Cassandra cluster, or about
      the data objects stored in the cluster. Use in one of the following ways:...<omitted for brevity>
  • DESCRIBE <your key space name> - describes the command used to create keyspace

cqlsh> DESCRIBE testkeyspace;

CREATE KEYSPACE testkeyspace WITH replication = {'class':'SimpleStrategy', 'replication_factor': '3'} AND durable_writes = true;

  • DESCRIBE keyspaces - lists all keyspaces

cqlsh> DESCRIBE KEYSPACES

system_schema system testkeyspace system_auth
system_distributed system_traces

  • DESCRIBE TABLES - List all tables in current keyspace

cqlsh:system> DESCRIBE TABLES;

available_ranges peers paxos
range_xfers batches compaction_history batchlog
local "IndexInfo" sstable_activity
size_estimates hints views_builds_in_progress peer_events
built_views

  • DESCRIBE your table name or DESCRIBE TABLE your table name - Gives the table details

cqlsh:system> DESCRIBE TABLE batchlog

CREATE TABLE system.batchlog ( id uuid PRIMARY KEY, data blob, version int, written_at timestamp ) WITH bloom_filter_fp_chance = 0.01 AND caching = {'keys': 'ALL', 'rows_per_partition': 'NONE'} AND comment = 'DEPRECATED batchlog entries' ....omitted for brevity

Function to return only alpha-numeric characters from string?

Warning: Note that English is not restricted to just A-Z.

Try this to remove everything except a-z, A-Z and 0-9:

$result = preg_replace("/[^a-zA-Z0-9]+/", "", $s);

If your definition of alphanumeric includes letters in foreign languages and obsolete scripts then you will need to use the Unicode character classes.

Try this to leave only A-Z:

$result = preg_replace("/[^A-Z]+/", "", $s);

The reason for the warning is that words like résumé contains the letter é that won't be matched by this. If you want to match a specific list of letters adjust the regular expression to include those letters. If you want to match all letters, use the appropriate character classes as mentioned in the comments.

What is output buffering?

As name suggest here memory buffer used to manage how the output of script appears.

Here is one very good tutorial for the topic

Environment Specific application.properties file in Spring Boot application

My Point , IN this arent way asking developer to create all environment related in single go, resulting in risk of exposing Production Configuration to end developer

as per 12-Factor, shouldnt be enviornment specific reside in Enviornment only .

How do we do for CI CD

  • Build Spring one time and promote to aother environment, in that case, if we have spring jar has all environment, it iwll security risk, having all environment variable in GIT

How to get request url in a jQuery $.get/ajax request

I can't get it to work on $.get() because it has no complete event.

I suggest to use $.ajax() like this,

$.ajax({
    url: 'http://www.example.org',
    data: {'a':1,'b':2,'c':3},
    dataType: 'xml',
    complete : function(){
        alert(this.url)
    },
    success: function(xml){
    }
});

craz demo

javax.faces.application.ViewExpiredException: View could not be restored

I ran into this problem myself and realized that it was because of a side-effect of a Filter that I created which was filtering all requests on the appliation. As soon as I modified the filter to pick only certain requests, this problem did not occur. It maybe good to check for such filters in your application and see how they behave.

How do I consume the JSON POST data in an Express application

Sometimes you don't need third party libraries to parse JSON from text. Sometimes all you need it the following JS command, try it first:

        const res_data = JSON.parse(body);

json: cannot unmarshal object into Go value of type

You JSON doesn't match your struct fields: E.g. "district" in JSON and "District" as the field.

Also: Your Item is a slice type but your JSON is a dict value. Do not mix this up. Slices decode from arrays.

How can I disable all views inside the layout?

Set

android:descendantFocusability="blocksDescendants"

for yor ViewGroup view. All descendants will not take focus.

Python Create unix timestamp five minutes in the future

def expiration_time():
    import datetime,calendar
    timestamp = calendar.timegm(datetime.datetime.now().timetuple())
    returnValue = datetime.timedelta(minutes=5).total_seconds() + timestamp
    return returnValue

Easiest way to activate PHP and MySQL on Mac OS 10.6 (Snow Leopard), 10.7 (Lion), 10.8 (Mountain Lion)?

It's an invisible folder. Just hit Command + Shift + G (takes you to the Go to Folder menu item) and type /etc/.

Then it will take you to inside that folder.

How do I download NLTK data?

Try

nltk.download('all')

this will download all the data and no need to download individually.

javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found

Hi same problem i have solved you can try this

java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.NETWORK

 // SET SSL
public static OkClient setSSLFactoryForClient(OkHttpClient client) {
    try {
        // Create a trust manager that does not validate certificate chains
        final TrustManager[] trustAllCerts = new TrustManager[]{
                new X509TrustManager() {
                    @Override
                    public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                    }

                    @Override
                    public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                    }

                    @Override
                    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }
                }
        };

        // Install the all-trusting trust manager
        final SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
        // Create an ssl socket factory with our all-trusting manager
        final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();


        client.setSslSocketFactory(sslSocketFactory);
        client.setHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });

    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return new OkClient(client);
}

Schema validation failed with the following errors: Data path ".builders['app-shell']" should have required property 'class'

This is worked for me

  1. npm uninstall @angular-devkit/build-angular
  2. npm install @angular-devkit/[email protected]

Secure Web Services: REST over HTTPS vs SOAP + WS-Security. Which is better?

I don't yet have the rep needed to add a comment or I would have just added this to Bell's answer. I think Bell did a very good job of summing up the top level pros and cons of the two approaches. Just a few other factors that you might want to consider:

1) Do the requests between your clients and your service need to go through intermediaries that require access to the payload? If so then WS-Security might be a better fit.

2) It is actually possible to use SSL to provide the server with assurance as to the clients identity using a feature called mutual authentication. However, this doesn't get much use outside of some very specialized scenarios due to the complexity of configuring it. So Bell is right that WS-Sec is a much better fit here.

3) SSL in general can be a bit of a bear to setup and maintain (even in the simpler configuration) due largely to certificate management issues. Having someone who knows how to do this for your platform will be a big plus.

4) If you might need to do some form of credential mapping or identity federation then WS-Sec might be worth the overhead. Not that you can't do this with REST, you just have less structure to help you.

5) Getting all the WS-Security goop into the right places on the client side of things can be more of a pain than you would think it should.

In the end though it really does depend on a lot of things we're not likely to know. For most situations I would say that either approach will be "secure enough" and so that shouldn't be the main deciding factor.

html <input type="text" /> onchange event not working

Checking for keystrokes is only a partial solution, because it's possible to change the contents of an input field using mouse clicks. If you right-click into a text field you'll have cut and paste options that you can use to change the value without making a keystroke. Likewise, if autocomplete is enabled then you can left-click into a field and get a dropdown of previously entered text, and you can select from among your choices using a mouse click. Keystroke trapping will not detect either of these types of changes.

Sadly, there is no "onchange" event that reports changes immediately, at least as far as I know. But there is a solution that works for all cases: set up a timing event using setInterval().

Let's say that your input field has an id and name of "city":

<input type="text" name="city" id="city" />

Have a global variable named "city":

var city = "";

Add this to your page initialization:

setInterval(lookForCityChange, 100);

Then define a lookForCityChange() function:

function lookForCityChange()
{
    var newCity = document.getElementById("city").value;
    if (newCity != city) {
        city = newCity;
        doSomething(city);     // do whatever you need to do
    }
}

In this example, the value of "city" is checked every 100 milliseconds, which you can adjust according to your needs. If you like, use an anonymous function instead of defining lookForCityChange(). Be aware that your code or even the browser might provide an initial value for the input field so you might be notified of a "change" before the user does anything; adjust your code as necessary.

If the idea of a timing event going off every tenth of a second seems ungainly, you can initiate the timer when the input field receives the focus and terminate it (with clearInterval()) upon a blur. I don't think it's possible to change the value of an input field without its receiving the focus, so turning the timer on and off in this fashion should be safe.

Save and load MemoryStream to/from a file

Assuming that MemoryStream name is ms.

This code writes down MemoryStream to a file:

using (FileStream file = new FileStream("file.bin", FileMode.Create, System.IO.FileAccess.Write)) {
   byte[] bytes = new byte[ms.Length];
   ms.Read(bytes, 0, (int)ms.Length);
   file.Write(bytes, 0, bytes.Length);
   ms.Close();
}

and this reads a file to a MemoryStream :

using (MemoryStream ms = new MemoryStream())
using (FileStream file = new FileStream("file.bin", FileMode.Open, FileAccess.Read)) {
   byte[] bytes = new byte[file.Length];
   file.Read(bytes, 0, (int)file.Length);
   ms.Write(bytes, 0, (int)file.Length);
}

In .Net Framework 4+, You can simply copy FileStream to MemoryStream and reverse as simple as this:

MemoryStream ms = new MemoryStream();
using (FileStream file = new FileStream("file.bin", FileMode.Open, FileAccess.Read))
    file.CopyTo(ms);

And the Reverse (MemoryStream to FileStream):

using (FileStream file = new FileStream("file.bin", FileMode.Create, System.IO.FileAccess.Write))
    ms.CopyTo(file);

WPF Check box: Check changed handling

Im putting this in an answer because it's too long for a comment:

If you need the VM to be aware when the CheckBox is changed, you should really bind the CheckBox to the VM, and not a static value:

public class ViewModel
{
    private bool _caseSensitive;
    public bool CaseSensitive
    {
        get { return _caseSensitive; }
        set
        {
            _caseSensitive = value;
            NotifyPropertyChange(() => CaseSensitive);

            Settings.Default.bSearchCaseSensitive = value;
        }
    }
}

XAML:

<CheckBox Content="Case Sensitive" IsChecked="{Binding CaseSensitive}"/>

Spring MVC: difference between <context:component-scan> and <annotation-driven /> tags?

<mvc:annotation-driven /> means that you can define spring beans dependencies without actually having to specify a bunch of elements in XML or implement an interface or extend a base class. For example @Repository to tell spring that a class is a Dao without having to extend JpaDaoSupport or some other subclass of DaoSupport. Similarly @Controller tells spring that the class specified contains methods that will handle Http requests without you having to implement the Controller interface or extend a subclass that implements the controller.

When spring starts up it reads its XML configuration file and looks for <bean elements within it if it sees something like <bean class="com.example.Foo" /> and Foo was marked up with @Controller it knows that the class is a controller and treats it as such. By default, Spring assumes that all the classes it should manage are explicitly defined in the beans.XML file.

Component scanning with <context:component-scan base-package="com.mycompany.maventestwebapp" /> is telling spring that it should search the classpath for all the classes under com.mycompany.maventestweapp and look at each class to see if it has a @Controller, or @Repository, or @Service, or @Component and if it does then Spring will register the class with the bean factory as if you had typed <bean class="..." /> in the XML configuration files.

In a typical spring MVC app you will find that there are two spring configuration files, a file that configures the application context usually started with the Spring context listener.

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

And a Spring MVC configuration file usually started with the Spring dispatcher servlet. For example.

<servlet>
        <servlet-name>main</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>main</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

Spring has support for hierarchical bean factories, so in the case of the Spring MVC, the dispatcher servlet context is a child of the main application context. If the servlet context was asked for a bean called "abc" it will look in the servlet context first, if it does not find it there it will look in the parent context, which is the application context.

Common beans such as data sources, JPA configuration, business services are defined in the application context while MVC specific configuration goes not the configuration file associated with the servlet.

Hope this helps.

How do I set the default Java installation/runtime (Windows)?

This is a bit of a pain on Windows. Here's what I do.

Install latest Sun JDK, e.g. 6u11, in path like c:\install\jdk\sun\6u11, then let the installer install public JRE in the default place (c:\program files\blah). This will setup your default JRE for the majority of things.

Install older JDKs as necessary, like 5u18 in c:\install\jdk\sun\5u18, but don't install the public JREs.

When in development, I have a little batch file that I use to setup a command prompt for each JDK version. Essentially just set JAVA_HOME=c:\jdk\sun\JDK_DESIRED and then set PATH=%JAVA_HOME%\bin;%PATH%. This will put the desired JDK first in the path and any secondary tools like Ant or Maven can use the JAVA_HOME variable.

The path is important because most public JRE installs put a linked executable at c:\WINDOWS\System32\java.exe, which usually overrides most other settings.

How to do left join in Doctrine?

If you have an association on a property pointing to the user (let's say Credit\Entity\UserCreditHistory#user, picked from your example), then the syntax is quite simple:

public function getHistory($users) {
    $qb = $this->entityManager->createQueryBuilder();
    $qb
        ->select('a', 'u')
        ->from('Credit\Entity\UserCreditHistory', 'a')
        ->leftJoin('a.user', 'u')
        ->where('u = :user')
        ->setParameter('user', $users)
        ->orderBy('a.created_at', 'DESC');

    return $qb->getQuery()->getResult();
}

Since you are applying a condition on the joined result here, using a LEFT JOIN or simply JOIN is the same.

If no association is available, then the query looks like following

public function getHistory($users) {
    $qb = $this->entityManager->createQueryBuilder();
    $qb
        ->select('a', 'u')
        ->from('Credit\Entity\UserCreditHistory', 'a')
        ->leftJoin(
            'User\Entity\User',
            'u',
            \Doctrine\ORM\Query\Expr\Join::WITH,
            'a.user = u.id'
        )
        ->where('u = :user')
        ->setParameter('user', $users)
        ->orderBy('a.created_at', 'DESC');

    return $qb->getQuery()->getResult();
}

This will produce a resultset that looks like following:

array(
    array(
        0 => UserCreditHistory instance,
        1 => Userinstance,
    ),
    array(
        0 => UserCreditHistory instance,
        1 => Userinstance,
    ),
    // ...
)

CSS3 transition doesn't work with display property

Made some changes, but I think I got the effect you want using visibility. http://jsfiddle.net/9dsGP/49/

I also made these changes:

position: absolute; /* so it doesn't expand the button background */
top: calc(1em + 8px); /* so it's under the "button" */
left:8px; /* so it's shifted by padding-left */
width: 182px; /* so it fits nicely under the button, width - padding-left - padding-right - border-left-width - border-right-width, 200 - 8 - 8 - 1 - 1 = 182 */

Alternatively, you could put .content as a sibling of .button, but I didn't make an example for this.

How to have a drop down <select> field in a rails form?

You can take a look at the Rails documentation . Anyways , in your form :

  <%= f.collection_select :provider_id, Provider.order(:name),:id,:name, include_blank: true %>

As you can guess , you should predefine email-providers in another model -Provider , to have where to select them from .

Simple GUI Java calculator

Somewhere you have to keep track of what button had been pressed. When things happen, you need to store something in a variable so you can recall the information or it's gone forever.

When someone pressed one of the operator buttons, don't just let them type in another value. Save the operator symbol, then let them type in another value. You could literally just have a String operator that gets the text of the operator button pressed. Then, when the equals button is pressed, you have to check to see which operator you stored. You could do this with an if/else if/else chain.

So, in your symbol's button press event, store the symbol text in a variable, then, in the = button press event, check to see which symbol is in the variable and act accordingly.

Alternatively, if you feel comfortable enough with enums (looks like you're just starting, so if you're not to that point yet, ignore this), you could have an enumeration of symbols that lets you check symbols easily with a switch.

What is the best way to add a value to an array in state

the best away now.

this.setState({ myArr: [...this.state.myArr, new_value] })

MySQL check if a table exists without throwing an exception

If you're using MySQL 5.0 and later, you could try:

SELECT COUNT(*)
FROM information_schema.tables 
WHERE table_schema = '[database name]' 
AND table_name = '[table name]';

Any results indicate the table exists.

From: http://www.electrictoolbox.com/check-if-mysql-table-exists/

Target a css class inside another css class

Not certain what the HTML looks like (that would help with answers). If it's

<div class="testimonials content">stuff</div>

then simply remove the space in your css. A la...

.testimonials.content { css here }

UPDATE:

Okay, after seeing HTML see if this works...

.testimonials .wrapper .content { css here }

or just

.testimonials .wrapper { css here }

or

.desc-container .wrapper { css here }

all 3 should work.

Conditional Logic on Pandas DataFrame

In [34]: import pandas as pd

In [35]: import numpy as np

In [36]:  df = pd.DataFrame([1,2,3,4], columns=["data"])

In [37]: df
Out[37]: 
   data
0     1
1     2
2     3
3     4

In [38]: df["desired_output"] = np.where(df["data"] <2.5, "False", "True")

In [39]: df
Out[39]: 
   data desired_output
0     1          False
1     2          False
2     3           True
3     4           True

Iptables setting multiple multiports in one rule

As a workaround to this limitation, I use two rules to cover all the cases.

For example, if I want to allow or deny these 18 ports:

465,110,995,587,143,11025,20,21,22,26,80,443,3000,10000,7080,8080,3000,5666

I use the below rules:

iptables -A INPUT -p tcp -i eth0 -m multiport --dports 465,110,995,587,143,11025,20,21,22,26,80,443 -j ACCEPT

iptables -A INPUT -p tcp -i eth0 -m multiport --dports 3000,10000,7080,8080,3000,5666 -j ACCEPT

The above rules should work for your scenario also. You can create another rule if you hit 15 ports limit on both first and second rule.

How do I create a ListView with rounded corners in Android?

Here is one way of doing it (Thanks to Android Documentation though!):

Add the following into a file (say customshape.xml) and then place it in (res/drawable/customshape.xml)

<?xml version="1.0" encoding="UTF-8"?> 
<shape xmlns:android="http://schemas.android.com/apk/res/android" 
     android:shape="rectangle"> 
     <gradient 
         android:startColor="#SomeGradientBeginColor"
         android:endColor="#SomeGradientEndColor" 
         android:angle="270"/> 

    <corners 
         android:bottomRightRadius="7dp" 
         android:bottomLeftRadius="7dp" 
         android:topLeftRadius="7dp" 
         android:topRightRadius="7dp"/> 
</shape> 

Once you are done with creating this file, just set the background in one of the following ways:

Through Code: listView.setBackgroundResource(R.drawable.customshape);

Through XML, just add the following attribute to the container (ex: LinearLayout or to any fields):

android:background="@drawable/customshape"

Hope someone finds it useful...

Get rid of "The value for annotation attribute must be a constant expression" message

The value for an annotation must be a compile time constant, so there is no simple way of doing what you are trying to do.

See also here: How to supply value to an annotation from a Constant java

It is possible to use some compile time tools (ant, maven?) to config it if the value is known before you try to run the program.

Plotting power spectrum in python

From the numpy fft page http://docs.scipy.org/doc/numpy/reference/routines.fft.html:

When the input a is a time-domain signal and A = fft(a), np.abs(A) is its amplitude spectrum and np.abs(A)**2 is its power spectrum. The phase spectrum is obtained by np.angle(A).

Keeping session alive with Curl and PHP

This is how you do CURL with sessions

//initial request with login data

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/login.php');
curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/32.0.1700.107 Chrome/32.0.1700.107 Safari/537.36');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, "username=XXXXX&password=XXXXX");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_COOKIESESSION, true);
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie-name');  //could be empty, but cause problems on some hosts
curl_setopt($ch, CURLOPT_COOKIEFILE, '/var/www/ip4.x/file/tmp');  //could be empty, but cause problems on some hosts
$answer = curl_exec($ch);
if (curl_error($ch)) {
    echo curl_error($ch);
}

//another request preserving the session

curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/profile');
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, "");
$answer = curl_exec($ch);
if (curl_error($ch)) {
    echo curl_error($ch);
}

I've seen this on ImpressPages

Getting all request parameters in Symfony 2

With Recent Symfony 2.6+ versions as a best practice Request is passed as an argument with action in that case you won't need to explicitly call $this->getRequest(), but rather call $request->request->all()

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\NotAcceptableHttpException;
use Symfony\Component\HttpFoundation\RedirectResponse;

    class SampleController extends Controller
    {


        public function indexAction(Request $request) {

           var_dump($request->request->all());
        }

    }

How to combine 2 plots (ggplot) into one plot?

Just combine them. I think this should work but it's untested:

p <- ggplot(visual1, aes(ISSUE_DATE,COUNTED)) + geom_point() + 
     geom_smooth(fill="blue", colour="darkblue", size=1)

p <- p + geom_point(data=visual2, aes(ISSUE_DATE,COUNTED)) + 
     geom_smooth(data=visual2, fill="red", colour="red", size=1)

print(p)

How to detect the device orientation using CSS media queries?

I think we need to write more specific media query. Make sure if you write one media query it should be not effect to other view (Mob,Tab,Desk) otherwise it can be trouble. I would like suggest to write one basic media query for respective device which cover both view and one orientation media query that you can specific code more about orientation view its for good practice. we Don't need to write both media orientation query at same time. You can refer My below example. I am sorry if my English writing is not much good. Ex:

For Mobile

@media screen and (max-width:767px) {

..This is basic media query for respective device.In to this media query  CSS code cover the both view landscape and portrait view.

}


@media screen and (min-width:320px) and (max-width:767px) and (orientation:landscape) {


..This orientation media query. In to this orientation media query you can specify more about CSS code for landscape view.

}

For Tablet

@media screen and (max-width:1024px){
..This is basic media query for respective device.In to this media query  CSS code cover the both view landscape and portrait view.
}
@media screen and (min-width:768px) and (max-width:1024px) and (orientation:landscape){

..This orientation media query. In to this orientation media query you can specify more about CSS code for landscape view.

}

Desktop

make as per your design requirement enjoy...(:

Thanks, Jitu

Remove all HTMLtags in a string (with the jquery text() function)

If you need to remove the HTML but does not know if it actually contains any HTML tags, you can't use the jQuery method directly because it returns empty wrapper for non-HTML text.

$('<div>Hello world</div>').text(); //returns "Hello world"
$('Hello world').text(); //returns empty string ""

You must either wrap the text in valid HTML:

$('<div>' + 'Hello world' + '</div>').text();

Or use method $.parseHTML() (since jQuery 1.8) that can handle both HTML and non-HTML text:

var html = $.parseHTML('Hello world'); //parseHTML return HTMLCollection
var text = $(html).text(); //use $() to get .text() method

Plus parseHTML removes script tags completely which is useful as anti-hacking protection for user inputs.

$('<p>Hello world</p><script>console.log(document.cookie)</script>').text();
//returns "Hello worldconsole.log(document.cookie)"

$($.parseHTML('<p>Hello world</p><script>console.log(document.cookie)</script>')).text();
//returns "Hello world"

Installing PIL (Python Imaging Library) in Win7 64 bits, Python 2.6.4

http://www.lfd.uci.edu/~gohlke/pythonlibs/

press contrl F type Pillow-2.4.0.win-amd64-py3.3.exe

then click and downloadd the 64 bit version

Pillow is a replacement for PIL, the Python Image Library, which provides image processing functionality and supports many file formats. Note: use from PIL import Image instead of import Image. PIL-1.1.7.win-amd64-py2.5.exe PIL-1.1.7.win32-py2.5.exe Pillow-2.4.0.win-amd64-py2.6.exe Pillow-2.4.0.win-amd64-py2.7.exe Pillow-2.4.0.win-amd64-py3.2.exe Pillow-2.4.0.win-amd64-py3.3.exe Pillow-2.4.0.win-amd64-py3.4.exe Pillow-2.4.0.win32-py2.6.exe Pillow-2.4.0.win32-py2.7.exe Pillow-2.4.0.win32-py3.2.exe Pillow-2.4.0.win32-py3.3.exe Pillow-2.4.0.win32-py3.4.exe

Print in Landscape format

you cannot set this in javascript, you have to do this with html/css:

<style type="text/css" media="print">
  @page { size: landscape; }
</style>

EDIT: See this Question and the accepted answer for more information on browser support: Is @Page { size:landscape} obsolete?

How to get String Array from arrays.xml file

Your array.xml is not right. change it to like this

Here is array.xml file

<?xml version="1.0" encoding="utf-8"?>  
<resources>  
    <string-array name="testArray">  
        <item>first</item>  
        <item>second</item>  
        <item>third</item>  
        <item>fourth</item>  
        <item>fifth</item>  
   </string-array>
</resources>

Get specific line from text file using just shell script

Assuming line is a variable which holds your required line number, if you can use head and tail, then it is quite simple:

head -n $line file | tail -1

If not, this should work:

x=0
want=5
cat lines | while read line; do
  x=$(( x+1 ))
  if [ $x -eq "$want" ]; then
    echo $line
    break
  fi
done

Multiple "order by" in LINQ

This should work for you:

var movies = _db.Movies.OrderBy(c => c.Category).ThenBy(n => n.Name)

How to make a WPF window be on top of all other windows of my app (not system wide)?

use the Activate() method. This attempts to bring the window to the foreground and activate it. e.g. Window wnd = new xyz(); wnd.Activate();

SQL to Entity Framework Count Group-By

Edit: EF Core 2.1 finally supports GroupBy

But always look out in the console / log for messages. If you see a notification that your query could not be converted to SQL and will be evaluated locally then you may need to rewrite it.


Entity Framework 7 (now renamed to Entity Framework Core 1.0 / 2.0) does not yet support GroupBy() for translation to GROUP BY in generated SQL (even in the final 1.0 release it won't). Any grouping logic will run on the client side, which could cause a lot of data to be loaded.

Eventually code written like this will automagically start using GROUP BY, but for now you need to be very cautious if loading your whole un-grouped dataset into memory will cause performance issues.

For scenarios where this is a deal-breaker you will have to write the SQL by hand and execute it through EF.

If in doubt fire up Sql Profiler and see what is generated - which you should probably be doing anyway.

https://blogs.msdn.microsoft.com/dotnet/2016/05/16/announcing-entity-framework-core-rc2

Difference in make_shared and normal shared_ptr in C++

I see one problem with std::make_shared, it doesn't support private/protected constructors

MySql difference between two timestamps in days?

CREATE TABLE t (d1 timestamp, d2 timestamp);

INSERT INTO t VALUES ('2010-03-11 12:00:00', '2010-03-30 05:00:00');
INSERT INTO t VALUES ('2010-03-11 12:00:00', '2010-03-30 13:00:00');
INSERT INTO t VALUES ('2010-03-11 00:00:00', '2010-03-30 13:00:00');
INSERT INTO t VALUES ('2010-03-10 12:00:00', '2010-03-30 13:00:00');
INSERT INTO t VALUES ('2010-03-10 12:00:00', '2010-04-01 13:00:00');

SELECT d2, d1, DATEDIFF(d2, d1) AS diff FROM t;

+---------------------+---------------------+------+
| d2                  | d1                  | diff |
+---------------------+---------------------+------+
| 2010-03-30 05:00:00 | 2010-03-11 12:00:00 |   19 |
| 2010-03-30 13:00:00 | 2010-03-11 12:00:00 |   19 |
| 2010-03-30 13:00:00 | 2010-03-11 00:00:00 |   19 |
| 2010-03-30 13:00:00 | 2010-03-10 12:00:00 |   20 |
| 2010-04-01 13:00:00 | 2010-03-10 12:00:00 |   22 |
+---------------------+---------------------+------+
5 rows in set (0.00 sec)

java.lang.UnsupportedClassVersionError

This class was compiled with a JDK more recent than the one used for execution.

The easiest is to install a more recent JRE on the computer where you execute the program. If you think you installed a recent one, check the JAVA_HOME and PATH environment variables.

Version 49 is java 1.5. That means the class was compiled with (or for) a JDK which is yet old. You probably tried to execute the class with JDK 1.4. You really should use one more recent (1.6 or 1.7, see java version history).

How to parse/read a YAML file into a Python object?

From http://pyyaml.org/wiki/PyYAMLDocumentation:

add_path_resolver(tag, path, kind) adds a path-based implicit tag resolver. A path is a list of keys that form a path to a node in the representation graph. Paths elements can be string values, integers, or None. The kind of a node can be str, list, dict, or None.

#!/usr/bin/env python
import yaml

class Person(yaml.YAMLObject):
  yaml_tag = '!person'

  def __init__(self, name):
    self.name = name

yaml.add_path_resolver('!person', ['Person'], dict)

data = yaml.load("""
Person:
  name: XYZ
""")

print data
# {'Person': <__main__.Person object at 0x7f2b251ceb10>}

print data['Person'].name
# XYZ

NotificationCenter issue on Swift 3

Swift 3 & 4

Swift 3, and now Swift 4, have replaced many "stringly-typed" APIs with struct "wrapper types", as is the case with NotificationCenter. Notifications are now identified by a struct Notfication.Name rather than by String. For more details see the now legacy Migrating to Swift 3 guide

Swift 2.2 usage:

// Define identifier
let notificationIdentifier: String = "NotificationIdentifier"

// Register to receive notification
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(YourClassName.methodOfReceivedNotification(_:)), name: notificationIdentifier, object: nil)

// Post a notification
NSNotificationCenter.defaultCenter().postNotificationName(notificationIdentifier, object: nil)

Swift 3 & 4 usage:

// Define identifier
let notificationName = Notification.Name("NotificationIdentifier")

// Register to receive notification
NotificationCenter.default.addObserver(self, selector: #selector(YourClassName.methodOfReceivedNotification), name: notificationName, object: nil)

// Post notification
NotificationCenter.default.post(name: notificationName, object: nil)

// Stop listening notification
NotificationCenter.default.removeObserver(self, name: notificationName, object: nil)

All of the system notification types are now defined as static constants on Notification.Name; i.e. .UIApplicationDidFinishLaunching, .UITextFieldTextDidChange, etc.

You can extend Notification.Name with your own custom notifications in order to stay consistent with the system notifications:

// Definition:
extension Notification.Name {
    static let yourCustomNotificationName = Notification.Name("yourCustomNotificationName")
}

// Usage:
NotificationCenter.default.post(name: .yourCustomNotificationName, object: nil)

Swift 4.2 usage:

Same as Swift 4, except now system notifications names are part of UIApplication. So in order to stay consistent with the system notifications you can extend UIApplication with your own custom notifications instead of Notification.Name :

// Definition:
UIApplication {
    public static let yourCustomNotificationName = Notification.Name("yourCustomNotificationName")
}

// Usage:
NotificationCenter.default.post(name: UIApplication.yourCustomNotificationName, object: nil)

How to make an element in XML schema optional?

Try this

<xs:element name="description" type="xs:string" minOccurs="0" maxOccurs="1" />

if you want 0 or 1 "description" elements, Or

<xs:element name="description" type="xs:string" minOccurs="0" maxOccurs="unbounded" />

if you want 0 to infinity number of "description" elements.

ASP.NET MVC 3 - redirect to another action

return RedirectToAction("ActionName", "ControllerName");

Unsupported Media Type in postman

Thanks for all Contributions;

that is happening with me in XML; I just Change application/XML to be text/XML which solve my Problem

Origin http://localhost is not allowed by Access-Control-Allow-Origin

a thorough reading of jQuery AJAX cross domain seems to indicate that the server you are querying is returning a header string that prohibits cross-domain json requests. Check the headers of the response you are receiving to see if the Access-Control-Allow-Origin header is set, and whether its value restricts cross-domain requests to the local host.

How to center a subview of UIView

func callAlertView() {

    UIView.animate(withDuration: 0, animations: {
        let H = self.view.frame.height * 0.4
        let W = self.view.frame.width * 0.9
        let X = self.view.bounds.midX - (W/2)
        let Y = self.view.bounds.midY - (H/2)
        self.alertView.frame = CGRect(x:X, y: Y, width: W, height: H)
        self.alertView.layer.borderWidth = 1
        self.alertView.layer.borderColor = UIColor.red.cgColor
        self.alertView.layer.cornerRadius = 16
        self.alertView.layer.masksToBounds = true
        self.view.addSubview(self.alertView)

    })


}// calculation works adjust H and W according to your requirement

How to edit nginx.conf to increase file size upload

In case if one is using nginx proxy as a docker container (e.g. jwilder/nginx-proxy), there is the following way to configure client_max_body_size (or other properties):

  1. Create a custom config file e.g. /etc/nginx/proxy.conf with a right value for this property
  2. When running a container, add it as a volume e.g. -v /etc/nginx/proxy.conf:/etc/nginx/conf.d/my_proxy.conf:ro

Personally found this way rather convenient as there's no need to build a custom container to change configs. I'm not affiliated with jwilder/nginx-proxy, was just using it in my project, and the way described above helped me. Hope it helps someone else, too.

Android: disabling highlight on listView click

You only need to add: android:cacheColorHint="@android:color/transparent"

Import Excel to Datagridview

try the following program

using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        System.Data.OleDb.OleDbConnection MyConnection;
        System.Data.DataSet DtSet;
        System.Data.OleDb.OleDbDataAdapter MyCommand;
        MyConnection = new System.Data.OleDb.OleDbConnection(@"provider=Microsoft.Jet.OLEDB.4.0;Data Source='c:\csharp.net-informations.xls';Extended Properties=Excel 8.0;");
        MyCommand = new System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection);
        MyCommand.TableMappings.Add("Table", "Net-informations.com");
        DtSet = new System.Data.DataSet();
        MyCommand.Fill(DtSet);
        dataGridView1.DataSource = DtSet.Tables[0];
        MyConnection.Close();
    }
}
} 

How to generate java classes from WSDL file

jdk 6 comes with wsimport that u can use to create Java-classes from a WSDL. It also creates a Service-class.

http://docs.oracle.com/javase/6/docs/technotes/tools/share/wsimport.html

PHP function to generate v4 UUID

A slight variation on Jack's answer to add support for PHP < 7:

// Get an RFC-4122 compliant globaly unique identifier
function get_guid() {
    $data = PHP_MAJOR_VERSION < 7 ? openssl_random_pseudo_bytes(16) : random_bytes(16);
    $data[6] = chr(ord($data[6]) & 0x0f | 0x40);    // Set version to 0100
    $data[8] = chr(ord($data[8]) & 0x3f | 0x80);    // Set bits 6-7 to 10
    return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
}

How to add calendar events in Android?

Just in case if someone needs this for Xamarin in c#:

        Intent intent = new Intent(Intent.ActionInsert);
        intent.SetData(Android.Provider.CalendarContract.Events.ContentUri);
        intent.PutExtra(Android.Provider.CalendarContract.ExtraEventBeginTime, Utils.Tools.CurrentTimeMillis(game.Date));
        intent.PutExtra(Android.Provider.CalendarContract.EventsColumns.AllDay, false);
        intent.PutExtra(Android.Provider.CalendarContract.EventsColumns.EventLocation, "Location");
        intent.PutExtra(Android.Provider.CalendarContract.EventsColumns.Description, "Description");
        intent.PutExtra(Android.Provider.CalendarContract.ExtraEventEndTime, Utils.Tools.CurrentTimeMillis(game.Date.AddHours(2)));
        intent.PutExtra(Android.Provider.CalendarContract.EventsColumns.Title, "Title");
        StartActivity(intent);

Helper Functions:

    private static readonly DateTime Jan1st1970 = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

    public static long CurrentTimeMillis(DateTime date)
    {
        return (long)(date.ToUniversalTime() - Jan1st1970).TotalMilliseconds;
    }

Any way to generate ant build.xml file automatically from Eclipse?

Right-click on an Eclipse project then "Export" then "General" then "Ant build files". I don't think it is possible to customise the output format though.

Get current category ID of the active page

I use the get_queried_object function to get the current category on a category.php template page.

$current_category = get_queried_object();

Jordan Eldredge is right, get_the_category is not suitable here.

Blocking device rotation on mobile web pages

seems weird that no one proposed the CSS media query solution:

@media screen and (orientation: portrait) {
  ...
}

and the option to use a specific style sheet:

<link rel="stylesheet" type="text/css" href="css/style_p.css" media="screen and (orientation: portrait)">

MDN: https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Media_queries#orientation

Why does overflow:hidden not work in a <td>?

I'm not familiar with the specific issue, but you could stick a div, etc inside the td and set overflow on that.

How to make flexbox items the same size?

Set them so that their flex-basis is 0 (so all elements have the same starting point), and allow them to grow:

flex: 1 1 0px

Your IDE or linter might mention that the unit of measure 'px' is redundant. If you leave it out (like: flex: 1 1 0), IE will not render this correctly. So the px is required to support Internet Explorer, as mentioned in the comments by @fabb;

Group by multiple field names in java 8

You can use List as a classifier for many fields, but you need wrap null values into Optional:

Function<String, List> classifier = (item) -> List.of(
    item.getFieldA(),
    item.getFieldB(),
    Optional.ofNullable(item.getFieldC())
);

Map<List, List<Item>> grouped = items.stream()
    .collect(Collectors.groupingBy(classifier));

How do I Alter Table Column datatype on more than 1 column?

Use the following syntax:

  ALTER TABLE your_table
  MODIFY COLUMN column1 datatype,
  MODIFY COLUMN column2 datatype,
  ... ... ... ... ... 
  ... ... ... ... ...

Based on that, your ALTER command should be:

  ALTER TABLE webstore.Store
  MODIFY COLUMN ShortName VARCHAR(100),
  MODIFY COLUMN UrlShort VARCHAR(100)

Note that:

  1. There are no second brackets around the MODIFY statements.
  2. I used two separate MODIFY statements for two separate columns.

This is the standard format of the MODIFY statement for an ALTER command on multiple columns in a MySQL table.

Take a look at the following: http://dev.mysql.com/doc/refman/5.1/en/alter-table.html and Alter multiple columns in a single statement

select into in mysql

In MySQL, It should be like this

INSERT INTO this_table_archive (col1, col2, ..., coln)
SELECT col1, col2, ..., coln
FROM this_table
WHERE entry_date < '2011-01-01 00:00:00';

MySQL Documentation

wget command to download a file and save as a different filename

Use the -O file option.

E.g.

wget google.com
...
16:07:52 (538.47 MB/s) - `index.html' saved [10728]

vs.

wget -O foo.html google.com
...
16:08:00 (1.57 MB/s) - `foo.html' saved [10728]

Setting the default active profile in Spring-boot

What you are doing here is setting the default default profile (the profile that is used on any bean if you don't specify the @Profile annotation) to be production.

What you actually need to do is set the default active profile, which is done like this:

spring.profiles.active=production

Best way to add Gradle support to IntelliJ Project

Another way, simpler.

Add your

build.gradle

file to the root of your project. Close the project. Manually remove *.iml file. Then choose "Import Project...", navigate to your project directory, select the build.gradle file and click OK.

How to 'restart' an android application programmatically

Checkout intent properties like no history , clear back stack etc ... Intent.setFlags

Intent mStartActivity = new Intent(HomeActivity.this, SplashScreen.class);
int mPendingIntentId = 123456;
PendingIntent mPendingIntent = PendingIntent.getActivity(HomeActivity.this, mPendingIntentId, mStartActivity,
PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager mgr = (AlarmManager) HomeActivity.this.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
System.exit(0);

How to execute Ant build in command line

Go to the Ant website and download. This way, you have a copy of Ant outside of Eclipse. I recommend to put it under the C:\ant directory. This way, it doesn't have any spaces in the directory names. In your System Control Panel, set the Environment Variable ANT_HOME to this directory, then pre-pend to the System PATHvariable, %ANT_HOME%\bin. This way, you don't have to put in the whole directory name.

Assuming you did the above, try this:

C:\> cd \Silk4J\Automation\iControlSilk4J
C:\Silk4J\Automation\iControlSilk4J> ant -d build

This will do several things:

  • It will eliminate the possibility that the problem is with Eclipe's version of Ant.
  • It is way easier to type
  • Since you're executing the build.xml in the directory where it exists, you don't end up with the possibility that your Ant build can't locate a particular directory.

The -d will print out a lot of output, so you might want to capture it, or set your terminal buffer to something like 99999, and run cls first to clear out the buffer. This way, you'll capture all of the output from the beginning in the terminal buffer.

Let's see how Ant should be executing. You didn't specify any targets to execute, so Ant should be taking the default build target. Here it is:

<target depends="build-subprojects,build-project" name="build"/>

The build target does nothing itself. However, it depends upon two other targets, so these will be called first:

The first target is build-subprojects:

<target name="build-subprojects"/>

This does nothing at all. It doesn't even have a dependency.

The next target specified is build-project does have code:

<target depends="init" name="build-project">

This target does contain tasks, and some dependent targets. Before build-project executes, it will first run the init target:

<target name="init">
    <mkdir dir="bin"/>
    <copy includeemptydirs="false" todir="bin">
        <fileset dir="src">
            <exclude name="**/*.java"/>
        </fileset>
    </copy>
</target>

This target creates a directory called bin, then copies all files under the src tree with the suffix *.java over to the bin directory. The includeemptydirs mean that directories without non-java code will not be created.

Ant uses a scheme to do minimal work. For example, if the bin directory is created, the <mkdir/> task is not executed. Also, if a file was previously copied, or there are no non-Java files in your src directory tree, the <copy/> task won't run. However, the init target will still be executed.

Next, we go back to our previous build-project target:

<target depends="init" name="build-project">
    <echo message="${ant.project.name}: ${ant.file}"/>
    <javac debug="true" debuglevel="${debuglevel}" destdir="bin" source="${source}" target="${target}">
        <src path="src"/>
        <classpath refid="iControlSilk4J.classpath"/>
    </javac>
</target>

Look at this line:

<echo message="${ant.project.name}: ${ant.file}"/>

That should have always executed. Did your output print:

[echo] iControlSilk4J: C:\Silk4J\Automation\iControlSilk4J\build.xml

Maybe you didn't realize that was from your build.

After that, it runs the <javac/> task. That is, if there's any files to actually compile. Again, Ant tries to avoid work it doesn't have to do. If all of the *.java files have previously been compiled, the <javac/> task won't execute.

And, that's the end of the build. Your build might not have done anything simply because there was nothing to do. You can try running the clean task, and then build:

C:\Silk4J\Automation\iControlSilk4J> ant -d clean build

However, Ant usually prints the target being executed. You should have seen this:

init:

build-subprojects:

build-projects:

    [echo] iControlSilk4J: C:\Silk4J\Automation\iControlSilk4J\build.xml

build:

Build Successful

Note that the targets are all printed out in order they're executed, and the tasks are printed out as they are executed. However, if there's nothing to compile, or nothing to copy, then you won't see these tasks being executed. Does this look like your output? If so, it could be there's nothing to do.

  • If the bin directory already exists, <mkdir/> isn't going to execute.
  • If there are no non-Java files in src, or they have already been copied into bin, the <copy/> task won't execute.
  • If there are no Java file in your src directory, or they have already been compiled, the <java/> task won't run.

If you look at the output from the -d debug, you'll see Ant looking at a task, then explaining why a particular task wasn't executed. Plus, the debug option will explain how Ant decides what tasks to execute.

See if that helps.

Error: expected type-specifier before 'ClassName'

For future people struggling with a similar problem, the situation is that the compiler simply cannot find the type you are using (even if your Intelisense can find it).

This can be caused in many ways:

  • You forgot to #include the header that defines it.
  • Your inclusion guards (#ifndef BLAH_H) are defective (your #ifndef BLAH_H doesn't match your #define BALH_H due to a typo or copy+paste mistake).
  • Your inclusion guards are accidentally used twice (two separate files both using #define MYHEADER_H, even if they are in separate directories)
  • You forgot that you are using a template (eg. new Vector() should be new Vector<int>())
  • The compiler is thinking you meant one scope when really you meant another (For example, if you have NamespaceA::NamespaceB, AND a <global scope>::NamespaceB, if you are already within NamespaceA, it'll look in NamespaceA::NamespaceB and not bother checking <global scope>::NamespaceB) unless you explicitly access it.
  • You have a name clash (two entities with the same name, such as a class and an enum member).

To explicitly access something in the global namespace, prefix it with ::, as if the global namespace is a namespace with no name (e.g. ::MyType or ::MyNamespace::MyType).

useState set method not reflecting change immediately

// replace
return <p>hello</p>;
// with
return <p>{JSON.stringify(movies)}</p>;

Now you should see, that your code actually does work. What does not work is the console.log(movies). This is because movies points to the old state. If you move your console.log(movies) outside of useEffect, right above the return, you will see the updated movies object.

Ajax success function

The answer given above can't solve my problem.So I change async into false to get the alert message.

jQuery.ajax({
            type:"post",
            dataType:"json",
            async: false,
            url: myAjax.ajaxurl,
            data: {action: 'submit_data', info: info},
            success: function(data) {
                alert("Data was succesfully captured");
            },
        });

Can't ping a local VM from the host

I had the same issue. Fixed it by adding a static route on my host to my VM via the VMnet8 adapter:

route ADD VM_addr MASK 255.255.255.255 VMnet8_addr

As previously mentioned, you need a bridged connection.

How to debug external class library projects in visual studio?

NuGet references

Assume the -Project_A (produces project_a.dll) -Project_B (produces project_b.dll) and Project_B references to Project_A by NuGet packages then just copy project_a.dll , project_a.pdb to the folder Project_B/Packages. In effect that should be copied to the /bin.

Now debug Project_A. When code reaches the part where you need to call dll's method or events etc while debugging, press F11 to step into the dll's code.

Creating a new user and password with Ansible

Mxx's answer is correct but you the python crypt.crypt() method is not safe when different operating systems are involved (related to glibc hash algorithm used on your system.)

For example, It won't work if your generate your hash from MacOS and run a playbook on linux. In such case , You can use passlib (pip install passlib to install locally).

from passlib.hash import md5_crypt
python -c 'import crypt; print md5_crypt.encrypt("This is my Password,salt="SomeSalt")'
'$1$SomeSalt$UqddPX3r4kH3UL5jq5/ZI.'

In JavaScript, why is "0" equal to false, but when tested by 'if' it is not false by itself?

This is the reason why you should whenever possible use strict equality === or strict inequality !==

"100" == 100

true because this only checks value, not the data type

"100" === 100

false this checks value and data type

How to convert string into float in JavaScript?

Have you ever tried to do this? :p

var str = '3.8';ie
alert( +(str) + 0.2 );

+(string) will cast string into float.

Handy!

So in order to solve your problem, you can do something like this:

var floatValue = +(str.replace(/,/,'.'));

Printing all variables value from a class

If you are using Eclipse, this should be easy:

1.Press Alt+Shift+S

2.Choose "Generate toString()..."

Enjoy! You can have any template of toString()s.

This also works with getter/setters.

Validating URL in Java

There is a way to perform URL validation in strict accordance to standards in Java without resorting to third-party libraries:

boolean isValidURL(String url) {
  try {
    new URI(url).parseServerAuthority();
    return true;
  } catch (URISyntaxException e) {
    return false;
  }
}

The constructor of URI checks that url is a valid URI, and the call to parseServerAuthority ensures that it is a URL (absolute or relative) and not a URN.

SQL search multiple values in same field

This has been partially answered here: MySQL Like multiple values

I advise against

$search = explode( ' ', $search );

and input them directly into the SQL query as this makes prone to SQL inject via the search bar. You will have to escape the characters first in case they try something funny like: "--; DROP TABLE name;

$search = str_replace('"', "''", search );

But even that is not completely safe. You must try to use SQL prepared statements to be safer. Using the regular expression is much easier to build a function to prepare and create what you want.

function makeSQL_search_pattern($search) {
    search_pattern = false;
    //escape the special regex chars
    $search = str_replace('"', "''", $search);
    $search = str_replace('^', "\\^", $search);
    $search = str_replace('$', "\\$", $search);
    $search = str_replace('.', "\\.", $search);
    $search = str_replace('[', "\\[", $search);
    $search = str_replace(']', "\\]", $search);
    $search = str_replace('|', "\\|", $search);
    $search = str_replace('*', "\\*", $search);
    $search = str_replace('+', "\\+", $search);
    $search = str_replace('{', "\\{", $search);
    $search = str_replace('}', "\\}", $search);
    $search = explode(" ", $search);
    for ($i = 0; $i < count($search); $i++) {
        if ($i > 0 && $i < count($search) ) {
           $search_pattern .= "|";
        }
        $search_pattern .= $search[$i];
    }
    return search_pattern;
}

$search_pattern = makeSQL_search_pattern($search);
$sql_query = "SELECT name FROM Products WHERE name REGEXP :search LIMIT 6"
$stmt = pdo->prepare($sql_query);
$stmt->bindParam(":search", $search_pattern, PDO::PARAM_STR);
$stmt->execute();

I have not tested this code, but this is what I would do in your case. I hope this helps.

How can I make grep print the lines below and above each matching line?

Use -B, -A or -C option

grep --help
...
-B, --before-context=NUM  print NUM lines of leading context
-A, --after-context=NUM   print NUM lines of trailing context
-C, --context=NUM         print NUM lines of output context
-NUM                      same as --context=NUM
...

What does this format means T00:00:00.000Z?

Please use DateTimeFormatter ISO_DATE_TIME = DateTimeFormatter.ISO_DATE_TIME; instead of DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss") or any pattern

This fixed my problem Below

java.time.format.DateTimeParseException: Text '2019-12-18T19:00:00.000Z' could not be parsed at index 10

Is there a way to list open transactions on SQL Server 2000 database?

You can get all the information of active transaction by the help of below query

SELECT
trans.session_id AS [SESSION ID],
ESes.host_name AS [HOST NAME],login_name AS [Login NAME],
trans.transaction_id AS [TRANSACTION ID],
tas.name AS [TRANSACTION NAME],tas.transaction_begin_time AS [TRANSACTION 
BEGIN TIME],
tds.database_id AS [DATABASE ID],DBs.name AS [DATABASE NAME]
FROM sys.dm_tran_active_transactions tas
JOIN sys.dm_tran_session_transactions trans
ON (trans.transaction_id=tas.transaction_id)
LEFT OUTER JOIN sys.dm_tran_database_transactions tds
ON (tas.transaction_id = tds.transaction_id )
LEFT OUTER JOIN sys.databases AS DBs
ON tds.database_id = DBs.database_id
LEFT OUTER JOIN sys.dm_exec_sessions AS ESes
ON trans.session_id = ESes.session_id
WHERE ESes.session_id IS NOT NULL

and it will give below similar result enter image description here

and you close that transaction by the help below KILL query by refering session id

KILL 77

WARNING: API 'variant.getJavaCompile()' is obsolete and has been replaced with 'variant.getJavaCompileProvider()'

1) Add android.debug.obsoleteApi=true to your gradle.properties. It will show you which modules is affected by your the warning log.

2) Update these deprecated functions.

  • variant.javaCompile to variant.javaCompileProvider

  • variant.javaCompile.destinationDir to variant.javaCompileProvider.get().destinationDir

/etc/apt/sources.list" E212: Can't open file for writing

I referenced to Zsolt in level 2, I input:

:w !sudo tee % > /dev/null

and then in my situation, I still can't modify the file, so it prompted that add "!". so I input

:q! 

then it works

Disable browser 'Save Password' functionality

Since Internet Explorer 11 no longer supports autocomplete="off" for input type="password" fields (hopefully no other browsers will follow their lead), the cleanest approach (at the time of writing) seems to be making users submit their username and password in different pages, i.e. the user enters their username, submit, then enters their password and submit. The Bank Of America and HSBC Bank websites are using this, too.

Because the browser is unable to associate the password with a username, it will not offer to store passwords. This approach works in all major browsers (at the time of writing) and will function properly without the use of Javascript. The downsides are that it would be more troublesome for the user, and would take 2 postbacks for a login action instead of one, so it really depends on how secure your website needs to be.

Update: As mentioned in this comment by Gregory, Firefox will be following IE11's lead and ignore autocomplete="off" for password fields.

jQuery click event not working after adding class

Here is the another solution as well, the bind method.

$(document).bind('click', ".intro", function() {
    var liId = $(this).parent("li").attr("id");
    alert(liId);        
});

Cheers :)

Change directory in PowerShell

If your Folder inside a Drive contains spaces In Power Shell you can Simply Type the command then drive name and folder name within Single Quotes(''):

Set-Location -Path 'E:\FOLDER NAME'

The Screenshot is attached here

PKIX path building failed: unable to find valid certification path to requested target

Java 8 Solution: I just had this problem and solved it by adding the remote site's certificate to my Java keystore. My solution was based on the solution at the myshittycode blog, which was based on a previous solution in mykong's blog. These blog article solutions boil down to downloading a program called InstallCert, which is a Java class you can run from the command line to obtain the certificate. You then proceed to install the certificate in Java's keystore.

The InstallCert Readme worked perfectly for me. You just need to run the following commands:

  1. javac InstallCert.java
  2. java InstallCert [host]:[port] (Enter the given list number of the certificate you want to add in the list when you run the command - likely just 1)
  3. keytool -exportcert -alias [host]-1 -keystore jssecacerts -storepass changeit -file [host].cer
  4. sudo keytool -importcert -alias [host] -keystore [path to system keystore] -storepass changeit -file [host].cer

See the referenced README file for an example if need be.

Access restriction on class due to restriction on required library rt.jar?

Just change the order of build path libraries of your project. Right click on project>Build Path> Configure Build Path>Select Order and Export(Tab)>Change the order of the entries. I hope moving the "JRE System library" to the bottom will work. It worked so for me. Easy and simple....!!!

How do I use System.getProperty("line.separator").toString()?

Try

rows = tabDelimitedTable.split("[" + newLine + "]");

This should solve the regex problem.

Also not that important but return type of

System.getProperty("line.separator")

is String so no need to call toString().

Auto margins don't center image in page

there is a alternative to margin-left:auto; margin-right: auto; or margin:0 auto; for the ones that use position:absolute; this is how:
you set the left position of the element to 50% (left:50%;) but that will not center it correctly in order for the element to be centered correctly you need to give it a margin of minus half of it`s width, that will center your element perfectly

here is an example: http://jsfiddle.net/35ERq/3/

Minimum and maximum value of z-index?

My tests show that z-index: 2147483647 is the maximum value, tested on FF 3.0.1 for OS X. I discovered a integer overflow bug: if you type z-index: 2147483648 (which is 2147483647 + 1) the element just goes behind all other elements. At least the browser doesn't crash.

And the lesson to learn is that you should beware of entering too large values for the z-index property because they wrap around.

Python Serial: How to use the read or readline function to read more than 1 character at a time

I was reciving some date from my arduino uno (0-1023 numbers). Using code from 1337holiday, jwygralak67 and some tips from other sources:

import serial
import time

ser = serial.Serial(
    port='COM4',\
    baudrate=9600,\
    parity=serial.PARITY_NONE,\
    stopbits=serial.STOPBITS_ONE,\
    bytesize=serial.EIGHTBITS,\
        timeout=0)

print("connected to: " + ser.portstr)

#this will store the line
seq = []
count = 1

while True:
    for c in ser.read():
        seq.append(chr(c)) #convert from ANSII
        joined_seq = ''.join(str(v) for v in seq) #Make a string from array

        if chr(c) == '\n':
            print("Line " + str(count) + ': ' + joined_seq)
            seq = []
            count += 1
            break


ser.close()

TypeError: You provided an invalid object where a stream was expected. You can provide an Observable, Promise, Array, or Iterable

You will get the following error message too when you provide undefined or so to an operator which expects an Observable, eg. takeUntil.

TypeError: You provided an invalid object where a stream was expected. You can provide an Observable, Promise, Array, or Iterable 

Format an Excel column (or cell) as Text in C#?

I've recently battled with this problem as well, and I've learned two things about the above suggestions.

  1. Setting the numberFormatting to @ causes Excel to left-align the value, and read it as if it were text, however, it still truncates the leading zero.
  2. Adding an apostrophe at the beginning results in Excel treating it as text and retains the zero, and then applies the default text format, solving both problems.

The misleading aspect of this is that you now have a different value in the cell. Fortuately, when you copy/paste or export to CSV, the apostrophe is not included.

Conclusion: use the apostrophe, not the numberFormatting in order to retain the leading zeros.

Unable to copy file - access to the path is denied

In my case it was the antivirus which blocked the file.

How to grep a string in a directory and all its subdirectories?

If your grep supports -R, do:

grep -R 'string' dir/

If not, then use find:

find dir/ -type f -exec grep -H 'string' {} +

How to import a module given the full path?

I have wrote my own global and portable import function, based on importlib module, for:

  • Be able to import both module as a submodule and to import content of a module to a parent module (or into a globals if has no parent module).
  • Be able to import modules with a period characters in a file name.
  • Be able to import modules with any extension.
  • Be able to use a standalone name for a submodule instead of a file name without extension which is by default.
  • Be able to define the import order based on previously imported module instead of dependent on sys.path or on a what ever search path storage.

The examples directory structure:

<root>
 |
 +- test.py
 |
 +- testlib.py
 |
 +- /std1
 |   |
 |   +- testlib.std1.py
 |
 +- /std2
 |   |
 |   +- testlib.std2.py
 |
 +- /std3
     |
     +- testlib.std3.py

Inclusion dependency and order:

test.py
  -> testlib.py
    -> testlib.std1.py
      -> testlib.std2.py
    -> testlib.std3.py 

Implementation:

Latest changes store: https://sourceforge.net/p/tacklelib/tacklelib/HEAD/tree/trunk/python/tacklelib/tacklelib.py

test.py:

import os, sys, inspect, copy

SOURCE_FILE = os.path.abspath(inspect.getsourcefile(lambda:0)).replace('\\','/')
SOURCE_DIR = os.path.dirname(SOURCE_FILE)

print("test::SOURCE_FILE: ", SOURCE_FILE)

# portable import to the global space
sys.path.append(TACKLELIB_ROOT) # TACKLELIB_ROOT - path to the library directory
import tacklelib as tkl

tkl.tkl_init(tkl)

# cleanup
del tkl # must be instead of `tkl = None`, otherwise the variable would be still persist
sys.path.pop()

tkl_import_module(SOURCE_DIR, 'testlib.py')

print(globals().keys())

testlib.base_test()
testlib.testlib_std1.std1_test()
testlib.testlib_std1.testlib_std2.std2_test()
#testlib.testlib.std3.std3_test()                             # does not reachable directly ...
getattr(globals()['testlib'], 'testlib.std3').std3_test()     # ... but reachable through the `globals` + `getattr`

tkl_import_module(SOURCE_DIR, 'testlib.py', '.')

print(globals().keys())

base_test()
testlib_std1.std1_test()
testlib_std1.testlib_std2.std2_test()
#testlib.std3.std3_test()                                     # does not reachable directly ...
globals()['testlib.std3'].std3_test()                         # ... but reachable through the `globals` + `getattr`

testlib.py:

# optional for 3.4.x and higher
#import os, inspect
#
#SOURCE_FILE = os.path.abspath(inspect.getsourcefile(lambda:0)).replace('\\','/')
#SOURCE_DIR = os.path.dirname(SOURCE_FILE)

print("1 testlib::SOURCE_FILE: ", SOURCE_FILE)

tkl_import_module(SOURCE_DIR + '/std1', 'testlib.std1.py', 'testlib_std1')

# SOURCE_DIR is restored here
print("2 testlib::SOURCE_FILE: ", SOURCE_FILE)

tkl_import_module(SOURCE_DIR + '/std3', 'testlib.std3.py')

print("3 testlib::SOURCE_FILE: ", SOURCE_FILE)

def base_test():
  print('base_test')

testlib.std1.py:

# optional for 3.4.x and higher
#import os, inspect
#
#SOURCE_FILE = os.path.abspath(inspect.getsourcefile(lambda:0)).replace('\\','/')
#SOURCE_DIR = os.path.dirname(SOURCE_FILE)

print("testlib.std1::SOURCE_FILE: ", SOURCE_FILE)

tkl_import_module(SOURCE_DIR + '/../std2', 'testlib.std2.py', 'testlib_std2')

def std1_test():
  print('std1_test')

testlib.std2.py:

# optional for 3.4.x and higher
#import os, inspect
#
#SOURCE_FILE = os.path.abspath(inspect.getsourcefile(lambda:0)).replace('\\','/')
#SOURCE_DIR = os.path.dirname(SOURCE_FILE)

print("testlib.std2::SOURCE_FILE: ", SOURCE_FILE)

def std2_test():
  print('std2_test')

testlib.std3.py:

# optional for 3.4.x and higher
#import os, inspect
#
#SOURCE_FILE = os.path.abspath(inspect.getsourcefile(lambda:0)).replace('\\','/')
#SOURCE_DIR = os.path.dirname(SOURCE_FILE)

print("testlib.std3::SOURCE_FILE: ", SOURCE_FILE)

def std3_test():
  print('std3_test')

Output (3.7.4):

test::SOURCE_FILE:  <root>/test01/test.py
import : <root>/test01/testlib.py as testlib -> []
1 testlib::SOURCE_FILE:  <root>/test01/testlib.py
import : <root>/test01/std1/testlib.std1.py as testlib_std1 -> ['testlib']
import : <root>/test01/std1/../std2/testlib.std2.py as testlib_std2 -> ['testlib', 'testlib_std1']
testlib.std2::SOURCE_FILE:  <root>/test01/std1/../std2/testlib.std2.py
2 testlib::SOURCE_FILE:  <root>/test01/testlib.py
import : <root>/test01/std3/testlib.std3.py as testlib.std3 -> ['testlib']
testlib.std3::SOURCE_FILE:  <root>/test01/std3/testlib.std3.py
3 testlib::SOURCE_FILE:  <root>/test01/testlib.py
dict_keys(['__name__', '__doc__', '__package__', '__loader__', '__spec__', '__annotations__', '__builtins__', '__file__', '__cached__', 'os', 'sys', 'inspect', 'copy', 'SOURCE_FILE', 'SOURCE_DIR', 'TackleGlobalImportModuleState', 'tkl_membercopy', 'tkl_merge_module', 'tkl_get_parent_imported_module_state', 'tkl_declare_global', 'tkl_import_module', 'TackleSourceModuleState', 'tkl_source_module', 'TackleLocalImportModuleState', 'testlib'])
base_test
std1_test
std2_test
std3_test
import : <root>/test01/testlib.py as . -> []
1 testlib::SOURCE_FILE:  <root>/test01/testlib.py
import : <root>/test01/std1/testlib.std1.py as testlib_std1 -> ['testlib']
import : <root>/test01/std1/../std2/testlib.std2.py as testlib_std2 -> ['testlib', 'testlib_std1']
testlib.std2::SOURCE_FILE:  <root>/test01/std1/../std2/testlib.std2.py
2 testlib::SOURCE_FILE:  <root>/test01/testlib.py
import : <root>/test01/std3/testlib.std3.py as testlib.std3 -> ['testlib']
testlib.std3::SOURCE_FILE:  <root>/test01/std3/testlib.std3.py
3 testlib::SOURCE_FILE:  <root>/test01/testlib.py
dict_keys(['__name__', '__doc__', '__package__', '__loader__', '__spec__', '__annotations__', '__builtins__', '__file__', '__cached__', 'os', 'sys', 'inspect', 'copy', 'SOURCE_FILE', 'SOURCE_DIR', 'TackleGlobalImportModuleState', 'tkl_membercopy', 'tkl_merge_module', 'tkl_get_parent_imported_module_state', 'tkl_declare_global', 'tkl_import_module', 'TackleSourceModuleState', 'tkl_source_module', 'TackleLocalImportModuleState', 'testlib', 'testlib_std1', 'testlib.std3', 'base_test'])
base_test
std1_test
std2_test
std3_test

Tested in Python 3.7.4, 3.2.5, 2.7.16

Pros:

  • Can import both module as a submodule and can import content of a module to a parent module (or into a globals if has no parent module).
  • Can import modules with periods in a file name.
  • Can import any extension module from any extension module.
  • Can use a standalone name for a submodule instead of a file name without extension which is by default (for example, testlib.std.py as testlib, testlib.blabla.py as testlib_blabla and so on).
  • Does not depend on a sys.path or on a what ever search path storage.
  • Does not require to save/restore global variables like SOURCE_FILE and SOURCE_DIR between calls to tkl_import_module.
  • [for 3.4.x and higher] Can mix the module namespaces in nested tkl_import_module calls (ex: named->local->named or local->named->local and so on).
  • [for 3.4.x and higher] Can auto export global variables/functions/classes from where being declared to all children modules imported through the tkl_import_module (through the tkl_declare_global function).

Cons:

  • [for 3.3.x and lower] Require to declare tkl_import_module in all modules which calls to tkl_import_module (code duplication)

Update 1,2 (for 3.4.x and higher only):

In Python 3.4 and higher you can bypass the requirement to declare tkl_import_module in each module by declare tkl_import_module in a top level module and the function would inject itself to all children modules in a single call (it's a kind of self deploy import).

Update 3:

Added function tkl_source_module as analog to bash source with support execution guard upon import (implemented through the module merge instead of import).

Update 4:

Added function tkl_declare_global to auto export a module global variable to all children modules where a module global variable is not visible because is not a part of a child module.

Update 5:

All functions has moved into the tacklelib library, see the link above.

Remove all subviews?

In order to remove all subviews Syntax :

- (void)makeObjectsPerformSelector:(SEL)aSelector;

Usage :

[self.View.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];

This method is present in NSArray.h file and uses NSArray(NSExtendedArray) interface

Sorting objects by property values

javascript has the sort function which can take another function as parameter - that second function is used to compare two elements.

Example:

cars = [

    {
        name: "Honda",
        speed: 80
    },

    {
        name: "BMW",
        speed: 180
    },

    {
        name: "Trabi",
        speed: 40
    },

    {
        name: "Ferrari",
        speed: 200
    }
]


cars.sort(function(a, b) { 
    return a.speed - b.speed;
})

for(var i in cars)
    document.writeln(cars[i].name) // Trabi Honda BMW Ferrari 

ok, from your comment i see that you're using the word 'sort' in a wrong sense. In programming "sort" means "put things in a certain order", not "arrange things in groups". The latter is much simpler - this is just how you "sort" things in the real world

  • make two empty arrays ("boxes")
  • for each object in your list, check if it matches the criteria
  • if yes, put it in the first "box"
  • if no, put it in the second "box"

Is there a timeout for idle PostgreSQL connections?

In PostgreSQL 9.6, there's a new option idle_in_transaction_session_timeout which should accomplish what you describe. You can set it using the SET command, e.g.:

SET SESSION idle_in_transaction_session_timeout = '5min';

Is there a color code for transparent in HTML?

If you are looking for android apps, you can use

#00000000 

Can RDP clients launch remote applications and not desktops

At least on 2008R2 if the accounts are only used for RDP and not for local logins then you can set this on a per-account basis. That should work for thin clients. If the accounts are also used on local desktops then this would also affect those logins.

In ADUsers&Computers, open the properties for the account and go to the Environment tab. On that tab, check "Start the following program at logon" and specify the path and executable for the program.

Get User Selected Range

You can loop through the Selection object to see what was selected. Here is a code snippet from Microsoft (http://msdn.microsoft.com/en-us/library/aa203726(office.11).aspx):

Sub Count_Selection()
    Dim cell As Object
    Dim count As Integer
    count = 0
    For Each cell In Selection
        count = count + 1
    Next cell
    MsgBox count & " item(s) selected"
End Sub

Failed binder transaction when putting an bitmap dynamically in a widget

This is caused because all the changes to the RemoteViews are serialised (e.g. setInt and setImageViewBitmap ). The bitmaps are also serialised into an internal bundle. Unfortunately this bundle has a very small size limit.

You can solve it by scaling down the image size this way:

 public static Bitmap scaleDownBitmap(Bitmap photo, int newHeight, Context context) {

 final float densityMultiplier = context.getResources().getDisplayMetrics().density;        

 int h= (int) (newHeight*densityMultiplier);
 int w= (int) (h * photo.getWidth()/((double) photo.getHeight()));

 photo=Bitmap.createScaledBitmap(photo, w, h, true);

 return photo;
 }

Choose newHeight to be small enough (~100 for every square it should take on the screen) and use it for your widget, and your problem will be solved :)

creating array without declaring the size - java

Once the array size is fixed while running the program ,it's size can't be changed further. So better go for ArrayList while dealing with dynamic arrays.

How can I show/hide a specific alert with twitter bootstrap?

You need to use an id selector:

 //show
 $('#passwordsNoMatchRegister').show();
 //hide
 $('#passwordsNoMatchRegister').hide();

# is an id selector and passwordsNoMatchRegister is the id of the div.

How do I dynamically set the selected option of a drop-down list using jQuery, JavaScript and HTML?

Here it goes.

_x000D_
_x000D_
// Select by value_x000D_
$('select[name="options"]').find('option[value="3"]').attr("selected",true);_x000D_
_x000D_
// Select by text_x000D_
//$('select[name="options"]').find('option:contains("Third")').attr("selected",true);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<html>_x000D_
<body>_x000D_
<select name="options">_x000D_
      <option value="1">First</option>_x000D_
      <option value="2">Second</option>_x000D_
      <option value="3">Third</option>_x000D_
</select>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Enable/Disable Anchor Tags using AngularJS

You may, redefine the a tag using angular directive:

angular.module('myApp').directive('a', function() {
  return {
    restrict: 'E',
    link: function(scope, elem, attrs) {
      if ('disabled' in attrs) {
        elem.on('click', function(e) {
          e.preventDefault(); // prevent link click
        });
      }
    }
  };
});

In html:

<a href="nextPage" disabled>Next</a>

How to include a class in PHP

You can use either of the following:

include "class.twitter.php";

or

require "class.twitter.php";

Using require (or require_once if you want to ensure the class is only loaded once during execution) will cause a fatal error to be raised if the file doesn't exist, whereas include will only raise a warning. See http://php.net/require and http://php.net/include for more details

Wait .5 seconds before continuing code VB.net

Make a timer, that activates whatever code you want to when it ticks. Make sure the first line in the timer's code is:

timer.enabled = false

Replace timer with whatever you named your timer.

Then use this in your code:

   WebBrowser1.Document.Window.DomWindow.execscript("checkPasswordConfirm();","JavaScript")
timer.enabled = true
Dim allelements As HtmlElementCollection = WebBrowser1.Document.All
For Each webpageelement As HtmlElement In allelements
    If webpageelement.InnerText = "Sign Up" Then
        webpageelement.InvokeMember("click")
    End If
Next

Eclipse error: R cannot be resolved to a variable

I assume you have updated ADT with version 22 and R.java file is not getting generated.

If this is the case, then here is the solution:

Hope you know Android studio has gradle building tool. Same as in eclipse they have given new component in the Tools folder called Android SDK Build-tools that needs to be installed. Open the Android SDK Manager, select the newly added build tools, install it, restart the SDK Manager after the update.

enter image description here

Open File in Another Directory (Python)

If you know the full path to the file you can just do something similar to this. However if you question directly relates to relative paths, that I am unfamiliar with and would have to research and test.

path = 'C:\\Users\\Username\\Path\\To\\File'

with open(path, 'w') as f:
    f.write(data)

Edit:

Here is a way to do it relatively instead of absolute. Not sure if this works on windows, you will have to test it.

import os

cur_path = os.path.dirname(__file__)

new_path = os.path.relpath('..\\subfldr1\\testfile.txt', cur_path)
with open(new_path, 'w') as f:
    f.write(data)

Edit 2: One quick note about __file__, this will not work in the interactive interpreter due it being ran interactively and not from an actual file.

delete word after or around cursor in VIM

The below works for Normal mode: I agree with Dan Olson's answer that you should probably be in normal mode for most deletions. More details below.

If the cursor is inside the word:
diw to delete in the word (doesn't include spaces)
daw to delete around the word (includes spaces before the next word).

If the cursor is at the start of the word, just press dw.

This can be multiplied by adding the usual numbers for movement, e.g. 2w to move forward 2 words, so d2w deletes two words.

Insert Mode ^w
The idea of using hjkl for movement in Vim is that it's more productive to keep your hands on the home row. At the end of a word ^w works great to quickly delete the word. If you've gone into insert mode, entered some text and used the arrow keys to end up in the middle of the word you've gone against the home-row philosophy.
If you're in normal mode and want to change the word you can simply use the c (change) rather than d (delete) if you'd like to completely change the word, and re-enter insert mode without having to press i to get back to typing.

Insert php variable in a href

You could try:

<a href="<?php echo $directory ?>">The link to the file</a>

Or for PHP 5.4+ (<?= is the PHP short echo tag):

<a href="<?= $directory ?>">The link to the file</a>

But your path is relative to the server, don't forget that.

Java BigDecimal: Round to the nearest whole value

If i go by Grodriguez's answer

System.out.println("" + value);
value = value.setScale(0, BigDecimal.ROUND_HALF_UP);
System.out.println("" + value);

This is the output

100.23 -> 100
100.77 -> 101

Which isn't quite what i want, so i ended up doing this..

System.out.println("" + value);
value = value.setScale(0, BigDecimal.ROUND_HALF_UP);
value = value.setScale(2, BigDecimal.ROUND_HALF_UP);
System.out.println("" + value);

This is what i get

100.23 -> 100.00
100.77 -> 101.00

This solves my problem for now .. : ) Thank you all.

Select only rows if its value in a particular column is less than the value in the other column

If you use dplyr package you can do:

library(dplyr)
filter(df, aged <= laclen)

JSON find in JavaScript

If you are doing this in more than one place in your application it would make sense to use a client-side JSON database because creating custom search functions is messy and less maintainable than the alternative.

Check out ForerunnerDB which provides you with a very powerful client-side JSON database system and includes a very simple query language to help you do exactly what you are looking for:

// Create a new instance of ForerunnerDB and then ask for a database
var fdb = new ForerunnerDB(),
    db = fdb.db('myTestDatabase'),
    coll;

// Create our new collection (like a MySQL table) and change the default
// primary key from "_id" to "id"
coll = db.collection('myCollection', {primaryKey: 'id'});

// Insert our records into the collection
coll.insert([
    {"name":"my Name","id":12,"type":"car owner"},
    {"name":"my Name2","id":13,"type":"car owner2"},
    {"name":"my Name4","id":14,"type":"car owner3"},
    {"name":"my Name4","id":15,"type":"car owner5"}
]);

// Search the collection for the string "my nam" as a case insensitive
// regular expression - this search will match all records because every
// name field has the text "my Nam" in it
var searchResultArray = coll.find({
    name: /my nam/i
});

console.log(searchResultArray);

/* Outputs
[
    {"name":"my Name","id":12,"type":"car owner"},
    {"name":"my Name2","id":13,"type":"car owner2"},
    {"name":"my Name4","id":14,"type":"car owner3"},
    {"name":"my Name4","id":15,"type":"car owner5"}
]
*/

Disclaimer: I am the developer of ForerunnerDB.

TypeError: unsupported operand type(s) for -: 'str' and 'int'

  1. The reason this is failing is because (Python 3) input returns a string. To convert it to an integer, use int(some_string).

  2. You do not typically keep track of indices manually in Python. A better way to implement such a function would be

    def cat_n_times(s, n):
        for i in range(n):
            print(s) 
    
    text = input("What would you like the computer to repeat back to you: ")
    num = int(input("How many times: ")) # Convert to an int immediately.
    
    cat_n_times(text, num)
    
  3. I changed your API above a bit. It seems to me that n should be the number of times and s should be the string.

How to locate the Path of the current project directory in Java (IDE)?

Use user.dir key for get project location using java.

Code:

System.out.println("Present Project Directory : "+ System.getProperty("user.dir"));

OutPut:

Present Project Directory :C:\workspace\MyEclipse 10\examples\MySqlMavenDomain

For displaying all systems properties simply use System.getProperties();

Use Key value in System.getProperty("java.version"); for get output.

Code:

Properties properties = System.getProperties();
Enumeration<Object> enumeration = properties.keys();
for (int i = 0; i < properties.size(); i++) {
    Object obj = enumeration.nextElement();
    System.out.println("Key: "+obj+"\tOutPut= "+System.getProperty(obj.toString()));
}

OutPut:

Key: java.runtime.name  OutPut= Java(TM) SE Runtime Environment
Key: sun.boot.library.path  OutPut= C:\Program Files\Java\jdk1.7.0_45\jre\bin
Key: java.vm.version    OutPut= 24.45-b08
Key: java.vm.vendor OutPut= Oracle Corporation
Key: java.vendor.url    OutPut= http://java.oracle.com/
Key: path.separator OutPut= ;
Key: java.vm.name   OutPut= Java HotSpot(TM) Client VM
Key: file.encoding.pkg  OutPut= sun.io
Key: user.country   OutPut= US
Key: user.script    OutPut= 
Key: sun.java.launcher  OutPut= SUN_STANDARD
Key: sun.os.patch.level OutPut= Service Pack 3
Key: java.vm.specification.name OutPut= Java Virtual Machine Specification
Key: user.dir   OutPut= C:\workspace\MyEclipse 10\examples\MySqlMavenDomain
Key: java.runtime.version   OutPut= 1.7.0_45-b18
Key: java.awt.graphicsenv   OutPut= sun.awt.Win32GraphicsEnvironment
Key: java.endorsed.dirs OutPut= C:\Program Files\Java\jdk1.7.0_45\jre\lib\endorsed
Key: os.arch    OutPut= x86
Key: java.io.tmpdir OutPut= C:\DOCUME~1\UDAYP~2.PBS\LOCALS~1\Temp\
Key: line.separator OutPut= 

Key: java.vm.specification.vendor   OutPut= Oracle Corporation
Key: user.variant   OutPut= 
Key: os.name    OutPut= Windows XP
Key: sun.jnu.encoding   OutPut= Cp1252
Key: java.library.path  OutPut= C:\Program Files\Java\jdk1.7.0_45\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:/Program Files/MyEclipse/Common/binary/com.sun.java.jdk.win32.x86_1.6.0.013/jre/bin/client;C:/Program Files/MyEclipse/Common/binary/com.sun.java.jdk.win32.x86_1.6.0.013/jre/bin;C:/Program Files/MyEclipse/Common/binary/com.sun.java.jdk.win32.x86_1.6.0.013/jre/lib/i386;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\system32\WindowsPowerShell\v1.0;D:\Program Files\Microsoft SQL Server\100\Tools\Binn\VSShell\Common7\IDE\;D:\Program Files\Microsoft SQL Server\100\Tools\Binn\;D:\Program Files\Microsoft SQL Server\100\DTS\Binn\;.
Key: java.specification.name    OutPut= Java Platform API Specification
Key: java.class.version OutPut= 51.0
Key: sun.management.compiler    OutPut= HotSpot Client Compiler
Key: os.version OutPut= 5.1
Key: user.home  OutPut= C:\Documents and Settings\uday.p.PBSYSTEMS
Key: user.timezone  OutPut= 
Key: java.awt.printerjob    OutPut= sun.awt.windows.WPrinterJob
Key: file.encoding  OutPut= UTF-8
Key: java.specification.version OutPut= 1.7
Key: java.class.path    OutPut= C:\workspace\MyEclipse 10\examples\MySqlMavenDomain\target\test-classes;C:\workspace\MyEclipse 10\examples\MySqlMavenDomain\target\classes;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\jstl\jstl\1.2\jstl-1.2.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\javax\servlet\javax.servlet-api\3.1.0\javax.servlet-api-3.1.0.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\mysql\mysql-connector-java\5.1.28\mysql-connector-java-5.1.28.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\javax\mail\mail\1.4.7\mail-1.4.7.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\javax\activation\activation\1.1\activation-1.1.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\junit\junit\4.11\junit-4.11.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\org\hamcrest\hamcrest-core\1.3\hamcrest-core-1.3.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\org\hibernate\hibernate-core\4.3.0.Final\hibernate-core-4.3.0.Final.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\org\jboss\logging\jboss-logging\3.1.3.GA\jboss-logging-3.1.3.GA.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\org\jboss\logging\jboss-logging-annotations\1.2.0.Beta1\jboss-logging-annotations-1.2.0.Beta1.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\org\jboss\spec\javax\transaction\jboss-transaction-api_1.2_spec\1.0.0.Final\jboss-transaction-api_1.2_spec-1.0.0.Final.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\dom4j\dom4j\1.6.1\dom4j-1.6.1.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\xml-apis\xml-apis\1.0.b2\xml-apis-1.0.b2.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\org\hibernate\common\hibernate-commons-annotations\4.0.4.Final\hibernate-commons-annotations-4.0.4.Final.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\org\hibernate\javax\persistence\hibernate-jpa-2.1-api\1.0.0.Final\hibernate-jpa-2.1-api-1.0.0.Final.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\org\javassist\javassist\3.18.1-GA\javassist-3.18.1-GA.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\antlr\antlr\2.7.7\antlr-2.7.7.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\org\jboss\jandex\1.1.0.Final\jandex-1.1.0.Final.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\org\hibernate\hibernate-entitymanager\4.3.0.Final\hibernate-entitymanager-4.3.0.Final.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\commons-dbcp\commons-dbcp\1.4\commons-dbcp-1.4.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\commons-fileupload\commons-fileupload\1.3\commons-fileupload-1.3.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\commons-io\commons-io\2.4\commons-io-2.4.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\commons-net\commons-net\3.3\commons-net-3.3.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\commons-codec\commons-codec\1.9\commons-codec-1.9.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\commons-pool\commons-pool\1.6\commons-pool-1.6.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\commons-collections\commons-collections\3.2.1\commons-collections-3.2.1.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\commons-logging\commons-logging\1.1.3\commons-logging-1.1.3.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\commons-beanutils\commons-beanutils\1.9.0\commons-beanutils-1.9.0.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\org\apache\commons\commons-lang3\3.1\commons-lang3-3.1.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\log4j\log4j\1.2.16\log4j-1.2.16.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\org\springframework\spring-orm\3.2.6.RELEASE\spring-orm-3.2.6.RELEASE.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\aopalliance\aopalliance\1.0\aopalliance-1.0.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\org\springframework\spring-jdbc\3.2.6.RELEASE\spring-jdbc-3.2.6.RELEASE.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\org\springframework\spring-tx\3.2.6.RELEASE\spring-tx-3.2.6.RELEASE.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\org\springframework\spring-web\3.2.6.RELEASE\spring-web-3.2.6.RELEASE.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\org\springframework\spring-aop\3.2.6.RELEASE\spring-aop-3.2.6.RELEASE.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\org\springframework\spring-webmvc\3.2.6.RELEASE\spring-webmvc-3.2.6.RELEASE.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\org\springframework\spring-aspects\3.2.6.RELEASE\spring-aspects-3.2.6.RELEASE.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\org\aspectj\aspectjweaver\1.7.2\aspectjweaver-1.7.2.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\org\springframework\spring-beans\3.2.6.RELEASE\spring-beans-3.2.6.RELEASE.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\org\springframework\spring-context\3.2.6.RELEASE\spring-context-3.2.6.RELEASE.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\org\springframework\spring-context-support\3.2.6.RELEASE\spring-context-support-3.2.6.RELEASE.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\org\springframework\spring-core\3.2.6.RELEASE\spring-core-3.2.6.RELEASE.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\org\springframework\spring-expression\3.2.6.RELEASE\spring-expression-3.2.6.RELEASE.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\org\springframework\spring-instrument\3.2.6.RELEASE\spring-instrument-3.2.6.RELEASE.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\org\springframework\spring-instrument-tomcat\3.2.6.RELEASE\spring-instrument-tomcat-3.2.6.RELEASE.jar
Key: user.name  OutPut= uday.p
Key: java.vm.specification.version  OutPut= 1.7
Key: sun.java.command   OutPut= com.uk.mysqlmaven.domain.test.UserLoginDetails
Key: java.home  OutPut= C:\Program Files\Java\jdk1.7.0_45\jre
Key: sun.arch.data.model    OutPut= 32
Key: user.language  OutPut= en
Key: java.specification.vendor  OutPut= Oracle Corporation
Key: awt.toolkit    OutPut= sun.awt.windows.WToolkit
Key: java.vm.info   OutPut= mixed mode, sharing
Key: java.version   OutPut= 1.7.0_45
Key: java.ext.dirs  OutPut= C:\Program Files\Java\jdk1.7.0_45\jre\lib\ext;C:\WINDOWS\Sun\Java\lib\ext
Key: sun.boot.class.path    OutPut= C:\Program Files\Java\jdk1.7.0_45\jre\lib\resources.jar;C:\Program Files\Java\jdk1.7.0_45\jre\lib\rt.jar;C:\Program Files\Java\jdk1.7.0_45\jre\lib\sunrsasign.jar;C:\Program Files\Java\jdk1.7.0_45\jre\lib\jsse.jar;C:\Program Files\Java\jdk1.7.0_45\jre\lib\jce.jar;C:\Program Files\Java\jdk1.7.0_45\jre\lib\charsets.jar;C:\Program Files\Java\jdk1.7.0_45\jre\lib\jfr.jar;C:\Program Files\Java\jdk1.7.0_45\jre\classes
Key: java.vendor    OutPut= Oracle Corporation
Key: file.separator OutPut= \
Key: java.vendor.url.bug    OutPut= http://bugreport.sun.com/bugreport/
Key: sun.io.unicode.encoding    OutPut= UnicodeLittle
Key: sun.cpu.endian OutPut= little
Key: sun.desktop    OutPut= windows
Key: sun.cpu.isalist    OutPut= pentium_pro+mmx pentium_pro pentium+mmx pentium i486 i386 i86

For more details refer Class System

ant build.xml file doesn't exist

You have invoked Ant with the verbose (-v) mode but the default buildfile build.xml does not exist. Nor have you specified any other buildfile for it to use.

I would say your Ant installation is fine.

How to open new browser window on button click event?

It can be done all on the client-side using the OnClientClick[MSDN] event handler and window.open[MDN]:

<asp:Button 
     runat="server" 
     OnClientClick="window.open('http://www.stackoverflow.com'); return false;">
     Open a new window!
</asp:Button>

What datatype to use when storing latitude and longitude data in SQL databases?

I would use a decimal with the proper precision for your data.

Why is my power operator (^) not working?

include math.h and compile with gcc test.c -lm

How to concatenate and minify multiple CSS and JavaScript files with Grunt.js (0.3.x)

I want to mention here a very, VERY, interesting technique that is being used in huge projects like jQuery and Modernizr for concatenate things.

Both of this projects are entirely developed with requirejs modules (you can see that in their github repos) and then they use the requirejs optimizer as a very smart concatenator. The interesting thing is that, as you can see, nor jQuery neither Modernizr needs on requirejs to work, and this happen because they erase the requirejs syntatic ritual in order to get rid of requirejs in their code. So they end up with a standalone library that was developed with requirejs modules! Thanks to this they are able to perform cutsom builds of their libraries, among other advantages.

For all those interested in concatenation with the requirejs optimizer, check out this post

Also there is a small tool that abstracts all the boilerplate of the process: AlbanilJS

How do I turn off Oracle password expiration?

I will suggest its not a good idea to turn off the password expiration as it can lead to possible threats to confidentiality, integrity and availability of data.

However if you want so.

If you have proper access use following SQL

SELECT username, account_status FROM dba_users;

This should give you result like this.

   USERNAME                       ACCOUNT_STATUS
------------------------------ -----------------

SYSTEM                         OPEN
SYS                            OPEN
SDMADM                         OPEN
MARKETPLACE                    OPEN
SCHEMAOWNER                    OPEN
ANONYMOUS                      OPEN
SCHEMAOWNER2                   OPEN
SDMADM2                        OPEN
SCHEMAOWNER1                   OPEN
SDMADM1                        OPEN
HR                             EXPIRED(GRACE)

USERNAME                       ACCOUNT_STATUS
------------------------------ -----------------

APEX_PUBLIC_USER               LOCKED
APEX_040000                    LOCKED
FLOWS_FILES                    LOCKED
XS$NULL                        EXPIRED & LOCKED
OUTLN                          EXPIRED & LOCKED
XDB                            EXPIRED & LOCKED
CTXSYS                         EXPIRED & LOCKED
MDSYS                          EXPIRED & LOCKED

Now you can use Pedro Carriço answer https://stackoverflow.com/a/6777079/2432468

How to turn on WCF tracing?

Instead of you manual adding the tracing enabling bit into web.config you can also try using the WCF configuration editor which comes with VS SDK to enable tracing

https://stackoverflow.com/a/16715631/2218571

How do I publish a UDP Port on Docker?

Use the -p flag and add /udp suffix to the port number.

-p 53160:53160/udp

Full command

sudo docker run -p 53160:53160 \
    -p 53160:53160/udp -p 58846:58846 \ 
    -p 8112:8112 -t -i aostanin/deluge /start.sh

If you're running boot2docker on Mac, be sure to forward the same ports on boot2docker to your local machine.

You can also document that your container needs to receive UDP using EXPOSE in The Dockerfile (EXPOSE does not publish the port):

EXPOSE 8285/udp

Here is a link with more Docker Networking info covered in the container docs: https://docs.docker.com/config/containers/container-networking/ (Courtesy of Old Pro in the comments)

Force browser to download image files on click

Update Spring 2018

<a href="/path/to/image.jpg" download="FileName.jpg">

While this is still supported, as of February 2018 chrome disabled this feature for cross-origin downloading meaning this will only work if the file is located on the same domain name.

I figured out a workaround for downloading cross domain images after Chrome's new update which disabled cross domain downloading. You could modify this into a function to suit your needs. You might be able to get the image mime-type (jpeg,png,gif,etc) with some more research if you needed to. There may be a way to do something similar to this with videos as well. Hope this helps someone!

Leeroy & Richard Parnaby-King:

UPDATE: As of spring 2018 this is no longer possible for cross-origin hrefs. So if you want to create on a domain other than imgur.com it will not work as intended. Chrome deprecations and removals announcement

_x000D_
_x000D_
var image = new Image();_x000D_
image.crossOrigin = "anonymous";_x000D_
image.src = "https://is3-ssl.mzstatic.com/image/thumb/Music62/v4/4b/f6/a2/4bf6a267-5a59-be4f-6947-d803849c6a7d/source/200x200bb.jpg";_x000D_
// get file name - you might need to modify this if your image url doesn't contain a file extension otherwise you can set the file name manually_x000D_
var fileName = image.src.split(/(\\|\/)/g).pop();_x000D_
image.onload = function () {_x000D_
    var canvas = document.createElement('canvas');_x000D_
    canvas.width = this.naturalWidth; // or 'width' if you want a special/scaled size_x000D_
    canvas.height = this.naturalHeight; // or 'height' if you want a special/scaled size_x000D_
    canvas.getContext('2d').drawImage(this, 0, 0);_x000D_
    var blob;_x000D_
    // ... get as Data URI_x000D_
    if (image.src.indexOf(".jpg") > -1) {_x000D_
    blob = canvas.toDataURL("image/jpeg");_x000D_
    } else if (image.src.indexOf(".png") > -1) {_x000D_
    blob = canvas.toDataURL("image/png");_x000D_
    } else if (image.src.indexOf(".gif") > -1) {_x000D_
    blob = canvas.toDataURL("image/gif");_x000D_
    } else {_x000D_
    blob = canvas.toDataURL("image/png");_x000D_
    }_x000D_
    $("body").html("<b>Click image to download.</b><br><a download='" + fileName + "' href='" + blob + "'><img src='" + blob + "'/></a>");_x000D_
};
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

How to align two elements on the same line without changing HTML

Change your css as below

#element1 {float:left;margin-right:10px;} 
#element2 {float:left;} 

Here is the JSFiddle http://jsfiddle.net/a4aME/

Git will not init/sync/update new submodules

I had the same problem today and figured out that because I typed git submodule init then I had those line in my .git/config:

[submodule]
   active = .

I removed that and typed:

git submodule update --init --remote

And everything was back to normal, my submodule updated in its subdirectory as usual.

How to duplicate a git repository? (without forking)

If you just want to create a new repository using all or most of the files from an existing one (i.e., as a kind of template), I find the easiest approach is to make a new repo with the desired name etc, clone it to your desktop, then just add the files and folders you want in it.

You don't get all the history etc, but you probably don't want that in this case.

How to detect Ctrl+V, Ctrl+C using JavaScript?

There is some ways to prevent it.

However the user will be always able to turn the javascript off or just look on the source code of the page.

Some examples (require jQuery)

/**
* Stop every keystroke with ctrl key pressed
*/
$(".textbox").keydown(function(){
    if (event.ctrlKey==true) {
        return false;
    }
});

/**
* Clear all data of clipboard on focus
*/
$(".textbox").focus(function(){
    if ( window.clipboardData ) {
        window.clipboardData.setData('text','');
    }
});

/**
* Block the paste event
*/
$(".textbox").bind('paste',function(e){return false;});

Edit: How Tim Down said, this functions are all browser dependents.

How do I display todays date on SSRS report?

date column 1:

=formatdatetime(today)

Node.js: get path from the request

simply call req.url. that should do the work. you'll get something like /something?bla=foo

Set up adb on Mac OS X

Note: this was originally written on Installing ADB on macOS but that question was closed as a duplicate of this one.

Note for zsh users: replace all references to ~/.bash_profile with ~/.zshrc.

Option 1 - Using Homebrew

This is the easiest way and will provide automatic updates.

  1. Install homebrew

     /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"
    
  2. Install adb

      brew install android-platform-tools
    
  3. Start using adb

     adb devices
    

Option 2 - Manually (just the platform tools)

This is the easiest way to get a manual installation of ADB and Fastboot.

  1. Delete your old installation (optional)

     rm -rf ~/.android-sdk-macosx/
    
  2. Navigate to https://developer.android.com/studio/releases/platform-tools.html and click on the SDK Platform-Tools for Mac link.

  3. Go to your Downloads folder

     cd ~/Downloads/
    
  4. Unzip the tools you downloaded

     unzip platform-tools-latest*.zip 
    
  5. Move them somewhere you won't accidentally delete them

     mkdir ~/.android-sdk-macosx
     mv platform-tools/ ~/.android-sdk-macosx/platform-tools
    
  6. Add platform-tools to your path

     echo 'export PATH=$PATH:~/.android-sdk-macosx/platform-tools/' >> ~/.bash_profile
    
  7. Refresh your bash profile (or restart your terminal app)

     source ~/.bash_profile
    
  8. Start using adb

     adb devices
    

Option 3 - If you already have Android Studio installed

  1. Add platform-tools to your path

     echo 'export ANDROID_HOME=/Users/$USER/Library/Android/sdk' >> ~/.bash_profile
     echo 'export PATH=${PATH}:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools' >> ~/.bash_profile
    
  2. Refresh your bash profile (or restart your terminal app)

     source ~/.bash_profile
    
  3. Start using adb

     adb devices
    

Option 4 - MacPorts

  1. Install the Android SDK:

     sudo port install android
    
  2. Run the SDK manager:

     sh /opt/local/share/java/android-sdk-macosx/tools/android
    
  3. Uncheck everything but Android SDK Platform-tools (optional)

  4. Install the packages, accepting licenses. Close the SDK Manager.

  5. Add platform-tools to your path; in MacPorts, they're in /opt/local/share/java/android-sdk-macosx/platform-tools. E.g., for bash:

     echo 'export PATH=$PATH:/opt/local/share/java/android-sdk-macosx/platform-tools' >> ~/.bash_profile
    
  6. Refresh your bash profile (or restart your terminal/shell):

    source ~/.bash_profile
    
  7. Start using adb:

    adb devices
    

Option 5 - Manually (with SDK Manager)

  1. Delete your old installation (optional)

     rm -rf ~/.android-sdk-macosx/
    
  2. Download the Mac SDK Tools from the Android developer site under "Get just the command line tools". Make sure you save them to your Downloads folder.

  3. Go to your Downloads folder

     cd ~/Downloads/
    
  4. Unzip the tools you downloaded

     unzip tools_r*-macosx.zip 
    
  5. Move them somewhere you won't accidentally delete them

     mkdir ~/.android-sdk-macosx
     mv tools/ ~/.android-sdk-macosx/tools
    
  6. Run the SDK Manager

     sh ~/.android-sdk-macosx/tools/android
    
  7. Uncheck everything but Android SDK Platform-tools (optional)

enter image description here

  1. Click Install Packages, accept licenses, click Install. Close the SDK Manager window.

enter image description here

  1. Add platform-tools to your path

     echo 'export PATH=$PATH:~/.android-sdk-macosx/platform-tools/' >> ~/.bash_profile
    
  2. Refresh your bash profile (or restart your terminal app)

    source ~/.bash_profile
    
  3. Start using adb

    adb devices
    

socket.error:[errno 99] cannot assign requested address and namespace in python

This error will also appear if you try to connect to an exposed port from within a Docker container, when nothing is actively serving the port.

On a host where nothing is listening/bound to that port you'd get a No connection could be made because the target machine actively refused it error instead when making a request to a local URL that is not served, eg: localhost:5000. However, if you start a container that binds to the port, but there is no server running inside of it actually serving the port, any requests to that port on localhost will result in:

  • [Errno 99] Cannot assign requested address (if called from within the container), or
  • [Errno 0] Error (if called from outside of the container).

You can reproduce this error and the behaviour described above as follows:

Start a dummy container (note: this will pull the python image if not found locally):

docker run --name serv1 -p 5000:5000 -dit python

Then for [Errno 0] Error enter a Python console on host, while for [Errno 99] Cannot assign requested address access a Python console on the container by calling:

docker exec -it -u 0 serv1 python

And then in either case call:

import urllib.request
urllib.request.urlopen('https://localhost:5000')

I concluded with treating either of these errors as equivalent to No connection could be made because the target machine actively refused it rather than trying to fix their cause - although please advise if that's a bad idea.


I've spent over a day figuring this one out, given that all resources and answers I could find on the [Errno 99] Cannot assign requested address point in the direction of binding to an occupied port, connecting to an invalid IP, sysctl conflicts, docker network issues, TIME_WAIT being incorrect, and many more things. Therefore I wanted to leave this answer here, despite not being a direct answer to the question at hand, given that it can be a common cause for the error described in this question.

Getting an odd error, SQL Server query using `WITH` clause

It should be legal to put a semicolon directly before the WITH keyword.

Python Timezone conversion

import datetime
import pytz

def convert_datetime_timezone(dt, tz1, tz2):
    tz1 = pytz.timezone(tz1)
    tz2 = pytz.timezone(tz2)

    dt = datetime.datetime.strptime(dt,"%Y-%m-%d %H:%M:%S")
    dt = tz1.localize(dt)
    dt = dt.astimezone(tz2)
    dt = dt.strftime("%Y-%m-%d %H:%M:%S")

    return dt

-

  • dt: date time string
  • tz1: initial time zone
  • tz2: target time zone

-

> convert_datetime_timezone("2017-05-13 14:56:32", "Europe/Berlin", "PST8PDT")
'2017-05-13 05:56:32'

> convert_datetime_timezone("2017-05-13 14:56:32", "Europe/Berlin", "UTC")
'2017-05-13 12:56:32'

-

> pytz.all_timezones[0:10]
['Africa/Abidjan',
 'Africa/Accra',
 'Africa/Addis_Ababa',
 'Africa/Algiers',
 'Africa/Asmara',
 'Africa/Asmera',
 'Africa/Bamako',
 'Africa/Bangui',
 'Africa/Banjul',
 'Africa/Bissau']

Watch multiple $scope attributes

Here's a solution very similar to your original pseudo-code that actually works:

$scope.$watch('[item1, item2] | json', function () { });

EDIT: Okay, I think this is even better:

$scope.$watch('[item1, item2]', function () { }, true);

Basically we're skipping the json step, which seemed dumb to begin with, but it wasn't working without it. They key is the often omitted 3rd parameter which turns on object equality as opposed to reference equality. Then the comparisons between our created array objects actually work right.

TreeMap sort by value

polygenelubricants answer is almost perfect. It has one important bug though. It will not handle map entries where the values are the same.

This code:...

Map<String, Integer> nonSortedMap = new HashMap<String, Integer>();
nonSortedMap.put("ape", 1);
nonSortedMap.put("pig", 3);
nonSortedMap.put("cow", 1);
nonSortedMap.put("frog", 2);

for (Entry<String, Integer> entry  : entriesSortedByValues(nonSortedMap)) {
    System.out.println(entry.getKey()+":"+entry.getValue());
}

Would output:

ape:1
frog:2
pig:3

Note how our cow dissapeared as it shared the value "1" with our ape :O!

This modification of the code solves that issue:

static <K,V extends Comparable<? super V>> SortedSet<Map.Entry<K,V>> entriesSortedByValues(Map<K,V> map) {
        SortedSet<Map.Entry<K,V>> sortedEntries = new TreeSet<Map.Entry<K,V>>(
            new Comparator<Map.Entry<K,V>>() {
                @Override public int compare(Map.Entry<K,V> e1, Map.Entry<K,V> e2) {
                    int res = e1.getValue().compareTo(e2.getValue());
                    return res != 0 ? res : 1; // Special fix to preserve items with equal values
                }
            }
        );
        sortedEntries.addAll(map.entrySet());
        return sortedEntries;
    }

How do I reference a local image in React?

Step 1 : import MyIcon from './img/icon.png'

step 2 :

<img
    src={MyIcon}
    style={{width:'100%', height:'100%'}}
/>    

Lodash .clone and .cloneDeep behaviors

Thanks to Gruff Bunny and Louis' comments, I found the source of the issue.

As I use Backbone.js too, I loaded a special build of Lodash compatible with Backbone and Underscore that disables some features. In this example:

var clone = _.clone(data, true);

data[1].values.d = 'x';

I just replaced the Underscore build with the Normal build in my Backbone application and the application is still working. So I can now use the Lodash .clone with the expected behaviour.

Edit 2018: the Underscore build doesn't seem to exist anymore. If you are reading this in 2018, you could be interested by this documentation (Backbone and Lodash).

Boxplot in R showing the mean

I also think chart.Boxplot is the best option, it gives you the position of the mean but if you have a matrix with returns all you need is one line of code to get all the boxplots in one graph.

Here is a small ETF portfolio example.

library(zoo)
library(PerformanceAnalytics)
library(tseries)
library(xts)

VTI.prices = get.hist.quote(instrument = "VTI", start= "2007-03-01", end="2013-03-01",
                        quote = c("AdjClose"),provider = "yahoo",origin ="1970-01-01", 
                        compression = "m", retclass = c("zoo"))

VEU.prices = get.hist.quote(instrument = "VEU", start= "2007-03-01", end="2013-03-01",
                        quote = c("AdjClose"),provider = "yahoo",origin ="1970-01-01", 
                        compression = "m", retclass = c("zoo"))

VWO.prices = get.hist.quote(instrument = "VWO", start= "2007-03-01", end="2013-03-01",
                        quote = c("AdjClose"),provider = "yahoo",origin ="1970-01-01", 
                        compression = "m", retclass = c("zoo"))


VNQ.prices = get.hist.quote(instrument = "VNQ", start= "2007-03-01", end="2013-03-01",
                       quote = c("AdjClose"),provider = "yahoo",origin ="1970-01-01", 
                       compression = "m", retclass = c("zoo"))

TLT.prices = get.hist.quote(instrument = "TLT", start= "2007-03-01", end="2013-03-01",
                        quote = c("AdjClose"),provider = "yahoo",origin ="1970-01-01", 
                        compression = "m", retclass = c("zoo"))

TIP.prices = get.hist.quote(instrument = "TIP", start= "2007-03-01", end="2013-03-01",
                         quote = c("AdjClose"),provider = "yahoo",origin ="1970-01-01", 
                         compression = "m", retclass = c("zoo"))

index(VTI.prices) = as.yearmon(index(VTI.prices))
index(VEU.prices) = as.yearmon(index(VEU.prices))
index(VWO.prices) = as.yearmon(index(VWO.prices))

index(VNQ.prices) = as.yearmon(index(VNQ.prices))
index(TLT.prices) = as.yearmon(index(TLT.prices))
index(TIP.prices) = as.yearmon(index(TIP.prices))

Prices.z=merge(VTI.prices, VEU.prices, VWO.prices, VNQ.prices, 
           TLT.prices, TIP.prices)

colnames(Prices.z) = c("VTI", "VEU", "VWO" , "VNQ", "TLT", "TIP")

returnscc.z = diff(log(Prices.z))

start(returnscc.z)
end(returnscc.z)
colnames(returnscc.z) 
head(returnscc.z)

Return Matrix

ret.mat = coredata(returnscc.z)
class(ret.mat)
colnames(ret.mat)
head(ret.mat)

Box Plot of Return Matrix

chart.Boxplot(returnscc.z, names=T, horizontal=TRUE, colorset="darkgreen", as.Tufte =F,
          mean.symbol = 20, median.symbol="|", main="Return Distributions Comparison",
          element.color = "darkgray", outlier.symbol = 20, 
          xlab="Continuously Compounded Returns", sort.ascending=F)

You can try changing the mean.symbol, and remove or change the median.symbol. Hope it helped. :)

How to convert string to binary?

If by binary you mean bytes type, you can just use encode method of the string object that encodes your string as a bytes object using the passed encoding type. You just need to make sure you pass a proper encoding to encode function.

In [9]: "hello world".encode('ascii')                                                                                                                                                                       
Out[9]: b'hello world'

In [10]: byte_obj = "hello world".encode('ascii')                                                                                                                                                           

In [11]: byte_obj                                                                                                                                                                                           
Out[11]: b'hello world'

In [12]: byte_obj[0]                                                                                                                                                                                        
Out[12]: 104

Otherwise, if you want them in form of zeros and ones --binary representation-- as a more pythonic way you can first convert your string to byte array then use bin function within map :

>>> st = "hello world"
>>> map(bin,bytearray(st))
['0b1101000', '0b1100101', '0b1101100', '0b1101100', '0b1101111', '0b100000', '0b1110111', '0b1101111', '0b1110010', '0b1101100', '0b1100100']
 

Or you can join it:

>>> ' '.join(map(bin,bytearray(st)))
'0b1101000 0b1100101 0b1101100 0b1101100 0b1101111 0b100000 0b1110111 0b1101111 0b1110010 0b1101100 0b1100100'

Note that in python3 you need to specify an encoding for bytearray function :

>>> ' '.join(map(bin,bytearray(st,'utf8')))
'0b1101000 0b1100101 0b1101100 0b1101100 0b1101111 0b100000 0b1110111 0b1101111 0b1110010 0b1101100 0b1100100'

You can also use binascii module in python 2:

>>> import binascii
>>> bin(int(binascii.hexlify(st),16))
'0b110100001100101011011000110110001101111001000000111011101101111011100100110110001100100'

hexlify return the hexadecimal representation of the binary data then you can convert to int by specifying 16 as its base then convert it to binary with bin.

VBScript to send email without running Outlook

You can send email without Outlook in VBScript using the CDO.Message object. You will need to know the address of your SMTP server to use this:

Set MyEmail=CreateObject("CDO.Message")

MyEmail.Subject="Subject"
MyEmail.From="[email protected]"
MyEmail.To="[email protected]"
MyEmail.TextBody="Testing one two three."

MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusing")=2

'SMTP Server
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserver")="smtp.server.com"

'SMTP Port
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserverport")=25 

MyEmail.Configuration.Fields.Update
MyEmail.Send

set MyEmail=nothing

If your SMTP server requires a username and password then paste these lines in above the MyEmail.Configuration.Fields.Update line:

'SMTP Auth (For Windows Auth set this to 2)
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate")=1
'Username
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusername")="username" 
'Password
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendpassword")="password"

More information on using CDO to send email with VBScript can be found on the link below: http://www.paulsadowski.com/wsh/cdo.htm

Convert Year/Month/Day to Day of Year in Python

Just subtract january 1 from the date:

import datetime
today = datetime.datetime.now()
day_of_year = (today - datetime.datetime(today.year, 1, 1)).days + 1

`require': no such file to load -- mkmf (LoadError)

I got the similar error when install bundle

sudo apt-get install ruby-dev

Works great for me and solve the problem Mint 16 ruby1.9.3

AngularJS ui-router login authentication

The solutions posted so far are needlessly complicated, in my opinion. There's a simpler way. The documentation of ui-router says listen to $locationChangeSuccess and use $urlRouter.sync() to check a state transition, halt it, or resume it. But even that actually doesn't work.

However, here are two simple alternatives. Pick one:

Solution 1: listening on $locationChangeSuccess

You can listen to $locationChangeSuccess and you can perform some logic, even asynchronous logic there. Based on that logic, you can let the function return undefined, which will cause the state transition to continue as normal, or you can do $state.go('logInPage'), if the user needs to be authenticated. Here's an example:

angular.module('App', ['ui.router'])

// In the run phase of your Angular application  
.run(function($rootScope, user, $state) {

  // Listen to '$locationChangeSuccess', not '$stateChangeStart'
  $rootScope.$on('$locationChangeSuccess', function() {
    user
      .logIn()
      .catch(function() {
        // log-in promise failed. Redirect to log-in page.
        $state.go('logInPage')
      })
  })
})

Keep in mind that this doesn't actually prevent the target state from loading, but it does redirect to the log-in page if the user is unauthorized. That's okay since real protection is on the server, anyway.

Solution 2: using state resolve

In this solution, you use ui-router resolve feature.

You basically reject the promise in resolve if the user is not authenticated and then redirect them to the log-in page.

Here's how it goes:

angular.module('App', ['ui.router'])

.config(
  function($stateProvider) {
    $stateProvider
      .state('logInPage', {
        url: '/logInPage',
        templateUrl: 'sections/logInPage.html',
        controller: 'logInPageCtrl',
      })
      .state('myProtectedContent', {
        url: '/myProtectedContent',
        templateUrl: 'sections/myProtectedContent.html',
        controller: 'myProtectedContentCtrl',
        resolve: { authenticate: authenticate }
      })
      .state('alsoProtectedContent', {
        url: '/alsoProtectedContent',
        templateUrl: 'sections/alsoProtectedContent.html',
        controller: 'alsoProtectedContentCtrl',
        resolve: { authenticate: authenticate }
      })

    function authenticate($q, user, $state, $timeout) {
      if (user.isAuthenticated()) {
        // Resolve the promise successfully
        return $q.when()
      } else {
        // The next bit of code is asynchronously tricky.

        $timeout(function() {
          // This code runs after the authentication promise has been rejected.
          // Go to the log-in page
          $state.go('logInPage')
        })

        // Reject the authentication promise to prevent the state from loading
        return $q.reject()
      }
    }
  }
)

Unlike the first solution, this solution actually prevents the target state from loading.

Creating temporary files in Android

This is what I typically do:

File outputDir = context.getCacheDir(); // context being the Activity pointer
File outputFile = File.createTempFile("prefix", "extension", outputDir);

As for their deletion, I am not complete sure either. Since I use this in my implementation of a cache, I manually delete the oldest files till the cache directory size comes down to my preset value.

Eclipse: "'Periodic workspace save.' has encountered a pro?blem."

I ran into this problem today after they switched our anti-virus software to Kaspersky.
In my case, the platform is Windows 7. My workspace is stored on mapped network drive. The strange thing is that, even though this appears to be a permission issue, I could manipulate files and folders at the same level as the inaccessible file without incident. So far, the only two workarounds are to move the workspace to the local drive or to uninstall Kaspersky. Removing and re-installing Kaspersky without the firewall feature did not do the trick.

I will update this answer if and when we find a more accommodating solution, though I expect that will involve adjusting the anti-virus software, not Eclipse.

No tests found with test runner 'JUnit 4'

I've had issues with this recently, which seem to be fixed in the latest Eclipse.

eclipse-java 4.11.0,2019-03:R -> 4.12.0,2019-06:R

Java Timestamp - How can I create a Timestamp with the date 23/09/2007?

A more general answer would be to import java.util.Date, then when you need to set a timestamp equal to the current date, simply set it equal to new Date().

How to find current transaction level?

DECLARE   @UserOptions TABLE(SetOption varchar(100), Value varchar(100))
DECLARE   @IsolationLevel varchar(100)

INSERT    @UserOptions
EXEC('DBCC USEROPTIONS WITH NO_INFOMSGS')

SELECT    @IsolationLevel = Value
FROM      @UserOptions
WHERE     SetOption = 'isolation level'

-- Do whatever you want with the variable here...  
PRINT     @IsolationLevel

Python: Removing spaces from list objects

Strings in Python are immutable (meaning that their data cannot be modified) so the replace method doesn't modify the string - it returns a new string. You could fix your code as follows:

for i in hello:
    j = i.replace(' ','')
    k.append(j)

However a better way to achieve your aim is to use a list comprehension. For example the following code removes leading and trailing spaces from every string in the list using strip:

hello = [x.strip(' ') for x in hello]

Break out of a While...Wend loop

A While/Wend loop can only be exited prematurely with a GOTO or by exiting from an outer block (Exit sub/function or another exitable loop)

Change to a Do loop instead:

Do While True
    count = count + 1

    If count = 10 Then
        Exit Do
    End If
Loop

Or for looping a set number of times:

for count = 1 to 10
   msgbox count
next

(Exit For can be used above to exit prematurely)

Can someone provide an example of a $destroy event for scopes in AngularJS?

$destroy can refer to 2 things: method and event

1. method - $scope.$destroy

.directive("colorTag", function(){
  return {
    restrict: "A",
    scope: {
      value: "=colorTag"
    },
    link: function (scope, element, attrs) {
      var colors = new App.Colors();
      element.css("background-color", stringToColor(scope.value));
      element.css("color", contrastColor(scope.value));

      // Destroy scope, because it's no longer needed.
      scope.$destroy();
    }
  };
})

2. event - $scope.$on("$destroy")

See @SunnyShah's answer.

Easiest way to use SVG in Android?

1)Right Click On drawable directory then go to new then go to vector assets 2)change asset type from clip art to local 3)browse your file 4)give size 5)then click next then done Your usable svg will be generated in drawable directory

read input separated by whitespace(s) or newline...?

the user pressing enter or spaces is the same.

int count = 5;
int list[count]; // array of known length
cout << "enter the sequence of " << count << " numbers space separated: ";
// user inputs values space separated in one line.  Inputs more than the count are discarded.
for (int i=0; i<count; i++) {
    cin >> list[i];
}

Converting a column within pandas dataframe from int to string

Just for an additional reference.

All of the above answers will work in case of a data frame. But if you are using lambda while creating / modify a column this won't work, Because there it is considered as a int attribute instead of pandas series. You have to use str( target_attribute ) to make it as a string. Please refer the below example.

def add_zero_in_prefix(df):
    if(df['Hour']<10):
        return '0' + str(df['Hour'])

data['str_hr'] = data.apply(add_zero_in_prefix, axis=1)

How does one sum only those rows in excel not filtered out?

If you aren't using an auto-filter (i.e. you have manually hidden rows), you will need to use the AGGREGATE function instead of SUBTOTAL.

md-table - How to update the column width

I just used:

th:nth-child(4) {
    width: 10%;
}

Replace 4 with the position of the header that you need to adjust the width for.The examples in the documentation used:

td, th {
  width: 25%;
}

So I just modified it to get what I wanted.

Throwing multiple exceptions in a method of an interface in java

You need to specify it on the methods that can throw the exceptions. You just seperate them with a ',' if it can throw more than 1 type of exception. e.g.

public interface MyInterface {
  public MyObject find(int x) throws MyExceptionA,MyExceptionB;
}

Windows equivalent to UNIX pwd

cd ,

it will give the current directory

D:\Folder\subFolder>cd ,
D:\Folder\subFolder