Programs & Examples On #Tomcat7

Version 7.x (June 2010) of the Apache Tomcat servlet container. Use only if your question is specifically related to features of this version.

The absolute uri: http://java.sun.com/jsp/jstl/core cannot be resolved in either web.xml or the jar files deployed with this application

The error in question may also be caused by disabled JarScanner in tomcat/conf/context.xml.

See also Upgrade from Tomcat 8.0.39 to 8.0.41 results in 'failed to scan' errors.

<JarScanner scanManifest="false"/> allows to avoid both problems.

How to set the context path of a web application in Tomcat 7.0

I faced this problem for one month,Putting context tag inside server.xml is not safe it affect context elements deploying for all other host ,for big apps it take connection errors also not good isolation for example you may access other sites by folder name domain2.com/domain1Folder !! also database session connections loaded twice ! the other way is put ROOT.xml file that has context tag with full path such :

 <Context path="" docBase="/var/lib/tomcat7/webapps/ROOT" />

in conf/catalina/webappsfoldername and deploy war file as ROOT.war inside webappsfoldername and also specify host such

 <Host name="domianname"  appBase="webapps2" unpackWARs="true"  autoDeploy="true"  xmlValidation="false" xmlNamespaceAware="false" >

        <Logger className="org.apache.catalina.logger.FileLogger"
               directory="logs"  prefix="localhost_log." suffix=".txt"
          timestamp="true"/>
</Host>

In this approach also for same type apps user sessions has not good isolation ! you may inside app1 if app1 same as app2 you may after login by server side session automatically can login to app2 ?! So you have to keep users session in client side cache and not with jsessionid ! we may change engine name from localhost to solve it. but let say playing with tomcat need more time than play with other cats!

I cannot access tomcat admin console?

If you are running tomcat from eclipse (probably problem exists with another IDEs), it could have a different configuration- not based on files .

The solution is to edit tomcat users file, as you wrote, and then start tomcat from command prompt with

{tomcat-directory}/bin/startup

java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener

If you are using IntelliJ IDEA, and deploy application on Tomcat Server, it says: Under File menu -> select project Structure -> click artifact -> select your jars and right click -> put in WEB\lib -> restart serverenter image description here

How do I use Apache tomcat 7 built in Host Manager gui?

Well if you are using Netbeans in Linux, then you should look for the tomcat-user.xml in

/home/Username/.netbeans/8.0/apache-tomcat-8.0.3.0_base/conf (its called Catalina Base and is often hidden)

instead of the apacahe installation directory.

open tomcat-user.xml inside that folder, uncomment the user and roles and add/replace the following line.

    <user username="tomcat" password="tomcat" roles="tomcat,admin,admin-gui,manager,manager-gui"/>

restart the server . That's all

How to increase number of threads in tomcat thread pool?

From Tomcat Documentation

maxConnections When this number has been reached, the server will accept, but not process, one further connection. once the limit has been reached, the operating system may still accept connections based on the acceptCount setting. (The maximum queue length for incoming connection requests when all possible request processing threads are in use. Any requests received when the queue is full will be refused. The default value is 100.) For BIO the default is the value of maxThreads unless an Executor is used in which case the default will be the value of maxThreads from the executor. For NIO and NIO2 the default is 10000. For APR/native, the default is 8192. Note that for APR/native on Windows, the configured value will be reduced to the highest multiple of 1024 that is less than or equal to maxConnections. This is done for performance reasons.

maxThreads
The maximum number of request processing threads to be created by this Connector, which therefore determines the maximum number of simultaneous requests that can be handled. If not specified, this attribute is set to 200. If an executor is associated with this connector, this attribute is ignored as the connector will execute tasks using the executor rather than an internal thread pool.

"starting Tomcat server 7 at localhost has encountered a prob"

Go to web.xml add <element> before <web-app> and close </element> after </web-app>

should be somethings like this

<?xml version="1.0" encoding="UTF-8"?>

<element>

<web-app>

....
</web-app>

</element>

How to fix: "No suitable driver found for jdbc:mysql://localhost/dbname" error when using pools?

Since no one gave this answer, I would also like to add that, you can just add the jdbc driver file(mysql-connector-java-5.1.27-bin.jar in my case) to the lib folder of your server(Tomcat in my case). Restart the server and it should work.

At least one JAR was scanned for TLDs yet contained no TLDs

For me I was getting the problem when deploying a geoserver WAR into tomcat 7

To fix it, I was on Java 7 and upgrading to Java 8.

This is running under a docker container. Tomcat 7.0.75 + Java 8 + Geos 2.10.2

java.lang.ClassNotFoundException: HttpServletRequest

Thanks guys. All above failed except this that deleted all content from the file C:\Users\debasish\workspace\.metadata\.plugins\org.eclipse.wst.server.core then creating server again.

But delete server first before deleting those file contents.

jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class

To fix it, set the scope to provided. This tells Maven use code servlet-api.jar for compiling and testing only, but NOT include it in the WAR file. The deployed container will “provide” the servlet-api.jar at runtime.

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>servlet-api</artifactId>
    <version>2.5</version>
    <scope>provided</scope>
</dependency>

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

I have same problem but in my case By mistake I added a context in server.xml ($Tomcat_Install_Dir/conf/) and doesn't deployed corresponing war in webapps($Tomcat_Install_Dir/webapps). As I removed that context and restarted tomcat it working fine.

How do I increase memory on Tomcat 7 when running as a Windows Service?

Assuming that you've downloaded and installed Tomcat as Windows Service Installer exe file from the Tomcat homepage, then check the Apache feather icon in the systray (or when absent, run Monitor Tomcat from the start menu). Doubleclick the feather icon and go to the Java tab. There you can configure the memory.

enter image description here

Restart the service to let the changes take effect.

Name [jdbc/mydb] is not bound in this Context

You need a ResourceLink in your META-INF/context.xml file to make the global resource available to the web application.

 <ResourceLink name="jdbc/mydb"
             global="jdbc/mydb"
              type="javax.sql.DataSource" />

HTTP Status 500 - Servlet.init() for servlet Dispatcher threw exception

You map your dispatcher on *.do:

<servlet-mapping>
   <servlet-name>Dispatcher</servlet-name>
   <url-pattern>*.do</url-pattern>
</servlet-mapping>

but your controller is mapped on an url without .do:

@RequestMapping("/editPresPage")

Try changing this to:

@RequestMapping("/editPresPage.do")

How to Detect cause of 503 Service Temporarily Unavailable error and handle it?

There is of course some apache log files. Search in your apache configuration files for 'Log' keyword, you'll certainly find plenty of them. Depending on your OS and installation places may vary (in a Typical Linux server it would be /var/log/apache2/[access|error].log).

Having a 503 error in Apache usually means the proxied page/service is not available. I assume you're using tomcat and that means tomcat is either not responding to apache (timeout?) or not even available (down? crashed?). So chances are that it's a configuration error in the way to connect apache and tomcat or an application inside tomcat that is not even sending a response for apache.

Sometimes, in production servers, it can as well be that you get too much traffic for the tomcat server, apache handle more request than the proxyied service (tomcat) can accept so the backend became unavailable.

How to fix JSP compiler warning: one JAR was scanned for TLDs yet contained no TLDs?

If the extra entries in the log bother you but an extra second of start-up time doesn't, just add this to your logging.properties and forget about it:

org.apache.jasper.servlet.TldScanner.level = WARNING

Tomcat 7: How to set initial heap size correctly?

setenv.sh is better, because you can easily port such configuration from one machine to another, or from one Tomcat version to another. catalina.sh changes from one version of Tomcat to another. But you can keep your setenv.sh unchanged with any version of Tomcat.

Another advantage is, that it is easier to track the history of your changes if you add it to your backup or versioning system. If you look how you setenv.sh changes along the history, you will see only your own changes. Whereas if you use catalina.sh, you will always see not only your changes, but also changes that came with each newer version of the Tomcat.

Tomcat Server not starting with in 45 seconds

URL pattern of <servlet-mapping>:

Check project explorer → Deployment descriptor → Servlet Mapping → check that all mapping present in controller package. ref. image as below:

shop project ref

if there is any mapping not available, Then remove that <servlet> and <servlet-mapping> tag in web.xml.

Installing Tomcat 7 as Service on Windows Server 2008

I have spent a couple of hours looking for the magic configuration to get Tomcat 7 running as a service on Windows Server 2008... no luck.

I do have a solution though.

My install of Tomcat 7 works just fine if I just jump into a console window and run...

C:\apache-tomcat-7.0.26\bin\start.bat

At this point another console window pops up and tails the logs (tail meaning show the server logs as they happen).

SOLUTION

Run the start.bat file as a Scheduled Task.

  1. Start Menu > Accessories > System Tools > Task Scheduler

  2. In the Actions Window: Create Basic Task...

  3. Name the task something like "Start Tomcat 7" or something that makes sense a year from now.

  4. Click Next >

  5. Trigger should be set to "When the computer starts"

  6. Click Next >

  7. Action should be set to "Start a program"

  8. Click Next >

  9. Program/script: should be set to the location of the startup.bat file.

  10. Click Next >

  11. Click Finish

  12. IF YOUR SERVER IS NOT BEING USED: Reboot your server to test this functionality

INFO: No Spring WebApplicationInitializer types detected on classpath

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>          
    <configuration>
        <source>1.8</source>
        <target>1.8</target>
    </configuration>
 </plugin>

This is the important plugin that should be in pom.xml. I spent my two days debugging and researching. This was the solution. This is Apache plugin to tell maven to use the the given Compiler.

How to set level logging to DEBUG in Tomcat?

Firstly, the level name to use is FINE, not DEBUG. Let's assume for a minute that DEBUG is actually valid, as it makes the following explanation make a bit more sense...

In the Handler specific properties section, you're setting the logging level for those handlers to DEBUG. This means the handlers will handle any log messages with the DEBUG level or higher. It doesn't necessarily mean any DEBUG messages are actually getting passed to the handlers.

In the Facility specific properties section, you're setting the logging level for a few explicitly-named loggers to DEBUG. For those loggers, anything at level DEBUG or above will get passed to the handlers.

The default logging level is INFO, and apart from the loggers mentioned in the Facility specific properties section, all loggers will have that level.

If you want to see all FINE messages, add this:

.level = FINE

However, this will generate a vast quantity of log messages. It's probably more useful to set the logging level for your code:

your.package.level = FINE

See the Tomcat 6/Tomcat 7 logging documentation for more information. The example logging.properties file shown there uses FINE instead of DEBUG:

...
1catalina.org.apache.juli.FileHandler.level = FINE
...

and also gives you examples of setting additional logging levels:

# For example, set the com.xyz.foo logger to only log SEVERE
# messages:
#org.apache.catalina.startup.ContextConfig.level = FINE
#org.apache.catalina.startup.HostConfig.level = FINE
#org.apache.catalina.session.ManagerBase.level = FINE

Tomcat 7.0.43 "INFO: Error parsing HTTP request header"

If there are too many cookies cached, it breaks the server (the size of a request header is too big!). Clearing the cookies can fix this issue as well.

Could not load the Tomcat server configuration

I've just been encountering a very similar issue in Ubuntu while trying to get Eclipse Mars and Tomcat7 integrated because Eclipse was expecting the tomcat configuration files etc to be all in the same location, and with the necessary permissions to be able to change those files.

The following instructions from this blog article helped me in the end:

cd /usr/share/tomcat7
sudo ln -s /var/lib/tomcat7/conf conf
sudo ln -s /var/log/tomcat7 log
sudo ln -s /etc/tomcat7/policy.d/03catalina.policy conf/catalina.policy
sudo chmod -R a+rwx /usr/share/tomcat7/conf

java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver

team! For execute SQL-query from your Servlet you should add JDBC jar library in folder

WEB-INF/lib

After this you could call driver, example :

Class.forName("oracle.jdbc.OracleDriver");

Now Y can use connection to DB-server

==> 73!

How do I find the value of $CATALINA_HOME?

Tomcat can tell you in several ways. Here's the easiest:

 $ /path/to/catalina.sh version
Using CATALINA_BASE:   /usr/local/apache-tomcat-7.0.29
Using CATALINA_HOME:   /usr/local/apache-tomcat-7.0.29
Using CATALINA_TMPDIR: /usr/local/apache-tomcat-7.0.29/temp
Using JRE_HOME:        /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Home
Using CLASSPATH:       /usr/local/apache-tomcat-7.0.29/bin/bootstrap.jar:/usr/local/apache-tomcat-7.0.29/bin/tomcat-juli.jar
Server version: Apache Tomcat/7.0.29
Server built:   Jul 3 2012 11:31:52
Server number:  7.0.29.0
OS Name:        Mac OS X
OS Version:     10.7.4
Architecture:   x86_64
JVM Version:    1.6.0_33-b03-424-11M3720
JVM Vendor:     Apple Inc.

If you don't know where catalina.sh is (or it never gets called), you can usually find it via ps:

$ ps aux | grep catalina
chris            930   0.0  3.1  2987336 258328 s000  S    Wed01PM   2:29.43 /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home/bin/java -Dnop -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager -Djava.library.path=/usr/local/apache-tomcat-7.0.29/lib -Djava.endorsed.dirs=/usr/local/apache-tomcat-7.0.29/endorsed -classpath /usr/local/apache-tomcat-7.0.29/bin/bootstrap.jar:/usr/local/apache-tomcat-7.0.29/bin/tomcat-juli.jar -Dcatalina.base=/Users/chris/blah/blah -Dcatalina.home=/usr/local/apache-tomcat-7.0.29 -Djava.io.tmpdir=/Users/chris/blah/blah/temp org.apache.catalina.startup.Bootstrap start

From the ps output, you can see both catalina.home and catalina.base. catalina.home is where the Tomcat base files are installed, and catalina.base is where the running configuration of Tomcat exists. These are often set to the same value unless you have configured your Tomcat for multiple (configuration) instances to be launched from a single Tomcat base install.

You can also interrogate the JVM directly if you can't find it in a ps listing:

$ jinfo -sysprops 930 | grep catalina
Attaching to process ID 930, please wait...
Debugger attached successfully.
Server compiler detected.
JVM version is 20.8-b03-424
catalina.base = /Users/chris/blah/blah
[...]
catalina.home = /usr/local/apache-tomcat-7.0.29

If you can't manage that, you can always try to write a JSP that dumps the values of the two system properties catalina.home and catalina.base.

ipad safari: disable scrolling, and bounce effect?

You can also change the position of the body/html to fixed:

body,
html {
  position: fixed;
}

How To Create Table with Identity Column

Unique key allows max 2 NULL values. Explaination:

create table teppp
(
id int identity(1,1) primary key,
name varchar(10 )unique,
addresss varchar(10)
)

insert into teppp ( name,addresss) values ('','address1')
insert into teppp ( name,addresss) values ('NULL','address2')
insert into teppp ( addresss) values ('address3')

select * from teppp
null string , address1
NULL,address2
NULL,address3

If you try inserting same values as below:

insert into teppp ( name,addresss) values ('','address4')
insert into teppp ( name,addresss) values ('NULL','address5')
insert into teppp ( addresss) values ('address6')

Every time you will get error like:

Violation of UNIQUE KEY constraint 'UQ__teppp__72E12F1B2E1BDC42'. Cannot insert duplicate key in object 'dbo.teppp'.
The statement has been terminated.

Number of processors/cores in command line

On newer kernels you could also possibly use the the /sys/devices/system/cpu/ interface to get a bit more information:

$ ls /sys/devices/system/cpu/
cpu0  cpufreq  kernel_max  offline  possible  present  release
cpu1  cpuidle  modalias    online   power     probe    uevent
$ cat /sys/devices/system/cpu/kernel_max 
255
$ cat /sys/devices/system/cpu/offline 
2-63
$ cat /sys/devices/system/cpu/possible 
0-63
$ cat /sys/devices/system/cpu/present 
0-1
$ cat /sys/devices/system/cpu/online 
0-1

See the official docs for more information on what all these mean.

Connecting PostgreSQL 9.2.1 with Hibernate

Yes by using spring-boot with hibernate configuration files we can persist the data to the database. keep hibernating .cfg.xml in your src/main/resources folder for reading the configurations related to database.

enter image description here

Font is not available to the JVM with Jasper Reports

Try adding the line

net.sf.jasperreports.awt.ignore.missing.font=true

to your jasperreports.properties file.

Jasper stops finding one font

Regex Email validation

This code will help to validate email id using regex expression in c#.Net..it is easy to use

if (!System.Text.RegularExpressions.Regex.IsMatch("<Email String Here>", @"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$"))
        {
            MessageBox.show("Incorrect Email Id.");
        }

How to get JSON Key and Value?

$.each(result, function(key, value) {
  console.log(key+ ':' + value);
});

How do I open a new fragment from another fragment?

Use this,

AppCompatActivity activity = (AppCompatActivity) view.getContext();
Fragment myFragment = new MyFragment();
activity.getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, myFragment).addToBackStack(null).commit();

Converting any object to a byte array in java

What you want to do is called "serialization". There are several ways of doing it, but if you don't need anything fancy I think using the standard Java object serialization would do just fine.

Perhaps you could use something like this?

package com.example;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class Serializer {

    public static byte[] serialize(Object obj) throws IOException {
        try(ByteArrayOutputStream b = new ByteArrayOutputStream()){
            try(ObjectOutputStream o = new ObjectOutputStream(b)){
                o.writeObject(obj);
            }
            return b.toByteArray();
        }
    }

    public static Object deserialize(byte[] bytes) throws IOException, ClassNotFoundException {
        try(ByteArrayInputStream b = new ByteArrayInputStream(bytes)){
            try(ObjectInputStream o = new ObjectInputStream(b)){
                return o.readObject();
            }
        }
    }

}

There are several improvements to this that can be done. Not in the least the fact that you can only read/write one object per byte array, which might or might not be what you want.

Note that "Only objects that support the java.io.Serializable interface can be written to streams" (see java.io.ObjectOutputStream).

Since you might run into it, the continuous allocation and resizing of the java.io.ByteArrayOutputStream might turn out to be quite the bottle neck. Depending on your threading model you might want to consider reusing some of the objects.

For serialization of objects that do not implement the Serializable interface you either need to write your own serializer, for example using the read*/write* methods of java.io.DataOutputStream and the get*/put* methods of java.nio.ByteBuffer perhaps together with reflection, or pull in a third party dependency.

This site has a list and performance comparison of some serialization frameworks. Looking at the APIs it seems Kryo might fit what you need.

Signed to unsigned conversion in C - is it always safe?

As was previously answered, you can cast back and forth between signed and unsigned without a problem. The border case for signed integers is -1 (0xFFFFFFFF). Try adding and subtracting from that and you'll find that you can cast back and have it be correct.

However, if you are going to be casting back and forth, I would strongly advise naming your variables such that it is clear what type they are, eg:

int iValue, iResult;
unsigned int uValue, uResult;

It is far too easy to get distracted by more important issues and forget which variable is what type if they are named without a hint. You don't want to cast to an unsigned and then use that as an array index.

Android requires compiler compliance level 5.0 or 6.0. Found '1.7' instead. Please use Android Tools > Fix Project Properties

That isn't the problem, Jack. Android SDK isn't x64, but works ok with x64 jvm (and x64 eclipse IDE).

As helios said, you must set project compatibility to Java 5.0 or Java 6.0.

To do that, 2 options:

  1. Right-click on your project and select "Android Tools -> Fix Project Properties" (if this din't work, try second option)
  2. Right-click on your project and select "Properties -> Java Compiler", check "Enable project specific settings" and select 1.5 or 1.6 from "Compiler compliance settings" select box.

Getting Unexpected Token Export

My two cents

Export

ES6

myClass.js

export class MyClass1 {
}
export class MyClass2 {
}

other.js

import { MyClass1, MyClass2 } from './myClass';

CommonJS Alternative

myClass.js

class MyClass1 {
}
class MyClass2 {
}
module.exports = { MyClass1, MyClass2 }
// or
// exports = { MyClass1, MyClass2 };

other.js

const { MyClass1, MyClass2 } = require('./myClass');

Export Default

ES6

myClass.js

export default class MyClass {
}

other.js

import MyClass from './myClass';

CommonJS Alternative

myClass.js

module.exports = class MyClass1 {
}

other.js

const MyClass = require('./myClass');

Hope this helps

Writing binary number system in C code

Standard C doesn't define binary constants. There's a GNU (I believe) extension though (among popular compilers, clang adapts it as well): the 0b prefix:

int foo = 0b1010;

If you want to stick with standard C, then there's an option: you can combine a macro and a function to create an almost readable "binary constant" feature:

#define B(x) S_to_binary_(#x)

static inline unsigned long long S_to_binary_(const char *s)
{
        unsigned long long i = 0;
        while (*s) {
                i <<= 1;
                i += *s++ - '0';
        }
        return i;
}

And then you can use it like this:

int foo = B(1010);

If you turn on heavy compiler optimizations, the compiler will most likely eliminate the function call completely (constant folding) or will at least inline it, so this won't even be a performance issue.

Proof:

The following code:

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <string.h>


#define B(x) S_to_binary_(#x)

static inline unsigned long long S_to_binary_(const char *s)
{
    unsigned long long i = 0;
    while (*s) {
        i <<= 1;
        i += *s++ - '0';
    }
    return i;
}

int main()
{
    int foo = B(001100101);

    printf("%d\n", foo);

    return 0;
}

has been compiled using clang -o baz.S baz.c -Wall -O3 -S, and it produced the following assembly:

    .section    __TEXT,__text,regular,pure_instructions
    .globl  _main
    .align  4, 0x90
_main:                                  ## @main
    .cfi_startproc
## BB#0:
    pushq   %rbp
Ltmp2:
    .cfi_def_cfa_offset 16
Ltmp3:
    .cfi_offset %rbp, -16
    movq    %rsp, %rbp
Ltmp4:
    .cfi_def_cfa_register %rbp
    leaq    L_.str1(%rip), %rdi
    movl    $101, %esi               ## <= This line!
    xorb    %al, %al
    callq   _printf
    xorl    %eax, %eax
    popq    %rbp
    ret
    .cfi_endproc

    .section    __TEXT,__cstring,cstring_literals
L_.str1:                                ## @.str1
    .asciz   "%d\n"


.subsections_via_symbols

So clang completely eliminated the call to the function, and replaced its return value with 101. Neat, huh?

Reason for Column is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause

"All I want to do is join the tables and then group all the employees in a particular location together."

It sounds like what you want is for the output of the SQL statement to list every employee in the company, but first all the people in the Anaheim office, then the people in the Buffalo office, then the people in the Cleveland office (A, B, C, get it, obviously I don't know what locations you have).

In that case, lose the GROUP BY statement. All you need is ORDER BY loc.LocationID

How can I retrieve Id of inserted entity using Entity framework?

The object you're saving should have a correct Id after propagating changes into database.

Send cookies with curl

.example.com TRUE / FALSE 1560211200 MY_VARIABLE MY_VALUE

The cookies file format apparently consists of a line per cookie and each line consists of the following seven tab-delimited fields:

  • domain - The domain that created AND that can read the variable.
  • flag - A TRUE/FALSE value indicating if all machines within a given domain can access the variable. This value is set automatically by the browser, depending on the value you set for domain.
  • path - The path within the domain that the variable is valid for.
  • secure - A TRUE/FALSE value indicating if a secure connection with the domain is needed to access the variable.
  • expiration - The UNIX time that the variable will expire on. UNIX time is defined as the number of seconds since Jan 1, 1970 00:00:00 GMT.
  • name - The name of the variable.
  • value - The value of the variable.

From http://www.cookiecentral.com/faq/#3.5

What does "javascript:void(0)" mean?

A link must have an href target to be specified to enable it to be a usable display object.

Most browsers will not parse advanced JavaScript in the href of an <a> element, for example:

<a href="javascript:var el = document.getElementById('foo');">Get element</a>

Because the href tag in most browsers does not allow whitespace or will convert whitespace to %20 (the HEX code for space), the JavaScript interpreter will run into multiple errors.

So if you want to use an <a> element's href to execute inline JavaScript, you must specify a valid value for href first that isn't too complex (doesn't contain whitespace), and then provide the JavaScript in an event attribute tag like onClick, onMouseOver, onMouseOut, etc.

The typical answer is to do something like this:

<a href="#" onclick="var el = document.getElementById('foo');">Get element</a>

This works fine but it makes the page scroll to the top because the # in the href tells the browser to do this.

Placing a # in the <a> element's href specifies the root anchor, which is by default the top of the page, but you can specify a different location by specifying the name attribute inside an <a> element.

<a name="middleOfPage"></a>

You can then change your <a> element's href to jump to middleOfPage and execute the JavaScript in the onClick event:

<a href="#middleOfPage" onclick="var el = document.getElementById('foo');">Get element</a>

There will be many times where you do not want that link jumping around, so you can do two things:

<a href="#thisLinkName" name="thisLinkCame" onclick="var elem = document.getElementById('foo');">Get element</a>

Now it will go nowhere when clicked, but it could cause the page to re-centre itself from its current viewport.

The best way to use in-line javascript using an <a> element's href, but without having to do any of the above is JavaScript:void(0);:

<a href="javascript:void(0);" onclick="var el = document.getElementById('foo');">Get element</a>

This tells the browser no to go anywhere, but instead execute the JavaScript:void(0); function in the href because it contains no whitespace, and will not be parsed as a URL. It will instead be run by the compiler.

void is a keyword which, when supplied with a parameter of 0 returns undefined, which does not use any more resources to handle a return value that would occur without specifying the 0 (it is more memory-management/performance friendly).

The next thing that happens is the onClick gets executed. The page does not move, nothing happens display-wise.

How to programmatically log out from Facebook SDK 3.0 without using Facebook login/logout button?

This method will help you to logout from facebook programmatically in android

/**
 * Logout From Facebook 
 */
public static void callFacebookLogout(Context context) {
    Session session = Session.getActiveSession();
    if (session != null) {

        if (!session.isClosed()) {
            session.closeAndClearTokenInformation();
            //clear your preferences if saved
        }
    } else {

        session = new Session(context);
        Session.setActiveSession(session);

        session.closeAndClearTokenInformation();
            //clear your preferences if saved

    }

}

Run javascript function when user finishes typing instead of on key up?

So, I'm going to guess finish typing means you just stop for a while, say 5 seconds. So with that in mind, lets start a timer when the user releases a key and clear it when they press one. I decided the input in question will be #myInput.

Making a few assumptions...

//setup before functions
var typingTimer;                //timer identifier
var doneTypingInterval = 5000;  //time in ms, 5 second for example
var $input = $('#myInput');

//on keyup, start the countdown
$input.on('keyup', function () {
  clearTimeout(typingTimer);
  typingTimer = setTimeout(doneTyping, doneTypingInterval);
});

//on keydown, clear the countdown 
$input.on('keydown', function () {
  clearTimeout(typingTimer);
});

//user is "finished typing," do something
function doneTyping () {
  //do something
}

SQL query, store result of SELECT in local variable

You can create table variables:

DECLARE @result1 TABLE (a INT, b INT, c INT)

INSERT INTO @result1
SELECT a, b, c
FROM table1

SELECT a AS val FROM @result1
UNION
SELECT b AS val FROM @result1
UNION
SELECT c AS val FROM @result1

This should be fine for what you need.

What requests do browsers' "F5" and "Ctrl + F5" refreshes generate?

At least in Firefox (v3.5), cache seems to be disabled rather than simply cleared. If there are multiple instances of the same image on a page, it will be transferred multiple times. That is also the case for img tags that are added subsequently via Ajax/JavaScript.

So in case you're wondering why the browser keeps downloading the same little icon a few hundred times on your auto-refresh Ajax site, it's because you initially loaded the page using CTRL-F5.

Most efficient way to get table row count

Couldn't you just create a record in a separate table or whatever with a column called Users and UPDATE it with the last inserted id on User Registration?

Then you would just check this field with a simple query.

It might be rough but it would work perfectly.

Get name of current class?

EDIT: Yes, you can; but you have to cheat: The currently running class name is present on the call stack, and the traceback module allows you to access the stack.

>>> import traceback
>>> def get_input(class_name):
...     return class_name.encode('rot13')
... 
>>> class foo(object):
...      _name = traceback.extract_stack()[-1][2]
...     input = get_input(_name)
... 
>>> 
>>> foo.input
'sbb'

However, I wouldn't do this; My original answer is still my own preference as a solution. Original answer:

probably the very simplest solution is to use a decorator, which is similar to Ned's answer involving metaclasses, but less powerful (decorators are capable of black magic, but metaclasses are capable of ancient, occult black magic)

>>> def get_input(class_name):
...     return class_name.encode('rot13')
... 
>>> def inputize(cls):
...     cls.input = get_input(cls.__name__)
...     return cls
... 
>>> @inputize
... class foo(object):
...     pass
... 
>>> foo.input
'sbb'
>>> 

Detecting which UIButton was pressed in a UITableView

create an nsmutable array and put all button in that array usint[array addObject:yourButton];

in the button press method

-

 (void)buttonPressedAction:(id)sender
{
    UIButton *button = (UIButton *)sender;

for(int i=0;i<[yourArray count];i++){

if([buton isEqual:[yourArray objectAtIndex:i]]){

//here write wat u need to do

}
}

Subtracting 2 lists in Python

arr1=[1,2,3]
arr2=[2,1,3]
ls=[arr2-arr1 for arr1,arr2 in zip(arr1,arr2)]
print(ls)
>>[1,-1,0]

Maven artifact and groupId naming

Your convention seems to be reasonable. If I were searching for your framework in the Maven repo, I would look for awesome-inhouse-framework-x.y.jar in com.mycompany.awesomeinhouseframework group directory. And I would find it there according to your convention.

Two simple rules work for me:

  • reverse-domain-packages for groupId (since such are quite unique) with all the constrains regarding Java packages names
  • project name as artifactId (keeping in mind that it should be jar-name friendly i.e. not contain characters that maybe invalid for a file name or just look weird)

Joining Multiple Tables - Oracle

I recommend that you get in the habit, right now, of using ANSI-style joins, meaning you should use the INNER JOIN, LEFT OUTER JOIN, RIGHT OUTER JOIN, FULL OUTER JOIN, and CROSS JOIN elements in your SQL statements rather than using the "old-style" joins where all the tables are named together in the FROM clause and all the join conditions are put in the the WHERE clause. ANSI-style joins are easier to understand and less likely to be miswritten and/or misinterpreted than "old-style" joins.

I'd rewrite your query as:

SELECT bc.firstname,
       bc.lastname,
       b.title,
       TO_CHAR(bo.orderdate, 'MM/DD/YYYY') "Order Date",
       p.publishername
FROM BOOK_CUSTOMER bc
INNER JOIN books b
  ON b.BOOK_ID = bc.BOOK_ID
INNER JOIN  book_order bo
  ON bo.BOOK_ID = b.BOOK_ID
INNER JOIN publisher p
  ON p.PUBLISHER_ID = b.PUBLISHER_ID
WHERE p.publishername = 'PRINTING IS US';

Share and enjoy.

How to remove an item from an array in AngularJS scope?

You can also use this

$scope.persons = $filter('filter')($scope.persons , { id: ('!' + person.id) });

Cast received object to a List<object> or IEnumerable<object>

This Code worked for me

List<Object> collection = new List<Object>((IEnumerable<Object>)myObject);

eloquent laravel: How to get a row count from a ->get()

Direct get a count of row

Using Eloquent

 //Useing Eloquent
 $count = Model::count();    

 //example            
 $count1 = Wordlist::count();

Using query builder

 //Using query builder
 $count = \DB::table('table_name')->count();

 //example
 $count2 = \DB::table('wordlist')->where('id', '<=', $correctedComparisons)->count();

Calculating percentile of dataset column

You can also use the hmisc package that will give you the following percentiles:

0.05, 0.1, 0.25, 0.5, 0.75, 0.9 , 0.95

Just use the describe(table_ages)

PostgreSQL Crosstab Query

Crosstab function is available under the tablefunc extension. You'll have to create this extension one time for the database.

CREATE EXTENSION tablefunc;

You can use the below code to create pivot table using cross tab:

create table test_Crosstab( section text,
<br/>status text,
<br/>count numeric)

<br/>insert into test_Crosstab values ( 'A','Active',1)
                <br/>,( 'A','Inactive',2)
                <br/>,( 'B','Active',4)
                <br/>,( 'B','Inactive',5)

select * from crosstab(
<br/>'select section
    <br/>,status
    <br/>,count
    <br/>from test_crosstab'
    <br/>)as ctab ("Section" text,"Active" numeric,"Inactive" numeric)

Set HTTP header for one request

There's a headers parameter in the config object you pass to $http for per-call headers:

$http({method: 'GET', url: 'www.google.com/someapi', headers: {
    'Authorization': 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='}
});

Or with the shortcut method:

$http.get('www.google.com/someapi', {
    headers: {'Authorization': 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='}
});

The list of the valid parameters is available in the $http service documentation.

"An access token is required to request this resource" while accessing an album / photo with Facebook php sdk

To get an access token: facebook Graph API Explorer

You can customize specific access permissions, basic permissions are included by default.

How to convert List<Integer> to int[] in Java?

Using a lambda you could do this (compiles in jdk lambda):

public static void main(String ars[]) {
        TransformService transformService = (inputs) -> {
            int[] ints = new int[inputs.size()];
            int i = 0;
            for (Integer element : inputs) {
                ints[ i++ ] = element;
            }
            return ints;
        };

        List<Integer> inputs = new ArrayList<Integer>(5) { {add(10); add(10);} };

        int[] results = transformService.transform(inputs);
    }

    public interface TransformService {
        int[] transform(List<Integer> inputs);
    }

Create 3D array using Python

The right way would be

[[[0 for _ in range(n)] for _ in range(n)] for _ in range(n)]

(What you're trying to do should be written like (for NxNxN)

[[[0]*n]*n]*n

but that is not correct, see @Adaman comment why).

onclick open window and specific size

window.open ("http://www.javascript-coder.com",
"mywindow","menubar=1,resizable=1,width=350,height=250");

from

http://www.javascript-coder.com/window-popup/javascript-window-open.phtml

:]

How to convert an Instant to a date format?

An Instant is what it says: a specific instant in time - it does not have the notion of date and time (the time in New York and Tokyo is not the same at a given instant).

To print it as a date/time, you first need to decide which timezone to use. For example:

System.out.println(LocalDateTime.ofInstant(i, ZoneOffset.UTC));

This will print the date/time in iso format: 2015-06-02T10:15:02.325

If you want a different format you can use a formatter:

LocalDateTime datetime = LocalDateTime.ofInstant(i, ZoneOffset.UTC);
String formatted = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss").format(datetime);
System.out.println(formatted);

C# winforms combobox dynamic autocomplete

This code is write on your form load. It display all the Tour in database when user type letter in combo box. This code automatically suggest and append the right choice as user want.

            con.Open();
            cmd = new SqlCommand("SELECT DISTINCT Tour FROM DetailsTB", con);
            SqlDataReader sdr = cmd.ExecuteReader();
            DataTable dt = new DataTable();
            dt.Load(sdr);
            combo_search2.DisplayMember = "Tour";
            combo_search2.DroppedDown = true;

            List<string> list = new List<string>();
            foreach (DataRow row in dt.Rows)
            {
                list.Add(row.Field<string>("Tour"));
            }
            this.combo_search2.Items.AddRange(list.ToArray<string>());
            combo_search2.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
            combo_search2.AutoCompleteSource = AutoCompleteSource.ListItems;
            con.Close();

Why is textarea filled with mysterious white spaces?

Basically it should be

<textarea>something here with no spaces in the begining</textarea>

If there are some predefined spaces lets say due to code formatting like below

<textarea>.......
....some_variable
</textarea>

The spaces shown by dots keeps on adding on each submit.

How to git commit a single file/directory

If you are in the folder which contains the file

git commit -m 'my notes' ./name_of_file.ext

How do I test a website using XAMPP?

Just edit the httpd-vhost-conf scroll to the bottom and on the last example/demo for creating a virtual host, remove the hash-tags for DocumentRoot and ServerName. You may have hash-tags just before the <VirtualHost *.80> and </VirtualHost>

After DocumentRoot, just add the path to your web-docs ... and add your domain-name after ServerNmane

<VirtualHost *:80>
    ##ServerAdmin [email protected]
    DocumentRoot "C:/xampp/htdocs/www"
    ServerName example.com
    ##ErrorLog "logs/dummy-host2.example.com-error.log"
    ##CustomLog "logs/dummy-host2.example.com-access.log" common
</VirtualHost>

Be sure to create the www folder under htdocs. You do not have to name the folder www but I did just to be simple about it. Be sure to restart Apache and bang! you can now store files in the newly created directory. To test things out just create a simple index.html or index.php file and place in the www folder, then go to your browser and test it out localhost/ ... Note: if your server is serving php files over html then remember to add localhost/index.html if the html file is the one you choose to use for this test.

Something I should add, in order to still have access to the xampp homepage then you will need to create another VirtualHost. To do this just add

<VirtualHost *:80>
    ##ServerAdmin [email protected]
    DocumentRoot "C:/xampp/htdocs"
    ServerName htdocs.example.com
    ##ErrorLog "logs/dummy-host2.example.com-error.log"
    ##CustomLog "logs/dummy-host2.example.com-access.log" common
</VirtualHost>

underneath the last VirtualHost that you created. Next make the necessary changes to your host file and restart Apache. Now go to your browser and visit htdocs.example.com and your all set.

Using StringWriter for XML Serialization

public static T DeserializeFromXml<T>(string xml)
{
    T result;
    XmlSerializerFactory serializerFactory = new XmlSerializerFactory();
    XmlSerializer serializer =serializerFactory.CreateSerializer(typeof(T));

    using (StringReader sr3 = new StringReader(xml))
    {
        XmlReaderSettings settings = new XmlReaderSettings()
        {
            CheckCharacters = false // default value is true;
        };

        using (XmlReader xr3 = XmlTextReader.Create(sr3, settings))
        {
            result = (T)serializer.Deserialize(xr3);
        }
    }

    return result;
}

CSS align images and text on same line

vertical-align: text-bottom;

Tested, this worked for me perfectly, just apply this to the image.

Creating InetAddress object in Java

The api is fairly easy to use.

// Lookup the dns, if the ip exists.
 if (!ip.isEmpty()) {
     InetAddress inetAddress = InetAddress.getByName(ip);
     dns = inetAddress.getCanonicalHostName(); 
 }

Unable to execute dex: Multiple dex files define

For me the issue was that, i had added a lib project(autobahn lib) earlier and later switched the to Jar file of the same library.Though i had removed references to the older library project, i was getting this error. Following all the answers here i checked the build path etc. But i haven't added these libs to build path manually. So i had nothing to remove. Finally came across this folder.

bin/dexedLibs

I noticed that there were two jar files with the same name corresponding to autobahn Android which was causing the conflict. So i deleted all the jar files in the dexedLibs folder and rebuild the project. That resolved the issue.

How to disable logging on the standard error stream in Python?

To fully disable logging:

logging.disable(sys.maxint) # Python 2

logging.disable(sys.maxsize) # Python 3

To enable logging:

logging.disable(logging.NOTSET)

Other answers provide work arounds which don't fully solve the problem, such as

logging.getLogger().disabled = True

and, for some n greater than 50,

logging.disable(n)

The problem with the first solution is that it only works for the root logger. Other loggers created using, say, logging.getLogger(__name__) are not disabled by this method.

The second solution does affect all logs. But it limits output to levels above that given, so one could override it by logging with a level greater than 50.

That can be prevented by

logging.disable(sys.maxint)

which as far as I can tell (after reviewing the source) is the only way to fully disable logging.

Selenium WebDriver.get(url) does not open the URL

I had the same problem but with Chrome.

Solved it using the following steps

  1. Install Firefox/Chrome webdriver from Google
  2. Put the webdriver in Chrome's directory.

Here's the code and it worked fine

from selenium import webdriver

class InstaBot(object):
    def __init__(self):
        self.driver=webdriver.Chrome("C:\Program 
        Files(x86)\Google\Chrome\Application\chromedriver.exe")# make sure 
                                                      #it is chrome driver 
        self.driver.get("https://www.wikipedia.com")
        
        
InstaBot()

Python update a key in dict if it doesn't exist

Use dict.setdefault():

>>> d = {1: 'one'}
>>> d.setdefault(1, '1')
'one'
>>> d    # d has not changed because the key already existed
{1: 'one'}
>>> d.setdefault(2, 'two')
'two'
>>> d
{1: 'one', 2: 'two'}

Change a column type from Date to DateTime during ROR migration

There's a change_column method, just execute it in your migration with datetime as a new type.

change_column(:my_table, :my_column, :my_new_type)

What does "both" mean in <div style="clear:both">

Both means "every item in a set of two things". The two things being "left" and "right"

How to best display in Terminal a MySQL SELECT returning too many fields?

Using the Windows Command Prompt you can increase the buffer size of the window as much you want to see the number of columns. This depends on the no of columns in the table.

Authentication issues with WWW-Authenticate: Negotiate

Putting this information here for future readers' benefit.

  • 401 (Unauthorized) response header -> Request authentication header

  • Here are several WWW-Authenticate response headers. (The full list is at IANA: HTTP Authentication Schemes.)

    • WWW-Authenticate: Basic-> Authorization: Basic + token - Use for basic authentication
    • WWW-Authenticate: NTLM-> Authorization: NTLM + token (2 challenges)
    • WWW-Authenticate: Negotiate -> Authorization: Negotiate + token - used for Kerberos authentication
      • By the way: IANA has this angry remark about Negotiate: This authentication scheme violates both HTTP semantics (being connection-oriented) and syntax (use of syntax incompatible with the WWW-Authenticate and Authorization header field syntax).

You can set the Authorization: Basic header only when you also have the WWW-Authenticate: Basic header on your 401 challenge.

But since you have WWW-Authenticate: Negotiate this should be the case for Kerberos based authentication.

How can I get the current directory name in Javascript?

Assuming you are talking about the current URL, you can parse out part of the URL using window.location. See: http://java-programming.suite101.com/article.cfm/how_to_get_url_parts_in_javascript

How to submit a form with JavaScript by clicking a link?

The best way

The best way is to insert an appropriate input tag:

<input type="submit" value="submit" />

The best JS way

<form id="form-id">
  <button id="your-id">submit</button>
</form>
var form = document.getElementById("form-id");

document.getElementById("your-id").addEventListener("click", function () {
  form.submit();
});

Enclose the latter JavaScript code by an DOMContentLoaded event (choose only load for backward compatiblity) if you haven't already done so:

window.addEventListener("DOMContentLoaded", function () {
  var form = document.... // copy the last code block!
});

The easy, not recommandable way (the former answer)

Add an onclick attribute to the link and an id to the form:

<form id="form-id">

  <a href="#" onclick="document.getElementById('form-id').submit();"> submit </a>

</form>

All ways

Whatever way you choose, you have call formObject.submit() eventually (where formObject is the DOM object of the <form> tag).

You also have to bind such an event handler, which calls formObject.submit(), so it gets called when the user clicked a specific link or button. There are two ways:

  • Recommended: Bind an event listener to the DOM object.

    // 1. Acquire a reference to our <form>.
    //    This can also be done by setting <form name="blub">:
    //       var form = document.forms.blub;
    
    var form = document.getElementById("form-id");
    
    
    // 2. Get a reference to our preferred element (link/button, see below) and
    //    add an event listener for the "click" event.
    document.getElementById("your-id").addEventListener("click", function () {
      form.submit();
    });
    
  • Not recommended: Insert inline JavaScript. There are several reasons why this technique is not recommendable. One major argument is that you mix markup (HTML) with scripts (JS). The code becomes unorganized and rather unmaintainable.

    <a href="#" onclick="document.getElementById('form-id').submit();">submit</a>
    
    <button onclick="document.getElementById('form-id').submit();">submit</button>
    

Now, we come to the point at which you have to decide for the UI element which triggers the submit() call.

  1. A button

    <button>submit</button>
    
  2. A link

    <a href="#">submit</a>
    

Apply the aforementioned techniques in order to add an event listener.

Accessing constructor of an anonymous class

From the Java Language Specification, section 15.9.5.1:

An anonymous class cannot have an explicitly declared constructor.

Sorry :(

EDIT: As an alternative, you can create some final local variables, and/or include an instance initializer in the anonymous class. For example:

public class Test {
    public static void main(String[] args) throws Exception {
        final int fakeConstructorArg = 10;

        Object a = new Object() {
            {
                System.out.println("arg = " + fakeConstructorArg);
            }
        };
    }
}

It's grotty, but it might just help you. Alternatively, use a proper nested class :)

Dynamically change color to lighter or darker by percentage CSS (Javascript)

See my comment on Ctford's reply.

I'd think the easy way to lighten a color would be to take each of the RGB components, add to 0xff and divide by 2. If that doesn't give the exact results you want, take 0xff minus the current value times some constant and then add back to the current value. For example if you want to shift 1/3 of the way toward white, take (0xff - current)/3+current.

You'd have to play with it to see what results you got. I would worry that with this simple a formula, a factor big enough to make dark colors fade nicely might make light colors turn completely white, while a factor small enough to make light colors only lighten a little might make dark colors not lighten enough.

Still, I think going by a fraction of the distance to white is more promising than a fixed number of steps.

Correct way to create rounded corners in Twitter Bootstrap

What you want is a Bootstrap panel. Just add the panel class, and your header will look uniform. You can also add classes panel panel-info, panel panel-success, etc. It works for pretty much any block element, and should work with <header>, but I expect it would be used mostly with <div>s.

How to handle static content in Spring MVC?

I solved it this way:

<servlet-mapping>
    <servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.jpg</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.png</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.gif</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.js</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.css</url-pattern>
</servlet-mapping>

This works on Tomcat and ofcourse Jboss. However in the end I decided to use the solution Spring provides (as mentioned by rozky) which is far more portable.

Twitter Bootstrap scrollable table rows and fixed header

Here is a jQuery plugin that does exactly that: http://fixedheadertable.com/

Usage:

$('selector').fixedHeaderTable({ fixedColumn: 1 });

Set the fixedColumn option if you want any number of columns to be also fixed for horizontal scrolling.

EDIT: This example http://www.datatables.net/examples/basic_init/scroll_y.html is much better in my opinion, although with DataTables you'll need to get a better understanding of how it works in general.

EDIT2: For Bootstrap to work with DataTables you need to follow the instructions here: http://datatables.net/blog/Twitter_Bootstrap_2 (I have tested this and it works)- For Bootstrap 3 there's a discussion here: http://datatables.net/forums/discussion/comment/53462 - (I haven't tested this)

How to go from one page to another page using javascript?

The correct solution that i get is

<html>
      <head>
        <script type="text/javascript" language="JavaScript">
                  function clickedButton()
            {

                window.location = 'new url'

            }
             </script>
      </head>

      <form name="login_form" method="post">
            ..................
            <input type="button" value="Login" onClick="clickedButton()"/>
      </form>
 </html>

Here the new url is given inside the single quote.

How do you execute SQL from within a bash script?

Here is a simple way of running MySQL queries in the bash shell

mysql -u [database_username] -p [database_password] -D [database_name] -e "SELECT * FROM [table_name]"

How to convert a huge list-of-vector to a matrix more efficiently?

This should be equivalent to your current code, only a lot faster:

output <- matrix(unlist(z), ncol = 10, byrow = TRUE)

Excel compare two columns and highlight duplicates

The easiest way to do it, at least for me, is:

Conditional format-> Add new rule->Set your own formula:

=ISNA(MATCH(A2;$B:$B;0))

Where A2 is the first element in column A to be compared and B is the column where A's element will be searched.

Once you have set the formula and picked the format, apply this rule to all elements in the column.

Hope this helps

Javascript to display the current date and time

To return the client side date you can use the following javascript:

var d = new Date();
var month = d.getMonth()+1;
var date = d.getDate()+"."+month+"."+d.getFullYear();
document.getElementById('date').innerHTML = date;

or in jQuery:

var d = new Date();
var month = d.getMonth()+1;
var date = d.getDate()+"."+month+"."+d.getFullYear();
$('#date').html(date);

equivalent to following PHP:

<?php date("j.n.Y"); ?>

To get equivalent to the following PHP (i.e. leading 0's):

<?php date("d.m.Y"); ?>

JavaScript:

var d = new Date();
var day = d.getDate();
var month = d.getMonth()+1;

if(day < 10){
    day = "0"+d.getDate();
}

if(month < 10){
    month = "0"+eval(d.getMonth()+1);
}

var date = day+"."+month+"."+d.getFullYear();
document.getElementById('date').innerHTML = date;

jQuery:

var d = new Date();
var day = d.getDate();
var month = d.getMonth()+1;

if(day < 10){
    day = "0"+d.getDate();
}

if(month < 10){
    month = "0"+eval(d.getMonth()+1);
}

var date = day+"."+month+"."+d.getFullYear();
$('#date').html(date);

How do I disable right click on my web page?

First, you cannot achieve this without using a client side capability. This is where the javascript runs.

Secondly, if you are trying to control what an end user can consume from your site, then you need to rethink how you display that information. An image has a public url that can be fetched via HTTP without the need for a browser.

Authentication can control who has access to what resources.

Embedded watermarking in images can prove that the image was from a specific person/company.

At the end of the day, resource management is really user/guest managment.

The first rule of the Internet, if you dont want it taken, dont make it public!

The second rule of the Internet, if you dont want it taken, dont put it on the Internet!

How to "add existing frameworks" in Xcode 4?

  1. In the project navigator, select your project.

  2. Select your target.

  3. Select the "Build Phases" tab.

  4. expander. Click the + button.

  5. Select your framework.

  6. (optional) Drag and drop the added framework to the "Frameworks" group.

    enter image description here

Hive ParseException - cannot recognize input near 'end' 'string'

You can always escape the reserved keyword if you still want to make your query work!!

Just replace end with `end`

Here is the list of reserved keywords https://cwiki.apache.org/confluence/display/Hive/LanguageManual+DDL

CREATE EXTERNAL TABLE moveProjects (cid string, `end` string, category string)
STORED BY 'org.apache.hadoop.hive.dynamodb.DynamoDBStorageHandler'
TBLPROPERTIES ("dynamodb.table.name" = "Projects",
    "dynamodb.column.mapping" = "cid:cid,end:end,category:category");

Removing specific rows from a dataframe

One simple solution:

cond1 <- df$sub == 1 & df$day == 2

cond2 <- df$sub == 3 & df$day == 4

df <- df[!(cond1 | cond2),]

How to split a comma separated string and process in a loop using JavaScript

My two cents, adding trim to remove the initial whitespaces left in sAc's answer.

var str = 'Hello, World, etc';
var str_array = str.split(',');

for(var i = 0; i < str_array.length; i++) {
   // Trim the excess whitespace.
   str_array[i] = str_array[i].replace(/^\s*/, "").replace(/\s*$/, "");
   // Add additional code here, such as:
   alert(str_array[i]);
}

Edit:

After getting several upvotes on this answer, I wanted to revisit this. If you want to split on comma, and perform a trim operation, you can do it in one method call without any explicit loops due to the fact that split will also take a regular expression as an argument:

'Hello, cruel , world!'.split(/\s*,\s*/);
//-> ["Hello", "cruel", "world!"]

This solution, however, will not trim the beginning of the first item and the end of the last item which is typically not an issue.

And so to answer the question in regards to process in a loop, if your target browsers support ES5 array extras such as the map or forEach methods, then you could just simply do the following:

myStringWithCommas.split(/\s*,\s*/).forEach(function(myString) {
    console.log(myString);
});

How to generate different random numbers in a loop in C++?

I had this same problem for days. Keeping srand() out of the loop is a +. Also, dont assign rand() % 100 to any variable. Simply cout rand() % 100 in the loop. Try this:

    srand (time(NULL));
    (int t=0;t<10;t++)
    {
    cout << rand() % 100 << endl;
    } 

jQuery - multiple $(document).ready ...?

Execution is top-down. First come, first served.

If execution sequence is important, combine them.

Post values from a multiple select

try this : here select is your select element

let select = document.getElementsByClassName('lstSelected')[0],
    options = select.options,
    len = options.length,
    data='',
    i=0;
while (i<len){
    if (options[i].selected)
        data+= "&" + select.name + '=' + options[i].value;
    i++;
}
return data;

Data is in the form of query string i.e.name=value&name=anotherValue

How do I enable index downloads in Eclipse for Maven dependency search?

  1. In Eclipse, click on Windows > Preferences, and then choose Maven in the left side.
  2. Check the box "Download repository index updates on startup".
    • Optionally, check the boxes Download Artifact Sources and Download Artifact JavaDoc.
  3. Click OK. The warning won't appear anymore.
  4. Restart Eclipse.

http://i.imgur.com/IJ2T3vc.png

Random string generation with upper case letters and digits

>>> import random
>>> str = []
>>> chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
>>> num = int(raw_input('How long do you want the string to be?  '))
How long do you want the string to be?  10
>>> for k in range(1, num+1):
...    str.append(random.choice(chars))
...
>>> str = "".join(str)
>>> str
'tm2JUQ04CK'

The random.choice function picks a random entry in a list. You also create a list so that you can append the character in the for statement. At the end str is ['t', 'm', '2', 'J', 'U', 'Q', '0', '4', 'C', 'K'], but the str = "".join(str) takes care of that, leaving you with 'tm2JUQ04CK'.

Hope this helps!

python filter list of dictionaries based on key value

Use filter, or if the number of dictionaries in exampleSet is too high, use ifilter of the itertools module. It would return an iterator, instead of filling up your system's memory with the entire list at once:

from itertools import ifilter
for elem in ifilter(lambda x: x['type'] in keyValList, exampleSet):
    print elem

Javascript add leading zeroes to date

try this for a basic function, no libraries required

Date.prototype.CustomformatDate = function() {
 var tmp = new Date(this.valueOf());
 var mm = tmp.getMonth() + 1;
 if (mm < 10) mm = "0" + mm;
 var dd = tmp.getDate();
 if (dd < 10) dd = "0" + dd;
 return mm + "/" + dd + "/" + tmp.getFullYear();
};

Enum "Inheritance"

I also wanted to overload Enums and created a mix of the answer of 'Seven' on this page and the answer of 'Merlyn Morgan-Graham' on a duplicate post of this, plus a couple of improvements.
Main advantages of my solution over the others:

  • automatic increment of the underlying int value
  • automatic naming

This is an out-of-the-box solution and may be directly inserted into your project. It is designed to my needs, so if you don't like some parts of it, just replace them with your own code.

First, there is the base class CEnum that all custom enums should inherit from. It has the basic functionality, similar to the .net Enum type:

public class CEnum
{
  protected static readonly int msc_iUpdateNames  = int.MinValue;
  protected static int          ms_iAutoValue     = -1;
  protected static List<int>    ms_listiValue     = new List<int>();

  public int Value
  {
    get;
    protected set;
  }

  public string Name
  {
    get;
    protected set;
  }

  protected CEnum ()
  {
    CommonConstructor (-1);
  }

  protected CEnum (int i_iValue)
  {
    CommonConstructor (i_iValue);
  }

  public static string[] GetNames (IList<CEnum> i_listoValue)
  {
    if (i_listoValue == null)
      return null;
    string[] asName = new string[i_listoValue.Count];
    for (int ixCnt = 0; ixCnt < asName.Length; ixCnt++)
      asName[ixCnt] = i_listoValue[ixCnt]?.Name;
    return asName;
  }

  public static CEnum[] GetValues ()
  {
    return new CEnum[0];
  }

  protected virtual void CommonConstructor (int i_iValue)
  {
    if (i_iValue == msc_iUpdateNames)
    {
      UpdateNames (this.GetType ());
      return;
    }
    else if (i_iValue > ms_iAutoValue)
      ms_iAutoValue = i_iValue;
    else
      i_iValue = ++ms_iAutoValue;

    if (ms_listiValue.Contains (i_iValue))
      throw new ArgumentException ("duplicate value " + i_iValue.ToString ());
    Value = i_iValue;
    ms_listiValue.Add (i_iValue);
  }

  private static void UpdateNames (Type i_oType)
  {
    if (i_oType == null)
      return;
    FieldInfo[] aoFieldInfo = i_oType.GetFields (BindingFlags.Public | BindingFlags.Static);

    foreach (FieldInfo oFieldInfo in aoFieldInfo)
    {
      CEnum oEnumResult = oFieldInfo.GetValue (null) as CEnum;
      if (oEnumResult == null)
        continue;
      oEnumResult.Name = oFieldInfo.Name;
    }
  }
}

Secondly, here are 2 derived Enum classes. All derived classes need some basic methods in order to work as expected. It's always the same boilerplate code; I haven't found a way yet to outsource it to the base class. The code of the first level of inheritance differs slightly from all subsequent levels.

public class CEnumResult : CEnum
{
  private   static List<CEnumResult>  ms_listoValue = new List<CEnumResult>();

  public    static readonly CEnumResult Nothing         = new CEnumResult (  0);
  public    static readonly CEnumResult SUCCESS         = new CEnumResult (  1);
  public    static readonly CEnumResult UserAbort       = new CEnumResult ( 11);
  public    static readonly CEnumResult InProgress      = new CEnumResult (101);
  public    static readonly CEnumResult Pausing         = new CEnumResult (201);
  private   static readonly CEnumResult Dummy           = new CEnumResult (msc_iUpdateNames);

  protected CEnumResult () : base ()
  {
  }

  protected CEnumResult (int i_iValue) : base (i_iValue)
  {
  }

  protected override void CommonConstructor (int i_iValue)
  {
    base.CommonConstructor (i_iValue);

    if (i_iValue == msc_iUpdateNames)
      return;
    if (this.GetType () == System.Reflection.MethodBase.GetCurrentMethod ().DeclaringType)
      ms_listoValue.Add (this);
  }

  public static new CEnumResult[] GetValues ()
  {
    List<CEnumResult> listoValue = new List<CEnumResult> ();
    listoValue.AddRange (ms_listoValue);
    return listoValue.ToArray ();
  }
}

public class CEnumResultClassCommon : CEnumResult
{
  private   static List<CEnumResultClassCommon> ms_listoValue = new List<CEnumResultClassCommon>();

  public    static readonly CEnumResult Error_InternalProgramming           = new CEnumResultClassCommon (1000);

  public    static readonly CEnumResult Error_Initialization                = new CEnumResultClassCommon ();
  public    static readonly CEnumResult Error_ObjectNotInitialized          = new CEnumResultClassCommon ();
  public    static readonly CEnumResult Error_DLLMissing                    = new CEnumResultClassCommon ();
  // ... many more
  private   static readonly CEnumResult Dummy                               = new CEnumResultClassCommon (msc_iUpdateNames);

  protected CEnumResultClassCommon () : base ()
  {
  }

  protected CEnumResultClassCommon (int i_iValue) : base (i_iValue)
  {
  }

  protected override void CommonConstructor (int i_iValue)
  {
    base.CommonConstructor (i_iValue);

    if (i_iValue == msc_iUpdateNames)
      return;
    if (this.GetType () == System.Reflection.MethodBase.GetCurrentMethod ().DeclaringType)
      ms_listoValue.Add (this);
  }

  public static new CEnumResult[] GetValues ()
  {
    List<CEnumResult> listoValue = new List<CEnumResult> (CEnumResult.GetValues ());
    listoValue.AddRange (ms_listoValue);
    return listoValue.ToArray ();
  }
}

The classes have been successfully tested with follwing code:

private static void Main (string[] args)
{
  CEnumResult oEnumResult = CEnumResultClassCommon.Error_Initialization;
  string sName = oEnumResult.Name;   // sName = "Error_Initialization"

  CEnum[] aoEnumResult = CEnumResultClassCommon.GetValues ();   // aoEnumResult = {testCEnumResult.Program.CEnumResult[9]}
  string[] asEnumNames = CEnum.GetNames (aoEnumResult);
  int ixValue = Array.IndexOf (aoEnumResult, oEnumResult);    // ixValue = 6
}

How to find out which JavaScript events fired?

You can use getEventListeners in your Google Chrome developer console.

getEventListeners(object) returns the event listeners registered on the specified object.

getEventListeners(document.querySelector('option[value=Closed]'));

Refused to apply inline style because it violates the following Content Security Policy directive

Another method is to use the CSSOM (CSS Object Model), via the style property on a DOM node.

var myElem = document.querySelector('.my-selector');
myElem.style.color = 'blue';

More details on CSSOM: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement.style

As mentioned by others, enabling unsafe-line for css is another method to solve this.

How to use and style new AlertDialog from appCompat 22.1 and above

Follow @reVerse answer but in my case, I already had some property in my AppTheme like

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    ...
    <item name="android:textColor">#111</item>
    <item name="android:textSize">13sp</item>
</style>

So my dialog will look like
enter image description here

I solved it by

1) Change the import from android.app.AlertDialog to android.support.v7.app.AlertDialog
2) I override 2 property in AppTheme with null value

<style name="MyAlertDialogStyle" parent="Theme.AppCompat.Light.Dialog.Alert">
    <!-- Used for the buttons -->
    <item name="colorAccent">#FFC107</item>
    <!-- Used for the title and text -->
    <item name="android:textColorPrimary">#FFFFFF</item>
    <!-- Used for the background -->
    <item name="android:background">#4CAF50</item>


    <item name="android:textColor">@null</item>
    <item name="android:textSize">@null</item>
</style>

.

AlertDialog.Builder builder = new AlertDialog.Builder(mContext, R.style.MyAlertDialogStyle);

Hope it help another people

enter image description here

DELETE_FAILED_INTERNAL_ERROR Error while Installing APK

I had same problem in my xiaomi note 4a device. I solved it by turning off MIUI optimization.

How do I center this form in css?

Another way

_x000D_
_x000D_
body {_x000D_
    text-align: center;_x000D_
}_x000D_
form {_x000D_
    display: inline-block;_x000D_
}
_x000D_
<body>_x000D_
  <form>_x000D_
    <input type="text" value="abc">_x000D_
  </form>_x000D_
</body>
_x000D_
_x000D_
_x000D_

Opening a .ipynb.txt File

Below is the easiest way in case if Anaconda is already installed.

1) Under "Files", there is an option called,"Upload".

2) Click on "Upload" button and it asks for the path of the file and select the file and click on upload button present beside the file.

Evaluate list.contains string in JSTL

${fn:contains({1,2,4,8}, 2)}

OR

  <c:if test = "${fn:contains(theString, 'test')}">
     <p>Found test string<p>
  </c:if>

  <c:if test = "${fn:contains(theString, 'TEST')}">
     <p>Found TEST string<p>
  </c:if>

How to increase IDE memory limit in IntelliJ IDEA on Mac?

go to that path "C:\Program Files (x86)\JetBrains\IntelliJ IDEA 12.1.4\bin\idea.exe.vmoptions" and change size to -Xmx512m

  -Xms128m
  -Xmx512m
  -XX:MaxPermSize=250m
  -XX:ReservedCodeCacheSize=64m
  -XX:+UseCodeCacheFlushing
  -ea
  -Dsun.io.useCanonCaches=false
  -Djava.net.preferIPv4Stack=true

hope its will work

Adjusting HttpWebRequest Connection Timeout in C#

From the documentation of the HttpWebRequest.Timeout property:

A Domain Name System (DNS) query may take up to 15 seconds to return or time out. If your request contains a host name that requires resolution and you set Timeout to a value less than 15 seconds, it may take 15 seconds or more before a WebException is thrown to indicate a timeout on your request.

Is it possible that your DNS query is the cause of the timeout?

Difference between x86, x32, and x64 architectures?

Hans and DarkDust answer covered i386/i686 and amd64/x86_64, so there's no sense in revisiting them. This answer will focus on X32, and provide some info learned after a X32 port.

x32 is an ABI for amd64/x86_64 CPUs using 32-bit integers, longs and pointers. The idea is to combine the smaller memory and cache footprint from 32-bit data types with the larger register set of x86_64. (Reference: Debian X32 Port page).

x32 can provide up to about 30% reduction in memory usage and up to about 40% increase in speed. The use cases for the architecture are:

  • vserver hosting (memory bound)
  • netbooks/tablets (low memory, performance)
  • scientific tasks (performance)

x32 is a somewhat recent addition. It requires kernel support (3.4 and above), distro support (see below), libc support (2.11 or above), and GCC 4.8 and above (improved address size prefix support).

For distros, it was made available in Ubuntu 13.04 or Fedora 17. Kernel support only required pointer to be in the range from 0x00000000 to 0xffffffff. From the System V Application Binary Interface, AMD64 (With LP64 and ILP32 Programming Models), Section 10.4, p. 132 (its the only sentence):

10.4 Kernel Support
Kernel should limit stack and addresses returned from system calls between 0x00000000 to 0xffffffff.

When booting a kernel with the support, you must use syscall.x32=y option. When building a kernel, you must include the CONFIG_X86_X32=y option. (Reference: Debian X32 Port page and X32 System V Application Binary Interface).


Here is some of what I have learned through a recent port after the Debian folks reported a few bugs on us after testing:

  • the system is a lot like X86
  • the preprocessor defines __x86_64__ (and friends) and __ILP32__, but not __i386__/__i686__ (and friends)
  • you cannot use __ILP32__ alone because it shows up unexpectedly under Clang and Sun Studio
  • when interacting with the stack, you must use the 64-bit instructions pushq and popq
  • once a register is populated/configured from 32-bit data types, you can perform the 64-bit operations on them, like adcq
  • be careful of the 0-extension that occurs on the upper 32-bits.

If you are looking for a test platform, then you can use Debian 8 or above. Their wiki page at Debian X32 Port has all the information. The 3-second tour: (1) enable X32 in the kernel at boot; (2) use debootstrap to install the X32 chroot environment, and (3) chroot debian-x32 to enter into the environment and test your software.

MongoDB: How to update multiple documents with a single command?

MongoDB will find only one matching document which matches the query criteria when you are issuing an update command, whichever document matches first happens to be get updated, even if there are more documents which matches the criteria will get ignored.

so to overcome this we can specify "MULTI" option in your update statement, meaning update all those documnets which matches the query criteria. scan for all the documnets in collection finding those which matches the criteria and update :

db.test.update({"foo":"bar"},{"$set":{"test":"success!"}}, {multi:true} )

How to add subject alernative name to ssl certs?

When generating CSR is possible to specify -ext attribute again to have it inserted in the CSR

keytool -certreq -file test.csr -keystore test.jks -alias testAlias -ext SAN=dns:test.example.com

complete example here: How to create CSR with SANs using keytool

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

For me it was my internet, I was working on restricted network

How to get a list of properties with a given attribute?

var props = t.GetProperties().Where(
                prop => Attribute.IsDefined(prop, typeof(MyAttribute)));

This avoids having to materialize any attribute instances (i.e. it is cheaper than GetCustomAttribute[s]().

How can I profile C++ code running on Linux?

At work we have a really nice tool that helps us monitoring what we want in terms of scheduling. This has been useful numerous times.

It's in C++ and must be customized to your needs. Unfortunately I can't share code, just concepts. You use a "large" volatile buffer containing timestamps and event ID that you can dump post mortem or after stopping the logging system (and dump this into a file for example).

You retrieve the so-called large buffer with all the data and a small interface parses it and shows events with name (up/down + value) like an oscilloscope does with colors (configured in .hpp file).

You customize the amount of events generated to focus solely on what you desire. It helped us a lot for scheduling issues while consuming the amount of CPU we wanted based on the amount of logged events per second.

You need 3 files :

toolname.hpp // interface
toolname.cpp // code
tool_events_id.hpp // Events ID

The concept is to define events in tool_events_id.hpp like that :

// EVENT_NAME                         ID      BEGIN_END BG_COLOR NAME
#define SOCK_PDU_RECV_D               0x0301  //@D00301 BGEEAAAA # TX_PDU_Recv
#define SOCK_PDU_RECV_F               0x0302  //@F00301 BGEEAAAA # TX_PDU_Recv

You also define a few functions in toolname.hpp :

#define LOG_LEVEL_ERROR 0
#define LOG_LEVEL_WARN 1
// ...

void init(void);
void probe(id,payload);
// etc

Wherever in you code you can use :

toolname<LOG_LEVEL>::log(EVENT_NAME,VALUE);

The probe function uses a few assembly lines to retrieve the clock timestamp ASAP and then sets an entry in the buffer. We also have an atomic increment to safely find an index where to store the log event. Of course buffer is circular.

Hope the idea is not obfuscated by the lack of sample code.

Update MongoDB field using value of another field

For a database with high activity, you may run into issues where your updates affect actively changing records and for this reason I recommend using snapshot()

db.person.find().snapshot().forEach( function (hombre) {
    hombre.name = hombre.firstName + ' ' + hombre.lastName; 
    db.person.save(hombre); 
});

http://docs.mongodb.org/manual/reference/method/cursor.snapshot/

Oracle SQL query for Date format

to_date() returns a date at 00:00:00, so you need to "remove" the minutes from the date you are comparing to:

select * 
from table
where trunc(es_date) = TO_DATE('27-APR-12','dd-MON-yy')

You probably want to create an index on trunc(es_date) if that is something you are doing on a regular basis.

The literal '27-APR-12' can fail very easily if the default date format is changed to anything different. So make sure you you always use to_date() with a proper format mask (or an ANSI literal: date '2012-04-27')

Although you did right in using to_date() and not relying on implict data type conversion, your usage of to_date() still has a subtle pitfall because of the format 'dd-MON-yy'.

With a different language setting this might easily fail e.g. TO_DATE('27-MAY-12','dd-MON-yy') when NLS_LANG is set to german. Avoid anything in the format that might be different in a different language. Using a four digit year and only numbers e.g. 'dd-mm-yyyy' or 'yyyy-mm-dd'

How do you style a TextInput in react native for password input

I am using 0.56RC secureTextEntry={true} Along with password={true} then only its working as mentioned by @NicholasByDesign

Adding Buttons To Google Sheets and Set value to Cells on clicking

You can insert an image that looks like a button. Then attach a script to the image.

  • INSERT menu
  • Image

Insert Image

You can insert any image. The image can be edited in the spreadsheet

Edit Image

Image of a Button

Image of Button

Assign a function name to an image:

Assign Function

How can I specify a display?

I faced similar problem today. So, here's a simple solution: While doing SSH to the machine, just add Ctrl - Y.

ssh user@ip_address -Y

After login, type firefox &. And you are good to go.

AngularJS ui router passing data between states without URL

The params object is included in $stateParams, but won't be part of the url.

1) In the route configuration:

$stateProvider.state('edit_user', {
    url: '/users/:user_id/edit',
    templateUrl: 'views/editUser.html',
    controller: 'editUserCtrl',
    params: {
        paramOne: { objectProperty: "defaultValueOne" },  //default value
        paramTwo: "defaultValueTwo"
    }
});

2) In the controller:

.controller('editUserCtrl', function ($stateParams, $scope) {       
    $scope.paramOne = $stateParams.paramOne;
    $scope.paramTwo = $stateParams.paramTwo;
});

3A) Changing the State from a controller

$state.go("edit_user", {
    user_id: 1,                
    paramOne: { objectProperty: "test_not_default1" },
    paramTwo: "from controller"
});

3B) Changing the State in html

<div ui-sref="edit_user({ user_id: 3, paramOne: { objectProperty: 'from_html1' }, paramTwo: 'fromhtml2' })"></div>

Example Plunker

Change Oracle port from port 8080

From this blog post:

XE: Changing the default http port

Oracle XE uses the embedded http listener that comes with the XML DB (XDB) to serve http requests. The default port for HTTP access is 8080.

EDIT:

Update 8080 port to which port(9090 for example) you like

SQL> -- set http port
SQL> begin
 2    dbms_xdb.sethttpport('9090');
 3  end;
 4  /

After changing the port, when we start Oracle it will go on port 8080, we should type manually new port(9090) in the address bar to run Oracle XE.

How to find all serial devices (ttyS, ttyUSB, ..) on Linux without opening them?

I'm doing something like the following code. It works for USB-devices and also the stupid serial8250-devuices that we all have 30 of - but only a couple of them realy works.

Basically I use concept from previous answers. First enumerate all tty-devices in /sys/class/tty/. Devices that does not contain a /device subdir is filtered away. /sys/class/tty/console is such a device. Then the devices actually containing a devices in then accepted as valid serial-port depending on the target of the driver-symlink fx.

$ ls -al /sys/class/tty/ttyUSB0//device/driver
lrwxrwxrwx 1 root root 0 sep  6 21:28 /sys/class/tty/ttyUSB0//device/driver -> ../../../bus/platform/drivers/usbserial

and for ttyS0

$ ls -al /sys/class/tty/ttyS0//device/driver
lrwxrwxrwx 1 root root 0 sep  6 21:28 /sys/class/tty/ttyS0//device/driver -> ../../../bus/platform/drivers/serial8250

All drivers driven by serial8250 must be probes using the previously mentioned ioctl.

        if (ioctl(fd, TIOCGSERIAL, &serinfo)==0) {
            // If device type is no PORT_UNKNOWN we accept the port
            if (serinfo.type != PORT_UNKNOWN)
                the_port_is_valid

Only port reporting a valid device-type is valid.

The complete source for enumerating the serialports looks like this. Additions are welcome.

#include <stdlib.h>
#include <dirent.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <termios.h>
#include <sys/ioctl.h>
#include <linux/serial.h>

#include <iostream>
#include <list>

using namespace std;

static string get_driver(const string& tty) {
    struct stat st;
    string devicedir = tty;

    // Append '/device' to the tty-path
    devicedir += "/device";

    // Stat the devicedir and handle it if it is a symlink
    if (lstat(devicedir.c_str(), &st)==0 && S_ISLNK(st.st_mode)) {
        char buffer[1024];
        memset(buffer, 0, sizeof(buffer));

        // Append '/driver' and return basename of the target
        devicedir += "/driver";

        if (readlink(devicedir.c_str(), buffer, sizeof(buffer)) > 0)
            return basename(buffer);
    }
    return "";
}

static void register_comport( list<string>& comList, list<string>& comList8250, const string& dir) {
    // Get the driver the device is using
    string driver = get_driver(dir);

    // Skip devices without a driver
    if (driver.size() > 0) {
        string devfile = string("/dev/") + basename(dir.c_str());

        // Put serial8250-devices in a seperate list
        if (driver == "serial8250") {
            comList8250.push_back(devfile);
        } else
            comList.push_back(devfile); 
    }
}

static void probe_serial8250_comports(list<string>& comList, list<string> comList8250) {
    struct serial_struct serinfo;
    list<string>::iterator it = comList8250.begin();

    // Iterate over all serial8250-devices
    while (it != comList8250.end()) {

        // Try to open the device
        int fd = open((*it).c_str(), O_RDWR | O_NONBLOCK | O_NOCTTY);

        if (fd >= 0) {
            // Get serial_info
            if (ioctl(fd, TIOCGSERIAL, &serinfo)==0) {
                // If device type is no PORT_UNKNOWN we accept the port
                if (serinfo.type != PORT_UNKNOWN)
                    comList.push_back(*it);
            }
            close(fd);
        }
        it ++;
    }
}

list<string> getComList() {
    int n;
    struct dirent **namelist;
    list<string> comList;
    list<string> comList8250;
    const char* sysdir = "/sys/class/tty/";

    // Scan through /sys/class/tty - it contains all tty-devices in the system
    n = scandir(sysdir, &namelist, NULL, NULL);
    if (n < 0)
        perror("scandir");
    else {
        while (n--) {
            if (strcmp(namelist[n]->d_name,"..") && strcmp(namelist[n]->d_name,".")) {

                // Construct full absolute file path
                string devicedir = sysdir;
                devicedir += namelist[n]->d_name;

                // Register the device
                register_comport(comList, comList8250, devicedir);
            }
            free(namelist[n]);
        }
        free(namelist);
    }

    // Only non-serial8250 has been added to comList without any further testing
    // serial8250-devices must be probe to check for validity
    probe_serial8250_comports(comList, comList8250);

    // Return the lsit of detected comports
    return comList;
}


int main() {
    list<string> l = getComList();

    list<string>::iterator it = l.begin();
    while (it != l.end()) {
        cout << *it << endl;
        it++;
    }

    return 0;   
}

How to pass optional parameters while omitting some other optional parameters?

You could try to set title to null.

This worked for me.

error('This is the ',null,1000)

How can I get new selection in "select" in Angular 2?

From angular 7 and up, since ngModel is deprecated, we can simply use the control to get the new selected value very easily in a reactive way.

Example:

<form [formGroup]="frmMyForm">
  <select class="form-control" formControlName="fieldCtrl">
    <option value=""></option>
    <option value="val1">label val 1</option>
    <option value="val2">label val 2</option>
    <option value="val3">label val 3</option>
  </select>
</form>
this.frmMyForm.get('fieldCtrl').valueChanges.subscribe( value => {
  this.selectedValue = value;
});

By using this fully reactive way, we can upgrade older angular application version to newer ones more easily.

CSS Box Shadow Bottom Only

try this to get the box-shadow under your full control.

    <html>

    <head>
        <style> 
            div {
                width:300px;
                height:100px;
                background-color:yellow;
                box-shadow: 0 10px black inset,0 -10px red inset, -10px 0 blue inset, 10px 0 green inset;
           }
        </style>
    </head>
    <body>
        <div>
        </div>
    </body>

    </html>

this would apply to outer box-shadow as well.

How to parse JSON to receive a Date object in JavaScript?

using eval function works just have to remove the forward slash at front and back.

var date1 = "/Date(25200000)/"
eval("new " + date1.substring(1, date1.length - 1));

yields Thu Jan 01 1970 00:00:00 GMT-0700 (US Mountain Standard Time)

What is the effect of extern "C" in C++?

In every C++ program, all non-static functions are represented in the binary file as symbols. These symbols are special text strings that uniquely identify a function in the program.

In C, the symbol name is the same as the function name. This is possible because in C no two non-static functions can have the same name.

Because C++ allows overloading and has many features that C does not — like classes, member functions, exception specifications - it is not possible to simply use the function name as the symbol name. To solve that, C++ uses so-called name mangling, which transforms the function name and all the necessary information (like the number and size of the arguments) into some weird-looking string processed only by the compiler and linker.

So if you specify a function to be extern C, the compiler doesn't performs name mangling with it and it can be directly accessed using its symbol name as the function name.

This comes handy while using dlsym() and dlopen() for calling such functions.

How to open a specific port such as 9090 in Google Compute Engine

console.cloud.google.com >> select project >> Networking > VPC network >> firewalls >> create firewall.

To apply the rule to VM instances, select Targets, "Specified target tags", and enter into "Target tags" the name of the tag. This tag will be used to apply the new firewall rule onto whichever instance you'd like.

in "Protocols and Ports" enter tcp:9090

Click Save.

Array and string offset access syntax with curly braces is deprecated

It's really simple to fix the issue, however keep in mind that you should fork and commit your changes for each library you are using in their repositories to help others as well.

Let's say you have something like this in your code:

$str = "test";
echo($str{0});

since PHP 7.4 curly braces method to get individual characters inside a string has been deprecated, so change the above syntax into this:

$str = "test";
echo($str[0]);

Fixing the code in the question will look something like this:

public function getRecordID(string $zoneID, string $type = '', string $name = ''): string
{
    $records = $this->listRecords($zoneID, $type, $name);
    if (isset($records->result[0]->id)) {
        return $records->result[0]->id;
    }
    return false;
}

What's the simplest way to list conflicted files in Git?

you may hit git ls-files -u on your command line it lists down files with conflicts

Collapse all methods in Visual Studio Code

To collapse methods in the Visual Studio Code editor:

  1. Right-click anywhere in document and select "format document" option.
  2. Then hover next to number lines and you will see the (-) sign for collapsing method.

NB.: As per the Visual Studio Code documentation, a folding region starts when a line has a smaller indent than one or more following lines, and ends when there is a line with the same or smaller indent.

Android list view inside a scroll view

This code will solve your problem if you have implemented just a ListView in a code.

If you are using RelativeLayout as ListView child than this code return a NullPointerException here listItem.measure(0, 0);, because of RelativeLayout.And the solution is put your Relativelayout inside a LinearLayout and it will work fine.

public static void setListViewHeightBasedOnChildren(ListView listView) {
    ListAdapter listAdapter = listView.getAdapter(); 
    if (listAdapter == null) {
        // pre-condition
        return;
    }

    int totalHeight = 0;
    for (int i = 0; i < listAdapter.getCount(); i++) {
        View listItem = listAdapter.getView(i, null, listView);
        listItem.measure(0, 0);
        totalHeight += listItem.getMeasuredHeight();
    }

    ViewGroup.LayoutParams params = listView.getLayoutParams();
    params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
    listView.setLayoutParams(params);
    listView.requestLayout();
}

Regular expression negative lookahead

A negative lookahead says, at this position, the following regex can not match.

Let's take a simplified example:

a(?!b(?!c))

a      Match: (?!b) succeeds
ac     Match: (?!b) succeeds
ab     No match: (?!b(?!c)) fails
abe    No match: (?!b(?!c)) fails
abc    Match: (?!b(?!c)) succeeds

The last example is a double negation: it allows a b followed by c. The nested negative lookahead becomes a positive lookahead: the c should be present.

In each example, only the a is matched. The lookahead is only a condition, and does not add to the matched text.

Javamail Could not convert socket to TLS GMail

Make sure your antivirus program isn't interfering and be sure to add an exclusion to your firewall.

html5 audio player - jquery toggle click play/pause?

You can call native methods trough trigger in jQuery. Just do this:

$('.play').trigger("play");

And the same for pause: $('.play').trigger("pause");

EDIT: as F... pointed out in the comments, you can do something similar to access properties: $('.play').prop("paused");

Why does JSHint throw a warning if I am using const?

In a new version of Dreamweaver to solve this error

  • Go to Edit->Preference->Linting
  • And the go-to js Edit rule set and past

    "jshintConfig":{ "esversion": 6 }

How to use the switch statement in R functions?

Well, switch probably wasn't really meant to work like this, but you can:

AA = 'foo'
switch(AA, 
foo={
  # case 'foo' here...
  print('foo')
},
bar={
  # case 'bar' here...
  print('bar')    
},
{
   print('default')
}
)

...each case is an expression - usually just a simple thing, but here I use a curly-block so that you can stuff whatever code you want in there...

How to change the order of DataFrame columns?

Hackiest method in the book

df.insert(0, "test", df["mean"])
df = df.drop(columns=["mean"]).rename(columns={"test": "mean"})

Intercept page exit event

Instead of an annoying confirmation popup, it would be nice to delay leaving just a bit (matter of milliseconds) to manage successfully posting the unsaved data to the server, which I managed for my site using writing dummy text to the console like this:

window.onbeforeunload=function(e){
  // only take action (iterate) if my SCHEDULED_REQUEST object contains data        
  for (var key in SCHEDULED_REQUEST){   
    postRequest(SCHEDULED_REQUEST); // post and empty SCHEDULED_REQUEST object
    for (var i=0;i<1000;i++){
      // do something unnoticable but time consuming like writing a lot to console
      console.log('buying some time to finish saving data'); 
    };
    break;
  };
}; // no return string --> user will leave as normal but data is send to server

Edit: See also Synchronous_AJAX and how to do that with jquery

Java, Shifting Elements in an Array

You can use the Below codes for shifting not rotating:

    int []arr = {1,2,3,4,5,6,7,8,9,10,11,12};
            int n = arr.length;
            int d = 3;

Programm for shifting array of size n by d elements towards left:

    Input : {1,2,3,4,5,6,7,8,9,10,11,12}
    Output: {4,5,6,7,8,9,10,11,12,10,11,12}

        public void shiftLeft(int []arr,int d,int n) {
            for(int i=0;i<n-d;i++) {
                arr[i] = arr[i+d];
            }
        }

Programm for shifting array of size n by d elements towards right:

    Input : {1,2,3,4,5,6,7,8,9,10,11,12}
    Output: {1,2,3,1,2,3,4,5,6,7,8,9}

        public void shiftRight(int []arr,int d,int n) {

            for(int i=n-1;i>=d;i--) {
                arr[i] = arr[i-d];
            }
        }

favicon.png vs favicon.ico - why should I use PNG instead of ICO?

For what it's worth, I do this:

    <!-- Favicon - Generic -->
    <link rel="icon" href="path/favicon-32_x_32.png" sizes="32x32">
    <link rel="icon" href="path/favicon-57_x_57.png" sizes="57x57">
    <link rel="icon" href="path/favicon-76_x_76.png" sizes="76x76">
    <link rel="icon" href="path/favicon-96_x_96.png" sizes="96x96">
    <link rel="icon" href="path/favicon-128_x_128.png" sizes="128x128">
    <link rel="icon" href="path/favicon-192_x_192.png" sizes="192x192">
    <link rel="icon" href="path/favicon-228_x_228.png" sizes="228x228">
    <!-- Favicon - Android -->
    <link rel="shortcut icon" href="path/favicon-196_x_196.png" sizes="196x196">
    <!-- Favicon - iOS -->
    <link rel="apple-touch-icon" href="path/favicon-120_x_120.png" sizes="120x120">
    <link rel="apple-touch-icon" href="path/favicon-152_x_152.png" sizes="152x152">
    <link rel="apple-touch-icon" href="path/favicon-180_x_180.png" sizes="180x180">

And I still keep the favicon.ico in root.

Asynchronous Requests with Python requests

Note

The below answer is not applicable to requests v0.13.0+. The asynchronous functionality was moved to grequests after this question was written. However, you could just replace requests with grequests below and it should work.

I've left this answer as is to reflect the original question which was about using requests < v0.13.0.


To do multiple tasks with async.map asynchronously you have to:

  1. Define a function for what you want to do with each object (your task)
  2. Add that function as an event hook in your request
  3. Call async.map on a list of all the requests / actions

Example:

from requests import async
# If using requests > v0.13.0, use
# from grequests import async

urls = [
    'http://python-requests.org',
    'http://httpbin.org',
    'http://python-guide.org',
    'http://kennethreitz.com'
]

# A simple task to do to each response object
def do_something(response):
    print response.url

# A list to hold our things to do via async
async_list = []

for u in urls:
    # The "hooks = {..." part is where you define what you want to do
    # 
    # Note the lack of parentheses following do_something, this is
    # because the response will be used as the first argument automatically
    action_item = async.get(u, hooks = {'response' : do_something})

    # Add the task to our list of things to do via async
    async_list.append(action_item)

# Do our list of things to do via async
async.map(async_list)

docker container ssl certificates

You can use relative path to mount the volume to container:

docker run -v `pwd`/certs:/container/path/to/certs ...

Note the back tick on the pwd which give you the present working directory. It assumes you have the certs folder in current directory that the docker run is executed. Kinda great for local development and keep the certs folder visible to your project.

How to switch a user per task or set of tasks?

You can specify become_method to override the default method set in ansible.cfg (if any), and which can be set to one of sudo, su, pbrun, pfexec, doas, dzdo, ksu.

- name: I am confused
  command: 'whoami'
  become: true
  become_method: su
  become_user: some_user
  register: myidentity

- name: my secret identity
  debug:
    msg: '{{ myidentity.stdout }}'

Should display

TASK [my-task : my secret identity] ************************************************************
ok: [my_ansible_server] => {
    "msg": "some_user"
}

What is the difference between "is None" and "== None"

class Foo:
    def __eq__(self,other):
        return True
foo=Foo()

print(foo==None)
# True

print(foo is None)
# False

How to do a https request with bad certificate?

Proper way (as of Go 1.13) (provided by answer below):

customTransport := http.DefaultTransport.(*http.Transport).Clone()
customTransport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
client := &http.Client{Transport: customTransport}

Original Answer:

Here's a way to do it without losing the default settings of the DefaultTransport, and without needing the fake request as per user comment.

defaultTransport := http.DefaultTransport.(*http.Transport)

// Create new Transport that ignores self-signed SSL
customTransport := &http.Transport{
  Proxy:                 defaultTransport.Proxy,
  DialContext:           defaultTransport.DialContext,
  MaxIdleConns:          defaultTransport.MaxIdleConns,
  IdleConnTimeout:       defaultTransport.IdleConnTimeout,
  ExpectContinueTimeout: defaultTransport.ExpectContinueTimeout,
  TLSHandshakeTimeout:   defaultTransport.TLSHandshakeTimeout,
  TLSClientConfig:       &tls.Config{InsecureSkipVerify: true},
}
client := &http.Client{Transport: customTransport}

Shorter way:

customTransport := &(*http.DefaultTransport.(*http.Transport)) // make shallow copy
customTransport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
client := &http.Client{Transport: customTransport}

Warning: For testing/development purposes only. Anything else, proceed at your own risk!!!

count files in specific folder and display the number into 1 cel

Try below code :

Assign the path of the folder to variable FolderPath before running the below code.

Sub sample()

    Dim FolderPath As String, path As String, count As Integer
    FolderPath = "C:\Documents and Settings\Santosh\Desktop"

    path = FolderPath & "\*.xls"

    Filename = Dir(path)

    Do While Filename <> ""
       count = count + 1
        Filename = Dir()
    Loop

    Range("Q8").Value = count
    'MsgBox count & " : files found in folder"
End Sub

How to add an Access-Control-Allow-Origin header

The accepted answer doesn't work for me unfortunately, since my site CSS files @import the font CSS files, and these are all stored on a Rackspace Cloud Files CDN.

Since the Apache headers are never generated (since my CSS is not on Apache), I had to do several things:

  1. Go to the Cloud Files UI and add a custom header (Access-Control-Allow-Origin with value *) for each font-awesome file
  2. Change the Content-Type of the woff and ttf files to font/woff and font/ttf respectively

See if you can get away with just #1, since the second requires a bit of command line work.

To add the custom header in #1:

  • view the cloud files container for the file
  • scroll down to the file
  • click the cog icon
  • click Edit Headers
  • select Access-Control-Allow-Origin
  • add the single character '*' (without the quotes)
  • hit enter
  • repeat for the other files

If you need to continue and do #2, then you'll need a command line with CURL

curl -D - --header "X-Auth-Key: your-auth-key-from-rackspace-cloud-control-panel" --header "X-Auth-User: your-cloud-username" https://auth.api.rackspacecloud.com/v1.0

From the results returned, extract the values for X-Auth-Token and X-Storage-Url

curl -X POST \
  -H "Content-Type: font/woff" \
  --header "X-Auth-Token: returned-x-auth-token" returned-x-storage-url/name-of-your-container/fonts/fontawesome-webfont.woff

curl -X POST \
  -H "Content-Type: font/ttf" \
  --header "X-Auth-Token: returned-x-auth-token" returned-x-storage-url/name-of-your-container/fonts/fontawesome-webfont.ttf

Of course, this process only works if you're using the Rackspace CDN. Other CDNs may offer similar facilities to edit object headers and change content types, so maybe you'll get lucky (and post some extra info here).

How to post data using HttpClient?

Use UploadStringAsync method:

WebClient webClient = new WebClient();
webClient.UploadStringCompleted += (s, e) =>
{
    if (e.Error != null)
    {
        //handle your error here
    }
    else
    {
        //post was successful, so do what you need to do here
    }
};

webClient.UploadStringAsync(new Uri(yourUri), UriKind.Absolute), "POST", yourParameters);     

Angular 2.0 and Modal Dialog

Here is my full implementation of modal bootstrap angular2 component:

I assume that in your main index.html file (with <html> and <body> tags) at the bottom of <body> tag you have:

  <script src="assets/js/jquery-2.1.1.js"></script>
  <script src="assets/js/bootstrap.min.js"></script>

modal.component.ts:

import { Component, Input, Output, ElementRef, EventEmitter, AfterViewInit } from '@angular/core';

declare var $: any;// this is very importnant (to work this line: this.modalEl.modal('show')) - don't do this (becouse this owerride jQuery which was changed by bootstrap, included in main html-body template): let $ = require('../../../../../node_modules/jquery/dist/jquery.min.js');

@Component({
  selector: 'modal',
  templateUrl: './modal.html',
})
export class Modal implements AfterViewInit {

    @Input() title:string;
    @Input() showClose:boolean = true;
    @Output() onClose: EventEmitter<any> = new EventEmitter();

    modalEl = null;
    id: string = uniqueId('modal_');

    constructor(private _rootNode: ElementRef) {}

    open() {
        this.modalEl.modal('show');
    }

    close() {
        this.modalEl.modal('hide');
    }

    closeInternal() { // close modal when click on times button in up-right corner
        this.onClose.next(null); // emit event
        this.close();
    }

    ngAfterViewInit() {
        this.modalEl = $(this._rootNode.nativeElement).find('div.modal');
    }

    has(selector) {
        return $(this._rootNode.nativeElement).find(selector).length;
    }
}

let modal_id: number = 0;
export function uniqueId(prefix: string): string {
    return prefix + ++modal_id;
}

modal.html:

<div class="modal inmodal fade" id="{{modal_id}}" tabindex="-1" role="dialog"  aria-hidden="true" #thisModal>
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header" [ngClass]="{'hide': !(has('mhead') || title) }">
                <button *ngIf="showClose" type="button" class="close" (click)="closeInternal()"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
                <ng-content select="mhead"></ng-content>
                <h4 *ngIf='title' class="modal-title">{{ title }}</h4>
            </div>
            <div class="modal-body">
                <ng-content></ng-content>
            </div>

            <div class="modal-footer" [ngClass]="{'hide': !has('mfoot') }" >
                <ng-content select="mfoot"></ng-content>
            </div>
        </div>
    </div>
</div>

And example of usage in client Editor component: client-edit-component.ts:

import { Component } from '@angular/core';
import { ClientService } from './client.service';
import { Modal } from '../common';

@Component({
  selector: 'client-edit',
  directives: [ Modal ],
  templateUrl: './client-edit.html',
  providers: [ ClientService ]
})
export class ClientEdit {

    _modal = null;

    constructor(private _ClientService: ClientService) {}

    bindModal(modal) {this._modal=modal;}

    open(client) {
        this._modal.open();
        console.log({client});
    }

    close() {
        this._modal.close();
    }

}

client-edit.html:

<modal [title]='"Some standard title"' [showClose]='true' (onClose)="close()" #editModal>{{ bindModal(editModal) }}
    <mhead>Som non-standart title</mhead>
    Some contents
    <mfoot><button calss='btn' (click)="close()">Close</button></mfoot>
</modal>

Ofcourse title, showClose, <mhead> and <mfoot> ar optional parameters/tags.

Print all properties of a Python Class

Here is full code. The result is exactly what you want.

class Animal(object):
    def __init__(self):
        self.legs = 2
        self.name = 'Dog'
        self.color= 'Spotted'
        self.smell= 'Alot'
        self.age  = 10
        self.kids = 0

if __name__ == '__main__':
    animal = Animal()
    temp = vars(animal)
    for item in temp:
        print item , ' : ' , temp[item]
        #print item , ' : ', temp[item] ,

EditText request focus

It has worked for me as follows.

ed1.requestFocus();

            return; //Faça um return para retornar o foco

Check if xdebug is working

Try as following, should return "exists" or "non exists":

<?php
echo (extension_loaded('xdebug') ? '' : 'non '), 'exists';

How can I remove all my changes in my SVN working directory?

svn revert will undo any local changes you've made

How to make a redirection on page load in JSF 1.x

you should use action instead of actionListener:

<h:commandLink id="close" action="#{bean.close}" value="Close" immediate="true" 
                                   />

and in close method you right something like:

public String close() {
   return "index?faces-redirect=true";
}

where index is one of your pages(index.xhtml)

Of course, all this staff should be written in our original page, not in the intermediate. And inside the close() method you can use the parameters to dynamically choose where to redirect.

How to convert a hex string to hex number

Use format string

intNum = 123
print "0x%x"%(intNum)

or hex function.

intNum = 123
print hex(intNum)

Excel formula to get cell color

Color is not data.

The Get.cell technique has flaws.

  1. It does not update as soon as the cell color changes, but only when the cell (or the sheet) is recalculated.
  2. It does not have sufficient numbers for the millions of colors that are available in modern Excel. See the screenshot and notice how the different intensities of yellow or purple all have the same number.

enter image description here

That does not surprise, since the Get.cell uses an old XML command, i.e. a command from the macro language Excel used before VBA was introduced. At that time, Excel colors were limited to less than 60.

Again: Color is not data.

If you want to color-code your cells, use conditional formatting based on the cell values or based on rules that can be expressed with logical formulas. The logic that leads to conditional formatting can also be used in other places to report on the data, regardless of the color value of the cell.

Correct use for angular-translate in controllers

Actually, you should use the translate directive for such stuff instead.

<h1 translate="{{pageTitle}}"></h1>

The directive takes care of asynchronous execution and is also clever enough to unwatch translation ids on the scope if the translation has no dynamic values.

However, if there's no way around and you really have to use $translate service in the controller, you should wrap the call in a $translateChangeSuccess event using $rootScope in combination with $translate.instant() like this:

.controller('foo', function ($rootScope, $scope, $translate) {
  $rootScope.$on('$translateChangeSuccess', function () {
    $scope.pageTitle = $translate.instant('PAGE.TITLE');
  });
})

So why $rootScope and not $scope? The reason for that is, that in angular-translate's events are $emited on $rootScope rather than $broadcasted on $scope because we don't need to broadcast through the entire scope hierarchy.

Why $translate.instant() and not just async $translate()? When $translateChangeSuccess event is fired, it is sure that the needed translation data is there and no asynchronous execution is happening (for example asynchronous loader execution), therefore we can just use $translate.instant() which is synchronous and just assumes that translations are available.

Since version 2.8.0 there is also $translate.onReady(), which returns a promise that is resolved as soon as translations are ready. See the changelog.

Convert xlsx file to csv using batch

Get all file item and filter them by suffix and then use PowerShell Excel VBA object to save the excel files to csv files.

$excelApp = New-Object -ComObject Excel.Application 
$excelApp.DisplayAlerts = $false 

$ExcelFiles | ForEach-Object { 
    $workbook = $excelApp.Workbooks.Open($_.FullName) 
    $csvFilePath = $_.FullName -replace "\.xlsx$", ".csv" 
    $workbook.SaveAs($csvFilePath, [Microsoft.Office.Interop.Excel.XlFileFormat]::xlCSV) 
    $workbook.Close() 
} 

You can find the complete sample here How to convert Excel xlsx file to csv file in batch by PowerShell

How to use sed to replace only the first occurrence in a file?

i would do this with an awk script:

BEGIN {i=0}
(i==0) && /#include/ {print "#include \"newfile.h\""; i=1}
{print $0}    
END {}

then run it with awk:

awk -f awkscript headerfile.h > headerfilenew.h

might be sloppy, I'm new to this.

Oracle Installer:[INS-13001] Environment does not meet minimum requirements

its awful oracle installer:

[INS-13001]

I got it as I used MY_PC as NETBIOS name instead of MYPC (Underscore is bad for it..)

Can be an historical reason.. but message is obscure.

Using .otf fonts on web browsers

You can implement your OTF font using @font-face like:

@font-face {
    font-family: GraublauWeb;
    src: url("path/GraublauWeb.otf") format("opentype");
}

@font-face {
    font-family: GraublauWeb;
    font-weight: bold;
    src: url("path/GraublauWebBold.otf") format("opentype");
}

// Edit: OTF now works in most browsers, see comments

However if you want to support a wide variety of browsers i would recommend you to switch to WOFF and TTF font types. WOFF type is implemented by every major desktop browser, while the TTF type is a fallback for older Safari, Android and iOS browsers. If your font is a free font, you could convert your font using for example a transfonter.

@font-face {
    font-family: GraublauWeb;
    src: url("path/GraublauWebBold.woff") format("woff"), url("path/GraublauWebBold.ttf")  format("truetype");
}

If you want to support nearly every browser that is still out there (not necessary anymore IMHO), you should add some more font-types like:

@font-face {
    font-family: GraublauWeb;
    src: url("webfont.eot"); /* IE9 Compat Modes */
    src: url("webfont.eot?#iefix") format("embedded-opentype"), /* IE6-IE8 */
         url("webfont.woff") format("woff"), /* Modern Browsers */
         url("webfont.ttf")  format("truetype"), /* Safari, Android, iOS */
         url("webfont.svg#svgFontName") format("svg"); /* Legacy iOS */
}

You can read more about why all these types are implemented and their hacks here. To get a detailed view of which file-types are supported by which browsers, see:

@font-face Browser Support

EOT Browser Support

WOFF Browser Support

TTF Browser Support

SVG-Fonts Browser Support

hope this helps

How do I use grep to search the current directory for all files having the a string "hello" yet display only .h and .cc files?

find . -name \*.cc -print0 -or -name \*.h -print0 | xargs -0 grep "hello".

Check the manual pages for find and xargs for details.

What's the difference between align-content and align-items?

I had the same confusion. After some tinkering based on many of the answers above, I can finally see the differences. In my humble opinion, the distinction is best demonstrated with a flex container that satisfies the following two conditions:

  1. The flex container itself has a height constraint (e.g., min-height: 60rem) and thus can become too tall for its content
  2. The child items enclosed in the container have uneven heights

Condition 1 helps me understand what content means relative to its parent container. When the content is flush with the container, we will not be able to see any positioning effects coming from align-content. It is only when we have extra space along the cross axis, we start to see its effect: It aligns the content relative to the boundaries of the parent container.

Condition 2 helps me visualize the effects of align-items: it aligns items relative to each other.


Here is a code example. Raw materials come from Wes Bos' CSS Grid tutorial (21. Flexbox vs. CSS Grid)

  • Example HTML:
  <div class="flex-container">
    <div class="item">Short</div>
    <div class="item">Longerrrrrrrrrrrrrr</div>
    <div class="item"></div>
    <div class="item" id="tall">This is Many Words</div>
    <div class="item">Lorem, ipsum.</div>
    <div class="item">10</div>
    <div class="item">Snickers</div>
    <div class="item">Wes Is Cool</div>
    <div class="item">Short</div>
  </div>
  • Example CSS:
.flex-container {
  display: flex;
  /*dictates a min-height*/
  min-height: 60rem;
  flex-flow: row wrap;
  border: 5px solid white;
  justify-content: center;
  align-items: center;
  align-content: flex-start;
 }

#tall {
  /*intentionally made tall*/
  min-height: 30rem;
}

.item {
  margin: 10px;
  max-height: 10rem;
}

Example 1: Let's narrow the viewport so that the content is flush with the container. This is when align-content: flex-start; has no effects since the entire content block is tightly fit inside the container (no extra room for repositioning!)

Also, note the 2nd row--see how the items are center aligned among themselves.

enter image description here

Example 2: As we widen the viewport, we no longer have enough content to fill the entire container. Now we start to see the effects of align-content: flex-start;--it aligns the content relative to the top edge of the container. enter image description here


These examples are based on flexbox, but the same principles are applicable to CSS grid. Hope this helps :)

Why is "using namespace std;" considered bad practice?

If you import the right header files you suddenly have names like hex, left, plus or count in your global scope. This might be surprising if you are not aware that std:: contains these names. If you also try to use these names locally it can lead to quite some confusion.

If all the standard stuff is in its own namespace you don't have to worry about name collisions with your code or other libraries.

How to validate array in Laravel?

The below code working for me on array coming from ajax call .

  $form = $request->input('form');
  $rules = array(
            'facebook_account' => 'url',
            'youtube_account' => 'url',
            'twitter_account' => 'url',
            'instagram_account' => 'url',
            'snapchat_account' => 'url',
            'website' => 'url',
        );
        $validation = Validator::make($form, $rules);

        if ($validation->fails()) {
            return Response::make(['error' => $validation->errors()], 400);
        }

Comments in Android Layout xml

<!-- comment here -->

How do you get the current text contents of a QComboBox?

You can convert the QString type to python string by just using the str function. Assuming you are not using any Unicode characters you can get a python string as below:

text = str(combobox1.currentText())

If you are using any unicode characters, you can do:

text = unicode(combobox1.currentText())

How do I use the lines of a file as arguments of a command?

As already mentioned, you can use the backticks or $(cat filename).

What was not mentioned, and I think is important to note, is that you must remember that the shell will break apart the contents of that file according to whitespace, giving each "word" it finds to your command as an argument. And while you may be able to enclose a command-line argument in quotes so that it can contain whitespace, escape sequences, etc., reading from the file will not do the same thing. For example, if your file contains:

a "b c" d

the arguments you will get are:

a
"b
c"
d

If you want to pull each line as an argument, use the while/read/do construct:

while read i ; do command_name $i ; done < filename

Checking if a folder exists (and creating folders) in Qt, C++

When you use QDir.mkpath() it returns true if the path already exists, in the other hand QDir.mkdir() returns false if the path already exists. So depending on your program you have to choose which fits better.

You can see more on Qt Documentation

Can I fade in a background image (CSS: background-image) with jQuery?

I know i'm late, but I found a way using jquery which works on every browser(i tested it on chrome, firefox and Ie 9)and th fore-ground elements are always displayed instead of css3 transition property.

create 2 absolute wrapper and using z-index.

First set the elements that have to be in the fore-ground with the highest z-index property value, and the other elemets(all included in the body, so: body{}) with a lower z-index property value than the fore-ground elements'one , at least of 2 number lower.

HTML part:

         <div class="wrapper" id="wrapper1"></div>
         <div class="wrapper" id="wrapper2"></div>

css part:

        .fore-groundElements{              //select all fore-ground elements
                  z-index:0;               //>=0
        }
       .wrapper{
                  background-size: cover;
                  width:100%;
                  height:100%;
                  background-size: 100% 100%;
                  position:absolute;
         }

        #wrapper1{
               z-index:-1; 
        }


        #wrapper2{
                 z-index:-2;
         }
         body{

              height:100%;
              width:100%;
              margin:0px;   
              display:cover;
              z-index:-3                          //<=-3
         }

than the javascript/jquery one:

i needed to change the background image every three second so i used a set timeout.

this is the code:

  $(document).ready(main);

  var main = function(){

             var imgPath=[imagesPath1,..,...];                 // the array in which store the image paths

             var newWrapper;                     // the wrapper to display 
             var currentWrapper;                 //the current displayed wrapper which has to be faded
             var l=2;                             // the next image index  to be displayed, it is set to 2 because the first two position of the array(first two images) start already setted up
             var imgNumber= imgPath.length;        //to know when the images are over and restart the carousel
             var currentImg;                       //the next image path to be displayed


             $('#wrapper1').css("background-image", 'url'+imgPath[0]);         //pre set the first wrapper background images
             $('#wrapper2').css("background-image", 'url'+imgPath[1]);          //pre set the first wrapper background images   

             setInterval(myfunction,3000);                //refresh the background image every three seconds

             function myfunction(){
                    if(l===imgNumber-1){               //restart the carousel if every single image has already been displayed                  
                         l=0;
                     };

             if(l%2==0||l%2==2){                    //set the wrapper that will be displaied after the fadeOut callback function
                  currentWrapper='#wrapper1';         
                  newWrapper='#wrapper2';
             }else{
                  currentWrapper='#wrapper2';
                  newWrapper='#wrapper1';
             };
             currentImg=imgPath[l];
            $(currentWrapper).fadeOut(1000,function(){               //fade out the current wrapper, so now the back-ground wrapper is fully displayed
                  $(newWrapper).css("z-index", "-1");                //move the shown wrapper in the fore-ground
                  $(currentWrapper).css("z-index","-2");             //move the hidden wrapper in the back ground
                  $(currentWrapper).css("background-image",'url'+currentImg);                   // sets up the next image that is now shown in the actually hidden background wrapper
                  $(currentWrapper).show();          //shows the background wrapper, which is not visible yet, and it will be shown the next time the setInterval event will be triggered
                  l++;                         //set the next image index that will be set the next time the setInterval event will be triggered 
             });


         };                   //end of myFunction
  }                          //end of main

i hope that my answer is clear,if you need more explanation comment it.

sorry for my english :)

How to link an input button to a file select window?

You could use JavaScript and trigger the hidden file input when the button input has been clicked.

http://jsfiddle.net/gregorypratt/dhyzV/ - simple

http://jsfiddle.net/gregorypratt/dhyzV/1/ - fancier with a little JQuery

Or, you could style a div directly over the file input and set pointer-events in CSS to none to allow the click events to pass through to the file input that is "behind" the fancy div. This only works in certain browsers though; http://caniuse.com/pointer-events

How can bcrypt have built-in salts?

This is from PasswordEncoder interface documentation from Spring Security,

 * @param rawPassword the raw password to encode and match
 * @param encodedPassword the encoded password from storage to compare with
 * @return true if the raw password, after encoding, matches the encoded password from
 * storage
 */
boolean matches(CharSequence rawPassword, String encodedPassword);

Which means, one will need to match rawPassword that user will enter again upon next login and matches it with Bcrypt encoded password that's stores in database during previous login/registration.

how to remove json object key and value.?

There are several ways to do this, lets see them one by one:

  1. delete method: The most common way

_x000D_
_x000D_
const myObject = {_x000D_
    "employeeid": "160915848",_x000D_
    "firstName": "tet",_x000D_
    "lastName": "test",_x000D_
    "email": "[email protected]",_x000D_
    "country": "Brasil",_x000D_
    "currentIndustry": "aaaaaaaaaaaaa",_x000D_
    "otherIndustry": "aaaaaaaaaaaaa",_x000D_
    "currentOrganization": "test",_x000D_
    "salary": "1234567"_x000D_
};_x000D_
_x000D_
delete myObject['currentIndustry'];_x000D_
// OR delete myObject.currentIndustry;_x000D_
  _x000D_
console.log(myObject);
_x000D_
_x000D_
_x000D_

  1. By making key value undefined: Alternate & a faster way:

_x000D_
_x000D_
let myObject = {_x000D_
    "employeeid": "160915848",_x000D_
    "firstName": "tet",_x000D_
    "lastName": "test",_x000D_
    "email": "[email protected]",_x000D_
    "country": "Brasil",_x000D_
    "currentIndustry": "aaaaaaaaaaaaa",_x000D_
    "otherIndustry": "aaaaaaaaaaaaa",_x000D_
    "currentOrganization": "test",_x000D_
    "salary": "1234567"_x000D_
  };_x000D_
_x000D_
myObject.currentIndustry = undefined;_x000D_
myObject = JSON.parse(JSON.stringify(myObject));_x000D_
_x000D_
console.log(myObject);
_x000D_
_x000D_
_x000D_

  1. With es6 spread Operator:

_x000D_
_x000D_
const myObject = {_x000D_
    "employeeid": "160915848",_x000D_
    "firstName": "tet",_x000D_
    "lastName": "test",_x000D_
    "email": "[email protected]",_x000D_
    "country": "Brasil",_x000D_
    "currentIndustry": "aaaaaaaaaaaaa",_x000D_
    "otherIndustry": "aaaaaaaaaaaaa",_x000D_
    "currentOrganization": "test",_x000D_
    "salary": "1234567"_x000D_
};_x000D_
_x000D_
_x000D_
const {currentIndustry, ...filteredObject} = myObject;_x000D_
console.log(filteredObject);
_x000D_
_x000D_
_x000D_

Or if you can use omit() of underscore js library:

const filteredObject = _.omit(currentIndustry, 'myObject');
console.log(filteredObject);

When to use what??

If you don't wanna create a new filtered object, simply go for either option 1 or 2. Make sure you define your object with let while going with the second option as we are overriding the values. Or else you can use any of them.

hope this helps :)

What does the Visual Studio "Any CPU" target mean?

Check out the article Visual Studio .NET Platform Target Explained.

The default setting, "Any CPU", means that the assembly will run natively on the CPU it is currently running on. Meaning, it will run as 64-bit on a 64-bit machine and 32-bit on a 32-bit machine. If the assembly is called from a 64-bit application, it will perform as a 64-bit assembly and so on.

The above link has been reported to be broken, so here is another article with a similar explanation: What AnyCPU Really Means As Of .NET 4.5 and Visual Studio 11

How do I get the project basepath in CodeIgniter

use base_url()

echo $baseurl=base_url();

if you need to pass url to a function then use site_url()

 echo site_url('controller/function');

if you need the root path then FCPATH..

echo FCPATH;

Why would Oracle.ManagedDataAccess not work when Oracle.DataAccess does?

To avoid all the Oracle mess of not knowing where it is looking for the TNSNAMES.ORA (I have the added confusion of multiple Oracle versions and 32/64 bit), you can copy the setting from your existing TNSNAMES.ORA to your own config file and use that for your connection.
Say you're happy with the 'DSDSDS' reference in TNSNAMES.ORA which maps to something like:

DSDSDS=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(Host=DSDSDSHost)(Port=4521)))(CONNECT_DATA=(SERVICE_NAME=DSDSDSService)))

You can take the text after the first '=' and use that wherever you are using 'DSDSDS' and it won't need to find TNSNAMES.ORA to know how to connect.
Now your connection string would look like this:
string connectionString = "Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(Host=DSDSDSHost)(Port=4521)))(CONNECT_DATA=(SERVICE_NAME=DSDSDSService)));User Id=UNUNUN;Password=PWPWPW;";

How to log cron jobs?

There are at least three different types of logging:

  1. The logging BEFORE the program is executed, which only logs IF the cronjob TRIED to execute the command. That one is located in /var/log/syslog, as already mentioned by @Matthew Lock.

  2. The logging of errors AFTER the program tried to execute, which can be sent to an email or to a file, as mentioned by @Spliffster. I prefer logging to a file, because with email THEN you have a NEW source of problems, and its checking if email sending and reception is working perfectly. Sometimes it is, sometimes it's not. For example, in a simple common desktop machine in which you are not interested in configuring an smtp, sometimes you will prefer logging to a file:

     * * * *  COMMAND_ABSOLUTE_PATH > /ABSOLUTE_PATH_TO_LOG 2>&1
    
    • I would also consider checking the permissions of /ABSOLUTE_PATH_TO_LOG, and run the command from that user's permissions. Just for verification, while you test whether it might be a potential source of problems.
  3. The logging of the program itself, with its own error-handling and logging for tracking purposes.

There are some common sources of problems with cronjobs: * The ABSOLUTE PATH of the binary to be executed. When you run it from your shell, it might work, but the cron process seems to use another environment, and hence it doesn't always find binaries if you don't use the absolute path. * The LIBRARIES used by a binary. It's more or less the same previous point, but make sure that, if simply putting the NAME of the command, is referring to exactly the binary which uses the very same library, or better, check if the binary you are referring with the absolute path is the very same you refer when you use the console directly. The binaries can be found using the locate command, for example:

$locate python

Be sure that the binary you will refer, is the very same the binary you are calling in your shell, or simply test again in your shell using the absolute path that you plan to put in the cronjob.

  • Another common source of problems is the syntax in the cronjob. Remember that there are special characters you can use for lists (commas), to define ranges (dashes -), to define increment of ranges (slashes), etc. Take a look: http://www.softpanorama.org/Utilities/cron.shtml

How can I see an the output of my C programs using Dev-C++?

The use of line system("PAUSE") will fix that problem and also include the pre processor directory #include<stdlib.h>.

Getting text from td cells with jQuery

$(document).ready(function() {
  $('td').on('click', function() {
    var value = $this.text();
  });
});

Get List of connected USB Devices

Adel Hazzah's answer gives working code, Daniel Widdis's and Nedko's comments mention that you need to query Win32_USBControllerDevice and use its Dependent property, and Daniel's answer gives a lot of detail without code.

Here's a synthesis of the above discussion to provide working code that lists the directly accessible PNP device properties of all connected USB devices:

using System;
using System.Collections.Generic;
using System.Management; // reference required

namespace cSharpUtilities
{
    class UsbBrowser
    {

        public static void PrintUsbDevices()
        {
            IList<ManagementBaseObject> usbDevices = GetUsbDevices();

            foreach (ManagementBaseObject usbDevice in usbDevices)
            {
                Console.WriteLine("----- DEVICE -----");
                foreach (var property in usbDevice.Properties)
                {
                    Console.WriteLine(string.Format("{0}: {1}", property.Name, property.Value));
                }
                Console.WriteLine("------------------");
            }
        }

        public static IList<ManagementBaseObject> GetUsbDevices()
        {
            IList<string> usbDeviceAddresses = LookUpUsbDeviceAddresses();

            List<ManagementBaseObject> usbDevices = new List<ManagementBaseObject>();

            foreach (string usbDeviceAddress in usbDeviceAddresses)
            {
                // query MI for the PNP device info
                // address must be escaped to be used in the query; luckily, the form we extracted previously is already escaped
                ManagementObjectCollection curMoc = QueryMi("Select * from Win32_PnPEntity where PNPDeviceID = " + usbDeviceAddress);
                foreach (ManagementBaseObject device in curMoc)
                {
                    usbDevices.Add(device);
                }
            }

            return usbDevices;
        }

        public static IList<string> LookUpUsbDeviceAddresses()
        {
            // this query gets the addressing information for connected USB devices
            ManagementObjectCollection usbDeviceAddressInfo = QueryMi(@"Select * from Win32_USBControllerDevice");

            List<string> usbDeviceAddresses = new List<string>();

            foreach(var device in usbDeviceAddressInfo)
            {
                string curPnpAddress = (string)device.GetPropertyValue("Dependent");
                // split out the address portion of the data; note that this includes escaped backslashes and quotes
                curPnpAddress = curPnpAddress.Split(new String[] { "DeviceID=" }, 2, StringSplitOptions.None)[1];

                usbDeviceAddresses.Add(curPnpAddress);
            }

            return usbDeviceAddresses;
        }

        // run a query against Windows Management Infrastructure (MI) and return the resulting collection
        public static ManagementObjectCollection QueryMi(string query)
        {
            ManagementObjectSearcher managementObjectSearcher = new ManagementObjectSearcher(query);
            ManagementObjectCollection result = managementObjectSearcher.Get();

            managementObjectSearcher.Dispose();
            return result;
        }

    }

}

You'll need to add exception handling if you want it. Consult Daniel's answer if you want to figure out the device tree and such.

How to merge 2 JSON objects from 2 files using jq?

Here's a version that works recursively (using *) on an arbitrary number of objects:

echo '{"A": {"a": 1}}' '{"A": {"b": 2}}' '{"B": 3}' |\
  jq --slurp 'reduce .[] as $item ({}; . * $item)'

{
  "A": {
    "a": 1,
    "b": 2
  },
  "B": 3
}

QString to char* conversion

It is a viable way to use std::vector as an intermediate container:

QString dataSrc("FooBar");
QString databa = dataSrc.toUtf8();
std::vector<char> data(databa.begin(), databa.end());
char* pDataChar = data.data();

Can't get private key with openssl (no start line:pem_lib.c:703:Expecting: ANY PRIVATE KEY)

I ran into the 'Expecting: ANY PRIVATE KEY' error when using openssl on Windows (Ubuntu Bash and Git Bash had the same issue).

The cause of the problem was that I'd saved the key and certificate files in Notepad using UTF8. Resaving both files in ANSI format solved the problem.

How to get text and a variable in a messagebox

Why not use:

Dim msg as String = String.Format("Variable = {0}", variable)

More info on String.Format

Return None if Dictionary key is not available

If you want a more transparent solution, you can subclass dict to get this behavior:

class NoneDict(dict):
    def __getitem__(self, key):
        return dict.get(self, key)

>>> foo = NoneDict([(1,"asdf"), (2,"qwerty")])
>>> foo[1]
'asdf'
>>> foo[2]
'qwerty'
>>> foo[3] is None
True

Datatables: Cannot read property 'mData' of undefined

Tips 1:

Refer to this Link you get some Ideas:

https://datatables.net/forums/discussion/20273/uncaught-typeerror-cannot-read-property-mdata-of-undefined

Tips 2:

Check following is correct:

  • Please check the Jquery Vesion
  • Please check the versiion of yours CDN or your local datatable related .min & css files
  • your table have <thead></thead> & <tbody></tbody> tags
  • Your table Header Columns Length same like Body Columns Length
  • Your Using some cloumns in style='display:none' as same propery apply in you both Header & body.
  • your table columns no empty, use something like [ Null, --, NA, Nil ]
  • Your table is well one with out <td>, <tr> issue

Why doesn't os.path.join() work in this case?

To make your function more portable, use it as such:

os.path.join(os.sep, 'home', 'build', 'test', 'sandboxes', todaystr, 'new_sandbox')

or

os.path.join(os.environ.get("HOME"), 'test', 'sandboxes', todaystr, 'new_sandbox')

How to install python-dateutil on Windows?

First confirm that you have in C:/python##/Lib/Site-packages/ a folder dateutil, perhaps you download it, you should already have pip,matplotlib, six##,,confirm you have installed dateutil by--- go to the cmd, cd /python, you should have a folder /Scripts. cd to Scripts, then type --pip install python-dateutil -- ----This applies to windows 7 Ultimate 32bit, Python 3.4------

How to pass credentials to httpwebrequest for accessing SharePoint Library

If you need to run request as the current user from desktop application use CredentialCache.DefaultCredentials (see on MSDN).

Your code looks fine if you need to run a request from server side code or under a different user.

Please note that you should be careful when storing passwords - consider using the SecureString version of the constructor.

How does one make random number between range for arc4random_uniform()?

I successfully accomplished creating a random number using the following code:

var coin = arc4random_uniform(2) + 1

Hope this can help you.

How to get row count in an Excel file using POI library?

getLastRowNum() return index of last row.

So if you wants to know total number of row = getLastRowNum() +1.

I hope this will work.

int rowTotal = sheet.getLastRowNum() +1;

How to set a value to a file input in HTML?

Actually we can do it. we can set the file value default by using webbrowser control in c# using FormToMultipartPostData Library.We have to download and include this Library in our project. Webbrowser enables the user to navigate Web pages inside form. Once the web page loaded , the script inside the webBrowser1_DocumentCompleted will be executed. So,

private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
    {
       FormToMultipartPostData postData = 
            new FormToMultipartPostData(webBrowser1, form);
        postData.SetFile("fileField", @"C:\windows\win.ini");
        postData.Submit();
    }

Refer the below link for downloading and complete reference.

https://www.codeproject.com/Articles/28917/Setting-a-file-to-upload-inside-the-WebBrowser-com

SimpleXML - I/O warning : failed to load external entity

this also works:

$url = "http://www.some-url";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$xmlresponse = curl_exec($ch);
$xml=simplexml_load_string($xmlresponse);

then I just run a forloop to grab the stuff from the nodes.

like this:`

for($i = 0; $i < 20; $i++) {
$title = $xml->channel->item[$i]->title;
$link = $xml->channel->item[$i]->link;
$desc = $xml->channel->item[$i]->description;
$html .="<div><h3>$title</h3>$link<br />$desc</div><hr>";
}
echo $html;

***note that your node names will differ, obviously..and your HTML might be structured differently...also your loop might be set to higher or lower amount of results.

Example of SOAP request authenticated with WS-UsernameToken

May be this post (Secure Metro JAX-WS UsernameToken Web Service with Signature, Encryption and TLS (SSL)) provides more insight. As they mentioned "Remember, unless password text or digested password is sent on a secured channel or the token is encrypted, neither password digest nor cleartext password offers no real additional security. "

What does jQuery.fn mean?

jQuery.fn is defined shorthand for jQuery.prototype. From the source code:

jQuery.fn = jQuery.prototype = {
    // ...
}

That means jQuery.fn.jquery is an alias for jQuery.prototype.jquery, which returns the current jQuery version. Again from the source code:

// The current version of jQuery being used
jquery: "@VERSION",

How to make the background image to fit into the whole page without repeating using plain css?

background:url(bgimage.jpg) no-repeat; background-size: cover;

This did the trick

How do I convert datetime.timedelta to minutes, hours in Python?

datetime.timedelta(hours=1, minutes=10)
#python 2.7

How to add element in List while iterating in java?

Iterate through a copy of the list and add new elements to the original list.

for (String s : new ArrayList<String>(list))     
{
    list.add("u");
}

See How to make a copy of ArrayList object which is type of List?

postgresql return 0 if returned value is null

(this answer was added to provide shorter and more generic examples to the question - without including all the case-specific details in the original question).


There are two distinct "problems" here, the first is if a table or subquery has no rows, the second is if there are NULL values in the query.

For all versions I've tested, postgres and mysql will ignore all NULL values when averaging, and it will return NULL if there is nothing to average over. This generally makes sense, as NULL is to be considered "unknown". If you want to override this you can use coalesce (as suggested by Luc M).

$ create table foo (bar int);
CREATE TABLE

$ select avg(bar) from foo;
 avg 
-----

(1 row)

$ select coalesce(avg(bar), 0) from foo;
 coalesce 
----------
        0
(1 row)

$ insert into foo values (3);
INSERT 0 1
$ insert into foo values (9);
INSERT 0 1
$ insert into foo values (NULL);
INSERT 0 1
$ select coalesce(avg(bar), 0) from foo;
      coalesce      
--------------------
 6.0000000000000000
(1 row)

of course, "from foo" can be replaced by "from (... any complicated logic here ...) as foo"

Now, should the NULL row in the table be counted as 0? Then coalesce has to be used inside the avg call.

$ select coalesce(avg(coalesce(bar, 0)), 0) from foo;
      coalesce      
--------------------
 4.0000000000000000
(1 row)

Import/Index a JSON file into Elasticsearch

The right command if you want to use a file with curl is this:

curl -XPOST 'http://jfblouvmlxecs01:9200/test/_doc/1' -d @lane.json

Elasticsearch is schemaless, therefore you don't necessarily need a mapping. If you send the json as it is and you use the default mapping, every field will be indexed and analyzed using the standard analyzer.

If you want to interact with Elasticsearch through the command line, you may want to have a look at the elasticshell which should be a little bit handier than curl.

2019-07-10: Should be noted that custom mapping types is deprecated and should not be used. I updated the type in the url above to make it easier to see which was the index and which was the type as having both named "test" was confusing.

Where is the visual studio HTML Designer?

Go to [Tools, Options], section "Web Forms Designer" and enable the option "Enable Web Forms Designer". That should give you the Design and Split option again.

Warning: mysqli_real_escape_string() expects exactly 2 parameters, 1 given... what I do wrong?

Replace your query with the following:

$query = mysql_query("INSERT INTO users VALUES('$username','$pass','$email')", `$Connect`);

Vue.js: Conditional class style binding

<i class="fa" v-bind:class="cravings"></i>

and add in computed :

computed: {
    cravings: function() {
        return this.content['cravings'] ? 'fa-checkbox-marked' : 'fa-checkbox-blank-outline';
    }
}

form confirm before submit

var r = confirm('Want to delete ?'); 

if (r == true) { 
    $('#admin-category-destroy').submit(); 
}

Python - How to sort a list of lists by the fourth element in each list?

Use sorted() with a key as follows -

>>> unsorted_list = [['a','b','c','5','d'],['e','f','g','3','h'],['i','j','k','4','m']]
>>> sorted(unsorted_list, key = lambda x: int(x[3]))
[['e', 'f', 'g', '3', 'h'], ['i', 'j', 'k', '4', 'm'], ['a', 'b', 'c', '5', 'd']]

The lambda returns the fourth element of each of the inner lists and the sorted function uses that to sort those list. This assumes that int(elem) will not fail for the list.

Or use itemgetter (As Ashwini's comment pointed out, this method would not work if you have string representations of the numbers, since they are bound to fail somewhere for 2+ digit numbers)

>>> from operator import itemgetter
>>> sorted(unsorted_list, key = itemgetter(3))
[['e', 'f', 'g', '3', 'h'], ['i', 'j', 'k', '4', 'm'], ['a', 'b', 'c', '5', 'd']]

How to read a file line-by-line into a list?

If you want the \n included:

with open(fname) as f:
    content = f.readlines()

If you do not want \n included:

with open(fname) as f:
    content = f.read().splitlines()

Java ArrayList for integers

you should not use Integer[] array inside the list as arraylist itself is a kind of array. Just leave the [] and it should work

adb shell su works but adb root does not

I ran into this issue when trying to root the emulator, I found out it was because I was running the Nexus 5x emulator which had Google Play on it. Created a different emulator that didn't have google play and adb root will root the device for you. Hope this helps someone.

How to set auto increment primary key in PostgreSQL?

Try this command:

ALTER TABLE your_table ADD COLUMN key_column BIGSERIAL PRIMARY KEY;

Try it with the same DB-user as the one you have created the table.

int to unsigned int conversion

You can convert an int to an unsigned int. The conversion is valid and well-defined.

Since the value is negative, UINT_MAX + 1 is added to it so that the value is a valid unsigned quantity. (Technically, 2N is added to it, where N is the number of bits used to represent the unsigned type.)

In this case, since int on your platform has a width of 32 bits, 62 is subtracted from 232, yielding 4,294,967,234.

How to remove an element from the flow?

Another option is to set height: 0; overflow: visible; to an element, though it won't be really outside the flow and therefore may break margin collapsing.

Show "loading" animation on button click

            //do processing
            $(this).attr("label", $(this).text()).text("loading ....").animate({ disabled: true }, 1000, function () {
                //original event call
                $.when($(elm).delay(1000).one("click")).done(function () {//processing finalized
                    $(this).text($(this).attr("label")).animate({ disabled: false }, 1000, function () {
                    })
                });
            });

Vertical divider CSS

.headerDivider {
     border-left:1px solid #38546d; 
     border-right:1px solid #16222c; 
     height:80px;
     position:absolute;
     right:249px;
     top:10px; 
}

<div class="headerDivider"></div>

Xcopy Command excluding files and folders

Like Andrew said /exclude parameter of xcopy should be existing file that has list of excludes.

Documentation of xcopy says:

Using /exclude

List each string in a separate line in each file. If any of the listed strings match any part of the absolute path of the file to be copied, that file is then excluded from the copying process. For example, if you specify the string "\Obj\", you exclude all files underneath the Obj directory. If you specify the string ".obj", you exclude all files with the .obj extension.

Example:

xcopy c:\t1 c:\t2 /EXCLUDE:list-of-excluded-files.txt

and list-of-excluded-files.txt should exist in current folder (otherwise pass full path), with listing of files/folders to exclude - one file/folder per line. In your case that would be:

exclusion.txt

Google Maps v2 - set both my location and zoom in

You cannot animate two things (like zoom in and go to my location) in one google map?

From a coding standpoint, you would do them sequentially:

    CameraUpdate center=
        CameraUpdateFactory.newLatLng(new LatLng(40.76793169992044,
                                                 -73.98180484771729));
    CameraUpdate zoom=CameraUpdateFactory.zoomTo(15);

    map.moveCamera(center);
    map.animateCamera(zoom);

Here, I move the camera first, then animate the camera, though both could be animateCamera() calls. Whether GoogleMap consolidates these into a single event, I can't say, as it goes by too fast. :-)

Here is the sample project from which I pulled the above code.


Sorry, this answer is flawed. See Rob's answer for a way to truly do this in one shot, by creating a CameraPosition and then creating a CameraUpdate from that CameraPosition.

FIX CSS <!--[if lt IE 8]> in IE

    <!--[if IE]>
    <style type='text/css'>
    #header ul#h-menu li a{font-weight:normal!important}
    </style>
    <![endif]-->

will apply that style in all versions of IE.

Javascript - Track mouse position

I don't have enough reputation to post a comment reply, but took TJ Crowder's excellent answer and fully defined the code on a 100ms timer. (He left some details to the imagination.)

Thanks OP for the question, and TJ for the answer! You're both a great help. Code is embedded below as a mirror of isbin.

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
  <meta charset="utf-8">_x000D_
  <title>Example</title>_x000D_
  <style>_x000D_
    body {_x000D_
      height: 3000px;_x000D_
    }_x000D_
    .dot {_x000D_
      width: 2px;_x000D_
      height: 2px;_x000D_
      background-color: black;_x000D_
      position: absolute;_x000D_
    }_x000D_
  </style>_x000D_
</head>_x000D_
<body>_x000D_
<script>_x000D_
(function() {_x000D_
    "use strict";_x000D_
    var mousePos;_x000D_
_x000D_
    document.onmousemove = handleMouseMove;_x000D_
    setInterval(getMousePosition, 100); // setInterval repeats every X ms_x000D_
_x000D_
    function handleMouseMove(event) {_x000D_
        var eventDoc, doc, body;_x000D_
_x000D_
        event = event || window.event; // IE-ism_x000D_
_x000D_
        // If pageX/Y aren't available and clientX/Y are,_x000D_
        // calculate pageX/Y - logic taken from jQuery._x000D_
        // (This is to support old IE)_x000D_
        if (event.pageX == null && event.clientX != null) {_x000D_
            eventDoc = (event.target && event.target.ownerDocument) || document;_x000D_
            doc = eventDoc.documentElement;_x000D_
            body = eventDoc.body;_x000D_
_x000D_
            event.pageX = event.clientX +_x000D_
              (doc && doc.scrollLeft || body && body.scrollLeft || 0) -_x000D_
              (doc && doc.clientLeft || body && body.clientLeft || 0);_x000D_
            event.pageY = event.clientY +_x000D_
              (doc && doc.scrollTop  || body && body.scrollTop  || 0) -_x000D_
              (doc && doc.clientTop  || body && body.clientTop  || 0 );_x000D_
        }_x000D_
_x000D_
        mousePos = {_x000D_
            x: event.pageX,_x000D_
            y: event.pageY_x000D_
        };_x000D_
    }_x000D_
    function getMousePosition() {_x000D_
        var pos = mousePos;_x000D_
  _x000D_
        if (!pos) {_x000D_
            // We haven't seen any movement yet, so don't add a duplicate dot _x000D_
        }_x000D_
        else {_x000D_
            // Use pos.x and pos.y_x000D_
            // Add a dot to follow the cursor_x000D_
            var dot;_x000D_
            dot = document.createElement('div');_x000D_
            dot.className = "dot";_x000D_
            dot.style.left = pos.x + "px";_x000D_
            dot.style.top = pos.y + "px";_x000D_
            document.body.appendChild(dot);_x000D_
        }_x000D_
    }_x000D_
})();_x000D_
</script>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to fix "Referenced assembly does not have a strong name" error?

To avoid this error you could either:

  • Load the assembly dynamically, or
  • Sign the third-party assembly.

You will find instructions on signing third-party assemblies in .NET-fu: Signing an Unsigned Assembly (Without Delay Signing).

Signing Third-Party Assemblies

The basic principle to sign a thirp-party is to

  1. Disassemble the assembly using ildasm.exe and save the intermediate language (IL):

    ildasm /all /out=thirdPartyLib.il thirdPartyLib.dll 
    
  2. Rebuild and sign the assembly:

    ilasm /dll /key=myKey.snk thirdPartyLib.il
    

Fixing Additional References

The above steps work fine unless your third-party assembly (A.dll) references another library (B.dll) which also has to be signed. You can disassemble, rebuild and sign both A.dll and B.dll using the commands above, but at runtime, loading of B.dll will fail because A.dll was originally built with a reference to the unsigned version of B.dll.

The fix to this issue is to patch the IL file generated in step 1 above. You will need to add the public key token of B.dll to the reference. You get this token by calling

sn -Tp B.dll 

which will give you the following output:

Microsoft (R) .NET Framework Strong Name Utility  Version 4.0.30319.33440
Copyright (c) Microsoft Corporation.  All rights reserved.

Public key (hash algorithm: sha1):
002400000480000094000000060200000024000052534131000400000100010093d86f6656eed3
b62780466e6ba30fd15d69a3918e4bbd75d3e9ca8baa5641955c86251ce1e5a83857c7f49288eb
4a0093b20aa9c7faae5184770108d9515905ddd82222514921fa81fff2ea565ae0e98cf66d3758
cb8b22c8efd729821518a76427b7ca1c979caa2d78404da3d44592badc194d05bfdd29b9b8120c
78effe92

Public key token is a8a7ed7203d87bc9

The last line contains the public key token. You then have to search the IL of A.dll for the reference to B.dll and add the token as follows:

.assembly extern /*23000003*/ MyAssemblyName
{
  .publickeytoken = (A8 A7 ED 72 03 D8 7B C9 )                         
  .ver 10:0:0:0
}