text:
Q: Add custom parameters in SoundClound embed I use oEmbedd functionality of WordPress. All work fine but I need to set custom parameters in the iframe
So I try this without success :
function my_oembed_fetch_url( $provider, $url, $args ) {
    // You can find the list of defaults providers in WP_oEmbed::__construct()
    if ( strpos( $provider, 'soundcloud.com' ) !== false) {

        if ( isset( $args['show_artwork'] ) ) {
            $provider = add_query_arg( 'show_artwork', absint( $args['show_artwork'] ), $provider );
        }
    }

    return $provider;
}

wp_oembed_get('https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/number-exampleXXXXXXX', array('show_artwork' => 'false'));

What's wrong ? Thank you in advance

A: Have you added the filter in your code to utilize "my_oembed_fetch_url" ?
add_filter( 'oembed_fetch_url', 'my_oembed_fetch_url', 10, 3 );


text:
Q: Команда DROP не работает Всем привет, только начал изучать MySQL и почти сразу столкнулся с проблемой. Не работает команда DROP не смотря на то что в настройках разрешено удалять базу данных.Это первый вопрос.
Второй вопрос, можно ли создавать и удалять базы данных с помощью php файлов.
Пример:
CREATE DATABASE test;(что нужно сделать чтоб эта команда сработала в php, если это конечно вообще возможно). Ну или как создать базу данных вручную, не заходя в phpMyAdmim?
A: если не работает команда DROP, и права все верны, и подключились вы хорошо, то она не соответствует шаблону

DROP DATABASE `имя_БД`

безусловно можно создавать и удалять БД из скрипта.
после подключения ручками пишем:

mysql_query('запрос');

про виды запросов о БД можно почитать здесь.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I show this function is monotonically decreasing? Let $p = $Probability of head on a coin toss ; $p < 0.5$ (biased coin).  $f(k) =$ Probability that heads is the majority from $k$ tosses, where $k$ takes odd values. I want to show that $f(k)$ monotonically decreases with increasing $k$. How do I go about doing this? I know that $$ f(k) = \sum_{i=\frac{k+1}{2}}^k {k \choose i} p^i (1-p)^{k-i}.$$ How do I proceed from here; I don't know how to compute $f'(k)$ from this point..

A: Denote $g(l,k)={\rm Prob}(l\textrm{ out of first }k\textrm{ are heads})$. Then $f(k)=\sum\limits_{l>k/2}g(l,k)$ and
$$\begin{array}{ll} f(k+1) & \displaystyle =\sum_{l>(k+1)/2}g(l,k+1) \\[5pt] & \displaystyle = \sum_{l>(k+1)/2} \left[p\,g(l-1,k)+(1-p)\,g(l,k)\right] \\[5pt] & \displaystyle = p\sum_{l>(k-1)/2}g(l,k)+(1-p)\sum_{l>(k+1)/2}g(l,k) \\[5pt] & \displaystyle = p\,\underbrace{g(k/2,k)}_{k\textrm{ is even}} + p\,f(k)+(1-p)\,f(k)-(1-p)\,\underbrace{g\left(\frac{k+1}{2},k\right)}_{k\textrm{ is odd}}\end{array}$$
If $k$ is odd then
$$\begin{array}{ll} f(k+1)& =f(k)-(1-p)\,g\left(\frac{k+1}{2},k\right) \\  f(k+2) & = p\,g\left(\frac{k+1}{2},k+1\right)+f(k+1) \\ & = f(k)+p\,g(\left(\frac{k+1}{2},k+1\right)-(1-p)\,g\left(\frac{k+1}{2},k\right).\end{array} $$
Therefore when $k$ is odd:
$$f(k+2)<f(k) \iff f(k+2)-f(k)<0$$
$$\iff p\,g\left(\frac{k+1}{2},k+1\right)-(1-p)\,g\left(\frac{k+1}{2}\right)<0 $$
$$\iff p\binom{k+1}{\frac{k+1}{2}}p^{(k+1)/2}(1-p)^{(k+1)/2}-(1-p)\binom{k}{\frac{k+1}{2}}p^{(k+1)/2}(1-p)^{(k-1)/2}<0 $$
$$\iff p\binom{k+1}{\frac{k+1}{2}}-\binom{k}{\frac{k+1}{2}}<0\iff p<\frac{\displaystyle \binom{k}{\frac{k+1}{2}}}{\displaystyle \binom{k+1}{\frac{k+1}{2}}}=\frac{1}{2}. $$


text:
Q: Matching timestamped data to closest time in another dataset. Properly vectorized? Faster way? I have a timestamp in one data frame that I am trying to match to the closest timestamp in a second dataframe, for the purpose of extracting data from the second dataframe. See below for a generic example of my approach:
library(lubridate)

data <- data.frame(datetime=ymd_hms(c('2015-04-01 12:23:00 UTC', '2015-04-01 13:49:00 UTC', '2015-04-01 14:06:00 UTC' ,'2015-04-01 14:49:00 UTC')),
                   value=c(1,2,3,4))
reference <- data.frame(datetime=ymd_hms(c('2015-04-01 12:00:00 UTC', '2015-04-01 13:00:00 UTC', '2015-04-01 14:00:00 UTC' ,'2015-04-01 15:00:00 UTC', '2015-04-01 16:00:00 UTC')),
                        refvalue=c(5,6,7,8,9))

data$refvalue <- apply(data, 1, function (x){
  differences <- abs(as.numeric(difftime(ymd_hms(x['datetime']), reference$datetime)))
  mindiff <- min(differences)
  return(reference$refvalue[differences == mindiff])
})

data
#              datetime value refvalue
# 1 2015-04-01 12:23:00     1        5
# 2 2015-04-01 13:49:00     2        7
# 3 2015-04-01 14:06:00     3        7
# 4 2015-04-01 14:49:00     4        8

This works fine, except it is very slow, because the reference dataframe is quite large in my real-world application. Is this code properly vectorized? Is there a faster, more elegant way of performing this operation?

A: You can try data.tables rolling join using the "nearest" option
library(data.table) # v1.9.6+
setDT(reference)[data, refvalue, roll = "nearest", on = "datetime"]
# [1] 5 7 7 8

A: I wondered if this would be able to match a data.table solution for speed, but it's a base-R vectorized solution which should outperform your apply version. And since it doesn't actually ever calculate a distance, it might actually be faster than the data.table-nearest approach. This adds the length of the midpoints of the intervals to either the lowest possible value or the starting point of the the intervals to create a set of "mid-breaks" and then uses the findInterval function to process the times. That creates a suitable index into the rows of the reference dataset and the "refvalue" can then be "transferred" to the data-object.
 data$reefvalue <- reference$refvalue[
                      findInterval( data$datetime,
                                     c(-Inf, head(reference$datetime,-1))+
                                     c(0, diff(as.numeric(reference$datetime))/2 )) ]
 # values are [1] 5 7 7 8


text:
Q: How to open 10 tabs in FF and be automaticilly logged in (name:passwd) I have just read this article how to open more tabs via parameter in shortcut file already been asked here:
how to Create browser shortcut which will open certain pages?
But, I also need to be logged in, after this 10 tabs/10 addresses will be opened, I can save my credentials uname/passwd, but something needs to click on "Login" button to log me in.
Any suggestions would be appreciated...

A: I would consider using AutoIt to open and click the Login with the stored passwords.  There is also iMacros for Firefox.


text:
Q: Strange VIM behaviour with wrapped lines: When using word movements, visual and actual cursor position diverge I did the following:
caw for change word.
Then, esc for normal mode.
Then, b a couple of times.
However, while I expected to jump to the beginning of the words sit, dolor, ipsum, the cursor did not move there. When I inserted text, however, it somehow actually was there.
To sum up, what I wanted to do worked, but the cursor position did not reflect that when pressing b. Also, the line wrapping looked strange.
What's wrong here?
I recently upgraded from Vim 7.3 to 7.4. The problem does not occur in the previous version!

Here's the part of my .vimrc I edited last (the rest has been there for about a year, so I skipped it):
set number
set tabstop=2 shiftwidth=2 noet
set clipboard+=unnamed
set linebreak
set nobackup
set nowritebackup
set shell=/bin/sh
set ic
set completeopt=menu,menuone
let g:ycm_auto_trigger=0
let g:tex_flavor="latex"
let g:ycm_key_invoke_completion = ""
inoremap <c-@> <c-x><c-u>

A: This is a bug, that has been fixed with patch 7.4.579. There have been other similar patches afterwards added, because of some similar problems.


text:
Q: Internet not working after configuring server for DNS with dyndns Objective to be achieved: To access the  server using a name server.xyz.com.
I've a domain xyz.com and a server behind a router. Also, I've configured my server with dyndns. On executing the following command

dig xyz.com

I get this output:
; <<>> DiG 9.8.2rc1-RedHat-9.8.2-0.17.rc1.el6_4.4 <<>> xyz.com
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 5351
;; flags: qr aa rd; QUERY: 1, ANSWER: 0, AUTHORITY: 1, ADDITIONAL: 0
;; WARNING: recursion requested but not available

;; QUESTION SECTION:
;xyz.com.       IN  A

;; AUTHORITY SECTION:
xyz.com.    1800    IN  SOA ns1.mydyndns.org. zone-admin.dyndns.com. 2013052111 10800 1800 604800 1800

;; Query time: 180 msec
;; SERVER: 208.76.58.198#53(208.76.58.198)
;; WHEN: Wed May 22 17:44:28 2013
;; MSG SIZE  rcvd: 106

However,
ping google.com
gives me
ping: unknown host google.com
Moreover,
hostname
displays
server.xyz.com
Futhermore,
domainname
displays
xyz.com
I've also configured my dlink router to update public ipaddress with dyndns, using Dynamic DNS configuration in the router.
Have I configured dns properly? Also, I'm not being able to access internet after the configuration.

A: In my dyndns account, the delegation status showed Incorrect. This implied that I had not configured the nameservers with my domain registrar, the site from where I bought my domain.
On doing the needful, the delegation status changed to Correct. Please note, it did not require me to modify my resolv.conf


text:
Q: Azure WADLogsTable is getting flooded with information traces Azure WADLogsTable is getting flooded with information traces on ServiceRunTime setting reads. Is it possible to configure the service to skip logging these unnecessary information?
Eg:
Getting "DataConnectionString" from ServiceRuntime: PASS (DefaultEndpointsProtocol=https;AccountName=xxxxxxxxxxx;AccountKey=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx).
-Thanks

A: Yup - that's the verbose information.  Azure logs at 5 different levels, Verbose (5), Information (4), Warning (3), Error (2) and Critical (1).  You can filter the logs to skip the verbose or other levels as you see fit - an example being setting the log level to Information should capture all your Trace information and above.
To configure the log level, you set this within the Azure Cloud Project settings where the numeric filter will apply, i.e. by filtering on Information you will collect Information, Warnings, Errors and Criticals - if you filter by Error you will collection Errors and Criticals.
It would appear you're either collecting all everything or have you log level to Verbose / All.
HTH


text:
Q: Batch Insert Limit mySQL PHP I need to do multiple inserts in a mySQL table using a PHP script, say Table1 but the number may exceed 1000 so I want to know if there is an insert limit as either memory or number of rows in mySQL? Also if this limit varies from server to server?

A: The primary limiting factor here is how long a statement MySQL will accept. This is defined with the max_allowed_packet system variable.
Setting this in your my.cnf file or equivalent to 1GB is usually fine. Anything beyond that gets to be absurd but you're free to increase it if you have the memory to accommodate it. Remember that both client and server will often need this in memory, so if this is on the same machine 2GB is theoretically required. Don't get too crazy here.
An INSERT statement with multiple VALUES entries can otherwise load in as much data as you can fit in that packet size.
If you're doing really big imports, LOAD DATA INFILE is often a lot faster but you will have to prepare your data in a format it can accommodate. CSV files are usually the easiest to work with here.

A: google max_allowed_packet. set it as high as your memory allows.
if strlen($YourQueryString) <= this limit, you are OK to send it
for example, once I wanted to maximize throughput of php script, so I  collected rows and counted they strlen until I hit max_allowed_packet, then send it. In cycle. It was much faster than limiting on number of rows.


text:
Q: How do you implement constructor injection in a factory? When you're using a factory pattern, how do you inject dependencies into constructors at runtime?
I'm building Foos with different formats - boolean, array, freetext, matrix, etc.  That format list will grow as we find different uses for Foo.  Here's my basic core domain:
public interface IFoo
{
    FooFormat Format { get; }
}

public class Foo : IFoo
{
    private FooFormat _format;

    internal Foo(FooFormat format)
    {
        _format = format;
    }

    public FooFormat Format { get { return _format; } }
}

public abstract class FooFormat
{
}

public class DefaultFooFormat : FooFormat
{
}

public class BooleanFooFormat : FooFormat
{
    public IList<bool> Values { get; set; }
}

public class ArrayFooFormat : FooFormat
{
    private IList<string> _values;

    public ArrayFooFormat(IList<string> values)
    {
        _values = values;
    }

    public IList<string> Values { get { return _values; } }
}

IFoo is decorated for the consumer context:
public abstract class FooDecorator : IFoo
{
    private IFoo _foo;

    protected FooDecorator(IFoo foo)
    {
        _foo = foo;
    }

    public FooFormat Format
    {
        get { return _foo.Format; }
    }

    protected IFoo foo
    {
        get { return _foo; }
    }
}

I don't want my consumer to instantiate a Foo directly, so I force them to use a factory:
public abstract class FooFactory
{
    protected IFoo Build<T>()
    {
        FooFormat format = GetFormat<T>();
        return new Foo(format);
    }

    private FooFormat GetFormat<T>()
    {
        if (typeof(T) == typeof(ArrayFooFormat)) return new ArrayFooFormat(new List<string>());
        if (typeof(T) == typeof(BooleanFooFormat)) return new BooleanFooFormat();
        return new DefaultFooFormat();
    }
}

And even then, they need to derive a factory from my abstract factory for their particular context.
I'm specifically building foos in an html context, like so:
public class HtmlFoo : FooDecorator
{
    public HtmlFoo(IFoo foo) : base(foo) { }

    public string ToHtml()
    {
        return "<div>" + this.Format.ToString() + "</div>";
    }
}

public class HtmlFooFactory : FooFactory
{
    public IFoo BuildFoo<T>()
    {
        IFoo foo = Build<T>();
        return new HtmlFoo(foo);
    }
}

public class HtmlFooConsumer
{
    public void DoSomeFoo()
    {
        var factory = new HtmlFooFactory();
        var htmlBooleanFoo = factory.BuildFoo<BooleanFooFormat>();
        var htmlArrayFoo = factory.BuildFoo<ArrayFooFormat>();
    }
}

My problem is in my abstract FooFactory: I'm always injecting an empty value list into my ArrayFooFormat.  I want to be able to pass in a value list from the consumer.  For other FooFormats, I want to pass in the right constructor arguments from the consumer.  But I want to keep the public API dead simple - I don't want a bunch of overloads on BuildFoo().
So how do I pass a custom value list into the factory.BuildFoo<T>() call from inside HtmlFooConsumer.DoSomeFoo()?  Any ideas, stackoverflow gurus?

A: Maybe you can do something along these lines where your abstract FooFormat becomes IFooFormat and a generic FooFormat provides an Init method that gets passed the parameter.
Then a single overload of Build lets you pass in the parameter.
public interface IFooFormat
{
}

public class FooFormat<TValue> : IFooFormat
{
    private TValue _value;

    public void Init(TValue value)
    {
        _value = value;
    }

    public TValue Value
    {
        get { return _value; }
    }
}

public class ArrayFooFormat : FooFormat<IList<string>> { }

public class BooleanFooFormat : FooFormat<bool> { }

public class DefaultFooFormat : IFooFormat { }

public interface IFoo { }

public class Foo : IFoo
{
    private IFooFormat _format;

    internal Foo(IFooFormat format)
    {
        _format = format;
    }

    public IFooFormat Format { get { return _format; } }
}

public class FooFactory
{
    protected IFoo Build<TFormat, TArg>(TArg arg) where TFormat : FooFormat<TArg>, new()
    {
        TFormat format = new TFormat();
        format.Init(arg);
        return new Foo(format);
    }

    protected IFoo Build<TFormat>() where TFormat : IFooFormat, new()
    {
        return new Foo(new TFormat());
    }
}

A: A factory is basically the object oriented version of a static variable. I'd avoid using one alltogether. Instead of forcing clients to use a factory, perhaps you can simply inject objects into their constructors, sidestepping the need for a factory.


text:
Q: Symfony2/Sylius don't detect stripe/stripe-php library I'm using Symfony 2.8 with Sylius 0.16.0-dev and despite of installing stripe-php library via composer composer require stripe/stripe-php this part of code throw an exception
if (!class_exists('Stripe')) {
            throw new \LogicException('You must install "stripe/stripe-php" library.');
}

Could you explain me why?

A: Add stripe/stripe-php in the require-dev section of your composer.json. Like this:
"require-dev": {
    ...
    "stripe/stripe-php": "~1.0"
},

A: As requested..
If you are using version 1.1.4 of Payum there aren't a lot of changes since then to the master (https://github.com/Payum/Payum/compare/1.1.4...master). You could use the master version in place of the actual one "payum/payum": "dev-master as 1.1.4" until the latest version is released.


text:
Q: postgresql function: Final statement returns bigint instead of integer I am using PostgreSQL ver 8.4 and have written the following custom grouping function:
CREATE OR REPLACE FUNCTION custom_group(integer)
RETURNS TABLE (
grp INTEGER,
entry_date DATE,
col1 REAL,
col2 REAL,
col3 REAL,
col4 REAL,
col5 INTEGER,
col6 INTEGER) AS
$BODY$
    SELECT ceil(rank() OVER (ORDER BY entry_date) / $1)::int as grp
          ,entry_date, col1, col2, col3, col4, col5, col6
    FROM   table_foo
    ORDER  BY 1;
$BODY$ LANGUAGE SQL;

When I try to import the function into using psql, I get the following error:

Final statement returns bigint instead of integer

I don't understand the error message, especially since I am expecting a RECORD (well table) type back.
What is causing the error, and how do I fix this?
[[Edit]]
I changed grp data type to BIGINT as suggested in the comments, however I got the same error. Details:
ERROR:  return type mismatch in function declared to return record
DETAIL:  Final statement returns integer instead of bigint at column 1.
CONTEXT:  SQL function "custom_group"

A: After the edit you are now getting a different error. You should get this new error because you explicitly cast column 1 to int and declared it to be bigint. My guess is that your original problem was col5 or col6 in table_foo is a bigint.


text:
Q: .load() firing before image ready I have some dynamically loading images that change depending on the link a user clicks.
I need to get the images width and height before displaying the images so that the page can be formatted correctly, however the .load() event will fire before the image is fully loaded and my width / height calls return NULL or 0.
I need a way to check that the images are actually loaded before trying to get the dimensions.
Any help?
CODE:
Ajax Call
function loadImages() {
    //___ Variables
    var xmlhttp;
    var responseArray = [];

    if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    } else {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange=function() {

        if (xmlhttp.readyState==4 && xmlhttp.status==200) {
            $("#preload").empty();
            //___ Get server response / Convert to Array / Drop last field
            var responseArray = xmlhttp.responseText.split(',');
            responseArray.pop();

            var windowHeight = $(window).height();
            var imgHeight = windowHeight * .9
            if (imgHeight > 1000) {//___ if WindowHeight is > 1000px make images max 900px
                imgHeight = 900;
            }

            //___ Place images in preload
            //$("#preload").append("

");
            for(var i=0;i<responseArray.length;i++){
                $("").appendTo("#preload");
            }
            ready();
        }

    };
    //console.log(portLink); //Display link clicked
    xmlhttp.open("GET","includes/displayimagesLive.php?portname="+portLink,true);
    xmlhttp.send();
}

ready() function:
function ready() {
    var div = document.getElementById("preload").childNodes;
    var count = $(div).length;
    console.log(count);

    $("#responseImage0")
        .load(function() {
            //alert("Loaded");
            alert($("#responseImage"+count).width());
        })
        .error(function() {
            alert("Error");
        });
}

A: Fellow user undefined pointed me to an awesome gitHub plugin called imagesLoaded that is doing the job perfectly.
Uncanny, really.
After doing a bunch of research and mucking about on both MAMP and live I went with lazyLoad to get the job done. Mainly because my images are large, but not so huge they need preloading.


text:
Q: Speeding up this code for codefighters javascript firstDuplicate() function Per Codefighters:

Note: Write a solution with O(n) time complexity and O(1) additional
  space complexity, since this is what you would be asked to do during a
  real interview.
Given an array a that contains only numbers in the range from 1 to
  a.length, find the first duplicate number for which the second
  occurrence has the minimal index. In other words, if there are more
  than 1 duplicated numbers, return the number for which the second
  occurrence has a smaller index than the second occurrence of the other
  number does. If there are no such elements, return -1.
Example
For a = [2, 3, 3, 1, 5, 2], the output should be firstDuplicate(a) =
  3.
There are 2 duplicates: numbers 2 and 3. The second occurrence of 3
  has a smaller index than than second occurrence of 2 does, so the
  answer is 3.
For a = [2, 4, 3, 5, 1], the output should be firstDuplicate(a) = -1.

So here is what I came up with. It works but fails on the final test because it ran over 4000ms. I'm at a loss as to what else I can do. Any Ideas to improve speed?
function firstDuplicate(a) {
    var test   = [],
        lowest = undefined;

    for (var i=0; i<a.length; i++) {
        if (test.indexOf(a[i]) > -1) {
            lowest = lowest || i;
            if (i < lowest) {
                lowest = i;
            }
        }
        else {
            test.push(a[i]);
        }
    }

    return lowest ? a[lowest] : -1;
}

Here was my second attempt but still failing on the last test...
function firstDuplicate(a) {
    var low = undefined,
        last = -1;

    for (var i=0; i<a.length; i++) {
        last = a.lastIndexOf(a[i])
        if (last > i && (low === undefined || last < low)) {
            low = last;
        }
    }

    return low !== undefined ? a[low] : -1;
}

A: We will take advantage of the fact that the array a contains only numbers in the range from 1 to a.length, to remember that a value has been seen by reversing the sign of whatever is in that position in the array.

function lowestDuplicate(arr) {

  for (let i = 0; i < arr.length; i++) {
    const val = Math.abs(arr[i]);
    if (arr[val - 1] < 0) return val;
    arr[val - 1] = -arr[val - 1];
  }
  return -1;
}

console.log(lowestDuplicate([1, 2, 3, 4, 3, 2, 1]));
console.log(lowestDuplicate([1, 2, 3, 4, 5]));
console.log(lowestDuplicate([5, 4, 3, 2, 2]));
console.log(lowestDuplicate([2, 2]));
console.log(lowestDuplicate([2, 3, 3]));
console.log(lowestDuplicate([3, 3, 3]));
console.log(lowestDuplicate([2, 3, 3, 1, 5, 2]));

A: The requirements give a clue of how to solve this. The set of numbers contained in the array must match the following critera:

only numbers in the range from 1 to a.length

In other words, only positive numbers that are less than or equal to the length of the array. If the array contains ten numbers, none of them will be greater than 10.
With that insight, we have a means of keeping track of numbers that we have already seen. We can treat the numbers themselves as indexes into the array, modify the element at that index (in this case by making it negative) and if we run into the same number and the element at that index is less than zero, then we know we have seen it.

console.clear()
const test1 = [2, 3, 3, 1, 5, 2]
const test2 = [2, 4, 3, 5, 1]

function firstDuplicate(a) {
  for (let i of a) {
    let posi = Math.abs(i) - 1
    if (a[posi] < 0) return posi + 1
    a[posi] = a[posi] * -1
  }

  return -1
}

console.log(firstDuplicate(test1))
console.log(firstDuplicate(test2))
console.log(firstDuplicate([2,2]))
console.log(firstDuplicate([2,3,3]))
console.log(firstDuplicate([3,3,3]))

Original Incorrect Answer
Keep track of what numbers have already been seen and return the first one that has been seen before.

console.clear()
const test1 =   [2, 3, 3, 1, 5, 2]
const test2 = [2, 4, 3, 5, 1]

function firstDuplicate(a){
  const seen = {}
  for (let v of a){
    if (seen[v]) return v
    seen[v] = v
  }

  return -1
}

console.log(firstDuplicate(test1))
console.log(firstDuplicate(test2))

As pointed out in the comments, however, this answer takes O(n) additional space, not O(1) additional space.

A: Python 3 version that passes the tests.
def firstDuplicate(a):
    oldies={}
    notfound=True
    for i in range(len(a)):
        try:
            if oldies[a[i]]==a[i]:
                notfound=False
                return a[i]
        except:
            oldies[a[i]]=a[i]
    if notfound:
        return -1

A: You are iterating n times in both examples.
What if the array length was 200,000,000 and the first duplicate was found at index 3? The loop is still running 200,000,000 times unnecessarily.
So the idea is to break out of the loop once you find the first duplicate.
you can use break or just return.

A: A simple solution in JS. As the question title focus, you just need to find the first duplicate of the number you already traversed. So i guess this will do:
function solution(a) {
let duplicateArray = []
for(let i=0;i<a.length;i++){
    if(duplicateArray.includes(a[i])){
        return a[i];
    }
    duplicateArray.push(a[i])
}return -1;}

Hope this helps.


text:
Q: Add fade to this jQuery rollover How would I add a fade, or animate a change in opacity to this piece of jQuery?
Thanks
<script  type='text/javascript'>
$(document).ready(function(){
    $(".alain").hover(
        function() {$(this).attr("src","images/rollovers/alain-rollover.png");},
        function() {$(this).attr("src","thumbnails/alain-thumbnail.jpg");
    });
});
</script>

A: fade the image out, change the source, fade the image back in :
$(document).ready(function(){
    $(".alain").on('mouseenter mouseleave', function(e) {
        var src = e.type == 'mouseenter' ? 'images/rollovers/alain-rollover.png' : 'thumbnails/alain-thumbnail.jpg';

        $(this).fadeOut('slow', function() {
            $(this).prop('src', src).fadeIn('slow');
        });
    });
});

jsbin
If older browsers aren't an issue, adding and removing a class with CSS3 transitions seems easier.


text:
Q: I want to get the location changes, but I get JNI DETECTED ERROR IN APPLICATION in GoogleApiClient I want to get the location changes by the method of OnLocationChanged, I used the OnMyLocationChanged before but I see that this method is already in disuse, but with the new meotodo it marks me error when assigning the mGoogleApiClient variable
namespace FuncionesAndroid.Droid
{
    [Activity(Label = "MainMapa")]
    public class MainMapa : Activity, IOnMapReadyCallback, IOnMyLocationClickListener, IOnMyLocationButtonClickListener, Android.Gms.Location.ILocationListener, GoogleApiClient.IConnectionCallbacks, GoogleApiClient.IOnConnectionFailedListener
    {
        private string _tag = "MainMapa";
        GoogleMap mapa = null;
        DataBase db = new DataBase();
        private LocationRequest locationRequest;
        static GoogleApiClient mGoogleApiClient;
        public static int MILISEGUNDOS_POR_SECUNDOS = 1000;
        public static int MINUTO = 60 * MILISEGUNDOS_POR_SECUNDOS;
        //private IFusedLocationProviderApi locationProvider = LocationServices.FusedLocationApi;
        public async void  OnMapReady(GoogleMap googleMap)
        {
            mapa = googleMap;
            googleMap.MyLocationEnabled = true;
            googleMap.SetOnMyLocationButtonClickListener(this);
            googleMap.SetOnMyLocationClickListener(this);
            googleMap.SetMinZoomPreference(6.0F);

        //Opcional
        googleMap.SetLatLngBoundsForCameraTarget(new LatLngBounds(new LatLng(14.399838, -119.346947),new LatLng(30.706694, -83.355215)));
        googleMap.UiSettings.ZoomControlsEnabled = true;
        googleMap.UiSettings.CompassEnabled = true;
        locationRequest = new LocationRequest();
        locationRequest.SetInterval(MINUTO);
        locationRequest.SetFastestInterval(15 * MILISEGUNDOS_POR_SECUNDOS);
        locationRequest.SetPriority(LocationRequest.PriorityHighAccuracy);

        try
        {
            mGoogleApiClient = new GoogleApiClient.Builder(this)
            .AddConnectionCallbacks(this)
            .AddOnConnectionFailedListener(this)
            .AddApi(LocationServices.API)
            .Build();
        }
        catch (Exception e)
        {
            Log.Debug(_tag, e.Message);
        }

        googleMap.MoveCamera(CameraUpdateFactory.ZoomIn());
        CargarMarcadores();
        CentrarMyUbicacion();

    }

    private void GuardarRutas(ArrayList rutas, int idInicio, int idFin)
    {
        foreach (ArrayList path in rutas)
        {
            foreach (Dictionary<String, Double> punto in path)
            {
                Model.Polyline polyline = new Model.Polyline()
                {
                    id_inicio = idInicio,
                    id_fin = idFin,
                    lat = punto["lat"],
                    lon = punto["lon"]
                };
                db.InsertarDatoPolyline(polyline, this);
            }
        }
    }

    public void CargarMarcadores()
    {
        BitmapDrawable bitmapClienteDraw = (BitmapDrawable)GetDrawable(Resource.Mipmap.marker_map_us);
        Bitmap bitmapCliente = bitmapClienteDraw.Bitmap;
        Bitmap smallMarkerCliente = Bitmap.CreateScaledBitmap(bitmapCliente, 60, 90, false);

        List<ClientesGps> clientesGps;
        clientesGps = db.selectTablaClientesGps(this);
        Location miUbicacion = ObtenerUbicacionActual();
        foreach (ClientesGps cliente in clientesGps)
        {
            MarkerOptions clienteMarcador = new MarkerOptions()
            .SetPosition(new LatLng(cliente.lat, cliente.lon))
            .SetIcon(BitmapDescriptorFactory.FromBitmap(smallMarkerCliente))
            .SetTitle(cliente.nombre);
            mapa.AddMarker(clienteMarcador);
        }
    }

    public void CentrarMyUbicacion()
    {
        LocationManager locationManager = (LocationManager)
            GetSystemService(Context.LocationService);
        Criteria criteria = new Criteria();
        criteria.Accuracy = Accuracy.Fine;
        Location Ubicación = locationManager.GetLastKnownLocation(locationManager.GetBestProvider(criteria, false));
        if (Ubicación != null)
        {
            LatLng myUbicación = new LatLng(Ubicación.Latitude, Ubicación.Longitude);
            mapa.AnimateCamera(CameraUpdateFactory.NewLatLngZoom(myUbicación,15.4F));
        }
    }

    public Location ObtenerUbicacionActual()
    {
        LocationManager locationManager = (LocationManager)
            GetSystemService(Context.LocationService);
        Criteria criteria = new Criteria();
        criteria.Accuracy = Accuracy.Fine;
        Location Ubicación = locationManager.GetLastKnownLocation(locationManager.GetBestProvider(criteria, false));
        return Ubicación;
    }

    public void DibujarRutas(ArrayList rutas, GoogleMap googleMap)
    {
        PolylineOptions polylineOptions = null;

        foreach(ArrayList path in rutas)
        {
            polylineOptions = new PolylineOptions();

            foreach(Dictionary<String, Double> punto in path)
            {
                double lat, lon;
                lat = punto["lat"];
                lon = punto["lon"];
                polylineOptions.Add(new LatLng(lat, lon));
            }
            polylineOptions.InvokeWidth(15);
            polylineOptions.InvokeColor(Color.Blue);
            polylineOptions.Geodesic(true);
        }

        if(polylineOptions!=null)
        {
            googleMap.AddPolyline(polylineOptions);
        }
        else
        {
            Toast.MakeText(this, "Direcciones no encontradas", ToastLength.Short).Show();
        }
    }

    private async Task<ArrayList> GetUrlAsync(LatLng origin,LatLng dest, String directionMode)
    {
        String str_origin = "origin=" + origin.Latitude + "," + origin.Longitude;
        String str_dest = "destination=" + dest.Latitude + "," + dest.Longitude;
        String mode = "mode=" + directionMode;
        String parameters = str_origin + "&" + str_dest + "&" + mode;
        String output = "json";
        JObject json = await Servicios.Servicio.ObtenerRutaGoogleMaps(output, parameters, GetString(Resource.String.GoogleKey));

        ArrayList routes = new ArrayList();
        JArray jRoutes = null;
        JArray jLegs = null;
        JArray jSteps = null;
        try
        {
            jRoutes = (JArray)json["routes"];
            for (int i = 0; i < jRoutes.Count; i++)
            {
                jLegs = (JArray)jRoutes[i]["legs"];
                ArrayList path = new ArrayList();
                for (int j = 0; j < jLegs.Count; j++)
                {
                    jSteps = (JArray)jLegs[j]["steps"];
                    for (int k = 0; k < jSteps.Count; k++)
                    {
                        String polyline = "";
                        polyline = (String)jSteps[k]["polyline"]["points"];
                        ArrayList list = decodePolyline(polyline);
                        for(int l = 0; l < list.Count; l++)
                        {
                            Dictionary<String, Double> hm = new Dictionary<string, Double>();
                            hm.Add("lat", ((LatLng)list[l]).Latitude);
                            hm.Add("lon", ((LatLng)list[l]).Longitude);
                            path.Add(hm);
                        }
                    }
                    routes.Add(path);
                }
            }
            return routes;
        }
        catch (JsonReaderException e)
        {
            routes = null;
            return routes;
        }
    }

    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        SetContentView(Resource.Layout.MainMapa);
        MapFragment mapFragment = (MapFragment)FragmentManager.FindFragmentById(Resource.Id.map);
        mapFragment.GetMapAsync(this);
    }

    protected override void OnResume()
    {
        base.OnResume();
        if(mGoogleApiClient.IsConnected)
        {
            RequestLocationUpdates();
        }
    }

    protected override void OnStart()
    {
        base.OnStart();
        mGoogleApiClient.Connect();
    }

    protected override void OnStop()
    {
        base.OnStop();
        mGoogleApiClient.Disconnect();
    }

    private void RequestLocationUpdates()
    {
        LocationServices.FusedLocationApi.RequestLocationUpdates(mGoogleApiClient, locationRequest, this);
    }

    protected override void OnPause()
    {
        base.OnPause();
        LocationServices.FusedLocationApi.RemoveLocationUpdates(mGoogleApiClient, this);
    }

    public void OnMyLocationClick(Location location)
    {
        Toast.MakeText(this, "My Ubicación actual", ToastLength.Short).Show();
    }

    public bool OnMyLocationButtonClick()
    {
        Toast.MakeText(this, "Centrando en ubicación actual", ToastLength.Short).Show();
        return false;
    }

    public async void OnLocationChanged(Location location)
    {
        Toast.MakeText(this, location.ToString(),ToastLength.Short).Show();
    }

    public void OnConnectionFailed(ConnectionResult result)
    {
        //throw new NotImplementedException();
    }

    public void OnConnected(Bundle connectionHint)
    {
        RequestLocationUpdates();
    }

    public void OnConnectionSuspended(int cause)
    {
        //throw new NotImplementedException();
    }
}
}

Likewise, I have seen some codes that are not in disuse, that do not use the Google AppClient, but do not explain the use or are not very well documented, if they have some better code I would appreciate it very much

A: The solution was very simple and silly, I read in another forum, when it comes to GoogleApiClient is normal to fail the first in Xamarin, the right thing is to clean and recompile the solution when it comes to it, thank you very much as you want to read !


text:
Q: How to bottom align Button in the popup? How to bottom align button in the popup ?
here is my tried code, but its giving some space from bottom.
I have used listview to build up popup
     onPressed: () {
         // Navigator.of(context).pushNamed(homePageTag);
            showDialog(
                context: context,
                builder: (BuildContext context) {
                  return AlertDialog(
                    content: Form(
                      key: _formKey,
                      child: ListView(
                        shrinkWrap: true,//This tells items to be put in center
                        children: <Widget>[

                          FlatButton(
                              //padding: EdgeInsets.fromLTRB(0, 0, 0, 0),
                              color: appGreenColor,
                              child: Text("UPDATE", style: TextStyle(color: Colors.white)),
                              onPressed: () {

                              },
                            ),

                        ],
                      ),
                    ),
                  );
                });
        },

Looking for this-  https://ibb.co/19k2ty7
& getting this - https://ibb.co/h7KwXbn

A:     import 'package:flutter/material.dart';

    void main() => runApp(MyApp());
    Color myColor = Color(0xff00bfa5);

    class MyApp extends StatelessWidget {
    @override
    Widget build(BuildContext context) {
        return MaterialApp(
        debugShowCheckedModeBanner: false,
        title: "Rounde Alert Box",
        home: Scaffold(
            appBar: AppBar(
            backgroundColor: myColor,
            title: Text("Rounded Alert Box"),
            ),
            body: RoundedAlertBox(),
        ),
        );
    }
    }

    class RoundedAlertBox extends StatefulWidget {
    @override
    _RoundedAlertBoxState createState() => _RoundedAlertBoxState();
    }

    class _RoundedAlertBoxState extends State<RoundedAlertBox> {
    @override
    Widget build(BuildContext context) {
        return Center(
        child: RaisedButton(
            onPressed: openAlertBox,
            color: myColor,
            child: Text(
            "Open Alert Box",
            style: TextStyle(color: Colors.white),
            ),
        ),
        );
    }

    openAlertBox() {
        return showDialog(
            context: context,
            builder: (BuildContext context) {
            return AlertDialog(
                shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.all(Radius.circular(32.0))),
                contentPadding: EdgeInsets.only(top: 10.0),
                content: Container(
                width: 300.0,
                child: Column(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.stretch,
                    mainAxisSize: MainAxisSize.min,
                    children: <Widget>[
                    Row(
                        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                        mainAxisSize: MainAxisSize.min,
                        children: <Widget>[
                        Text(
                            "Rate",
                            style: TextStyle(fontSize: 24.0),
                        ),
                        Row(
                            mainAxisSize: MainAxisSize.min,
                            children: <Widget>[
                            Icon(
                                Icons.star_border,
                                color: myColor,
                                size: 30.0,
                            ),
                            Icon(
                                Icons.star_border,
                                color: myColor,
                                size: 30.0,
                            ),
                            Icon(
                                Icons.star_border,
                                color: myColor,
                                size: 30.0,
                            ),
                            Icon(
                                Icons.star_border,
                                color: myColor,
                                size: 30.0,
                            ),
                            Icon(
                                Icons.star_border,
                                color: myColor,
                                size: 30.0,
                            ),
                            ],
                        ),
                        ],
                    ),
                    SizedBox(
                        height: 5.0,
                    ),
                    Divider(
                        color: Colors.grey,
                        height: 4.0,
                    ),
                    Padding(
                        padding: EdgeInsets.only(left: 30.0, right: 30.0),
                        child: TextField(
                        decoration: InputDecoration(
                            hintText: "Add Review",
                            border: InputBorder.none,
                        ),
                        maxLines: 8,
                        ),
                    ),
                    InkWell(
                        child: Container(
                        padding: EdgeInsets.only(top: 20.0, bottom: 20.0),
                        decoration: BoxDecoration(
                            color: myColor,
                            borderRadius: BorderRadius.only(
                                bottomLeft: Radius.circular(32.0),
                                bottomRight: Radius.circular(32.0)),
                        ),
                        child: Text(
                            "Rate Product",
                            style: TextStyle(color: Colors.white),
                            textAlign: TextAlign.center,
                        ),
                        ),
                    ),
                    ],
                ),
                ),
            );
            });
    }
    }


text:
Q: vbscript string INequality when one side is null other not First post here.  Please feel free to let me know if I should post this somewhere else or whatever. :)
I've Googled for variations on "String Compare" and "String Inequality" and their results are useless.  My problem is that I'm checking for string inequality and I'm getting surprising results when one side is null and the other isn't.  Consider the following demonstration code:
TestStr "foo", "foo", "="
TestStr "foo", "bar", "<>"
TestStr Null, "foo", "<>"
TestStr "foo", Null, "<>"

Sub TestStr(left, right, expected)
    ' I actually don't care about this - it's here for reference
    If left = right Then
        WScript.Echo "left = right - expected " & expected
    Else
        WScript.Echo "left <> right - expected " & expected
    End If

    If left <> right Then
        WScript.Echo "left <> right - expected " & expected
    Else
        WScript.Echo "left = right - expected " & expected
    End If
    WScript.Echo ""
End Sub

Running this code produces the following output ("codified" so it isn't formatted):
left = right - expected =
left = right - expected =

left <> right - expected <>
left <> right - expected <>

left <> right - expected <>
left = right - expected <>

left <> right - expected <>
left = right - expected <>

As you can see, string inequality fails when one side is null and the other isn't - which I'm current experiencing.  I know I can do what's below, but I'm wondering if I'm missing an easier way:
If (left = right) Then
Else
    ' Do inequality stuff here...
End If

[EDIT] I'm getting great feedback on why this is happening.  Thanks folks!  However, I'm also interested in how to avoid this.
[EDIT 2] What I'm hoping for is a simple way to know when the strings are different (thanks for the suggestion Ekkehard.Horner).

*

*If both are null, then one could argue that they aren't the same, but they're same enough for me.

*If one is null and the other is not, then they're different - pretty obviously.

*If both are not null, then they are the same if they're the exactly the same - including case sensitivity.

So for my purposes, something where "expected" and what actually happens in my demo code agree would be sufficient.

A: I think you miss the base of Comparison Operators in VBScript.
Comparing with Null always return Null, not boolean (True/False).
Update:
String comparison is case sensitive, but your script will compare String with Null in some cases, and your second question is how to simplify this task, right? In this case writing a function is a good idea.
Function CompStr(sVal1, sVal2)
    CompStr = False
    If VarType(sVal1) <> vbString Then Exit Function
    If VarType(sVal2) <> vbString Then Exit Function
    CompStr = sVal1 = sVal2
End Function

A: To illustrate Panayot's statement (+1) and make it easy to experiment:
  ' vbEmpty         0  Uninitialized (default)
  ' vbNull          1  Contains no valid data
  ' vbInteger       2  Integer subtype
  ' vbLong          3  Long subtype
  ' vbSingle        4  Single subtype
  ' vbDouble        5  Double subtype
  ' vbCurrency      6  Currency subtype
  ' vbDate          7  Date subtype
  ' vbString        8  String subtype
  ' vbObject        9  Object
  ' vbError        10  Error subtype
  ' vbBoolean      11  Boolean subtype
  ' vbVariant      12  Variant (used only for arrays of variants)
  ' vbDataObject   13  Data access object
  ' vbDecimal      14  Decimal subtype
  ' vbByte         17  Byte subtype
  ' vbArray      8192  Array
  Dim aData : aData = Array(Empty, Null, CInt(0), CLng(0), "", "a", Nothing)
  Dim sXfx  : sXfx  = Space(25)
  Dim k     : k     = 0
  Dim i, j
  For i = 0 To UBound(aData)
      For j = 0 To UBound(aData)
          WScript.Echo               _
               Right(1000 + k, 3)     _
             , Right(sXfx & toTypeStr(aData(i)), 25)   _
             , Left(toTypeStr(aData(j))& sXfx, 25)   _
             , compareX(aData(i), aData(j))
          k = k + 1
      Next
  Next

Function toTypeStr(vX)
  Dim aTmp : aTmp = Array(VarType(vX), TypeName(vX), "")
  Select Case aTmp(0)
    Case vbEmpty  : aTmp(2) = "<Empty>"
    Case vbNull   : aTmp(2) = "<Null>"
    Case vbString : aTmp(2) = """" & vX & """"
    Case vbObject : aTmp(2) = "<Object>"
    Case Else     : aTmp(2) = CStr(vX)
  End Select
  toTypeStr = Join(aTmp, ":")
End Function

Function compareX(vLHS, vRHS)
  Dim vEQ
 On Error Resume Next
  vEQ = vLHS = vRHS
  If Err.Number Then compareX = Err.Description : Exit Function : End If
 On Error GoTo 0
  Select Case True
    Case VarType(vEQ) = vbNull
      compareX = toTypeStr(vEQ) & " - can't compare with Null"
    Case VarType(vEQ) <> vbBoolean
      compareX = toTypeStr(vEQ) & " surprise"
    Case vEQ
      compareX = "equal"
    Case Else
      compareX = "not equal"
  End Select
End Function

output:
000           0:Empty:<Empty> 0:Empty:<Empty>           equal
001           0:Empty:<Empty> 1:Null:<Null>             1:Null:<Null> - can't compare with Null
002           0:Empty:<Empty> 2:Integer:0               equal
003           0:Empty:<Empty> 3:Long:0                  equal
004           0:Empty:<Empty> 8:String:""               equal
005           0:Empty:<Empty> 8:String:"a"              not equal
006           0:Empty:<Empty> 9:Nothing:<Object>        Object variable not set
007             1:Null:<Null> 0:Empty:<Empty>           1:Null:<Null> - can't compare with Null
008             1:Null:<Null> 1:Null:<Null>             1:Null:<Null> - can't compare with Null
009             1:Null:<Null> 2:Integer:0               1:Null:<Null> - can't compare with Null
010             1:Null:<Null> 3:Long:0                  1:Null:<Null> - can't compare with Null
011             1:Null:<Null> 8:String:""               1:Null:<Null> - can't compare with Null
012             1:Null:<Null> 8:String:"a"              1:Null:<Null> - can't compare with Null
013             1:Null:<Null> 9:Nothing:<Object>        Object variable not set
014               2:Integer:0 0:Empty:<Empty>           equal
015               2:Integer:0 1:Null:<Null>             1:Null:<Null> - can't compare with Null
016               2:Integer:0 2:Integer:0               equal
017               2:Integer:0 3:Long:0                  equal
018               2:Integer:0 8:String:""               not equal
019               2:Integer:0 8:String:"a"              not equal
020               2:Integer:0 9:Nothing:<Object>        Object variable not set
021                  3:Long:0 0:Empty:<Empty>           equal
022                  3:Long:0 1:Null:<Null>             1:Null:<Null> - can't compare with Null
023                  3:Long:0 2:Integer:0               equal
024                  3:Long:0 3:Long:0                  equal
025                  3:Long:0 8:String:""               not equal
026                  3:Long:0 8:String:"a"              not equal
027                  3:Long:0 9:Nothing:<Object>        Object variable not set
028               8:String:"" 0:Empty:<Empty>           equal
029               8:String:"" 1:Null:<Null>             1:Null:<Null> - can't compare with Null
030               8:String:"" 2:Integer:0               not equal
031               8:String:"" 3:Long:0                  not equal
032               8:String:"" 8:String:""               equal
033               8:String:"" 8:String:"a"              not equal
034               8:String:"" 9:Nothing:<Object>        Object variable not set
035              8:String:"a" 0:Empty:<Empty>           not equal
036              8:String:"a" 1:Null:<Null>             1:Null:<Null> - can't compare with Null
037              8:String:"a" 2:Integer:0               not equal
038              8:String:"a" 3:Long:0                  not equal
039              8:String:"a" 8:String:""               not equal
040              8:String:"a" 8:String:"a"              equal
041              8:String:"a" 9:Nothing:<Object>        Object variable not set
042        9:Nothing:<Object> 0:Empty:<Empty>           Object variable not set
043        9:Nothing:<Object> 1:Null:<Null>             Object variable not set
044        9:Nothing:<Object> 2:Integer:0               Object variable not set
045        9:Nothing:<Object> 3:Long:0                  Object variable not set
046        9:Nothing:<Object> 8:String:""               Object variable not set
047        9:Nothing:<Object> 8:String:"a"              Object variable not set
048        9:Nothing:<Object> 9:Nothing:<Object>        Object variable not set

As you can see from #001 and #007-#013, the result of an operation (here: =) applied to a Null value is always Null.
Update:
For the special case (Null or Strings only, both Null are considered equal):
  Dim aData : aData = Array(Null, "", "a")
  Dim sXfx  : sXfx  = Space(25)
  Dim k     : k     = 0
  Dim i, j
  For i = 0 To UBound(aData)
      For j = 0 To UBound(aData)
          WScript.Echo               _
               Right(1000 + k, 3)     _
             , Right(sXfx & toTypeStr(aData(i)), 25)   _
             , Left(toTypeStr(aData(j))& sXfx, 25)   _
             , CStr(compareStrNull(aData(i), aData(j)))
          k = k + 1
      Next
  Next

Function compareStrNull(vLHS, vRHS)
  Dim ntLHS : ntLHS = VarType(vLHS)
  Dim ntRHS : ntRHS = VarType(vRHS)
  Select Case True
'   If both are null, then one could argue that they aren't the same, but they're same enough for me.
    Case ntLHS = ntRHS And ntLHS = vbNull
      compareStrNull = True
'   If one is null and the other is not, then they're different - pretty obviously.
    Case ntLHS = vbNull Or ntRHS = vbNull
      compareStrNull = False
'   If both are not null, then they are the same if they're the exactly the same - including case sensitivity.
    Case ntLHS = ntRHS And ntLHS = vbString
      compareStrNull = vLHS = vRHS
    Case Else
      Err.Raise 4711, "compareStrNull", "surprise"
  End Select
End Function

output:
000             1:Null:<Null> 1:Null:<Null>             True
001             1:Null:<Null> 8:String:""               False
002             1:Null:<Null> 8:String:"a"              False
003               8:String:"" 1:Null:<Null>             False
004               8:String:"" 8:String:""               True
005               8:String:"" 8:String:"a"              False
006              8:String:"a" 1:Null:<Null>             False
007              8:String:"a" 8:String:""               False
008              8:String:"a" 8:String:"a"              True

Update II:
Simplified/Optimized version of the compare function:
Function compareStrNull02(vLHS, vRHS)
  compareStrNull02 = vLHS = vRHS                      ' native compare
  If VarType(compareStrNull02) = vbNull Then          ' at least one param is Null
     compareStrNull02 = VarType(vLHS) = VarType(vRHS) ' are both Null?
  End If
End Function

Dealing with arrays or objects needs further work.

A: Try adding this as the first line:
if isnull (left) or isnull (right) then exit sub


text:
Q: Python making sure x is an int, and not a pesky float For example:
import random
x = random.randint(1, 6)
y = 2
new = x / y
...

now, lets say x turns out to be 5.
How can I catch if it's an int or a float before doing other things in my program?

A: By default, integer division works a little unexpected in python 2, if you don't
from __future__ import division

Example:
>>> 5 / 3
1
>>> isinstance(5 / 3, int)
True

Explanation: Why doesn't this division work in python?
Finally, you can always convert numbers to int:
>>> from __future__ import division
>>> int(5/3)
1

A: If you want want new to always be an int, one option is floor division:
new = x // y

Another is to round:
new = int(round(x/y))

If instead, you just wanted to check if new is a float, that's a little unusual in Python (usually, type-checking isn't necessary). If so, tell us more about why you want to check and you'll get better guidance.

A: isinstance(x, int)

But it's rare you need to do this.  Double-checking the standard library is probably not one of those times. :)
Note that you can also catch exceptions in some cases (though that wouldn't apply to this example).

A: If you don't mind the value being truncated (5.7 would become 5), you can simply cast it to an int.
must_be_an_int = int(x)

If for some reason x is something that python can't convert to an int, it will raise a ValueError exception.


text:
Q: R: Implementing Elo ratings for team game; assigning values to multiple variables from within a loop I have data that looks like this:
  a1   a2   a3   a4   a5   h1   h2   h3   h4   h5 a.evt.score   h.evt.score
3311 4003 2737 3784 4177 2632  726  633  438 5444           0             1
1696  371 4471 2119  274 1947 5745 3622  438 5444           1             0
1696  371 4471 1199 2230 1947 5745 3622 5034 4166           1             0
3191 4471 2737  274 2230 3598  633 5034 5444 3485           1             0
3191 3685 3486 3784 4177 2632  726  633  438 5444           0             1
127  713 1609 5444 4166 3311  371 4471 1199 2230           1             0
127  713 1609 2345 3485 1696 4003 2737 1199 2230           1             0
127  713 1609 2345 3485 1696 4003 2737 1199 2230           1             0
1947 5745 3622  438 5444 3311  371 4471 3784 4177           1             0
2632  726  633 5444 4166 3191 3685 3486  274 2230           0             1
2632  726  633  438 5444 3191 3685 3486 3784 4177           0             1
5745 3598 5198 4166 3485 1696 4003 2737  274 2230           0             1
2632  726  633 2345 5034 3311  371 4471 3784 4177           1             0
127 3859  726  438 5444 1696 4003 2737 2119  274           1             0
2632  713  633 5034 4166 3191 3685 3486 3784 4177           1             0

The numbers in the a1, a2, a3..., h4, h5 columns are unique ids of players.
(a1, ... , a5) play on the "away" team, and (h1, ..., h5) are their opponents.
Each row is an event in the game.
"a.evt.score" indicates whether or not the away team "won" the event.
I would like to, for each player, calculate his Elo rating after every event (row) in the data.
The formula used to calculate a players' rating is:
R_new = R_old + k*(Score - Expected)
Where "Score" is 1 if the team wins the event, and 0 if not.
Let k be 30 (tells how much each event influences the overall rating).
And have every player start with an R_old of 2200.
"Expected", I calculate with the formula (say we are looking at player 1 on the away team):
h.R <- c(h1.R, h2.R, h3.R, h4.R, h5.R)
a1.E <- sum(1/(1+10^((h.R - a1.R)/400)))/5

So, a1's new rating would be:
a1.R <- a1.R + 30*(a.evt.score - a1.E)

I would like my end result to be a vector, for every player,
of their history of Elo ratings.
So, for every row in the data, I would like to:

*

*Get the most recent Elo for every player involved. Set this to R_old.

*For each player, calculate a new Elo based on the result of the event.

*Append this new rating (R_new) to the start of each players' history vector.

The issue I'm running into is that I can't figure out how to pull a value (R_old) from a named variable (a given player's Elo history vector) when I'm inside a loop/apply function, or how to append the calculated rating to the variable.
How can I go about doing the above?

A: My best bet, there's probably room for improvement.
The main idea is to build a list of players, with one entry by player id to store the player score history.
The new score calculation is done in a separate function, maybe I didn't get exactly what you're wishing to do. I hope I commented enough to explain what's going on.
k<-30
ateam<-paste0("a",1:5)
hteam<-paste0("h",1:5)
playersid <- unique(unname( unlist( datas[, c(ateam,hteam) ] ) ))
scores=as.list(rep(2200,length(playersid)))
names(scores)<-playersid

getPlayerScore <- function(player,team_score,opponents_scores) {
  old_score <- scores[[as.character(player)]][1]
  expect <- sum(1/10^((opponents_scores - old_score)/400))/5
  return(old_score + k*(team_score - expect))
}

updateTeamPlayersScore<-function(row,team) {
  opteam<-ifelse(team=="a","h","a") # get the team we're against
  players <- unlist(row[get(paste0(team,"team"))]) # get the players list
  opponents <- unlist(row[get(paste0(opteam,"team"))]) # get the oppenents list
  # Get the oppents scores
  opponents_score <- sapply(scores[as.character(opponents)],function(x) { x[[1]] } )
  # loop over the players and return the list of updated scores
  r<-lapply(players,function(x) {
    new_score <- getPlayerScore(x,as.numeric(row[paste0(team,".evt.score")]),opponents_score)
    c(new_score,scores[[as.character(x)]])
  })
  # Update the list names
  names(r) <- as.character(opponents)
  r # return the new scores list
}

# loop over the rows.
# The update is done after calculation to avoid side-effect on h scores with updated a scores
for (i in 1:nrow(datas)) {
  row <- datas[i,]
  # Get updated scores for team a
  new_a <- updateTeamPlayersScore(row,"a")
  # Get updated scores for team h
  new_h <- updateTeamPlayersScore(row,"h")
  # update team 'a' scores
  scores[names(new_a)] <- new_a
  # update team 'h' scores
  scores[names(new_h)] <- new_h
}

Result
> head(scores)
$`3311`
[1] 2124.757 2119.203 2111.189 2136.164 2165.133 2200.000

$`1696`
[1] 2135.691 2135.032 2170.030 2168.635 2200.000 2200.000

$`3191`
[1] 2142.342 2141.330 2176.560 2174.560 2170.000 2200.000

$`127`
[1] 2098.406 2123.018 2158.292 2193.603 2200.000

$`1947`
[1] 2158.292 2193.603 2200.000

$`2632`
[1] 2100.837 2132.849 2168.509 2173.636 2170.000 2200.000

Data used:
datas<-read.table(text="  a1   a2   a3   a4   a5   h1   h2   h3   h4   h5 a.evt.score   h.evt.score
    3311 4003 2737 3784 4177 2632  726  633  438 5444           0             1
    1696  371 4471 2119  274 1947 5745 3622  438 5444           1             0
    1696  371 4471 1199 2230 1947 5745 3622 5034 4166           1             0
    3191 4471 2737  274 2230 3598  633 5034 5444 3485           1             0
    3191 3685 3486 3784 4177 2632  726  633  438 5444           0             1
    127  713 1609 5444 4166 3311  371 4471 1199 2230           1             0
    127  713 1609 2345 3485 1696 4003 2737 1199 2230           1             0
    127  713 1609 2345 3485 1696 4003 2737 1199 2230           1             0
    1947 5745 3622  438 5444 3311  371 4471 3784 4177           1             0
    2632  726  633 5444 4166 3191 3685 3486  274 2230           0             1
    2632  726  633  438 5444 3191 3685 3486 3784 4177           0             1
    5745 3598 5198 4166 3485 1696 4003 2737  274 2230           0             1
    2632  726  633 2345 5034 3311  371 4471 3784 4177           1             0
    127 3859  726  438 5444 1696 4003 2737 2119  274           1             0
    2632  713  633 5034 4166 3191 3685 3486 3784 4177           1             0",header=T)

A: I build and maintain a separate running list of ratings of every player after every event. That way you can refer to it for calculation in the next event.
First, loading all data , parameters and packages.
library(tidyr)
library(dplyr)

crosstab <- read.table(header=T,
                       text="  a1   a2   a3   a4   a5   h1   h2   h3   h4   h5 a.evt.score   h.evt.score
                       3311 4003 2737 3784 4177 2632  726  633  438 5444           0             1
                       1696  371 4471 2119  274 1947 5745 3622  438 5444           1             0
                       1696  371 4471 1199 2230 1947 5745 3622 5034 4166           1             0
                       3191 4471 2737  274 2230 3598  633 5034 5444 3485           1             0
                       3191 3685 3486 3784 4177 2632  726  633  438 5444           0             1
                       127  713 1609 5444 4166 3311  371 4471 1199 2230           1             0
                       127  713 1609 2345 3485 1696 4003 2737 1199 2230           1             0
                       127  713 1609 2345 3485 1696 4003 2737 1199 2230           1             0
                       1947 5745 3622  438 5444 3311  371 4471 3784 4177           1             0
                       2632  726  633 5444 4166 3191 3685 3486  274 2230           0             1
                       2632  726  633  438 5444 3191 3685 3486 3784 4177           0             1
                       5745 3598 5198 4166 3485 1696 4003 2737  274 2230           0             1
                       2632  726  633 2345 5034 3311  371 4471 3784 4177           1             0
                       127 3859  726  438 5444 1696 4003 2737 2119  274           1             0
                       2632  713  633 5034 4166 3191 3685 3486 3784 4177           1             0")

#parameters
k <- 30
seed.rating <- 2200   # default used if a player is not found on ratings table

Next, two local helper functions to do the expectation calculations.
# calculate expected win against an opponent
calcExpect <- function(rating, opp.rating) {
  return(1/(1+10^((opp.rating-rating)/400)))
}

# calculate average expectation of a player against all opponents in current event
compileExpect <- function(id) {
  rowno <- which(roster$playerid==id)
  opp <- roster %>% filter(ah!=roster$ah[rowno])
  all.expected <- sapply(opp$rating,
                         function(x) calcExpect(roster$rating[rowno], x))
  return(mean(all.expected))
}

Then setup the list that is updated after every event (i.e. ratings list, and optionally result after every event). Here we start with an empty ratings list, but if you have an existing rating list, you can easily start with that data frame as the first element in the list.
# start with a blank rating list; can always start with the latest ELO table
ratings <- list(data.frame(playerid=integer(0), rating=numeric(0)))

# optional for logging result for every round, for error checking
rosters <- NULL

Now the main meat: loop through the entire events data i.e. crosstab and processing each event, creating one entry in ratings (and optionally rosters) after every event.
You will notice that after I built the roster, I don't have different code lines to calculate ratings or expectation for players on "a" or "h" teams. This should make this code easier to adapt for events where there are more than 2 teams (e.g. a league).
for (i in seq_len(nrow(crosstab))) {

  # get latest ratings
  elo <- as.data.frame(tail(ratings, 1))

  # take one row of data corresponding to an event
  event <- crosstab[i, ]

  # spread the row into a player roster
  roster <- event %>% gather(key=no, value=playerid, a1:h5) %>%
    mutate(ah = substr(no, 1, 1),    # away or home team
           score = ifelse(ah=="a", a.evt.score, h.evt.score)) %>%   #win or lose
    select(playerid, ah, score) %>%
    left_join(elo)  # get current rating

  # unrated players assigned base rating
  roster$rating[is.na(roster$rating)] <- seed.rating

  # calculate expected and new ratings of event participants
  roster$expected <- sapply(roster$playerid, compileExpect)
  roster$new.rating <- with(roster, rating + k*(score-expected))

  # calculate new overall ratings
  new.ratings <- roster %>% select(playerid, new.rating) %>%
    rename(rating=new.rating) %>%
    rbind(elo) %>%
    filter(!duplicated(playerid))  # remove old ratings of player

  #update ratings
  ratings <- c(ratings, list(new.ratings))

  # Optional for error checking: update log of result every round
  rosters <- c(rosters, list(roster))

}

The output would be a list ratings with 16 elements, and rosters with 15 elements. Element x in ratings is the ratings before event number x, while element x in rosters is the outcome after event number x.
Let's take for example event 2 (i.e. second row in your table).
> rosters[[2]]
   playerid ah score rating  expected new.rating
1      1696  a     1   2200 0.4913707   2215.259
2       371  a     1   2200 0.4913707   2215.259
3      4471  a     1   2200 0.4913707   2215.259
4      2119  a     1   2200 0.4913707   2215.259
5       274  a     1   2200 0.4913707   2215.259
6      1947  h     0   2200 0.5000000   2185.000
7      5745  h     0   2200 0.5000000   2185.000
8      3622  h     0   2200 0.5000000   2185.000
9       438  h     0   2215 0.5215733   2199.353
10     5444  h     0   2215 0.5215733   2199.353

Initial inspection seems that everything is in order: 8 players who didn't play earlier have starting rating of 2200, two players who were on the winning team earlier have rating > 2200. Expectation for new players in team "h" is 0.5, because they have same ratings as all players in team "a" (who are all new).
Ratings after event 2 would be the ratings before event 3 (which include players from both event 1 and event 2):
> ratings[[3]]
   playerid   rating
1       438 2199.353
2      1947 2185.000
3      2632 2215.000
4      2119 2215.259
5      3622 2185.000
6      3311 2185.000
7      4003 2185.000
8       726 2215.000
9      5444 2215.000
10     1696 2215.259
11      371 2215.259
12      274 2215.259
13     3784 2185.000
14     4471 2215.259
15     4177 2185.000
16     5745 2185.000
17      633 2215.000
18     2737 2185.000

At the end of it all, there are 33 rated players in ratings[[16]], which should match the total number of unique player numbers in your table.
EDIT: I missed out that the desired output is vector of player rating history (thanks @Tensibai for pointing that out). To do that, I create a helper function to pull out any players history by his id.
getPlayerHistory <- function(id) {
  # pull all ratings of the player
  temp <- lapply(ratings, function(x) x$rating[x$playerid==id])
  # coerce into vector with same length as the list, forcing parts with no values into NA
  vec <- do.call(c, lapply(temp, function(x) {length(x) <- 1; return(x)}))
  return(vec)
}

You can call up directly e.g.
getPlayerHistory("5034")
 [1]       NA       NA       NA 2185.395 2171.403 2171.403 2171.403 2171.403 2171.403
[10] 2171.403 2171.403 2171.403 2171.403 2186.862 2186.862 2202.293

Note that there are 16 values in this vector, because they are ratings before an event. So the first NA is because there was no starting rating, the next two NAs are because player "5034" played for the first time in event 3, so the first rating available is before event 4. When the player didn't play in an event, his rating stays the same.
You can use the helper function to pull the entire rating history into a list.
idList <- tail(ratings, 1)[[1]]$playerid   # get the latest ratings list
ratList <- lapply(idList, getPlayerHistory)
names(ratList) <- idList

Then you can get the same by calling the list.
> ratList[["5034"]]
 [1]       NA       NA       NA 2185.395 2171.403 2171.403 2171.403 2171.403 2171.403
[10] 2171.403 2171.403 2171.403 2171.403 2186.862 2186.862 2202.293


text:
Q: Call image from post on index page? I am facing one problem in which i dont understand what I used to call the  image from post in WordPress themes on front page where n numbers of image are show with there description and user can dynamically image change. whatever he wants.
What I write the code in .php file

A: Use like this:
 <?php
 while ( have_posts() ): the_post();
    // Display post
    if ( have_posts() ):
            the_post_thumbnail();     //call image that you set in featured image in each post on right sidebar of admin panel.
            the_content();            //call content
    endif;
 endwhile;
 ?>


text:
Q: access real time database within onAuthStateChanged I'm trying to access firebase database after creating a user using Auth without any success.
After creating the user with Auth I'd like to save it on realtime database and add more fields.
signUpBrother(email: string, password: string) {
  this.fireAuth.auth.createUserWithEmailAndPassword(email, password)

  this.fireAuth.auth.onAuthStateChanged(function(user) {
    this.firebase.list('brothers').set(uid, {
      'email': user.email,
      'nickname': 'nickname',
      'avatar': 'avatar',
      'is_big_brother': true
    })
  })
}

the error I'm getting is:

ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'firebase' of undefined

Thanks for your help!

A: As codtex commented this has a different meaning in the callback than outside of it. And the new this doesn't have a firebase property.
To make sure you can access your function, you can capture this under a different name:
signUpBrother(email: string, password: string) {
  this.fireAuth.auth.createUserWithEmailAndPassword(email, password)

  var that = this;
  this.fireAuth.auth.onAuthStateChanged(function(user) {
    that.firebase.list('brothers').set(uid, {
      'email': user.email,
      'nickname': 'nickname',
      'avatar': 'avatar',
      'is_big_brother': true
    })
  })
}


text:
Q: Add column with column name as input string Quick dplyr question here. I'm trying to create a function that takes in any column name and adds the column to the dataframe. For example:
Name               Age
Misty              4
Crookshanks        12
Simba              18

Now i want to add the column 'type' via the function at the bottom:
addColumn(myDF, 'Type', 'Cat')

Name               Age       Type
Misty              4         Cat
Crookshanks        12        Cat
Simba              18        Cat

How do I use that function to accept the column string input? Right now it is just writing the column as 'column' instead of 'Type'
addColumn <- function(df, column, value) {

  df <- df %>%
    mutate( column  = value )

  View(df)
}

A: You have to use some non-standard evaluation.
library(dplyr)
library(rlang)

addColumn <- function(df, column, value) {
   df %>% mutate(!!column := value )
}

addColumn(myDF, 'Type', 'Cat')

#        Name  Age Type
#1       Misty   4  Cat
#2 Crookshanks  12  Cat
#3       Simba  18  Cat

A: Just in order to offer an alternative, you could rewrite your function using good old base R as:
addColumn <- function(df, column, value) {
  df[column]<-value
  return(df)
}

Which will give you the same result:
> print(addColumn(myDF,"Type", "Cat"))
         Name Age Type
1       Misty   4  Cat
2 Crookshanks  12  Cat
3       Simba  18  Cat

Without needing to call additional libraries (not even dplyr)


text:
Q: App Only Crashes for Iphone 6 and IPad in IOS 11 using Vision & Machine Learning API I made a live translation app that identifies an object and translates it using the user's camera. It works just fine on my iPhone 6s and doesn't crash in any of the simulators, but when I run it on an iPhone 6, it crashes as soon I try to segue to the camera feed.  Apple also says it crashes on the iPad as well.
Do certain devices just not support Vision API or is something wrong with my code?
import UIKit
import AVKit
import Vision

var lang = ""
var lang2 = ""

class ViewController: UIViewController, AVCaptureVideoDataOutputSampleBufferDelegate, AVCapturePhotoCaptureDelegate {

      @IBAction func screenshotB(_ sender: Any) {
       //screenshot camera screen view

    }
    @IBOutlet weak var screenshotBOutlet: UIButton!
    @IBOutlet weak var swirlyGuy: UIActivityIndicatorView!
    @IBOutlet weak var title1: UILabel!
    @IBOutlet weak var settingsButtonOutlet: UIButton!
    @IBOutlet weak var launchScreen: UIViewX!
    @IBOutlet weak var launchScreenLogo: UIImageView!

    func stopSwirlyGuy(){
        swirlyGuy.stopAnimating()
    }
    let identifierLabel: UILabel = {
        let label = UILabel()
        label.backgroundColor = UIColor(red: 0, green: 0, blue:0, alpha: 0.4)
        label.textColor = .white
        label.textAlignment = .center
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()

    @IBAction func prepareForUnwind (segue:UIStoryboardSegue) {

    }

    override func viewDidLoad() {
        super.viewDidLoad()
        launchScreen.alpha = 1
        launchScreenLogo.alpha = 1
        swirlyGuy.startAnimating()

        // start up the camera

        let captureSession = AVCaptureSession()
        captureSession.sessionPreset = .hd4K3840x2160

        guard let captureDevice = AVCaptureDevice.default(for: .video) else { return }
        guard let input = try? AVCaptureDeviceInput(device: captureDevice) else { return }
        captureSession.addInput(input)

        captureSession.startRunning()

        let previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
        view.layer.addSublayer(previewLayer)
        previewLayer.frame = view.frame

        let dataOutput = AVCaptureVideoDataOutput()
        dataOutput.setSampleBufferDelegate(self, queue: DispatchQueue(label: "videoQueue"))
        captureSession.addOutput(dataOutput)

        setupIdentifierConfidenceLabel()
        setupSettingsButton()
        setupTitle()
        setupSwirlyGuy()
        setupScreenshot()
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

        UIView.animate(withDuration: 1.5) {
            self.launchScreen.alpha = 0
            self.launchScreenLogo.alpha = 0
        }

    }
    fileprivate func setupSettingsButton() {

        view.addSubview(settingsButtonOutlet)
    }

    fileprivate func setupScreenshot() {

        view.addSubview(screenshotBOutlet)
    }

    fileprivate func setupSwirlyGuy() {

        view.addSubview(swirlyGuy)
    }

    fileprivate func setupTitle() {

        view.addSubview(title1)
    }

    fileprivate func setupIdentifierConfidenceLabel() {
        view.addSubview(identifierLabel)
        identifierLabel.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
        identifierLabel.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
        identifierLabel.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
        identifierLabel.heightAnchor.constraint(equalToConstant: 100).isActive = true
        identifierLabel.numberOfLines = 0
    }

    func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
        //        print("Camera was able to capture a frame:", Date())

        guard let pixelBuffer: CVPixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else { return }

      // model
        guard let model = try? VNCoreMLModel(for: Resnet50().model) else { return }
        let request = VNCoreMLRequest(model: model) { (finishedReq, err) in

            //perhaps check the err

            //            print(finishedReq.results)

            guard let results = finishedReq.results as? [VNClassificationObservation] else { return }

            guard let firstObservation = results.first else { return }

            print(firstObservation.identifier, firstObservation.confidence)

            let x = (firstObservation.confidence)

            let y = (x * 10000).rounded() / 10000

            let z = (firstObservation.identifier)

            let s = (self.translateSpanish(object1: firstObservation.identifier))

            let f = (self.translateFrench(object1: firstObservation.identifier))
       //      var lang = ""
       //      var lang2 = ""

             if language == "English" {
             lang = z
             }
             else if language == "Spanish" {
             lang = s
             }
             else {
             lang = f

             }

             if language2 == "Spanish" {
             lang2 = s
             }
             else if language2 == "English" {
             lang2 = z
             }
             else {
             lang2 = f
             }

             DispatchQueue.main.async {

             self.identifierLabel.text = "\(lang)" + " = " + "\(lang2) \n \(y * 100)% accuracy"
             self.stopSwirlyGuy()
             }

        }

        try? VNImageRequestHandler(cvPixelBuffer: pixelBuffer, options: [:]).perform([request])
    }

//Translation fucntions omitted for brevity

This is the code for the view controller that segues into the main screen where the camera feed and Vision processing take place.
import UIKit
class FirstLaunchViewController: UIViewController {
@IBOutlet weak var title1: UILabelX!
@IBOutlet weak var logo1: UIImageView!
@IBOutlet weak var description1: UILabel!
@IBOutlet weak var buttonOutlet: UIButtonX!
@IBOutlet weak var initialBackground: UIViewX!
@IBOutlet weak var initialLogo: UIImageView!

@IBAction func toVC(_ sender: Any) {
        UserDefaults.standard.set(false, forKey: "name")
        performSegue(withIdentifier: "toMain", sender: self)
}

override func viewDidLoad() {
    super.viewDidLoad()
    initialLogo.alpha = 1
    initialBackground.alpha = 1
    title1.alpha = 0
    logo1.alpha = 0
    description1.alpha = 0
    buttonOutlet.alpha = 0

    // Do any additional setup after loading the view.
}

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    UIView.animate(withDuration: 1.5, animations: {
        self.initialLogo.alpha = 0
        self.initialBackground.alpha = 0
    }) { (true) in
        self.initialBackgroundGone()
    }
}
       func initialBackgroundGone() {
    UIView.animate(withDuration: 1.5, animations: {
        self.title1.alpha = 1
    }) { (true) in
        self.showBackgroundAgain()
    }

}

func showBackgroundAgain() {
    UIView.animate(withDuration: 1.3, animations: {
        self.logo1.alpha = 1
    }) { (true) in
        self.showTitle()
    }
}

func showTitle() {
    UIView.animate(withDuration: 1.5, animations: {
        self.description1.alpha = 1
    }) { (true) in
        self.showEverythingElse()
    }
}

func showEverythingElse() {
    UIView.animate(withDuration: 3.5) {
        self.buttonOutlet.alpha = 1
    }
}

}

A: This is a lot of code but I think your issue comes from the video preset your are using as iPhone 6 doesn't have support for 4K video recording.
When setting the session preset you should test that it is supported by all the targeted devices:
if captureSession.canSetSessionPreset(.hd4K3840x2160) {
    captureSession.sessionPreset = .hd4K3840x2160
} else {
    captureSession.sessionPreset = .high // or any other preset that suits your needs
}


text:
Q: How to format a URL.Action() call in JQuery to set a link's href attribute? I need to set the href attribute of a link to point to a specific image, which has its id from the database set as its title. However, I am having trouble with trying to format the string to include a call to get the title attribute of the image.
Here is the base string:
$("#favoriteLink").hover(function() {
    $(this).attr("href", '<%: Url.Action("FavoriteWallpaper", "Wallpaper", new{wallpaperId='+$(this).children.attr("title")+'}) %>');
});

favoriteLink is a div and the child is just one image.

A: Oh no, you can't mix server side code and javascript as you are trying to. How about this:
$('#favoriteLink').hover(function() {
    var title = $(this).children.attr('title');
    $(this).attr('href', function() {
        var url = '<%= Url.Action("FavoriteWallpaper", "Wallpaper", new { wallpaperId= "_TITLE_TO_REPLACE_"}) %>';
        return this.href.replace('_TITLE_TO_REPLACE_', title);
    });
});

A: You're URL.Action is rendered serverside and your javascript client-side. You wont have access to dom elements when you're trying to build the link.
You should get the actual URL thats rendered in URL.Action and build the string client-side


text:
Q: angularjs : watch of array has been triggered when the array in initial load and not being changed

  $scope.$watch('selectedCategories', function(newValue, oldValue){
    console.log(newValue);
    console.log(oldValue);
    $scope.loadPosts();
  }, true);

  $scope.$watch('selectedCities', function(newValue, oldValue) {
    console.log(newValue);
    console.log(oldValue);
    $scope.loadPosts();
  }, true);

These two watches have been triggered when the page is initially loaded. Isn't it supposed not to trigger when the page is loading and the array not being changed?

A: From the Angular Docs (just before the first example)

After a watcher is registered with the scope, the listener fn is
  called asynchronously (via $evalAsync) to initialize the watcher. In
  rare cases, this is undesirable because the listener is called when
  the result of watchExpression didn't change. To detect this scenario
  within the listener fn, you can compare the newVal and oldVal. If
  these two values are identical (===) then the listener was called due
  to initialization.

You could check if newValue !== oldValue to prevent it or create a variable that prevents the first check.

A: That's correct watcher's behavior. Adding if (angular.equals(newValue, oldValue)) { return; } inside callback will solve your issue.


text:
Q: Where should autloader go in MVC? I'm trying to build a simple MVC framework to better understand certain concepts. The first thing that I thought would be important to address is a front controller that handles all of the requests for my applications.
Once I started to think about it, I wasn't sure of the best way to load the classes that my application would be using. My current thought process is that my autoloader should be located in the front controller since every request utilizes it. Where do most frameworks typically put this? Looking through a few already built frameworks hasn't helped me much as a lot of the functionality far exceeds what I need, complicating it so much that it's hard to understand.
The class loader that I am trying to use can be found here https://gist.github.com/221634
Just trying to figure out how to appropriately build and organize a simple MVC framework.

A: You should put it in your bootstrap file.
This is how you can do this:

*

*Force every HTTP request to your front controller, index.php, app.php or how ever you want to call it.

*Front Controller can define some constants used in framework and then include your Bootstrap.php file. Bootstrap will boot up your application.

*Now, first thing in I do in Bootstrap is to register autoloading. This way I can easily get \System\Router\Router class, or \System\Router\Dispatcher class, you get the point.

One more thing, you can even register your application Models folder with PSR0 class loader.
So lets say that your Models folder looks like this:
application/Models/
    - Entities
    - Services
        Email.php
        Cache.php

From inside your controller you can easily get Models like this
public function someController()
{
    $email = new \Models\Services\Email();
    // Do stuff with email service
}

So short answer to your question is that the best thing to have is first Front Controller that gives you some "wiggle" room, then from there you load your Bootstrap that boots up your app, and first thing in Bootstrap is to require your class loader, and register libraries you want to use through application.
And then you can even register autoloading for your application Controllers and Models folder, and at the end of Bootstrap file when you are about to dispatch request you can ask for Controller like this:
$app = new '\\Application\\Controllers\\' . $class;
// Dispatch request with call_user_func_array or ReflectionMethod and ReflectionClass

No need to require Controller class since its autoloaded, just provide it with correct namespace.
Great question, hope this helps! Nice to see there are other guys playing around with their custome MVC :)

A: Definitely in the bootstrap stage!
The autoloader should be part of every PHP application and it should be (one of) the first classes/code initialized.
My MVC initialization steps:

*

*index is the entry point

*bootstrap for initializing error handling, autoloader and IoC

*application, mostly a MVC app

*routing mechanism

*controller

*model

*view

A: Well, the question "Where does it go?" to me suggests two more precise questions:

*

*Where is the file stored that contains the autoloader function/class definition?

*Where in your request dispatch cycle should it be instantiated, configured, and allowed to do its magic?

The first question - "Where to place the file containing the class?" - is probably not so critical for you since you have identified an autoloader class you want to use. The precise answer depends upon your own framework app structure, but for an externally developed class like the one you cite, someplace within a lib or vendor directory probably makes sense.
For the second question - "Where to instantiate, configure, etc?" - the answer is: as early as possible in the request cycle, so you can get the benefit of autoloading for all classes that are referenced later. In practical terms, that probably means somewhere in your bootstrap process.
Of course, this usually means that in order to load your autoloader class, you will probably have to do a manual require/include call, instantiate your autoloader object, and configure it with with namespaces and paths.


text:
Q: Passing dict to try except function to check if value exist Please I need help, I have to check if some values exist in dictionary so I have multiple try except statements.
So, what I'm thinking is to write a function that takes the dict and checks if that value exist or not (if it didn't exist will return None) but the problem is when I call that function with dict as parameter it gives error since that field doesn;t exits. So here is what I did so far but is giving error in main function:
def main():
  return_value = test(dict["one"]["two"])

And here is the test function:

def test(value):
  try:
    one = value
  except:
    one = None
  finally:
    return one

A: If you want to test if a value exists as a key in a dictionary , simply do this:
value in dict

Example:
d = { 4 : "exists"}

assert 4 in d
assert 5 not in d

If you want a default value, you can use get:
v = d.get(5, "mydefault")
assert v == "mydefault"

A: You can use the method get() from dict.
It will return None if your dict does not have the key.
return_value = dict.get("one")
# return_value is equal to None if "one" is not in the dict


text:
Q: awk, mawk, nawk, gawk... WHAT? I've just started learning awk and I'm a little confused about all those versions around. Is there any "version" which is found on all Unix-like systems? Like, you know, plain vi? Does the standard awk support the -F option?

A: You can just use awk. It is defined by POSIX and therefore has to exist on all POSIX-conformant systems.
The -F parameter is mandated by that as well.

A: awk - the most common and will be found on most Unix-like systems, oldest version and inferior to newer ones.
mawk - fast AWK implementation which it's code base is based on a byte-code interpreter.
nawk - while the AWK language was being developed the authors released a new version (hence the n - new awk) to avoid confusion. Think of it like the Python 3.0 of AWK.
gawk - abbreviated from GNU awk. The only version in which the developers attempted to add i18n support. Allowed users to write their own C shared libraries to extend it with their own "plug-ins". This version is the standard implementation for Linux, original AWK was written for Unix v7.
There are other versions like jawk (java implementation), bwk (Brian W. Kernighan's implementation) and so on.

A: awk will be on just about every *NIX based system, but the exact specifics of what it supports will shift slightly as it's entirely possible it will simply be symlinked to a different version akin to how /bin/sh is often linked to a specific shell, often bash or one of its derivatives. (For the record, I also know alot of machines where vi is symlinked to vim as well.)

A: The Wikipedia AWK page is a good starter reference for beginning to understand AWK.
The Field Separator option '-F' is supported in all variants of AWK -- afaik.


text:
Q: Why need e.preventDefault I'm using below code to send an email. it's not working if i remove the e.preventDefault();. Why do i need to disable the default submit behavior of the form? how can i achieve it without e.preventDefault();?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title></title>

   <form name="appointment" id="appointment" method="post" action="About.aspx">

Contact Form

      <form name="appointment" id="Form1" method="post" action="send_contact.php">
Full Name:

  <input name="fname" type="text" class="form-input" id="fname" size="30" />

Email Address:

  <input name="email" type="text" class="form-input" id="email" size="30" />

Telephone:

  <input name="phone" type="text" class="form-input" id="phone" size="30" />

Your Comment:

<textarea name="comment" cols="28" rows="4" class="form-input-box" id="comment"></textarea>

 <input name="submit" type="submit" class="form-input-submit" value="Submit" id="btnMail"/>

    </form>

A: This code relies on disabling the default submit behavior of the form because the form-data is being sent with ajax (instead of a GET or POST request, which would also make the browser navigate to About.aspx).
You can achieve it without e.preventDefault(); by returning false.
Or by not using ajax, in which case you'd get the POST data on the server-side using: Page.Request.QueryString["htmlElementName"]

A: The event.preventDefault() method stops the default action of an element from happening.
instead of that you can use return false.

For example, clicked anchors will not take the browser to a new URL. We can use event.isDefaultPrevented() to determine if this method has been called by an event handler that was triggered by this event.

A: If you don't use e.preventDefault(), the default behaviour of form submit will fire. It will send browser to the action property of form and browser will disappeared that you don't want it.

A: You are using ajax, which means you don't need the form to submit at all. If you'd still like the page to redirect to about.aspx after sending the email, change your success function to be:
function successFunc(data, status) {
    $('#divLoading').hide();
    window.location = "about.aspx";
}

If you allow the form's default post behaviour, the form will post before your ajax request is complete, and will interfere with your email being sent.
As a side note, you have 2 forms with the name appointment, which may be causing you some confusion. Your code is referencing the first one, not the second.


text:
Q: Why is Pinety asking Geralt about how he fishes? In Sezon burz (the Witcher's Season of Storms), the sorcerer Pinety has this conversation with Geralt.

"Have you ever angled, Witcher? Does hunting attract you?"
"I hunt when I have an urge for a fish. I always carry a line with me."
Pinety was silent for a long time.
  "A line," he finally uttered in a strange tone. "A line, with a lead weight. With many little hooks. On which you skewer worms?"
"Yes. Why?"
"Nothing. It was a needless question."

What is the meaning of his words?
What I took from this was how Pinety thought strange that the Witcher (who had previously avoided gruesome details of what a loose demon was doing to people, and who avoids torture and malice) didn't mind torturing and hurting lesser animals, like fish and worms. How Geralt unconsciously distinguished between creatures that should not suffer, and creatures who could be tortured and hurt at will, even if for feeding purposes.
Please pay attention to spoilers, and use spoiler tags as necessary. I have not finished the book.

A: Pinety tried to bond with Geralt. It didn't work.
It has nothing to do with cruelty: in Geralt times most people hunt and kill  for sustenance and are not overly concerned with the suffering of their prey. The difference is in the method:

A fisherman is like a duffer in golf. They go out there and just give it a try. They use bait and whatever they can find that might work. They are trying to catch fish to eat in most cases and are not just there for the sporting part of it although that can be a factor."
An angler uses specific equipment and practiced techniques that are designed to bring in large trophy-sized fish. Often, they don't even keep the fish they catch. They practice catch-and-release often and rarely throw one in the cooler unless it is injured or they find it a particularly tasty type of fish. They are there particularly for the sport of it." source

For Pintey catching fish is a sport - something requiring skills, patience and concentration, something he does for pleasure. For Geralt it is a means to catch something to eat and he doesn't care how he gets it and how "fair" it is to the fish.
Pinety was trying to share his passion with the witcher, just to find that Geralt is (at least in this case) crude and primitive. It is like if an artist tried to share his feeling about painting with a guy who occasionally whitewashes walls.


text:
Q: Invalid Session (Try restarting your game) error in Minecraft I've been trying to connect to multiplayer servers, which I could connect to just fine just a few hours ago, but now I'm getting the error message "Failed to login: Invalid session (Try restarting your game.)" I've restarted my game multiple times, and even restarted my PC, but still the same error. I need help.

A: You may have signed in from another computer or location. Try logging out, then back in. If this doesn't help, please refer to Failed to Login : Invalid session (Try restarting your game) Minecraft Error


text:
Q: How to convert jQuery live() to jQuery on() function I just used jquery .live() function in jQuery v.1.7 for an asp.net webform app popup. The target is to load another .aspx page on click event using jquery popup dialog. Since new JQuery library doesn't support .live() anymore. I am unable to change it to .on() in the following code base.
Html Part in aspx page:

         <asp:Repeater ID="LetterGrid" runat="server">
           <HeaderTemplate>

                      Receive Date
                      Sender Name
                      Received By
                      Delivery Date
                      Receive Status

           </HeaderTemplate>
           <ItemTemplate>

                   <%# string.Format(" {0:dd/MM/yyyy}",Eval("ReceiveDate"))%>
                  <%# Eval("SenderName")%>
                  <%# Eval("ReceivedByName")%>
                  <%# Eval("DeliveryDate")%>

                      <label class="<%# Eval("ReceiveStatusClass")%>" aria-label="Left Align">
                          <%# Eval("ReceiveStatusName")%>

           </ItemTemplate>
           <FooterTemplate>

           </FooterTemplate>
       </asp:Repeater>

Javascript section:
$('a#popup1').live('click', function (e) {

    var page = $(this).attr("href");
    var $dialog = $('

')
    .html('')
    .dialog({
        autoOpen: false,
        modal: true,
        height: 350,
        width: 320, /* 'auto' */
        title: "Add To Do Items",
        buttons: {
            "Close": function () {
                $dialog.dialog('close');
                parent.location.href = parent.location.href;
            }
        },
        close: function (event, ui) {
            parent.location.href = parent.location.href;
        }
    });
    $dialog.dialog('open');
    e.preventDefault();
});

I tried the following but no popup is displayed
$('.box-body').on('click', '#popup', function (e) {

    var page = $(this).attr("href");
    var $dialog = $('

')
    .html('')
    .dialog({
        autoOpen: false,
        modal: true,
        height: 480,
        width: 320, /* 'auto' */
        title: "Add Appointment Details",
        buttons: {
            "Close": function () {
                $dialog.dialog('close');
                parent.location.href = parent.location.href;
            }
        },
        close: function (event, ui) {
            parent.location.href = parent.location.href;
        }
    });
    $dialog.dialog('open');
    e.preventDefault();
});

But the modal is not working. It is redirecting to that page.. no popup dialogue displayed.

A: I agree with @freedomn-m, #popup1 is id selector but the  doesn't have id popup1.
In this code the  have class popup1, so it's better to use class selector .popup1.
$('.box-body').on('click', '.popup1', function (e) {});