Programs & Examples On #Loadmodule

Please add a @Pipe/@Directive/@Component annotation. Error

In my case I mistakenly added this:

@Component({
    selector: 'app-some-item',
    templateUrl: './some-item.component.html',
    styleUrls: ['./some-item.component.scss'],
    providers: [ConfirmationService]
})

declare var configuration: any;

while the correct form is:

declare var configuration: any;

@Component({
    selector: 'app-some-item',
    templateUrl: './some-item.component.html',
    styleUrls: ['./some-item.component.scss'],
    providers: [ConfirmationService]
})    

Httpd returning 503 Service Unavailable with mod_proxy for Tomcat 8

(Answered by the OP in a question edit. Converted to a community wiki answer. See Question with no answers, but issue solved in the comments (or extended in chat) )

The OP wrote:

The answer is here: http://sysadminsjourney.com/content/2010/02/01/apache-modproxy-error-13permission-denied-error-rhel/

Which is a link to a blog that explains:

SELinux on RHEL/CentOS by default ships so that httpd processes cannot initiate outbound connections, which is just what mod_proxy attempts to do.

If this is the problem, it can be solved by running:

 /usr/sbin/setsebool -P httpd_can_network_connect 1

And for a more definitive source of information, see https://wiki.apache.org/httpd/13PermissionDenied

Apache Proxy: No protocol handler was valid

In my case, I needed proxy_ajp module.

a2enmod proxy proxy_http proxy_ajp 

Forbidden You don't have permission to access / on this server

Found my solution thanks to Error with .htaccess and mod_rewrite
For Apache 2.4 and in all *.conf files (e.g. httpd-vhosts.conf, http.conf, httpd-autoindex.conf ..etc) use

Require all granted

instead of

Order allow,deny
Allow from all

The Order and Allow directives are deprecated in Apache 2.4.

Apache: "AuthType not set!" 500 Error

Alternatively, this solution works with both Apache2 version < 2.4 as well as >= 2.4. Make sure that the "version" module is enabled:

a2enmod version

And then use this code instead:

<IfVersion < 2.4>
    Allow from all
</IfVersion>
<IfVersion >= 2.4>
    Require all granted
</IfVersion>

New xampp security concept: Access Forbidden Error 403 - Windows 7 - phpMyAdmin

This could be because of wrong configuration, esp if your other sites are working fine.

<VirtualHost cmsdemo.git:88>
    DocumentRoot "C:/Projects/rwp/"
    ServerName cmsdemo.git
    <Directory C:/Projects/cmsdemo/>
        Require all granted 
        AllowOverride All
    </Directory>
</VirtualHost>

Notice in DocumentRoot I am specifying one folder and in Directory, I am specifying another hence 403 Error. This fixed my problem.

Apache: The requested URL / was not found on this server. Apache

Non-trivial reasons:

  • if your .htaccess is in DOS format, change it to UNIX format (in Notepad++, click Edit>Convert )
  • if your .htaccess is in UTF8 Without-BOM, make it WITH BOM.

cannot load such file -- bundler/setup (LoadError)

I've fixed that problem by creating test rails project and install all gems then I've replaced my current Gemfile.lock with the test and all thing works fine.

I think that this problem from bundler versions with hosting, so please make sure that hosting bundler is the same version with your project.

404 Not Found The requested URL was not found on this server

If your .htaccess file is ok and the problem persist try to make the AllowOverride directive enabled in your httpd.conf. If the AllowOverride directive is set to None in your Apache httpd.config file, then .htaccess files are completely ignored. Example of enabled AllowOverride directive in httpd.config:

 <Directory />
    Options FollowSymLinks
    **AllowOverride All**
 </Directory>

Therefor restart your server.

Apache is downloading php files instead of displaying them

I had the same problem after using zypper rm php* to uninstall PHP and installing it again with zypper in php7 php7-gd php7-gettext php7-mbstring php7-mysql php7-pear

I solved it by enabling the apache2 module and restarting the webserver:

a2enmod php7 && service apache2 restart

Apache shows PHP code instead of executing it

Posting what worked for me in case in helps someone down the road, though it is an unusual case.

I had set a handler to force my web host to use a higher version of php than their default. There's was 5.1, but I wanted 5.6 so I had this:

<FilesMatch \.php$>
    SetHandler php56-cgi
</FilesMatch>

in my .htaccess file.

When trying to run my site locally, having that in there caused php code to be output to the browser. Removing it solved the problem.

Error message "Forbidden You don't have permission to access / on this server"

I solved my problem by adding my user to httpd.conf.

# User/Group: The name (or #number) of the user/group to run httpd as.
# It is usually good practice to create a dedicated user and group for
# running httpd, as with most system services.
#
#User daemon
User my_username
Group daemon

apache mod_rewrite is not working or not enabled

Please try

sudo a2enmod rewrite

or use correct apache restart command

sudo /etc/init.d/apache2 restart 

How to install mod_ssl for Apache httpd?

I found I needed to enable the SSL module in Apache (obviously prefix commands with sudo if you are not running as root):

a2enmod ssl

then restart Apache:

/etc/init.d/apache2 restart

More details of SSL in Apache for Ubuntu / Debian here.

How to use .htaccess in WAMP Server?

Open the httpd.conf file and search for

"rewrite"

, then remove

"#"

at the starting of the line,so the line looks like.

LoadModule rewrite_module modules/mod_rewrite.so

then restart the wamp.

How to enable mod_rewrite for Apache 2.2

I just did this

sudo a2enmod rewrite

then you have to restart the apache service by following command

sudo service apache2 restart

to call onChange event after pressing Enter key

Here is a common use case using class-based components: The parent component provides a callback function, the child component renders the input box, and when the user presses Enter, we pass the user's input to the parent.

class ParentComponent extends React.Component {
  processInput(value) {
    alert('Parent got the input: '+value);
  }

  render() {
    return (
      <div>
        <ChildComponent handleInput={(value) => this.processInput(value)} />
      </div>
    )
  }
}

class ChildComponent extends React.Component {
  constructor(props) {
    super(props);
    this.handleKeyDown = this.handleKeyDown.bind(this);
  }

  handleKeyDown(e) {
    if (e.key === 'Enter') {
      this.props.handleInput(e.target.value);
    }
  }

  render() {
    return (
      <div>
        <input onKeyDown={this.handleKeyDown} />
      </div>
    )
  }      
}

Angular2 material dialog has issues - Did you add it to @NgModule.entryComponents?

You must add it to entryComponents, as specified in the docs.

@NgModule({
  imports: [
    // ...
  ],
  entryComponents: [
    DialogInvokingComponent, 
    DialogResultExampleDialog
  ],
  declarations: [
    DialogInvokingComponent,   
    DialogResultExampleDialog
  ],
  // ...
})

Here is a full example for an app module file with a dialog defined as entryComponents.

What is the difference between 'my' and 'our' in Perl?

The perldoc has a good definition of our.

Unlike my, which both allocates storage for a variable and associates a simple name with that storage for use within the current scope, our associates a simple name with a package variable in the current package, for use within the current scope. In other words, our has the same scoping rules as my, but does not necessarily create a variable.

Calling the base class constructor from the derived class constructor

First off, a PetStore is not a farm.

Let's get past this though. You actually don't need access to the private members, you have everything you need in the public interface:

Animal_* getAnimal_(int i);
void addAnimal_(Animal_* newAnimal);

These are the methods you're given access to and these are the ones you should use.

I mean I did this Inheritance so I can add animals to my PetStore but now since sizeF is private how can I do that ??

Simple, you call addAnimal. It's public and it also increments sizeF.

Also, note that

PetStore()
{
 idF=0;
};

is equivalent to

PetStore() : Farm()
{
 idF=0;
};

i.e. the base constructor is called, base members are initialized.

ES6 Class Multiple inheritance

Justin Fagnani describes a very clean (imho) way to compose multiple classes into one using the fact that in ES2015, classes can be created with class expressions.

Expressions vs declarations

Basically, just like you can create a function with an expression:

function myFunction() {}      // function declaration
var myFunction = function(){} // function expression

you can do the same with classes:

class MyClass {}             // class declaration
var MyClass = class {}       // class expression

The expression is evaluated at runtime, when the code executes, whereas a declaration is executed beforehand.

Using class expressions to create mixins

You can use this to create a function that dynamically creates a class only when the function is called:

function createClassExtending(superclass) {
  return class AwesomeClass extends superclass {
    // you class body here as usual
  }
}

The cool thing about it is that you can define the whole class beforehand and only decide on which class it should extend by the time you call the function:

class A {}
class B {}
var ExtendingA = createClassExtending(A)
var ExtendingB = createClassExtending(B)

If you want to mix multiple classes together, because ES6 classes only support single inheritance, you need to create a chain of classes that contains all the classes you want to mix together. So let's say you want to create a class C that extends both A and B, you could do this:

class A {}
class B extends A {}
class C extends B {}  // C extends both A and B

The problem with this is that it's very static. If you later decide you want to make a class D that extends B but not A, you have a problem.

But with some smart trickery using the fact that classes can be expressions, you can solve this by creating A and B not directly as classes, but as class factories (using arrow functions for brevity):

class Base {} // some base class to keep the arrow functions simple
var A = (superclass) => class A extends superclass
var B = (superclass) => class B extends superclass
var C = B(A(Base))
var D = B(Base)

Notice how we only decide at the last moment which classes to include in the hierarchy.

avrdude: stk500v2_ReceiveMessage(): timeout

I was running this code from Arduino setup , got same error resolve after changing
serial port to COM13
GO TO Option
tool>> serial port>> COM132

jquery equivalent for JSON.stringify

There is no such functionality in jQuery. Use JSON.stringify or alternatively any jQuery plugin with similar functionality (e.g jquery-json).

SVN Commit failed, access forbidden

I was unable to commit csharp-files (*.cs). In the end the problem was that at some point i installed mod_mono, which made the *.cs-files inaccessible, through its configuration. So it may well be an apache-configuration issue, if only some sort of files are not accessible.

grep ".cs" /etc/apache2/mods-enabled/*
...
mod_mono_auto.conf:AddType application/x-asp-net .cs
...

Create a directory if it doesn't exist

You can use cstdlib

Although- http://www.cplusplus.com/articles/j3wTURfi/

#include <cstdlib>

const int dir= system("mkdir -p foo");
if (dir< 0)
{
     return;
}

you can also check if the directory exists already by using

#include <dirent.h>

How update the _id of one MongoDB Document?

To do it for your whole collection you can also use a loop (based on Niels example):

db.status.find().forEach(function(doc){ 
    doc._id=doc.UserId; db.status_new.insert(doc);
});
db.status_new.renameCollection("status", true);

In this case UserId was the new ID I wanted to use

When to use: Java 8+ interface default method, vs. abstract method

when should interface with default methods be used and when should an abstract class be used?

Backward compatibility: Imagine that your interface is implemented by hundreds of classes, modifying that interface will force all the users to implement the newly added method, even though it could be not essential for many other classes that implements your interface, Plus it allows your interface to be a functional interface

Facts & Restrictions:

1-May only be declared within an interface and not within a class or abstract class.

2-Must provide a body

3-It is not assumed to be abstract as other normal methods used in an interface.

NotificationCenter issue on Swift 3

Notifications appear to have changed again (October 2016).

// Register to receive notification

NotificationCenter.default.addObserver(self, selector: #selector(yourClass.yourMethod), name: NSNotification.Name(rawValue: "yourNotificatioName"), object: nil)

// Post notification

NotificationCenter.default.post(name: NSNotification.Name(rawValue: "yourNotificationName"), object: nil)

How to compare type of an object in Python?

It is because you have to write

s="hello"
type(s) == type("")

type accepts an instance and returns its type. In this case you have to compare two instances' types.

If you need to do preemptive checking, it is better if you check for a supported interface than the type.

The type does not really tell you much, apart of the fact that your code want an instance of a specific type, regardless of the fact that you could have another instance of a completely different type which would be perfectly fine because it implements the same interface.

For example, suppose you have this code

def firstElement(parameter):
    return parameter[0]

Now, suppose you say: I want this code to accept only a tuple.

import types

def firstElement(parameter):
    if type(parameter) != types.TupleType:
         raise TypeError("function accepts only a tuple")
    return parameter[0]

This is reducing the reusability of this routine. It won't work if you pass a list, or a string, or a numpy.array. Something better would be

def firstElement(parameter):
    if not (hasattr(parameter, "__getitem__") and callable(getattr(parameter,"__getitem__"))):
        raise TypeError("interface violation")
    return parameter[0]

but there's no point in doing it: parameter[0] will raise an exception if the protocol is not satisfied anyway... this of course unless you want to prevent side effects or having to recover from calls that you could invoke before failing. (Stupid) example, just to make the point:

def firstElement(parameter):
    if not (hasattr(parameter, "__getitem__") and callable(getattr(parameter,"__getitem__"))):
        raise TypeError("interface violation")
    os.system("rm file")
    return parameter[0]

in this case, your code will raise an exception before running the system() call. Without interface checks, you would have removed the file, and then raised the exception.

Iterate two Lists or Arrays with one ForEach statement in C#

No, you would have to use a for-loop for that.

for (int i = 0; i < lst1.Count; i++)
{
    //lst1[i]...
    //lst2[i]...
}

You can't do something like

foreach (var objCurrent1 int lst1, var objCurrent2 in lst2)
{
    //...
}

Easy way of running the same junit test over and over?

I've found that Spring's repeat annotation is useful for that kind of thing:

@Repeat(value = 10)

Latest (Spring Framework 4.3.11.RELEASE API) doc:

How can I get the error message for the mail() function?

$e=error_get_last();
if($e['message']!==''){
    // An error function
}

error_get_last(); - return the last error that occurred

How to justify navbar-nav in Bootstrap 3

<div class="navbar navbar-default navbar-fixed-top" role="navigation">
 <div class="container">
<div class="navbar-header">
  <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
    <span class="sr-only">Toggle navigation</span>
    <span class="icon-bar"></span>
    <span class="icon-bar"></span>
    <span class="icon-bar"></span>
  </button>
</div>
<div class="collapse navbar-collapse">
  <ul class="nav navbar-nav">
    <li><a href="#">Home</a></li>
    <li><a href="#about">About</a></li>
    <li><a href="#contact">Contact</a></li>  
  </ul>
</div>

and for the css

@media ( min-width: 768px ) { 
    .navbar > .container {
        text-align: center;
    }
    .navbar-header,.navbar-brand,.navbar .navbar-nav,.navbar .navbar-nav > li {
        float: none;
        display: inline-block;
    }
    .collapse.navbar-collapse {
        width: auto;
        clear: none;
    }
}

see it live http://www.bootply.com/103172

Android Studio Stuck at Gradle Download on create new project

For Windows Users

Use your Network Resource Monitor

enter image description here

Open Task Manager [Ctrl+Shift+Esc]

Performance Tab

Open Resource Monitor (From the bottom)

First i decided to wait after reading answers here. But how long..? How to make sure it will finish.? They should have provided percentage of download, but they have not. So to know some kind of progress is going on, open this network resource monitor, it will show you some kind of download is going on for the Studio64.exe. IF not (if it shows 0B/Sec), then either network is not available or the application is not responding.

Is there a query language for JSON?

In MongoDB, this is how it would work (in the mongo shell, there exist drivers for a language of your choice).

db.collection.insert({"x": 2, "y": 0}); // notice the ':' instead of ','
db.collection.insert({"x": 3, "y": 1});
db.collection.insert({"x": 4, "y": 1});

db.collection.aggregate([{$match: {"y": {$gt: 0}}}, 
                         {$group: {_id: "sum", sum: {$sum: "$x"}}}]);
db.collection.aggregate([{$match: {"y": {$gt: 0}}}, 
                         {$group: {_id: "list", list: {$push: "$x"}}}]);

The first three commands insert the data into your collection. (Just start the mongod server and connect with the mongo client.)

The next two process the data. $match filters, $group applies the sum and list, respectively.

What is "overhead"?

The meaning of the word can differ a lot with context. In general, it's resources (most often memory and CPU time) that are used, which do not contribute directly to the intended result, but are required by the technology or method that is being used. Examples:

  • Protocol overhead: Ethernet frames, IP packets and TCP segments all have headers, TCP connections require handshake packets. Thus, you cannot use the entire bandwidth the hardware is capable of for your actual data. You can reduce the overhead by using larger packet sizes and UDP has a smaller header and no handshake.
  • Data structure memory overhead: A linked list requires at least one pointer for each element it contains. If the elements are the same size as a pointer, this means a 50% memory overhead, whereas an array can potentially have 0% overhead.
  • Method call overhead: A well-designed program is broken down into lots of short methods. But each method call requires setting up a stack frame, copying parameters and a return address. This represents CPU overhead compared to a program that does everything in a single monolithic function. Of course, the added maintainability makes it very much worth it, but in some cases, excessive method calls can have a significant performance impact.

How do I select text nodes with jQuery?

if you want to strip all tags, then try this

function:

String.prototype.stripTags=function(){
var rtag=/<.*?[^>]>/g;
return this.replace(rtag,'');
}

usage:

var newText=$('selector').html().stripTags();

How can I read command line parameters from an R script?

Add this to the top of your script:

args<-commandArgs(TRUE)

Then you can refer to the arguments passed as args[1], args[2] etc.

Then run

Rscript myscript.R arg1 arg2 arg3

If your args are strings with spaces in them, enclose within double quotes.

Add timer to a Windows Forms application

Download http://download.cnet.com/Free-Desktop-Timer/3000-2350_4-75415517.html

Then add a button or something on the form and inside its event, just open this app ie:

{

Process.Start(@"C:\Program Files (x86)\Free Desktop Timer\DesktopTimer");

}

Objective-C: Calling selectors with multiple arguments

Think the class should be defined as:

- (void) myTestWithSomeString:(NSString *) astring{
    NSLog(@"hi, %s", astring);
}

You only have a single parameter so you should only have a single :

You might want to consider using %@ in your NSLog also - it is just a good habit to get into - will then write out any object - not just strings.

Java: Integer equals vs. ==

Besides these given great answers, What I have learned is that:

NEVER compare objects with == unless you intend to be comparing them by their references.

Do AJAX requests retain PHP Session info?

What you're really getting at is: are cookies sent to with the AJAX request? Assuming the AJAX request is to the same domain (or within the domain constraints of the cookie), the answer is yes. So AJAX requests back to the same server do retain the same session info (assuming the called scripts issue a session_start() as per any other PHP script wanting access to session information).

Hidden features of Windows batch files

Line continuation:

call C:\WINDOWS\system32\ntbackup.exe ^
    backup ^
    /V:yes ^
    /R:no ^
    /RS:no ^
    /HC:off ^
    /M normal ^
    /L:s ^
    @daily.bks ^
    /F daily.bkf

How to convert a PNG image to a SVG?

A png is a bitmap image style and an SVG is a vector-based graphics design which supports bitmaps so it's not as if it would convert the image to vectors, just an image embedded in a vector-based format. You could do this using http://www.inkscape.org/ which is free. It would embed it, however it also has a Live Trace like engine which will try to convert it to paths if you wish (using potrace). See live trace in adobe illustrator (commericial) is an example:

http://graphicssoft.about.com/od/illustrator/ss/sflivetrace.htm

How to add class active on specific li on user click with jQuery

//Write a javascript method to bind click event of each "li" item

    function BindClickEvent()
    {
    var selector = '.nav li';
    //Removes click event of each li
    $(selector ).unbind('click');
    //Add click event
    $(selector ).bind('click', function()
    {
        $(selector).removeClass('active');
        $(this).addClass('active');
    });

    }

//first call this method when first time when page load

    $( document ).ready(function() {
         BindClickEvent();
    });

//Call BindClickEvent method from server side

    protected void Page_Load(object sender, EventArgs e)
    {
        ScriptManager.RegisterStartupScript(Page,GetType(), Guid.NewGuid().ToString(),"BindClickEvent();",true);
    }

What is the difference between sed and awk?

sed is a stream editor. It works with streams of characters on a per-line basis. It has a primitive programming language that includes goto-style loops and simple conditionals (in addition to pattern matching and address matching). There are essentially only two "variables": pattern space and hold space. Readability of scripts can be difficult. Mathematical operations are extraordinarily awkward at best.

There are various versions of sed with different levels of support for command line options and language features.

awk is oriented toward delimited fields on a per-line basis. It has much more robust programming constructs including if/else, while, do/while and for (C-style and array iteration). There is complete support for variables and single-dimension associative arrays plus (IMO) kludgey multi-dimension arrays. Mathematical operations resemble those in C. It has printf and functions. The "K" in "AWK" stands for "Kernighan" as in "Kernighan and Ritchie" of the book "C Programming Language" fame (not to forget Aho and Weinberger). One could conceivably write a detector of academic plagiarism using awk.

GNU awk (gawk) has numerous extensions, including true multidimensional arrays in the latest version. There are other variations of awk including mawk and nawk.

Both programs use regular expressions for selecting and processing text.

I would tend to use sed where there are patterns in the text. For example, you could replace all the negative numbers in some text that are in the form "minus-sign followed by a sequence of digits" (e.g. "-231.45") with the "accountant's brackets" form (e.g. "(231.45)") using this (which has room for improvement):

sed 's/-\([0-9.]\+\)/(\1)/g' inputfile

I would use awk when the text looks more like rows and columns or, as awk refers to them "records" and "fields". If I was going to do a similar operation as above, but only on the third field in a simple comma delimited file I might do something like:

awk -F, 'BEGIN {OFS = ","} {gsub("-([0-9.]+)", "(" substr($3, 2) ")", $3); print}' inputfile

Of course those are just very simple examples that don't illustrate the full range of capabilities that each has to offer.

Is it possible to set an object to null?

While it is true that an object cannot be "empty/null" in C++, in C++17, we got std::optional to express that intent.

Example use:

std::optional<int> v1;      // "empty" int
std::optional<int> v2(3);   // Not empty, "contains a 3"

You can then check if the optional contains a value with

v1.has_value(); // false

or

if(v2) {
    // You get here if v2 is not empty
}

A plain int (or any type), however, can never be "null" or "empty" (by your definition of those words) in any useful sense. Think of std::optional as a container in this regard.

If you don't have a C++17 compliant compiler at hand, you can use boost.optional instead. Some pre-C++17 compilers also offer std::experimental::optional, which will behave at least close to the actual std::optional afaik. Check your compiler's manual for details.

What do hjust and vjust do when making a plot using ggplot?

Probably the most definitive is Figure B.1(d) of the ggplot2 book, the appendices of which are available at http://ggplot2.org/book/appendices.pdf.

enter image description here

However, it is not quite that simple. hjust and vjust as described there are how it works in geom_text and theme_text (sometimes). One way to think of it is to think of a box around the text, and where the reference point is in relation to that box, in units relative to the size of the box (and thus different for texts of different size). An hjust of 0.5 and a vjust of 0.5 center the box on the reference point. Reducing hjust moves the box right by an amount of the box width times 0.5-hjust. Thus when hjust=0, the left edge of the box is at the reference point. Increasing hjust moves the box left by an amount of the box width times hjust-0.5. When hjust=1, the box is moved half a box width left from centered, which puts the right edge on the reference point. If hjust=2, the right edge of the box is a box width left of the reference point (center is 2-0.5=1.5 box widths left of the reference point. For vertical, less is up and more is down. This is effectively what that Figure B.1(d) says, but it extrapolates beyond [0,1].

But, sometimes this doesn't work. For example

DF <- data.frame(x=c("a","b","cdefghijk","l"),y=1:4)
p <- ggplot(DF, aes(x,y)) + geom_point()

p + opts(axis.text.x=theme_text(vjust=0))
p + opts(axis.text.x=theme_text(vjust=1))
p + opts(axis.text.x=theme_text(vjust=2))

The three latter plots are identical. I don't know why that is. Also, if text is rotated, then it is more complicated. Consider

p + opts(axis.text.x=theme_text(hjust=0, angle=90))
p + opts(axis.text.x=theme_text(hjust=0.5 angle=90))
p + opts(axis.text.x=theme_text(hjust=1, angle=90))
p + opts(axis.text.x=theme_text(hjust=2, angle=90))

The first has the labels left justified (against the bottom), the second has them centered in some box so their centers line up, and the third has them right justified (so their right sides line up next to the axis). The last one, well, I can't explain in a coherent way. It has something to do with the size of the text, the size of the widest text, and I'm not sure what else.

Simulate string split function in Excel formula

If you need the allocation to the columns only once the answer is the "Text to Columns" functionality in MS Excel.

See MS help article here: http://support.microsoft.com/kb/214261

HTH

Address already in use: JVM_Bind java

This recently happen to me when enabling JMX on two running tomcat service within Eclipse. I mistakenly put the same port for each server.

Simply give each jmx remote a different port

Server 1

-Dcom.sun.management.jmxremote.port=9000

Server 2

-Dcom.sun.management.jmxremote.port=9001

How do you Change a Package's Log Level using Log4j?

Which app server are you using? Each one puts its logging config in a different place, though most nowadays use Commons-Logging as a wrapper around either Log4J or java.util.logging.

Using Tomcat as an example, this document explains your options for configuring logging using either option. In either case you need to find or create a config file that defines the log level for each package and each place the logging system will output log info (typically console, file, or db).

In the case of log4j this would be the log4j.properties file, and if you follow the directions in the link above your file will start out looking like:

log4j.rootLogger=DEBUG, R 
log4j.appender.R=org.apache.log4j.RollingFileAppender 
log4j.appender.R.File=${catalina.home}/logs/tomcat.log 
log4j.appender.R.MaxFileSize=10MB 
log4j.appender.R.MaxBackupIndex=10 
log4j.appender.R.layout=org.apache.log4j.PatternLayout 
log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n

Simplest would be to change the line:

log4j.rootLogger=DEBUG, R

To something like:

log4j.rootLogger=WARN, R

But if you still want your own DEBUG level output from your own classes add a line that says:

log4j.category.com.mypackage=DEBUG

Reading up a bit on Log4J and Commons-Logging will help you understand all this.

method in class cannot be applied to given types

I think you want something like this. The formatting is off, but it should give the essential information you want.

   import java.util.Scanner;
public class BookstoreCredit 
{

   public static void computeDiscount(String name, double gpa) 
   {
      double credits;
      credits = gpa * 10;
      System.out.println(name + " your GPA is " +
         gpa + " so your credit is $" + credits);
   
   }

   public static void main (String args[]) 
   {
      String studentName;
      double gradeAverage;
      Scanner inputDevice = new Scanner(System.in);
      System.out.println("Enter Student name: ");
      studentName = inputDevice.nextLine();
      System.out.println("Enter student GPA: ");
      gradeAverage = inputDevice.nextDouble();  
      
      computeDiscount(studentName, gradeAverage);
   }
}

LINQ query on a DataTable

I propose following solution:

DataView view = new DataView(myDataTable); 
view.RowFilter = "RowNo = 1";
DataTable results = view.ToTable(true);

Looking at the DataView Documentation, the first thing we can see is this:

Represents a databindable, customized view of a DataTable for sorting, filtering, searching, editing, and navigation.

What I am getting from this is that DataTable is meant to only store data and DataView is there enable us to "query" against the DataTable.

Here is how this works in this particular case:

You try to implement the SQL Statement

SELECT *
FROM myDataTable
WHERE RowNo = 1

in "DataTable language". In C# we would read it like this:

FROM myDataTable
WHERE RowNo = 1
SELECT *

which looks in C# like this:

DataView view = new DataView(myDataTable);  //FROM myDataTable
view.RowFilter = "RowNo = 1";  //WHERE RowNo = 1
DataTable results = view.ToTable(true);  //SELECT *

Convert boolean to int in Java

If you want to obfuscate, use this:

System.out.println( 1 & Boolean.hashCode( true ) >> 1 );  // 1
System.out.println( 1 & Boolean.hashCode( false ) >> 1 ); // 0

Exact time measurement for performance testing

Stopwatch is fine, but loop the work 10^6 times, then divide by 10^6. You'll get a lot more precision.

Adding a regression line on a ggplot

I found this function on a blog

 ggplotRegression <- function (fit) {

    `require(ggplot2)

    ggplot(fit$model, aes_string(x = names(fit$model)[2], y = names(fit$model)[1])) + 
      geom_point() +
      stat_smooth(method = "lm", col = "red") +
      labs(title = paste("Adj R2 = ",signif(summary(fit)$adj.r.squared, 5),
                         "Intercept =",signif(fit$coef[[1]],5 ),
                         " Slope =",signif(fit$coef[[2]], 5),
                         " P =",signif(summary(fit)$coef[2,4], 5)))
    }`

once you loaded the function you could simply

ggplotRegression(fit)

you can also go for ggplotregression( y ~ x + z + Q, data)

Hope this helps.

EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0) on dispatch_semaphore_dispose

My issue was that it was in my init(). Probably the "weak self" killed him while the init wasn't finished. I moved it from the init and it solved my issue.

Command line for looking at specific port

For Windows 8 User : Open Command Prompt, type netstat -an | find "your port number" , enter .

If reply comes like LISTENING then the port is in use, else it is free .

How do I list all loaded assemblies?

Here's what I ended up with. It's a listing of all properties and methods, and I listed all parameters for each method. I didn't succeed on getting all of the values.

foreach(System.Reflection.AssemblyName an in System.Reflection.Assembly.GetExecutingAssembly().GetReferencedAssemblies()){                      
            System.Reflection.Assembly asm = System.Reflection.Assembly.Load(an.ToString());
            foreach(Type type in asm.GetTypes()){   
                //PROPERTIES
                foreach (System.Reflection.PropertyInfo property in type.GetProperties()){
                    if (property.CanRead){
                        Response.Write("<br>" + an.ToString() + "." + type.ToString() + "." + property.Name);       
                    }
                }
                //METHODS
                var methods = type.GetMethods();
                foreach (System.Reflection.MethodInfo method in methods){               
                    Response.Write("<br><b>" + an.ToString() + "."  + type.ToString() + "." + method.Name  + "</b>");   
                    foreach (System.Reflection.ParameterInfo param in method.GetParameters())
                    {
                        Response.Write("<br><i>Param=" + param.Name.ToString());
                        Response.Write("<br>  Type=" + param.ParameterType.ToString());
                        Response.Write("<br>  Position=" + param.Position.ToString());
                        Response.Write("<br>  Optional=" + param.IsOptional.ToString() + "</i>");
                    }
                }
            }
        }

Tools to get a pictorial function call graph of code

Astrée is the most robust and sophisticated tool out there, IMHO.

What's the idiomatic syntax for prepending to a short python list?

If someone finds this question like me, here are my performance tests of proposed methods:

Python 2.7.8

In [1]: %timeit ([1]*1000000).insert(0, 0)
100 loops, best of 3: 4.62 ms per loop

In [2]: %timeit ([1]*1000000)[0:0] = [0]
100 loops, best of 3: 4.55 ms per loop

In [3]: %timeit [0] + [1]*1000000
100 loops, best of 3: 8.04 ms per loop

As you can see, insert and slice assignment are as almost twice as fast than explicit adding and are very close in results. As Raymond Hettinger noted insert is more common option and I, personally prefer this way to prepend to list.

How to get WooCommerce order details

WOOCOMMERCE ORDERS IN VERSION 3.0+

Since Woocommerce mega major Update 3.0+ things have changed quite a lot:

Related:
How to get Customer details from Order in WooCommerce?
Get Order items and WC_Order_Item_Product in WooCommerce 3

So the Order items properties will not be accessible as before in a foreach loop and you will have to use these specific getter and setter methods instead.

Using some WC_Order and WC_Abstract_Order methods (example):

// Get an instance of the WC_Order object (same as before)
$order = wc_get_order( $order_id );

$order_id  = $order->get_id(); // Get the order ID
$parent_id = $order->get_parent_id(); // Get the parent order ID (for subscriptions…)

$user_id   = $order->get_user_id(); // Get the costumer ID
$user      = $order->get_user(); // Get the WP_User object

$order_status  = $order->get_status(); // Get the order status (see the conditional method has_status() below)
$currency      = $order->get_currency(); // Get the currency used  
$payment_method = $order->get_payment_method(); // Get the payment method ID
$payment_title = $order->get_payment_method_title(); // Get the payment method title
$date_created  = $order->get_date_created(); // Get date created (WC_DateTime object)
$date_modified = $order->get_date_modified(); // Get date modified (WC_DateTime object)

$billing_country = $order->get_billing_country(); // Customer billing country

// ... and so on ...

For order status as a conditional method (where "the_targeted_status" need to be defined and replaced by an order status to target a specific order status):

if ( $order->has_status('completed') ) {
    // Do something
}

Get and access to the order data properties (in an array of values):

// Get an instance of the WC_Order object
$order = wc_get_order( $order_id );

$order_data = $order->get_data(); // The Order data

$order_id = $order_data['id'];
$order_parent_id = $order_data['parent_id'];
$order_status = $order_data['status'];
$order_currency = $order_data['currency'];
$order_version = $order_data['version'];
$order_payment_method = $order_data['payment_method'];
$order_payment_method_title = $order_data['payment_method_title'];
$order_payment_method = $order_data['payment_method'];
$order_payment_method = $order_data['payment_method'];

## Creation and modified WC_DateTime Object date string ##

// Using a formated date ( with php date() function as method)
$order_date_created = $order_data['date_created']->date('Y-m-d H:i:s');
$order_date_modified = $order_data['date_modified']->date('Y-m-d H:i:s');

// Using a timestamp ( with php getTimestamp() function as method)
$order_timestamp_created = $order_data['date_created']->getTimestamp();
$order_timestamp_modified = $order_data['date_modified']->getTimestamp();

$order_discount_total = $order_data['discount_total'];
$order_discount_tax = $order_data['discount_tax'];
$order_shipping_total = $order_data['shipping_total'];
$order_shipping_tax = $order_data['shipping_tax'];
$order_total = $order_data['total'];
$order_total_tax = $order_data['total_tax'];
$order_customer_id = $order_data['customer_id']; // ... and so on

## BILLING INFORMATION:

$order_billing_first_name = $order_data['billing']['first_name'];
$order_billing_last_name = $order_data['billing']['last_name'];
$order_billing_company = $order_data['billing']['company'];
$order_billing_address_1 = $order_data['billing']['address_1'];
$order_billing_address_2 = $order_data['billing']['address_2'];
$order_billing_city = $order_data['billing']['city'];
$order_billing_state = $order_data['billing']['state'];
$order_billing_postcode = $order_data['billing']['postcode'];
$order_billing_country = $order_data['billing']['country'];
$order_billing_email = $order_data['billing']['email'];
$order_billing_phone = $order_data['billing']['phone'];

## SHIPPING INFORMATION:

$order_shipping_first_name = $order_data['shipping']['first_name'];
$order_shipping_last_name = $order_data['shipping']['last_name'];
$order_shipping_company = $order_data['shipping']['company'];
$order_shipping_address_1 = $order_data['shipping']['address_1'];
$order_shipping_address_2 = $order_data['shipping']['address_2'];
$order_shipping_city = $order_data['shipping']['city'];
$order_shipping_state = $order_data['shipping']['state'];
$order_shipping_postcode = $order_data['shipping']['postcode'];
$order_shipping_country = $order_data['shipping']['country'];

Get the order items and access the data with WC_Order_Item_Product and WC_Order_Item methods:

// Get an instance of the WC_Order object
$order = wc_get_order($order_id);

// Iterating through each WC_Order_Item_Product objects
foreach ($order->get_items() as $item_key => $item ):

    ## Using WC_Order_Item methods ##

    // Item ID is directly accessible from the $item_key in the foreach loop or
    $item_id = $item->get_id();

    ## Using WC_Order_Item_Product methods ##

    $product      = $item->get_product(); // Get the WC_Product object

    $product_id   = $item->get_product_id(); // the Product id
    $variation_id = $item->get_variation_id(); // the Variation id

    $item_type    = $item->get_type(); // Type of the order item ("line_item")

    $item_name    = $item->get_name(); // Name of the product
    $quantity     = $item->get_quantity();  
    $tax_class    = $item->get_tax_class();
    $line_subtotal     = $item->get_subtotal(); // Line subtotal (non discounted)
    $line_subtotal_tax = $item->get_subtotal_tax(); // Line subtotal tax (non discounted)
    $line_total        = $item->get_total(); // Line total (discounted)
    $line_total_tax    = $item->get_total_tax(); // Line total tax (discounted)

    ## Access Order Items data properties (in an array of values) ##
    $item_data    = $item->get_data();

    $product_name = $item_data['name'];
    $product_id   = $item_data['product_id'];
    $variation_id = $item_data['variation_id'];
    $quantity     = $item_data['quantity'];
    $tax_class    = $item_data['tax_class'];
    $line_subtotal     = $item_data['subtotal'];
    $line_subtotal_tax = $item_data['subtotal_tax'];
    $line_total        = $item_data['total'];
    $line_total_tax    = $item_data['total_tax'];

    // Get data from The WC_product object using methods (examples)
    $product        = $item->get_product(); // Get the WC_Product object

    $product_type   = $product->get_type();
    $product_sku    = $product->get_sku();
    $product_price  = $product->get_price();
    $stock_quantity = $product->get_stock_quantity();

endforeach;

So using get_data() method allow us to access to the protected data (associative array mode) …

What are the differences between numpy arrays and matrices? Which one should I use?

Just to add one case to unutbu's list.

One of the biggest practical differences for me of numpy ndarrays compared to numpy matrices or matrix languages like matlab, is that the dimension is not preserved in reduce operations. Matrices are always 2d, while the mean of an array, for example, has one dimension less.

For example demean rows of a matrix or array:

with matrix

>>> m = np.mat([[1,2],[2,3]])
>>> m
matrix([[1, 2],
        [2, 3]])
>>> mm = m.mean(1)
>>> mm
matrix([[ 1.5],
        [ 2.5]])
>>> mm.shape
(2, 1)
>>> m - mm
matrix([[-0.5,  0.5],
        [-0.5,  0.5]])

with array

>>> a = np.array([[1,2],[2,3]])
>>> a
array([[1, 2],
       [2, 3]])
>>> am = a.mean(1)
>>> am.shape
(2,)
>>> am
array([ 1.5,  2.5])
>>> a - am #wrong
array([[-0.5, -0.5],
       [ 0.5,  0.5]])
>>> a - am[:, np.newaxis]  #right
array([[-0.5,  0.5],
       [-0.5,  0.5]])

I also think that mixing arrays and matrices gives rise to many "happy" debugging hours. However, scipy.sparse matrices are always matrices in terms of operators like multiplication.

I want to calculate the distance between two points in Java

Based on the @trashgod's comment, this is the simpliest way to calculate >distance:

double distance = Math.hypot(x1-x2, y1-y2); From documentation of Math.hypot:

Returns: sqrt(x²+ y²) without intermediate overflow or underflow.

Bob

Below Bob's approved comment he said he couldn't explain what the

Math.hypot(x1-x2, y1-y2);

did. To explain a triangle has three sides. With two points you can find the length of those points based on the x,y of each. Xa=0, Ya=0 If thinking in Cartesian coordinates that is (0,0) and then Xb=5, Yb=9 Again, cartesian coordinates is (5,9). So if you were to plot those on a grid, the distance from from x to another x assuming they are on the same y axis is +5. and the distance along the Y axis from one to another assuming they are on the same x-axis is +9. (think number line) Thus one side of the triangle's length is 5, another side is 9. A hypotenuse is

 (x^2) + (y^2) = Hypotenuse^2

which is the length of the remaining side of a triangle. Thus being quite the same as a standard distance formula where

 Sqrt of (x1-x2)^2 + (y1-y2)^2 = distance 

because if you do away with the sqrt on the lefthand side of the operation and instead make distance^2 then you still have to get the sqrt from the distance. So the distance formula is the Pythagorean theorem but in a way that teachers can call it something different to confuse people.

How to convert int to float in python?

The answers provided above are absolutely correct and worth to read but I just wanted to give a straight forward answer to the question.

The question asked is just a type conversion question and here its conversion from int data type to float data type and for that you can do it by the function :

float()

And for more details you can visit this page.

Send HTTP GET request with header

You do it exactly as you showed with this line:

get.setHeader("Content-Type", "application/x-zip");

So your header is fine and the problem is some other input to the web service. You'll want to debug that on the server side.

Add a auto increment primary key to existing table in oracle

Say your table is called t1 and your primary-key is called id
First, create the sequence:

create sequence t1_seq start with 1 increment by 1 nomaxvalue; 

Then create a trigger that increments upon insert:

create trigger t1_trigger
before insert on t1
for each row
   begin
     select t1_seq.nextval into :new.id from dual;
   end;

How to programmatically set cell value in DataGridView?

I searched for the solution how I can insert a new row and How to set the individual values of the cells inside it like Excel. I solved with following code:

dataGridView1.ReadOnly = false; //Before modifying, it is required.
dataGridView1.Rows.Add(); //Inserting first row if yet there is no row, first row number is '0'
dataGridView1.Rows[0].Cells[0].Value = "Razib, this is 0,0!"; //Setting the leftmost and topmost cell's value (Not the column header row!)
dataGridView1[1, 0].Value = "This is 0,1!"; //Setting the Second cell of the first row!

Note:

  1. Previously I have designed the columns in design mode.
  2. I have set the row header visibility to false from property of the datagridview.
  3. The last line is important to understand: When yoou directly giving index of datagridview, the first number is cell number, second one is row number! Remember it!

Hope this might help you.

String literals and escape characters in postgresql

Partially. The text is inserted, but the warning is still generated.

I found a discussion that indicated the text needed to be preceded with 'E', as such:

insert into EscapeTest (text) values (E'This is the first part \n And this is the second');

This suppressed the warning, but the text was still not being returned correctly. When I added the additional slash as Michael suggested, it worked.

As such:

insert into EscapeTest (text) values (E'This is the first part \\n And this is the second');

window.print() not working in IE

For Firefox use

iframewin.print()

for IE use

iframedocument.execCommand('print', false, null);

see also Unable to print an iframe on IE using JavaScript, prints parent page instead

"This operation requires IIS integrated pipeline mode."

Try using Response.AddHeader instead of Response.Headers.Add()

Multiple variables in a 'with' statement?

From Python 3.10 there is a new feature of Parenthesized context managers, which permits syntax such as:

with (
    A() as a,
    B() as b
):
    do_something(a, b)

SQL query for today's date minus two months

TSQL, Alternative using variable declaration. (it might improve Query's readability)

DECLARE @gapPeriod DATETIME = DATEADD(MONTH,-2,GETDATE()); --Period:Last 2 months.

SELECT 
        *
    FROM 
        FB as A
    WHERE
        A.Dte <= @gapPeriod;                               --only older records.

How create a new deep copy (clone) of a List<T>?

I'm disappointed Microsoft didn't offer a neat, fast and easy solution like Ruby are doing with the clone() method.

Except that does not create a deep copy, it creates a shallow copy.

With deep copying, you have to be always careful, what exactly do you want to copy. Some examples of possible issues are:

  1. Cycle in the object graph. For example, Book has an Author and Author has a list of his Books.
  2. Reference to some external object. For example, an object could contain open Stream that writes to a file.
  3. Events. If an object contains an event, pretty much anyone could be subscribed to it. This can get especially problematic if the subscriber is something like a GUI Window.

Now, there are basically two ways how to clone something:

  1. Implement a Clone() method in each class that you need cloned. (There is also ICloneable interface, but you should not use that; using a custom ICloneable<T> interface as Trevor suggested is okay.) If you know that all you need is to create a shallow copy of each field of this class, you could use MemberwiseClone() to implement it. As an alternative, you could create a “copy constructor”: public Book(Book original).
  2. Use serialization to serialize your objects into a MemoryStream and then deserialize them back. This requires you to mark each class as [Serializable] and it can also be configured what exactly (and how) should be serialized. But this is more of a “quick and dirty” solution, and will most likely also be less performant.

Difference between string object and string literal

A String literal is a Java language concept. This is a String literal:

"a String literal"

A String object is an individual instance of the java.lang.String class.

String s1 = "abcde";
String s2 = new String("abcde");
String s3 = "abcde";

All are valid, but have a slight difference. s1 will refer to an interned String object. This means, that the character sequence "abcde" will be stored at a central place, and whenever the same literal "abcde" is used again, the JVM will not create a new String object but use the reference of the cached String.

s2 is guranteed to be a new String object, so in this case we have:

s1 == s2 // is false
s1 == s3 // is true
s1.equals(s2) // is true

Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"

Check if you have entered the correct URL Mapping as specified in the Web.xml

For example:

In the web.xml, your servlet declaration maybe:

<servlet>
        <servlet-name>ControllerA</servlet-name>
        <servlet-class>PackageName.ControllerA</servlet-class>
</servlet>

<servlet-mapping>
        <servlet-name>ControllerA</servlet-name>
        <url-pattern>/theController</url-pattern>
</servlet-mapping>

What this snippet does is <url-pattern>/theController</url-pattern>will set the name that will be used to call the servlet from the front end (eg: form) through the URL. Therefore when you reference the servlet in the front end, in order to ensure that the request goes to the servlet "ControllerA", it should refer the specified URL Pattern "theController" from the form.

eg:

<form action="theController" method="POST">
</form>

"Unable to acquire application service" error while launching Eclipse

In the Windows environment, running Eclipse as Administrator solved the issue. (Right click>Run as Administrator)

Count number of lines in a git repository

I've encountered batching problems with git ls-files | xargs wc -l when dealing with large numbers of files, where the line counts will get chunked out into multiple total lines.

Taking a tip from question Why does the wc utility generate multiple lines with "total"?, I've found the following command to bypass the issue:

wc -l $(git ls-files)

Or if you want to only examine some files, e.g. code:

wc -l $(git ls-files | grep '.*\.cs')

jQuery Ajax calls and the Html.AntiForgeryToken()

Don't use Html.AntiForgeryToken. Instead, use AntiForgery.GetTokens and AntiForgery.Validate from Web API as described in Preventing Cross-Site Request Forgery (CSRF) Attacks in ASP.NET MVC Application.

DELETE ... FROM ... WHERE ... IN

Try adding parentheses around the row in table1 e.g.

DELETE 
  FROM table1
 WHERE (stn, year(datum)) IN (SELECT stn, jaar FROM table2);

The above is Standard SQL-92 code. If that doesn't work, it could be that your SQL product of choice doesn't support it.

Here's another Standard SQL approach that is more widely implemented among vendors e.g. tested on SQL Server 2008:

MERGE INTO table1 AS t1
   USING table2 AS s1
      ON t1.stn = s1.stn
         AND s1.jaar = YEAR(t1.datum)
WHEN MATCHED THEN DELETE;

remove None value from a list without removing the 0 value

Say the list is like below

iterator = [None, 1, 2, 0, '', None, False, {}, (), []]

This will return only those items whose bool(item) is True

print filter(lambda item: item, iterator)
# [1, 2]

This is equivalent to

print [item for item in iterator if item]

To just filter None:

print filter(lambda item: item is not None, iterator)
# [1, 2, 0, '', False, {}, (), []]

Equivalent to:

print [item for item in iterator if item is not None]

To get all the items that evaluate to False

print filter(lambda item: not item, iterator)
# Will print [None, '', 0, None, False, {}, (), []]

How to cast ArrayList<> from List<>

May be:

ArrayList<ServiceModel> services = new ArrayList<>(parking.getServices());
intent.putExtra("servicios",services);

ArrayList - How to modify a member of an object?

Try this.This works while traversing the code and modifying the fields at once of all the elements of Arraylist.

public Employee(String name,String email){
this.name=name;
this.email=email;
}

public void setName(String name) {
this.name = name;
}

public String getName() {
return name;
}

public void setEmail(String email) {
this.email = email;
}

public String getEmail() {
return email;
}

for(int i=0;i++){
List.get(i).setName("Anonymous");
List.get(i).setEmail("[email protected]");
}

Update Git submodule to latest commit on origin

In your project parent directory, run:

git submodule update --init

Or if you have recursive submodules run:

git submodule update --init --recursive

Sometimes this still doesn't work, because somehow you have local changes in the local submodule directory while the submodule is being updated.

Most of the time the local change might not be the one you want to commit. It can happen due to a file deletion in your submodule, etc. If so, do a reset in your local submodule directory and in your project parent directory, run again:

git submodule update --init --recursive

List of <p:ajax> events

Unfortunatelly, Ajax events are poorly documented and I haven't found any comprehensive list. For example, User Guide v. 3.5 lists itemChange event for p:autoComplete, but forgets to mention change event.

If you want to find out which events are supported:

  1. Download and unpack primefaces source jar
  2. Find the JavaScript file, where your component is defined (for example, most form components such as SelectOneMenu are defined in forms.js)
  3. Search for this.cfg.behaviors references

For example, this section is responsible for launching toggleSelect event in SelectCheckboxMenu component:

fireToggleSelectEvent: function(checked) {
    if(this.cfg.behaviors) {
        var toggleSelectBehavior = this.cfg.behaviors['toggleSelect'];

        if(toggleSelectBehavior) {
            var ext = {
                params: [{name: this.id + '_checked', value: checked}]
            }
        }

        toggleSelectBehavior.call(this, null, ext);
    }
},

How to define a connection string to a SQL Server 2008 database?

Standard Security
Data Source=serverName\instanceName;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;

Trusted Connection
Data Source=serverName\instanceName;Initial Catalog=myDataBase;Integrated Security=SSPI;

Here's a good reference on connection strings that I keep handy: ConnectionStrings.com

requestFeature() must be called before adding content

I was extending a DialogFragment and the above answer didnot work. I had to use getDialog() to achieve remove the title:

getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);

Android Studio-No Module

enter image description here

For those of you who are visual learners here is another place to look for the fix. I did indeed find that the underlined tag was pointing to "library" and a change to "application" and then updating gradle got my project running on the emulator.

Groovy: How to check if a string contains any element of an array?

def valid = pointAddress.findAll { a ->
    validPointTypes.any { a.contains(it) }
}

Should do it

Google Maps: Auto close open InfoWindows?

//assuming you have a map called 'map'
var infowindow = new google.maps.InfoWindow();

var latlng1 = new google.maps.LatLng(0,0);
var marker1 = new google.maps.Marker({position:latlng1, map:map});
google.maps.event.addListener(marker1, 'click',
    function(){
        infowindow.close();//hide the infowindow
        infowindow.setContent('Marker #1');//update the content for this marker
        infowindow.open(map, marker1);//"move" the info window to the clicked marker and open it
    }
);
var latlng2 = new google.maps.LatLng(10,10);
var marker2 = new google.maps.Marker({position:latlng2, map:map});
google.maps.event.addListener(marker2, 'click',
    function(){
        infowindow.close();//hide the infowindow
        infowindow.setContent('Marker #2');//update the content for this marker
        infowindow.open(map, marker2);//"move" the info window to the clicked marker and open it
    }
);

This will "move" the info window around to each clicked marker, in effect closing itself, then reopening (and panning to fit the viewport) in its new location. It changes its contents before opening to give the desired effect. Works for n markers.

Java to Jackson JSON serialization: Money fields

As Sahil Chhabra suggested you can use @JsonFormat with proper shape on your variable. In case you would like to apply it on every BigDecimal field you have in your Dto's you can override default format for given class.

@Configuration
public class JacksonObjectMapperConfiguration {

    @Autowired
    public void customize(ObjectMapper objectMapper) {
         objectMapper
            .configOverride(BigDecimal.class).setFormat(JsonFormat.Value.forShape(JsonFormat.Shape.STRING));
    }
}

What are Java command line options to set to allow JVM to be remotely debugged?

I have this article bookmarked on setting this up for Java 5 and below.

Basically run it with:

-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=1044

For Java 5 and above, run it with:

-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=1044

Can you do a partial checkout with Subversion?

Indeed, thanks to the comments to my post here, it looks like sparse directories are the way to go. I believe the following should do it:

svn checkout --depth empty http://svnserver/trunk/proj
svn update --set-depth infinity proj/foo
svn update --set-depth infinity proj/bar
svn update --set-depth infinity proj/baz

Alternatively, --depth immediates instead of empty checks out files and directories in trunk/proj without their contents. That way you can see which directories exist in the repository.


As mentioned in @zigdon's answer, you can also do a non-recursive checkout. This is an older and less flexible way to achieve a similar effect:

svn checkout --non-recursive http://svnserver/trunk/proj
svn update trunk/foo
svn update trunk/bar
svn update trunk/baz

How to retrieve SQL result column value using column name in Python?

import mysql
import mysql.connector

db = mysql.connector.connect(
   host = "localhost",
    user = "root",
    passwd = "P@ssword1",
    database = "appbase"
)

cursor = db.cursor(dictionary=True)

sql = "select Id, Email from appuser limit 0,1"
cursor.execute(sql)
result = cursor.fetchone()

print(result)
# output =>  {'Id': 1, 'Email': '[email protected]'}

print(result["Id"])
# output => 1

print(result["Email"])
# output => [email protected]

How to format strings using printf() to get equal length in the output

Additionally, if you want the flexibility of choosing the width, you can choose between one of the following two formats (with or without truncation):

int width = 30;
// No truncation uses %-*s
printf( "%-*s %s\n", width, "Starting initialization...", "Ok." );
// Output is "Starting initialization...     Ok."

// Truncated to the specified width uses %-.*s
printf( "%-.*s %s\n", width, "Starting initialization...", "Ok." );
// Output is "Starting initialization... Ok."

Convert array values from string to int?

This is almost 3 times faster than explode(), array_map() and intval():

$integerIDs = json_decode('[' . $string . ']', true);

How do I get the size of a java.sql.ResultSet?

[Speed consideration]

Lot of ppl here suggests ResultSet.last() but for that you would need to open connection as a ResultSet.TYPE_SCROLL_INSENSITIVE which for Derby embedded database is up to 10 times SLOWER than ResultSet.TYPE_FORWARD_ONLY.

According to my micro-tests for embedded Derby and H2 databases it is significantly faster to call SELECT COUNT(*) before your SELECT.

Here is in more detail my code and my benchmarks

pdftk compression option

If file size is still too large it could help using ps2pdf to downscale the resolution of the produced pdf file:

pdf2ps input.pdf tmp.ps
ps2pdf -dPDFSETTINGS=/screen -dDownsampleColorImages=true -dColorImageResolution=200 -dColorImageDownsampleType=/Bicubic tmp.ps output.pdf

Adjust the value of the -dColorImageResolution option to achieve a result that fits your needs (the value describes the image resolution in DPIs). If your input file is in grayscale, replacing Color through Gray or using both options in the above command could also help. Further fine-tuning is possible by changing the -dPDFSETTINGS option to /default or /printer. For explanations of the all possible options consult the ps2pdf manual.

Tkinter: How to use threads to preventing main event loop from "freezing"

I will submit the basis for an alternate solution. It is not specific to a Tk progress bar per se, but it can certainly be implemented very easily for that.

Here are some classes that allow you to run other tasks in the background of Tk, update the Tk controls when desired, and not lock up the gui!

Here's class TkRepeatingTask and BackgroundTask:

import threading

class TkRepeatingTask():

    def __init__( self, tkRoot, taskFuncPointer, freqencyMillis ):
        self.__tk_   = tkRoot
        self.__func_ = taskFuncPointer        
        self.__freq_ = freqencyMillis
        self.__isRunning_ = False

    def isRunning( self ) : return self.__isRunning_ 

    def start( self ) : 
        self.__isRunning_ = True
        self.__onTimer()

    def stop( self ) : self.__isRunning_ = False

    def __onTimer( self ): 
        if self.__isRunning_ :
            self.__func_() 
            self.__tk_.after( self.__freq_, self.__onTimer )

class BackgroundTask():

    def __init__( self, taskFuncPointer ):
        self.__taskFuncPointer_ = taskFuncPointer
        self.__workerThread_ = None
        self.__isRunning_ = False

    def taskFuncPointer( self ) : return self.__taskFuncPointer_

    def isRunning( self ) : 
        return self.__isRunning_ and self.__workerThread_.isAlive()

    def start( self ): 
        if not self.__isRunning_ :
            self.__isRunning_ = True
            self.__workerThread_ = self.WorkerThread( self )
            self.__workerThread_.start()

    def stop( self ) : self.__isRunning_ = False

    class WorkerThread( threading.Thread ):
        def __init__( self, bgTask ):      
            threading.Thread.__init__( self )
            self.__bgTask_ = bgTask

        def run( self ):
            try :
                self.__bgTask_.taskFuncPointer()( self.__bgTask_.isRunning )
            except Exception as e: print repr(e)
            self.__bgTask_.stop()

Here's a Tk test which demos the use of these. Just append this to the bottom of the module with those classes in it if you want to see the demo in action:

def tkThreadingTest():

    from tkinter import Tk, Label, Button, StringVar
    from time import sleep

    class UnitTestGUI:

        def __init__( self, master ):
            self.master = master
            master.title( "Threading Test" )

            self.testButton = Button( 
                self.master, text="Blocking", command=self.myLongProcess )
            self.testButton.pack()

            self.threadedButton = Button( 
                self.master, text="Threaded", command=self.onThreadedClicked )
            self.threadedButton.pack()

            self.cancelButton = Button( 
                self.master, text="Stop", command=self.onStopClicked )
            self.cancelButton.pack()

            self.statusLabelVar = StringVar()
            self.statusLabel = Label( master, textvariable=self.statusLabelVar )
            self.statusLabel.pack()

            self.clickMeButton = Button( 
                self.master, text="Click Me", command=self.onClickMeClicked )
            self.clickMeButton.pack()

            self.clickCountLabelVar = StringVar()            
            self.clickCountLabel = Label( master,  textvariable=self.clickCountLabelVar )
            self.clickCountLabel.pack()

            self.threadedButton = Button( 
                self.master, text="Timer", command=self.onTimerClicked )
            self.threadedButton.pack()

            self.timerCountLabelVar = StringVar()            
            self.timerCountLabel = Label( master,  textvariable=self.timerCountLabelVar )
            self.timerCountLabel.pack()

            self.timerCounter_=0

            self.clickCounter_=0

            self.bgTask = BackgroundTask( self.myLongProcess )

            self.timer = TkRepeatingTask( self.master, self.onTimer, 1 )

        def close( self ) :
            print "close"
            try: self.bgTask.stop()
            except: pass
            try: self.timer.stop()
            except: pass            
            self.master.quit()

        def onThreadedClicked( self ):
            print "onThreadedClicked"
            try: self.bgTask.start()
            except: pass

        def onTimerClicked( self ) :
            print "onTimerClicked"
            self.timer.start()

        def onStopClicked( self ) :
            print "onStopClicked"
            try: self.bgTask.stop()
            except: pass
            try: self.timer.stop()
            except: pass                        

        def onClickMeClicked( self ):
            print "onClickMeClicked"
            self.clickCounter_+=1
            self.clickCountLabelVar.set( str(self.clickCounter_) )

        def onTimer( self ) :
            print "onTimer"
            self.timerCounter_+=1
            self.timerCountLabelVar.set( str(self.timerCounter_) )

        def myLongProcess( self, isRunningFunc=None ) :
            print "starting myLongProcess"
            for i in range( 1, 10 ):
                try:
                    if not isRunningFunc() :
                        self.onMyLongProcessUpdate( "Stopped!" )
                        return
                except : pass   
                self.onMyLongProcessUpdate( i )
                sleep( 1.5 ) # simulate doing work
            self.onMyLongProcessUpdate( "Done!" )                

        def onMyLongProcessUpdate( self, status ) :
            print "Process Update: %s" % (status,)
            self.statusLabelVar.set( str(status) )

    root = Tk()    
    gui = UnitTestGUI( root )
    root.protocol( "WM_DELETE_WINDOW", gui.close )
    root.mainloop()

if __name__ == "__main__": 
    tkThreadingTest()

Two import points I'll stress about BackgroundTask:

1) The function you run in the background task needs to take a function pointer it will both invoke and respect, which allows the task to be cancelled mid way through - if possible.

2) You need to make sure the background task is stopped when you exit your application. That thread will still run even if your gui is closed if you don't address that!

With CSS, how do I make an image span the full width of the page as a background image?

If you're hoping to use background-image: url(...);, I don't think you can. However, if you want to play with layering, you can do something like this:

<img class="bg" src="..." />

And then some CSS:

.bg
{
  width: 100%;
  z-index: 0;
}

You can now layer content above the stretched image by playing with z-indexes and such. One quick note, the image can't be contained in any other elements for the width: 100%; to apply to the whole page.

Here's a quick demo if you can't rely on background-size: http://jsfiddle.net/bB3Uc/

vertical-align image in div

If you have a fixed height in your container, you can set line-height to be the same as height, and it will center vertically. Then just add text-align to center horizontally.

Here's an example: http://jsfiddle.net/Cthulhu/QHEnL/1/

EDIT

Your code should look like this:

.img_thumb {
    float: left;
    height: 120px;
    margin-bottom: 5px;
    margin-left: 9px;
    position: relative;
    width: 147px;
    background-color: rgba(0, 0, 0, 0.5);
    border-radius: 3px;
    line-height:120px;
    text-align:center;
}

.img_thumb img {
    vertical-align: middle;
}

The images will always be centered horizontally and vertically, no matter what their size is. Here's 2 more examples with images with different dimensions:

http://jsfiddle.net/Cthulhu/QHEnL/6/

http://jsfiddle.net/Cthulhu/QHEnL/7/

UPDATE

It's now 2016 (the future!) and looks like a few things are changing (finally!!).

Back in 2014, Microsoft announced that it will stop supporting IE8 in all versions of Windows and will encourage all users to update to IE11 or Edge. Well, this is supposed to happen next Tuesday (12th January).

Why does this matter? With the announced death of IE8, we can finally start using CSS3 magic.

With that being said, here's an updated way of aligning elements, both horizontally and vertically:

.container {
    position: relative;
}

.container .element {
   position: absolute;
   left: 50%;
   top: 50%;
   transform: translate(-50%, -50%);
}

Using this transform: translate(); method, you don't even need to have a fixed height in your container, it's fully dynamic. Your element has fixed height or width? Your container as well? No? It doesn't matter, it will always be centered because all centering properties are fixed on the child, it's independent from the parent. Thank you CSS3.

If you only need to center in one dimension, you can use translateY or translateX. Just try it for a while and you'll see how it works. Also, try to change the values of the translate, you will find it useful for a bunch of different situations.

Here, have a new fiddle: https://jsfiddle.net/Cthulhu/1xjbhsr4/

For more information on transform, here's a good resource.

Happy coding.

"And" and "Or" troubles within an IF statement

I like assylias' answer, however I would refactor it as follows:

Sub test()

Dim origNum As String
Dim creditOrDebit As String

origNum = "30062600006"
creditOrDebit = "D"

If creditOrDebit = "D" Then
  If origNum = "006260006" Then
    MsgBox "OK"
  ElseIf origNum = "30062600006" Then
    MsgBox "OK"
  End If
End If

End Sub

This might save you some CPU cycles since if creditOrDebit is <> "D" there is no point in checking the value of origNum.

Update:

I used the following procedure to test my theory that my procedure is faster:

Public Declare Function timeGetTime Lib "winmm.dll" () As Long

Sub DoTests2()

  Dim startTime1 As Long
  Dim endTime1 As Long
  Dim startTime2 As Long
  Dim endTime2 As Long
  Dim i As Long
  Dim msg As String

  Const numberOfLoops As Long = 10000
  Const origNum As String = "006260006"
  Const creditOrDebit As String = "D"

  startTime1 = timeGetTime
  For i = 1 To numberOfLoops
    If creditOrDebit = "D" Then
      If origNum = "006260006" Then
        ' do something here
        Debug.Print "OK"
      ElseIf origNum = "30062600006" Then
        ' do something here
        Debug.Print "OK"
      End If
    End If
  Next i
  endTime1 = timeGetTime

  startTime2 = timeGetTime
  For i = 1 To numberOfLoops
    If (origNum = "006260006" Or origNum = "30062600006") And _
      creditOrDebit = "D" Then
      ' do something here
      Debug.Print "OK"
    End If
  Next i
  endTime2 = timeGetTime

  msg = "number of iterations: " & numberOfLoops & vbNewLine
  msg = msg & "JP proc: " & Format$((endTime1 - startTime1), "#,###") & _
       " ms" & vbNewLine
  msg = msg & "assylias proc: " & Format$((endTime2 - startTime2), "#,###") & _
       " ms"

  MsgBox msg

End Sub

I must have a slow computer because 1,000,000 iterations took nowhere near ~200 ms as with assylias' test. I had to limit the iterations to 10,000 -- hey, I have other things to do :)

After running the above procedure 10 times, my procedure is faster only 20% of the time. However, when it is slower it is only superficially slower. As assylias pointed out, however, when creditOrDebit is <>"D", my procedure is at least twice as fast. I was able to reasonably test it at 100 million iterations.

And that is why I refactored it - to short-circuit the logic so that origNum doesn't need to be evaluated when creditOrDebit <> "D".

At this point, the rest depends on the OP's spreadsheet. If creditOrDebit is likely to equal D, then use assylias' procedure, because it will usually run faster. But if creditOrDebit has a wide range of possible values, and D is not any more likely to be the target value, my procedure will leverage that to prevent needlessly evaluating the other variable.

Defining custom attrs

The traditional approach is full of boilerplate code and clumsy resource handling. That's why I made the Spyglass framework. To demonstrate how it works, here's an example showing how to make a custom view that displays a String title.

Step 1: Create a custom view class.

public class CustomView extends FrameLayout {
    private TextView titleView;

    public CustomView(Context context) {
        super(context);
        init(null, 0, 0);
    }

    public CustomView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(attrs, 0, 0);
    }

    public CustomView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(attrs, defStyleAttr, 0);
    }

    @RequiresApi(21)
    public CustomView(
            Context context, 
            AttributeSet attrs,
            int defStyleAttr,
            int defStyleRes) {

        super(context, attrs, defStyleAttr, defStyleRes);
        init(attrs, defStyleAttr, defStyleRes);
    }

    public void setTitle(String title) {
        titleView.setText(title);
    }

    private void init(AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        inflate(getContext(), R.layout.custom_view, this);

        titleView = findViewById(R.id.title_view);
    }
}

Step 2: Define a string attribute in the values/attrs.xml resource file:

<resources>
    <declare-styleable name="CustomView">
        <attr name="title" format="string"/>
    </declare-styleable>
</resources>

Step 3: Apply the @StringHandler annotation to the setTitle method to tell the Spyglass framework to route the attribute value to this method when the view is inflated.

@HandlesString(attributeId = R.styleable.CustomView_title)
public void setTitle(String title) {
    titleView.setText(title);
}

Now that your class has a Spyglass annotation, the Spyglass framework will detect it at compile-time and automatically generate the CustomView_SpyglassCompanion class.

Step 4: Use the generated class in the custom view's init method:

private void init(AttributeSet attrs, int defStyleAttr, int defStyleRes) {
    inflate(getContext(), R.layout.custom_view, this);

    titleView = findViewById(R.id.title_view);

    CustomView_SpyglassCompanion
            .builder()
            .withTarget(this)
            .withContext(getContext())
            .withAttributeSet(attrs)
            .withDefaultStyleAttribute(defStyleAttr)
            .withDefaultStyleResource(defStyleRes)
            .build()
            .callTargetMethodsNow();
}

That's it. Now when you instantiate the class from XML, the Spyglass companion interprets the attributes and makes the required method call. For example, if we inflate the following layout then setTitle will be called with "Hello, World!" as the argument.

<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:width="match_parent"
    android:height="match_parent">

    <com.example.CustomView
        android:width="match_parent"
        android:height="match_parent"
        app:title="Hello, World!"/>
</FrameLayout>

The framework isn't limited to string resources has lots of different annotations for handling other resource types. It also has annotations for defining default values and for passing in placeholder values if your methods have multiple parameters.

Have a look at the Github repo for more information and examples.

Declaring a xsl variable and assigning value to it

No, unlike in a lot of other languages, XSLT variables cannot change their values after they are created. You can however, avoid extraneous code with a technique like this:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>

  <xsl:variable name="mapping">
    <item key="1" v1="A" v2="B" />
    <item key="2" v1="X" v2="Y" />
  </xsl:variable>
  <xsl:variable name="mappingNode"
                select="document('')//xsl:variable[@name = 'mapping']" />

  <xsl:template match="....">
    <xsl:variable name="testVariable" select="'1'" />

    <xsl:variable name="values" select="$mappingNode/item[@key = $testVariable]" />

    <xsl:variable name="variable1" select="$values/@v1" />
    <xsl:variable name="variable2" select="$values/@v2" />
  </xsl:template>
</xsl:stylesheet>

In fact, once you've got the values variable, you may not even need separate variable1 and variable2 variables. You could just use $values/@v1 and $values/@v2 instead.

Removing the password from a VBA project

I found this here that describes how to set the VBA Project Password. You should be able to modify it to unset the VBA Project Password.

This one does not use SendKeys.

Let me know if this helps! JFV

How can I use goto in Javascript?

Another alternative way to achieve the same is to use the tail calls. But, we don’t have anything like that in JavaScript. So generally, the goto is accomplished in JS using the below two keywords. break and continue, reference: Goto Statement in JavaScript

Here is an example:

var number = 0;
start_position: while(true) {
document.write("Anything you want to print");
number++;
if(number < 100) continue start_position;
break;
}

jQuery - Detect value change on hidden input field

Building off of Viktar's answer, here's an implementation you can call once on a given hidden input element to ensure that subsequent change events get fired whenever the value of the input element changes:

/**
 * Modifies the provided hidden input so value changes to trigger events.
 *
 * After this method is called, any changes to the 'value' property of the
 * specified input will trigger a 'change' event, just like would happen
 * if the input was a text field.
 *
 * As explained in the following SO post, hidden inputs don't normally
 * trigger on-change events because the 'blur' event is responsible for
 * triggering a change event, and hidden inputs aren't focusable by virtue
 * of being hidden elements:
 * https://stackoverflow.com/a/17695525/4342230
 *
 * @param {HTMLInputElement} inputElement
 *   The DOM element for the hidden input element.
 */
function setupHiddenInputChangeListener(inputElement) {
  const propertyName = 'value';

  const {get: originalGetter, set: originalSetter} =
    findPropertyDescriptor(inputElement, propertyName);

  // We wrap this in a function factory to bind the getter and setter values
  // so later callbacks refer to the correct object, in case we use this
  // method on more than one hidden input element.
  const newPropertyDescriptor = ((_originalGetter, _originalSetter) => {
    return {
      set: function(value) {
        const currentValue = originalGetter.call(inputElement);

        // Delegate the call to the original property setter
        _originalSetter.call(inputElement, value);

        // Only fire change if the value actually changed.
        if (currentValue !== value) {
          inputElement.dispatchEvent(new Event('change'));
        }
      },

      get: function() {
        // Delegate the call to the original property getter
        return _originalGetter.call(inputElement);
      }
    }
  })(originalGetter, originalSetter);

  Object.defineProperty(inputElement, propertyName, newPropertyDescriptor);
};

/**
 * Search the inheritance tree of an object for a property descriptor.
 *
 * The property descriptor defined nearest in the inheritance hierarchy to
 * the class of the given object is returned first.
 *
 * Credit for this approach:
 * https://stackoverflow.com/a/38802602/4342230
 *
 * @param {Object} object
 * @param {String} propertyName
 *   The name of the property for which a descriptor is desired.
 *
 * @returns {PropertyDescriptor, null}
 */
function findPropertyDescriptor(object, propertyName) {
  if (object === null) {
    return null;
  }

  if (object.hasOwnProperty(propertyName)) {
    return Object.getOwnPropertyDescriptor(object, propertyName);
  }
  else {
    const parentClass = Object.getPrototypeOf(object);

    return findPropertyDescriptor(parentClass, propertyName);
  }
}

Call this on document ready like so:

$(document).ready(function() {
  setupHiddenInputChangeListener($('myinput')[0]);
});

ld cannot find an existing library

It is Debian convention to separate shared libraries into their runtime components (libmagic1: /usr/lib/libmagic.so.1 ? libmagic.so.1.0.0) and their development components (libmagic-dev: /usr/lib/libmagic.so ? …).

Because the library's soname is libmagic.so.1, that's the string that gets embedded into the executable so that's the file that is loaded when the executable is run.

However, because the library is specified as -lmagic to the linker, it looks for libmagic.so, which is why it is needed for development.

See Diego E. Pettenò: Linkers and names for details on how this all works on Linux.


In short, you should apt-get install libmagic-dev. This will not only give you libmagic.so but also other files necessary for compiling like /usr/include/magic.h.

Why use $_SERVER['PHP_SELF'] instead of ""

I know that the question is two years old, but it was the first result of what I am looking for. I found a good answers and I hope I can help other users.

Look at this

I will make this brief:

  • use the $_SERVER["PHP_SELF"] Variable with htmlspecialchars():

    `htmlspecialchars($_SERVER["PHP_SELF"]);`
    
  • PHP_SELF returns the filename of the currently executing script.

  • The htmlspecialchars() function converts special characters to HTML entities. --> NO XSS

AngularJs: How to check for changes in file input fields?

This is a refinement of some of the other ones around, the data will end up in an ng-model, which is normally what you want.

Markup (just make an attribute data-file so the directive can find it)

<input
    data-file
    id="id_image" name="image"
    ng-model="my_image_model" type="file">

JS

app.directive('file', function() {
    return {
        require:"ngModel",
        restrict: 'A',
        link: function($scope, el, attrs, ngModel){
            el.bind('change', function(event){
                var files = event.target.files;
                var file = files[0];

                ngModel.$setViewValue(file);
                $scope.$apply();
            });
        }
    };
});

How to use JQuery with ReactJS

Earlier,I was facing problem in using jquery with React js,so I did following steps to make it working-

  1. npm install jquery --save

  2. Then, import $ from "jquery";

    See here

Converting a char to uppercase

Since you know the chars are lower case, you can subtract the according ASCII value to make them uppercase:

char a = 'a';
a -= 32;
System.out.println("a is " + a); //a is A

Here is an ASCII table for reference

current/duration time of html5 video?

I am assuming you want to display this as part of the player.

This site breaks down how to get both the current and total time regardless of how you want to display it though using jQuery:

http://dev.opera.com/articles/view/custom-html5-video-player-with-css3-and-jquery/

This will also cover how to set it to a specific div. As philip has already mentioned, .currentTime will give you where you are in the video.

Is there a method for String conversion to Title Case?

This is something I wrote to convert snake_case to lowerCamelCase but could easily be adjusted based on the requirements

private String convertToLowerCamel(String startingText)
{
    String[] parts = startingText.split("_");
    return parts[0].toLowerCase() + Arrays.stream(parts)
                    .skip(1)
                    .map(part -> part.substring(0, 1).toUpperCase() + part.substring(1).toLowerCase())
                    .collect(Collectors.joining());
}

Handling null values in Freemarker

If you have a lot of variables to convert in optional, you can use SubimeText with this:

Find: \${([A-Za-z_0-9]*)}
Replace: \$\{${1}!\}

Be sure regex and case-sensitive options are enabled:

Sublime regex replace

CodeIgniter - return only one row?

You can do like this

$q  = $this->db->get()->row();

return $q->campaign_id;

Documentation : http://www.codeigniter.com/user_guide/database/results.html

Typescript - multidimensional array initialization

You only need [] to instantiate an array - this is true regardless of its type. The fact that the array is of an array type is immaterial.

The same thing applies at the first level in your loop. It is merely an array and [] is a new empty array - job done.

As for the second level, if Thing is a class then new Thing() will be just fine. Otherwise, depending on the type, you may need a factory function or other expression to create one.

class Something {
    private things: Thing[][];

    constructor() {
        this.things = [];

        for(var i: number = 0; i < 10; i++) {
            this.things[i] = [];
            for(var j: number = 0; j< 10; j++) {
                this.things[i][j] = new Thing();
            }
        }
    }
}

IF-THEN-ELSE statements in postgresql

case when field1>0 then field2/field1 else 0 end as field3

How to use Oracle's LISTAGG function with a unique filter?

create table demotable(group_id number, name varchar2(100));
insert into demotable values(1,'David');
insert into demotable values(1,'John');
insert into demotable values(1,'Alan');
insert into demotable values(1,'David');
insert into demotable values(2,'Julie');
insert into demotable values(2,'Charles');
commit;

select group_id, 
       (select listagg(column_value, ',') within group (order by column_value) from table(coll_names)) as names
from (
  select group_id, collect(distinct name) as coll_names 
    from demotable
    group by group_id 
)

GROUP_ID    NAMES
1   Alan,David,John
2   Charles,Julie

Editable 'Select' element

Nothing is impossible. Here's a solution that simply sets the value of a text input whenever the value of the <select> changes (rendering has been tested on Firefox and Google Chrome):

_x000D_
_x000D_
.select-editable {position:relative; background-color:white; border:solid grey 1px;  width:120px; height:18px;}_x000D_
.select-editable select {position:absolute; top:0px; left:0px; font-size:14px; border:none; width:120px; margin:0;}_x000D_
.select-editable input {position:absolute; top:0px; left:0px; width:100px; padding:1px; font-size:12px; border:none;}_x000D_
.select-editable select:focus, .select-editable input:focus {outline:none;}
_x000D_
<div class="select-editable">_x000D_
  <select onchange="this.nextElementSibling.value=this.value">_x000D_
    <option value=""></option>_x000D_
    <option value="115x175 mm">115x175 mm</option>_x000D_
    <option value="120x160 mm">120x160 mm</option>_x000D_
    <option value="120x287 mm">120x287 mm</option>_x000D_
  </select>_x000D_
  <input type="text" name="format" value=""/>_x000D_
</div>
_x000D_
_x000D_
_x000D_ jsfiddle: https://jsfiddle.net/nwH8A/

The next example adds the user input to the empty option slot of the <select> (thanks to @TomerPeled). It also has a little bit more flexible/variable CSS:

_x000D_
_x000D_
.select-editable {position:relative; width:120px;}_x000D_
.select-editable > * {position:absolute; top:0; left:0; box-sizing:border-box; outline:none;}_x000D_
.select-editable select {width:100%;}_x000D_
.select-editable input {width:calc(100% - 20px); margin:1px; border:none; text-overflow:ellipsis;}
_x000D_
<div class="select-editable">_x000D_
  <select onchange="this.nextElementSibling.value=this.value">_x000D_
    <option value=""></option>_x000D_
    <option value="115x175 mm">115x175 mm</option>_x000D_
    <option value="120x160 mm">120x160 mm</option>_x000D_
    <option value="120x287 mm">120x287 mm</option>_x000D_
  </select>_x000D_
  <input type="text" oninput="this.previousElementSibling.options[0].value=this.value; this.previousElementSibling.options[0].innerHTML=this.value" onchange="this.previousElementSibling.selectedIndex=0" value="" />_x000D_
</div>
_x000D_
_x000D_
_x000D_ jsfiddle: https://jsfiddle.net/pu7cndLv/1/


DataList

In HTML5 you can also do this with the <input> list attribute and <datalist> element:

_x000D_
_x000D_
<input list="browsers" name="browser">_x000D_
<datalist id="browsers">_x000D_
  <option value="Internet Explorer">_x000D_
  <option value="Firefox">_x000D_
  <option value="Chrome">_x000D_
  <option value="Opera">_x000D_
  <option value="Safari">_x000D_
</datalist>_x000D_
(click once to focus and edit, click again to see option dropdown)
_x000D_
_x000D_
_x000D_ jsfiddle: https://jsfiddle.net/hrkxebtw/

But this acts more like an auto-complete list; once you start typing, only the options that contain the typed string are left as suggestions. Depending on what you want to use it for, this may or may not be practical.

Spring CrudRepository findByInventoryIds(List<Long> inventoryIdList) - equivalent to IN clause

For any method in a Spring CrudRepository you should be able to specify the @Query yourself. Something like this should work:

@Query( "select o from MyObject o where inventoryId in :ids" )
List<MyObject> findByInventoryIds(@Param("ids") List<Long> inventoryIdList);

Will the IE9 WebBrowser Control Support all of IE9's features, including SVG?

I had the same problem, and the registry answers here didn't work.

I had a browser control in new version of my program that worked fine on XP, failed in Windows 7 (64 bit). The old version worked on both XP and Windows 7.

The webpage displayed in the browser uses some strange plugin for showing old SVG maps (I think its a Java applet).

Turns out the problem is related to DEP protection in Windows 7.

Old versions of dotnet 2 didn't set the DEP required flag in the exe, but from dotnet 2, SP 1 onwards it did (yep, the compiling behaviour and hence runtime behaviour of exe changed depending on which machine you compiled on, nice ...).

It is documented on a MSDN blog NXCOMPAT and the C# compiler. To quote : This will undoubtedly surprise a few developers...download a framework service pack, recompile, run your app, and you're now getting IP_ON_HEAP exceptions.

Adding the following to the post build in Visual Studio, turns DEP off for the exe, and everything works as expected:

all "$(DevEnvDir)..\tools\vsvars32.bat"
editbin.exe /NXCOMPAT:NO "$(TargetPath)"

Get event listeners attached to node using addEventListener

Since there is no native way to do this ,Here is less intrusive solution i found (dont add any 'old' prototype methods):

var ListenerTracker=new function(){
    var is_active=false;
    // listener tracking datas
    var _elements_  =[];
    var _listeners_ =[];
    this.init=function(){
        if(!is_active){//avoid duplicate call
            intercep_events_listeners();
        }
        is_active=true;
    };
    // register individual element an returns its corresponding listeners
    var register_element=function(element){
        if(_elements_.indexOf(element)==-1){
            // NB : split by useCapture to make listener easier to find when removing
            var elt_listeners=[{/*useCapture=false*/},{/*useCapture=true*/}];
            _elements_.push(element);
            _listeners_.push(elt_listeners);
        }
        return _listeners_[_elements_.indexOf(element)];
    };
    var intercep_events_listeners = function(){
        // backup overrided methods
        var _super_={
            "addEventListener"      : HTMLElement.prototype.addEventListener,
            "removeEventListener"   : HTMLElement.prototype.removeEventListener
        };

        Element.prototype["addEventListener"]=function(type, listener, useCapture){
            var listeners=register_element(this);
            // add event before to avoid registering if an error is thrown
            _super_["addEventListener"].apply(this,arguments);
            // adapt to 'elt_listeners' index
            useCapture=useCapture?1:0;

            if(!listeners[useCapture][type])listeners[useCapture][type]=[];
            listeners[useCapture][type].push(listener);
        };
        Element.prototype["removeEventListener"]=function(type, listener, useCapture){
            var listeners=register_element(this);
            // add event before to avoid registering if an error is thrown
            _super_["removeEventListener"].apply(this,arguments);
            // adapt to 'elt_listeners' index
            useCapture=useCapture?1:0;
            if(!listeners[useCapture][type])return;
            var lid = listeners[useCapture][type].indexOf(listener);
            if(lid>-1)listeners[useCapture][type].splice(lid,1);
        };
        Element.prototype["getEventListeners"]=function(type){
            var listeners=register_element(this);
            // convert to listener datas list
            var result=[];
            for(var useCapture=0,list;list=listeners[useCapture];useCapture++){
                if(typeof(type)=="string"){// filtered by type
                    if(list[type]){
                        for(var id in list[type]){
                            result.push({"type":type,"listener":list[type][id],"useCapture":!!useCapture});
                        }
                    }
                }else{// all
                    for(var _type in list){
                        for(var id in list[_type]){
                            result.push({"type":_type,"listener":list[_type][id],"useCapture":!!useCapture});
                        }
                    }
                }
            }
            return result;
        };
    };
}();
ListenerTracker.init();

Configuring RollingFileAppender in log4j

I had a similar problem and just found a way to solve it (by single-stepping through log4j-extras source, no less...)

The good news is that, unlike what's written everywhere, it turns out that you actually CAN configure TimeBasedRollingPolicy using log4j.properties (XML config not needed! At least in versions of log4j >1.2.16 see this bug report)

Here is an example:

log4j.appender.File = org.apache.log4j.rolling.RollingFileAppender
log4j.appender.File.rollingPolicy = org.apache.log4j.rolling.TimeBasedRollingPolicy
log4j.appender.File.rollingPolicy.FileNamePattern = logs/worker-${instanceId}.%d{yyyyMMdd-HHmm}.log

BTW the ${instanceId} bit is something I am using on Amazon's EC2 to distinguish the logs from all my workers -- I just need to set that property before calling PropertyConfigurator.configure(), as follow:

p.setProperty("instanceId", EC2Util.getMyInstanceId());
PropertyConfigurator.configure(p);

Compare two dates with JavaScript

The easiest way to compare dates in javascript is to first convert it to a Date object and then compare these date-objects.

Below you find an object with three functions:

  • dates.compare(a,b)

    Returns a number:

    • -1 if a < b
    • 0 if a = b
    • 1 if a > b
    • NaN if a or b is an illegal date
  • dates.inRange (d,start,end)

    Returns a boolean or NaN:

    • true if d is between the start and end (inclusive)
    • false if d is before start or after end.
    • NaN if one or more of the dates are illegal.
  • dates.convert

    Used by the other functions to convert their input to a date object. The input can be

    • a date-object : The input is returned as is.
    • an array: Interpreted as [year,month,day]. NOTE month is 0-11.
    • a number : Interpreted as number of milliseconds since 1 Jan 1970 (a timestamp)
    • a string : Several different formats is supported, like "YYYY/MM/DD", "MM/DD/YYYY", "Jan 31 2009" etc.
    • an object: Interpreted as an object with year, month and date attributes. NOTE month is 0-11.

.

// Source: http://stackoverflow.com/questions/497790
var dates = {
    convert:function(d) {
        // Converts the date in d to a date-object. The input can be:
        //   a date object: returned without modification
        //  an array      : Interpreted as [year,month,day]. NOTE: month is 0-11.
        //   a number     : Interpreted as number of milliseconds
        //                  since 1 Jan 1970 (a timestamp) 
        //   a string     : Any format supported by the javascript engine, like
        //                  "YYYY/MM/DD", "MM/DD/YYYY", "Jan 31 2009" etc.
        //  an object     : Interpreted as an object with year, month and date
        //                  attributes.  **NOTE** month is 0-11.
        return (
            d.constructor === Date ? d :
            d.constructor === Array ? new Date(d[0],d[1],d[2]) :
            d.constructor === Number ? new Date(d) :
            d.constructor === String ? new Date(d) :
            typeof d === "object" ? new Date(d.year,d.month,d.date) :
            NaN
        );
    },
    compare:function(a,b) {
        // Compare two dates (could be of any type supported by the convert
        // function above) and returns:
        //  -1 : if a < b
        //   0 : if a = b
        //   1 : if a > b
        // NaN : if a or b is an illegal date
        // NOTE: The code inside isFinite does an assignment (=).
        return (
            isFinite(a=this.convert(a).valueOf()) &&
            isFinite(b=this.convert(b).valueOf()) ?
            (a>b)-(a<b) :
            NaN
        );
    },
    inRange:function(d,start,end) {
        // Checks if date in d is between dates in start and end.
        // Returns a boolean or NaN:
        //    true  : if d is between start and end (inclusive)
        //    false : if d is before start or after end
        //    NaN   : if one or more of the dates is illegal.
        // NOTE: The code inside isFinite does an assignment (=).
       return (
            isFinite(d=this.convert(d).valueOf()) &&
            isFinite(start=this.convert(start).valueOf()) &&
            isFinite(end=this.convert(end).valueOf()) ?
            start <= d && d <= end :
            NaN
        );
    }
}

How to move a git repository into another directory and make that directory a git repository?

To do this without any headache:

  1. Check out what's the current branch in the gitrepo1 with git status, let's say branch "development".
  2. Change directory to the newrepo, then git clone the project from repository.
  3. Switch branch in newrepo to the previous one: git checkout development.
  4. Syncronize newrepo with the older one, gitrepo1 using rsync, excluding .git folder: rsync -azv --exclude '.git' gitrepo1 newrepo/gitrepo1. You don't have to do this with rsync of course, but it does it so smooth.

The benefit of this approach: you are good to continue exactly where you left off: your older branch, unstaged changes, etc.

Node.js ES6 classes with require

Just treat the ES6 class name the same as you would have treated the constructor name in the ES5 way. They are one and the same.

The ES6 syntax is just syntactic sugar and creates exactly the same underlying prototype, constructor function and objects.

So, in your ES6 example with:

// animal.js
class Animal {
    ...
}

var a = new Animal();

module.exports = {Animal: Animal};

You can just treat Animal like the constructor of your object (the same as you would have done in ES5). You can export the constructor. You can call the constructor with new Animal(). Everything is the same for using it. Only the declaration syntax is different. There's even still an Animal.prototype that has all your methods on it. The ES6 way really does create the same coding result, just with fancier/nicer syntax.


On the import side, this would then be used like this:

const Animal = require('./animal.js').Animal;

let a = new Animal();

This scheme exports the Animal constructor as the .Animal property which allows you to export more than one thing from that module.

If you don't need to export more than one thing, you can do this:

// animal.js
class Animal {
    ...
}

module.exports = Animal;

And, then import it with:

const Animal = require('./animal.js');

let a = new Animal();

How does database indexing work?

Just a quick suggestion.. As indexing costs you additional writes and storage space, so if your application requires more insert/update operation, you might want to use tables without indexes, but if it requires more data retrieval operations, you should go for indexed table.

Checking Date format from a string in C#

Try this

DateTime dDate;
dDate = DateTime.TryParse(inputString);
String.Format("{0:d/MM/yyyy}", dDate); 

see this link for more info. http://msdn.microsoft.com/en-us/library/ch92fbc1.aspx

What does AND 0xFF do?

& 0xFF by itself only ensures that if bytes are longer than 8 bits (allowed by the language standard), the rest are ignored.

And that seems to work fine too?

If the result ends up greater than SHRT_MAX, you get undefined behavior. In that respect both will work equally poorly.

Pass a data.frame column name to a function

Personally I think that passing the column as a string is pretty ugly. I like to do something like:

get.max <- function(column,data=NULL){
    column<-eval(substitute(column),data, parent.frame())
    max(column)
}

which will yield:

> get.max(mpg,mtcars)
[1] 33.9
> get.max(c(1,2,3,4,5))
[1] 5

Notice how the specification of a data.frame is optional. you can even work with functions of your columns:

> get.max(1/mpg,mtcars)
[1] 0.09615385

Get UTC time and local time from NSDate object

My Xcode Version 6.1.1 (6A2008a)

In playground, test like this:

// I'm in East Timezone 8
let x = NSDate() //Output:"Dec 29, 2014, 11:37 AM"
let y = NSDate.init() //Output:"Dec 29, 2014, 11:37 AM"
println(x) //Output:"2014-12-29 03:37:24 +0000"


// seconds since 2001
x.hash //Output:441,517,044
x.hashValue //Output:441,517,044
x.timeIntervalSinceReferenceDate //Output:441,517,044.875367

// seconds since 1970
x.timeIntervalSince1970 //Output:1,419,824,244.87537

How to get response using cURL in PHP

am using this simple one

´´´´ class Connect {

public $url;
public $path;
public $username;
public $password;

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $this->url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    curl_setopt($ch, CURLOPT_USERPWD, "$this->username:$this->password");

    //PROPFIND request that lists all requested properties.
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PROPFIND");
    $response = curl_exec($ch);

    curl_close($ch);

How to convert POJO to JSON and vice versa?

You can use jackson api for the conversion

<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>2.9.4</version>
</dependency>

add above maven dependency in your POM, In your main method create ObjectMapper

ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);

later we nee to add our POJO class to the mapper

String json = mapper.writeValueAsString(pojo);

jQuery scrollTop() doesn't seem to work in Safari or Chrome (Windows)

Yeah, there appears to be a bug in Chrome when it comes to modifying the body, trying to make it into an offsetParent. As a work-around, I suggest you simply add another div to wrap the #content div, and make that scroll:

html, body { height: 100%; padding: 0; } 
html { width: 100%; background-color: #222; overflow: hidden; margin: 0; } 
body 
{ 
   width: 40em; margin: 0px auto; /* narrow center column layout */
   background-color: white; 
   position: relative; /* allow positioning children relative to this element */
} 
#scrollContainer /* wraps #content, scrolls */
{ 
  overflow: auto; /* scroll! */
  position:absolute; /* make offsetParent */
  top: 0; height: 100%; width: 100%; /* fill parent */
} 
#header 
{ 
  position: absolute; 
  top: 0px; height: 50px; width: 38.5em; 
  background-color: white; 
  z-index: 1; /* sit above #content in final layout */
} 
#content { padding: 5px 14px 50px 5px;  } 

Tested in FF 3.5.5, Chrome 3.0.195.33, IE8

Live demonstration:

_x000D_
_x000D_
$(function() {_x000D_
        $('#header').find('button').click(function(ev) {_x000D_
          var button = $(this), target = $('div.' + button.attr('class'));_x000D_
          var scroll = target.offsetParent().scrollTop(); _x000D_
          target.offsetParent().scrollTop(target.offset().top + scroll - 50);_x000D_
        });_x000D_
      });
_x000D_
html, body { height: 100%; padding: 0; }_x000D_
      html { width: 100%; background-color: #222; overflow: hidden; margin: 0; }_x000D_
      body { width: 40em; margin: 0px auto; background-color: white; position: relative; }_x000D_
      #scrollContainer { overflow: auto; position:absolute; top: 0; height: 100%; width: 100%; }_x000D_
      #header { position: absolute; top: 0px; height: 50px; width: 38.5em; background-color: white; z-index: 1; }_x000D_
      #content { padding: 5px 14px 50px 5px;  }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
    <div id='header'> _x000D_
      Header Box_x000D_
      <button class='A'>A</button> _x000D_
      <button class='B'>B</button> _x000D_
      <button class='C'>C</button> _x000D_
    </div> _x000D_
    <div id='scrollContainer'>_x000D_
    <div id='content'> _x000D_
      <div style='height: 50px'> </div> _x000D_
      <div class='A'> _x000D_
        <h1>A</h1> _x000D_
        <p>My name is Boffer Bings. I was born of honest parents in one of the humbler walks of life, my father being a manufacturer of dog-oil and my mother having a small studio in the shadow of the village church, where she disposed of unwelcome babes. In my boyhood I was trained to habits of industry; I not only assisted my father in procuring dogs for his vats, but was frequently employed by my mother to carry away the debris of her work in the studio. In performance of this duty I sometimes had need of all my natural intelligence for all the law officers of the vicinity were opposed to my mother's business. They were not elected on an opposition ticket, and the matter had never been made a political issue; it just happened so. My father's business of making dog-oil was, naturally, less unpopular, though the owners of missing dogs sometimes regarded him with suspicion, which was reflected, to some extent, upon me. My father had, as silent partners, all the physicians of the town, who seldom wrote a prescription which did not contain what they were pleased to designate as _Ol. can._ It is really the most valuable medicine ever discovered. But most persons are unwilling to make personal sacrifices for the afflicted, and it was evident that many of the fattest dogs in town had been forbidden to play with me--a fact which pained my young sensibilities, and at one time came near driving me to become a pirate._x000D_
      </div> _x000D_
      <div class='B'> _x000D_
        <h1>B</h1> _x000D_
        <p> _x000D_
        Looking back upon those days, I cannot but regret, at times, that by indirectly bringing my beloved parents to their death I was the author of misfortunes profoundly affecting my future._x000D_
        <p> _x000D_
        One evening while passing my father's oil factory with the body of a foundling from my mother's studio I saw a constable who seemed to be closely watching my movements. Young as I was, I had learned that a constable's acts, of whatever apparent character, are prompted by the most reprehensible motives, and I avoided him by dodging into the oilery by a side door which happened to stand ajar. I locked it at once and was alone with my dead. My father had retired for the night. The only light in the place came from the furnace, which glowed a deep, rich crimson under one of the vats, casting ruddy reflections on the walls. Within the cauldron the oil still rolled in indolent ebullition, occasionally pushing to the surface a piece of dog. Seating myself to wait for the constable to go away, I held the naked body of the foundling in my lap and tenderly stroked its short, silken hair. Ah, how beautiful it was! Even at that early age I was passionately fond of children, and as I looked upon this cherub I could almost find it in my heart to wish that the small, red wound upon its breast--the work of my dear mother--had not been mortal._x000D_
      </div> _x000D_
      <div class='C'> _x000D_
        <h1>C</h1> _x000D_
        <p>It had been my custom to throw the babes into the river which nature had thoughtfully provided for the purpose, but that night I did not dare to leave the oilery for fear of the constable. "After all," I said to myself, "it cannot greatly matter if I put it into this cauldron. My father will never know the bones from those of a puppy, and the few deaths which may result from administering another kind of oil for the incomparable _ol. can._ are not important in a population which increases so rapidly." In short, I took the first step in crime and brought myself untold sorrow by casting the babe into the cauldron._x000D_
      </div> _x000D_
      <div style='height: 75em;'> </div> _x000D_
    </div> _x000D_
    </div>
_x000D_
_x000D_
_x000D_

Paste text on Android Emulator

I came here looking for a solution to the same problem, and ended up writing an Android application to solve this problem. You can download it at http://www.box.net/shared/6203bn441bfltkimajmk. Just give a URL via Preferences menu to point to a place where you can change the Web response easily. The first line of the Web response will be copied to your emulator's clipboard for you. More details can be found at http://agilesc.barryku.com/?p=255.

Connecting to remote URL which requires authentication using Java

You can also use the following, which does not require using external packages:

URL url = new URL(“location address”);
URLConnection uc = url.openConnection();

String userpass = username + ":" + password;
String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userpass.getBytes());

uc.setRequestProperty ("Authorization", basicAuth);
InputStream in = uc.getInputStream();

Adding POST parameters before submit

PURE JavaScript:

Creating the XMLHttpRequest:

function getHTTPObject() {
    /* Crea el objeto AJAX. Esta funcion es generica para cualquier utilidad de este tipo, 
       por lo que se puede copiar tal como esta aqui */
    var xmlhttp = false;
    /* No mas soporte para Internet Explorer
    try { // Creacion del objeto AJAX para navegadores no IE
        xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch(nIE) {
        try { // Creacion del objet AJAX para IE
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        } catch(IE) {
            if (!xmlhttp && typeof XMLHttpRequest!='undefined') 
                xmlhttp = new XMLHttpRequest();
        }
    }
    */
    xmlhttp = new XMLHttpRequest();
    return xmlhttp; 
}

JavaScript function to Send the info via POST:

function sendInfo() {
    var URL = "somepage.html"; //depends on you
    var Params = encodeURI("var1="+val1+"var2="+val2+"var3="+val3);
    console.log(Params);
    var ajax = getHTTPObject();     
    ajax.open("POST", URL, true); //True:Sync - False:ASync
    ajax.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    ajax.setRequestHeader("Content-length", Params.length);
    ajax.setRequestHeader("Connection", "close");
    ajax.onreadystatechange = function() { 
        if (ajax.readyState == 4 && ajax.status == 200) {
            alert(ajax.responseText);
        } 
    }
    ajax.send(Params);
}

Difference between no-cache and must-revalidate

With Jeffrey Fox's interpretation about no-cache, i've tested under chrome 52.0.2743.116 m, the result shows that no-cache has the same behavior as must-revalidate, they all will NOT use local cache when server is unreachable, and, they all will use cache while tap browser's Back/Forward button when server is unreachable. As above, i think max-age=0, must-revalidate is identical to no-cache, at least in implementation.

Angular 2 declaring an array of objects

Datatype: array_name:datatype[]=[]; Example string: users:string[]=[];

For array of objects:

Objecttype: object_name:objecttype[]=[{}]; Example user: Users:user[]=[{}];

And if in some cases it's coming undefined in binding, make sure to initialize it on Oninit().

How do I calculate the percentage of a number?

$percentage = 50;
$totalWidth = 350;

$new_width = ($percentage / 100) * $totalWidth;

Transfer git repositories from GitLab to GitHub - can we, how to and pitfalls (if any)?

With default Github repository import it is possible, but just make sure the two factor authentication is not enabled in Gitlab.

Thanks

Converting <br /> into a new line for use in a text area

Here is another approach.

class orbisius_custom_string {
    /**
     * The reverse of nl2br. Handles <br/> <br/> <br />
     * usage: orbisius_custom_string::br2nl('Your buffer goes here ...');
     * @param str $buff
     * @return str
     * @author Slavi Marinov | http://orbisius.com
     */
    public static function br2nl($buff = '') {
        $buff = preg_replace('#<br[/\s]*>#si', "\n", $buff);
        $buff = trim($buff);

        return $buff;
    }
}

Can JavaScript connect with MySQL?

No.

You need to write a wrapper in PHP, and then export the returned data (probably as Json). NEVER, get from your "_GET" the SQL code, as this is called an SQL injection (people who learn this will have full control over your database).

This is an example I wrote:

function getJsonData()
{
        global $db;
        if (!$db->isConnected()) {
               return "Not connected";
        }
        $db->query("SELECT * FROM entries");
        $values = array();
        while( $v = $db->fetchAssoc()){
                $values[] = $v;
        }
        return json_encode($values);    
}

switch (@$_GET["cmd"]){
        case 'data':
                print getJsonData();
                exit;

        default:
                print getMainScreen();
                exit; 
}

Do learn about SQL injections please.

Static Block in Java

It is a static initializer. It's executed when the class is loaded and a good place to put initialization of static variables.

From http://java.sun.com/docs/books/tutorial/java/javaOO/initial.html

A class can have any number of static initialization blocks, and they can appear anywhere in the class body. The runtime system guarantees that static initialization blocks are called in the order that they appear in the source code.

If you have a class with a static look-up map it could look like this

class MyClass {
    static Map<Double, String> labels;
    static {
        labels = new HashMap<Double, String>();
        labels.put(5.5, "five and a half");
        labels.put(7.1, "seven point 1");
    }
    //...
}

It's useful since the above static field could not have been initialized using labels = .... It needs to call the put-method somehow.

Create directory if it does not exist

From your situation it sounds like you need to create a "Revision#" folder once a day with a "Reports" folder in there. If that's the case, you just need to know what the next revision number is. Write a function that gets the next revision number, Get-NextRevisionNumber. Or you could do something like this:

foreach($Project in (Get-ChildItem "D:\TopDirec" -Directory)){
    # Select all the Revision folders from the project folder.
    $Revisions = Get-ChildItem "$($Project.Fullname)\Revision*" -Directory

    # The next revision number is just going to be one more than the highest number.
    # You need to cast the string in the first pipeline to an int so Sort-Object works.
    # If you sort it descending the first number will be the biggest so you select that one.
    # Once you have the highest revision number you just add one to it.
    $NextRevision = ($Revisions.Name | Foreach-Object {[int]$_.Replace('Revision','')} | Sort-Object -Descending | Select-Object -First 1)+1

    # Now in this we kill two birds with one stone.
    # It will create the "Reports" folder but it also creates "Revision#" folder too.
    New-Item -Path "$($Project.Fullname)\Revision$NextRevision\Reports" -Type Directory

    # Move on to the next project folder.
    # This untested example loop requires PowerShell version 3.0.
}

PowerShell 3.0 installation.

error LNK2005: xxx already defined in MSVCRT.lib(MSVCR100.dll) C:\something\LIBCMT.lib(setlocal.obj)

You are mixing code that was compiled with /MD (use DLL version of CRT) with code that was compiled with /MT (use static CRT library). That cannot work, all source code files must be compiled with the same setting. Given that you use libraries that were pre-compiled with /MD, almost always the correct setting, you must compile your own code with this setting as well.

Project + Properties, C/C++, Code Generation, Runtime Library.

Beware that these libraries were probably compiled with an earlier version of the CRT, msvcr100.dll is quite new. Not sure if that will cause trouble, you may have to prevent the linker from generating a manifest. You must also make sure to deploy the DLLs you need to the target machine, including msvcr100.dll

Check if a Bash array contains a value

Combining a few of the ideas presented here you can make an elegant if statment without loops that does exact word matches.

find="myword"
array=(value1 value2 myword)
if [[ ! -z $(printf '%s\n' "${array[@]}" | grep -w $find) ]]; then
  echo "Array contains myword";
fi

This will not trigger on word or val, only whole word matches. It will break if each array value contains multiple words.

Converting from byte to int in java

byte b = (byte)0xC8;
int v1 = b;       // v1 is -56 (0xFFFFFFC8)
int v2 = b & 0xFF // v2 is 200 (0x000000C8)

Most of the time v2 is the way you really need.

htaccess "order" Deny, Allow, Deny

Change your code to

<Limit GET POST>
deny from all

allow from 139.82.0.0/16
allow from 143.54.0.0/16
allow from 186.192.0.0/11
allow from 186.224.0.0/11
</Limit>

This way your htaccess will deny every except those that you explicitly allow with allow from..

A proxy within the allow range can easily be overwritten with an additional deny from.. rule.

Does Spring @Transactional attribute work on a private method?

The Question is not private or public, the question is: How is it invoked and which AOP implementation you use!

If you use (default) Spring Proxy AOP, then all AOP functionality provided by Spring (like @Transactional) will only be taken into account if the call goes through the proxy. -- This is normally the case if the annotated method is invoked from another bean.

This has two implications:

  • Because private methods must not be invoked from another bean (the exception is reflection), their @Transactional Annotation is not taken into account.
  • If the method is public, but it is invoked from the same bean, it will not be taken into account either (this statement is only correct if (default) Spring Proxy AOP is used).

@See Spring Reference: Chapter 9.6 9.6 Proxying mechanisms

IMHO you should use the aspectJ mode, instead of the Spring Proxies, that will overcome the problem. And the AspectJ Transactional Aspects are woven even into private methods (checked for Spring 3.0).

An internal error occurred during: "Updating Maven Project". java.lang.NullPointerException

I've had the same problem in one of my modules.

Running "mvn eclipse:eclipse" in the console/cmd solved the problem for me.

Multiple linear regression in Python

sklearn.linear_model.LinearRegression will do it:

from sklearn import linear_model
clf = linear_model.LinearRegression()
clf.fit([[getattr(t, 'x%d' % i) for i in range(1, 8)] for t in texts],
        [t.y for t in texts])

Then clf.coef_ will have the regression coefficients.

sklearn.linear_model also has similar interfaces to do various kinds of regularizations on the regression.

How to access single elements in a table in R

?"[" pretty much covers the various ways of accessing elements of things.

Under usage it lists these:

x[i]
x[i, j, ... , drop = TRUE]
x[[i, exact = TRUE]]
x[[i, j, ..., exact = TRUE]]
x$name
getElement(object, name)

x[i] <- value
x[i, j, ...] <- value
x[[i]] <- value
x$i <- value

The second item is sufficient for your purpose

Under Arguments it points out that with [ the arguments i and j can be numeric, character or logical

So these work:

data[1,1]
data[1,"V1"]

As does this:

data$V1[1]

and keeping in mind a data frame is a list of vectors:

data[[1]][1]
data[["V1"]][1]

will also both work.

So that's a few things to be going on with. I suggest you type in the examples at the bottom of the help page one line at a time (yes, actually type the whole thing in one line at a time and see what they all do, you'll pick up stuff very quickly and the typing rather than copypasting is an important part of helping to commit it to memory.)

When should I use nil and NULL in Objective-C?

Beware that if([NSNull null]) returns true.

Pass a datetime from javascript to c# (Controller)

Try to use toISOString(). It returns string in ISO8601 format.

GET method

javascript

$.get('/example/doGet?date=' + new Date().toISOString(), function (result) {
    console.log(result);
});

c#

[HttpGet]
public JsonResult DoGet(DateTime date)
{
    return Json(date.ToString(), JsonRequestBehavior.AllowGet);
}

POST method

javascript

$.post('/example/do', { date: date.toISOString() }, function (result) {
    console.log(result);
});

c#

[HttpPost]
public JsonResult Do(DateTime date)
{
     return Json(date.ToString());
}

codes for ADD,EDIT,DELETE,SEARCH in vb2010

Have you googled about it - insert update delete access vb.net, there are lots of reference about this.

Insert Update Delete Navigation & Searching In Access Database Using VB.NET

  • Create Visual Basic 2010 Project: VB-Access
  • Assume that, we have a database file named data.mdb
  • Place the data.mdb file into ..\bin\Debug\ folder (Where the project executable file (.exe) is placed)

what could be the easier way to connect and manipulate the DB?
Use OleDBConnection class to make connection with DB

is it by using MS ACCESS 2003 or MS ACCESS 2007?
you can use any you want to use or your client will use on their machine.

it seems that you want to find some example of opereations fo the database. Here is an example of Access 2010 for your reference:

Example code snippet:

Imports System
Imports System.Data
Imports System.Data.OleDb

Public Class DBUtil

 Private connectionString As String

 Public Sub New()

  Dim con As New OleDb.OleDbConnection
  Dim dbProvider As String = "Provider=Microsoft.ace.oledb.12.0;"
  Dim dbSource = "Data Source=d:\DB\Database11.accdb"

  connectionString = dbProvider & dbSource

 End Sub

 Public Function GetCategories() As DataSet

  Dim query As String = "SELECT * FROM Categories"
  Dim cmd As New OleDbCommand(query)
  Return FillDataSet(cmd, "Categories")

 End Function

 Public SubUpdateCategories(ByVal name As String)
  Dim query As String = "update Categories set name = 'new2' where name = ?"
  Dim cmd As New OleDbCommand(query)
cmd.Parameters.AddWithValue("Name", name)
  Return FillDataSet(cmd, "Categories")

 End Sub

 Public Function GetItems() As DataSet

  Dim query As String = "SELECT * FROM Items"
  Dim cmd As New OleDbCommand(query)
  Return FillDataSet(cmd, "Items")

 End Function

 Public Function GetItems(ByVal categoryID As Integer) As DataSet

  'Create the command.
  Dim query As String = "SELECT * FROM Items WHERE Category_ID=?"
  Dim cmd As New OleDbCommand(query)
  cmd.Parameters.AddWithValue("category_ID", categoryID)

  'Fill the dataset.
  Return FillDataSet(cmd, "Items")

 End Function

 Public Sub AddCategory(ByVal name As String)

  Dim con As New OleDbConnection(connectionString)

  'Create the command.
  Dim insertSQL As String = "INSERT INTO Categories "
  insertSQL &= "VALUES(?)"
  Dim cmd As New OleDbCommand(insertSQL, con)
  cmd.Parameters.AddWithValue("Name", name)

  Try
   con.Open()
   cmd.ExecuteNonQuery()
  Finally
   con.Close()
  End Try

 End Sub

 Public Sub AddItem(ByVal title As String, ByVal description As String, _
    ByVal price As Decimal, ByVal categoryID As Integer)

  Dim con As New OleDbConnection(connectionString)

  'Create the command.
  Dim insertSQL As String = "INSERT INTO Items "
  insertSQL &= "(Title, Description, Price, Category_ID)"
  insertSQL &= "VALUES (?, ?, ?, ?)"
  Dim cmd As New OleDb.OleDbCommand(insertSQL, con)
  cmd.Parameters.AddWithValue("Title", title)
  cmd.Parameters.AddWithValue("Description", description)
  cmd.Parameters.AddWithValue("Price", price)
  cmd.Parameters.AddWithValue("CategoryID", categoryID)

  Try
   con.Open()
   cmd.ExecuteNonQuery()
  Finally
   con.Close()
  End Try

 End Sub

 Private Function FillDataSet(ByVal cmd As OleDbCommand, ByVal tableName As String) As DataSet

  Dim con As New OleDb.OleDbConnection
  Dim dbProvider As String = "Provider=Microsoft.ace.oledb.12.0;"
  Dim dbSource = "Data Source=D:\DB\Database11.accdb"

  connectionString = dbProvider & dbSource
  con.ConnectionString = connectionString
  cmd.Connection = con
  Dim adapter As New OleDbDataAdapter(cmd)
  Dim ds As New DataSet()

  Try
   con.Open()
   adapter.Fill(ds, tableName)
  Finally
   con.Close()
  End Try
  Return ds

 End Function

End Class

Refer these links:
Insert, Update, Delete & Search Values in MS Access 2003 with VB.NET 2005
INSERT, DELETE, UPDATE AND SELECT Data in MS-Access with VB 2008
How Add new record ,Update record,Delete Records using Vb.net Forms when Access as a back

Numpy matrix to array

A, = np.array(M.T)

depends what you mean by elegance i suppose but thats what i would do

Request UAC elevation from within a Python script?

It seems there's no way to elevate the application privileges for a while for you to perform a particular task. Windows needs to know at the start of the program whether the application requires certain privileges, and will ask the user to confirm when the application performs any tasks that need those privileges. There are two ways to do this:

  1. Write a manifest file that tells Windows the application might require some privileges
  2. Run the application with elevated privileges from inside another program

This two articles explain in much more detail how this works.

What I'd do, if you don't want to write a nasty ctypes wrapper for the CreateElevatedProcess API, is use the ShellExecuteEx trick explained in the Code Project article (Pywin32 comes with a wrapper for ShellExecute). How? Something like this:

When your program starts, it checks if it has Administrator privileges, if it doesn't it runs itself using the ShellExecute trick and exits immediately, if it does, it performs the task at hand.

As you describe your program as a "script", I suppose that's enough for your needs.

Cheers.

Positioning <div> element at center of screen

Set the width and height and you're good.

div {
  position: absolute;
  margin: auto;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  width: 200px;
  height: 200px;
}

If you want the element dimensions to be flexible (and don't care about legacy browsers), go with XwipeoutX's answer.

Which data structures and algorithms book should I buy?

I think introduction to Algorithms is the reference books, and a must have for any serious programmer.

http://en.wikipedia.org/wiki/Introduction_to_Algorithms

Other fun book is The algorithm design manual http://www.algorist.com/. It covers more sophisticated algorithms.

I can't not mention The art of computer programming of Knuth http://www-cs-faculty.stanford.edu/~knuth/taocp.html

How to write an async method with out parameter?

You can do this by using TPL (task parallel library) instead of direct using await keyword.

private bool CheckInCategory(int? id, out Category category)
    {
        if (id == null || id == 0)
            category = null;
        else
            category = Task.Run(async () => await _context.Categories.FindAsync(id ?? 0)).Result;

        return category != null;
    }

if(!CheckInCategory(int? id, out var category)) return error

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'
>>> 

How to swap two variables in JavaScript

ES6 array destructuring is used to swap two variables. See example

var [x,y]=[1,2];
[x,y]=[y,x];

Easier way possible with :

x === 1 and y === 2; But after destructuring, x is y, i.e. 2, and y is x, i.e. 1.

Python module os.chmod(file, 664) does not change the permission to rw-rw-r-- but -w--wx----

So for people who want semantics similar to:

$ chmod 755 somefile

Use:

$ python -c "import os; os.chmod('somefile', 0o755)"

If your Python is older than 2.6:

$ python -c "import os; os.chmod('somefile', 0755)"

ActiveX component can't create object

I know this is an old thread, but has anyone checked if their Antivirus is blocking Win32API and Scripting on their systems? I have CylanceProtect installed on my office system and i found the same issues occurring as listed by others. This can be confirmed if you check the Windows Logs in Event Viewer.

How to check for an active Internet connection on iOS or macOS?

Alamofire

I know the question is asking for Coca Touch solution, but I want to provide a solution for people who searched check internet connection on iOS and will have one more option here.

If you are already using Alamofire, here is what you can benifit from that.

You can add following class to your app, and call MNNetworkUtils.main.isConnected() to get a boolean on whether its connected or not.

#import Alamofire

class MNNetworkUtils {
  static let main = MNNetworkUtils()
  init() {
    manager = NetworkReachabilityManager(host: "google.com")
    listenForReachability()
  }

  private let manager: NetworkReachabilityManager?
  private var reachable: Bool = false
  private func listenForReachability() {
    self.manager?.listener = { [unowned self] status in
      switch status {
      case .notReachable:
        self.reachable = false
      case .reachable(_), .unknown:
        self.reachable = true
      }
    }
    self.manager?.startListening()
  }

  func isConnected() -> Bool {
    return reachable
  }
}

This is a singleton class. Every time, when user connect or disconnect the network, it will override self.reachable to true/false correctly, because we start listening for the NetworkReachabilityManager on singleton initialization.

Also in order to monitor reachability, you need to provide a host, currently I am using google.com feel free to change to any other hosts or one of yours if needed. Change the class name and file name to anything matching your project.

ArrayBuffer to base64 encoded string

function _arrayBufferToBase64( buffer ) {
    var binary = '';
    var bytes = new Uint8Array( buffer );
    var len = bytes.byteLength;
    for (var i = 0; i < len; i++) {
        binary += String.fromCharCode( bytes[ i ] );
    }
    return window.btoa( binary );
}

but, non-native implementations are faster e.g. https://gist.github.com/958841 see http://jsperf.com/encoding-xhr-image-data/6

An invalid form control with name='' is not focusable

Adding a novalidate attribute to the form will help:

<form name="myform" novalidate>

How to properly import a selfsigned certificate into Java keystore that is available to all Java applications by default?

If you are using a certificate signed by a Certificate Authority that is not included in the Java cacerts file by default, you need to complete the following configuration for HTTPS connections. To import certificates into cacerts:

  1. Open Windows Explorer and navigate to the cacerts file, which is located in the jre\lib\security subfolder where AX Core Client is installed. The default location is C:\Program Files\ACL Software\AX Core Client\jre\lib\security
  2. Create a backup copy of the file before making any changes.
  3. Depending on the certificates you receive from the Certificate Authority you are using, you may need to import an intermediate certificate and/or root certificate into the cacerts file. Use the following syntax to import certificates: keytool -import -alias -keystore -trustcacerts -file
  4. If you are importing both certificates the alias specified for each certificate should be unique.
  5. Type the password for the keystore at the “Password” prompt and press Enter. The default Java password for the cacerts file is “changeit”. Type ‘y’ at the “Trust this certificate?” prompt and press Enter.

The ALTER TABLE statement conflicted with the FOREIGN KEY constraint

Please first delete data from that table and then run the migration again. You will get success

php mysqli_connect: authentication method unknown to the client [caching_sha2_password]

If you're on a Mac, here's how to fix it. This is after tons of trial and error. Hope this helps others..

Debugging:

$mysql --verbose --help | grep my.cnf

$ which mysql
/usr/local/bin/mysql

Resolution: nano /usr/local/etc/my.cnf

Add: default-authentication-plugin=mysql_native_password

-------
# Default Homebrew MySQL server config
[mysqld]
# Only allow connections from localhost
bind-address = 127.0.0.1
default-authentication-plugin=mysql_native_password
------

Finally Run: brew services restart mysql

Where do I find the definition of size_t?

I'm not familiar with void_t except as a result of a Google search (it's used in a vmalloc library by Kiem-Phong Vo at AT&T Research - I'm sure it's used in other libraries as well).

The various xxx_t typedefs are used to abstract a type from a particular definite implementation, since the concrete types used for certain things might differ from one platform to another. For example:

  • size_t abstracts the type used to hold the size of objects because on some systems this will be a 32-bit value, on others it might be 16-bit or 64-bit.
  • Void_t abstracts the type of pointer returned by the vmalloc library routines because it was written to work on systems that pre-date ANSI/ISO C where the void keyword might not exist. At least that's what I'd guess.
  • wchar_t abstracts the type used for wide characters since on some systems it will be a 16 bit type, on others it will be a 32 bit type.

So if you write your wide character handling code to use the wchar_t type instead of, say unsigned short, that code will presumably be more portable to various platforms.

How to take a first character from the string

Try this:

Dim s = "RAJAN"
Dim firstChar = s(0)

You can even do this:

Dim firstChar = "RAJAN"(0)

How to change working directory in Jupyter Notebook?

You may use jupyter magic command as below

%cd "C:\abc\xyz\"

MySQL Foreign Key Error 1005 errno 150 primary key as foreign key

I realize this is an old post, but it ranks high in Google, so I'm adding what I figured out for MY problem. If you have a mix of table types (e.g. MyISAM and InnoDB), you will get this error as well. In this case, InnoDB is the default table type, but one table needed fulltext searching so it was migrated to MyISAM. In this situation, you cannot create a foreign key in the InnoDB table that references the MyISAM table.

How do I reset the setInterval timer?

If by "restart", you mean to start a new 4 second interval at this moment, then you must stop and restart the timer.

function myFn() {console.log('idle');}

var myTimer = setInterval(myFn, 4000);

// Then, later at some future time, 
// to restart a new 4 second interval starting at this exact moment in time
clearInterval(myTimer);
myTimer = setInterval(myFn, 4000);

You could also use a little timer object that offers a reset feature:

function Timer(fn, t) {
    var timerObj = setInterval(fn, t);

    this.stop = function() {
        if (timerObj) {
            clearInterval(timerObj);
            timerObj = null;
        }
        return this;
    }

    // start timer using current settings (if it's not already running)
    this.start = function() {
        if (!timerObj) {
            this.stop();
            timerObj = setInterval(fn, t);
        }
        return this;
    }

    // start with new or original interval, stop current interval
    this.reset = function(newT = t) {
        t = newT;
        return this.stop().start();
    }
}

Usage:

var timer = new Timer(function() {
    // your function here
}, 5000);


// switch interval to 10 seconds
timer.reset(10000);

// stop the timer
timer.stop();

// start the timer
timer.start();

Working demo: https://jsfiddle.net/jfriend00/t17vz506/

cannot import name patterns

Pattern module in not available from django 1.8. So you need to remove pattern from your import and do something similar to the following:

from django.conf.urls import include, url
from django.contrib import admin

admin.autodiscover()

urlpatterns = [                 
    # here we are not using pattern module like in previous django versions
    url(r'^admin/', include(admin.site.urls)),
]

Selecting and manipulating CSS pseudo-elements such as ::before and ::after using javascript (or jQuery)

Here is the way to access :after and :before style properties, defined in css:

// Get the color value of .element:before
var color = window.getComputedStyle(
    document.querySelector('.element'), ':before'
).getPropertyValue('color');

// Get the content value of .element:before
var content = window.getComputedStyle(
    document.querySelector('.element'), ':before'
).getPropertyValue('content');

Assembly code vs Machine code vs Object code?

The source files of your programs are compiled into object files, and then the linker links those object files together, producing an executable file including your architecture's machine codes.

Both object file and executable file involves architecture's machine code in the form of printable and non-printable characters when it's opened by a text editor.

Nonetheless, the dichotomy between the files is that the object file(s) may contain unresolved external references (such as printf, for instance). So, it may need to be linked against other object files.. That is to say, the unresolved external references are needed to be resolved in order to get the decent runnable executable file by linking with other object files such as C/C++ runtime library's.

How to change the Text color of Menu item in Android?

Thanks to max.musterman, this is the solution I got to work in level 22:

public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);
    SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
    MenuItem searchMenuItem = menu.findItem(R.id.search);
    SearchView searchView = (SearchView) searchMenuItem.getActionView();
    searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
    searchView.setSubmitButtonEnabled(true);
    searchView.setOnQueryTextListener(this);
    setMenuTextColor(menu, R.id.displaySummary, R.string.show_summary);
    setMenuTextColor(menu, R.id.about, R.string.text_about);
    setMenuTextColor(menu, R.id.importExport, R.string.import_export);
    setMenuTextColor(menu, R.id.preferences, R.string.settings);
    return true;
}

private void setMenuTextColor(Menu menu, int menuResource, int menuTextResource) {
    MenuItem item = menu.findItem(menuResource);
    SpannableString s = new SpannableString(getString(menuTextResource));
    s.setSpan(new ForegroundColorSpan(Color.BLACK), 0, s.length(), 0);
    item.setTitle(s);
}

The hardcoded Color.BLACK could become an additional parameter to the setMenuTextColor method. Also, I only used this for menu items which were android:showAsAction="never".

Laravel migration: unique key is too long, even if specified

Update 1

As of Laravel 5.4 those changes are no more needed.

Laravel 5.4 uses the utf8mb4 character set by default, which includes support for storing "emojis" in the database. If you are upgrading your application from Laravel 5.3, you are not required to switch to this character set.

Update 2

Current production MariaDB versions DO NOT support this setting by default globally. It is implemented in MariaDB 10.2.2+ by default.

Solution

And if you intentionally want to use the correct future-default (starting from Laravel 5.4) UTF8 multi-byte utf8mb4 support for then start to fix your database configuration.

In Laravel config/database.php define:

'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'engine' => 'InnoDB ROW_FORMAT=DYNAMIC',

DYNAMIC allows to store long key indexes.

Server settings (by default included in MySQL 5.7.7+ / MariaDB 10.2.2+):

[mysqld]
# default character set and collation
collation-server = utf8mb4_unicode_ci
character-set-server = utf8mb4

# utf8mb4 long key index
innodb_large_prefix = 1
innodb_file_format = barracuda
innodb_file_format_max = barracuda
innodb_file_per_table = 1

For clients:

[mysql]
default-character-set=utf8mb4

And then STOP your MySQL/MariaDB server. After that START. Hot RESTART may not work.

sudo systemctl stop mysqld
sudo systemctl start mysqld

Now you have Laravel 5.x with UTF8 support.

Double border with different color

Use of pseudo-element as suggested by Terry has one PRO and one CON:

  1. PRO - great cross-browser compatibility because pseudo-element are supported also on older IE.
  2. CON - it requires to create an extra (even if generated) element, that infact is defined pseudo-element.

Anyway is a great solution.


OTHER SOLUTIONS:

If you can accept compatibility since IE9 (IE8 does not have support for this), you can achieve desired result in other two possible ways:

  1. using outline property combined with border and a single inset box-shadow
  2. using two box-shadow combined with border.

Here a jsFiddle with Terry's modified code that shows, side by side, these other possible solutions. Main specific properties for each one are the following (others are shared in .double-border class):

.left
{
  outline: 4px solid #fff;
  box-shadow:inset 0 0 0 4px #fff;
}

.right
{
  box-shadow:0 0 0 4px #fff, inset 0 0 0 4px #fff;
}

LESS code:

You asked for possible advantages about using a pre-processor like LESS. I this specific case, utility is not so great, but anyway you could optimize something, declaring colors and border/ouline/shadow with @variable.

Here an example of my CSS code, declared in LESS (changing colors and border-width becomes very quick):

@double-border-size:4px;
@inset-border-color:#fff;
@content-color:#ccc;

.double-border 
{
  background-color: @content-color;
  border: @double-border-size solid @content-color;
  padding: 2em;
  width: 16em;
  height: 16em;
  float:left;
  margin-right:20px;
  text-align:center;
}

.left
{
  outline: @double-border-size solid @inset-border-color;
  box-shadow:inset 0 0 0 @double-border-size @inset-border-color;
}

.right
{
  box-shadow:0 0 0 @double-border-size @inset-border-color, inset 0 0 0 @double-border-size @inset-border-color;
}

Grep to find item in Perl array

The first arg that you give to grep needs to evaluate as true or false to indicate whether there was a match. So it should be:

# note that grep returns a list, so $matched needs to be in brackets to get the 
# actual value, otherwise $matched will just contain the number of matches
if (my ($matched) = grep $_ eq $match, @array) {
    print "found it: $matched\n";
}

If you need to match on a lot of different values, it might also be worth for you to consider putting the array data into a hash, since hashes allow you to do this efficiently without having to iterate through the list.

# convert array to a hash with the array elements as the hash keys and the values are simply 1
my %hash = map {$_ => 1} @array;

# check if the hash contains $match
if (defined $hash{$match}) {
    print "found it\n";
}

PHP cURL, extract an XML response

<?php
function download_page($path){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$path);
    curl_setopt($ch, CURLOPT_FAILONERROR,1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 15);
    $retValue = curl_exec($ch);          
    curl_close($ch);
    return $retValue;
}

$sXML = download_page('http://alanstorm.com/atom');
$oXML = new SimpleXMLElement($sXML);

foreach($oXML->entry as $oEntry){
    echo $oEntry->title . "\n";
}

How to set java_home on Windows 7?

You have to first Install JDK in your system.

Set Java Home

JAVA_HOME = C:\Program Files\Java\jdk1.7.0 [Location of your JDK Installation Directory]

Once you have the JDK installation path:

  • Right-click the My Computer icon on
  • Select Properties.
  • Click the Advanced system setting tab on left side of your screen
  • Aadvance Popup is open.
  • Click on Environment Variables button.

enter image description here

  • Under System Variables, click New.
  • Enter the variable name as JAVA_HOME.
  • Enter the variable value as the installation path for the Java Development Kit.
  • Click OK.
  • Click Apply Changes.

Set JAVA Path under system variable

PATH= C:\Program Files\Java\jdk1.7.0; [Append Value with semi-colon]

check here

Different CURRENT_TIMESTAMP and SYSDATE in oracle

Note: SYSDATE - returns only date, i.e., "yyyy-mm-dd" is not correct. SYSDATE returns the system date of the database server including hours, minutes, and seconds. For example:

SELECT SYSDATE FROM DUAL; will return output similar to the following: 12/15/2017 12:42:39 PM

TextView bold via xml file?

Use android:textStyle="bold"

4 ways to make Android TextView Bold

like this

<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:textSize="12dip"
android:textStyle="bold"
/>

There are many ways to make Android TextView bold.

syntax error near unexpected token `('

Try

sudo -su db2inst1 /opt/ibm/db2/V9.7/bin/db2 force application \(1995\)

How to deselect a selected UITableView cell?

Swift 4:

func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
    let cell = tableView.cellForRow(at: indexPath)
    if cell?.isSelected == true { // check if cell has been previously selected
        tableView.deselectRow(at: indexPath, animated: true)
        return nil
    } else {
        return indexPath
    }
}

Creating random numbers with no duplicates

The most easy way is use nano DateTime as long format. System.nanoTime();

Where does error CS0433 "Type 'X' already exists in both A.dll and B.dll " come from?

Reference : https://support.microsoft.com/en-in/help/2028526/building-an-asp-net-project-in-visual-studio-results-in-compiler-error

When building an ASP.NET project using Visual Studio, you may randomly see an error message similar to the following:

Compiler Error Message: CS0433: The type 'ASP.summary_common_controls_notes_ascx' exists in both 'c:\Windows\Microsoft.NET\Framework64\v2.0.50727\Temporary ASP.NET Files\Book_Details\abc12345\def8910\App_Web_msftx123.dll' and 'c:\Windows\Microsoft.NET\Framework64\v2.0.50727\Temporary ASP.NET Files\Book_Details\abc12345\def8910\App_Web_msfty456.dll'

Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.

Source Error: Line 100: Line 101:
New Notes Line 102:
Line 103:
1450 Line 104:

Summary.

Source File: d:\http\post\publisher\default.aspx Line: 102

Common scenarios where this error can occur are discussed below

Scenario 1

Description: A common cause is when there are two assemblies in the same web application bin folder containing two class definitions but that have the same class name. This can happen if more than one Default.aspx was compiled into a single assembly. Commonly, this occurs when the Master page (Default.master) and the Default ASPX page (Default.aspx) both declare a _Default class. Solution: Change the class name of the master page (from _Default in most cases) and rebuild the project. It is important to resolve any naming conflict between classes.

Scenario 2

Description: The Reference Paths in Visual Studio is used to specify the folder path for assembly references used by the project. It is possible that the path contains an assembly that contains the same class name. It may be that there are multiple References added to the same assembly (possibly different version or name) causing a naming conflict.
Solution: Remove the old version reference. To do so, in Visual Studio right-click your web site and check the "References" in the properties.

Scenario 3

Description: By default, when an ASP.NET Web application is compiled the compiled code is placed in the Temporary ASP.NET Files folder. By default the access permissions are given to the ASP.NET local user account, which has the high-trust permissions needed to access compiled code. It is possible that there were some changes in the default permissions causing versioning conflicts. Another possibility would be that anti-virus software could be locking an assembly inadvertently. Solution: Clear the Temporary ASP.NET Files Folder of all contents.

Scenario 4

Description: When the batch attribute in the web.config is set to True it eliminates the delay caused by the compilation required when you access a file for the first time. ASP.NET precompiles all the un-compiled files in a batch mode, which causes delays the first time the files are compiled. Turning off batch compilation may expose masked compilation errors that may exist in the application but are not reported. However more importantly for this issue it tells ASP.NET to dynamically compile individual .aspx/.ascx files into separate assemblies instead of into a single assembly. Solution: Set batch=false in the section in web.config. This should be considered a temporary solution as setting batch=false in the compilation section has a significant performance impact on build times for the application in Visual Studio.

Scenario 5

Description: Modifying the web.config file for an ASP.NET application or changing a file in the bin folder (such as adding, deleting, or renaming) causes the AppDomain to restart. When this occurs all session state is lost and cached items are removed from the cache as the website restarts. It is possible that the problem is caused by an inconsistent state in the web application. Solution: Trigger an AppDomain restart by touching (editing) the web.config file.

Scenario 6

Description: You can store source code in the App_Code folder, and it will be automatically compiled at run time. The resulting assembly is accessible to any other code in the Web application. The App_Code folder therefore works much like the Bin folder, except that you can store source code in it instead of compiled code. The class will be recompiled when there is a change in the source file. If there is conflict due to an outdated assembly then forcing a recompile may resolve the problem. Solution: Touch a file in the Bin or App_Code folders to trigger a full recompilation.

Pure CSS checkbox image replacement

You are close already. Just make sure to hide the checkbox and associate it with a label you style via input[checkbox] + label

Complete Code: http://gist.github.com/592332

JSFiddle: http://jsfiddle.net/4huzr/

Xcode 6 iPhone Simulator Application Support location

To know where your .sqlite file is stored in your AppDelegate.m add the following code

- (NSURL *)applicationDocumentsDirectory
{
    NSLog(@"%@",[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory      inDomains:NSUserDomainMask] lastObject]);

    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory     inDomains:NSUserDomainMask] lastObject];
 }

now call this method in AppDelegate.m

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{

  //call here
   [self applicationDocumentsDirectory];

}

How to list records with date from the last 10 days?

My understanding from my testing (and the PostgreSQL dox) is that the quotes need to be done differently from the other answers, and should also include "day" like this:

SELECT Table.date
  FROM Table 
  WHERE date > current_date - interval '10 day';

Demonstrated here (you should be able to run this on any Postgres db):

SELECT DISTINCT current_date, 
                current_date - interval '10' day, 
                current_date - interval '10 days' 
  FROM pg_language;

Result:

2013-03-01  2013-03-01 00:00:00 2013-02-19 00:00:00

Write to CSV file and export it?

A comment about Will's answer, you might want to replace HttpContext.Current.Response.End(); with HttpContext.Current.ApplicationInstance.CompleteRequest(); The reason is that Response.End() throws a System.Threading.ThreadAbortException. It aborts a thread. If you have an exception logger, it will be littered with ThreadAbortExceptions, which in this case is expected behavior.

Intuitively, sending a CSV file to the browser should not raise an exception.

See here for more Is Response.End() considered harmful?

Can't choose class as main class in IntelliJ

The documentation you linked actually has the answer in the link associated with the "Java class located out of the source root." Configure your source and test roots and it should work.

https://www.jetbrains.com/idea/webhelp/configuring-content-roots.html

Since you stated that these are tests you should probably go with them marked as Test Source Root instead of Source Root.

Setting Remote Webdriver to run tests in a remote computer using Java

By Default the InternetExplorerDriver listens on port "5555". Change your huburl to match that. you can look on the cmd box window to confirm.

Difference between Spring MVC and Spring Boot

  • Using spring boot you will no need to build configuration. This will have done automatically when you create project.

  • If you use spring MVC you need to build configuration yourself. It is more complicated, but it is crucial.

How can I add an empty directory to a Git repository?

Here is a hack, but it's funny that it works (Git 2.2.1). Similar to what @Teka suggested, but easier to remember:

  • Add a submodule to any repository (git submodule add path_to_repo)
  • This will add a folder and a file .submodules. Commit a change.
  • Delete .submodules file and commit the change.

Now, you have a directory that gets created when commit is checked out. An interesting thing though is that if you look at the content of tree object of this file you'll get:

fatal: Not a valid object name b64338b90b4209263b50244d18278c0999867193

I wouldn't encourage to use it though since it may stop working in the future versions of Git. Which may leave your repository corrupted.

Shorten string without cutting words in JavaScript

'Pasta with tomato and spinach'

if you do not want to cut the word in half

first iteration:

acc:0 / acc +cur.length = 5 / newTitle = ['Pasta'];

second iteration:

acc:5 / acc + cur.length = 9 / newTitle = ['Pasta', 'with'];

third iteration:

acc:9 / acc + cur.length = 15 / newTitle = ['Pasta', 'with', 'tomato'];

fourth iteration:

acc:15 / acc + cur.length = 18(limit bound) / newTitle = ['Pasta', 'with', 'tomato'];

const limitRecipeTitle = (title, limit=17)=>{
    const newTitle = [];
    if(title.length>limit){
        title.split(' ').reduce((acc, cur)=>{
            if(acc+cur.length <= limit){
                newTitle.push(cur);
            }
            return acc+cur.length;
        },0);
    }

    return `${newTitle.join(' ')} ...`
}

output: Pasta with tomato ...

What is DOM Event delegation?

Event delegation makes use of two often overlooked features of JavaScript events: event bubbling and the target element.When an event is triggered on an element, for example a mouse click on a button, the same event is also triggered on all of that element’s ancestors. This process is known as event bubbling; the event bubbles up from the originating element to the top of the DOM tree.

Imagine an HTML table with 10 columns and 100 rows in which you want something to happen when the user clicks on a table cell. For example, I once had to make each cell of a table of that size editable when clicked. Adding event handlers to each of the 1000 cells would be a major performance problem and, potentially, a source of browser-crashing memory leaks. Instead, using event delegation, you would add only one event handler to the table element, intercept the click event and determine which cell was clicked.

What is the main difference between Inheritance and Polymorphism?

Inheritance is when a 'class' derives from an existing 'class'. So if you have a Person class, then you have a Student class that extends Person, Student inherits all the things that Person has. There are some details around the access modifiers you put on the fields/methods in Person, but that's the basic idea. For example, if you have a private field on Person, Student won't see it because its private, and private fields are not visible to subclasses.

Polymorphism deals with how the program decides which methods it should use, depending on what type of thing it has. If you have a Person, which has a read method, and you have a Student which extends Person, which has its own implementation of read, which method gets called is determined for you by the runtime, depending if you have a Person or a Student. It gets a bit tricky, but if you do something like

Person p = new Student();
p.read();

the read method on Student gets called. Thats the polymorphism in action. You can do that assignment because a Student is a Person, but the runtime is smart enough to know that the actual type of p is Student.

Note that details differ among languages. You can do inheritance in javascript for example, but its completely different than the way it works in Java.

Best HTTP Authorization header type for JWT

Short answer

The Bearer authentication scheme is what you are looking for.

Long answer

Is it related to bears?

Errr... No :)

According to the Oxford Dictionaries, here's the definition of bearer:

bearer /'b??r?/
noun

  1. A person or thing that carries or holds something.

  2. A person who presents a cheque or other order to pay money.

The first definition includes the following synonyms: messenger, agent, conveyor, emissary, carrier, provider.

And here's the definition of bearer token according to the RFC 6750:

1.2. Terminology

Bearer Token

A security token with the property that any party in possession of the token (a "bearer") can use the token in any way that any other party in possession of it can. Using a bearer token does not require a bearer to prove possession of cryptographic key material (proof-of-possession).

The Bearer authentication scheme is registered in IANA and originally defined in the RFC 6750 for the OAuth 2.0 authorization framework, but nothing stops you from using the Bearer scheme for access tokens in applications that don't use OAuth 2.0.

Stick to the standards as much as you can and don't create your own authentication schemes.


An access token must be sent in the Authorization request header using the Bearer authentication scheme:

2.1. Authorization Request Header Field

When sending the access token in the Authorization request header field defined by HTTP/1.1, the client uses the Bearer authentication scheme to transmit the access token.

For example:

GET /resource HTTP/1.1
Host: server.example.com
Authorization: Bearer mF_9.B5f-4.1JqM

[...]

Clients SHOULD make authenticated requests with a bearer token using the Authorization request header field with the Bearer HTTP authorization scheme. [...]

In case of invalid or missing token, the Bearer scheme should be included in the WWW-Authenticate response header:

3. The WWW-Authenticate Response Header Field

If the protected resource request does not include authentication credentials or does not contain an access token that enables access to the protected resource, the resource server MUST include the HTTP WWW-Authenticate response header field [...].

All challenges defined by this specification MUST use the auth-scheme value Bearer. This scheme MUST be followed by one or more auth-param values. [...].

For example, in response to a protected resource request without authentication:

HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer realm="example"

And in response to a protected resource request with an authentication attempt using an expired access token:

HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer realm="example",
                         error="invalid_token",
                         error_description="The access token expired"

Reading Properties file in Java

Make sure that the file name is correct and that the file is actually in the class path. getResourceAsStream() will return null if this is not the case which causes the last line to throw the exception.

If myProp.properties is in the root directory of your project, use /myProp.properties instead.

What do pty and tty mean?

tty: teletype. Usually refers to the serial ports of a computer, to which terminals were attached.

pty: pseudoteletype. Kernel provided pseudoserial port connected to programs emulating terminals, such as xterm, or screen.

py2exe - generate single executable file

As the other poster mention, py2exe, will generate an executable + some libraries to load. You can also have some data to add to your program.

Next step is to use an installer, to package all this into one easy-to-use installable/unistallable program.

I have used InnoSetup with delight for several years and for commercial programs, so I heartily recommend it.

Get href attribute on jQuery

Use $(this) for get the desire element.

function openAll()
{
     $("tr.b_row").each(function(){
        var a_href = $(this).find('.cpt h2 a').attr('href');
        alert ("Href is: "+a_href);
     });
}

Mailbox unavailable. The server response was: 5.7.1 Unable to relay Error

The default configuration of most SMTP servers is not to relay from an untrusted source to outside domains. For example, imagine that you contact the SMTP server for foo.com and ask it to send a message to [email protected]. Because the SMTP server doesn't really know who you are, it will refuse to relay the message. If the server did do that for you, it would be considered an open relay, which is how spammers often do their thing.

If you contact the foo.com mail server and ask it to send mail to [email protected], it might let you do it. It depends on if they trust that you're who you say you are. Often, the server will try to do a reverse DNS lookup, and refuse to send mail if the IP you're sending from doesn't match the IP address of the MX record in DNS. So if you say that you're the bar.com mail server but your IP address doesn't match the MX record for bar.com, then it will refuse to deliver the message.

You'll need to talk to the administrator of that SMTP server to get the authentication information so that it will allow relay for you. You'll need to present those credentials when you contact the SMTP server. Usually it's either a user name/password, or it can use Windows permissions. Depends on the server and how it's configured.

See Unable to send emails to external domain using SMTP for an example of how to send the credentials.

JavaScript checking for null vs. undefined and difference between == and ===

The spec is the place to go for full answers to these questions. Here's a summary:

  1. For a variable x, you can:

    • check whether it's null by direct comparison using ===. Example: x === null
    • check whether it's undefined by either of two basic methods: direct comparison with undefined or typeof. For various reasons, I prefer typeof x === "undefined".
    • check whether it's one of null and undefined by using == and relying on the slightly arcane type coercion rules that mean x == null does exactly what you want.

  2. The basic difference between == and === is that if the operands are of different types, === will always return false while == will convert one or both operands into the same type using rules that lead to some slightly unintuitive behaviour. If the operands are of the same type (e.g. both are strings, such as in the typeof comparison above), == and === will behave exactly the same.

More reading:

Linq to SQL how to do "where [column] in (list of values)"

Here is how I do it by using HashSet

        HashSet<String> hs = new HashSet<string>(new String[] { "Pluto", "Earth", "Neptune" });
        String[] arr =
        {
            "Pluto",
            "Earth",
            "Neptune",
            "Jupiter",
            "Saturn",
            "Mercury",
            "Pluto",
            "Earth",
            "Neptune",
            "Jupiter",
            "Saturn",
            "Mercury",
            // etc.
        };
        ICollection<String> coll = arr;

        String[] arrStrFiltered = coll.Where(str => hs.Contains(str)).ToArray();

HashSet is basically almost to O(1) so your complexity remains O(n).