Typescript - Self-Executing Anonymous Functions

Question: How I can create self-executing anonymous functions using type script?
For example
(function() {
 var someClass = {
 }
}.call(this));

I want a built a plugin that may work for Node.js, also for fron-tend as well.
Comment: no because all answers cannot produce about output
Comment: I actually don't understand what you mean by that.
Answer: /**
 * Self executing anonymous function using TS.
 */
(()=> {
    // Whatever is here will be executed as soon as the script is loaded.
    console.log('executed')
})();

I want a built a plugin that may work for Node.js, also for fron-tend as well.

In that case you should compile your TypeScript in AMD and use an AMD loader on the frontend, like http://requirejs.org/docs/start.html
On the server side, you would need to use requirejs node package as well to load the file. Take a look at this: http://requirejs.org/docs/node.html
Basically there are two ways to compile TS to JS, using AMD, which is browser compliant, or using CommonJS, which is node.js compliant. Loading an AMD script in the browser or in the server needs to use an AMD compliant loader, and *requirejs** is one of them. (the most famous/used I'd say)
Answer: First rule in TypeScript: Any valid JavaScript is valid TypeScript.
No, there are are no special way to write Self-Executing Anonymous Functions in TS as of right now.
But, below is some code that might be of some use in your situation.
Every Class in TS is compiled to a (Named) Self-Executing Anonymous Functions, which returns a function.
Example:
//ts
class someClass {
  someProperty = "this is a property";
}

Translates to
//js
var someClass = (function () {
    function someClass() {
        this.someProperty = "this is a property";
    }
    return someClass;
})();

Hope this is of some help.
Comment: I wish the **Any valid JavaScript is valid TypeScript** rule was true. TypeScript is great but I get soo frustrated with type exceptions for perfectly valid JavaScript... I am currently researching how to create jQuery plugs in TypeScript... Nightmare!
Answer: An self-executing, immediate, recursive top-level React function in Typescript:
(function handleAutomatonTypeChange(newtype: AutomatonType) {
  ReactDOM.render(
    <Automaton automatonType={newtype}
               onAutomatonTypeChange={handleAutomatonTypeChange} />,
    document.getElementById('automaton')
  );
})('diadic');

Answer: (function(){
    document.body.innerHTML = "Self Calling Function";
}.call(this));

Comment: Please edit your answer to include some explanation. Code-only answers do very little to educate future SO readers. Your answer is in the moderation queue for being low-quality.


Why isn't my composer installation working?

Question: I followed the instructions on docs.drush.org for installing Drush, proceeded by the recommended steps for installing Composer and a new Drupal 8 project. My project (cfbtv) is located at ~/sites/cfbtv and it appears the composer template (whatever that is) installed Drupal in the web directory.
When I try the recommended Composer commands they fail. composer update devel outputs the following.

Package "devel" listed for update is not installed. Ignoring.
  Loading composer repositories with package information   Updating
  dependencies (including require-dev)   Nothing to install or update
  Generating autoload files

When I run composer require devel, I get this message.

[InvalidArgumentException]
  Could not find package devel at any version for your minimum-stability (stable).
  Check the package spelling or your minimum-stability.
require [--dev] [--prefer-source] [--prefer-dist] [--no-progress] [--no-suggest] [--no-update] [--no-scripts] [--update-no-dev] [--update-with-dependencies] [--ignore-platform-reqs] [--prefer-stable] [--prefer-lowest] [--sort-packages] [-o|--optimize-autoloader] [-a|--classmap-authoritative] [--apcu-autoloader] [--] [<packages>]...

So what is the problem here?
Composer seems to have installed properly, but I'm surprised these commands aren't working. Maybe it works and I'm not using it correctly.
Answer: As shown in the example reported in the documentation page you linked, you need to add drupal/ to the machine name of the module you want to install. The given example is exactly for the Devel module.
composer require drupal/devel:~1.0

The name of the packages handled from Packagist has the format vendor/package, so if you simply use the machine name of the module, Composer will not be able to find the package you meant.
Remember to run the commands from the directory containing the composer.json and the composer.lock files, not from the core directory.


PHP shell_exec doesn't work in Windows Azure

Question: We need to execute an .exe file in a remote Windows Azure Server.
We call it from PHP with shell_exec. The .exe should create new files in two different folders into the server and generate data entries in a data base and returns a string, but it doesn't work.
We don't have any problem executing it in our local server with windows 7 Enterprise and IIS 7. That's why we thought it could be a permissions problem, and then we have created a .user.ini file with the following content:
safe_mode= off
safe_mode_exec_dir= off
Unfortunately it doesn't work too.
Any suggestions?
Thanks in advance.
Answer: You are most probably working with Windows Azure Web Sites. This is a high-density shared hosting with tightened security. If you need things like shell_exec you shall move to Windows Azure Cloud Service (Web Role), where you have full control over the OS and web server / php settings.
Using Cloud Service you will be able to use shell_exec. However when you move to Cloud Service you have begin thinking of saving files in Azure Blob Storage, as the local storage for cloud service is:

Not persistent
not synchronized across role instances

If you want don't yet know what Role and Role Instance is, or are little confused, please go through this article.
Comment: Thank you very much Anton. We appreciate your help but we have changed to Amazon EC2.

All seems to be easier. Easier to learn, easier to manage, better documentation.

As always happens with Microsoft, the environment, and the interface are beautifull, but only that.

Unfortunatly we don't have much time. Perhaps later we'll test again the Azure.


The Poisson Distribution

Question: Customers arrive at a casino as a Poisson process of rate 100 customers per hour. Upon
arriving, each customer must flip a coin, and only those customers who flips heads actually enter the casino.
So how can I find

the PMF of N? Let's say for the
number of customers who arrive
between 5PM to 7PM.
the pdf of T? The    time between
successive customers    arriving.
Answer: The key observation is that the new process, denote it by $N = \lbrace N(t) : t \geq 0 \rbrace$, has rate $\lambda$ which is half the original, that is $\lambda=50$.
Then the answers to your questions follow immediately. Denote the original process by $N_0$, and set $\lambda_0 = 100$.
Then, the distribution of $N(1)$ (that is, the number of customers who actually enter the casino in one hour) is obtained (using the law of total probability) as follows.
$$
{\rm P}(N(1) = k) = \sum\limits_{j = k}^\infty  {{\rm P}(N(1) = k|N_0 (1) = j) {\rm P}(N_0 (1) = j)}.
$$
Given $N_0 (1) = j$, $N(1)$ is binomial$(j,1/2)$. Hence,
$$
{\rm P}(N (1) = k) = \sum\limits_{j = k}^\infty  {\frac{{e^{ - \lambda _0 } \lambda _0^j }}{{j!}}{j \choose k}\frac{1}{{2^j }}} = \cdots = \frac{{e^{ - \lambda _0 /2} (\lambda _0 /2)^k }}{{k!}}.
$$
EDIT: For a proof that the new process $N$ indeed has stationary independent increments, see, for example, p. 211 here (where $\lambda$ and $p$ correspond to $100$ and $1/2$, respectively).
Comment: Of course, for your first question, you need to consider $N(2)$ (but the answer can be adapted immediately to any $t>0$).
Comment: https://math.stackexchange.com/questions/2002756/poisson-process-pizza-orders-2-types-over-period-of-time?rq=1
Answer: Note that the pdf of $T$ is an exponential distribution.

The Poisson Distribution


There is something about Javascript inheritance that I can't understand

Question: I was reading Introduction to Object-Oriented JavaScript from Mozilla Developer Network, time to learn so serious Javascript before start using node.js.
Anyway, inheritance thing seems so obscure to me. Copy and paste from the documentation:
// define the Person Class
function Person() {}

Person.prototype.walk = function(){
  alert ('I am walking!');
};
Person.prototype.sayHello = function(){
  alert ('hello');
};

This is easy, but things get complicated with Student inheritance. Does anyone else think that the following three statements do essentially the same thing?
// define the Student class
function Student() {
  // Call the parent constructor
  Person.call(this);
}

// inherit Person
Student.prototype = new Person();

// correct the constructor pointer because it points to Person
Student.prototype.constructor = Student;

I understand the first one (calling the parent constructor) because is so similar to Java, PHP and so on. But then problems begin.
Why there is the need of calling Student.prototype and Student.prototype.constructor?
A clear explanation is needed. Why this code:
// define the Student class
function Student() {
  // Call the parent constructor
  Person.call(this);
}

var student1 = new Student();

is not enough for inheritance to work?
EDIT: regarding the constructor thing, it has been already answered here.
Comment: possible duplicate of [Why is it necessary to set the prototype constructor?](http://stackoverflow.com/questions/8453887/why-is-it-necessary-to-set-the-prototype-constructor)
Comment: @Chiguireitor i didn't write the documentation title, you know...
Comment: "Object-Oriented JavaScript" doesn't exists, Javascript is Prototype Oriented and you must adapt your Object-Oriented approaches to Prototypes.
Comment: @pimvdb you're partially right. My question overlaps that posted by you for the constructor thing. But it's not exactly the same: i'd like to know why the second statement is needed.
Answer: This doesn't work:
function Student() {
  Person.call(this);
}

var student1 = new Student();

because Person's prototype properties are not available on Student instances. Person.call(this) merely calls Person with a specific this value (namely the Student instance). But the Person function is completely empty - so here it doesn't do anything. There is no relation between Student and Person other than the useless Person call.
To get Person's functions the .prototype assignment is necessary.
Before:

  its prototype: Student.prototype, with all student functions
    its prototype: Object.prototype

After:

  its prototype: , with all student functions if you add them
    its prototype: Person.prototype, with all person functions
      its prototype: Object.prototype

Answer: If you're using Node.js, I would suggest looking into ECMAScript 5 methods for object creation. MDN has a page here which might be a good guide. See also John Resig's overview of the new method. Prototypal inheritance is hard to get your head around when coming from a classical OO language like Java. Good luck!


TensorFlow takes too long to load data into a tf.Dataset

Question: I am using TensorFlow 1.9 to train an image dataset, which is too big to load from my hard drive into RAM. Therefore, I have split the dataset into two halves on my hard drive. I want to know what is the most efficient way to train on the entire dataset.
My GPU has 3 GB of memory, and my RAM has 32 GB of memory. The size of each half dataset is 20 GB. My hard drive has plenty of free space (over 1 TB).
My attempt is as follows. I create an initializable tf.Dataset, and then on every epoch, I initialize it twice: once for each of the halves of the dataset. In this way, each epoch sees the entire dataset, but only has to have half of it loaded in RAM at any one time.
However, this is very slow, because it takes a long time to load the data from my hard drive, and also quite a long time to initialize the dataset with this data each time.
Is there a more efficient way to do this?
I have tried training on each half of the dataset for multiple epochs before loading the other half of the dataset, which is much faster, but this gives much worse performance on the validation data. Presumably, this is because the model is overfitting on each half and then not generalising to the data in the other half.
In my code below, I create and save some test data, which is then loaded as described above. The time to load each half dataset is about 5 seconds, and the time to initialize the dataset with this data is about 1 second. This may only seem like small amounts, but it all adds up over multiple epochs. In fact, my computer spends almost as much time loading the data as it does actually training on the data.
import tensorflow as tf
import numpy as np
import time

# Create and save 2 datasets of test NumPy data
dataset_num_elements = 100000
element_dim = 10000
batch_size = 50
test_data = np.zeros([2, int(dataset_num_elements * 0.5), element_dim], dtype=np.float32)
np.savez('test_data_1.npz', x=test_data[0])
np.savez('test_data_2.npz', x=test_data[1])

# Create the TensorFlow dataset
data_placeholder = tf.placeholder(tf.float32, [int(dataset_num_elements * 0.5), element_dim])
dataset = tf.data.Dataset.from_tensor_slices(data_placeholder)
dataset = dataset.shuffle(buffer_size=dataset_num_elements)
dataset = dataset.repeat()
dataset = dataset.batch(batch_size=batch_size)
dataset = dataset.prefetch(1)
iterator = dataset.make_initializable_iterator()
next_element = iterator.get_next()
init_op = iterator.initializer

num_batches = int(dataset_num_elements / batch_size)

with tf.Session() as sess:
    while True:
        for dataset_section in range(2):
            # Load the data from the hard drive
            t1 = time.time()
            print('Loading')
            loaded_data = np.load('test_data_' + str(dataset_section + 1) + '.npz')
            x = loaded_data['x']
            print('Loaded')
            t2 = time.time()
            loading_time = t2 - t1
            print('Loading time = ' + str(loading_time))
            # Initialize the dataset with this loaded data
            t1 = time.time()
            sess.run(init_op, feed_dict={data_placeholder: x})
            t2 = time.time()
            initialization_time = t2 - t1
            print('Initialization time = ' + str(initialization_time))
            # Read the data in batches
            for i in range(num_batches):
                x = sess.run(next_element)

Comment: Please provide more information about total data size, total RAM size and total *free* Hard Disk space. I assume you are not using any GPUs?
Comment: [`TFRecord`](https://www.tensorflow.org/guide/datasets#consuming_tfrecord_data) format may be a better choice
Comment: @geekonedge I have added these details, and I am using the GPU for training.
Answer: Feed is not an efficient way to input data. You can input data like this:

create a filename dataset containing all the input file names. you can shuffle, repeat the dataset here.
map this dataset to data, map function is to read, decode, transform image. Use multi-thread for the map convert.
prefetch the data to train.

This is just an example way. You could design your own pipeline, remember the following:

use lightweight feed as possible
use multi-thread to read and preprocess
prefetch data for training


CSS Filter Regex JS

Question: I'm trying to detect if the CSS attribute filter of an element already contains some rules.
But my regex never finds any match : /saturate\(.[^\)]\)/
Here's a demo for you guys :

var filter = $('div').css('filter');

$('p').eq(0).text(filter.search(/saturate\(.[^\)]\)/)); //Should return something else than -1
$('p').eq(1).text(filter.search(/contrast\(.[^\)]\)/)); //Should return -1
div{
  filter: brightness(1.9) saturate(80%);
}

Comment: Use `\([^)]+\)` instead of `\(.[^\)]\)`
Answer: You're missing a + in your regex

var filter = $('div').css('filter');
//                                               V here!
$('p').eq(0).text(filter.search(/saturate\(.[^\)]+\)/)); //Should return something else than -1
$('p').eq(1).text(filter.search(/contrast\(.[^\)]+\)/)); //Should return -1
div{
  filter: brightness(1.9) saturate(80%);
}

Answer: You should use \([^)]+\) instead of \(.[^\)]\) in your regexps:

var filter = $('div').css('filter');

$('p').eq(0).text(filter.search(/saturate\([^)]+\)/)); // 16
$('p').eq(1).text(filter.search(/contrast\([^)]+\)/)); // -1
div{
  filter: brightness(1.9) saturate(80%);
}

The \(.[^\)]\) matches (, then any char other than a line break char (with .), and then a single char other than ) (your negated character class [^\)]), and then a literal ).
The \([^)]+\) will match

\( - a literal (
[^)]+ - 1 or more chars other than )
\) - a literal ).
Comment: Oh, you don't have to escape the `)` inside the `[]` ?
Comment: @Zenoo: No, no need escaping `(` and `)`. Only `^`, ``\``, `]` and `-` require escaping (though in some cases, `^`, and `-` may be used as literals inside character classes, too).
Comment: Thanks, I didn't know that !

CSS Filter Regex JS


"Symbol not found: _getentropy" error after updating command line tools on yosemite

Question: I recently created a python application which trawls through Bing and saves the pages as PDF's using WKHTMLTOPDF, it was built using Py2APP.
Everything was working perfectly and as I wanted it to do until I updated Command Line Tools (OS X 10.10) for Xcode.
Now whenever I try to run the app it instantly crashed and i get the following error:
<code>Time Awake Since Boot: 70 seconds

Crashed Thread:        0  Dispatch queue: com.apple.main-thread

Exception Type:        EXC_BREAKPOINT (SIGTRAP)
Exception Codes:       0x0000000000000002, 0x0000000000000000

Dyld Error Message:
  Symbol not found: _getentropy
  Referenced from: /Users/USER/*/EnglishSearch.app/Contents/Frameworks/Python.framework/Versions/3.5/Python (which was built for Mac OS X 10.12)
  Expected in: /usr/lib/libSystem.B.dylib

Thread 0 Crashed:: Dispatch queue: com.apple.main-thread
0   dyld                            0x00007fff63035075 dyld_fatal_error + 1
1   dyld                            0x00007fff630382a8 dyld::fastBindLazySymbol(ImageLoader**, unsigned long) + 180
2   libdyld.dylib                   0x00007fff8c2983ba dyld_stub_binder + 282
3   ???                             0x00000001040af190 0 + 4362793360
4   org.python.python               0x000000010400d0b8 _Py_InitializeEx_Private + 375
5   org.pythonmac.unspecified.EnglishSearch 0x00000001000024ac 0x100000000 + 9388
6   org.pythonmac.unspecified.EnglishSearch 0x000000010000117a main + 650
7   org.pythonmac.unspecified.EnglishSearch 0x0000000100000be4 start + 52

Thread 1:: Dispatch queue: com.apple.libdispatch-manager
0   libsystem_kernel.dylib          0x00007fff8db0c232 kevent64 + 10
1   libdispatch.dylib               0x00007fff8dc5b26e _dispatch_mgr_thread + 52

Thread 2:
0   libsystem_kernel.dylib          0x00007fff8db0b94a __workq_kernreturn + 10
1   libsystem_pthread.dylib         0x00007fff8941a3dd start_wqthread + 13

Thread 3:
0   libsystem_kernel.dylib          0x00007fff8db0b94a __workq_kernreturn + 10
1   libsystem_pthread.dylib         0x00007fff8941a3dd start_wqthread + 13

Thread 4:
0   libsystem_kernel.dylib          0x00007fff8db0b94a __workq_kernreturn + 10
1   libsystem_pthread.dylib         0x00007fff8941a3dd start_wqthread + 13

Thread 0 crashed with X86 Thread State (64-bit):
  rax: 0x00007fff6306d288  rbx: 0x0000000100200390  rcx: 0x0000000000000000  rdx: 0x0000000000000000
  rdi: 0x00007fff6306d3f0  rsi: 0x0000000000000000  rbp: 0x00007fff5fbfd290  rsp: 0x00007fff5fbfd278
   r8: 0x00007fff63057b4c   r9: 0x0000000000000000  r10: 0x00007fff6305afb6  r11: 0x00007fff6306d3f0
  r12: 0x0000000000000018  r13: 0x0000000000000000  r14: 0x00007fff6306d3f0  r15: 0x0000000104130188
  rip: 0x00007fff63035075  rfl: 0x0000000000000246  cr2: 0x000000010009c000

Logical CPU:     0
Error Code:      0x00000000
Trap Number:     3
</code>
I've searched around online and it seems to be a problem with CommandLineTools. I think this to be the case because I tried running the exact same app on my other laptop which hasn't been updated in a while and it worked.
My version of Xcode is 2339 and the Path is /Library/Developer/CommandLineTools
Does anyone out there know how to fix this error?
Thanks :)
Answer: Mac has an inbuilt version of python that it needs. The command line tools may well update and alter this version of python. If you want to develop applications it's best to use a python that's independent of the operating system. Try installing python from an external source, such as using anaconda. This will install another python on your system that is only used by you, so you can update it and add libraries to it without worrying about command line tools altering it.


Writing a Mozart-style cadenza

Question: What distinctive stylistic elements from Mozart's works should I include in a horn solo cadenza (in Horn Concerto III, Movement I) to make it fit well with the rest of the piece? (Oppositely, is there anything [certain rhythms, interval sequences, etc.] that I should avoid?)
(I am aware that cadenzas are often supposed to be ad-lib; in this case, however, I am going to take the time to write one out.)
Comment: Why don't you listen to his works and study his scores to seek your answer? They are all in the public domain and are easily accessible.
Comment: @jjmusicnotes Perhaps I am not quite sure exactly what it is that defines his style and thought someone here would know off the top of their head?
Comment: which was my point exactly. If you don't know, do the work / research yourself and come to your own conclusions rather than just asking someone to give you the answer.  There is no worth in being fed.
Comment: @jjmusicnotes Just saw your comment today and I'd like to explain that I'm entirely self-taught in the field of composition. (I play French horn in my high school's band [hence the Solo&Ensemble contest I was playing the horn concerto for]) There's a lot of music theory terminology I dont know,& because I lack formal training,I'm equipped solely with my ears & knowledge of chord construction(not chord sequences).Did tons (read:hours) of Googling but couldnt find anything explaining which chord patterns, etc are Mozart-y. I'm not lazy,just without cash for textbooks that'd spell that stuff out.
Answer: The quickest solution would be to find as many different recordings of this piece that you can find, to listen to the cadenzas that different performers play, and to construct a written cadenza that feels similar in style. That is always what I have done as a solo singer.
Try to find recordings that say that they were made "on period instruments" or "in historically-informed performance". Those have been made by musical groups that take care to play in the style that Mozart himself employed, and to play replicas of the same design of instruments that Mozart's own orchestras used.
Consider that your modern horn is very different than the horn used in Mozart's day; specifically, the horn in Mozart's time was much more restricted in the notes it could play; it could not play all 12 notes in the octave. I do not understand the mechanics of horns, but the idea is that you might decide that your cadenza should not use any of the pitches that were not available on the horns from Mozart's time. But this is your artistic decision to make.
So do some Google searching and find out about the kind of horn or horns used in Mozart's era in Austria, and how they were constructed, and specifically what pitches and what range they could play in. Then consider applying these parameters to your cadenza.
Comment: @WheatWilliams - just to clarify, the horn of Mozart's day was called the *natural horn* and was actually capable of performing chromatic scales, though it required an incredibly skilled player to do so.  The reason for this is the necessary hand placement and embouchure control that would allow for notes to be "bent" in order to achieve scales that would otherwise lie outside of a given overtone series.
Comment: Thank you, @jjmusicnotes. I know a good deal about historically-informed performance in the Baroque and classical periods, but I am a singer, and I know nothing about how to play brass instruments!
Answer: Cadenzas often have a slightly different musical style than the works they are based on -- for example, Joachim's standard cadenzas for the Mozart violin concerti -- but are not usually way off.  For example, I wouldn't expect a cadenza in a Mozart horn concerto to include a bunch of pedal notes or lip glissandi or other techniques that were not commonly used in that day; and I would expect it to at least loosely follow Mozart's stylistic language.  It shouldn't sound like Webern, for example.
Cadenzas always incorporate themes from the movement that they are in.  It is common to have wider leaps, faster and higher notes, and generally show off more than in the rest of the concerto.  And finally, it is customary to end a cadenza on a trill.  When cadenzas used to be improvised, this was done in order to signal the conductor that you were done with the cadenza and the orchestra needed to come back in again.  However, typically (but not always) these days, cadenzas are not in fact improvised, but are slavishly prepared in advance of the performance.
Comment: In Mozart's time and before, solo classical musicians were expected to be able to improvise, not unlike jazz musicians in the modern era. Improvisation was something that was taught to young musicians in Mozart's time. Over subsequent generations, this fell out of fashion, for performers and for the expectations of the composers themselves. In the present day, it seems that many classical musicians are re-discovering improvisation (in a historically-appropriate, limited sense) through the early music movement, or what we call "historically-informed performance practice".

Writing a Mozart-style cadenza


Por que as imagens não ficam coladas?

Question: Bom estou fazendo um carousel, e quero colocar outra imagem do lado do carousel porém fica com um espaço queria saber como remover, na minha tentativa eu fiz duas divs flutuarem um para a direita e esquerda por meu carousel coloquei 70% e para minhas imagens coloquei 30 %, porém o espaço continua, como resolver ?
<!DOCTYPE html>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<title>Olá, mundo!</title>

Comment: Esse carrossel eh o padrão do bootstrap ou vc usou algum outro?
Comment: padrão do bootstrap
Answer: Se o problema de espaço for nas laterais remova o espaço assim:

Se for entre as imagens é só alterar a margin:

e

Se o problema for o espaço em branco do tamanho original da imagem:

seu codigo

<!DOCTYPE html>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<title>Olá, mundo!</title>

Answer: Provavelmente a largura das imagens são menores do que os 70% que você definiu. Com isso ela não ocupa toda a largura da div, deixando um espaço à direita.
Você pode resolver isso adicionando a classe w-100 nas imagens, que irá adicionar a propriedade width: 100%, fazendo com que elas ocupem toda a largura da div.

Porém as imagens precisam ter uma resolução onde a largura seja no
  mínimo do mesmo tamanho da largura da div, senão elas irão "estourar"
  quando o CSS aumentá-las.

<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">

Por que as imagens não ficam coladas?


Probabilities in a multiple choice test

Question: 70 students take a multiple choice test with 100 questions. Each question has 4 possible answers— a, b, c, d — and there is only one correct answer per question. Student 1 gets 22 wrong answers
and Student 2 gets 19 wrong answers.  What is the probability that Students 1 and 2 have 13 wrong answers that are the same (eg. both picked "c" when c is one of the three possible wrong answers to a question) out of the 100 questions?
Does the fact that Student 1 had 13 out of 22 wrong answers that were the same as Student 2's wrong answers prove that the two students were cheating off each other's tests?
Comment: This does not have an answer unless you assume that the students are using random guessing.
Comment: Pretty high if there's "hot tip" going around that in this class you should pick (c) when in doubt because on the last few exams there were lots of correct (c) answers. Not unlikely that two students would believe it.
Answer: If all wrong answers are equally probable, it is indeed very unlikely that out of 19 wrong, 13 would match another's work.  I calculate about 0.2%
$$p(i matches) = \left( \frac{1}{3} \right)^i \cdot \left( \frac{2}{3} \right) ^ {19-i} \cdot {{19}\choose{i}} $$
$$\sum_{i=13}^{19}{p(i)} \approx 0.0019$$
However!!!!!!!  In every multiple choice test I've ever taken, there have always been better and worse distractor answers.  And even just having one really obvious bad choice in each problem is enough to change the odds materially - I calculate better than 8% of at least 13 matches if there are only 2 good distractors.  8% might not sound high, but at 8% per student a class of 30 would have over 90% chance of at least one falling into that category!
Comment: Very helpful-thank you!  Using your assumption two distractors and an 8% chance per student, is it likely that 2 students would have 13 wrong answers the same?  Can you calculate the probability?  The class has 70 students.
Comment: Thanks @HMK!  Yes, as a matter of fact, I think I underestimated the 90%, treating every match as independent.  Are you familiar with the Birthday Problem?  The odds of two people sharing is less than 1/3 %, but all you need are 23 or 24 people for there to be a 50% chance of a match.  I think this would be a similar case, so 8% per match with 70 students (assuming at least half had 19+ wrong out of 100) would nearly guarantee at least one such match.

Probabilities in a multiple choice test


Rota e form no Laravel

Question: Tenho uma rota
Route::get('/','WebController@index');

Tenho um controller
public function index()
{
    $cars = Cars::table('cars')->get();
    return view('web::index')->with('cars', $cars);
}

E no form passa a seguinte URL
{!! Form::open(['class' => 'form-horizontal search-side-box', 'url' => '/', 'method' => 'post', 'autocomplete' => 'off']) !!}

Mas quando clico no botão submit do form, da o seguinte erro:
Class App\Front\Http\Controllers\WebController does not exist

Mas o controller está configurado, tanto que em outros lugaras eu chamo a URL '/' e ele funciona, só no form que não. E quando eu passo outra URL no form ele também funciona:
{!! Form::open(['class' => 'form-horizontal search-side-box', 'url' => '/about', 'method' => 'post', 'autocomplete' => 'off']) !!}

Comment: @EdinhoRodrigues, vc tem que criar uma rota post: Route::post('/','WebController@index');
Comment: O que seu form faz ou deve fazer?
Comment: Nesse caso passa os dados de pesquisa de um item especifico. Se não tiver nenhum campo preenchido ele deve buscar todos os itens, senão busca passando os parametros do form
Comment: Valeu, resolvi ainda melhor: Route::any('/',  'WebController@index');
Comment: @EdinhoRodrigues, antes de usar a Route::any() verifica a questão de segurança. Tenho que confirmar, mas se não engano favorece vulnerabilidades.
Answer: Bom primeiro seu método no Form e nas rotas está errado, em um é definido um post e no outro o get.
Normalmente get é usado para paginas simples, e o post em submissão de formularios e afins, nesse teu caso acho que está faltando um pouco de código aí:
Defina mais uma rota
Route::get('/', 'WebController@index'); // renderiza a pagina com o form
Route::post('/busca_detalhe', ['as'=>'car.busca_detalhe', 'uses'=> 'WebController@busca_detalhe']); // Retornará os resultados submetidos na busca do form

Adicione uma função no WebController
public function busca_detalhe(Request $request)
{
    $dados = $request->except('_token');
    $cars = DB::table('cars')->select('*')->where('parametro', '=', $dado['parametro'])->->get();
    return view('car.detalhes', compact('cars')); //Crie a view para mostrar os resultados
}

Pode também definir a abertura do Form com a route ao invés da url:
{!!  Form::open(['route' => 'car.busca_detalhe', 'method' => 'POST', 'class'=>'form-horizontal bordered-row']) !!}

Não tente fazer tudo na mesma função/Controller usando as mesmas rotas, isso vai te confundir na hora da manutenção, e nem preciso citar se outro desenvolvedor for analisar teu código um dia...
Comment: @DarleiFernandoZillmer, verdade! O Laravel é muito robusto quanto a segurança! O problema é o uso inadequado da cultura de implementar para funcionar e embutir vulnerabilidade com isso!
Comment: Laravel é bem consistente em questão de segurança, mas realmente, qualquer brecha que pode ser evitada é melhor evitar...não custa criar uma rota e uma view novas
Comment: Obrigado Darlei, eu fiz a rota passa any, assim posso fazer tanto get qt post, q acha, pode ser assim? EX: Route::any('/', 'WebController@index');
Comment: @EdinhoRodrigues, antes de usar a Route::any() verifica a questão de segurança. Tenho que confirmar, mas se não engano favorece vulnerabilidades.

Rota e form no Laravel


VBScript generating same random number when in loop - how to solve?

Question: So I have this function which generates a random string of digits 8 characters long. It works if its called once per page, ie if I refresh it will show a new number.
But I want to generate many of these inside a loop and its returning the same number. How can I solve this?
Function generateCode()

   pChar = "0123456789"

   pCount = Len(pChar)

   Dim psw
   psw = ""

   Randomize
   For i = 1 To 8 ' password length
      psw = psw & Mid( pChar, 1 + Int(Rnd * pCount), 1 )
   Next

 generateCode= psw
End Function

Now I thought Randomize may be based off the current time, so I took the Randomize line out and called Randomize before the loop that calls generateCode() i- still didn't work!
Answer: Randomize without any arguments seeds the pseudo-random number generator using the system time. If you call it multiple times very quickly the system time won't have changed so you will reinitialize the PRNG with the same seed each time, giving the same random numbers.
You should only call Randomize only once on your page, not multiple times.
Comment: I have been yelling at my PC looking for an answer to this for almost two days, thank you!  +1


Limiting distribution and initial distribution of a Markov chain

Question: For a Markov chain (can the following discussion be for either discrete time or continuous time, or just discrete time?),

if for an initial distribution i.e. the distribution of $X_0$, there
exists a limiting distribution for the distribution of $X_t$  as $t
    \to \infty$, I wonder if there exists a limiting distribution for
the distribution of $X_t$  as $t \to \infty$, regardless of the
distribution of $X_0$?
When talking about limiting distribution of a Markov chain, is it in
the sense that some distributions converge to a distribution? How is
the convergence defined?

Thanks!
Comment: can you word question number one a bit more clearly?
Answer:
No, let $X$ be a Markov process having each state being absorbing, i.e. if you start from $x$ then you always stay there. For any initial distribution $\delta_x$, there is a limiting distribution which is also $\delta_x$ - but this distribution is different for all initial conditions.
The convergence of distributions of Markov Chains is usually discussed in terms of
$$
 \lim_{t\to\infty}\|\nu P_t - \pi\| = 0
$$
where $\nu$ is the initial distribution and $\pi$ is the limiting one, here $\|\cdot\|$ is the   total variation norm. AFAIK there is at least a strong theory for the discrete-time case, see e.g. the book by S. Meyn and R. Tweedie "Markov Chains and Stochastic Stability" - the first edition you can easily find online. In fact, there are also extension of this theory by the same authors to the continuous time case - just check out their work to start with.
Comment: Thanks! I was wondering if the limiting distribution which is independent of initial distributions is unique when it exists?
Comment: @Tim: could you please define the uniqueness? Is far as my guess is true, you mean exactly its independence from the initial distribution.
Comment: By "uniqueness" of the limiting distribution, I mean if there are two different probability measures on the state space s.t. they can both be the limiting distribution for a Markov chain, and the limiting distribution is defined to be the same for all initial distributions.
Comment: @Tim Given any initial distribution it admits (if admits) a unique limiting distribution. Thus, if the latter is independent of the former, the latter is unique. In other words, suppose there are two limiting distributions $\pi_1$ and $\pi_2$, then $\|\nu_1 P^n - \pi_1\| \to 0$ and $\|\nu_2 P^n - \pi_2\| \to 0$ for some $\nu_1, \nu_2$ which contradicts with the fact that limit of $\nu_1 P^n$ is the same as of $\nu_2 P^n$
Comment: Thanks! (1) Do you mean that for any given initial distribution, its limiting distribution (not necessarily the same one for other initial distributions) is unique? Why is that? (2) also I feel the first comment on my another post is confusing http://math.stackexchange.com/questions/248609/relation-between-reversible-distribution-and-limiting-distribution. If you can let me know what you think, that will be appreciated!
Comment: @Tim: its time for you to define (formally) the limiting distribution.
Comment: For a Markov chain $(X_t)$with given transition distributions, a limiting distribution $\pi$ is defined to be a probability measure on the state space, s.t. for any initial distribution $\nu$ of $X_0$, the distribution of $X_t$ will converge to $\pi$ in total variation norm sense, as $t \to \infty$. Is it the one in your mind?


derivative of functions

Question: The question is to find the derivative of $ f(x) = (3x^2-3x-6)^\frac{2}{3} $
The answer says :
$ \frac{2}{3}(3x^2-3x-6)^\frac{-1}{3} \cdot (6x-3) $
$ = \frac{2(2x-1)}{(3x^2-3x-6)^\frac{1}{3}} $
How did he get from the first one to the second ?
My answer was :
$ \frac{2(6x-3)}{3(3x^2.3x-6)^\frac{1}{3}} $
Guys i know it's algebra thing so i will appreciate it if you explained what happened here.
And there is another one which was to find the second derivative of $arcsin(2x^3)$
The answers says for the second derivative :
$ \frac{12x \cdot \sqrt{1-4x^6} - 6x^2 \cdot \frac{1}{2}(1-4x^6)^\frac{-1}{2}(-24x^5)}{1-4x^6} $
$ = \frac{12x(1-4x^6)-3x^2(-24x^5)}{(1-4x^6)^\frac{3}{2}} $
So why here the square root disappeared from the first one ?
Comment: $a^{-1} = \dfrac{1}{a}$ and a $3$ factors and cancels from the numerator. Regards
Comment: Did the answer resolve your issues?
Answer: We can reduce your answer as:
$$ \dfrac{2(6x-3)}{3(3x^2-3x-6)^\frac{1}{3}} = \dfrac{2 \times 3 (2x-1)}{3(3x^2-3x-6)^\frac{1}{3}} = \dfrac{2(2x-1)}{(3x^2-3x-6)^\frac{1}{3}}$$
A $3$ factors from the numerator and then we can cancel it out.
For the second item, we have:
$ \dfrac{12x \cdot \sqrt{1-4x^6} - 6x^2 \cdot \dfrac{1}{2}(1-4x^6)^\frac{-1}{2}(-24x^5)}{1-4x^6} = \dfrac{12x(1-4x^6)-3x^2(-24x^5)}{(1-4x^6)^\frac{3}{2}} $
What if were to multiply (or, this can be seen as simplifying the numerator) the numerator and denominator by $\sqrt{1-4x^6}$?
Is that clear?
Comment: You're welcome!! +1

derivative of functions


Antipodal gluing of a disk is homeomorphic to a disk.

Question: Given $D=\{(x,y)\in \mathbb{R}^2 \mid x^2+y^2\leq 1\}$, if I define $\sim $ as $(x,y)\sim (x',y') \iff x'=-x, y'=-y$ is the gluing of points across the line $y=-x$. The same way that the antipodal gluing of a circle is homemorphic to a circle, the same is true for a disk. The problem is, I am not really sure what a continuous map from the disk to the glued disk would look like--let alone a homeomorphism. The plan I had was to identify points over the reflective line $y=-x$ but I am having trouble writing down a closed form. Any hints?
Answer: If you identify points $(x,y)$ and $(-x,-y)$ then you are not "glueing points across the line $y=-x$" but extending the antipodal map to the interior of $D$. In terms of (vectors or) complex numbers $z$ you are identifying $z$ and $-z$. Let $\hat z:=\{z,-z\}$ be the equivalence class represented by $z$, and denote the resulting space by $\hat D$. A homeomorphism $f:\>\hat D\to D$ is then given by
$$f\bigl(\hat z):=z^2\qquad\bigl(\hat z\in\hat D)\ .$$
Think about it!


Is 1100 a valid state for this machine?

Question: A room starts out empty. Every hour, either 2 people enter or 4 people leave. In exactly a year, can there be exactly 1100 people in the room?
I think there can be because 1100 is even, but how do I prove/disprove it?
Comment: I think you have to take into account how many hours are in a year. For instance, in four hours, it is impossible for there to be $6$ people in the room.
Answer: A general advice: Whenever you have to distill a simple answer from a confusing medley of cases, look out for the invariant!
The remainder mod 6 increases by $2$ per hour; therefore it is periodic with period 3 hours. As 24 is divisible by $3$, after exactly one year the remainder mod $6$ will be $0$, whether we have a leap year or not. It follows that an occupancy of $1100$ is impossible then.
Comment: @David Faux: We don't know whether $2$ are added or $4$ are subtracted in any given hour. Fortunately in both cases the remainder mod $6$ increases by $2$.
Comment: @David: Because 2 and -4 are congruent mod 6
Comment: Thanks, though how did you come up with 6 to mod by? It seems a bit out of the blue for me.
Comment: Though cliché, I might add to the general advice (and was trying to induce such thinking in my comment above): sole a simpler problem!
Answer: Exactly a year is $24*365=8760$ hours (or $8784$ for a leap year-maybe you need to try both).  If there are $x$ times that two people enter and $y$ times that four people leave, you want $x+y=8760,\ 2x-4y=1100$.  Two equations in two unknowns, and if the solution is integral you are there.
Answer: Here's a slightly different take on Christian's approach. There's almost nothing in it that isn't at least implicit in one or another of the other answers, but it may be of some use in showing one way in which one might approach the problem.
First, I notice that we can divide everything in the problem by $2$: each day either one person enters or two leave, and we want to know whether we can have $550$ people in the room after exactly one year. This makes no essential change in the problem, but sometimes it's easier to spot things when working with smaller numbers.
Then I ask myself after how many hours the room can be empty. Clearly if there were $n$ hours in which two people left, there must have been $2n$ hours in which one person entered, so $3n$ hours must have passed. In other words, the room can be empty only after a multiple of $3$ hours. This naturally makes me wonder what can happen after $3n+1$ or $3n+2$ hours. That in turn gets me to thinking mod $3$, and I realize that subtracting $2$ is the same as adding $1$ mod $3$. In other words, no matter what happens, every hour the population of the room increases by $1$ mod $3$. One regular year has $8760$ hours, so (mod $3$) at the end of a year the room must contain $8760\bmod 3=0$ people. Unfortunately, $550\bmod 3=1$, so we can't end up with $550$ people in the room at the end of a regular year. And since the extra day in a leap year adds another $24\bmod 3=0$ people, we can't end up with $550$ sardines people in the room at the end of a leap year, either.
Comment: Great walkthrough, but is it really fair to say that at the end of a year the room _must_ contain 8760 mod 3 = 0 people, when in fact there are 8760 different possibilities?
Comment: @Milosz: But mod $3$ there is only one possibility, and I was working entirely mod $3$.
Comment: I'm not very confident with modular notation, but wouldn't rephrasing it as "the room must contain $0\ (\text{mod } 3)$ people" be more correct/read more clearly?
Comment: @Milosz: Probably, though I chose a different solution.
Comment: Nicely done, Brian.
Answer: The answer is no. Since there are 24 hours in the day, the number of hours in a year is multiple of 3.
It taakes a non-multiple of three hours to fill the room with 1100 people, and then a multiple of three hours to balance the room.
Alternately: $(2x-4y)-(x+y)$ is a multiple of three. Thus 1100- no of hours must be multiple of three....
Answer: The process can be rephrased as making a required motion of $+2$ every time, with an optional additional motion of $-6$ at some steps.  The forward part of that motion will reach $+2N$ in $N$ steps, plus some backward motion divisible by $6$ to attain the final total motion of $T=+1100$.  Here $N$ and $T$ are given and the exact condition for a pair $(N,T)$ to be realizable is that $(2N - T)/6$ be a non-negative integer.  That integer is equal to the number of backward moves, whether thought of as $-4$'s or $-6$'s.
This answer was found in reverse, by solving the linear $2 \times 2$ system for the number of $+2$ and $-4$ moves (given $N$ and $T$), and interpreting the condition for the numbers to be non-negative integers.
As explained in the previous answers, for the problem as posted, $2N = 2 \times 24 \times \text{(days in year)}$ is divisible by $6$ and $1100$ is not, so the conditions are not satisfied.

Is 1100 a valid state for this machine?


Comparar o elemento com o resto da lista Python

Question: Preciso criar um programa onde na lista dada, se o nome estiver repetido ele coloca uma numeração. Por exemplo: nomes = [maria, joao, maria] o resultado deve ser resultado = [maria, joao, maria1]
Outro exemplo: nomes = [eduardo, joao, eduardo, eduardo] resultado = [eduardo, joao, eduardo1, eduardo2]
montei um codigo onde compara com o próximo nome, não sei como faz para continuar a comparação.
segue o meu codigo:
Comment: Seja bem vinda Tatiane, pode ser mais especifica? [Edite](https://pt.stackoverflow.com/posts/404021/edit) a pergunta e dê algum exemplo prático ou  coloque parte do seu código.
Answer: A solução desse problema é simples e pode ser facilmente acalcando com o uso de uma Tabela de Hash para contabilizar as repetições de cada nome enquanto itera pela lista de nomes.
Em python uma tabela de hash é compreendida como um dicionário.
O algoritmo é simples:

nomes é a lista de entradas para o algoritmo.
Aloca em contadores a referência para uma tabela de hash vazia para então manter um contador de repetições de nomes.
Aloca e resultado uma lista vazia que receberá um nome da lista nomes apensado ou não da sua contagem.
Itere a cada nome n contido na lista nomes:

Verifique se a chave n existe no dicionário contadores:

Caso a chave n exista em contadores, adicione n apensado do valor de contadores[n] ao resultado e incrementa em 1 o valor de contadores[n].
Caso a chave n não exista em contadores, adiciona n ao resultado e inicializa o contador[n] em 1.

imprima o resultado

nomes = ['eduardo', 'joao', 'eduardo', 'eduardo', 'maria', 'joao', 'maria']

contadores = {}       #Cria uma tabela de hash para manter um contador de repetições de nomes.
resultado = []        #Lista que receberá um nome da lista nomes apensado da sua contagem.

#Para cada nome n em nomes...
for n in nomes:
  #...se n for chave em contadores...
  if n in contadores:
    resultado.append(f'{n}{contadores[n]}')  #...adiciona n apensado a sua contagem ao resultado.
    contadores[n] += 1                       #...incrementa o contador para n.
  #...caso n não seja chave em contadores...
  else:
    resultado.append(n)                      #...adiciona n ao resultado.
    contadores[n] = 1                        #...inicializa o contador n e uma ocorrencia.

print(resultado)
#['eduardo', 'joao', 'eduardo1', 'eduardo2', 'maria', 'joao1', 'maria1']

Teste o exemplo no Ideone.com
Answer: Você pode usar um dicionário para salvar quantas vezes um nome já apareceu.
names = ['eduardo', 'joao', 'eduardo', 'eduardo', 'joao']

d = {}

for i in range(len(names)):
    if names[i] in d:
        d[names[i]] += 1
        names[i] += str(d[names[i]])
    else:
        d[names[i]] = 0

Answer: Com dictionary é possível guardar os nomes e o número de vezes que vai repetindo:
    def usernamesSystem(u):
        cont = 0
        aDict = {}
        result = []
        for i in range(len(u)):
            cont = checkKey(aDict, u[i]) # verifica o numero de ocorrencia do nome
            if cont == 0:
                aDict[u[i]] = 1 # primeira ocorrencia, guarda valor 1 no dictionary
                result.append(u[i]) # carrega o array de output com a palavra
            else:
                aDict.update({u[i]: cont + 1 }) # atualiza as ocorrencias do nome no dictionary
                result.append(u[i] + str(cont)) # carrega o array de output com o nome concatenado com o numero de vezes repetido
        return result # array de output com o resultado

    def checkKey(dict, key):
        if key in dict.keys():
            return dict[key] # retorna o numero de ocorrencias quando ja existe no dictionary
        else:
            return 0 # retorna 0 se não existir

Answer: coloco agora a resposta mais completa, com a classe que utilizei.
class Usernames:

    @staticmethod
    def usernamesSystem(u):
        cont = 0
        aDict = {}
        result = []
        for i in range(len(u)):
            cont = Usernames.checkKey(aDict, u[i])
            if cont == 0:
                aDict[u[i]] = 1
                result.append(u[i])
            else:
                aDict.update({u[i]: cont + 1 })
                result.append(u[i] + str(cont))
        return result

    @staticmethod
    def checkKey(dict, key):
        if key in dict.keys():
            return dict[key]
        else:
            return 0

nomes = ['eduardo', 'joao', 'eduardo', 'eduardo']
print(Usernames.usernamesSystem(nomes))

Comment: Muito obrigada! deu certo!!!!
Comment: Boa. Não te esqueças de dar feedback (votar).


Determinant of $\delta$ function

Question: Let
$$\delta_i^j=\left\{
\begin{aligned}
1 ~~~~~~i=j   \\
0 ~~~~~~i\ne j
\end{aligned}
\right.
$$
$1\le i,j\le n$.
How to prove
$$
\begin{vmatrix}
\delta_{j_1}^{i_1} ~...~ \delta_{j_n}^{i_1} \\
\\
\delta_{j_1}^{i_n} ~...~ \delta_{j_n}^{i_n}
\end{vmatrix}
=\left\{
\begin{aligned}
1          &~~~~~~~~~\forall~ 1\le k,l \le n , i_k\ne i_l \text{ and $j_1...j_n$ is even permutation of $i_1...i_n$ }    \\
-1         &~~~~~~~~~\forall~ 1\le k,l \le n , i_k\ne i_l \text{ and $j_1...j_n$ is odd permutation of $i_1...i_n$ }     \\
0          &~~~~~~~~~\text{others}     \\
\end{aligned}
\right.
$$
I try to use induction to prove it ,but seemly it is too complex.
Answer: Denote the given matrix by $D$. If there are $k \ne l$ such that $i_k = i_l$, then the $k$-th and $l$-th row of $D$ are equal, hence $\det(D) = 0$. So suppose all $i_k$ are distinct. If $i_k = j_k$ for all $k$, then $D$ is the identity matrix, so $\det(D) = 1$. For the general case, we first prove the following: if we switch $j_k$ and $j_l$ for some $l \ne k$, then the determinant changes sign. Indeed, switching $j_l$ and $j_k$ corresponds to switching the $j$-th and $k$-th column of $D$. Hence, the determinant switches sign.
The statement follows now from the following observation: denote by $\sigma$ the permutation of $i_1, \ldots, i_n$ resulting in $j_1, \ldots, j_n$, i.e. $\sigma(i_k) = j_k$. Writing $\sigma$ as a composition of transpositions, we obtain $D$ from the identity matrix by consecutevily switching the columns corresponding to the transposition. With each transposition, the determinant flips sign. In the end, the determinant equals the sign of $\sigma$, which is $1$ if $\sigma$ is an even permutation and $-1$ if $\sigma$ is odd.

Determinant of $\delta$ function


Flexslider field: number of thumbs, number photos and thumb slider

Question: I just installed the module Flexslider. I want to create an image gallery similar to this one: http://flexslider.woothemes.com/thumbnail-slider.html, with a main big photo slider and thumbs sliders (carousel).
I'm using Flexslider field (that means it will create a gallery with the images of the node) instead of Views. I'm not sure how to show all thumbs (all the images I uploaded to the node) in the strip.
I was playing around with the settings in the section "Edit optionset" of the Flexslider module, specially with Item width, Minumum items and Max items. When I change the values, sometimes it shows 2 thumbnails, sometimes 3, etc, depending of the quantity I put in the values.
The weird thing is, when displaying the node if it shows only 3 thumbnails, the main big slider just will have 3 photos, even if the node have a lot of more photos.
What I need is simple, create a gallery that shows all the images in the slider and per each image it should shows one thumb. How I do that? And what means the fields Item width, Minumum items and Max items
Thanks in advance.
Answer: I ended up doing it from scratch. I created a custom node.tpl.php, got all the pictures with
<code>$photos = field_get_items('node', $node, 'field_photos');
</code>
Then looping through all items and creating for each item the options
<code>$photos_slide = array(
    'style_name'    => 'large',
    'path'          => $photo['uri'],
    'width'         => '',
    'height'        => '',
    'alt'           => '',
    'title'         => $title,
);
</code>
and then print the image:
<code>print theme('image_style', $photos_slide);
</code>
You can follow this example http://flexslider.woothemes.com/thumbnail-slider.html in order to know how to set the HTML.


Specifying lag in `dlnm` when passing arguments to `crossbasis`

Question: I am using the dlnm package to build a finite distribute lag linear model. I intend on testing the model-fit based on various lag levels to assess which lag is suitable. Needless to mention I will apply some domain knowledge to make a good call. I am using these two available resources to carry out this rather complex exercise:
http://www.ncbi.nlm.nih.gov/pmc/articles/PMC3191524/
http://cran.r-project.org/web/packages/dlnm/vignettes/dlnmOverview.pdf
I first created a Matrix to include non-linear effects of both my predictors using this:
ImpressionsA.x<-onebasis(locanatmodelset$ImpressionsA.x, fun="poly", degree=2)
ImpressionsA.y<-onebasis(locanatmodelset$ImpressionsA.y, fun="poly", degree=2)
Since my non-linear relationship is tending to be quadratic, I am using 2nd degree polynomials. Now I need to factor in the lags for each variable by calling crossbasis. This is where I am confused. The function as per the package documentation is of the format:
cb <- crossbasis(chicagoNMMAPS$temp,lag=30,argvar=list("thr",thr.value=c(10,20)),
arglag=list(knots=c(1,4,12)))
my doubts are :
1) in lag=30 is 30 of the same units as my response variable or will it be in the units of my predictor variable? In my case, my lag is specified in days. I want to specify 5 days as lag before fitting the model. How should I pass the argument?
2) Since I have already created my basis matrix for predictor variables using onebasis, how should I pass the arguments argvar and arglag?
3) I also wanted to extract the lagged values of my predictor variables (ImpressionsA.x and ImpressionsA.y) in their original units. The matrix itself is not helpful. It transforms everything into negative values on some other scale all together.
Comment: @Wayne I've made edits based on my progress with the work so far.
Comment: You mention that you are doing a "finite distribute lag linear model".  Has an "infinite" DLNM ever been proposed?
Comment: Please look up Koyck Model or Geometric Lags.
Comment: @zkurtz, an example of an "infinite" dlm shows up here as equation 3: http://link.springer.com/article/10.1007/s10182-006-0221-5#
Comment: The $y=x1*x2$ formula is shorthand for $y=x1+x2+x1:x2$. That is, it introduces the interaction between the two variables. Not sure if you're confusing autocorrelation and correlation: autocorrelation is correlation of a variable with lagged versions of itself. ("Auto" = "Self")
Comment: thanks Wayne. Apologies for wrong usage of concepts & terms. I am reading http://www.ncbi.nlm.nih.gov/pmc/articles/PMC3191524/ and its very insightful on how dlnm should be used for lag models. I might self answer after reading it.
Comment: This question seems to be cross-posted:  http://stackoverflow.com/questions/24984893/specifying-lag-in-dlnm-when-passing-arguments-to-crossbasis
Comment: Yes, why is that a problem?
Answer: This answer will likely be an iterative process, because you may want to rephrase your question as things become more clear.
1) In your usage, the first argument to crossbasis is a vector.  According to ?crossbasis, as a vector it needs to represent "a complete series of ordered observations".  You said that your time units are days.  Thus, presumably, lag = 30 means that you'll be looking back 1 day, 2 days, ..., 30 days simultaneously.  With dlnm, you never fit individual lags.  You fit the whole range of lags.  If you are particularly interested in the 5th lag, maybe you want to use lag = 8 or so and then see if the estimated effect for the fifth lag stands out as being bigger than the effects for the other lags.  NOTE:  The whole idea of the word "distributed" in dlnm is that the lagged effect of a variable is literally distributed across several lags, or even fractions of lags.
2) The crossbasis function does not accept the output of onebasis as an argument; it's just not set up that way.  Instead, you pass in your arguments to onebasis through argvar=list(), arglag=list() in crossbasis, which calls onebasis internally.  In particular, if you do crossbasis(locanatmodelset$ImpressionsA.x, lag = 8,..., then crossbasis will actually go and call onebasis two times, once to make a basis for locanatmodelset$ImpressionsA.x and once to make a basis for the lags [0,1, ...,8].
3) Clarify what you mean here.  If you want to "extract the lagged value" of any vector element, say the kth element of a vector x, you just do x[k-L] to get the Lth lag.  No special R package is necessary.


Simultaneous CW Approximation

Question: Given a topological space $X$, we know that there is a CW complex $Z$ with a map $Z\rightarrow X$ inducing an isomorphism on homotopy groups.
If we are given two spaces $X_{1}$ and $X_{2}$ with isomorphic homotopy groups (but no continuous map inducing the isomorphism), it makes sense that there shouldn't be a simultaneous CW approximation of $X_{1}$ and $X_{2}$, that is, there shouldn't be a CW complex $Z$ with maps to both $X_{1}$ and $X_{2}$ inducing isomorphisms on homotopy groups.
So why does the naive approach to use the method in Hatcher (Proposition 4.13) not work? Assume without loss of generality everything is path connected and our spaces are pointed.
1) Let $Z_{0}$ be a point and we fix an inclusion of $Z_{0}$ into $X_{1}$ and $X_{2}$.
2) Now, let $\{\gamma_{\alpha}\}$ be generators of $\pi_{1}(X_{1})$. Let $\{\gamma_{\alpha}'\}$ be the corresponding generators in $\pi_{1}(X_{2})$ under the isomorphism $\pi_{1}(X_{1})\rightarrow \pi_{1}(X_{2})$ (that is not induced by a continuous map).
3) So now, attach a copy of $S^{1}$ to $Z_{0}$ for each generator $\gamma_{\alpha}$ and map $S^{1}$ to $X_{1}$ as a representative of the class of $\gamma_{\alpha}$ in $\pi_{1}(X_{1})$. For the \emph{same} copy of $S^{1}$, map it to the representative of the class of $\gamma_{\alpha}'$ in $\pi_{1}(X_{2})$.
4) Let this new space be $Z_{1}$. By construction, the map $Z_{1}\rightarrow X_{1}$ induces a surjection $\pi_{1}(Z_{1})\rightarrow \pi_{1}(X_{1})$ and similarly, $Z_{1}\rightarrow X_{2}$ induces a surjection $\pi_{1}(Z_{1})\rightarrow \pi_{1}(X_{2})$.
5) For each element $\alpha$ of the kernel of $\pi_{1}(Z_{1})\rightarrow \pi_{1}(X_{1})$
, attach a disk $D^{2}$, where the boundary map is a representative of $\alpha$. From the isomorphism $\pi_{1}(X_{1})\rightarrow\pi_{1}(X_{2})$, $\alpha$ is also in the kernel of $\pi_{1}(Z_{1})\rightarrow \pi_{1}(X_{2})$.
6) Let the new space obtained after attaching these disks be $Z_{1}'$.
7) Now, we want to attach copies of $S^{2}$ so that our maps will induce surjections on $\pi_{2}$. We do the same thing as we did for step three to get a space $Z_{2}$.
8) Continue this process indefinitely to build a $CW$ approximation $Z$ of $X_{1}$ and $X_{2}$ such that $Z\rightarrow X_{1}$ induces isomorphisms $\pi_{*}(Z)\rightarrow \pi_{*}(X_{1})$ and $\pi_{*}(Z)\rightarrow \pi_{*}(X_{2})$.
Answer: As you say there is often not even a zigzag of weak equivalences between two arbitrary spaces with the same homotopy groups.
See https://mathoverflow.net/questions/3540/are-there-two-non-homotopy-equivalent-spaces-with-equal-homotopy-groups for some examples.  These are examples that are CW complexes, and so if there were a zig-zag of weak equivalences there would actually be a homotopy equivalence (Whitehead's theorem).
I would guess the problem is that you don't have any way of extending the particular map constructed in steps 1-6 to a map between the spaces constructed in step 7.
Answer: Your construction looks fine to me, however you have not actually shown that there exists a weak homotopy equivalence between $X_1$ and $X_2$.
Let $\stackrel{\sim}{\rightarrow}$ denote the relation of weak equivalence. You have shown that $Z\stackrel{\sim}{\rightarrow}X_1$ and $Z\stackrel{\sim}{\rightarrow}X_2$ but, because $\stackrel{\sim}{\rightarrow}$ is not a symmetric relation, we can not deduce that $X_1\stackrel{\sim}{\rightarrow}X_2$ without further assumptions (normally CW assumptions).
I'm not sure on the history of the subject, but I imagine maps with these properties are only called equivalences because they really do induce equivalence relations in some categories.
Comment: They are equivalences in the Quillen model structure on topological spaces: http://ncatlab.org/nlab/show/model+structure+on+topological+spaces. By formally inverting the equivalences, you get a homotopy category, with a natural map from the original model category (Top in this case.) But not every map in the homotopy category comes from the original category, unless you restrict to objects that are both fibrant and cofibrant, which I believe here are spaces dominated by a CW complex.
Comment: So in model category theory, which is admittedly a rather ahistorical explanation, they are called equivalences because they should induce an equivalence relation in the corresponding homotopy category. But here, not every object is cofibrant and fibrant, so the inverse morphism may not correspond to anything in Top, while in the Hurewicz model structure (which uses homotopy equivalences instead of weak homotopy equivalences), it will, as every object is cofibrant and fibrant there.

Simultaneous CW Approximation


A symbol on page 302 of Goldblatt's "Topoi [. . .]".

Question: I'm reading Goldblatt's "Topoi: A Categorial Analysis of Logic."
There's a symbol I don't recognise on page 302 of the copy with International Standard Book Number 0-486-45026-0. It's in the definition of a natural number object and resembles a cross between $s$ and $\sigma$.
For lack of a better format to show you what it is, here is a picture:
.
I have tried using Detexify but to no avail.

What symbol is it?

Please help :)
Answer: That symbol looks like a cursive letter s (lower case).
Comment: From that Wikipedia article:   Cursive has been in decline throughout the 21st century due to its perceived lack of necessity. The largest teachers' union in Fairfax County, Virginia, has called cursive a "dying art"
Comment: Your answer would make sense in the context. The motivating example for an nno talks of the successor function on the natural numbers, denoted $s$. Thank you :)


Weyl group of $\mathfrak{sl}(2,\mathbb{C})$

Question: $\mathfrak{g}$ is a complex semisimple lie algebra which is a subalgebra of some $\mathfrak{gl}(n,\mathbb{C})$, we have chosen a compact real form $\mathfrak{l}$ of $\mathfrak{g}$ and let $K$ be the compact subgroup of $\operatorname{GL}(n,\mathbb{C})$ whose lie algebra is $\mathfrak{l}$, we have chosen a maximal commutative subalgebra $\mathfrak{t}$ of $\mathfrak{l}$ and we work with the associated cartan subalgebra $\mathfrak{h}=\mathfrak{t}+i\mathfrak{t}$, we have chosen an inner product on $\mathfrak{g}$ that is invariant under the adjoint action of $K$ and that takes real values on $\mathfrak{l}$. Consider the subgroups: $$Z(\mathfrak{t})=\{A\in K: \operatorname{Ad}_A(H)=H,\forall H\in \mathfrak{t}\}$$ $$N(\mathfrak{t})=\{\operatorname{Ad}_A(H)\in \mathfrak{t},\forall H\in\mathfrak{t}\}$$
Weyl group is defined as $W=N(\mathfrak{t})/Z(\mathfrak{t})$,
for $\mathfrak{sl}(2,\mathbb{C})$ we take $\mathfrak{t}=\left\{\left(\begin{smallmatrix}ia&0\\0&-ia\end{smallmatrix}\right):a\in\mathbb{R}\right\}$
I understand $Z(\mathfrak{t})=\left\{\left(\begin{smallmatrix}e^{ia}&0\\0&e^{-ia}\end{smallmatrix}\right):a\in\mathbb{R}\right\}$
 and $N(\mathfrak{t})=\left\{\left(\begin{smallmatrix}e^{ia}&0\\0&e^{-ia}\end{smallmatrix}\right):a\in\mathbb{R}\right\}$ or $N(\mathfrak{t})=\left\{\left(\begin{smallmatrix}0&e^{ia}\\-e^{-ia}&0\end{smallmatrix}\right):a\in\mathbb{R}\right\}$
but I dont understand why the quotient group $N(\mathfrak{t})/Z(\mathfrak{t})$ has $2$ elements? Could it not be only one element?
And I do not understand the action of the Weyl group on $\mathfrak{t}$, please help.
Answer: The centralizer $Z(\mathfrak{t})$ is a subgroup of the normalizer $N(\mathfrak{t})$.
Note that
$$Z(\mathfrak{t})=\left\{\begin{pmatrix} a&\\&a^{-1}\end{pmatrix}a\in\mathbb{R}^\times_{+}\right\}
$$
and
$$N(\mathfrak{t})=\left\{\begin{pmatrix} a&\\&a^{-1}\end{pmatrix},\begin{pmatrix}&-b\\b\end{pmatrix},a,b\in\mathbb{R}^\times_{+}\right\}.
$$
Thus obviously
$$N(\mathfrak{t})/Z(\mathfrak {t})=\left\{\begin{pmatrix} 1&\\&1\end{pmatrix}Z(\mathfrak{t}),\quad\begin{pmatrix} &-1\\1&\end{pmatrix}Z(\mathfrak{t})\right\}$$
contains only two elements.
Note that $Z(\mathfrak{t})$ acts on $A$ trivially. Thus one can choose the following two elements
$$
I=\begin{pmatrix} 1&\\&1\end{pmatrix},\quad\omega=\begin{pmatrix} &-1\\1&\end{pmatrix}
$$
in the cosets, repsectively.
The Adjoint action of $I$ on elements $\begin{pmatrix} ia_1\\&ia_2\end{pmatrix}$ gives
$$
\mathrm{Ad} (I)\begin{pmatrix} ia_1\\&ia_2\end{pmatrix}=\begin{pmatrix} ia_1\\&ia_2\end{pmatrix},
$$
and
$$
\mathrm{Ad} (\omega)\begin{pmatrix} ia_1\\&ia_2\end{pmatrix}=\omega\begin{pmatrix} ia_1\\&ia_2\end{pmatrix}\omega^{-1}=\begin{pmatrix} ia_2\\&ia_1\end{pmatrix}.
$$


How to customize the last row of a CellTable in GWT?

Question: Assume each row has the format:
Data   | <Delete Button>

Now I am trying to add an empty row at the end. And I would like to not showing the <Delete Button> at the last row. I added the empty data through data provider. Is there a way to achieve this?
Answer: There is a method you can override when you create a column:
Column<MyObject, Number> myColumn = new Column<MyObject, Number>(new NumberCell()) {

    @Override
    public String getCellStyleNames(Context context, MyObject myObject) {
        return context.getIndex() == displayItems.size() - 1 ? "hide" : null;
    }
};

context.getIndex() gives you a row number. You can define a CSS style in your CSS file like "hide" with a rule "opacity: 0" or "display: none", and return this style only for the last row.
My example is NumberCell, but it applies to all cells.


Alguém poderia explicar este código em batch para mim?

Question: Alguém poderia explicar este código para mim?
Eu sei noção do que se trata, mas não consigo aplica-lo.
for /f "tokens=2 delims== " %%A in ('wmic baseboard get serialnumber /value ^| find /i "SerialNumber="') do set serialnumber=%%A
if /i not "%serialnumber%" == "PF0TPMUN" goto :exit

Answer:
O for /f é um comando para uso em loopings, aonde vai permitir obter e manipular as informações que retornarem de sua execução, quer seja invocando um programa, um comando interno/externo do sistema, um outro for looping, um outro script, enfim, um ou mais comandos, e as suas respectivas saídas serão submetidos para os tratamentos que o autor do código desenvolveu, e que vai resumir em ações que resultem em algo proveitoso para ele de alguma forma.
For /f também pode ser usado para processar o conteúdo de arquivos (legível, imprimível, entenda "texto"), e o conforme o objetivo do usuário, o for /f vai abrir, ler, escrever, e desenvolver as ações com os dados do(s) do(s) arquivo(s) e/ou com as saídas dos comandos que forem passados dentro das ações do loop, quer numa prévia ação de filtragem no conteúdo da saída, ou nas manipulações que retornarem dessa execução, usando opções como o uso de aspas com usebackq, pulando uma ou mais linhas na saída, com skip, definir o qual/quais pegar com tokens, e quer na/no a1ª token, e/ou o2ª, e/ou o 3ª, e/ou todas (*) as ocorrências restantes, além de também definir ou/não, um delimitador apropriado (ou múltiplos, se for o caso) com delims, e também qual caractere vais usar para definir/limitar o final de linha, com eol.
Mas agora que tens uma breve noção do que envolve um comando for /f, você pode tentar ver nesse seu comando for /f, que vai executar owmic.exe já passando alguns argumentos para que obtenha/retorne o número serial da placa mãe do computador, além já ter definido que dessa saída, ele vai usar apenas o texto/strings que vem no segundo token, assumindo como delimitadores (múltiplos), o sinal de igual e o espaço.
Observe que nessa execução, as strings resultantes desse comando wmic + for, e, na verdade, eles estão fazendo uma pré-seleção/(filtragem) direto da saída da execução, e manipulando as strings conforme definido nos argumentos do wmic /value com as opções do for /f tokens=2 delims== ", para depois enviar/direcionar o que sobrar para uso dentro do loop pelos comandos seguintes, como o set, que vei definir uma variável armazenado as strings presentes no serial da placa, e o if que vai testar uma condição e comparar o que retornou com uma string "PF0TPMUN", se a condição se mostrar verdadeira na comparação de igualdade da string "conhecida", o bat segue as ações imediatamente posteriores a esse loop, mas se não forem iguais, vai para o label :exit e executa os comandos que está tens "enfileirado".
Sobre uso de multiplicidade no delimitador, isso é dispensável para obtenção do serial, entendendo que a execução wmic não vai precisar do argumento /value, que acabam obrigando o uso das opções do for, mas, em fazendo a remoção desse argumento, você também pode remover os do for /f "tokens=2 delims== ", e usar apenas o skip^=1 no seu for, que vai pular a primeira linha na saída, e com a ausência de um tokens/delims definidos, o "tokens=1 delims= " por padrão serão usados.
Observe o wmic sem /value, e o for /f apenas usando skip^=1:

E veja a saída com linha adicional por conta do unicode do output do wmic, e é visível na primeira execução, mas removida na segunda com substituição do find "SerialNumber=" pelo simples uso do **findstr .** // siga o ^< nul` no primeiro comando, e perca ele de vista na segunda execução:

Sobre a linha adicional por conta do unicode no  output do wmic

Obs.: 1 No caso de rodar em um computador netbook/laptop/desktop de marca/fabricado, é comum o número serial da placa mãe ser o mesmo do serial da bios.
Obs.: 2 Eu usaria wmic bios get serialnumber direto, depois passaria para uma conversão dessa num hash, e essa string em md5, ou shada vida, é o que eu usária para comparação, ai sim, a edição do código não deixaria "facilitado" para alteração manipulação de "validador, e isso usando o certUtil.exe que já vem com o Windows.

    O comando wmic baseboard get serialnumber /value
    Saida do comando: SerialNumber=PE03A187      -> = // Meu Computador
    Delimitadores 2 : "delims== " =igual+espaço  -> = // Delims==' '
    Saida com for /F: tokens 1    =tokens 2      -> = // Tokens=2
                      ignorado    =ocorrência    -> = // PE03A187
Obs.: 3  Não existe um segundo sinal de igual, o que vem após primeiro
também é o segundo token!

Para obter ajuda e onde encontar os comandos utilizados:

     if | Comando: Interno do cmd.exe
        | Caminho: C:\WINDOWS\System32\CMD.exe
        |   Ajuda: C:\Windows\System32\cmd.exe /k if /?

    set | Comando: Interno do cmd.exe
        | Caminho: C:\WINDOWS\System32\CMD.exe
        |   Ajuda: C:\Windows\System32\cmd.exe /k set /?

    for | Comando: Interno do cmd.exe
        | Caminho: C:\WINDOWS\System32\CMD.exe
        |   Ajuda: C:\Windows\System32\cmd.exe /k for /?

   find | Comando: Interno do cmd.exe
        | Caminho: C:\WINDOWS\System32\CMD.exe
        |   Ajuda: C:\Windows\System32\cmd.exe /k find /?

   goto | Comando: Interno do cmd.exe
  ref.: | Caminho: C:\WINDOWS\System32\CMD.exe
  :exit |   Ajuda: C:\Windows\System32\cmd.exe /k goto /?

   wmic | Comando: Externo do Windows
        | Caminho: C:\Windows\System32\wbem\WMIC.exe
        |   Ajuda: C:\Windows\System32\wbem\WMIC.exe /?

findstr | Comando: Externo do Windows
        | Caminho: C:\Windows\System32\findstr.exe
        |   Ajuda: C:\Windows\System32\cmd.exe /k findstr /?

        rem :: Os comandos listados aqui funcionam para linda de comando e
               também no iniciar / executar do Windows, case quera copiar
               as saídas para ler de outra forma(editor de text) adicione
               | clip e cole onde desejar:
                 Ex.:   for /? | clip

Uma sugestão de edição/alteração no código para o seu bat:

O ^< nul set^ é um escape para toda linha, onde a saída sera tratada como texto escapando qualquer caractere não alfanumérico que possa vir de uma placa estilo "ching ling", e com o findstr . para encontrar qualquer caractere, ajudando a lidar com a linha que juto do unicode que vem trazendo um adicional  no final da string. Já o skip^=1 é para pular/ignorar a primeira linha na saída do wmic, e um outra coisa, no seu comando set, procura usar aspas set AbreAspasVariavel=ValorFecheAspas == set "SerialNumber=PE03A187"
for /f skip^=1 %%i in ('^<con: wmic.exe baseboard get serialnumber^|findstr .
')do ^< nul set^ "SerialNumber=%%~i" & if not "%%~A" == "PF0TPMUN" goto=:exit


Should I take $|ex|=1$ value?

Question: Test the convergence of the series
$$
x+\frac{2^{2} x^{2}}{2 !}+\frac{3^{3} x^{3}}{3 !}+\frac{4^{4} x^{4}}{4 !}+\cdots $$
Assume $x>0$ and examine all possibilities.
My approach:
Using ratio test I am getting
$$
L=\lim _{n \rightarrow \infty}\left|\frac{a_{n+1}}{a_{n}}\right| = |e.x| >1 $$
 Can I conclude the series is divergent?
Comment: Welcome to Maths SX! How do you know $|\mathrm ex|>1$? This depends on $x$, and you easily deduce the radius of convergence.
Comment: your comment is not clear.And by replacing n->(n+1),and then taking the ratio u will get L=|e.x|
Comment: Yes, absolutely. You can't say $|\mathrm e x|>1$ if you don't know $x$.
Answer: For x = 1/e ; U can go for a ratio test and by then u will find the series will come as a divergent one
$c=\lim _{n \rightarrow \infty} \frac{b_{n}}{a_{n}}$
Let,
$b_{n}=\frac{1}{\sqrt{n}}=\frac{1}{n^{1 / 2}}$
So,
$\lim _{n \rightarrow \infty}$
$ \frac{b n}{a_{n}}=\frac{\frac{1}{\sqrt{n}}}{\frac{1}{\sqrt{2nπ}}}=\sqrt{2π} \neq 1$
${b_n}$  & ${a_n}$ have similar char.
 By p-series test* we can tell ${b_n}$ is divergent.
Hence $a_{n}$ is divergernt
*p series test:
For the series: $\sum_{n=1}^{\infty} \frac{1}{n^{p}}$
The $p$ -series converges if $p>1$
The $p$ -series diverges if $p \leq 1$
here p = 1/2
Answer: Careful : you have to check for $x>0$ what is the limit of $\left|\dfrac{a_{n+1}x^{n+1}}{a_nx^n}\right| = \left|\dfrac{a_{n+1}}{a_n}x\right|$. This is equal to $\left|\dfrac{(n+1)^{n+1}}{n^n(n+1)}x \right|$ with limit $|ex|$ Thus the limit is $<1$ if and only if $x < 1/e$. Then the radius of convergence is $1/e$. You have to check manually for $|x|= 1/e$ if it converges.
Comment: Here it is asked to determine is the series is convergence or not? If u take it as a converging series  then u must take x<1/e. But is not it clear that for x>0 ; |ex| > 0
Comment: If $ x>0$, then $|ex| = e x >0$. I don't get what you're talking about. The series depends on $x$ thus determining if it is convergent is exactly determining for which value of $x$ it converges.
Comment: No need to be agressive. Moreover, your question isn't that clear : read again what you asked, it is not at all a question about the last case. Then I already answered for that : it is convergent for all $x$ such that $|x| <1/e$, divergent for all $x$ such that $|x| >1/e$, and for $|x| = 1/e$, I said you have to check it manually. Then, what I did not say was : for $x=1/e$ it is divergent (check with Stirling formula). For $x= -1/e$, it converges because of the alternating sum.
Comment: i AM not aggresive.I am sorry if u mind anything.

Should I take $|ex|=1$ value?


Filter numeric column containing a digit

Question: Is there any way to filter rows of a table where a numeric column contains a digit using maths?
I mean, currently, I'm solving that using:
where cast(t.numeric_column as varchar(255)) like "%2%"

However, I would like to know if could be possible to filter apply numeric operations...
Any ideas?
Comment: The above would likely fail, with the error *"Invalid column name '%2'."*
Comment: Is your `numeric` column always an integer value?
Comment: Why do you require a conversion? Doesn't produce SELECT yourcolumn
FROM yourtable
WHERE yourcolumn LIKE '%2%' the intended result?
Comment: That would, in fact, implicitly convert the value on the left hand side of the `LIKE`, @JonasMetzler .
Comment: Sure, but why is that a problem? Performance too poor?
Comment: Both conversion and `LIKE` with a leading wild card make the query non-SARGable, and thus result in a scan of the table, @JonasMetzler .
Comment: Evidence that there is an implicit conversion: [Query Plan 1](https://i.stack.imgur.com/9nRs1.png) (with no explicit convert) vs [Query Plan 2](https://i.stack.imgur.com/YMqPp.png) (with explicit convert). Note that the 1st plan has a CONVERT_IMPLICIT instead.
Comment: Thanks @Larnu Just was curious if this performance issue is the reason why the author wanted to avoid that or if this had another background.
Answer: You could use division plus the modulus, if you knew the range of possible numbers.  For example, assuming all expected numbers were positive and less than 100,000, you could use:
SELECT *
FROM yourTable
WHERE numeric_column % 10 = 2 OR
      (numeric_column / 10) % 10 = 2 OR
      (numeric_column / 100) % 10 = 2 OR
      (numeric_column / 1000) % 10 = 2 OR
      (numeric_column / 10000) % 10 = 2;

Although the above is ugly and unwieldy, it might actually outperform your approach which requires a costly conversion to string.
Comment: Worth noting that this won't work is the `numeric` column contains non-integer values. For example `10.124` won't appear in the results, despite it containing the digit `2`.
Comment: Should your approach work in case: `like "%25%"`, or `like "%56%"`... So, is there any way to get using numeric operations if a numeric value contains another one?
Comment: @Larnu That being said, given that floats are not exact anway, who could say for certain that a 2 were really there.
Comment: One would *assume* that a column called `numeric_column` is a `numeric` rather than a `float`; so hopefully that issue won't arise, @TimBiegeleisen . But them people have columns called "Date` that are an `int` or `varchar`, so it's more *hope* than assumption.


Complicated string data extraction

Question: I want to extract data from given strings, I've managed to do so yet I've encountered some difficulties.
I'll give you two strings:
"ESS23300RGR","Boorum & Pease 23 Series Columnar Book, Record, 300 Page, Black/Red (23-300-R)","UnbeatableSale, Inc (Amazon Marketplace)","180.80","6.09","http://www.amazon.com/gp/offer-listing/B000DLBVU4/ref=olp_page_next?ie=UTF8&shipPromoFilter=0&startIndex=15&sort=sip&me=&condition=new","http://www.amazon.com/gp/offer-listing/B000DLBVU4/ref=olp_page_next?ie=UTF8&shipPromoFilter=0&startIndex=15&sort=sip&me=&condition=new"
"WLJ36210WGR","Basic Round Ring View Binder, 362 Line, 3 Ring, 1" Capacity, 8-1/2" x 5-1/2" Sheet Size, White","Gov Group (Amazon Marketplace)","3.61","7.70","http://www.amazon.com/gp/offer-listing/B0006OF55A/ref=olp_seeall_fm?ie=UTF8&shipPromoFilter=0&startIndex=0&sort=sip&me=&condition=new","http://www.amazon.com/gp/offer-listing/B0006OF55A/ref=olp_seeall_fm?ie=UTF8&shipPromoFilter=0&startIndex=0&sort=sip&me=&condition=new"

This is the expression I've used:regexChecker("[\w\s&\(\)-^,]{3,}", longString);
Using it I've managed to separated perfectly the first string yet the second one not, since it uses , and " as part of some sections.
How can I extract the data from the second string similar to the first one?
Data needed to be extracted is: SKU,Name,Competitor,Price,Shipping,URL,SourceURL
Thanks in advance.
Comment: just add backslash before comma in your regex
Comment: Extracted like this SKU,Name,Competitor,Price,Shipping,URL,SourceURL or like: "SKU","Name","Competitor", etc.
Answer: Try :
String[] tabS = myLine.substring(1, myLine.lenght() -1).split("\",\"");

to remove all significant "
Comment: Yes, the problem is the unescape `1" Capacity` quote.
Comment: @PaulVargas Here you remove the first and the last `"`, then you putthe words between `","` in a array. is it a good solution ?
Comment: Good. Hopefully this will work properly. The CSV is not properly escaped.
Comment: The problem is the _3_ unescaped quotes in `1" Capacity, 8-1/2" x 5-1/2"`.
Comment: @MRAB it seems this it not the problem for OP. You can remove them with somethiong like `String result = tabS[i].trim().replaceAll("\"", "");`
Answer: Check following code. It gave me desired results for both of your input strings.
StringBuilder testt = new StringBuilder("\"ESS23300RGR\",\"Boorum & Pease 23 Series Columnar Book, Record, 300 Page, Black/Red (23-300-R)\",\"UnbeatableSale, Inc (Amazon Marketplace)\",\"180.80\",\"6.09\",\"http://rads.stackoverflow.com/amzn/click/B000DLBVU4\",\"http://rads.stackoverflow.com/amzn/click/B000DLBVU4\"");

 Pattern varPattern = Pattern.compile(",\"", Pattern.CASE_INSENSITIVE);

 Matcher varMatcher = varPattern.matcher(testt);

 List<String> list = new ArrayList<String>();

 int startIndex = 0, endIndex = 0;
 boolean found = false;

 while (varMatcher.find()) {
  endIndex = varMatcher.start();
  if (startIndex == 0) {
   list.add(testt.substring(startIndex, endIndex));
  } else {
   list.add(testt.substring(startIndex + 1, endIndex));
  }
  startIndex = varMatcher.start();
  found = true;
 }
 if (found) {
  if (startIndex == 0) {
   list.add(testt.substring(startIndex));
  } else {
   list.add(testt.substring(startIndex + 1));
  }
 }
 for (String s : list) {
  System.out.println(s);
 }
}

Complicated string data extraction


New to the field of stats, trying to apply it to my day job (cost estimating)

Question: So to preface, I am very new to the world of Stats / quantitative analysis (I have recently gone back to uni and the paper I just completed is QA, specifically Regression, Estimation, Hyp. testing, Optimization.
I have really enjoyed the course but sadly never got a chance to apply it to my day job during the semester.
I work in the construction industry running the estimating department (i am a  tradesman by nature and have gained alot of experience at the coal face).
What I would ideally like is a regression model that can give me guidance on what the estimated margin should be according to historical records.  Do you think this is even achievable? Or is there anything you can see that would be possible from the info?
Another inclusion I considered was the actual end of job report when all costs and final sell price is known.
EM, Estimated Margin,   Dependent Variable, Best guess estimated margin
E,  Estimator,      Independent,    Non-metric, Name
PH, Project hours,  Independent,    Man hours total
MT, Materials total,    Independent,    Dollar value of materials
WT, Work Type,      Independent,    Non-metric,technical,maintenance,Construction
S,  Successful,     Independent,    Yes, No, Pending, Cancelled (I can filter to only look at yes/no
I have loads of info but not sure where to start really start, I have tried running one model but excel crashed over and over again. (too much data for excel I guess, I do have SPSS but not 100% sure how to use it)
Currently the way we take a guess at where the margin should be, My chief estimator has 40+ years experience and he is always on the money... However he has 40+ years of experience and is looking to make a move to retirement.........
Any feedback or help would be greatly appreciated.
Comment: Hi, welcome to Cross Validated. The title of your post won't help people with similar questions find your question; please use one that describes the problem. You should also reframe your question from being about what something "should be" (a normative question) to one that can be measured with data; for example, you can develop a model for historical margins (what margins actually *were* along, with variables that should be useful for calculating them), so if your chief estimator was always on the money and you have data for his estimations, they'd probably be good data to use in a model.
Answer: To answer your broadest question, yes, it can be done. However, your results might have extremely large (and unacceptable) uncertainties depending upon your data and specific questions. If I were in your shoes, here are the broad steps I would take:

Think about what questions you want to answer. You've started doing this, but try to be more specific. Start broad and then focus your question down (e.g., you are broadly interested in estimating margin the margin. What does this mean financially? What specifics do you have data for to help you understand this?). Ultimately, you'll end up with a quantitative relationship you can express algebraically, e.g, $ margin \sim predictors$.
Use your quantitative data to choose and formulate a model. Start simple and and make the model more complex as needed. Make sure the model you choose makes sense and is reasonable given both the data and your question. Ask yourself questions about the model (e.g., do you meet the assumptions? does the model make sense?).
Choose the tools you need to solve your problem. Personally, I like R, but it has a steep learning curve if you're new to programing and it took me years to become good at using it. (@Mox's answer provides some useful tips for using R). Perhaps SPSS or Excel meet your needs. I would suggest the book Modeling for Insight because provides great tips for how to quantitatively think about problems in business. The book also provides a good tutorial for using spreadsheets for modeling.

In summary, think about your questions first and the tools second (and also ask your chief estimator how he thinks though his job!). Good luck!
Answer: First, get the R language for statistical computing and RStudio to the the analysis.
Second, save it out of Excel as a csv, and import it into R, like so:
yourfile = read.csv("C:/directory/subdirectory/csvname.csv", header=TRUE)

Third, start running regression models. Basic syntax is like this:
Regressionmodel_1<- lm(EM ~ E +PH _MT+WT+S,data=yourdata)

Fourth, start googling for help on R--it's plentiful, and you can copy-paste it in.


What is the best way to collect and report statistics from within views 3's exposed filter?

Question: I have a content type "song" and created a view on it. Using Views 3 exposed filter, people can search with different criteria.

With Google Analytics, I can collect some rough statistics. But I do not want anonymous statistics. I would like to collect and report the criteria by the login user/roles.
I can put a PHP code into my view so that every time someone interacts with this view, the PHP code will collect the criteria from the URL and save to a table.
Is there a better way?
EDIT
I've got an interim solution:

Write a custom module that uses hook_form_alter to update the exposed filter form. See link.
Install Views Watchdog
Create a view that reports on these watchdog entries. I can use PHP to parse the watchdog's location field to get my reports better.

If you have a better alternatives, please let me know.
Comment: Are you using a google analytics module? It allows tons of options and you can tweak it to fit your requirements.
Comment: When you say 'I can put PHP code into my view' do you mean using PHP Filter?
Comment: Yes, PHP filter. To expand further, I'm thinking that whenever some interacts this view, it'll runs some PHP to read the URL and save to a table. Then I can write something to report from those data. I just thought there is a neater way to do this
Comment: @Ash Upadhayay, yes, I'm already using the google analytics module but it can only capture anonymous data
Answer: You can use GA Push module:

GA Push offers an API to enqueue informations that are sent GA
  servers, and three submodules to track browser events (using jQuery),
  form validation errors and log exceptions.

Instead of saving the data in your custom table you can just send it to Google Analytics.
Collect your data in your PHP code and send it like this:
      $push = array(
        'eventCategory' => $category,
        'eventAction'   => $action.
        'eventLabel'    => $label,
        'eventValue'    => $value,
      );
      ga_push_add_event($push);

You may hook on the form submit instead of adding PHP code to the view.
Comment: Google Analytics requires data to remain anonymous. So while this is good method, it prevents me send any usernames.
Comment: That's true if oyu send any user identifiers, but you can send data without any user id adn have the data aggregated. What GA doesn't allow is to track user activity and link with their id or any other data that can identify the individual user. But you can aggregate data withuot problem. If you need data linked to each individual user then yes, you need to save the data in your database.


Solving this differential equation $y'=\frac{x+y+4}{x-y-6}$

Question: If $\frac{dy}{dx}=\frac{x+y+4}{x-y-6}$ then I set $x=z+1$ and $y=w-5$ to get $\frac{dw}{dz}=\frac{z+w}{z-w}$ from here it's been solved in the text (George Simmons Differential equations). My concern is I made a mistake using $\frac{dy}{dx}=\frac{dw}{dz}$. My reason is $\frac{dy}{dx}=\frac{dy}{dw}\frac{dw}{dz}\frac{dz}{dx}$. The answer I get doesn't have (x+y+4) or (x-y-6) anywhere unlike the solutions I find through wolfram alpha. My solution is $\tan^{-1}(\frac{y+5}{x-1})=\log(\sqrt{(x-1)^2+(y+5)^2}+c$.
Comment: It would help if you'd include what answer you do get: without that there's no solution to validate.
Comment: OK. Should we close this question as a duplicate of that one? Or do you want to post a solution of your question here, based on what you learned from the other question?
Comment: wolfram alpha uses substitution $u=\frac{x+y+4}{x-y-6}$. Then get separable ode $u'=\frac{u^3-u^2+u-1}{2x-2}$ and solution with $\arctan u$
Comment: Your answer should be $y=f(x)$, where $f$ is just some function that does not depend on $y$
Comment: @Semiclassical Sorry I should have included my solution. I just edited it.
Comment: @Andrei I included my solution. it isn't $y=f(x)$ but rather an implicit relationship.
Comment: Substitute $v=y/x$. Then you will get a seperable equation.
Comment: Related: https://math.stackexchange.com/questions/1195583/how-to-proceed-for-these-two-differential-equations and https://math.stackexchange.com/questions/1692467/differential-equation and https://math.stackexchange.com/questions/2926293/a-specific-homogeneous-polar-differential-equation and probably many others.
Comment: @GerryMyerson Thanks, the last one had a good solution, which indicated that wolfram alpha uses a different substitution.
Answer: As indicated in the comments wolfram alpha uses the substitution $u=\frac{x+y+4}{x-y-6}$, which leads to a solution in terms of $u$. Which is different than the substitutions $x=z+5$ and $y=w-1$ which leads to solutions in terms of $x-5$ and $y+1$ as in my posted solution.


AutoComplete do Primefaces não passa value para o bean

Question: Estou com um problema com o componente autoComplete do PrimeFaces. O parâmetro value não está sendo passado para o meu bean.
private String filtroClientes;

public List<String> listarFiltroDeClientes()
{
    List<String> lista = new ArrayList<String>();
    List<Cliente> clientesFiltrados = Clientes.buscarPorPartesDoNome(filtroClientes);

    for(int  i = 0; i < clientesFiltrados.size(); i++)
    {
        lista.add(clientesFiltrados.get(i).getNomeCliente());
    }

    return lista;

}

public String getFiltroClientes() {
    return filtroClientes;
}

public void setFiltroClientes(String filtroClientes) {
    this.filtroClientes = filtroClientes;
}

Ao dar um print no "filtroClientes" ele mostra o valor null, ou seja o que foi digitado no input do autoComplete não está passando para o bean. Fora isso o componente está funcionando normalmente, já testei passar uma string qualquer para filtrar os clientes e o componente funcionou.
Quem puder ajudar desde já agradeço. Valeu!!
Comment: Você chegou a ver o exemplo la no showcase do prime? eu não tenho mais utilizado JSF mas em todos exemplos que vi ele recebem no método listarFiltroDeClientes() uma query String ex: listarFiltroDeClientes(String query) para concatenar com o nome ex: lista.add(query + clientesFiltrados.get(i).getNomeCliente());
Um outro detalhe é que eles não usam construtor na EL ex: completeMethod="#{projetosBean.listarFiltroDeClientes}" veja: [Auto Complete](http://www.primefaces.org/showcase/ui/input/autoComplete.xhtml)
Comment: criou um método get para filtroClientes ?
Comment: Sim criei os métodos, o interessante que se eu inicio a variável com algum valor, ele pega aquele valor mais não atualiza ele, ou seja o get funciona o set não.
Comment: Qual o Scopo do seu managerbean ? Veja se esta com ViewScope.
Answer: O erro está no completeMethod:

Não se usa o "()" chamando métodos do mbean. Mude para:

Da forma que estava teu método de autocompletar nem era chamado, por isso o valor não era setado no value. Com essa mudança deve funcionar.


the concept of matrix transform

Question: These statements are picked from Intro to Linear Algebra 4th by Strang
If we accpet this conception:

And an example
$ v = [a \ b\ c\ d]^T = a*[1\ 0\ 0\ 0]^T +  b*[0\ 1\ 0\ 0]^T+  c*[0\ 0\ 1\ 0]^T + d*[0\ 0\ 0\ 1]^T $
So $\ v_3 = [0\ 0\ 1\ 0]^T $,
and $ w_2 = [ 0 \ 1 \ 0]^T$.
According the statement, $T(v_3) = a_{23}*w_2$, but it is obviously wrong.
There is another question: why is $T(v_j) $ is the comb. of $W$, I think $W$ is a comb. of $v$ ( linear combination)
Comment: $a_{23} = firstname.lastname@example.com
Comment: $v_3$ is a basis vector , why do you multiply $v_3$ with a constant?
Comment: @M.Vinay Oh, I am sorry , I have edited my question
Comment: Okay, now $T(v_3) = T\begin{bmatrix}0\\ 0\\ 1\\ 0\end{bmatrix} = \begin{bmatrix}0\\ 2\\ 0\end{bmatrix} = 2w_2$. Why do you think this is wrong?
Comment: Er..? Yep, it is right... Maybe I calculate wrongly..@M.Vinay
Answer: $T(v_j)$ is the projection of $v_j$ in $W$ space and columns of $W$ make the space $W$. So, $T(v_j)$, which is an element of the space $W$, is a combination of the matrix $W$.
about the first question, if you have a polynomial $ax^3+bx^2+cx+d$ choosing the coefficients using $[0,1,0,0]$ would give $x^2$ and the respective derivative (the actual transform)is $2x$ which corresponds to the vector $[0,2,0]$. so, I think you should do the calculation more carefully.
Comment: Actually, is the matrix called "transition matrix" which stands for the basis? Or it is just the coffeicient matrix? I am very confused..
Comment: well,I think, the term transition matrix is used when dealing with markov chains. In linear algebra it is usually called transformation matrix. It does not always correspond to a basis. it is only a function
Comment: Oh.. What is the relationship between transformation matrix and new/ old basis and new/ old vector?
Comment: put basis vectors of the first space in columns of a matrix and call it W. let T be the transformation matrix. TW would give you a new matrix. call it V. columns of V are vectors in the new space. depending on the transformation, the new matrix V may have dependent or independent columns.

the concept of matrix transform


Where is the Harmonic mean used?

Question: There is a mean called Harmonic mean.
http://dlmf.nist.gov/1.2#E19
I mostly see usage of arithematic mean and geometric mean. On the other hand, I have never seen the usage of Harmonic mean yet.
In what kind of case, is the Harmonic mean used?
Comment: See [this](http://en.wikipedia.org/wiki/Harmonic_mean#Examples).
Comment: @mathlove Thank you for the link.
Answer: You go on a round trip.  You go out at $50$ miles per hour and come back at $60$ miles per hour.  The average speed of your whole trip will be the harmonic mean of $50$ and $60$ (mph).  You can extend this to several legs of a trip all the same length.  Your overall average speed will be the harmonic mean of the speeds on the various legs of the trip.
Comment: Thank you very much. Your reply is very simple to understand for me.
Answer: The harmonic mean usually appears when averaging speed (or rates in general).
See this question as a reference:
https://stackoverflow.com/questions/34794664/how-should-i-calculate-the-average-speed-by-road-segment-for-multiple-segments/34795821#34795821

Where is the Harmonic mean used?


Flutter: How to add a Foreground to a dismissable widget

Question: I want to add a foreground to a dismissible while swipe, Able to set a background . But i need a foreground instead of background?
return Dismissible(
    key: UniqueKey(),
    onDismissed: (direction) {
        setState(() {
            model.removeAt(index);
        });
    },
    background: Card(
        elevation: 10,
        child:
            ext(
                'delete',
                style: TextStyle(
                    fontSize: 26,
                    color: Colors.white
                ),
            ),
    ),

    child: Padding(
        padding: const EdgeInsets.all(12.0),
        child: Center(
            child: Text('ab'),
        ),
    )
);

Comment: Improved formatting. Check if brackets are balanced.
Answer: check this library out: flutter_slidable
By adding 'actions' you can handle the background.The first child of Slidable is the foreground and can be altered during a swipe gesture through the use of if-else.