Programs & Examples On #Floating point exceptions

Codes that make heavy use of floating point computations need to successfully alert the user when a particular mathematical operation results in an invalid computation. Examples are divide by 0 (which results in a mathematical 'inf'), a "Not-A-Number" or NaN, and so on. Va Compilers and hardware must work together to provide the programming with these alerts, so the solutions are often hardware and compiler specific.

MySQL, Concatenate two columns

$crud->set_relation('id','students','{first_name} {last_name}');
$crud->display_as('student_id','Students Name');

Converting Chart.js canvas chart to image using .toDataUrl() results in blank image

@EH_warch You need to use the Complete callback to generate your base64:

onAnimationComplete: function(){
    console.log(this.toBase64Image())
}

If you see a white image, it means you called the toBase64Image before it finished rendering.

VBA: activating/selecting a worksheet/row/cell

This is just a sample code, but it may help you get on your way:

Public Sub testIt()
    Workbooks("Workbook2").Activate
    ActiveWorkbook.Sheets("Sheet2").Activate
    ActiveSheet.Range("B3").Select
    ActiveCell.EntireRow.Insert
End Sub

I am assuming that you can open the book (called Workbook2 in the example).


I think (but I'm not sure) you can squash all this in a single line of code:

    Workbooks("Workbook2").Sheets("Sheet2").Range("B3").EntireRow.Insert

This way you won't need to activate the workbook (or sheet or cell)... Obviously, the book has to be open.

Difference between Constructor and ngOnInit

The first one (constructor) is related to the class instantiation and has nothing to do with Angular2. I mean a constructor can be used on any class. You can put in it some initialization processing for the newly created instance.

The second one corresponds to a lifecycle hook of Angular2 components:

Quoted from official angular's website:

  • ngOnChanges is called when an input or output binding value changes
  • ngOnInit is called after the first ngOnChanges

So you should use ngOnInit if initialization processing relies on bindings of the component (for example component parameters defined with @Input), otherwise the constructor would be enough...

Convert Unix timestamp into human readable date using MySQL

Since I found this question not being aware, that mysql always stores time in timestamp fields in UTC but will display (e.g. phpmyadmin) in local time zone I would like to add my findings.

I have an automatically updated last_modified field, defined as:

`last_modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP

Looking at it with phpmyadmin, it looks like it is in local time, internally it is UTC

SET time_zone = '+04:00'; // or '+00:00' to display dates in UTC or 'UTC' if time zones are installed.
SELECT last_modified, UNIX_TIMESTAMP(last_modified), from_unixtime(UNIX_TIMESTAMP(last_modified), '%Y-%c-%d %H:%i:%s'), CONVERT_TZ(last_modified,@@session.time_zone,'+00:00') as UTC FROM `table_name`

In any constellation, UNIX_TIMESTAMP and 'as UTC' are always displayed in UTC time.

Run this twice, first without setting the time_zone.

Sort a list by multiple attributes?

It appears you could use a list instead of a tuple. This becomes more important I think when you are grabbing attributes instead of 'magic indexes' of a list/tuple.

In my case I wanted to sort by multiple attributes of a class, where the incoming keys were strings. I needed different sorting in different places, and I wanted a common default sort for the parent class that clients were interacting with; only having to override the 'sorting keys' when I really 'needed to', but also in a way that I could store them as lists that the class could share

So first I defined a helper method

def attr_sort(self, attrs=['someAttributeString']:
  '''helper to sort by the attributes named by strings of attrs in order'''
  return lambda k: [ getattr(k, attr) for attr in attrs ]

then to use it

# would defined elsewhere but showing here for consiseness
self.SortListA = ['attrA', 'attrB']
self.SortListB = ['attrC', 'attrA']
records = .... #list of my objects to sort
records.sort(key=self.attr_sort(attrs=self.SortListA))
# perhaps later nearby or in another function
more_records = .... #another list
more_records.sort(key=self.attr_sort(attrs=self.SortListB))

This will use the generated lambda function sort the list by object.attrA and then object.attrB assuming object has a getter corresponding to the string names provided. And the second case would sort by object.attrC then object.attrA.

This also allows you to potentially expose outward sorting choices to be shared alike by a consumer, a unit test, or for them to perhaps tell you how they want sorting done for some operation in your api by only have to give you a list and not coupling them to your back end implementation.

Make the current Git branch a master branch

From what I understand, you can branch the current branch into an existing branch. In essence, this will overwrite master with whatever you have in the current branch:

git branch -f master HEAD

Once you've done that, you can normally push your local master branch, possibly requiring the force parameter here as well:

git push -f origin master

No merges, no long commands. Simply branch and push— but, yes, this will rewrite history of the master branch, so if you work in a team you have got to know what you're doing.




Alternatively, I found that you can push any branch to the any remote branch, so:

# This will force push the current branch to the remote master
git push -f origin HEAD:master

# Switch current branch to master
git checkout master

# Reset the local master branch to what's on the remote
git reset --hard origin/master

The type or namespace name 'Objects' does not exist in the namespace 'System.Data'

I added a reference to the .dll file, for System.Data.Linq, the above was not sufficient. You can find .dll in the various directories for the following versions.

System.Data.Linq C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\v3.5\System.Data.Linq.dll 3.5.0.0

System.Data.Linq C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.0\Profile\Client\System.Data.Linq.dll 4.0.0.0

Configure Log4net to write to multiple files

I wanted to log all messages to root logger, and to have a separate log with errors, here is how it can be done:

<log4net>
    <appender name="FileAppender" type="log4net.Appender.FileAppender">
        <file value="allMessages.log" />
        <appendToFile value="true" />
        <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%date  %-5level %logger  - %message%newline" />
        </layout>
    </appender>

    <appender name="ErrorsFileAppender" type="log4net.Appender.FileAppender">
        <file value="errorsLog.log" />
        <appendToFile value="true" />
        <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%date  %-5level %logger  - %message%newline" />
        </layout>
        <filter type="log4net.Filter.LevelRangeFilter">
            <levelMin value="ERROR" />
            <levelMax value="FATAL" />
        </filter>
    </appender>

    <root>
        <level value="ALL" />
        <appender-ref ref="FileAppender" />
        <appender-ref ref="ErrorsFileAppender" />
    </root>
</log4net>

Notice the use of filter element.

Determine path of the executing script

I liked steamer25's solution as it seems the most robust for my purposes. However, when debugging in RStudio (in windows), the path would not get set properly. The reason being that if a breakpoint is set in RStudio, sourcing the file uses an alternate "debug source" command which sets the script path a little differently. Here is the final version which I am currently using which accounts for this alternate behavior within RStudio when debugging:

# @return full path to this script
get_script_path <- function() {
    cmdArgs = commandArgs(trailingOnly = FALSE)
    needle = "--file="
    match = grep(needle, cmdArgs)
    if (length(match) > 0) {
        # Rscript
        return(normalizePath(sub(needle, "", cmdArgs[match])))
    } else {
        ls_vars = ls(sys.frames()[[1]])
        if ("fileName" %in% ls_vars) {
            # Source'd via RStudio
            return(normalizePath(sys.frames()[[1]]$fileName)) 
        } else {
            # Source'd via R console
            return(normalizePath(sys.frames()[[1]]$ofile))
        }
    }
}

How to make HTML code inactive with comments

Just create a multi-line comment around it. When you want it back, just erase the comment tags.

For example, <!-- Stuff to comment out or make inactive -->

How to store a command in a variable in a shell script?

var=$(echo "asdf")
echo $var
# => asdf

Using this method, the command is immediately evaluated and it's return value is stored.

stored_date=$(date)
echo $stored_date
# => Thu Jan 15 10:57:16 EST 2015
# (wait a few seconds)
echo $stored_date
# => Thu Jan 15 10:57:16 EST 2015

Same with backtick

stored_date=`date`
echo $stored_date
# => Thu Jan 15 11:02:19 EST 2015
# (wait a few seconds)
echo $stored_date
# => Thu Jan 15 11:02:19 EST 2015

Using eval in the $(...) will not make it evaluated later

stored_date=$(eval "date")
echo $stored_date
# => Thu Jan 15 11:05:30 EST 2015
# (wait a few seconds)
echo $stored_date
# => Thu Jan 15 11:05:30 EST 2015

Using eval, it is evaluated when eval is used

stored_date="date" # < storing the command itself
echo $(eval "$stored_date")
# => Thu Jan 15 11:07:05 EST 2015
# (wait a few seconds)
echo $(eval "$stored_date")
# => Thu Jan 15 11:07:16 EST 2015
#                     ^^ Time changed

In the above example, if you need to run a command with arguments, put them in the string you are storing

stored_date="date -u"
# ...

For bash scripts this is rarely relevant, but one last note. Be careful with eval. Eval only strings you control, never strings coming from an untrusted user or built from untrusted user input.

  • Thanks to @CharlesDuffy for reminding me to quote the command!

SELECT *, COUNT(*) in SQLite

SELECT *, COUNT(*) FROM my_table is not what you want, and it's not really valid SQL, you have to group by all the columns that's not an aggregate.

You'd want something like

SELECT somecolumn,someothercolumn, COUNT(*) 
   FROM my_table 
GROUP BY somecolumn,someothercolumn

Get the first element of an array

I think using array_values would be your best bet here. You could return the value at index zero from the result of that function to get 'apple'.

Converting newline formatting from Mac to Windows

Expanding on the answers of Anne and JosephH, using perl in a short perl script, since i'm too lazy to type the perl-one-liner very time.
Create a file, named for example "unix2dos.pl" and put it in a directory in your path. Edit the file to contain the 2 lines:

#!/usr/bin/perl -wpi
s/\n|\r\n/\r\n/g;

Assuming that "which perl" returns "/usr/bin/perl" on your system. Make the file executable (chmod u+x unix2dos.pl).

Example:
$ echo "hello" > xxx
$ od -c xxx (checking that the file ends with a nl)
0000000 h e l l o \n

$ unix2dos.pl xxx
$ od -c xxx (checking that it ends now in cr lf)
0000000 h e l l o \r \n

javascript: detect scroll end

I found an alternative that works.

None of these answers worked for me (currently testing in FireFox 22.0), and after a lot of research I found, what seems to be, a much cleaner and straight forward solution.

Implemented solution:

function IsScrollbarAtBottom() {
    var documentHeight = $(document).height();
    var scrollDifference = $(window).height() + $(window).scrollTop();
    return (documentHeight == scrollDifference);
}

Resource: http://jquery.10927.n7.nabble.com/How-can-we-find-out-scrollbar-position-has-reached-at-the-bottom-in-js-td145336.html

Regards

If Else If In a Sql Server Function

Look at these lines:

If yes_ans > no_ans and yes_ans > na_ans

and similar. To what do "yes_ans" etc. refer? You're not using these in the context of a query; the "if exists" condition doesn't extend to the column names you're using inside.

Consider assigning those values to variables you can then use for your conditional flow below. Thus,

if exists (some record)
begin
   set @var = column, @var2 = column2, ...

   if (@var1 > @var2)
      -- do something

end

The return type is also mismatched with the declaration. It would help a lot if you indented, used ANSI-standard punctuation (terminate statements with semicolons), and left out superfluous begin/end - you don't need these for single-statement lines executed as the result of a test.

How to use http.client in Node.js if there is basic authorization

for what it's worth I'm using node.js 0.6.7 on OSX and I couldn't get 'Authorization':auth to work with our proxy, it needed to be set to 'Proxy-Authorization':auth my test code is:

var http = require("http");
var auth = 'Basic ' + new Buffer("username:password").toString('base64');
var options = {
    host: 'proxyserver',
    port: 80,
    method:"GET",
    path: 'http://www.google.com',
    headers:{
        "Proxy-Authorization": auth,
        Host: "www.google.com"
    } 
};
http.get(options, function(res) {
    console.log(res);
    res.pipe(process.stdout);
});

Displaying output of a remote command with Ansible

I'm not sure about the syntax of your specific commands (e.g., vagrant, etc), but in general...

Just register Ansible's (not-normally-shown) JSON output to a variable, then display each variable's stdout_lines attribute:

- name: Generate SSH keys for vagrant user
  user: name=vagrant generate_ssh_key=yes ssh_key_bits=2048
  register: vagrant
- debug: var=vagrant.stdout_lines

- name: Show SSH public key
  command: /bin/cat $home_directory/.ssh/id_rsa.pub
  register: cat
- debug: var=cat.stdout_lines

- name: Wait for user to copy SSH public key
  pause: prompt="Please add the SSH public key above to your GitHub account"
  register: pause
- debug: var=pause.stdout_lines

Way to create multiline comments in Bash?

I tried the chosen answer, but found when I ran a shell script having it, the whole thing was getting printed to screen (similar to how jupyter notebooks print out everything in '''xx''' quotes) and there was an error message at end. It wasn't doing anything, but: scary. Then I realised while editing it that single-quotes can span multiple lines. So.. lets just assign the block to a variable.

x='
echo "these lines will all become comments."
echo "just make sure you don_t use single-quotes!"

ls -l
date

'

Adding one day to a date

Try this

echo date('Y-m-d H:i:s',date(strtotime("+1 day", strtotime("2009-09-30 20:24:00"))));

Open a file with Notepad in C#

Use System.Diagnostics.Process to launch an instance of Notepad.exe.

Python unittest passing arguments

Even if the test gurus say that we should not do it: I do. In some context it makes a lot of sense to have parameters to drive the test in the right direction, for example:

  • which of the dozen identical USB cards should I use for this test now?
  • which server should I use for this test now?
  • which XXX should I use?

For me, the use of the environment variable is good enough for this puprose because you do not have to write dedicated code to pass your parameters around; it is supported by Python. It is clean and simple.

Of course, I'm not advocating for fully parametrizable tests. But we have to be pragmatic and, as I said, in some context you need a parameter or two. We should not abouse of it :)

import os
import unittest


class MyTest(unittest.TestCase):
    def setUp(self):
        self.var1 = os.environ["VAR1"]
        self.var2 = os.environ["VAR2"]

    def test_01(self):
        print("var1: {}, var2: {}".format(self.var1, self.var2))

Then from the command line (tested on Linux)

$ export VAR1=1
$ export VAR2=2
$ python -m unittest MyTest
var1: 1, var2: 2
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK

How to silence output in a Bash script?

Useful in scripts:


Get only the STDERR in a file, while hiding any STDOUT even if the program to hide isn't existing at all (does not ever hang parent script), this alone was working:

stty -echo && ./programMightNotExist 2> errors.log && stty echo

Detach completely and silence everything, even killing the parent script won't abort ./prog :

 ./prog </dev/null >/dev/null 2>&1 &

The name 'controlname' does not exist in the current context

Also, make sure you have no files that accidentally try to inherit or define the same (partial) class as other files. Note that these files can seem unrelated to the files where the error actually appeared!

`export const` vs. `export default` in ES6

I had the problem that the browser doesn't use ES6.

I have fix it with:

 <script type="module" src="index.js"></script>

The type module tells the browser to use ES6.

export const bla = [1,2,3];

import {bla} from './example.js';

Then it should work.

How to add directory to classpath in an application run profile in IntelliJ IDEA?

Suppose you need only x:target/classes in your classpath. Then you just add this folder to your classpath and %IDEA%\lib\idea_rt.jar. Now it will work. That's it.

sys.argv[1], IndexError: list index out of range

sys.argv represents the command line options you execute a script with.

sys.argv[0] is the name of the script you are running. All additional options are contained in sys.argv[1:].

You are attempting to open a file that uses sys.argv[1] (the first argument) as what looks to be the directory.

Try running something like this:

python ConcatenateFiles.py /tmp

How to compare two Carbon Timestamps?

First, Eloquent automatically converts it's timestamps (created_at, updated_at) into carbon objects. You could just use updated_at to get that nice feature, or specify edited_at in your model in the $dates property:

protected $dates = ['edited_at'];

Now back to your actual question. Carbon has a bunch of comparison functions:

  • eq() equals
  • ne() not equals
  • gt() greater than
  • gte() greater than or equals
  • lt() less than
  • lte() less than or equals

Usage:

if($model->edited_at->gt($model->created_at)){
    // edited at is newer than created at
}

ERROR: SQLSTATE[HY000] [2002] No connection could be made because the target machine actively refused it

Ensure your WAMP Server (or XAMP) is working, i.e. the wamp icon should be green.

Store output of subprocess.Popen call in a string

This works perfectly for me:

import subprocess
try:
    #prints results and merges stdout and std
    result = subprocess.check_output("echo %USERNAME%", stderr=subprocess.STDOUT, shell=True)
    print result
    #causes error and merges stdout and stderr
    result = subprocess.check_output("copy testfds", stderr=subprocess.STDOUT, shell=True)
except subprocess.CalledProcessError, ex: # error code <> 0 
    print "--------error------"
    print ex.cmd
    print ex.message
    print ex.returncode
    print ex.output # contains stdout and stderr together 

Upload File With Ajax XmlHttpRequest

  1. There is no such thing as xhr.file = file;; the file object is not supposed to be attached this way.
  2. xhr.send(file) doesn't send the file. You have to use the FormData object to wrap the file into a multipart/form-data post data object:

    var formData = new FormData();
    formData.append("thefile", file);
    xhr.send(formData);
    

After that, the file can be access in $_FILES['thefile'] (if you are using PHP).

Remember, MDC and Mozilla Hack demos are your best friends.

EDIT: The (2) above was incorrect. It does send the file, but it would send it as raw post data. That means you would have to parse it yourself on the server (and it's often not possible, depend on server configuration). Read how to get raw post data in PHP here.

How to uncheck a radio button?

Rewrite of Igor's code as plugin.

Use:

$('input[type=radio]').uncheckableRadio();

Plugin:

(function( $ ){

    $.fn.uncheckableRadio = function() {

        return this.each(function() {
            $(this).mousedown(function() {
                $(this).data('wasChecked', this.checked);
            });

            $(this).click(function() {
                if ($(this).data('wasChecked'))
                    this.checked = false;
            });
        });

    };

})( jQuery );

How to split a string, but also keep the delimiters?

I like the idea of StringTokenizer because it is Enumerable.
But it is also obsolete, and replace by String.split which return a boring String[] (and does not includes the delimiters).

So I implemented a StringTokenizerEx which is an Iterable, and which takes a true regexp to split a string.

A true regexp means it is not a 'Character sequence' repeated to form the delimiter:
'o' will only match 'o', and split 'ooo' into three delimiter, with two empty string inside:

[o], '', [o], '', [o]

But the regexp o+ will return the expected result when splitting "aooob"

[], 'a', [ooo], 'b', []

To use this StringTokenizerEx:

final StringTokenizerEx aStringTokenizerEx = new StringTokenizerEx("boo:and:foo", "o+");
final String firstDelimiter = aStringTokenizerEx.getDelimiter();
for(String aString: aStringTokenizerEx )
{
    // uses the split String detected and memorized in 'aString'
    final nextDelimiter = aStringTokenizerEx.getDelimiter();
}

The code of this class is available at DZone Snippets.

As usual for a code-challenge response (one self-contained class with test cases included), copy-paste it (in a 'src/test' directory) and run it. Its main() method illustrates the different usages.


Note: (late 2009 edit)

The article Final Thoughts: Java Puzzler: Splitting Hairs does a good work explaning the bizarre behavior in String.split().
Josh Bloch even commented in response to that article:

Yes, this is a pain. FWIW, it was done for a very good reason: compatibility with Perl.
The guy who did it is Mike "madbot" McCloskey, who now works with us at Google. Mike made sure that Java's regular expressions passed virtually every one of the 30K Perl regular expression tests (and ran faster).

The Google common-library Guava contains also a Splitter which is:

  • simpler to use
  • maintained by Google (and not by you)

So it may worth being checked out. From their initial rough documentation (pdf):

JDK has this:

String[] pieces = "foo.bar".split("\\.");

It's fine to use this if you want exactly what it does: - regular expression - result as an array - its way of handling empty pieces

Mini-puzzler: ",a,,b,".split(",") returns...

(a) "", "a", "", "b", ""
(b) null, "a", null, "b", null
(c) "a", null, "b"
(d) "a", "b"
(e) None of the above

Answer: (e) None of the above.

",a,,b,".split(",")
returns
"", "a", "", "b"

Only trailing empties are skipped! (Who knows the workaround to prevent the skipping? It's a fun one...)

In any case, our Splitter is simply more flexible: The default behavior is simplistic:

Splitter.on(',').split(" foo, ,bar, quux,")
--> [" foo", " ", "bar", " quux", ""]

If you want extra features, ask for them!

Splitter.on(',')
.trimResults()
.omitEmptyStrings()
.split(" foo, ,bar, quux,")
--> ["foo", "bar", "quux"]

Order of config methods doesn't matter -- during splitting, trimming happens before checking for empties.

Failed to install Python Cryptography package with PIP and setup.py

I encountered a similar issue recently. In my case the versions of cffi and cryptography written in requirements.txt weren't compatible (cffi==1.8.9 and cryptography==1.9). I solved updating cffi with the last available version.

Use of exit() function

exit(int code); is declared in stdlib.h so you need an

#include <stdlib.h>

Also:
- You have no parameter for the exit(), it requires an int so provide one.
- Burn this book, it uses goto which is (for everyone but linux kernel hackers) bad, very, very, VERY bad.

Edit:
Oh, and

void main()

is bad, too, it's:

int main(int argc, char *argv[])

How to override the path of PHP to use the MAMP path?

you might still run into mysql binary not being found in that manner

open terminal, type
touch ~/.bash_profile; open ~/.bash_profile

edit as follows below, save, quite and restart terminal or alternately

source ~/.bash_profile

to execute new PATH without restarting terminal

and in the fashion of the DavidYell's post above, also add the following. You can stack various variables by exporting them followed by a single PATH export which I demonstrated below

export MAMP_PHP=/Applications/MAMP/bin/php/php5.6.2/bin
export MAMP_BINS=/Applications/MAMP/Library/bin
export USERBINS=~/bins
export PATH="$USERBINS:$MAMP_PHP:$MAMP_BINS:$PATH"

cheers

how to convert current date to YYYY-MM-DD format with angular 2

Here is a very nice and compact way to do this, you can also change this function as your case needs:

result: 03.11.2017

//get date now function
    getNowDate() {
    //return string
    var returnDate = "";
    //get datetime now
    var today = new Date();
    //split
    var dd = today.getDate();
    var mm = today.getMonth() + 1; //because January is 0! 
    var yyyy = today.getFullYear();
    //Interpolation date
    if (dd < 10) {
        returnDate += `0${dd}.`;
    } else {
        returnDate += `${dd}.`;
    }

    if (mm < 10) {
        returnDate += `0${mm}.`;
    } else {
        returnDate += `${mm}.`;
    }
    returnDate += yyyy;
    return returnDate;
}

Apache redirect to another port

Found this out by trial and error. If your configuration specifies a ServerName, then your VirtualHost directive will need to do the same. In the following example, awesome.example.com and amazing.example.com would both be forwarded to some local service running on port 4567.

ServerName example.com:80

<VirtualHost example.com:80>
  ProxyPreserveHost On
  ProxyRequests Off
  ServerName awesome.example.com
  ServerAlias amazing.example.com
  ProxyPass / http://localhost:4567/
  ProxyPassReverse / http://localhost:4567/
</VirtualHost>

I know this doesn't exactly answer the question, but I'm putting it here because this is the top search result for Apache port forwarding. So I figure it'll help somebody someday.

Vertically align text next to an image?

Actually, in this case it's quite simple: apply the vertical align to the image. Since it's all in one line, it's really the image you want aligned, not the text.

_x000D_
_x000D_
<!-- moved "vertical-align:middle" style from span to img -->_x000D_
<div>_x000D_
  <img style="vertical-align:middle" src="https://placehold.it/60x60">_x000D_
  <span style="">Works.</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Tested in FF3.

Now you can use flexbox for this type of layout.

_x000D_
_x000D_
.box {_x000D_
   display: flex;_x000D_
   align-items:center;_x000D_
}
_x000D_
<div class="box">_x000D_
    <img src="https://placehold.it/60x60">_x000D_
    <span style="">Works.</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Choosing a file in Python with simple Dialog

Another option to consider is Zenity: http://freecode.com/projects/zenity.

I had a situation where I was developing a Python server application (no GUI component) and hence didn't want to introduce a dependency on any python GUI toolkits, but I wanted some of my debug scripts to be parameterized by input files and wanted to visually prompt the user for a file if they didn't specify one on the command line. Zenity was a perfect fit. To achieve this, invoke "zenity --file-selection" using the subprocess module and capture the stdout. Of course this solution isn't Python-specific.

Zenity supports multiple platforms and happened to already be installed on our dev servers so it facilitated our debugging/development without introducing an unwanted dependency.

Constructor in an Interface?

A problem that you get when you allow constructors in interfaces comes from the possibility to implement several interfaces at the same time. When a class implements several interfaces that define different constructors, the class would have to implement several constructors, each one satisfying only one interface, but not the others. It will be impossible to construct an object that calls each of these constructors.

Or in code:

interface Named { Named(String name); }
interface HasList { HasList(List list); }

class A implements Named, HasList {

  /** implements Named constructor.
   * This constructor should not be used from outside, 
   * because List parameter is missing
   */
  public A(String name)  { 
    ...
  }

  /** implements HasList constructor.
   * This constructor should not be used from outside, 
   * because String parameter is missing
   */
  public A(List list) {
    ...
  }

  /** This is the constructor that we would actually 
   * need to satisfy both interfaces at the same time
   */ 
  public A(String name, List list) {
    this(name);
    // the next line is illegal; you can only call one other super constructor
    this(list); 
  }
}

sass --watch with automatic minify?

There are some different way to do that

sass --watch --style=compressed main.scss main.css

or

sass --watch a.scss:a.css --style compressed

or

By Using visual studio code extension live sass compiler

see more

Get JSON object from URL

$json = file_get_contents('url_here');
$obj = json_decode($json);
echo $obj->access_token;

For this to work, file_get_contents requires that allow_url_fopen is enabled. This can be done at runtime by including:

ini_set("allow_url_fopen", 1);

You can also use curl to get the url. To use curl, you can use the example found here:

$ch = curl_init();
// IMPORTANT: the below line is a security risk, read https://paragonie.com/blog/2017/10/certainty-automated-cacert-pem-management-for-php-software
// in most cases, you should set it to true
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, 'url_here');
$result = curl_exec($ch);
curl_close($ch);

$obj = json_decode($result);
echo $obj->access_token;

How to use bitmask?

Briefly bitmask helps to manipulate position of multiple values. There is a good example here ;

Bitflags are a method of storing multiple values, which are not mutually exclusive, in one variable. You've probably seen them before. Each flag is a bit position which can be set on or off. You then have a bunch of bitmasks #defined for each bit position so you can easily manipulate it:

    #define LOG_ERRORS            1  // 2^0, bit 0
    #define LOG_WARNINGS          2  // 2^1, bit 1
    #define LOG_NOTICES           4  // 2^2, bit 2
    #define LOG_INCOMING          8  // 2^3, bit 3
    #define LOG_OUTGOING         16  // 2^4, bit 4
    #define LOG_LOOPBACK         32  // and so on...

// Only 6 flags/bits used, so a char is fine
unsigned char flags;

// initialising the flags
// note that assigning a value will clobber any other flags, so you
// should generally only use the = operator when initialising vars.
flags = LOG_ERRORS;
// sets to 1 i.e. bit 0

//initialising to multiple values with OR (|)
flags = LOG_ERRORS | LOG_WARNINGS | LOG_INCOMING;
// sets to 1 + 2 + 8 i.e. bits 0, 1 and 3

// setting one flag on, leaving the rest untouched
// OR bitmask with the current value
flags |= LOG_INCOMING;

// testing for a flag
// AND with the bitmask before testing with ==
if ((flags & LOG_WARNINGS) == LOG_WARNINGS)
   ...

// testing for multiple flags
// as above, OR the bitmasks
if ((flags & (LOG_INCOMING | LOG_OUTGOING))
         == (LOG_INCOMING | LOG_OUTGOING))
   ...

// removing a flag, leaving the rest untouched
// AND with the inverse (NOT) of the bitmask
flags &= ~LOG_OUTGOING;

// toggling a flag, leaving the rest untouched
flags ^= LOG_LOOPBACK;



**

WARNING: DO NOT use the equality operator (i.e. bitflags == bitmask) for testing if a flag is set - that expression will only be true if that flag is set and all others are unset. To test for a single flag you need to use & and == :

**

if (flags == LOG_WARNINGS) //DON'T DO THIS
   ...
if ((flags & LOG_WARNINGS) == LOG_WARNINGS) // The right way
   ...
if ((flags & (LOG_INCOMING | LOG_OUTGOING)) // Test for multiple flags set
         == (LOG_INCOMING | LOG_OUTGOING))
   ...

You can also search C++ Triks

Why is System.Web.Mvc not listed in Add References?

I have had the same problem and here is the funny reason: My guess is that you expect System.Web.Mvc to be located under System.Web in the list. But the list is not alphabetical.

First sort the list and then look near the System.Web.

MySQL INNER JOIN Alias

Use a seperate column to indicate the join condition

SELECT  t.importid, 
        case 
            when t.importid = g.home 
            then 'home' 
            else 'away' 
        end as join_condition, 
        g.network, 
        g.date_start 
FROM    game g
INNER JOIN team t ON (t.importid = g.home OR t.importid = g.away)
ORDER BY date_start DESC 
LIMIT 7

Creating a BAT file for python script

Here's how you can put both batch code and the python one in single file:

0<0# : ^
''' 
@echo off
echo batch code
python "%~f0" %*
exit /b 0
'''

print("python code")

the ''' respectively starts and ends python multi line comments.

0<0# : ^ is more interesting - due to redirection priority in batch it will be interpreted like :0<0# ^ by the batch script which is a label which execution will be not displayed on the screen. The caret at the end will escape the new line and second line will be attached to the first line.For python it will be 0<0 statement and a start of inline comment.

The credit goes to siberia-man

CMD command to check connected USB devices

You can use the wmic command:

wmic path CIM_LogicalDevice where "Description like 'USB%'" get /value

How to convert a date string to different format

I assume I have import datetime before running each of the lines of code below

datetime.datetime.strptime("2013-1-25", '%Y-%m-%d').strftime('%m/%d/%y')

prints "01/25/13".

If you can't live with the leading zero, try this:

dt = datetime.datetime.strptime("2013-1-25", '%Y-%m-%d')
print '{0}/{1}/{2:02}'.format(dt.month, dt.day, dt.year % 100)

This prints "1/25/13".

EDIT: This may not work on every platform:

datetime.datetime.strptime("2013-1-25", '%Y-%m-%d').strftime('%m/%d/%y')

What does (function($) {})(jQuery); mean?

Type 3, in order to work would have to look like this:

(function($){
    //Attach this new method to jQuery
    $.fn.extend({     
        //This is where you write your plugin's name
        'pluginname': function(_options) {
            // Put defaults inline, no need for another variable...
            var options =  $.extend({
                'defaults': "go here..."
            }, _options);

            //Iterate over the current set of matched elements
            return this.each(function() {

                //code to be inserted here

            });
        }
    }); 
})(jQuery);

I am unsure why someone would use extend over just directly setting the property in the jQuery prototype, it is doing the same exact thing only in more operations and more clutter.

Can I change the viewport meta tag in mobile safari on the fly?

in your <head>

<meta id="viewport"
      name="viewport"
      content="width=1024, height=768, initial-scale=0, minimum-scale=0.25" />

somewhere in your javascript

document.getElementById("viewport").setAttribute("content",
      "initial-scale=0.5; maximum-scale=1.0; user-scalable=0;");

... but good luck with tweaking it for your device, fiddling for hours... and i'm still not there!

source

In SQL, is UPDATE always faster than DELETE+INSERT?

Keep in mind the actual fragmentation that occurs when DELETE+INSERT is issued opposed to a correctly implemented UPDATE will make great difference by time.

Thats why, for instance, REPLACE INTO that MySQL implements is discouraged as opposed to using the INSERT INTO ... ON DUPLICATE KEY UPDATE ... syntax.

How to recover closed output window in netbeans?

Easy way, just write some wrong code and Run > Build it will show the error in output window.

I tried all of the above but no success, just this one worked.

CSS: How to have position:absolute div inside a position:relative div not be cropped by an overflow:hidden on a container

There's no magical solution of displaying something outside an overflow hidden container.

A similar effect can be achieved by having an absolute positioned div that matches the size of its parent by positioning it inside your current relative container (the div you don't wish to clip should be outside this div):

#1 .mask {
  width: 100%;
  height: 100%;
  position: absolute;
  z-index: 1;
  overflow: hidden;
}

Take in mind that if you only have to clip content on the x axis (which appears to be your case, as you only have set the div's width), you can use overflow-x: hidden.

How to match any non white space character except a particular one?

On my system: CentOS 5

I can use \s outside of collections but have to use [:space:] inside of collections. In fact I can use [:space:] only inside collections. So to match a single space using this I have to use [[:space:]] Which is really strange.

echo a b cX | sed -r "s/(a\sb[[:space:]]c[^[:space:]])/Result: \1/"

Result: a b cX
  • first space I match with \s
  • second space I match alternatively with [[:space:]]
  • the X I match with "all but no space" [^[:space:]]

These two will not work:

a[:space:]b  instead use a\sb or a[[:space:]]b

a[^\s]b      instead use a[^[:space:]]b

How to access PHP session variables from jQuery function in a .js file?

This is strictly not speaking using jQuery, but I have found this method easier than using jQuery. There are probably endless methods of achieving this and many clever ones here, but not all have worked for me. However the following method has always worked and I am passing it one in case it helps someone else.

Three javascript libraries are required, createCookie, readCookie and eraseCookie. These libraries are not mine but I began using them about 5 years ago and don't know their origin.

createCookie = function(name, value, days) {
if (days) {
    var date = new Date();
    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
    var expires = "; expires=" + date.toGMTString();
}
else var expires = "";

document.cookie = name + "=" + value + expires + "; path=/";
}

readCookie = function (name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') c = c.substring(1, c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
eraseCookie = function (name) {
   createCookie(name, "", -1);
}

To call them you need to create a small PHP function, normally as part of your support library, as follows:

<?php
 function createjavaScriptCookie($sessionVarible) {
 $s =  "<script>";
 $s = $s.'createCookie('. '"'. $sessionVarible                 
 .'",'.'"'.$_SESSION[$sessionVarible].'"'. ',"1"'.')';
 $s = $s."</script>";
 echo $s;
}
?>

So to use all you now have to include within your index.php file is

$_SESSION["video_dir"] = "/video_dir/";
createjavaScriptCookie("video_dir");

Now in your javascript library.js you can recover the cookie with the following code:

var videoPath = readCookie("video_dir") +'/'+ video_ID + '.mp4';

I hope this helps.

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

If using win7 64 bit OS:

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

Mad

edit:

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

Cannot import keras after installation

Diagnose

If you have pip installed (you should have it until you use Python 3.5), list the installed Python packages, like this:

$ pip list | grep -i keras
Keras (1.1.0)

If you don’t see Keras, it means that the previous installation failed or is incomplete (this lib has this dependancies: numpy (1.11.2), PyYAML (3.12), scipy (0.18.1), six (1.10.0), and Theano (0.8.2).)

Consult the pip.log to see what’s wrong.

You can also display your Python path like this:

$ python3 -c 'import sys, pprint; pprint.pprint(sys.path)'
['',
 '/Library/Frameworks/Python.framework/Versions/3.5/lib/python35.zip',
 '/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5',
 '/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/plat-darwin',
 '/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/lib-dynload',
 '/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages']

Make sure the Keras library appears in the /Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages path (the path is different on Ubuntu).

If not, try do uninstall it, and retry installation:

$ pip uninstall Keras

Use a virtualenv

It’s a bad idea to use and pollute your system-wide Python. I recommend using a virtualenv (see this guide).

The best usage is to create a virtualenv directory (in your home, for instance), and store your virtualenvs in:

cd virtualenv/
virtualenv -p python3.5 py-keras
source py-keras/bin/activate
pip install -q -U pip setuptools wheel

Then install Keras:

pip install keras

You get:

$ pip list
Keras (1.1.0)
numpy (1.11.2)
pip (8.1.2)
PyYAML (3.12)
scipy (0.18.1)
setuptools (28.3.0)
six (1.10.0)
Theano (0.8.2)
wheel (0.30.0a0)

But, you also need to install extra libraries, like Tensorflow:

$ python -c "import keras"
Using TensorFlow backend.
Traceback (most recent call last):
  ...
ImportError: No module named 'tensorflow'

The installation guide of TesnsorFlow is here: https://www.tensorflow.org/versions/r0.11/get_started/os_setup.html#pip-installation

'NOT LIKE' in an SQL query

After "AND" and after "OR" the QUERY has forgotten what it is all about.

I would also not know that it is about in any SQL / programming language.

if(SOMETHING equals "X" or SOMETHING equals "Y")

COLUMN NOT LIKE "A%" AND COLUMN NOT LIKE "B%"

How to get jQuery dropdown value onchange event

$('#drop').change(
    function() {
        var val1 = $('#pick option:selected').val();
        var val2 = $('#drop option:selected').val();

        // Do something with val1 and val2 ...
    }
);

Using bootstrap with bower

I finally ended using the following : bower install --save http://twitter.github.com/bootstrap/assets/bootstrap.zip

Seems cleaner to me since it doesn't clone the whole repo, it only unzip the required assests.

The downside of that is that it breaks the bower philosophy since a bower update will not update bootstrap.

But I think it's still cleaner than using bower install bootstrap and then building bootstrap in your workflow.

It's a matter of choice I guess.

Update : seems they now version a dist folder (see: https://github.com/twbs/bootstrap/pull/6342), so just use bower install bootstrap and point to the assets in the dist folder

Parse XLSX with Node and create json

I think this code will do what you want. It stores the first row as a set of headers, then stores the rest in a data object which you can write to disk as JSON.

var XLSX = require('xlsx');
var workbook = XLSX.readFile('test.xlsx');
var sheet_name_list = workbook.SheetNames;
sheet_name_list.forEach(function(y) {
    var worksheet = workbook.Sheets[y];
    var headers = {};
    var data = [];
    for(z in worksheet) {
        if(z[0] === '!') continue;
        //parse out the column, row, and value
        var col = z.substring(0,1);
        var row = parseInt(z.substring(1));
        var value = worksheet[z].v;

        //store header names
        if(row == 1) {
            headers[col] = value;
            continue;
        }

        if(!data[row]) data[row]={};
        data[row][headers[col]] = value;
    }
    //drop those first two rows which are empty
    data.shift();
    data.shift();
    console.log(data);
});

prints out

[ { id: 1,
    headline: 'team: sally pearson',
    location: 'Australia',
    'body text': 'majority have…',
    media: 'http://www.youtube.com/foo' },
  { id: 2,
    headline: 'Team: rebecca',
    location: 'Brazil',
    'body text': 'it is a long established…',
    media: 'http://s2.image.foo/' } ]

HTTP POST with URL query parameters -- good idea or not?

I would think it could still be quite RESTful to have query arguments that identify the resource on the URL while keeping the content payload confined to the POST body. This would seem to separate the considerations of "What am I sending?" versus "Who am I sending it to?".

What is the __del__ method, How to call it?

I wrote up the answer for another question, though this is a more accurate question for it.

How do constructors and destructors work?

Here is a slightly opinionated answer.

Don't use __del__. This is not C++ or a language built for destructors. The __del__ method really should be gone in Python 3.x, though I'm sure someone will find a use case that makes sense. If you need to use __del__, be aware of the basic limitations per http://docs.python.org/reference/datamodel.html:

  • __del__ is called when the garbage collector happens to be collecting the objects, not when you lose the last reference to an object and not when you execute del object.
  • __del__ is responsible for calling any __del__ in a superclass, though it is not clear if this is in method resolution order (MRO) or just calling each superclass.
  • Having a __del__ means that the garbage collector gives up on detecting and cleaning any cyclic links, such as losing the last reference to a linked list. You can get a list of the objects ignored from gc.garbage. You can sometimes use weak references to avoid the cycle altogether. This gets debated now and then: see http://mail.python.org/pipermail/python-ideas/2009-October/006194.html.
  • The __del__ function can cheat, saving a reference to an object, and stopping the garbage collection.
  • Exceptions explicitly raised in __del__ are ignored.
  • __del__ complements __new__ far more than __init__. This gets confusing. See http://www.algorithm.co.il/blogs/programming/python-gotchas-1-del-is-not-the-opposite-of-init/ for an explanation and gotchas.
  • __del__ is not a "well-loved" child in Python. You will notice that sys.exit() documentation does not specify if garbage is collected before exiting, and there are lots of odd issues. Calling the __del__ on globals causes odd ordering issues, e.g., http://bugs.python.org/issue5099. Should __del__ called even if the __init__ fails? See http://mail.python.org/pipermail/python-dev/2000-March/thread.html#2423 for a long thread.

But, on the other hand:

And my pesonal reason for not liking the __del__ function.

  • Everytime someone brings up __del__ it devolves into thirty messages of confusion.
  • It breaks these items in the Zen of Python:
    • Simple is better than complicated.
    • Special cases aren't special enough to break the rules.
    • Errors should never pass silently.
    • In the face of ambiguity, refuse the temptation to guess.
    • There should be one – and preferably only one – obvious way to do it.
    • If the implementation is hard to explain, it's a bad idea.

So, find a reason not to use __del__.

How to destroy a JavaScript object?

I was facing a problem like this, and had the idea of simply changing the innerHTML of the problematic object's children.

adiv.innerHTML = "<div...> the original html that js uses </div>";

Seems dirty, but it saved my life, as it works!

How to get the python.exe location programmatically?

This works in Linux & Windows:

Python 3.x

>>> import sys
>>> print(sys.executable)
C:\path\to\python.exe

Python 2.x

>>> import sys
>>> print sys.executable
/usr/bin/python

What are the best use cases for Akka framework

We use Akka in several projects at work, the most interesting of which is related to vehicle crash repair. Primarily in the UK but now expanding to the US, Asia, Australasia and Europe. We use actors to ensure that crash repair information is provided realtime to enable the safe and cost effective repair of vehicles.

The question with Akka is really more 'what can't you do with Akka'. Its ability to integrate with powerful frameworks, its powerful abstraction and all of the fault tolerance aspects make it a very comprehensive toolkit.

Format an Excel column (or cell) as Text in C#?

   if (dtCustomers.Columns[j - 1].DataType != typeof(decimal) && dtCustomers.Columns[j - 1].DataType != typeof(int))
   {
      myWorksheet.Cells[i + 2, j].NumberFormat = "@";
   }

Margin while printing html page

Updated, Simple Solution

@media print {
   body {
       display: table;
       table-layout: fixed;
       padding-top: 2.5cm;
       padding-bottom: 2.5cm;
       height: auto;
   }
}

Old Solution

Create section with each page, and use the below code to adjust margins, height and width.

If you are printing A4 size.

Then user

Size : 8.27in and 11.69 inches

@page Section1 {
    size: 8.27in 11.69in; 
    margin: .5in .5in .5in .5in; 
    mso-header-margin: .5in; 
    mso-footer-margin: .5in; 
    mso-paper-source: 0;
}



div.Section1 {
    page: Section1;
} 

then create a div with all your content in it.

<div class="Section1"> 
    type your content here... 
</div>

PHP Remove elements from associative array

  ...

  $array = array(
      1 => 'Awaiting for Confirmation', 
      2 => 'Asssigned', 
      3 => 'In Progress', 
      4 => 'Completed', 
      5 => 'Mark As Spam', 
  );



  return array_values($array);
  ...

Meaning of = delete after function declaration

A deleted function is implicitly inline

(Addendum to existing answers)

... And a deleted function shall be the first declaration of the function (except for deleting explicit specializations of function templates - deletion should be at the first declaration of the specialization), meaning you cannot declare a function and later delete it, say, at its definition local to a translation unit.

Citing [dcl.fct.def.delete]/4:

A deleted function is implicitly inline. ( Note: The one-definition rule ([basic.def.odr]) applies to deleted definitions. — end note ] A deleted definition of a function shall be the first declaration of the function or, for an explicit specialization of a function template, the first declaration of that specialization. [ Example:

struct sometype {
  sometype();
};
sometype::sometype() = delete;      // ill-formed; not first declaration

end example )

A primary function template with a deleted definition can be specialized

Albeit a general rule of thumb is to avoid specializing function templates as specializations do not participate in the first step of overload resolution, there are arguable some contexts where it can be useful. E.g. when using a non-overloaded primary function template with no definition to match all types which one would not like implicitly converted to an otherwise matching-by-conversion overload; i.e., to implicitly remove a number of implicit-conversion matches by only implementing exact type matches in the explicit specialization of the non-defined, non-overloaded primary function template.

Before the deleted function concept of C++11, one could do this by simply omitting the definition of the primary function template, but this gave obscure undefined reference errors that arguably gave no semantic intent whatsoever from the author of primary function template (intentionally omitted?). If we instead explicitly delete the primary function template, the error messages in case no suitable explicit specialization is found becomes much nicer, and also shows that the omission/deletion of the primary function template's definition was intentional.

#include <iostream>
#include <string>

template< typename T >
void use_only_explicit_specializations(T t);

template<>
void use_only_explicit_specializations<int>(int t) {
    std::cout << "int: " << t;
}

int main()
{
    const int num = 42;
    const std::string str = "foo";
    use_only_explicit_specializations(num);  // int: 42
    //use_only_explicit_specializations(str); // undefined reference to `void use_only_explicit_specializations< ...
}

However, instead of simply omitting a definition for the primary function template above, yielding an obscure undefined reference error when no explicit specialization matches, the primary template definition can be deleted:

#include <iostream>
#include <string>

template< typename T >
void use_only_explicit_specializations(T t) = delete;

template<>
void use_only_explicit_specializations<int>(int t) {
    std::cout << "int: " << t;
}

int main()
{
    const int num = 42;
    const std::string str = "foo";
    use_only_explicit_specializations(num);  // int: 42
    use_only_explicit_specializations(str);
    /* error: call to deleted function 'use_only_explicit_specializations' 
       note: candidate function [with T = std::__1::basic_string<char>] has 
       been explicitly deleted
       void use_only_explicit_specializations(T t) = delete; */
}

Yielding a more more readable error message, where the deletion intent is also clearly visible (where an undefined reference error could lead to the developer thinking this an unthoughtful mistake).

Returning to why would we ever want to use this technique? Again, explicit specializations could be useful to implicitly remove implicit conversions.

#include <cstdint>
#include <iostream>

void warning_at_best(int8_t num) { 
    std::cout << "I better use -Werror and -pedantic... " << +num << "\n";
}

template< typename T >
void only_for_signed(T t) = delete;

template<>
void only_for_signed<int8_t>(int8_t t) {
    std::cout << "UB safe! 1 byte, " << +t << "\n";
}

template<>
void only_for_signed<int16_t>(int16_t t) {
    std::cout << "UB safe! 2 bytes, " << +t << "\n";
}

int main()
{
    const int8_t a = 42;
    const uint8_t b = 255U;
    const int16_t c = 255;
    const float d = 200.F;

    warning_at_best(a); // 42
    warning_at_best(b); // implementation-defined behaviour, no diagnostic required
    warning_at_best(c); // narrowing, -Wconstant-conversion warning
    warning_at_best(d); // undefined behaviour!

    only_for_signed(a);
    only_for_signed(c);

    //only_for_signed(b);  
    /* error: call to deleted function 'only_for_signed' 
       note: candidate function [with T = unsigned char] 
             has been explicitly deleted
       void only_for_signed(T t) = delete; */

    //only_for_signed(d);
    /* error: call to deleted function 'only_for_signed' 
       note: candidate function [with T = float] 
             has been explicitly deleted
       void only_for_signed(T t) = delete; */
}

How to use the TextWatcher class in Android?

    public class Test extends AppCompatActivity {

    EditText firstEditText;
    EditText secondEditText;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.test);
        firstEditText = (EditText)findViewById(R.id.firstEditText);
        secondEditText = (EditText)findViewById(R.id.secondEditText);

        firstEditText.addTextChangedListener(new EditTextListener());

    }

    private class EditTextListener implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            secondEditText.setText(firstEditText.getText());
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    }
}

Is it possible to get a list of files under a directory of a website? How?

Any crawler or spider will read your index.htm or equivalent, that is exposed to the web, they will read the source code for that page, and find everything that is associated to that webpage and contains subdirectories. If they find a "contact us" button, there may be is included the path to the webpage or php that deal with the contact-us action, so they now have one more subdirectory/folder name to crawl and dig more. But even so, if that folder has a index.htm or equivalent file, it will not list all the files in such folder.

If by mistake, the programmer never included an index.htm file in such folder, then all the files will be listed on your computer screen, and also for the crawler/spider to keep digging. But, if you created a folder www.yoursite.com/nombresinistro75crazyragazzo19/ and put several files in there, and never published any button or never exposed that folder address anywhere in the net, keeping only in your head, chances are that nobody ever will find that path, with crawler or spider, for more sophisticated it can be.

Except, of course, if they can enter your FTP or access your site control panel.

How to hide .php extension in .htaccess

The other option for using PHP scripts sans extension is

Options +MultiViews

Or even just following in the directories .htaccess:

DefaultType application/x-httpd-php

The latter allows having all filenames without extension script being treated as PHP scripts. While MultiViews makes the webserver look for alternatives, when just the basename is provided (there's a performance hit with that however).

How to exclude file only from root folder in Git

If the above solution does not work for you, try this:

#1.1 Do NOT ignore file pattern in  any subdirectory
!*/config.php
#1.2 ...only ignore it in the current directory
/config.php

##########################

# 2.1 Ignore file pattern everywhere
config.php
# 2.2 ...but NOT in the current directory
!/config.php

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

I faced the same issue while trying to transpile some jsx with babel. Below is the solution that worked for me. You can add the following json to your .babelrc

{
  "presets": [
    [
      "@babel/preset-react",
      { "targets": { "browsers": ["last 3 versions", "safari >= 6"] } }
    ]
  ],
  "plugins": [["@babel/plugin-proposal-class-properties"]]
}

pandas DataFrame: replace nan values with average of columns

You can simply use DataFrame.fillna to fill the nan's directly:

In [27]: df 
Out[27]: 
          A         B         C
0 -0.166919  0.979728 -0.632955
1 -0.297953 -0.912674 -1.365463
2 -0.120211 -0.540679 -0.680481
3       NaN -2.027325  1.533582
4       NaN       NaN  0.461821
5 -0.788073       NaN       NaN
6 -0.916080 -0.612343       NaN
7 -0.887858  1.033826       NaN
8  1.948430  1.025011 -2.982224
9  0.019698 -0.795876 -0.046431

In [28]: df.mean()
Out[28]: 
A   -0.151121
B   -0.231291
C   -0.530307
dtype: float64

In [29]: df.fillna(df.mean())
Out[29]: 
          A         B         C
0 -0.166919  0.979728 -0.632955
1 -0.297953 -0.912674 -1.365463
2 -0.120211 -0.540679 -0.680481
3 -0.151121 -2.027325  1.533582
4 -0.151121 -0.231291  0.461821
5 -0.788073 -0.231291 -0.530307
6 -0.916080 -0.612343 -0.530307
7 -0.887858  1.033826 -0.530307
8  1.948430  1.025011 -2.982224
9  0.019698 -0.795876 -0.046431

The docstring of fillna says that value should be a scalar or a dict, however, it seems to work with a Series as well. If you want to pass a dict, you could use df.mean().to_dict().

Format date and time in a Windows batch script

If you don't exactly need this format:

2009_07_28__08_36_01

Then you could use the following 3 lines of code which uses %date% and %time%:

set mydate=%date:/=%
set mytime=%time::=%
set mytimestamp=%mydate: =_%_%mytime:.=_%

Note: The characters / and : are removed and the character . and space is replaced with an underscore.

Example output (taken Wednesday 8/5/15 at 12:49 PM with 50 seconds and 93 milliseconds):

echo %mytimestamp%
Wed_08052015_124950_93

How do I set up CLion to compile and run?

I ran into the same issue with CLion 1.2.1 (at the time of writing this answer) after updating Windows 10. It was working fine before I had updated my OS. My OS is installed in C:\ drive and CLion 1.2.1 and Cygwin (64-bit) are installed in D:\ drive.

The issue seems to be with CMake. I am using Cygwin. Below is the short answer with steps I used to fix the issue.

SHORT ANSWER (should be similar for MinGW too but I haven't tried it):

  1. Install Cygwin with GCC, G++, GDB and CMake (the required versions)
  2. Add full path to Cygwin 'bin' directory to Windows Environment variables
  3. Restart CLion and check 'Settings' -> 'Build, Execution, Deployment' to make sure CLion has picked up the right versions of Cygwin, make and gdb
  4. Check the project configuration ('Run' -> 'Edit configuration') to make sure your project name appears there and you can select options in 'Target', 'Configuration' and 'Executable' fields.
  5. Build and then Run
  6. Enjoy

LONG ANSWER:

Below are the detailed steps that solved this issue for me:

  1. Uninstall/delete the previous version of Cygwin (MinGW in your case)

  2. Make sure that CLion is up-to-date

  3. Run Cygwin setup (x64 for my 64-bit OS)

  4. Install at least the following packages for Cygwin: gcc g++ make Cmake gdb Make sure you are installing the correct versions of the above packages that CLion requires. You can find the required version numbers at CLion's Quick Start section (I cannot post more than 2 links until I have more reputation points).

  5. Next, you need to add Cygwin (or MinGW) to your Windows Environment Variable called 'Path'. You can Google how to find environment variables for your version of Windows

[On Win 10, right-click on 'This PC' and select Properties -> Advanced system settings -> Environment variables... -> under 'System Variables' -> find 'Path' -> click 'Edit']

  1. Add the 'bin' folder to the Path variable. For Cygwin, I added: D:\cygwin64\bin

  2. Start CLion and go to 'Settings' either from the 'Welcome Screen' or from File -> Settings

  3. Select 'Build, Execution, Deployment' and then click on 'Toolchains'

  4. Your 'Environment' should show the correct path to your Cygwin installation directory (or MinGW)

  5. For 'CMake executable', select 'Use bundled CMake x.x.x' (3.3.2 in my case at the time of writing this answer)

  6. 'Debugger' shown to me says 'Cygwin GDB GNU gdb (GDB) 7.8' [too many gdb's in that line ;-)]

  7. Below that it should show a checkmark for all the categories and should also show the correct path to 'make', 'C compiler' and 'C++ compiler'

See screenshot: Check all paths to the compiler, make and gdb

  1. Now go to 'Run' -> 'Edit configuration'. You should see your project name in the left-side panel and the configurations on the right side

See screenshot: Check the configuration to run the project

  1. There should be no errors in the console window. You will see that the 'Run' -> 'Build' option is now active

  2. Build your project and then run the project. You should see the output in the terminal window

Hope this helps! Good luck and enjoy CLion.

Print a list of space-separated elements in Python 3

Although the accepted answer is absolutely clear, I just wanted to check efficiency in terms of time.

The best way is to print joined string of numbers converted to strings.

print(" ".join(list(map(str,l))))

Note that I used map instead of loop. I wrote a little code of all 4 different ways to compare time:

import time as t

a, b = 10, 210000
l = list(range(a, b))
tic = t.time()
for i in l:
    print(i, end=" ")

print()
tac = t.time()
t1 = (tac - tic) * 1000
print(*l)
toe = t.time()
t2 = (toe - tac) * 1000
print(" ".join([str(i) for i in l]))
joe = t.time()
t3 = (joe - toe) * 1000
print(" ".join(list(map(str, l))))
toy = t.time()
t4 = (toy - joe) * 1000
print("Time",t1,t2,t3,t4)

Result:

Time 74344.76 71790.83 196.99 153.99

The output was quite surprising to me. Huge difference of time in cases of 'loop method' and 'joined-string method'.

Conclusion: Do not use loops for printing list if size is too large( in order of 10**5 or more).

Speed tradeoff of Java's -Xms and -Xmx options

I have found that in some cases too much memory can slow the program down.

For example I had a hibernate based transform engine that started running slowly as the load increased. It turned out that each time we got an object from the db, hibernate was checking memory for objects that would never be used again.

The solution was to evict the old objects from the session.

Stuart

How to insert a large block of HTML in JavaScript?

Add each line of the code to a variable and then write the variable to your inner HTML. See below:

var div = document.createElement('div');
div.setAttribute('class', 'post block bc2');
var str = "First Line";
str += "Second Line";
str += "So on, all of your lines";
div.innerHTML = str;
document.getElementById('posts').appendChild(div);

Control the size of points in an R scatterplot?

Try the cex argument:

?par

  • cex
    A numerical value giving the amount by which plotting text and symbols should be magnified relative to the default. Note that some graphics functions such as plot.default have an argument of this name which multiplies this graphical parameter, and some functions such as points accept a vector of values which are recycled. Other uses will take just the first value if a vector of length greater than one is supplied.

Why does ++[[]][+[]]+[+[]] return the string "10"?

Step by steps of that, + turn value to a number and if you add to an empty array +[]...as it's empty and is equal to 0, it will

So from there, now look into your code, it's ++[[]][+[]]+[+[]]...

And there is plus between them ++[[]][+[]] + [+[]]

So these [+[]] will return [0] as they have an empty array which gets converted to 0 inside the other array...

So as imagine, the first value is a 2-dimensional array with one array inside... so [[]][+[]] will be equal to [[]][0] which will return []...

And at the end ++ convert it and increase it to 1...

So you can imagine, 1 + "0" will be "10"...

Why does return the string “10”?

High-precision clock in Python

If Python 3 is an option, you have two choices:

  • time.perf_counter which always use the most accurate clock on your platform. It does include time spent outside of the process.
  • time.process_time which returns the CPU time. It does NOT include time spent outside of the process.

The difference between the two can be shown with:

from time import (
    process_time,
    perf_counter,
    sleep,
)

print(process_time())
sleep(1)
print(process_time())

print(perf_counter())
sleep(1)
print(perf_counter())

Which outputs:

0.03125
0.03125
2.560001310720671e-07
1.0005455362793145

Connecting to remote MySQL server using PHP

  • firewall of the server must be set-up to enable incomming connections on port 3306
  • you must have a user in MySQL who is allowed to connect from % (any host) (see manual for details)

The current problem is the first one, but right after you resolve it you will likely get the second one.

Difference between "process.stdout.write" and "console.log" in node.js?


Console.log implement process.sdout.write, process.sdout.write is a buffer/stream that will directly output in your console.

According to my puglin serverline : console = new Console(consoleOptions) you can rewrite Console class with your own readline system.

You can see code source of console.log:


See more :

What does Python's socket.recv() return for non-blocking sockets if no data is received until a timeout occurs?

It is simple: if recv() returns 0 bytes; you will not receive any more data on this connection. Ever. You still might be able to send.

It means that your non-blocking socket have to raise an exception (it might be system-dependent) if no data is available but the connection is still alive (the other end may send).

Update Angular model after setting input value with jQuery

I know it's a bit late to answer here but maybe I may save some once's day.

I have been dealing with the same problem. A model will not populate once you update the value of input from jQuery. I tried using trigger events but no result.

Here is what I did that may save your day.

Declare a variable within your script tag in HTML.

Like:

<script>
 var inputValue="";

// update that variable using your jQuery function with appropriate value, you want...

</script>

Once you did that by using below service of angular.

$window

Now below getData function called from the same controller scope will give you the value you want.

var myApp = angular.module('myApp', []);

app.controller('imageManagerCtrl',['$scope','$window',function($scope,$window) {

$scope.getData = function () {
    console.log("Window value " + $window.inputValue);
}}]);

Hibernate: How to set NULL query-parameter value with HQL?

You can use

Restrictions.eqOrIsNull("status", status)

insted of

status == null ? Restrictions.isNull("status") : Restrictions.eq("status", status)

Incorrect string value: '\xF0\x9F\x8E\xB6\xF0\x9F...' MySQL

I was finally able to figure out the issue. I had to change some settings in mysql configuration my.ini This article helped a lot http://mathiasbynens.be/notes/mysql-utf8mb4#character-sets

First i changed the character set in my.ini to utf8mb4 Next i ran the following commands in mysql client

SET NAMES utf8mb4; 
ALTER DATABASE dreams_twitter CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci;

Use the following command to check that the changes are made

SHOW VARIABLES WHERE Variable_name LIKE 'character\_set\_%' OR Variable_name LIKE 'collation%';

How to set specific window (frame) size in java swing?

Try this, but you can adjust frame size with bounds and edit title.

package co.form.Try;

import javax.swing.JFrame;

public class Form {

    public static void main(String[] args) {
        JFrame obj =new JFrame();
        obj.setBounds(10,10,700,600); 
        obj.setTitle("Application Form");
        obj.setResizable(false);                
        obj.setVisible(true);       
        obj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }

}

Close a MessageBox after several seconds

RogerB over at CodeProject has one of the slickest solutions to this answer, and he did that back in '04, and it's still bangin'

Basically, you go here to his project and download the CS file. In case that link ever dies, I've got a backup gist here. Add the CS file to your project, or copy/paste the code somewhere if you'd rather do that.

Then, all you'd have to do is switch

DialogResult result = MessageBox.Show("Text","Title", MessageBoxButtons.CHOICE)

to

DialogResult result = MessageBoxEx.Show("Text","Title", MessageBoxButtons.CHOICE, timer_ms)

And you're good to go.

java.io.FileNotFoundException: (Access is denied)

Here's a gotcha that I just discovered - perhaps it might help someone else. If using windows the classes folder must not have encryption enabled! Tomcat doesn't seem to like that. Right click on the classes folder, select "Properties" and then click the "Advanced..." button. Make sure the "Encrypt contents to secure data" checkbox is cleared. Restart Tomcat.

It worked for me so here's hoping it helps someone else, too.

How to add a 'or' condition in #ifdef

#if defined(CONDITION1) || defined(CONDITION2)

should work. :)

#ifdef is a bit less typing, but doesn't work well with more complex conditions

PHP - Check if the page run on Mobile or Desktop browser

There is a very nice PHP library for detecting mobile clients here: http://mobiledetect.net

Using that it's quite easy to only display content for a mobile:

include 'Mobile_Detect.php';
$detect = new Mobile_Detect();

// Check for any mobile device.
if ($detect->isMobile()){
   // mobile content
}
else {
   // other content for desktops
}

React.js: Set innerHTML vs dangerouslySetInnerHTML

Based on (dangerouslySetInnerHTML).

It's a prop that does exactly what you want. However they name it to convey that it should be use with caution

intl extension: installing php_intl.dll

In my case adding PHP directory to PATH in user environment didn't work. After some testing I've found that it should be added to system PATH (I don't know what's the name of this part of system setting windows, 'couse I have Polish Windows).

ThreeJS: Remove object from scene

I started to save this as a function, and call it as needed for whatever reactions require it:

function Remove(){
    while(scene.children.length > 0){ 
    scene.remove(scene.children[0]); 
}
}

Now you can call the Remove(); function where appropriate.

Wait for async task to finish

This will never work, because the JS VM has moved on from that async_call and returned the value, which you haven't set yet.

Don't try to fight what is natural and built-in the language behaviour. You should use a callback technique or a promise.

function f(input, callback) {
    var value;

    // Assume the async call always succeed
    async_call(input, function(result) { callback(result) };

}

The other option is to use a promise, have a look at Q. This way you return a promise, and then you attach a then listener to it, which is basically the same as a callback. When the promise resolves, the then will trigger.

Python str vs unicode types

Your terminal happens to be configured to UTF-8.

The fact that printing a works is a coincidence; you are writing raw UTF-8 bytes to the terminal. a is a value of length two, containing two bytes, hex values C3 and A1, while ua is a unicode value of length one, containing a codepoint U+00E1.

This difference in length is one major reason to use Unicode values; you cannot easily measure the number of text characters in a byte string; the len() of a byte string tells you how many bytes were used, not how many characters were encoded.

You can see the difference when you encode the unicode value to different output encodings:

>>> a = 'á'
>>> ua = u'á'
>>> ua.encode('utf8')
'\xc3\xa1'
>>> ua.encode('latin1')
'\xe1'
>>> a
'\xc3\xa1'

Note that the first 256 codepoints of the Unicode standard match the Latin 1 standard, so the U+00E1 codepoint is encoded to Latin 1 as a byte with hex value E1.

Furthermore, Python uses escape codes in representations of unicode and byte strings alike, and low code points that are not printable ASCII are represented using \x.. escape values as well. This is why a Unicode string with a code point between 128 and 255 looks just like the Latin 1 encoding. If you have a unicode string with codepoints beyond U+00FF a different escape sequence, \u.... is used instead, with a four-digit hex value.

It looks like you don't yet fully understand what the difference is between Unicode and an encoding. Please do read the following articles before you continue:

Can I have an IF block in DOS batch file?

You can indeed place create a block of statements to execute after a conditional. But you have the syntax wrong. The parentheses must be used exactly as shown:

if <statement> (
    do something
) else (
    do something else
)

However, I do not believe that there is any built-in syntax for else-if statements. You will unfortunately need to create nested blocks of if statements to handle that.


Secondly, that %GPMANAGER_FOUND% == true test looks mighty suspicious to me. I don't know what the environment variable is set to or how you're setting it, but I very much doubt that the code you've shown will produce the result you're looking for.


The following sample code works fine for me:

@echo off

if ERRORLEVEL == 0 (
    echo GP Manager is up
    goto Continue7
)
echo GP Manager is down
:Continue7

Please note a few specific details about my sample code:

  • The space added between the end of the conditional statement, and the opening parenthesis.
  • I am setting @echo off to keep from seeing all of the statements printed to the console as they execute, and instead just see the output of those that specifically begin with echo.
  • I'm using the built-in ERRORLEVEL variable just as a test. Read more here

How to change the JDK for a Jenkins job?

Using latest Jenkins version 2.7.4 which is also having a bug for existing jobs.

  1. Add new JDKs through Manage Jenkins -> Global Tool Configuration -> JDK ** If you edit current job then JDK dropdown is not showing (bug)

  2. Hit http://your_jenkin_server:8080/restart and restart the server

  3. Re-configure job

Now, you should see JDK dropdown in "job name" -> Configure in Jenkins web ui. It will list all JDKs available in Jenkins configuration.

Why this line xmlns:android="http://schemas.android.com/apk/res/android" must be the first in the layout xml file?

I think it makes clear with the namespace, as we can create our own attributes and if the user specified attribute is the same as the Android one it avoid the conflict of the namespace.

Use FontAwesome or Glyphicons with css :before

<ul class="icons-ul">
<li><i class="icon-play-sign"></i> <a>option</a></li>
<li><i class="icon-play-sign"></i> <a>option</a></li>
<li><i class="icon-play-sign"></i> <a>option</a></li>
<li><i class="icon-play-sign"></i> <a>option</a></li>
<li><i class="icon-play-sign"></i> <a>option</a></li>
</ul>

All the font awesome icons comes default with Bootstrap.

Ruby on Rails generates model field:type - what are the options for field:type?

$ rails g model Item name:string description:text product:references

I too found the guides difficult to use. Easy to understand, but hard to find what I am looking for.

Also, I have temp projects that I run the rails generate commands on. Then once I get them working I run it on my real project.

Reference for the above code: http://guides.rubyonrails.org/getting_started.html#associating-models

How to properly assert that an exception gets raised in pytest?

There are two ways to handle exceptions in pytest:

  1. Using pytest.raises to write assertions about raised exceptions
  2. Using @pytest.mark.xfail

1. Using pytest.raises

From the docs:

In order to write assertions about raised exceptions, you can use pytest.raises as a context manager

Examples:

Asserting just an exception:

import pytest


def test_zero_division():
    with pytest.raises(ZeroDivisionError):
        1 / 0

with pytest.raises(ZeroDivisionError) says that whatever is in the next block of code should raise a ZeroDivisionError exception. If no exception is raised, the test fails. If the test raises a different exception, it fails.

If you need to have access to the actual exception info:

import pytest

def f():
    f()

def test_recursion_depth():
    with pytest.raises(RuntimeError) as excinfo:
        f()
    assert "maximum recursion" in str(excinfo.value)

excinfo is a ExceptionInfo instance, which is a wrapper around the actual exception raised. The main attributes of interest are .type, .value and .traceback.

2. Using @pytest.mark.xfail

It is also possible to specify a raises argument to pytest.mark.xfail.

import pytest

@pytest.mark.xfail(raises=IndexError)
def test_f():
    l = [1, 2, 3]
    l[10]

@pytest.mark.xfail(raises=IndexError) says that whatever is in the next block of code should raise an IndexError exception. If an IndexError is raised, test is marked as xfailed (x). If no exception is raised, the test is marked as xpassed (X). If the test raises a different exception, it fails.

Notes:

  • Using pytest.raises is likely to be better for cases where you are testing exceptions your own code is deliberately raising, whereas using @pytest.mark.xfail with a check function is probably better for something like documenting unfixed bugs or bugs in dependencies.

  • You can pass a match keyword parameter to the context-manager (pytest.raises) to test that a regular expression matches on the string representation of an exception. (see more)

How to add additional libraries to Visual Studio project?

Add #pragma comment(lib, "Your library name here") to your source.

Iterating over arrays in Python 3

You can use

    nditer

Here I calculated no. of positive and negative coefficients in a logistic regression:

b=sentiment_model.coef_
pos_coef=0
neg_coef=0
for i in np.nditer(b):
    if i>0:
    pos_coef=pos_coef+1
    else:
    neg_coef=neg_coef+1
print("no. of positive coefficients is : {}".format(pos_coef))
print("no. of negative coefficients is : {}".format(neg_coef))

Output:

no. of positive coefficients is : 85035
no. of negative coefficients is : 36199

How to Convert Int to Unsigned Byte and Back

The Integer.toString(size) call converts into the char representation of your integer, i.e. the char '5'. The ASCII representation of that character is the value 65.

You need to parse the string back to an integer value first, e.g. by using Integer.parseInt, to get back the original int value.

As a bottom line, for a signed/unsigned conversion, it is best to leave String out of the picture and use bit manipulation as @JB suggests.

laravel the requested url was not found on this server

I have faced the same problem in cPanel and I fixed my problem to add in .htaccess file below these line

# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]

What is the best (idiomatic) way to check the type of a Python variable?

You may want to check out typecheck. http://pypi.python.org/pypi/typecheck

Type-checking module for Python

This package provides powerful run-time typechecking facilities for Python functions, methods and generators. Without requiring a custom preprocessor or alterations to the language, the typecheck package allows programmers and quality assurance engineers to make precise assertions about the input to, and output from, their code.

How do I populate a JComboBox with an ArrayList?

i think that is the solution

ArrayList<table> libel = new ArrayList<table>();
try {
SessionFactory sf = new Configuration().configure().buildSessionFactory();
Session s = sf.openSession();
s.beginTransaction();

String hql = "FROM table ";

org.hibernate.Query query = s.createQuery(hql);
libel= (ArrayList<table>) query.list();
Iterator it = libel.iterator();
while(it.hasNext()) {
table cat = (table) it.next();

cat.getLibCat();//table colonm getter


combobox.addItem(cat.getLibCat());
}
s.getTransaction().commit();
s.close();
sf.close();
} catch (Exception e) {
System.out.println("Exception in getSelectedData::"+e.getMessage());

How using try catch for exception handling is best practice

The second approach is a good one.

If you don't want to show the error and confuse the user of application by showing runtime exception(i.e. error) which is not related to them, then just log error and the technical team can look for the issue and resolve it.

try
{
  //do some work
}
catch(Exception exception)
{
   WriteException2LogFile(exception);//it will write the or log the error in a text file
}

I recommend that you go for the second approach for your whole application.

jQuery Uncaught TypeError: Property '$' of object [object Window] is not a function

In Wordpress just replace

$(function(){...});

with

jQuery(function(){...});

Node Multer unexpected field

Different file name which posted as "recfile" at <input type="file" name='recfile' placeholder="Select file"/> and received as "file" at upload.single('file')

Solution : make sure both sent and received file are similar upload.single('recfile')

How to count the number of set bits in a 32-bit integer?

#!/user/local/bin/perl


    $c=0x11BBBBAB;
     $count=0;
     $m=0x00000001;
    for($i=0;$i<32;$i++)
    {
        $f=$c & $m;
        if($f == 1)
        {
            $count++;
        }
        $c=$c >> 1;
    }
    printf("%d",$count);

ive done it through a perl script. the number taken is $c=0x11BBBBAB   
B=3 1s   
A=2 1s   
so in total  
1+1+3+3+3+2+3+3=19

Forward X11 failed: Network error: Connection refused

you should install a x server such as XMing. and keep the x server is running. config your putty like this :Connection-Data-SSH-X11-Enable X11 forwarding should be checked. and X display location : localhost:0

document.body.appendChild(i)

You could try

document.getElementsByTagName('body')[0].appendChild(i);

Now that won't do you any good if the code is running in the <head>, and running before the <body> has even been seen by the browser. If you don't want to mess with "onload" handlers, try moving your <script> block to the very end of the document instead of the <head>.

How to initialize var?

Nope. var needs to be initialized to a type, it can't be null.

Calculate days between two Dates in Java 8

Use the class or method that best meets your needs:

  • the Duration class,
  • Period class,
  • or the ChronoUnit.between method.

A Duration measures an amount of time using time-based values (seconds, nanoseconds).

A Period uses date-based values (years, months, days).

The ChronoUnit.between method is useful when you want to measure an amount of time in a single unit of time only, such as days or seconds.

https://docs.oracle.com/javase/tutorial/datetime/iso/period.html

How to return a file using Web API?

Just a note for .Net Core: We can use the FileContentResult and set the contentType to application/octet-stream if we want to send the raw bytes. Example:

[HttpGet("{id}")]
public IActionResult GetDocumentBytes(int id)
{
    byte[] byteArray = GetDocumentByteArray(id);
    return new FileContentResult(byteArray, "application/octet-stream");
}

Angular2 *ngIf check object array length in template

You could use *ngIf="teamMembers != 0" to check whether data is present

How to copy java.util.list Collection

You may create a new list with an input of a previous list like so:

List one = new ArrayList()
//... add data, sort, etc
List two = new ArrayList(one);

This will allow you to modify the order or what elemtents are contained independent of the first list.

Keep in mind that the two lists will contain the same objects though, so if you modify an object in List two, the same object will be modified in list one.

example:

MyObject value1 = one.get(0);
MyObject value2 = two.get(0);
value1 == value2 //true
value1.setName("hello");
value2.getName(); //returns "hello"

Edit

To avoid this you need a deep copy of each element in the list like so:

List<Torero> one = new ArrayList<Torero>();
//add elements

List<Torero> two = new Arraylist<Torero>();
for(Torero t : one){
    Torero copy = deepCopy(t);
    two.add(copy);
}

with copy like the following:

public Torero deepCopy(Torero input){
    Torero copy = new Torero();
    copy.setValue(input.getValue());//.. copy primitives, deep copy objects again

    return copy;
}

How to get json key and value in javascript?

you have parse that Json string using JSON.parse()

..
}).done(function(data){
    obj = JSON.parse(data);
    alert(obj.jobtitel);
});

FPDF error: Some data has already been output, can't send PDF

For fpdf to work properly, there cannot be any output at all beside what fpdf generates. For example, this will work:

<?php
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>

While this will not (note the leading space before the opening <? tag)

 <?php
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>

Also, this will not work either (the echo will break it):

<?php
echo "About to create pdf";
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>

I'm not sure about the drupal side of things, but I know that absolutely zero non-fpdf output is a requirement for fpdf to work.


add ob_start (); at the top and at the end add ob_end_flush();

<?php
    ob_start();
    require('fpdf.php');
    $pdf = new FPDF();
    $pdf->AddPage();
    $pdf->SetFont('Arial','B',16);
    $pdf->Cell(40,10,'Hello World!');
    $pdf->Output();
    ob_end_flush(); 
?>

give me an error as below:
FPDF error: Some data has already been output, can't send PDF

to over come this error: go to fpdf.php in that,goto line number 996

function Output($name='', $dest='')

after that make changes like this:

function Output($name='', $dest='') {   
    ob_clean();     //Output PDF to so

Hi do you have a session header on the top of your page. or any includes If you have then try to add this codes on top pf your page it should works fine.

<?

while (ob_get_level())
ob_end_clean();
header("Content-Encoding: None", true);

?>

cheers :-)


In my case i had set:

ini_set('display_errors', 'on');
error_reporting(E_ALL | E_STRICT);

When i made the request to generate the report, some warnings were displayed in the browser (like the usage of deprecated functions).
Turning off the display_errors option, the report was generated successfully.

Adding ID's to google map markers

JavaScript is a dynamic language. You could just add it to the object itself.

var marker = new google.maps.Marker(markerOptions);
marker.metadata = {type: "point", id: 1};

Also, because all v3 objects extend MVCObject(). You can use:

marker.setValues({type: "point", id: 1});
// or
marker.set("type", "point");
marker.set("id", 1);
var val = marker.get("id");

How to simulate browsing from various locations?

Besides using multiple proxies or proxy-networks, you might want to try the planet-lab. (And probably there are other similar institutions around).

The social solution would be to post a question on some board that you are searching for volunteers that proxy your requests. (They only have to allow for one destination in their proxy config thus the danger of becoming spam-whores is relatively low.) You should prepare credentials that ensure your partners of the authenticity of the claim that the destination is indeed your computer.

How to update an object in a List<> in C#

You can do somthing like :

if (product != null) {
    var products = Repository.Products;
    var indexOf = products.IndexOf(products.Find(p => p.Id == product.Id));
    Repository.Products[indexOf] = product;
    // or 
    Repository.Products[indexOf].prop = product.prop;
}

How to detect my browser version and operating system using JavaScript?

Try this one..

// Browser with version  Detection
navigator.sayswho= (function(){
    var N= navigator.appName, ua= navigator.userAgent, tem;
    var M= ua.match(/(opera|chrome|safari|firefox|msie)\/?\s*(\.?\d+(\.\d+)*)/i);
    if(M && (tem= ua.match(/version\/([\.\d]+)/i))!= null) M[2]= tem[1];
    M= M? [M[1], M[2]]: [N, navigator.appVersion,'-?'];
    return M;
})();

var browser_version          = navigator.sayswho;
alert("Welcome to " + browser_version);

check out the working fiddle ( here )

Function passed as template argument

The reason your functor example does not work is that you need an instance to invoke the operator().

How to display list of repositories from subversion server

Sometimes you may wish to check on the timestamp for when the repo was updated, for getting this handy info you can use the svn -v (verbose) option as in

svn list -v svn://123.123.123.123/svn/repo/path

The matching wildcard is strict, but no declaration can be found for element 'context:component-scan

There are 'META-INF/spring.schemas' files in various Spring jars containing the mappings for the URLs that are intercepted for local resolution. If a particular xsd URL is not listed in these files (for example after switching from http to https) Spring tries to load schemas from the Internet and if the system has no Internet connection it fails and causes this error.

This can be the case with Spring Security v5.2 and up where there is no http mapping for the xsd file.

To fix it change

xsi:schemaLocation="
    http://www.springframework.org/schema/beans     
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/security  
    http://www.springframework.org/schema/security/spring-security.xsd"

to

xsi:schemaLocation="
    http://www.springframework.org/schema/beans     
    https://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/security  
    https://www.springframework.org/schema/security/spring-security.xsd"

Note that only actual xsd URL was modified from http to https (only two places above).

Setting device orientation in Swift iOS

In info.plist file , change the orientations which you want in "supported interface orientation".

In swift the way supporting files->info.plist->supporting interface orientation.

Multiple IF statements between number ranges

standalone one cell solution based on VLOOKUP

US syntax:

=IFERROR(ARRAYFORMULA(IF(LEN(A2:A),
        IF(A2:A>2000, "More than 2000",VLOOKUP(A2:A,
 {{(TRANSPOSE({{{0;   "Less than 500"},
               {500;  "Between 500 and 1000"}},
              {{1000; "Between 1000 and 1500"},
               {1500; "Between 1500 and 2000"}}}))}}, 2)),)), )

EU syntax:

=IFERROR(ARRAYFORMULA(IF(LEN(A2:A);
        IF(A2:A>2000; "More than 2000";VLOOKUP(A2:A;
 {{(TRANSPOSE({{{0;   "Less than 500"}\
               {500;  "Between 500 and 1000"}}\
              {{1000; "Between 1000 and 1500"}\
               {1500; "Between 1500 and 2000"}}}))}}; 2));)); )

alternatives: https://webapps.stackexchange.com/questions/123729/

How to convert enum names to string in c

A function like that without validating the enum is a trifle dangerous. I suggest using a switch statement. Another advantage is that this can be used for enums that have defined values, for example for flags where the values are 1,2,4,8,16 etc.

Also put all your enum strings together in one array:-

static const char * allEnums[] = {
    "Undefined",
    "apple",
    "orange"
    /* etc */
};

define the indices in a header file:-

#define ID_undefined       0
#define ID_fruit_apple     1
#define ID_fruit_orange    2
/* etc */

Doing this makes it easier to produce different versions, for example if you want to make international versions of your program with other languages.

Using a macro, also in the header file:-

#define CASE(type,val) case val: index = ID_##type##_##val; break;

Make a function with a switch statement, this should return a const char * because the strings static consts:-

const char * FruitString(enum fruit e){

    unsigned int index;

    switch(e){
        CASE(fruit, apple)
        CASE(fruit, orange)
        CASE(fruit, banana)
        /* etc */
        default: index = ID_undefined;
    }
    return allEnums[index];
}

If programming with Windows then the ID_ values can be resource values.

(If using C++ then all the functions can have the same name.

string EnumToString(fruit e);

)

How does Google reCAPTCHA v2 work behind the scenes?

A new paper has been released with several tests against reCAPTCHA:

https://www.blackhat.com/docs/asia-16/materials/asia-16-Sivakorn-Im-Not-a-Human-Breaking-the-Google-reCAPTCHA-wp.pdf

Some highlights:

  • By keeping a cookie active for +9 days (by browsing sites with Google resources), you can then pass reCAPTCHA by only clicking the checkbox;
  • There are no restrictions based on requests per IP;
  • The browser's user agent must be real, and Google run tests against your environment to ensure it matches the user agent;
  • Google tests if the browser can render a Canvas;
  • Screen resolution and mouse events don't affect the results;

Google has already fixed the cookie vulnerability and is probably restricting some behaviors based on IPs.

Another interesting finding is that Google runs a VM in JavaScript that obfuscates much of reCAPTCHA code and behavior. This VM is known as botguard and is used to protect other services besides reCAPTCHA:

https://github.com/neuroradiology/InsideReCaptcha

UPDATE 2017

A recent paper (from August) was published on WOOT 2017 achieving 85% accuracy in solving noCAPTCHA reCAPTCHA audio challenges:

http://uncaptcha.cs.umd.edu/papers/uncaptcha_woot17.pdf

UPDATE 2018

Google is introducing reCAPTCHA v3, which looks like a "human score prediction engine" that is calibrated per website. It can be installed into different pages of a website (working like a Google Analytics script) to help reCAPTCHA and the website owner to understand the behaviour of humans vs. bots before filling a reCAPTCHA.

https://www.google.com/recaptcha/intro/v3beta.html

google maps v3 marker info window on mouseover

Thanks to duncan answer, I end up with this:

marker.addListener('mouseover', () => infoWindow.open(map, marker))
marker.addListener('mouseout', () => infoWindow.close())

Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost."

Restarting the computer fixed the issue for me with Xcode9.1. I had restarted the simulator and Xcode, it doesn't work.

Efficient way of having a function only execute once in a loop

I'm not sure that I understood your problem, but I think you can divide loop. On the part of the function and the part without it and save the two loops.

Forward slash in Java Regex

Double escaping is required when presented as a string.

Whenever I'm making a new regular expression I do a bunch of tests with online tools, for example: http://www.regexplanet.com/advanced/java/index.html

That website allows you to enter the regular expression, which it'll escape into a string for you, and you can then test it against different inputs.

How can I select and upload multiple files with HTML and PHP, using HTTP POST?

in the first you should make form like this :

<form method="post" enctype="multipart/form-data" >
   <input type="file" name="file[]" multiple id="file"/>
   <input type="submit" name="ok"  />
</form> 

that is right . now add this code under your form code or on the any page you like

<?php
if(isset($_POST['ok']))
   foreach ($_FILES['file']['name'] as $filename) {
    echo $filename.'<br/>';
}
?>

it's easy... finish

Print "\n" or newline characters as part of the output on terminal

Another suggestion is to do that way:

string = "abcd\n"
print(string.replace("\n","\\n"))

But be aware that the print function actually print to the terminal the "\n", your terminal interpret that as a newline, that's it. So, my solution just change the newline in \ + n

Better way to set distance between flexbox items

Here's my solution, that doesn't require setting any classes on the child elements:

.flex-inline-row {
    display: inline-flex;
    flex-direction: row;
}

.flex-inline-row.flex-spacing-4px > :not(:last-child) {
    margin-right: 4px;
}

Usage:

<div class="flex-inline-row flex-spacing-4px">
  <span>Testing</span>
  <span>123</span>
</div>

The same technique can be used for normal flex rows and columns in addition to the inline example given above, and extended with classes for spacing other than 4px.

How do I 'overwrite', rather than 'merge', a branch on another branch in Git?

Other answers looked incomplete.
I have tried below in full, and it worked fine.

NOTE:
1. Make a copy of your repository before you try below, to be on safe side.

Details:
1. All development happens in dev branch
2. qa branch is just the same copy of dev
3. Time to time, dev code needs to be moved/overwrite to qa branch

so we need to overwrite qa branch, from dev branch

Part 1:
With below commands, old qa has been updated to newer dev:

git checkout dev
git merge -s ours qa
git checkout qa
git merge dev
git push

Automatic comment for last push gives below:

// Output:
//  *<MYNAME> Merge branch 'qa' into dev,*  

This comment looks reverse, because above sequence also looks reverse

Part 2:

Below are unexpected, new local commits in dev, the unnecessary ones
so, we need to throw away, and make dev untouched.

git checkout dev

// Output:
//  Switched to branch 'dev'  
//  Your branch is ahead of 'origin/dev' by 15 commits.  
//  (use "git push" to publish your local commits)


git reset --hard origin/dev  

//  Now we threw away the unexpected commits

Part 3:
Verify everything is as expected:

git status  

// Output:
//  *On branch dev  
//  Your branch is up-to-date with 'origin/dev'.  
//  nothing to commit, working tree clean*  

That's all.
1. old qa is now overwritten by new dev branch code
2. local is clean (remote origin/dev is untouched)

Why do you use typedef when declaring an enum in C++?

In C, declaring your enum the first way allows you to use it like so:

TokenType my_type;

If you use the second style, you'll be forced to declare your variable like this:

enum TokenType my_type;

As mentioned by others, this doesn't make a difference in C++. My guess is that either the person who wrote this is a C programmer at heart, or you're compiling C code as C++. Either way, it won't affect the behaviour of your code.

Capturing multiple line output into a Bash variable

Another pitfall with this is that command substitution$() — strips trailing newlines. Probably not always important, but if you really want to preserve exactly what was output, you'll have to use another line and some quoting:

RESULTX="$(./myscript; echo x)"
RESULT="${RESULTX%x}"

This is especially important if you want to handle all possible filenames (to avoid undefined behavior like operating on the wrong file).

CAST DECIMAL to INT

1 cent: no space b/w CAST and (expression). i.e., CAST(columnName AS SIGNED).

`require': no such file to load -- mkmf (LoadError)

You've Ruby 1.8 so you need to upgrade to at least 1.9 to make it working.

If so, then check How to install a specific version of a ruby gem?

If this won't help, then reinstalling ruby-dev again.

Why can't Visual Studio find my DLL?

Specifying the path to the DLL file in your project's settings does not ensure that your application will find the DLL at run-time. You only told Visual Studio how to find the files it needs. That has nothing to do with how the program finds what it needs, once built.

Placing the DLL file into the same folder as the executable is by far the simplest solution. That's the default search path for dependencies, so you won't need to do anything special if you go that route.
To avoid having to do this manually each time, you can create a Post-Build Event for your project that will automatically copy the DLL into the appropriate directory after a build completes.

Alternatively, you could deploy the DLL to the Windows side-by-side cache, and add a manifest to your application that specifies the location.

Why does the PHP json_encode function convert UTF-8 strings to hexadecimal entities?

JSON_UNESCAPED_UNICODE is available on PHP Version 5.4 or later.
The following code is for Version 5.3.

UPDATED

  • html_entity_decode is a bit more efficient than pack + mb_convert_encoding.
  • (*SKIP)(*FAIL) skips backslashes itself and specified characters by JSON_HEX_* flags.

 

function raw_json_encode($input, $flags = 0) {
    $fails = implode('|', array_filter(array(
        '\\\\',
        $flags & JSON_HEX_TAG ? 'u003[CE]' : '',
        $flags & JSON_HEX_AMP ? 'u0026' : '',
        $flags & JSON_HEX_APOS ? 'u0027' : '',
        $flags & JSON_HEX_QUOT ? 'u0022' : '',
    )));
    $pattern = "/\\\\(?:(?:$fails)(*SKIP)(*FAIL)|u([0-9a-fA-F]{4}))/";
    $callback = function ($m) {
        return html_entity_decode("&#x$m[1];", ENT_QUOTES, 'UTF-8');
    };
    return preg_replace_callback($pattern, $callback, json_encode($input, $flags));
}

SQL time difference between two dates result in hh:mm:ss

declare @StartDate datetime;
declare @EndDate datetime;
select @StartDate = '10/01/2012 08:40:18.000';
select @EndDate='10/04/2012 09:52:48.000';
select  cast(datediff(hour,@StartDate,@EndDate) as varchar(10)) + left(right(cast(cast(cast((@EndDate-@StartDate) as datetime) as time) as varchar(16)),14),6)

SQL - IF EXISTS UPDATE ELSE INSERT INTO

Try this:

INSERT INTO `center_course_fee` (`fk_course_id`,`fk_center_code`,`course_fee`) VALUES ('69', '4920153', '6000') ON DUPLICATE KEY UPDATE `course_fee` = '6000';

Checking for empty queryset in Django

if not orgs:
    # Do this...
else:
    # Do that...

How do I get the picture size with PIL?

Here's how you get the image size from the given URL in Python 3:

from PIL import Image
import urllib.request
from io import BytesIO

file = BytesIO(urllib.request.urlopen('http://getwallpapers.com/wallpaper/full/b/8/d/32803.jpg').read())
im = Image.open(file)
width, height = im.size

Creating an abstract class in Objective-C

No, there is no way to create an abstract class in Objective-C.

You can mock an abstract class - by making the methods/ selectors call doesNotRecognizeSelector: and therefore raise an exception making the class unusable.

For example:

- (id)someMethod:(SomeObject*)blah
{
     [self doesNotRecognizeSelector:_cmd];
     return nil;
}

You can also do this for init.

Set mouse focus and move cursor to end of input using jQuery

Here is another one, a one liner which does not reassign the value:

$("#inp").focus()[0].setSelectionRange(99999, 99999);

JBoss vs Tomcat again

I have also read that for some servers one for example needs only annotate persistence contexts, but in some servers, the injection should be done manually.

How to calculate the sentence similarity using word2vec model of gensim with python

Facebook Research group released a new solution called InferSent Results and code are published on Github, check their repo. It is pretty awesome. I am planning to use it. https://github.com/facebookresearch/InferSent

their paper https://arxiv.org/abs/1705.02364 Abstract: Many modern NLP systems rely on word embeddings, previously trained in an unsupervised manner on large corpora, as base features. Efforts to obtain embeddings for larger chunks of text, such as sentences, have however not been so successful. Several attempts at learning unsupervised representations of sentences have not reached satisfactory enough performance to be widely adopted. In this paper, we show how universal sentence representations trained using the supervised data of the Stanford Natural Language Inference datasets can consistently outperform unsupervised methods like SkipThought vectors on a wide range of transfer tasks. Much like how computer vision uses ImageNet to obtain features, which can then be transferred to other tasks, our work tends to indicate the suitability of natural language inference for transfer learning to other NLP tasks. Our encoder is publicly available.

link_to image tag. how to add class to a tag

Just adding that you can pass the link_to method a block:

<%= link_to href: 'http://www.example.com/' do %>
    <%= image_tag 'happyface.png', width: 136, height: 67, alt: 'a face that is unnervingly happy'%>
<% end %>

results in:

<a href="/?href=http%3A%2F%2Fhttp://www.example.com/k%2F">
    <img alt="a face that is unnervingly happy" height="67" src="/assets/happyface.png" width="136">
</a>

This has been a life saver when the designer has given me complex links with fancy css3 roll-over effects.

On - window.location.hash - Change?

Note that in case of Internet Explorer 7 and Internet Explorer 9 the if statment will give true (for "onhashchange" in windows), but the window.onhashchange will never fire, so it's better to store hash and check it after every 100 millisecond whether it's changed or not for all versions of Internet Explorer.

    if (("onhashchange" in window) && !($.browser.msie)) {
         window.onhashchange = function () {
              alert(window.location.hash);
         }
         // Or $(window).bind( 'hashchange',function(e) {
         //       alert(window.location.hash);
         //   });
    }
    else {
        var prevHash = window.location.hash;
        window.setInterval(function () {
           if (window.location.hash != prevHash) {
              prevHash = window.location.hash;
              alert(window.location.hash);
           }
        }, 100);
    }

EDIT - Since jQuery 1.9, $.browser.msie is not supported. Source: http://api.jquery.com/jquery.browser/

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);
        });     

javascript get x and y coordinates on mouse click

Like this.

_x000D_
_x000D_
function printMousePos(event) {_x000D_
  document.body.textContent =_x000D_
    "clientX: " + event.clientX +_x000D_
    " - clientY: " + event.clientY;_x000D_
}_x000D_
_x000D_
document.addEventListener("click", printMousePos);
_x000D_
_x000D_
_x000D_

MouseEvent - MDN

MouseEvent.clientX Read only
The X coordinate of the mouse pointer in local (DOM content) coordinates.

MouseEvent.clientY Read only
The Y coordinate of the mouse pointer in local (DOM content) coordinates.

How to turn on/off MySQL strict mode in localhost (xampp)?

Check the value with

SELECT @@GLOBAL.sql_mode;

then clear the @@global.sql_mode by using this command:

SET @@GLOBAL.sql_mode=''

In ASP.NET MVC: All possible ways to call Controller Action Method from a Razor View

Method 1 : Using jQuery Ajax Get call (partial page update).

Suitable for when you need to retrieve jSon data from database.

Controller's Action Method

[HttpGet]
public ActionResult Foo(string id)
{
    var person = Something.GetPersonByID(id);
    return Json(person, JsonRequestBehavior.AllowGet);
}

Jquery GET

function getPerson(id) {
    $.ajax({
        url: '@Url.Action("Foo", "SomeController")',
        type: 'GET',
        dataType: 'json',
        // we set cache: false because GET requests are often cached by browsers
        // IE is particularly aggressive in that respect
        cache: false,
        data: { id: id },
        success: function(person) {
            $('#FirstName').val(person.FirstName);
            $('#LastName').val(person.LastName);
        }
    });
}

Person class

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

Method 2 : Using jQuery Ajax Post call (partial page update).

Suitable for when you need to do partial page post data into database.

Post method is also same like above just replace [HttpPost] on Action method and type as post for jquery method.

For more information check Posting JSON Data to MVC Controllers Here

Method 3 : As a Form post scenario (full page update).

Suitable for when you need to save or update data into database.

View

@using (Html.BeginForm("SaveData","ControllerName", FormMethod.Post))
{        
    @Html.TextBoxFor(model => m.Text)
    
    <input type="submit" value="Save" />
}

Action Method

[HttpPost]
public ActionResult SaveData(FormCollection form)
    {
        // Get movie to update
        return View();
   }

Method 4 : As a Form Get scenario (full page update).

Suitable for when you need to Get data from database

Get method also same like above just replace [HttpGet] on Action method and FormMethod.Get for View's form method.

I hope this will help to you.

Table 'mysql.user' doesn't exist:ERROR

My solution was to run

mysql_upgrade -u root

Scenario: I updated the MySQL version on my Mac with 'homebrew upgrade'. Afterwards, some stuff worked, but other commands raised the error described in the question.

Add tooltip to font awesome icon

codepen Is perhaps a helpful example.

<div class="social-icons">
  <a class="social-icon social-icon--codepen">
    <i class="fa fa-codepen"></i>
    <div class="tooltip">Codepen</div>
</div>

body {  
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
}

/* Color Variables */
$color-codepen: #000;

/* Social Icon Mixin */
@mixin social-icon($color) {
  background: $color;
  background: linear-gradient(tint($color, 5%), shade($color, 5%));
  border-bottom: 1px solid shade($color, 20%);
  color: tint($color, 50%);

  &:hover {
    color: tint($color, 80%);
    text-shadow: 0px 1px 0px shade($color, 20%);
  }

  .tooltip {
    background: $color;
    background: linear-gradient(tint($color, 15%), $color);
    color: tint($color, 80%);

    &:after {
      border-top-color: $color;
    }
  }
}

/* Social Icons */
.social-icons {
  display: flex;
}

.social-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  width: 80px;
  height: 80px;
  margin: 0 0.5rem;
  border-radius: 50%;
  cursor: pointer;
  font-family: "Helvetica Neue", "Helvetica", "Arial", sans-serif;
  font-size: 2.5rem;
  text-decoration: none;
  text-shadow: 0 1px 0 rgba(0,0,0,0.2);
  transition: all 0.15s ease;

  &:hover {
    color: #fff;

    .tooltip {
      visibility: visible;
      opacity: 1;
      transform: translate(-50%, -150%);
    }
  }

  &:active {
    box-shadow: 0px 1px 3px rgba(0, 0, 0, 0.5) inset;
  }

  &--codepen { @include social-icon($color-codepen); }

  i {
    position: relative;
    top: 1px;
  }
}

/* Tooltips */
.tooltip {
  display: block;
  position: absolute;
  top: 0;
  left: 50%;
  padding: 0.8rem 1rem;
  border-radius: 3px;
  font-size: 0.8rem;
  font-weight: bold;
  opacity: 0;
  pointer-events: none;
  text-transform: uppercase;
  transform: translate(-50%, -100%);
  transition: all 0.3s ease;
  z-index: 1;

  &:after {
    display: block;
    position: absolute;
    bottom: 0;
    left: 50%;
    width: 0;
    height: 0;
    content: "";
    border: solid;
    border-width: 10px 10px 0 10px;
    border-color: transparent;
    transform: translate(-50%, 100%);
  }
}

How to convert Milliseconds to "X mins, x seconds" in Java?

    long startTime = System.currentTimeMillis();
    // do your work...
    long endTime=System.currentTimeMillis();
    long diff=endTime-startTime;       
    long hours=TimeUnit.MILLISECONDS.toHours(diff);
    diff=diff-(hours*60*60*1000);
    long min=TimeUnit.MILLISECONDS.toMinutes(diff);
    diff=diff-(min*60*1000);
    long seconds=TimeUnit.MILLISECONDS.toSeconds(diff);
    //hour, min and seconds variables contains the time elapsed on your work

PHP executable not found. Install PHP 7 and add it to your PATH or set the php.executablePath setting

For those who are using xampp:

File -> Preferences -> Settings

"php.validate.executablePath": "C:\\xampp\\php\\php.exe",
"php.executablePath": "C:\\xampp\\php\\php.exe"

Iterating over a numpy array

I think you're looking for the ndenumerate.

>>> a =numpy.array([[1,2],[3,4],[5,6]])
>>> for (x,y), value in numpy.ndenumerate(a):
...  print x,y
... 
0 0
0 1
1 0
1 1
2 0
2 1

Regarding the performance. It is a bit slower than a list comprehension.

X = np.zeros((100, 100, 100))

%timeit list([((i,j,k), X[i,j,k]) for i in range(X.shape[0]) for j in range(X.shape[1]) for k in range(X.shape[2])])
1 loop, best of 3: 376 ms per loop

%timeit list(np.ndenumerate(X))
1 loop, best of 3: 570 ms per loop

If you are worried about the performance you could optimise a bit further by looking at the implementation of ndenumerate, which does 2 things, converting to an array and looping. If you know you have an array, you can call the .coords attribute of the flat iterator.

a = X.flat
%timeit list([(a.coords, x) for x in a.flat])
1 loop, best of 3: 305 ms per loop

What is the difference between Scope_Identity(), Identity(), @@Identity, and Ident_Current()?

  • The @@identity function returns the last identity created in the same session.
  • The scope_identity() function returns the last identity created in the same session and the same scope.
  • The ident_current(name) returns the last identity created for a specific table or view in any session.
  • The identity() function is not used to get an identity, it's used to create an identity in a select...into query.

The session is the database connection. The scope is the current query or the current stored procedure.

A situation where the scope_identity() and the @@identity functions differ, is if you have a trigger on the table. If you have a query that inserts a record, causing the trigger to insert another record somewhere, the scope_identity() function will return the identity created by the query, while the @@identity function will return the identity created by the trigger.

So, normally you would use the scope_identity() function.

Adding values to an array in java

public class Array {
    static int a[] = new int[101];
    int counter = 0;
    public int add(int num) {
        if (num <= 100) {
            Array.a[this.counter] = num;
            System.out.println(a[this.counter]);
            this.counter++;

            return add(num + 1);
        }
        return 0;
    }

    public static void main(String[] args) {
        Array c = new Array();
        c.add(1);
    }
}

How to read data from excel file using c#

Save the Excel file to CSV, and read the resulting file with C# using a CSV reader library like FileHelpers.

How do you develop Java Servlets using Eclipse?

I use Eclipse Java EE edition

Create a "Dynamic Web Project"

Install a local server in the server view, for the version of Tomcat I'm using. Then debug, and run on that server for testing.

When I deploy I export the project to a war file.

Multi-dimensional arraylist or list in C#?

you just make a list of lists like so:

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

and then it's just a matter of using the functionality you want

results.Add(new List<string>()); //adds a new list to your list of lists
results[0].Add("this is a string"); //adds a string to the first list
results[0][0]; //gets the first string in your first list

notifyDataSetChange not working from custom adapter

In my case I simply forget to add in my fragment mRecyclerView.setAdapter(adapter)

Git conflict markers

The line (or lines) between the lines beginning <<<<<<< and ====== here:

<<<<<<< HEAD:file.txt
Hello world
=======

... is what you already had locally - you can tell because HEAD points to your current branch or commit. The line (or lines) between the lines beginning ======= and >>>>>>>:

=======
Goodbye
>>>>>>> 77976da35a11db4580b80ae27e8d65caf5208086:file.txt

... is what was introduced by the other (pulled) commit, in this case 77976da35a11. That is the object name (or "hash", "SHA1sum", etc.) of the commit that was merged into HEAD. All objects in git, whether they're commits (version), blobs (files), trees (directories) or tags have such an object name, which identifies them uniquely based on their content.

Remove the string on the beginning of an URL

You can overload the String prototype with a removePrefix function:

String.prototype.removePrefix = function (prefix) {
    const hasPrefix = this.indexOf(prefix) === 0;
    return hasPrefix ? this.substr(prefix.length) : this.toString();
};

usage:

const domain = "www.test.com".removePrefix("www."); // test.com

Declaring abstract method in TypeScript

I use to throw an exception in the base class.

protected abstractMethod() {
    throw new Error("abstractMethod not implemented");
}

Then you have to implement in the sub-class. The cons is that there is no build error, but run-time. The pros is that you can call this method from the super class, assuming that it will work :)

HTH!

Milton

jQuery plugin returning "Cannot read property of undefined"

Usually that problem is that in the last iteration you have an empty object or undefine object. use console.log() inside you cicle to check that this doent happend.

Sometimes a prototype in some place add an extra element.

How to start new activity on button click

Intent iinent= new Intent(Homeactivity.this,secondactivity.class);
startActivity(iinent);

Exception: Unexpected end of ZLIB input stream

You have to call close() on the GZIPOutputStream before you attempt to read it. The final bytes of the file will only be written when the file is actually closed. (This is irrespective of any explicit buffering in the output stack. The stream only knows to compress and write the last bytes when you tell it to close. A flush() probably won't help ... though calling finish() instead of close() should work. Look at the javadocs.)

Here's the correct code (in Java);

package test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class GZipTest {

    public static void main(String[] args) throws
                FileNotFoundException, IOException {
        String name = "/tmp/test";
        GZIPOutputStream gz = new GZIPOutputStream(new FileOutputStream(name));
        gz.write(10);
        gz.close();       // Remove this to reproduce the reported bug
        System.out.println(new GZIPInputStream(new FileInputStream(name)).read());
    }
}

(I've not implemented resource management or exception handling / reporting properly as they are not relevant to the purpose of this code. Don't treat this as an example of "good code".)

Better naming in Tuple classes than "Item1", "Item2"

Just to add to @MichaelMocko answer. Tuples have couple of gotchas at the moment:

You can't use them in EF expression trees

Example:

public static (string name, string surname) GetPersonName(this PersonContext ctx, int id)
{
    return ctx.Persons
        .Where(person => person.Id == id)
        // Selecting as Tuple
        .Select(person => (person.Name, person.Surname))
        .First();
}

This will fail to compile with "An expression tree may not contain a tuple literal" error. Unfortunately, the expression trees API wasn't expanded with support for tuples when these were added to the language.

Track (and upvote) this issue for the updates: https://github.com/dotnet/roslyn/issues/12897

To get around the problem, you can cast it to anonymous type first and then convert the value to tuple:

// Will work
public static (string name, string surname) GetPersonName(this PersonContext ctx, int id)
{
    return ctx.Persons
        .Where(person => person.Id == id)
        .Select(person => new { person.Name, person.Surname })
        .ToList()
        .Select(person => (person.Name, person.Surname))
        .First();
}

Another option is to use ValueTuple.Create:

// Will work
public static (string name, string surname) GetPersonName(this PersonContext ctx, int id)
{
    return ctx.Persons
        .Where(person => person.Id == id)
        .Select(person => ValueTuple.Create(person.Name, person.Surname))
        .First();
}

References:

You can't deconstruct them in lambdas

There's a proposal to add the support: https://github.com/dotnet/csharplang/issues/258

Example:

public static IQueryable<(string name, string surname)> GetPersonName(this PersonContext ctx, int id)
{
    return ctx.Persons
        .Where(person => person.Id == id)
        .Select(person => ValueTuple.Create(person.Name, person.Surname));
}

// This won't work
ctx.GetPersonName(id).Select((name, surname) => { return name + surname; })

// But this will
ctx.GetPersonName(id).Select(t => { return t.name + t.surname; })

References:

They won't serialize nicely

using System;
using Newtonsoft.Json;

public class Program
{
    public static void Main() {
        var me = (age: 21, favoriteFood: "Custard");
        string json = JsonConvert.SerializeObject(me);

        // Will output {"Item1":21,"Item2":"Custard"}
        Console.WriteLine(json); 
    }
}

Tuple field names are only available at compile time and are completely wiped out at runtime.

References:

Javascript String to int conversion

Use parseInt():

var number = (parseInt(id.substring(indexPos)) + 1);` // creates the number that will go in the title

What's the best way to select the minimum value from several columns?

The best way to do that is probably not to do it - it's strange that people insist on storing their data in a way that requires SQL "gymnastics" to extract meaningful information, when there are far easier ways to achieve the desired result if you just structure your schema a little better :-)

The right way to do this, in my opinion, is to have the following table:

ID    Col    Val
--    ---    ---
 1      1      3
 1      2     34
 1      3     76

 2      1     32
 2      2    976
 2      3     24

 3      1      7
 3      2    235
 3      3      3

 4      1    245
 4      2      1
 4      3    792

with ID/Col as the primary key (and possibly Col as an extra key, depending on your needs). Then your query becomes a simple select min(val) from tbl and you can still treat the individual 'old columns' separately by using where col = 2 in your other queries. This also allows for easy expansion should the number of 'old columns' grow.

This makes your queries so much easier. The general guideline I tend to use is, if you ever have something that looks like an array in a database row, you're probably doing something wrong and should think about restructuring the data.


However, if for some reason you can't change those columns, I'd suggest using insert and update triggers and add another column which these triggers set to the minimum on Col1/2/3. This will move the 'cost' of the operation away from the select to the update/insert where it belongs - most database tables in my experience are read far more often than written so incurring the cost on write tends to be more efficient over time.

In other words, the minimum for a row only changes when one of the other columns change, so that's when you should be calculating it, not every time you select (which is wasted if the data isn't changing). You would then end up with a table like:

ID   Col1   Col2   Col3   MinVal
--   ----   ----   ----   ------
 1      3     34     76        3
 2     32    976     24       24
 3      7    235      3        3
 4    245      1    792        1

Any other option that has to make decisions at select time is usually a bad idea performance-wise, since the data only changes on insert/update - the addition of another column takes up more space in the DB and will be slightly slower for the inserts and updates but can be much faster for selects - the preferred approach should depend on your priorities there but, as stated, most tables are read far more often than they're written.

PySpark 2.0 The size or shape of a DataFrame

I think there is not similar function like data.shape in Spark. But I will use len(data.columns) rather than len(data.dtypes)

Increasing nesting function calls limit

Personally I would suggest this is an error as opposed to a setting that needs adjusting. In my code it was because I had a class that had the same name as a library within one of my controllers and it seemed to trip it up.

Output errors and see where this is being triggered.

What are NR and FNR and what does "NR==FNR" imply?

Look up NR and FNR in the awk manual and then ask yourself what is the condition under which NR==FNR in the following example:

$ cat file1
a
b
c

$ cat file2
d
e

$ awk '{print FILENAME, NR, FNR, $0}' file1 file2
file1 1 1 a
file1 2 2 b
file1 3 3 c
file2 4 1 d
file2 5 2 e

Deleting DataFrame row in Pandas based on column value

Though the previou answer are almost similar to what I am going to do, but using the index method does not require using another indexing method .loc(). It can be done in a similar but precise manner as

df.drop(df.index[df['line_race'] == 0], inplace = True)

Extract first item of each sublist

You could use zip:

>>> lst=[[1,2,3],[11,12,13],[21,22,23]]
>>> zip(*lst)[0]
(1, 11, 21)

Or, Python 3 where zip does not produce a list:

>>> list(zip(*lst))[0]
(1, 11, 21)

Or,

>>> next(zip(*lst))
(1, 11, 21)

Or, (my favorite) use numpy:

>>> import numpy as np
>>> a=np.array([[1,2,3],[11,12,13],[21,22,23]])
>>> a
array([[ 1,  2,  3],
       [11, 12, 13],
       [21, 22, 23]])
>>> a[:,0]
array([ 1, 11, 21])

Setting a property with an EventTrigger

Just create your own action.

namespace WpfUtil
{
    using System.Reflection;
    using System.Windows;
    using System.Windows.Interactivity;


    /// <summary>
    /// Sets the designated property to the supplied value. TargetObject
    /// optionally designates the object on which to set the property. If
    /// TargetObject is not supplied then the property is set on the object
    /// to which the trigger is attached.
    /// </summary>
    public class SetPropertyAction : TriggerAction<FrameworkElement>
    {
        // PropertyName DependencyProperty.

        /// <summary>
        /// The property to be executed in response to the trigger.
        /// </summary>
        public string PropertyName
        {
            get { return (string)GetValue(PropertyNameProperty); }
            set { SetValue(PropertyNameProperty, value); }
        }

        public static readonly DependencyProperty PropertyNameProperty
            = DependencyProperty.Register("PropertyName", typeof(string),
            typeof(SetPropertyAction));


        // PropertyValue DependencyProperty.

        /// <summary>
        /// The value to set the property to.
        /// </summary>
        public object PropertyValue
        {
            get { return GetValue(PropertyValueProperty); }
            set { SetValue(PropertyValueProperty, value); }
        }

        public static readonly DependencyProperty PropertyValueProperty
            = DependencyProperty.Register("PropertyValue", typeof(object),
            typeof(SetPropertyAction));


        // TargetObject DependencyProperty.

        /// <summary>
        /// Specifies the object upon which to set the property.
        /// </summary>
        public object TargetObject
        {
            get { return GetValue(TargetObjectProperty); }
            set { SetValue(TargetObjectProperty, value); }
        }

        public static readonly DependencyProperty TargetObjectProperty
            = DependencyProperty.Register("TargetObject", typeof(object),
            typeof(SetPropertyAction));


        // Private Implementation.

        protected override void Invoke(object parameter)
        {
            object target = TargetObject ?? AssociatedObject;
            PropertyInfo propertyInfo = target.GetType().GetProperty(
                PropertyName,
                BindingFlags.Instance|BindingFlags.Public
                |BindingFlags.NonPublic|BindingFlags.InvokeMethod);

            propertyInfo.SetValue(target, PropertyValue);
        }
    }
}

In this case I'm binding to a property called DialogResult on my viewmodel.

<Grid>

    <Button>
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="Click">
                <wpf:SetPropertyAction PropertyName="DialogResult" TargetObject="{Binding}"
                                       PropertyValue="{x:Static mvvm:DialogResult.Cancel}"/>
            </i:EventTrigger>
        </i:Interaction.Triggers>
        Cancel
    </Button>

</Grid>

Simple CSS Animation Loop – Fading In & Out "Loading" Text

As King King said, you must add the browser specific prefix. This should cover most browsers:

_x000D_
_x000D_
@keyframes flickerAnimation {_x000D_
  0%   { opacity:1; }_x000D_
  50%  { opacity:0; }_x000D_
  100% { opacity:1; }_x000D_
}_x000D_
@-o-keyframes flickerAnimation{_x000D_
  0%   { opacity:1; }_x000D_
  50%  { opacity:0; }_x000D_
  100% { opacity:1; }_x000D_
}_x000D_
@-moz-keyframes flickerAnimation{_x000D_
  0%   { opacity:1; }_x000D_
  50%  { opacity:0; }_x000D_
  100% { opacity:1; }_x000D_
}_x000D_
@-webkit-keyframes flickerAnimation{_x000D_
  0%   { opacity:1; }_x000D_
  50%  { opacity:0; }_x000D_
  100% { opacity:1; }_x000D_
}_x000D_
.animate-flicker {_x000D_
   -webkit-animation: flickerAnimation 1s infinite;_x000D_
   -moz-animation: flickerAnimation 1s infinite;_x000D_
   -o-animation: flickerAnimation 1s infinite;_x000D_
    animation: flickerAnimation 1s infinite;_x000D_
}
_x000D_
<div class="animate-flicker">Loading...</div>
_x000D_
_x000D_
_x000D_

Android checkbox style

Note: Using Android Support Library v22.1.0 and targeting API level 11 and up? Scroll down to the last update.


My application style is set to Theme.Holo which is dark and I would like the check boxes on my list view to be of style Theme.Holo.Light. I am not trying to create a custom style. The code below doesn't seem to work, nothing happens at all.

At first it may not be apparent why the system exhibits this behaviour, but when you actually look into the mechanics you can easily deduce it. Let me take you through it step by step.

First, let's take a look what the Widget.Holo.Light.CompoundButton.CheckBox style defines. To make things more clear, I've also added the 'regular' (non-light) style definition.

<style name="Widget.Holo.Light.CompoundButton.CheckBox" parent="Widget.CompoundButton.CheckBox" />

<style name="Widget.Holo.CompoundButton.CheckBox" parent="Widget.CompoundButton.CheckBox" />

As you can see, both are empty declarations that simply wrap Widget.CompoundButton.CheckBox in a different name. So let's look at that parent style.

<style name="Widget.CompoundButton.CheckBox">
    <item name="android:background">@android:drawable/btn_check_label_background</item>
    <item name="android:button">?android:attr/listChoiceIndicatorMultiple</item>
</style>

This style references both a background and button drawable. btn_check_label_background is simply a 9-patch and hence not very interesting with respect to this matter. However, ?android:attr/listChoiceIndicatorMultiple indicates that some attribute based on the current theme (this is important to realise) will determine the actual look of the CheckBox.

As listChoiceIndicatorMultiple is a theme attribute, you will find multiple declarations for it - one for each theme (or none if it gets inherited from a parent theme). This will look as follows (with other attributes omitted for clarity):

<style name="Theme">
    <item name="listChoiceIndicatorMultiple">@android:drawable/btn_check</item>
    ...
</style>

<style name="Theme.Holo">
    <item name="listChoiceIndicatorMultiple">@android:drawable/btn_check_holo_dark</item>
    ...
</style>

<style name="Theme.Holo.Light" parent="Theme.Light">
    <item name="listChoiceIndicatorMultiple">@android:drawable/btn_check_holo_light</item>
    ...
</style>

So this where the real magic happens: based on the theme's listChoiceIndicatorMultiple attribute, the actual appearance of the CheckBox is determined. The phenomenon you're seeing is now easily explained: since the appearance is theme-based (and not style-based, because that is merely an empty definition) and you're inheriting from Theme.Holo, you will always get the CheckBox appearance matching the theme.

Now, if you want to change your CheckBox's appearance to the Holo.Light version, you will need to take a copy of those resources, add them to your local assets and use a custom style to apply them.

As for your second question:

Also can you set styles to individual widgets if you set a style to the application?

Absolutely, and they will override any activity- or application-set styles.

Is there any way to set a theme(style with images) to the checkbox widget. (...) Is there anyway to use this selector: link?


Update:

Let me start with saying again that you're not supposed to rely on Android's internal resources. There's a reason you can't just access the internal namespace as you please.

However, a way to access system resources after all is by doing an id lookup by name. Consider the following code snippet:

int id = Resources.getSystem().getIdentifier("btn_check_holo_light", "drawable", "android");
((CheckBox) findViewById(R.id.checkbox)).setButtonDrawable(id);

The first line will actually return the resource id of the btn_check_holo_light drawable resource. Since we established earlier that this is the button selector that determines the look of the CheckBox, we can set it as 'button drawable' on the widget. The result is a CheckBox with the appearance of the Holo.Light version, no matter what theme/style you set on the application, activity or widget in xml. Since this sets only the button drawable, you will need to manually change other styling; e.g. with respect to the text appearance.

Below a screenshot showing the result. The top checkbox uses the method described above (I manually set the text colour to black in xml), while the second uses the default theme-based Holo styling (non-light, that is).

Screenshot showing the result


Update2:

With the introduction of Support Library v22.1.0, things have just gotten a lot easier! A quote from the release notes (my emphasis):

Lollipop added the ability to overwrite the theme at a view by view level by using the android:theme XML attribute - incredibly useful for things such as dark action bars on light activities. Now, AppCompat allows you to use android:theme for Toolbars (deprecating the app:theme used previously) and, even better, brings android:theme support to all views on API 11+ devices.

In other words: you can now apply a theme on a per-view basis, which makes solving the original problem a lot easier: just specify the theme you'd like to apply for the relevant view. I.e. in the context of the original question, compare the results of below:

<CheckBox
    ...
    android:theme="@android:style/Theme.Holo" />

<CheckBox
    ...
    android:theme="@android:style/Theme.Holo.Light" />

The first CheckBox is styled as if used in a dark theme, the second as if in a light theme, regardless of the actual theme set to your activity or application.

Of course you should no longer be using the Holo theme, but instead use Material.

String Pattern Matching In Java

You can do it using string.indexOf("{item}"). If the result is greater than -1 {item} is in the string