Programs & Examples On #Mainclass

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

I had the same its because of version incompatibility check for version or remove version if using spring boot

Java 6 Unsupported major.minor version 51.0

The problem is because you haven't set JDK version properly.You should use jdk 7 for major number 51. Like this:

JAVA_HOME=/usr/java/jdk1.7.0_79

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

Place your springbootapplication class in root package for example if your service,controller is in springBoot.xyz package then your main class should be in springBoot package otherwise it will not scan below packages

Maven Error: Could not find or load main class

TLDR : check if packaging element inside the pom.xml file is set to jar.

Like this - <packaging>jar</packaging>. If it set to pom your target folder will not be created even after you Clean and Build your project and Maven executable won't be able to find .class files (because they don't exist), after which you get Error: Could not find or load main class your.package.name.MainClass


After creating a Maven POM project in Netbeans 8.2, the content of the default pom.xml file are as follows -

<?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.mycompany</groupId>
   <artifactId>myproject</artifactId>
   <version>1.0-SNAPSHOT</version>
   <packaging>pom</packaging>
   <properties>
       <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
   </properties>
</project>

Here packaging element is set to pom. Hence the target directory is not created as we are not enabling maven to package our application as a jar file. Change it to jar then Clean and Build your project, you should see target directory created at root location. Now you should be able to run that java file with main method.

When no packaging is declared, Maven assumes the packaging as jar. Other core packaging values are pom, war, maven-plugin, ejb, ear, rar. These define the goals that execute on each corresponsding build life-cycle phase of that package. See more here

Maven Installation OSX Error Unsupported major.minor version 51.0

Please rather try:

$JAVA_HOME/bin/java -version

Maven uses $JAVA_HOME for classpath resolution of JRE libs. To be sure to use a certain JDK, set it explicitly before compiling, for example:

export JAVA_HOME=/usr/java/jdk1.7.0_51

Isn't there a version < 1.7 and you're using Maven 3.3.1? In this case the reason is a new prerequisite: https://issues.apache.org/jira/browse/MNG-5780

Can't Autowire @Repository annotated interface in Spring Boot

I had a similar problem but with a different cause:

In my case the problem was that in the interface defining the repository

public interface ItemRepository extends Repository {..}

I was omitting the types of the template. Setting them right:

public interface ItemRepository extends Repository<Item,Long> {..}

did the trick.

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>

The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Path

Adding the Tomcat server in the server runtime will do the job:

Project properties ? Java Build Path ? Add Library ? Select "Server Runtime" from the list ? Next ? Select "Apache Tomcat" ? Finish.

Gradle - Could not find or load main class

Struggled with the same problem for some time. But after creating the directory structure src/main/java and putting the source(from the top of the package), it worked as expected.

The tutorial I tried with. After you execute gradle build, you will have to be able to find classes under build directory.

Disable Logback in SpringBoot

Add this in your build.gradle

configurations.all {
    exclude group: 'org.springframework.boot', module: 'spring-boot-starter-tomcat'
    exclude group: 'org.springframework.boot', module: 'spring-boot-starter-logging'
    exclude group: 'org.springframework.boot', module: 'logback-classic'
}

Gradle to execute Java class (without modifying build.gradle)

You can parameterise it and pass gradle clean build -Pprokey=goodbye

task choiceMyMainClass(type: JavaExec) {
     group = "Execution"
    description = "Run Option main class with JavaExecTask"
    classpath = sourceSets.main.runtimeClasspath

    if (project.hasProperty('prokey')){
        if (prokey == 'hello'){
            main = 'com.sam.home.HelloWorld'
        } 
        else if (prokey == 'goodbye'){
            main = 'com.sam.home.GoodBye'
        }
    } else {
            println 'Invalid value is enterrd';

       // println 'Invalid value is enterrd'+ project.prokey;
    }

Error creating bean with name 'entityManagerFactory

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

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

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

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

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

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

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

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

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


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

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

and replace it with

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

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

<scope>test</scope>

Unable to Build using MAVEN with ERROR - Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile

Your Maven is reading Java version as 1.6.0_65, Where as the pom.xml says the version is 1.7.

Try installing the required verison.

If already installed check your $JAVA_HOME environment variable, it should contain the path of Java JDK 7. If you dont find it, fix your environment variable.

also remove the lines

 <fork>true</fork>
     <executable>${JAVA_1_7_HOME}/bin/javac</executable>

from the pom.xml

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

Netbeans needs to be able to index the maven repository. Allow it to do that and try again. It was giving me the same error and after it indexed the repository it ran like a charm

CreateProcess error=2, The system cannot find the file specified

The dir you specified is a working directory of running process - it doesn't help to find executable. Use cmd /c winrar ... to run process looking for executable in PATH or try to use absolute path to winrar.

How to add an object to an ArrayList in Java

change Date to Object which is between parenthesis

Understanding Spring @Autowired usage

Nothing in the example says that the "classes implementing the same interface". MovieCatalog is a type and CustomerPreferenceDao is another type. Spring can easily tell them apart.

In Spring 2.x, wiring of beans mostly happened via bean IDs or names. This is still supported by Spring 3.x but often, you will have one instance of a bean with a certain type - most services are singletons. Creating names for those is tedious. So Spring started to support "autowire by type".

What the examples show is various ways that you can use to inject beans into fields, methods and constructors.

The XML already contains all the information that Spring needs since you have to specify the fully qualified class name in each bean. You need to be a bit careful with interfaces, though:

This autowiring will fail:

 @Autowired
 public void prepare( Interface1 bean1, Interface1 bean2 ) { ... }

Since Java doesn't keep the parameter names in the byte code, Spring can't distinguish between the two beans anymore. The fix is to use @Qualifier:

 @Autowired
 public void prepare( @Qualifier("bean1") Interface1 bean1,
     @Qualifier("bean2")  Interface1 bean2 ) { ... }

fix java.net.SocketTimeoutException: Read timed out

I don't think it's enough merely to get the response. I think you need to read it (get the entity and read it via EntityUtils.consume()).

e.g. (from the doc)

     System.out.println("<< Response: " + response.getStatusLine());
     System.out.println(EntityUtils.toString(response.getEntity()));

Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2:java (default-cli)

Your problem is that you have declare twice the exec-maven-plugin :

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>exec-maven-plugin</artifactId>
    <version>1.2.1</version>
    <executions>
        <execution>
            <goals>
                <goal>java</goal>
            </goals>
        </execution>
    </executions>
    <configuration>
        <mainClass>C:\apache-camel-2.11.0\examples\camel-example-smooks-  
      integration\src\main\java\example\Main< /mainClass>
    </configuration>
</plugin>

...

< plugin>
    < groupId>org.codehaus.mojo</groupId>
    < artifactId>exec-maven-plugin</artifactId>
    < version>1.2</version>
< /plugin>

Maven compile: package does not exist

You do not include a <scope> tag in your dependency. If you add it, your dependency becomes something like:

<dependency>
     <groupId>org.openrdf.sesame</groupId>
     <artifactId>sesame-runtime</artifactId>
     <version>2.7.2</version>
     <scope> ... </scope>
</dependency>

The "scope" tag tells maven at which stage of the build your dependency is needed. Examples for the values to put inside are "test", "provided" or "runtime" (omit the quotes in your pom). I do not know your dependency so I cannot tell you what value to choose. Please consult the Maven documentation and the documentation of your dependency.

C# importing class into another class doesn't work

MyClass is a class not a namespace. So this code is wrong:

using MyClass //THIS CODE IS NOT CORRECT

You should check the namespace of the MyClass (e.g: MyNamespace). Then call it in a proper way:

MyNamespace.MyClass myClass =new MyNamespace.MyClass();

Difference between Static methods and Instance methods

The static modifier when placed in front of a function implies that only one copy of that function exists. If the static modifier is not placed in front of the function then with every object or instance of that class a new copy of that function is made. :) Same is the case with variables.

How do I put all required JAR files in a library folder inside the final JAR file with Maven?

The executable packer maven plugin can be used for exactly that purpose: creating standalone java applications containing all dependencies as JAR files in a specific folder.

Just add the following to your pom.xml inside the <build><plugins> section (be sure to replace the value of mainClass accordingly):

<plugin>
    <groupId>de.ntcomputer</groupId>
    <artifactId>executable-packer-maven-plugin</artifactId>
    <version>1.0.1</version>
    <configuration>
        <mainClass>com.example.MyMainClass</mainClass>
    </configuration>
    <executions>
        <execution>
            <goals>
                <goal>pack-executable-jar</goal>
            </goals>
        </execution>
    </executions>
</plugin>

The built JAR file is located at target/<YourProjectAndVersion>-pkg.jar after you run mvn package. All of its compile-time and runtime dependencies will be included in the lib/ folder inside the JAR file.

Disclaimer: I am the author of the plugin.

Tomcat 7 "SEVERE: A child container failed during start"

Tomcat Server fails to start and throws the exception because, inside the section Deployment Descriptor:MyProyect / Servlet Mappings there are mappings that don´t exist. Delete or correct those elements; then starting the server works without problems.

Resource from src/main/resources not found after building with maven

I think assembly plugin puts the file on class path. The location will be different in in the JAR than you see on disk. Unpack the resulting JAR and look where the file is located there.

Maven: How to run a .java file from command line passing arguments

In addition to running it with mvn exec:java, you can also run it with mvn exec:exec

mvn exec:exec -Dexec.executable="java" -Dexec.args="-classpath %classpath your.package.MainClass"

run main class of Maven project

Although maven exec does the trick here, I found it pretty poor for a real test. While waiting for maven shell, and hoping this could help others, I finally came out to this repo mvnexec

Clone it, and symlink the script somewhere in your path. I use ~/bin/mvnexec, as I have ~/bin in my path. I think mvnexec is a good name for the script, but is up to you to change the symlink...

Launch it from the root of your project, where you can see src and target dirs.

The script search for classes with main method, offering a select to choose one (Example with mavenized JMeld project)

$ mvnexec 
 1) org.jmeld.ui.JMeldComponent
 2) org.jmeld.ui.text.FileDocument
 3) org.jmeld.JMeld
 4) org.jmeld.util.UIDefaultsPrint
 5) org.jmeld.util.PrintProperties
 6) org.jmeld.util.file.DirectoryDiff
 7) org.jmeld.util.file.VersionControlDiff
 8) org.jmeld.vc.svn.InfoCmd
 9) org.jmeld.vc.svn.DiffCmd
10) org.jmeld.vc.svn.BlameCmd
11) org.jmeld.vc.svn.LogCmd
12) org.jmeld.vc.svn.CatCmd
13) org.jmeld.vc.svn.StatusCmd
14) org.jmeld.vc.git.StatusCmd
15) org.jmeld.vc.hg.StatusCmd
16) org.jmeld.vc.bzr.StatusCmd
17) org.jmeld.Main
18) org.apache.commons.jrcs.tools.JDiff
#? 

If one is selected (typing number), you are prompt for arguments (you can avoid with mvnexec -P)

By default it compiles project every run. but you can avoid that using mvnexec -B

It allows to search only in test classes -M or --no-main, or only in main classes -T or --no-test. also has a filter by name option -f <whatever>

Hope this could save you some time, for me it does.

"Could not find the main class" error when running jar exported by Eclipse

Have you renamed your project/main class (e.g. through refactoring) ? If yes your Launch Configuration might be set up incorrectly (e.g. refering to the old main class or configuration). Even though the project name appears in the 'export runnable jar' dialog, a closer inspection might reveal an unmatched main class name.

Go to 'Properties->Run/Debug Settings' of your project and make sure your Launch Configuration (the same used to export runnable jar) is set to the right name of project AND your main class is set to name.space.of.your.project/YouMainClass.

What is the equivalent of Java's System.out.println() in Javascript?

I found a solution:

print("My message here");

LINQ orderby on date field in descending order

This statement will definitely help you:

env = env.OrderByDescending(c => c.ReportDate).ToList();

How to run a class from Jar which is not the Main-Class in its Manifest file

Another similar option that I think Nick briefly alluded to in the comments is to create multiple wrapper jars. I haven't tried it, but I think they could be completely empty other than the manifest file, which should specify the main class to load as well as the inclusion of the MyJar.jar to the classpath.

MyJar1.jar\META-INF\MANIFEST.MF

Manifest-Version: 1.0
Main-Class: com.mycomp.myproj.dir1.MainClass1
Class-Path: MyJar.jar

MyJar2.jar\META-INF\MANIFEST.MF

Manifest-Version: 1.0
Main-Class: com.mycomp.myproj.dir2.MainClass2
Class-Path: MyJar.jar

etc. Then just run it with java -jar MyJar2.jar

C# JSON Serialization of Dictionary into {key:value, ...} instead of {key:key, value:value, ...}

Json.NET does this...

Dictionary<string, string> values = new Dictionary<string, string>();
values.Add("key1", "value1");
values.Add("key2", "value2");

string json = JsonConvert.SerializeObject(values);
// {
//   "key1": "value1",
//   "key2": "value2"
// }

More examples: Serializing Collections with Json.NET

Debugging in Maven?

Just as Brian said, you can use remote debugging:

mvn exec:exec -Dexec.executable="java" -Dexec.args="-classpath %classpath -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=1044 com.mycompany.app.App"

Then in your eclipse, you can use remote debugging and attach the debugger to localhost:1044.

Why has it failed to load main-class manifest attribute from a JAR file?

I discovered that I was also having this error in NetBeans. I hope the following is helpful.

  1. Make sure that when you go to Project Configuration you set the main class you intend for running.
  2. Do a Build or Clean Build
  3. Place the jar file where you wish and try: java -jar "YourProject.jar" again at the command line.

This was the problem I was getting because I had other "test" programs I was using in NetBeans and I had to make sure the Main Class under the Run portion of the Project configuration was set correctly.

many blessings, John P

How do I execute a program using Maven?

In order to execute multiple programs, I also needed a profiles section:

<profiles>
  <profile>
    <id>traverse</id>
    <activation>
      <property>
        <name>traverse</name>
      </property>
    </activation>
    <build>
      <plugins>
        <plugin>
          <groupId>org.codehaus.mojo</groupId>
          <artifactId>exec-maven-plugin</artifactId>
          <configuration>
            <executable>java</executable>
            <arguments>
              <argument>-classpath</argument>
              <argument>org.dhappy.test.NeoTraverse</argument>
            </arguments>
          </configuration>
        </plugin>
      </plugins>
    </build>
  </profile>
</profiles>

This is then executable as:

mvn exec:exec -Ptraverse

Building executable jar with maven?

Right click the project and give maven build,maven clean,maven generate resource and maven install.The jar file will automatically generate.

Moment js get first and last day of current month

As simple we can use daysInMonth() and endOf()

const firstDay = moment('2016-09-15 00:00', 'YYYY-MM-DD h:m').startOf('month').format('D')
const lastDay = moment('2016-09-15 00:00', 'YYYY-MM-DD h:m').endOf('month').format('D')

How can I open a .tex file?

I don't know what the .tex extension on your file means. If we are saying that it is any file with any extension you have several methods of reading it.

I have to assume you are using windows because you have mentioned notepad++.

  1. Use notepad++. Right click on the file and choose "edit with notepad++"

  2. Use notepad Change the filename extension to .txt and double click the file.

  3. Use command prompt. Open the folder that your file is in. Hold down shift and right click. (not on the file, but in the folder that the file is in.) Choose "open command window here" from the command prompt type: "type filename.tex"

If these don't work, I would need more detail as to how they are not working. Errors that you may be getting or what you may expect to be in the file might help.

Why can't I declare static methods in an interface?

Since static methods can not be inherited . So no use placing it in the interface. Interface is basically a contract which all its subscribers have to follow . Placing a static method in interface will force the subscribers to implement it . which now becomes contradictory to the fact that static methods can not be inherited .

Could not get constructor for org.hibernate.persister.entity.SingleTableEntityPersister

in my case, the problem got solved only by implementing serializable as below:

@Entity @Table(name = "User" , uniqueConstraints = { @UniqueConstraint(columnNames = {"nam"}) }) public class User extends GenericT implements Serializable

Setting Custom ActionBar Title from Fragment

Save ur Answer in String[] object and set it OnTabChange() in MainActivity as Belowwww

String[] object = {"Fragment1","Fragment2","Fragment3"};

public void OnTabChange(String tabId)
{
int pos =mTabHost.getCurrentTab();     //To get tab position
 actionbar.setTitle(object.get(pos));
}


//Setting in View Pager
public void onPageSelected(int arg0) {
    mTabHost.setCurrentTab(arg0);
actionbar.setTitle(object.get(pos));
}

What does "export" do in shell programming?

Exported variables such as $HOME and $PATH are available to (inherited by) other programs run by the shell that exports them (and the programs run by those other programs, and so on) as environment variables. Regular (non-exported) variables are not available to other programs.

$ env | grep '^variable='
$                                 # No environment variable called variable
$ variable=Hello                  # Create local (non-exported) variable with value
$ env | grep '^variable='
$                                 # Still no environment variable called variable
$ export variable                 # Mark variable for export to child processes
$ env | grep '^variable='
variable=Hello
$
$ export other_variable=Goodbye   # create and initialize exported variable
$ env | grep '^other_variable='
other_variable=Goodbye
$

For more information, see the entry for the export builtin in the GNU Bash manual, and also the sections on command execution environment and environment.

Note that non-exported variables will be available to subshells run via ( ... ) and similar notations because those subshells are direct clones of the main shell:

$ othervar=present
$ (echo $othervar; echo $variable; variable=elephant; echo $variable)
present
Hello
elephant
$ echo $variable
Hello
$

The subshell can change its own copy of any variable, exported or not, and may affect the values seen by the processes it runs, but the subshell's changes cannot affect the variable in the parent shell, of course.

Some information about subshells can be found under command grouping and command execution environment in the Bash manual.

How to join two sets in one line without using "|"

You can use union method for sets: set.union(other_set)

Note that it returns a new set i.e it doesn't modify itself.

Regular expression to validate US phone numbers?

The easiest way to match both

^\([0-9]{3}\)[0-9]{3}-[0-9]{4}$

and

^[0-9]{3}-[0-9]{3}-[0-9]{4}$

is to use alternation ((...|...)): specify them as two mostly-separate options:

^(\([0-9]{3}\)|[0-9]{3}-)[0-9]{3}-[0-9]{4}$

By the way, when Americans put the area code in parentheses, we actually put a space after that; for example, I'd write (123) 123-1234, not (123)123-1234. So you might want to write:

^(\([0-9]{3}\) |[0-9]{3}-)[0-9]{3}-[0-9]{4}$

(Though it's probably best to explicitly demonstrate the format that you expect phone numbers to be in.)

IOException: The process cannot access the file 'file path' because it is being used by another process

My below code solve this issue, but i suggest First of all you need to understand what causing this issue and try the solution which you can find by changing code

I can give another way to solve this issue but better solution is to check your coding structure and try to analyse what makes this happen,if you do not find any solution then you can go with this code below

try{
Start:
///Put your file access code here


}catch (Exception ex)
 {
//by anyway you need to handle this error with below code
   if (ex.Message.StartsWith("The process cannot access the file"))
    {
         //Wait for 5 seconds to free that file and then start execution again
         Thread.Sleep(5000);
         goto Start;
    }
 }

How to round a number to n decimal places in Java

  1. In order to have trailing 0s up to 5th position
DecimalFormat decimalFormatter = new DecimalFormat("#.00000");
decimalFormatter.format(0.350500); // result 0.350500
  1. In order to avoid trailing 0s up to 5th position
DecimalFormat decimalFormatter= new DecimalFormat("#.#####");
decimalFormatter.format(0.350500); // result o.3505

How to concatenate properties from multiple JavaScript objects

function Collect(a, b, c) {
    for (property in b)
        a[property] = b[property];

    for (property in c)
        a[property] = c[property];

    return a;
}

Notice: Existing properties in previous objects will be overwritten.

Excel: VLOOKUP that returns true or false?

We've always used an

if(iserror(vlookup,"n/a",vlookup))

Excel 2007 introduced IfError which allows you to do the vlookup and add output in case of error, but that doesn't help you with 2003...

How to reference image resources in XAML?

If the image is in your resources folder and its build action is set to Resource. You can reference the image in XAML as follows:

"pack://application:,,,/Resources/Search.png"

Assuming you do not have any folder structure under the Resources folder and it is an application. For example I use:

ImageSource="pack://application:,,,/Resources/RibbonImages/CloseButton.png"

when I have a folder named RibbonImages under Resources folder.

Import multiple csv files into pandas and concatenate into one DataFrame

import pandas as pd
import glob

path = r'C:\DRO\DCL_rawdata_files' # use your path
file_path_list = glob.glob(path + "/*.csv")

file_iter = iter(file_path_list)

list_df_csv = []
list_df_csv.append(pd.read_csv(next(file_iter)))

for file in file_iter:
    lsit_df_csv.append(pd.read_csv(file, header=0))
df = pd.concat(lsit_df_csv, ignore_index=True)

how to use Blob datatype in Postgres

I think this is the most comprehensive answer on the PostgreSQL wiki itself: https://wiki.postgresql.org/wiki/BinaryFilesInDB

Read the part with the title 'What is the best way to store the files in the Database?'

Python requests - print entire http request (raw)?

requests supports so called event hooks (as of 2.23 there's actually only response hook). The hook can be used on a request to print full request-response pair's data, including effective URL, headers and bodies, like:

import textwrap
import requests

def print_roundtrip(response, *args, **kwargs):
    format_headers = lambda d: '\n'.join(f'{k}: {v}' for k, v in d.items())
    print(textwrap.dedent('''
        ---------------- request ----------------
        {req.method} {req.url}
        {reqhdrs}

        {req.body}
        ---------------- response ----------------
        {res.status_code} {res.reason} {res.url}
        {reshdrs}

        {res.text}
    ''').format(
        req=response.request, 
        res=response, 
        reqhdrs=format_headers(response.request.headers), 
        reshdrs=format_headers(response.headers), 
    ))

requests.get('https://httpbin.org/', hooks={'response': print_roundtrip})

Running it prints:

---------------- request ----------------
GET https://httpbin.org/
User-Agent: python-requests/2.23.0
Accept-Encoding: gzip, deflate
Accept: */*
Connection: keep-alive

None
---------------- response ----------------
200 OK https://httpbin.org/
Date: Thu, 14 May 2020 17:16:13 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 9593
Connection: keep-alive
Server: gunicorn/19.9.0
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true

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

You may want to change res.text to res.content if the response is binary.

How can I check if a file exists in Perl?

You can use: if(-e $base_path)

Local package.json exists, but node_modules missing

npm start runs a script that the app maker built for easy starting of the app npm install installs all the packages in package.json

run npm install first

then run npm start

How to handle the `onKeyPress` event in ReactJS?

React is not passing you the kind of events you might think. Rather, it is passing synthetic events.

In a brief test, event.keyCode == 0 is always true. What you want is event.charCode

PHP move_uploaded_file() error?

Check that the web server has permissions to write to the "images/" directory

How to subtract X day from a Date object in Java?

I have created a function to make the task easier.

  • For 7 days after dateString: dateCalculate(dateString,"yyyy-MM-dd",7);

  • To get 7 days upto dateString: dateCalculate(dateString,"yyyy-MM-dd",-7);


public static String dateCalculate(String dateString, String dateFormat, int days) {
    Calendar cal = Calendar.getInstance();
    SimpleDateFormat s = new SimpleDateFormat(dateFormat);
    try {
        cal.setTime(s.parse(dateString));
    } catch (ParseException e) {
        e.printStackTrace();
    }
    cal.add(Calendar.DATE, days);
    return s.format(cal.getTime());
}

'const string' vs. 'static readonly string' in C#

OQ asked about static string vs const. Both have different use cases (although both are treated as static).

Use const only for truly constant values (e.g. speed of light - but even this varies depending on medium). The reason for this strict guideline is that the const value is substituted into the uses of the const in assemblies that reference it, meaning you can have versioning issues should the const change in its place of definition (i.e. it shouldn't have been a constant after all). Note this even affects private const fields because you might have base and subclass in different assemblies and private fields are inherited.

Static fields are tied to the type they are declared within. They are used for representing values that need to be the same for all instances of a given type. These fields can be written to as many times as you like (unless specified readonly).

If you meant static readonly vs const, then I'd recommend static readonly for almost all cases because it is more future proof.

Google OAuth 2 authorization - Error: redirect_uri_mismatch

Make sure to check the protocol "http://" or "https://" as google checks protocol as well. Better to add both URL in the list.

Oracle: how to set user password unexpire?

While applying the new profile to the user,you should also check for resource limits are "turned on" for the database as a whole i.e.RESOURCE_LIMIT = TRUE

Let check the parameter value.
If in Case it is :

SQL> show parameter resource_limit
NAME                                 TYPE        VALUE
------------------------------------ ----------- ---------
resource_limit                       boolean     FALSE
Its mean resource limit is off,we ist have to enable it. 

Use the ALTER SYSTEM statement to turn on resource limits. 

SQL> ALTER SYSTEM SET RESOURCE_LIMIT = TRUE;
System altered.

How can I stop .gitignore from appearing in the list of untracked files?

Watch out for the following "problem" Sometimes you want to add directories but no files within those directories. The simple solution is to create a .gitignore with the following content:

*

This seams to work fine until you realize that the directory was not added (as expected to your repository. The reason for that is that the .gitignore will also be ignored, and thereby the directory is empty. Thus, you should do something like this:

*
!.gitignore

java.util.zip.ZipException: error in opening zip file

In my case , my -Dloader.path="lib" contains other jars that doesn't need. for example,mvn dependency:copy-dependencies lists 100 jar files.but my lib directory contains 101 jar files.

Cell spacing in UICollectionView

Define UICollectionViewDelegateFlowLayout protocol in your header file.

Implement following method of UICollectionViewDelegateFlowLayout protocol like this:

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(5, 5, 5, 5);
}

Click Here to see Apple Documentation of UIEdgeInsetMake method.

How to add users to Docker container?

Adding user in docker and running your app under that user is very good practice for security point of view. To do that I would recommend below steps:

FROM node:10-alpine

# Copy source to container
RUN mkdir -p /usr/app/src

# Copy source code
COPY src /usr/app/src
COPY package.json /usr/app
COPY package-lock.json /usr/app

WORKDIR /usr/app

# Running npm install for production purpose will not run dev dependencies.
RUN npm install -only=production    

# Create a user group 'xyzgroup'
RUN addgroup -S xyzgroup

# Create a user 'appuser' under 'xyzgroup'
RUN adduser -S -D -h /usr/app/src appuser xyzgroup

# Chown all the files to the app user.
RUN chown -R appuser:xyzgroup /usr/app

# Switch to 'appuser'
USER appuser

# Open the mapped port
EXPOSE 3000

# Start the process
CMD ["npm", "start"]

Above steps is a full example of the copying NodeJS project files, creating a user group and user, assigning permissions to the user for the project folder, switching to the newly created user and running the app under that user.

How would I extract a single file (or changes to a file) from a git stash?

On the git stash manpage you can read (in the "Discussion" section, just after "Options" description) that:

A stash is represented as a commit whose tree records the state of the working directory, and its first parent is the commit at HEAD when the stash was created.

So you can treat stash (e.g. stash@{0} is first / topmost stash) as a merge commit, and use:

$ git diff stash@{0}^1 stash@{0} -- <filename>

Explanation: stash@{0}^1 means the first parent of the given stash, which as stated in the explanation above is the commit at which changes were stashed away. We use this form of "git diff" (with two commits) because stash@{0} / refs/stash is a merge commit, and we have to tell git which parent we want to diff against. More cryptic:

$ git diff stash@{0}^! -- <filename>

should also work (see git rev-parse manpage for explanation of rev^! syntax, in "Specifying ranges" section).

Likewise, you can use git checkout to check a single file out of the stash:

$ git checkout stash@{0} -- <filename>

or to save it under another filename:

$ git show stash@{0}:<full filename>  >  <newfile>

or

$ git show stash@{0}:./<relative filename> > <newfile>

(note that here <full filename> is full pathname of a file relative to top directory of a project (think: relative to stash@{0})).


You might need to protect stash@{0} from shell expansion, i.e. use "stash@{0}" or 'stash@{0}'.

How to open google chrome from terminal?

In Terminal, type open -a Google\ Chrome

This will open Google Chrome application without any need to manipulate directories!

onclick="javascript:history.go(-1)" not working in Chrome

Try this dude,

<button onclick="goBack()">Go Back 2 Pages</button>
<script>
  function goBack() {
    window.history.go(-2);
  }
</script>

How to sort by column in descending order in Spark SQL?

In the case of Java:

If we use DataFrames, while applying joins (here Inner join), we can sort (in ASC) after selecting distinct elements in each DF as:

Dataset<Row> d1 = e_data.distinct().join(s_data.distinct(), "e_id").orderBy("salary");

where e_id is the column on which join is applied while sorted by salary in ASC.

Also, we can use Spark SQL as:

SQLContext sqlCtx = spark.sqlContext();
sqlCtx.sql("select * from global_temp.salary order by salary desc").show();

where

  • spark  -> SparkSession
  • salary -> GlobalTemp View.

Adding an onclick event to a div element

maybe your script tab has some problem.

if you set type, must type="application/javascript".

<!DOCTYPE html>
<html>
    <head>
        <title>
            Hello
        </title>
    </head>
    <body>
        <div onclick="showMsg('Hello')">
            Click me show message
        </div>
        <script type="application/javascript">
            function showMsg(item) {
            alert(item);
        }
        </script>
    </body>
</html>

How to plot a very simple bar chart (Python, Matplotlib) using input *.txt file?

First, what you are looking for is a column or bar diagram, not really a histogram. A histogram is made from a frequency distribution of a continuous variable that is separated into bins. Here you have a column against separate labels.

To make a bar diagram with matplotlib, use the matplotlib.pyplot.bar() method. Have a look at this page of the matplotlib documentation that explains very well with examples and source code how to do it.

If it is possible though, I would just suggest that for a simple task like this if you could avoid writing code that would be better. If you have any spreadsheet program this should be a piece of cake because that's exactly what they are for, and you won't have to 'reinvent the wheel'. The following is the plot of your data in Excel:

Bar diagram plot in Excel

I just copied your data from the question, used the text import wizard to put it in two columns, then I inserted a column diagram.

rand() returns the same number each time the program is run

srand() seeds the random number generator. Without a seed, the generator is unable to generate the numbers you are looking for. As long as one's need for random numbers is not security-critical (e.g. any sort of cryptography), common practice is to use the system time as a seed by using the time() function from the <ctime> library as such: srand(time(0)). This will seed the random number generator with the system time expressed as a Unix timestamp (i.e. the number of seconds since the date 1/1/1970). You can then use rand() to generate a pseudo-random number.

Here is a quote from a duplicate question:

The reason is that a random number generated from the rand() function isn't actually random. It simply is a transformation. Wikipedia gives a better explanation of the meaning of pseudorandom number generator: deterministic random bit generator. Every time you call rand() it takes the seed and/or the last random number(s) generated (the C standard doesn't specify the algorithm used, though C++11 has facilities for specifying some popular algorithms), runs a mathematical operation on those numbers, and returns the result. So if the seed state is the same each time (as it is if you don't call srand with a truly random number), then you will always get the same 'random' numbers out.

If you want to know more, you can read the following:

http://www.dreamincode.net/forums/topic/24225-random-number-generation-102/

http://www.dreamincode.net/forums/topic/29294-making-pseudo-random-number-generators-more-random/

How to center a table of the screen (vertically and horizontally)

I think this should do the trick:

<table border="1px" align="center">

According to http://w3schools.com/tags/tag_table.asp this is deprecated, but try it. If it does not work, go for styles, as mentioned on the site.

How do you convert a jQuery object into a string?

I assume you're asking for the full HTML string. If that's the case, something like this will do the trick:

$('<div>').append($('#item-of-interest').clone()).html(); 

This is explained in more depth here, but essentially you make a new node to wrap the item of interest, do the manipulations, remove it, and grab the HTML.

If you're just after a string representation, then go with new String(obj).

Update

I wrote the original answer in 2009. As of 2014, most major browsers now support outerHTML as a native property (see, for example, Firefox and Internet Explorer), so you can do:

$('#item-of-interest').prop('outerHTML');

What is the dual table in Oracle?

It is a dummy table with one element in it. It is useful because Oracle doesn't allow statements like

 SELECT 3+4

You can work around this restriction by writing

 SELECT 3+4 FROM DUAL

instead.

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

The optimizer should eliminate most of the local variables. The tmp pointer is there to make sure strcpy doesn't have to walk the string to find the null. tmp points to the end of result after each call. (See Shlemiel the painter's algorithm for why strcpy can be annoying.)

// You must free the result if result is non-NULL.
char *str_replace(char *orig, char *rep, char *with) {
    char *result; // the return string
    char *ins;    // the next insert point
    char *tmp;    // varies
    int len_rep;  // length of rep (the string to remove)
    int len_with; // length of with (the string to replace rep with)
    int len_front; // distance between rep and end of last rep
    int count;    // number of replacements

    // sanity checks and initialization
    if (!orig || !rep)
        return NULL;
    len_rep = strlen(rep);
    if (len_rep == 0)
        return NULL; // empty rep causes infinite loop during count
    if (!with)
        with = "";
    len_with = strlen(with);

    // count the number of replacements needed
    ins = orig;
    for (count = 0; tmp = strstr(ins, rep); ++count) {
        ins = tmp + len_rep;
    }

    tmp = result = malloc(strlen(orig) + (len_with - len_rep) * count + 1);

    if (!result)
        return NULL;

    // first time through the loop, all the variable are set correctly
    // from here on,
    //    tmp points to the end of the result string
    //    ins points to the next occurrence of rep in orig
    //    orig points to the remainder of orig after "end of rep"
    while (count--) {
        ins = strstr(orig, rep);
        len_front = ins - orig;
        tmp = strncpy(tmp, orig, len_front) + len_front;
        tmp = strcpy(tmp, with) + len_with;
        orig += len_front + len_rep; // move to next "end of rep"
    }
    strcpy(tmp, orig);
    return result;
}

How do I get a value of a <span> using jQuery?

Assuming you intended it to read id="item1", you need

$('#item1 span').text()

Two values from one input in python?

if we want to two inputs in a single line so, the code is are as follows enter code here

x,y=input().split(" ")

print(x,y)

after giving value as input we have to give spaces between them because of split(" ") function or method.

but these values are of string type if to perform some arithmetic operations we have to convert the type of x,y are as follows int(x),int(y)

we can do this also with the help of list in python.enter code here

list1=list(map(int,input().split()))
print(list1)

this list gives the elements in int type

How to enable Logger.debug() in Log4j

If you are coming here because you are using Apache commons logging with log4j and log4j isn't working as you expect then check that you actually have a log4j.jar in your run-time classpath. That one had me puzzled for a little while. I have now configured the runner in my dev environment to include -Dlog4j.debug in the Java command line so I can always see that Log4j is being initialized correctly

How can I list the contents of a directory in Python?

One way:

import os
os.listdir("/home/username/www/")

Another way:

glob.glob("/home/username/www/*")

Examples found here.

The glob.glob method above will not list hidden files.

Since I originally answered this question years ago, pathlib has been added to Python. My preferred way to list a directory now usually involves the iterdir method on Path objects:

from pathlib import Path
print(*Path("/home/username/www/").iterdir(), sep="\n")

Self-references in object literals / initializers

Creating new function on your object literal and invoking a constructor seems a radical departure from the original problem, and it's unnecessary.

You cannot reference a sibling property during object literal initialization.

var x = { a: 1, b: 2, c: a + b } // not defined 
var y = { a: 1, b: 2, c: y.a + y.b } // not defined 

The simplest solution for computed properties follows (no heap, no functions, no constructor):

var x = { a: 1, b: 2 };

x.c = x.a + x.b; // apply computed property

How to PUT a json object with an array using curl

Try using a single quote instead of double quotes along with -g

Following scenario worked for me

curl -g -d '{"collection":[{"NumberOfParcels":1,"Weight":1,"Length":1,"Width":1,"Height":1}]}" -H "Accept: application/json" -H "Content-Type: application/json" --user [email protected]:123456 -X POST  https://yoururl.com

WITH

curl -g -d "{'collection':[{'NumberOfParcels':1,'Weight':1,'Length':1,'Width':1,'Height':1}]}" -H "Accept: application/json" -H "Content-Type: application/json" --user [email protected]:123456 -X POST  https://yoururl.com

This especially resolved my error curl command error : bad url colon is first character

laravel 5.4 upload image

A good logic for your application could be something like:

 public function uploadGalery(Request $request){
      $this->validate($request, [
        'file' => 'required|image|mimes:jpeg,png,jpg,bmp,gif,svg|max:2048',
      ]);
      if ($request->hasFile('file')) {
        $image = $request->file('file');
        $name = time().'.'.$image->getClientOriginalExtension();
        $destinationPath = public_path('/storage/galeryImages/');
        $image->move($destinationPath, $name);
        $this->save();
        return back()->with('success','Image Upload successfully');
      }

    }

How to use filesaver.js

Here is a guide to JSZIP to create ZIP files by JavaScript. To download files you need to have filesaver.js, You can include those libraries by:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.4/jszip.min.js"  type="text/javascript"></script>
<script type="text/javascript" src="https://fastcdn.org/FileSaver.js/1.1.20151003/FileSaver.js" ></script>

Now copy this code and this code will download a zip file with a file hello.txt having content Hello World. If everything thing works fine, this will download a file.

<script type="text/javascript">
    var zip = new JSZip();
    zip.file("Hello.txt", "Hello World\n");
    zip.generateAsync({type:"blob"})
    .then(function(content) {
        // see FileSaver.js
        saveAs(content, "file.zip");
    });
</script>

Now let's get in to deeper. Create an instance of JSZip.

var zip = new JSZip();

Add a file with a Hello World text:

zip.file("hello.txt", "Hello World\n");

Download the filie with name archive.zip

zip.generateAsync({type:"blob"}).then(function(zip) {
    saveAs(zip, "archive.zip");
});

Read More from here: http://www.wapgee.com/story/248/guide-to-create-zip-files-using-javascript-by-using-jszip-library

How to monitor the memory usage of Node.js?

The original memwatch is essentially dead. Try memwatch-next instead, which seems to be working well on modern versions of Node.

Can't specify the 'async' modifier on the 'Main' method of a console app

In my case I had a list of jobs that I wanted to run in async from my main method, have been using this in production for quite sometime and works fine.

static void Main(string[] args)
{
    Task.Run(async () => { await Task.WhenAll(jobslist.Select(nl => RunMulti(nl))); }).GetAwaiter().GetResult();
}
private static async Task RunMulti(List<string> joblist)
{
    await ...
}

Select a Column in SQL not in Group By

The direct answer is that you can't. You must select either an aggregate or something that you are grouping by.

So, you need an alternative approach.

1). Take you current query and join the base data back on it

SELECT
  cpe.*
FROM
  Filteredfmgcms_claimpaymentestimate cpe
INNER JOIN
  (yourQuery) AS lookup
    ON  lookup.MaxData           = cpe.createdOn
    AND lookup.fmgcms_cpeclaimid = cpe.fmgcms_cpeclaimid

2). Use a CTE to do it all in one go...

WITH
  sequenced_data AS
(
  SELECT
    *,
    ROW_NUMBER() OVER (PARITION BY fmgcms_cpeclaimid ORDER BY CreatedOn DESC) AS sequence_id
  FROM
    Filteredfmgcms_claimpaymentestimate
  WHERE
    createdon < 'reportstartdate'
)
SELECT
  *
FROM
  sequenced_data
WHERE
  sequence_id = 1

NOTE: Using ROW_NUMBER() will ensure just one record per fmgcms_cpeclaimid. Even if multiple records are tied with the exact same createdon value. If you can have ties, and want all records with the same createdon value, use RANK() instead.

Bootstrap number validation

you can use PATTERN:

<input class="form-control" minlength="1" pattern="[0-9]*" [(ngModel)]="value" #name="ngModel">

<div *ngIf="name.invalid && (name.dirty || name.touched)" class="text-danger">
  <div *ngIf="name.errors?.pattern">Is not a number</div>
</div>

How to enumerate a range of numbers starting at 1

enumerate is trivial, and so is re-implementing it to accept a start:

def enumerate(iterable, start = 0):
    n = start
    for i in iterable:
        yield n, i
        n += 1

Note that this doesn't break code using enumerate without start argument. Alternatively, this oneliner may be more elegant and possibly faster, but breaks other uses of enumerate:

enumerate = ((index+1, item) for index, item)

The latter was pure nonsense. @Duncan got the wrapper right.

PHP Checking if the current date is before or after a set date

I wanted to set a specific date so have used this to do stuff before 2nd December 2013

if(mktime(0,0,0,12,2,2013) > strtotime('now')) {
    // do stuff
}

The 0,0,0 is midnight, the 12 is the month, the 2 is the day and the 2013 is the year.

cannot call member function without object

If you want to call them like that, you should declare them static.

android - listview get item view by position

workignHoursListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent,View view, int position, long id) {
        viewtype yourview=yourListViewId.getChildAt(position).findViewById(R.id.viewid);
    }
});

COUNT / GROUP BY with active record?

I believe you'll want something like this:

 $this->db->select('user_id, COUNT(user_id) as total');
 $this->db->group_by('user_id'); 
 $this->db->order_by('total', 'desc'); 
 $this->db->get('tablename', 10);

This will produce a result like

|  USER_ID |  TOTAL  |
|    12    |    3    |
|    15    |    2    |
|    18    |    1    |

UPDATE: As some pointed out in the comments the original query was summing the user_ids rather than counting them. I've updated the active record query to correct this.

How do you convert an entire directory with ffmpeg?

A one-line bash script would be easy to do - replace *.avi with your filetype:

for i in *.avi; do ffmpeg -i "$i" -qscale 0 "$(basename "$i" .avi)".mov  ; done

Difference between array_map, array_walk and array_filter

The other answers demonstrate the difference between array_walk (in-place modification) and array_map (return modified copy) quite well. However, they don't really mention array_reduce, which is an illuminating way to understand array_map and array_filter.

The array_reduce function takes an array, a two-argument function and an 'accumulator', like this:

array_reduce(array('a', 'b', 'c', 'd'),
             'my_function',
             $accumulator)

The array's elements are combined with the accumulator one at a time, using the given function. The result of the above call is the same as doing this:

my_function(
  my_function(
    my_function(
      my_function(
        $accumulator,
        'a'),
      'b'),
    'c'),
  'd')

If you prefer to think in terms of loops, it's like doing the following (I've actually used this as a fallback when array_reduce wasn't available):

function array_reduce($array, $function, $accumulator) {
  foreach ($array as $element) {
    $accumulator = $function($accumulator, $element);
  }
  return $accumulator;
}

This looping version makes it clear why I've called the third argument an 'accumulator': we can use it to accumulate results through each iteration.

So what does this have to do with array_map and array_filter? It turns out that they're both a particular kind of array_reduce. We can implement them like this:

array_map($function, $array)    === array_reduce($array, $MAP,    array())
array_filter($array, $function) === array_reduce($array, $FILTER, array())

Ignore the fact that array_map and array_filter take their arguments in a different order; that's just another quirk of PHP. The important point is that the right-hand-side is identical except for the functions I've called $MAP and $FILTER. So, what do they look like?

$MAP = function($accumulator, $element) {
  $accumulator[] = $function($element);
  return $accumulator;
};

$FILTER = function($accumulator, $element) {
  if ($function($element)) $accumulator[] = $element;
  return $accumulator;
};

As you can see, both functions take in the $accumulator and return it again. There are two differences in these functions:

  • $MAP will always append to $accumulator, but $FILTER will only do so if $function($element) is TRUE.
  • $FILTER appends the original element, but $MAP appends $function($element).

Note that this is far from useless trivia; we can use it to make our algorithms more efficient!

We can often see code like these two examples:

// Transform the valid inputs
array_map('transform', array_filter($inputs, 'valid'))

// Get all numeric IDs
array_filter(array_map('get_id', $inputs), 'is_numeric')

Using array_map and array_filter instead of loops makes these examples look quite nice. However, it can be very inefficient if $inputs is large, since the first call (map or filter) will traverse $inputs and build an intermediate array. This intermediate array is passed straight into the second call, which will traverse the whole thing again, then the intermediate array will need to be garbage collected.

We can get rid of this intermediate array by exploiting the fact that array_map and array_filter are both examples of array_reduce. By combining them, we only have to traverse $inputs once in each example:

// Transform valid inputs
array_reduce($inputs,
             function($accumulator, $element) {
               if (valid($element)) $accumulator[] = transform($element);
               return $accumulator;
             },
             array())

// Get all numeric IDs
array_reduce($inputs,
             function($accumulator, $element) {
               $id = get_id($element);
               if (is_numeric($id)) $accumulator[] = $id;
               return $accumulator;
             },
             array())

NOTE: My implementations of array_map and array_filter above won't behave exactly like PHP's, since my array_map can only handle one array at a time and my array_filter won't use "empty" as its default $function. Also, neither will preserve keys.

It's not difficult to make them behave like PHP's, but I felt that these complications would make the core idea harder to spot.

Why won't eclipse switch the compiler to Java 8?

Two things:

First, JRE is not the same as the JDK. If you do have the JDK, you need to configure eclipse to point to that in your settings.

Second, in your screenshot above, your compiler compliance level is set to 1.7. This will treat all your code as if it's using Java 1.7. Change this to 1.8 to fix your error.

You will need to have Eclipse Luna in order to get support for Java 8, but you can add it to Kepler SR2 if you want. I'd try with Luna and the above suggestions before you go any further. See this reference.

Once you get Luna, your JAVA_HOME variable should be enough to get Eclipse to recognize JDK 8. If you want to specify an additional JDK, you can add a new Java System Library by going to:

Project -> Properties -> Java Build Path -> Libraries -> Add Library -> Java System Library

and navigating to a valid location for the JDK 8.

You can download your platform's JDK 8 here

How do I implement basic "Long Polling"?

For a ASP.NET MVC implementation, look at SignalR which is available on NuGet.. note that the NuGet is often out of date from the Git source which gets very frequent commits.

Read more about SignalR on a blog on by Scott Hanselman

How to hide/show more text within a certain length (like youtube)

Here's a really simple solution that worked for me,

<span id="text">Extra Text</span>
<span id="more">show more...</span>
<span id="less">show less...</span>

<script>
 $("#text").hide();
 $("#less").hide();
 $("#more").click( function() {
   $("#text").show();
   $("#less").show();
   $("#more").hide();
 });
 $("#less").click( function() {
   $("#text").hide();
   $("#less").hide();
   $("#more").show();
 });
</script>

How can I change the color of pagination dots of UIPageControl?

Adding to existing answers, it can be done like,

enter image description here

Converting NSString to NSDictionary / JSON

Use this code where str is your JSON string:

NSError *err = nil;
NSArray *arr = 
 [NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding] 
                                 options:NSJSONReadingMutableContainers 
                                   error:&err];
// access the dictionaries
NSMutableDictionary *dict = arr[0];
for (NSMutableDictionary *dictionary in arr) {
  // do something using dictionary
}

What is a "web service" in plain English?

An operating system provides a GUI (and CLI) that you can interact with. It also provides an API that you can interact with programmatically.

Similarly, a website provides HTML pages that you can interact with and may also provide an API that offers the same information and operations programmatically. Or those services may only be available via an API with no associated user interface.

ASP.NET MVC Yes/No Radio Buttons with Strongly Bound Model MVC

Here is a more complete example using a fieldset for accessibility reasons and specifying the first button as the default. Without a fieldset, what the radio buttons are for as a whole can not be programmatically determined.

Model

public class MyModel
{
    public bool IsMarried { get; set; }
}

View

<fieldset>
    <legend>Married</legend>

    @Html.RadioButtonFor(e => e.IsMarried, true, new { id = "married-true" })
    @Html.Label("married-true", "Yes")

    @Html.RadioButtonFor(e => e.IsMarried, false, new { id = "married-false" })
    @Html.Label("married-false", "No")
</fieldset>

You can add a @checked argument to the anonymous object to set the radio button as the default:

new { id = "married-true", @checked = 'checked' }

Note that you can bind to a string by replacing true and false with the string values.

How to join three table by laravel eloquent model

Try:

$articles = DB::table('articles')
            ->select('articles.id as articles_id', ..... )
            ->join('categories', 'articles.categories_id', '=', 'categories.id')
            ->join('users', 'articles.user_id', '=', 'user.id')

            ->get();

How to check if all of the following items are in a list?

I like these two because they seem the most logical, the latter being shorter and probably fastest (shown here using set literal syntax which has been backported to Python 2.7):

all(x in {'a', 'b', 'c'} for x in ['a', 'b'])
#   or
{'a', 'b'}.issubset({'a', 'b', 'c'})

Regex - how to match everything except a particular pattern

Match against the pattern and use the host language to invert the boolean result of the match. This will be much more legible and maintainable.

ViewBag, ViewData and TempData

ViewBag, ViewData, TempData and View State in MVC

http://royalarun.blogspot.in/2013/08/viewbag-viewdata-tempdata-and-view.html

ASP.NET MVC offers us three options ViewData, VieBag and TempData for passing data from controller to view and in next request. ViewData and ViewBag are almost similar and TempData performs additional responsibility.

Similarities between ViewBag & ViewData :

Helps to maintain data when you move from controller to view. Used to pass data from controller to corresponding view. Short life means value becomes null when redirection occurs. This is because their goal is to provide a way to communicate between controllers and views. It’s a communication mechanism within the server call.

Difference between ViewBag & ViewData:

ViewData is a dictionary of objects that is derived from ViewDataDictionary class and accessible using strings as keys. ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0. ViewData requires typecasting for complex data type and check for null values to avoid error. ViewBag doesn’t require typecasting for complex data type.

ViewBag & ViewData Example:

public ActionResult Index()

{  
    ViewBag.Name = "Arun Prakash";
    return View();    
}

public ActionResult Index()  
{
    ViewData["Name"] = "Arun Prakash";
    return View(); 
}

In View, we call like below:

@ViewBag.Name   
@ViewData["Name"]

TempData:

Helps to maintain data when you move from one controller to other controller or from one action to other action. In other words when you redirect, “Tempdata” helps to maintain data between those redirects. It internally uses session variables. TempData is meant to be a very short-lived instance, and you should only use it during the current and the subsequent requests only

The only scenario where using TempData will reliably work is when you are redirecting. This is because a redirect kills the current request (and sends HTTP status code 302 Object Moved to the client), then creates a new request on the server to serve the redirected view.

It requires typecasting for complex data type and check for null values to avoid error.

public ActionResult Index()
{   
   var model = new Review()  
   {  
      Body = "Start",  
      Rating=5  
   };  

    TempData["ModelName"] = model;    
    return RedirectToAction("About");   
} 

public ActionResult About()       
{  
    var model= TempData["ModelName"];  
    return View(model);   
}  

How to create CSV Excel file C#?

How about using string.Join instead of all the foreach Loops?

How to show android checkbox at right side?

Adding another answer to this question that uses CheckedTextView If anyone is trying to do it programatically. It also has the option of using custom images for checkbox. And can be done in a single View

final CheckedTextView checkBox = new CheckedTextView(getApplicationContext());
    checkBox.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
    checkBox.setId(1);
    checkBox.setCheckMarkDrawable(android.R.drawable.checkbox_off_background);
    checkBox.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (checkBox.isChecked()){
                checkBox.setChecked(false);
                checkBox.setCheckMarkDrawable(android.R.drawable.checkbox_off_background);
            }else{
                checkBox.setChecked(true);
                checkBox.setCheckMarkDrawable(android.R.drawable.checkbox_on_background);
            }
        }
    });
    checkBox.setTextColor(Color.BLACK);
    checkBox.setGravity(Gravity.LEFT);
    checkBox.setText("hi");

From XML if you want to initiate -

<CheckedTextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:checkMark="@android:drawable/checkbox_off_background"
        android:checked="false"
        android:text="Hi from xml"/>

Mercurial stuck "waiting for lock"

I had the same problem on Win 7. The solution was to remove following files:

  1. .hg/store/phaseroots
  2. .hg/wlock

As for .hg/store/lock - there was no such file.

Python equivalent of D3.js

One recipe that I have used (described here: Co-Director Network Data Files in GEXF and JSON from OpenCorporates Data via Scraperwiki and networkx ) runs as follows:

  • generate a network representation using networkx
  • export the network as a JSON file
  • import that JSON into to d3.js. (networkx can export both the tree and graph/network representations that d3.js can import).

The networkx JSON exporter takes the form:

from networkx.readwrite import json_graph
import json
print json.dumps(json_graph.node_link_data(G))

Alternatively you can export the network as a GEXF XML file and then import this representation into the sigma.js Javascript visualisation library.

from xml.etree.cElementTree import tostring
writer=gf.GEXFWriter(encoding='utf-8',prettyprint=True,version='1.1draft')
writer.add_graph(G)
print tostring(writer.xml)

How to bring an activity to foreground (top of stack)?

You can try this FLAG_ACTIVITY_REORDER_TO_FRONT (the document describes exactly what you want to)

Differences between JDK and Java SDK

Best example for this Question, SDK - Software Development Kit - Ex: Netbeans JDK - Java Development Kit.(This is Java compiler). Without JDK, we unable to run java programs in SDK.

get value from DataTable

It looks like you have accidentally declared DataType as an array rather than as a string.

Change line 3 to:

Dim DataType As String = myTableData.Rows(i).Item(1)

That should work.

How to pass json POST data to Web API method as an object?

Working with POST in webapi can be tricky! Would like to add to the already correct answer..

Will focus specifically on POST as dealing with GET is trivial. I don't think many would be searching around for resolving an issue with GET with webapis. Anyways..

If your question is - In MVC Web Api, how to- - Use custom action method names other than the generic HTTP verbs? - Perform multiple posts? - Post multiple simple types? - Post complex types via jQuery?

Then the following solutions may help:

First, to use Custom Action Methods in Web API, add a web api route as:

public static void Register(HttpConfiguration config)
{
    config.Routes.MapHttpRoute(
        name: "ActionApi",
        routeTemplate: "api/{controller}/{action}");
}

And then you may create action methods like:

[HttpPost]
public string TestMethod([FromBody]string value)
{
    return "Hello from http post web api controller: " + value;
}

Now, fire the following jQuery from your browser console

$.ajax({
    type: 'POST',
    url: 'http://localhost:33649/api/TestApi/TestMethod',
    data: {'':'hello'},
    contentType: 'application/x-www-form-urlencoded',
    dataType: 'json',
    success: function(data){ console.log(data) }
});

Second, to perform multiple posts, It is simple, create multiple action methods and decorate with the [HttpPost] attrib. Use the [ActionName("MyAction")] to assign custom names, etc. Will come to jQuery in the fourth point below

Third, First of all, posting multiple SIMPLE types in a single action is not possible. Moreover, there is a special format to post even a single simple type (apart from passing the parameter in the query string or REST style). This was the point that had me banging my head with Rest Clients (like Fiddler and Chrome's Advanced REST client extension) and hunting around the web for almost 5 hours when eventually, the following URL proved to be of help. Will quote the relevant content for the link might turn dead!

Content-Type: application/x-www-form-urlencoded
in the request header and add a = before the JSON statement:
={"Name":"Turbo Tina","Email":"[email protected]"}

PS: Noticed the peculiar syntax?

http://forums.asp.net/t/1883467.aspx?The+received+value+is+null+when+I+try+to+Post+to+my+Web+Api

Anyways, let us get over that story. Moving on:

Fourth, posting complex types via jQuery, ofcourse, $.ajax() is going to promptly come in the role:

Let us say the action method accepts a Person object which has an id and a name. So, from javascript:

var person = { PersonId:1, Name:"James" }
$.ajax({
    type: 'POST',
    url: 'http://mydomain/api/TestApi/TestMethod',
    data: JSON.stringify(person),
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    success: function(data){ console.log(data) }
});

And the action will look like:

[HttpPost]
public string TestMethod(Person person)
{
    return "Hello from http post web api controller: " + person.Name;
}

All of the above, worked for me!! Cheers!

How to convert milliseconds to "hh:mm:ss" format?

Well, you could try something like this, :

public String getElapsedTimeHoursMinutesSecondsString() {       
     long elapsedTime = getElapsedTime();  
     String format = String.format("%%0%dd", 2);  
     elapsedTime = elapsedTime / 1000;  
     String seconds = String.format(format, elapsedTime % 60);  
     String minutes = String.format(format, (elapsedTime % 3600) / 60);  
     String hours = String.format(format, elapsedTime / 3600);  
     String time =  hours + ":" + minutes + ":" + seconds;  
     return time;  
 }  

to convert milliseconds to a time value

"Faceted Project Problem (Java Version Mismatch)" error message

You have two options to fix the issue:

1- Manually make sure the two versions match.
2- Use the IDE's help as follows:
- Right mouse click on the error in the 'Problems' view
- Select the 'Quick Fix' menu item from the pop-up menu
- Select the right compiler level in the provided dialog and click 'Finish'.

Taken from Eclipse: Java compiler level and project facet mismatch

Also gives location of where you can access the Java compiler and facet version.

Reading Xml with XmlReader in C#

The following example navigates through the stream to determine the current node type, and then uses XmlWriter to output the XmlReader content.

    StringBuilder output = new StringBuilder();

    String xmlString =
            @"<?xml version='1.0'?>
            <!-- This is a sample XML document -->
            <Items>
              <Item>test with a child element <more/> stuff</Item>
            </Items>";
    // Create an XmlReader
    using (XmlReader reader = XmlReader.Create(new StringReader(xmlString)))
    {
        XmlWriterSettings ws = new XmlWriterSettings();
        ws.Indent = true;
        using (XmlWriter writer = XmlWriter.Create(output, ws))
        {

            // Parse the file and display each of the nodes.
            while (reader.Read())
            {
                switch (reader.NodeType)
                {
                    case XmlNodeType.Element:
                        writer.WriteStartElement(reader.Name);
                        break;
                    case XmlNodeType.Text:
                        writer.WriteString(reader.Value);
                        break;
                    case XmlNodeType.XmlDeclaration:
                    case XmlNodeType.ProcessingInstruction:
                        writer.WriteProcessingInstruction(reader.Name, reader.Value);
                        break;
                    case XmlNodeType.Comment:
                        writer.WriteComment(reader.Value);
                        break;
                    case XmlNodeType.EndElement:
                        writer.WriteFullEndElement();
                        break;
                }
            }

        }
    }
    OutputTextBlock.Text = output.ToString();

The following example uses the XmlReader methods to read the content of elements and attributes.

StringBuilder output = new StringBuilder();

String xmlString =
    @"<bookstore>
        <book genre='autobiography' publicationdate='1981-03-22' ISBN='1-861003-11-0'>
            <title>The Autobiography of Benjamin Franklin</title>
            <author>
                <first-name>Benjamin</first-name>
                <last-name>Franklin</last-name>
            </author>
            <price>8.99</price>
        </book>
    </bookstore>";

// Create an XmlReader
using (XmlReader reader = XmlReader.Create(new StringReader(xmlString)))
{
    reader.ReadToFollowing("book");
    reader.MoveToFirstAttribute();
    string genre = reader.Value;
    output.AppendLine("The genre value: " + genre);

    reader.ReadToFollowing("title");
    output.AppendLine("Content of the title element: " + reader.ReadElementContentAsString());
}

OutputTextBlock.Text = output.ToString();

SVN "Already Locked Error"

I had the same problem. This problem is easily solved if you issue the Cleanup command from AnkhSVN.

MySQL Multiple Where Clause

select unique red24.image_id from 
( 
    select image_id from `list` where style_id = 24 and style_value = 'red' 
) red24
inner join 
( 
    select image_id from `list` where style_id = 25 and style_value = 'big' 
) big25
on red24.image_id = big25.image_id
inner join 
( 
    select image_id from `list` where style_id = 27 and style_value = 'round' 
) round27
on red24.image_id = round27.image_id

StringIO in Python3

On Python 3 numpy.genfromtxt expects a bytes stream. Use the following:

numpy.genfromtxt(io.BytesIO(x.encode()))

C# looping through an array

Your for loop doesn't need to just add one. You can loop by three.

for(int i = 0; i < theData.Length; i+=3)
{
  string value1 = theData[i];
  string value2 = theData[i+1];
  string value3 = theData[i+2];
}

Basically, you are just using indexes to grab the values in your array. One point to note here, I am not checking to see if you go past the end of your array. Make sure you are doing bounds checking!

Create a button programmatically and set a background image

To set background we can no longer use forState, so we have to use for to set the UIControlState:

let zoomInImage = UIImage(named: "Icon - plus") as UIImage?
let zoomInButton = UIButton(frame: CGRect(x: 10), y: 10, width: 45, height: 45))
zoomInButton.setBackgroundImage(zoomInImage, for: UIControlState.normal)
zoomInButton.addTarget(self, action: #selector(self.mapZoomInAction), for: .touchUpInside)
self.view.addSubview(zoomInButton)

How to update attributes without validation

Shouldn't that be

validates_length_of :title, :in => 6..255, :on => :create

so it only works during create?

How to localise a string inside the iOS info.plist file?

In my case the localization not worked cause of '-' symbol in the name. Example: "aero-Info.plist" And localized files: "aero-InfoPlist.strings" and "aeroInfoPlist.strings" did not work.

Reload an iframe with jQuery

Just reciprocating Alex's answer but with jQuery

var currSrc = $("#currentElement").attr("src");
$("#currentElement").attr("src", currSrc);

How can I call a method in Objective-C?

use this,
[self score]; 
instead of @selector(score).

How to get ° character in a string in python?

just use \xb0 (in a string); python will convert it automatically

Accessing a property in a parent Component

On Angular 6, I access parent properties by injecting the parent via constructor. Not the best solution but it works:

 constructor(@Optional() public parentComponentInjectionObject: ParentComponent){
    // And access like this:
    parentComponentInjectionObject.thePropertyYouWantToAccess;
}

Wrap text in <td> tag

To make cell width exactly same as the longest word of the text, just set width of the cell to 1px

i.e.

td {
  width: 1px;
}

This is experimental and i came to know about this while doing trial and error

Live fiddle: http://jsfiddle.net/harshjv/5e2oLL8L/2/

Convert PDF to clean SVG?

You can use Inkscape on the commandline only, without opening a GUI. Try this:

inkscape \
  --without-gui \
  --file=input.pdf \
  --export-plain-svg=output.svg 

For a complete list of all commandline options, run inkscape --help.

Are types like uint32, int32, uint64, int64 defined in any stdlib header?

The C99 stdint.h defines these:

  • int8_t
  • int16_t
  • int32_t
  • uint8_t
  • uint16_t
  • uint32_t

And, if the architecture supports them:

  • int64_t
  • uint64_t

There are various other integer typedefs in stdint.h as well.

If you're stuck without a C99 environment then you should probably supply your own typedefs and use the C99 ones anyway.

The uint32 and uint64 (i.e. without the _t suffix) are probably application specific.

numpy.where() detailed, step-by-step explanation / examples

Here is a little more fun. I've found that very often NumPy does exactly what I wish it would do - sometimes it's faster for me to just try things than it is to read the docs. Actually a mixture of both is best.

I think your answer is fine (and it's OK to accept it if you like). This is just "extra".

import numpy as np

a = np.arange(4,10).reshape(2,3)

wh = np.where(a>7)
gt = a>7
x  = np.where(gt)

print "wh: ", wh
print "gt: ", gt
print "x:  ", x

gives:

wh:  (array([1, 1]), array([1, 2]))
gt:  [[False False False]
      [False  True  True]]
x:   (array([1, 1]), array([1, 2]))

... but:

print "a[wh]: ", a[wh]
print "a[gt]  ", a[gt]
print "a[x]:  ", a[x]

gives:

a[wh]:  [8 9]
a[gt]   [8 9]
a[x]:   [8 9]

Facebook Oauth Logout

With PHP I'm doing:

<a href="?action=logout">logout.</a>

if(isset($_GET['action']) && $_GET['action'] === 'logout'){
    $facebook->destroySession();
    header(WHERE YOU WANT TO REDIRECT TO);
    exit();
}

Works and is nice and easy am just trying to find a logout button graphic now!

Time calculation in php (add 10 hours)?

You can simply make use of the DateTime class , OOP Style.

<?php
$date = new DateTime('1:00:00');
$date->add(new DateInterval('PT10H'));
echo $date->format('H:i:s a'); //"prints" 11:00:00 a.m

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

you can use -f option to force delete the containers .

sudo docker rmi -f training/webapp

You may stop the containers using sudo docker stop training/webapp before deleting

Android Recyclerview vs ListView with Viewholder

Okay so little bit of digging and I found these gems from Bill Philips article on RecycleView

RecyclerView can do more than ListView, but the RecyclerView class itself has fewer responsibilities than ListView. Out of the box, RecyclerView does not:

  • Position items on the screen
  • Animate views
  • Handle any touch events apart from scrolling

All of this stuff was baked in to ListView, but RecyclerView uses collaborator classes to do these jobs instead.

The ViewHolders you create are beefier, too. They subclass RecyclerView.ViewHolder, which has a bunch of methods RecyclerView uses. ViewHolders know which position they are currently bound to, as well as which item ids (if you have those). In the process, ViewHolder has been knighted. It used to be ListView’s job to hold on to the whole item view, and ViewHolder only held on to little pieces of it.

Now, ViewHolder holds on to all of it in the ViewHolder.itemView field, which is assigned in ViewHolder’s constructor for you.

Is there a Mutex in Java?

No one has clearly mentioned this, but this kind of pattern is usually not suited for semaphores. The reason is that any thread can release a semaphore, but you usually only want the owner thread that originally locked to be able to unlock. For this use case, in Java, we usually use ReentrantLocks, which can be created like this:

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

private final Lock lock = new ReentrantLock(true);

And the usual design pattern of usage is:

  lock.lock();
  try {
      // do something
  } catch (Exception e) {
      // handle the exception
  } finally {
      lock.unlock();
  }

Here is an example in the java source code where you can see this pattern in action.

Reentrant locks have the added benefit of supporting fairness.

Use semaphores only if you need non-ownership-release semantics.

Disable single warning error

#pragma warning( push )
#pragma warning( disable : 4101)
// Your function
#pragma warning( pop ) 

MongoDB not equal to

If you want to do multiple $ne then do

db.users.find({name : {$nin : ["mary", "dick", "jane"]}})

Create list of object from another using Java 8 Streams

What you are possibly looking for is map(). You can "convert" the objects in a stream to another by mapping this way:

...
 .map(userMeal -> new UserMealExceed(...))
...

Convert floating point number to a certain precision, and then copy to string

With Python < 3 (e.g. 2.6 [see comments] or 2.7), there are two ways to do so.

# Option one
older_method_string = "%.9f" % numvar

# Option two
newer_method_string = "{:.9f}".format(numvar)

But note that for Python versions above 3 (e.g. 3.2 or 3.3), option two is preferred.

For more information on option two, I suggest this link on string formatting from the Python documentation.

And for more information on option one, this link will suffice and has info on the various flags.

Python 3.6 (officially released in December of 2016), added the f string literal, see more information here, which extends the str.format method (use of curly braces such that f"{numvar:.9f}" solves the original problem), that is,

# Option 3 (versions 3.6 and higher)
newest_method_string = f"{numvar:.9f}"

solves the problem. Check out @Or-Duan's answer for more info, but this method is fast.

How do I set the background color of my main screen in Flutter?

Here's one way that I found to do it. I don't know if there are better ways, or what the trade-offs are.

Container "tries to be as big as possible", according to https://flutter.io/layout/. Also, Container can take a decoration, which can be a BoxDecoration, which can have a color (which, is the background color).

Here's a sample that does indeed fill the screen with red, and puts "Hello, World!" into the center:

import 'package:flutter/material.dart';

void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return new Container(
      decoration: new BoxDecoration(color: Colors.red),
      child: new Center(
        child: new Text("Hello, World!"),
      ),
    );
  }
}

Note, the Container is returned by the MyApp build(). The Container has a decoration and a child, which is the centered text.

See it in action here:

enter image description here

Python: Select subset from list based on index set

Assuming you only have the list of items and a list of true/required indices, this should be the fastest:

property_asel = [ property_a[index] for index in good_indices ]

This means the property selection will only do as many rounds as there are true/required indices. If you have a lot of property lists that follow the rules of a single tags (true/false) list you can create an indices list using the same list comprehension principles:

good_indices = [ index for index, item in enumerate(good_objects) if item ]

This iterates through each item in good_objects (while remembering its index with enumerate) and returns only the indices where the item is true.


For anyone not getting the list comprehension, here is an English prose version with the code highlighted in bold:

list the index for every group of index, item that exists in an enumeration of good objects, if (where) the item is True

JavaScript: changing the value of onclick with or without jQuery

You shouldn't be using onClick any more if you are using jQuery. jQuery provides its own methods of attaching and binding events. See .click()

$(document).ready(function(){
    var js = "alert('B:' + this.id); return false;";
    // create a function from the "js" string
    var newclick = new Function(js);

    // clears onclick then sets click using jQuery
    $("#anchor").attr('onclick', '').click(newclick);
});

That should cancel the onClick function - and keep your "javascript from a string" as well.

The best thing to do would be to remove the onclick="" from the <a> element in the HTML code and switch to using the Unobtrusive method of binding an event to click.

You also said:

Using onclick = function() { return eval(js); } doesn't work because you are not allowed to use return in code passed to eval().

No - it won't, but onclick = eval("(function(){"+js+"})"); will wrap the 'js' variable in a function enclosure. onclick = new Function(js); works as well and is a little cleaner to read. (note the capital F) -- see documentation on Function() constructors

How to position one element relative to another with jQuery?

Here is a jQuery function I wrote that helps me position elements.

Here is an example usage:

$(document).ready(function() {
  $('#el1').position('#el2', {
    anchor: ['br', 'tr'],
    offset: [-5, 5]
  });
});

The code above aligns the bottom-right of #el1 with the top-right of #el2. ['cc', 'cc'] would center #el1 in #el2. Make sure that #el1 has the css of position: absolute and z-index: 10000 (or some really large number) to keep it on top.

The offset option allows you to nudge the coordinates by a specified number of pixels.

The source code is below:

jQuery.fn.getBox = function() {
  return {
    left: $(this).offset().left,
    top: $(this).offset().top,
    width: $(this).outerWidth(),
    height: $(this).outerHeight()
  };
}

jQuery.fn.position = function(target, options) {
  var anchorOffsets = {t: 0, l: 0, c: 0.5, b: 1, r: 1};
  var defaults = {
    anchor: ['tl', 'tl'],
    animate: false,
    offset: [0, 0]
  };
  options = $.extend(defaults, options);

  var targetBox = $(target).getBox();
  var sourceBox = $(this).getBox();

  //origin is at the top-left of the target element
  var left = targetBox.left;
  var top = targetBox.top;

  //alignment with respect to source
  top -= anchorOffsets[options.anchor[0].charAt(0)] * sourceBox.height;
  left -= anchorOffsets[options.anchor[0].charAt(1)] * sourceBox.width;

  //alignment with respect to target
  top += anchorOffsets[options.anchor[1].charAt(0)] * targetBox.height;
  left += anchorOffsets[options.anchor[1].charAt(1)] * targetBox.width;

  //add offset to final coordinates
  left += options.offset[0];
  top += options.offset[1];

  $(this).css({
    left: left + 'px',
    top: top + 'px'
  });

}

The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. on deploying to tomcat

Trying to run a servlet in Eclipse (right-click + "Run on Server") I encountered the very same problem: "HTTP Status: 404 / Description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists." Adding an index.html did not help, neither changing various settings of the tomcat.

Finally, I found the problem in an unexpected place: In Eclipse, the Option "Build automatically" was not set. Thus the servlet was not compiled, and no File "myServlet.class" was deployed to the server (in my case in the path .wtpwebapps/projectXX/WEB-INF/classes/XXpackage/). Building the project manually and restarting the server solved the problem.

My environment: Eclipse Neon.3 Release 4.6.3, Tomcat-Version 8.5.14., OS Linux Mint 18.1.

Why am I getting "void value not ignored as it ought to be"?

  int a = srand(time(NULL));

The prototype for srand is void srand(unsigned int) (provided you included <stdlib.h>).
This means it returns nothing ... but you're using the value it returns (???) to assign, by initialization, to a.


Edit: this is what you need to do:

#include <stdlib.h> /* srand(), rand() */
#include <time.h>   /* time() */

#define ARRAY_SIZE 1024

void getdata(int arr[], int n)
{
    for (int i = 0; i < n; i++)
    {
        arr[i] = rand();
    }
}

int main(void)
{
    int arr[ARRAY_SIZE];
    srand(time(0));
    getdata(arr, ARRAY_SIZE);
    /* ... */
}

Angular JS POST request not sending JSON data

$http({
    url: '/api/user',
    method: "POST",
    data: angular.toJson(yourData)
}).success(function (data, status, headers, config) {
    $scope.users = data.users;
}).error(function (data, status, headers, config) {
    $scope.status = status + ' ' + headers;
});

Best ways to teach a beginner to program?

http://tryruby.hobix.com/">Try Ruby (In Your Browser)

How to dockerize maven project? and how many ways to accomplish it?

There may be many ways.. But I implemented by following two ways

Given example is of maven project.

1. Using Dockerfile in maven project

Use the following file structure:

Demo
+-- src
|    +-- main
|    ¦   +-- java
|    ¦       +-- org
|    ¦           +-- demo
|    ¦               +-- Application.java
|    ¦   
|    +-- test
|
+---- Dockerfile
+---- pom.xml

And update the Dockerfile as:

FROM java:8
EXPOSE 8080
ADD /target/demo.jar demo.jar
ENTRYPOINT ["java","-jar","demo.jar"]

Navigate to the project folder and type following command you will be ab le to create image and run that image:

$ mvn clean
$ mvn install
$ docker build -f Dockerfile -t springdemo .
$ docker run -p 8080:8080 -t springdemo

Get video at Spring Boot with Docker

2. Using Maven plugins

Add given maven plugin in pom.xml

<plugin>
    <groupId>com.spotify</groupId>
    <artifactId>docker-maven-plugin</artifactId>
    <version>0.4.5</version>
        <configuration>
            <imageName>springdocker</imageName>
            <baseImage>java</baseImage>
            <entryPoint>["java", "-jar", "/${project.build.finalName}.jar"]</entryPoint>
            <resources>
                <resource>
                    <targetPath>/</targetPath>
                    <directory>${project.build.directory}</directory>
                    <include>${project.build.finalName}.jar</include>
                </resource>
            </resources>
        </configuration>
    </plugin>

Navigate to the project folder and type following command you will be able to create image and run that image:

$ mvn clean package docker:build
$ docker images
$ docker run -p 8080:8080 -t <image name>

In first example we are creating Dockerfile and providing base image and adding jar an so, after doing that we will run docker command to build an image with specific name and then run that image..

Whereas in second example we are using maven plugin in which we providing baseImage and imageName so we don't need to create Dockerfile here.. after packaging maven project we will get the docker image and we just need to run that image..

Calculate mean and standard deviation from a vector of samples in C++ using Boost

2x faster than the versions before mentioned - mostly because transform() and inner_product() loops are joined. Sorry about my shortcut/typedefs/macro: Flo = float. CR const ref. VFlo - vector. Tested in VS2010

#define fe(EL, CONTAINER)   for each (auto EL in CONTAINER)  //VS2010
Flo stdDev(VFlo CR crVec) {
    SZ  n = crVec.size();               if (n < 2) return 0.0f;
    Flo fSqSum = 0.0f, fSum = 0.0f;
    fe(f, crVec) fSqSum += f * f;       // EDIT: was Cit(VFlo, crVec) {
    fe(f, crVec) fSum   += f;
    Flo fSumSq      = fSum * fSum;
    Flo fSumSqDivN  = fSumSq / n;
    Flo fSubSqSum   = fSqSum - fSumSqDivN;
    Flo fPreSqrt    = fSubSqSum / (n - 1);
    return sqrt(fPreSqrt);
}

Adding blur effect to background in swift

U can also use CoreImage to create blurred image with dark effect

  1. Make snapshot for image

    func snapShotImage() -> UIImage {
        UIGraphicsBeginImageContext(self.frame.size)
        if let context = UIGraphicsGetCurrentContext() {
            self.layer.renderInContext(context)
            let image = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            return image
        }
    
        return UIImage()
    }
    
  2. Apply CoreImage Filters as u wish with

    private func bluredImage(view:UIView, radius:CGFloat = 1) -> UIImage {
    let image = view.snapShotImage()
    
    if let source = image.CGImage {
        let context = CIContext(options: nil)
        let inputImage = CIImage(CGImage: source)
    
        let clampFilter = CIFilter(name: "CIAffineClamp")
        clampFilter?.setDefaults()
        clampFilter?.setValue(inputImage, forKey: kCIInputImageKey)
    
        if let clampedImage = clampFilter?.valueForKey(kCIOutputImageKey) as? CIImage {
            let explosureFilter = CIFilter(name: "CIExposureAdjust")
            explosureFilter?.setValue(clampedImage, forKey: kCIInputImageKey)
            explosureFilter?.setValue(-1.0, forKey: kCIInputEVKey)
    
            if let explosureImage = explosureFilter?.valueForKey(kCIOutputImageKey) as? CIImage {
                let filter = CIFilter(name: "CIGaussianBlur")
                filter?.setValue(explosureImage, forKey: kCIInputImageKey)
                filter?.setValue("\(radius)", forKey:kCIInputRadiusKey)
    
                if let result = filter?.valueForKey(kCIOutputImageKey) as? CIImage {
                    let bounds = UIScreen.mainScreen().bounds
                    let cgImage = context.createCGImage(result, fromRect: bounds)
                    let returnImage = UIImage(CGImage: cgImage)
                    return returnImage
                }
            }
        }
    }
    return UIImage()
    }
    

Passing a string array as a parameter to a function java

All the answers above are correct. But just note that you'll be passing the reference to the string array when you pass like this. If you make any modifications to the array in your called function, it will be reflected in the calling function also.

There is another concept called variable arguments in Java which you can look into. It basically works like this. Eg:-

 String concat (String ... strings)
   {
      StringBuilder sb = new StringBuilder ();
      for (int i = 0; i &lt; strings.length; i++)
           sb.append (strings [i]);
      return sb.toString ();
   }

Here we can call the function like concat(a,b,c,d) or any number of params you want.

More Info: http://today.java.net/pub/a/today/2004/04/19/varargs.html

Android Studio Run/Debug configuration error: Module not specified

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

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

enter image description here

Catching KeyboardInterrupt in Python during program shutdown

Checkout this thread, it has some useful information about exiting and tracebacks.

If you are more interested in just killing the program, try something like this (this will take the legs out from under the cleanup code as well):

if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        print('Interrupted')
        try:
            sys.exit(0)
        except SystemExit:
            os._exit(0)

Single Form Hide on Startup

    protected override void OnLoad(EventArgs e)
    {
        Visible = false; // Hide form window.
        ShowInTaskbar = false; // Remove from taskbar.
        Opacity = 0;

        base.OnLoad(e);
    }

What's the complete range for Chinese characters in Unicode?

The exact ranges for Chinese characters (except the extensions) are [\u2E80-\u2FD5\u3190-\u319f\u3400-\u4DBF\u4E00-\u9FCC\uF900-\uFAAD].

  1. [\u2e80-\u2fd5]

CJK Radicals Supplement is a Unicode block containing alternative, often positional, forms of the Kangxi radicals. They are used headers in dictionary indices and other CJK ideograph collections organized by radical-stroke.

  1. [\u3190-\u319f]

Kanbun is a Unicode block containing annotation characters used in Japanese copies of classical Chinese texts, to indicate reading order.

  1. [\u3400-\u4DBF]

CJK Unified Ideographs Extension-A is a Unicode block containing rare Han ideographs.

  1. [\u4E00-\u9FCC]

CJK Unified Ideographs is a Unicode block containing the most common CJK ideographs used in modern Chinese and Japanese.

  1. [\uF900-\uFAAD]

CJK Compatibility Ideographs is a Unicode block created to contain Han characters that were encoded in multiple locations in other established character encodings, in addition to their CJK Unified Ideographs assignments, in order to retain round-trip compatibility between Unicode and those encodings.

For the details please refer to here, and the extensions are provided in other answers.

How can I insert binary file data into a binary SQL field using a simple insert statement?

I believe this would be somewhere close.

INSERT INTO Files
(FileId, FileData)
SELECT 1, * FROM OPENROWSET(BULK N'C:\Image.jpg', SINGLE_BLOB) rs

Something to note, the above runs in SQL Server 2005 and SQL Server 2008 with the data type as varbinary(max). It was not tested with image as data type.

How do I check if an element is really visible with JavaScript?

Try element.getBoundingClientRect(). It will return an object with properties

  • bottom
  • top
  • right
  • left
  • width -- browser dependent
  • height -- browser dependent

Check that the width and height of the element's BoundingClientRect are not zero which is the value of hidden or non-visible elements. If the values are greater than zero the element should be visible in the body. Then check if the bottom property is less than screen.height which would imply that the element is withing the viewport. (Technically you would also have to account for the top of the browser window including the searchbar, buttons, etc.)

Div Scrollbar - Any way to style it?

There's also the iScroll project which allows you to style the scrollbars plus get it to work with touch devices. http://cubiq.org/iscroll-4

Specified cast is not valid.. how to resolve this

Use Convert.ToDouble(value) rather than (double)value. It takes an object and supports all of the types you asked for! :)

Also, your method is always returning a string in the code above; I'd recommend having the method indicate so, and give it a more obvious name (public string FormatLargeNumber(object value))

How to select last child element in jQuery?

For perfomance:

$('#example').children().last()

or if you want a last children with a certain class as commented above.

$('#example').children('.test').last()

or a specific child element with a specific class

$('#example').children('li.test').last()

How do I install a JRE or JDK to run the Android Developer Tools on Windows 7?

If using win7 64 bit OS:

After installing the latest JDK make sure you copy the jre folder from the install location {C:\Program Files\Java\jdk1.7.0_40} directly to your eclipse folder as even pathing it apparently does nothing on win7.

Mad

edit:

Actual jdk version number on folder name will vary as newer versions are released

postgresql sequence nextval in schema

SELECT last_value, increment_by from "other_schema".id_seq;

for adding a seq to a column where the schema is not public try this.

nextval('"other_schema".id_seq'::regclass)

How to completely hide the navigation bar in iPhone / HTML5

Try the following:

  1. Add this meta tag in the head of your HTML file:

    <meta name="apple-mobile-web-app-capable" content="yes" />
    
  2. Open your site with Safari on iPhone, and use the bookmark feature to add your site to the home screen.

  3. Go back to home screen and open the bookmarked site. The URL and status bar will be gone.

As long as you only need to work with the iPhone, you should be fine with this solution.

In addition, your sample on the warnerbros.com site uses the Sencha touch framework. You can Google it for more information or check out their demos.

ImportError: no module named win32api

I didn't find the package of the most voted answer in my Python 3 dist.

I had the same problem and solved it installing the module pywin32:

In a normal python:

pip install pywin32

In anaconda:

conda install pywin32

My python installation (Intel® Distribution for Python) had some kind of dependency problem and was giving this error. After installing this module it stopped appearing.

How can I pretty-print JSON using Go?

Edit Looking back, this is non-idiomatic Go. Small helper functions like this add an extra step of complexity. In general, the Go philosophy prefers to include the 3 simple lines over 1 tricky line.


As @robyoder mentioned, json.Indent is the way to go. Thought I'd add this small prettyprint function:

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
)

//dont do this, see above edit
func prettyprint(b []byte) ([]byte, error) {
    var out bytes.Buffer
    err := json.Indent(&out, b, "", "  ")
    return out.Bytes(), err
}

func main() {
    b := []byte(`{"hello": "123"}`)
    b, _ = prettyprint(b)
    fmt.Printf("%s", b)
}

https://go-sandbox.com/#/R4LWpkkHIN or http://play.golang.org/p/R4LWpkkHIN

Cannot run emulator in Android Studio

A common approach to follow to solve this problem.

1.CHECK your SDK manager by running from your android studio and stand alons sdk folder by executing ./android.sh helps you to find broken packages

  1. Try installing System emulator images with google API support than the Intel one. Just like , i solved my problem by running into another system image.

  2. Experment on KVM based Virtulaization suggested by Google for Linux

How to style the parent element when hovering a child element?

I know it is an old question, but I just managed to do so without a pseudo child (but a pseudo wrapper).

If you set the parent to be with no pointer-events, and then a child div with pointer-events set to auto, it works:)
Note that <img> tag (for example) doesn't do the trick.
Also remember to set pointer-events to auto for other children which have their own event listener, or otherwise they will lose their click functionality.

_x000D_
_x000D_
div.parent {  _x000D_
    pointer-events: none;_x000D_
}_x000D_
_x000D_
div.child {_x000D_
    pointer-events: auto;_x000D_
}_x000D_
_x000D_
div.parent:hover {_x000D_
    background: yellow;_x000D_
}    
_x000D_
<div class="parent">_x000D_
  parent - you can hover over here and it won't trigger_x000D_
  <div class="child">hover over the child instead!</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Edit:
As Shadow Wizard kindly noted: it's worth to mention this won't work for IE10 and below. (Old versions of FF and Chrome too, see here)

How to make a Java Generic method static?

I'll explain it in a simple way.

Generics defined at Class level are completely separate from the generics defined at the (static) method level.

class Greet<T> {

    public static <T> void sayHello(T obj) {
        System.out.println("Hello " + obj);
    }
}

When you see the above code anywhere, please note that the T defined at the class level has nothing to do with the T defined in the static method. The following code is also completely valid and equivalent to the above code.

class Greet<T> {

    public static <E> void sayHello(E obj) {
        System.out.println("Hello " + obj);
    }
}

Why the static method needs to have its own generics separate from those of the Class?

This is because, the static method can be called without even instantiating the Class. So if the Class is not yet instantiated, we do not yet know what is T. This is the reason why the static methods needs to have its own generics.

So, whenever you are calling the static method,

Greet.sayHello("Bob");
Greet.sayHello(123);

JVM interprets it as the following.

Greet.<String>sayHello("Bob");
Greet.<Integer>sayHello(123);

Both giving the same outputs.

Hello Bob
Hello 123

Python naming conventions for modules

I know my solution is not very popular from the pythonic point of view, but I prefer to use the Java approach of one module->one class, with the module named as the class. I do understand the reason behind the python style, but I am not too fond of having a very large file containing a lot of classes. I find it difficult to browse, despite folding.

Another reason is version control: having a large file means that your commits tend to concentrate on that file. This can potentially lead to a higher quantity of conflicts to be resolved. You also loose the additional log information that your commit modifies specific files (therefore involving specific classes). Instead you see a modification to the module file, with only the commit comment to understand what modification has been done.

Summing up, if you prefer the python philosophy, go for the suggestions of the other posts. If you instead prefer the java-like philosophy, create a Nib.py containing class Nib.

Difference between return 1, return 0, return -1 and exit?

return n from main is equivalent to exit(n).

The valid returned is the rest of your program. It's meaning is OS dependent. On unix, 0 means normal termination and non-zero indicates that so form of error forced your program to terminate without fulfilling its intended purpose.

It's unusual that your example returns 0 (normal termination) when it seems to have run out of memory.

Custom Cell Row Height setting in storyboard is not responding

I've built the code the various answers/comments hint at so that this works for storyboards that use prototype cells.

This code:

  • Does not require the cell height to be set anywhere other than the obvious place in the storyboard
  • Caches the height for performance reasons
  • Uses a common function to get the cell identifier for an index path to avoid duplicated logic

Thanks to Answerbot, Brennan and lensovet.

- (NSString *)cellIdentifierForIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellIdentifier = nil;

    switch (indexPath.section)
    {
        case 0:
            cellIdentifier = @"ArtworkCell";
            break;
         <... and so on ...>
    }

    return cellIdentifier;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellIdentifier = [self cellIdentifierForIndexPath:indexPath];
    static NSMutableDictionary *heightCache;
    if (!heightCache)
        heightCache = [[NSMutableDictionary alloc] init];
    NSNumber *cachedHeight = heightCache[cellIdentifier];
    if (cachedHeight)
        return cachedHeight.floatValue;

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    CGFloat height = cell.bounds.size.height;
    heightCache[cellIdentifier] = @(height);
    return height;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellIdentifier = [self cellIdentifierForIndexPath:indexPath];

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];

    <... configure cell as usual...>

How do I view the Explain Plan in Oracle Sql developer?

We use Oracle PL/SQL Developer(Version 12.0.7). And we use F5 button to view the explain plan.

How to include() all PHP files from a directory?

I suggest you use a readdir() function and then loop and include the files (see the 1st example on that page).

How to show full column content in a Spark Dataframe?

results.show(false) will show you the full column content.

Show method by default limit to 20, and adding a number before false will show more rows.

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

just add in build.gradle

compile 'com.parse.bolts:bolts-android:1.+'

compile 'com.parse:parse-android:1.11.0'

and sync Project with Gradle Files enter image description here But Don't Add The parse Jar in libs :) OKK

How can I use Async with ForEach?

Starting with C# 8.0, you can create and consume streams asynchronously.

    private async void button1_Click(object sender, EventArgs e)
    {
        IAsyncEnumerable<int> enumerable = GenerateSequence();

        await foreach (var i in enumerable)
        {
            Debug.WriteLine(i);
        }
    }

    public static async IAsyncEnumerable<int> GenerateSequence()
    {
        for (int i = 0; i < 20; i++)
        {
            await Task.Delay(100);
            yield return i;
        }
    }

More

Print very long string completely in pandas dataframe

The way I often deal with the situation you describe is to use the .to_csv() method and write to stdout:

import sys

df.to_csv(sys.stdout)

Update: it should now be possible to just use None instead of sys.stdout with similar effect!

This should dump the whole dataframe, including the entirety of any strings. You can use the to_csv parameters to configure column separators, whether the index is printed, etc. It will be less pretty than rendering it properly though.

I posted this originally in answer to the somewhat-related question at Output data from all columns in a dataframe in pandas

How to write UPDATE SQL with Table alias in SQL Server 2008?

You can always take the CTE, (Common Tabular Expression), approach.

;WITH updateCTE AS
(
    SELECT ID, TITLE 
    FROM HOLD_TABLE
    WHERE ID = 101
)

UPDATE updateCTE
SET TITLE = 'TEST';

How to get the date 7 days earlier date from current date in Java

Or use JodaTime:

DateTime lastWeek = new DateTime().minusDays(7);

How to export private key from a keystore of self-signed certificate

It is a little tricky. First you can use keytool to put the private key into PKCS12 format, which is more portable/compatible than Java's various keystore formats. Here is an example taking a private key with alias 'mykey' in a Java keystore and copying it into a PKCS12 file named myp12file.p12. [note that on most screens this command extends beyond the right side of the box: you need to scroll right to see it all]

keytool -v -importkeystore -srckeystore .keystore -srcalias mykey -destkeystore myp12file.p12 -deststoretype PKCS12
Enter destination keystore password:  
Re-enter new password: 
Enter source keystore password:  
[Storing myp12file.p12]

Now the file myp12file.p12 contains the private key in PKCS12 format which may be used directly by many software packages or further processed using the openssl pkcs12 command. For example,

openssl pkcs12 -in myp12file.p12 -nocerts -nodes
Enter Import Password:
MAC verified OK
Bag Attributes
    friendlyName: mykey
    localKeyID: 54 69 6D 65 20 31 32 37 31 32 37 38 35 37 36 32 35 37 
Key Attributes: <No Attributes>
-----BEGIN RSA PRIVATE KEY-----
MIIC...
.
.
.
-----END RSA PRIVATE KEY-----

Prints out the private key unencrypted.

Note that this is a private key, and you are responsible for appreciating the security implications of removing it from your Java keystore and moving it around.

Differences between hard real-time, soft real-time, and firm real-time?

After reading the Wikipedia page and other pages on real-time computing. I made the following inferences:

1> For a Hard real-time system, if the system fails to meet the deadline even once the system is considered to have Failed.

2> For a Firm real-time system, even if the system fails to meet the deadline, possibly more than once (i.e. for multiple requests), the system is not considered to have failed. Also, the responses for the requests (replies to a query, result of a task, etc.) are worthless once the deadline for that particular request has passed (The usefulness of a result is zero after its deadline). A hypothetical example can be a storm forecast system (if a storm is predicted before arrival, then the system has done its job, prediction after the event has already happened or when it is happening is of no value).

3> For a Soft real-time system, even if the system fails to meet the deadline, possibly more than once (i.e. for multiple requests), the system is not considered to have failed. But, in this case the results of the requests are not worthless value for a result after its deadline, is not zero, rather it degrades as time passes after the deadline. Eg.: Streaming audio-video.

Here is a link to a resource that was very helpful.

How to get numbers after decimal point?

This is only if you want toget the first decimal

print(int(float(input()) * 10) % 10)

Or you can try this

num = float(input())
b = num - int(num) 
c = b * 10
print(int(c))

Enable IIS7 gzip

Another easy way to test without installing anything, neither is it dependent on IIS version. Paste your url to this link - SEO Checkup

test gzip

To add to web.config: http://www.iis.net/configreference/system.webserver/httpcompression

What is the difference between a field and a property?

Properties encapsulate fields, thus enabling you to perform additional processing on the value to be set or retrieved. It is typically overkill to use properties if you will not be doing any pre- or postprocessing on the field value.

How to use jQuery to show/hide divs based on radio button selection?

Just hide them before showing them:

$(document).ready(function(){ 
    $("input[name$='group2']").click(function() {
        var test = $(this).val();
        $("div.desc").hide();
        $("#"+test).show();
    }); 
});

TypeError: $(...).DataTable is not a function

There can be two reasons for that error:

First

You are loding jQuery.DataTables.js before jquery.js so for that :-

You need to load jQuery.js before you load jQuery.DataTables.js

Second

You are using two versions of jQuery.js on the same page so for that :-

Try to use the higher version and make sure both links have same version of jQuery

Query to list all stored procedures

As Mike stated, the best way is to use information_schema. As long as you're not in the master database, system stored procedures won't be returned.

SELECT * 
  FROM DatabaseName.INFORMATION_SCHEMA.ROUTINES
 WHERE ROUTINE_TYPE = 'PROCEDURE'

If for some reason you had non-system stored procedures in the master database, you could use the query (this will filter out MOST system stored procedures):

SELECT * 
  FROM [master].INFORMATION_SCHEMA.ROUTINES
 WHERE ROUTINE_TYPE = 'PROCEDURE' 
   AND LEFT(ROUTINE_NAME, 3) NOT IN ('sp_', 'xp_', 'ms_')

Convert varchar2 to Date ('MM/DD/YYYY') in PL/SQL

Example query: SELECT TO_CHAR(TO_DATE('2017-08-23','YYYY-MM-DD'), 'MM/DD/YYYY') FROM dual;

Use Device Login on Smart TV / Console

They change it again. At this moment documentation does not fit actual situation.

Commonly all works as expected with one small difference. Login from Devices config now moves to Products -> Facebook Login.

So you need to:

  • get your App id from headline,
  • get Client Token from app Settings -> Advanced. There is also Native or desktop app? question/config. I turn it on.
  • Add product (just click on Add product and then Get started on Facebook login. Move back to your app config, click to newly added Facebook login and you'll see your Login from Devices config.

Spring JDBC Template for calling Stored Procedures

There are a number of ways to call stored procedures in Spring.

If you use CallableStatementCreator to declare parameters, you will be using Java's standard interface of CallableStatement, i.e register out parameters and set them separately. Using SqlParameter abstraction will make your code cleaner.

I recommend you looking at SimpleJdbcCall. It may be used like this:

SimpleJdbcCall jdbcCall = new SimpleJdbcCall(jdbcTemplate)
    .withSchemaName(schema)
    .withCatalogName(package)
    .withProcedureName(procedure)();
...
jdbcCall.addDeclaredParameter(new SqlParameter(paramName, OracleTypes.NUMBER));
...
jdbcCall.execute(callParams);

For simple procedures you may use jdbcTemplate's update method:

jdbcTemplate.update("call SOME_PROC (?, ?)", param1, param2);

How to disable registration new users in Laravel

On laravel 5.6 and above you can edit in web.php file

Auth::routes(['verify' => true, 'register' => false]);

and you can make it true if you change your mind, i see it easy this way

Is there an equivalent method to C's scanf in Java?

Take a look at this site, it explains two methods for reading from console in java, using Scanner or the classical InputStreamReader from System.in.

Following code is taken from cited website:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class ReadConsoleSystem {
  public static void main(String[] args) {

    System.out.println("Enter something here : ");

    try{
        BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
        String s = bufferRead.readLine();

        System.out.println(s);
    }
    catch(IOException e)
    {
        e.printStackTrace();
    }

  }
}

--

import java.util.Scanner;

public class ReadConsoleScanner {
  public static void main(String[] args) {

      System.out.println("Enter something here : ");

       String sWhatever;

       Scanner scanIn = new Scanner(System.in);
       sWhatever = scanIn.nextLine();

       scanIn.close();            
       System.out.println(sWhatever);
  }
}

Regards.

Connection string using Windows Authentication

For connecting to a sql server database via Windows authentication basically needs which server you want to connect , what is your database name , Integrated Security info and provider name.

Basically this works:

<connectionStrings>      
<add name="MyConnectionString"
         connectionString="data source=ServerName;
   Initial Catalog=DatabaseName;Integrated Security=True;"
         providerName="System.Data.SqlClient" />
</connectionStrings> 

Setting Integrated Security field true means basically you want to reach database via Windows authentication, if you set this field false Windows authentication will not work.

It is also working different according which provider you are using.

  • SqlClient both Integrated Security=true; or IntegratedSecurity=SSPI; is working.

  • OleDb it is Integrated Security=SSPI;

  • Odbc it is Trusted_Connection=yes;
  • OracleClient it is Integrated Security=yes;

Integrated Security=true throws an exception when used with the OleDb provider.

How to stick a footer to bottom in css?

I agree with Luke Vo's solution. I thought it would better to omit justify-content: space-between; from layout-wrapper and add margin-top: auto; to footer.

You wouldn't want your body to be hanging in the middle and only have footer pushed to the bottom.

This approach addresses any content extending beyond the viewport.

How do I parse JSON from a Java HTTPResponse?

Use JSON Simple,

http://code.google.com/p/json-simple/

Which has a small foot-print, no dependencies so it's perfect for Android.

You can do something like this,

Object obj=JSONValue.parse(buffer.tString());
JSONArray finalResult=(JSONArray)obj;

When using Spring Security, what is the proper way to obtain current username (i.e. SecurityContext) information in a bean?

I get authenticated user by HttpServletRequest.getUserPrincipal();

Example:

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.web.authentication.preauth.RequestHeaderAuthenticationFilter;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.support.RequestContext;

import foo.Form;

@Controller
@RequestMapping(value="/welcome")
public class IndexController {

    @RequestMapping(method=RequestMethod.GET)
    public String getCreateForm(Model model, HttpServletRequest request) {

        if(request.getUserPrincipal() != null) {
            String loginName = request.getUserPrincipal().getName();
            System.out.println("loginName : " + loginName );
        }

        model.addAttribute("form", new Form());
        return "welcome";
    }
}

Storing Form Data as a Session Variable

Yes this is possible. kizzie is correct with the session_start(); having to go first.

another observation I made is that you need to filter your form data using:

strip_tags($value);

and/or

stripslashes($value);

How to convert image to byte array

Do you only want the pixels or the whole image (including headers) as an byte array?

For pixels: Use the CopyPixels method on Bitmap. Something like:

var bitmap = new BitmapImage(uri);

//Pixel array
byte[] pixels = new byte[width * height * 4]; //account for stride if necessary and whether the image is 32 bit, 16 bit etc.

bitmap.CopyPixels(..size, pixels, fullStride, 0); 

make *** no targets specified and no makefile found. stop

I recently ran into this problem while trying to do a manual install of texane's open-source STLink utility on Ubuntu. The solution was, oddly enough,

make clean
make

How to convert a double to long without casting?

Assuming you're happy with truncating towards zero, just cast:

double d = 1234.56;
long x = (long) d; // x = 1234

This will be faster than going via the wrapper classes - and more importantly, it's more readable. Now, if you need rounding other than "always towards zero" you'll need slightly more complicated code.

The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value

Error: The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value.

This error occurred when due to NOT assigning any value against a NOT NULL date column in SQL DB using EF and was resolved by assigning the same.

Hope this helps!

Return a value if no rows are found in Microsoft tSQL

@hai-phan's answer using LEFT JOIN is the key, but it might be a bit hard to follow. I had a complicated query that may also return nothing. I just simplified his answer to my need. It's easy to apply to query with many columns.

;WITH CTE AS (
  -- SELECT S.Id, ...
  -- FROM Sites S WHERE Id = @SiteId
  -- EXCEPT SOME CONDITION.
  -- Whatever your query is
)
SELECT CTE.* -- If you want something else instead of NULL, use COALESCE.
FROM (SELECT @SiteId AS ID) R
LEFT JOIN CTE ON CTE.Id = R.ID

Update: This answer on SqlServerCentral is the best. It utilizes this feature of MAX - "MAX returns NULL when there is no row to select."

SELECT ISNULL(MAX(value), 0) FROM table WHERE Id = @SiteId

Efficiency of Java "Double Brace Initialization"?

Here's the problem when I get too carried away with anonymous inner classes:

2009/05/27  16:35             1,602 DemoApp2$1.class
2009/05/27  16:35             1,976 DemoApp2$10.class
2009/05/27  16:35             1,919 DemoApp2$11.class
2009/05/27  16:35             2,404 DemoApp2$12.class
2009/05/27  16:35             1,197 DemoApp2$13.class

/* snip */

2009/05/27  16:35             1,953 DemoApp2$30.class
2009/05/27  16:35             1,910 DemoApp2$31.class
2009/05/27  16:35             2,007 DemoApp2$32.class
2009/05/27  16:35               926 DemoApp2$33$1$1.class
2009/05/27  16:35             4,104 DemoApp2$33$1.class
2009/05/27  16:35             2,849 DemoApp2$33.class
2009/05/27  16:35               926 DemoApp2$34$1$1.class
2009/05/27  16:35             4,234 DemoApp2$34$1.class
2009/05/27  16:35             2,849 DemoApp2$34.class

/* snip */

2009/05/27  16:35               614 DemoApp2$40.class
2009/05/27  16:35             2,344 DemoApp2$5.class
2009/05/27  16:35             1,551 DemoApp2$6.class
2009/05/27  16:35             1,604 DemoApp2$7.class
2009/05/27  16:35             1,809 DemoApp2$8.class
2009/05/27  16:35             2,022 DemoApp2$9.class

These are all classes which were generated when I was making a simple application, and used copious amounts of anonymous inner classes -- each class will be compiled into a separate class file.

The "double brace initialization", as already mentioned, is an anonymous inner class with an instance initialization block, which means that a new class is created for each "initialization", all for the purpose of usually making a single object.

Considering that the Java Virtual Machine will need to read all those classes when using them, that can lead to some time in the bytecode verfication process and such. Not to mention the increase in the needed disk space in order to store all those class files.

It seems as if there is a bit of overhead when utilizing double-brace initialization, so it's probably not such a good idea to go too overboard with it. But as Eddie has noted in the comments, it's not possible to be absolutely sure of the impact.


Just for reference, double brace initialization is the following:

List<String> list = new ArrayList<String>() {{
    add("Hello");
    add("World!");
}};

It looks like a "hidden" feature of Java, but it is just a rewrite of:

List<String> list = new ArrayList<String>() {

    // Instance initialization block
    {
        add("Hello");
        add("World!");
    }
};

So it's basically a instance initialization block that is part of an anonymous inner class.


Joshua Bloch's Collection Literals proposal for Project Coin was along the lines of:

List<Integer> intList = [1, 2, 3, 4];

Set<String> strSet = {"Apple", "Banana", "Cactus"};

Map<String, Integer> truthMap = { "answer" : 42 };

Sadly, it didn't make its way into neither Java 7 nor 8 and was shelved indefinitely.


Experiment

Here's the simple experiment I've tested -- make 1000 ArrayLists with the elements "Hello" and "World!" added to them via the add method, using the two methods:

Method 1: Double Brace Initialization

List<String> l = new ArrayList<String>() {{
  add("Hello");
  add("World!");
}};

Method 2: Instantiate an ArrayList and add

List<String> l = new ArrayList<String>();
l.add("Hello");
l.add("World!");

I created a simple program to write out a Java source file to perform 1000 initializations using the two methods:

Test 1:

class Test1 {
  public static void main(String[] s) {
    long st = System.currentTimeMillis();

    List<String> l0 = new ArrayList<String>() {{
      add("Hello");
      add("World!");
    }};

    List<String> l1 = new ArrayList<String>() {{
      add("Hello");
      add("World!");
    }};

    /* snip */

    List<String> l999 = new ArrayList<String>() {{
      add("Hello");
      add("World!");
    }};

    System.out.println(System.currentTimeMillis() - st);
  }
}

Test 2:

class Test2 {
  public static void main(String[] s) {
    long st = System.currentTimeMillis();

    List<String> l0 = new ArrayList<String>();
    l0.add("Hello");
    l0.add("World!");

    List<String> l1 = new ArrayList<String>();
    l1.add("Hello");
    l1.add("World!");

    /* snip */

    List<String> l999 = new ArrayList<String>();
    l999.add("Hello");
    l999.add("World!");

    System.out.println(System.currentTimeMillis() - st);
  }
}

Please note, that the elapsed time to initialize the 1000 ArrayLists and the 1000 anonymous inner classes extending ArrayList is checked using the System.currentTimeMillis, so the timer does not have a very high resolution. On my Windows system, the resolution is around 15-16 milliseconds.

The results for 10 runs of the two tests were the following:

Test1 Times (ms)           Test2 Times (ms)
----------------           ----------------
           187                          0
           203                          0
           203                          0
           188                          0
           188                          0
           187                          0
           203                          0
           188                          0
           188                          0
           203                          0

As can be seen, the double brace initialization has a noticeable execution time of around 190 ms.

Meanwhile, the ArrayList initialization execution time came out to be 0 ms. Of course, the timer resolution should be taken into account, but it is likely to be under 15 ms.

So, there seems to be a noticeable difference in the execution time of the two methods. It does appear that there is indeed some overhead in the two initialization methods.

And yes, there were 1000 .class files generated by compiling the Test1 double brace initialization test program.

How to decompile an APK or DEX file on Android platform?

You need Three Tools to decompile an APK file.

  1. Dex2jar - Tools to work with android .dex and java .class files

  2. ApkTool - A tool for reverse engineering Android apk files

  3. JD-GUI - Java Decompiler is a tools to decompile and analyze Java 5 “byte code” and the later versions.

for more how-to-use-dextojar. Hope this will help You and all! :)

Google Maps API v3: How do I dynamically change the marker icon?

You can also use a circle as a marker icon, for example:

var oMarker = new google.maps.Marker({
    position: latLng,
    sName: "Marker Name",
    map: map,
    icon: {
        path: google.maps.SymbolPath.CIRCLE,
        scale: 8.5,
        fillColor: "#F00",
        fillOpacity: 0.4,
        strokeWeight: 0.4
    },
});

and then, if you want to change the marker dynamically (like on mouseover), you can, for example:

oMarker.setIcon({
            path: google.maps.SymbolPath.CIRCLE,
            scale: 10,
            fillColor: "#00F",
            fillOpacity: 0.8,
            strokeWeight: 1
        })

Making a triangle shape using xml definitions?

Using the solution of Jacek Milewski I made an oriented down angle with a transparent background.

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <rotate
            android:fromDegrees="135"
            android:pivotX="65%"
            android:pivotY="20%"
            android:toDegrees="135"
            >
            <shape android:shape="rectangle">
                <stroke
                    android:width="1dp"
                    android:color="@color/blue"
                    />
                <solid android:color="@color/transparent" />
            </shape>
        </rotate>
    </item>
</layer-list>

You can change android:pivotX and android:pivotY to shift the angle.

Usage:

<ImageView
    android:layout_width="10dp"
    android:layout_height="10dp"
    android:src="@drawable/ic_angle_down"
    />

enter image description here

Parameters depend on the size of the image. For instance, if ImageView has size 100dp*80dp, you should use these constants:

<rotate
    android:fromDegrees="135"
    android:pivotX="64.5%"
    android:pivotY="19%"
    android:toDegrees="135"
    >

enter image description here

Application not picking up .css file (flask/python)

In jinja2 templates (which flask uses), use

href="{{ url_for('static', filename='mainpage.css')}}"

The static files are usually in the static folder, though, unless configured otherwise.

NVIDIA-SMI has failed because it couldn't communicate with the NVIDIA driver

I had to install the NVIDIA 367.57 driver and CUDA 7.5 with Tensorflow on the g2.2xlarge Ubuntu 14.04LTS instance. e.g. nvidia-graphics-drivers-367_367.57.orig.tar

Now the GRID K520 GPU is working while I train tensorflow models:

ubuntu@ip-10-0-1-70:~$ nvidia-smi
Sat Apr  1 18:03:32 2017       
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 367.57                 Driver Version: 367.57                    |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|===============================+======================+======================|
|   0  GRID K520           Off  | 0000:00:03.0     Off |                  N/A |
| N/A   39C    P8    43W / 125W |   3800MiB /  4036MiB |      0%      Default |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                       GPU Memory |
|  GPU       PID  Type  Process name                               Usage      |
|=============================================================================|
|    0      2254    C   python                                        3798MiB |
+-----------------------------------------------------------------------------+

ubuntu@ip-10-0-1-70:~/NVIDIA_CUDA-7.0_Samples/1_Utilities/deviceQuery$ ./deviceQuery 
./deviceQuery Starting...

 CUDA Device Query (Runtime API) version (CUDART static linking)

Detected 1 CUDA Capable device(s)

Device 0: "GRID K520"
  CUDA Driver Version / Runtime Version          8.0 / 7.0
  CUDA Capability Major/Minor version number:    3.0
  Total amount of global memory:                 4036 MBytes (4232052736 bytes)
  ( 8) Multiprocessors, (192) CUDA Cores/MP:     1536 CUDA Cores
  GPU Max Clock rate:                            797 MHz (0.80 GHz)
  Memory Clock rate:                             2500 Mhz
  Memory Bus Width:                              256-bit
  L2 Cache Size:                                 524288 bytes
  Maximum Texture Dimension Size (x,y,z)         1D=(65536), 2D=(65536, 65536), 3D=(4096, 4096, 4096)
  Maximum Layered 1D Texture Size, (num) layers  1D=(16384), 2048 layers
  Maximum Layered 2D Texture Size, (num) layers  2D=(16384, 16384), 2048 layers
  Total amount of constant memory:               65536 bytes
  Total amount of shared memory per block:       49152 bytes
  Total number of registers available per block: 65536
  Warp size:                                     32
  Maximum number of threads per multiprocessor:  2048
  Maximum number of threads per block:           1024
  Max dimension size of a thread block (x,y,z): (1024, 1024, 64)
  Max dimension size of a grid size    (x,y,z): (2147483647, 65535, 65535)
  Maximum memory pitch:                          2147483647 bytes
  Texture alignment:                             512 bytes
  Concurrent copy and kernel execution:          Yes with 2 copy engine(s)
  Run time limit on kernels:                     No
  Integrated GPU sharing Host Memory:            No
  Support host page-locked memory mapping:       Yes
  Alignment requirement for Surfaces:            Yes
  Device has ECC support:                        Disabled
  Device supports Unified Addressing (UVA):      Yes
  Device PCI Domain ID / Bus ID / location ID:   0 / 0 / 3
  Compute Mode:
     < Default (multiple host threads can use ::cudaSetDevice() with device simultaneously) >

deviceQuery, CUDA Driver = CUDART, CUDA Driver Version = 8.0, CUDA Runtime Version = 7.0, NumDevs = 1, Device0 = GRID K520
Result = PASS

How to get the last five characters of a string using Substring() in C#?

// Get first three characters
string sub = input.Substring(0, 3);
Console.WriteLine("Substring: {0}", sub); // Output One. 

string sub = input.Substring(6, 5);
Console.WriteLine("Substring: {0}", sub); //You'll get output: Three

Launching an application (.EXE) from C#?

Additionally you will want to use the Environment Variables for your paths if at all possible: http://en.wikipedia.org/wiki/Environment_variable#Default_Values_on_Microsoft_Windows

E.G.

  • %WINDIR% = Windows Directory
  • %APPDATA% = Application Data - Varies alot between Vista and XP.

There are many more check out the link for a longer list.

Rounded corner for textview in android

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:id="@android:id/background">
        <shape>
            <corners android:radius="5dp" />
            <solid android:color="#ffffff"/>

        </shape>
    </item>
</layer-list>

Angular2 Routing with Hashtag to page anchor

Unlike other answers I'd additionally also add focus() along with scrollIntoView(). Also I'm using setTimeout since it jumps to top otherwise when changing the URL. Not sure what was the reason for that but it seems setTimeout does the workaround.

Origin:

<a [routerLink] fragment="some-id" (click)="scrollIntoView('some-id')">Jump</a>

Destination:

<a id="some-id" tabindex="-1"></a>

Typescript:

scrollIntoView(anchorHash) {
    setTimeout(() => {
        const anchor = document.getElementById(anchorHash);
        if (anchor) {
            anchor.focus();
            anchor.scrollIntoView();
        }
    });
}

Returning value from Thread

With small modifications to your code, you can achieve it in a more generic way.

 final Handler responseHandler = new Handler(Looper.getMainLooper()){
            @Override
            public void handleMessage(Message msg) {
                //txtView.setText((String) msg.obj);
                Toast.makeText(MainActivity.this,
                        "Result from UIHandlerThread:"+(int)msg.obj,
                        Toast.LENGTH_LONG)
                        .show();
            }
        };

        HandlerThread handlerThread = new HandlerThread("UIHandlerThread"){
            public void run(){
                Integer a = 2;
                Message msg = new Message();
                msg.obj = a;
                responseHandler.sendMessage(msg);
                System.out.println(a);
            }
        };
        handlerThread.start();

Solution :

  1. Create a Handler in UI Thread,which is called as responseHandler
  2. Initialize this Handler from Looper of UI Thread.
  3. In HandlerThread, post message on this responseHandler
  4. handleMessgae shows a Toast with value received from message. This Message object is generic and you can send different type of attributes.

With this approach, you can send multiple values to UI thread at different point of times. You can run (post) many Runnable objects on this HandlerThread and each Runnable can set value in Message object, which can be received by UI Thread.

Roblox Admin Command Script

for i=1,#target do
    game.Players.target[i].Character:BreakJoints()
end

Is incorrect, if "target" contains "FakeNameHereSoNoStalkers" then the run code would be:

game.Players.target.1.Character:BreakJoints()

Which is completely incorrect.


c = game.Players:GetChildren()

Never use "Players:GetChildren()", it is not guaranteed to return only players.

Instead use:

c = Game.Players:GetPlayers()

if msg:lower()=="me" then
    table.insert(people, source)
    return people

Here you add the player's name in the list "people", where you in the other places adds the player object.


Fixed code:

local Admins = {"FakeNameHereSoNoStalkers"}

function Kill(Players)
    for i,Player in ipairs(Players) do
        if Player.Character then
            Player.Character:BreakJoints()
        end
    end
end

function IsAdmin(Player)
    for i,AdminName in ipairs(Admins) do
        if Player.Name:lower() == AdminName:lower() then return true end
    end
    return false
end

function GetPlayers(Player,Msg)
    local Targets = {}
    local Players = Game.Players:GetPlayers()

    if Msg:lower() == "me" then
        Targets = { Player }
    elseif Msg:lower() == "all" then
        Targets = Players
    elseif Msg:lower() == "others" then
        for i,Plr in ipairs(Players) do
            if Plr ~= Player then
                table.insert(Targets,Plr)
            end
        end
    else
        for i,Plr in ipairs(Players) do
            if Plr.Name:lower():sub(1,Msg:len()) == Msg then
                table.insert(Targets,Plr)
            end
        end
    end
    return Targets
end

Game.Players.PlayerAdded:connect(function(Player)
    if IsAdmin(Player) then
        Player.Chatted:connect(function(Msg)
            if Msg:lower():sub(1,6) == ":kill " then
                Kill(GetPlayers(Player,Msg:sub(7)))
            end
        end)
    end
end)

How to display raw JSON data on a HTML page

JSON in any HTML tag except <script> tag would be a mere text. Thus it's like you add a story to your HTML page.

However, about formatting, that's another matter. I guess you should change the title of your question.

Take a look at this question. Also see this page.

save a pandas.Series histogram plot to file

You can use ax.figure.savefig():

import pandas as pd

s = pd.Series([0, 1])
ax = s.plot.hist()
ax.figure.savefig('demo-file.pdf')

This has no practical benefit over ax.get_figure().savefig() as suggested in Philip Cloud's answer, so you can pick the option you find the most aesthetically pleasing. In fact, get_figure() simply returns self.figure:

# Source from snippet linked above
def get_figure(self):
    """Return the `.Figure` instance the artist belongs to."""
    return self.figure

ORA-12560: TNS:protocol adaptor error

In my case (for OracleExpress) the service was running, but I got this issue when trying to access the database via sqlplus without connection identifier:

sqlplus sys/mypassword as sysdba  

To make it work I needed to add the connection identifier (XE for Oracle Express), so following command worked ok:

sqlplus sys/mypassword@XE as sysdba

If you still get ORA-12560, make sure you can ping the XE service. Use:

tnsping XE

And you should get OK message along with full connection string (tnsping command is located in oracle's installation dir: [oracle express installation dir]\app\oracle\product\11.2.0\server\bin). If you can not ping make sure your tnsnames.ora file is reachable for sqlplus. You might need to set TNS_ADMIN environment variable pointing to your ADMIN directory, where the file is located, for example:

TNS_ADMIN=[oracle express installation dir]\app\oracle\product\11.2.0\server\network\ADMIN

JavaScript "cannot read property "bar" of undefined

If an object's property may refer to some other object then you can test that for undefined before trying to use its properties:

if (thing && thing.foo)
   alert(thing.foo.bar);

I could update my answer to better reflect your situation if you show some actual code, but possibly something like this:

function someFunc(parameterName) {
   if (parameterName && parameterName.foo)
       alert(parameterName.foo.bar);
}

Clearing _POST array fully

Yes, that is fine. $_POST is just another variable, except it has (super)global scope.

$_POST = array();

...will be quite enough. The loop is useless. It's probably best to keep it as an array rather than unset it, in case other files are attempting to read it and assuming it is an array.

SQL to Query text in access with an apostrophe in it

...better is declare the name as varible ,and ask before if thereis a apostrophe in the string:

e.g.:

DIM YourName string

YourName = "Daniel O'Neal"

  If InStr(YourName, "'") Then
      SELECT * FROM tblStudents WHERE [name]  Like """ Your Name """ ;
   else
      SELECT * FROM tblStudents WHERE [name] Like '" Your Name "' ;       
  endif

How to delete shared preferences data from App in Android

As of API 24 (Nougat) you can just do:

context.deleteSharedPreferences("YOUR_PREFS");

However, there is no backward compatibility, so if you're supporting anything less than 24, stick with:

context.getSharedPreferences("YOUR_PREFS", Context.MODE_PRIVATE).edit().clear().apply(); 

How can I access "static" class variables within class methods in Python?

bar is your static variable and you can access it using Foo.bar.

Basically, you need to qualify your static variable with Class name.

Rewrite all requests to index.php with nginx

Flat and simple config without rewrite, can work in some cases:

location / {
    fastcgi_pass unix:/var/run/php5-fpm.sock;
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME /home/webuser/site/index.php;
}

Replace a value in a data frame based on a conditional (`if`) statement

As the data you show are factors, it complicates things a little bit. @diliop's Answer approaches the problem by converting to nm to a character variable. To get back to the original factors a further step is required.

An alternative is to manipulate the levels of the factor in place.

> lev <- with(junk, levels(nm))
> lev[lev == "B"] <- "b"
> junk2 <- within(junk, levels(nm) <- lev)
> junk2
   nm val
1   A   a
2   b   b
3   C   c
4   D   d
5   A   e
6   b   f
7   C   g
8   D   h
9   A   i
10  b   j
11  C   k
12  D   l

That is quite simple and I often forget that there is a replacement function for levels().

Edit: As noted by @Seth in the comments, this can be done in a one-liner, without loss of clarity:

within(junk, levels(nm)[levels(nm) == "B"] <- "b")

Proxy setting for R

I had the same problem at my office and I solved it adding the proxy in the destination of the R shortcut; clik on right button of the R icon, preferences, and in the destination field add

"C:\Program Files\R\your_R_version\bin\Rgui.exe" http_proxy=http://user_id:passwod@your_proxy:your_port/

Be sure to put the directory where you have the R program installed. That works for me. Hope this help.

Java NoSuchAlgorithmException - SunJSSE, sun.security.ssl.SSLContextImpl$DefaultSSLContext

Well after doing some more searching I discovered the error may be related to other issues as invalid keystores, passwords etc.

I then remembered that I had set two VM arguments for when I was testing SSL for my network connectivity.

I removed the following VM arguments to fix the problem:

-Djavax.net.ssl.keyStore=mySrvKeystore -Djavax.net.ssl.keyStorePassword=123456

Note: this keystore no longer exists so that's probably why the Exception.

creating array without declaring the size - java

You might be looking for a List? Either LinkedList or ArrayList are good classes to take a look at. You can then call toArray() to get the list as an array.

How can I read the contents of an URL with Python?

We can read website html content as below :

from urllib.request import urlopen
response = urlopen('http://google.com/')
html = response.read()
print(html)

jQuery ajax request with json response, how to?

Connect your javascript clientside controller and php serverside controller using sending and receiving opcodes with binded data. So your php code can send as response functional delta for js recepient/listener

see https://github.com/ArtNazarov/LazyJs

Sorry for my bad English

Raise an error manually in T-SQL to jump to BEGIN CATCH block

You could use THROW (available in SQL Server 2012+):

THROW 50000, 'Your custom error message', 1
THROW <error_number>, <message>, <state>

MSDN THROW (Transact-SQL)

Differences Between RAISERROR and THROW in Sql Server

Disable vertical scroll bar on div overflow: auto

overflow: auto;
overflow-y: hidden;

For IE8: -ms-overflow-y: hidden;

Or Else :

To hide X:

<div style="height:150x; width:450px; overflow-x:hidden; overflow-y: scroll; padding-bottom:10px;"></div>

To hide Y:

<div style="height:150px; width:450px; overflow-x:scroll ; overflow-y: hidden; padding-bottom:10px;"></div>

How do you do natural logs (e.g. "ln()") with numpy in Python?

Correct, np.log(x) is the Natural Log (base e log) of x.

For other bases, remember this law of logs: log-b(x) = log-k(x) / log-k(b) where log-b is the log in some arbitrary base b, and log-k is the log in base k, e.g.

here k = e

l = np.log(x) / np.log(100)

and l is the log-base-100 of x

ALTER COLUMN in sqlite

There's no ALTER COLUMN in sqlite.

I believe your only option is to:

  • Rename the table to a temporary name
  • Create a new table without the NOT NULL constraint
  • Copy the content of the old table to the new one
  • Remove the old table

This other Stackoverflow answer explains the process in details

C++ cout hex values?

std::hex is defined in <ios> which is included by <iostream>. But to use things like std::setprecision/std::setw/std::setfill/etc you have to include <iomanip>.