Programs & Examples On #Ssp

How do I get the command-line for an Eclipse run configuration?

I found a solution on Stack Overflow for Java program run configurations which also works for JUnit run configurations.

You can get the full command executed by your configuration on the Debug tab, or more specifically the Debug view.

  1. Run your application
  2. Go to your Debug perspective
  3. There should be an entry in there (in the Debug View) for the app you've just executed
  4. Right-click the node which references java.exe or javaw.exe and select Properties In the dialog that pops up you'll see the Command Line which includes all jars, parameters, etc

dotnet ef not found in .NET Core 3

For me, The problem was solved after I close Visual Studio and Open it again

Android Gradle 5.0 Update:Cause: org.jetbrains.plugins.gradle.tooling.util

For anybody facing a similar issue at this point in time, all you need to do is update your Android Studio to the latest version

Support for the experimental syntax 'classProperties' isn't currently enabled

Change

"plugins": [
    "@babel/plugin-proposal-class-properties"
  ]

To

"plugins": [
    [
      "@babel/plugin-proposal-class-properties",
      {
        "loose": true
      }
    ]
  ]

This worked for me

Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured

Your problem is the dependency of spring batch spring-boot-starter-batch that has a spring-boot-starter-jdbc transitive maven dependency.

Spring Batch is a framework for building reliable and fault tolerance enterprise batch jobs. It supports many features like restarting a failed batch, recording the status of the batch execution and so on. In order to achieve that Spring Batch uses a database schema to store the status of the registered jobs, the auto-configuration already provides you the basic configuration of the required data source and it is this configuration that requires the relational database configuration.

To solve this you must include some database driver like mysql, h2, etc. to configure the url.

Update: Just for getting start you can configure your application.yml like below:

spring:
  datasource:
    driver-class-name: org.h2.Driver
    url: jdbc:h2:mem:localhost;DB_CLOSE_ON_EXIT=FALSE
    username: admin
    password:

and of course in your pom.xml include the h2 dirver like this:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>demo</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.3.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
       ....
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
        </dependency>

....
    </dependencies>
...

</project>

The motivation, because you can not use mongo for this purpose, is that the usage of mongo is provided only for item readers and writers and not for managing the internal database of Spring Batch that is an internal schema, not a business schema. The query is plain SQL query and the internal abstraction relies on a relational database. It is necessary to have a database with ACID capability because every batch reads and writes a chunk of work and saves that information in order to restart the job. A NoSql solution is not suitable for this.

At the end you have configured a relational database in order to prepare Spring Batch for internal capability, the internal abstraction does not rely on mongo only on jdbc. Then mongo can be used but for the business side of the batch via item reader/writer.

I hope that this can help you to clear your doubts.

Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve

I think the problems comes from the following: The internet connection with u was unavailable so Android Studio asked you to enable the "offline work" and you just enabled it

To fix this:

  • File
  • Settings
  • Build, Execution, Deployment
  • Gradle
  • Uncheck offline work

why might unchecking the offline work solves the problem, because in the Gradle sometimes some dependencies need to update (the ones containing '+'), so internet connection is needed.

ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean

The solution is:

I explicitly set the below property to none in application.yml file.

spring:
  main:
    web-application-type: none

Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified

I encountered this error simply because I misspelled the spring.datasource.url value in the application.properties file and I was using postgresql:

Problem was: jdbc:postgres://localhost:<port-number>/<database-name>

Fixed to: jdbc:postgresql://localhost:<port-number>/<database-name>

NOTE: the difference is postgres & postgresql, the two are 2 different things.

Further causes and solutions may be found here

How to start up spring-boot application via command line?

A Spring Boot project configured through Maven can be run using the following command from the project source folder

mvn spring-boot:run

Could not resolve com.android.support:appcompat-v7:26.1.0 in Android Studio new project

This work for me. In the android\app\build.gradle file you need to specify the following

compileSdkVersion 26
buildToolsVersion "26.0.1"

and then find this

compile "com.android.support:appcompat-v7"

and make sure it says

compile "com.android.support:appcompat-v7:26.0.1"

Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve com.android.support:appcompat-v7:26.1.0

Invalidate Cache / Restart from File option.

Just unchecking offline mode did not work for me.

Android studio 3.0: Unable to resolve dependency for :app@dexOptions/compileClasspath': Could not resolve project :animators

I met the same problems and has solved.

Due to my situation, I guess your build.gradle file for app project contains snippets below:

android {
    ...
    buildTypes {
        debug {...}
        release {...}
        dexOptions {...}
    }
}

but actually, dexOptions is not a build type, you should move dexOptions section out buildTypes, like this:

android {
    ...
    dexOptions {
        ...
    }

    buildTypes {
        debug {...}
        release {...}
    }
}

Hope that can help someone.

Unable to merge dex

if(1. Try to clean and rebuild work ) then good

else if (2. Try to remove gradle work ) then good

else-> 3. Try to add in grade.properties

android.enableD8 = false

Edit 2021: This 3rd option is deprecated now, use the other options

else-> 4. Add multiDexEnabled true to your build.gradle

android {
    compileSdkVersion 26
    defaultConfig {
      ...
        minSdkVersion 15
        targetSdkVersion 26
        multiDexEnabled true
     ...
    }
}

and add the dependency

dependencies {
    compile 'com.android.support:multidex:1.0.1'}

It may the first one works for u and so on but it really depends on the nature of your problem for me for example

I got the error once I have added this library

implementation 'com.jjoe64:graphview:4.2.2'

and later I discovered that I have to check that and I have to add the same version of the support libraries. So I have to try another version

compile 'com.jjoe64:graphview:4.2.1'

and it fixes the problem. So pay attention for that.

Vuex - passing multiple parameters to mutation

In simple terms you need to build your payload into a key array

payload = {'key1': 'value1', 'key2': 'value2'}

Then send the payload directly to the action

this.$store.dispatch('yourAction', payload)

No change in your action

yourAction: ({commit}, payload) => {
  commit('YOUR_MUTATION',  payload )
},

In your mutation call the values with the key

'YOUR_MUTATION' (state,  payload ){
  state.state1 = payload.key1
  state.state2 =  payload.key2
},

PYODBC--Data source name not found and no default driver specified

Do not put a space after the Driver keyword in the connection string.

This fails on Windows ...

conn_str = (
    r'DRIVER = {SQL Server};'
    r'SERVER=(local)\SQLEXPRESS;'
    r'DATABASE=myDb;'
    r'Trusted_Connection=yes;'
)
cnxn = pyodbc.connect(conn_str)

... but this works:

conn_str = (
    r'DRIVER={SQL Server};'
    r'SERVER=(local)\SQLEXPRESS;'
    r'DATABASE=myDb;'
    r'Trusted_Connection=yes;'
)
cnxn = pyodbc.connect(conn_str)

Android dependency has different version for the compile and runtime

Switching my conflicting dependencies from implementation to api does the trick. Here's a good article by mindorks explaining the difference.

https://medium.com/mindorks/implementation-vs-api-in-gradle-3-0-494c817a6fa

Edit:

Here's my dependency resolutions as well

 subprojects {
        project.configurations.all {
            resolutionStrategy.eachDependency { details ->
                if (details.requested.group == 'com.android.support'
                        && !details.requested.name.contains('multidex')) {
                    details.useVersion "28.0.0"
                }
                if (details.requested.group == 'com.google.android.gms'
                        && details.requested.name.contains('play-services-base')) {
                    details.useVersion "15.0.1"
                }
                if (details.requested.group == 'com.google.android.gms'
                        && details.requested.name.contains('play-services-tasks')) {
                    details.useVersion "15.0.1"
                }
            }
        }
    }

More than one file was found with OS independent path 'META-INF/LICENSE'

app build.gradle

android {
    packagingOptions {
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/INDEX.LIST'
    }
}

Could not find com.android.tools.build:gradle:3.0.0-alpha1 in circle ci

Just add this

buildscript {
    repositories {
        ...
        google() 
        jcenter()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:3.3.0' 
    }
}

It works...Cheers!!!

Error:Execution failed for task ':app:compileDebugKotlin'. > Compilation error. See log for more details

I have found one solution to this problem.

Please follow below these steps:

  1. Go to File->Settings->Compiler->add To --stacktrace --debug in Command-line-Options box and then apply & ok.
  2. Rebuild a project.
  3. Run a project.

Android: Getting "Manifest merger failed" error after updating to a new version of gradle

Put this at the end of your app module build.gradle:

configurations.all {
    resolutionStrategy.eachDependency { DependencyResolveDetails details ->
        def requested = details.requested
        if (requested.group == 'com.android.support') {
            if (!requested.name.startsWith("multidex")) {
                details.useVersion '25.3.0'
            }
        }
    }
}

Credit to Eugen Pechanec

Hibernate Error executing DDL via JDBC Statement

in your CFG file please change the hibernate dialect

<!-- SQL dialect -->
    <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>

Gradle error: Minimum supported Gradle version is 3.3. Current version is 3.2

For Android Studion version 3.3.2

1) I updated the gradle distribution URL to distributionUrl=https\://services.gradle.org/distributions/gradle-4.10.1-all.zip in gradle-wrapper.properties file

2) Within the top-level build.gradle file updated the gradle plugin to version 3.3.2

dependencies {
    classpath 'com.android.tools.build:gradle:3.3.2'
    classpath 'com.google.gms:google-services:4.2.0'
}

key_load_public: invalid format

As Roland mentioned in their answer, it's a warning that the ssh-agent doesn't understand the format of the public key and even then, the public key will not be used locally.

However, I can also elaborate and answer why the warning is there. It simply boils down to the fact that the PuTTY Key Generator generates two different public key formats depending on what you do in the program.

Note: Throughout my explanation, the key files I will be using/generating will be named id_rsa with their appropriate extensions. Furthermore, for copy-paste convenience, the parent folder of the keys will be assumed to be ~/.ssh/. Adjust these details to suit your needs as desired.

The Formats

Link to the relevant PuTTY documentation

SSH-2

When you save a key using the PuTTY Key Generator using the "Save public key" button, it will be saved in the format defined by RFC 4716.

Example:

---- BEGIN SSH2 PUBLIC KEY ----
Comment: "github-example-key"
AAAAB3NzaC1yc2EAAAABJQAAAQEAhl/CNy9wI1GVdiHAJQV0CkHnMEqW7+Si9WYF
i2fSBrsGcmqeb5EwgnhmTcPgtM5ptGBjUZR84nxjZ8SPmnLDiDyHDPIsmwLBHxcp
pY0fhRSGtWL5fT8DGm9EfXaO1QN8c31VU/IkD8niWA6NmHNE1qEqpph3DznVzIm3
oMrongEjGw7sDP48ZTZp2saYVAKEEuGC1YYcQ1g20yESzo7aP70ZeHmQqI9nTyEA
ip3mL20+qHNsHfW8hJAchaUN8CwNQABJaOozYijiIUgdbtSTMRDYPi7fjhgB3bA9
tBjh7cOyuU/c4M4D6o2mAVYdLAWMBkSoLG8Oel6TCcfpO/nElw==
---- END SSH2 PUBLIC KEY ----

OpenSSH

Contrary to popular belief, this format doesn't get saved by the generator. However it is generated and shown in the text box titled "Public key for pasting into OpenSSH authorized_keys file". To save it as a file, you have to manually copy it from the text box and paste it into a new text file.

For the key shown above, this would be:

ssh-rsa AAAAB3NzaC1yc2EAAAABJQAAAQEAhl/CNy9wI1GVdiHAJQV0CkHnMEqW7+Si9WYFi2fSBrsGcmqeb5EwgnhmTcPgtM5ptGBjUZR84nxjZ8SPmnLDiDyHDPIsmwLBHxcppY0fhRSGtWL5fT8DGm9EfXaO1QN8c31VU/IkD8niWA6NmHNE1qEqpph3DznVzIm3oMrongEjGw7sDP48ZTZp2saYVAKEEuGC1YYcQ1g20yESzo7aP70ZeHmQqI9nTyEAip3mL20+qHNsHfW8hJAchaUN8CwNQABJaOozYijiIUgdbtSTMRDYPi7fjhgB3bA9tBjh7cOyuU/c4M4D6o2mAVYdLAWMBkSoLG8Oel6TCcfpO/nElw== github-example-key

The format of the key is simply ssh-rsa <signature> <comment> and can be created by rearranging the SSH-2 formatted file.

Regenerating Public Keys

If you are making use of ssh-agent, you will likely also have access to ssh-keygen.

If you have your OpenSSH Private Key (id_rsa file), you can generate the OpenSSH Public Key File using:

ssh-keygen -f ~/.ssh/id_rsa -y > ~/.ssh/id_rsa.pub

If you only have the PUTTY Private Key (id_rsa.ppk file), you will need to convert it first.

  1. Open the PuTTY Key Generator
  2. On the menu bar, click "File" > "Load private key"
  3. Select your id_rsa.ppk file
  4. On the menu bar, click "Conversions" > "Export OpenSSH key"
  5. Save the file as id_rsa (without an extension)

Now that you have an OpenSSH Private Key, you can use the ssh-keygen tool as above to perform manipulations on the key.

Bonus: The PKCS#1 PEM-encoded Public Key Format

To be honest, I don't know what this key is used for as I haven't needed it. But I have it in my notes I've collated over the years and I'll include it here for wholesome goodness. The file will look like this:

-----BEGIN RSA PUBLIC KEY-----
MIIBCAKCAQEAhl/CNy9wI1GVdiHAJQV0CkHnMEqW7+Si9WYFi2fSBrsGcmqeb5Ew
gnhmTcPgtM5ptGBjUZR84nxjZ8SPmnLDiDyHDPIsmwLBHxcppY0fhRSGtWL5fT8D
Gm9EfXaO1QN8c31VU/IkD8niWA6NmHNE1qEqpph3DznVzIm3oMrongEjGw7sDP48
ZTZp2saYVAKEEuGC1YYcQ1g20yESzo7aP70ZeHmQqI9nTyEAip3mL20+qHNsHfW8
hJAchaUN8CwNQABJaOozYijiIUgdbtSTMRDYPi7fjhgB3bA9tBjh7cOyuU/c4M4D
6o2mAVYdLAWMBkSoLG8Oel6TCcfpO/nElwIBJQ==
-----END RSA PUBLIC KEY-----

This file can be generated using an OpenSSH Private Key (as generated in "Regenerating Public Keys" above) using:

ssh-keygen -f ~/.ssh/id_rsa -y -e -m pem > ~/.ssh/id_rsa.pem

Alternatively, you can use an OpenSSH Public Key using:

ssh-keygen -f ~/.ssh/id_rsa.pub -e -m pem > ~/.ssh/id_rsa.pem

References:

java.io.FileNotFoundException: class path resource cannot be opened because it does not exist

What you put directly under src/main/java is in the default package, at the root of the classpath. It's the same for resources put under src/main/resources: they end up at the root of the classpath.

So the path of the resource is app-context.xml, not main/resources/app-context.xml.

"SSL certificate verify failed" using pip to install packages

Pretty unique case here, but having Fiddler running (not even targeting the same process) gave me the same SSL errors. Running pip install with --verbose showed an error with Fiddler, closing Fiddler immediately fixed the issue.

Error:Cause: unable to find valid certification path to requested target

I just encountered the similar problem and found a series of steps did help me. Of course few of them is to Change the network to a stronger,better one.or if you have only one network then try Reconnecting to the network and then simply INVALIDATE/RESTART your android studio. If it still shows the error you need to add the "maven" in repositories and point it out to the link as shown below: maven { url "http://jcenter.bintray.com"}

Finally,Go to *File *Settings *Build,Execution and deployment *Gradle *Android Studio --------And check Enable maven repository option.

After that simply clean and rebuild your APP and you will be good to go.

npm start error with create-react-app

incase you happened to be so unlucky like me that spent three(3) days in a row trying to solve this problem every solution proposed here failed me ... create a .env file in your project root and add this code SKIP_PREFLIGHT_CHECK=true. Good luck

Plugin with id 'com.google.gms.google-services' not found

In the app build.gradle dependency, you must add the following code

classpath 'com.google.gms:google-services:$last_version'

And then please check the Google Play Service SDK tools installing status.

Didn't find class "com.google.firebase.provider.FirebaseInitProvider"?

I too faced the same issue and finally solved it by disabling Instant Run in an android studio.

Settings ? Build, Execution, Deployment ? Instant Run and uncheck Enable Instant Run

Update:

There is no Instant Run option available in latest Android Studio 3.5+. It should be applicable only for older versions.

gzip: stdin: not in gzip format tar: Child returned status 1 tar: Error is not recoverable: exiting now

This means the file isn't really a gzipped tar file -- or any kind of gzipped file -- in spite of being named like one.

When you download a file with wget, check for indications like Length: unspecified [text/html] which shows it is plain text (text) and that it is intended to be interpreted as html. Check the wget output below -

[root@XXXXX opt]# wget --no-cookies --no-check-certificate --header "Cookie: gpw_e24=http%3A%2F%2Fwww.oracle.com%2F; oraclelicense=accept-securebackup-cookie" "http://download.oracle.com/otn-pub/java/jdk/8u144-b01/090f390dda5b47b9b721c7dfaa008135/jdk-8u144-linux-x64.tar.gz"
--2017-10-12 12:39:40--  http://download.oracle.com/otn-pub/java/jdk/8u144-b01/090f390dda5b47b9b721c7dfaa008135/jdk-8u144-linux-x64.tar.gz
Resolving download.oracle.com (download.oracle.com)... 23.72.136.27, 23.72.136.67
Connecting to download.oracle.com (download.oracle.com)|23.72.136.27|:80... connected.
HTTP request sent, awaiting response... 302 Not Allowed
Location: http://XXXX/FAQs/URLFiltering/ProxyWarning.html [following]
--2017-10-12 12:39:40--  http://XXXX/FAQs/URLFiltering/ProxyWarning.html
Resolving XXXX (XXXXX)... XXX.XX.XX.XXX
Connecting to XXXX (XXXX)|XXX.XX.XX.XXX|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 17121 (17K) [text/html]
Saving to: ‘jdk-8u144-linux-x64.tar.gz’

100%[=========================================================================================================================================================================>] 17,121      --.-K/s   in 0.05s   

2017-10-12 12:39:40 (349 KB/s) - ‘jdk-8u144-linux-x64.tar.gz’ saved [17121/17121]

This sort of confirms that you haven't received a gzip file.

For a correct file, the wget output will show something like Length: 185515842 (177M) [application/x-gzip] as shown in the below output -

[root@txcdtl01ss270n opt]# wget --no-cookies --no-check-certificate --header "Cookie: gpw_e24=http%3A%2F%2Fwww.oracle.com%2F; oraclelicense=accept-securebackup-cookie" "http://download.oracle.com/otn-pub/java/jdk/8u144-b01/090f390dda5b47b9b721c7dfaa008135/jdk-8u144-linux-x64.tar.gz"
--2017-10-12 12:50:06--  http://download.oracle.com/otn-pub/java/jdk/8u144-b01/090f390dda5b47b9b721c7dfaa008135/jdk-8u144-linux-x64.tar.gz
Resolving download.oracle.com (download.oracle.com)... XX.XXX.XX.XX, XX.XX.XXX.XX
Connecting to download.oracle.com (download.oracle.com)|XX.XX.XXX.XX|:80... connected.
HTTP request sent, awaiting response... 302 Moved Temporarily
Location: https://edelivery.oracle.com/otn-pub/java/jdk/8u144-b01/090f390dda5b47b9b721c7dfaa008135/jdk-8u144-linux-x64.tar.gz [following]
--2017-10-12 12:50:06--  https://edelivery.oracle.com/otn-pub/java/jdk/8u144-b01/090f390dda5b47b9b721c7dfaa008135/jdk-8u144-linux-x64.tar.gz
Resolving edelivery.oracle.com (edelivery.oracle.com)... XXX.XX.XXX.XX, 2600:1404:16:188::2d3e, 2600:1404:16:180::2d3e
Connecting to edelivery.oracle.com (edelivery.oracle.com)|XXX.XX.XX.XXX|:443... connected.
HTTP request sent, awaiting response... 302 Moved Temporarily
Location: http://download.oracle.com/otn-pub/java/jdk/8u144-b01/090f390dda5b47b9b721c7dfaa008135/jdk-8u144-linux-x64.tar.gz?AuthParam=1507827127_f44251ebbb44c6e61e7f202677f94afd [following]
--2017-10-12 12:50:07--  http://download.oracle.com/otn-pub/java/jdk/8u144-b01/090f390dda5b47b9b721c7dfaa008135/jdk-8u144-linux-x64.tar.gz?AuthParam=1507827127_f44251ebbb44c6e61
Connecting to download.oracle.com (download.oracle.com)|XX.XX.XXX.XX|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 185515842 (177M) [application/x-gzip]
Saving to: ‘jdk-8u144-linux-x64.tar.gz’

100%[=========================================================================================================================================================================>] 185,515,842 6.60MB/s   in 28s    

2017-10-12 12:50:34 (6.43 MB/s) - ‘jdk-8u144-linux-x64.tar.gz’ saved [185515842/185515842]

The above shows a correct gzip application file has been downloaded.

You can also file, head, less, view utilities to check the file. For example a HTML file would give below output -

[root@XXXXXX opt]# head jdk-8u144-linux-x64.tar.gz
<!doctype html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="/css/print.css" rel="stylesheet" media="print">
    <link href="/css/main.css" rel="stylesheet" media="screen">
    <link href="/css/font-awesome.min.css" rel="stylesheet">

The above shows it is indeed an HTML page which we are trying to unzip/untar - something that won't work. If it was indeed a correct zip file (binary in nature) the output of head would have produced garbage - something like below -

[root@XXXX opt]# head jdk-8u144-linux-x64.tar.gz 
x?rY?[ms?F???????t?l???DR??????j
                                       $?$,`0?h?_????/??=?@Q?w+???*?Hbfz?{?~?{?i?x??k?????}????z???w????g?????{???;{s????w?????7?N????i?
?????}
?¿g????????????7??s??????î??????~i??j?/??????#???=??=>???{}??|?????????????3???X???]9??????u?????%g?<^)?H?8?F?R?t?o?L?u??S%?ds5?2_EZn?t^??
                                                                                                                                                 ?N3??(??<??|'?q???R?N?gq?Uv!???p???rL??M??u??.?Q?5?T??BNw?!$??<>?7G'$?,Mt4WY?Gi"?=??p?)?VIN3????\ek??0??G
                                            ?<L?c?e?t-???2???G:?ia??I?<?g3???d?H????[2`?<I?A?6?W??<??C???????h??A0QL?2?4?-*
?x?????t%t1??f?>+A??,Lr?
                        ?Fe:MBH????
C?Q?r?S??<M?b?<,5???@???s???c??sp?f?=g?????k???4?}??kh)?¹Z??#d?*{???-?.N?)?e??s:?H(VQ??3*?$2??r?v?"o?_??!A???????B?l=A?|??@??0??1??5??4g?
?
???Se????H[2?????t??5?Df????$1???b$? h?Op????!Lvb!p??b?8^?Y???n?
                                                                          O??????|??lW?lu??*?N?M???
?/?^0~?~?#??q????????K??;?d???aw4?????'?~?7??ky?o?????????t?'k??f????!vo???'o???     ?.?Pn\?
               ?+??K"FA{????n2????v??!/Ok??r4?c5?x$'?.?&w?!?%??o??????2???i
                                                                               ?a0??Ag?d????GH)G7~?g???b??%?b??rt?m~?   ?????t0??   <????????????5?q?t??K(??+Z<??=???:1?\?x?p=t?`??G@F??    i?????p8?????H.???dMLE??e[?`?'n??*h[??;?0w'??6A??M?x?fpeB>&???MO???????`?@á/?"?????(??^???n??=????5??@?Mx??d:\YAn???]|?w>??S??FA9?J?k!?@?

Try downloading from the official site and check if their download links have changed. Also check your proxy settings and make sure you have the right proxies enabled to download/wget it from the correct source.

Hope this helps.

gpg failed to sign the data fatal: failed to write commit object [Git 2.10.0]

To anybody who is facing this issue on MacOS machines, try this:

  1. brew uninstall gpg
  2. brew install gpg2
  3. brew install pinentry-mac (if needed)
  4. gpg --full-generate-key Create a key by using an algorithm.
  5. Get generated key by executing: gpg --list-keys
  6. Set the key here git config --global user.signingkey <Key from your list>
  7. git config --global gpg.program /usr/local/bin/gpg
  8. git config --global commit.gpgsign true
  9. If you want to export your Key to GitHub then: gpg --armor --export <key> and add this key to GitHub at GPG keys: https://github.com/settings/keys (with START and END line included)

If the issue still exists:

test -r ~/.bash_profile && echo 'export GPG_TTY=$(tty)' >> ~/.bash_profile

echo 'export GPG_TTY=$(tty)' >> ~/.profile

If the issue still exists:

Install https://gpgtools.org and sign the key that you used by pressing Sign from the menu bar: Key->Sign

If the issue still exists:

Go to: ??your global .gitconfig file which in my case is at: ??/Users/gent/.gitconfig And modify the .gitconfig file (please make sure Email and Name are the same with the one that you have created while generating the Key):

_x000D_
_x000D_
[user]_x000D_
 email = [email protected]_x000D_
 name = Gent_x000D_
 signingkey = <YOURKEY>_x000D_
[gpg]_x000D_
 program = /usr/local/bin/gpg_x000D_
[commit]_x000D_
 gpsign = true_x000D_
 gpgsign = true_x000D_
[filter "lfs"]_x000D_
 process = git-lfs filter-process_x000D_
 required = true_x000D_
 clean = git-lfs clean -- %f_x000D_
 smudge = git-lfs smudge -- %f_x000D_
[credential]_x000D_
 helper = osxkeychain
_x000D_
_x000D_
_x000D_

Adding Access-Control-Allow-Origin header response in Laravel 5.3 Passport

Just add this to your view:

<?php header("Access-Control-Allow-Origin: *"); ?>

Unable to find a @SpringBootConfiguration when doing a JpaTest

In my case the packages were different between the Application and Test classes

package com.example.abc;
...
@SpringBootApplication
public class ProducerApplication {

and

package com.example.abc_etc;
...
@RunWith(SpringRunner.class)
@SpringBootTest
public class ProducerApplicationTest {

After making them agree the tests ran correctly.

React eslint error missing in props validation

It seems that the problem is in eslint-plugin-react.

It can not correctly detect what props were mentioned in propTypes if you have annotated named objects via destructuring anywhere in the class.

There was similar problem in the past

Vue equivalent of setTimeout?

vuejs 2

first add this to methods

methods:{
    sayHi: function () {
      var v = this;
      setTimeout(function () {
        v.message = "Hi Vue!";
    }, 3000);
   }

after that call this method on mounted

mounted () {
  this.sayHi()
}

Google Play Services GCM 9.2.0 asks to "update" back to 9.0.0

I had the same problem, today 2016 - october - 06 I solved with this:

I changed all dependencies that began with 9.?.? to 9.6.1 I compiled with sdk version 24 and target version 17.

There is another packages in my solution because I used more things then only authentication.

After changed your build.gradle (Module:app) with the code below do it:

  1. Put your package NAME in the line with the words applicationId "com.YOUR_PACKAGE_HERE"

  2. Synchronize your project (Ctrl+alt+v) and Build Again.

This is the code of the file buid.gradle (Module:app) that worked for me:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 24
    buildToolsVersion "24.0.3"
    defaultConfig {
        applicationId "com.YOUR_PACKAGE_HERE"
        minSdkVersion 24
        targetSdkVersion 17
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

    compile 'com.google.firebase:firebase-core:9.6.1'
    compile 'com.google.firebase:firebase-database:9.6.1'

    compile 'com.android.support:appcompat-v7:24.2.1'
    compile 'com.android.support:design:24.2.1'

    compile 'com.google.firebase:firebase-crash:9.6.1'
    testCompile 'junit:junit:4.12'

    compile 'com.google.firebase:firebase-messaging:9.6.1'

    compile 'com.google.firebase:firebase-ads:9.6.1'


    compile 'com.google.firebase:firebase-auth:9.6.1'


    compile 'com.google.android.gms:play-services:9.6.1'

}
apply plugin: 'com.google.gms.google-services'

Error: Module not specified (IntelliJ IDEA)

this is how I fix this issue
1.open my project structure

2.click module enter image description here 3.click plus button enter image description here 4.click import module,and find the module's pom enter image description here
5.make sure you select the module you want to import,then next next finish:) enter image description here

How to configure Spring Security to allow Swagger URL to be accessed without authentication

Here's a complete solution for Swagger with Spring Security. We probably want to only enable Swagger in our development and QA environment and disable it in the production environment. So, I am using a property (prop.swagger.enabled) as a flag to bypass spring security authentication for swagger-ui only in development/qa environment.

@Configuration
@EnableSwagger2
public class SwaggerConfiguration extends WebSecurityConfigurerAdapter implements WebMvcConfigurer {

@Value("${prop.swagger.enabled:false}")
private boolean enableSwagger;

@Bean
public Docket SwaggerConfig() {
    return new Docket(DocumentationType.SWAGGER_2)
            .enable(enableSwagger)
            .select()
            .apis(RequestHandlerSelectors.basePackage("com.your.controller"))
            .paths(PathSelectors.any())
            .build();
}

@Override
public void configure(WebSecurity web) throws Exception {
    if (enableSwagger)  
        web.ignoring().antMatchers("/v2/api-docs",
                               "/configuration/ui",
                               "/swagger-resources/**",
                               "/configuration/security",
                               "/swagger-ui.html",
                               "/webjars/**");
}

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    if (enableSwagger) {
        registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
  }
}

org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:transformClassesWithDexForDebug'

Check build.gradle(Module: Android) fixed problem for me.

Modify it to workable version.

android {
    buildToolsVersion '23.0.1'
}

Print: Entry, ":CFBundleIdentifier", Does Not Exist

Try to look into previous error message happened before current error i.e., "CFBundleIdentifier”, Does Not Exist.

Fix previous error then this error should disappear.

I fixed previous duplicate symbols for architecture error when run react-native run-ios --simulator="iPad Pro (9.7-inch), then the problem gone.

JPA Hibernate Persistence exception [PersistenceUnit: default] Unable to build Hibernate SessionFactory

The issue is that you are not able to get a connection to MYSQL database and hence it is throwing an error saying that cannot build a session factory.

Please see the error below:

 Caused by: java.sql.SQLException: Access denied for user ''@'localhost' (using password: NO) 

which points to username not getting populated.

Please recheck system properties

dataSource.setUsername(System.getProperty("root"));

some packages seems to be missing as well pointing to a dependency issue:

package org.gjt.mm.mysql does not exist

Please run a mvn dependency:tree command to check for dependencies

Could not find method android() for arguments

This error appear because the compiler could not found "my-upload-key.keystore" file in your project

After you have generated the file you need to paste it into project's andorid/app folder

this worked for me!

Add jars to a Spark Job - spark-submit

Other configurable Spark option relating to jars and classpath, in case of yarn as deploy mode are as follows
From the spark documentation,

spark.yarn.jars

List of libraries containing Spark code to distribute to YARN containers. By default, Spark on YARN will use Spark jars installed locally, but the Spark jars can also be in a world-readable location on HDFS. This allows YARN to cache it on nodes so that it doesn't need to be distributed each time an application runs. To point to jars on HDFS, for example, set this configuration to hdfs:///some/path. Globs are allowed.

spark.yarn.archive

An archive containing needed Spark jars for distribution to the YARN cache. If set, this configuration replaces spark.yarn.jars and the archive is used in all the application's containers. The archive should contain jar files in its root directory. Like with the previous option, the archive can also be hosted on HDFS to speed up file distribution.

Users can configure this parameter to specify their jars, which inturn gets included in Spark driver's classpath.

Failed to load ApplicationContext (with annotation)

In my case, I had to do the following while running with Junit5

@SpringBootTest(classes = {abc.class}) @ExtendWith(SpringExtension.class

Here abc.class was the class that was being tested

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12:test (default-test) on project.

HI All can you try adding the below in your POM and then use mvn clean compile and then mvn install.

<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
</dependency>

Spring Boot access static resources missing scr/main/resources

While working with Spring Boot application, it is difficult to get the classpath resources using resource.getFile() when it is deployed as JAR as I faced the same issue. This scan be resolved using Stream which will find out all the resources which are placed anywhere in classpath.

Below is the code snippet for the same -

ClassPathResource classPathResource = new ClassPathResource("fileName");
InputStream inputStream = classPathResource.getInputStream();
content = IOUtils.toString(inputStream);

Android- Error:Execution failed for task ':app:transformClassesWithDexForRelease'

By default, Android Studio has a maximum heap size of 1280MB. If you are working on a large project, or your system has a lot of RAM, you can improve performance by increasing the maximum heap size for Android Studio processes, such as the core IDE, Gradle daemon, and Kotlin daemon.

If you use a 64-bit system that has at least 5 GB of RAM, you can also adjust the heap sizes for your project manually. To do so, follow these steps:

Click File > Settings from the menu bar (or Android Studio > Preferences on macOS). Click Appearance & Behavior > System Settings > Memory Settings.

For more Info click

https://developer.android.com/studio/intro/studio-config

enter image description here

java.lang.RuntimeException: Unable to instantiate org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient

In my case when i tried

$ hive --service metastore 

I got

MetaException(message:Version information not found in metastore. )

The necessary tables required for the metastore are missing in MySQL. Manually create the tables and restart hive metastore.

cd $HIVE_HOME/scripts/metastore/upgrade/mysql/ 

< Login into MySQL > 

mysql> drop database IF EXISTS <metastore db name>; 
mysql> create database <metastore db name>; 
mysql> use <metastore db name>; 
mysql> source hive-schema-2.x.x.mysql.sql; 

metastore db name should match the database name mentioned in hive-site.xml files connection property tag.

hive-schema-2.x.x.mysql.sql file depends on the version available in the current directory. Try to go for the latest because it holds many old schema files also.

Now try to execute hive --service metastore If everything goes cool, then simply start the hive from terminal.

>hive

I hope the above answer serves your need.

Error: No toolchains found in the NDK toolchains folder for ABI with prefix: llvm

Solved it by adding google() dependency into both repositories in build.gradle(Project: ProjectName). then sync your project

buildscript {
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.2'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

Android Studio Could not initialize class org.codehaus.groovy.runtime.InvokerHelper

I also had the same problem and and it looks like this problem is due to the gradle version in the project directory

  • This is the version of my jdk:
openjdk version "15-ea" 2020-09-15
OpenJDK Runtime Environment (build 15-ea+32-Ubuntu-220.04)
OpenJDK 64-Bit Server VM (build 15-ea+32-Ubuntu-220.04, mixed mode, sharing)
  • Please check gradle whether it is installed. This is the version of my gradle:
------------------------------------------------------------
Gradle 6.8
------------------------------------------------------------

Build time:   2021-01-08 16:38:46 UTC
Revision:     b7e82460c5373e194fb478a998c4fcfe7da53a7e

Kotlin:       1.4.20
Groovy:       2.5.12
Ant:          Apache Ant(TM) version 1.10.9 compiled on September 27 2020
JVM:          15-ea (Private Build 15-ea+32-Ubuntu-220.04)
OS:           Linux 5.4.0-65-generic amd64
  • Then open the gradle-wrapper.properties file in your project folder, in the folder: project name/android/gradle/wrapper/gradle-wrapper.properties

  • Change the gradle version. Here I changed the gradle version to 6.5

The video version can be seen here: https://www.youtube.com/watch?v=mcclcscUpV0

"Gradle Version 2.10 is required." Error

for me all previous solutions failed, so i just edited

Project\gradle\wrapper\gradle-wrapper.properties -> field distributionUrl 
distributionUrl=https\://services.gradle.org/distributions/gradle-2.8-all.zip

to

distributionUrl=https://services.gradle.org/distributions/gradle-2.10-all.zip

Gradle version 2.2 is required. Current version is 2.10

I Had similar issue. Every project has his own gradle folder, check if in your project root there's another gradle folder:

/my_projects_root_folder/project/gradle
/my_projects_root_folder/gradle

If so, in every folder you'll find /gradle/wrapper/gradle-wrapper.properties.

Check if in /my_projects_root_folder/gradle/gradle-wrapper.properties gradle version at least match /my_projects_root_folder/ project/ gradle/ gradle-wrapper.properties gradle version

Or just delete/rename your /my_projects_root_folder/gradle and restart android studio and let Gradle sync work and download required gradle.

Android Studio Gradle: Error:Execution failed for task ':app:processDebugGoogleServices'. > No matching client found for package

Happened to me when switching flavors.

Now you can also use the google-services.json with different flavors.

See https://stackoverflow.com/a/34364376/570168

How can I install Python's pip3 on my Mac?

For me brew postinstall python3 didn't work. I found this solution on the GitHub Homebrew issues page:

$ brew rm python
$ rm -rf /usr/local/opt/python
$ brew cleanup
$ brew install python3

Could not determine the dependencies of task ':app:crashlyticsStoreDeobsDebug' if I enable the proguard

You can run this command in your project directory. Basically it just cleans the build and gradle.

   cd android && rm -R .gradle && cd app && rm -R build

In my case, I was using react-native using this as a script in package.json

"scripts": { "clean-android": "cd android && rm -R .gradle && cd app && rm -R build" }

Spring Boot @autowired does not work, classes in different package

In my case @component was not working because I initialized that class instance by using new <classname>().

If we initialize instance by conventional Java way anywhere in code, then spring won't add that component in IOC container.

android : Error converting byte to dex

I met the same problem,and i clean project ,some other problems causeed can not clean,so i manually delete dir 'build' ,so it can can clean Ok,then run it ok for me.

Error "File google-services.json is missing from module root folder. The Google Services Plugin cannot function without it"

Even after adding all the dependencies and the file if you face any such problem it could be your incorrect file name of "google-services.json".

Make sure you have the exact file name without any additional spaces or characters.

I had renamed the file and had space" " in my filename which was not noticeable, later I found that my file name is wrong, so fixed it!.

NodeJs : TypeError: require(...) is not a function

Just wrap in Arrow function where you requiring the files

Spring jUnit Testing properties file

As for the testing, you should use from Spring 4.1 which will overwrite the properties defined in other places:

@TestPropertySource("classpath:application-test.properties")

Test property sources have higher precedence than those loaded from the operating system's environment or Java system properties as well as property sources added by the application like @PropertySource

com.android.build.transform.api.TransformException

I resolved it with the next:

I configured multidex

In build.gradle you need to add the next one.

android {
...
   defaultConfig {
       ...
       // Enabling multidex support.
       multiDexEnabled true
       ...
   }
   dexOptions {
      incremental true
      maxProcessCount 4 // this is the default value
      javaMaxHeapSize "2g"
   }
...
}
dependencies {
...
   compile 'com.android.support:multidex:1.0.1'
...
}

Add the next one in local.properties

org.gradle.parallel=true
org.gradle.configureondemand=true
org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8

After that into Application class you need to add the Multidex too.

 public class MyApplication extends MultiDexApplication {

   @Override
   public void onCreate() {
       super.onCreate();
       //mas codigo
   }

   @Override
   protected void attachBaseContext(Context base) {
       super.attachBaseContext(base);
       MultiDex.install(this);
   }
}

Don't forget add the line code into Manifest.xml

<application
    ...
    android:name=".MyApplication"
    ...
/>

That's it with this was enough for resolve the bug: Execution failed for task ':app:transformClassesWithDexForDebug. Check very well into build.gradle with javaMaxHeapSize "2g" and the local.properties org.gradle.jvmargs=-Xmx2048m are of 2 gigabyte.

java.lang.IllegalStateException: Error processing condition on org.springframework.boot.autoconfigure.jdbc.JndiDataSourceAutoConfiguration

This error is because of multiple project having the offending resources.

Try out adding the dependencies projects other way around. (like in pom.xml or external depandancies)

enter image description here

The target principal name is incorrect. Cannot generate SSPI context

Integrated Security=false

Make this flag as false in webconfig connection string. It will work!

Spring - No EntityManager with actual transaction available for current thread - cannot reliably process 'persist' call

boardRepo.deleteByBoardId(id);

Faced the same issue. GOT javax.persistence.TransactionRequiredException: No EntityManager with actual transaction available for current thread

I resolved it by adding @Transactional annotation above the controller/service.

Module is not available, misspelled or forgot to load (but I didn't)

It should be

var app = angular.module("MesaViewer", []);

This is the syntax you need to define a module and you need the array to show it has no dependencies.

You use the

angular.module("MesaViewer");

syntax when you are referencing a module you've already defined.

Spring Boot: Cannot access REST Controller on localhost (404)

It also works if we use as follows:

@SpringBootApplication(scanBasePackages = { "<class ItemInventoryController package >.*" })

Error inflating class android.support.design.widget.NavigationView

This error can be caused due to reasons as mentioned below.

  1. This problem will likely occur when the version of your appcompat library and design support library doesn't match. Example of matching condition

     compile 'com.android.support:appcompat-v7:24.2.0' // appcompat library
    
     compile 'com.android.support:design:24.2.0' //design support library
    
  2. If your theme file in styles have only these two,

     <item name="colorPrimary">#4A0958</item>
     <item name="colorPrimaryDark">#4A0958</item>
    

then add ColorAccent too. It should look somewhat like this.

 <style name="AppTheme.Base" parent="Theme.AppCompat.Light.NoActionBar">

  <item name="colorPrimary">#4A0958</item>
  <item name="colorPrimaryDark">#4A0958</item>
  <item name="colorAccent">#4A0958</item>

 </style>

How do I edit $PATH (.bash_profile) on OSX?

You have to open that file with a text editor and then save it.

touch ~/.bash_profile; open ~/.bash_profile

It will open the file with TextEdit, paste your things and then save it. If you open it again you'll find your edits.

You can use other editors:

nano ~/.bash_profile
mate ~/.bash_profile
vim ~/.bash_profile

But if you don't know how to use them, it's easier to use the open approach.


Alternatively, you can rely on pbpaste. Copy

export ANDROID_HOME=/<installation location>/android-sdk-macosx
export PATH=${PATH}:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools

in the system clipboard and then in a shell run

pbpaste > ~/.bash_profile

Or alternatively you can also use cat

cat > ~/.bash_profile

(now cat waits for input: paste the two export definitions and then hit ctrl-D).

Execution failed for task ':app:compileDebugAidl': aidl is missing

To build your application without aidl is missing error with compileSdkVersion 23 and buildToolsVersion "23.0.1" you should specify latest versions for Android Gradle plugin (and Google Play Services Gradle plugin if you are using it) in main build.gradle file:

buildscript {
    repositories {
        ...
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.3.1'
        classpath 'com.google.gms:google-services:1.3.1'
    }
}

Override default Spring-Boot application.properties settings in Junit Test

If you're using Spring 5.2.5 and Spring Boot 2.2.6 and want to override just a few properties instead of the whole file. You can use the new annotation: @DynamicPropertySource

@SpringBootTest
@Testcontainers
class ExampleIntegrationTests {

    @Container
    static Neo4jContainer<?> neo4j = new Neo4jContainer<>();

    @DynamicPropertySource
    static void neo4jProperties(DynamicPropertyRegistry registry) {
        registry.add("spring.data.neo4j.uri", neo4j::getBoltUrl);
    }
}

Can't Autowire @Repository annotated interface in Spring Boot

You are scanning the wrong package:

@ComponentScan("**org**.pharmacy")

Where as it should be:

@ComponentScan("**com**.pharmacy")

Since your package names start with com and not org.

How to allow Cross domain request in apache2

Ubuntu Apache2 solution that worked for me .htaccess edit did not work for me I had to modify the conf file.

nano /etc/apache2/sites-available/mydomain.xyz.conf

my config that worked to allow CORS Support

<IfModule mod_ssl.c>
    <VirtualHost *:443>

        ServerName mydomain.xyz
        ServerAlias www.mydomain.xyz

        ServerAdmin [email protected]
        DocumentRoot /var/www/mydomain.xyz/public

        ### following three lines are for CORS support
        Header add Access-Control-Allow-Origin "*"
        Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
        Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined

        SSLCertificateFile /etc/letsencrypt/live/mydomain.xyz/fullchain.pem
        SSLCertificateKeyFile /etc/letsencrypt/live/mydomain.xyz/privkey.pem

    </VirtualHost>
</IfModule>

then type the following command

a2enmod headers

make sure cache is clear before trying

spark submit add multiple jars in classpath

I was trying to connect to mysql from the python code that was executed using spark-submit.

I was using HDP sandbox that was using Ambari. Tried lot of options such as --jars, --driver-class-path, etc, but none worked.

Solution

Copy the jar in /usr/local/miniconda/lib/python2.7/site-packages/pyspark/jars/

As of now I'm not sure if it's a solution or a quick hack, but since I'm working on POC so it kind of works for me.

Plugin is too old, please update to a more recent version, or set ANDROID_DAILY_OVERRIDE environment variable to

You should upgrade the version of gradle. for example: com.android.build.gradle 1.3.0

this issue occurs when version of the gradle is changed.

How to resolve this JNI error when trying to run LWJGL "Hello World"?

I had same issue using different dependancy what helped me is to set scope to compile.

<dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.0.1</version>
        <scope>compile</scope>
    </dependency>

Error:Execution failed for task ':app:dexDebug'. com.android.ide.common.process.ProcessException

Finally I solved this problem by changing compile 'com.google.guava:guava:18.0 ' to compile 'com.google.guava:guava-jdk5:17.0'

Hadoop cluster setup - java.net.ConnectException: Connection refused

  • Stop it by-: stop-all.sh

  • format the namenode-: hadoop namenode -format

  • again start-: start-all.sh

"Could not find acceptable representation" using spring-boot-starter-web

I had a similar error using spring/jhipster RESTful service (via Postman)

The endpoint was something like:

@RequestMapping(value = "/index-entries/{id}",
        method = RequestMethod.GET,
        produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public ResponseEntity<IndexEntry> getIndexEntry(@PathVariable Long id) {

I was attempting to call the restful endpoint via Postman with header Accept: text/plain but I needed to use Accept: application/json

Java GC (Allocation Failure)

"Allocation Failure" is a cause of GC cycle to kick in.

"Allocation Failure" means that no more space left in Eden to allocate object. So, it is normal cause of young GC.

Older JVM were not printing GC cause for minor GC cycles.

"Allocation Failure" is almost only possible cause for minor GC. Another reason for minor GC to kick could be CMS remark phase (if +XX:+ScavengeBeforeRemark is enabled).

gpg decryption fails with no secret key error

You can also be interested at the top answer in here: https://askubuntu.com/questions/1080204/gpg-problem-with-the-agent-permission-denied

basically the solution that worked for me too is:

gpg --decrypt --pinentry-mode=loopback <file>

Spring Could not Resolve placeholder

Hopefully it will be still helpful, the application.properties (or application.yml) file must be in both the paths:

  • src/main/resource/config
  • src/test/resource/config

containing the same property you are referring

Spring Boot - Error creating bean with name 'dataSource' defined in class path resource

I solved my problem with the change of the parent Spring Boot Dependency.

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.0.RELEASE</version>
</parent>

to

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.6.RELEASE</version>
</parent>

For more Information, take a look at the release notes: Spring Boot 2.1.0 Release Notes

Android Studio Gradle DSL method not found: 'android()' -- Error(17,0)

This error has occurred when i was importing a project from Github. This happens as the project was of older version. Just try to delete these methods below from your root gradle.

android { compileSdkVersion 19 buildToolsVersion "19.1" }

then try again.

I hope it works.

Specifying trust store information in spring boot application.properties

I have the same problem, I'll try to explain it a bit more in detail.

I'm using spring-boot 1.2.2-RELEASE and tried it on both Tomcat and Undertow with the same result.

Defining the trust-store in application.yml like:

server:
  ssl:
    trust-store: path-to-truststore...
    trust-store-password: my-secret-password...

Doesn't work, while:

$ java -Djavax.net.debug=ssl -Djavax.net.ssl.trustStore=path-to-truststore... -Djavax.net.ssl.trustStorePassword=my-secret-password... -jar build/libs/*.jar  

works perfectly fine.

The easiest way to see the difference at rutime is to enable ssl-debug in the client. When working (i.e. using -D flags) something like the following is written to the console (during processing of the first request):

trustStore is: path-to-truststore...
trustStore type is : jks
trustStore provider is :
init truststore
adding as trusted cert:
  Subject: C=..., ST=..., O=..., OU=..., CN=...
  Issuer:  C=..., ST=..., O=..., OU=..., CN=...
  Algorithm: RSA; Serial number: 0x4d2
  Valid from Wed Oct 16 17:58:35 CEST 2013 until Tue Oct 11 17:58:35 CEST 2033

Without the -D flags I get:

trustStore is: /Library/Java/JavaVirtualMachines/jdk1.8.0_11.jdk/Contents/Home/jre/lib/security/cacerts
trustStore type is : jks
trustStore provider is :
init truststore
adding as trusted cert: ... (one for each CA-cert in the defult truststore)

...and when performing a request I get the exception:

sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

Hope it helps to understand the issue better!

Understanding passport serialize deserialize

For anyone using Koa and koa-passport:

Know that the key for the user set in the serializeUser method (often a unique id for that user) will be stored in:

this.session.passport.user

When you set in done(null, user) in deserializeUser where 'user' is some user object from your database:

this.req.user OR this.passport.user

for some reason this.user Koa context never gets set when you call done(null, user) in your deserializeUser method.

So you can write your own middleware after the call to app.use(passport.session()) to put it in this.user like so:

app.use(function * setUserInContext (next) {
  this.user = this.req.user
  yield next
})

If you're unclear on how serializeUser and deserializeUser work, just hit me up on twitter. @yvanscher

Gradle task - pass arguments to Java application

Of course the answers above all do the job, but still i would like to use something like

gradle run path1 path2

well this can't be done, but what if we can:

gralde run --- path1 path2

If you think it is more elegant, then you can do it, the trick is to process the command line and modify it before gradle does, this can be done by using init scripts

The init script below:

  1. Process the command line and remove --- and all other arguments following '---'
  2. Add property 'appArgs' to gradle.ext

So in your run task (or JavaExec, Exec) you can:

if (project.gradle.hasProperty("appArgs")) {
                List<String> appArgs = project.gradle.appArgs;

                args appArgs

 }

The init script is:

import org.gradle.api.invocation.Gradle

Gradle aGradle = gradle

StartParameter startParameter = aGradle.startParameter

List tasks = startParameter.getTaskRequests();

List<String> appArgs = new ArrayList<>()

tasks.forEach {
   List<String> args = it.getArgs();


   Iterator<String> argsI = args.iterator();

   while (argsI.hasNext()) {

      String arg = argsI.next();

      // remove '---' and all that follow
      if (arg == "---") {
         argsI.remove();

         while (argsI.hasNext()) {

            arg = argsI.next();

            // and add it to appArgs
            appArgs.add(arg);

            argsI.remove();

        }
    }
}

}


   aGradle.ext.appArgs = appArgs

Limitations:

  1. I was forced to use '---' and not '--'
  2. You have to add some global init script

If you don't like global init script, you can specify it in command line

gradle -I init.gradle run --- f:/temp/x.xml

Or better add an alias to your shell:

gradleapp run --- f:/temp/x.xml

Android Studio update -Error:Could not run build action using Gradle distribution

I have run into a similar problem on Mac.

Looking at the log under Help -> Show logs in Finder I found the following entry.

You have JVM property "https.proxyHost" set to "127.0.0.1".
This may lead to incorrect behaviour. Proxy should be set in Settings | HTTP Proxy
This JVM property is old and its usage is not recommended by Oracle.
(Note: It could have been assigned by some code dynamically.)

and it turned out I had Charles as a network proxy running. Shutting down Charles solved the problem.

Using Excel VBA to run SQL query

Below is code that I currently use to pull data from a MS SQL Server 2008 into VBA. You need to make sure you have the proper ADODB reference [VBA Editor->Tools->References] and make sure you have Microsoft ActiveX Data Objects 2.8 Library checked, which is the second from the bottom row that is checked (I'm using Excel 2010 on Windows 7; you might have a slightly different ActiveX version, but it will still begin with Microsoft ActiveX):

References required for SQL

Sub Module for Connecting to MS SQL with Remote Host & Username/Password

Sub Download_Standard_BOM()
'Initializes variables
Dim cnn As New ADODB.Connection
Dim rst As New ADODB.Recordset
Dim ConnectionString As String
Dim StrQuery As String

'Setup the connection string for accessing MS SQL database
   'Make sure to change:
       '1: PASSWORD
       '2: USERNAME
       '3: REMOTE_IP_ADDRESS
       '4: DATABASE
    ConnectionString = "Provider=SQLOLEDB.1;Password=PASSWORD;Persist Security Info=True;User ID=USERNAME;Data Source=REMOTE_IP_ADDRESS;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Use Encryption for Data=False;Tag with column collation when possible=False;Initial Catalog=DATABASE"

    'Opens connection to the database
    cnn.Open ConnectionString
    'Timeout error in seconds for executing the entire query; this will run for 15 minutes before VBA timesout, but your database might timeout before this value
    cnn.CommandTimeout = 900

    'This is your actual MS SQL query that you need to run; you should check this query first using a more robust SQL editor (such as HeidiSQL) to ensure your query is valid
    StrQuery = "SELECT TOP 10 * FROM tbl_table"

    'Performs the actual query
    rst.Open StrQuery, cnn
    'Dumps all the results from the StrQuery into cell A2 of the first sheet in the active workbook
    Sheets(1).Range("A2").CopyFromRecordset rst
End Sub

variable is not declared it may be inaccessible due to its protection level

This error occurred for me when I mistakenly added a comment following a line continuation character in VB.Net. I removed the comment and the problem went away.

How do I use tools:overrideLibrary in a build.gradle file?

As library requires minSdkVersion 17 then you can change the same in build.gradle(Module:Application) file:

defaultConfig {
        minSdkVersion 17 
        targetSdkVersion 25
}

and after that building the project should not throw any build error.

Multipart File Upload Using Spring Rest Template + Spring Web MVC

For those who are getting the error as:

I/O error on POST request for "anothermachine:31112/url/path";: class path 
resource [fileName.csv] cannot be resolved to URL because it does not exist.

It can be resolved by using the

LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
map.add("file", new FileSystemResource(file));

If the file is not present in the classpath, and an absolute path is required.

Intellij Cannot resolve symbol on import

I tried invalidating caches and restarting, but the only thing that worked for me was wiping out the .idea directory completely, then creating a new project from scratch.

"The system cannot find the file C:\ProgramData\Oracle\Java\javapath\java.exe"

This will solve all problems relating to Java and environment variables:

  1. Make your way to Windows' Environment Variables dialog.
  2. Under System variables, select the variable named Path. Click Edit...
  3. Remove the entry that looks like:

    C:\ProgramData\Oracle\Java\javapath
    
  4. Add the path of your JDK/JRE's bin folder.

  5. Don't forget to set JAVA_HOME.

Android Studio - Unable to find valid certification path to requested target

I'm in an enterprise environment with a proxy/firewall/virus-scanner combination adding the company own SSL root certificate (self signed) to the trustpath of every SSL connection to investigate also into SSL connections. That was exactly the problem. If you are in the same situation this solution could help:

  1. Open https://jcenter.bintray.com in the browser (I prefer Firefox)
  2. Click on the padlock symbold to check the certificated trustpath. If the top/root certificate in the tree is a certficate signed by your company export it to your harddisk.
  3. To be safe export also every certificate in between
  4. Open the truststore of Android Studio in path JDKPATH/jre/lib/security/cacerts with the Keystore Explorer tool Keystore Exlorer with password "changeit"
  5. Import the exported certs into the trusstore starting with the root certificate of you company and go the step 6. In the most cases this will do the trick. If not, import the other certs as well step by step.
  6. Save the truststore
  7. Exit Android Studio with "File -> Invalidate Caches/Restart"

Eclipse - Installing a new JRE (Java SE 8 1.8.0)

You can have many java versions in your system.

I think you should add the java 8 in yours JREs installed or edit.

Take a look my screen:

enter image description here

If you click in edit (check your java 8 path):

enter image description here

Spring Hibernate - Could not obtain transaction-synchronized Session for current thread

Check your dao class. It must be like this:

Session session = getCurrentSession();
Query query = session.createQuery(GET_ALL);

And annotations:

@Transactional
@Repository

Spring Boot: Is it possible to use external application.properties files in arbitrary directories with a fat jar?

You would be able to launch your spring boot appication with the external properties file path as follows:

java -jar {jar-file-name}.jar 
--spring.config.location=file:///C:/{file-path}/{file-name}.properties

No found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations:

In my case I had to move the @Service annotation from the interface to the implementation class.

Eclipse error "Could not find or load main class"

I had this error. It was because I had static void main(String[] args)
instead of public static void main(String[] args)

I spent nearly an hour trying to figure that out.

Note: The only difference is that I didn't declare main to be public

Could not resolve all dependencies for configuration ':classpath'

Find and Replace:

jcenter()
maven {
    url "https://maven.google.com"
}

to:

maven {
    url "https://maven.google.com"
}
jcenter()

Classpath resource not found when running as jar

Regarding to the originally error message

cannot be resolved to absolute file path because it does not reside in the file system

The following code could be helpful, to find the solution for the path problem:

Paths.get("message.txt").toAbsolutePath().toString();

With this you can determine, where the application expects the missing file. You can execute this in the main method of your application.

Spring Boot and multiple external configuration files

spring boot allows us to write different profiles to write for different environments, for example we can have separate properties files for production, qa and local environments

application-local.properties file with configurations according to my local machine is

spring.profiles.active=local

spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=users
spring.data.mongodb.username=humble_freak
spring.data.mongodb.password=freakone

spring.rabbitmq.host=localhost
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
spring.rabbitmq.port=5672

rabbitmq.publish=true

Similarly, we can write application-prod.properties and application-qa.properties as many properties files as we want

then write some scripts to start the application for different environments, for e.g.

mvn spring-boot:run -Drun.profiles=local
mvn spring-boot:run -Drun.profiles=qa
mvn spring-boot:run -Drun.profiles=prod

Where can I download mysql jdbc jar from?

Go to http://dev.mysql.com/downloads/connector/j and with in the dropdown select "Platform Independent" then it will show you the options to download tar.gz file or zip file.

Download zip file and extract it, with in that you will find mysql-connector-XXX.jar file

If you are using maven then you can add the dependency from the link http://mvnrepository.com/artifact/mysql/mysql-connector-java

Select the version you want to use and add the dependency in your pom.xml file

Error: org.testng.TestNGException: Cannot find class in classpath: EmpClass

I also ran into the same problem with TestNG version 6.14.2

However, this was due to a foolish mistake on my end and there is no issue whatsoever with maven, testng or eclipse. What I was doing was -

  1. Run project as "mvn clean"
  2. Select "testng.xml" file and right click on it to run as TestNG suite
  3. This was giving me the same error as reported in the original question
  4. I soon realized that I have not compiled the project and the required class files have not been generated that the TestNG would utilize subsequently
  5. The "target" folder will be generated only after the project is compiled (Run as "mvn build")
  6. If your project is compiled, this issue should not be there.

How to check the gradle version in Android Studio?

I know this is really old and most of the folks have already answered it right. Here are at least two ways you can find out the gradle version (not the gradle plugin version) by selecting one of the following on project tab on left:

  1. Android > Gradle Scripts > gradle-wrapper.properties (Gradle Version) > distributionURL
  2. Project > .gradle > x.y.z <--- this is your gradle version

How to turn off INFO logging in Spark?

Inspired by the pyspark/tests.py I did

def quiet_logs(sc):
    logger = sc._jvm.org.apache.log4j
    logger.LogManager.getLogger("org"). setLevel( logger.Level.ERROR )
    logger.LogManager.getLogger("akka").setLevel( logger.Level.ERROR )

Calling this just after creating SparkContext reduced stderr lines logged for my test from 2647 to 163. However creating the SparkContext itself logs 163, up to

15/08/25 10:14:16 INFO SparkDeploySchedulerBackend: SchedulerBackend is ready for scheduling beginning after reached minRegisteredResourcesRatio: 0.0

and it's not clear to me how to adjust those programmatically.

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

Make sure you have the latest values in your gradle files. As of this writing:

  • buildToolsVersion "21.1.2"

  • dependencies { classpath 'com.android.tools.build:gradle:1.1.0' }

Android Studio Google JAR file causing GC overhead limit exceeded error

In my case, to increase the heap-size looks like this:

Using Android Studio 1.1.0

android {
    dexOptions {
        incremental true
        javaMaxHeapSize "2048M"
    }
}

Put the above code in your Build.gradle file.

How to create JNDI context in Spring Boot with Embedded Tomcat Container

After all i got the answer thanks to wikisona, first the beans:

@Bean
public TomcatEmbeddedServletContainerFactory tomcatFactory() {
    return new TomcatEmbeddedServletContainerFactory() {

        @Override
        protected TomcatEmbeddedServletContainer getTomcatEmbeddedServletContainer(
                Tomcat tomcat) {
            tomcat.enableNaming();
            return super.getTomcatEmbeddedServletContainer(tomcat);
        }

        @Override
        protected void postProcessContext(Context context) {
            ContextResource resource = new ContextResource();
            resource.setName("jdbc/myDataSource");
            resource.setType(DataSource.class.getName());
            resource.setProperty("driverClassName", "your.db.Driver");
            resource.setProperty("url", "jdbc:yourDb");

            context.getNamingResources().addResource(resource);
        }
    };
}

@Bean(destroyMethod="")
public DataSource jndiDataSource() throws IllegalArgumentException, NamingException {
    JndiObjectFactoryBean bean = new JndiObjectFactoryBean();
    bean.setJndiName("java:comp/env/jdbc/myDataSource");
    bean.setProxyInterface(DataSource.class);
    bean.setLookupOnStartup(false);
    bean.afterPropertiesSet();
    return (DataSource)bean.getObject();
}

the full code it's here: https://github.com/wilkinsona/spring-boot-sample-tomcat-jndi

How to count digits, letters, spaces for a string in Python?


# Write a Python program that accepts a string and calculate the number of digits 
# andletters.

    stre =input("enter the string-->")
    countl = 0
    countn = 0
    counto = 0
    for i in stre:
        if i.isalpha():
            countl += 1
        elif i.isdigit():
            countn += 1
        else:
            counto += 1
    print("The number of letters are --", countl)
    print("The number of numbers are --", countn)
    print("The number of characters are --", counto)

Error:(1, 0) Plugin with id 'com.android.application' not found

This may also happen when you have both settings.gradle and settings.gradle.kts files are present in project root directory (possibly with the same module included). You should only have one of these files.

Composer Update Laravel

The following works for me:

composer update --no-scripts

Failed to load ApplicationContext from Unit Test: FileNotFound

Give the below

@ContextConfiguration(locations =  {"classpath*:/spring/test-context.xml"})

And in pom.xml give the following plugin:

<plugin>
   <groupId>org.apache.maven.plugins</groupId>
   <artifactId>maven-surefire-plugin</artifactId>
   <version>2.20.1</version>
<configuration>
    <additionalClasspathElements>
       <additionalClasspathElement>${basedir}/src/test/resources</additionalClasspathElement>
    </additionalClasspathElements>
</configuration>

Could not extract response: no suitable HttpMessageConverter found for response type

As Artem Bilan said, this problem occures because MappingJackson2HttpMessageConverter supports response with application/json content-type only. If you can't change server code, but can change client code(I had such case), you can change content-type header with interceptor:

restTemplate.getInterceptors().add((request, body, execution) -> {
            ClientHttpResponse response = execution.execute(request,body);
            response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
            return response;
        });

Spring data jpa- No bean named 'entityManagerFactory' is defined; Injection of autowired dependencies failed

I had the same problem and got it resolved by deleting .m2 maven repo (C:\Users\user\ .m2)

How do I choose the URL for my Spring Boot webapp?

You need to set the property server.contextPath to /myWebApp.

Check out this part of the documentation

The easiest way to set that property would be in the properties file you are using (most likely application.properties) but Spring Boot provides a whole lot of different way to set properties. Check out this part of the documentation

EDIT

As has been mentioned by @AbdullahKhan, as of Spring Boot 2.x the property has been deprecated and should be replaced with server.servlet.contextPath as has been correctly mentioned in this answer.

Manifest merger failed : uses-sdk:minSdkVersion 14

You just change Minimum API Level from Build Settings -> Player Settings -> Other Settings -> Minimum SDK Level to some higher version.

bodyParser is deprecated express 4

What is your opinion to use express-generator it will generate skeleton project to start with, without deprecated messages appeared in your log

run this command

npm install express-generator -g

Now, create new Express.js starter application by type this command in your Node projects folder.

express node-express-app

That command tell express to generate new Node.js application with the name node-express-app.

then Go to the newly created project directory, install npm packages and start the app using the command

cd node-express-app && npm install && npm start

Spring Boot - Cannot determine embedded database driver class for database type NONE

If you really need "spring-boot-starter-data-jpa" as your project dependency and at the same time you don't want to allow your app to access any database, you can simply exclude auto-configuration classes

@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)

Lombok annotations do not compile under Intellij idea

For me, both lombok plugin and annotation processing enable needed, no else. No need to Use Eclipse and additional -javaagent:lombok.jar options.

  • Idea 14.1.3, build 141.1010
  • Lombok plugin[Preference->plugins->browse repositories->search 'lombok'->install and restart idea.
  • Preference ->search 'annotation'->enter annotation processor ->enable annotation processing.

Disable Logback in SpringBoot

Adding exclusions was not enough for me. I had to provide a fake jar:

    <dependency>
        <groupId>ch.qos.logback</groupId>
        <artifactId>logback-classic</artifactId>
        <scope>system</scope>
        <systemPath>${project.basedir}/empty.jar</systemPath>
    </dependency>

Spring boot Security Disable security

Add the below lines to your main app.

Remove org.activiti.spring.boot.SecurityAutoConfiguration.class if you're not using activiti.

Similarly, remove the one for actuator if you're not using spring-boot-actuator.

@EnableAutoConfiguration(exclude = {
org.activiti.spring.boot.SecurityAutoConfiguration.class,
org.springframework.boot.actuate.autoconfigure.ManagementWebSecurityAutoConfiguration.class,
org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration.class })

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'MyController':

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'MyController'

Make sure that you have added ojdbc14.jar into your library.

For oracle 11g, usie ojdbc6.jar.

Project with path ':mypath' could not be found in root project 'myproject'

Remove all the texts in android/settings.gradle and paste the below code

rootProject.name = '****Your Project Name****'
apply from: file("../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesSettingsGradle(settings)
include ':app'

This issue will usually happen when you migrate from react-native < 0.60 to react-native >0.60. If you create a new project in react-native >0.60 you will see the same settings as above mentioned

How to encrypt and decrypt String with my passphrase in Java (Pc not mobile platform)?

The code marked as the solution did not work for me. This was my solution.

/*
 * http://www.java2s.com/Code/Java/Security/EncryptingaStringwithDES.htm
 * https://stackoverflow.com/questions/23561104/how-to-encrypt-and-decrypt-string-with-my-passphrase-in-java-pc-not-mobile-plat
 */
package encryptiondemo;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;


/**
 *
 * @author zchumager
 */
public class EncryptionDemo {

  Cipher ecipher;
  Cipher dcipher;

  EncryptionDemo(SecretKey key) throws Exception {
    ecipher = Cipher.getInstance("AES");
    dcipher = Cipher.getInstance("AES");
    ecipher.init(Cipher.ENCRYPT_MODE, key);
    dcipher.init(Cipher.DECRYPT_MODE, key);
  }

  public String encrypt(String str) throws Exception {
    // Encode the string into bytes using utf-8
    byte[] utf8 = str.getBytes("UTF8");

    // Encrypt
    byte[] enc = ecipher.doFinal(utf8);

    // Encode bytes to base64 to get a string
    return new sun.misc.BASE64Encoder().encode(enc);
  }

  public String decrypt(String str) throws Exception {
    // Decode base64 to get bytes
    byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);

    byte[] utf8 = dcipher.doFinal(dec);

    // Decode using utf-8
    return new String(utf8, "UTF8");
  }


    public static void main(String args []) throws Exception
    {

        String data = "Don't tell anybody!";
        String k = "Bar12345Bar12345";

        //SecretKey key = KeyGenerator.getInstance("AES").generateKey();
        SecretKey key = new SecretKeySpec(k.getBytes(), "AES");
        EncryptionDemo encrypter = new EncryptionDemo(key);

        System.out.println("Original String: " + data);

        String encrypted = encrypter.encrypt(data);

        System.out.println("Encrypted String: " + encrypted);

        String decrypted = encrypter.decrypt(encrypted);

        System.out.println("Decrypted String: " + decrypted);
    }
}

org.apache.tomcat.util.bcel.classfile.ClassFormatException: Invalid byte tag in constant pool: 15

Update to Tomcat 7.0.58 (or newer).

See: https://bz.apache.org/bugzilla/show_bug.cgi?id=57173#c16

The performance improvement that triggered this regression has been reverted from from trunk, 8.0.x (for 8.0.16 onwards) and 7.0.x (for 7.0.58 onwards) and will not be reapplied.

"Could not find or load main class" Error while running java program using cmd prompt

I had the same problem, mine was a little different though I did not have a package name. My problem was the Class Path for example:

C:\Java Example>java -cp . HelloWorld 

The -cp option for Java and from what I can tell from my experience (not much) but I encountered the error about 20 times trying different methods and until I declared the class Path I was receiving the same error. Vishrant was correct in stating that . represents current directory.

If you need more information about the java options enter java -? or java -help I think the options are not optional.

I just did some more research I found a website that goes into detail about CLASSPATH. The CLASSPATH must be set as an environment variable; to the current directory <.>. You can set it from the command line in windows:

// Set CLASSPATH to the current directory '.'
prompt> set CLASSPATH=.

When you add a new environment setting you need to reboot before enabling the variable. But from the command prompt you can set it. It also can be set like I mentioned at the beginning. For more info, and if your using a different OS, check: Environment Variables.

Access all Environment properties as a Map or Properties object

This is an old question, but the accepted answer has a serious flaw. If the Spring Environment object contains any overriding values (as described in Externalized Configuration), there is no guarantee that the map of property values it produces will match those returned from the Environment object. I found that simply iterating through the PropertySources of the Environment did not, in fact, give any overriding values. Instead it produced the original value, the one that should have been overridden.

Here is a better solution. This uses the EnumerablePropertySources of the Environment to iterate through the known property names, but then reads the actual value out of the real Spring environment. This guarantees that the value is the one actually resolved by Spring, including any overriding values.

Properties props = new Properties();
MutablePropertySources propSrcs = ((AbstractEnvironment) springEnv).getPropertySources();
StreamSupport.stream(propSrcs.spliterator(), false)
        .filter(ps -> ps instanceof EnumerablePropertySource)
        .map(ps -> ((EnumerablePropertySource) ps).getPropertyNames())
        .flatMap(Arrays::<String>stream)
        .forEach(propName -> props.setProperty(propName, springEnv.getProperty(propName)));

Saving binary data as file using JavaScript from a browser

Try

_x000D_
_x000D_
let bytes = [65,108,105,99,101,39,115,32,65,100,118,101,110,116,117,114,101];_x000D_
_x000D_
let base64data = btoa(String.fromCharCode.apply(null, bytes));_x000D_
_x000D_
let a = document.createElement('a');_x000D_
a.href = 'data:;base64,' + base64data;_x000D_
a.download = 'binFile.txt'; _x000D_
a.click();
_x000D_
_x000D_
_x000D_

I convert here binary data to base64 (for bigger data conversion use this) - during downloading browser decode it automatically and save raw data in file. 2020.06.14 I upgrade Chrome to 83.0 and above SO snippet stop working (probably due to sandbox security restrictions) - but JSFiddle version works - here

use "netsh wlan set hostednetwork ..." to create a wifi hotspot and the authentication can't work correctly

Problem solved.

Just drop down status bar, touch Choose input method, then change to another input method, type the password again. And everything is OK.

So weird...

Solution from a Chinese BBS. Thanks for the answer's author and all above who try to provide a solution, thanks!

How do I mock an autowired @Value field in Spring with Mockito?

You can also mock your property configuration into your test class

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({ "classpath:test-context.xml" })
public class MyTest 
{ 
   @Configuration
   public static class MockConfig{
       @Bean
       public Properties myProps(){
             Properties properties = new Properties();
             properties.setProperty("default.url", "myUrl");
             properties.setProperty("property.value2", "value2");
             return properties;
        }
   }
   @Value("#{myProps['default.url']}")
   private String defaultUrl;

   @Test
   public void testValue(){
       Assert.assertEquals("myUrl", defaultUrl);
   }
}

org.hibernate.hql.internal.ast.QuerySyntaxException: table is not mapped

add parameter nativeQuery = true

ex: @Query(value="Update user set user_name =:user_name,password =:password where user_id =:user_id",nativeQuery = true)

INFO: No Spring WebApplicationInitializer types detected on classpath

I had this info message "No Spring WebApplicationInitializer types detected on classpath" while deploying a WAR with spring integration beans in WebLogic server. Actually, I could observe that the servlet URL returned 404 Not Found and beside that info message with a negative tone "No Spring ...etc" in Server logs, nothing else was seemingly in error in my spring config; no build or deployment errors, no complaints. Indeed, I suspected that the beans.xml (spring context XML) was actually not picked up at all and that was bound to the very specific organizing of artefacts in Oracle's jDeveloper. The solution is to play carefully with the 'contributors' and 'filters' for the WEB-INF/classes category when you edit your deployment profile under the 'deployment' topic in project properties.

Precisely, I would advise to name your spring context by the jDeveloper default "beans.xml" and place it side by side to the WEB-INF subdirectory itself (under your web Apllication source path, e.g. like <...your project path>/public_html/). Then in the WEB-INF/classes category (when editing the deployment profile) your can check the Project HTML root directory in the 'contributor' list, and then select the beans.xml in filters, and then ensure your web.xml features a context-param value like classpath:beans.xml.

Once that was fixed, I was able to progress and after some more bean config changes and implementations, the message "No Spring WebApplicationInitializer types detected on classpath" came back! Actually, I did not notice when and why exactly it came back. This second time, I added a

public class HttpGatewayInit implements WebApplicationInitializer { ... }

which implements empty inherited methods, and the whole application works fine!

...If you feel that java EE development has been getting a bit too crazy with cascades of XML configuration files (some edited manually, others through wizards) intepreted by cascades of variant initializers, let me insist that I fully share your point.

Error: Configuration with name 'default' not found in Android Studio

If suppose you spotted this error after removing certain node modules, ideally should not be present the library under build.gradle(Module:app) . It can be removed manually and sync the project again.

"No cached version... available for offline mode."

With the new Android Studio 3.6 to toggle Gradle's offline mode go to View > Tool Windows > Gradle from the menu bar and toggle the value of Offline Mode that is near the top of the Gradle window.

enter image description here

enter image description here

Unable to load AWS credentials from the /AwsCredentials.properties file on the classpath

In my case I was deploying my webapp inside a docker: I was setting

ENV AWS_ACCESS_KEY_ID=blahblah%&/(
ENV AWS_SECRET_ACCESS_KEY=supersecret%&/(

but I still got errors, I got fixed this by adding

cloud.aws.credentials.useDefaultAwsCredentialsChain=true

inside application.properties

Configuration with name 'default' not found. Android Studio

The message is a known Gradle bug. The reason of your error is that some of your gradle.build files has no apply plugin: 'java' in it. And due to the bug Gradle doesn't say you, where is the problem.

But you can easily overcome it. Simply put apply plugin: 'java' in every your 'gradle.build'

Extension exists but uuid_generate_v4 fails

If the extension is already there but you don't see the uuid_generate_v4() function when you do a describe functions \df command then all you need to do is drop the extension and re-add it so that the functions are also added. Here is the issue replication:

db=# \df
                       List of functions
 Schema | Name | Result data type | Argument data types | Type
--------+------+------------------+---------------------+------
(0 rows)
CREATE EXTENSION "uuid-ossp";
ERROR:  extension "uuid-ossp" already exists
DROP EXTENSION "uuid-ossp";
CREATE EXTENSION "uuid-ossp";
db=# \df
                                  List of functions
 Schema |        Name        | Result data type |    Argument data types    |  Type
--------+--------------------+------------------+---------------------------+--------
 public | uuid_generate_v1   | uuid             |                           | normal
 public | uuid_generate_v1mc | uuid             |                           | normal
 public | uuid_generate_v3   | uuid             | namespace uuid, name text | normal
 public | uuid_generate_v4   | uuid             |                           | normal

db=# select uuid_generate_v4();
           uuid_generate_v4
--------------------------------------
 b19d597c-8f54-41ba-ba73-02299c1adf92
(1 row)

What probably happened is that the extension was originally added to the cluster at some point in the past and then you probably created a new database within that cluster afterward. If that was the case then the new database will only be "aware" of the extension but it will not have the uuid functions added which happens when you add the extension. Therefore you must re-add it.

The model backing the 'ApplicationDbContext' context has changed since the database was created

This post fixed my issue. It's all about adding the following line in Application_Start() in Global.asax :

Database.SetInitializer<Models.YourDbContext>(null);

However it cause database recreation for every edit in your model and you may loose your data.

AngularJS: Uncaught Error: [$injector:modulerr] Failed to instantiate module?

Try using No Wrap - In Head or No wrap - in body in your fiddle:

Working fiddle: http://jsfiddle.net/Q5hd6/

Explanation:

Angular begins compiling the DOM when the DOM is fully loaded. You register your code to run onLoad (onload option in fiddle) => it's too late to register your myApp module because angular begins compiling the DOM and angular sees that there is no module named myApp and throws an exception.

By using No Wrap - In Head, your code looks like this:

<head>

    <script type='text/javascript' src='//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.1/angular.js'></script>

    <script type='text/javascript'>
      //Your script.
    </script>

</head>

Your script has a chance to run before angular begins compiling the DOM and myApp module is already created when angular starts compiling the DOM.

how to configure lombok in eclipse luna

Step 1: Goto https://projectlombok.org/download and click on 1.18.2

Step 2: Place your jar file in java installation path in my case it is C:\Program Files\Java\jdk-10.0.1\lib

step 3: Open your Eclipse IDE folder where you have in your PC.

Step 4: Add the place where I added then open your IDE it will open without any errors.

-startup
plugins/org.eclipse.equinox.launcher_1.5.0.v20180512-1130.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_64_1.1.700.v20180518-1200
-product
org.eclipse.epp.package.jee.product
-showsplash
org.eclipse.epp.package.common
--launcher.defaultAction
openFile
--launcher.defaultAction
openFile
--launcher.appendVmargs
-vmargs
-Dosgi.requiredJavaVersion=1.8
-javaagent:C:\Program Files\Java\jdk-10.0.1\lib\lombok.jar
-Xbootclasspath/a:C:\Program Files\Java\jdk-10.0.1\lib\lombok.jar
[email protected]/eclipse-workspace
-XX:+UseG1GC
-XX:+UseStringDeduplication
--add-modules=ALL-SYSTEM
-Dosgi.requiredJavaVersion=1.8
-Dosgi.dataAreaRequiresExplicitInit=true
-Xms256m
-Xmx1024m
--add-modules=ALL-SYSTEM

System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll?

This is not a problem with XAML. The error message is saying that it tried to create an instance of DVRClientInterface.MainWindow and your constructor threw an exception.

You will need to look at the "Inner Exception" property to determine the underlying cause. It could be quite literally anything, but should provide direction.

example of an inner exception shown in Visual Studio

An example would be that if you are connecting to a database in the constructor for your window, and for some reason that database is unavailable, the inner exception may be a TimeoutException or a SqlException or any other exception thrown by your database code.

If you are throwing exceptions in static constructors, the exception could be generated from any class referenced by the MainWindow. Class initializers are also run, if any MainWindow fields are calling a method which may throw.

Set UITableView content inset permanently

Probably it was some sort of my mistake because of me messing with autolayouts and storyboard but I found an answer.

You have to take care of this little guy in View Controller's Attribute Inspector asvi

It must be unchecked so the default contentInset wouldn't be set after any change. After that it is just adding one-liner to viewDidLoad:

[self.tableView setContentInset:UIEdgeInsetsMake(108, 0, 0, 0)]; // 108 is only example

iOS 11, Xcode 9 update

Looks like the previous solution is no longer a correct one if it comes to iOS 11 and Xcode 9. automaticallyAdjustsScrollViewInsets has been deprecated and right now to achieve similar effect you have to go to Size Inspector where you can find this: enter image description here
Also, you can achieve the same in code:

if #available(iOS 11.0, *) {
    scrollView.contentInsetAdjustmentBehavior = .never
} else {
    automaticallyAdjustsScrollViewInsets = false
}

How to write JUnit test with Spring Autowire?

I've done it with two annotations for test class: @RunWith(SpringRunner.class) and @SpringBootTest. Example:

@RunWith(SpringRunner.class )
@SpringBootTest
public class ProtocolTransactionServiceTest {

    @Autowired
    private ProtocolTransactionService protocolTransactionService;
}

@SpringBootTest loads the whole context, which was OK in my case.

How to download dependencies in gradle

There is no task to download dependencies; they are downloaded on demand. To learn how to manage dependencies with Gradle, see "Chapter 8. Dependency Management Basics" in the Gradle User Guide.

Spring Boot: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean

check your pom.xml is exists

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
    </dependency>

I've had a problem like this;For lack this dependency

http://localhost:8080/ Access Error: 404 -- Not Found Cannot locate document: /

When I had an error Access Error: 404 -- Not Found I fixed it by doing the following:

  1. Open command prompt and type "netstat -aon" (without the quotes)
  2. Search for port 8080 and look at its PID number/code.
  3. Open Task Manager (CTRL+ALT+DELETE), go to Services tab, and find the service with the exact PID number. Then right click it and stop the process.

Autoincrement VersionCode with gradle extra properties

Create file version.properties

MAJOR=1
MINOR=3
PATCH=6
VERSION_CODE=1

Change build.gradle :

android {
def _versionCode=0
def _major=0
def _minor=0
def _patch=0

def _applicationId = "com.example.test"

def versionPropsFile = file('version.properties')

if (versionPropsFile.canRead()) {
    def Properties versionProps = new Properties()

    versionProps.load(new FileInputStream(versionPropsFile))

    _patch = versionProps['PATCH'].toInteger() + 1
    _major = versionProps['MAJOR'].toInteger()
    _minor = versionProps['MINOR'].toInteger() 
    _versionCode= versionProps['VERSION_CODE'].toInteger()+1
    if(_patch==99)
    {
        _patch=0
        _minor=_minor+1
    }
    if(_major==99){
        _major=0
        _major=_major+1
    }

    versionProps['MAJOR']=_major.toString()
    versionProps['MINOR']=_minor.toString()
    versionProps['PATCH']=_patch.toString()
    versionProps['VERSION_CODE']=_versionCode.toString()
    versionProps.store(versionPropsFile.newWriter(), null)
}
else {
    throw new GradleException("Could not read version.properties!")
}
def _versionName = "${_major}.${_versionCode}.${_minor}.${_patch}"


compileSdkVersion 23
buildToolsVersion "23.0.3"

defaultConfig {
    applicationId _applicationId
    minSdkVersion 11
    targetSdkVersion 23
    versionCode _versionCode
    versionName _versionName
}

}

Output : 1.1.3.6

Scope 'session' is not active for the current thread; IllegalStateException: No thread-bound request found

Had the same error when I had @Order annotation on a filter class. Even thou I added the filter through the HttpSecurity chain.

Removed the @Order and it worked.

Spring @PropertySource using YAML

There is no need to add like YamlPropertyLoaderFactory or YamlFileApplicationContextInitializer. You should convert your idea. just like common spring project. You know, not using Java config. Just *.xml

Follow these steps:

Just add applicationContext.xml like

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"
       default-autowire="byName">

    <context:property-placeholder location="classpath*:*.yml"/>
</beans>

then add

@ImportResource({"classpath:applicationContext.xml"})

to your ApplicationMainClass.

This can help scan your application-test.yml

db:
  url: jdbc:oracle:thin:@pathToMyDb
  username: someUser
  password: fakePassword

How do I use Spring Boot to serve static content located in Dropbox folder?

Based on @Dave Syer, @kaliatech and @asmaier answers the springboot v2+ way would be:

@Configuration
@AutoConfigureAfter(DispatcherServletAutoConfiguration.class)
public class StaticResourceConfiguration implements WebMvcConfigurer  {

  @Override
  public void addResourceHandlers(ResourceHandlerRegistry registry) {
    String myExternalFilePath = "file:///C:/temp/whatever/m/";

     registry.addResourceHandler("/m/**").addResourceLocations(myExternalFilePath);

  }

}

Android Studio suddenly cannot resolve symbols

Please check if you have a project path which has special characters like ! (exclamation mark).

In a similar problem that I experienced, this was the root cause - since many Java applications seem not to tolerate such special characters (For e.g. doing a 'gradlew clean' from the terminal would fail and throw a RunTimeException.). None of the other solutions posted online had helped me. But, once I had removed the ! from the path and did a clean build, Android Studio magically worked.

SSH Key - Still asking for password and passphrase

Same problem to me and the solution was:

See this github doc to convert remote's URL from https to ssh. To check if remote's URL is ssh or https, use git remote -v. To switch from https to ssh: git remote set-url origin [email protected]:USERNAME/REPOSITORY.git @jeeYem

Import Google Play Services library in Android Studio

I solved the problem by installing the google play services package in sdk manager.

After it, create a new application & in the build.gradle add this

compile 'com.google.android.gms:play-services:4.3.+'

Like this

dependencies {
    compile 'com.android.support:appcompat-v7:+'
    compile 'com.google.android.gms:play-services:4.3.+'
}

Tomcat starts but home page cannot open with url http://localhost:8080

I am using Eclipse Java EE IDE for Web Developers. Version: Oxygen.1a Release (4.7.1a) in Windows 8.1 x64 with Apache Tomcat 8.5.24 (for testing purpose).

Port Name & Numbers for my Tomcat Server are :

Tomcat admin port   :   8005
HTTP/1.1            :   8081 (my Tomcat Listening Port Number)
AJP/1.3             :   8009

Peoples, for those the Tomcat were running good earlier, and sometimes sudden after stopping tomcat server explicitly by pressing the below shown image button or may be other reasons.

Stopping Tomcat Server through Eclipse Standard Toolbar button explicitly

Either they continuously failed to start/restart the tomcat with below said error:

Server Tomcat vX.Y Server at localhost failed to start.

or sometimes the Tomcat Server is started but instead of showing Tomcat Homepage in web browser, it is throwing client exception HTTP Status 404 – Not Found. in preferred web browser.

possibly, there are many reasons i.e. wrong Host name defined, Wrong Tomcat Server Locations defined in eclipse, project JDK/JRE version mismatch with Tomcat JRE dependent version, maven project version mismatch due to maven.compiler.source and maven.compiler.target version not defined under properties tag, mismatch version of project facet Dynamic Web Module to 2.5/3.0, Sometimes Tomcat Server is running on Windows Services level, previous stopped Tomcat port number were still listening and the processing pid were not killed in Tomcat defined timespan Timeouts Stop (in seconds): 15(by default) in eclipse and pid still running, failed to start in defined Start (in seconds): XX, etc.

Here I will give the resolution on, how to check and kill the running existing Tomcat port number's processing pid(beware, you must be aware with after effects).

In Windows, open you command prompt, and follow steps(my tomcat HTTP port is 8081):

netstat -ano | findstr :8081
TCP    0.0.0.0:8081           0.0.0.0:0              LISTENING       2284
TCP    [::]:8081              [::]:0                 LISTENING       2284

if any listening is being there, above command will list details of port listening along with processing pid at last of the line(here pid is 2284).

now kill the running pid like:

taskkill /PID 2284 /F
SUCCESS: The process with PID 2284 has been terminated.

also illustrated the above two steps like following:

Killing running PID

Now, after resolving above illustrated reason, start the Tomcat Server.

jQuery change event on dropdown

The html

<select id="drop"  name="company" class="company btn btn-outline   dropdown-toggle" >
   <option value="demo1">Group Medical</option>
   <option value="demo">Motor Insurance</option>
</select>

Script.js

$("#drop").change(function () {                            
   var category= $('select[name=company]').val() // Here we can get the value of selected item
   alert(category); 
});

How do you run a .exe with parameters using vba's shell()?

Here are some examples of how to use Shell in VBA.
Open stackoverflow in Chrome.

Call Shell("C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" & _
 " -url" & " " & "www.stackoverflow.com",vbMaximizedFocus)

Open some text file.

Call Shell ("notepad C:\Users\user\Desktop\temp\TEST.txt")

Open some application.

Call Shell("C:\Temp\TestApplication.exe",vbNormalFocus)

Hope this helps!

Disable password authentication for SSH

Here's a script to do this automatically

# Only allow key based logins
sed -n 'H;${x;s/\#PasswordAuthentication yes/PasswordAuthentication no/;p;}' /etc/ssh/sshd_config > tmp_sshd_config
cat tmp_sshd_config > /etc/ssh/sshd_config
rm tmp_sshd_config

Curl: Fix CURL (51) SSL error: no alternative certificate subject name matches

It usually happens when the certificate does not match with the host name.

The solution would be to contact the host and ask it to fix its certificate.
Otherwise you can turn off cURL's verification of the certificate, use the -k (or --insecure) option.
Please note that as the option said, it is insecure. You shouldn't use this option because it allows man-in-the-middle attacks and defeats the purpose of HTTPS.

More can be found in here: http://curl.haxx.se/docs/sslcerts.html

Symfony2 and date_default_timezone_get() - It is not safe to rely on the system's timezone settings

add this code to Your AppKernel Class:

public function init()
{
    date_default_timezone_set('Asia/Tehran');
    parent::init();
}

Android Gradle plugin 0.7.0: "duplicate files during packaging of APK"

In my case I had to include several additional exclusions. It appears it doesn't like Regular expressions which would've made this a nice one-liner.

android {
    packagingOptions {
        exclude 'META-INF/DEPENDENCIES.txt'
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/dependencies.txt'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/license.txt'
        exclude 'META-INF/LGPL2.1'
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/notice.txt'
    }
}

VirtualBox error "Failed to open a session for the virtual machine"

maybe it is caused by privilege, please try this:

#sudo chmod 755 /Applications 
#sudo chmod 755 /Applications/Virtualbox.app

javac: file not found: first.java Usage: javac <options> <source files>

first set the path of jdk bin steps to be follow: - open computer properties. - Advanced system settings - Environment Variables look for the system variables -Click on the "path" variable - Edit copy the jdk bin path and done.

The Problem is you just open the command prompt which is default set on current user like "C:\users\ABC>" You have to change the location where your .java file store like "D:\javafiles>"

Now you are able to run the command javac filename.java

How to check if a table exists in a given schema

It depends on what you want to test exactly.

Information schema?

To find "whether the table exists" (no matter who's asking), querying the information schema (information_schema.tables) is incorrect, strictly speaking, because (per documentation):

Only those tables and views are shown that the current user has access to (by way of being the owner or having some privilege).

The query provided by @kong can return FALSE, but the table can still exist. It answers the question:

How to check whether a table (or view) exists, and the current user has access to it?

SELECT EXISTS (
   SELECT FROM information_schema.tables 
   WHERE  table_schema = 'schema_name'
   AND    table_name   = 'table_name'
   );

The information schema is mainly useful to stay portable across major versions and across different RDBMS. But the implementation is slow, because Postgres has to use sophisticated views to comply to the standard (information_schema.tables is a rather simple example). And some information (like OIDs) gets lost in translation from the system catalogs - which actually carry all information.

System catalogs

Your question was:

How to check whether a table exists?

SELECT EXISTS (
   SELECT FROM pg_catalog.pg_class c
   JOIN   pg_catalog.pg_namespace n ON n.oid = c.relnamespace
   WHERE  n.nspname = 'schema_name'
   AND    c.relname = 'table_name'
   AND    c.relkind = 'r'    -- only tables
   );

Use the system catalogs pg_class and pg_namespace directly, which is also considerably faster. However, per documentation on pg_class:

The catalog pg_class catalogs tables and most everything else that has columns or is otherwise similar to a table. This includes indexes (but see also pg_index), sequences, views, materialized views, composite types, and TOAST tables;

For this particular question you can also use the system view pg_tables. A bit simpler and more portable across major Postgres versions (which is hardly of concern for this basic query):

SELECT EXISTS (
   SELECT FROM pg_tables
   WHERE  schemaname = 'schema_name'
   AND    tablename  = 'table_name'
   );

Identifiers have to be unique among all objects mentioned above. If you want to ask:

How to check whether a name for a table or similar object in a given schema is taken?

SELECT EXISTS (
   SELECT FROM pg_catalog.pg_class c
   JOIN   pg_catalog.pg_namespace n ON n.oid = c.relnamespace
   WHERE  n.nspname = 'schema_name'
   AND    c.relname = 'table_name'
   );

Alternative: cast to regclass

SELECT 'schema_name.table_name'::regclass

This raises an exception if the (optionally schema-qualified) table (or other object occupying that name) does not exist.

If you do not schema-qualify the table name, a cast to regclass defaults to the search_path and returns the OID for the first table found - or an exception if the table is in none of the listed schemas. Note that the system schemas pg_catalog and pg_temp (the schema for temporary objects of the current session) are automatically part of the search_path.

You can use that and catch a possible exception in a function. Example:

A query like above avoids possible exceptions and is therefore slightly faster.

to_regclass(rel_name) in Postgres 9.4+

Much simpler now:

SELECT to_regclass('schema_name.table_name');

Same as the cast, but it returns ...

... null rather than throwing an error if the name is not found

add maven repository to build.gradle

You will need to define the repository outside of buildscript. The buildscript configuration block only sets up the repositories and dependencies for the classpath of your build script but not your application.

scp copy directory to another server with private key auth

Covert .ppk to id_rsa using tool PuttyGen, (http://mydailyfindingsit.blogspot.in/2015/08/create-keys-for-your-linux-machine.html) and

scp -C -i ./id_rsa -r /var/www/* [email protected]:/var/www

it should work !

@Autowired - No qualifying bean of type found for dependency

This may help you:

I have the same exception in my project. After searching while I found that I am missing the @Service annotation to the class where I am implementing the interface which I want to @Autowired.

In your code you can add the @Service annotation to MailManager class.

@Transactional
@Service
public class MailManager extends AbstractManager implements IMailManager {

Could not resolve placeholder in string value

I got the same error in my microservice project.The property itself missed in my yml file.So I added property name and value that resolves my problem

Failed to instantiate module error in Angular js

For me the error occurred due to my browser using a cached version of the js file containing the module. Clearing the cache and reloading the page solved the problem.

could not extract ResultSet in hibernate

The @JoinColumn annotation specifies the name of the column being used as the foreign key on the targeted entity.

On the Product class above, the name of the join column is set to ID_CATALOG.

@ManyToOne
@JoinColumn(name="ID_CATALOG")
private Catalog catalog;

However, the foreign key on the Product table is called catalog_id

`catalog_id` int(11) DEFAULT NULL,

You'll need to change either the column name on the table or the name you're using in the @JoinColumn so that they match. See http://docs.jboss.org/hibernate/annotations/3.5/reference/en/html/entity.html#entity-mapping-association

Maven won't run my Project : Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2.1:exec

  1. This error would spring up arbitrarily and caused quite a bit of trouble though the code on my end was solid.

I did the following :

  • I closed it on netbeans.
  • Then open the project by clicking "Open Project", selecting my project and
  • Simply hit the run button in netbeans.

I would not build or clean build it. Hope that helps you out.

  1. I noticed another reason why this happens. If you moved your main class to another package, the same error springs up. In that case you :
    • Right Click Project > Properties > Run
    • Set the "Main Class" correctly by clicking "Browse" and selecting.

How to run a jar file in a linux commandline

Running a from class inside your JAR file load.jar is possible via

java -jar load.jar

When doing so, you have to define the application entry point. Usually this is done by providing a manifest file that contains the Main-Class tag. For documentation and examples have a look at this page. The argument load=2 can be supplied like in a normal Java applications:

java -jar load.jar load=2

Having also the current directory contained in the classpath, required to also make use of the Class-Path tag. See here for more information.

"The import org.springframework cannot be resolved."

Right click project name in Eclipse, -->Maven-->Select Maven Profiles... Then tick the maven profile you want to set. After click OK, Eclipse will automatically import the maven setting to your project. If you check your project's Property, you will find Maven Dependencies Library has been added.

getting JRE system library unbound error in build path

This is like user3076252's answer, but you'll be choosing a different set of options:

  • Project > Properties > Java Build Path
  • Select Libraries tab > Alternate JRE > Installed JREs...
  • Click "Search." Unless you know the exact folder name, you should choose a drive to search.

It should find your unbound JRE, but this time with all the numbers in it's name (rather than unbound), and you can select it. It will take a while to search the drive, but you can stop it at any time, and it will save the results, if any.

Compile throws a "User-defined type not defined" error but does not go to the offending line of code

A bit late, and not a complete solution either, but for everyone who gets hit by this error without any obvious reason (having all the references defined, etc.) This thread put me on the correct track though. The issue seems to originate from some caching related bug in MS Office VBA Editor.

After making some changes to a project including about 40 forms with code modules plus 40 classes and some global modules in MS Access 2016 the compilation failed.

Commenting out code was obviously not an option, nor did exporting and re-importing all the 80+ files seem reasonable. Concentrating on what had recently been changed, my suspicions focused on removal of one class module.

Having no better ideas I re-cereated an empty class module with the same name that had previously been removed. And voliá the error was gone! It was even possible to remove the unused class module again without the error reappearing, until any changes were saved to a form module which previously had contained a WithEvents declaration involving the now removed class.

Not completely sure if WithEvents declaration really is what triggers the error even after the declaration has been removed. And no clues how to actually find out (without having information about the development history) which Form might be the culprit...

But what finally solved the issue was:

  1. In VBE - Copy all code from Form code module
  2. In Access open Form in Design view and set Has Module property to No
  3. Save the project (this removes any code associated with Form)
  4. (Not sure if need to close and re-open Access, but I did it)
  5. Open Form in Design view and set Has Module property back to Yes
  6. In VBE paste back the copied out module code
  7. Save

How to get resources directory path programmatically

Just use com.google.common.io.Resources class. Example:

 URL url = Resources.getResource("file name")

After that you have methods like: .getContent(), .getFile(), .getPath() etc

Spring JUnit: How to Mock autowired component in autowired component

Another approach in integration testing is to define a new Configuration class and provide it as your @ContextConfiguration. Into the configuration you will be able to mock your beans and also you must define all types of beans which you are using in test/s flow. To provide an example :

@RunWith(SpringRunner.class)
@ContextConfiguration(loader = AnnotationConfigContextLoader.class)
public class MockTest{
 @Configuration
 static class ContextConfiguration{
 // ... you beans here used in test flow
 @Bean
    public MockMvc mockMvc() {
        return MockMvcBuilders.standaloneSetup(/*you can declare your controller beans defines on top*/)
                .addFilters(/*optionally filters*/).build();
    }
 //Defined a mocked bean
 @Bean
    public MyService myMockedService() {
        return Mockito.mock(MyService.class);
    }
 }

 @Autowired
 private MockMvc mockMvc;

 @Autowired
 MyService myMockedService;

 @Before
 public void setup(){
  //mock your methods from MyService bean 
  when(myMockedService.myMethod(/*params*/)).thenReturn(/*my answer*/);
 }

 @Test
 public void test(){
  //test your controller which trigger the method from MyService
  MvcResult result = mockMvc.perform(get(CONTROLLER_URL)).andReturn();
  // do your asserts to verify
 }
}

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.

CURL to pass SSL certifcate and password

I went through this when trying to get a clientcert and private key out of a keystore.

The link above posted by welsh was great, but there was an extra step on my redhat distribution. If curl is built with NSS ( run curl --version to see if you see NSS listed) then you need to import the keys into an NSS keystore. I went through a bunch of convoluted steps, so this may not be the cleanest way, but it got things working

So export the keys into .p12

keytool -importkeystore -srckeystore $jksfile -destkeystore $p12file \
        -srcstoretype JKS -deststoretype PKCS12 \
        -srcstorepass $jkspassword -deststorepass $p12password  
        -srcalias $myalias -destalias $myalias \
        -srckeypass $keypass -destkeypass $keypass -noprompt

And generate the pem file that holds only the key

 echo making ${fileroot}.key.pem
 openssl pkcs12 -in $p12 -out ${fileroot}.key.pem  \
         -passin pass:$p12password  \
         -passout pass:$p12password  -nocerts
  • Make an empty keystore:
mkdir ~/nss
chmod 700 ~/nss
certutil -N -d ~/nss
  • Import the keys into the keystore
pks12util -i <mykeys>.p12 -d ~/nss -W <password for cert >

Now curl should work.

curl --insecure --cert <client cert alias>:<password for cert> \
     --key ${fileroot}.key.pem  <URL>

As I mentioned, there may be other ways to do this, but at least this was repeatable for me. If curl is compiled with NSS support, I was not able to get it to pull the client cert from a file.

How to connect to a remote Windows machine to execute commands using python?

Many answers already, but one more option

PyPSExec https://pypi.org/project/pypsexec/

It's a python clone of the famous psexec. Works without any installation on the remote windows machine.

Ignore .classpath and .project from Git

Use a .gitignore file. This allows you to ignore certain files. http://git-scm.com/docs/gitignore

Here's an example Eclipse one, which handles your classpath and project files: https://github.com/github/gitignore/blob/master/Global/Eclipse.gitignore

.gitignore file for java eclipse project

You need to add your source files with git add or the GUI equivalent so that Git will begin tracking them.

Use git status to see what Git thinks about the files in any given directory.

Gradle error: could not execute build using gradle distribution

I had the same problem on Ubuntu with Eclipse 4.3 (Kepler) and the problem was that I created the project with a minus-sign in it.

I recreated the project with no specialchars and it all worked fine

How to set up gradle and android studio to do release build?

No need to update gradle for making release application in Android studio.If you were eclipse user then it will be so easy for you. If you are new then follow the steps

1: Go to the "Build" at the toolbar section. 2: Choose "Generate Signed APK..." option. enter image description here

3:fill opened form and go next 4 :if you already have .keystore or .jks then choose that file enter your password and alias name and respective password. 5: Or don't have .keystore or .jks file then click on Create new... button as shown on pic 1 then fill the form.enter image description here

Above process was to make build manually. If You want android studio to automatically Signing Your App

In Android Studio, you can configure your project to sign your release APK automatically during the build process:

On the project browser, right click on your app and select Open Module Settings. On the Project Structure window, select your app's module under Modules. Click on the Signing tab. Select your keystore file, enter a name for this signing configuration (as you may create more than one), and enter the required information. enter image description here Figure 4. Create a signing configuration in Android Studio.

Click on the Build Types tab. Select the release build. Under Signing Config, select the signing configuration you just created. enter image description here Figure 5. Select a signing configuration in Android Studio.

4:Most Important thing that make debuggable=false at gradle.

    buildTypes {
        release {
           minifyEnabled false
          proguardFiles getDefaultProguardFile('proguard-  android.txt'), 'proguard-rules.txt'
        debuggable false
        jniDebuggable false
        renderscriptDebuggable false
        zipAlignEnabled true
       }
     }

visit for more in info developer.android.com

Run a JAR file from the command line and specify classpath

Alternatively, use the manifest to specify the class-path and main-class if you like, so then you don't need to use -cp or specify the main class. In your case it would contain lines like this:

Main-Class: com.test.App
Class-Path: lib/one.jar lib/two.jar

Unfortunately you need to spell out each jar in the manifest (not a biggie as you only do once, and you can use a script to build the file or use a build tool like ANT or Maven or Gradle). And the reference has to be a relative or absolute directory to where you run the java -jar MyJar.jar.

Then execute it with

java -jar MyJar.jar

Change project name on Android Studio

Change the Project Name


Change the name of your project by closing the Android Studio, go to your project folder, rename it…


enter image description here


Delete the .idea folder and .iml file. (To show hidden folders, press Cmd + Shift + . (dot) ).


enter image description here


Open the settings.gradle file with a text editor, like VSCode, and change the rootProject.name to your new project name.


enter image description here


Done! The project name has been changed! Just open your project with the Android Studio and Gradle will sync again.

Gradle Build Android Project "Could not resolve all dependencies" error

Add this to your gradle:

allprojects {
    buildscript {
        repositories {
            maven {
                url "https://dl.bintray.com/android/android-tools"
            }
        }
    }
...
}

Android Studio: Gradle - build fails -- Execution failed for task ':dexDebug'

ANDROID STUDIO Users try this:-

You need to add the following to your gradle file dependencies:

compile 'com.android.support:multidex:1.0.0'

And then add below line ( multidex support application ) to your manifest's application tag:

android:name="android.support.multidex.MultiDexApplication"

How to solve java.lang.NoClassDefFoundError?

if you recently added multidex support in android studio like this:

// To Support MultiDex
implementation 'com.android.support:multidex:1.0.1'

so your solution is just extend From MultiDexApplication instead of Application

public class MyApp extends MultiDexApplication {

How to use opencv in using Gradle?

It works with Android Studio 1.2 + OpenCV-2.4.11-android-sdk (.zip), too.

Just do the following:

1) Follow the answer that starts with "You can do this very easily in Android Studio. Follow the steps below to add OpenCV in your project as library." by TGMCians.

2) Modify in the <yourAppDir>\libraries\opencv folder your newly created build.gradle to (step 4 in TGMCians' answer, adapted to OpenCV2.4.11-android-sdk and using gradle 1.1.0):

apply plugin: 'android-library'

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.1.0'
    }
}

android {
    compileSdkVersion 21
    buildToolsVersion "21.1.2"

    defaultConfig {
        minSdkVersion 8
        targetSdkVersion 21
        versionCode 2411
        versionName "2.4.11"
    }

    sourceSets {
        main {
            manifest.srcFile 'AndroidManifest.xml'
            java.srcDirs = ['src']
            resources.srcDirs = ['src']
            res.srcDirs = ['res']
            aidl.srcDirs = ['src']
        }
    }
}

3) *.so files that are located in the directories "armeabi", "armeabi-v7a", "mips", "x86" can be found under (default OpenCV-location): ..\OpenCV-2.4.11-android-sdk\OpenCV-android-sdk\sdk\native\libs (step 9 in TGMCians' answer).

Enjoy and if this helped, please give a positive reputation. I need 50 to answer directly to answers (19 left) :)

Spring not autowiring in unit tests with JUnit

Missing Context file location in configuration can cause this, one approach to solve this:

  • Specifying Context file location in ContextConfiguration

like:

@ContextConfiguration(locations = { "classpath:META-INF/your-spring-context.xml" })

More details

@RunWith( SpringJUnit4ClassRunner.class )
@ContextConfiguration(locations = { "classpath:META-INF/your-spring-context.xml" })
public class UserServiceTest extends AbstractJUnit4SpringContextTests {}

Reference:Thanks to @Xstian

how to pass variable from shell script to sqlplus

You appear to have a heredoc containing a single SQL*Plus command, though it doesn't look right as noted in the comments. You can either pass a value in the heredoc:

sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql BUILDING
exit;
EOF

or if BUILDING is $2 in your script:

sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql $2
exit;
EOF

If your file.sql had an exit at the end then it would be even simpler as you wouldn't need the heredoc:

sqlplus -S user/pass@localhost @/opt/D2RQ/file.sql $2

In your SQL you can then refer to the position parameters using substitution variables:

...
}',SEM_Models('&1'),NULL,
...

The &1 will be replaced with the first value passed to the SQL script, BUILDING; because that is a string it still needs to be enclosed in quotes. You might want to set verify off to stop if showing you the substitutions in the output.


You can pass multiple values, and refer to them sequentially just as you would positional parameters in a shell script - the first passed parameter is &1, the second is &2, etc. You can use substitution variables anywhere in the SQL script, so they can be used as column aliases with no problem - you just have to be careful adding an extra parameter that you either add it to the end of the list (which makes the numbering out of order in the script, potentially) or adjust everything to match:

sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql total_count BUILDING
exit;
EOF

or:

sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql total_count $2
exit;
EOF

If total_count is being passed to your shell script then just use its positional parameter, $4 or whatever. And your SQL would then be:

SELECT COUNT(*) as &1
FROM TABLE(SEM_MATCH(
'{
        ?s rdf:type :ProcessSpec .
        ?s ?p ?o
}',SEM_Models('&2'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));

If you pass a lot of values you may find it clearer to use the positional parameters to define named parameters, so any ordering issues are all dealt with at the start of the script, where they are easier to maintain:

define MY_ALIAS = &1
define MY_MODEL = &2

SELECT COUNT(*) as &MY_ALIAS
FROM TABLE(SEM_MATCH(
'{
        ?s rdf:type :ProcessSpec .
        ?s ?p ?o
}',SEM_Models('&MY_MODEL'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));

From your separate question, maybe you just wanted:

SELECT COUNT(*) as &1
FROM TABLE(SEM_MATCH(
'{
        ?s rdf:type :ProcessSpec .
        ?s ?p ?o
}',SEM_Models('&1'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));

... so the alias will be the same value you're querying on (the value in $2, or BUILDING in the original part of the answer). You can refer to a substitution variable as many times as you want.

That might not be easy to use if you're running it multiple times, as it will appear as a header above the count value in each bit of output. Maybe this would be more parsable later:

select '&1' as QUERIED_VALUE, COUNT(*) as TOTAL_COUNT

If you set pages 0 and set heading off, your repeated calls might appear in a neat list. You might also need to set tab off and possibly use rpad('&1', 20) or similar to make that column always the same width. Or get the results as CSV with:

select '&1' ||','|| COUNT(*)

Depends what you're using the results for...

WCF error - There was no endpoint listening at

You can solve the issue by clearing value of address in endpoint tag in web.config:

<endpoint address="" name="wsHttpEndpoint"  .......           />

How to get the path of running java program

Use

System.getProperty("java.class.path")

see http://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html

You can also split it into it's elements easily

String classpath = System.getProperty("java.class.path");
String[] classpathEntries = classpath.split(File.pathSeparator);

Android Studio marks R in red with error message "cannot resolve symbol R", but build succeeds

DO NOTHING. Just Update Android Studio. Resolve my problem! Work perfectly.

how to fix groovy.lang.MissingMethodException: No signature of method:

This may also be because you might have given classname with all letters in lowercase something which groovy (know of version 2.5.0) does not support.

class name - User is accepted but user is not.

Failed to load ApplicationContext for JUnit test of Spring controller

As mentioned in duscusion: WEB-INF is not really a part of class path. If you use a common template such as maven, use src/main/resources or src/test/resources to place the app-context.xml into. Then you can use 'classpath:'.

Place your config file into src/main/resources/app-context.xml and use code

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:app-context.xml")
public class PersonControllerTest {
...
}

or you can make yout test context with different configuration of beans.

Place your config file into src/test/resources/test-app-context.xml and use code

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:test-app-context.xml")
public class PersonControllerTest {
...
}

Android Studio Gradle Configuration with name 'default' not found

When i import my library manually i had same issue. I tried to add my library with file > import module and it solved my issue.

using if else with eval in aspx page

If you absolutely do not want to use code-behind, you can try conditional operator for this:

<%# ((int)Eval("Percentage") < 50) ? "0 %" : Eval("Percentage") %>

That is assuming field Percentage contains integer.

Update: Version for VB.NET, just in case, provided by tomasofen:

<%# If(Eval("Status") < 50, "0 %", Eval("Percentage")) %>

cURL not working (Error #77) for SSL connections on CentOS for non-root users

For Ubuntu:

sudo apt-get install ca-certificates

Hit this problem trying to curl things as ROOT inside of Dockerfile

Delete all SYSTEM V shared memory and semaphores on UNIX-like systems

1 line will do all

For message queue

ipcs -q | sed "$ d; 1,2d" |  awk '{ print "Removing " $2; system("ipcrm -q " $2) }'

ipcs -q will give the records of message queues

sed "$ d; 1,2d " will remove last blank line ("$ d") and first two header lines ("1,2d")

awk will do the rest i.e. printing and removing using command "ipcrm -q" w.r.t. the value of column 2 (coz $2)

How to write "not in ()" sql query using join

I would opt for NOT EXISTS in this case.

SELECT D1.ShortCode
FROM Domain1 D1
WHERE NOT EXISTS
    (SELECT 'X'
     FROM Domain2 D2
     WHERE D2.ShortCode = D1.ShortCode
    )

WordPress Get the Page ID outside the loop

Use below two lines of code to get current page or post ID

global $post;
echo $post->ID;

How to set the max size of upload file

put this in your application.yml file to allow uploads of files up to 900 MB

server:
  servlet:
    multipart:
      enabled: true
      max-file-size: 900000000  #900M
      max-request-size: 900000000

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

go to project properties and change the target from 7 to 8 also change the target in android manifest and also go to properties of project by right clicking on the project and choose the target

Round double in two decimal places in C#?

Use Math.Round

value = Math.Round(48.485, 2);

Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Widget.Button.Borderless.Colored'

in my case i was using compile sdk 23 and build tools 25.0.0 just changed compile sdk to 25 and done..

How to Alter Constraint

No. We cannot alter the constraint, only thing we can do is drop and recreate it

ALTER TABLE [TABLENAME] DROP CONSTRAINT [CONSTRAINTNAME]

Foreign Key Constraint

Alter Table Table1 Add Constraint [CONSTRAINTNAME] Foreign Key (Column) References Table2 (Column) On Update Cascade On Delete Cascade

Primary Key constraint

Alter Table Table add constraint [Primary Key] Primary key(Column1,Column2,.....)

How to see query history in SQL Server Management Studio

If you want an history for the queries you executed through SMSS.

You may want to try SSMSPlus.

https://github.com/akarzazi/SSMSPlus

This feature does not exists out of the box in SSMS.

You'll need SSMS 18 or newer.

Disclaimer : I'm the author.

How to parse JSON without JSON.NET library?

For those who do not have 4.5, Here is my library function that reads json. It requires a project reference to System.Web.Extensions.

using System.Web.Script.Serialization;

public object DeserializeJson<T>(string Json)
{
    JavaScriptSerializer JavaScriptSerializer = new JavaScriptSerializer();
    return JavaScriptSerializer.Deserialize<T>(Json);
}

Usually, json is written out based on a contract. That contract can and usually will be codified in a class (T). Sometimes you can take a word from the json and search the object browser to find that type.

Example usage:

Given the json

{"logEntries":[],"value":"My Code","text":"My Text","enabled":true,"checkedIndices":[],"checkedItemsTextOverflows":false}

You could parse it into a RadComboBoxClientState object like this:

string ClientStateJson = Page.Request.Form("ReportGrid1_cboReportType_ClientState");
RadComboBoxClientState RadComboBoxClientState = DeserializeJson<RadComboBoxClientState>(ClientStateJson);
return RadComboBoxClientState.Value;

PHP: if !empty & empty

Here's a compact way to do something different in all four cases:

if(empty($youtube)) {
    if(empty($link)) {
        # both empty
    } else {
        # only $youtube not empty
    }
} else {
    if(empty($link)) {
        # only $link empty
    } else {
        # both not empty
    }
}

If you want to use an expression instead, you can use ?: instead:

echo empty($youtube) ? ( empty($link) ? 'both empty' : 'only $youtube not empty' )
                     : ( empty($link) ? 'only $link empty' : 'both not empty' );

IP to Location using Javascript

You can use this google service free IP geolocation webservice

update

the link is broken, I put here other link that include @NickSweeting in the comments:

ip-api.com

and you can get the data in json format:

http://ip-api.com/docs/api:json

Strip double quotes from a string in .NET

If you only want to strip the quotes from the ends of the string (not the middle), and there is a chance that there can be spaces at either end of the string (i.e. parsing a CSV format file where there is a space after the commas), then you need to call the Trim function twice...for example:

string myStr = " \"sometext\"";     //(notice the leading space)
myStr = myStr.Trim('"');            //(would leave the first quote: "sometext)
myStr = myStr.Trim().Trim('"');     //(would get what you want: sometext)

Converting Java file:// URL to File(...) path, platform independent, including UNC paths

Java (at least 5 and 6, java 7 Paths solved most) has a problem with UNC and URI. Eclipse team wrapped it up here : http://wiki.eclipse.org/Eclipse/UNC_Paths

From java.io.File javadocs, the UNC prefix is "////", and java.net.URI handles file:////host/path (four slashes).

More details on why this happens and possible problems it causes in other URI and URL methods can be found in the list of bugs at the end of the link given above.

Using these informations, Eclipse team developed org.eclipse.core.runtime.URIUtil class, which source code can probably help out when dealing with UNC paths.

How can I check if character in a string is a letter? (Python)

This works:

any(c.isalpha() for c in 'string')

Compare two data.frames to find the rows in data.frame 1 that are not present in data.frame 2

Your example data does not have any duplicates, but your solution handle them automatically. This means that potentially some of the answers won't match to results of your function in case of duplicates.
Here is my solution which address duplicates the same way as yours. It also scales great!

a1 <- data.frame(a = 1:5, b=letters[1:5])
a2 <- data.frame(a = 1:3, b=letters[1:3])
rows.in.a1.that.are.not.in.a2  <- function(a1,a2)
{
    a1.vec <- apply(a1, 1, paste, collapse = "")
    a2.vec <- apply(a2, 1, paste, collapse = "")
    a1.without.a2.rows <- a1[!a1.vec %in% a2.vec,]
    return(a1.without.a2.rows)
}

library(data.table)
setDT(a1)
setDT(a2)

# no duplicates - as in example code
r <- fsetdiff(a1, a2)
all.equal(r, rows.in.a1.that.are.not.in.a2(a1,a2))
#[1] TRUE

# handling duplicates - make some duplicates
a1 <- rbind(a1, a1, a1)
a2 <- rbind(a2, a2, a2)
r <- fsetdiff(a1, a2, all = TRUE)
all.equal(r, rows.in.a1.that.are.not.in.a2(a1,a2))
#[1] TRUE

It needs data.table 1.9.8+

what does this mean ? image/png;base64?

It's an inlined image (png), encoded in base64. It can make a page faster: the browser doesn't have to query the server for the image data separately, saving a round trip.

(It can also make it slower if abused: these resources are not cached, so the bytes are included in each page load.)

How can I save an image with PIL?

Try removing the . before the .bmp (it isn't matching BMP as expected). As you can see from the error, the save_handler is upper-casing the format you provided and then looking for a match in SAVE. However the corresponding key in that object is BMP (instead of .BMP).

I don't know a great deal about PIL, but from some quick searching around it seems that it is a problem with the mode of the image. Changing the definition of j to:

j = Image.fromarray(b, mode='RGB')

Seemed to work for me (however note that I have very little knowledge of PIL, so I would suggest using @mmgp's solution as s/he clearly knows what they are doing :) ). For the types of mode, I used this page - hopefully one of the choices there will work for you.

If "0" then leave the cell blank

=iferror(1/ (1/ H15+G16-F16 ), "")

this way avoids repeating the central calculation (which can often be much longer or more processor hungry than the one you have here...

enjoy

Finding partial text in range, return an index

This formula will do the job:

=INDEX(G:G,MATCH(FALSE,ISERROR(SEARCH(H1,G:G)),0)+3)

you need to enter it as an array formula, i.e. press Ctrl-Shift-Enter. It assumes that the substring you're searching for is in cell H1.

Create a temporary table in MySQL with an index from a select

Did find the answer on my own. My problem was, that i use two temporary tables for a join and create the second one out of the first one. But the Index was not copied during creation...

CREATE TEMPORARY TABLE tmpLivecheck (tmpid INTEGER NOT NULL AUTO_INCREMENT, PRIMARY    
KEY(tmpid), INDEX(tmpid))
SELECT * FROM tblLivecheck_copy WHERE tblLivecheck_copy.devId = did;

CREATE TEMPORARY TABLE tmpLiveCheck2 (tmpid INTEGER NOT NULL, PRIMARY KEY(tmpid), 
INDEX(tmpid))  
SELECT * FROM tmpLivecheck;

... solved my problem.

Greetings...

PHP: How to remove specific element from an array?

Using array_seach(), try the following:

if(($key = array_search($del_val, $messages)) !== false) {
    unset($messages[$key]);
}

array_search() returns the key of the element it finds, which can be used to remove that element from the original array using unset(). It will return FALSE on failure, however it can return a "falsey" value on success (your key may be 0 for example), which is why the strict comparison !== operator is used.

The if() statement will check whether array_search() returned a value, and will only perform an action if it did.

javascript close current window

I found this method by Jeff Clayton. It is working for me with Firefox 56 and Chrome (on Windows and Android).

Did not try all possibilities. On my side, I open a window with a target name in my A links, for example, target="mywindowname", so all my links open inside the same window name: mywindowname.

To open a new window:

<a href="example-link.html" target="mywindowname">New Window</a>

And then in the new window (inside example-link.html):

<a href="#" onclick="return quitBox('quit');"></a>

Javascript:

function quitBox(cmd) {   
    if (cmd=='quit') {
        open(location, '_self').close();
    }   
    return false;   
}

Hope this can help anyone else that is looking for a method to close a window. I tried a lot of other methods and this one is the best I found.

How can I check the size of a collection within a Django template?

I need the collection length to decide whether I should render table <thead></thead>

but don't know why @Django 2.1.7 the chosen answer will fail(empty) my forloop afterward.

I got to use {% if forloop.first %} {% endif %} to overcome:

<table>
    {% for record in service_list %}
        {% if forloop.first %}
            <thead>
            <tr>
                <th>??</th>
            </tr>
            </thead>
        {% endif %}
        <tbody>
        <tr>
            <td>{{ record.date }}</td>
        </tr>
    {% endfor %}
    </tbody>
</table>

How to query GROUP BY Month in a Year

I am doing like this in MSSQL

Getting Monthly Data:

 SELECT YEAR(DATE_CREATED) [Year], MONTH(DATE_CREATED) [Month], 
     DATENAME(MONTH,DATE_CREATED) [Month Name], SUM(Num_of_Pictures) [Pictures Count]
    FROM pictures_table
    GROUP BY YEAR(DATE_CREATED), MONTH(DATE_CREATED), 
     DATENAME(MONTH, DATE_CREATED)
    ORDER BY 1,2

Getting Monthly Data using PIVOT:

SELECT *
FROM (SELECT YEAR(DATE_CREATED) [Year], 
       DATENAME(MONTH, DATE_CREATED) [Month], 
       SUM(Num_of_Pictures) [Pictures Count]
      FROM pictures_table
      GROUP BY YEAR(DATE_CREATED), 
      DATENAME(MONTH, DATE_CREATED)) AS MontlySalesData
PIVOT( SUM([Pictures Count])   
    FOR Month IN ([January],[February],[March],[April],[May],
    [June],[July],[August],[September],[October],[November],
    [December])) AS MNamePivot

How to check if the URL contains a given string?

You need add href property and check indexOf instead of contains

_x000D_
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script type="text/javascript">_x000D_
  $(document).ready(function() {_x000D_
    if (window.location.href.indexOf("franky") > -1) {_x000D_
      alert("your url contains the name franky");_x000D_
    }_x000D_
  });_x000D_
</script>
_x000D_
_x000D_
_x000D_

How to enter command with password for git pull?

Below cmd will work if we dont have @ in password: git pull https://username:pass@[email protected]/my/repository If you have @ in password then replace it by %40 as shown below: git pull https://username:pass%[email protected]/my/repository

How to call a JavaScript function from PHP?

You can't. You can call a JS function from HTML outputted by PHP, but that's a whole 'nother thing.

First Or Create

An update:

As of Laravel 5.3 doing this in a single step is possible; the firstOrCreate method now accepts an optional second array as an argument.

The first array argument is the array on which the fields/values are matched, and the second array is the additional fields to use in the creation of the model if no match is found via matching the fields/values in the first array:

See documentation

Keeping session alive with Curl and PHP

You have correctly used "CURLOPT_COOKIEJAR" (writing) but you also need to set "CURLOPT_COOKIEFILE" (reading)

curl_setopt ($ch, CURLOPT_COOKIEJAR, COOKIE_FILE); 
curl_setopt ($ch, CURLOPT_COOKIEFILE, COOKIE_FILE); 

Emulating a do-while loop in Bash

Place the body of your loop after the while and before the test. The actual body of the while loop should be a no-op.

while 
    check_if_file_present
    #do other stuff
    (( current_time <= cutoff ))
do
    :
done

Instead of the colon, you can use continue if you find that more readable. You can also insert a command that will only run between iterations (not before first or after last), such as echo "Retrying in five seconds"; sleep 5. Or print delimiters between values:

i=1; while printf '%d' "$((i++))"; (( i <= 4)); do printf ','; done; printf '\n'

I changed the test to use double parentheses since you appear to be comparing integers. Inside double square brackets, comparison operators such as <= are lexical and will give the wrong result when comparing 2 and 10, for example. Those operators don't work inside single square brackets.

Determine .NET Framework version for dll

dotPeek is a great (free) tool to show this information.

If you are having a few issues getting hold of Reflector then this is a good alternative.

enter image description here

How to check if a python module exists without importing it

I wrote this helper function:

def is_module_available(module_name):
    if sys.version_info < (3, 0):
        # python 2
        import importlib
        torch_loader = importlib.find_loader(module_name)
    elif sys.version_info <= (3, 3):
        # python 3.0 to 3.3
        import pkgutil
        torch_loader = pkgutil.find_loader(module_name)
    elif sys.version_info >= (3, 4):
        # python 3.4 and above
        import importlib
        torch_loader = importlib.util.find_spec(module_name)

    return torch_loader is not None

ASP.NET MVC 404 Error Handling

In IIS, you can specify a redirect to "certain" page based on error code. In you example, you can configure 404 - > Your customized 404 error page.

How to make a DIV not wrap?

overflow: hidden should give you the correct behavior. My guess is that RTL is messed up because you have float: left on the encapsulated divs.

Beside that bug, you got the right behavior.

Keyboard shortcut to comment lines in Sublime Text 3

On windows, use Ctrl + Shift + ?. You will be able to comment the HTML.

setting min date in jquery datepicker

$(function () {
    $('#datepicker').datepicker({
        dateFormat: 'yy-mm-dd',
        showButtonPanel: true,
        changeMonth: true,
        changeYear: true,
yearRange: '1999:2012',
        showOn: "button",
        buttonImage: "images/calendar.gif",
        buttonImageOnly: true,
        minDate: new Date(1999, 10 - 1, 25),
        maxDate: '+30Y',
        inline: true
    });
});

Just added year range option. It should solve the problem

Exception of type 'System.OutOfMemoryException' was thrown.

This problem usually occurs when some process such as loading huge data to memory stream and your system memory is not capable of storing so much of data. Try clearing temp folder by giving the command

start -> run -> %temp%

How to SHUTDOWN Tomcat in Ubuntu?

If you installed tomcat manually, run the shutdown.sh(/.../tomcat/bin) from the terminal to shut it down easily.

Virtualhost For Wildcard Subdomain and Static Subdomain

Wildcards can only be used in the ServerAlias rather than the ServerName. Something which had me stumped.

For your use case, the following should suffice

<VirtualHost *:80>
    ServerAlias *.example.com
    VirtualDocumentRoot /var/www/%1/
</VirtualHost>

Removing cordova plugins from the project

When running the command: cordova plugin remove <PLUGIN NAME>, ensure that you do not add the version number to the plugin name. Just plain plugin name, for example:

cordova plugin remove cordova.plugin_name 

and not:

cordova plugin remove cordova.plugin_name 0.01 

or

cordova plugin remove "cordova.plugin_name 0.01"

In case there is a privilege issue, run with sudo if you are on a *nix system, for example:

sudo cordova plugin remove cordova.plugin_name

Then you may add --save to remove it from the config.xml file. For example:

cordova plugin remove cordova.plugin_name --save

How to use both onclick and target="_blank"

The window.open method is prone to cause popup blockers to complain

A better approach is:

Put a form in the webpage with an id

<form action="theUrlToGoTo" method="post" target="yourTarget" id="yourFormName"> </form>

Then use:

function openYourRequiredPage() {
var theForm = document.getElementById("yourFormName");
theForm.submit();

}

and

onclick="Javascript: openYourRequiredPage()"

You can use

method="post"

or

method="get"

As you wish

How to print table using Javascript?

One cheeky solution :

  function printDiv(divID) {
        //Get the HTML of div
        var divElements = document.getElementById(divID).innerHTML;
        //Get the HTML of whole page
        var oldPage = document.body.innerHTML;
        //Reset the page's HTML with div's HTML only
        document.body.innerHTML = 
          "<html><head><title></title></head><body>" + 
          divElements + "</body>";
        //Print Page
        window.print();
        //Restore orignal HTML
        document.body.innerHTML = oldPage;

    }

HTML :

<form id="form1" runat="server">
    <div id="printablediv" style="width: 100%; background-color: Blue; height: 200px">
        Print me I am in 1st Div
    </div>
    <div id="donotprintdiv" style="width: 100%; background-color: Gray; height: 200px">
        I am not going to print
    </div>
    <input type="button" value="Print 1st Div" onclick="javascript:printDiv('printablediv')" />
</form>

How can I add the sqlite3 module to Python?

For Python version 3:

pip install pysqlite3 

Could not find method android() for arguments

This error appear because the compiler could not found "my-upload-key.keystore" file in your project

After you have generated the file you need to paste it into project's andorid/app folder

this worked for me!

How to Determine the Screen Height and Width in Flutter

MediaQuery.of(context).size.width and MediaQuery.of(context).size.height works great, but every time need to write expressions like width/20 to set specific height width.

I've created a new application on flutter, and I've had problems with the screen sizes when switching between different devices.

Yes, flutter_screenutil plugin available for adapting screen and font size. Let your UI display a reasonable layout on different screen sizes!

Usage:

Add dependency:

Please check the latest version before installation.

dependencies:
  flutter:
    sdk: flutter
  # add flutter_ScreenUtil
  flutter_screenutil: ^0.4.2

Add the following imports to your Dart code:

import 'package:flutter_screenutil/flutter_screenutil.dart';

Initialize and set the fit size and font size to scale according to the system's "font size" accessibility option

//fill in the screen size of the device in the design

//default value : width : 1080px , height:1920px , allowFontScaling:false
ScreenUtil.instance = ScreenUtil()..init(context);

//If the design is based on the size of the iPhone6 ??(iPhone6 ??750*1334)
ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);

//If you wang to set the font size is scaled according to the system's "font size" assist option
ScreenUtil.instance = ScreenUtil(width: 750, height: 1334, allowFontScaling: true)..init(context);

Use:

//for example:
//rectangle
Container(
           width: ScreenUtil().setWidth(375),
           height: ScreenUtil().setHeight(200),
           ...
            ),

////If you want to display a square:
Container(
           width: ScreenUtil().setWidth(300),
           height: ScreenUtil().setWidth(300),
            ),

Please refer updated documentation for more details

Note: I tested and using this plugin, which really works great with all devices including iPad

Hope this will helps someone

Two submit buttons in one form

Simple you can change the action of form on different submit buttons Click.

Try this in document.Ready

$(".acceptOffer").click(function () {
       $("form").attr("action", "/Managers/SubdomainTransactions");
});

$(".declineOffer").click(function () {
       $("form").attr("action", "/Sales/SubdomainTransactions");
});

Embed HTML5 YouTube video without iframe?

Here is a example of embedding without an iFrame:

_x000D_
_x000D_
<div style="width: 560px; height: 315px; float: none; clear: both; margin: 2px auto;">
  <embed
    src="https://www.youtube.com/embed/J---aiyznGQ?autohide=1&autoplay=1"
    wmode="transparent"
    type="video/mp4"
    width="100%" height="100%"
    allow="autoplay; encrypted-media; picture-in-picture"
    allowfullscreen
    title="Keyboard Cat"
  >
</div>
_x000D_
_x000D_
_x000D_

compare to regular iframe "embed" code from YouTube:

_x000D_
_x000D_
<iframe
  width="560"
  height="315"
  src="https://www.youtube.com/embed/J---aiyznGQ?autoplay=1"
  frameborder="0"
  allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"
  allowfullscreen>
</iframe>
_x000D_
_x000D_
_x000D_

and as far as HTML5 goes, use <object> tag like so (corrected):

_x000D_
_x000D_
<object
  style="width: 820px; height: 461.25px; float: none; clear: both; margin: 2px auto;"
  data="http://www.youtube.com/embed/J---aiyznGQ?autoplay=1">
</object>
_x000D_
_x000D_
_x000D_

WebSockets and Apache proxy : how to configure mod_proxy_wstunnel?

User this link for perfact solution for ws https://httpd.apache.org/docs/2.4/mod/mod_proxy_wstunnel.html

You have to just do below step..

Go to /etc/apache2/mods-available

Step...1

Enable mode proxy_wstunnel.load by using below command

$a2enmod proxy_wstunnel.load

Step...2

Go to /etc/apache2/sites-available

and add below line in your .conf file inside virtual host

ProxyPass "/ws2/"  "ws://localhost:8080/"

ProxyPass "/wss2/" "wss://localhost:8080/"

Note : 8080 mean your that your tomcat running port because we want to connect ws where our War file putted in tomcat and tomcat serve apache for ws. thank you

My Configuration

ws://localhost/ws2/ALLCAD-Unifiedcommunication-1.0/chatserver?userid=4 =Connected

How to execute an Oracle stored procedure via a database link

The syntax is

EXEC mySchema.myPackage.myProcedure@myRemoteDB( 'someParameter' );

Selected value for JSP drop down using JSTL

I tried the accepted answer, it did not work.

However the simple way to do it is below:-

<option value="1" <c:if test="${item.quantity == 1}"> <c:out value= "selected=selected"/</c:if>>1</option>
<option value="2" <c:if test="${item.quantity == 2}"> <c:out value= "selected=selected"/</c:if>>2</option>
<option value="3" <c:if test="${item.quantity == 3}"> <c:out value= "selected=selected"/</c:if>>3</option>

Enjoy!!

Given URL is not allowed by the Application configuration

The problem is that whatever url you are currently hosting your app is not setup in your Application configuration. Go to your app settings and ensure the urls are matching.

Updated

Steps:

  1. Go to 'Basic' settings for your app
  2. Select 'Add Platform'
  3. Select 'Website'
  4. Put your website URL under 'Site URL'

enter image description here

Mockito. Verify method arguments

I have used Mockito.verify in this way

@UnitTest
public class JUnitServiceTest
{
    @Mock
    private MyCustomService myCustomService;


    @Test
    public void testVerifyMethod()
    {
       Mockito.verify(myCustomService, Mockito.never()).mymethod(parameters); // method will never call (an alternative can be pick to use times(0))
       Mockito.verify(myCustomService, Mockito.times(2)).mymethod(parameters); // method will call for 2 times
       Mockito.verify(myCustomService, Mockito.atLeastOnce()).mymethod(parameters); // method will call atleast 1 time
       Mockito.verify(myCustomService, Mockito.atLeast(2)).mymethod(parameters); // method will call atleast 2 times
       Mockito.verify(myCustomService, Mockito.atMost(3)).mymethod(parameters); // method will call at most 3 times
       Mockito.verify(myCustomService, Mockito.only()).mymethod(parameters); //   no other method called except this
    }
}

Quick way to retrieve user information Active Directory

I'm not sure how much of your "slowness" will be due to the loop you're doing to find entries with particular attribute values, but you can remove this loop by being more specific with your filter. Try this page for some guidance ... Search Filter Syntax

mvn command is not recognized as an internal or external command

I had this same error but my problem was I had the following:

M2_HOME = C:\Program Files (x86)\Apache Software Foundation\apache-maven-2.2.1;

Which meant my PATH = %M2_HOME%\bin; (etc)

...became C:\Program Files (x86)\Apache Software Foundation\apache-maven-2.2.1;\bin

i.e. a semicolon was where it shouldn't be.

Which I discovered because Michael Ferry suggested using 'ECHO %PATH%' to see what the actual PATH output was.

Trim string in JavaScript?

Use the Native JavaScript Methods: String.trimLeft(), String.trimRight(), and String.trim().


String.trim() is supported in IE9+ and all other major browsers:

'  Hello  '.trim()  //-> 'Hello'


String.trimLeft() and String.trimRight() are non-standard, but are supported in all major browsers except IE

'  Hello  '.trimLeft()   //-> 'Hello  '
'  Hello  '.trimRight()  //-> '  Hello'


IE support is easy with a polyfill however:

if (!''.trimLeft) {
    String.prototype.trimLeft = function() {
        return this.replace(/^\s+/,'');
    };
    String.prototype.trimRight = function() {
        return this.replace(/\s+$/,'');
    };
    if (!''.trim) {
        String.prototype.trim = function() {
            return this.replace(/^\s+|\s+$/g, '');
        };
    }
}

Mounting multiple volumes on a docker container?

Pass multiple -v arguments.

For instance:

docker -v /on/my/host/1:/on/the/container/1 \
       -v /on/my/host/2:/on/the/container/2 \
       ...

java.io.FileNotFoundException: (Access is denied)

Here's a gotcha that I just discovered - perhaps it might help someone else. If using windows the classes folder must not have encryption enabled! Tomcat doesn't seem to like that. Right click on the classes folder, select "Properties" and then click the "Advanced..." button. Make sure the "Encrypt contents to secure data" checkbox is cleared. Restart Tomcat.

It worked for me so here's hoping it helps someone else, too.

How to discard local commits in Git?

I have seen instances where the remote became out of sync and needed to be updated. If a reset --hard or a branch -D fail to work, try

git pull origin
git reset --hard 

Procedure expects parameter which was not supplied

First - why is that an EXEC? Shouldn't that just be

AS
SELECT Column_Name, ...
FROM ...
WHERE TABLE_NAME = @template

The current SP doesn't make sense? In particular, that would look for a column matching @template, not the varchar value of @template. i.e. if @template is 'Column_Name', it would search WHERE TABLE_NAME = Column_Name, which is very rare (to have table and column named the same).

Also, if you do have to use dynamic SQL, you should use EXEC sp_ExecuteSQL (keeping the values as parameters) to prevent from injection attacks (rather than concatenation of input). But it isn't necessary in this case.

Re the actual problem - it looks OK from a glance; are you sure you don't have a different copy of the SP hanging around? This is a common error...

How do I bind the enter key to a function in tkinter?

Try running the following program. You just have to be sure your window has the focus when you hit Return--to ensure that it does, first click the button a couple of times until you see some output, then without clicking anywhere else hit Return.

import tkinter as tk

root = tk.Tk()
root.geometry("300x200")

def func(event):
    print("You hit return.")
root.bind('<Return>', func)

def onclick():
    print("You clicked the button")

button = tk.Button(root, text="click me", command=onclick)
button.pack()

root.mainloop()

Then you just have tweak things a little when making both the button click and hitting Return call the same function--because the command function needs to be a function that takes no arguments, whereas the bind function needs to be a function that takes one argument(the event object):

import tkinter as tk

root = tk.Tk()
root.geometry("300x200")

def func(event):
    print("You hit return.")

def onclick(event=None):
    print("You clicked the button")

root.bind('<Return>', onclick)

button = tk.Button(root, text="click me", command=onclick)
button.pack()

root.mainloop()

Or, you can just forgo using the button's command argument and instead use bind() to attach the onclick function to the button, which means the function needs to take one argument--just like with Return:

import tkinter as tk

root = tk.Tk()
root.geometry("300x200")

def func(event):
    print("You hit return.")

def onclick(event):
    print("You clicked the button")

root.bind('<Return>', onclick)

button = tk.Button(root, text="click me")
button.bind('<Button-1>', onclick)
button.pack()

root.mainloop()

Here it is in a class setting:

import tkinter as tk

class Application(tk.Frame):
    def __init__(self):
        self.root = tk.Tk()
        self.root.geometry("300x200")

        tk.Frame.__init__(self, self.root)
        self.create_widgets()

    def create_widgets(self):
        self.root.bind('<Return>', self.parse)
        self.grid()

        self.submit = tk.Button(self, text="Submit")
        self.submit.bind('<Button-1>', self.parse)
        self.submit.grid()

    def parse(self, event):
        print("You clicked?")

    def start(self):
        self.root.mainloop()


Application().start()

Check play state of AVPlayer

Currently with swift 5 the easiest way to check if the player is playing or paused is to check the .timeControlStatus variable.

player.timeControlStatus == .paused
player.timeControlStatus == .playing

How to bring a window to the front?

The rules governing what happens when you .toFront() a JFrame are the same in windows and in linux :

-> if a window of the existing application is currently the focused window, then focus swaps to the requested window -> if not, the window merely flashes in the taskbar

BUT :

-> new windows automatically get focus

So let's exploit this ! You want to bring a window to the front, how to do it ? Well :

  1. Create an empty non-purpose window
  2. Show it
  3. Wait for it to show up on screen (setVisible does that)
  4. When shown, request focus for the window you actually want to bring the focus to
  5. hide the empty window, destroy it

Or, in java code :

// unminimize if necessary
this.setExtendedState(this.getExtendedState() & ~JFrame.ICONIFIED);

// don't blame me, blame my upbringing
// or better yet, blame java !
final JFrame newFrame = new JFrame();
newFrame.add(new JLabel("boembabies, is this in front ?"));

newFrame.pack();
newFrame.setVisible(true);
newFrame.toFront();

this.toFront();
this.requestFocus();

// I'm not 100% positive invokeLater is necessary, but it seems to be on
// WinXP. I'd be lying if I said I understand why
SwingUtilities.invokeLater(new Runnable() {
  @Override public void run() {
    newFrame.setVisible(false);
  }
});

Regex to get NUMBER only from String

\d+

\d represents any digit, + for one or more. If you want to catch negative numbers as well you can use -?\d+.

Note that as a string, it should be represented in C# as "\\d+", or @"\d+"

Select All Rows Using Entity Framework

I used the entitydatasource and it provide everything I needed for what I wanted to do.

_repository.[tablename].ToList();

Java Swing revalidate() vs repaint()

revalidate() just request to layout the container, when you experienced simply call revalidate() works, it could be caused by the updating of child components bounds triggers the repaint() when their bounds are changed during the re-layout. In the case you mentioned, only component removed and no component bounds are changed, this case no repaint() is "accidentally" triggered.

How to calculate an age based on a birthday?

Another clever way from that ancient thread:

int age = (
    Int32.Parse(DateTime.Today.ToString("yyyyMMdd")) - 
    Int32.Parse(birthday.ToString("yyyyMMdd"))) / 10000;

Composer: how can I install another dependency without updating old ones?

My use case is simpler, and fits simply your title but not your further detail.

That is, I want to install a new package which is not yet in my composer.json without updating all the other packages.

The solution here is composer require x/y

Compile to stand alone exe for C# app in Visual Studio 2010

You can get single file EXE after build the console application

your Application folder - > bin folder -> there will have lot of files there is need 2 files must and other referenced dlls

1. IMG_PDF_CONVERSION [this is my application name, take your application name]
2. IMG_PDF_CONVERSION.exe [this is supporting configure file]
3. your refered dll's

then you can move that 3(exe, configure file, refered dll's) dll to any folder that's it

if you click on 1st IMG_PDF_CONVERSION it will execute the application cool way

any calcification please ask your queries.

@property retain, assign, copy, nonatomic in Objective-C

After reading many articles I decided to put all the attributes information together:

  1. atomic //default
  2. nonatomic
  3. strong=retain //default
  4. weak= unsafe_unretained
  5. retain
  6. assign //default
  7. unsafe_unretained
  8. copy
  9. readonly
  10. readwrite //default

Below is a link to the detailed article where you can find these attributes.

Many thanks to all the people who give best answers here!!

Variable property attributes or Modifiers in iOS

Here is the Sample Description from Article

  1. atomic -Atomic means only one thread access the variable(static type). -Atomic is thread safe. -but it is slow in performance -atomic is default behavior -Atomic accessors in a non garbage collected environment (i.e. when using retain/release/autorelease) will use a lock to ensure that another thread doesn't interfere with the correct setting/getting of the value. -it is not actually a keyword.

Example :

@property (retain) NSString *name;

@synthesize name;
  1. nonatomic -Nonatomic means multiple thread access the variable(dynamic type). -Nonatomic is thread unsafe. -but it is fast in performance -Nonatomic is NOT default behavior,we need to add nonatomic keyword in property attribute. -it may result in unexpected behavior, when two different process (threads) access the same variable at the same time.

Example:

@property (nonatomic, retain) NSString *name;

@synthesize name;

Explain:

Suppose there is an atomic string property called "name", and if you call [self setName:@"A"] from thread A, call [self setName:@"B"] from thread B, and call [self name] from thread C, then all operation on different thread will be performed serially which means if one thread is executing setter or getter, then other threads will wait. This makes property "name" read/write safe but if another thread D calls [name release] simultaneously then this operation might produce a crash because there is no setter/getter call involved here. Which means an object is read/write safe (ATOMIC) but not thread safe as another threads can simultaneously send any type of messages to the object. Developer should ensure thread safety for such objects.

If the property "name" was nonatomic, then all threads in above example - A,B, C and D will execute simultaneously producing any unpredictable result. In case of atomic, Either one of A, B or C will execute first but D can still execute in parallel.

  1. strong (iOS4 = retain ) -it says "keep this in the heap until I don't point to it anymore" -in other words " I'am the owner, you cannot dealloc this before aim fine with that same as retain" -You use strong only if you need to retain the object. -By default all instance variables and local variables are strong pointers. -We generally use strong for UIViewControllers (UI item's parents) -strong is used with ARC and it basically helps you , by not having to worry about the retain count of an object. ARC automatically releases it for you when you are done with it.Using the keyword strong means that you own the object.

Example:

@property (strong, nonatomic) ViewController *viewController;

@synthesize viewController;
  1. weak (iOS4 = unsafe_unretained ) -it says "keep this as long as someone else points to it strongly" -the same thing as assign, no retain or release -A "weak" reference is a reference that you do not retain. -We generally use weak for IBOutlets (UIViewController's Childs).This works because the child object only needs to exist as long as the parent object does. -a weak reference is a reference that does not protect the referenced object from collection by a garbage collector. -Weak is essentially assign, a unretained property. Except the when the object is deallocated the weak pointer is automatically set to nil

Example :

@property (weak, nonatomic) IBOutlet UIButton *myButton;

@synthesize myButton;

Strong & Weak Explanation, Thanks to BJ Homer:

Imagine our object is a dog, and that the dog wants to run away (be deallocated). Strong pointers are like a leash on the dog. As long as you have the leash attached to the dog, the dog will not run away. If five people attach their leash to one dog, (five strong pointers to one object), then the dog will not run away until all five leashes are detached. Weak pointers, on the other hand, are like little kids pointing at the dog and saying "Look! A dog!" As long as the dog is still on the leash, the little kids can still see the dog, and they'll still point to it. As soon as all the leashes are detached, though, the dog runs away no matter how many little kids are pointing to it. As soon as the last strong pointer (leash) no longer points to an object, the object will be deallocated, and all weak pointers will be zeroed out. When we use weak? The only time you would want to use weak, is if you wanted to avoid retain cycles (e.g. the parent retains the child and the child retains the parent so neither is ever released).

  1. retain = strong -it is retained, old value is released and it is assigned -retain specifies the new value should be sent -retain on assignment and the old value sent -release -retain is the same as strong. -apple says if you write retain it will auto converted/work like strong only. -methods like "alloc" include an implicit "retain"

Example:

@property (nonatomic, retain) NSString *name;

@synthesize name;
  1. assign -assign is the default and simply performs a variable assignment -assign is a property attribute that tells the compiler how to synthesize the property's setter implementation -I would use assign for C primitive properties and weak for weak references to Objective-C objects.

Example:

@property (nonatomic, assign) NSString *address;

@synthesize address;
  1. unsafe_unretained

    -unsafe_unretained is an ownership qualifier that tells ARC how to insert retain/release calls -unsafe_unretained is the ARC version of assign.

Example:

@property (nonatomic, unsafe_unretained) NSString *nickName;

@synthesize nickName;
  1. copy -copy is required when the object is mutable. -copy specifies the new value should be sent -copy on assignment and the old value sent -release. -copy is like retain returns an object which you must explicitly release (e.g., in dealloc) in non-garbage collected environments. -if you use copy then you still need to release that in dealloc. -Use this if you need the value of the object as it is at this moment, and you don't want that value to reflect any changes made by other owners of the object. You will need to release the object when you are finished with it because you are retaining the copy.

Example:

@property (nonatomic, copy) NSArray *myArray;

@synthesize myArray;

How do I upload a file with the JS fetch API?

An important note for sending Files with Fetch API

One needs to omit content-type header for the Fetch request. Then the browser will automatically add the Content type header including the Form Boundary which looks like

Content-Type: multipart/form-data; boundary=—-WebKitFormBoundaryfgtsKTYLsT7PNUVD

Form boundary is the delimiter for the form data

Get random boolean in Java

Have you tried looking at the Java Documentation?

Returns the next pseudorandom, uniformly distributed boolean value from this random number generator's sequence ... the values true and false are produced with (approximately) equal probability.

For example:

import java.util.Random;

Random random = new Random();
random.nextBoolean();

Python glob multiple filetypes

For example, for *.mp3 and *.flac on multiple folders, you can do:

mask = r'music/*/*.[mf][pl][3a]*'
glob.glob(mask)

The idea can be extended to more file extensions, but you have to check that the combinations won't match any other unwanted file extension you may have on those folders. So, be careful with this.

To automatically combine an arbitrary list of extensions into a single glob pattern, you can do the following:

def multi_extension_glob_mask(mask_base, *extensions):
    mask_ext = ['[{}]'.format(''.join(set(c))) for c in zip(*extensions)]
    if not mask_ext or len(set(len(e) for e in extensions)) > 1:
        mask_ext.append('*')
    return mask_base + ''.join(mask_ext)

mask = multi_extension_glob_mask('music/*/*.', 'mp3', 'flac', 'wma')
print(mask)  # music/*/*.[mfw][pml][a3]*

How to change font-color for disabled input?

You can use readonly instead. Following would do the trick for you.

<input type="text" class="details-dialog" style="background-color: #bbbbbb" readonly>

But you need to note the following. Depends on your business requirement, you can use it.

A readonly element is just not editable, but gets sent when the according form submits. A disabled element isn't editable and isn't sent on submit.

Headers and client library minor version mismatch

I ran into the same issue on centos7. Removing php-mysql and installing php-mysqlnd fixed the problem. Thanks Carlos Buenosvinos Zamora for your suggestion.

Here are my commands on centos7 just in case this can be of help to anybody as most of the answers here are based on Debian/Ubuntu.

To find the installed php-mysql package

yum list installed | grep mysql

To remove the installed php-mysql package

yum remove php55w-mysql.x86_64

To install php-mysqlnd

yum install php-mysqlnd.x86_64

Addition for BigDecimal

You can also do it like this:

BigDecimal A = new BigDecimal("10000000000");
BigDecimal B = new BigDecimal("20000000000");
BigDecimal C = new BigDecimal("30000000000");
BigDecimal resultSum = (A).add(B).add(C);
System.out.println("A+B+C= " + resultSum);

Prints:

A+B+C= 60000000000

Connect over ssh using a .pem file

Use the -i option:

ssh -i mykey.pem [email protected]

As noted in this answer, this file needs to have correct permissions set. The ssh man page says:

ssh will simply ignore a private key file if it is accessible by others.

You can change the permissions with this command:

chmod go= mykey.pem

That is, set permissions for group and others equal to the empty list of permissions.

.NET Global exception handler in console application

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

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

    REM Do other stuff
End Sub

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

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

Generate insert script for selected records?

CREATE PROCEDURE sp_generate_insertscripts
(
    @TABLENAME VARCHAR(MAX),
    @FILTER_CONDITION VARCHAR(MAX)=''   -- where TableId = 5 or some value
)
AS
BEGIN

SET NOCOUNT ON

DECLARE @TABLE_NAME VARCHAR(MAX),
        @CSV_COLUMN VARCHAR(MAX),
        @QUOTED_DATA VARCHAR(MAX),
        @TEXT VARCHAR(MAX),
        @FILTER VARCHAR(MAX) 

SET @TABLE_NAME=@TABLENAME

SELECT @FILTER=@FILTER_CONDITION

SELECT @CSV_COLUMN=STUFF
(
    (
     SELECT ',['+ NAME +']' FROM sys.all_columns 
     WHERE OBJECT_ID=OBJECT_ID(@TABLE_NAME) AND 
     is_identity!=1 FOR XML PATH('')
    ),1,1,''
)

SELECT @QUOTED_DATA=STUFF
(
    (
     SELECT ' ISNULL(QUOTENAME('+NAME+','+QUOTENAME('''','''''')+'),'+'''NULL'''+')+'','''+'+' FROM sys.all_columns 
     WHERE OBJECT_ID=OBJECT_ID(@TABLE_NAME) AND 
     is_identity!=1 FOR XML PATH('')
    ),1,1,''
)

SELECT @TEXT='SELECT ''INSERT INTO '+@TABLE_NAME+'('+@CSV_COLUMN+')VALUES('''+'+'+SUBSTRING(@QUOTED_DATA,1,LEN(@QUOTED_DATA)-5)+'+'+''')'''+' Insert_Scripts FROM '+@TABLE_NAME + @FILTER

--SELECT @CSV_COLUMN AS CSV_COLUMN,@QUOTED_DATA AS QUOTED_DATA,@TEXT TEXT

EXECUTE (@TEXT)

SET NOCOUNT OFF

END

How to run a script at a certain time on Linux?

The at command exists specifically for this purpose (unlike cron which is intended for scheduling recurring tasks).

at $(cat file) </path/to/script

Newline in JLabel

You can try and do this:

myLabel.setText("<html>" + myString.replaceAll("<","&lt;").replaceAll(">", "&gt;").replaceAll("\n", "<br/>") + "</html>")

The advantages of doing this are:

  • It replaces all newlines with <br/>, without fail.
  • It automatically replaces eventual < and > with &lt; and &gt; respectively, preventing some render havoc.

What it does is:

  • "<html>" + adds an opening html tag at the beginning
  • .replaceAll("<", "&lt;").replaceAll(">", "&gt;") escapes < and > for convenience
  • .replaceAll("\n", "<br/>") replaces all newlines by br (HTML line break) tags for what you wanted
  • ... and + "</html>" closes our html tag at the end.

P.S.: I'm very sorry to wake up such an old post, but whatever, you have a reliable snippet for your Java!

REST API using POST instead of GET

It is nice that REST brings meaning to HTTP verbs (as they defined) but I prefer to agree with Scott Peal.

Here is also item from WIKI's extended explanation on POST request:

There are times when HTTP GET is less suitable even for data retrieval. An example of this is when a great deal of data would need to be specified in the URL. Browsers and web servers can have limits on the length of the URL that they will handle without truncation or error. Percent-encoding of reserved characters in URLs and query strings can significantly increase their length, and while Apache HTTP Server can handle up to 4,000 characters in a URL,[5] Microsoft Internet Explorer is limited to 2,048 characters in any URL.[6] Equally, HTTP GET should not be used where sensitive information, such as user names and passwords, have to be submitted along with other data for the request to complete. Even if HTTPS is used, preventing the data from being intercepted in transit, the browser history and the web server's logs will likely contain the full URL in plaintext, which may be exposed if either system is hacked. In these cases, HTTP POST should be used.[7]

I could only suggest to REST team to consider more secure use of HTTP protocol to avoid making consumers struggle with non-secure "good practice".

How to make an input type=button act like a hyperlink and redirect using a get request?

Do not do it. I might want to run my car on monkey blood. I have my reasons, but sometimes it's better to stick with using things the way they were designed even if it doesn't "absolutely perfectly" match the exact look you are driving for.

To back up my argument I submit the following.

  • See how this image lacks the status bar at the bottom. This link is using the onclick="location.href" model. (This is a real-life production example from my predecessor) This can make users hesitant to click on the link, since they have no idea where it is taking them, for starters.

Image

You are also making Search engine optimization more difficult IMO as well as making the debugging and reading of your code/HTML more complex. A submit button should submit a form. Why should you(the development community) try to create a non-standard UI?

How to style dt and dd so they are on the same line?

Depending on how you style the dt and dd elements, you might encounter a problem: making them have the same height. For instance, if you want to but some visible border at the bottom of those elements, you most probably want to display the border at the same height, like in a table.

One solution for this is cheating and make each row a "dl" element. (this is equivalent to using tr in a table) We loose the original interest of definition lists, but on the counterpart this is an easy manner to get pseudo-tables that are quickly and pretty styled.

THE CSS:

dl {
 margin:0;
 padding:0;
 clear:both;
 overflow:hidden;
}
dt {
 margin:0;
 padding:0;
 float:left;
 width:28%;
 list-style-type:bullet;
}
dd {
 margin:0;
 padding:0;
 float:right;
 width:72%;
}

.huitCinqPts dl dt, .huitCinqPts dl dd {font-size:11.3px;}
.bord_inf_gc dl {padding-top:0.23em;padding-bottom:0.5em;border-bottom:1px solid #aaa;}

THE HTML:

<div class="huitCinqPts bord_inf_gc">
  <dl><dt>Term1</dt><dd>Definition1</dd></dl>
  <dl><dt>Term2</dt><dd>Definition2</dd></dl>
</div>

Fit cell width to content

I'm not sure if I understand your question, but I'll take a stab at it:

_x000D_
_x000D_
td {
    border: 1px solid #000;
}

tr td:last-child {
    width: 1%;
    white-space: nowrap;
}
_x000D_
<table style="width: 100%;">
    <tr>
        <td class="block">this should stretch</td>
        <td class="block">this should stretch</td>
        <td class="block">this should be the content width</td>
    </tr>
</table>
_x000D_
_x000D_
_x000D_

Programmatically select a row in JTable

You can do it calling setRowSelectionInterval :

table.setRowSelectionInterval(0, 0);

to select the first row.

No 'Access-Control-Allow-Origin' header is present on the requested resource - Resteasy

Seems your resource POSTmethod won't get hit as @peeskillet mention. Most probably your ~POST~ request won't work, because it may not be a simple request. The only simple requests are GET, HEAD or POST and request headers are simple(The only simple headers are Accept, Accept-Language, Content-Language, Content-Type= application/x-www-form-urlencoded, multipart/form-data, text/plain).

Since in you already add Access-Control-Allow-Origin headers to your Response, you can add new OPTIONS method to your resource class.

    @OPTIONS
@Path("{path : .*}")
public Response options() {
    return Response.ok("")
            .header("Access-Control-Allow-Origin", "*")
            .header("Access-Control-Allow-Headers", "origin, content-type, accept, authorization")
            .header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD")
            .header("Access-Control-Max-Age", "2000")
            .build();
}

Remove all stylings (border, glow) from textarea

try this:

textarea {
        border-style: none;
        border-color: Transparent;
        overflow: auto;
        outline: none;
      }

jsbin: http://jsbin.com/orozon/2/

How can I generate a tsconfig.json file?

If you don't want to install Typescript globally (which makes sense to me, so you don't need to update it constantly), you can use npx:

npx -p typescript tsc --init

The key point is using the -p flag to inform npx that the tsc binary belongs to the typescript package

android asynctask sending callbacks to ui

I felt the below approach is very easy.

I have declared an interface for callback

public interface AsyncResponse {
    void processFinish(Object output);
}

Then created asynchronous Task for responding all type of parallel requests

 public class MyAsyncTask extends AsyncTask<Object, Object, Object> {

    public AsyncResponse delegate = null;//Call back interface

    public MyAsyncTask(AsyncResponse asyncResponse) {
        delegate = asyncResponse;//Assigning call back interfacethrough constructor
    }

    @Override
    protected Object doInBackground(Object... params) {

    //My Background tasks are written here

      return {resutl Object}

    }

    @Override
    protected void onPostExecute(Object result) {
        delegate.processFinish(result);
    }

}

Then Called the asynchronous task when clicking a button in activity Class.

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {

        Button mbtnPress = (Button) findViewById(R.id.btnPress);

        mbtnPress.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                MyAsyncTask asyncTask =new MyAsyncTask(new AsyncResponse() {

                    @Override
                    public void processFinish(Object output) {
                        Log.d("Response From Asynchronous task:", (String) output);          
                        mbtnPress.setText((String) output);
                    }
                });
                asyncTask.execute(new Object[] { "Youe request to aynchronous task class is giving here.." });

            }
        });
    }
}

Thanks

How to convert seconds to time format?

$hours = floor($seconds / 3600);
$mins = floor($seconds / 60 % 60);
$secs = floor($seconds % 60);

If you want to get time format:

$timeFormat = sprintf('%02d:%02d:%02d', $hours, $mins, $secs);

How to delete the top 1000 rows from a table using Sql Server 2008?

I agree with the Hamed elahi and Glorfindel.

My suggestion to add is you can delete and update using aliases

/* 
  given a table bi_customer_actions
  with a field bca_delete_flag of tinyint or bit
    and a field bca_add_date of datetime

  note: the *if 1=1* structure allows me to fold them and turn them on and off
 */
declare
        @Nrows int = 1000

if 1=1 /* testing the inner select */
begin
  select top (@Nrows) * 
    from bi_customer_actions
    where bca_delete_flag = 1
    order by bca_add_date
end

if 1=1 /* delete or update or select */
begin
  --select bca.*
  --update bca  set bca_delete_flag = 0
  delete bca
    from (
      select top (@Nrows) * 
        from bi_customer_actions
        where bca_delete_flag = 1
        order by bca_add_date
    ) as bca
end 

How to check for DLL dependency?

Please search "depends.exe" in google, it's a tiny utility to handle this.

Why does dividing two int not yield the right value when assigned to double?

The important thing is one of the elements of calculation be a float-double type. Then to get a double result you need to cast this element like shown below:

c = static_cast<double>(a) / b;

or c = a / static_cast(b);

Or you can create it directly::

c = 7.0 / 3;

Note that one of elements of calculation must have the '.0' to indicate a division of a float-double type by an integer. Otherwise, despite the c variable be a double, the result will be zero too (an integer).

Set attribute without value

You can do it without jQuery!

Example:

_x000D_
_x000D_
document.querySelector('button').setAttribute('disabled', '');
_x000D_
<button>My disabled button!</button>
_x000D_
_x000D_
_x000D_

To set the value of a Boolean attribute, such as disabled, you can specify any value. An empty string or the name of the attribute are recommended values. All that matters is that if the attribute is present at all, regardless of its actual value, its value is considered to be true. The absence of the attribute means its value is false. By setting the value of the disabled attribute to the empty string (""), we are setting disabled to true, which results in the button being disabled.

From MDN Element.setAttribute()

Foreach value from POST from form

i wouldn't do it this way

I'd use name arrays in the form elements

so i'd get the layout

$_POST['field'][0]['name'] = 'value';
$_POST['field'][0]['price'] = 'value';
$_POST['field'][1]['name'] = 'value';
$_POST['field'][1]['price'] = 'value';

then you could do an array slice to get the amount you need

How to use moment.js library in angular 2 typescript app?

--- Update 11/01/2017

Typings is now deprecated and it was replaced by npm @types. From now on getting type declarations will require no tools apart from npm. To use Moment you won't need to install the type definitions through @types because Moment already provides its own type definitions.

So, it reduces to just 3 steps:

1 - Install moment which includes the type definitions:

npm install moment --save

2 - Add the script tag in your HTML file:

<script src="node_modules/moment/moment.js" />

3 - Now you can just use it. Period.

today: string = moment().format('D MMM YYYY');

--- Original answer

This can be done in just 3 steps:

1 - Install moment definition - *.d.ts file:

typings install --save --global dt~moment dt~moment-node

2 - Add the script tag in your HTML file:

<script src="node_modules/moment/moment.js" />

3 - Now you can just use it. Period.

today: string = moment().format('D MMM YYYY');

How to describe "object" arguments in jsdoc?

From the @param wiki page:


Parameters With Properties

If a parameter is expected to have a particular property, you can document that immediately after the @param tag for that parameter, like so:

 /**
  * @param userInfo Information about the user.
  * @param userInfo.name The name of the user.
  * @param userInfo.email The email of the user.
  */
 function logIn(userInfo) {
        doLogIn(userInfo.name, userInfo.email);
 }

There used to be a @config tag which immediately followed the corresponding @param, but it appears to have been deprecated (example here).

TypeError: Cannot read property "0" from undefined

Under normal circumstances,out of bound of array when you encounter the error. So,check uo your array subscript.

What I can do to resolve "1 commit behind master"?

If the message is "n commits behind master."

You need to rebase your dev branch with master. You got the above message because after checking out dev branch from master, the master branch got new commit and has moved ahead. You need to get those new commits to your dev branch.

Steps:

git checkout master
git pull        #this will update your local master
git checkout yourDevBranch
git rebase master

there can be some merge conflicts which you have to resolve.

json_encode is returning NULL?

The PHP.net recommended way of setting the charset is now this:

mysqli_set_charset('utf8')

View google chrome's cached pictures

Modified version from @dovidev as his version loads the image externally instead of reading the local cache.

  1. Navigate to chrome://cache/
  2. In the chrome top menu go to "View > Developer > Javascript Console"
  3. In the console that opens paste the below and press enter

_x000D_
_x000D_
var cached_anchors = $$('a');_x000D_
document.body.innerHTML = '';_x000D_
for (var i in cached_anchors) {_x000D_
    var ca = cached_anchors[i];_x000D_
    if(ca.href.search('.png') > -1 || ca.href.search('.gif') > -1 || ca.href.search('.jpg') > -1) {_x000D_
        var xhr = new XMLHttpRequest();_x000D_
        xhr.open("GET", ca.href);_x000D_
        xhr.responseType = "document";_x000D_
        xhr.onload = response;_x000D_
        xhr.send();_x000D_
    }_x000D_
}_x000D_
_x000D_
function response(e) {_x000D_
  var hexdata = this.response.getElementsByTagName("pre")[2].innerHTML.split(/\r?\n/).slice(0,-1).map(e => e.split(/[\s:]+\s/)[1]).map(e => e.replace(/\s/g,'')).join('');_x000D_
  var byteArray = new Uint8Array(hexdata.length/2);_x000D_
  for (var x = 0; x < byteArray.length; x++){_x000D_
      byteArray[x] = parseInt(hexdata.substr(x*2,2), 16);_x000D_
  }_x000D_
  var blob = new Blob([byteArray], {type: "application/octet-stream"});_x000D_
  var image = new Image();_x000D_
  image.src = URL.createObjectURL(blob);_x000D_
  document.body.appendChild(image);_x000D_
}
_x000D_
_x000D_
_x000D_

What is the difference between JVM, JDK, JRE & OpenJDK?

JVM is the virtual machine Java code executes on

JRE is the environment (standard libraries and JVM) required to run Java applications

JDK is the JRE with developer tools and documentations

OpenJDK is an open-source version of the JDK, unlike the common JDK owned by Oracle

Regular Expression with wildcards to match any character

The following should work:

ABC: *\([a-zA-Z]+\) *(.+)

Explanation:

ABC:            # match literal characters 'ABC:'
 *              # zero or more spaces
\([a-zA-Z]+\)   # one or more letters inside of parentheses
 *              # zero or more spaces
(.+)            # capture one or more of any character (except newlines)

To get your desired grouping based on the comments below, you can use the following:

(ABC:) *(\([a-zA-Z]+\).+)

UPDATE with CASE and IN - Oracle

Use to_number to convert budgpost to a number:

when to_number(budgpost,99999) in (1001,1012,50055) THEN 'BP_GR_A' 

EDIT: Make sure there are enough 9's in to_number to match to largest budget post.

If there are non-numeric budget posts, you could filter them out with a where clause at then end of the query:

where regexp_like(budgpost, '^-?[[:digit:],.]+$')

How to get enum value by string or int

Simply try this

It's another way

public enum CaseOriginCode
{
    Web = 0,
    Email = 1,
    Telefoon = 2
}

public void setCaseOriginCode(string CaseOriginCode)
{
    int caseOriginCode = (int)(CaseOriginCode)Enum.Parse(typeof(CaseOriginCode), CaseOriginCode);
}

Java: Integer equals vs. ==

You can't compare two Integer with a simple == they're objects so most of the time references won't be the same.

There is a trick, with Integer between -128 and 127, references will be the same as autoboxing uses Integer.valueOf() which caches small integers.

If the value p being boxed is true, false, a byte, a char in the range \u0000 to \u007f, or an int or short number between -128 and 127, then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2.


Resources :

On the same topic :

ORA-01843 not a valid month- Comparing Dates

I know this is a bit late, but I'm having a similar issue. SQL*Plus executes the query successfully, but Oracle SQL Developer shows the ORA-01843: not a valid month error.

SQL*Plus seems to know that the date I'm using is in the valid format, whereas Oracle SQL Developer needs to be told explicitly what format my date is in.

  • SQL*Plus statement:

    select count(*) from some_table where DATE_TIME_CREATED < '09-12-23';
    

VS

  • Oracle SQL Developer statement:

     select count(*) from some_table where DATE_TIME_CREATED < TO_DATE('09-12-23','RR-MM-DD');
    

Difference between Width:100% and width:100vw?

vw and vh stand for viewport width and viewport height respectively.

The difference between using width: 100vw instead of width: 100% is that while 100% will make the element fit all the space available, the viewport width has a specific measure, in this case the width of the available screen, including the document margin.

If you set the style body { margin: 0 }, 100vw should behave the same as 100%.

Additional notes

Using vw as unit for everything in your website, including font sizes and heights, will make it so that the site is always displayed proportionally to the device's screen width regardless of it's resolution. This makes it super easy to ensure your website is displayed properly in both workstation and mobile.

You can set font-size: 1vw (or whatever size suits your project) in your body CSS and everything specified in rem units will automatically scale according to the device screen, so it's easy to port existing projects and even frameworks (such as Bootstrap) to this concept.

How can I detect Internet Explorer (IE) and Microsoft Edge using JavaScript?

Here is a javascript class that detects IE10, IE11 and Edge.
Navigator object is injected for testing purposes.

var DeviceHelper = function (_navigator) {
    this.navigator = _navigator || navigator;
};
DeviceHelper.prototype.isIE = function() {
    if(!this.navigator.userAgent) {
        return false;
    }

    var IE10 = Boolean(this.navigator.userAgent.match(/(MSIE)/i)),
        IE11 = Boolean(this.navigator.userAgent.match(/(Trident)/i));
    return IE10 || IE11;
};

DeviceHelper.prototype.isEdge = function() {
    return !!this.navigator.userAgent && this.navigator.userAgent.indexOf("Edge") > -1;
};

DeviceHelper.prototype.isMicrosoftBrowser = function() {
    return this.isEdge() || this.isIE();
};

ResourceDictionary in a separate assembly

Check out the pack URI syntax. You want something like this:

<ResourceDictionary Source="pack://application:,,,/YourAssembly;component/Subfolder/YourResourceFile.xaml"/>

Why doesn't list have safe "get" method like dictionary?

A reasonable thing you can do is to convert the list into a dict and then access it with the get method:

>>> my_list = ['a', 'b', 'c', 'd', 'e']
>>> my_dict = dict(enumerate(my_list))
>>> print my_dict
{0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e'}
>>> my_dict.get(2)
'c'
>>> my_dict.get(10, 'N/A')

JPA Criteria API - How to add JOIN clause (as general sentence as possible)

Warning! There's a numbers of errors on the Sun JPA 2 example and the resulting pasted content in Pascal's answer. Please consult this post.

This post and the Sun Java EE 6 JPA 2 example really held back my comprehension of JPA 2. After plowing through the Hibernate and OpenJPA manuals and thinking that I had a good understanding of JPA 2, I still got confused afterwards when returning to this post.

How to convert milliseconds into a readable date?

Building on lonesomeday's example (upvote that answer not this one), I ran into this output:

undefined NaN, NaN

_x000D_
_x000D_
var datetime = '1324339200000'; //LOOK HERE_x000D_
_x000D_
function prettyDate(date) {_x000D_
  var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',_x000D_
                'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];_x000D_
_x000D_
  return months[date.getUTCMonth()] + ' ' + date.getUTCDate() + ', ' + date.getUTCFullYear();_x000D_
}_x000D_
_x000D_
console.log(prettyDate(new Date(datetime))); //AND HERE
_x000D_
_x000D_
_x000D_

The cause was using a string as input. To fix it, prefix the string with a plus sign:

prettyDate(new Date(+datetime));

_x000D_
_x000D_
var datetime = '1324339200000';_x000D_
_x000D_
function prettyDate(date) {_x000D_
  var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',_x000D_
                'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];_x000D_
_x000D_
  return months[date.getUTCMonth()] + ' ' + date.getUTCDate() + ', ' + date.getUTCFullYear();_x000D_
}_x000D_
_x000D_
console.log(prettyDate(new Date(+datetime))); //HERE
_x000D_
_x000D_
_x000D_

To add Hours/Minutes to the output:

_x000D_
_x000D_
var datetime = '1485010730253';_x000D_
_x000D_
function prettyDate(date) {_x000D_
  var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',_x000D_
                'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];_x000D_
_x000D_
  return months[date.getUTCMonth()] +' '+ date.getUTCDate()+ ', '+ date.getUTCHours() +':'+ date.getUTCMinutes();_x000D_
}_x000D_
_x000D_
console.log(prettyDate(new Date(+datetime)));
_x000D_
_x000D_
_x000D_

Accessing dict_keys element by index in Python3

Python 3

mydict = {'a': 'one', 'b': 'two', 'c': 'three'}
mykeys = [*mydict]          #list of keys
myvals = [*mydict.values()] #list of values

print(mykeys)
print(myvals)

Output

['a', 'b', 'c']
['one', 'two', 'three']

Also see this detailed answer

How to install sklearn?

You didn't provide us which operating system are you on? If it is a Linux, make sure you have scipy installed as well, after that just do

pip install -U scikit-learn

If you are on windows you might want to check out these pages.

Installing cmake with home-brew

Typing brew install cmake as you did installs cmake. Now you can type cmake and use it.

If typing cmake doesn’t work make sure /usr/local/bin is your PATH. You can see it with echo $PATH. If you don’t see /usr/local/bin in it add the following to your ~/.bashrc:

export PATH="/usr/local/bin:$PATH"

Then reload your shell session and try again.


(all the above assumes Homebrew is installed in its default location, /usr/local. If not you’ll have to replace /usr/local with $(brew --prefix) in the export line)

Print in new line, java

/n and /r usage depends on the platform (Window, Mac, Linux) which you are using.
But there are some platform independent separators too:

  1. System.lineSeparator()
    
  2. System.getProperty("line.separator")
    

Angular 2 Scroll to top on Route Change

The best answer resides in the Angular GitHub discussion (Changing route doesn't scroll to top in the new page).

Maybe you want go to top only in root router changes (not in children, because you can load routes with lazy load in f.e. a tabset)

app.component.html

<router-outlet (deactivate)="onDeactivate()"></router-outlet>

app.component.ts

onDeactivate() {
  document.body.scrollTop = 0;
  // Alternatively, you can scroll to top by using this other call:
  // window.scrollTo(0, 0)
}

Full credits to JoniJnm (original post)

How to deep merge instead of shallow merge?

You can use Lodash merge:

var object = {
  'a': [{ 'b': 2 }, { 'd': 4 }]
};

var other = {
  'a': [{ 'c': 3 }, { 'e': 5 }]
};

_.merge(object, other);
// => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] }

Creating default object from empty value in PHP?

Try this if you have array and add objects to it.

$product_details = array();

foreach ($products_in_store as $key => $objects) {
  $product_details[$key] = new stdClass(); //the magic
  $product_details[$key]->product_id = $objects->id; 
   //see new object member created on the fly without warning.
}

This sends ARRAY of Objects for later use~!

Simple http post example in Objective-C?

I am a beginner in iPhone apps and I still have an issue although I followed the above advices. It looks like POST variables are not received by my server - not sure if it comes from php or objective-c code ...

the objective-c part (coded following Chris' protocol methodo)

// Create the request.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://example.php"]];

// Specify that it will be a POST request
request.HTTPMethod = @"POST";

// This is how we set header fields
[request setValue:@"application/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];

// Convert your data and set your request's HTTPBody property
NSString *stringData = [NSString stringWithFormat:@"user_name=%@&password=%@", self.userNameField.text , self.passwordTextField.text];
NSData *requestBodyData = [stringData dataUsingEncoding:NSUTF8StringEncoding];
request.HTTPBody = requestBodyData;

// Create url connection and fire request
//NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
NSData *response = [NSURLConnection sendSynchronousRequest:request
                                         returningResponse:nil error:nil];

NSLog(@"Response: %@",[[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]);

Below the php part :

if (isset($_POST['user_name'],$_POST['password'])) 

{

// Create connection
$con2=mysqli_connect($servername, $username, $password, $dbname);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else 
{
// retrieve POST vars
$username = $_POST['user_name'];
$password = $_POST['password'];

$sql = "INSERT INTO myTable (user_name, password) VALUES ('$username',   '$password')";
$retval = mysqli_query( $sql, $con2 );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";

mysqli_close($con2);

}
}
else
{
echo "No data input in php";
}

I have been stuck the last days on this one.

How to uninstall Anaconda completely from macOS

In my case (Mac High Sierra) it was installed at ~/opt/anaconda3.

https://docs.anaconda.com/anaconda/install/uninstall/

Order by in Inner Join

In SQL, the order of the output is not defined unless you specify it in the ORDER BY clause.

Try this:

SELECT  *
FROM    one
JOIN    two
ON      one.one_name = two.one_name
ORDER BY
        one.id

How to pass params with history.push/Link/Redirect in react-router v4?

React TypeScript with Hooks

From a Class

  this.history.push({
      pathname: "/unauthorized",
      state: { message: "Hello" },
    });

UnAuthorized Functional Component

interface IState {
  message?: string;
}

export default function UnAuthorized() {
  const location = useLocation();
  const message = (location.state as IState).message;

  return (
    <div className="jumbotron">
      <h6>{message}</h6>
    </div>
  );
}

Mongoimport of json file

  1. Just copy path of json file like example "C:\persons.json"
  2. go to C:\Program Files\MongoDB\Server\4.2\bin
  3. open cmd on that mongodb bin folder and run this command

mongoimport --jsonArray --db dbname--collection collectionName--file FilePath

example mongoimport --jsonArray --db learnmongo --collection persons --file C:\persons.json

how to save canvas as png image?

I had this problem and this is the best solution without any external or additional script libraries: In Javascript tags or file create this function: We assume here that canvas is your canvas:

function download(){
        var download = document.getElementById("download");
        var image = document.getElementById("canvas").toDataURL("image/png")
                    .replace("image/png", "image/octet-stream");
        download.setAttribute("href", image);

    }

In the body part of your HTML specify the button:

<a id="download" download="image.png"><button type="button" onClick="download()">Download</button></a>

This is working and download link looks like a button. Tested in Firefox and Chrome.

What exactly does a jar file contain?

However, I got curious to what each class contained and when I try to open one of the classes in the jar file, it tells me that I need a source file.

A jar file is basically a zip file containing .class files and potentially other resources (and metadata about the jar itself). It's hard to compare C to Java really, as Java byte code maintains a lot more metadata than most binary formats - but the class file is compiled code instead of source code.

If you either open the jar file with a zip utility or run jar xf foo.jar you can extract the files from it, and have a look at them. Note that you don't need a jar file to run Java code - classloaders can load class data directly from the file system, or from URLs, as well as from jar files.

Can I animate absolute positioned element with CSS transition?

try this:

.test {
    position:absolute;
    background:blue;
    width:200px;
    height:200px;
    top:40px;
    transition:left 1s linear;
    left: 0;
}

Failed to instantiate module error in Angular js

You need to include angular-route.js in your HTML:

<script src="angular-route.js">

http://docs.angularjs.org/api/ngRoute

How to inspect Javascript Objects

var str = "";
for(var k in obj)
    if (obj.hasOwnProperty(k)) //omit this test if you want to see built-in properties
        str += k + " = " + obj[k] + "\n";
alert(str);

How to output an Excel *.xls file from classic ASP

You can always just export the HTML table to an XLS document. Excel does a pretty good job understanding HTML tables.

Another possiblitly is to export the HTML tables as a CSV or TSV file, but you would need to setup the formatting in your code. This isn't too difficult to accomplish.

There's some classes in the Microsoft.Office.Interop that allow you to create an Excel file programatically, but I have always found them to be a little clumsy. You can find a .NET version of creating a spreadsheet here, which should be pretty easy to modify for classic ASP.

As for .NET, I've always liked CarlosAG's Excel XML Writer Library. It has a nice generator so you can setup your Excel file, save it as an XML spreadsheet and it generates the code to do all the formatting and everything. I know it's not classic ASP, but I thought that I would throw it out there.


With what you're trying above, try adding the header:

"Content-Disposition", "attachment; filename=excelTest.xls"

See if that works. Also, I always use this for the content type:

  Response.ContentType = "application/octet-stream"
    Response.ContentType = "application/vnd.ms-excel"

Get value of multiselect box using jQuery or pure JS

According to the widget's page, it should be:

var myDropDownListValues = $("#myDropDownList").multiselect("getChecked").map(function()
{
    return this.value;    
}).get();

It works for me :)

How to print third column to last column?

The following awk command prints the last N fields of each line and at the end of the line prints a new line character:

awk '{for( i=6; i<=NF; i++ ){printf( "%s ", $i )}; printf( "\n"); }'

Find below an example that lists the content of the /usr/bin directory and then holds the last 3 lines and then prints the last 4 columns of each line using awk:

$ ls -ltr /usr/bin/ | tail -3
-rwxr-xr-x 1 root root       14736 Jan 14  2014 bcomps
-rwxr-xr-x 1 root root       10480 Jan 14  2014 acyclic
-rwxr-xr-x 1 root root    35868448 May 22  2014 skype

$ ls -ltr /usr/bin/ | tail -3 | awk '{for( i=6; i<=NF; i++ ){printf( "%s ", $i )}; printf( "\n"); }'
Jan 14 2014 bcomps 
Jan 14 2014 acyclic 
May 22 2014 skype

Fastest way to get the first n elements of a List into an Array

Option 1 Faster Than Option 2

Because Option 2 creates a new List reference, and then creates an n element array from the List (option 1 perfectly sizes the output array). However, first you need to fix the off by one bug. Use < (not <=). Like,

String[] out = new String[n];
for(int i = 0; i < n; i++) {
    out[i] = in.get(i);
}

How to create EditText with rounded corners?

Here is the same solution (with some extra bonus code) in just one XML file:

<?xml version="1.0" encoding="utf-8"?>
<!--  res/drawable/edittext_rounded_corners.xml -->
<selector xmlns:android="http://schemas.android.com/apk/res/android">

<item android:state_pressed="true" android:state_focused="true">
    <shape>
        <solid android:color="#FF8000"/>
        <stroke
            android:width="2.3dp"
            android:color="#FF8000" />
         <corners
            android:radius="15dp" />
    </shape>
</item>

<item android:state_pressed="true" android:state_focused="false">
    <shape>
        <solid android:color="#FF8000"/>
        <stroke
            android:width="2.3dp"
            android:color="#FF8000" />      
        <corners
            android:radius="15dp" />       
    </shape>
</item>

<item android:state_pressed="false" android:state_focused="true">
    <shape>
        <solid android:color="#FFFFFF"/>
        <stroke
            android:width="2.3dp"
            android:color="#FF8000" />  
        <corners
            android:radius="15dp" />                          
    </shape>
</item>

<item android:state_pressed="false" android:state_focused="false">
    <shape>
        <gradient 
            android:startColor="#F2F2F2"
            android:centerColor="#FFFFFF"
            android:endColor="#FFFFFF"
            android:angle="270"
        />
        <stroke
            android:width="0.7dp"                
            android:color="#BDBDBD" /> 
        <corners
            android:radius="15dp" />            
    </shape>
</item>

<item android:state_enabled="true">
    <shape>
        <padding 
                android:left="4dp"
                android:top="4dp"
                android:right="4dp"
                android:bottom="4dp"
            />
    </shape>
</item>

</selector>

You then just set the background attribute to edittext_rounded_corners.xml file:

<EditText  android:id="@+id/editText_name"
      android:background="@drawable/edittext_rounded_corners"/>

PHP: How do you determine every Nth iteration of a loop?

I am using this a status update to show a "+" character every 1000 iterations, and it seems to be working good.

if ($ucounter % 1000 == 0) { echo '+'; }

How to make child element higher z-index than parent?

To achieve what you want without removing any styles you have to make the z-index of the '.parent' class bigger then the '.wholePage' class.

.parent {
    position: relative;
    z-index: 4; /*matters since it's sibling to wholePage*/
}

.child {
    position: relative;
    z-index:1; /*doesn't matter */
    background-color: white;
    padding: 5px;
}

jsFiddle: http://jsfiddle.net/ZjXMR/2/

how to set the query timeout from SQL connection string

Only from code:

_x000D_
_x000D_
namespace xxx.DsXxxTableAdapters {_x000D_
    partial class ZzzTableAdapter_x000D_
    {_x000D_
        public void SetTimeout(int timeout)_x000D_
        {_x000D_
            if (this.Adapter.DeleteCommand != null) { this.Adapter.DeleteCommand.CommandTimeout = timeout; }_x000D_
            if (this.Adapter.InsertCommand != null) { this.Adapter.InsertCommand.CommandTimeout = timeout; }_x000D_
            if (this.Adapter.UpdateCommand != null) { this.Adapter.UpdateCommand.CommandTimeout = timeout; }_x000D_
            if (this._commandCollection == null) { this.InitCommandCollection(); }_x000D_
            if (this._commandCollection != null)_x000D_
            {_x000D_
                foreach (System.Data.SqlClient.SqlCommand item in this._commandCollection)_x000D_
                {_x000D_
                    if (item != null)_x000D_
                    { item.CommandTimeout = timeout; }_x000D_
                }_x000D_
            }_x000D_
        }_x000D_
    }_x000D_
 _x000D_
    //...._x000D_
 _x000D_
 }
_x000D_
_x000D_
_x000D_

How do I convert a long to a string in C++?

You could use stringstream.

#include <sstream>

// ...
std::string number;
std::stringstream strstream;
strstream << 1L;
strstream >> number;

There is usually some proprietary C functions in the standard library for your compiler that does it too. I prefer the more "portable" variants though.

The C way to do it would be with sprintf, but that is not very secure. In some libraries there is new versions like sprintf_s which protects against buffer overruns.

OR is not supported with CASE Statement in SQL Server

UPDATE table_name 
  SET column_name=CASE 
WHEN column_name in ('value1', 'value2',.....) 
  THEN 'update_value' 
WHEN column_name in ('value1', 'value2',.....) 
  THEN 'update_value' 
END

table_name = The name of table on which you want to perform operation.

column_name = The name of Column/Field of which value you want to set.

update_value = The value you want to set of column_name

I can't understand why this JAXB IllegalAnnotationException is thrown

for me this error was actually caused by a field falsely declared as public instead of private.

Loop through a comma-separated shell variable

Here is an alternative tr based solution that doesn't use echo, expressed as a one-liner.

for v in $(tr ',' '\n' <<< "$var") ; do something_with "$v" ; done

It feels tidier without echo but that is just my personal preference.

How to get JQuery.trigger('click'); to initiate a mouse click

Just use this:

$(function() {
 $('#watchButton').trigger('click');
});

Circle line-segment collision detection algorithm?

Here's an implementation in Javascript. My approach is to first convert the line segment into an infinite line then find the intersection point(s). From there I check if the point(s) found are on the line segment. The code is well documented, you should be able to follow along.

You can try out the code here on this live demo. The code was taken from my algorithms repo.

enter image description here

// Small epsilon value
var EPS = 0.0000001;

// point (x, y)
function Point(x, y) {
  this.x = x;
  this.y = y;
}

// Circle with center at (x,y) and radius r
function Circle(x, y, r) {
  this.x = x;
  this.y = y;
  this.r = r;
}

// A line segment (x1, y1), (x2, y2)
function LineSegment(x1, y1, x2, y2) {
  var d = Math.sqrt( (x1-x2)*(x1-x2) + (y1-y2)*(y1-y2) );
  if (d < EPS) throw 'A point is not a line segment';
  this.x1 = x1; this.y1 = y1;
  this.x2 = x2; this.y2 = y2;
}

// An infinite line defined as: ax + by = c
function Line(a, b, c) {
  this.a = a; this.b = b; this.c = c;
  // Normalize line for good measure
  if (Math.abs(b) < EPS) {
    c /= a; a = 1; b = 0;
  } else { 
    a = (Math.abs(a) < EPS) ? 0 : a / b;
    c /= b; b = 1; 
  }
}

// Given a line in standard form: ax + by = c and a circle with 
// a center at (x,y) with radius r this method finds the intersection
// of the line and the circle (if any). 
function circleLineIntersection(circle, line) {

  var a = line.a, b = line.b, c = line.c;
  var x = circle.x, y = circle.y, r = circle.r;

  // Solve for the variable x with the formulas: ax + by = c (equation of line)
  // and (x-X)^2 + (y-Y)^2 = r^2 (equation of circle where X,Y are known) and expand to obtain quadratic:
  // (a^2 + b^2)x^2 + (2abY - 2ac + - 2b^2X)x + (b^2X^2 + b^2Y^2 - 2bcY + c^2 - b^2r^2) = 0
  // Then use quadratic formula X = (-b +- sqrt(a^2 - 4ac))/2a to find the 
  // roots of the equation (if they exist) and this will tell us the intersection points

  // In general a quadratic is written as: Ax^2 + Bx + C = 0
  // (a^2 + b^2)x^2 + (2abY - 2ac + - 2b^2X)x + (b^2X^2 + b^2Y^2 - 2bcY + c^2 - b^2r^2) = 0
  var A = a*a + b*b;
  var B = 2*a*b*y - 2*a*c - 2*b*b*x;
  var C = b*b*x*x + b*b*y*y - 2*b*c*y + c*c - b*b*r*r;

  // Use quadratic formula x = (-b +- sqrt(a^2 - 4ac))/2a to find the 
  // roots of the equation (if they exist).

  var D = B*B - 4*A*C;
  var x1,y1,x2,y2;

  // Handle vertical line case with b = 0
  if (Math.abs(b) < EPS) {

    // Line equation is ax + by = c, but b = 0, so x = c/a
    x1 = c/a;

    // No intersection
    if (Math.abs(x-x1) > r) return [];

    // Vertical line is tangent to circle
    if (Math.abs((x1-r)-x) < EPS || Math.abs((x1+r)-x) < EPS)
      return [new Point(x1, y)];

    var dx = Math.abs(x1 - x);
    var dy = Math.sqrt(r*r-dx*dx);

    // Vertical line cuts through circle
    return [
      new Point(x1,y+dy),
      new Point(x1,y-dy)
    ];

  // Line is tangent to circle
  } else if (Math.abs(D) < EPS) {

    x1 = -B/(2*A);
    y1 = (c - a*x1)/b;

    return [new Point(x1,y1)];

  // No intersection
  } else if (D < 0) {

    return [];

  } else {

    D = Math.sqrt(D);

    x1 = (-B+D)/(2*A);
    y1 = (c - a*x1)/b;

    x2 = (-B-D)/(2*A);
    y2 = (c - a*x2)/b;

    return [
      new Point(x1, y1),
      new Point(x2, y2)
    ];

  }

}

// Converts a line segment to a line in general form
function segmentToGeneralForm(x1,y1,x2,y2) {
  var a = y1 - y2;
  var b = x2 - x1;
  var c = x2*y1 - x1*y2;
  return new Line(a,b,c);
}

// Checks if a point 'pt' is inside the rect defined by (x1,y1), (x2,y2)
function pointInRectangle(pt,x1,y1,x2,y2) {
  var x = Math.min(x1,x2), X = Math.max(x1,x2);
  var y = Math.min(y1,y2), Y = Math.max(y1,y2);
  return x - EPS <= pt.x && pt.x <= X + EPS &&
         y - EPS <= pt.y && pt.y <= Y + EPS;
}

// Finds the intersection(s) of a line segment and a circle
function lineSegmentCircleIntersection(segment, circle) {

  var x1 = segment.x1, y1 = segment.y1, x2 = segment.x2, y2 = segment.y2;
  var line = segmentToGeneralForm(x1,y1,x2,y2);
  var pts = circleLineIntersection(circle, line);

  // No intersection
  if (pts.length === 0) return [];

  var pt1 = pts[0];
  var includePt1 = pointInRectangle(pt1,x1,y1,x2,y2);

  // Check for unique intersection
  if (pts.length === 1) {
    if (includePt1) return [pt1];
    return [];
  }

  var pt2 = pts[1];
  var includePt2 = pointInRectangle(pt2,x1,y1,x2,y2);

  // Check for remaining intersections
  if (includePt1 && includePt2) return [pt1, pt2];
  if (includePt1) return [pt1];
  if (includePt2) return [pt2];
  return [];

}

How to merge a specific commit in Git

If you have committed changes to master branch. Now you want to move that same commit to release-branch. Check the commit id(Eg:xyzabc123) for the commit.

Now try following commands

git checkout release-branch
git cherry-pick xyzabc123
git push origin release-branch

MySQL command line client for Windows

mysql.exe is included in mysql package. You don't have to install anything additionally.

How to launch a Google Chrome Tab with specific URL using C#

If the user doesn't have Chrome, it will throw an exception like this:

    //chrome.exe http://xxx.xxx.xxx --incognito
    //chrome.exe http://xxx.xxx.xxx -incognito
    //chrome.exe --incognito http://xxx.xxx.xxx
    //chrome.exe -incognito http://xxx.xxx.xxx
    private static void Chrome(string link)
    {
        string url = "";

        if (!string.IsNullOrEmpty(link)) //if empty just run the browser
        {
            if (link.Contains('.')) //check if it's an url or a google search
            {
                url = link;
            }
            else
            {
                url = "https://www.google.com/search?q=" + link.Replace(" ", "+");
            }
        }

        try
        {
            Process.Start("chrome.exe", url + " --incognito");
        }
        catch (System.ComponentModel.Win32Exception e)
        {
            MessageBox.Show("Unable to find Google Chrome...",
                "chrome.exe not found!", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

How do I format a date in Jinja2?

Made it.

from datetime import datetime
dateNow = datetime.now().strftime('%Y%m%d')

select count(*) from table of mysql in php

If you only need the value:

$result = mysql_query("SELECT count(*) from Students;");
echo mysql_result($result, 0);

how to hide <li> bullets in navigation menu and footer links BUT show them for listing items

You can also define a class for the bullets you want to show, so in the CSS:

ul {list-style:none; list-style-type:none; list-style-image:none;}

And in the HTML you just define which lists to show:

<ul style="list-style:disc;">

Or you alternatively define a CSS class:

.show-list {list-style:disc;}

Then apply it to the list you want to show:

<ul class="show-list">

All other lists won't show the bullets...

Any good boolean expression simplifiers out there?

I found that The Boolean Expression Reducer is much easier to use than Logic Friday. Plus it doesn't require installation and is multi-platform (Java).

Also in Logic Friday the expression A | B just returns 3 entries in truth table; I expected 4.

Select row and element in awk

To print the columns with a specific string, you use the // search pattern. For example, if you are looking for second columns that contains abc:

awk '$2 ~ /abc/'

... and if you want to print only a particular column:

awk '$2 ~ /abc/ { print $3 }'

... and for a particular line number:

awk '$2 ~ /abc/ && FNR == 5 { print $3 }'

How can I add a variable to console.log?

You can use another console method:

let name = prompt("what is your name?");
console.log(`story ${name} story`);

Server.MapPath("."), Server.MapPath("~"), Server.MapPath(@"\"), Server.MapPath("/"). What is the difference?

Just to expand on @splattne's answer a little:

MapPath(string virtualPath) calls the following:

public string MapPath(string virtualPath)
{
    return this.MapPath(VirtualPath.CreateAllowNull(virtualPath));
}

MapPath(VirtualPath virtualPath) in turn calls MapPath(VirtualPath virtualPath, VirtualPath baseVirtualDir, bool allowCrossAppMapping) which contains the following:

//...
if (virtualPath == null)
{
    virtualPath = VirtualPath.Create(".");
}
//...

So if you call MapPath(null) or MapPath(""), you are effectively calling MapPath(".")

Django values_list vs values

values()

Returns a QuerySet that returns dictionaries, rather than model instances, when used as an iterable.

values_list()

Returns a QuerySet that returns list of tuples, rather than model instances, when used as an iterable.

distinct()

distinct are used to eliminate the duplicate elements.

Example:

>>> list(Article.objects.values_list('id', flat=True)) # flat=True will remove the tuples and return the list   
[1, 2, 3, 4, 5, 6]

>>> list(Article.objects.values('id'))
[{'id':1}, {'id':2}, {'id':3}, {'id':4}, {'id':5}, {'id':6}]

How can I convert an image into a Base64 string?

If you're doing this on Android, here's a helper copied from the React Native codebase:

import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import android.util.Base64;
import android.util.Base64OutputStream;
import android.util.Log;

// You probably don't want to do this with large files
// (will allocate a large string and can cause an OOM crash).
private String readFileAsBase64String(String path) {
  try {
    InputStream is = new FileInputStream(path);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    Base64OutputStream b64os = new Base64OutputStream(baos, Base64.DEFAULT);
    byte[] buffer = new byte[8192];
    int bytesRead;
    try {
      while ((bytesRead = is.read(buffer)) > -1) {
        b64os.write(buffer, 0, bytesRead);
      }
      return baos.toString();
    } catch (IOException e) {
      Log.e(TAG, "Cannot read file " + path, e);
      // Or throw if you prefer
      return "";
    } finally {
      closeQuietly(is);
      closeQuietly(b64os); // This also closes baos
    }
  } catch (FileNotFoundException e) {
    Log.e(TAG, "File not found " + path, e);
    // Or throw if you prefer
    return "";
  }
}

private static void closeQuietly(Closeable closeable) {
  try {
    closeable.close();
  } catch (IOException e) {
  }
}

String to Binary in C#

It sounds like you basically want to take an ASCII string, or more preferably, a byte[] (as you can encode your string to a byte[] using your preferred encoding mode) into a string of ones and zeros? i.e. 101010010010100100100101001010010100101001010010101000010111101101010

This will do that for you...

//Formats a byte[] into a binary string (010010010010100101010)
public string Format(byte[] data)
{
    //storage for the resulting string
    string result = string.Empty;
    //iterate through the byte[]
    foreach(byte value in data)
    {
        //storage for the individual byte
        string binarybyte = Convert.ToString(value, 2);
        //if the binarybyte is not 8 characters long, its not a proper result
        while(binarybyte.Length < 8)
        {
            //prepend the value with a 0
            binarybyte = "0" + binarybyte;
        }
        //append the binarybyte to the result
        result += binarybyte;
    }
    //return the result
    return result;
}

How to force link from iframe to be opened in the parent window

With JavaScript:

window.parent.location.href= "http://www.google.com";

Why am I getting InputMismatchException?

Here you can see the nature of Scanner:

double nextDouble()

Returns the next token as a double. If the next token is not a float or is out of range, InputMismatchException is thrown.

Try to catch the exception

try {
    // ...
} catch (InputMismatchException e) {
    System.out.print(e.getMessage()); //try to find out specific reason.
}

UPDATE

CASE 1

I tried your code and there is nothing wrong with it. Your are getting that error because you must have entered String value. When I entered a numeric value, it runs without any errors. But once I entered String it throw the same Exception which you have mentioned in your question.

CASE 2

You have entered something, which is out of range as I have mentioned above.

I'm really wondering what you could have tried to enter. In my system, it is running perfectly without changing a single line of code. Just copy as it is and try to compile and run it.

import java.util.*;

public class Test {
    public static void main(String... args) {
        new Test().askForMarks(5);
    }

    public void askForMarks(int student) {
        double marks[] = new double[student];
        int index = 0;
        Scanner reader = new Scanner(System.in);
        while (index < student) {
            System.out.print("Please enter a mark (0..30): ");
            marks[index] = (double) checkValueWithin(0, 30); 
            index++;
        }
    }

    public double checkValueWithin(int min, int max) {
        double num;
        Scanner reader = new Scanner(System.in);
        num = reader.nextDouble();                         
        while (num < min || num > max) {                 
            System.out.print("Invalid. Re-enter number: "); 
            num = reader.nextDouble();                         
        } 

        return num;
    }
}

As you said, you have tried to enter 1.0, 2.8 and etc. Please try with this code.

Note : Please enter number one by one, on separate lines. I mean, enter 2.7, press enter and then enter second number (e.g. 6.7).

How can I add a class to a DOM element in JavaScript?

Cross-browser solution

Note: The classList property is not supported in Internet Explorer 9. The following code will work in all browsers:

function addClass(id,classname) {
  var element, name, arr;
  element = document.getElementById(id);
  arr = element.className.split(" ");
  if (arr.indexOf(classname) == -1) { // check if class is already added
    element.className += " " + classname;
  }
}

addClass('div1','show')

Source: how to js add class

Django MEDIA_URL and MEDIA_ROOT

Following the steps mentioned above for =>3.0 for Debug mode

urlpatterns = [
...
]
+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

And also the part that caught me out, the above static URL only worked in my main project urls.py file. I was first attempting to add to my app, and wondering why I couldn't see the images.

Lastly make sure you set the following:

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

How to set width of a div in percent in JavaScript?

Yes, it is:

<div id="myid">Some Content........</div>

document.getElementById('#myid').style.width = '50%';

Set textbox to readonly and background color to grey in jquery

Can add disable like below and can get data on submit. something like this .. DEMO

Html

<input type="hidden" name="email" value="email" />
<input type="text" id="dis" class="disable" value="email"   name="email" >

JS

 $("#dis").attr('disabled','disabled');

CSS

    .disable { opacity : .35; background-color:lightgray; border:1px solid gray;}

Jquery click event not working after append method

Use on :

$('#registered_participants').on('click', '.new_participant_form', function() {

So that the click is delegated to any element in #registered_participants having the class new_participant_form, even if it's added after you bound the event handler.

PHP + curl, HTTP POST sample code?

curlPost('google.com', [
    'username' => 'admin',
    'password' => '12345',
]);


function curlPost($url, $data) {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    $response = curl_exec($ch);
    $error = curl_error($ch);
    curl_close($ch);
    if ($error !== '') {
        throw new \Exception($error);
    }

    return $response;
}

$_POST not working. "Notice: Undefined index: username..."

first of all,

be sure that there is a post

if(isset($_POST['username'])) { 
    // check if the username has been set
}

second, and most importantly, sanitize the data, meaning that

$query = "SELECT password FROM users WHERE username='".$_POST['username']."'";

is deadly dangerous, instead use

$query = "SELECT password FROM users WHERE username='".mysql_real_escape_string($_POST['username'])."'";

and please research the subject sql injection

Visual c++ can't open include file 'iostream'

I got this error when I created an 'Empty' console application in Visual Studio 2015. I re-created the application, leaving the 'Empty' box unchecked, it added all of the necessary libraries.

The transaction log for database is full. To find out why space in the log cannot be reused, see the log_reuse_wait_desc column in sys.databases

As an aside, it is always a good practice (and possibly a solution for this type of issue) to delete a large number of rows by using batches:

WHILE EXISTS (SELECT 1 
              FROM   YourTable 
              WHERE  <yourCondition>) 
  DELETE TOP(10000) FROM YourTable 
  WHERE  <yourCondition>

Multiline text in JLabel

Type the content (i.e., the "text" property field) inside a <html></html> tag. So you can use <br> or<P> to insert a newline.

For example:

String labelContent = "<html>Twinkle, twinkle, little star,<BR>How I wonder what you are.<BR>Up above the world so high,<BR>Like a diamond in the sky.</html>";

It will display as follows:

Twinkle, twinkle, little star,
How I wonder what you are.
Up above the world so high,
Like a diamond in the sky.

Could not find folder 'tools' inside SDK

If you get the "Failed to find DDMS files..." do this:

  1. Open eclipse
  2. Open install new software
  3. Click "Add..." -> type in (e.g.) "Android_over_HTTP" and in address put "http://dl-ssl.google.com/android/eclipse/".

Don't be alarmed that its not https, this helps to fetch stuff over http. This trick helped me to resolve the issue on MAC, I believe that this also should work on Windows / Linux

Hope this helps !

Composer: Command Not Found

Step 1 : Open Your terminal

Step 2 : Run bellow command

          curl -sS https://getcomposer.org/installer | php

Step 3 : After installation run bellow command

          sudo mv composer.phar /usr/local/bin/

Step 4 : Open bash_profile file create alias follow bellow steps

           vim ~/.bash_profile

Step 5 : Add bellow line in bash_profile file

          alias composer="php /usr/local/bin/composer.phar"

Step 6 : Close your terminal and reopen your terminal and run bellow command composer

Convert base64 string to image

  public Optional<String> InputStreamToBase64(Optional<InputStream> inputStream) throws IOException{
    if (inputStream.isPresent()) {
        ByteArrayOutputStream outpString base64Image = data.split(",")[1];
byte[] imageBytes = javax.xml.bind.DatatypeConverter.parseBase64Binary(base64Image);

Then you can do whatever you like with the bytes like:

BufferedImage img = ImageIO.read(new ByteArrayInputStream(imageBytes));ut = new ByteArrayOutputStream();
        FileCopyUtils.copy(inputStream.get(), output);
        //TODO retrieve content type from file, & replace png below with it
        return Optional.ofNullable("data:image/png;base64," + DatatypeConverter.printBase64Binary(output.toByteArray()));
    }

    return Optional.empty();

Polling the keyboard (detect a keypress) in python

The standard approach is to use the select module.

However, this doesn't work on Windows. For that, you can use the msvcrt module's keyboard polling.

Often, this is done with multiple threads -- one per device being "watched" plus the background processes that might need to be interrupted by the device.

Error 'tunneling socket' while executing npm install

Removing the proxy settings resolved the issue:

If you are no using any proxy:

npm config rm proxy
npm config rm https-proxy

If you are using Proxy:

npm config set proxy http://proxyhostname:proxyport
npm config set https-proxy https://proxyhostname:proxyport

Hopefully this will solve your problem :)

if else statement in AngularJS templates

Angular itself doesn't provide if/else functionality, but you can get it by including this module:

https://github.com/zachsnow/ng-elif

In its own words, it's just "a simple collection of control flow directives: ng-if, ng-else-if, and ng-else." It's easy and intuitive to use.

Example:

<div ng-if="someCondition">
    ...
</div>
<div ng-else-if="someOtherCondition">
    ...
</div>
<div ng-else>
    ...
</div>

Interview question: Check if one string is a rotation of other string

It's very easy to write in PHP using strlen and strpos functions:

function isRotation($string1, $string2) {
    return strlen($string1) == strlen($string2) && (($string1.$string1).strpos($string2) != -1);
}

I don't know what strpos uses internally, but if it uses KMP this will be linear in time.

How to find out which package version is loaded in R?

To check the version of R execute : R --version

Or after you are in the R shell print the contents of version$version.string

EDIT

To check the version of installed packages do the following.

After loading the library, you can execute sessionInfo ()

But to know the list of all installed packages:

packinfo <- installed.packages(fields = c("Package", "Version"))
packinfo[,c("Package", "Version")]

OR to extract a specific library version, once you have extracted the information using the installed.package function as above just use the name of the package in the first dimension of the matrix.

packinfo["RANN",c("Package", "Version")]
packinfo["graphics",c("Package", "Version")]

The above will print the versions of the RANN library and the graphics library.

What is the best way to repeatedly execute a function every x seconds?

I use Tkinter after() method, which doesn't "steal the game" (like the sched module that was presented earlier), i.e. it allows other things to run in parallel:

import Tkinter

def do_something1():
  global n1
  n1 += 1
  if n1 == 6: # (Optional condition)
    print "* do_something1() is done *"; return
  # Do your stuff here
  # ...
  print "do_something1() "+str(n1)
  tk.after(1000, do_something1)

def do_something2(): 
  global n2
  n2 += 1
  if n2 == 6: # (Optional condition)
    print "* do_something2() is done *"; return
  # Do your stuff here
  # ...
  print "do_something2() "+str(n2)
  tk.after(500, do_something2)

tk = Tkinter.Tk(); 
n1 = 0; n2 = 0
do_something1()
do_something2()
tk.mainloop()

do_something1() and do_something2() can run in parallel and in whatever interval speed. Here, the 2nd one will be executed twice as fast.Note also that I have used a simple counter as a condition to terminate either function. You can use whatever other contition you like or none if you what a function to run until the program terminates (e.g. a clock).

How to detect online/offline event cross-browser?

Here is my solution.

Tested with IE, Opera, Chrome, FireFox, Safari, as Phonegap WebApp on IOS 8 and as Phonegap WebApp on Android 4.4.2

This solution isn't working with FireFox on localhost.

=================================================================================

onlineCheck.js (filepath: "root/js/onlineCheck.js ):

var isApp = false;

function onLoad() {
        document.addEventListener("deviceready", onDeviceReady, false);
}

function onDeviceReady() {
    isApp = true;
    }


function isOnlineTest() {
    alert(checkOnline());
}

function isBrowserOnline(no,yes){
    //Didnt work local
    //Need "firefox.php" in root dictionary
    var xhr = XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHttp');
    xhr.onload = function(){
        if(yes instanceof Function){
            yes();
        }
    }
    xhr.onerror = function(){
        if(no instanceof Function){
            no();
        }
    }
    xhr.open("GET","checkOnline.php",true);
    xhr.send();
}

function checkOnline(){

    if(isApp)
    {
        var xhr = new XMLHttpRequest();
        var file = "http://dexheimer.cc/apps/kartei/neu/dot.png";

        try {
            xhr.open('HEAD', file , false); 
            xhr.send(null);

            if (xhr.status >= 200 && xhr.status < 304) {
                return true;
            } else {
                return false;
            }
        } catch (e) 
        {
            return false;
        }
    }else
    {
        var tmpIsOnline = false;

        tmpIsOnline = navigator.onLine;

        if(tmpIsOnline || tmpIsOnline == "undefined")
        {
            try{
                //Didnt work local
                //Need "firefox.php" in root dictionary
                var xhr = XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHttp');
                xhr.onload = function(){
                    tmpIsOnline = true;
                }
                xhr.onerror = function(){
                    tmpIsOnline = false;
                }
                xhr.open("GET","checkOnline.php",false);
                xhr.send();
            }catch (e){
                tmpIsOnline = false;
            }
        }
        return tmpIsOnline;

    }
}

=================================================================================

index.html (filepath: "root/index.html"):

<!DOCTYPE html>
<html>


<head>
    ...

    <script type="text/javascript" src="js/onlineCheck.js" ></script>

    ...

</head>

...

<body onload="onLoad()">

...

    <div onclick="isOnlineTest()">  
        Online?
    </div>
...
</body>

</html>

=================================================================================

checkOnline.php (filepath: "root"):

<?php echo 'true'; ?> 

Call another rest api from my server in Spring-Boot

Modern Spring 5+ answer using WebClient instead of RestTemplate.

Configure WebClient for a specific web-service or resource as a bean (additional properties can be configured).

@Bean
public WebClient localApiClient() {
    return WebClient.create("http://localhost:8080/api/v3");
}

Inject and use the bean from your service(s).

@Service
public class UserService {

    private static final Duration REQUEST_TIMEOUT = Duration.ofSeconds(3);

    private final WebClient localApiClient;

    @Autowired
    public UserService(WebClient localApiClient) {
        this.localApiClient = localApiClient;
    }

    public User getUser(long id) {
        return localApiClient
                .get()
                .uri("/users/" + id)
                .retrieve()
                .bodyToMono(User.class)
                .block(REQUEST_TIMEOUT);
    }

}

What is the "proper" way to cast Hibernate Query.list() to List<Type>?

Short answer @SuppressWarnings is the right way to go.

Long answer, Hibernate returns a raw List from the Query.list method, see here. This is not a bug with Hibernate or something the can be solved, the type returned by the query is not known at compile time.

Therefore when you write

final List<MyObject> list = query.list();

You are doing an unsafe cast from List to List<MyObject> - this cannot be avoided.

There is no way you can safely carry out the cast as the List could contain anything.

The only way to make the error go away is the even more ugly

final List<MyObject> list = new LinkedList<>();
for(final Object o : query.list()) {
    list.add((MyObject)o);
}

C++ cast to derived class

Think like this:

class Animal { /* Some virtual members */ };
class Dog: public Animal {};
class Cat: public Animal {};


Dog     dog;
Cat     cat;
Animal& AnimalRef1 = dog;  // Notice no cast required. (Dogs and cats are animals).
Animal& AnimalRef2 = cat;
Animal* AnimalPtr1 = &dog;
Animal* AnimlaPtr2 = &cat;

Cat&    catRef1 = dynamic_cast<Cat&>(AnimalRef1);  // Throws an exception  AnimalRef1 is a dog
Cat*    catPtr1 = dynamic_cast<Cat*>(AnimalPtr1);  // Returns NULL         AnimalPtr1 is a dog
Cat&    catRef2 = dynamic_cast<Cat&>(AnimalRef2);  // Works
Cat*    catPtr2 = dynamic_cast<Cat*>(AnimalPtr2);  // Works

// This on the other hand makes no sense
// An animal object is not a cat. Therefore it can not be treated like a Cat.
Animal  a;
Cat&    catRef1 = dynamic_cast<Cat&>(a);    // Throws an exception  Its not a CAT
Cat*    catPtr1 = dynamic_cast<Cat*>(&a);   // Returns NULL         Its not a CAT.

Now looking back at your first statement:

Animal   animal = cat;    // This works. But it slices the cat part out and just
                          // assigns the animal part of the object.
Cat      bigCat = animal; // Makes no sense.
                          // An animal is not a cat!!!!!
Dog      bigDog = bigCat; // A cat is not a dog !!!!

You should very rarely ever need to use dynamic cast.
This is why we have virtual methods:

void makeNoise(Animal& animal)
{
     animal.DoNoiseMake();
}

Dog    dog;
Cat    cat;
Duck   duck;
Chicken chicken;

makeNoise(dog);
makeNoise(cat);
makeNoise(duck);
makeNoise(chicken);

The only reason I can think of is if you stored your object in a base class container:

std::vector<Animal*>  barnYard;
barnYard.push_back(&dog);
barnYard.push_back(&cat);
barnYard.push_back(&duck);
barnYard.push_back(&chicken);

Dog*  dog = dynamic_cast<Dog*>(barnYard[1]); // Note: NULL as this was the cat.

But if you need to cast particular objects back to Dogs then there is a fundamental problem in your design. You should be accessing properties via the virtual methods.

barnYard[1]->DoNoiseMake();

Angularjs action on click of button

The calculation occurs immediately since the calculation call is bound in the template, which displays its result when quantity changes.

Instead you could try the following approach. Change your markup to the following:

<div ng-controller="myAppController" style="text-align:center">
  <p style="font-size:28px;">Enter Quantity:
      <input type="text" ng-model="quantity"/>
  </p>
  <button ng-click="calculateQuantity()">Calculate</button>
  <h2>Total Cost: Rs.{{quantityResult}}</h2>
</div>

Next, update your controller:

myAppModule.controller('myAppController', function($scope,calculateService) {
  $scope.quantity=1;
  $scope.quantityResult = 0;

  $scope.calculateQuantity = function() {
    $scope.quantityResult = calculateService.calculate($scope.quantity, 10);
  };
});

Here's a JSBin example that demonstrates the above approach.

The problem with this approach is the calculated result remains visible with the old value till the button is clicked. To address this, you could hide the result whenever the quantity changes.

This would involve updating the template to add an ng-change on the input, and an ng-if on the result:

<input type="text" ng-change="hideQuantityResult()" ng-model="quantity"/>

and

<h2 ng-if="showQuantityResult">Total Cost: Rs.{{quantityResult}}</h2>

In the controller add:

$scope.showQuantityResult = false;

$scope.calculateQuantity = function() {
  $scope.quantityResult = calculateService.calculate($scope.quantity, 10);
  $scope.showQuantityResult = true;
};

$scope.hideQuantityResult = function() {
  $scope.showQuantityResult = false;
}; 

These updates can be seen in this JSBin demo.

calling a java servlet from javascript

   function callServlet()


{
 document.getElementById("adminForm").action="./Administrator";
 document.getElementById("adminForm").method = "GET";
 document.getElementById("adminForm").submit();

}

<button type="submit"  onclick="callServlet()" align="center"> Register</button>

Delete specified file from document directory

In Swift both 3&4

 func removeImageLocalPath(localPathName:String) {
            let filemanager = FileManager.default
            let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory,.userDomainMask,true)[0] as NSString
            let destinationPath = documentsPath.appendingPathComponent(localPathName)
 do {
        try filemanager.removeItem(atPath: destinationPath)
        print("Local path removed successfully")
    } catch let error as NSError {
        print("------Error",error.debugDescription)
    }
    }

or This method can delete all local file

func deletingLocalCacheAttachments(){
        let fileManager = FileManager.default
        let documentsURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0]
        do {
            let fileURLs = try fileManager.contentsOfDirectory(at: documentsURL, includingPropertiesForKeys: nil)
            if fileURLs.count > 0{
                for fileURL in fileURLs {
                    try fileManager.removeItem(at: fileURL)
                }
            }
        } catch {
            print("Error while enumerating files \(documentsURL.path): \(error.localizedDescription)")
        }
    }

How to unzip files programmatically in Android?

I'm working with zip files which Java's ZipFile class isn't able to handle. Java 8 apparently can't handle compression method 12 (bzip2 I believe). After trying a number of methods including zip4j (which also fails with these particular files due to another issue), I had success with Apache's commons-compress which supports additional compression methods as mentioned here.

Note that the ZipFile class below is not the one from java.util.zip.

It's actually org.apache.commons.compress.archivers.zip.ZipFile so be careful with the imports.

try (ZipFile zipFile = new ZipFile(archiveFile)) {
    Enumeration<ZipArchiveEntry> entries = zipFile.getEntries();
    while (entries.hasMoreElements()) {
        ZipArchiveEntry entry = entries.nextElement();
        File entryDestination = new File(destination, entry.getName());
        if (entry.isDirectory()) {
            entryDestination.mkdirs();
        } else {
            entryDestination.getParentFile().mkdirs();
            try (InputStream in = zipFile.getInputStream(entry); OutputStream out = new FileOutputStream(entryDestination)) {
                IOUtils.copy(in, out);
            }
        }
    }
} catch (IOException ex) {
    log.debug("Error unzipping archive file: " + archiveFile, ex);
}

For Gradle:

compile 'org.apache.commons:commons-compress:1.18'

How to declare an array of strings in C++?

Problems - no way to get the number of strings automatically (that i know of).

There is a bog-standard way of doing this, which lots of people (including MS) define macros like arraysize for:

#define arraysize(ar)  (sizeof(ar) / sizeof(ar[0]))

When do I need to use AtomicBoolean in Java?

Excerpt from the package description

Package java.util.concurrent.atomic description: A small toolkit of classes that support lock-free thread-safe programming on single variables.[...]

The specifications of these methods enable implementations to employ efficient machine-level atomic instructions that are available on contemporary processors.[...]

Instances of classes AtomicBoolean, AtomicInteger, AtomicLong, and AtomicReference each provide access and updates to a single variable of the corresponding type.[...]

The memory effects for accesses and updates of atomics generally follow the rules for volatiles:

  • get has the memory effects of reading a volatile variable.
  • set has the memory effects of writing (assigning) a volatile variable.
  • weakCompareAndSet atomically reads and conditionally writes a variable, is ordered with respect to other memory operations on that variable, but otherwise acts as an ordinary non-volatile memory operation.
  • compareAndSet and all other read-and-update operations such as getAndIncrement have the memory effects of both reading and writing volatile variables.

Is there any way to call a function periodically in JavaScript?

You will want to have a look at setInterval() and setTimeout().

Here is a decent tutorial article.

Using a PagedList with a ViewModel ASP.Net MVC

I modified the code as follow:

ViewModel

using System.Collections.Generic;
using ContosoUniversity.Models;

namespace ContosoUniversity.ViewModels
{
    public class InstructorIndexData
    {
     public PagedList.IPagedList<Instructor> Instructors { get; set; }
     public PagedList.IPagedList<Course> Courses { get; set; }
     public PagedList.IPagedList<Enrollment> Enrollments { get; set; }
    }
}

Controller

public ActionResult Index(int? id, int? courseID,int? InstructorPage,int? CoursePage,int? EnrollmentPage)
{
 int instructPageNumber = (InstructorPage?? 1);
 int CoursePageNumber = (CoursePage?? 1);
 int EnrollmentPageNumber = (EnrollmentPage?? 1);
 var viewModel = new InstructorIndexData();
 viewModel.Instructors = db.Instructors
    .Include(i => i.OfficeAssignment)
    .Include(i => i.Courses.Select(c => c.Department))
    .OrderBy(i => i.LastName).ToPagedList(instructPageNumber,5);

 if (id != null)
 {
    ViewBag.InstructorID = id.Value;
    viewModel.Courses = viewModel.Instructors.Where(
        i => i.ID == id.Value).Single().Courses.ToPagedList(CoursePageNumber,5);
 }

 if (courseID != null)
 {
    ViewBag.CourseID = courseID.Value;
    viewModel.Enrollments = viewModel.Courses.Where(
        x => x.CourseID == courseID).Single().Enrollments.ToPagedList(EnrollmentPageNumber,5);
 }

 return View(viewModel);
}

View

<div>
   Page @(Model.Instructors.PageCount < Model.Instructors.PageNumber ? 0 : Model.Instructors.PageNumber) of @Model.Instructors.PageCount

   @Html.PagedListPager(Model.Instructors, page => Url.Action("Index", new {InstructorPage=page}))

</div>

I hope this would help you!!

Change User Agent in UIWebView

Taking everything this is how it was solved for me:

- (void)viewDidLoad {
    NSURL *url = [NSURL URLWithString: @"http://www.amazon.com"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setValue:@"Foobar/1.0" forHTTPHeaderField:@"User-Agent"];
    [webView loadRequest:request];
}

Thanks Everyone.

Angular2: How to load data before rendering the component?

update

original

When console.log(this.ev) is executed after this.fetchEvent();, this doesn't mean the fetchEvent() call is done, this only means that it is scheduled. When console.log(this.ev) is executed, the call to the server is not even made and of course has not yet returned a value.

Change fetchEvent() to return a Promise

     fetchEvent(){
        return  this._apiService.get.event(this.eventId).then(event => {
            this.ev = event;
            console.log(event); // Has a value
            console.log(this.ev); // Has a value
        });
     }

change ngOnInit() to wait for the Promise to complete

    ngOnInit() {
        this.fetchEvent().then(() =>
        console.log(this.ev)); // Now has value;
    }

This actually won't buy you much for your use case.

My suggestion: Wrap your entire template in an <div *ngIf="isDataAvailable"> (template content) </div>

and in ngOnInit()

    isDataAvailable:boolean = false;

    ngOnInit() {
        this.fetchEvent().then(() =>
        this.isDataAvailable = true); // Now has value;
    }

Execution failed for task 'app:mergeDebugResources' Crunching Cruncher....png failed

I had put my images into my drawable folder at the beginning of the project, and it would always give me this error and never build so I:

  1. Deleted everything from drawable
  2. Tried to run (which obviously caused another build error because it's missing a reference to files
  3. Re-added the images to the folder, re-built the project, ran it, and then it worked fine.

I have no idea why this worked for me, but it did. Good luck with this mess we call Android Studio.

Delete commits from a branch in Git

If you want to fix up your latest commit, you can undo the commit, and unstage the files in it, by doing:

git reset HEAD~1

This will return your repository to its state before the git add commands that staged the files. Your changes will be in your working directory. HEAD~1 refers to the commit below the current tip of the branch.

If you want to uncommit N commits, but keep the code changes in your working directory:

git reset HEAD~N

If you want to get rid of your latest commit, and do not want to keep the code changes, you can do a "hard" reset.

git reset --hard HEAD~1

Likewise, if you want to discard the last N commits, and do not want to keep the code changes:

git reset --hard HEAD~N

java.math.BigInteger cannot be cast to java.lang.Integer

The column in the database is probably a DECIMAL. You should process it as a BigInteger, not an Integer, otherwise you are losing digits. Or else change the column to int.

Best way to display data via JSON using jQuery

Perfect! Thank you Jay, below is my HTML:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Facebook like ajax post - jQuery - ryancoughlin.com</title>
<link rel="stylesheet" href="../css/screen.css" type="text/css" media="screen, projection" />
<link rel="stylesheet" href="../css/print.css" type="text/css" media="print" />
<!--[if IE]><link rel="stylesheet" href="../css/ie.css" type="text/css" media="screen, projection"><![endif]-->
<link href="../css/highlight.css" rel="stylesheet" type="text/css" media="screen" />
<script src="js/jquery.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
/* <![CDATA[ */
$(document).ready(function(){
    $.getJSON("readJSON.php",function(data){
        $.each(data.post, function(i,post){
            content += '<p>' + post.post_author + '</p>';
            content += '<p>' + post.post_content + '</p>';
            content += '<p' + post.date + '</p>';
            content += '<br/>';
            $(content).appendTo("#posts");
        });
    });   
});
/* ]]> */
</script>
</head>
<body>
        <div class="container">
                <div class="span-24">
                       <h2>Check out the following posts:</h2>
                        <div id="posts">
                        </di>
                </div>
        </div>
</body>
</html>

And my JSON outputs:

{ posts: [{"id":"1","date_added":"0001-02-22 00:00:00","post_content":"This is a post","author":"Ryan Coughlin"}]}

I get this error, when I run my code:

object is undefined
http://localhost:8888/rks/post/js/jquery.js
Line 19

Performing a query on a result from another query?

Note that your initial query is probably not returning what you want:

SELECT availables.bookdate AS Date, DATEDIFF(now(),availables.updated_at) as Age 
FROM availables INNER JOIN rooms ON availables.room_id=rooms.id 
WHERE availables.bookdate BETWEEN  '2009-06-25' AND date_add('2009-06-25', INTERVAL 4 DAY) AND rooms.hostel_id = 5094 GROUP BY availables.bookdate

You are grouping by book date, but you are not using any grouping function on the second column of your query.

The query you are probably looking for is:

SELECT availables.bookdate AS Date, count(*) as subtotal, sum(DATEDIFF(now(),availables.updated_at) as Age)
FROM availables INNER JOIN rooms ON availables.room_id=rooms.id
WHERE availables.bookdate BETWEEN '2009-06-25' AND date_add('2009-06-25', INTERVAL 4 DAY) AND rooms.hostel_id = 5094
GROUP BY availables.bookdate