Programs & Examples On #Mouseclick event

An event that is triggered when a Mouse input device is clicked

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

An interesting solution is to make this declarative: you just give every div that should be shown an attribute automaticallyVisibleIfIdChecked with the id of the checkbox or radio button on which it depends. That is, your form looks like this:

<form name="form1" id="my_form" method="post" action="">
    <div><label><input type="radio" name="group1" id="rdio1" value="opt1">opt1</label></div>  
    <div><label><input type="radio" name="group1" id="rdio2" value="opt2">opt2</label></div>  
</form>
....
<div id="opt1" automaticallyVisibleIfIdChecked="rdio1">lorem ipsum dolor</div>
<div id="opt2" automaticallyVisibleIfIdChecked="rdio2">consectetur adipisicing</div>

and have some page independent JavaScript that nicely uses functional programming:

function executeAutomaticVisibility(name) {
    $("[name="+name+"]:checked").each(function() {
        $("[automaticallyVisibleIfIdChecked=" + this.id+"]").show();
    });
    $("[name="+name+"]:not(:checked)").each(function() {
        $("[automaticallyVisibleIfIdChecked=" + this.id+"]").hide();
    });
}

$(document).ready( function() {
    triggers = $("[automaticallyVisibleIfIdChecked]")
        .map(function(){ return $("#" + $(this).attr("automaticallyVisibleIfIdChecked")).get() })
    $.unique(triggers);
    triggers.each( function() {
        executeAutomaticVisibility(this.name);
        $(this).change( function(){ executeAutomaticVisibility(this.name); } );
    });
});

Similarily you could automatically enable / disable form fields with an attribute automaticallyEnabledIfChecked.

I think this method is nice since it avoids having to create specific JavaScript for your page - you just insert some attributes that say what should be done.

How to simulate a mouse click using JavaScript?

You can use elementFromPoint:

document.elementFromPoint(x, y);

supported in all browsers: https://caniuse.com/#feat=element-from-point

How to simulate a click by using x,y coordinates in JavaScript?

it doenst work for me but it prints the correct element to the console

this is the code:

function click(x, y)
{
    var ev = new MouseEvent('click', {
        'view': window,
        'bubbles': true,
        'cancelable': true,
        'screenX': x,
        'screenY': y
    });

    var el = document.elementFromPoint(x, y);
    console.log(el); //print element to console
    el.dispatchEvent(ev);
}
click(400, 400);

Attaching click to anchor tag in angular

<a href="#" (click)="onGoToPage2()">Go to page 2</a>

Disallow Twitter Bootstrap modal window from closing

As D3VELOPER says, the following code resolve it:

$('#modal').removeData('bs.modal').modal({backdrop: 'static', keyboard: false});

I'm using both jquery & bootstrap and simply removeData('modal') don't work.

Mapping many-to-many association table with extra column(s)

Since the SERVICE_USER table is not a pure join table, but has additional functional fields (blocked), you must map it as an entity, and decompose the many to many association between User and Service into two OneToMany associations : One User has many UserServices, and one Service has many UserServices.

You haven't shown us the most important part : the mapping and initialization of the relationships between your entities (i.e. the part you have problems with). So I'll show you how it should look like.

If you make the relationships bidirectional, you should thus have

class User {
    @OneToMany(mappedBy = "user")
    private Set<UserService> userServices = new HashSet<UserService>();
}

class UserService {
    @ManyToOne
    @JoinColumn(name = "user_id")
    private User user;

    @ManyToOne
    @JoinColumn(name = "service_code")
    private Service service;

    @Column(name = "blocked")
    private boolean blocked;
}

class Service {
    @OneToMany(mappedBy = "service")
    private Set<UserService> userServices = new HashSet<UserService>();
}

If you don't put any cascade on your relationships, then you must persist/save all the entities. Although only the owning side of the relationship (here, the UserService side) must be initialized, it's also a good practice to make sure both sides are in coherence.

User user = new User();
Service service = new Service();
UserService userService = new UserService();

user.addUserService(userService);
userService.setUser(user);

service.addUserService(userService);
userService.setService(service);

session.save(user);
session.save(service);
session.save(userService);

How do you declare an object array in Java?

Like this

Vehicle[] car = new Vehicle[10];

Is there any difference between "!=" and "<>" in Oracle Sql?

Actually, there are four forms of this operator:

<>
!=
^=

and even

¬= -- worked on some obscure platforms in the dark ages

which are the same, but treated differently when a verbatim match is required (stored outlines or cached queries).

What is the best (and safest) way to merge a Git branch into master?

@KingCrunch's answer should work in many cases. One issue that can arise is you may be on a different machine that needs to pull the latest from test. So, I recommend pulling test first. The revision looks like this:

git checkout test
git pull
git checkout master
git pull origin master
git merge test
git push origin master

Check, using jQuery, if an element is 'display:none' or block on click

Yes, you can use the cssfunction. The below will search all divs, but you can modify it for whatever elements you need

$('div').each(function(){

    if ( $(this).css('display') == 'none')
    {
       //do something
    }
});

Android Studio Run/Debug configuration error: Module not specified

I would like to add some more information while I was facing this issue:

Ref: Answer from @Eli:

  1. Cut line include ':app' from the file.
  2. On Android Studio, click on the File Menu, and select Sync Project with Gradle files.
  3. After synchronisation, paste back line include ':app' to the settings.gradle file.
  4. Re-run Sync Project with Gradle files again.

So, let's follow the instruction and try to keep one thing in mind, that what is showing in your build configuration. Make sure you are seeing the name of your configuration app like the image below:

enter image description here

If you are seeing anything else, then the steps mentioned by @Eli (the most accepted answer) will not work.

An alternative Solution If you have a different name on the Run/Debug Configurations window and the above process is not working, please change the config name to 'app'

then -> hit Apply -> then Ok.

After that follow this:-

File->Sync project with gradle files (if needed).

Now check the issue will be resolved hopefully. I have faced this issue and I think it might help others as well.

How to define a two-dimensional array?

l=[[0]*(L) for _ in range(W)]

Will be faster than:

l = [[0 for x in range(L)] for y in range(W)] 

Remove carriage return in Unix

Removing \r on any UNIX® system:

Most existing solutions in this question are GNU-specific, and wouldn't work on OS X or BSD; the solutions below should work on many more UNIX systems, and in any shell, from tcsh to sh, yet still work even on GNU/Linux, too.

Tested on OS X, OpenBSD and NetBSD in tcsh, and on Debian GNU/Linux in bash.


With sed:

In tcsh on an OS X, the following sed snippet could be used together with printf, as neither sed nor echo handle \r in the special way like the GNU does:

sed `printf 's/\r$//g'` input > output

With tr:

Another option is tr:

tr -d '\r' < input > output

Difference between sed and tr:

It would appear that tr preserves a lack of a trailing newline from the input file, whereas sed on OS X and NetBSD (but not on OpenBSD or GNU/Linux) inserts a trailing newline at the very end of the file even if the input is missing any trailing \r or \n at the very end of the file.


Testing:

Here's some sample testing that could be used to ensure this works on your system, using printf and hexdump -C; alternatively, od -c could also be used if your system is missing hexdump:

% printf 'a\r\nb\r\nc' | hexdump -C
00000000  61 0d 0a 62 0d 0a 63                              |a..b..c|
00000007
% printf 'a\r\nb\r\nc' | ( sed `printf 's/\r$//g'` /dev/stdin > /dev/stdout ) | hexdump -C
00000000  61 0a 62 0a 63 0a                                 |a.b.c.|
00000006
% printf 'a\r\nb\r\nc' | ( tr -d '\r' < /dev/stdin > /dev/stdout ) | hexdump -C
00000000  61 0a 62 0a 63                                    |a.b.c|
00000005
% 

How can I read a text file from the SD card in Android?

package com.example.readfilefromexternalresource;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.os.Bundle;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import android.os.Build;

public class MainActivity extends Activity {
    private TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        textView = (TextView)findViewById(R.id.textView);
        String state = Environment.getExternalStorageState();

        if (!(state.equals(Environment.MEDIA_MOUNTED))) {
            Toast.makeText(this, "There is no any sd card", Toast.LENGTH_LONG).show();


        } else {
            BufferedReader reader = null;
            try {
                Toast.makeText(this, "Sd card available", Toast.LENGTH_LONG).show();
                File file = Environment.getExternalStorageDirectory();
                File textFile = new File(file.getAbsolutePath()+File.separator + "chapter.xml");
                reader = new BufferedReader(new FileReader(textFile));
                StringBuilder textBuilder = new StringBuilder();
                String line;
                while((line = reader.readLine()) != null) {
                    textBuilder.append(line);
                    textBuilder.append("\n");

                }
                textView.setText(textBuilder);

            } catch (FileNotFoundException e) {
                // TODO: handle exception
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            finally{
                if(reader != null){
                    try {
                        reader.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }

        }
    }
}

Cannot connect to MySQL Workbench on mac. Can't connect to MySQL server on '127.0.0.1' (61) Mac Macintosh

Ran into a similar issue and my problem was that MySQL installed itself configured to run on non-default port. I do not know the reason for that, but to find out which port MySQL is running on, run the following in MySql client:

SHOW GLOBAL VARIABLES LIKE 'PORT';

How to check if character is a letter in Javascript?

With respect to those special characters not being taken into account by simpler checks such as /[a-zA-Z]/.test(c), it can be beneficial to leverage ECMAScript case transformation (toUpperCase). It will take into account non-ASCII Unicode character classes of some foreign alphabets.

function isLetter(c) {
  return c.toLowerCase() != c.toUpperCase();
}

NOTE: this solution will work only for most Latin, Greek, Armenian and Cyrillic scripts. It will NOT work for Chinese, Japanese, Arabic, Hebrew and most other scripts.

Why use pip over easy_install?

As an addition to fuzzyman's reply:

pip won't install binary packages and isn't well tested on Windows.

As Windows doesn't come with a compiler by default pip often can't be used there. easy_install can install binary packages for Windows.

Here is a trick on Windows:

  • you can use easy_install <package> to install binary packages to avoid building a binary

  • you can use pip uninstall <package> even if you used easy_install.

This is just a work-around that works for me on windows. Actually I always use pip if no binaries are involved.

See the current pip doku: http://www.pip-installer.org/en/latest/other-tools.html#pip-compared-to-easy-install

I will ask on the mailing list what is planned for that.

Here is the latest update:

The new supported way to install binaries is going to be wheel! It is not yet in the standard, but almost. Current version is still an alpha: 1.0.0a1

https://pypi.python.org/pypi/wheel

http://wheel.readthedocs.org/en/latest/

I will test wheel by creating an OS X installer for PySide using wheel instead of eggs. Will get back and report about this.

cheers - Chris

A quick update:

The transition to wheel is almost over. Most packages are supporting wheel.

I promised to build wheels for PySide, and I did that last summer. Works great!

HINT: A few developers failed so far to support the wheel format, simply because they forget to replace distutils by setuptools. Often, it is easy to convert such packages by replacing this single word in setup.py.

What is IllegalStateException?

Usually, IllegalStateException is used to indicate that "a method has been invoked at an illegal or inappropriate time." However, this doesn't look like a particularly typical use of it.

The code you've linked to shows that it can be thrown within that code at line 259 - but only after dumping a SQLException to standard output.

We can't tell what's wrong just from that exception - and better code would have used the original SQLException as a "cause" exception (or just let the original exception propagate up the stack) - but you should be able to see more details on standard output. Look at that information, and you should be able to see what caused the exception, and fix it.

How to get current time with jQuery

Using JavaScript native Date functions you can get hours, minutes and seconds as you want. If you wish to format date and time in particular way you may want to implement a method extending JavaScript Date prototype.

Here is one already implemented: https://github.com/jacwright/date.format

Preferred method to store PHP arrays (json_encode vs serialize)

I would suggest you to use Super Cache, which is a file cache mechanism which won't use json_encode or serialize. It is simple to use and really fast compared to other PHP Cache mechanism.

https://packagist.org/packages/smart-php/super-cache

Ex:

<?php
require __DIR__.'/vendor/autoload.php';
use SuperCache\SuperCache as sCache;

//Saving cache value with a key
// sCache::cache('<key>')->set('<value>');
sCache::cache('myKey')->set('Key_value');

//Retrieving cache value with a key
echo sCache::cache('myKey')->get();
?>

Open file with associated application

Just write

System.Diagnostics.Process.Start(@"file path");

example

System.Diagnostics.Process.Start(@"C:\foo.jpg");
System.Diagnostics.Process.Start(@"C:\foo.doc");
System.Diagnostics.Process.Start(@"C:\foo.dxf");
...

And shell will run associated program reading it from the registry, like usual double click does.

Accessing attributes from an AngularJS directive

Although using '@' is more appropriate than using '=' for your particular scenario, sometimes I use '=' so that I don't have to remember to use attrs.$observe():

<su-label tooltip="field.su_documentation">{{field.su_name}}</su-label>

Directive:

myApp.directive('suLabel', function() {
    return {
        restrict: 'E',
        replace: true,
        transclude: true,
        scope: {
            title: '=tooltip'
        },
        template: '<label><a href="#" rel="tooltip" title="{{title}}" data-placement="right" ng-transclude></a></label>',
        link: function(scope, element, attrs) {
            if (scope.title) {
                element.addClass('tooltip-title');
            }
        },
    }
});

Fiddle.

With '=' we get two-way databinding, so care must be taken to ensure scope.title is not accidentally modified in the directive. The advantage is that during the linking phase, the local scope property (scope.title) is defined.

How to delete all files and folders in a directory?

private void ClearFolder(string FolderName)
{
    DirectoryInfo dir = new DirectoryInfo(FolderName);

    foreach(FileInfo fi in dir.GetFiles())
    {
        try
        {
            fi.Delete();
        }
        catch(Exception) { } // Ignore all exceptions
    }

    foreach(DirectoryInfo di in dir.GetDirectories())
    {
        ClearFolder(di.FullName);
        try
        {
            di.Delete();
        }
        catch(Exception) { } // Ignore all exceptions
    }
}

If you know there are no sub-folders, something like this may be the easiest:

    Directory.GetFiles(folderName).ForEach(File.Delete)

Getting "NoSuchMethodError: org.hamcrest.Matcher.describeMismatch" when running test in IntelliJ 10.5

This worked for me after struggling a bit

<dependency>
    <groupId>org.hamcrest</groupId>
    <artifactId>hamcrest-all</artifactId>
    <version>1.3</version>
    <scope>test</scope>
 </dependency>

 <dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-all</artifactId>
    <version>1.9.5</version>
    <scope>test</scope>
 </dependency>

 <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.11</version>
    <scope>test</scope>
 </dependency>

Unable to create Genymotion Virtual Device

I just ran into this problem too, so just in case anyone needs it: The reason why it needs admin privileges is probably because of your settings on where it store the virtual device.. Go to Settings - Virtual Box - and change your virtual devices storage area. I got mine set to something like \Program Files\Genymotion, that's why it needs Admin privileges. I only blanked the field, clicked ok, and it got set to the default which is in my home directory.. After that no need to run as admin anymore..

(I need 50 reputations to comment, so had to use this answer..)

What is difference between cacerts and keystore?

Cacerts are details of trusted signing authorities who can issue certs. This what most of the browsers have due to which certs determined to be authentic. Keystone has your service related certs to authenticate clients.

Where are Docker images stored on the host machine?

check for the docker folder in /var/lib

the images are stored at below location:

/var/lib/docker/image/overlay2/imagedb/content

How to change PHP version used by composer

You can change php version of composer without uninstalling it, follow these steps :

  1. Search for system environment variables in cortana.
  2. Click on the button "Environment variables".
  3. Under "System variables" select path and click on edit, you will see one entry like this "C:\wamp\bin\php\php5.6.13".
  4. Just change this to the folder name of the php located at your wamp/bin/php7.1.9, here php7.1.9 is folder name.
  5. Replace php5.6.13 with bin7.1.9, it will look like these "C:\wamp\bin\php\php7.1.9", just click ok on all the boxes.
  6. You are done.
  7. To verify, first close all the cmd windows, than open cmd and type php -v, press enter and you should see php7.1.9.
  8. If you don't see change in php version than just restart your pc and run php -v again in cmd , it will work.

Python class inherits object

The syntax of the class creation statement:

class <ClassName>(superclass):
    #code follows

In the absence of any other superclasses that you specifically want to inherit from, the superclass should always be object, which is the root of all classes in Python.

object is technically the root of "new-style" classes in Python. But the new-style classes today are as good as being the only style of classes.

But, if you don't explicitly use the word object when creating classes, then as others mentioned, Python 3.x implicitly inherits from the object superclass. But I guess explicit is always better than implicit (hell)

Reference

Openssl is not recognized as an internal or external command

Well at the place of openssl ... you have to put actually the path to your openssl folder that you have downloaded. Your actual command should look like:

keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore | "C:\Users\abc\openssl\bin\openssl.exe" sha1 -binary | "C:\Users\abc\openssl\bin\openssl.exe" base64

Remember, path that you will enter will be the path where you have installed the openssl...hope this helps..:-)

Edit:

you can download openssl for windows 32 and 64 bit from the respective links below:

OpenSSL for 64 Bits

OpenSSL for 32 Bits

MySql ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)

In my case, I needed to Edit Inbound Rules on my AWS RDS instance to accept All Traffic. The default TCP/IP constraint prevented me from creating a database from my local machine otherwise.

How to transfer some data to another Fragment?

If you are using graph for navigation between fragments you can do this: From fragment A:

    Bundle bundle = new Bundle();
    bundle.putSerializable(KEY, yourObject);
    Navigation.findNavController(view).navigate(R.id.fragment, bundle);

To fragment B:

    Bundle bundle = getArguments();
    object = (Object) bundle.getSerializable(KEY);

Of course your object must implement Serializable

Split column at delimiter in data frame

Combining @Ramnath and @Tommy's answers allowed me to find an approach that works in base R for one or more columns.

Basic usage:

> df = data.frame(
+   id=1:3, foo=c('a|b','b|c','c|d'), 
+   bar=c('p|q', 'r|s', 's|t'), stringsAsFactors=F)
> transform(df, test=do.call(rbind, strsplit(foo, '|', fixed=TRUE)), stringsAsFactors=F)
  id foo bar test.1 test.2
1  1 a|b p|q      a      b
2  2 b|c r|s      b      c
3  3 c|d s|t      c      d

Multiple columns:

> transform(df, lapply(list(foo,bar),
+ function(x)do.call(rbind, strsplit(x, '|', fixed=TRUE))), stringsAsFactors=F)
  id foo bar X1 X2 X1.1 X2.1
1  1 a|b p|q  a  b    p    q
2  2 b|c r|s  b  c    r    s
3  3 c|d s|t  c  d    s    t

Better naming of multiple split columns:

> transform(df, lapply({l<-list(foo,bar);names(l)=c('foo','bar');l}, 
+                          function(x)do.call(rbind, strsplit(x, '|', fixed=TRUE))), stringsAsFactors=F)
  id foo bar foo.1 foo.2 bar.1 bar.2
1  1 a|b p|q     a     b     p     q
2  2 b|c r|s     b     c     r     s
3  3 c|d s|t     c     d     s     t

how to compare the Java Byte[] array?

If you're trying to use the array as a generic HashMap key, that's not going to work. Consider creating a custom wrapper object that holds the array, and whose equals(...) and hashcode(...) method returns the results from the java.util.Arrays methods. For example...

import java.util.Arrays;

public class MyByteArray {
   private byte[] data;

   // ... constructors, getters methods, setter methods, etc...


   @Override
   public int hashCode() {
      return Arrays.hashCode(data);
   }

   @Override
   public boolean equals(Object obj) {
      if (this == obj)
         return true;
      if (obj == null)
         return false;
      if (getClass() != obj.getClass())
         return false;
      MyByteArray other = (MyByteArray) obj;
      if (!Arrays.equals(data, other.data))
         return false;
      return true;
   }


}

Objects of this wrapper class will work fine as a key for your HashMap<MyByteArray, OtherType> and will allow for clean use of equals(...) and hashCode(...) methods.

Renaming part of a filename

There are a couple of variants of a rename command, in your case, it may be as simple as

rename ABC XYZ *.dat

You may have a version which takes a Perl regex;

rename 's/ABC/XYZ/' *.dat

How to pass parameters on onChange of html select

Another approach wich can be handy in some situations, is passing the value of the selected <option /> directly to the function like this:

_x000D_
_x000D_
function myFunction(chosen) {_x000D_
  console.log(chosen);_x000D_
}
_x000D_
<select onChange="myFunction(this.options[this.selectedIndex].value)">_x000D_
  <option value="1">Text 1</option>_x000D_
  <option value="2">Text 2</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

ie8 var w= window.open() - "Message: Invalid argument."

I also meet this issue while I used the following code:

window.open('test.html','Window title','width=1200,height=800,scrollbars=yes');

but when I delete the blank space of the "Window title" the below code is working:

window.open('test.html','Windowtitle','width=1200,height=800,scrollbars=yes');

postgresql - replace all instances of a string within text field

The Regular Expression Way

If you need stricter replacement matching, PostgreSQL's regexp_replace function can match using POSIX regular expression patterns. It has the syntax regexp_replace(source, pattern, replacement [, flags ]).

I will use flags i and g for case-insensitive and global matching, respectively. I will also use \m and \M to match the beginning and the end of a word, respectively.

There are usually quite a few gotchas when performing regex replacment. Let's see how easy it is to replace a cat with a dog.

SELECT regexp_replace('Cat bobcat cat cats catfish', 'cat', 'dog');
-->                    Cat bobdog cat cats catfish

SELECT regexp_replace('Cat bobcat cat cats catfish', 'cat', 'dog', 'i');
-->                    dog bobcat cat cats catfish

SELECT regexp_replace('Cat bobcat cat cats catfish', 'cat', 'dog', 'g');
-->                    Cat bobdog dog dogs dogfish

SELECT regexp_replace('Cat bobcat cat cats catfish', 'cat', 'dog', 'gi');
-->                    dog bobdog dog dogs dogfish

SELECT regexp_replace('Cat bobcat cat cats catfish', '\mcat', 'dog', 'gi');
-->                    dog bobcat dog dogs dogfish

SELECT regexp_replace('Cat bobcat cat cats catfish', 'cat\M', 'dog', 'gi');
-->                    dog bobdog dog cats catfish

SELECT regexp_replace('Cat bobcat cat cats catfish', '\mcat\M', 'dog', 'gi');
-->                    dog bobcat dog cats catfish

SELECT regexp_replace('Cat bobcat cat cats catfish', '\mcat(s?)\M', 'dog\1', 'gi');
-->                    dog bobcat dog dogs catfish

Even after all of that, there is at least one unresolved condition. For example, sentences that begin with "Cat" will be replaced with lower-case "dog" which break sentence capitalization.

Check out the current PostgreSQL pattern matching docs for all the details.

Update entire column with replacement text

Given my examples, maybe the safest option would be:

UPDATE table SET field = regexp_replace(field, '\mcat\M', 'dog', 'gi');

jquery.ajax Access-Control-Allow-Origin

At my work we have our restful services on a different port number and the data resides in db2 on a pair of AS400s. We typically use the $.getJSON AJAX method because it easily returns JSONP using the ?callback=? without having any issues with CORS.

data ='USER=<?echo trim($USER)?>' +
         '&QRYTYPE=' + $("input[name=QRYTYPE]:checked").val();

        //Call the REST program/method returns: JSONP 
        $.getJSON( "http://www.stackoverflow.com/rest/resttest?callback=?",data)
        .done(function( json ) {        

              //  loading...
                if ($.trim(json.ERROR) != '') {
                    $("#error-msg").text(message).show();
                }
                else{
                    $(".error").hide();
                    $("#jsonp").text(json.whatever);

                }

        })  
        .fail(function( jqXHR, textStatus, error ) {
        var err = textStatus + ", " + error;
        alert('Unable to Connect to Server.\n Try again Later.\n Request Failed: ' + err);
        });     

Fast way to concatenate strings in nodeJS/JavaScript

There is not really any other way in JavaScript to concatenate strings.
You could theoretically use .concat(), but that's way slower than just +

Libraries are more often than not slower than native JavaScript, especially on basic operations like string concatenation, or numerical operations.

Simply put: + is the fastest.

What does ON [PRIMARY] mean?

It refers to which filegroup the object you are creating resides on. So your Primary filegroup could reside on drive D:\ of your server. you could then create another filegroup called Indexes. This filegroup could reside on drive E:\ of your server.

Stopword removal with NLTK

@alvas has a good answer. But again it depends on the nature of the task, for example in your application you want to consider all conjunction e.g. and, or, but, if, while and all determiner e.g. the, a, some, most, every, no as stop words considering all others parts of speech as legitimate, then you might want to look into this solution which use Part-of-Speech Tagset to discard words, Check table 5.1:

import nltk

STOP_TYPES = ['DET', 'CNJ']

text = "some data here "
tokens = nltk.pos_tag(nltk.word_tokenize(text))
good_words = [w for w, wtype in tokens if wtype not in STOP_TYPES]

Multiple file extensions in OpenFileDialog

Try:

Filter = "BMP|*.bmp|GIF|*.gif|JPG|*.jpg;*.jpeg|PNG|*.png|TIFF|*.tif;*.tiff"

Then do another round of copy/paste of all the extensions (joined together with ; as above) for "All graphics types":

Filter = "BMP|*.bmp|GIF|*.gif|JPG|*.jpg;*.jpeg|PNG|*.png|TIFF|*.tif;*.tiff|"
       + "All Graphics Types|*.bmp;*.jpg;*.jpeg;*.png;*.tif;*.tiff"

How to implement Rate It feature in Android App

As you see from the other post you have linked, there isn't a way for the app to know if the user has left a review or not. And for good reason.

Think about it, if an app could tell if the user has left a review or not, the developer could restrict certain features that would only be unlocked if the user leaves a 5/5 rating. This would lead the other users of Google Play to not trust the reviews and would undermine the rating system.

The alternative solutions I have seen is that the app reminds the user to submit a rating whenever the app is opened a specific number of times, or a set interval. For example, on every 10th time the app is opened, ask the user to leave a rating and provide a "already done" and "remind me later" button. Keep showing this message if the user has chosen to remind him/her later. Some other apps developers show this message with an increasing interval (like, 5, 10, 15nth time the app is opened), because if a user hasn't left a review on the, for example, 100th time the app was opened, it's probably likely s/he won't be leaving one.

This solution isn't perfect, but I think it's the best you have for now. It does lead you to trust the user, but realize that the alternative would mean a potentially worse experience for everyone in the app market.

Difference between map and collect in Ruby?

#collect is actually an alias for #map. That means the two methods can be used interchangeably, and effect the same behavior.

iOS 7 status bar overlapping UI

Write the following code inside AppDelegate.m in didFinishLaunchingWithOptions event (exactly before its last line of code "return YES;" ) :

if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7) 
{
    [application setStatusBarHidden:YES withAnimation:UIStatusBarAnimationNone];
}

I'll wait for your feedback! :)

Terminating idle mysql connections

I don't see any problem, unless you are not managing them using a connection pool.

If you use connection pool, these connections are re-used instead of initiating new connections. so basically, leaving open connections and re-use them it is less problematic than re-creating them each time.

Calling remove in foreach loop in Java

It's better to use an Iterator when you want to remove element from a list

because the source code of remove is

if (numMoved > 0)
    System.arraycopy(elementData, index+1, elementData, index,
             numMoved);
elementData[--size] = null;

so ,if you remove an element from the list, the list will be restructure ,the other element's index will be changed, this can result something that you want to happened.

How to create a date and time picker in Android?

You can use one of DatePicker library wdullaer/MaterialDateTimePicker

  • First show DatePicker.

    private void showDatePicker() {
    Calendar now = Calendar.getInstance();
    DatePickerDialog dpd = DatePickerDialog.newInstance(
            HomeActivity.this,
            now.get(Calendar.YEAR),
            now.get(Calendar.MONTH),
            now.get(Calendar.DAY_OF_MONTH)
    );
    dpd.show(getFragmentManager(), "Choose Date:");
    }
    
  • Then onDateSet callback store date & show TimePicker

    @Override
    public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {
    Calendar cal = Calendar.getInstance();
    cal.set(year, monthOfYear, dayOfMonth);
    filter.setDate(cal.getTime());
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            showTimePicker();
        }
    },500);
    }
    
  • On onTimeSet callback store time

     @Override
     public void onTimeSet(RadialPickerLayout view, int hourOfDay, int minute) {
    Calendar cal = Calendar.getInstance();
    if(filter.getDate()!=null)
        cal.setTime(filter.getDate());
    cal.set(Calendar.HOUR_OF_DAY,hourOfDay);
    cal.set(Calendar.MINUTE,minute);
    }
    

Getting multiple values with scanf()

You can do this with a single call, like so:

scanf( "%i %i %i %i", &minx, &maxx, &miny, &maxy);

httpd: Could not reliably determine the server's fully qualified domain name, using 127.0.0.1 for ServerName

Make sure you're editing the right httpd.conf file, then the error about unreliable server's domain name should be gone (this is the most common mistake).

To locate your httpd.conf Apache configuration file, run:

apachectl -t -D DUMP_INCLUDES

Then edit the file and uncomment or change ServerName line into:

ServerName localhost

Then restart your apache by: sudo apachectl restart

Drop columns whose name contains a specific string from pandas DataFrame

Solution when dropping a list of column names containing regex. I prefer this approach because I'm frequently editing the drop list. Uses a negative filter regex for the drop list.

drop_column_names = ['A','B.+','C.*']
drop_columns_regex = '^(?!(?:'+'|'.join(drop_column_names)+')$)'
print('Dropping columns:',', '.join([c for c in df.columns if re.search(drop_columns_regex,c)]))
df = df.filter(regex=drop_columns_regex,axis=1)

List comprehension vs. lambda + filter

generally filter is slightly faster if using a builtin function.

I would expect the list comprehension to be slightly faster in your case

jQuery toggle animation

I dont think adding dual functions inside the toggle function works for a registered click event (Unless I'm missing something)

For example:

$('.btnName').click(function() {
 top.$('#panel').toggle(function() {
   $(this).animate({ 
     // style change
   }, 500);
   },
   function() {
   $(this).animate({ 
     // style change back
   }, 500);
 });

PHP mail not working for some reason

The mail function do not guarantee the actual delivery of mail. All it do is to pass the message to external program (usually sendmail). You need a properly configured SMTP server in order for this to work. Also keep in mind it does not support SMTP authentication. You may check out the PEAR::Mail library of SwiftMailer, both of them give you more options.

How do I find which rpm package supplies a file I'm looking for?

You can do this alike here but with your package. In my case, it was lsb_release

Run: yum whatprovides lsb_release

Response:

redhat-lsb-core-4.1-24.el7.i686 : LSB Core module support
Repo        : rhel-7-server-rpms
Matched from:
Filename    : /usr/bin/lsb_release

redhat-lsb-core-4.1-24.el7.x86_64 : LSB Core module support
Repo        : rhel-7-server-rpms
Matched from:
Filename    : /usr/bin/lsb_release

redhat-lsb-core-4.1-27.el7.i686 : LSB Core module support
Repo        : rhel-7-server-rpms
Matched from:
Filename    : /usr/bin/lsb_release

redhat-lsb-core-4.1-27.el7.x86_64 : LSB Core module support
Repo        : rhel-7-server-rpms
Matched from:
Filename    : /usr/bin/lsb_release`

Run to install: yum install redhat-lsb-core

The package name SHOULD be without number and system type so yum packager can choose what is best for him.

fatal: git-write-tree: error building trees

This happened for me when I was trying to stash my changes, but then my changes had conflicts with my branch's current state.

So I did git reset --mixed and then resolved the git conflict and stashed again.

How to use MySQLdb with Python and Django in OSX 10.6?

The error raised here is in importing the python module. This can be solved by adding the python site-packages folder to the environment variable $PYTHONPATH on OS X. So we can add the following command to the .bash_profile file:

export PYTHONPATH="$PYTHONPATH:/usr/local/lib/pythonx.x/site-packages/"

*replace x.x with the python version you are using

JavaScript replace \n with <br />

You need the /g for global matching

replace(/\n/g, "<br />");

This works for me for \n - see this answer if you might have \r\n

NOTE: The dupe is the most complete answer for any combination of \r\n, \r or \n

_x000D_
_x000D_
var messagetoSend = document.getElementById('x').value.replace(/\n/g, "<br />");_x000D_
console.log(messagetoSend);
_x000D_
<textarea id="x" rows="9">_x000D_
    Line 1_x000D_
    _x000D_
    _x000D_
    Line 2_x000D_
    _x000D_
    _x000D_
    _x000D_
    _x000D_
    Line 3_x000D_
</textarea>
_x000D_
_x000D_
_x000D_

UPDATE

It seems some visitors of this question have text with the breaklines escaped as

some text\r\nover more than one line"

In that case you need to escape the slashes:

replace(/\\r\\n/g, "<br />");

NOTE: All browsers will ignore \r in a string when rendering.

appending array to FormData and send via AJAX

Next version valid for model containing arays of simple values:

function convertModelToFormData(val, formData = new FormData(), namespace = '') {
    if((typeof val !== 'undefined') && (val !== null)) {
        if(val instanceof Date) {
            formData.append(namespace, val.toISOString());
        } else if(val instanceof Array) {
            for(let element of val) {
                convertModelToFormData(element, formData, namespace + '[]');
            }
        } else if(typeof val === 'object' && !(val instanceof File)) {
            for (let propertyName in val) {
                if(val.hasOwnProperty(propertyName)) {
                    convertModelToFormData(val[propertyName], formData, namespace ? namespace + '[' + propertyName + ']' : propertyName);
                }
            }
        } else {
            formData.append(namespace, val.toString());
        }
    }
    return formData;
}

What's the difference between window.location= and window.location.replace()?

window.location adds an item to your history in that you can (or should be able to) click "Back" and go back to the current page.

window.location.replace replaces the current history item so you can't go back to it.

See window.location:

assign(url): Load the document at the provided URL.

replace(url):Replace the current document with the one at the provided URL. The difference from the assign() method is that after using replace() the current page will not be saved in session history, meaning the user won't be able to use the Back button to navigate to it.

Oh and generally speaking:

window.location.href = url;

is favoured over:

window.location = url;

How do I get the current username in .NET using C#?

Use:

System.Security.Principal.WindowsIdentity.GetCurrent().Name

That will be the logon name.

CSS Grid Layout not working in IE11 even with prefixes

To support IE11 with auto-placement, I converted grid to table layout every time I used the grid layout in 1 dimension only. I also used margin instead of grid-gap.

The result is the same, see how you can do it here https://jsfiddle.net/hp95z6v1/3/

How to list only files and not directories of a directory Bash?

{ find . -maxdepth 1 -type f | xargs ls -1t | less; }

added xargs to make it works, and used -1 instead of -l to show only filenames without additional ls info

Https Connection Android

I make this class and found

package com.example.fakessl;

import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;

import android.util.Log;

public class CertificadoAceptar {
    private static TrustManager[] trustManagers;

    public static class _FakeX509TrustManager implements
            javax.net.ssl.X509TrustManager {
        private static final X509Certificate[] _AcceptedIssuers = new X509Certificate[] {};

        public void checkClientTrusted(X509Certificate[] arg0, String arg1)
                throws CertificateException {
        }

        public void checkServerTrusted(X509Certificate[] arg0, String arg1)
                throws CertificateException {
        }

        public boolean isClientTrusted(X509Certificate[] chain) {
            return (true);
        }

        public boolean isServerTrusted(X509Certificate[] chain) {
            return (true);
        }

        public X509Certificate[] getAcceptedIssuers() {
            return (_AcceptedIssuers);
        }
    }

    public static void allowAllSSL() {

        javax.net.ssl.HttpsURLConnection
                .setDefaultHostnameVerifier(new HostnameVerifier() {
                    public boolean verify(String hostname, SSLSession session) {
                        return true;
                    }
                });

        javax.net.ssl.SSLContext context = null;

        if (trustManagers == null) {
            trustManagers = new javax.net.ssl.TrustManager[] { new _FakeX509TrustManager() };
        }

        try {
            context = javax.net.ssl.SSLContext.getInstance("TLS");
            context.init(null, trustManagers, new SecureRandom());
        } catch (NoSuchAlgorithmException e) {
            Log.e("allowAllSSL", e.toString());
        } catch (KeyManagementException e) {
            Log.e("allowAllSSL", e.toString());
        }
        javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(context
                .getSocketFactory());
    }
}

in you code white this

CertificadoAceptar ca = new CertificadoAceptar();
ca.allowAllSSL();
HttpsTransportSE Transport = new HttpsTransportSE("iphost or host name", 8080, "/WS/wsexample.asmx?WSDL", 30000);

What's the best way to iterate an Android Cursor?

How about using foreach loop:

Cursor cursor;
for (Cursor c : CursorUtils.iterate(cursor)) {
    //c.doSth()
}

However my version of CursorUtils should be less ugly, but it automatically closes the cursor:

public class CursorUtils {
public static Iterable<Cursor> iterate(Cursor cursor) {
    return new IterableWithObject<Cursor>(cursor) {
        @Override
        public Iterator<Cursor> iterator() {
            return new IteratorWithObject<Cursor>(t) {
                @Override
                public boolean hasNext() {
                    t.moveToNext();
                    if (t.isAfterLast()) {
                        t.close();
                        return false;
                    }
                    return true;
                }
                @Override
                public Cursor next() {
                    return t;
                }
                @Override
                public void remove() {
                    throw new UnsupportedOperationException("CursorUtils : remove : ");
                }
                @Override
                protected void onCreate() {
                    t.moveToPosition(-1);
                }
            };
        }
    };
}

private static abstract class IteratorWithObject<T> implements Iterator<T> {
    protected T t;
    public IteratorWithObject(T t) {
        this.t = t;
        this.onCreate();
    }
    protected abstract void onCreate();
}

private static abstract class IterableWithObject<T> implements Iterable<T> {
    protected T t;
    public IterableWithObject(T t) {
        this.t = t;
    }
}
}

How to find the first and second maximum number?

If you want the second highest number you can use

=LARGE(E4:E9;2)

although that doesn't account for duplicates so you could get the same result as the Max

If you want the largest number that is smaller than the maximum number you can use this version

=LARGE(E4:E9;COUNTIF(E4:E9;MAX(E4:E9))+1)

CSS to hide INPUT BUTTON value text

Have you tried setting the text-indent property to something like -999em? That's a good way to 'hide' text.

Or you can set the font-size to 0, which would work too.

http://www.productivedreams.com/ie-not-intepreting-text-indent-on-submit-buttons/

How to remove newlines from beginning and end of a string?

If your string is potentially null, consider using StringUtils.trim() - the null-safe version of String.trim().

fatal: The current branch master has no upstream branch

on a very simple side, once you have other branches, you can't just use for pushing a branch

git push

But you need to specify the branch now, even if you have checkout the branch you want to push, so

git push origin <feature_branch>

Where can be even the master branch

Python constructor and default value

Let's illustrate what's happening here:

Python 3.1.2 (r312:79147, Sep 27 2010, 09:45:41) 
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class Foo:
...     def __init__(self, x=[]):
...         x.append(1)
... 
>>> Foo.__init__.__defaults__
([],)
>>> f = Foo()
>>> Foo.__init__.__defaults__
([1],)
>>> f2 = Foo()
>>> Foo.__init__.__defaults__
([1, 1],)

You can see that the default arguments are stored in a tuple which is an attribute of the function in question. This actually has nothing to do with the class in question and goes for any function. In python 2, the attribute will be func.func_defaults.

As other posters have pointed out, you probably want to use None as a sentinel value and give each instance it's own list.

Using :before and :after CSS selector to insert Html

content doesn't support HTML, only text. You should probably use javascript, jQuery or something like that.

Another problem with your code is " inside a " block. You should mix ' and " (class='headingDetail').

If content did support HTML you could end up in an infinite loop where content is added inside content.

The tilde operator in Python

One should note that in the case of array indexing, array[~i] amounts to reversed_array[i]. It can be seen as indexing starting from the end of the array:

[0, 1, 2, 3, 4, 5, 6, 7, 8]
    ^                 ^
    i                ~i

Recommended way to save uploaded files in a servlet application

Store it anywhere in an accessible location except of the IDE's project folder aka the server's deploy folder, for reasons mentioned in the answer to Uploaded image only available after refreshing the page:

  1. Changes in the IDE's project folder does not immediately get reflected in the server's work folder. There's kind of a background job in the IDE which takes care that the server's work folder get synced with last updates (this is in IDE terms called "publishing"). This is the main cause of the problem you're seeing.

  2. In real world code there are circumstances where storing uploaded files in the webapp's deploy folder will not work at all. Some servers do (either by default or by configuration) not expand the deployed WAR file into the local disk file system, but instead fully in the memory. You can't create new files in the memory without basically editing the deployed WAR file and redeploying it.

  3. Even when the server expands the deployed WAR file into the local disk file system, all newly created files will get lost on a redeploy or even a simple restart, simply because those new files are not part of the original WAR file.

It really doesn't matter to me or anyone else where exactly on the local disk file system it will be saved, as long as you do not ever use getRealPath() method. Using that method is in any case alarming.

The path to the storage location can in turn be definied in many ways. You have to do it all by yourself. Perhaps this is where your confusion is caused because you somehow expected that the server does that all automagically. Please note that @MultipartConfig(location) does not specify the final upload destination, but the temporary storage location for the case file size exceeds memory storage threshold.

So, the path to the final storage location can be definied in either of the following ways:

  • Hardcoded:

      File uploads = new File("/path/to/uploads");
    
  • Environment variable via SET UPLOAD_LOCATION=/path/to/uploads:

      File uploads = new File(System.getenv("UPLOAD_LOCATION"));
    
  • VM argument during server startup via -Dupload.location="/path/to/uploads":

      File uploads = new File(System.getProperty("upload.location"));
    
  • *.properties file entry as upload.location=/path/to/uploads:

      File uploads = new File(properties.getProperty("upload.location"));
    
  • web.xml <context-param> with name upload.location and value /path/to/uploads:

      File uploads = new File(getServletContext().getInitParameter("upload.location"));
    
  • If any, use the server-provided location, e.g. in JBoss AS/WildFly:

      File uploads = new File(System.getProperty("jboss.server.data.dir"), "uploads");
    

Either way, you can easily reference and save the file as follows:

File file = new File(uploads, "somefilename.ext");

try (InputStream input = part.getInputStream()) {
    Files.copy(input, file.toPath());
}

Or, when you want to autogenerate an unique file name to prevent users from overwriting existing files with coincidentally the same name:

File file = File.createTempFile("somefilename-", ".ext", uploads);

try (InputStream input = part.getInputStream()) {
    Files.copy(input, file.toPath(), StandardCopyOption.REPLACE_EXISTING);
}

How to obtain part in JSP/Servlet is answered in How to upload files to server using JSP/Servlet? and how to obtain part in JSF is answered in How to upload file using JSF 2.2 <h:inputFile>? Where is the saved File?

Note: do not use Part#write() as it interprets the path relative to the temporary storage location defined in @MultipartConfig(location).

See also:

READ_EXTERNAL_STORAGE permission for Android

Please Check below code that using that You can find all Music Files from sdcard :

public class MainActivity extends Activity{

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_animations);
    getAllSongsFromSDCARD();

}

public void getAllSongsFromSDCARD() {
    String[] STAR = { "*" };
    Cursor cursor;
    Uri allsongsuri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
    String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";

    cursor = managedQuery(allsongsuri, STAR, selection, null, null);

    if (cursor != null) {
        if (cursor.moveToFirst()) {
            do {
                String song_name = cursor
                        .getString(cursor
                                .getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME));
                int song_id = cursor.getInt(cursor
                        .getColumnIndex(MediaStore.Audio.Media._ID));

                String fullpath = cursor.getString(cursor
                        .getColumnIndex(MediaStore.Audio.Media.DATA));

                String album_name = cursor.getString(cursor
                        .getColumnIndex(MediaStore.Audio.Media.ALBUM));
                int album_id = cursor.getInt(cursor
                        .getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));

                String artist_name = cursor.getString(cursor
                        .getColumnIndex(MediaStore.Audio.Media.ARTIST));
                int artist_id = cursor.getInt(cursor
                        .getColumnIndex(MediaStore.Audio.Media.ARTIST_ID));
                System.out.println("sonng name"+fullpath);
            } while (cursor.moveToNext());

        }
        cursor.close();
    }
}


}

I have also added following line in the AndroidManifest.xml file as below:

<uses-sdk
    android:minSdkVersion="16"
    android:targetSdkVersion="17" />

<uses-permission android:name="android.permission.MEDIA_CONTENT_CONTROL" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

C# equivalent of C++ vector, with contiguous memory?

use List<T>. Internally it uses arrays and arrays do use contiguous memory.

PHP Notice: Undefined offset: 1 with array when reading data

In your code: $parts = array_map('trim', explode(':', $line_of_text, 2)); You have ":" as separator. If you use another separator in file, then you will get an "Undefined offset: 1" but not "Undefined offset: 0" All information will be in $parts[0] but no information in $parts[1] or [2] etc. Try to echo $part[0]; echo $part[1]; you will see the information.

Android overlay a view ontop of everything?

You can use bringToFront:

    View view=findViewById(R.id.btnStartGame);
    view.bringToFront();

How to remove old Docker containers

Remove all containers created from a certain image:

docker rm  $(docker ps -a | awk '/myimage:mytag/{print $1}')

Is there a developers api for craigslist.org

The closest I have been able to find is called 3taps. 3taps was sued by Craigslist with the result that "access to public data on a public website can be selectively censored by blacklisting certain viewers (i.e. competitors)", and thus states that "3taps will therefore access the very same data exclusively from public sources that retain open and equal access rights to public data".

VBA - If a cell in column A is not blank the column B equals

A simpler way to do this would be:

Sub populateB()

For Each Cel in Range("A1:A100")
    If Cel.value <> "" Then Cel.Offset(0, 1).value = "Your Text"
Next

End Sub

What's the difference between Apache's Mesos and Google's Kubernetes

I like this short video here mesos learning material

with bare metal clusters, you would need to spawn stacks like HDFS, SPARK, MR etc... so if you launch tasks related to these using only bare metal cluster management, there will be a lot cold starting time.

with mesos, you can install these services on top of the bare metals and you can avoid the bring up time of those base services. This is something mesos does well. and can be utilised by kubernetes building on top of it.

C# if/then directives for debug vs release

I prefer checking it like this over looking for #define directives:

if (System.Diagnostics.Debugger.IsAttached)
{
   //...
}
else
{
   //...
}

With the caveat that of course you could compile and deploy something in debug mode but still not have the debugger attached.

selecting rows with id from another table

You can use a subquery:

SELECT *
FROM terms
WHERE id IN (SELECT term_id FROM terms_relation WHERE taxonomy='categ');

and if you need to show all columns from both tables:

SELECT t.*, tr.*
FROM terms t, terms_relation tr
WHERE t.id = tr.term_id
AND tr.taxonomy='categ'

Best way to store date/time in mongodb

One datestamp is already in the _id object, representing insert time

So if the insert time is what you need, it's already there:

Login to mongodb shell

ubuntu@ip-10-0-1-223:~$ mongo 10.0.1.223
MongoDB shell version: 2.4.9
connecting to: 10.0.1.223/test

Create your database by inserting items

> db.penguins.insert({"penguin": "skipper"})
> db.penguins.insert({"penguin": "kowalski"})
> 

Lets make that database the one we are on now

> use penguins
switched to db penguins

Get the rows back:

> db.penguins.find()
{ "_id" : ObjectId("5498da1bf83a61f58ef6c6d5"), "penguin" : "skipper" }
{ "_id" : ObjectId("5498da28f83a61f58ef6c6d6"), "penguin" : "kowalski" }

Get each row in yyyy-MM-dd HH:mm:ss format:

> db.penguins.find().forEach(function (doc){ d = doc._id.getTimestamp(); print(d.getFullYear()+"-"+(d.getMonth()+1)+"-"+d.getDate() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds()) })
2014-12-23 3:4:41
2014-12-23 3:4:53

If that last one-liner confuses you I have a walkthrough on how that works here: https://stackoverflow.com/a/27613766/445131

Cannot deserialize the current JSON array (e.g. [1,2,3])

I think the problem you're having is that your JSON is a list of objects when it comes in and it doesnt directly relate to your root class.

var content would look something like this (i assume):

[
  {
    "id": 3636,
    "is_default": true,
    "name": "Unit",
    "quantity": 1,
    "stock": "100000.00",
    "unit_cost": "0"
  },
  {
    "id": 4592,
    "is_default": false,
    "name": "Bundle",
    "quantity": 5,
    "stock": "100000.00",
    "unit_cost": "0"
  }
]

Note: make use of http://jsonviewer.stack.hu/ to format your JSON.

So if you try the following it should work:

  public static List<RootObject> GetItems(string user, string key, Int32 tid, Int32 pid)
    {
        // Customize URL according to geo location parameters
        var url = string.Format(uniqueItemUrl, user, key, tid, pid);

        // Syncronious Consumption
        var syncClient = new WebClient();

        var content = syncClient.DownloadString(url);

        return JsonConvert.DeserializeObject<List<RootObject>>(content);

    }

You will need to then iterate if you don't wish to return a list of RootObject.


I went ahead and tested this in a Console app, worked fine.

enter image description here

Ternary operators in JavaScript without an "else"

First of all, a ternary expression is not a replacement for an if/else construct - it's an equivalent to an if/else construct that returns a value. That is, an if/else clause is code, a ternary expression is an expression, meaning that it returns a value.

This means several things:

  • use ternary expressions only when you have a variable on the left side of the = that is to be assigned the return value
  • only use ternary expressions when the returned value is to be one of two values (or use nested expressions if that is fitting)
  • each part of the expression (after ? and after : ) should return a value without side effects (the expression x = true returns true as all expressions return the last value, but it also changes x without x having any effect on the returned value)

In short - the 'correct' use of a ternary expression is

var resultofexpression = conditionasboolean ? truepart: falsepart;

Instead of your example condition ? x=true : null ;, where you use a ternary expression to set the value of x, you can use this:

 condition && (x = true);

This is still an expression and might therefore not pass validation, so an even better approach would be

 void(condition && x = true);

The last one will pass validation.

But then again, if the expected value is a boolean, just use the result of the condition expression itself

var x = (condition); // var x = (foo == "bar");

UPDATE

In relation to your sample, this is probably more appropriate:

defaults.slideshowWidth = defaults.slideshowWidth || obj.find('img').width()+'px';

DISTINCT clause with WHERE

Try:

SELECT * FROM table GROUP BY email

  • This returns all rows with a unique email taken by the first ID appearance (if that makes sense)
  • I assume this is what you were looking since I had about the same question but none of these answers worked for me.

CSS rule to apply only if element has BOTH classes

Below applies to all tags with the following two classes

.abc.xyz {  
  width: 200px !important;
}

applies to div tags with the following two classes

div.abc.xyz {  
  width: 200px !important;
}

If you wanted to modify this using jQuery

$(document).ready(function() {
  $("div.abc.xyz").width("200px");
});

Cannot read property 'push' of undefined when combining arrays

order is an Object, not an Array().

push() is for arrays.

Refer to this post

Try this though(but your subobjects have to be Arrays()):

var order = new Array();

// initialize order; n = index
order[n] = new Array();

// and then you can perform push()
order[n].push(some_value);

Or you can just use order as an array of non-array objects:

var order = new Array();

order.push(a[n]);

Disable future dates after today in Jquery Ui Datepicker

Change maxDate to current date

maxDate: new Date()

It will set current date as maximum value.

Can you install and run apps built on the .NET framework on a Mac?

Yes you can!

As of November 2016, Microsoft now has integrated .NET Core in it's official .NET Site

They even have a new Visual Studio app that runs on MacOS

How to set adaptive learning rate for GradientDescentOptimizer?

Tensorflow provides an op to automatically apply an exponential decay to a learning rate tensor: tf.train.exponential_decay. For an example of it in use, see this line in the MNIST convolutional model example. Then use @mrry's suggestion above to supply this variable as the learning_rate parameter to your optimizer of choice.

The key excerpt to look at is:

# Optimizer: set up a variable that's incremented once per batch and
# controls the learning rate decay.
batch = tf.Variable(0)

learning_rate = tf.train.exponential_decay(
  0.01,                # Base learning rate.
  batch * BATCH_SIZE,  # Current index into the dataset.
  train_size,          # Decay step.
  0.95,                # Decay rate.
  staircase=True)
# Use simple momentum for the optimization.
optimizer = tf.train.MomentumOptimizer(learning_rate,
                                     0.9).minimize(loss,
                                                   global_step=batch)

Note the global_step=batch parameter to minimize. That tells the optimizer to helpfully increment the 'batch' parameter for you every time it trains.

SQLite error 'attempt to write a readonly database' during insert?

In summary, I've fixed the problem by putting the database file (* .db) in a subfolder.

  • The subfolder and the database file within it must be a member of the www-data group.
  • In the www-data group, you must have the right to write to the subfolder and the database file.

How to use variables in a command in sed?

Say:

sed "s|\$ROOT|${HOME}|" abc.sh

Note:

  • Use double quotes so that the shell would expand variables.
  • Use a separator different than / since the replacement contains /
  • Escape the $ in the pattern since you don't want to expand it.

EDIT: In order to replace all occurrences of $ROOT, say

sed "s|\$ROOT|${HOME}|g" abc.sh

Copy text from nano editor to shell

Much easier method:
$ cat my_file

Ctrl+Shift+c to copy the required output from the terminal

Ctrl+Shift+v to paste it wherever you like

PHP Warning: PHP Startup: ????????: Unable to initialize module

This is just describing why I had this issue in case someone finds it helpful.

My problem was that I had upgraded php with homebrew and had forced at some point the variable PHP_INI_SCAN_DIR in my profile or bashrc file so it was pointing to the old php version. Removed that line and fixed.

.NET data structures: ArrayList, List, HashTable, Dictionary, SortedList, SortedDictionary -- Speed, memory, and when to use each?

I sympathise with the question - I too found (find?) the choice bewildering, so I set out scientifically to see which data structure is the fastest (I did the test using VB, but I imagine C# would be the same, since both languages do the same thing at the CLR level). You can see some benchmarking results conducted by me here (there's also some discussion of which data type is best to use in which circumstances).

Cannot create PoolableConnectionFactory

This happens because firewall blocks the database connection.

Disable the firewall and then try running the program again. It worked for me... :D

What is a "slug" in Django?

A "slug" is a way of generating a valid URL, generally using data already obtained. For instance, a slug uses the title of an article to generate a URL. I advise to generate the slug by means of a function, given the title (or another piece of data), rather than setting it manually.

An example:

<title> The 46 Year Old Virgin </title>
<content> A silly comedy movie </content>
<slug> the-46-year-old-virgin </slug>

Now let's pretend that we have a Django model such as:

class Article(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField(max_length=1000)
    slug = models.SlugField(max_length=40)

How would you reference this object with a URL and with a meaningful name? You could for instance use Article.id so the URL would look like this:

www.example.com/article/23

Or, you might want to reference the title like this:

www.example.com/article/The 46 Year Old Virgin

Since spaces aren't valid in URLs, they must be replaced by %20, which results in:

www.example.com/article/The%2046%20Year%20Old%20Virgin

Both attempts are not resulting in very meaningful, easy-to-read URL. This is better:

www.example.com/article/the-46-year-old-virgin

In this example, the-46-year-old-virgin is a slug: it is created from the title by down-casing all letters, and replacing spaces by hyphens -.

Also see the URL of this very web page for another example.

Transparent CSS background color

In this case background-color:rgba(0,0,0,0.5); is the best way. For example: background-color:rgba(0,0,0,opacity option);

How to create Gmail filter searching for text only at start of subject line?

I was wondering how to do this myself; it seems Gmail has since silently implemented this feature. I created the following filter:

Matches: subject:([test])
Do this: Skip Inbox

And then I sent a message with the subject

[test] foo

And the message was archived! So it seems all that is necessary is to create a filter for the subject prefix you wish to handle.

Convert hex color value ( #ffffff ) to integer value

Based on CQM's answer and on ovokerie-ogbeta's answer to another question I've come up with this solution:

if (colorAsString.length() == 4) { // #XXX
    colorAsString = colorAsString.replaceAll("#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])", "#$1$1$2$2$3$3");
}

int color = Color.parseColor(colorAsString);

How to set image on QPushButton?

You can also use:

button.setStyleSheet("qproperty-icon: url(:/path/to/images.png);");

Note: This is a little hacky. You should use this only as last resort. Icons should be set from C++ code or Qt Designer.

How to use MD5 in javascript to transmit a password

I would suggest you to use CryptoJS in this case.

Basically CryptoJS is a growing collection of standard and secure cryptographic algorithms implemented in JavaScript using best practices and patterns. They are fast, and they have a consistent and simple interface.

So In case you want calculate hash(MD5) of your password string then do as follows :

<script src="http://crypto-js.googlecode.com/svn/tags/3.0.2/build/rollups/md5.js"></script>
<script>
    var passhash = CryptoJS.MD5(password).toString();

    $.post(
      'includes/login.php', 
      { user: username, pass: passhash },
      onLogin, 
      'json' );
</script>

So this script will post hash of your password string to the server.

For further info and support on other hash calculating algorithms you can visit at:

http://code.google.com/p/crypto-js/

How can I pretty-print JSON in a shell script?

UPDATE I'm using jq now as suggested in another answer. It's extremely powerful at filtering JSON, but, at its most basic, also an awesome way to pretty print JSON for viewing.

jsonpp is a very nice command line JSON pretty printer.

From the README:

Pretty print web service responses like so:

curl -s -L http://<!---->t.co/tYTq5Pu | jsonpp

and make beautiful the files running around on your disk:

jsonpp data/long_malformed.json

If you're on Mac OS X, you can brew install jsonpp. If not, you can simply copy the binary to somewhere in your $PATH.

How to insert an image in python

Install PIL(Python Image Library) :

then:

from PIL import Image
myImage = Image.open("your_image_here");
myImage.show();

MySQL and GROUP_CONCAT() maximum length

The correct syntax is mysql> SET @@global.group_concat_max_len = integer;
If you do not have the privileges to do this on the server where your database resides then use a query like:
mySQL="SET @@session.group_concat_max_len = 10000;"or a different value.
Next line:
SET objRS = objConn.Execute(mySQL)  your variables may be different.
then
mySQL="SELECT GROUP_CONCAT(......);" etc
I use the last version since I do not have the privileges to change the default value of 1024 globally (using cPanel).
Hope this helps.

What's wrong with foreign keys?

I'll echo what Dmitriy said, but adding on a point.

I worked on a batch billing system that needed to insert large sets of rows on 30+ tables. We weren't allowed to do a data pump (Oracle) so we had to do bulk inserts. Those tables had foreign keys on them, but we had already ensured that they were not breaking any relationships.

Before insert, we disable the foreign key constraints so that Oracle doesn't take forever doing the inserts. After the insert is successful, we re-enable the constraints.

PS: In a large database with many foreign keys and child row data for a single record, sometimes foreign keys can be bad, and you may want to disallow cascading deletes. For us in the billing system, it would take too long and be too taxing on the database if we did cascading deletes, so we just mark the record as bad with a field on the main driver (parent) table.

How do you use String.substringWithRange? (or, how do Ranges work in Swift?)

Rob Napier had already given a awesome answer using subscript. But i felt one drawback in that as there is no check for out of bound conditions. This can tend to crash. So i modified the extension and here it is

extension String {
    subscript (r: Range<Int>) -> String? { //Optional String as return value
        get {
            let stringCount = self.characters.count as Int
            //Check for out of boundary condition
            if (stringCount < r.endIndex) || (stringCount < r.startIndex){
                return nil
            }
            let startIndex = self.startIndex.advancedBy(r.startIndex)

            let endIndex = self.startIndex.advancedBy(r.endIndex - r.startIndex)

            return self[Range(start: startIndex, end: endIndex)]
        }
    }
}

Output below

var str2 = "Hello, World"

var str3 = str2[0...5]
//Hello,
var str4 = str2[0..<5]
//Hello
var str5 = str2[0..<15]
//nil

So i suggest always to check for the if let

if let string = str[0...5]
{
    //Manipulate your string safely
}

Inserting one list into another list in java?

100, it will hold the same references. Therefore if you make a change to a specific object in the list, it will affect the same object in anotherList.

Adding or removing objects in any of the list will not affect the other.

list and anotherList are two different instances, they only hold the same references of the objects "inside" them.

Read files from a Folder present in project

it depends where is your Data folder

To get the directory where the .exe file is:

AppDomain.CurrentDomain.BaseDirectory

To get the current directory:

Environment.CurrentDirectory

Then you can concatenate your directory path (@"\Data\Names.txt")

How to center links in HTML

Try doing a nav element with a ul element. Mine has a main above but I don't think you need it.

<main>
<nav>
<ul><li><a href="http//www.google.com">search</a>
<li><a href="http//www.google.com">search</a>
<li><a href="http//www.google.com">search</a>

The code is something like this.
When ever I put in the code it wouldn't work right so you need to fill in the blank,
then center it.

main
nav
ul> li> a>: href="link of choice":name of link:/a>

How do I clone a Django model instance object and save it to the database?

There is a package that can do this which creates a UI within the django admin site: https://github.com/RealGeeks/django-modelclone

pip install django-modelclone

Add "modelclone" to INSTALLED_APPS and import it within admin.py.

Then, whenever you want to make a model clonable, you just replace "admin.ModelAdmin" in the given admin model class "modelclone.ClonableModelAdmin". This results in a "Duplicate" button appearing within the instance details page for that given model.

Input mask for numeric and decimal

Now that I understand better what you need, here's what I propose. Add a keyup handler for your textbox that checks the textbox contents with this regex ^[0-9]{1,14}\.[0-9]{2}$ and if it doesn't match, make the background red or show a text or whatever you like. Here's the code to put in document.ready

$(document).ready(function() {
    $('selectorForTextbox').bind('keyup', function(e) {
        if (e.srcElement.value.match(/^[0-9]{1,14}\.[0-9]{2}$/) === null) {
            $(this).addClass('invalid');
        } else {
            $(this).removeClass('invalid');
        }
    });
});

Here's a JSFiddle of this in action. Also, do the same regex server side and if it doesn't match, the requirements have not been met. You can also do this check the onsubmit event and not let the user submit the page if the regex didn't match.

The reason for not enforcing the mask upon text inserting is that it complicates things a lot, e.g. as I mentioned in the comment, the user cannot begin entering the valid input since the beggining of it is not valid. It is possible though, but I suggest this instead.

Execute command on all files in a directory

I'm doing this on my raspberry pi from the command line by running:

for i in *;do omxplayer "$i";done

SQL Server - Case Statement

The query can be written slightly simpler, like this:

DECLARE @T INT = 2 

SELECT CASE 
         WHEN @T < 1 THEN 'less than one' 
         WHEN @T = 1 THEN 'one' 
         ELSE 'greater than one' 
       END T

Getting the actual usedrange

Readify made a very complete answer. Yet, I wanted to add the End statement, you can use:

Find the last used cell, before a blank in a Column:

Sub LastCellBeforeBlankInColumn()
Range("A1").End(xldown).Select
End Sub

Find the very last used cell in a Column:

Sub LastCellInColumn()
Range("A" & Rows.Count).End(xlup).Select
End Sub

Find the last cell, before a blank in a Row:

Sub LastCellBeforeBlankInRow()
Range("A1").End(xlToRight).Select
End Sub

Find the very last used cell in a Row:

Sub LastCellInRow()
Range("IV1").End(xlToLeft).Select
End Sub

See here for more information (and the explanation why xlCellTypeLastCell is not very reliable).

NSPhotoLibraryUsageDescription key must be present in Info.plist to use camera roll

In order to save or retrieve an image from the camera roll. Additionally, you need to ask the user for the permission otherwise you'll get this error or your app may get crashed. To save yourself from this add this into your info.plist

<key>NSPhotoLibraryAddUsageDescription</key>
<string>This app requires read and write permission from the user.</string>

In the case of Xamarin.iOS

 if you're adding it from the generic editor then "Privacy - Photo Library Additions Usage Description" will be the given option you will find out instead of "NSPhotoLibraryAddUsageDescription".

Are HTTPS headers encrypted?

HTTPS (HTTP over SSL) sends all HTTP content over a SSL tunel, so HTTP content and headers are encrypted as well.

ORA-01008: not all variables bound. They are bound

I know this is an old question, but it hasn't been correctly addressed, so I'm answering it for others who may run into this problem.

By default Oracle's ODP.net binds variables by position, and treats each position as a new variable.

Treating each copy as a different variable and setting it's value multiple times is a workaround and a pain, as furman87 mentioned, and could lead to bugs, if you are trying to rewrite the query and move things around.

The correct way is to set the BindByName property of OracleCommand to true as below:

var cmd = new OracleCommand(cmdtxt, conn);
cmd.BindByName = true;

You could also create a new class to encapsulate OracleCommand setting the BindByName to true on instantiation, so you don't have to set the value each time. This is discussed in this post

How to check all checkboxes using jQuery?

html :

    <div class="col-md-3 general-sidebar" id="CategoryGrid">
                                                    <h5>Category &amp; Sub Category <span style="color: red;">* </span></h5>
                                                    <div class="checkbox">
                                                        <label>
                                                            <input onclick="checkUncheckAll(this)" type="checkbox">
                                                            All
                                                        </label>
                                                    </div>
                                                <div class="checkbox"><label><input class="cat" type="checkbox" value="Quality">Quality</label></div>
<div class="checkbox"><label><input class="subcat" type="checkbox" value="Planning process and execution">Planning process and execution</label></div>

javascript:

function checkUncheckAll(ele) {
    if (ele.checked) {
        $('.cat').prop('checked', ele.checked);
        $('.subcat').prop('checked', ele.checked);
    }
    else {
        $('.cat').prop('checked', ele.checked);
        $('.subcat').prop('checked', ele.checked);
    }
}

Write a formula in an Excel Cell using VBA

Treb, Matthieu's problem was caused by using Excel in a non-English language. In many language versions ";" is the correct separator. Even functions are translated (SUM can be SOMMA, SUMME or whatever depending on what language you work in). Excel will generally understand these differences and if a French-created workbook is opened by a Brazilian they will normally not have any problem. But VBA speaks only US English so for those of us working in one (or more) foreign langauges, this can be a headache. You and CharlesB both gave answers that would have been OK for a US user but Mikko understod the REAL problem and gave the correct answer (which was also the correct one for me too - I'm a Brit working in Italy for a German-speaking company).

How to disable JavaScript in Chrome Developer Tools?

chrome://settings/content Javascript/Manage Exceptions

Is Safari on iOS 6 caching $.ajax results?

I just had this issue as well in a PhoneGap application. I solved it by using the JavaScript function getTime() in the following manner:

var currentTime = new Date();
var n = currentTime.getTime();
postUrl = "http://www.example.com/test.php?nocache="+n;
$.post(postUrl, callbackFunction);

I wasted a few hours figuring this out. It would have been nice of Apple to notify developers of this caching issue.

What is the difference between jQuery: text() and html() ?

Strange that no-one mentioned the Cross Site scripting prevention benefit of .text() over .html() (Although others have just mentioned that .text() escapes the data).

It's always recommended to use .text() when you want to update data in DOM which is just data / text for the user to see.

.html() should be mostly used to get the HTML content within a div.

HTML text-overflow ellipsis detection

The e.offsetWidth < e.scrollWidth solution is not always working.

And if you want to use pure JavaScript, I recommend to use this:

(typescript)

public isEllipsisActive(element: HTMLElement): boolean {
    element.style.overflow = 'initial';
    const noEllipsisWidth = element.offsetWidth;
    element.style.overflow = 'hidden';
    const ellipsisWidth = element.offsetWidth;

    if (ellipsisWidth < noEllipsisWidth) {
      return true;
    } else {
      return false;
    }
}

How do I get total physical memory size using PowerShell without WMI?

Let's not over complicate things...:

(Get-CimInstance Win32_PhysicalMemory | Measure-Object -Property capacity -Sum).sum /1gb

Can you change what a symlink points to after it is created?

It is not necessary to explicitly unlink the old symlink. You can do this:

ln -s newtarget temp
mv temp mylink

(or use the equivalent symlink and rename calls). This is better than explicitly unlinking because rename is atomic, so you can be assured that the link will always point to either the old or new target. However this will not reuse the original inode.

On some filesystems, the target of the symlink is stored in the inode itself (in place of the block list) if it is short enough; this is determined at the time it is created.

Regarding the assertion that the actual owner and group are immaterial, symlink(7) on Linux says that there is a case where it is significant:

The owner and group of an existing symbolic link can be changed using lchown(2). The only time that the ownership of a symbolic link matters is when the link is being removed or renamed in a directory that has the sticky bit set (see stat(2)).

The last access and last modification timestamps of a symbolic link can be changed using utimensat(2) or lutimes(3).

On Linux, the permissions of a symbolic link are not used in any operations; the permissions are always 0777 (read, write, and execute for all user categories), and can't be changed.

how to query child objects in mongodb

Assuming your "states" collection is like:

{"name" : "Spain", "cities" : [ { "name" : "Madrid" }, { "name" : null } ] }
{"name" : "France" }

The query to find states with null cities would be:

db.states.find({"cities.name" : {"$eq" : null, "$exists" : true}});

It is a common mistake to query for nulls as:

db.states.find({"cities.name" : null});

because this query will return all documents lacking the key (in our example it will return Spain and France). So, unless you are sure the key is always present you must check that the key exists as in the first query.

Distinct by property of class with LINQ

Same approach as Guffa but as an extension method:

public static IEnumerable<T> DistinctBy<T, TKey>(this IEnumerable<T> items, Func<T, TKey> property)
{
    return items.GroupBy(property).Select(x => x.First());
}

Used as:

var uniqueCars = cars.DistinctBy(x => x.CarCode);

How can I dynamically switch web service addresses in .NET without a recompile?

I know this is an old question, but our solution is much simpler than what I see here. We use it for WCF calls with VS2010 and up. The string url can come from app settings or another source. In my case it is a drop down list where the user picks the server. TheService was configured through VS add service reference.

private void CallTheService( string url )
{
   TheService.TheServiceClient client = new TheService.TheServiceClient();
   client.Endpoint.Address = new System.ServiceModel.EndpointAddress(url);
   var results = client.AMethodFromTheService();
}

Sorting object property by values

JavaScript objects are unordered by definition (see the ECMAScript Language Specification, section 8.6). The language specification doesn't even guarantee that, if you iterate over the properties of an object twice in succession, they'll come out in the same order the second time.

If you need things to be ordered, use an array and the Array.prototype.sort method.

Java Reflection Performance

Yes, it's slower.

But remember the damn #1 rule--PREMATURE OPTIMIZATION IS THE ROOT OF ALL EVIL

(Well, may be tied with #1 for DRY)

I swear, if someone came up to me at work and asked me this I'd be very watchful over their code for the next few months.

You must never optimize until you are sure you need it, until then, just write good, readable code.

Oh, and I don't mean write stupid code either. Just be thinking about the cleanest way you can possibly do it--no copy and paste, etc. (Still be wary of stuff like inner loops and using the collection that best fits your need--Ignoring these isn't "unoptimized" programming, it's "bad" programming)

It freaks me out when I hear questions like this, but then I forget that everyone has to go through learning all the rules themselves before they really get it. You'll get it after you've spent a man-month debugging something someone "Optimized".

EDIT:

An interesting thing happened in this thread. Check the #1 answer, it's an example of how powerful the compiler is at optimizing things. The test is completely invalid because the non-reflective instantiation can be completely factored out.

Lesson? Don't EVER optimize until you've written a clean, neatly coded solution and proven it to be too slow.

Java equivalent to #region in C#

If anyone is interested, in Eclipse you can collapse all your methods etc in one go, just right click when you'd normally insert a break point, click 'Folding' > 'Collapse all'. It know it's not an answer to the question, but just providing an alternative to quick code folding.

Check if an element contains a class in JavaScript?

I've created a prototype method which uses classList, if possible, else resorts to indexOf:

_x000D_
_x000D_
Element.prototype.hasClass = Element.prototype.hasClass || _x000D_
  function(classArr){_x000D_
    var hasClass = 0,_x000D_
        className = this.getAttribute('class');_x000D_
  _x000D_
    if( this == null || !classArr || !className ) return false;_x000D_
  _x000D_
    if( !(classArr instanceof Array) )_x000D_
      classArr = classArr.split(' ');_x000D_
_x000D_
    for( var i in classArr )_x000D_
      // this.classList.contains(classArr[i]) // for modern browsers_x000D_
      if( className.split(classArr[i]).length > 1 )  _x000D_
          hasClass++;_x000D_
_x000D_
    return hasClass == classArr.length;_x000D_
};_x000D_
_x000D_
_x000D_
///////////////////////////////_x000D_
// TESTS (see browser's console when inspecting the output)_x000D_
_x000D_
var elm1 = document.querySelector('p');_x000D_
var elm2 = document.querySelector('b');_x000D_
var elm3 = elm1.firstChild; // textNode_x000D_
var elm4 = document.querySelector('text'); // SVG text_x000D_
_x000D_
console.log( elm1, ' has class "a": ', elm1.hasClass('a') );_x000D_
console.log( elm1, ' has class "b": ', elm1.hasClass('b') );_x000D_
console.log( elm1, ' has class "c": ', elm1.hasClass('c') );_x000D_
console.log( elm1, ' has class "d": ', elm1.hasClass('d') );_x000D_
console.log( elm1, ' has class "a c": ', elm1.hasClass('a c') );_x000D_
console.log( elm1, ' has class "a d": ', elm1.hasClass('a d') );_x000D_
console.log( elm1, ' has class "": ', elm1.hasClass('') );_x000D_
_x000D_
console.log( elm2, ' has class "a": ', elm2.hasClass('a') );_x000D_
_x000D_
// console.log( elm3, ' has class "a": ', elm3.hasClass('a') );_x000D_
_x000D_
console.log( elm4, ' has class "a": ', elm4.hasClass('a') );
_x000D_
<p class='a b c'>This is a <b>test</b> string</p>_x000D_
<svg xmlns="http://www.w3.org/2000/svg" width="100px" height="50px">_x000D_
    <text x="10" y="20" class='a'>SVG Text Example</text>_x000D_
</svg>
_x000D_
_x000D_
_x000D_

Test page

Get table names using SELECT statement in MySQL

This below query worked for me. This can able to show the databases,tables,column names,data types and columns count.

**select table_schema Schema_Name ,table_name TableName,column_name ColumnName,ordinal_position "Position",column_type DataType,COUNT(1) ColumnCount
FROM information_schema.columns
GROUP by table_schema,table_name,column_name,ordinal_position, column_type;**

MS-DOS Batch file pause with enter key

There's a pause command that does just that, though it's not specifically the enter key.

If you really want to wait for only the enter key, you can use the set command to ask for user input with a dummy variable, something like:

set /p DUMMY=Hit ENTER to continue...

How to add LocalDB to Visual Studio 2015 Community's SQL Server Object Explorer?

  1. Search for sqllocaldb or localDB in your windows start menu and right click on open file location
  2. Open command prompt in the file location you found from the search
  3. On your command prompt type sqllocaldb start

  4. Use <add name="defaultconnection" connectionString="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=tododb;Integrated Security=True" providerName="System.Data.SqlClient" />

How can I limit ngFor repeat to some number of items in Angular?

 <div *ngFor="let item of list;trackBy: trackByFunc" >
   {{item.value}}
 </div>

In your ts file

 trackByFunc(index, item){
    return item ? item.id : undefined;
  }

Using DISTINCT inner join in SQL

I believe your 1:m relationships should already implicitly create DISTINCT JOINs.

But, if you're goal is just C's in each A, it might be easier to just use DISTINCT on the outer-most query.

SELECT DISTINCT a.valueA, c.valueC
FROM C
    INNER JOIN B ON B.lookupC = C.id
    INNER JOIN A ON A.lookupB = B.id
ORDER BY a.valueA, c.valueC

Failed to load JavaHL Library

For Eclipse/STS v3.9.X windows user, you may need to update your subclipse version.

Go to Help > Install New Software > Click on Subclipse and edit the version from 1.6.X to 1.8.X

This method also apply to those who encounter JavaHL not available. You can check whether JavaHL is available or not by Go to Windows > Preference > Team > SVN. You may check it in SVN Interface > Client section.

If this work on MAC OS, kindly response in comment section. :)

Git: See my last commit

This question is already answered above which states the file names in last commit by git log / other commands. If someone wants to see what all changed in last commit (line differences), you can use this command -

git show

This automatically displays the line differences in last commit.

PHPMailer - SMTP ERROR: Password command failed when send mail from my server

You need to use an APP password.

Visit this link to view how to create one.

Why doesn't java.util.Set have get(int index)?

java.util.Set is a collection of un-ordered items. It doesn't make any sense if the Set has a get(int index), because Set doesn't has an index and also you only can guess the value.

If you really want this, code a method to get random element from Set.

sql query to return differences between two tables

IF you have tables A and B, both with colum C, here are the records, which are present in table A but not in B:

SELECT A.*
FROM A
    LEFT JOIN B ON (A.C = B.C)
WHERE B.C IS NULL

To get all the differences with a single query, a full join must be used, like this:

SELECT A.*, B.*
FROM A
    FULL JOIN B ON (A.C = B.C)
WHERE A.C IS NULL OR B.C IS NULL

What you need to know in this case is, that when a record can be found in A, but not in B, than the columns which come from B will be NULL, and similarly for those, which are present in B and not in A, the columns from A will be null.

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

Might want to try

keytool -import -trustcacerts -noprompt -keystore <full path to cacerts> -storepass changeit -alias $REMHOST -file $REMHOST.pem

i honestly have no idea where it puts your certificate if you just write cacerts just give it a full path

Hashing a dictionary?

Here is a clearer solution.

def freeze(o):
  if isinstance(o,dict):
    return frozenset({ k:freeze(v) for k,v in o.items()}.items())

  if isinstance(o,list):
    return tuple([freeze(v) for v in o])

  return o


def make_hash(o):
    """
    makes a hash out of anything that contains only list,dict and hashable types including string and numeric types
    """
    return hash(freeze(o))  

Make a bucket public in Amazon S3

You can set a bucket policy as detailed in this blog post:

http://ariejan.net/2010/12/24/public-readable-amazon-s3-bucket-policy/


As per @robbyt's suggestion, create a bucket policy with the following JSON:

{
  "Version": "2008-10-17",
  "Statement": [{
    "Sid": "AllowPublicRead",
    "Effect": "Allow",
    "Principal": { "AWS": "*" },
    "Action": ["s3:GetObject"],
    "Resource": ["arn:aws:s3:::bucket/*" ]
  }]
}

Important: replace bucket in the Resource line with the name of your bucket.

Using Jquery AJAX function with datatype HTML

var datos = $("#id_formulario").serialize();
$.ajax({         
    url: "url.php",      
    type: "POST",                   
    dataType: "html",                 
    data: datos,                 
    success: function (prueba) { 
        alert("funciona!");
    }//FIN SUCCES

});//FIN  AJAX

How do I get an element to scroll into view, using jQuery?

After trying to find a solution that handled every circumstance (options for animating the scroll, padding around the object once it scrolls into view, works even in obscure circumstances such as in an iframe), I finally ended up writing my own solution to this. Since it seems to work when many other solutions failed, I thought I'd share it:

function scrollIntoViewIfNeeded($target, options) {

    var options = options ? options : {},
    $win = $($target[0].ownerDocument.defaultView), //get the window object of the $target, don't use "window" because the element could possibly be in a different iframe than the one calling the function
    $container = options.$container ? options.$container : $win,        
    padding = options.padding ? options.padding : 20,
    elemTop = $target.offset().top,
    elemHeight = $target.outerHeight(),
    containerTop = $container.scrollTop(),
    //Everything past this point is used only to get the container's visible height, which is needed to do this accurately
    containerHeight = $container.outerHeight(),
    winTop = $win.scrollTop(),
    winBot = winTop + $win.height(),
    containerVisibleTop = containerTop < winTop ? winTop : containerTop,
    containerVisibleBottom = containerTop + containerHeight > winBot ? winBot : containerTop + containerHeight,
    containerVisibleHeight = containerVisibleBottom - containerVisibleTop;

    if (elemTop < containerTop) {
        //scroll up
        if (options.instant) {
            $container.scrollTop(elemTop - padding);
        } else {
            $container.animate({scrollTop: elemTop - padding}, options.animationOptions);
        }
    } else if (elemTop + elemHeight > containerTop + containerVisibleHeight) {
        //scroll down
        if (options.instant) {
            $container.scrollTop(elemTop + elemHeight - containerVisibleHeight + padding);
        } else {
            $container.animate({scrollTop: elemTop + elemHeight - containerVisibleHeight + padding}, options.animationOptions);
        }
    }
}

$target is a jQuery object containing the object you wish to scroll into view if needed.

options (optional) can contain the following options passed in an object:

options.$container - a jQuery object pointing to the containing element of $target (in other words, the element in the dom with the scrollbars). Defaults to the window that contains the $target element and is smart enough to select an iframe window. Remember to include the $ in the property name.

options.padding - the padding in pixels to add above or below the object when it is scrolled into view. This way it is not right against the edge of the window. Defaults to 20.

options.instant - if set to true, jQuery animate will not be used and the scroll will instantly pop to the correct location. Defaults to false.

options.animationOptions - any jQuery options you wish to pass to the jQuery animate function (see http://api.jquery.com/animate/). With this, you can change the duration of the animation or have a callback function executed when the scrolling is complete. This only works if options.instant is set to false. If you need to have an instant animation but with a callback, set options.animationOptions.duration = 0 instead of using options.instant = true.

Insert a new row into DataTable

You can do this, I am using

DataTable 1.10.5

using this code:

var versionNo = $.fn.dataTable.version;
alert(versionNo);

This is how I insert new record on my DataTable using row.add (My table has 10 columns), which can also includes HTML tag elements:

function fncInsertNew() {
            var table = $('#tblRecord').DataTable();

            table.row.add([
                    "Tiger Nixon",
                    "System Architect",
                    "$3,120",
                    "2011/04/25",
                    "Edinburgh",
                    "5421",
                    "Tiger Nixon",
                    "System Architect",
                    "$3,120",
                    "<p>Hello</p>"
            ]).draw();
        }

For multiple inserts at the same time, use rows.add instead:

var table = $('#tblRecord').DataTable();

table.rows.add( [ {
        "Tiger Nixon",
        "System Architect",
        "$3,120",
        "2011/04/25",
        "Edinburgh",
        "5421"
    }, {
        "Garrett Winters",
        "Director",
        "$5,300",
        "2011/07/25",
        "Edinburgh",
        "8422"
    }]).draw();

Table row and column number in jQuery

Can you output that data in the cells as you are creating the table?

so your table would look like this:

<table>
  <thead>...</thead>
  <tbody>
    <tr><td data-row='1' data-column='1'>value</td>
      <td data-row='1' data-column='2'>value</td>
      <td data-row='1' data-column='3'>value</td></tr>

  <tbody>
</table>

then it would be a simple matter

$("td").click(function(event) {
   var row = $(this).attr("data-row");
   var col = $(this).attr("data-col");
}

Random string generation with upper case letters and digits

I would like to suggest you next option:

import crypt
n = 10
crypt.crypt("any sring").replace('/', '').replace('.', '').upper()[-n:-1]

Paranoic mode:

import uuid
import crypt
n = 10
crypt.crypt(str(uuid.uuid4())).replace('/', '').replace('.', '').upper()[-n:-1]

How to tell if node.js is installed or not

(This is for windows OS but concept can be applied to other OS)

Running command node -v will be able to confirm if it is installed, however it will not be able to confirm if it is NOT installed. (Executable may not be on your PATH)

Two ways you can check if it is actually installed:

  1. Check default install location C:\Program Files\nodejs\

or

  1. Go to System Settings -> Add or Remove Programs and filter by node, it should show you if you have it installed. For me, it shows as title:"Node.js" and description "Node.js Foundation", with no version specified. Install size is 52.6MB

If you don't have it installed, get it from here https://nodejs.org/en/download/

Bootstrap 3.0 Popovers and tooltips

I had to do it on DOM ready

$( document ).ready(function () { // this has to be done after the document has been rendered
    $("[data-toggle='tooltip']").tooltip({html: true}); // enable bootstrap 3 tooltips
    $('[data-toggle="popover"]').popover({
        trigger: 'hover',
        'placement': 'top',
        'show': true
    });
});

And change my load orders to be:

  • jQuery
  • jQuery UI
  • Bootstrap

C++ performance vs. Java/C#

I don't know either...my Java programs are always slow. :-) I've never really noticed C# programs being particularly slow, though.

What's the difference between .bashrc, .bash_profile, and .environment?

I have used Debian-family distros which appear to execute .profile, but not .bash_profile, whereas RHEL derivatives execute .bash_profile before .profile.

It seems to be a mess when you have to set up environment variables to work in any Linux OS.

Check if a string contains an element from a list (of strings)

I liked Marc's answer, but needed the Contains matching to be CaSe InSenSiTiVe.

This was the solution:

bool b = listOfStrings.Any(s => myString.IndexOf(s, StringComparison.OrdinalIgnoreCase) >= 0))

Copy table from one database to another

Assuming that they are in the same server, try this:

SELECT *
INTO SecondDB.TableName
FROM FirstDatabase.TableName

This will create a new table and just copy the data from FirstDatabase.TableName to SecondDB.TableName and won't create foreign keys or indexes.

Qt jpg image display

You could attach the image (as a pixmap) to a label then add that to your layout...

...

QPixmap image("blah.jpg");

QLabel *imageLabel = new QLabel();
imageLabel->setPixmap(image);

mainLayout.addWidget(imageLabel);

...

Apologies, this is using Jambi (Qt for Java) so the syntax is different, but the theory is the same.

Any way to exit bash script, but not quitting the terminal

Yes; you can use return instead of exit. Its main purpose is to return from a shell function, but if you use it within a source-d script, it returns from that script.

As §4.1 "Bourne Shell Builtins" of the Bash Reference Manual puts it:

     return [n]

Cause a shell function to exit with the return value n. If n is not supplied, the return value is the exit status of the last command executed in the function. This may also be used to terminate execution of a script being executed with the . (or source) builtin, returning either n or the exit status of the last command executed within the script as the exit status of the script. Any command associated with the RETURN trap is executed before execution resumes after the function or script. The return status is non-zero if return is used outside a function and not during the execution of a script by . or source.

Warning: The method assertEquals from the type Assert is deprecated

When I use Junit4, import junit.framework.Assert; import junit.framework.TestCase; the warning info is :The type of Assert is deprecated

when import like this: import org.junit.Assert; import org.junit.Test; the warning has disappeared

possible duplicate of differences between 2 JUnit Assert classes

Java read file and store text in an array

Just read the whole file into a StringBuilder, then split the String by dot following a space. You will get a String array.

Scanner inFile1 = new Scanner(new File("KeyWestTemp.txt"));

StringBuilder sb = new Stringbuilder();
while(inFile1.hasNext()) {
    sb.append(inFile1.nextLine());
}

String[] yourArray = sb.toString().split(", ");

What is NODE_ENV and how to use it in Express?

I assume the original question included how does Express use this environment variable.

Express uses NODE_ENV to alter its own default behavior. For example, in development mode, the default error handler will send back a stacktrace to the browser. In production mode, the response is simply Internal Server Error, to avoid leaking implementation details to the world.

Remove a git commit which has not been pushed

This is what I do:

First checkout your branch (for my case master branch):

git checkout master

Then reset to remote HEAD^ (it'll remove all your local changes), force clean and pull:

git reset HEAD^ --hard && git clean -df && git pull

How do you comment out code in PowerShell?

Here

# Single line comment in Powershell

<# 
--------------------------------------
Multi-line comment in PowerShell V2+ 
-------------------------------------- 
#>

How to grep (search) committed code in the Git history

You should use the pickaxe (-S) option of git log.

To search for Foo:

git log -SFoo -- path_containing_change
git log -SFoo --since=2009.1.1 --until=2010.1.1 -- path_containing_change

See Git history - find lost line by keyword for more.


As Jakub Narebski commented:

  • this looks for differences that introduce or remove an instance of <string>. It usually means "revisions where you added or removed line with 'Foo'".

  • the --pickaxe-regex option allows you to use extended POSIX regex instead of searching for a string. Example (from git log): git log -S"frotz\(nitfol" --pickaxe-regex


As Rob commented, this search is case-sensitive - he opened a follow-up question on how to search case-insensitive.

How to set timer in android?

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;

import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.app.Activity;

public class MainActivity extends Activity {

 CheckBox optSingleShot;
 Button btnStart, btnCancel;
 TextView textCounter;

 Timer timer;
 MyTimerTask myTimerTask;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  optSingleShot = (CheckBox)findViewById(R.id.singleshot);
  btnStart = (Button)findViewById(R.id.start);
  btnCancel = (Button)findViewById(R.id.cancel);
  textCounter = (TextView)findViewById(R.id.counter);

  btnStart.setOnClickListener(new OnClickListener(){

   @Override
   public void onClick(View arg0) {

    if(timer != null){
     timer.cancel();
    }

    //re-schedule timer here
    //otherwise, IllegalStateException of
    //"TimerTask is scheduled already" 
    //will be thrown
    timer = new Timer();
    myTimerTask = new MyTimerTask();

    if(optSingleShot.isChecked()){
     //singleshot delay 1000 ms
     timer.schedule(myTimerTask, 1000);
    }else{
     //delay 1000ms, repeat in 5000ms
     timer.schedule(myTimerTask, 1000, 5000);
    }
   }});

  btnCancel.setOnClickListener(new OnClickListener(){

   @Override
   public void onClick(View v) {
    if (timer!=null){
     timer.cancel();
     timer = null;
    }
   }
  });

 }

 class MyTimerTask extends TimerTask {

  @Override
  public void run() {
   Calendar calendar = Calendar.getInstance();
   SimpleDateFormat simpleDateFormat = 
     new SimpleDateFormat("dd:MMMM:yyyy HH:mm:ss a");
   final String strDate = simpleDateFormat.format(calendar.getTime());

   runOnUiThread(new Runnable(){

    @Override
    public void run() {
     textCounter.setText(strDate);
    }});
  }

 }

}

.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context=".MainActivity" >

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:autoLink="web"
    android:text="http://android-er.blogspot.com/"
    android:textStyle="bold" />
<CheckBox 
    android:id="@+id/singleshot"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Single Shot"/>

What is content-type and datatype in an AJAX request?

See http://api.jquery.com/jQuery.ajax/, there's mention of datatype and contentType there.

They are both used in the request to the server so the server knows what kind of data to receive/send.

How can I get the active screen dimensions?

WinForms

For multi-monitor setups you will also need account for the X and Y position:

Rectangle activeScreenDimensions = Screen.FromControl(this).Bounds;
this.Size = new Size(activeScreenDimensions.Width + activeScreenDimensions.X, activeScreenDimensions.Height + activeScreenDimensions.Y);

Handle Button click inside a row in RecyclerView

this is how I handle multiple onClick events inside a recyclerView:

Edit : Updated to include callbacks (as mentioned in other comments). I have used a WeakReference in the ViewHolder to eliminate a potential memory leak.

Define interface :

public interface ClickListener {

    void onPositionClicked(int position);
    
    void onLongClicked(int position);
}

Then the Adapter :

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
    
    private final ClickListener listener;
    private final List<MyItems> itemsList;

    public MyAdapter(List<MyItems> itemsList, ClickListener listener) {
        this.listener = listener;
        this.itemsList = itemsList;
    }

    @Override public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new MyViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.my_row_layout), parent, false), listener);
    }

    @Override public void onBindViewHolder(MyViewHolder holder, int position) {
        // bind layout and data etc..
    }

    @Override public int getItemCount() {
        return itemsList.size();
    }

    public static class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener {

        private ImageView iconImageView;
        private TextView iconTextView;
        private WeakReference<ClickListener> listenerRef;

        public MyViewHolder(final View itemView, ClickListener listener) {
            super(itemView);

            listenerRef = new WeakReference<>(listener);
            iconImageView = (ImageView) itemView.findViewById(R.id.myRecyclerImageView);
            iconTextView = (TextView) itemView.findViewById(R.id.myRecyclerTextView);

            itemView.setOnClickListener(this);
            iconTextView.setOnClickListener(this);
            iconImageView.setOnLongClickListener(this);
        }

        // onClick Listener for view
        @Override
        public void onClick(View v) {

            if (v.getId() == iconTextView.getId()) {
                Toast.makeText(v.getContext(), "ITEM PRESSED = " + String.valueOf(getAdapterPosition()), Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(v.getContext(), "ROW PRESSED = " + String.valueOf(getAdapterPosition()), Toast.LENGTH_SHORT).show();
            }
            
            listenerRef.get().onPositionClicked(getAdapterPosition());
        }


        //onLongClickListener for view
        @Override
        public boolean onLongClick(View v) {

            final AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
            builder.setTitle("Hello Dialog")
                    .setMessage("LONG CLICK DIALOG WINDOW FOR ICON " + String.valueOf(getAdapterPosition()))
                    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    });

            builder.create().show();
            listenerRef.get().onLongClicked(getAdapterPosition());
            return true;
        }
    }
}

Then in your activity/fragment - whatever you can implement : Clicklistener - or anonymous class if you wish like so :

MyAdapter adapter = new MyAdapter(myItems, new ClickListener() {
            @Override public void onPositionClicked(int position) {
                // callback performed on click
            }

            @Override public void onLongClicked(int position) {
                // callback performed on click
            }
        });

To get which item was clicked you match the view id i.e. v.getId() == whateverItem.getId()

Hope this approach helps!

How to make a section of an image a clickable link

You can auto generate Image map from this website for selected area of image. https://www.image-map.net/

Easiest way to execute!

An Authentication object was not found in the SecurityContext - Spring 3.2.2

The security's authorization check part gets the authenticated object from SecurityContext, which will be set when a request gets through the spring security filter. My assumption here is that soon after the login this is not being set. You probably can use a hack as given below to set the value.

try {
    SecurityContext ctx = SecurityContextHolder.createEmptyContext();
    SecurityContextHolder.setContext(ctx);
    ctx.setAuthentication(event.getAuthentication());

    //Do what ever you want to do

} finally {
    SecurityContextHolder.clearContext();
}

Update:

Also you can have a look at the InteractiveAuthenticationSuccessEvent which will be called once the SecurityContext is set.

Python reading from a file and saving to utf-8

You can also get through it by the code below:

file=open(completefilepath,'r',encoding='utf8',errors="ignore")
file.read()

How to remove extension from string (only real extension!)

I found many examples on the Google but there are bad because just remove part of string with "."

Actually that is absolutely the correct thing to do. Go ahead and use that.

The file extension is everything after the last dot, and there is no requirement for a file extension to be any particular number of characters. Even talking only about Windows, it already comes with file extensions that don't fit 3-4 characters, such as eg. .manifest.

Print out the values of a (Mat) matrix in OpenCV C++

See the first answer to Accessing a matrix element in the "Mat" object (not the CvMat object) in OpenCV C++
Then just loop over all the elements in cout << M.at<double>(0,0); rather than just 0,0

Or better still with the C++ interface:

cv::Mat M;
cout << "M = " << endl << " "  << M << endl << endl;

How to change the map center in Leaflet.js

For example:

map.panTo(new L.LatLng(40.737, -73.923));

How to connect to mysql with laravel?

I spent a lot of time trying to figure this one out. Finally, I tried shutting down my development server and booting it up again. Frustratingly, this worked for me. I came to the conclusion, that after editing the .env file in Laravel 5, you have to exit the server, and run php artisan serve again.

Color text in discord

Discord doesn't allow colored text. Though, currently, you have two options to "mimic" colored text.

Option #1 (Markdown code-blocks)

Discord supports Markdown and uses highlight.js to highlight code-blocks. Some programming languages have specific color outputs from highlight.js and can be used to mimic colored output.

To use code-blocks, send a normal message in this format (Which follows Markdown's standard format).

```language
message
```

Languages that currently reproduce nice colors: prolog (red/orange), css (yellow).

Option #2 (Embeds)

Discord now supports Embeds and Webhooks, which can be used to display colored blocks, they also support markdown. For documentation on how to use Embeds, please read your lib's documentation.

(Embed Cheat-sheet)
Embed Cheat-sheet

Is there a Subversion command to reset the working copy?

To remove untracked files

I was able to list all untracked files reported by svn st in bash by doing:

echo $(svn st | grep -P "^\?" | cut -c 9-)

If you are feeling lucky, you could replace echo with rm to delete untracked files. Or copy the files you want to delete by hand, if you are feeling a less lucky.


(I used @abe-voelker 's answer to revert the remaining files: https://stackoverflow.com/a/6204601/1695680)

Multiple REPLACE function in Oracle

The accepted answer to how to replace multiple strings together in Oracle suggests using nested REPLACE statements, and I don't think there is a better way.

If you are going to make heavy use of this, you could consider writing your own function:

CREATE TYPE t_text IS TABLE OF VARCHAR2(256);

CREATE FUNCTION multiple_replace(
  in_text IN VARCHAR2, in_old IN t_text, in_new IN t_text
)
  RETURN VARCHAR2
AS
  v_result VARCHAR2(32767);
BEGIN
  IF( in_old.COUNT <> in_new.COUNT ) THEN
    RETURN in_text;
  END IF;
  v_result := in_text;
  FOR i IN 1 .. in_old.COUNT LOOP
    v_result := REPLACE( v_result, in_old(i), in_new(i) );
  END LOOP;
  RETURN v_result;
END;

and then use it like this:

SELECT multiple_replace( 'This is #VAL1# with some #VAL2# to #VAL3#',
                         NEW t_text( '#VAL1#', '#VAL2#', '#VAL3#' ),
                         NEW t_text( 'text', 'tokens', 'replace' )
                       )
FROM dual

This is text with some tokens to replace

If all of your tokens have the same format ('#VAL' || i || '#'), you could omit parameter in_old and use your loop-counter instead.

Best C++ Code Formatter/Beautifier

AStyle can be customized in great detail for C++ and Java (and others too)

This is a source code formatting tool.


clang-format is a powerful command line tool bundled with the clang compiler which handles even the most obscure language constructs in a coherent way.

It can be integrated with Visual Studio, Emacs, Vim (and others) and can format just the selected lines (or with git/svn to format some diff).

It can be configured with a variety of options listed here.

When using config files (named .clang-format) styles can be per directory - the closest such file in parent directories shall be used for a particular file.

Styles can be inherited from a preset (say LLVM or Google) and can later override different options

It is used by Google and others and is production ready.


Also look at the project UniversalIndentGUI. You can experiment with several indenters using it: AStyle, Uncrustify, GreatCode, ... and select the best for you. Any of them can be run later from a command line.


Uncrustify has a lot of configurable options. You'll probably need Universal Indent GUI (in Konstantin's reply) as well to configure it.

How to specify test directory for mocha?

Run all files in test_directory including sub directories that match test.js

find ./parent_test_directory -name '*test.js' | xargs mocha -R spec

or use the --recursive switch

mocha --recursive test_directory/

Android sqlite how to check if a record exists

One thing the top voted answer did not mention was that you need single quotes, 'like this', around your search value if it is a text value like so:

public boolean checkIfMyTitleExists(String title) {
    String Query = "Select * from " + TABLE_NAME + " where " + COL1 + " = " + "'" + title + "'";
    Cursor cursor = database.rawQuery(Query, null);
    if(cursor.getCount() <= 0){
        cursor.close();
        return false;
    }
    cursor.close();

    return true;
}

Otherwise, you will get a "SQL(query) error or missing database" error like I did without the single quotes around the title field.

If it is a numeric value, it does not need single quotes.

Refer to this SQL post for more details

Is there any way I can define a variable in LaTeX?

I think you probably want to use a token list for this purpose: to set up the token list \newtoks\packagename to assign the name: \packagename={New Name for the package} to put the name into your output: \the\packagename.

How to get document height and width without using jquery

How to find out the document width and height very easily?

in HTML
<span id="hidden_placer" style="position:absolute;right:0;bottom:0;visibility:hidden;"></span>

in javascript

     var c=document.querySelector('#hidden_placer');

     var r=c.getBoundingClientRect();
     r.right=document width
     r.bottom=document height`

You may update this on every window resize event, if needed.

How to set default value to all keys of a dict object in python?

Not after creating it, no. But you could use a defaultdict in the first place, which sets default values when you initialize it.

Action Image MVC3 Razor

Well, you could use @Lucas solution, but there's also another way.

 @Html.ActionLink("Update", "Update", *Your object value*, new { @class = "imgLink"})

Now, add this class on a CSS file or in your page:

.imgLink
{
  background: url(YourImage.png) no-repeat;
}

With that class, any link will have your desired image.

Android Spinner: Get the selected item change event

I know this was long solved but I have a "Please select" string at the top of my string arrays. Then when you write the listener

yourspinner.onItemSelectedListener = object : OnItemSelectedListener {
            override fun onItemSelected(adapterView: AdapterView<*>?, view: View, i: Int, l: Long) {
                yourvalue = yourspinner.getSelectedItem().toString()

                when(yourvalue){
                    "Please Select" -> // DO nothing
                    else -> // Do something
                }
            }

            override fun onNothingSelected(adapterView: AdapterView<*>?) {
                return
            }
        }

You can of course extend the when statement to have different responses or actions.

changing the language of error message in required field in html5 contact form

setCustomValidity's purpose is not just to set the validation message, it itself marks the field as invalid. It allows you to write custom validation checks which aren't natively supported.

You have two possible ways to set a custom message, an easy one that does not involve Javascript and one that does.

The easiest way is to simply use the title attribute on the input element - its content is displayed together with the standard browser message.

<input type="text" required title="Lütfen isaretli yerleri doldurunuz" />

enter image description here

If you want only your custom message to be displayed, a bit of Javascript is required. I have provided both examples for you in this fiddle.

Proper MIME media type for PDF files

The standard MIME type is application/pdf. The assignment is defined in RFC 3778, The application/pdf Media Type, referenced from the MIME Media Types registry.

MIME types are controlled by a standards body, The Internet Assigned Numbers Authority (IANA). This is the same organization that manages the root name servers and the IP address space.

The use of x-pdf predates the standardization of the MIME type for PDF. MIME types in the x- namespace are considered experimental, just as those in the vnd. namespace are considered vendor-specific. x-pdf might be used for compatibility with old software.

How do I export (and then import) a Subversion repository?

Assuming you have the necessary privileges to run svnadmin, you need to use the dump and load commands.

Configuration System Failed to Initialize

In my case the only solution was to add the reference to the System.Configuration in my Test project as well.

How do I convert a String to an InputStream in Java?

You can try cactoos for that.

final InputStream input = new InputStreamOf("example");

The object is created with new and not a static method for a reason.

How to make type="number" to positive numbers only

I cannot find the perfect solution as some work for inputting but not for copy&paste, some are the other way around. This solution works for me. It prevents from negative number, typing "e", copy&paste "e" text.

create a function.

<script language="JavaScript">

  // this prevents from typing non-number text, including "e".
  function isNumber(evt) {
    evt = (evt) ? evt : window.event;
    let charCode = (evt.which) ? evt.which : evt.keyCode;
    if ((charCode > 31 && (charCode < 48 || charCode > 57)) && charCode !== 46) {
      evt.preventDefault();
    } else {
      return true;
    }
  }
</script>

add these properties to input. this two prevent from copy&paste non-number text, including "e". you need to have both together to take effect.

<input type="number" oninput="validity.valid||(value='');" onpress="isNumber(event)" />

If you are using Vue you can refer this answer here. I have extracted it to a mixin which can be reused.

System.Security.SecurityException when writing to Event Log

I hit similar issue - in my case Source contained <, > characters. 64 bit machines are using new even log - xml base I would say and these characters (set from string) create invalid xml which causes exception. Arguably this should be consider Microsoft issue - not handling the Source (name/string) correctly.

How to detect Windows 64-bit platform with .NET?

Include the following code into a class in your project:

    [DllImport("kernel32.dll", SetLastError = true, CallingConvention = CallingConvention.Winapi)]
    [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool IsWow64Process([In] IntPtr hProcess, [Out] out bool wow64Process);

    public static int GetBit()
    {
        int MethodResult = "";
        try
        {
            int Architecture = 32;

            if ((Environment.OSVersion.Version.Major == 5 && Environment.OSVersion.Version.Minor >= 1) || Environment.OSVersion.Version.Major >= 6)
            {
                using (Process p = Process.GetCurrentProcess())
                {
                    bool Is64Bit;

                    if (IsWow64Process(p.Handle, out Is64Bit))
                    {
                        if (Is64Bit)
                        {
                            Architecture = 64;

                        }

                    }

                }

            }

            MethodResult = Architecture;

        }
        catch //(Exception ex)
        {
            //ex.HandleException();
        }
        return MethodResult;
    }

Use it like so:

string Architecture = "This is a " + GetBit() + "bit machine";

get url content PHP

original answer moved to this topic .

Force LF eol in git repo and working copy

Without a bit of information about what files are in your repository (pure source code, images, executables, ...), it's a bit hard to answer the question :)

Beside this, I'll consider that you're willing to default to LF as line endings in your working directory because you're willing to make sure that text files have LF line endings in your .git repository wether you work on Windows or Linux. Indeed better safe than sorry....

However, there's a better alternative: Benefit from LF line endings in your Linux workdir, CRLF line endings in your Windows workdir AND LF line endings in your repository.

As you're partially working on Linux and Windows, make sure core.eol is set to native and core.autocrlf is set to true.

Then, replace the content of your .gitattributes file with the following

* text=auto

This will let Git handle the automagic line endings conversion for you, on commits and checkouts. Binary files won't be altered, files detected as being text files will see the line endings converted on the fly.

However, as you know the content of your repository, you may give Git a hand and help him detect text files from binary files.

Provided you work on a C based image processing project, replace the content of your .gitattributes file with the following

* text=auto
*.txt text
*.c text
*.h text
*.jpg binary

This will make sure files which extension is c, h, or txt will be stored with LF line endings in your repo and will have native line endings in the working directory. Jpeg files won't be touched. All of the others will be benefit from the same automagic filtering as seen above.

In order to get a get a deeper understanding of the inner details of all this, I'd suggest you to dive into this very good post "Mind the end of your line" from Tim Clem, a Githubber.

As a real world example, you can also peek at this commit where those changes to a .gitattributes file are demonstrated.

UPDATE to the answer considering the following comment

I actually don't want CRLF in my Windows directories, because my Linux environment is actually a VirtualBox sharing the Windows directory

Makes sense. Thanks for the clarification. In this specific context, the .gitattributes file by itself won't be enough.

Run the following commands against your repository

$ git config core.eol lf
$ git config core.autocrlf input

As your repository is shared between your Linux and Windows environment, this will update the local config file for both environment. core.eol will make sure text files bear LF line endings on checkouts. core.autocrlf will ensure potential CRLF in text files (resulting from a copy/paste operation for instance) will be converted to LF in your repository.

Optionally, you can help Git distinguish what is a text file by creating a .gitattributes file containing something similar to the following:

# Autodetect text files
* text=auto

# ...Unless the name matches the following
# overriding patterns

# Definitively text files 
*.txt text
*.c text
*.h text

# Ensure those won't be messed up with
*.jpg binary
*.data binary

If you decided to create a .gitattributes file, commit it.

Lastly, ensure git status mentions "nothing to commit (working directory clean)", then perform the following operation

$ git checkout-index --force --all

This will recreate your files in your working directory, taking into account your config changes and the .gitattributes file and replacing any potential overlooked CRLF in your text files.

Once this is done, every text file in your working directory WILL bear LF line endings and git status should still consider the workdir as clean.

jQuery DataTables Getting selected row values

You can iterate over the row data

$('#button').click(function () {
    var ids = $.map(table.rows('.selected').data(), function (item) {
        return item[0]
    });
    console.log(ids)
    alert(table.rows('.selected').data().length + ' row(s) selected');
});

Demo: Fiddle

Difference between a SOAP message and a WSDL?

In a simple terms if you have a web service of calculator. WSDL tells about the functions that you can implement or exposed to the client. For example: add, delete, subtract and so on. Where as using SOAP you actually perform actions like doDelete(), doSubtract(), doAdd(). So SOAP and WSDL are apples and oranges. We should not compare them. They both have their own different functionality.