Show that an element $x$ belongs to the unique maximal ideal of the commutative ring $R$ if and only if $ 1+xr$ is invertible.

Question: Let R be a commutative ring with $1 \neq 0$. Let $M$ be the unique maximal ideal of R. I want to show that $x \in M$ if and only if $1+xr$ is invertible for every $r \in R$. I am a bit stuck on where to begin. Any hints are appreciated.
Comment: What happens if an element is not invertible?
Answer: Suppose that $x\in M, $ for every $r, xr\in M$ since $M$ is an ideal. If $(1+xr)$ is not invertible, it is contained in a maximal ideal which is $M$, you deduce that $1=(1+xr)-xr\in M$. Contradiction.
Suppose that $(1+xr)$  is invertible for every $r$, if $x$ is not in $M$, it is invertible, there exists $u$ such that $ux=1$, $1+(-u)x=0$ is not invertible. Contradiction.
Answer: It is the special case $\rm\ J = (x)\ $ in $\ (1) \iff (2)\ $ below.
Theorem $\ $ TFAE in ring $\rm\:R\:$ with units $\rm\:U,\:$ ideal $\rm\:J,\:$ and Jacobson radical $\rm\:Jac(R)$
$\rm(1)\quad  J \subseteq Jac(R),\quad $ i.e.  $\rm\:J\:$  lies in every max ideal $\rm\:M\:$ of $\rm\:R$
$\rm(2)\quad  1+J \subseteq U,\quad\ \ $  i.e. $\rm\: 1 + j\:$  is a unit for every $\rm\: j \in J$
$\rm(3)\quad  I\neq 1\ \Rightarrow\  I\,+\,J \neq 1,\quad $  i.e.  proper  ideals survive in $\rm\:R/J$
$\rm(4)\quad\!\! M$ max $\rm\,\Rightarrow  M+J \ne 1,\quad $  i.e. max ideals survive in $\rm\:R/J$
Proof $\: $ (sketch) $\ $  With  $\rm\:i \in I,\ j \in J,\:$ and max ideal $\rm\:M,$
$\rm(1\Rightarrow 2)\quad  j \in all\ M\ \Rightarrow\ 1+j \in no\ M\ \Rightarrow\ 1+j\:$ unit.
$\rm(2\Rightarrow 3)\quad i+j = 1\ \Rightarrow\ 1-j = i\:$ unit $\rm\:\Rightarrow\:  I = 1$
$\rm(3\Rightarrow 4)\ \ \ $  Let $\rm\:I = M\:$ max.
$\rm(4\Rightarrow 1)\quad  M+J \ne 1 \Rightarrow\ J \subseteq M\:$  by  $\rm\:M\:$ max.


Is it possible to use the created like button on this website (https://likebtn.com/en/) in an app being developed in Smartface App Studio?

Question: Is it possible to use the created like button on this website (https://likebtn.com/en/) in an app being developed in Smartface App Studio?
I've tried adding the like button onto a website and it was very successful.
Thankyou☺
Answer: It is possible with image button.You can create a button like that using following codes:
<code>var myImgBtn = new SMF.UI.ImageButton({
        left : '10%',
        top : '10%',
        width : '20%',
        height : '10%',
        defaultImage : 'likebutton.png',
        highlightedImage : 'buttonhighlighted.png',
        inactiveImage : 'buttoninactive.png',
        text : 'Like',
        onPressed : function(e){
                  ...
                  }
        });
        Pages.Page1.add(myImgBtn);
</code>


Is there a ML model that can determine the sequence that leads to an outcome?

Question: I have a problem where a certain sequence of events leads to a certain outcome.  The problem is, I am not sure exactly what the sequence is.  I am hoping to get some possible sequences to test as opposed to analyzing the events one by one.
Is there a ML technique that can allow me to determine the sequence of predictors that allow me to predict a response?  It's pretty easy to put in a bunch of raw features and see which ones matter, but when it comes to a sequence of features, I am not sure what to do.
The goal here is not only prediction, but also interpretation in that I need to know what features and what sequences matter.
Thanks!
Comment: Would something like this make sense?  Instead of trying to determine the sequence all at once, just build several models, one that predicts the next.  So build a model that predicts T0 with T-1.  Then build a model that predicts T-1 with T-2.  Etc...  I think this is what I'll attempt unless there's a better idea.
Answer: You may be interested in a particular kind of neural network designed for sequential tasks: rnns come in several flavors, including lstm and gru networks which have been used to model long sequences such as natural language. This can be used to generate $n$-step ahead predictions; in the natural language setting, this can be used to do stuff like writing novel tweets.
Comment: Thanks.  This would be preferred to a convolution neural network?
Comment: RNNs and CNNs are not mutually exclusive. Anyway, which model does best for some particular problem probably depends on the problem.


How to show $|\int_ae^{iz^2}dz|\le\frac{\pi(1-e^{-R^2})}{4R}<\frac{\pi}{4R}$?

Question: Let $ a:[0,\frac{\pi}{4}]\mapsto\Bbb C, a(t)=Re^{it}(R>0)$ a curve.
Show that
$$\left|\int_ae^{iz^2}dz\right|\le\frac{\pi(1-e^{-R^2})}{4R}<\frac{\pi}{4R}$$
Can you help me to solve this? will we use $|f^n(z)\le\frac{n!}{2\pi }M \int_\varphi\frac{dw}{|w-z|^{n-1}}$
Comment: Can you use the $ML$-inequality?
Answer: $$\int_a dz \, e^{i z^2} = i R \int_0^{\pi/4} dt \, e^{i t} \, e^{i R^2 \cos{2 t}} \, e^{-R^2 \sin{2 t}}$$
Therefore the magnitude of the integral is
$$\left | \int_a dz \, e^{i z^2}\right | \le R \int_0^{\pi/4} dt \, e^{-R^2 \sin{2 t}}$$
Now use the fact that
$$\sin{u} \ge \frac{2}{\pi} u \quad u \in \left [ 0,\frac{\pi}{2}\right ]$$
Thus,
$$\left | \int_a dz \, e^{i z^2}\right | \le R \int_0^{\pi/4} dt \,e^{-2 R^2 2 t/\pi}  = \frac{\pi}{4 R} \left (1-e^{-R^2}\right )$$


Como alinhar uma div com display inline-block?

Question: Tenho um feed de notícias que consiste em duas divs inline-block.
1° - A primeira contem o título e imagem da notícia (esquerda).
2° - A outra o conteúdo da notícia (direita).
Queria que mesmo que os parágrafos do conteúdo da notícia variem de notícia para notícia, que alinha-se ao centro da div da esquerda.
Algo assim:

Como posso conseguir este resultado ?(desculpem pelas mad photoshop skillz)
Answer: Olá,
você pode colocá-las alinhadas lado a lado usando float. Daí a largura será respeitada, e não importa quanto texto você colocar na div da direita.
Segue um exemplo de código:

       img and titulo

       linhas e linhas de conteudo


Set of orthogonal matrix over $\Bbb{R}$: Closed, convex, open?

Question: Reading my course on topology we haven't answering this exercise:

Show that the set of orthogonal matrix over $\Bbb{R}$ is closed. Is it convex? Open

For the fact is closed I wrote $\mathcal{O}_n(\Bbb{R})=f^{-1}\{I_n\}$ where $f:M \rightarrow M^{T}M$ is continuous.
For the convexity I think the answer is no because $I_n$ and $-I_n$ are orthogonal but the midpoint of the segment joining these two matrices is $0$ witch is not orthogonal. I am stuck for the last question. I am terrible to prove something is open or not.
Any ideas please?
Comment: You have answered the first two parts correctly. The last part is quite trivial: The set $\Omega$ of all $(n\times n)$-matrices is obviously connected. Therefore ${\cal O}(n)$ could only be closed and open at the same time if it were all of $\Omega$.
Comment: I was focus on the main definition. I should have thought about it. Thank you @ChristianBlatter.
Answer: Hint: When is a diagonal matrix orthogonal? Can you find diagonal non-orthogonal matrices $(D_m)$ such that $D_m \to I_n$?
Comment: A diagonal matrix is orthogonal if $D=D^{-1}$. For the your second question I don't understand do you want a diagonal matrix of order $n$ such that the coefficient are $m$-dependent and $D$ converges to $I_n$ as $m\rightarrow +\infty$? Anyway I don't understand how can I relate this with the fact $O_n$ is not open?
Comment: If $O(n)$ were open, there would exist a open neighborhood around $I_n$, so that any sequence converging to $I_n$ would be eventually in $O(n)$.
Comment: I never thought about that. So $Diag(1+1/m,1,\cdots,1_n)$ will do the job?
Comment: Absolutely, it works.
Comment: Thank to you now I have an another way to thing about open set. +1 and accept.


How to remove HTML tags from ajax response using PHP?

Question: I need to check from the database if email exists or not by using Ajax. I am getting a response, but coming with some HTML content. I have given below my code what I have followed.
My Ajax code:
var username_state = false;
var email_state = false;
$('#username').on('blur', function(){
    var username = $('#username').val();
    if (username == '') {
        username_state = false;
        return;
    }
    $.ajax({
        url: 'user_list.php',
        type: 'post',
        data: {
            'username_check' : 1,
            'user_name' : username,
        },
        success: function(response){
            $("html").html($("html", response).html());
            if (response == 'taken' ) {
                response.find(element).remove();
                alert('hi');
                username_state = false;
                $('#username').parent().removeClass();
                $('#username').parent().addClass("form_error");
                $('#username').siblings("span").text('Sorry... Username already taken');
            }
            else if (response == 'not_taken') {
                username_state = true;
                $('#username').parent().removeClass();
                $('#username').parent().addClass("form_success");
                $('#username').siblings("span").text('Username available');
            }
        }
    });
});

My php Code
$db = mysqli_connect('localhost', 'root', '', 'my_assesment');

if (isset($_POST['username_check'])) {
$username = $_POST['user_name'];
// echo  $username;
$sql = "SELECT * FROM user_information
            WHERE user_name='".$_POST["user_name"]."'";
//echo  $sql;
$results = mysqli_query($db, $sql);
if (mysqli_num_rows($results) > 0) {
    //$response = true;
    echo "taken";
}else{
    $response = false;
  echo 'not_taken';
}

This is am getting  response
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">

not_taken

Comment: Are you sending the AJAX request to the same page?
Comment: no I am sending to different page
Comment: How did you get here? You can't generally build an API based app only with frontend work and without a proper backend server. Whatever you manage to build will break randomly when anything changes on the server.
Comment: No, actually am working localhost Now am getting valid response, but it's not checking if condition . What I need to do?
Comment: **Warning:** You are wide open to [SQL Injections](https://php.net/manual/en/security.database.sql-injection.php) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/5741187)
Answer: Looking at the output you are receiving my guess is that the ajax request is being sent to the same page. If that is the case then initially wrap the entire username checking code within a suitable if test and ensure that any HTML buffer content is disposed of completely before sending the response to the ajax callback.
/*
    Test that the request is a POST request and that
    the variables you are expecting have been sent.

    As you are using data sent by the client you MUST
    take precautions to mitigate SQL injection attacks.

    Use a Prepared statement rather than directly embedding
    user supplied data in the SQL.
*/
if( $_SERVER['REQUEST_METHOD']=='POST' && isset(
    $_POST['username_check'],
    $_POST['user_name']
)){

    $db = mysqli_connect('localhost', 'root', '', 'my_assesment');
    $sql='SELECT `user_name` FROM `user_information` WHERE `user_name`=?';
    $stmt=$db->prepare( $sql );
    $stmt->bind_param('s',$_POST['user_name']);
    $stmt->execute();
    $stmt->store_result();
    $rows=$stmt->num_rows;
    $stmt->close();

    $response=( $rows > 0 ) ? 'taken' : 'not_taken';

    # flush buffer to remove any other HTML / text content
    ob_clean();

    #exit completely from this logic branch
    exit( $response );
}

The test page I used to try to figure out the fault in the callback was exactly as follows. Essentially rather than respecting the checkbox to do a test and querying the db a random integer determines if the status is taken or not_taken simply to test the logic in the callback.
<?php
    if( $_SERVER['REQUEST_METHOD']=='POST' && isset(
        $_POST['username_check'],
        $_POST['user_name']
    )){
        /*
        $db = mysqli_connect('localhost', 'root', '', 'my_assesment');
        $sql='SELECT `user_name` FROM `user_information` WHERE `user_name`=?';
        $stmt=$db->prepare( $sql );
        $stmt->bind_param('s',$_POST['user_name']);
        $stmt->execute();
        $stmt->store_result();
        $rows=$stmt->num_rows;
        $stmt->close();
        */
        $rows=mt_rand(0,1);
        $response=( $rows > 0 ) ? 'taken' : 'not_taken';

        ob_clean();
        exit( $response );
    }
?>
<!DOCTYPE html>

        <meta charset='utf-8' />
        <title>?Username Check Test Page</title>

        <form name='usercheck'>
            Username:<input type='text' id='username' name='user_name' value='geronimo' />
            Username Check:<input type='checkbox' name='username_check' value=1 />
        </form>

Comment: Hi, Thank you for your response. Now am getting a valid response, but it's not going to the  inside of if condition, what I need to do?
Comment: `"it's not going to the inside of if condition"` - do you mean within the AJAX callback?
Comment: Yes,  success: function(response){

      if (response == 'taken' )
   {//conditions not checking here }
Comment: But you can see a response in the console/network tab??
Comment: Yes, I c an able to see the response but it's not checking the conditions
Comment: I just created a basic test page and found that `response.find(element).remove();` was preventing the alert from appearing
Comment: Ok Thanks, can you give me the sample code? already I have tried this code but its not working this code. If you want I will send you my code. Today I have to complete this task.


Qual tipo de PDO::FETCH_* é o mais rápido?

Question: Das que eu conheço, existem 5 maneiras de realizar, mas na documentação oficial é apresentado cerca de 8 maneiras diferentes de realizar um FETCH_*.
Gostaria de saber, de todos as maneiras de fazer um PDO::FETCH_*, qual é o mais rápido de se utilizar?
Answer: Existe um script que faz um teste de velocidade: Benchmark Script.
Sugiro que você execute este benchmark em seu próprio servidor, no entanto, este é um resultado típico na minha configuração, para resultados de uma única linha:
PDO::FETCH_ASSOC - 936 ms
PDO::FETCH_BOTH - 948 ms
PDO::FETCH_NUM - 1,184 ms
PDO::FETCH_OBJ - 1,272 ms
PDO::FETCH_LAZY - 1,276 ms

Para grandes conjuntos de dados, esses resultados são apresentados:
PDO::FETCH_LAZY - 5,490 ms
PDO::FETCH_NUM - 8,818 ms
PDO::FETCH_ASSOC- 10,220 ms
PDO::FETCH_BOTH - 11,359 ms
PDO::FETCH_OBJ - 14,027 ms


No score method for MeanShift estimator - scikit-learn

Question: I was trying to use GridSearch to iterate over different values of bandwidth for MeanShift algorithm and it shows this error; does any of you know how can I fix this? Thanks a lot!
# Using GridSearch for Algorithm Tuning
from sklearn.model_selection import GridSearchCV
meanshift=MeanShift()
C = range(48, 69) # For MeanShift bandwidth
param_grid = {"bandwidth": range(48, 69)}

mean_grid = GridSearchCV(estimator=meanshift, param_grid=param_grid, scoring=None)

mean_grid.fit(X)

And this is the error I get:
TypeError: If no scoring is specified, the estimator passed should have a 'score' method. The estimator MeanShift(bandwidth=None, bin_seeding=False, cluster_all=True, min_bin_freq=1,
     n_jobs=1, seeds=None) does not.

Comment: Do you have the actual labels of clusters? Since you dont pass any ground truth data (actual labels of clusters,`y`) in the `fit()`, how would you calculate the score? On what basis, GridSearchCV will decide that a specific `bandwidth` value is better than other values?
Comment: No class in [`sklearn.clustering`](http://scikit-learn.org/stable/modules/classes.html#module-sklearn.cluster) supports `score()`, except `KMeans`. Do you want to use that `score()` function?
Comment: @VivekKumar; thank you so much for your response. I acutally don't have any idea about the clusters I should be having in the end.. which means I can't calculate the score for MeanShift. However, I was wondering if there are other so that we set a score based on the clusters number we want?
Answer: You can't use GridSearch with an unsupervised method well.
The concept of grid search is to choose those parameters that have the best score when predicting on held out data. But since most clustering algorithms cannot predict on unseen data, this does not work.
It's not that straightforward to choose "optimal" parameters in unsupervised learning. That is why there isn't an easy automation like gridsearch available.
Answer: It's because MeanShift algoritm does not contain score function. In this case you have to specify scoring in GridSearchCV. Here is a complete list.
From the documentation of GridSearchCV:

Parameters:
estimator : estimator object.
This is assumed to implement the scikit-learn estimator interface. Either estimator needs to provide a score function, or scoring must be passed.
Comment: Why (-1) score ?


VB6 Crystal Reports ActiveX viewer not displaying all export formats

Question: I am using the Crystal Reports ActiveX viewer (v10) in a VB6 app.
10/12/2003  01:41 AM           799,944 crviewer.dll
The viewer loads OK and displays the report but the export formats available using the button on the dialog are limited to:

Crystal Report (RPT)
Tab seperated text
Text

I have confirmed that the required export DLLs such as u2fsepv.dll, u2fxls.dll, etc are located in both the windows\system32 and Common files\Crystal Decisions\2.5\bin directories.
I have checked the source code used to load the viewer and it is not limiting export formats in any way that I can see.
Is this a known issue? Any ideas?
Answer: Those DLL's (u2*.dll) need to be dropped in C:\Windows\Crystal.
EDIT
For v8.5, I also install and register:
$PROGRAMFILES\Seagate Software\Shared\ExportModeller.dll
$PROGRAMFILES\Seagate Software\Shared\crtslv.dll

Note, that the export driver for PDF is not a u2f*.dll; I use crxf_pdf.dll (which does go in $WINDIR\Crystal)
Comment: Thanks @Lynn. Just tried that (also copied them to the app directory) - No difference. Have noticed that the date/time stamps on the u2x dlls not showing up don't look right so am now looking into that - they maybe the 8.5 versions of the DLLs and maybe that is the issue. Funny that the only destination is 'Disk' but other 10.x destination DLLs are present.
Comment: I didn't think that native apps (read: vb6) could use anything newer than cr8.5. When you said you were using cr10, I figured that maybe I've just been wrong all of these years. Any chance I'm right?
Comment: Seems to work ok with VB6. I think the issue is that the run-time files have not been installed properly on the box (some key files that handle the export fns are missing). This is what I am chasing up now. Your initial answer did present me with some deja vu , though. What a nightmare CR is to support!
Comment: I'm going to edit my post to include the locations of the other files that I deliver.


Check if a text array contains one or more parameters

Question: I have a column of type text[] in that column looks like this
Example Column
I want to return any row that contains one or more of the passed parameters but i am not able to do this
I have tried
<code>securitygroups: { [Op.contains]: ["blah-house","admin"] }
</code>
this only returns me the first row and not the second even though admin is in both row
i can loop through each of the parameters but that requires multiple database query's
Any suggestions on how to do this by passing multiple parameters
Answer: Fixed by using op.overlap
<code>{ securitygroups: { [Op.overlap]: ["blah-house","admin"] } }
</code>


Minha aplicação em React da erro de página não encontrada se eu digitar a url

Question: Olá quando eu digito a segunda url no meu local o Route funciona levando para página solicitada, porém quando eu fiz o build hospedei e repeti o mesmo procedimento a mesma não funciona dando página não encontrada alguém sabe informar como corrijo esse problema? Segue em Anexo a imagem do meu App.js.
Comment: Problema resolvido, precisei criar um arquivo .htaccess na pasta public simples e fácil.
Porém em outro servidor que estava com o mesmo problema eu criei um arquivo chamado "_redirects" e dentro adicionai a linha " /* /index.html 200 " também tive sucesso. Obs: Duas soluções que resolvem o mesmo problema em servidores de hospedagens diferentes.
Comment: Olá, você poderia mostrar seu código do componente Routes ?
Answer:

import React from 'react';
import { Switch, BrowserRouter } from 'react-router-dom';

import RouteHandler from './components/RouteHandler';

import Home from './pages/Home';
import Leitura from './pages/Leitura';
import Admin from './pages/Admin';
import NotFound from './pages/NotFound';
import SignIn from './pages/SignIn';
import SignUp from './pages/SignUp';
import AddConteudo from './pages/AddConteudo';
import Listagem from './pages/Listagem';

export default () => {
    return (
        <Switch>
            <RouteHandler exact path="/">
                <Home />
            </RouteHandler>
            <RouteHandler exact path="/ad/:id">
                <Leitura />
            </RouteHandler>
            <RouteHandler private exact path="/admin">
                <Admin />
            </RouteHandler>
            <RouteHandler exact path="/signin">
                <SignIn />
            </RouteHandler>
            <RouteHandler exact path="/signup">
                <SignUp />
            </RouteHandler>
            <RouteHandler private exact path="/addconteudo">
                <AddConteudo />
            </RouteHandler>
            <RouteHandler exact path="/listagem">
                <Listagem />
            </RouteHandler>
            <RouteHandler>
                <NotFound />
            </RouteHandler>
        </Switch>
    );
}

Observe que RouteHandler herda de outro componente Segue a baixo...

import React  from 'react';
import { Route, Redirect } from 'react-router-dom';
import { isLogged } from '../helpers/AuthHandler';

export default ({ children, ...rest }) => {
    let logged = isLogged();
    let autorizado = (rest.private && !logged) ? false : true;
    return (
        <Route
            {...rest}
            render={ () =>
                autorizado ? children : <Redirect to="/entrar" />}
        />
    );
}
Answer: coloca no htaccess:
RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule .* index.html
Options -Indexes


Correct sbin-path during nginx rebuild

Question: When I rebuilding nginx I am running these commands
./configure --add-module=$HOME/nginx_mod_h264_streaming-2.2.7 --sbin-path=/usr/local/sbin --with-debug
make
sudo make install

Should the --sbin-path point to my current nginx sbin directory or the actual binary file in the sbin directory?
Answer: If you run ./configure --help and grep for sbin-path, it will tell you for certain, but it   specifies the directory where the make install procedure will put any files that would normally go in /sbin.
Answer: Based on this page - It looks like it wants the nginx sbin directory - ./configure --help |grep -i 'sbin' should yield some assistance.
Comment: Looks like binary file for me   --sbin-path=PATH                   set path to the nginx binary file

Correct sbin-path during nginx rebuild


Im getting funny % signs back how do I get rid of them?

Question: Im trying to parse a response from an authentication server that is url encoded. However when I do it I am getting \r\n characters. And I need to not have these in my text as I need to be able to run a regular expression that looks for white space but doesnt work with these escape characters.
So basically the string returned is:
ClientIP=192.168.20.31%0d%0aUrl%3d%2fflash%2f56553550_hi%3funiqueReference%3d27809666.mp4

After url decoding it it is:
192.168.20.31\r\nUrl=/flash/56553550_hi?uniqueReference=27809666.mp4

So you see I dont want it to have \r \n etc I want to have:
"192.168.20.31 Url=/flash/56553550_hi?uniqueReference=27809666.mp4"

As a verbatim string in c#.
Is this possible? Or do I have to do a string.replace on \r and replace with " "?
Answer: Either replace %0d%0a with %20 before URL decoding the string, or the \r\n with  after.
Since the data exists in the original string, you can't just make it go away without replacing it.
Comment: isnt there a more elegant way of doing this?
Comment: @Pete2k - not really. You could use RegEx to do the same, but that's even more complicated.
Comment: sorry Oded why would the auth server be using %0d%0a and not %20 in the first place. I appreciate your response :-)
Comment: @Pete2k - How would I know that? You need to ask the people behind the auth server...
Comment: Well okay this is wierd because when I look at the value in the trace.axd that asp.net it comes out how I want it, so obviously %0d%0a equates to something doesnt it? Just like %20 equates to a space?
Comment: @Pete2k - `%0d` is `\r` and `%0a` is `\n`. This is the URL encoding for each.


Applying the master theorem

Question: State the asymptotic runtime found by the master theorem. If the master theorem does not apply state why:
1) $T(n) = $T($n/3)$
2) $T(n)= $  $5T$($2n/5$) + $n$
3) $T(n) = 4T(n/2) +15n^3 + 4n^2 +n+4$
1) For the first one I think the master theorem does not apply because I do not have a k-value, is this enough to show that I can't use the master theorem?
2) For the second one I know $a = 5 , b=2/5, k = 1$, so $log_\frac{2}{5}5$ < 1 , so the complexity would be O(n)
3) I don't know how to do can someone show me?
Can you guys verify whether my answers for 1 and 2 hold true and if possible show me how to deal with 3)?
Thank you
Comment: can someone confirm the answer below? thanks
Answer: If will use the variable names from the Wikipedia page on the Master theorem.

$a = 1$, $b = 3$, so $\log_b(a) = 0$. But since $f(n) = 0$ it is also $f(n) \in O(n^{-1})$, so $c = -1$.
Then $c < \log_b(a)$ and $T \in \Theta(n^0) = \Theta(1)$, which should be obvious as $T(n) = T(0)$ for any n.
$a$ and $c$ (or $k$) are correct but $b = 2.5$. So $T \in \Theta(n^{1.76})$.
$a = 4$, $b = 2$, $\log_b(a) = 2$, $f(n) \in \Omega(n^3)$.
So $T \in \Theta(n^3)$.
Comment: so the master theorem can be used for all three of them?
Comment: Yes, I would say so. I am not completely sure for the first one because c is negative, but since it gives the correct result, I think my solution is correct.
Comment: thank you, hopefully someone can confirm just in case

Applying the master theorem


Fatal error: Class 'plgContentWidgetkit_Content' not found in

Question: My website http://gutenberginstitute.com was developped using joomla and yootheme "venice". However, I have download and installed Widgetkit (free version so far) to test it on my site, and I can't make it work. It seems there are some plugins that are not installed, and if I put
...
[widgetkit id=1]
...
in some article, for example...
http://gutenberginstitute.com/index.php/es/our-teachers-es
It's not converted into the widget, but it shows just "[widgetkit id=1]"
On the other hand, if I use the module that gets created after the installation of widgetkit, in the "Modules" tab, I get an error when trying to show the article:

Fatal error: Class 'plgContentWidgetkit_Content' not found in
{..}public_html/administrator/components/com_widgetkit/helpers/system.php
on line 312

Anyone know what could be here happening?
Comment: Try uninstalling widgetkit, and then installing it again. one done, ensure everything was installed correctly. You should also make sure the wdigetkit plugin is enabled
Comment: All plugins are enabled. I have unistalled it about 10 times. Even installing other versions doesn't fix the problem, widgetkit behaviour is quite weird :( But I don't get any javascript error in the cosole, nothing :(
Comment: Now, with the new widgetkit, ZOO and K2 installed - the same. 1) either it shows "[widgetkit id=1]"  in text or, if creating a module, it just displays the title but not the widget, as shown in http://gutenberginstitute.com/index.php/our-teachers.  It seems to be a conflict somewhere, but I don't know where to start from.
Answer: This is already fixed. It was related to different uikit.js version (2.18) and templates (2.20) and yoo_theme out of date. Update your yoo_theme version and all the rest will be fixed automatically!


Mysql usar ou não o 'as' em aliases?

Question: Escrevendo uma query em MySQL me deparei com essa duvida, fiz uma busca, porem, não achei nada (ou não soube procurar), a duvida é simples, existe alguma diferença entre usar ou não o as na hora de criar um nome temporário para a colunas do MySQL?
Exemplo:
No exemplo a baixo usei o as para definir o nome temporário:
SELECT nome_titulo as Titulo, nome_exibicao as 'Nome de Exibição' , created_at as 'Data de Criação' FROM moneyguard_database.titulos;

Já nesse exemplo eu não utilizei apenas passei o nome temporário ao lado:
SELECT nome_titulo Titulo, nome_exibicao 'Nome de Exibição' , created_at 'Data de Criação' FROM moneyguard_database.titulos;

Em ambos os casos eu tenho o mesmo resultado, será que existe alguma diferente em desempenho ou algum caso que uma forma seja melhor que a outra?
Desde já agradeço o esclarecimento.
Answer: Segundo a documentação do MySQL:
Uma expressão select pode receber um alias usando AS alias_name. O Alias é usado como o nome da coluna da expressão e pode ser usado em: ORDER BY, GROUP BY ou HAVING. Por exemplo:
SELECT CONCAT(last_name,', ',first_name) AS full_name   FROM mytable ORDER BY full_name;

A palavra-chave AS é opcional quando criando um alias em uma expressão select com um identificador. O exemplo anterior poderia ser escrito assim:
SELECT CONCAT(last_name,', ',first_name) full_name   FROM mytable
ORDER BY full_name;

No entanto, como o AS é opcional, um problema que pode acontecer se você esquecer de colocar a vírgula entre dois itens do select: o MySQL vai interpretar o segundo nome como um alias. Por exemplo, na seguinte expressão, columnb é tratado como um alias:
SELECT columna columnb FROM mytable;

Por este motivo, é uma boa prática ter o hábito de usar AS quando especificando um alias de uma coluna.

Mysql usar ou não o 'as' em aliases?


Cannot remove alternate computername after in-place upgrade from 2008 R2 to 2012 R2

Question: We have some servers that were upgraded in-place from 2008 R2 to 2012 R2. While they were running 2008 R2 alternate computer names were added to them with netdom computername <computer> /add:<alternate-name>. Now we're in the process of killing the 2012 R2 servers and moving their functionality to new 2022 servers, the problem we're facing is that the alternate computer names cannot be removed from the 2012 R2 servers. Running netdom computername <computer> /remove:<alternate-name> results in:
Unable to remove <alternate-name> as an alternamte [sic] name for the computer.
The error is:

The system cannot find the file specified.

The command failed to complete successfully.

%errorlevel% is 2.
We cannot add the alternate names from the 2012 R2 servers to the new 2022 servers until the alternate name is removed. Removing the computer object in AD allows the alternate name to be created in 2022, but the servers are being gradually decommissioned so this would be a last resort.
I've verified that it's the in-place upgrade is causing the error by

Installing a new clean 2008 R2, not domain joined or anything.
Adding an alternate name, confirming that the remove works.
Running in-place upgrade, confirming that the remove of the name added in 2008 R2 doesn't work.
Comment: Questions should demonstrate reasonable information technology management practices. Questions that relate to unsupported hardware or software platforms or unmaintained environments may not be suitable for Server Fault.
Both 2008 and 2012 are end of life.
Comment: The upgrade from 2008 R2 was a while ago. We're explicitly trying to leave 2012 R2 but are being hindered by this problem.
Answer: This is stored in the msDS-AdditionalDnsHostName multivalued attribute on the old host. You will need to remove the value using Active Directory Users and Computers. You may need to select Advanced view to display the Attributes Editor tab on the computer object.
https://learn.microsoft.com/en-us/windows/win32/adschema/a-msds-additionaldnshostname
Comment: In addition to `netdom /remove` or just remove in AD?
Comment: Netdom isn't needed to remove the attribute when AD Users and Computers is used.
Comment: Something else you may want to check. A CNAME for the desired name, either create it in DNS or update the record with the new host.
Comment: I've tried just removing the value from `msDS-AdditionalDnsHostName` now and updating the A record to point to the new host. Running `netdom /add` on the new host results in `Cannot create a file when that file already exists`. Running `/enum` on the old host still returns the alternate name. I've checked with `setspn -L ` that no SPNs with the alternate name is present for the old host.

I can see the old alternate name without FQDN under `msDS-AdditionalSamAccountName`, but the option to remove it is greyed out.
Answer: I had the same problem when migrating a server and trying to add the name to the new server. I just removed the old server from the domain and suddenly it worked.


Will running CSF & Bastille cause any conflicts?

Question: I'm taking my first steps into the world of un-managed servers, and have confused myself whilst reading through the 101 tutorials on server hardening that Google spews out!
The most recent advice I have been given is to install both CSF and Bastille on my server (used to serve a consumer-facing ecommerce site and act as the business' email server), but my understanding was that both of these tools were an abstraction layer above netfilter / iptables. Will installing both packages cause any conflicts, or do they play well together?
Answer: Bastille deals with the configuration of the server itself. It helps you harden services/operating system.  It doesn't actually touch the firewall, so it should have no conflicts with CSF.


dice roll of 20

Question: what formula would be correct to find the odds of rolling 2 dice "X" number of times without a seven showing. There are 36 combinations when rolling 2 dice with six sides. Im wondering how often one could roll 20 times. One person suggested $\displaystyle 1 - \left(\frac{5}{6}\right)^{26}$. Another stated it would have to be $\displaystyle 1 - \frac{5}{6} \cdot \frac{1}{6}$.
Also curious if this would be true... At times during the game the 'button' is 'off' and one could roll a seven without harm. If I wanted to count only the rolls when the button is 'on' wouldn't it be the same likelihood/formula? as in not counting the 'off' rolls. Trying to say a person rolled 6 times, then button was turned off for 3 rolls, then the person rolled another 14 times, wouldnt that be the same as odds of rolling 20 times at once?
Answer: If you roll two dice the number of ways to get a total of seven is 6 as you could roll any of the following (1,6) (2,5) (3,4) (4,3) (5,2) (6,1).  Since there are 36 possible results then from one roll the probability of total not being 7 is
$$\frac{36 - 6}{36} = \frac{30}{36} = \frac{5}{6}$$
For no six from two rolls the probability of no 7 is
$$\left(\frac{5}{6}\right)^2 = \frac{25}{36} \approx 0.6944$$
And for X rolls it's simply
$$\left(\frac{5}{6}\right)^X$$
Note: that because the outcome of a roll is random if you roll 6 times while counting the result then roll 3 times not counting the result (or even a million times) then roll another 14 times counting the result the probability is still
$$\left(\frac{5}{6}\right)^{20} \approx 0.026084$$
Answer: rolling 2 dice X times gives you $36^X$ unique combinations.  The chances of getting a 7 on a roll are $\frac{6}{36}=\frac{1}{6}$.  so the chances of not getting a 7 on a roll are $1-\frac{1}{6}=\frac{5}{6}$.  The chances of this happening X times is $(\frac{5}{6})^X$
Comment: to consider when the button is on, let X=number of rolls where the button is on.

dice roll of 20


Python Script runs fine on RPi until I try creating shortcut - ConfigParser throws "no section" error

Question: I have a functioning python script that runs fine when I call it via terminal or any Python editor. But when I create a shortcut or bash to open the file it makes it part way through the code until it comes across ConfigParser which is of course using a config file.
I get the following error:
pi@raspberrypi:~ $ ./short.sh
pygame 1.9.6
Hello from the pygame community. https://www.pygame.org/contribute.html
this is a linux machine
i should not be here right now
Traceback (most recent call last):
  File "/home/pi/KeymasterGame/keymaster.py", line 46, in <module>
    comport = config1.get('general', 'comport')
  File "/usr/lib/python3.9/configparser.py", line 781, in get
    d = self._unify_values(section, vars)
  File "/usr/lib/python3.9/configparser.py", line 1149, in _unify_values
    raise NoSectionError(section) from None
configparser.NoSectionError: No section: 'general'

Of course, there is a section "general" which does work when being called from terminal
Python Code (just the beginning until the error):
import tkinter
from tkinter import *
import keyboard
import tkinter.font as TkFont
from pyfirmata import Arduino, util
import time
import pygame
from configparser import ConfigParser
import ast
from sys import platform
import sys
import os

#detect operating system
if platform == "linux" or platform == "linux2":
    print("this is a linux machine")
    linux = 'yes'
    import RPi.GPIO as GPIO
    pygame.mixer.init()

    print("i should not be here right now")

elif platform == "darwin":
   print("this is a mac")
elif platform == "win32":
   print("this is a windows machine")
   import pygame
   pygame.mixer.init()

config1 = ConfigParser()

# setup for increasing page count
updatePage = 1
page = "page" + str(updatePage)
root = "root" + str(updatePage)
bgimage = 'bgimage' + str(updatePage)

### these are the config things that should only be setup once
config1.read("config1.ini")
comport = config1.get('general', 'comport')
win_res = config1.get('general','win_res')
hardware = config1.get('general', 'hardware')
pins = config1.get('general', 'pins')
state = config1.get('general', 'state')

Then, here is the beginning of my config (which works otherwise):
[general]
hardware =
pins = 11,12
state = 0
usb = no
comport = COM9
win_res = 1920x1080

And I was using a .desktop entry earlier but switched it to this bash for now:
#!/bin/bash

python3.9 /home/pi/KeymasterGame/keymaster.py

As you'll notice, the python script begins to run until it hits the ConfigParser actually looking through the config1.ini file. Yet, it does not behave like this when I simply run the python script manually.
Comment: you need to paste your code and error log so other people could help you
Comment: A thing I've noticed about configparser is that, if the file doesn't exist, it loads an empty config rather than complaining about it. Another thing is that files are located relative to your current directory, not the script's directory.
Comment: @Ouroborus hmm is there maybe a way to point it towards that specific directory? So I wouldn't have gotten an error when I declared   config1.read("config1.ini")   ?
Comment: I guess I could change the directory of where the bash is calling the python script from? or put it in the same as the python script
Comment: Yep, that worked! Made a bash file that changed the directory to the appropriate folder, then the bash called the python script. Made a desktop shortcut that called the bash file. Worked! Thank you for the insight. I was at a dead end.
Answer: Edit:

line 46, in
comport = config1.get('general', 'comport')

configparser.NoSectionError: No section: 'general'

Does this help if you're adding if/else condition?
config1.read("config1.ini")
if config1.has_section('general'): # <== Add this
    comport = config1.get('general', 'comport')
    win_res = config1.get('general','win_res')
    hardware = config1.get('general', 'hardware')
    pins = config1.get('general', 'pins')
    state = config1.get('general', 'state')


Is there a shortcut for System.out.println on Netbeans?

Question: I have seen that on Ecplise you can type sysout and then the shortcut will change to System.out.println();
I was wondering if there was a shortcut like this for Netbeans(currently 8.1).
Comment: "sout' is the keyword.

Additionally, if "soutv" it would look something like below.

`System.out.println("something = " + something);`
Answer: Type "sout" then hit tab.
See https://netbeans.org/project_downloads/usersguide/shortcuts-80.pdf
Comment: Hi @Dimi as this is your first question, you must know: if this or any answer has solved your question please **consider [accepting it](http://meta.stackexchange.com/q/5234/179419) by clicking the check-mark.** This indicates to the wider community that you've found a solution and **gives some reputation to both the answerer and yourself**. Of course, there is no obligation to do this. And IMO this should be the accedpted answer because is prior to mine.
Comment: The link is now https://netbeans.apache.org/tutorials/70/nbm-code-template.html and for other ide stuff https://netbeans.apache.org/kb/docs/java/editor-codereference.html
Answer: Just write:
sout + tab
SOURCE.
Comment: Or you can just type  some part of the code you would like to use and hit ** Ctrl + Space **
Comment: @HasS NetBeans is not Eclipse ;) autocomplete exists, but netbeas has it's owns codetemplates rules


What does "pairwise p-value" mean without any specified tests?

Question: I am reading a paper that reports "pairwise p-value"s. If someone reports "pairwise p-value" for 4 pair of values without telling anything about the performed statistical tests, does this make any sense? Is there an assumption of a specific test that automatically comes with the "pairwise p-value" terminology?

Additional info from my comment below: The authors of the paper mention that they are testing whether the mean of the first set in the pair is smaller than the mean of the second set in the pair. Maybe then "pairwise p-value" automatically means the p-value from a paired t-test since t-test is the simplest thing to test for whether the means of two pair of values are different or not?
Comment: Is the author perhaps implying a multiple testing correction has been applied (e.g. Bonferroni)?
Comment: I think there are no multiple hypothesis here, just one, so I think they don't mean Bonferroni. They mention that they are testing whether the mean of the first set in the pair is smaller than the mean of the second set in the pair. Maybe then "pairwise p-value" automatically means the p-value from a paired t-test since t-test is the simplest thing to test for whether the means of two pair of values are different or not?
Answer: Without mention of the type of test performed and without multiple 'pairs' of comparisons, a 'pairwise $p$-value' could describe any $p$-value arising from a test for location shift between two groups. Most commonly, this is a $t$-test, which compares means (as you pointed out in the comments, means are compared). Other tests for location shift include non-parametric alternatives, such as the Wilcoxon rank sum test.
Since you mentioned the author indicates testing for whether one group is smaller than the other, this would be the $p$-value of a one-sided test. But it could still be a paired/ unpaired, equal variance/Welch $t$-test or even a different test entirely.
Pairwise vs Paired
The word pairwise refers to the pair of groups being compared, so without further information, I do not believe there is a reason to assume this concerns a paired test, where both samples are measurements from the same group.
Edit
As David Ernst pointed out, the use of pairwise instead of paired may simply have been a mistake on the author's side.
Comment: Perhaps mention more explicitly the possibility that the author of the paper got the notions of paired and pairwise confused or made a simple typo.
Answer: It does make sense, but there's not much information:

You know the author made four pairwise tests, but you don't know they are independent or not
You don't know anything about the null hypothesis
You can't assume any specific  test, there're many pairwise tests in statistics!

Generally, it means something like post-hoc test in ANOVA (https://onlinecourses.science.psu.edu/stat200/node/158) in the litetature, but you should double check.
Comment: I edited my question. They are in fact comparing means, they state that. Does that modify your response?


What are the solutions for the following equation?

Question: I have the following equation:
$\log_{2x}4x+\log_{4x}16x=4$
What are the solutions of this equation?
This is what I did:
Firstly, I applied the following conditions:
$2x>0 \Rightarrow x>0$
$2x \ne 1 \Rightarrow x \ne \dfrac{1}{2}$
$4x>0 \Rightarrow x>0$
$4x \ne 1 \Rightarrow x \ne \dfrac{1}{4}$
$16x > 0 \Rightarrow x > 0$
Considering all of these at once, I have: $x \in (0, + \infty) \setminus \bigg\{\dfrac{1}{2}, \dfrac{1}{4} \bigg \}$
Next, I wrote the equation like so:
$\log_{2x}(2x*2) + \log_{4x}(4x*4)=4$
$\log_{2x}2x + \log_{2x}2 + \log_{4x}4x+\log_{4x}4 = 4$
$1 + \log_{2x}2 + 1 + \log_{4x}4 = 4$
$\log_{2x}2 + \log_{4x}4 =2$
$\log_{2x}2 + 2\log_{4x}2=2$
$\log_{2x}2 + \dfrac{2}{\log_{2}4x}=2$
$\log_{2x}2 + \dfrac{2}{\log_2 2 + \log_2 2x}=2$
$\log_{2x}2+\dfrac{2}{1+\dfrac{1}{\log_{2x}2}}=2$
Then I used the substitution $\log_{2x}2=t$
$t+ \dfrac2{1+ \dfrac{1}{t}}=2$
$...$
$t^2+t-2=0$
$(t+2)(t-1)=0$
In the case that $t=-2$,
$\log_{2x}2=-2$
$(2x)^{-2}=2$
$\dfrac{1}{4x^2}=2$
$x^2= \dfrac{1}{8}$
$x = \pm \dfrac{1}{2 \sqrt{2}}$, but because of our conditions: $x = \dfrac{1}{2 \sqrt{2}}$
And in the case that $t=1$,
$\log_{2x}2=1$
$2x=2$
$x=1$
So, in the end I got: $x \in \bigg \{ \dfrac{1}{2 \sqrt{2}}, 1 \bigg \}$. The only problem with this is that it is completly wrong...
My textbook says that the correct answer should be: $\bigg [ \dfrac{1}{2 \sqrt{2}}, 2 \bigg ]$. So you see I'm not even close, I need an interval of values, not just $2$ solutions like I got. So, where did I make mistakes and what should I do to get the right answer?
Comment: You are completely right. (I also checked the answer in Maple). There is a mistake in the textbook (or in the question).
Comment: Just plug in $2$ or $1.5$ into the original equation, and you see that the given solution is wrong. Yours is fine.
Comment: To be fair, I suspect the textbook meant to write the two solutions $\{\frac{1}{2\sqrt 2}, 2\}$, and not an interval. Still wrong though.
Comment: Your answer is correct and the textbook is wrong.

You may want to have a look at [this plot](http://www.wolframalpha.com/input/?i=plot%28log_%7B2x%7D%284x%29%2Blog_%7B4x%7D%2816x%29%2C%204%2C%20x%3D0..2%29).
Comment: By the way, another pretty clean way to solve it is to rewrite all the log's in terms of $\log_2$. I.e. use $\log_a(x) = \frac{\log_2(x)}{\log_2(a)}$.
Comment: I'm curious how you figure the book having one of two values at $2$ while you have $1$ and you both having the other one the same is "completely wrong" and "not even close".  "purple monkey dishwasher" is "not even close", having one number off by a factor of $2$ is a small mistake somewhere.
Comment: @fleablood Well, it's not just that. I got those $2$ numbers as solutions, but the textbook gave an *interval* as solutions. That is why I said that my answer is completly wrong. Granted, I probably exaggerated.
Answer: As mentioned in the comments, your answer is perfectly correct and the textbook is the one which is wrong. You can check this by substituting the values in. Another way to see that it certainly cannot be an interval of solutions is by noticing that the equation $$\log_{2x}2+\log_{4x}4=2,\tag{1}$$
which is equivalent to the given one, has a LHS which changes with $x$, and on no interval $[a,b]$ is it constant. So it is absurd that there can be an interval on which the LHS is constant at $2$.
I will say though that in questions involving the logarithm like this one, a smart general approach is to convert everything to the same base. So starting from $(1)$, write
$$\frac{1}{1+\log_2(x)}+\frac{2}{2+\log_2(x)}=2,$$
and then substitute $y=\log_2(x)$ to solve for $y$ and hence for $x$. This is slightly cleaner than your solution, but of course yours is correct too.


How to format Javascript Fetch API output

Question: The REST API that I'm using returns data in the following format:
data:1
data:2
data:3

I would like to display the output in the following format instead:
123

This is how I'm making an API call using Javascript Fetch (with test url as an example):
let url = "https://jsonplaceholder.typicode.com/todos/" // test url
  fetch(url)
    .then(response => response.json())
    .then(data => {
      let htmlOutput = document.getElementById("htmlOutput");
      // parsing the JSON value to string
      htmlOutput.value = JSON.stringify(data);
    })

How can I format the output that I get when I make a call to an API, the way I want?
Answer: htmlOutput.value = data.map(e => e.data).join('');

const data = [{ data: 1 }, { data: 2 }, { data: 3 }]
const result = data.map(e => e.data).join('');

console.log(result);
Comment: Updated the answer + included a snippet, does that work?


VBA-Excel Import Issue re: file name

Question: A brief description of what I'm trying to do:

Import data from multiple .csv files into a single workbook with multiple sheets.

Description of the problem I'm encountering:

The suffixes of the original .csv data files change daily (the database automatically adds the date the report was run as a suffix as integers [e.g. today's date would be a suffix of 03182019]).
I've created the below macro to locate the requisite file and then offer an InputBox in order to manually enter the suffix (report date as integers). This code works perfectly and largely meets my needs, but I would like to eliminate the need to manually enter the suffix since the macro will be importing 15 separate workbooks. As a result, I would have to enter the suffix 15 times - once for each of the original .csv files.
Dim otherWB As Workbook, ThisWS As Worksheet
Dim sFileName As String
Dim sBase As String
Dim sExt As String
Dim sSuffix As String

Sheets("AJP EGC").Select
Set ThisWS = ActiveSheet

sBase = "/Users/plum/Downloads/AJP EGC "
sExt = ".csv"
sSuffix = InputBox("Enter suffix for filename")

sFileName = sBase & sSuffix & sExt
Workbooks.Open FileName:=sFileName

Set otherWB = ActiveWorkbook

Application.ScreenUpdating = False

ActiveSheet.Range("A1").CurrentRegion.Copy
Destination:=ThisWS.Range("A1")

otherWB.Close False
ThisWS.Activate

Set ThisWS = Nothing
Set otherWB = Nothing

Application.ScreenUpdating = True

As noted above, this macro works fine but I have to enter the suffix manually. I've tried variations of this code in order to eliminate the need to manually enter the suffix since the original .csv files are always downloaded to the same location on my computer. Here's the new code I tried:
    Dim otherWB As Workbook, ThisWS As Worksheet
    Dim sFileName As String
    Dim sBase As String
    Dim sExt As String

    Sheets("AJP EGC").Select
    Set ThisWS = ActiveSheet

    sBase = "/Users/plum/Downloads/AJP EGC "
    sExt = ".csv"

    sFileName = Dir(sBase & "*" & sExt)
    Workbooks.Open FileName:=sFileName

    Set otherWB = ActiveWorkbook

    Application.ScreenUpdating = False

    ActiveSheet.Range("A1").CurrentRegion.Copy
    Destination:=ThisWS.Range("A1")

    otherWB.Close False
    ThisWS.Activate

    Set ThisWS = Nothing
    Set otherWB = Nothing

    Application.ScreenUpdating = True

When I run this code, I get the following Run-time error:

This image of the Run-time error shows that the correct suffix has been selected and I've verified that this is the exact name of the correct file to be imported; however, the error indicates it is not able to locate the file on my computer. When I select 'Debug' in the error box, it takes me to the following line:
Workbooks.Open FileName:=sFileName

When I hover over FileName:=sFileName after clicking 'Debug', the correct file name again shows, though it does not include the directory location...just the file name. The files have not changed location, and as I said, when I run the first code I provided that prompts the user to manually enter the suffix, it finds the files without issue.
I have also tried to change the sSuffix = InputBox in the original code to sSuffix = "*" which returns the same run-time error related to the FileName:=sFileName snippet. Again, the correct file name is shown in the run-time error message.
I'm not sure what I'm missing here and feel like it's got to be something painfully obvious. Would appreciate any insight you could offer. I'm a relative noob to VBA and have exhausted Google and this site in an effort to figure out the issue.
Comment: Change ``/`` to ``\``
Answer: The Dir() function returns the name of a file and also its extension type.
To fix the problem, try:
sFileName = Dir(sBase & "*" & sExt)
sFileName = sBase & sFileName

Comment: You all rock - thanks so much for your help. Figured it was something painfully obvious. Changed code per your suggestions and it worked perfectly. Here's the fixed code:
    `sFileName = Dir(sBase & "*" & sExt)
    sBase = "/Users/plum/Downloads/"
    sFileName = sBase & sFileName

    Workbooks.Open FileName:=sFileName`
Comment: "AJP EGC" will be part of both `sBase` and the result of `Dir`; I think you want just the `/Users/plum/Downloads/` portion of `sBase`

VBA-Excel Import Issue re: file name


Why is the Pearson correlation 1 when only two data values are available?

Question: I am trying to obtain a Pearson correlation between 6 different variables (represented by columns in the matrix below) with two datapoints each (rows).
This is the matrix:
<code>     scer       bay      par       mik      glab       lac
var1 2.2273444 2.0923416 2.044007 1.7664921 1.3832924 2.4294228
var2 0.3000878 0.2792936 0.286928 0.3246768 0.4946222 0.3083171
</code>
When I apply the standard R code for correlation:
<code>cor(mat)
</code>
I obtain the following result:
<code>     scer bay par mik glab lac
scer    1   1   1   1    1   1
bay     1   1   1   1    1   1
par     1   1   1   1    1   1
mik     1   1   1   1    1   1
glab    1   1   1   1    1   1
lac     1   1   1   1    1   1
</code>
If I add another two rows to the original matrix:
<code>                scer       bay       par       mik      glab       lac
var1    2.2273444 2.0923416 2.0440068 1.7664921 1.3832924 2.4294228
var2    0.3000878 0.2792936 0.2869280 0.3246768 0.4946222 0.3083171
var3    1.1399738 1.2899311 1.1071462 1.0180361 1.4507592 2.4078977
var4    0.7107440 0.6415944 0.7197905 0.7357125 0.4571745 0.3173547
</code>
and re-execute the above code with the new matrix, I obtain a more familiar result:
<code>          scer       bay       par       mik      glab       lac
scer 1.0000000 0.9895959 0.9991065 0.9967358 0.7860344 0.8246286
bay  0.9895959 1.0000000 0.9916464 0.9890492 0.8647974 0.8958393
par  0.9991065 0.9916464 1.0000000 0.9991332 0.7928330 0.8310776
mik  0.9967358 0.9890492 0.9991332 1.0000000 0.7845007 0.8235245
glab 0.7860344 0.8647974 0.7928330 0.7845007 1.0000000 0.9978420
lac  0.8246286 0.8958393 0.8310776 0.8235245 0.9978420 1.0000000
</code>
Why does the correlation function return a matrix of 1s if I use 2 values?
Comment: Please start sentences with capital letters and end them with appropriate punctuation. And use "I" when that's what you mean. Writing otherwise may be quicker or seem cuter, but it just makes questions more difficult to read, which is not in your interest.
Comment: @whuber in hindsight i agree with you, i will fix the title and the text. i wasn't sure if the matrix of 1s were really a result or some sort of erroneous output due to the fact that the correlation could not be performed correctly.
Comment: the statistical question is whether there is some inherent limitation in calculating Pearson correlation with only 2 datapoints.
Comment: This is actually the answer i was looking for, thank you. I will mark it as such if you post it.
Comment: There really isn't a clear question here. Although you ask for a reason why you cannot "perform Pearson correlation," you actually have done so, as evidenced after "obtained the following result." From the comments it sounds like you should change the entire text of your question to read "Why is the Pearson correlation $\pm 1$ when only two distinct data values are available?"
Comment: It's correct; just inevitable and not useful. By the way, don't be fooled by your output into reporting correlations to 7 decimal places. 2 or 3 d.p. fit most purposes.
Comment: yes, i see the point now. as for the 7 decimal places, it's a byproduct of having copied the raw output of R. should i edit it?
Comment: As you say, it's what R shows you. I would leave it as it is.
Answer: Correlation, meaning Pearson correlation, can be thought of as a numerical answer to the question: Is there a linear relationship between two variables?
If you have two distinct data points, the only possible correlation result is $+1$ or $-1$, because two such points define a perfect linear relationship.
This matches the observation that a straight line can be found to interpolate two distinct points exactly.
The only choice is between a rising and a falling straight line, which give $+1$ or $-1$ respectively.
(If your two points are identical on either of the two variables, the correlation is indeterminate.)
In scientific terms, a correlation involving just two points is useless by itself.
Comment: Stated another way: Pearson's correlation coefficient between two random variables $\zeta$ and $\eta$ will be +/-1 when you can find an $a$ and $b$ such that $\zeta = a + b \eta$. This can be easily done if you only have one sample for each variable by setting $a$ as the difference between the two variables.
Comment: @Nathan You need an extra condition $b \ne 0$. Otherwise the correlation is also 0.
Answer: Besides Nick's intuitive and graphical explanation, I believe it is valid to also point out a mathematical one. Consider two variables with two positive observations each:
$X = \{x_1, x_2\}$
$Y = \{y_1, y_2\}$
Now let's calculate the standard deviation of $X$:
$S_X = \sqrt{\frac{\sum{X^2} - n\bar{X}^2}{n - 1}} = \sqrt{\frac{x_1^2 + x_2^2 - 2\frac{(x_1 + x_2)^2}{2^2}}{2 - 1}} = \sqrt{x_1^2 + x_2^2 - \frac{1}{2}(x^2 + 2x_1x_2 + x^2)} = \sqrt{\frac{1}{2}(2x_1^2 + 2x_2^2 - x_1 - 2x_1x_2 - x_2)} = \sqrt{\frac{1}{2}(x_1^2 + x_2^2 - 2x_1x_2)} = \sqrt{\frac{1}{2}(x_1 - x_2)^2} = \frac{1}{\sqrt{2}}(x_1 - x_2)$
That means the standard deviation of $Y$ is equal to $\frac{1}{\sqrt{2}}(y_1 - y_2)$.
Now let's calculate the covariance of $X$ and $Y$:
$S_{XY} = \frac{\sum{XY} - n\bar{X}\bar{Y}}{n - 1} = \frac{x_1y_1 + x_2y_2 - 2\frac{(x_1+x_2)}{2}\frac{(y_1+y_2)}{2}}{2 - 1} = x_1y_1 + x_2y_2 - \frac{1}{2}(x_1+x_2)(y_1+y_2) = \frac{1}{2}(2x_1y_1 + 2x_2y_2 - x_1y_1 - x_1y_2 - x_2y_1 - x_2y_2) = \frac{1}{2}(x_1y_1 + x_2y_2 - x_1y_2 - x_2y_1) = \frac{1}{2}(x_1y_1 + x_2y_2 - x_1y_2 - x_2y_1)$
The correlation between $X$ and $Y$, $R_{XY}$, is defined as follows:
$R_{XY} = \frac{S_{XY}}{S_XS_Y} = \frac{\frac{1}{2}(x_1y_1 + x_2y_2 - x_1y_2 - x_2y_1)}{\frac{1}{\sqrt{2}}(x_1 - x_2)\frac{1}{\sqrt{2}}(y_1 - y_2)} = \frac{(x_1y_1 + x_2y_2 - x_1y_2 - x_2y_1)}{(x_1 - x_2)(y_1 - y_2)} = \frac{(x_1y_1 + x_2y_2 - x_1y_2 - x_2y_1)}{(x_1y_1 + x_2y_2 - x_1y_2 - x_2y_1)} = 1$
If you define some of those values as negative so that the covariance would yield some negative products, the correlation would be -1. Compare, for instance, the following results in R:
<code>> cor(c(1, 2), c(3, 4))
[1] 1
> cor(c(1, 2), c(-3, -4))
[1] -1
> cor(c(1, 2), c(-3, 4))
[1] 1
> cor(c(1, -2), c(-3, 4))
[1] -1
> cor(c(-1, -2), c(-3, -4))
[1] 1
</code>
Comment: (1) Why do you assume the $x_i$ and $y_j$ are positive in your example? (2) The calculation threatens to obscure the essential point. It can be avoided by noting that the *standardized* values of the $x_i$ are $\{1,-1\}$ and the standardized values of the $y_j$ are the same. The correlation, by definition, is the average product. Depending on how the $x_i$ are associated with the $y_j,$ all products are either $1$ or $-1$, QED.
Comment: Thank you both for your constructive answers and discussions. i really appreciate it.
Comment: @whuber, (1) I assumed positive values to make the covariance calculations easier and to be in line with the OP data; I hope my last paragraph is enough to shed a light on cases with negative values. (2) You're right, my answer is more convoluted than it needs to be, and I appreciate your observation on the standardized values. However, I feel my basic-yet-verbose approach contributes to the discussion and might even be easier to understand for some folks.
Comment: @whuber What do you mean by standardized value? Because I thought that for $x_i$ that is $\frac{x_i - μ_x}{\sigma_x}$, but then that is  $\frac{1}{\sqrt{2}}$ and not 1?
Comment: @user106860 It doesn't matter how you standardize, but the result is immediate when you use the empirical standard deviation (for which the values are $\pm 1$ as I claimed) rather than the standard deviation estimator.


An easy computation of the laplacian of $\lvert{f(z)\rvert}^2$ for a holomorphic function $f$.

Question: I'm reading Narasimhan's book "Complex Analysis in one complex variable" ($2$nd ed).
After proving the weak form of the Maximum Principle (p. $25$, Theorem $3$), he applies the result to the function $u(z)=\lvert{f(z)\rvert}^2=f(z)\overline{f(z)}$, and gets the equality (p. $26$, $2$nd row):
$$\frac{\partial^2 \lvert{f\rvert}^2}{\partial z \partial\overline{z}}=\frac{\partial f}{\partial z}\cdot \frac{\partial \overline{f}}{\partial \overline{z}}.$$
Recall that $\frac{\partial}{\partial z}=\frac{1}{2}(\frac{\partial}{\partial x}-i \frac{\partial}{\partial y})$ and $\frac{\partial}{\partial \overline{z}}=\frac{1}{2}(\frac{\partial}{\partial x}+i \frac{\partial}{\partial y})$ by definition.
After many long computations (and a lot of time spent on it), I hope someone can help me to prove this apparently easily derived equality.
Please, tell me if I need to elaborate further my question.
Comment: $\frac{\partial^2\overline{f}}{\partial z\partial\overline{z}}=0$ since it is $\frac{\partial}{\partial z}\frac{\partial \bar f}{\partial \bar z}$ and $\frac{\partial \bar f}{\partial \bar z}$ is antiholomorphic still (or directly using that an anti-holomoprhic function like a holomorphic function for that matter is harmonic and that the second order partial derivative above is the Laplacian up to a factor)
Comment: apply the product rule first say to $\frac{\partial (f \bar f)}{\partial z}$ and then to the partial wr to $\bar z$ noting that $\frac{\partial \bar f}{\partial z}=0$ since $f$ holomorphic and same for $\frac{\partial f_z}{\partial {\bar z}}=0$ since $f_z$ is holomoprhic too
Comment: $\frac{\partial(f\overline{f})}{\partial\overline{z}}=\frac{\partial f}{\partial\overline{z}}\overline{f}+f\frac{\partial\overline{f}}{\partial\overline{z}}.$ Now, $f$ holomorphic implies $\frac{\partial f}{\partial\overline{z}}=0$, hence the $\frac{\partial(f\overline{f})}{\partial\overline{z}}=f\frac{\partial\overline{f}}{\partial\overline{z}}$. Now, $\frac{\partial}{\partial z}(f\frac{\partial\overline{f}}{\partial \overline{z}})=\frac{\partial f}{\partial z}\frac{\partial\overline{f}}{\partial \overline{z}}+f\frac{\partial^2\overline{f}}{\partial z\partial\overline{z}}$. But...
Comment: ... second order derivative does not vanish, right?
Answer: $$\frac{\partial }{\partial z}\left(\frac{\partial }{\partial \overline{z}}f\overline{f}\right)=\frac{\partial}{\partial z}\left(f\frac{\partial \overline{f}}{\partial z}\right)=\frac{\partial f}{\partial z}\cdot\frac{\partial \overline{f}}{\partial \overline{z}},$$
because $\frac{\partial f}{\partial \overline{z}}=\frac{\partial \overline{f}}{\partial z}=0$ from Cauchy-Riemann equation.


How to transform the structure of xml document using xslt

Question: Here my XML doc :
<?xml version="1.0" ?>
<ArrayOfPrimitiveParameter xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <PrimitiveParameter>
        <Name>field</Name>
        <Value xsi:type="xsd:string">TNA</Value>
    </PrimitiveParameter>
    <PrimitiveParameter>
        <Name>date</Name>
        <Value xsi:type="xsd:dateTime">2011-12-14T00:00:00</Value>
    </PrimitiveParameter>
</ArrayOfPrimitiveParameter>

And I want to transform its structure in :

  TNA
  2011-12-14T00:00:00

for the moment, I wrote this :
<xsl:stylesheet version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns="http://www.w3.org/TR/REC-html40"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:xsd="http://www.w3.org/2001/XMLSchema"
                >
  <xsl:output method="xml" encoding="utf-8"/>
  <xsl:template match="/">
    <Parameters>
      <xsl:apply-templates/>
    </Parameters>
  </xsl:template>

  <xsl:template match="ArrayOfPrimitiveParameters">

      <xsl:if test="PrimitiveParameter/@xsi:type = 'xsd:string'">
        <StringParameter>
          <xsl:attribute name="name">
            <xsl:value-of select='PrimitiveParameter/name' />">
          </xsl:attribute>
          <xsl:value-of select='PrimitiveParameter/value'/>
        </StringParameter>
      </xsl:if>

      <xsl:if test="PrimitiveParameter/@xsi:type = 'xsd:dateTime'">
        <DateParameter>
          <xsl:attribute name="name">
            <xsl:value-of select='PrimitiveParameter/name' />">
          </xsl:attribute>
          <xsl:value-of select='PrimitiveParameter/value'/>
        </DateParameter>
      </xsl:if>

    </xsl:template>
</xsl:stylesheet>

but the output of my XML is that :
<?xml version="1.0" encoding="utf-8"?><Parameters xmlns="http://www.w3.org/TR/REC-html40" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">

        field
        TNA

        date
        2011-12-14T00:00:00

</Parameters>

Thank you for your help,
Florian
Answer: Try with the below XSL.
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns="http://www.w3.org/TR/REC-html40"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
            >
<xsl:output method="xml" encoding="utf-8"/>
<xsl:template match="/">
  <Parameters>
    <xsl:apply-templates/>
  </Parameters>
</xsl:template>

<xsl:template match="PrimitiveParameter">

    <xsl:if test="Value/@xsi:type='xsd:string'">
      <xsl:element name="StringParameter">
        <xsl:attribute name="name">
          <xsl:value-of select="Name" />
        </xsl:attribute>
        <xsl:value-of select="Value" />
      </xsl:element>
    </xsl:if>

    <xsl:if test="Value/@xsi:type='xsd:dateTime'">
      <xsl:element name="DateParameter">
        <xsl:attribute name="name">
          <xsl:value-of select="Name" />
        </xsl:attribute>
        <xsl:value-of select="Value" />
      </xsl:element>
    </xsl:if>

  </xsl:template>
</xsl:stylesheet>


Lost connection to MySQL server during query

Question: I am trying to import our old database into a new databsae on our test server however I keep coming accross this error:
"Lost connection to MySQL server during query".
As you can see below I have tried starting the server with increased values for read timeout and wait timeout. Plus I
have increased max_allowed_packet = 1024M
[root@DB-01 alexl]# /etc/init.d/mysql start
Starting MySQL (Percona Server). SUCCESS!
[root@DB-01 alexl]# mysql -hlocalhost magento < magento.sql
ERROR 2013 (HY000) at line 15235: Lost connection to MySQL server during query

The sql file is ~7gig but need it all.
Any help is appreciated.
+-----------------------------+----------+
| Variable_name               | Value    |
+-----------------------------+----------+
| connect_timeout             | 10       |
| delayed_insert_timeout      | 300      |
| have_statement_timeout      | YES      |
| innodb_flush_log_at_timeout | 1        |
| innodb_lock_wait_timeout    | 50       |
| innodb_rollback_on_timeout  | OFF      |
| interactive_timeout         | 28800    |
| lock_wait_timeout           | 31536000 |
| net_read_timeout            | 6000     |
| net_write_timeout           | 6000     |
| rpl_stop_slave_timeout      | 31536000 |
| slave_net_timeout           | 3600     |
| thread_pool_idle_timeout    | 60       |
| wait_timeout                | 28800    |
+-----------------------------+----------+

| max_allowed_packet          | 1024M    |

Comment: And what is written on the MySQL log at the time of the crash?
Comment: There must be something else.  1) Does the connection drop immediately or after a while?  2) Please post the MySQL log file.  3) It might be that the magento database is corrupted, please try `mysqlcheck -hlocalhost -uroot -p --check --all-databases` and post all lines that are not OK.
Comment: No issues with tables via `mysqlcheck`.
Comment: The connection takes about 10 mins to drop.
Comment: Have you tried to examine if your server is running out of memory when executing the 7 Gig file. Try increasing the RAM size or swap file and see if you get the same error.
Answer: The value of max_allowed_packet is too small. You can overwrite it in an import by running mysql --max_allowed_packet=7500M magento < magento.sql or by editing the my.cnf file and restarting MySQL as explained here.
Comment: Still dropping connection


ImageIO timeout javaj

Question: I have an ImageIO read function that will be slower when the downloaded image is larger or on a slow server.  I there a way to have timeout on ImageIO?  Say max 10 seconds or I cancel the download?
BufferedImage  image = ImageIO.read(url);

The above function I want to complete in 10 seconds or cancel.
Answer: You could call your read method in a Callable object and submit it with executor service to get Future object. something like:
public class MyImageCallable implments Callable..
    //..
    public void call()..
      //here your download image

On future object you could call get with 10 seconds time out and once time out reaches, your request get cancelled. Something like:
Future<..> f = executorService.submit(/* MyImageCallable object */);
try {
    g.get.. 10 seconds..
} ..

ImageIO timeout javaj


Using Material Icons with Styled Components

Question: Just started playing around with Styled Components. Is there a way to style third party icons such as Material Design Icons? This is the code I have so far but obviously it isn't working. Relavant code is below Content component Thanks!
const MaterialIcon = (props) => account_balance;

const Icon = styled(MaterialIcon)`
  background-color: green;
  font-size: 50px;
`;

const CheckThisOut = props => (
  <Wrapper>

{props.title}

      <Icon />

    <Divider />
    <Content>

5% of all participants in this campaign were first time users.

    </Content>
  </Wrapper>
);

export default CheckThisOut;

Answer: For the styled(AnyComp) notation to work AnyComp needs to accept the incoming className prop and attach it to a DOM node.
For your example to work MaterialIcon has to use the passed in className, otherwise the styles are injected but no DOM node is targeted:
const MaterialIcon = (props) => (
  <i className={`material-icons ${props.className}`}>account_balance
);

// WORKS
const Icon = styled(MaterialIcon)`
  background-color: green;
  font-size: 50px;
`;

See our documentation page about styling any component for more information!
Answer: I know this is an old post, but here's another way to write it as a single expression. Using styled components' .attrs() (see docs) for the class name and the CSS ::after selector for the icon name.
const ThumbUp = styled.i.attrs(() => ({ className: "material-icons" }))`
  background-color: green;
  font-size: 50px;
  &:after {
    content: "thumb_up";
  }
`;

Writing this in a more generic way will allow you to use it for any of the available icons. This makes use of styled component ability to adapt based on props (see styled components docs for more info).
const MaterialIcon = styled.i.attrs(() => ({ className: "material-icons" }))`
  background-color: green;
  font-size: 50px;
  &:after {
    content: ${props => props.iconName || "help"};
  }
`;

Which you could then use like this:
<MaterialIcon iconName="check" />


Dropbox not uploading the changed files frequently

Question: I have installed the dropbox and linked with eclipsed workspace but I have found that file which is on server is old one. I have made many changes using control s and its not saving
or is there any way by which I can manually click on sync now.
or any other software
Comment: This should probably be on http://webapps.stackexchange.com - there is currently no migration path to this site.
Comment: Maybe this is just me being weird, but it scares the hell out of me just to think that some people use DropBox for their source code.
Answer: I have noticed with dropbox that sometimes a file will not update, this happens a lot with my password safe file if I have it open on more then one machine. Could this be your problem?
It may not open if something is locking the file.
Answer: It happens to me frequently on Windows 7. Most of the times it is solved by exiting Dropbox (click on the Dropbox icon and select "exit") and then restarting drop-box again (find Dropbox in your start menu and select it).
Sometimes it will not sync even with a system restart, and I assume that there is some lag in the Dropbox infrastructure causing that.


Android udp multicast fail with permission denied

Question: I encounter a problem when trying broadcast udp packet.
08-22 16:36:13.359 E/UDPTester.UDPEndpoint( 3657): IOException : Permission denied
08-22 16:36:13.359 W/System.err( 3657): java.net.SocketException: Permission denied
08-22 16:36:13.369 W/System.err( 3657):     at org.apache.harmony.luni.platform.OSNetworkSystem.send(Native Method)
08-22 16:36:13.369 W/System.err( 3657):     at dalvik.system.BlockGuard$WrappedNetworkSystem.send(BlockGuard.java:308)
08-22 16:36:13.369 W/System.err( 3657):     at org.apache.harmony.nio.internal.DatagramChannelImpl.send(DatagramChannelImpl.java:359)
08-22 16:36:13.369 W/System.err( 3657):     at zexing.udptester.UDPEndpoint.broadcast(UDPEndpoint.java:151)
08-22 16:36:13.369 W/System.err( 3657):     at zexing.udptester.MainActivity.onClickBroadcast(MainActivity.java:162)
08-22 16:36:13.369 W/System.err( 3657):     at java.lang.reflect.Method.invokeNative(Native Method)
08-22 16:36:13.369 W/System.err( 3657):     at java.lang.reflect.Method.invoke(Method.java:507)
08-22 16:36:13.369 W/System.err( 3657):     at android.view.View$1.onClick(View.java:2155)
08-22 16:36:13.369 W/System.err( 3657):     at android.view.View.performClick(View.java:2501)
08-22 16:36:13.369 W/System.err( 3657):     at android.view.View$PerformClick.run(View.java:9107)
08-22 16:36:13.369 W/System.err( 3657):     at android.os.Handler.handleCallback(Handler.java:587)
08-22 16:36:13.369 W/System.err( 3657):     at android.os.Handler.dispatchMessage(Handler.java:92)
08-22 16:36:13.369 W/System.err( 3657):     at android.os.Looper.loop(Looper.java:130)
08-22 16:36:13.369 W/System.err( 3657):     at android.app.ActivityThread.main(ActivityThread.java:3835)
08-22 16:36:13.369 W/System.err( 3657):     at java.lang.reflect.Method.invokeNative(Native Method)
08-22 16:36:13.369 W/System.err( 3657):     at java.lang.reflect.Method.invoke(Method.java:507)
08-22 16:36:13.369 W/System.err( 3657):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:847)
08-22 16:36:13.369 W/System.err( 3657):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:605)
08-22 16:36:13.369 W/System.err( 3657):     at dalvik.system.NativeStart.main(Native Method)

In AndroidManifest.xml, I already add these permission.
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>

Also, I get the multicast lock before broadcast
// create multicast lock @ Activity.onCreate
mcastLock =  wifiManager.createMulticastLock("zexing.udptester.Multicast");

// acquire multicast lock during broadcast
mcastLock.acquire();
if (mcastLock.isHeld()) {
    Log.i(TAG, "held multicast lock");
}
udpEndpoint.broadcast(msg, port);
Log.v(TAG, "broadcast " + msg + " to port : " + port);
Log.d(TAG, "Release wifi Multicast lock to enable wifi UDP broadcast");
mcastLock.release();

// UdpEndpoint.broadcast
public void broadcast(String msg, int port) {
    try {
        if (broadcastChannel == null) {
            Log.v(TAG, "opening write DatagramChannel");
            broadcastChannel = DatagramChannel.open();
            Log.v(TAG, "config write channel to non-blocking");
            broadcastChannel.configureBlocking(false);
            Log.v(TAG, "reuse address");
            broadcastChannel.socket().setReuseAddress(true);
            Log.v(TAG, "set broadcast to true");
            broadcastChannel.socket().setReuseAddress(true);
            Log.v(TAG, "register broadcast Channel");
            broadcastChannel.register(selector, SelectionKey.OP_READ);
            Log.v(TAG, "register broadcast channel successfully");
        }
        if (msg.length() == 0) {
            Log.w(TAG, "message to broadcast is null, skip sending");
        }
        SocketAddress addr = new InetSocketAddress(InetAddress.getByName("255.255.255.255"), port);
        Log.v(TAG, "allocate " + msg.length() + " bytes. msg.getBytes().length = " + msg.getBytes().length);
        ByteBuffer bb = ByteBuffer.allocate(msg.length());
        bb.clear();
        bb.put(msg.getBytes());
        bb.flip();
        Log.v(TAG, "write channel broadcast " + msg + " to " + addr);
        int bytes = broadcastChannel.send(bb, addr);
        Log.v(TAG, "broadcast " + bytes + " bytes to " + addr);
    } catch (UnknownHostException uhe) {
        Log.e(TAG, "UnknownHostException : " + uhe.getMessage());
    } catch (IOException e) {
        Log.e(TAG, "IOException : " + e.getMessage());
        e.printStackTrace();
    }
}

Comment: Did you resolve this problem?
Answer: Try sending broadcast to subnet´s broadcast address example: 192.168.1.255 instead of 255.255.... aditionally make sure your port is major than 1024 or just port 0 and the system will chose one for you


Passar variavel javascript para Django Form

Question: Tenho um formulario Django com esse campo "Exame vinculado" que funciona da seguinte forma: O usuario clica em Selecionar Exame, vai para outra janela em que seleciona um exame ja existente, e com isso retorna para a pagina de criacao de modo que a url informa o exame que foi selecionado (ex: http://127.0.0.1:8000/exam/create?exam_index=23201 indica que o exame 23201 foi selecionado e deve ser vinculado).

Assim, eu gostaria de, ao voltar para a tela com o exame selecionado, exibir esse id no campo (atualmente, se eu digitar um valor e clicar em salvar funciona, o que esta faltando e isso de preencher).
Tambem ja consigo pegar esse id da seguinte forma:
var param = /exam_index=([^&#=]*)/.exec(window.location.search);
var exam_id = param[1];

Tentei utilizar o "getElementById" mas nao estou conseguindo:

                 Exame Vinculado
                    {{form.linked_exam}}

                     Selecionar Exame

Como posso fazer isso?
Comment: Onde esta o input com o id `linked-exam-field`? Você esta a pegar a `div`? Não entendi muito bem.
Comment: Vc esta oferecendo muito pouco para alguem tentar ajudar, veja se consegue criar um [exemplo mínimo, completo e verificável](https://pt.stackoverflow.com/help/mcve), fazendo esse esforço, é bem provável que vc mesma resolva seu problema, ah! da uma olhada no final [dessa resposta](https://pt.stackoverflow.com/a/190406/7412), nos links.
Answer: No Html:

{{form.linked_exam}}

No script:
document.getElementById("linked_exam").innerText = exam_id;

Primeiro: no seu código você está capturando a label em vez do campo em si, logo para pegar o campo, foi posto uma tag quanquer e posto o id para assim o js pegar o objeto correto. Caso continuasse pegando a label, o código script iria sobrescrever a label.
Segundo: Seu código js estava quase certo, a lógica que falta entender é a seguinte: O getElementX pega o elemento html completo, ou seja, ele usa o X para encontrar o elemento que deseja porém ele te retorna atributos, valores, class, name e etc... O uso do console.log é um grande aliado para entender e selecionar o elemento que deseja trabalhar, no seu caso que é escrever dentro do html, o elemento que quase sempre funciona é o "innerText", porém existem outras opções como o "innerHtml", vai depender muito de como foi feito, renderizado o html.
Comment: Considere adicionar uma breve explicação para a sua solução.


Specral Radius stability condition

Question: A Multi-Input Multi-Output system with stable transfer matrix $L(s)$ is considered.
The theorem states that if $\rho(L(j\omega)<1$ then the closed-loop system is stable.
In place of the actual theorem its reverse is proved: if the closed-loop is unstable (that is the Nyquist plot of $\det(I+L(s))$ does encircle the origin) then there exists an eigenvalue $\lambda_i(L(j\omega))$ which is larger than $1$ at some $\omega$.
The textbook says: if $\det(I+L(s))$ does encircle the origin then there must exists a gain  $\epsilon \in (0, 1]$ and a frequency $\omega'$ such that:
$$\det(I+\epsilon L(j\omega'))=0$$
I really cannot figure out the reason why this holds.
Comment: what is $L$ in terms of the representation $\dot{x} = Ax + Bu$? I'm assuming the system is LTI because otherwise the Nyquist criterion doesn't apply.
Comment: @ALB $L$ is the loop gain of the MIMO feedback system, that the product of all the transfer functions (Laplace transforms, so LTI system of course) in the loop (feedforward and feedback paths). For the sake of simplicity, it is assumed the $L(s)$ is the transfer function of the direct path, while the feedback is unitary: in this case the (matrix) transfer function between the reference input and the output is $\frac{Y(s)}{R(s)} = L(s)\left( I+L(s) \right)^{-1}$
Comment: I'm in the process of writing a answer, but just to be 100% clear, the system is LTI with A, B ,C ,D as usual and introduces the state feedback $u(t) = K(r-x)$, making $L = (sI-A)^{-1}BK$. This is the state realization of the diagram which closes the loop around unity inverting FB in the feedback path and preamplifies it by the LTI gain $K$ before feeding into the plant.
Answer: This is the standard homotopy argument. The closed curve
$$
\gamma_\epsilon(\omega)=\det(I+\epsilon L(j\omega))
$$
depends continuously on $\epsilon$ and $\omega$ (the property of determinant). We know that for $\epsilon=1$ it encircles the origin at least once, and for $\epsilon=0$ it reduces to the point $(1,0)$ which does not encircle the origin. Therefore, due to continuity, the origin must escape from the area inside the curve to the outside at some $\epsilon'\in(0,1)$, that is for this $\epsilon'$ the origin must lie exactly on the curve $$\gamma_{\epsilon'}(\omega')=0.$$
Comment: Very clever, I was starting to think to something similar.

Specral Radius stability condition


Difference between action and strategy in game theory

Question: In the normal-form game below, the strategy set is $\{L,R\}$ for each players and $p_1$ denotes player $1$'s payoff and $p_2$ denotes player $2$'s payoff. Are the two games exactly the same? Does the change make any difference?
Game $1$:

$\begin{matrix} &&& \text{ Player } 1 && \\ & &L & &R \\&L &(p_1, p_2) &&(p_1, p_2) \\ \text{Player } 2\\ &R &(p_1, p_2) & &(p_1, p_2)  \end{matrix}$

Game $2$:

$\begin{matrix} &&& \text{ Player } 2 && \\ & &L & &R \\&L &(p_1, p_2) &&(p_1, p_2) \\ \text{Player } 1\\ &R &(p_1, p_2) & &(p_1, p_2)  \end{matrix}$

My second question is: What is the difference between actions and strategies? Can you please explain using this example? I think the strategies are simply $\{L,R\}$, but what about the actions? Can we write actions properly for infinite games?
Note: There's a slight abuse of notation as I wrote $p_1$ and $p_2$ instead of $p_1^{(i,j)}$ and $p_2^{(i,j)}$ (or something else) for the payoffs.
Answer: As for the first question, in the book which I used for studying, the first players was always put at the left, and the second at the top, so following this notation, in the game 2 the payoff vectors should be (p2,p1).
As for the second question, the strategy set for a player is the set of all strategies that the player can choose, in this case, the set of strategies for the player 1 is {L,R}. A profile of strategies is a vector that has a strategy of each player, in this case: (L,L), (R,L), (L,R) and (R,R). I didn't use the word action, but I suppose it depends on the book that you're reading.


Multiple plots in the same axis in plotly

Question: I'm trying to draw plots using the plotly where all of them share the same axis.
This is one dataset
  X variable       value
1 1       SH 0.002814895
2 1       VH 0.002591173
3 1       SS 0.002599700
4 1      HCG 0.002810790

and this is its plotly graph
plot_ly(rr1, x=~variable, y=~value, type = 'scatter', marker=list(size=10, color='rgba(255,182,193,0.9)',
    line=list(color='rgba(152,0,0,0.8)', width = 2)), name = "Character and Degree")%>%
 layout(title = "Graph", font = list(family = "Arial Black"),yaxis=list(zerolinecolor = toRGB("red"),
                                                                     gridcolor = "rgb(190,190,190)"), xaxis=list(gridcolor = "rgb(190,190,190)")) %>%
 layout(plot_bgcolor='rgb(230, 230, 230)',paper_bgcolor='rgb(220, 220, 220)',
     font = list(color = 'rgb(100,100,100)'))

and this is the other dataset
   X variable       value
 1 1       SH 0.000982607
 2 1       VH 0.000917569
 3 1       SS 0.000911039
 4 1      HCG 0.000971009

and this is its plot
     plot_ly(rr2, x=~variable, y=~value, type = 'scatter', marker=list(size=10, color='rgba(38,182,193,0.9)',

     line=list(color='rgba(75,0,0,0.8)', width = 2)), name = "Character and Degree")%>%
  layout(title = "Graph", font = list(family = "Arial Black"),yaxis=list(zerolinecolor = toRGB("red"),
                                                                     gridcolor = "rgb(190,190,190)"), xaxis=list(gridcolor = "rgb(190,190,190)")) %>%
   layout(plot_bgcolor='rgb(230, 230, 230)',paper_bgcolor='rgb(220, 220, 220)',
     font = list(color = 'rgb(100,100,100)'))

I want these two graphs to share the same axis leaving the colours as it is.
Answer: You can merge the two dataframes and use two add_markers, one for each value column:
df1 <- read.table(text="X variable       value
1 1       SH 0.002814895
2 1       VH 0.002591173
3 1       SS 0.002599700
4 1      HCG 0.002810790", header=TRUE)

df2 <- read.table(text="   X variable       value
 1 1       SH 0.000982607
 2 1       VH 0.000917569
 3 1       SS 0.000911039
 4 1      HCG 0.000971009", header=TRUE)

df12 <- merge(df1, df2, by=c("X","variable"))

library(plotly)

plot_ly(df12, x=~variable) %>%
  add_markers(y=~value.x, type = 'scatter') %>%
  add_markers(y=~value.y, type = 'scatter')

But the y-axis title and the legends are not nice:

So, modify them:
ax <- list(
  title = "Value",
  titlefont = list(
    family = "Arial, sans-serif",
    size = 18,
    color = "Red"
  ),
  showticklabels = TRUE
)

plot_ly(df12, x=~variable) %>%
  add_markers(y=~value.x, type = 'scatter', name="value1") %>%
  add_markers(y=~value.y, type = 'scatter', name="value2") %>%
  layout(yaxis=ax)

Comment: Thank you. Is there a way to change the shape and the color of the dots and add lines around the dot
Comment: @AyeshaPerera You're welcome. Look at [here](https://plot.ly/r/marker-style/) for the borders around the dots and the color. I have not found for the shape yet.
Comment: @ Stéphane Laurent Thank you very much for the complete answer


how to filter a listView in an Activity

Question: i want to filter the tasks to show by what the user will choose in the check boxes,but when i run this code there is an error.
this is the functions in the filter activity
enter code here
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_filter);
    INITIALIZE();
    DONE();
}

public void INITIALIZE()
   {

Go=(Button)findViewById(R.id.go);
ProH=(CheckBox)findViewById(R.id.pro1);
ProM=(CheckBox)findViewById(R.id.pro2);
ProL=(CheckBox)findViewById(R.id.pro3);
Finished=(CheckBox)findViewById(R.id.finished);
NotFinished=(CheckBox)findViewById(R.id.notfinished);
Past=(CheckBox)findViewById(R.id.past);
Future=(CheckBox)findViewById(R.id.future);

}
public void DONE()
{
final AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
Go.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View arg0) {
        // TODO Auto-generated method stub

        if((proH==1&&proM==1)||(proM==1&&proL==1)||(proH==1&&proL==1))
        {
            alertbox.setTitle("Error!");
            alertbox.setMessage("Please Choose one Priority");
            alertbox.setNeutralButton("ok",new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub
                }
            });
             alertbox.show();
             ProH.setChecked(false);
             ProM.setChecked(false);
             ProL.setChecked(false);
        }
    }
});}}

what it the error here?
Comment: You should share the error you're seeing. What does logcat say?
Comment: 01-24 21:51:33.931: E/AndroidRuntime(309): FATAL EXCEPTION: main
01-24 21:51:33.931: E/AndroidRuntime(309): android.content.ActivityNotFoundException: No Activity found to handle Intent { act=com.example.todolist.FILTER }
01-24 21:51:33.931: E/AndroidRuntime(309):  at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1408)
01-24 21:51:33.931: E/AndroidRuntime(309):  at android.app.Instrumentation.execStartActivity(Instrumentation.java:1378)
01-24 21:51:33.931: E/AndroidRuntime(309):  at android.app.Activity.startActivityForResult(Activity.java:2817)
Comment: this is part of the error, but when i click on l filter button in the main activity to open this activity it forse quit
Comment: show your main activity.
Comment: Filter.setOnClickListener(new View.OnClickListener() {

   @Override
   public void onClick(View arg0) {
    // TODO Auto-generated method stub
    Intent filter=new Intent("com.example.todolist.FILTER");
    startActivity(filter);
    finish();
   }
  });
 }
Answer: Judging by your error in the comments, the problem is you're using an Intent that isn't caught by any intent-filter.
"No Activity found to handle Intent { act=com.example.todolist.FILTER }"
Fix your intent-filters, or launch your FilterActivity a different way.
You can explicitly launch Activities with something like
Intent intent = new Intent(context, FilterActivity.class);
context.startActivity(intent);

Where 'context' might be your Activity (this)
Comment: how to launch my FilterActivity a different way.??
Comment: Here's a good page to read through:

http://developer.android.com/guide/components/intents-filters.html

how to filter a listView in an Activity


Format integer in ASP.NET

Question: I have a difficult time to format integer in asp script
The format of the integer right now is ######. I would like to format it to ####-##. For ex: Format 201602 to 2016-02. Can anyone help me on this? Thanks much!
    <asp:DropDownList ID="From" runat="server" DataSourceID="ShipDate"DataTextField="intYearMonth"> <asp:ListItem Text="" Value="0"/> </asp:DropDownList>

Comment: any way you can actually store it as 2 separate values or as a `DateTime`? your way seems risky.
Answer: You can accomplish this after everything loads with a For Each...
Note - No error checking here you may want to handle that...
For Each item As ListItem In DropDownList1.Items
   item.Text = item.Insert(4, "-")
Next

Output - 2016-02

Format integer in ASP.NET


Weak convergence - $f_n$ "goes up the spout"

Question: Fix $1 < p < \infty$. Given $f \in L^p(\mathbb{R})$ define $f_n(x) = n^{1/p}f(nx)$ for $n = 1, 2, \dots$. Prove that $f_n$ converges weakly to $0$ in $L^p$.
I'm really confised about this question. I know that I have to show that for every $g \in L^{p'}(\mathbb R)$, $\int_{\mathbb{R}} f_ng \to 0$, but I can't even visualize why $f_n$ would go to $0$ using any convergence. How do I "see" that things converge weakly? Also, how would I prove something like this?
Comment: Just an idea: You may choose a dense subset of $L^{p'}$. Take characteristic functions of intervals (Or compactly supported smooth testfunctions). Use the transformation formula (this rescales the interval) and see what happens.
Comment: For the visualization, try it for a single example.  For instance, $f(x) = \frac{1}{1+x^2}$ is in $L^2$.  Then $f_n(x) = \frac{\sqrt{n}}{1 + n^2x^2}$ tends to $0$ for each $x$ as $n\to\infty$.
Comment: @DavidMitra Edited it, sorry.
Comment: @MatthewLeingang It makes sense why it converges to $0$ in that specific example, but I still don't see why it converges for every $f$.
Answer: Warning: very loose answer, just for intuition purposes.
The function is integrable over all of $\Re$.  That means the as $|x| \rightarrow \infty$,$f(x) \rightarrow 0$.  The function sequence looks like f(nx).  That means for every $x \neq 0$, $nx \rightarrow \infty$, so $f(nx) \rightarrow 0$ as $nx \rightarrow \infty$.  Now for the $n^{1/p}$.  Let's look at p=1.  If n*f(nx) did not go to zero, then f(x) would look like 1/x going to infinity. But the integral of that does not converge.
Comment: Thank you! This is exactly the kind of answer I wanted.
Comment: This is indeed good intuition, but readers should note that several of the statements in this answer are *false*.  For instance, it is possible for a function to be integrable but not vanish at infinity.