Way to insert statement in oracle-db (Node-js)

Question: I am developing a web application. I am encountering difficulties to construct a sql statement to insert in a table. Other statements like select are working. I utilized oracle db for the connection.
This is the snippet for creating insert statement
<code>  async setAuditLogReprocessData( action, transaction_sequence, user) {

    const bindVars = {
      AUDIT_LOG_ID: AUDIT_LOG_ID_SEQ.NEXTVAL,
      AC: action,
      TRANSACTION_SEQUENCE: transaction_sequence,
      USER_ID: user
    };

    const sql = "AUDIT_LOG_ID, ACTION, TRANSACTION_SEQUENCE, USER_ID";

    let result;
    try {
      result = await this._database.simpleExecute(
        `INSERT INTO TABLE1 ${sql}
        VALUES (AUDIT_LOG_ID_SEQ.NEXTVAL, AC, TRANSACTION_SEQUENCE, USER_ID)`,
        bindVars
      );
    } catch (err) {
      this._logger.error("Could not add audit trail.", err);
      throw new TxnError(500, `Audit Trail error. ${err.message}`);
    }

    return result;

</code>
This is the code for database.js
<code>  simpleExecute(statement, binds = [], opts = {}) {
    return new Promise(async (resolve, reject) => {
      let conn;

      opts.outFormat = oracledb.OBJECT;
      opts.autoCommit = true;

      try {
        conn = await oracledb.getConnection();

        const result = await conn.execute(statement, binds, opts);
        resolve(result);
      } catch (err) {
        reject(err);
      } finally {
        if (conn) { // conn assignment worked, need to close
          try {
            await conn.close();
          } catch (err) {
            this._server.getLogger().log(err);
          }
        }
      }
    });
  }
</code>
Thank you so much for your help.
Answer: Generally speaking, it's helpful if you show the error message you're getting when you want help solving a problem. I'll take a shot at helping since there are some obvious mistakes.
First, you don't have any bind variables defined in your SQL statement. Bind variables are defined by putting a semicolon in front of the bind variable name. So your call to simpleExecute should look like this:
<code>      result = await this._database.simpleExecute(
        `INSERT INTO TABLE1 ${sql}
        VALUES (AUDIT_LOG_ID_SEQ.NEXTVAL, :AC, :TRANSACTION_SEQUENCE, :USER_ID)`,
        bindVars
      );
</code>
Note that the statement above has three bind variables: AC, TRANSACTION_SEQUENCE, and USER_ID. I didn't make AUDIT_LOG_ID_SEQ.NEXTVAL a bind variable because the value you're inserting is supposed to come from the sequence.
I'm guessing you want the value that was inserted into the AUDIT_LOG_ID column. For that, you need to define an "out" bind variable (the default is in) and then use the RETURNING clause to get the value.
Your bind variable definition would look like this:
<code>    const bindVars = {
      AUDIT_LOG_ID: {
        dir: oracledb.BIND_OUT,
        type: oracledb.NUMBER
      },
      AC: action,
      TRANSACTION_SEQUENCE: transaction_sequence,
      USER_ID: user
    };
</code>
Then you'd need to update your SQL to this:
<code>      result = await this._database.simpleExecute(
        `INSERT INTO TABLE1 ${sql}
        VALUES (AUDIT_LOG_ID_SEQ.NEXTVAL, :AC, :TRANSACTION_SEQUENCE, :USER_ID)
        RETURNING AUDIT_LOG_ID into :AUDIT_LOG_ID`,
        bindVars
      );
</code>
Try making those changes and let us know what you get.


Can you recursively run Virtual Machines

Question:
Possible Duplicate:
Is it possible to setup a virtual machine inside another virtual machine

A VM inside of a VM?
Comment: 'Cos you've watched Inception one too many times ;-)
Comment: @Gaius...so...you bluescreen each WinVM in succession to get back to the host?
Comment: Have a look at this SF question http://serverfault.com/questions/46960/is-it-possible-to-setup-a-virtual-machine-inside-another-virtual-machine
Comment: Why do you want to?
Answer: The ServerFault question is slightly out of date, and I only know the answer for the VMware platform. Short answer: yes, with restrictions. The latest versions of Workstation and ESX support running the latest version of ESX inside a VM for demonstration purposes. You can then build up a guest VM and run that from inside the guest ESX instance. You do need to edit the VM config though to turn on some advanced options.
Here's some info: http://www.vcritical.com/2009/05/vmware-esx-4-can-even-virtualize-itself/
Again, VMware does support this configuration, but only for demonstration purposes.
Comment: There's talk that it is also possible with VirtualBox too.
Answer: Not seriously. YOu can with software simulation (slow). But hardware virtualization (fast) only supports ONE layer. Because noone seriously needs more.
Answer: I have had success in running ESX under fusion 2.0, with several VMs but as other have mentioned it did require a bit of tweaking to get it running. I assume this is mostly for testing so I can see the reasons for doing it as was with my case. I cant imagine anyone doing this for production.
Also, as someone did point out it does require a bit of resources but I was able to manage all this on a mac pro with 4GB.
HTH
Answer: You can but you would be highly limited to resources. I recommend VirtualBox for something like this... and a lot of RAM


Use the Holder inequality to show that $f \ast g \in C_c(G)$

Question: Let $G$ be a locally compact abelian group, and let $f \in L^p(G), g \in L^q(G)$.  I'm trying to prove that $f \ast g \in C_0(G)$.  The book I'm reading (Rudin, Analysis on Groups) gives the following sketch of the proof:
Since $C_c(G)$ is dense in the $L^p$ spaces, there exist sequences $f_n \in L^p(G), g_n \in L^q(G)$ such that $||f - f_n||_p, ||g - g_n||_q \to 0$.  It suffices then, to show that $f_n \ast g_n$ converges to $f \ast g$ uniformly.  Since $f_n \ast g_n \in C_c(G)$ (we've already proved that $C_c(G)$ is closed under convolution), this will imply that $f_n \ast g_n \to f \ast g$ in the sup norm.  Since $C_c(G)$ is dense in $C_0(G)$, the claim will follow.
But, I don't see why $f_n \ast g_n \to f \ast g$ uniformly.  Rudin claims that this follows from the Holder inequality, but I'm having trouble making it work.
Comment: Yes, it is.  Most certainly (adding characters because of the minimum length.)
Comment: Is $\frac 1p + \frac 1q = 1$?
Answer: I'm not sure the following works. Please double check and let me know if I am wrong.

We have, for $x \in G$,
\begin{align}
|f_n*g_n(x)-f*g(x)| & = |f_n*g_n(x) - f*g_n(x) + f*g_n(x) - f*g(x)| \leq \\
& \leq |f_n*g_n(x) - f*g_n(x)| + |f*g_n(x) - f*g(x)| \leq \\
&  \leq|(f_n - f)*g_n(x)| + |f*(g_n-g)(x)| \leq \\
& \leq \|f_n-f\|_p\|g_n\|_q + \|f\|_p\|g_n-g\|_q \leq \\
& \leq M\|f_n-f\|_p + \|f\|_p\|g_n-g\|_q \to 0.
\end{align}
where we used the fact that $g_n$ is bounded in $L^q$ (since it is convergent) and that $f_n \to f$ in $L^p$ and $g_n \to q$ in $L^q$.
Since the final line goes to zero uniformly in $x$ the convergence is uniform. Moreover we have used the fact that $L^p$ norm is invariant under translation.
Comment: You're right.  I figured out this answer right after I posted the question :)


Finding the limit of a sequence that is convergent involving square roots

Question: Let $s_1 = \sqrt{6}$, $s_2 = \sqrt{6 +\sqrt{ 6 }}$, $s_3 = \sqrt{6 + \sqrt{6 +\sqrt {6} }}$, and in general define $s_{n + 1}= \sqrt{6 + s_n}$ . Prove that $(s_n)$ converges, and find its limit.
I know that the first part can be proved by theorem because our sequence $s_n$ is monotone increasing, but $s_n$ is bounded by induction if we choose an appropriate k in real numbers.
However, how does one find its limit.
Comment: Solve $s^2=s+6$, $s\gt0$
Answer: Algorithm for testing a sequence for convergence
Welcome to MSE, and I recently answered a similar question here.
From the stage that we know a limit exists, we can recognize that since $\lim_{n->\infty}s_{n+1}=\lim_{n->\infty}s_n$, $\lim_{n->\infty}s_n$ satisfies $s = \sqrt{6+s}$. From that, we get $s^2=6+s$, as J.W.Tanner suggested in his comment. We solve for the limit with a solution to this quadratic.
I hope this helps in your studies :)
Comment: Hahaha, I think this helps quite a bit
Answer: As you point out, the limit exists since $s_{n+1}>s_n$ and $s_n<3$. The first claim is apparent and the second follows by induction, since if $s_n<3$ then $s_{n+1}=\sqrt{6+s_n}<\sqrt{6+3}=3$.
Now that we know the limit exists, let $L$ denotes its value. Then necessarily $L=\sqrt{6+L}$, from which we see that $L\geq 0$ and also $L^2=6+L$. Thus $(L-3)(L+2)=0$ and so $L=3$.


Comparison of data to ground truth

Question: Anyway, I have paired distributions of values, all between 0 and 1 and I want to compare them.  One is simulated data, and is thus the 'truth' and I would like to compare how closely the other sets of data match this and also quantify which is the most similar. So, for example:
<code>truth<-c(0.1,0.2,0.3,0.4,0.45,0.5,0.55,0.6)

set1<-c(0.1,0.21,0.36,0.5,0.45,0.57,0.55,0.62)

set2<-c(0.08,0.2,0.36,0.57,0.45,0.54,0.56,0.62)
</code>
I thought about a simple correlation test and $R^2$ value to compare different pairs, but ultimately this would be testing how closely data points are grouped around an inferred regression line, which I don't think is what I want.  Because I know one of them is the 'truth' I really want to test how well the data points group around $x=y$.  Is there an obvious test for comparing whether set1 vs truth is a better match than set2 vs truth?
Answer: You could define any metric you like to decide whether a candidate is better than another. The most popular is the sum of squared errors (I'm going to call the truth $T$ and the candidates $X$ and $Y$):
$$SSE_X = \sum_{i=1}^{n_X} \left( X_i - T_i \right)^2$$
$$SSE_Y = \sum_{i=1}^{n_Y} \left( Y_i - T_i \right)^2$$
Whichever SSE is smaller is the one that is "closest", in the sense of Euclidean distance, to the truth.
EDIT: I'm using MATLAB but I get answers $SSE_{X}=0.019$ and $SSE_Y=0.035$, so the first set is "better" according to your defined rule of betterness. Now, the Mean Squared Error is also a possible rule; the Mean Absolute Deviation, the Mean Percentage Error: there's a whole host of metrics you can use.
Comment: Thanks very much for the reply.  So what test would I use to see whether the first model is statistically a better fit than the second one?
Comment: @Alan it depends what type of data you have and what you believe the generating distribution to be. Can you assume that your data are Gaussian (normal)?
Comment: yes, I believe I can assume that they are normal and independent.
Comment: @Alan, the most straightforward method would be to compare the [MSE](https://en.wikipedia.org/wiki/Mean_squared_error#Predictor) values for each candidate. The set with the lower MSE is the desired approximation of "truth". Mathematically,
$$MSE_X = \frac{1}{n_X}\sum_{i=1}^{n_X} (X_i -T_i)^2 \ \ \ \text{and} \ \ \ \ MSE_Y = \frac{1}{n_Y}\sum_{i=1}^{n_Y} (Y_i -T_i)^2$$

Comparison of data to ground truth


Android Bluetooth - Can't connect out

Question: I am developing an application which uses Bluetooth to connect to a device and send/receive data. I am doing all of my testing with a Nexus One phone.
I have never been able to establish a SPP (serial port) connection from my phone to any device. However, I have been able to connect from a device (my laptop) to my phone using a Mac equivalent of PuTTY (The only exception to this is the "Bluetooth File Transfer" app from the Marketplace seems to work, but I don't think that uses RFCOM/SPP...).
I keep seeing this message in my LogCat logs:
ERROR/BluetoothService.cpp(78): stopDiscoveryNative: D-Bus error in StopDiscovery: org.bluez.Error.Failed (Invalid discovery session)

as well as these:
java.io.IOException: Operation Canceled
java.io.IOException: Software caused connection abort

I have tried using the UUID of "00001101-0000-1000-8000-00805F9B34FB" and I have also tried using the:
Method m = device.getClass().getMethod("createRfcommSocket", new Class[] { int.class });
sock = (BluetoothSocket) m.invoke(device, Integer.valueOf(1));

method instead of device.createRfcommSocketToServiceRecord(UUID); as well--with no luck.
I am using the BluetoothChat example and variations of that code to do all of my testing...
Solutions or suggestions would be great...or even a better/less complex example of some testing code I can run on the phone, or a python script or something I can run on my computer to help debug?
Thanks! I hope this isn't a bug with the Android OS, but if it is I hope to find a workaround.

EDIT: I should also note that most devices show up as "paired, but not connected" in the Bluetooth settings.

EDIT 2: The solution seems to be simply disabling any Bluetooth listening. See my answer post for more information.
Comment: Other noteworthy topics related to this issue:
1)
http://stackoverflow.com/questions/2268365/android-bluetooth-cross-platform-interoperability
2)
http://stackoverflow.com/questions/2661932
3)
http://groups.google.com/group/android-developers/browse_thread/thread/348c269f2ef88327/
4)
http://stackoverflow.com/questions/2660968/how-to-prevent-android-bluetooth-rfcomm-connection-from-dying-immediately-after
5)
http://stackoverflow.com/questions/1953888/bluetooth-rfcomm-sdp-connection-to-a-rs232-adapter-in-android
Comment: did you use reflection with intent or by coincidence? The reason I ask is, I'm wondering if you used it as a way to work around a particular bug in the Bluetooth implementation? Ordinarily I would think one could have just used `BluetoothSocket bs = createRfCommSocket(...`. Thanks!
Comment: @Brad - It was intentional, because I have seen several people online having issues with createRfcommSocketToServiceRecord which were only resolved by using this unusual workaround.

See: http://stackoverflow.com/questions/2660968/how-to-prevent-android-bluetooth-rfcomm-connection-from-dying-immediately-after --and-- http://stackoverflow.com/questions/2661932/problem-with-bluetooth-on-android-2-1-samsung-spica-i5700-where-pairing-works-b
Answer: The solution, as it turns out, was to disable the server functionality of the Bluetooth service. By only using createRfcommSocketToServiceRecord and never calling listenUsingRfcommWithServiceRecord (in the BluetoothChat example this means never starting the "AcceptThread") the problem was fixed.
Even though these two calls are supposed to be totally separated and have no affect on each other (according to the Android docs), simply commenting out listenUsingRfcommWithServiceRecord fixed my supposedly unrelated issue.
I can take the Bluetooth Chat program unedited and it will not be able to establish an outgoing connection to ANY bluetooth device I have tested (laptops, desktops, headsets, etc.), but if I remove that one thing it works flawlessly as a client.
Anyway, I hope this will help someone else if they come across the same issue. This must be a bug with the Android OS, or possibly the firmware on the Nexus One.
Comment: Same here, did not work. Using same example and Nexus S +Galaxy tab
Comment: Disabling listening for connections does not make it work for me.  How would that even work?...

I get this issue occasionally but making it not start the accept thread makes it consistently not work.
Answer: I would ignore the stopDiscovery error - its good that you're cancelling discovery before making your connection. Per the SDK docs:

Because discovery is a heavyweight
  precedure for the Bluetooth adapter,
  this method should always be called
  before attempting to connect to a
  remote device with connect().
  Discovery is not managed by the
  Activity, but is run as a system
  service, so an application should
  always call cancel discovery even if
  it did not directly request a
  discovery, just to be sure.

So with that said, were you able to get the Bluetooth Chat example to work before you made any modifications to the code?
The UUID you want for SPP/RFCOMM is:
static UUID UUID_RFCOMM_GENERIC = new UUID(0x0000110100001000L,0x800000805F9B34FBL);

or defined another way (both accomplish the same thing).
static final UUID UUID_RFCOMM_GENERIC = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

Comment: Thanks, but I am actually already using the UUID you provided.

I was able to get the Bluetooth Chat app to work, but only if I connect from my device (computer) to the phone, and not the other way around. If I try to connect from the phone to the computer (from within the application menu) it will try for a few seconds, then Toast an error like "Connection failed" or something.
Comment: Did you explicitly add an RFCOMM service on your computer? Otherwise the computer has no reason to respond to RFCOMM requests. Just as your computer wouldn't respond to FTP requests unless you installed an FTP server and opened port 21.
Comment: I'm confused - are u trying to make the bluetooth chat work between two phones or between phone and PC? I think only the former makes sense but i may not be understanding your ultimate goal. Can you clarify?
Comment: I don't have two Android phones to test this on, but I have been testing with two PCs (using PuTTY on windows and Terminal on mac) as well as a special headset device that uses SPP. It wasn't working as a client on any of them (only as a server). I have fixed the issue now, as indicated by my post.

Android Bluetooth - Can't connect out


How do I retrieve node data for a referenced node in a template file?

Question: I have two content types, Event and Gallery. Each Event has a node-reference field to a gallery. I am now trying to style the gallery node page from inside the template file. I need to have a way of creating a link which links back to its parent, the Event.
How can I find this information?
Answer: it seems you need to know value of node which is referring the current node.
I am assuming machine name for the refernce field you have on event content type as "field_event_gallery"
In your custom module or template.php
// function to get backrefernce value.
function mymodulename_get_back_refernce_value($current_nid) {
  $nids = array();
  $results = db_select('field_data_field_event_gallery','n')
            ->fields('n',array('entity_id'))
            ->condition('field_event_gallery_nid',$current_nid)
            ->execute()
            ->fetchAll();
  if(is_array($results) && count($results) > 0) {
    foreach($results as $result) {
      $nids[] = $result->entity_id
    }
  }
  return $nids;
}

Now in your theme template.php use template_preprocess_node(),something like below
function MYTHEME_preprocess_node(&$variables) {
  $node = $variables['node'];
  if ($node->type == 'gallery') {
    //get referring nids
    $referring_nids = mymodulename_get_back_refernce_value($variables['node']->nid);
   if(count($referring_nids) > 0) {
     foreach($referring_nids as $referring_nid) {
       $referring_node = node_load($referring_nid);
       $variables['parent_event_link'][$referring_nid] = l(t('View parent event: @event_title', array('@event_title' => $referring_node->title)), 'node/' . $referring_nid);
   }
  }
}

finally in your template loop through $variables['parent_event_link'] and print it.
My codes are not tested, you have to debug to make them workign for you
Comment: @user1015214 did you get check this code?
Comment: Sorry, I was having computer issues last week. Yes, the code works! Thanks! But you had a typo, it should say $results = db_select...
Comment: oh, also, I needed to change the 'n' in  fields('n',array('entity_id')) to 'eg', to match the line above
Comment: updated just an table alias :)
Answer: The best way to prepare this for template is through hook_preprocess_node() implementation.
This code should be in your theme's template.php file:
function MYTHEME_preprocess_node(&$variables) {
  $node = $variables['node'];
  if ($node->type == 'gallery') {
    // You can add new attributes to the $variables variable and they will be
    // available automatically in the node template file as direct variables.
    $variables['parent_event_link'] = l(t('View parent event: @event_title', array('@event_title' => $variables['field_gallery_event'][0]['node']->title)), 'node/' . $variables['field_gallery_event'][0]['nid']);
  }
}

And in your node.tpl.php or node--gallery.tpl.php file you can use:
<?php print $parent_event_link; ?>

Comment: I guess he is asking for backreference.
Comment: This wont work, there is no field_gallery_event inside of the gallery node, thats my issue.
Comment: Install devel module and check the output of `dpm($variables)` in `hook_preprocess_node()`. Are you trying to do this on single node page or somewhere else?


como faco para resolver o erro Undefined property: stdClass::

Question: Notice: Undefined property: stdClass::$nome in C:\xampp\htdocs\peliculas\Model\Cliente.class.php on line 79
Notice: Undefined property: stdClass::$id in C:\xampp\htdocs\peliculas\Model\Cliente.class.php on line 80
como faco para resolver esse erro a linha em questão do erro a 79 e a 80 são:
$_SESSION['nomeCliente'] = $row->nome;
$_SESSION['idCliente'] = $row->id;
public function logarCliente(){
      $c = new Conexao();

      $sql = mysqli_query($c->conectar(), "SELECT email, senha FROM clientes WHERE email = '{$this->getEmail()}' AND senha = '{$this->getSenha()}' AND ativo = 1");
      $c->desconectar();

      if(mysqli_num_rows($sql) > 0){
        $row = $sql->fetch_object();
        $_SESSION['nomeCliente'] = $row->nome;
        $_SESSION['idCliente'] = $row->id;
        $_SESSION['logado'] = true;

        return true;
      }else{
        return false;
      }
    }

Answer: É impossível extrair id e nome da query. Isso porque no select só foram especificadas as colunas email e senha.
Você precisa alter o select ou escolher os campos corretamente.
ACHO que você pretendia escrever a query assim:
$sql = mysqli_query($c->conectar(), "SELECT id, nome FROM clientes
                                     WHERE email = '{$this->getEmail()}'
                                     AND senha = '{$this->getSenha()}'
                                     AND ativo = 1");

Comment: nuss eu nem vi isso obg pela resp


Compare percentage increase/decrease with different sample sizes

Question: I have a question here and in need of expert advices :).
Consider:
work_week = 52.
Total no. Samples = 360
Green = 73%
Red = 0%
Yellow = 27%
work_week = 53.
Total no. Samples = 650
Green = 66%
Yellow = 29%
Red = 4%
The number samples almost doubled up from work week 52 to work week 53.
Is there any way to say the percentage of green / yellow / red increased or decreased ?
How to say whether the number of Green or Yellow or Red increased / decreased ? The sample size is different?
Answer: Given the percentages and the absolute numbers you can compute absolute numbers of counts and you can then do $\chi^2$- and Binomial inference on those numbers.
Expl. Is the decrease in Green significant? We have .73 * 360 = 263 Green in week 52 and .66 * 650 = 429 in week 53. In R:
> prop.test(x = c(263, 429), n = c(360, 650))

    2-sample test for equality of proportions with continuity correction

data:  c(263, 429) out of c(360, 650)
X-squared = 5.0244, df = 1, p-value = 0.02499
alternative hypothesis: two.sided
95 percent confidence interval:
 0.009859771 0.131251340
sample estimates:
   prop 1    prop 2
0.7305556 0.6600000

So yes, the decrease in Green was significant with $p = .024$.
One Caveat: There is a slight imperfection due to rounding: 73% out of 360 may be 262 or 263 or 264. Rounding looses information. So if you can, try to obtain absolute numbers in the first place.


Problemas com o perfil do usuario

Question: O resulta do desta página da erro:

Notice: Undefined variable: nome in C:\xampp\htdocs\Techphp\perfil.php
  on line 57,  line 58,   line 59 e    line 60,

Que são as linha onde estão os dados do perfil do usuário.
O que não entendo porque esta dando esse resultado.
Será que não esta conectado?
<?php
mysql_connect("localhost", "root", "angola") or die("cannot connect");
mysql_select_db("login_senha");

session_start();
$login =  $_SESSION['login_usuario'];

$login =  $_SESSION['login_usuario']=$login;
$sql = mysql_query( "SELECT * FROM usuario WHERE  login='$login'");
while($linha= mysql_fetch_array($sql)){
    $nome=$linha['nome'];
    $email=$linha['email'];
    $idade=$linha['idade'];
    $cidade=$linha['cidade'] ;
    $foto=$linha['foto'] ;

}
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<link rel="stylesheet" type="text/css" href="/Techphp/css/estilo.css"/>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="/Techphp/css/estilo.css"/>
<title>Untitled Document</title>

            Voltar

            Administração

      <img src="fotos/<?php echo $foto?>" alt="imagem de perfil" title="imagem de perfil"  />

Nome

<?php echo $nome?>

Email

<?php echo $email?>

idade

40<?php echo $idade?>

Cidade

<?php echo $cidade?>

Comment: Conseguiu resolver Bruno?
Answer: Você pode elaborar da seguinte forma:
<?php
    session_start();
    mysql_connect("localhost", "root", "angola") or die("cannot connect");
    mysql_select_db("login_senha");

    $login = $_SESSION['login_usuario'];
    $sql = mysql_query( "SELECT * FROM usuario WHERE  login='{$login}'");
    $linha = mysql_fetch_array($sql);

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<link rel="stylesheet" type="text/css" href="/Techphp/css/estilo.css"/>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="/Techphp/css/estilo.css"/>
<title>Untitled Document</title>

            Voltar

            Administração

    <?
    if(mysql_num_rows($sql)>0){
    ?>

      <img src="fotos/<?php echo $linha['foto']; ?>" alt="imagem de perfil" title="imagem de perfil"  />

Nome

<?php echo $linha['nome']; ?>

Email

<?php echo $linha['email'];?>

idade

40<?php echo $linha['idade'];?>

Cidade

<?php echo $linha['cidade'];?>

    <? } else {  ?>

        Este usuário não está logado ou não foi encontrado.

    <? } ?>

Lembrando que o Login está vindo da session, procure verificar também a senha dele, pra ver se bate com a senha registrada, mas neste caso ele já está logado? Não entendi bem... Mas tente elaborar conforme minha sugestão.
Comment: ok,farei essas mudanças agradeço de coração
Comment: Ok! Qualquer coisa deixe-nos saber!
Comment: ok qualquer duvida darei noticias
Comment: Foi executado nesta ordem mas ele aparece com a seguinte noticia: Notice: Undefined index: login_usuario in C:\xampp\htdocs\Techphp\perfil.php on line 6 isto não entendi ate porque na pagina logar esta a  $login = $_SESSION['login_usuario']; não estou entendendo o que eta errado na index da linha 6 onde esta registrada : $login = $_SESSION['login_usuario'];
Comment: De onde você está buscando o Login? Ele normalmente vem por session ou post ou get?
Comment: ele esta no no post:  $login = $_POST['login'];
Comment: Então, só altere $login = $_SESSION['login_usuario']; para $login = $_POST['login'];
Comment: agora ele me mostra o erro na linha 8: Notice: Undefined variable: login in C:\xampp\htdocs\Techphp\perfil.php on line 8:   $sql = mysql_query( "SELECT * FROM usuario WHERE  login='{$login}'");
Comment: Troque $sql = mysql_query( "SELECT * FROM usuario WHERE login='{$login}'"); por $sql = mysql_query( "SELECT * FROM usuario WHERE login='{$login}'") or print mysql_error();
Comment: obs:desculpe eu errei na linha ainda continua erro na linha 6 :Notice: Undefined index: login in C:\xampp\htdocs\Techphp\perfil.php on line 6: onde esta o  $login = $_POST['login'];
Comment: vou te mandar todo o processo das paginas ok,
Comment: Ok, coloque aqui na sua pergunta.
Comment: ok vou mandar  na pergunta
Answer: Troque este trecho:
$login =  $_SESSION['login_usuario'];

$login =  $_SESSION['login_usuario']=$login;

Por este:
if( !isset($_SESSION['login_usuario']))
   die('Usuario nao logado');

$login = $_SESSION['login_usuario'];

E troque este trecho:
$sql = mysql_query( "SELECT * FROM usuario WHERE  login='$login'");

Por este:
$sql = mysql_query( "SELECT * FROM usuario WHERE  login='$login'");
if(mysql_num_rows($sql) == 0 )
 die('O usuario '.$login.' não existe');

Já vai resolver, ou no mínimo te ajudar a entender o próprio codigo.

Problemas com o perfil do usuario


Testing whether variance across 6 values is significantly above zero

Question: We estimated a network via the Ising model procedure. The network contains 11 variables, and therefore 55 pairwise associations (these are called edges).
We estimated this network in 6 different samples, leading to six networks.
Our question is now whether a given edge, for instance the edge between variable 1 and 2 (one of the 55 pairwise associations in each network), varies substantially across the six networks.
For each edge, we have 6 values (the edge weight of this edge in each network), and we can compute a variance over these 6 values. We now want to test whether this variance is substantial (i.e. significant from zero).
We can also derive confidence intervals around each edge, if that is helpful. So for the edge between variable 1 and 2, we could have the values (first: edge weight; then confidence interval):
<code>network 1: 4 (CI 3-5)
network 2: 5 (CI 4-6)
network 3: 2 (CI 1-3)
network 4: 3 (CI 2-4)
network 5: 4 (CI 3-5)
network 6: 5 (CI 4-6)
</code>
How do we test whether the variance of this particular edge is significantly different from 0? (or, if that is not possible, "substantial" [I know this is open to interpretation]).
Comment: Assuming no measurement error, if the observed variance is nonzero, then it is significantly above zero (at any possible level of significance), because it *definitively* establishes the variance is nonzero. If there is a possibility of measurement error, then what quantitative information can you provide about *its* variance? This is such a strange situation that it makes one wonder whether you are asking the question you need to. Could you clarify what you really mean by "significant variability across the ... networks in [an] edge"?
Comment: That's quite a different description of the problem! Please edit your post so that readers understand what you're looking for.
Comment: Thank you. In a minor analysis of a paper, we want to establish whether the 6 networks estimated via Ising Models differ (same variables, but different samples). This is extremely demanding and worth at least a PhD project, so not feasible for this paper. So we look for simpler ways. One idea we had was determine the variability of each edge across the 6 networks, and if this variability is substantial, that provides *some* information. I could bootstrap confidence interval around each edge in each network. That would provide information about error. Would that help?
Answer: Assuming you have large set of data , the sample variance chi square distribution of data will tend to be normal , then you can use t-test to reject the null hypothesis of your variance to be zero
Comment: This recommendation is of doubtful validity. Exactly how would you apply a t-test? Why, indeed, could it be applicable at all to a null hypothesis of zero variance?  In such a case the sample variance does not have either a chi-square distribution or a normal distribution: it's constantly zero.
Comment: I thought of this as well originally, but I also believe that the assumptions would not be fulfilled.
Comment: t-test is used to test whe ~ther the mean of RV differs significantly from some value hence considering sample variance as RV ~ Normal within large sample , i thought he can use it


Increasing RAID1 (mirror) redundancy in HP Smart Array P410?

Question: Please is it possible to add a third (or more) drives to a mirror (RAID1) in P410? IIUC it would mean creating "Mirror Group 3" (or more). I could not find any way to add a new mirror group using the HP tool ssacli, the documentation only talks about expanding capacity of the mirror (i.e. adding drives to existing mirror group/s), not about increasing redundancy (i.e. creating new mirror groups). Also google search for "Mirror Group 3" returned no results.
My intention is to add a drive, finish recovery/resync, and eventually to remove one of the old drives, all while running the OS using the ssacli tool. Basically replacing the old drives with new ones while keeping redundancy all the time.
Comment: `replacing the old drives with new ones` of the same capacity? Why are you doing that?
Comment: E.g. to use a new drive with a new lifetime. The existing logical drive capacity is more than sufficient for the given use case. Thanks.
Answer: It's not possible. What you can do however is to switch your RAID card into HBA mode and use Linux MDRAID or ZFS three-way mirrors. HP P410 is an "el cheapo" RAID, so software RAIDs would give you better performance either way (+ZFS will provide you with an on-the-fly meta and metadata integrity checks).
Comment: Yes, this is correct. Two-way mirror.
Comment: Thanks. Do I understand correctly then that the P410 is only capable of 2-drive mirrors? I use MDRAID and ZFS on other servers, but this one is a machine I cannot re-install at will.


Evaluate $\lim_{x\to 0}\frac{\sin(\ln(x+1))-\ln(\sin(x)+1)}{\sin^4\frac{x}{2}}$

Question: Compute the following limit: $$L=\lim_{x\to 0}\frac{\sin(\ln(x+1))-\ln(\sin(x)+1)}{\sin^4\left(\frac{x}{2}\right)}$$
Comment: Any ideas? What have you tried?
Comment: @S.Panja-1729 Ugh.  This problem is really messy in my opinion.
Comment: I have used L'hospital rule but it was very complicated.
Answer: It's easiest to use Taylor expansions about $x = 0$. First the denominator to leading order, so we can tell how many terms are needed:
$$
\sin\left(\frac{x}{2}\right)^4 = \frac{x^4}{16} + O(x^6)
$$
So we need expansions to this order also for the numerator:
$$
\sin(\ln(x+1)) = x-\frac{x^2}{2}+\frac{x^3}{6}-\frac{x^5}{12}+O\left(x^6\right)
$$
and
$$
\ln(sin(x) + 1) = x-\frac{x^2}{2}+\frac{x^3}{6}-\frac{x^4}{12}+\frac{x^5}{24}+O\left(x^6\right)
$$
You see that the two terms in the numerator agree through order $x^3$. Hence these terms all cancel. Then the leading term in the numerator is  $\frac{x^4}{12}$. Therefore, the limit equals $\frac{1/12}{1/16} = \frac{4}{3}$.
Answer: Well, it helps to notice that the function doesn't exist for $x\le-1$.
Also, you may also notice that it doesn't exist for $\sin(x)=-1$, which results in $x\ne(2n-1)\pi, n=0,\pm1,\pm2,\pm3,\dots$
The best way I see tackling this is with L'Hospital's rule:
$$L=\lim_{x\to 0}\frac{\sin(\ln(x+1))-\ln(\sin(x)+1)}{\sin^4(\frac{x}{2})}=\lim_{x\to0}\frac{\frac{\cos(\ln(x+1))}{x+1}-\frac{\cos(x)}{\sin(x)+1}}{\cos(\frac{x}2)\sin^3(\frac{x}2)}$$
$$\lim_{x\to0}\frac{\frac{\sin(\ln(x+1))+\cos(\ln(x+1))}{(x+1)^2}+\frac{\sin^2(x)+\sin(x)-\cos^2(x)}{(\sin(x)+1)^2}}{-\frac38\cos(\frac{x}2)\sin(\frac{x}2)\sin^2(\frac{x}2)}$$
It appears obvious that this is only going to get messier... and we pretty much have to repeat this until the limit is evaluable.
At this point, I'd just say your best bet is to look at this graphically or numerically, which produces:
$$L\approx1.333$$
Answer: $$\begin{align}\sin{\log{(1+x)}} &= \sin{\left (x - \frac12 x^2 + \frac13 x^3 - \cdots \right )} \\ &= \left (x - \frac12 x^2 + \frac13 x^3 - \cdots \right ) - \frac16 \left (x - \frac12 x^2 + \frac13 x^3 - \cdots \right )^3 + \cdots \\ &= x - \frac12 x^2 + \frac16 x^3 + \left ( \frac32 \cdot \frac16 - \frac14 \right ) \frac14 x^4 \cdots\end{align}$$
$$\begin{align}\log{(1+\sin{x})} &= \log{\left (1 + x - \frac16 x^3 +  \cdots \right )} \\ &= \left ( x - \frac16 x^3 +  \cdots \right ) - \frac12 \left (x - \frac16 x^3 +  \cdots \right )^2 + \cdots \\ &= x - \frac12 x^2 + \frac16 x^3 + \left (\frac16-\frac14 \right ) x^4 \cdots\end{align}$$
Thus the limit is equal to
$$\frac{1/12}{1/2^4} = \frac43 $$
Comment: you've made a mistake! This limit is equal to $\frac{4}{3}$
Answer: Hint:
$\sin^4(\frac{x}{2})$~$(\frac{x}{2})^4$
$\sin(\ln(x+1)) = \ln(x+1)-\frac{\ln^3(x+1)}{6}+o(x^4)$
Comment: Much, much, better idea in my opinion.


Freebsd 10 install with non standard gateway route

Question: Some service providers offer dedicated/vps nodes with non standard gateways (ie not in the same subnet).
For instance : ip add 10.0.1.1/32 with gateway 18.104.22.168
For this purpose some manual steps are required since the install wizard does not accept gateways outside the main ip's subnet.
Especially something like this :
   route add 188.8.131.52 10.0.1.1
   route add default 184.108.40.206
   echo "nameserver 126.96.36.199" >> /etc/resolv.conf
   ping google.com (working now)

The problem is that regardless of functionality up to this point, when you exit the install shell or you run bsdinstall from the live environment the settings are lost and the install fails to download from various ftp mirrors.
How do i fix this ?
Answer: The penultimate step in bsdinstall asks if you would like to open a shell to make manual modifications. At this point, you could edit either /etc/rc.conf and add some suitable directives or add an /etc/rc.local with the commands listed in your question.
I tested an Auto (UFS) and an Auto (ZFS) install and both times the newly created rc.conf file was writable at:
vi /etc/rc.conf

Comment: Yes good point but it doesn't work. complains the file is read only and it is since it's the mounted iso.
Comment: @Horatiu I have updated my answer.


How to check a folder for files, or else do nothing?

Question: I inherited the following script that essentially just looks in a folder, processes the files individually, then moves them and writes to a log.
The current issue I face is that if the folder is empty, the script still creates a processing folder to move the potential files to, as well as writes to the log.   Can anyone help me modify the script such that nothing will happen if there are no files in the folder?  I know I need to do the check at the top of the script, then exit out if there are no files, but I have no experience in batch files and I am not sure how to accomplish this.
<code>@ECHO OFF

set "folder=%~1"

::HERE I NEED ADD A CHECK TO SEE IF FILES EXIST.  IF THEY DO, GO THROUGH SCRIPT.
::IF NOT, EXIT EVERYTHING

:: Set timestamp for processed folders
set TIMESTAMP=%DATE:~10,4%%DATE:~4,2%%DATE:~7,2%-         %TIME:~0,2%.%TIME:~3,2%.%TIME:~6,2%.%TIME:~9,2%

:: If more than 0 files exist begin ftp and file archival otherwise exit
FOR %%a IN (c:\Encoded_HL7_Vanderbilt\*.*) DO (

cd\"Program Files (x86)\Ipswitch\WS_FTP 12"
IF ERRORLEVEL 1 (echo %TIMESTAMP% Error switching to ftp program     directory>E:\HL7_Vanderbilt_log\%folder%\%TIMESTAMP%.error.txt
goto :done)

wsftppro -s local:%%a -d Vandy!Vanderbilt:/incoming/
IF ERRORLEVEL 1 (echo %TIMESTAMP% Error transmitting "%%a" file to ftp     server>E:\HL7_Vanderbilt_log\%folder%\%TIMESTAMP%.error.txt
goto :done)

md "E:\Processed_HL7_Vanderbilt\%folder%\%TIMESTAMP%" 2>nul
IF ERRORLEVEL 1 (echo %TIMESTAMP% Error creating archive     directory>E:\HL7_Vanderbilt_log\%folder%\%TIMESTAMP%.error.txt
goto :done)

move "%%a" "E:\Processed_HL7_Vanderbilt\%folder%\%TIMESTAMP%"
IF ERRORLEVEL 1 (echo %TIMESTAMP% Error moving "%%a" file to archive         directory>E:\HL7_Vanderbilt_log\%folder%\%TIMESTAMP%.error.txt
goto :done)

)

echo %TIMESTAMP% File transfers completed successfully or no files were         found>E:\HL7_Vanderbilt_log\%folder%\%TIMESTAMP%.success.txt
exit

:done
goto :EOF
</code>
Answer: <code>dir "%~1" /a:-d /b >nul 2>&1
if %errorlevel%==1 exit
</code>
at the very beginning.
Comment: Hmm..that didn't seem to work.   I put this code at the very top, right under the @ECHO OFF statement, but whenever I execute the .bat file, it still creates the archive folder (the 1st statement before the FOR loop) as well as writes to the success log (the last statement outside the loop) even if no files are in the directory.  Not sure if this matters, but I didn't mention it, but the .bat files is being called from another directory, not from the directory that the files are located in.
Comment: be sure to specify the full path name then, and it might be an error in antoher part of your code, because I tested this.


How to boot HP Proliant DL360 G6 with the front panel missing (no button)?

Question: I came into possession of an HP Proliant DL360 G6 that I'm looking to turn into a file server.
Unfortunately the whole power button assembly is missing (complete with front panel, power button cable, as well -of course- the button itself). That part:

Apparently it was pried long ago as a means to repair another DL360 G6
I understand that booting a board is as simple as shorting the appropriate pins. But no matter how much I've searched, apparently, HP offers no pinout map of the power button connector of their boards. I can find no replacement in logical prices either.
Here's the front IO panel connector:

Now I know two of those pins when shorted will boot the board. But I'm afraid of shorting the wrong ones lest I do any lasting damage. Lacking any pinout map do you have any idea of how I should go about booting my server / trying things safely?
After having it booted for the first time I'll set it up booting remotely so this issue will go away. It's just for this -first- time.
Also I found this thread dealing with a similar issue: Turning on HP ProLiant DL 580 G5 with broken power button?
But it had no satisfying answer, that is why I'm reposing the question.
Thanks.
Answer: I'd recommend just getting the right part or using another chassis. These servers are only worth a small amount.

It's HP part #493800-001 and is available with or without ribbon cable for a small amount of money.
Comment: Thanks, didn't think to search ebay. That's very useful to know indeed.On an irrelevant note its PSU is dying as well and found (on the same ebay store) a DL360 G5 PSU (700w) for dirt cheap as well. Do you think it will be pin compatible with DL360 G6 board?
Comment: You need to use the G6/G7 PSU.
Comment: I actually have same model/gen server in my home lab.  Chugs away with no issues.  If you find the G6 PSU, and if you can afford two, you might consider getting both.  Single PS, single point of failure.  If you have more than one server, might even be worth it to ensure they all have two, and to put an extra one in the bench stock.
Answer: You also might try sending wake-on-lan signal to the network card.  This will only work if wake-on-lan is enabled in BIOS.  It may be disabled for security reasons in some environments.
Research iLO to determine if there's a way to power the system on through iLO.  This will only work if iLO was active on the system before, and if you can get the credentials.  The default credentials are on the system tag thing you can pull out, if it's not removed.
Consider searching online for replacement front panel.  This should work unless the connections were damaged.
If an HP service tech is visiting, ask them where to look for info, or any tricks they might know to start the system.


Regex for detecting preceeding and proceeding lowercase letters and numbers

Question: I am trying to find a particular pattern in my strings and my knowledge of regex is quite basic. To find lower case letters I can use [a-z0-9]+ but how would I go about finding the preceding and proceding characters?
Allowed examples:
(A), AB, ABC, [ABC], .AB' , @ABCD#. In essence only uppercase characters(any length), or uppercase(any length) with preceding or proceding or both(front and back), special chars.
Not Allowed:
abABCaa , ABCaa , aaAB , 123ABC , 12ABGGabc , aaBaa etc. In essence uppercase letters(any length) with preceding or proceding or both, alphabets or numbers.
How can I write a regex that filters either the allowed examples or the not allowed examples?
Hope I am clear
Comment: Mate, can you please edit your question to include a list of examples of what needs to be allowed, and a list of examples that should not be allowed.  Your question is too ambiguous at this stage, apparently ;-)
Comment: How are `(BBA)` and `[BB'` valid strings?
Comment: In my applications 'special' case, having special chars before and after the uppercase is of no harm!
Comment: You mean `(` and `'` need to be allowed?  I thought you were saying your code currently allows these, but that it was wrong.  So are there any other "special" cases that need to be allowed?
Comment: Or, in other words, any string that doesn't *entirely*  consist of uppercase letters is OK?
Comment: @Sepster yea they need to be allowed!
Comment: I want to allow only uppercase letters along with any special characters, but no lower case chars or chars or numbers.
Comment: sorry about that..I will edit it.
Comment: @Salmanmahmood Updated to match! ;-)
Comment: Mate, are `aaaB` and `Baaa` valid matches or not.  Your opening paragraph suggests (to me, at least) that they are valid.
Comment: I think he described in the opening paragraph the case for what is not allowed.
Comment: @Sednus The problem is we're both _thinking_ what is/isn't allowed, he's not telling us explicitly.  Note his explicit examples don't support _either_ your interpretation OR mine! ;-)
Comment: I've -1'd this question Salman... With all due respect unless you clean up the question this record isn't going to be of any value to anyone in future looking for a similar solution; It's simply not clear what you asked (despite my attempts to get clarification). In particular, are `aaB` and `Baa` valid or not? IMO the accepted answer doesn't line up with the question, so you need to update the question to clarify either way.  I'll happily remove the downvote once this is done.
Comment: check it now and see if it makes sense. I think you misunderstood that there is only one uppercase letter per word which was not the case.
Comment: Wow.  This question is about 180 degrees from where it started ;-)  Downvote removed.  Out of interest, what's the use-case you're modelling with this?
Comment: Thanks! thats why I hate regex. One needs a regex to explain the regex he wants ;). I have got stock exchange company symbols which are always in capital form. I am getting these symbols from different RSS feeds and sometimes they are like `[TH]` `(TH)` `TH` or `TH®`. Needed to differentiate them from usual words
Answer: This will match 3 groups: the Matched uppercase, the characters preceding it and the characters after it. If groups are not desired, just remove the parenthesis.
([^a-z0-9]*)([A-Z]+)([^a-z0-9]*)

For more information about matching and grouping please refer to the proper Javadoc .
Also, a suggestion for testing regex online
Comment: My +1 for your persistence @Sednus.  Glad you got it over the line for us :-)
Comment: that was a mistake. Sorry I meant `A-Z` for uppercase letters. Thanks
Comment: One minor nitpick: `[A-Z]+` will always only match one character, so you might as well drop the `+`.
Comment: You mean that capital letters will be matched in the first group and the second group will only match one always, yes, it is true. Nice! Thanks! :)
Answer: How about simple:
\b[A-Z]+\b

That will match uppercase letters surrounded by other characters than word character
Comment: However, this will not match `[ABC]`or `(AB)`
Comment: `aaBaaa` is supposed to be a valid input
Comment: @Sednus No it's not according to his examples.
Comment: @Sednus: No it is not, see last sentence of the question.
Comment: @Sednus: no problem. But it'll be nice to remove the downvote.
Comment: Im locked. I will ASAP, I suggest you make and edit so that you unlock me
Comment: @Sednus: yes it will. It'll match all examples given by OP and not match what is unwanted.
Comment: so `\b` will match `[` or `(`?. i dont have to do something like (\\[[A-Z]+\\])|(\\([A-Z]+\\))|(\b[A-Z]+\b) . (escaping the `[]` and `()` )
Comment: But this won't cover the initial requirement outlined in the OP's first paragraph "I need to know if an uppercase letter is preceded or proceded by lowercase letters or numbers."
Comment: Also /b doesn't work as intended in Java (apparently). I tried it. It does work in Javascript for example.
Comment: @Sednus: Double escape it in java i.e. `\\b`
Comment: yes thats not working for me either. going to try your solution @Sednus
Comment: My DV removed, my interpretation of requirements was wrong with re to pre/proceeding lower-case/numbers.
Answer: It's much easier. Simply check for a match against:
"^\\p{P}*[A-Z]+\\p{P}*$"

\p{P} matches any punctuation character.
^ and $ can be dropped if you're using the .matches() method.
So this matches AAB, #A, A. and fails 1A, aAa, aA and Aa.
Comment: Does \p{P} also matches symbols like `[` , `@` , `(`?
Comment: But this won't cover the initial requirement outlined in the OP's first paragraph "I need to know if an uppercase letter is preceded or proceded by lowercase letters or numbers."
Comment: @Sepster: If there is only punctuation (or nothing) around uppercase letter, then there are no lowercase letters there. QED. That's what he wants to exclude, so if this regex matches, that requirement is fulfilled.
Comment: @TimPietzcker Ah, difference in interpretation then.  I took his statement to mean he _wants_ `aaB` and `Baa` to be valid (as he said _is_, he didn't say _is not_).  But yep, I'll remove my down-vote because that's an issue with the question, not your answer! (edit: when I'm not locked).
Comment: @Sepster: Oh well, we probably deserve it, answering a vague question like this :)
Answer: not sure this can be done with regex. try it algorithmically by comparing :

start loop all characters of the string (alpha chars):
CurCharIsUpper = (curchar.uppercase == curchar.lower) ? false: true;
if (PrevCharIsUpper == CurCharIsUpper) blahblah;
PrevCharIsUpper = CurCharIsUpper;
end loop
Comment: I believe it can be (refer my answer)... but don't disagree it might be more intuitive to do this algorithmically in certain situations.


Envio de foto com privacidade pública

Question: Através do código abaixo, consigo enviar uma foto para as fotos do usuário que está logado, e a foto é enviada com sucesso.
Porém a foto vai com privacidade Amigos.
Como faço para enviar com privacidade Público?
Bundle params = new Bundle();
/* make the API call */
params.putByteArray("source", byteArray);
params.putString("caption", "Titulo");
params.putBoolean("published", true);

new GraphRequest(AccessToken.getCurrentAccessToken(), "/me/photos", params, HttpMethod.POST, new GraphRequest.Callback() {
    public void onCompleted(GraphResponse response) {
        Log.i(TAG, response.toString());
    }
}).executeAsync();

Answer: O nível de privacidade (audência no SDK Android) é configurado quando o usuário autoriza a sua app com permissão de escrita e não pode ser mudado pelo seu aplicativo.
Quando você solicita permissão de escrita, você pode setar a audência desejada. Trecho do exemplo RPSSample que acompanha o SDK:
LoginManager.getInstance()
.setDefaultAudience(DefaultAudience.FRIENDS)
.logInWithPublishPermissions(RpsFragment.this, Arrays.asList(ADDITIONAL_PERMISSIONS));

O nível de audiência que você procura é o DefaultAudience.EVERYONE.
https://developers.facebook.com/docs/reference/android/current/class/DefaultAudience/
Comment: Perfeito, exatamente o que precisava. Obrigado!

Envio de foto com privacidade pública


Posting in Ruby leads to a 403 error

Question: I am writing a Ruby script to ingest content into Drupal 7. This is on my local machine. I'm using the Services module and its rest service to GET and POST. I could log in and grab the csrf token and the cookie information but I get a 403 error when I try to post a new node. I checked my local apache access and error logs. There were no errors listed and the access log only reports the status. This is my code so far:
<code>require "rest-client"
require "json"

node = create_node(node_hsh)
node_json = JSON.generate(node)
response = RestClient.post('localhost/drupal/restfulapi/node', node_json,
:content_type => :json,
:accept => :json,
:headers => {:cookie => cookie, 'x-csrf-token' => csrf_token}
)
</code>
I'm not sure where else to look? I would really appreciate any pointers. Thanks.
Comment: Try your webservice in postman first, https://chrome.google.com/webstore/detail/postman/fhbjgbiflinjbdggehcddcbncdddomop?hl=en
Comment: Hi, Yes, this was helpful, When I tried to post a node I get a 403:Access denied for user anonymous.
Answer: I figured it out. Posting this for documentation: I had to pass the cookie after the user had logged in to do a GET on the token (localhost/services/session/token) for the Services module. Once I had the token, I could pass the cookie and the token to do a POST of the resources. I also switched the gem from rest-client to Faraday because I could customize my headers better. Also, the logging functionality was more verbose in Faraday which was helpful in debugging.
Answer: There are a couple ways to go about POSTing data to a resource. First,
there is a handy Firefox plugin called Poster which allows the posting
of arbitrary data to specified URLs. Poster can be downloaded from here.
For Google Chrome, you can use the Advanced REST Client extension found here.
It is fairly simple to use and it remembers your last entry so you can easily continue to test even after closing the browser.
The steps below are for Poster plugin for Firefox, but they are similar to Advanced REST Client for Chrome.
Here is a short tutorial on using Poster to POST data to create a new user through the user resource.

After installing Poster you will need to reboot Firefox. Once you have rebooted you can active Poster from the menu at Tools->Poster.
In the URL field, enter the base URL for your resource.
Click the Parameters tab. This is where you enter the data to be submitted, which mimics the fields that would be posted from a web
  form.

Note that for other types of data like nodes, you will need quite a
  bit more information than this. For more information on what type of
  data is needed to create a resource, please reference the
  documentation for that resource's create method.

Now click back to the Content to Send tab and click Parameter Body. This will convert your Parameters to properly encoded data, and change
  the Content Type to 'application/x-www-form-urlencoded' (you can test
  with your set Content Type).
Under Actions you'll see several buttons. Create requests are POSTed to the resource, so click Post. Ideally, if all went well, you will see something positive response.

Please let me know if you have any query/concern regarding this.
Comment: Thanks. I did this with Postman for Google Chrome. When I tried to post a node, I got a 403: Access denied for user anonymous
Comment: So, I got it to work in Postman. But not in my script. Even if I send the cookie and token information that I got in Postman through the script, I still get the same 403 error. Thanks for your time.

Posting in Ruby leads to a 403 error


SlideToggle Não carrega Maps Corretamente

Question: Tenho dois mapas numa página, estou usando slideToggle e slideUp para exibir deixar disponível para visualização apenas um mapa por vez.
mapa_fixo e mapa_movimento são as divs que contem os mapas.
<code>#mapa_fixo
{
    display:none;
}

#mapa_movimento
{
    display:none;
}

    function verifica_categoria_carrega_mapa(id)
    {

    var id_categoria = id;

    if(id==1)
    {

        if($("#mapa_fixo").is(":visible") == true)
        {
        }
        else
        {

            $("#mapa_fixo").slideToggle();
            $("#mapa_movimento").slideUp();
            return false;
        }
    }
    else if(id==2)
    {
        if($("#mapa_movimento").is(":visible") == true)
        {
        }
        else
        {

            $("#mapa_fixo").slideUp();
            $("#mapa_movimento").slideToggle();

            gmaps.refresh()

            return false;
        }

    }
}
</code>
Tá funcionando, mas, os mapas não estão sendo exibidos corretamente, devido a componentes jquery um dos mapas é carregado num arquivo .js o outro diretamente na página.
Se for carregar os mapas normalmente, sem estar com Display:none, os mapas carregam normalmente.
Mapa Fixo

Mapa Movimento
Comment: Você está usando algum plugin externo para fazer isso? O estado inicial do toggle é fechado?
Comment: Para o Toggle não estou usando nenhum plugin, inicialmente setei apenas as divs como display:none, não referenciando o toggle. Se tiver outra forma de fazer isso, mesmo sem usar o toggle, será ótimo.
Comment: Bom, eu tive um problema semelhante, mas no AngularJs (o código era um pouco diferente, não sei dizer como pode se adaptar ao seu modelo). O problema ocorria pois a div do mapa começava como `display:none` também. O que tive que fazer foi aplicar a reinicialização do mapa, que acontece no load do DOM.
Comment: Iniciei usando o `google.maps.event.addDomListener(window, 'load', initialize);`, mas, sem sucesso, vi algo relacionado a
`google.maps.event.addListenerOnce(map_rota, 'idle', function()`, mas, não achei metodo para executar, conhece algo?
Answer: Resolvido.
Iniciei os mapas sem Display:none, e após alguns segundos aplico o Display:none por função.
Os mapas já estão carregados e não ocorre mais o problema
<code>window.setTimeout(someFunction, 10000);
function someFunction()
{
    document.getElementById("mapa_fixo").style.display = "none";
    document.getElementById("mapa_movimento").style.display = "none";
}
</code>


Are the set of vectors linearly dependent?

Question:
Are the set of vectors linearly dependent?

$ \{ e^{x}, e^{-x}\} $ in $\mathcal{F} (\mathbb{R} ,\mathbb{R} )$

$ \{ \frac{1}{x-1}, \frac{1}{x + 1} \} $ in $ \mathcal{F} (]-1,1[,\mathbb{R})$

For $a,b \in \mathbb{R}$,

$ae^{x} + be^{-x} = 0$
We know that:  $e^x > 0 $ for all $x \in \mathbb{R} $
I am not sure if I can past to $a = b = 0$.

For $a,b \in \mathbb{R}$

$\frac{a}{x-1} + \frac{b}{x + 1} = 0 \implies x(a+b) + a - b =0$
Which does not tell anything about $a$ and $b$.
Answer: Guide:
Try to substitute some value of $x$, for example, in the first example, we can let $x=0$ and we obtain $a+b=0$, try to obtain another condition for $a$ and $b$ by letting $x$ equal to another value and then you can solve for $a$ and $b$.

 yes, they are linearly independent.


Changing bs4 to something faster for use with regex

Question: This is my (an amateur python learner) first question. I wrote this as regex practice, but I read several sites like this one which talk about how beautifulsoup is slow. I also read that lxml is faster, and I read the documentation for it but I still have no idea how to (or whether it makes sense to) swap bs4 for something faster here.
So I would greatly appreciate an example on how to swap bs4 for something faster in the code below. If my understanding on the situation is wrong, let me know too(I'm still learning)! Thanks!
'''
This script extracts all of Portia's lines in Shakespeare's Merchant of Venice
'''

import re
import urllib.request
import bs4

# use urllib.request.urlopen and beautifulsoup to get text of merchant of venice
u = urllib.request.urlopen('http://shakespeare.mit.edu/merchant/full.html')
sp = bs4.BeautifulSoup(u, 'lxml')
s = sp.get_text()

# extracts text which follows PORTIA\n\n, and which ends before \n\n, re.DOTALL causes '.' to include newlines
r = re.compile(r'(?<=PORTIA\n\n)(.+?)\n\n', re.DOTALL)

# print each match
for i in r.findall(s):
    print(i)

Comment: Never use regex to parse HTML
Comment: I'm trying to parse HTML with something else other than bs4, and then do my regex stuff on the result. But I don't know how.
Comment: Aren't you already using lxml as the parser? Is it really slow for you, or are you just going by what you've read? No point in fixing what is not broken.
Comment: It's not really slow for me. I'm just wondering if there's a better way. So bs4 is using lxml as the parser? Do I still need bs4 in this case? Does it slow things down?
Comment: First define 'slow'.
Comment: When I run the program, it takes about 5 seconds to get the result. But I don't know if that's slow or if it can be made faster because I don't have any benchmark. I'm just going off the comments I read online that bs4 is slow.
Comment: Have you timed the individual steps? Because on this machine the parsing + `get_text()` takes hundreds of milliseconds.
Answer: You can use lxml module which is order of magnitude faster than BeautifulSoup, if written properly, something like this :
import requests
from lxml import html
from datetime import datetime

u = requests.get('http://shakespeare.mit.edu/merchant/full.html').content
start_time = datetime.now()
sp = html.fromstring(u)
s = [' '.join(line.xpath('./a/text()')).strip() for line in sp.xpath('//a[./b[text() = "PORTIA"]]/following-sibling::blockquote[1]')]
print(s)
print(datetime.now() - start_time)

This will result in :
['By my troth, Nerissa, my little body is aweary of this great world.', 'Good sentences and well pronounced.', "If to do were as easy as to know what were good to do, chapels had been churches and poor men's cottages princes' palaces. It is a good divine that follows his own instructions: I can easier teach twenty what were good to be done, than be one of the twenty to follow mine own teaching. The brain may devise laws for the blood, but a hot temper leaps o'er a cold decree: such a hare is madness the youth, to skip o'er the meshes of good counsel the cripple. But this reasoning is not in the fashion to choose me a husband. O me, the word 'choose!' I may neither choose whom I would nor refuse whom I dislike; so is the will of a living daughter curbed by the will of a dead father. Is it not hard, Nerissa, that I cannot choose one nor refuse none?", 'I pray thee, over-name them; and as thou namest them, I will describe them; and, according to my description, level at my affection.', "Ay, that's a colt indeed, for he doth nothing but talk of his horse; and he makes it a great appropriation to his own good parts, that he can shoe him himself. I am much afeard my lady his mother played false with a smith.", "He doth nothing but frown, as who should say 'If you will not have me, choose:' he hears merry tales and smiles not: I fear he will prove the weeping philosopher when he grows old, being so full of unmannerly sadness in his youth. I had rather be married to a death's-head with a bone in his mouth than to either of these. God defend me from these two!", "God made him, and therefore let him pass for a man. In truth, I know it is a sin to be a mocker: but, he! why, he hath a horse better than the Neapolitan's, a better bad habit of frowning than the Count Palatine; he is every man in no man; if a throstle sing, he falls straight a capering: he will fence with his own shadow: if I should marry him, I should marry twenty husbands. If he would despise me I would forgive him, for if he love me to madness, I shall never requite him.", "You know I say nothing to him, for he understands not me, nor I him: he hath neither Latin, French, nor Italian, and you will come into the court and swear that I have a poor pennyworth in the English. He is a proper man's picture, but, alas, who can converse with a dumb-show? How oddly he is suited! I think he bought his doublet in Italy, his round hose in France, his bonnet in Germany and his behavior every where.", 'That he hath a neighbourly charity in him, for he borrowed a box of the ear of the Englishman and swore he would pay him again when he was able: I think the Frenchman became his surety and sealed under for another.', 'Very vilely in the morning, when he is sober, and most vilely in the afternoon, when he is drunk: when he is best, he is a little worse than a man, and when he is worst, he is little better than a beast: and the worst fall that ever fell, I hope I shall make shift to go without him.', "Therefore, for fear of the worst, I pray thee, set a deep glass of rhenish wine on the contrary casket, for if the devil be within and that temptation without, I know he will choose it. I will do any thing, Nerissa, ere I'll be married to a sponge.", "If I live to be as old as Sibylla, I will die as chaste as Diana, unless I be obtained by the manner of my father's will. I am glad this parcel of wooers are so reasonable, for there is not one among them but I dote on his very absence, and I pray God grant them a fair departure.", 'Yes, yes, it was Bassanio; as I think, he was so called.', 'I remember him well, and I remember him worthy of thy praise. How now! what news?', 'If I could bid the fifth welcome with so good a heart as I can bid the other four farewell, I should be glad of his approach: if he have the condition of a saint and the complexion of a devil, I had rather he should shrive me than wive me. Come, Nerissa. Sirrah, go before. Whiles we shut the gates upon one wooer, another knocks at the door.', "In terms of choice I am not solely led By nice direction of a maiden's eyes; Besides, the lottery of my destiny Bars me the right of voluntary choosing: But if my father had not scanted me And hedged me by his wit, to yield myself His wife who wins me by that means I told you, Yourself, renowned prince, then stood as fair As any comer I have look'd on yet For my affection.", 'You must take your chance, And either not attempt to choose at all Or swear before you choose, if you choose wrong Never to speak to lady afterward In way of marriage: therefore be advised.', 'First, forward to the temple: after dinner Your hazard shall be made.', 'Go draw aside the curtains and discover The several caskets to this noble prince. Now make your choice.', 'The one of them contains my picture, prince: If you choose that, then I am yours withal.', 'There, take it, prince; and if my form lie there, Then I am yours.', 'A gentle riddance. Draw the curtains, go. Let all of his complexion choose me so.', "Behold, there stand the caskets, noble prince: If you choose that wherein I am contain'd, Straight shall our nuptial rites be solemnized: But if you fail, without more speech, my lord, You must be gone from hence immediately.", 'To these injunctions every one doth swear That comes to hazard for my worthless self.', 'Too long a pause for that which you find there.', 'To offend, and judge, are distinct offices And of opposed natures.', 'Thus hath the candle singed the moth. O, these deliberate fools! when they do choose, They have the wisdom by their wit to lose.', 'Come, draw the curtain, Nerissa.', 'Here: what would my lord?', "No more, I pray thee: I am half afeard Thou wilt say anon he is some kin to thee, Thou spend'st such high-day wit in praising him. Come, come, Nerissa; for I long to see Quick Cupid's post that comes so mannerly.", "I pray you, tarry: pause a day or two Before you hazard; for, in choosing wrong, I lose your company: therefore forbear awhile. There's something tells me, but it is not love, I would not lose you; and you know yourself, Hate counsels not in such a quality. But lest you should not understand me well,-- And yet a maiden hath no tongue but thought,-- I would detain you here some month or two Before you venture for me. I could teach you How to choose right, but I am then forsworn; So will I never be: so may you miss me; But if you do, you'll make me wish a sin, That I had been forsworn. Beshrew your eyes, They have o'erlook'd me and divided me; One half of me is yours, the other half yours, Mine own, I would say; but if mine, then yours, And so all yours. O, these naughty times Put bars between the owners and their rights! And so, though yours, not yours. Prove it so, Let fortune go to hell for it, not I. I speak too long; but 'tis to peize the time, To eke it and to draw it out in length, To stay you from election.", 'Upon the rack, Bassanio! then confess What treason there is mingled with your love.', 'Ay, but I fear you speak upon the rack, Where men enforced do speak anything.', 'Well then, confess and live.', "Away, then! I am lock'd in one of them: If you do love me, you will find me out. Nerissa and the rest, stand all aloof. Let music sound while he doth make his choice; Then, if he lose, he makes a swan-like end, Fading in music: that the comparison May stand more proper, my eye shall be the stream And watery death-bed for him. He may win; And what is music then? Then music is Even as the flourish when true subjects bow To a new-crowned monarch: such it is As are those dulcet sounds in break of day That creep into the dreaming bridegroom's ear, And summon him to marriage. Now he goes, With no less presence, but with much more love, Than young Alcides, when he did redeem The virgin tribute paid by howling Troy To the sea-monster: I stand for sacrifice The rest aloof are the Dardanian wives, With bleared visages, come forth to view The issue of the exploit. Go, Hercules! Live thou, I live: with much, much more dismay I view the fight than thou that makest the fray. SONG. Tell me where is fancy bred, Or in the heart, or in the head? How begot, how nourished? Reply, reply. It is engender'd in the eyes, With gazing fed; and fancy dies In the cradle where it lies. Let us all ring fancy's knell I'll begin it,--Ding, dong, bell.", '[Aside]  How all the other passions fleet to air, As doubtful thoughts, and rash-embraced despair, And shuddering fear, and green-eyed jealousy! O love, Be moderate; allay thy ecstasy, In measure rein thy joy; scant this excess. I feel too much thy blessing: make it less, For fear I surfeit.', "You see me, Lord Bassanio, where I stand, Such as I am: though for myself alone I would not be ambitious in my wish, To wish myself much better; yet, for you I would be trebled twenty times myself; A thousand times more fair, ten thousand times more rich; That only to stand high in your account, I might in virtue, beauties, livings, friends, Exceed account; but the full sum of me Is sum of something, which, to term in gross, Is an unlesson'd girl, unschool'd, unpractised; Happy in this, she is not yet so old But she may learn; happier than this, She is not bred so dull but she can learn; Happiest of all is that her gentle spirit Commits itself to yours to be directed, As from her lord, her governor, her king. Myself and what is mine to you and yours Is now converted: but now I was the lord Of this fair mansion, master of my servants, Queen o'er myself: and even now, but now, This house, these servants and this same myself Are yours, my lord: I give them with this ring; Which when you part from, lose, or give away, Let it presage the ruin of your love And be my vantage to exclaim on you.", 'Is this true, Nerissa?', 'So do I, my lord: They are entirely welcome.', "There are some shrewd contents in yon same paper, That steals the colour from Bassanio's cheek: Some dear friend dead; else nothing in the world Could turn so much the constitution Of any constant man. What, worse and worse! With leave, Bassanio: I am half yourself, And I must freely have the half of anything That this same paper brings you.", 'Is it your dear friend that is thus in trouble?', 'What sum owes he the Jew?', "What, no more? Pay him six thousand, and deface the bond; Double six thousand, and then treble that, Before a friend of this description Shall lose a hair through Bassanio's fault. First go with me to church and call me wife, And then away to Venice to your friend; For never shall you lie by Portia's side With an unquiet soul. You shall have gold To pay the petty debt twenty times over: When it is paid, bring your true friend along. My maid Nerissa and myself meantime Will live as maids and widows. Come, away! For you shall hence upon your wedding-day: Bid your friends welcome, show a merry cheer: Since you are dear bought, I will love you dear. But let me hear the letter of your friend.", 'O love, dispatch all business, and be gone!', "I never did repent for doing good, Nor shall not now: for in companions That do converse and waste the time together, Whose souls do bear an equal yoke Of love, There must be needs a like proportion Of lineaments, of manners and of spirit; Which makes me think that this Antonio, Being the bosom lover of my lord, Must needs be like my lord. If it be so, How little is the cost I have bestow'd In purchasing the semblance of my soul From out the state of hellish misery! This comes too near the praising of myself; Therefore no more of it: hear other things. Lorenzo, I commit into your hands The husbandry and manage of my house Until my lord's return: for mine own part, I have toward heaven breathed a secret vow To live in prayer and contemplation, Only attended by Nerissa here, Until her husband and my lord's return: There is a monastery two miles off; And there will we abide. I do desire you Not to deny this imposition; The which my love and some necessity Now lays upon you.", 'My people do already know my mind, And will acknowledge you and Jessica In place of Lord Bassanio and myself. And so farewell, till we shall meet again.', "I thank you for your wish, and am well pleased To wish it back on you: fare you well Jessica. Now, Balthasar, As I have ever found thee honest-true, So let me find thee still. Take this same letter, And use thou all the endeavour of a man In speed to Padua: see thou render this Into my cousin's hand, Doctor Bellario; And, look, what notes and garments he doth give thee, Bring them, I pray thee, with imagined speed Unto the tranect, to the common ferry Which trades to Venice. Waste no time in words, But get thee gone: I shall be there before thee.", "Come on, Nerissa; I have work in hand That you yet know not of: we'll see our husbands Before they think of us.", "They shall, Nerissa; but in such a habit, That they shall think we are accomplished With that we lack. I'll hold thee any wager, When we are both accoutred like young men, I'll prove the prettier fellow of the two, And wear my dagger with the braver grace, And speak between the change of man and boy With a reed voice, and turn two mincing steps Into a manly stride, and speak of frays Like a fine bragging youth, and tell quaint lies, How honourable ladies sought my love, Which I denying, they fell sick and died; I could not do withal; then I'll repent, And wish for all that, that I had not killed them; And twenty of these puny lies I'll tell, That men shall swear I have discontinued school Above a twelvemonth. I have within my mind A thousand raw tricks of these bragging Jacks, Which I will practise.", "Fie, what a question's that, If thou wert near a lewd interpreter! But come, I'll tell thee all my whole device When I am in my coach, which stays for us At the park gate; and therefore haste away, For we must measure twenty miles to-day.", 'I did, my lord.', 'I am informed thoroughly of the cause. Which is the merchant here, and which the Jew?', 'Is your name Shylock?', 'Of a strange nature is the suit you follow; Yet in such rule that the Venetian law Cannot impugn you as you do proceed. You stand within his danger, do you not?', 'Do you confess the bond?', 'Then must the Jew be merciful.', "The quality of mercy is not strain'd, It droppeth as the gentle rain from heaven Upon the place beneath: it is twice blest; It blesseth him that gives and him that takes: 'Tis mightiest in the mightiest: it becomes The throned monarch better than his crown; His sceptre shows the force of temporal power, The attribute to awe and majesty, Wherein doth sit the dread and fear of kings; But mercy is above this sceptred sway; It is enthroned in the hearts of kings, It is an attribute to God himself; And earthly power doth then show likest God's When mercy seasons justice. Therefore, Jew, Though justice be thy plea, consider this, That, in the course of justice, none of us Should see salvation: we do pray for mercy; And that same prayer doth teach us all to render The deeds of mercy. I have spoke thus much To mitigate the justice of thy plea; Which if thou follow, this strict court of Venice Must needs give sentence 'gainst the merchant there.", 'Is he not able to discharge the money?', "It must not be; there is no power in Venice Can alter a decree established: 'Twill be recorded for a precedent, And many an error by the same example Will rush into the state: it cannot be.", 'I pray you, let me look upon the bond.', "Shylock, there's thrice thy money offer'd thee.", "Why, this bond is forfeit; And lawfully by this the Jew may claim A pound of flesh, to be by him cut off Nearest the merchant's heart. Be merciful: Take thrice thy money; bid me tear the bond.", 'Why then, thus it is: You must prepare your bosom for his knife.', 'For the intent and purpose of the law Hath full relation to the penalty, Which here appeareth due upon the bond.', 'Therefore lay bare your bosom.', 'It is so. Are there balance here to weigh The flesh?', 'Have by some surgeon, Shylock, on your charge, To stop his wounds, lest he do bleed to death.', "It is not so express'd: but what of that? 'Twere good you do so much for charity.", 'You, merchant, have you any thing to say?', 'Your wife would give you little thanks for that, If she were by, to hear you make the offer.', "A pound of that same merchant's flesh is thine: The court awards it, and the law doth give it.", 'And you must cut this flesh from off his breast: The law allows it, and the court awards it.', "Tarry a little; there is something else. This bond doth give thee here no jot of blood; The words expressly are 'a pound of flesh:' Take then thy bond, take thou thy pound of flesh; But, in the cutting it, if thou dost shed One drop of Christian blood, thy lands and goods Are, by the laws of Venice, confiscate Unto the state of Venice.", 'Thyself shalt see the act: For, as thou urgest justice, be assured Thou shalt have justice, more than thou desirest.', 'Soft! The Jew shall have all justice; soft! no haste: He shall have nothing but the penalty.', "Therefore prepare thee to cut off the flesh. Shed thou no blood, nor cut thou less nor more But just a pound of flesh: if thou cut'st more Or less than a just pound, be it but so much As makes it light or heavy in the substance, Or the division of the twentieth part Of one poor scruple, nay, if the scale do turn But in the estimation of a hair, Thou diest and all thy goods are confiscate.", 'Why doth the Jew pause? take thy forfeiture.', 'He hath refused it in the open court: He shall have merely justice and his bond.', 'Thou shalt have nothing but the forfeiture, To be so taken at thy peril, Jew.', "Tarry, Jew: The law hath yet another hold on you. It is enacted in the laws of Venice, If it be proved against an alien That by direct or indirect attempts He seek the life of any citizen, The party 'gainst the which he doth contrive Shall seize one half his goods; the other half Comes to the privy coffer of the state; And the offender's life lies in the mercy Of the duke only, 'gainst all other voice. In which predicament, I say, thou stand'st; For it appears, by manifest proceeding, That indirectly and directly too Thou hast contrived against the very life Of the defendant; and thou hast incurr'd The danger formerly by me rehearsed. Down therefore and beg mercy of the duke.", 'Ay, for the state, not for Antonio.', 'What mercy can you render him, Antonio?', 'Art thou contented, Jew? what dost thou say?', 'Clerk, draw a deed of gift.', 'I humbly do desire your grace of pardon: I must away this night toward Padua, And it is meet I presently set forth.', 'He is well paid that is well satisfied; And I, delivering you, am satisfied And therein do account myself well paid: My mind was never yet more mercenary. I pray you, know me when we meet again: I wish you well, and so I take my leave.', "You press me far, and therefore I will yield. Give me your gloves, I'll wear them for your sake; And, for your love, I'll take this ring from you: Do not draw back your hand; I'll take no more; And you in love shall not deny me this.", 'I will have nothing else but only this; And now methinks I have a mind to it.', "I see, sir, you are liberal in offers You taught me first to beg; and now methinks You teach me how a beggar should be answer'd.", "That 'scuse serves many men to save their gifts. An if your wife be not a mad-woman, And know how well I have deserved the ring, She would not hold out enemy for ever, For giving it to me. Well, peace be with you!", "Inquire the Jew's house out, give him this deed And let him sign it: we'll away to-night And be a day before our husbands home: This deed will be well welcome to Lorenzo.", "That cannot be: His ring I do accept most thankfully: And so, I pray you, tell him: furthermore, I pray you, show my youth old Shylock's house.", "[Aside to NERISSA]  Thou mayst, I warrant. We shall have old swearing That they did give the rings away to men; But we'll outface them, and outswear them too. Away! make haste: thou knowist where I will tarry.", 'That light we see is burning in my hall. How far that little candle throws his beams! So shines a good deed in a naughty world.', 'So doth the greater glory dim the less: A substitute shines brightly as a king Unto the king be by, and then his state Empties itself, as doth an inland brook Into the main of waters. Music! hark!', 'Nothing is good, I see, without respect: Methinks it sounds much sweeter than by day.', "The crow doth sing as sweetly as the lark, When neither is attended, and I think The nightingale, if she should sing by day, When every goose is cackling, would be thought No better a musician than the wren. How many things by season season'd are To their right praise and true perfection! Peace, ho! the moon sleeps with Endymion And would not be awaked.", 'He knows me as the blind man knows the cuckoo, By the bad voice.', "We have been praying for our husbands' healths, Which speed, we hope, the better for our words. Are they return'd?", 'Go in, Nerissa; Give order to my servants that they take No note at all of our being absent hence; Nor you, Lorenzo; Jessica, nor you.', "This night methinks is but the daylight sick; It looks a little paler: 'tis a day, Such as the day is when the sun is hid.", 'Let me give light, but let me not be light; For a light wife doth make a heavy husband, And never be Bassanio so for me: But God sort all! You are welcome home, my lord.', 'You should in all sense be much bound to him. For, as I hear, he was much bound for you.', 'Sir, you are very welcome to our house: It must appear in other ways than words, Therefore I scant this breathing courtesy.', "A quarrel, ho, already! what's the matter?", "You were to blame, I must be plain with you, To part so slightly with your wife's first gift: A thing stuck on with oaths upon your finger And so riveted with faith unto your flesh. I gave my love a ring and made him swear Never to part with it; and here he stands; I dare be sworn for him he would not leave it Nor pluck it from his finger, for the wealth That the world masters. Now, in faith, Gratiano, You give your wife too unkind a cause of grief: An 'twere to me, I should be mad at it.", 'What ring gave you my lord? Not that, I hope, which you received of me.', "Even so void is your false heart of truth. By heaven, I will ne'er come in your bed Until I see the ring.", "If you had known the virtue of the ring, Or half her worthiness that gave the ring, Or your own honour to contain the ring, You would not then have parted with the ring. What man is there so much unreasonable, If you had pleased to have defended it With any terms of zeal, wanted the modesty To urge the thing held as a ceremony? Nerissa teaches me what to believe: I'll die for't but some woman had the ring.", "Let not that doctor e'er come near my house: Since he hath got the jewel that I loved, And that which you did swear to keep for me, I will become as liberal as you; I'll not deny him any thing I have, No, not my body nor my husband's bed: Know him I shall, I am well sure of it: Lie not a night from home; watch me like Argus: If you do not, if I be left alone, Now, by mine honour, which is yet mine own, I'll have that doctor for my bedfellow.", 'Sir, grieve not you; you are welcome notwithstanding.', "Mark you but that! In both my eyes he doubly sees himself; In each eye, one: swear by your double self, And there's an oath of credit.", 'Then you shall be his surety. Give him this And bid him keep it better than the other.', 'I had it of him: pardon me, Bassanio; For, by this ring, the doctor lay with me.', "Speak not so grossly. You are all amazed: Here is a letter; read it at your leisure; It comes from Padua, from Bellario: There you shall find that Portia was the doctor, Nerissa there her clerk: Lorenzo here Shall witness I set forth as soon as you And even but now return'd; I have not yet Enter'd my house. Antonio, you are welcome; And I have better news in store for you Than you expect: unseal this letter soon; There you shall find three of your argosies Are richly come to harbour suddenly: You shall not know by what strange accident I chanced on this letter.", 'How now, Lorenzo! My clerk hath some good comforts too for you.', "It is almost morning, And yet I am sure you are not satisfied Of these events at full. Let us go in; And charge us there upon inter'gatories, And we will answer all things faithfully."]

The time taken to process and format the received information :
Your code : 0:00:00.187483
Above code : 0:00:00.026628

You can see from above that it is about 7-8 times faster than your code.
Note : These times excludes the time taken in getting the response as that is something independent of the code.
Comment: Thank you so much!
Comment: Your example is not faster because of lxml but because you're not using regexp. You can achieve the same with bs4 (using xpath) and probably get the same speed.


How to convert the Timestamp in millis to Date with TimeStamp in Rest ful service?

Question: I am trying to do to convert the Date in millis to Date in timestamp by using Jersey Converters. but I am not able to convert. Pleae help me .
Entity class:
<code>       @JsonSerialize(using=JsonDateSerializer.class)
             @Column(name="TSTAMP")
            private Timestamp timeStamp;
            **JsonDateSerializer:**
       @Component

            public

 class JsonDateSerializer extends JsonSerializer<Timestamp>{
        private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd HH:MM:SS");
        @Override
        public void serialize(Timestamp t, JsonGenerator gen,
                SerializerProvider arg2) throws IOException, JsonProcessingException {
            String formattedDate = dateFormat.format(t);

            gen.writeString(formattedDate);

        }

        }
</code>
Answer: You can use this to convert date to timestamp
//use your formatted date here
<code> Timestamp timestamp = new Timestamp(date.getTime());
</code>
Comment: I am getting the List from the DB as I expected but when I add the list Response in build() can changes the Timestamp in Millis
Comment: That is not . List ActivityDTOList = collarService.findMostRecentActivity(tagId, maxResults);                                     ActivityDTOList containes correct format but RestUtil.getOkResponse(dogActivityDTOList) -- now format is changing
Comment: didn't get u what do u mean by add the list Response in build() can changes the Timestamp in Millis


Displaying Integer Array Marks Under 40

Question: In my second loop, I wanted it to iterate through the arrays and display the names and marks of all students who have scored less than 40 marks.
How would I go about doing this?
            string[] studentNames = new string[5];
            int[] classScores = new int [5];

            for (int i = 0; i < classScores.Length; i++)
            {
                Console.WriteLine("Please enter a students name");
                studentNames[i] = Console.ReadLine();

                Console.WriteLine("Please enter marks");
                classScores[i] = int.Parse(Console.ReadLine());
            }

            for (int i = 0; i < 40; i++)
            {
                foreach (var item in studentNames)
                {
                    Console.WriteLine(item.ToString());
                }

                foreach (var item in classScores)
                {
                    Console.WriteLine(item.ToString());
                }
            }

            Console.WriteLine("Please enter the Return key to exit");
            ConsoleKeyInfo keyinfo = Console.ReadKey();
            while (keyinfo.Key != ConsoleKey.Enter)
                keyinfo = Console.ReadKey();

Comment: I showed you better approach to write your code. This is good example where you can understand use of `classes`, `Properties` and `Linq`. Use most of the feature of `C#` and write more readable program
Answer: Instead of creating two different array you should create a class called Student and add two properties to it i.e. Name and Score
public class Student
{
   public string Name {get;set;}
   public int Score {get;set;}
}

Now create list of Student to store data of all students.
List<Student> StudentList = new List<Student>();

Now use Linq query to get students having less than 40 score
var result = StudentList.Where(x => x.Score < 40).ToList();

Here is the your refactored code:
public class Student
{
   public string Name {get;set;}
   public int Score {get;set;}
}

public class Program
{
   public static void Main(string[] args)
   {
       List<Student> Students = new List<Student>();

       for (int i = 0; i < 5; i++)
        {
            Console.WriteLine("Please enter a students name");
            string name = Console.ReadLine();

            Console.WriteLine("Please enter marks");
            var score = int.Parse(Console.ReadLine());

            Students.Add(new Student(){Name = name, Score = score});
        }

       var result = Students.Where(x => x.Score < 40).ToList();

       foreach(var item in result)
       {
          Console.WriteLine($"Name : {item.Name} and Score : {item.Score}");
       }
       Console.ReadLine();
   }
}

Answer: Prasad's approach is cleaner than what you have presently. But if you insist.
Change this line:
for (int i = 0; i < 40; i++) {
foreach (var item in studentNames)
 {
 Console.WriteLine(item.ToString());
 }
 foreach (var item in classScores)
 {
Console.WriteLine(item.ToString()); }
 }

To:
    for(int i=0; i<classScores.Length; i++)
        {
            if(classScores[i]<40)
            {
               Console.WriteLine($"{studentNames[i] } scored {classScores[i] }");
            }
        }

That's assuming:
Both arrays are of the same fixed length.
The students' names and scores always correspond.

Displaying Integer Array Marks Under 40


Converge in distribution and order of convergence

Question: I have read an econometrics textbook on "converge in distribution" and found the following sentence.
\begin{equation}
  Z_{N} \xrightarrow{d} Z\implies Z_{N} = {O_p}(1)
\end{equation}
That is, if a random variable $Z_n$ converges in distribution to $Z$, $Z_N$ is bounded in probability.
The textbook states that this is easy to verify. However, I cannot figure it out at the moment.
Answer: We want to show $Z_n=O_p(1)$, that is, for any $\epsilon>0$, there exist $n_\epsilon\in\mathbb{N}$ and $a_\epsilon>0$, such that $P(|Z_n| > a_\epsilon)<\epsilon$ for all $n>n_\epsilon$.
To do this, let's first find a point $z>0$ at which $F_Z$ is continuous and $F_Z(-z) + 1-F_Z(z)<\epsilon/2$.
Now because of convergence in distribution, there exists $n_\epsilon\in\mathbb{N}$ such that $F_{Z_n}(-z) + 1-F_{Z_n}(z)<\epsilon$.
The last equation means $P(|Z_n| > z) < \epsilon$. Thus, we have found the bound $a_\epsilon>0$ and proved the result.
Comment: Minor note: you need "for all $n>n_\epsilon$" in   your definition of $O_p$
Comment: @ThomasLumley Yes. I've fixed the typo. Thanks a lot!
Comment: Thank you both of u!
Comment: @AlecosPapadopoulos Thanks for spotting that typo. Let me fix that!


What will happen if I query data (programmatically) while bookkeeper working on the Quickbooks?

Question: I want to know what exactly will happen when I query data(using php devkit or qbsdk) from quickbooks while bookkeepers are working on it.
The question looks pretty simple but I'm really concerning about the company file to be corrupted or not in this case.
Any opinions?
Answer: From your bookkeepers perspective - nothing will happen. They won't even know you're querying it.
From your perspective - you'll get some data back.
QuickBooks is a database just like any other database. You can query data from it, and it won't corrupt that data. It will just query it.


Achieving the optimal strike in squash: Is the wrist involved at all?

Question: I am a sports enthusiast who has tried out many ball sports through-out my life with years of training in football (read: "soccer" if you are American) and basketball, as well as many hours of experience/play time in tennis and table tennis, although no formal training.
Several years back I decided to give a shot to squash with a friend, both never even watched a game at that point. By reading and watching and asking, I got to a level where I think I know the basics of the game. Since I am familiar with ball sports, I don't find it hard to follow the ball or use the walls/bounces to my best advantage. However I don't think I have the best technique.
So, the question; when I watch videos of pros or the people who compete in my town, I realize that they use the wrist to create a whip effect, or at least that's my interpretation of it. I believe I tend to be more stale in an effort to keep the racket in balance when striking the ball. I am not sure if I'd be able to deliver much power if ended up hitting the ball with a wrist-powered shot, compared to a whole-arm strike which puts much of the strain on the shoulders and the chest. Am I doing something wrong? Is it common practice to use the wrist in squash? Could it be so that my racket is simply too heavy for me (alt. I am not strong enough in my wrist to deliver proper shots with my racket?)
Thanks for any tips!
Answer: I'm a lifelong squash player and what I'd say is don't worry so much about the wrist. You're going to use the wrist naturally as you make a full swing. You can add a bit of wrist at the point of impact to impart a little extra power, especially if you've taken a short backswing or you want to surprise your opponent by flicking the ball cross-court at the last second. But by and large, the wrist is a small percentage of your power. The real power comes from your LEGS. Step into each shot, move your arms through as you hit, and sure, use a bit of wrist, and you'll have yourself a powerful squash stroke. Keep up the playing, glad to see squash players out there!
Answer: Yes, according to an excerpt from this UK squash tips page:

So compact your stroke by remembering to keep your elbow in and to use your wrist as much as possible. Raise your shoulders, making
your head position lower between them. Keep your knees bent and stay
in the crouch position. A good practice technique is to crouch and
have your elbow and knee meet at the point of contact with the ball.
Not all players can do this. But, with time and with good footwork, it
can be done. Practicing volleys can also help shorten your swing.
But, the wrist is the best mechanism in getting your swing and power to potential.

Other pages also mention footwork and positioning as being important.


Define hidden markov model for word

Question: I'm attempting to define a hidden markov model and predict if given sequence of words is correct using Viterbi algorithm ( https://en.wikipedia.org/wiki/Viterbi_algorithm ). In order to aid understanding I've attempted to define the model paramters :
The letters in the corpus are abbd. From this I've defined :
states : a,b,b,d

trans_p (transition probabilities) :
There are
 a : 1/4
 b : 2/4
 d : 1/4

emit_p (emission probabilities) :
 count(a->b) / count(a) = 1/1 = 1
 count(b->b) / count(b) = 1/2 = 1/2
 count(b->d) / count(b) = 1/2 = 1/2

Is above correct ?
Do I need to define transition probabilities for d ?
Do I need to define emission probabilities for b->a & b->d ?
I also refer to :
https://stats.stackexchange.com/questions/212961/calculating-emission-probability-values-for-hidden-markov-model-hmm which aided in defining emission probabilities.
Answer: I think you are confusing emission probabilities with transition probabilities. When defining an HMM, you need to define

a set of (hidden) states, a set of observables,
a state transition matrix describing the probability of going from one space to the next
emission probabilities describing the probability of observing one
observable from a given (hidden) state
an initial state probability
vector describing what is your probability of starting in a given
state.

If they are in you corpus, I suppose that a,b and d are your observables, not your states. You need to define relevant states to complete your HMM. If you can observe the state, then your Markov model is not hidden, it's a plain Markov model and there is not need for the Viterbi algorithm

Define hidden markov model for word