Erro 1065 Query is Empty quando troco de pagina em minha paginação

Question: Quando entro na primeira página carrega a tabela normalmente mas quando vou para a segunda dá este erro
<?php
header("Content-type: text/html; charset=utf-8");
error_reporting(E_ERROR | E_WARNING | E_PARSE);
?>
<!DOCTYPE HTML>

    <link rel="stylesheet" type="text/css" href="css.css">
    <meta charset="utf-8">
    <title>TCC Consulta</title>

Controle de TCC

    <?php
    require_once "conexao/conexao.php";
    $maximo = 3;

    if (isset($_REQUEST['filtro'])) {
        $filtro = $_REQUEST['filtro'];
     }

    $pagina = intval(($_GET["pagina"]));
    if($pagina == "") {
        $pagina = "1";
    }

    $inicio = $pagina - 1;
    $inicio = $maximo * $inicio;

    $opcao = $_POST['opcao'];

        if($opcao=="opcProtocolo")
            $ComandoSQL = "select * from tb_tcc where num_protocolo like '$filtro%'";
        if($opcao=="opcOrientador")
            $ComandoSQL = "select * from tb_tcc where nm_orientador like '$filtro%'";
        if($opcao=="opcMembroBanca"){
            $ComandoSQL = "select * from tb_tcc where membro_banca1 like '$filtro%' or membro_banca2 like '$filtro%' or membro_banca3 like '$filtro%'
            or membro_banca4 like '$filtro%' or membro_banca5 like '$filtro%' or membro_banca6 like '$filtro%'";
        }

    $result = $conn->query($ComandoSQL);
    $rows = $result->fetchAll();
    $total = count($rows);

    if("$opcao"=='opcProtocolo')
        $ComandoSQL = "select * from tb_tcc where num_protocolo like '$filtro%' LIMIT $inicio, $maximo";

    if("$opcao"=='opcOrientador')
        $ComandoSQL = "select * from tb_tcc where nm_orientador like '$filtro%' LIMIT $inicio, $maximo";

    if("$opcao"=='opcMembroBanca'){
        $ComandoSQL = "select * from tb_tcc where membro_banca1 like '$filtro%' or membro_banca2 like '$filtro%' or membro_banca3 like '$filtro%'
         or membro_banca4 like '$filtro%' or membro_banca5 like '$filtro%' or membro_banca6 like '$filtro%' LIMIT $inicio, $maximo";
    }

    $result = $conn->query($ComandoSQL);
        try{
            if($total>0)
            {
                ?>

                        Nº de
 protocolo
                        Autor
                        Orientador
                        Co-Orientador
                        Banca
                        Título do trabalho
                        Data da proposta
                        Data da defesa
                          Resumo
                        Palavras chave
                         Área
                        TCC
                        Operação

                <?php
                while ($row = $result->fetch(PDO::FETCH_OBJ))
                {
                    ?>

                            <?php echo $row->num_protocolo; ?>
                            <?php echo $row->nm_autor; ?>
                            <?php echo $row->titulo.'. '.$row->nm_orientador; ?>
                            <?php echo $row->tituloc.'. '.$row->nm_coorientador; ?>
                            <?php echo $row->ttmb1.'. '.$row->membro_banca1.", ".$row->ttmb2.'. '.$row->membro_banca2.", ".$row->ttmb3.'. '.$row->membro_banca3;if($row->membro_banca4!="")echo ", ".$row->ttmb4.'. '.$row->membro_banca4;if($row->membro_banca5!="")echo ", ".$row->ttmb5.'. '.$row->membro_banca5;if($row->membro_banca6!="")echo ", ".$row->ttmb6.'. '.$row->membro_banca6; ?>
                            <?php echo $row->titulo_trabalho; ?>
                            <?php echo $row->dt_proposta; ?>
                            <?php echo $row->dt_defesa; ?>
                            <?php echo $row->resumo; ?>
                            <?php echo $row->palavras_chaves; ?>
                            <?php echo $row->area; ?>
                            <?php echo $row->tcc; ?>

                            <?php
                            echo "id . "'>";
                            echo " \n";
                            ?>

                    <?php
                }
                $conn = null;
                ?>

                <?php
            }
            else
            {
                echo "";
            }
        }
        catch(PDOException $e)
        {
            echo "Erro!: ".$e."\n";
        }
    $menos = $pagina - 1;
    $mais = $pagina + 1;
    $pgs = ceil($total / $maximo);
     if($pgs > 1 ) {
        echo "

";

      if($menos > 0) {
       echo "anterior  ";
      }

   for($i=1;$i <= $pgs;$i++) {
       if($i != $pagina) {
           echo "$i | ";
       } else {
           echo " $i | ";
       }
   }

   if($mais <= $pgs) {
       echo "Próxima";
   }
}

    ?>

Answer: Aqui é onde você pega a opção selecionada ateriormente para fazer a busca inicial que vai prover os dados para a pagina e assim calcular a necessidade da paginação, correto?
$opcao = $_POST['opcao'];

if($opcao=="opcProtocolo")
    $ComandoSQL = "select * from tb_tcc where num_protocolo like '$filtro%'";
if($opcao=="opcOrientador")
    $ComandoSQL = "select * from tb_tcc where nm_orientador like '$filtro%'";
if($opcao=="opcMembroBanca"){
    $ComandoSQL = "select * from tb_tcc where membro_banca1 like '$filtro%' or membro_banca2 like '$filtro%' or membro_banca3 like '$filtro%' or membro_banca4 like '$filtro%' or membro_banca5 like '$filtro%' or membro_banca6 like '$filtro%'";
}

E aqui ocorre a exposição dos links para as outras páginas, caso existam:
$menos = $pagina - 1;
$mais = $pagina + 1;
$pgs = ceil($total / $maximo);
if($pgs > 1 ) {
    echo "

";
}
if($menos > 0) {
    echo "anterior  ";
}
for($i=1;$i <= $pgs;$i++) {
    if($i != $pagina) {
        echo "$i | ";
    } else {
        echo " $i | ";
    }
}
if($mais <= $pgs) {
    echo "Próxima";
}

A grande questão é que na primeira página, na qual está carregando corretamente, você tem o $_POST["opcao"] que, na segunda parte onde é feita a paginação, não é passado como um parâmetro para as próximas páginas e sem esse parâmetro, que é o responsável por definir suas querys o sistema acusa o erro de que está vazio.
Sugiro que faça uma breve alteração para adicionar o campo $_POST["opcao"] aos parâmetros enviados às próximas páginas, assim por exemplo:
if(isset($_POST['opcao'])){
    $opcao = $_POST['opcao'];
}elseif(isset($_GET['opcao'])){
    $opcao = $_GET['opcao'];
}else{
    $opcao = "opcProtocolo"; //coloquei esse else como opção para vc entender que pode manter um valor padrão caso ocorra algum problema
}

E nos links da paginação ficaria assim:
echo "anterior  ";

Observe que adicionei o opcao=$opcao logo no primeiro parâmetro. Espero ter ajudado.


Static noise with a USB MIDI controller

Question: I have recently bought a seven-year old M-Audio Keystation Pro 88, and noticed that when I plug it into my MacBook Air, I get static noise when I press keys.
Once pressed, the same key makes a cracking sound and then works fine. But static noise may reappear later on the same key or when I play chords.
Have anyone had a similar problem? Is it due to hardware and cords or the controller needs a clean up?
Any suggestions are welcomed.
PS: I'm asking this question here according to the Help Center that allows asking questions about "usage of specific music software or hardware".
Comment: Sounds like the keystation is old and finicky. I have an older keyboard that has ground loop issues when I plug in both audio and MIDI which causes clicking noises whenever I press a key, but you can't really have a ground loop when nothing is plugged into power. The only other thing I could think of is using an external audio interface, but if you don't have one already that's an expensive option that might not even fix the problem.
Comment: What audio interface are you using? Are you just using the built in output? Is the MacBook plugged into power or running on battery? Is the keystation being bus powered?
Comment: @ToddWilcox (1) USB for both data and power, (2) I tried built in speakers and several  headphones, (3) I tried both on battery and into power, (4) Yes, bus powered.
Answer: I solved the problem. The solution is trivial:
Restarting the App
In my case, GarageBand.
With many apps open, Mac moves some apps from RAM to SSD. When a user presses a MIDI key for the first time, Mac moves the respective sound from SSD back into RAM. Which takes time and causes the cracking sound. Same for long notes and chords (they seemingly has different sounds).
Restarting the app ensures that it's entirely in RAM for now. And no cracking sounds.
(Optional) A USB cable with ferrite bead
A friend of mine recommended a USB cable with a ferrite bead (cylinders on both sides of the cable) to ensure that the cable collects no static noise from the environment.
That seems to be relevant for many noise-related issues.
Comment: This is a latency problem: check your audio/midi buffer settings etc. in garage band. The static noise from usb thing is a red herring: it may be true for analog, but not for usb.

Static noise with a USB MIDI controller


Create a view to show comments on a user ONLY from that user

Question: Am using comment as reviews for a content type. Now am trying to create a block in views that will appear on the user profile page. I want to show ONLY comments (reviews) that are from the specific users page i'm on. If the user has no comments made, then the block would be hidden. What settings in views would allow this to happen?
I've tried using content filters and relationship filters but I haven't been able get the right settings. Example: Am on User A's Profile page, I want to display all comments from User A on his profile page.
EDIT: Since my answer really didnt receive anything that can help. I will try to better word the question. I just need to create a block with comments from a specific content type in context to the user profile I'm on. I've created my view and added a contextual filter base off the author uid. But it still shows all the comments not just the ones from the current profile user.
Comment: create a normal views with contextual filter from url then follow http://drupal.org/node/544884
Answer: You should indeed use a contextual filter, selecting "When the filter value is NOT available", then "provide default value", and choose "user ID from loggued user".
That should work.


How can I make the correct time-series analysis for my data?

Question: I conducted a research with 90 participants who were exposed to a film stimuli for 60 minutes and their physiological responses were measured continuously. I would like to test the causal relationship between this psychological response and a another continously measured visual feature of the stimuli. Physiology was measured 15 times per second, the visual feature was measured 1 time per second.
I think that I need to use a cross-correlation and I found a function for it in SPSS (I am only able to work with SPSS and I have no background in mathematics). As I am complete beginner in time-series analysis, I would like to know:

if cross-correlation is the correct statistic here or whether I should use some other type of model?
if I need to consider anything during the data preparation
(detrending is often mentioned in the literature, but I don't know
how to do that in SPSS or if I need it at all)?
if there is a book with a gentle introduction to this topic?
Comment: Do you have any hypothesis on how much time the casual effect needs to affect the outcome?
Comment: No, I don't have a hypothesis on that. I think the lag function will tell me in retrospect how much later the effect may occur.
Comment: I put a bounty on this question because I think it is a topic that should be answerable by the community and is of interest to more people. Perhaps it did not get enough attention.
Answer: You would likely be looking to calculate the residual autocorrelation function (RACF), also called residual cross-correlation function, which is the autocorrelation function on the residuals of fitted models for two different time series (fitted using ARMA models, auto-regressive moving average models). The calculation will yield a plot that shows if there is a causality between the two inputs, X and Y, and at what lags it is significant.
In order to fit the ARMA models properly, there are some assumptions made. The model should be stationary, so you may need to use a differenced ARMA model in fitting (see ARIMA). There are also the usual assumptions in fitting an ARMA model, such as normality of data, iid, constant variance. You should check these in your data before proceeding; there are some transformations you can do to your data to help make them more normal if required (such as Box-Cox).
In terms of a textbook, I took a course with this professor and found the book to be fairly helpful. The link is no longer working but you can likely find another copy somewhere.
http://www.systems.uwaterloo.ca/Faculty/Hipel/Time%20Series%20Book.htm
Hope that helps. I am afraid I don't work in SPSS so I can't help you there (I work in R myself). If you can find a way to fit ARMA models in SPSS and get the residuals, you should be able to use the cross-correlation function on the residuals for your statistic.
Best of luck!


pooled regression in eviews

Question: Hey I have to regress abnormal returns for 202 companies over a period of 10 years (between 2004-2013) against their respective PE ratios and a Profitability measure for the same time period. Thus I have to run a pooled regression. I have read online on how to do it...but still am not sure of the process and also did not find any appropriate examples, or one similar to my case. Here my dependent variable are the returns of the 202 stocks over a 10 yr time period. And the two independent/ explanatory variables are their PE ratios, current and next year and profitability measures respectively (both of which are also considered fr the same time period of 10 years). So please could anyone tell me whether it is possible to run this regression in eviews?
I was confused regrading what should i select in the estimation box options. Firstly, what should I consider as my common coefficient/cross section coefficient..in the estimation box options. Also should I go for fixed effects/common/ random effects intercept option?
The equation I constructed to test whether there are any PE, Expected PE or time lag PE effects on Abnormal Returns is as follows:
Abnormal Return (t) = α+β1 (PE t-1)+β2(PE t)+β3 (PE t+1)+ β4(Profitability t)+ε
Please help me out anyone by telling me how can I run a pooled regression for my dataset and equation..or is it even possible..to take these data from three different sheets and accordingly run it because otherwise I have to take mean returns of all companies and mean PE of all companies and run the regression which would be less satisfactory to my dissertation research. Thanks alot in advance.
Regards,
Samiha
Answer: Pooled regression is only possible with panel data. Make sure your dataset is a paneldataset. So you need a timedimension and a crosssectional dimension. If so you can easily select your data and run a Pooled OLS regression. It is the standard regression method for panel data so you don't have to change settings.

pooled regression in eviews


How to add class to embedded Paragraphs field-items?

Question: I have a Paragraph field embedded on a node type. The Paragraph field type allows for many different Paragraph Bundles to be inserted into the node.
My mark up currently displays as (Drupal 7 zen Theme):

How can I add a class after each field-paragraphs? I would want to do this so that each Bundle has it's own class.
I've tried the following in my themes template file but it adds a class around the entire field and not on each Bundle:
    function mytheme_preprocess_paragraphs_items(&$vars, $hook) {

  // This will remove all the current classes
  $vars['classes_array'] = "";

  // You can now add the classes you want in this array
  $vars['classes_array'][] = "myclass";
}

Answer: Drupal 7
You should be able to copy this function into your template.php file of your theme:
/**
 * Process variables for paragraphs-items.tpl.php
 */
function mytheme_preprocess_paragraphs_items(&$variables, $hook) {
  $variables['view_mode'] = $variables['element']['#view_mode'];
  $variables['field_name'] = $variables['element']['#field_name'];

  $variables['content'] = $variables['element']['#children'];

  $variables['classes_array'][] = drupal_html_class('paragraphs-items-' . $variables['element']['#field_name']);
  $variables['classes_array'][] = drupal_html_class('paragraphs-items-' . $variables['element']['#field_name'] . '-' . $variables['view_mode']);
  $variables['classes_array'][] = drupal_html_class('paragraphs-items-' . $variables['view_mode']);

  $variables['theme_hook_suggestions'][] = 'paragraphs_items__' . $variables['element']['#field_name'];
  $variables['theme_hook_suggestions'][] = 'paragraphs_items__' . $variables['element']['#field_name'] . '__' . $variables['view_mode'];

  // your code here
  $variables['classes_array'][] = 'your-class';
  $variables['classes_array'][] = 'your-other-class';
}

You should also be able to do this for individual item:
/**
 * Process variables for paragraphs-item.tpl.php
 */
function mytheme_preprocess_paragraphs_item(&$variables, $hook) {
  // your code here
  $variables['classes_array'][] = 'your-class';
  $variables['classes_array'][] = 'your-other-class';
}

After adding this function, clear the cache so it is registered. You can then check if either one are being called by adding a breakpoint or print 'called'; exit; if you do not have something like XDebug installed.
Note how the second function is paragraphs_item and not paragraphs_items. Both of these are defined as theme hooks in paragraphs.module.
You can even do this as well:
/**
 * Implements hook_preprocess_entity().
 * @param $variables
 */
function mytheme_preprocess_entity(&$variables) {
  if ($variables['entity_type'] == 'paragraphs_item' && $variables['elements']['#bundle'] == 'your_bundle') {
    $variables['classes_array'][] = 'your-class';
  }
}

Comment: Sorry, I forgot to mention it's for Drupal 7!
Comment: Thanks Keven, the code for each paragraphs-item is working. But I want to add it to the bundle (so that  has my-class appended to it. Do I replace #field-name in the first snippet with my bundle name?
Comment: No, that is for constructing dynamic template suggestions via `theme_hook_suggestions`. Which are you trying to alter, the paragraphs output, or the field that outputs the paragraphs?
Comment: The field output. They all are combined under under one wrapper at the moment and I need to target certain fields.
Comment: I've added a image for clarity
Comment: @Kevin It is possible to add classes to individual fields or specify html elements to individual fields of paragraphs bundle items?


Do this algorithm terminates?

Question: Let $x \in \mathbb{R}^p$ denote a $p$ dimensional data point (a vector). I have two sets $A = \{x_1, .., x_n\}$ and $B = \{x_{n+1}, .., x_{n+m}\}$. So $|A| = n$, and $|B| = m$. Given $k \in \mathbb{N^*}$, let $d_x^{(A, k)}$ denote the mean Euclidean distance from $x$ to its $k$ nearest points in $A$; and $d_x^{(B, k)}$ denote the mean Euclidean distance from $x$ to its $k$ nearest points in $B$.
I have the following algorithm:

$A' = \{ x_i \in A \mid d_{x_i}^{A, k)} > d_{x_i}^{(B, k)} \}$ ... (1)
$B' = \{ x_i \in B \mid d_{x_i}^{A, k)} < d_{x_i}^{(B, k)}$ ... (2)
A = $\{ x_i \in A \mid x_i \not\in A' \} \cup B'$ ... (3)
B = $\{ x_i \in B \mid x_i \not\in B' \} \cup A'$ ... (4)
Repeat (1), (2), (3) and (4) until: (no element moves from $A$ to $B$ or from $B$ to $A$, that is A' and B' become empty) or (|A| $\leq$ or |B| $\leq$ 1)

Do this algorithm terminates, and if it so, is it possible to easily prove it ?
Note: the $k$ nearest points to $x$ in a set $S$, means: the $k$ points (others than $x$) in $S$, having the smallest Euclidean distance to $x$.
Answer: Take $p=1$ and $k=1$. Consider $A=\{0,3\}$ and $B=\{2,5\}$.

$d_0^A=3$ and $d_0^B=2$
$d_2^A=1$ and $d_2^B=3$
$d_3^A=3$ and $d_3^B=1$
$d_5^A=2$ and $d_5^B=3$
So $A'=A$ and $B'=B$, so $A$ becomes $B$ and $B$ becomes $A$, and the algorithm never stops.
Comment: Thank you for your example. If as soon as I find an element x in A having $d_x^A > d_x^B$ I put it in B, and as soon as I find an element x in B having $d_x^A < d_x^B$ I put it in B, would it be the same (algorithm never stops) ?
Comment: Yes, I think that the algorithm would eventually stop, but in that case there are examples where everything end with $A$ empty or $B$ empty, only depending of the order you choose to "find" your elements. So you could probably put everything in $A$ in one step, it would be much quicker :)

Do this algorithm terminates?


Show specific submenu and mark specific item as active when front page or specific node type is opened

Question: My front page is basically a view that lists teasers of node type article. How can I show a specific submenu and mark one item in this submenu as active (+ its parent) when
1) the front page is opened or
2) any article is opened?
I know 2) can be done with the module "Context Active Trail" and "Context UI", but I want to do it without a module and I think the module can't do 1) anyway.
Answer: So finally I used the Menu Position Module, which works perfectly.


"An error occurred opening snapshot" Process Monitor

Question: Each time I run a new instance of the Process Monitor, a dialog box pops up stating that "An error occurred opening snapshot", this error prevents the  capturing of any events.
Pressing the capture button or Ctrl+E reproduces the error message as well
Answer: In order to resolve this error you need to clear the Logfile registry key entry.

Close all instances of Process Monitor.

Open Regedit.

Find the Logfile registry entry located under
For 64 bit version:
HKEY_CURRENT_USER/Software/SysInternals/ProcessMonitor/
For 32 bit version:
KEY_CURRENT_USER/Software/SysInternals/ProcessMonitor32/

Locate the key named 'Logfile'.

Right click on the key and
select 'Modify'.

Set the Value data to an empty string and click 'OK'.

Launch Process Monitor - the issue should be resolved.


data transfer between android app and asp.net C#

Question: I want to send data from my android application to asp.net(c#).In C# page i will perform some database operations on the data received from android app and after that I will send back the results to my android application.
I don't have any idea of how to do this.Please anyone explain or give the link of some example.I have searched a lot but was not able to find the right answer.So please explain each step to follow or quote some links for examples.
Comment: I don't get the `send data to asp.net and then in C# page` part. You could use a service (wcf, for example) to perform your operations and send back the results to your android application. Does this satisfy your needs?
Comment: i have edited my question a little bit so please read it again and help me
Comment: @rupinder18: Are you saying that a service as suggested by Conrad does not satisfy your needs? What is this "data" you speak of? Is it some text like chat messages, or a ciphered byte stream? Can't you navigate to your asp page using the built in android web browser and send information "via http"?
Answer: I suggest you take a look at this, from MSDN:

Windows Communication Foundation (WCF) is a framework for building service-oriented applications. Using WCF, you can send data as asynchronous messages from one service endpoint to another. A service endpoint can be part of a continuously available service hosted by IIS, or it can be a service hosted in an application.

Check out the link for more information, and google for WCF. I won't be able to explain everything in this answer, but I'll provide you the guidelines.
You can host your WCF service, and access it through HTTP (or whatever protocol you can use) . In your android, to make it easy you can use a library such as KSOAP. You can check some SO questions as well, KSOAP ANDROID Implementation , Getting Started with KSOAP on Android.
Now, now, if you're talking about opening a page in your android to process something, you can just post information to it, and get the response back and process it.
In this second case, I think you can use HttpClient and HttpPost classes, from
org.apache.http.client package. Something in these lines:
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://www.myaspnetstuff.com/process");

try {
    List<NameValuePair> parameters = new ArrayList<NameValuePair>(1);
    parameters.add(new BasicNameValuePair("id", "1"));

    httpPost.setEntity(new UrlEncodedFormEntity(parameters));

    //here you get your response and do whatever fits your needs.
    HttpResponse response = httpClient.execute(httpPost);

} catch (ClientProtocolException e) {
    // TODO Auto-generated catch block
} catch (IOException e) {
    // TODO Auto-generated catch block
}

Comment: As far as I know, WCF is a replacement for all earlier web service technologies from Microsoft.
Comment: tell me one thing is WCF the advanced version of webservice?


Namespace loop or code leak in boost::function?

Question: I'm really baffled by this. Have I managed to do something to cause this, or is it an unclosed namespace block in boost, or some bug in VS c++ 2008? I'm definitely sure I've closed all my own namespaces properly, all includes are outside of and above them, and all my header files got include guards.
alt text http://lowtown.se/stuffs/superboost.png
The boost/function.hpp is only included in this header. Two other headers in my library includes the boost/cstdint.hpp but they don't have this problem.
Comment: This happens to me all the time. Microsoft's IntelliSense for C++ has always been somewhat broken. If you can afford it, buy VisualAssist.
Comment: "one time load" #defines => Include Guard or Macro Guard. FYI
Answer: Visual C++'s intellisense is a bit quirky. Sometimes it screws up. That doesn't mean there is a problem in your code. Always take C++ intellisense with a grain of salt.
Answer: Sometimes intellisense does that. If you use Visual Assist X it will fix that, but it is a very expensive program :(
Answer: Usually deleting ncb-file solves most of Intellisense problems. If it doesn't help — buy VA.


Java importing packages

Question: I have a program in my desktop that I want to run (structure in the url), but when I do compile, with
\code\nlp\assignments\parsing\javac PCFGParserTester.java
I get:
PCFGParserTester.java:6: error: package nlp.io does not exist
import nlp.io.PennTreebankReader;
         ^
PCFGParserTester.java:7: error: package nlp.ling does not exist
import nlp.ling.Tree;
           ^
PCFGParserTester.java:8: error: package nlp.ling does not exist
import nlp.ling.Trees;
           ^
PCFGParserTester.java:9: error: package nlp.parser does not exist
import nlp.parser.EnglishPennTreebankParseEvaluator;

how do I get my program to correctly import my packages?
Answer: You want to be in the \code directory and compile with:
javac nlp\assignments\parsing\PCFGParserTest.java

(And you should have a package declaration of package nlp.assignments.parsing; to match the position in the directory structure.)
That way javac will look for the other classes appropriately.
Alternatively, and rather more simply, you could use an IDE such as Eclipse or NetBeans, and it would take care of all this for you - you'd just specify the code directory as a source directory, and all would be well.

Java importing packages


Example of a connected Riemannian manifold containing a non-compact closed bounded set

Question: What is an example of a connected Riemannian manifold containing a non-compact closed bounded set?
By the Hopf-Rinow Theorem, I know that the closed bounded sets of a connected Riemannian manifold are compact if and only if the manifold is complete. So I have to pick a non complete Riemannian manifold. Let's say I choose the punctured sphere or an open hemisphere with the induced metric from Euclidean space. "Where is" that closed bounded subset of the sphere which is not compact? Or am I in the wrong track?
Answer: Take the open unit disk in the plane. It is closed in itself but not compact.
Comment: Or more intuitively (but not really) any diagonal that runs across it. It wont be compact as the endpoints are missing! This uses the fact that compactness is intrinsic and a segment missing endpoints is not compact either as a subset of plane or as a subset of part of plane.
Answer: In any metric space, if $(x_n)$ is a Cauchy sequence which does not converge, then the subset $\{x_n\}$ is closed, bounded, and not compact.  Alternatively, if your entire manifold is bounded (as in the examples you name), you can just take the closed bounded set to be the entire manifold.
Comment: Nope, if a Cauchy sequence accumulates at a point, it must converge to that point.  For if you can choose some very large $N$ such that $x_N$ is close to $p$, then $x_n$ will be close to $p$ for all $n>N$ as well since the sequence is Cauchy.
Comment: Thank you! I was just trying to figure out why the subset $\{x_n\}$ of a  non convergent Cauchy sequence has to be closed. Can't it have more than one accumulation point?


Validation for final model after cross validation

Question: The classical way in machine learning is to split the dataset into three parts: train, validation and test. The train dataset is used to update the weights, the validation dataset is used during to evaluate the model during training and e.g. perform early stopping and the test set is used once at the very end to get a final score.
When I use cross validation, I still have a separate test set, but I split the remaining samples into k-folds and train/validate with them k times.
According to this answer, I use the whole dataset (that is not reserved for test) after cross validation to train my final model. Does that mean I don't validate here while training the final model?
To clarify: I'm talking about how to train the final model after I did cross validation to select an algorithm and tune the parameters.
Comment: The link you provide explains it well. Use CV to find your model. Once selected you train it on the entire dataset, so there is no further validation. To report generalisation error you use what you found in the CV. After deploying the model in the real world you might get some more metrics to assess its performance, but I think that's a different topic.
Answer: You don't always have to validate, since a lot of times various CV techniques are employed for training and testing.   See, for example, Kohavi
$k$-fold cross-validation. One of the most efficient methods for building the confusion matrix C is to use $k$-fold cross-validation.  Let $\mathcal{D}$ represent all of the objects in a dataset.  In $k$-fold cross-validation, we split $\mathcal{D}$ into $k$ mutually exclusive partitions $\mathcal{D}$$_1$, $\mathcal{D}$$_2$,$\ldots$,$\mathcal{D}$$_k$ and the classifier is trained and tested $k$ times.  In 10-fold cross-validation, we set $k=10$.  Stratified 10-fold cross-validation is then carried out using ten repartitionings for each classification run. During a repartitioning, the order of objects is first shuffled and then objects are assigned to the 10 ordered partitions (folds), while ensuring that at least 1 objects from each class is in each partition.  Using the 10 partitions $\mathcal{D}$$_1$, $\mathcal{D}$$_2$,$\ldots$,$\mathcal{D}$$_{10}$ the classifier is first trained with objects in partitions  $\mathcal{D}$$_2$,$\ldots$,$\mathcal{D}$$_{10}$ and objects in partition $\mathcal{D}$$_1$ are then used for testing (class prediction).  Next, we train with partitions $\mathcal{D}$$_1$, $\mathcal{D}$$_3$,$\ldots$,$\mathcal{D}$$_{10}$ and test objects in partition $\mathcal{D}$$_2$.  This is repeated until training with partitions $\mathcal{D}$$_1$, $\mathcal{D}$$_2$,$\ldots$,$\mathcal{D}$$_{9}$ and test objects in partition $\mathcal{D}$$_{10}$ is completed.  This scheme is repeated 10 times, each time randomly assigning all objects into 10 partitions and then performing training and testing on objects in partitions $\mathcal{D}$$_1$, $\mathcal{D}$$_2$,$\ldots$,$\mathcal{D}$$_{10}$ sequentially.
Leave-one-out cross-validation. Another method for constructing the confusion matrix involves leave-one-out cross-validation or LOOCV, where $k=1$.  In LOOCV, class prediction is made on each test objects when is it held out from training. LOOCV is known to be a pessimistically unbiased estimate of the true error rate, but like other approaches does not guarantee the same accuracy for future objects.
0.632 Bootstrap.  This technique determines classifier accuracy using cross-validation based on the 0.632 bootstrapping method. For the $b$th iteration $(b=1,2,\ldots, B)$, objects are randomly selected with replacement and called sample $\mathcal{D}^b$.  The probability that an object is not selected during bootstrapping is $(1-1/n)^n=\exp(-1)=0.368$, and we call this sample of objects $\mathcal{D}^0$.  Next, the classifier is trained using $\mathcal{D}^b$.  The classification accuracy of objects in $\mathcal{D}^b$ is known as the apparent accuracy and is denoted as $Acc_b$.  The classification accuracy of objects in $\mathcal{D}^0$ based on training with $\mathcal{D}^b$ is denoted as $Acc_0$.  The steps necessary for CVB are listed below:

Select $n$ objects with replacement, and call this the ``bootstrap''
sample $\mathcal{D}^b$.  Call the set of objects not selected sample
$\mathcal{D}^0$.

Train the classifier using objects in $\mathcal{D}^b$.

Obtain $Acc_0$, by predicting class membership of objects in
$\mathcal{D}^0$.

Obtain $Acc_b$, by predicting class membership of objects in
$\mathcal{D}^b$.

The 0.632 cross-validation accuracy is determined with the
relationship \begin{equation} Acc_{0.632} =  0.368 Acc_b + 0.632
Acc_0. \end{equation}

The above steps are carried out, for example, $B=40$ times and the average of $Acc_{0.632}$ over the $B$ iterations is used as the final estimate of accuracy.
Holdout method. The holdout method for constructing the confusion matrix partitions the dataset $\mathcal{D}$ so that, for example, two-thirds of the objects are used for training and the remaining 1/3 are used for testing.  Random subsampling is often repeated $k$ times, in which objects are randomly selected followed by accuracy determination.  A drawback of the holdout method is that it makes inefficient use of $\mathcal{D}$, since, for example, a third of the objects are not used for training the classifier.
In the image below for training and testing error in 10 folds of a neural network, you can see that in folds 3,4,5,6,9 and 10 that the training error (red) continued to decrease over the epochs while the testing error has increased.  When error for testing and training start to diverge, you know the model is over-fitting, since test error is breaking down.
Comment: That doesn't fully answer my question. I know the principles of cross validation or bootstrap in general, I just wondered how to create the final model that I would use e.g. in a product then.
Do I just train on 100% of the training data and don't validate during training?
Comment: cv is just for parameter adjustment and to know what estimator and so on are good. If you are finished you build your pipeline on all your data. It can be still training data though. imagine you have 40 million rows in train and 5 mill in test. Then it would be suffiient if everything was fine. to just use train data, as fitting and deploying on all 45 would take for example 1-2 days longer and you are under time pressure in deploying and delivering. Than train data would be sufficient. to sum up: validation is done, you know your framework, deploy it.


How can I programmatically change the parse mode?

Question: We have a view that works with Search API and Solr search. The multiple search terms work with single quotes and with no quotes. I want to make the search terms work with double quotes as well. The issue is also listed here without a fix:
https://www.drupal.org/project/search_api/issues/2141575
I found that I can change the parse mode in the View > Query > Settings to direct method and the term with double quotes work just fine. I want to make this change using hooks. I have tried hook_search_api_views_query_alter and it does not work. Does anyone know how to change the parse mode in the query settings using hooks?
Answer: On Drupal 7, I've achieved this by using hook_views_pre_build() since this hook is executed before hook_views_pre_execute() and hook_search_api_views_query_alter(). Using code similar to the following will do the job.
$options = $view->display_handler->get_option('query');
$options['options']['parse_mode'] = 'TYPE_OF_PARSE_MODE';
$view->display_handler->set_option('query', $options);

Note that TYPE_OF_PARSE_MODE can be:

Direct query - direct
Single term - single
Multiple terms - terms


Why does pedal order matter?

Question: Why does the order in which I put my guitar/bass pedals matter?
For example, why does the compressor needs to be the first one in the order?
Comment: Just to add to Wheat and Peter's good answers:  Noise is another reason you'd want to order effects in a certain way.  For example, a noise gate as the first effect probably wouldn't work too well.  In general, [Some do this different] the groups are: (compression, overdrive, distortion), (wah), (modulation, pitchshift), (delays), (reverb), (noise gate).  Some groups can be moved around but the above general rule helps with noise and negative effects interaction.  An eq could be added anywhere in the chain though you'd probably want it after a compressor.
Answer: The short answer is yes, it matters. How much it matters, and whether it matters to you, depends on your pedals, the combinations in which you use them, and your desired sound.
Here are some general rules that most people follow; nothing's hard and fast:

Gain before synth. Effects come in two basic families. Gain effects alter the amplitude of portions of the incoming signal, and include EQ, compression, gating, wah, overdrive, distortion and most amp modeling. Synth effects take the incoming signal and generate a new signal based on it which then supplements or replaces the original, and these include chorus, flanging, phasing, octaves, delay/looping, and reverb.

There are obvious exceptions to this rule. Full-on "synth" effects, which replace your signal with another one outright (basically turning your instrument into a MIDi controller), generally come first; otherwise everything you're doing to your tone is lost when the signal is replaced. Also, amp modeling circuits typically go last in your chain, because hey, the amp comes last.

Wahs go first. Again, gain before synth, but more importantly, a lot of the most popular wah pedals, like the Cry Baby, are seen as "tone suckers", and this reputation is not undeserved; they're a "notch" equalizer, basically emphasizing one narrow frequency band while discarding all others. If a wah is a part of your chain, you want to do as little damage as possible, and then try to repair said damage downstream. It doesn't always work, and FWIW I say if this is a problem, you should spend good dough on a more transparent wah.
EQ next. This one's negotiable, but an EQ stage typically gives you the best results when you give it as clean a tone as possible. Most other effects, like reverb and overdrive, were originally done inside the amp circuitry, post-EQ. Following this rule is the biggest single reason to run your pedal board through the effects loop; that way, your signal hits the preamp of your amp head first and you don't have to spend a hundred bux or more on an actual EQ pedal.
Gating before compression. If you have an expander or "noise gate" in your signal chain, it should typically go before any compressor you have. This is so the compressor never sees your axe's noise, and so doesn't try to boost it above a downstream gate's ability to suppress it.
Compression before overdrive. Again, negotiable, but the objective is usually to maintain the distortion the way the natural "feedback" of a 100W full-stack into your guitar's strings would do. So, you use the compressor to keep the input into the overdrive "hot", so as the strings naturally decay the sound evolves into the classic single-toned "feedback" sound.
Distortion and Synth inline, "clean" effects in the loop. The main difference between an inline effect and an effect in the effects loop is pre-EQ versus post-EQ (and pre/post preamp clipping aka amp drive channel), and therefore between your axe's raw signal and the shaped and gain-boosted signal coming out of the preamp stage. In reality, how much and exactly what parts of your pedal board go inline versus in the loop is probably one of the biggest variables in pedal board design, even when following all other rules. Some players run everything inline, others loop their reverb and chorus type effects, others loop their looper, still others loop everything. This rule basically says to let the preamp do its job when and where it matters; if the effect produces an output within which it's easy to pick out your "native" tone, then put it in the loop, allowing you to shape the tone the effects will get.
Reverb last. Again, gain before synth, but this one stems more from what a reverb unit is supposed to emulate; a big, spacious, lively room that echoes what's finally coming out of the speakers of your amp. While actual reverb units in guitar amps were placed before the power amp stage by necessity (and thus you always got your reverb before the warm crispy goodness of the 6L6 or EL84 tubes), the point was to produce this kind of sound.

Again, there are exceptions; sometimes you'll want a looper last, or even a flanger or phaser, to take the "wet" reverbed signal and record it or further mess with it.

Now, given all that, you are free to follow absolutely none of it. The number one rule is "experiment"; you will get different sounds by putting different pedals in different places, and what you want may not be what the next guy wants. Putting your wah after a distortion or fuzz pedal instead of earlier in the chain typically gives a much more pronounced wah effect than vice-versa. If you want your sound to decay from a mild break-up back to clean, but a relatively constant volume level throughout instead of a volume dropoff, then by all means put your compressor after your Tube Screamer pedal. If you want to emulate a highly "pushed" Fender Twin Reverb, then you should definitely put your reverb before your gain pedal. If you want angry, sharp, dirty nu-metal grind, then put the EQ last so you can further shape your distortion pedal's output. A looper can go almost anywhere; it depends on whether you want the looped signal to always have the effects that were on when you recorded the loop track, or if you want to be able to switch the looped sound from clean to dirty. Anything goes; the "wrong" pedal order won't set your rig on fire. What matters is your sound and how you want to get it.
Comment: Interestingly, I always have my Wah as my penultimate pedal, with delay as the only one after it, as I don't like my effects being given a narrow notch. I'd rather use that notch on the wide soundscape I have post-effects.
Answer: This is a complicated subject. The answer depends on which effects pedals you are using. The best way to learn the results of putting your pedals in a different order is simply to plug them together in different configurations and listen to the results.
For example, a compressor works best if it is first, because a compressor works best if it receives a completely clean guitar signal that has not been changed by other effects. If you were to run your guitar into a digital delay first, making a large amount of echo sounds, the compressor would not be able to compress the echo-inflected signal effectively and the sound would be very unnatural.
You would also probably not want to use a modulation effect (reverb, echo, flanger, phase shifter) first and then send that signal to a distortion pedal. All of the crisp echoes and tonal changes in the sound (from a flanger or phase shifter, for example) would be smeared together by the distortion pedal, creating a muddy and indistinct sound. You would probably want the distortion pedal to be first, and then to send the distorted sound to the modulation effect.
Again, if you have several separate effects pedals, you should simply experiment with different orders of pedals and let your ear be the judge.
Comment: And if you find that putting them in a non-standard order creates an effect that you like, then by all means, take advantage of it!
Comment: A gated reverb can be a wonderous thing :)
Comment: Actually a subtle compressor may improve sound of echo delay
Answer: Pedals often have a different effect depending on the pitch and volume etc. of the sound going into them. If a pedal changes one of these attributes of the sound, it means the behaviour of every pedal after it could be changed.
Let's say you're only using an autowah pedal. It will respond to the volume of the signal, giving loud notes/chords quite a different shape and tone from quiet ones.
If you put a compressor on after it, the autowah pedal still affects the tone and shape of the sound in the same way. The only difference is that the dynamic range (i.e. volume differences) of the final output are reduced.
If you swap the pedals over so the compressor is first, you're altering the dynamic range going into the autowah. That means it won't vary the tone as much between the loud and quiet bits, so the overall effect is reduced. That may or may not be desirable, depending on what you want to achieve.
Volume is just one example, but it isn't the only consideration. It's often a question of just experimenting with effect orders to see what gives you the best overall sound.
Comment: Adding a compressor right before a whammy/pitch shifting pedal considerably helps improve the pitch tracking. Also increases the digital noise, if you're going for that Radiohead pitch shifter noise.
Comment: @DanGayle I had always heard a Whammy needs to go first (or right after a tuner, if a tuner is present) but you would put a compressor first and the Whammy second? Or do you only mean if the Whammy is further down in the chain?
Comment: @aeroNotAuto The guidance to put the whammy near to front is likely because you may want a clean signal going into it, for tracking purposes. Imagine a chorus pedal before a whammy, it won't track worth anything because a chorus pedal messes with the pitch. Things like distortions/fuzzes/compressors don't mess with pitch, making them largely safe to use in front. The reason I mentioned to put the compressor before the whammy is because it evens out the volume, making it easier for the Whammy to track.
Answer: Some pedals such a fuzz pedals or wahs are very temperamental about the order in which they're placed. Typically, these two types of pedals like to see the signal straight from the guitar, before other pedals and especially before any buffered pedals. It's an impedance thing, although you'll have to Google the specifics about that.
Long story short, a fuzz after another pedal usually sounds like crap when compared to when it's first in the chain.
Comment: A fuzz doesn't really need a compressor, since that's what the effect is basically doing. It's compressing the hell out of your signal, then chopping off the top half. That's why guys like David Gilmour and Carlos Santana never used compressors back in the day, because their fuzz pedals provided all the sustain they needed.
Comment: So, should the fuzz go before the compressor?

Why does pedal order matter?


Topology-Base for a topology

Question: We know that  the class of open intervals $(a,b)$, where $a,b$ are rational numbers is a countable base for $\mathbb R$.
But, $[a,b]$ where $a,b$ are rational numbers does not produce a base for $\mathbb R$.
Can we say that any $(a,b)$ or $[a,b]$ where $a$ is rational number and $b$ is an irrational number produce a base for $\mathbb R$?
Comment: Do you mean "base for the standard topology on the reals" or "base for *some* topology on the reals" ?
Comment: Obviously closed intervals can't, since they are not open in $\mathbb R$. For open intervals, remember that both the rationals and the irrationals are dense in $\mathbb R$.
Comment: @Henno,Base for the standard topology on R.
Answer: I assume that when you say "a base for $\mathbb R$" you mean "a base for the standard topology on $\mathbb R$. With that, the answer to your question is no since $[a,b]$ is never an open set in the standard topology on $\mathbb R$.
If you also meant to ask whether the collection of all $(a,b)$ where $a$ is rational and $b$ is irrational forms a basis for the standard topology on $\mathbb R $ then the answer is yes.
Answer: I am not sure if this is related to your question at all, but we could say that the family $\{ [a,b]\  \colon  a,b \in \mathbb R, a  <c< b\}$ form a neighborhood basis at the point $c$ with respect to the Euclidean topology. This is saying that $c$ is in the interior of $U$ iff there is some closed interval of nonzero length such that $c \in [a,b] \subseteq U$. The notion of a neighborhood basis is different than a base for a topology but might lead to confusion.

Topology-Base for a topology


How to call php snippet which is save as basic page?

Question: I have a php code as below:
<code>$("#tbMGroup tr.odd").click(function() {
              $("#m_id").val($(this).attr("m_id"));
              $("#form1").first().attr("action", "search.php");
              $("#form1").submit();
            });
</code>
but,
I have add search.php to a basic page. now, these code need to call search.php when mouse click, I don't know how to call search.php snippet, because search.php now is not a independent file, it is a snippet.
Thanks for your help...
Comment: Please try to explain more cleay what you want to achieve and what the problem is?
Comment: I have add search.php to a basic page. now, these code need to call search.php when mouse click, I don't know how to call search.php file, because search.php now is not a independent file, it is a node.
Answer: I think you should use hook_menu to define the path the drupal way and rewrite your form using drupal FAPI. This gives you a clean system.
Comment: Do you have any sample code for me reference? Thank you very much..
Answer: I figured out the way, just changed my snippet to:
<code>$("#tbMGroup tr.odd").click(function() {
  $("#m_id").val($(this).attr("m_id"));
  $("#form1").first().attr("action", "/node/nid");
  $("#form1").submit();
});
</code>
It works.


Why doesn't Python exit from a raised exception when executed with an absolute path?

Question: SOLVED: Rebooting the machine appears to have removed the issue.  I will update if the problem returns.
I'm having an issue where Python2.6 hangs after an exception is raised, specifically when foo.py is called with an absolute path (/home/user/bar/foo.py).  I am then required to ctrl+c out of the program.  If called from within the bar directory as ./foo.py or from the root directory as ./home/user/bar/foo.py, the program terminates correctly.
foo.py:
#!/usr/bin/env python2.6
print 'begin'
x = [0, 1, undefined]
print 'x'

or
#!/usr/bin/env python2.6
print 'begin'
raise Exception('stopping here')

I may also mention that a sys.exit() works fine, without issues.
#!/usr/bin/env python2.6
import sys
print 'begin'
sys.exit(0)

What is happening to the exception that is failing to terminate the program?  This is likely specific to my configuration.  Where should I begin looking for a solution?
EDIT:  execfile('/home/user/bar/foo.py') works fine if running interactive mode.  Additionally, running nohup /home/user/bar/foo.py & results in a hanging process that must be killed.
Running CentOS release 6.3 (Final).  This issue did not always exist.  This only started about a month ago over a weekend (I was not using the machine at that time).
UPDATE: Debugging with GDB, the backtrace points to libpthread.so.0.
#0  0x000000364340e890 in __connect_nocancel () from /lib64/libpthread.so.0
#1  0x00007ffff18960d8 in ?? () from /usr/lib64/python2.6/lib-dynload/_socketmodule.so
#2  0x00007ffff189815c in ?? () from /usr/lib64/python2.6/lib-dynload/_socketmodule.so
#3  0x00007ffff7d0a706 in PyEval_EvalFrameEx () from /usr/lib64/libpython2.6.so.1.0
#4  0x00007ffff7d0c797 in PyEval_EvalCodeEx () from /usr/lib64/libpython2.6.so.1.0
#5  0x00007ffff7d0abe4 in PyEval_EvalFrameEx () from /usr/lib64/libpython2.6.so.1.0
#6  0x00007ffff7d0bccf in PyEval_EvalFrameEx () from /usr/lib64/libpython2.6.so.1.0
#7  0x00007ffff7d0bccf in PyEval_EvalFrameEx () from /usr/lib64/libpython2.6.so.1.0
#8  0x00007ffff7d0c797 in PyEval_EvalCodeEx () from /usr/lib64/libpython2.6.so.1.0
#9  0x00007ffff7c9adb0 in ?? () from /usr/lib64/libpython2.6.so.1.0
#10 0x00007ffff7c70303 in PyObject_Call () from /usr/lib64/libpython2.6.so.1.0
#11 0x00007ffff7d04dd3 in PyEval_CallObjectWithKeywords () from /usr/lib64/libpython2.6.so.1.0
#12 0x00007ffff7d28cd2 in PyErr_PrintEx () from /usr/lib64/libpython2.6.so.1.0
#13 0x00007ffff7d29297 in PyRun_SimpleFileExFlags () from /usr/lib64/libpython2.6.so.1.0
#14 0x00007ffff7d35c32 in Py_Main () from /usr/lib64/libpython2.6.so.1.0
#15 0x000000364281ecdd in __libc_start_main () from /lib64/libc.so.6
#16 0x0000000000400649 in _start ()

Anybody know what this means?
Comment: Do you have a box which is similarly configured? Are you able to reproduce this issue on some other box?
Comment: Also I just tested this on Python 2.4.3, 2.6.5, and 2.7.3 and was unable to get the program to hang. Something else on your system (configuration setting or something) must be contributing somehow.
Comment: Have you tested this with any other versions of Python to see if the issue is limited to 2.6? It would help in being able to reproduce the error.
Comment: I do not have sudo privileges on this machine to try another version.
Comment: Tested on Python 2.4.3/RHEL 5.5, no repro
Comment: @user1742131 hm, how is it that you need sudo privileges to run another version of Python?
Comment: @DavidZaslavsky: Most probably he is talking about doing a system wide install of a new Python version.
Comment: Correct, I cannot install another python version.  Also execfile() works fine with an absolute path.
Comment: @Sanjay ah, the wording implied there was another Python version already installed which could not be run without `sudo` access. (Of course one _can_ always compile Python and try to run it directly from the build directory, but probably not worth the trouble for this)
Comment: the issue might be that the process is suspended when it tries to print something to stderr. You could test it with a bash script: `echo test >&2` Check your terminal settings (try: `stty sane`, `reset`)
Comment: What sort of machine is this running on?  It seems to be quite specific to this machine.  Is this a 'standard' build (ie - the distro version) of Python or was it built in-house?  Are you sure you're actually running the python interpreter or is there a wrapper script involved?  Do you have anything weird going on in your system's site.py?
Comment: The bash script works fine. `stty sane` doesn't help.
Comment: Running CentOS.  The problem didn't exist before.  Something happened at some point to something.  The python version hasn't changed.  Problem exists if I run it from a bash script, run with `nohup`, run by specifying `/path/foo.py` in the terminal, or run by calling `python /path/foo.py`.
Comment: does `print("abc")` as the only line in the Python script work?  If you set `sys.excepthook` to write to a file (flush it on every write); do you see any tracebacks in the file?
Comment: `print("abc")` works fine.  I don't understand what you mean with the `sys.excepthook`.  Care to explain with detail?  (I've added debug info up top btw.)
Comment: What's really odd is your gdb traceback shows Python down in the socket module - but your example code does not show any use of the socket module. Any ideas about your code that could shed light on that?
Comment: Another user ran the debugger.  He may have used different code.  More than one of us is trying to fix the issue.
Comment: Looking at the stack more closely, it looks like the exception fires and then Python starts running some code to print out the exception that then leads it down into the socket module where it never returns. It's not clear why printing an exception would lead into the socket module. Can you produce a stack trace that matches your example script?
Comment: I ran gdb myself and got essentially the same thing. (The OP now shows my own debug traceback.)
Comment: Thanks everyone for the help.
Answer: This exact issue has been biting me for awhile now on a RHEL 6 machine.  In certain cases, Exceptions cause a hang.  In fact, I was able to take your code verbatim and reproduce the symptom.
Thanks to the abrtd answer, I determined that abrt-addon-python package was installed which puts abrt_exception_handler.py into the site-packages location, and that is called during python startup.  This file overrides the sys.excepthook function which contacts the abrt daemon using sockets.  See ABRT Project Doc for more information.
I verified that adding -S to the python invocation prevents the hang.  This is not a good solution, however, because the -S option prevents ALL site packages from being imported on startup.
A better solution is to add the following in your python code:
import sys
sys.excepthook = sys.__excepthook__

which restores the original exception hook and prevents the hang.
Answer:
please inspect sys.path for non absolute directories.
you can always break into it with a debugger, e.g. gdb
sometimes I have stuff in PYTHONSTARTUP, which causes the interactive interpreter to do something different...
strace can aslo be your friend
Answer:
Reboot the machine.

Bowing to the graces of the all-powerful admin, I was able to get the machine rebooted.  All is well.  I'll update the question if the problem returns.
Answer: I tracked this problem down. It is trying to write to a socket that was held open by abrtd.
Restarting abrtd 'fixed' the issue. This is why the machine reboot worked. I haven't found the root cause of the issue though.


1959 White Sox World Series roster

Question: I thought the roster for the 1959 WHITE SOX  World Series had  25 players.  I can find stats on the 21  that played and   I  have found  3 that did not get into a game (Battey, Latman,  Arias) .  Was there  a 25th  player????
Comment: baseball-reference.com. They like all other sites show stats on 21 players who got into a game for the Sox during the 1959 World Series.  The Sox could not answer my question, they sent me a list of 40 who played for the Sox during the entire 1959 season. They have not responded to a follow-up  .  The Hall of Fame - Cooperstown sent me 1959 White Sox World Series Program showing all 25. The 4 not seeing any playing time were Battey , Arias , Moore,  and Mcbride.  Sabr.org ( society for American Baseball Research has an INCORRECT bio  on Mcbride (" left off the post season roster")Steve Fox
Comment: I don't see any site that lists the entire roster specifically for the World Series at least in a brief check.
Comment: What site did you use for the initial 25 number? And where did you find the 3 who did not play? And are you including pitchers?
Comment: Wow! Amazing work Steve Fox! I didn't ask this question but was glad to see someone found some good info.
Comment: Thanks Paul . After contacting SABR.org ,they confirmed this with reference from the Chicago Tribune and thanked me and would contact their webmaster for a correction to Mcbride's bio. The Hall of Fame  was very friendly and helpful. (not the Sox or Dodgers)
Answer: Steve Fox-
You almost got them. Moore did play as a reliever in game six (ninth inning) and Latman didn't play at all. So, Battey, Latman, Arias, and McBride didn't play.
Comment: If you can you should add a reference to where you found this
Comment: Thanks Keith, you are the only one in almost a year that noticed my error. I did notice it when I reread it later  but never bothered to correct . It is  very apparent , because all the websites do show the 21 players that got into a game for the Sox in the 1959 Series. Also SABR has still not corrected  Mcbride's bio( " left off the post season roster")  Great work . THANKS again.     Steve Fox

1959 White Sox World Series roster


NodeJS how to set csrf token correctly?

Question: This is a continuation of this question: Rest-auth still reports the error of "CSRF cookie not set", but I've set the csrf
The code I used for server.js is:
const cookieParser = require('cookie-parser');
const csrf = require('csurf');
app.use(cookieParser());
app.use(csrf({ cookie: true }));
app.use(function (req, res, next) {
  res.cookie('csrfmiddlewaretoken', req.csrfToken());
  next();
});

However, the result is

The reason I think is that I didn't set the cookie correctly. I tried to remove app.use(csrf({ cookie: true }));, but then it shows an error of csrf misconfigured.

In fiddler, I can see there are two tokens in the cookie, one default, one set by res.cookie('csrfmiddlewaretoken', req.csrfToken());, how can I set the cookie in the correct way?
UPDATE:
I kind of figured out a brute-force way to change the name of _csrf to csrfmiddlewaretoken.
app.use(function (req, res, next) {
  res.cookie('csrfmiddlewaretoken', req.cookies._csrf);
  next();
})

Then, in fiddler, I see the value are same.

But the django rest-auth still reports fail like:

Maybe that's not about the name. I am still researching....
Comment: What does this has to do with django-rest-framework ?
Comment: I used django rest-auth package here, logging in and registration use POST to url(r'^rest-auth/', include('rest_auth.urls')),
url(r'^rest-auth/registration/', include('rest_auth.registration.urls')). And the error information is from there. You can look at my former question,https://stackoverflow.com/questions/42099083/rest-auth-still-reports-the-error-of-csrf-cookie-not-set-but-ive-set-the-csr. Someone helped me figure out that only csrfmiddlewaretoken can be picked up by django, not _csrf.
Comment: My current problem is there are 2 csrf tokens in my cookie (as the screeshot above), _csrf and csrfmiddlewaretoken. The value csrfmiddlewaretoken is incorrect so the authentication fails. I think the value of _csrf is correct but the name is inproper. It should be changed to csrfmiddlewaretoken.
Answer: JiPanNYC, maybe you forgot to add
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.TokenAuthentication',
    )
}

in your settings.py

NodeJS how to set csrf token correctly?


Add HTML Chars To Breadcrumb Kickstart 2

Question: How does one enable html special chars (eg. ® ) in the breadcrumb?
Apparently, the Kickstart 2 uses a custom Crumbs module and I can't figure out how to override the PHP generated as with a 'regular' Drupal theme since it doesn't use the core theme_breadcrumb() function.
Comment: Can you provide more information where you want the special char to show up? It seems this is a bit misleading, and you rather just want to know "How can I change a breadcrumb item link text", right?
Comment: So, to clarify: You use stuff like "®" in a node title, but in the breadcrumb it shows up as "®" ?
Answer: There are different parts to this answer.

since it doesn't use the core theme_breadcrumb() function.

By default, it does use theme('breadcrumb').
But you should have a look at the settings in admin/structure/crumbs/display.
But the check_plain() that causes special characters to be double-escaped happens in theme_crumbs_breadcrumb_link() and theme_crumbs_breadcrumb_current_page(), which you could also override.
You could also look at the $double_encode option in htmlspecialchars(), so you could use your own version of check_plain().
This being said:
Simply omitting the sanitization for all breadcrumb links is a bad idea, and potentially exposes your site to script injection. If anything coming from a non-trusted source ends up in the breadcrumb, or if people add broken html into a node title or menu link title or elsewhere, this could cause broken or malicious html on your site.
I think the better option is to just use the literal character in the node title, instead of the html entity.

Some general info:
With Crumbs, every breadcrumb item title is provided by a plugin. The plugins take these from menu links, from the title / title callback of the router item, or elsewhere. In most cases there is already an existing plugin which provides the breadcrumb item title you need.
Otherwise you can write your own plugins. I can give you a hint about that, but I need more information where you want the special char to show up. (I will edit the answer then)
Comment: Please provide a hint. I need to be able to have breadcrumb strings and links like "MyTrademarkedProduct®"
Comment: but which breadcrumb item should have this link text? Is this a node title?
Comment: Yes, it's the title of a node... a Basic Page, although we will also want other content types (Commerce Products) to also have that capability.
Comment: ok, so now you have the node title show up as breadcrumb text, but the html chars are not showing as expected? are they filtered out?
Comment: I did a quick experiment with "»" in a node title on a local test site. This is escaped as "»" both on the page title display and in the breadcrumb. The title is simply meant to be sanitized, otherwise you could easily get into some injection problems.
Comment: But this being said, why don't you simply copy+paste the original character into the title? It is all UTF-8 so it should be possible.


How can I sort this using pivot as the leftmost key?

Question: How can I sort this using pivot as the leftmost key in quick sort? I'm getting the answer incorrectly.
public class QuicksortApp {
    private static int []a = {10, 12, 9, 23, 45, 31, 67, 44, 32, 77};

    public static void main(String[] args) {

        int left = 0;
        int right = a.length - 1;

        // prints the given array
        printArray();

        quickSort(left, right);

        System.out.println("");

        //prints the sorted array
        printArray();

    }

    private static void quickSort(int left, int right) {

        // If both cursor scanned the complete array quicksort exits
        if(left >= right)
            return;

        // We took the right most item of the array as a pivot
        int pivot = a[right];
        int partition = partition(left, right, pivot);

        quickSort(0, partition - 1);
        quickSort(partition + 1, right);
    }

    private static int partition(int left, int right, int pivot) {
        int leftCursor = left - 1;
        int rightCursor = right;

        while(leftCursor < rightCursor){
                while(a[++leftCursor] < pivot);
                while(rightCursor > 0 && a[--rightCursor] > pivot);
            if(leftCursor >= rightCursor) {
                break;
            } else {
                swap(leftCursor, rightCursor);
            }
        }
        swap(leftCursor, right);
        return leftCursor;
    }

    public static void swap(int left, int right) {
        int temp = a[left];
        a[left] = a[right];
        a[right] = temp;
    }

    public static void printArray() {
        for(int i : a){
            System.out.print(i + " ");
        }
    }
}

Comment: shouldn't your pivot be `pivot=a[left]` if you want the left most key as your pivot?
Comment: I put that so....but it's not working.
Answer: Try this
public class QuicksortApp {
private static int[] a = { 10, 12, 9, 23, 45, 31, 67, 44, 32, 77 };

public static void main(String[] args) {

    int left = 0;
    // you do not need to pass the length -1 because the for loop takse care
    // of it.
    int right = a.length;

    // prints the given array
    printArray();

    quickSort(left, right);

    System.out.println("");

    // prints the sorted array
    printArray();

}

private static void quickSort(int left, int right) {

    if (left >= right)
        return;
    //no need to pass the pivot since the pivot will always be the left most element in the array
    int partition = partition(left, right);

    quickSort(0, partition - 1);
    quickSort(partition + 1, right);
}

private static int partition(int left, int right) {

    int pivot = a[left];

    int splitter = left;
    /*
     * This is cleanest approach to the algorithm. I am not going to mention
     * the pseudo code of the alog but since you were trying to modify the
     * array in place,you need to decide what will be your separation
     * point,In my case this is called "splitter". The splitter takes care
     * of creating a boundary between the elements greater than and lesser
     * than the pivot
     */
    for (int i = left; i < right; i++) {
        // Check if the element currently being scanned is less than the
        // pivot
        if (pivot > a[i]) {
            // If it is lesser,then left most element which is greater than
            // the pivot with this element and increase your boundary
            // pointer(splitter) by one
            swap(++splitter, i);
        }
        // Do not do anything if the element is lesser than the pivot.

    }
    // swap the pivot and element at the splitter position
    // Please note that the splitter position contains the right most
    // element with a value lesser than the pivot
    swap(left, splitter);
    // return the splitter,which indicates the position of your pivot and
    // provides you information regarding how you should split and partition
    // to implement the Divide and Conquer Paradigm
    return splitter;
}

public static void swap(int left, int right) {
    int temp = a[left];
    a[left] = a[right];
    a[right] = temp;
}

public static void printArray() {
    for (int i : a) {
        System.out.print(i + " ");
    }
}
}

I have tried explaining with as many comments as possible.I presume this is some sort of assignment,So please try to understand the logic because the algorithms only get more complex as they come.This is one of the most simple algorithms.


What does it mean to have a voice of a "tenor 1"?

Question: When I sing I like the higher keys. I do not have that low voice that most people have. Even some tenors have that low voice. Sometimes I sing hymns a major thid higher than the keys found in the hymn books. Some of the melodies in the hymn books are extremely low for me. I find that Bb2 is too low for me. That note is extremely low.
G4 on the other hand is not that difficult to sing. The easiest key for Silent night is D.
My teacher told me that I have the voice of a "tenor 1" in the choir.
What does it mean to have a voice of a "tenor 1"?
Answer: Note that tenors are disposed differently in mixed choirs (where they are topped by alto and soprano) and in men's choirs where they are the highest voice.  When your teacher talks about "tenor 1", he probably talks about a men's choir disposed as TTBB (tenor 1, tenor 2, baritone, bass).  This is similar to barbershop which is TLBB (tenor, lead, baritone, bass).  Barbershop's tenor tends to deploy head voice (or even falsetto) more amply than "standard" tenor 1, usually supplying a harmony voice to the lead carrying the melody.  In classical choirs, the role of tenor 1 tends to be less complimentary.
Either way, in an all-male choir the ability to smoothly move into a heady or light register tends to be appreciated in the highest voice while it may not be as  popular in a mixed SATB choir.  Also, in a TTBB or TLBB choir, the low notes are sufficiently well catered for that the need to go low for first tenor just does not arise.
Answer: Tenor 1 voice is usually referred as "first tenor". Quoting Wikipedia:

Men's chorus usually denotes an ensemble of TTBB in which the first tenor is the highest voice.

Typically (but not always) the 1st Tenor part is the melody, with the other parts as harmony(s).

So basically tenor 1 is taking care of high part of the tenor range.
Comment: what range is tenor 1?
Comment: @Hank Basically the same as tenor, but T1 will be more comfortable, and so, have more power in the highest part of the tenor range.
Comment: Tenor parts are not that high in beginner choirs. A tenor might not even need to sing above F4. For a tenor this is not a very high note at all. I always thought that tenors needed to sing at least up to Ab4. Tenors parts are often kind of low. Perhaps professional choirs have high tenor parts


Why is the correlation between two data series negative when the top half and bottom half are both strongly correlated?

Question: I have two time series of data variables with each having 111 data points.
The data series should be strongly correlated given the nature of what is being explored.
However, the correlation between the data series is roughly -0.03 which confused me.
To explore further, I checked the correlation between data points 1-62 and 63-111 separately.
The correlation between the data series for points 1-62 was 0.83 and the correlation between the data series for points 63-111 was 0.55.
It is surprising to me that it is -0.03 for the whole series when they're positively correlated when split into two subsections.
Is this possible or am I making a mistake?
Comment: Have you plotted the data on a scatter plot with the two halves in different colors?  It might be that the first points fit a rising straight line and the last ones fit a falling line.  This might be a better fit for stats.stackexchange
Answer: Yes, and it would make sense if you think harder about it.
Take extreme and simplest example of 4 points, no pairs on the same horizontal line or vertical line.  Split the four points into pairs, each will be perfectly correlated, right?
Now imagine the 4 points are
$$
\pm (10,10) \pm (10^{-10},-10^{-10})
$$
so a very thin rectangle rotated at 45 degrees.  The four on the whole has $\rho_{xy}\approx +1$, but if you take the pair
$$
(10,10)\pm(10^{-10},-10^{-10})
$$
they are perfectly negatively correlated, similarly for $(-10,-10)\pm(10^{-10},-10^{-10})$.

In general, you can only split into two halves and expect the result to work if the two halves are about the same, in your time series case it means with the same model (same mean, same autocovariance).


Flink timeout using KeyedCoProcessFunction and order of reading for FlinkKafkaConsumer

Question: I am using the KeyedCoProcessFunction class in Flink DataStream APIs to implement a timeout like use case. The scenario is as follows: I have an input kafka topic and an output Kafka topic,  a service reads from the input topic processes it (for variable amount of time) and then publishes the response in the output kafka topic.
Now to implement the timeout (must be using Flink datastream APIs), I have a FlinkKafkaConsumer that reads from the kafka input topic, and another FlinkKafkaConsumer that reads from the kafka output topic. I am connecting the two streams, and  using the processElement1 I am registering a timer and waiting either that the onTimer method be fired (a timeout is declared), or the processElement2 is fired before and hence I delete the timer and do not declare a timeout.
While testing on large scale events, I am seeing NULLPTREXCEPTION and I suspect that processElement2 is fired before ProcessElement1, in the situation described above can the scenario of reading an element from the output topic  happen before reading from the input topic due to any reason  (knowing that the time taken to process the element by the service might take seconds)  and in such case what is the best case to implement the timeout functionality as described above strictly using the Flink DataStream APIs, Any hint please?
Thank you.
Answer: Yes, there's no guarantee that Flink will call the processElement1 method before processElement2. It's likely, but not certain. Or in other words, it probably won't always be the case.
This is exactly the same scenario as you will find in the LongRideAlerts exercise in the Flink Training -- https://github.com/apache/flink-training/tree/master/long-ride-alerts -- so you might emulate the solution used there. The logic is this:

whichever event (for a given key) arrives first, from either stream, store it
if it is the input event (from topic1) that arrives first, set a timer
if it is the output event (from topic2) that arrives second, before the timer fires, delete the timer
whichever event (for a given key) arrives second, from either stream, clear the state (that is shared by the two streams)
whenever the timer fires, use the input event saved from topic1 in keyed state to create a report and clear the state

This solution does leak state whenever an input event from topic1 is missing. See the discussion accompanying the training exercise for how to deal with that, if it matters (short version: use state TTL).
Comment: It is possible to force Flink to control the order in which a two-input stream operator reads from its inputs, but if you use that interface deadlocks are possible, and checkpointing may not work. In general it's better to cope with not knowing when the events will come. And even if you did use that mechanism, you would still not have a 100% guarantee.
Comment: The ExpiringState exercise you found, or https://github.com/apache/flink-training/tree/master/rides-and-fares, these are examples that involve two separate input streams, but they don't have quite the same "match two events before a timeout" requirement as in the first example I shared.
Comment: Perhaps I have completely misunderstood your question.
Comment: Well, if it is indeed one minute later then of course it is extremely unlikely. But the issue is that various parts of the pipeline are sometimes running in different threads, and sometimes in different processes, and sometimes on different machines. So a lot of things outside of Flink can have an effect.
Comment: Even If processElement1  comes way before processElement2 there is no guarantee on the order of calling, why is that? is there any way of forcing Flink to process first whichever element arrives first?
Comment: between were routing me to this https://github.com/ververica/flink-training-exercises/blob/master/src/main/scala/com/ververica/flinktraining/solutions/datastream_scala/process/ExpiringStateSolution.scala
Comment: Thank you sir, the example you mentionned in your first reply deals with one input stream 'rides', while in my case i have two different input streams (two different kafka consumers), so is it possible to route two different streams of the same type to the same Flink process function? and how about read ordering in such case is it first come first served?
Comment: Yes, you can route two streams of the same type to a CoProcessFunction, and you shouldn't expect to have any influence over when the operator will read from one input vs the other.
Comment: when i have two different input streams keyed by the same id, and read from two different sources (say two different kafka topics, with first stream is published/read from topic1, and after few seconds second stream is published/read from topic2), how would i implement a timeout functionality (if have not received an event from stream 2)...
it looks like impossible to implement using flink datastream APIs if i have no control over which element will be read first by a two inout stream operator? thank you so much I am sorry but i still do not get solution point.
Comment: It works just as I've outlined in my answer above (which I've edit a bit to try to clarify things). The reason this works is because the state and timers are per-key, and are shared between the two input streams. It makes no difference to the processing logic that the events are coming from two different streams. In the LongRides example there are START and END events in the same stream, but they could just as well be coming from different streams.
Comment: Thank you so much Sir. So  I can conclude that if an event is available now to Flink and if  another event will be available 1 minute later (same key), as a result of connecting the two streams,  Flink does not provide any guarantee that the event available now will be processed before the event available 1 minute later? is that accurate? and if that is the case why it would do that maybe is counter intuitive.  Thanks again.


pytest functions don't return data to be used in following functions in the same pytest file?

Question: I have developed a program (file.py) formed by a few functions and now I want to test each of these functions from test_file.py. I have tested the first function correctly but when I have wanted to test the second function I have noticed that I need the data generated from the first function. What is the best way to do this?
My first attend has been this
def test_load_sample():  # The first test for the first function
    '''Verify all rows of the body of the vcf file are taken'''
    data_to_test = load_sample (NAME_FILE_1) # load_sample() is the first function of file.py
    return data_to_test     # I need this data for the following tests
    assert len(data_to_test) == 1400

data_to_test = data_to_test

Because I expected that the function test_load_sample would return the data I want for the second test. However, it seems that pytest function doesn't return what has been tested?
What is the best way to do this? Am I doing something wrong? This is my first time working with pytest.
EDIT
# File.py

input_data = 1

function_1(data):
return data +1

data1 = function_1(input_data)

# Now input data is 2

function_2(data):
return data +1

data2 = function_2(data1)
...

Now I want to test the function to test function_2
test_function_1():
data_to_test = function_1(data_input)
assert data_to_test = 2

test_function_2():
# I need data_to_test from the previous function

Answer: What you are doing is not the convention (probably anti-pattern). Some points that you should consider:

Test functions are not meant to return any value. They are just used to run the source code and perform assertions on the results, nothing more.
Each test should be designed to be isolated from each other, in a way that if test1 fails, that doesn't mean test2 to test10 will also fail.
Also, such isolation is needed because depending on the way tests are run, they may be executed in parallel (at the same time) and not sequentially. Thus making test2 to depend on test1 would fail if there are times that test2 was executed first.

If you have a common resource that you want to share across multiple testcases, configure it in the tests. So if the output of load_sample(NAME_FILE_1) will be used in multiple tests and you don't want it to be re-executed anew for every test case, you may want to use a pytest fixture with session scope.

session: the fixture is destroyed at the end of the test session.

So for this test:
import pytest

@pytest.fixture(scope="function")
def my_funcion_fixture():
    print("Function fixture initialized")
    return 123

@pytest.fixture(scope="session")
def my_session_fixture():
    print("Session fixture initialized")
    return 456
    # Ideally, this is where you put <data_to_test = load_sample (NAME_FILE_1)> and return the <data_to_test>

def test_first(my_funcion_fixture, my_session_fixture):
    assert my_funcion_fixture == 123
    assert my_session_fixture == 456

def test_second(my_funcion_fixture, my_session_fixture):
    assert my_funcion_fixture == 123
    assert my_session_fixture == 456

def test_third(my_funcion_fixture, my_session_fixture):
    assert my_funcion_fixture == 123
    assert my_session_fixture == 456

def test_fourth(my_funcion_fixture, my_session_fixture):
    assert my_funcion_fixture == 123
    assert my_session_fixture == 456

Output
$ pytest -q -rP
....
[100%]
================================================================================================= PASSES ==================================================================================================
_______________________________________________________________________________________________ test_first ________________________________________________________________________________________________
------------------------------------------------------------------------------------------ Captured stdout setup ------------------------------------------------------------------------------------------
Session fixture initialized
Function fixture initialized
_______________________________________________________________________________________________ test_second _______________________________________________________________________________________________
------------------------------------------------------------------------------------------ Captured stdout setup ------------------------------------------------------------------------------------------
Function fixture initialized
_______________________________________________________________________________________________ test_third ________________________________________________________________________________________________
------------------------------------------------------------------------------------------ Captured stdout setup ------------------------------------------------------------------------------------------
Function fixture initialized
_______________________________________________________________________________________________ test_fourth _______________________________________________________________________________________________
------------------------------------------------------------------------------------------ Captured stdout setup ------------------------------------------------------------------------------------------
Function fixture initialized
4 passed in 0.07s

As you can see, we are able to use all fixtures in all our tests. The only difference is that our session fixture my_session_fixture was only instantiated once and not re-executed for every test case.
Answer: I have figured out how to do this
def test_load_sample():
    '''Verify all rows of the body of the vcf file are taken'''
    data_to_test = load_sample (NAME_FILE_1)
    return data_to_test
    assert len(data_to_test) == 1400

data_to_test = test_load_sample()
# Now, data_to_test can be used in the following test functions


Is every point on a Menger Sponge visible from the outside?

Question: Choose an arbitrary point on the surface of a Menger Sponge. Can you find a straight line starting at that point and extending beyond the sponge that doesn't intersect the sponge anywhere else? That is, is there a position and angle 'outside' the sponge from which an observer could see that point?
In one sense it seems the answer should be 'no', because a point on the sponge can be inside arbitrarily many twisting tunnels. But then again the construction of the shape means that every point is somehow 'near' the outside.
Answer: Yes, the whole surface is visible.
You can make the sponge by starting with a cube and then drilling out a square segment form all three sides. Then you take a smaller drill and repeat the process 3*8 times and so on.
Since all you do is drilling holes, the question simplifies to "can you see the entire inner surface of a straight pipe when looking at it from one end?"
The answer to it is obviously 'yes' even though the viewing angles will become infinitesimally small.
Edit:
We can probably generalize this for other shapes and higher dimensions like this:
"For a set $S$ Every point on its surface $\partial S$ can be viewed from the outside of the convex hull of $S$ if the set complementary to $S$ can be constructed from the union of straight lines (of infinite length and of which there are infinitely many)"
This still does not cover all possible shapes, like a hourglass, but it works for the Menger Sponge, Cantor Dust and similar fractals
Comment: Somehow your explanation doesn't satisfy me, because it presumes that the set of all points contained in the Menger sponge consists only of those points that are located on a boundary; i.e., $M = \partial M$.  But even for a 1-dimensional Cantor set, this is false:  there exist points of the Cantor set that are not endpoints, so it should be easy to see that there also must exist some point $x \in M$ but $x \not\in \partial M$:  for instance, because $1/4$ is in the Cantor set on $[0,1]$ but not an endpoint, $(1/4,1/4,1/4)$ is a non-boundary point of the Menger sponge.
Comment: not only the cantor set, this does not work for any non-connected set in 1d. But that wasnt the question, the question was, in fact, about the surface = $\partial M$ of the sponge
Comment: Indeed, I had missed that part of the original question!
Comment: This depends in essential fashion on the fact that all of the 'holes' in the sponge go all the way through from one end to the other (or, essentially, that the sponge is the intersection of three generalized cylinders); this is true but maybe not so self-evident as it would seem.
Comment: It's at least intuitively clear from looking at a picture that any hole through a cubelet actually extends all the way through the sponge, and that observation indeed makes the question trivial


how to display records in a dropdown using react redux

Question: Am using the code below to display records in reaxt redux, everything works fine. now I want to display the result in
a dropdown like in the code below but cannot get it to work.
    <select name="form-field-name" value={user.firstName} onChange={this.handleChange}/>
<option value="{user.id}">  {user.firstName + ' ' + user.lastName}  </option></select>

here is the main code
import React from 'react';
import { Link } from 'react-router-dom';
import { connect } from 'react-redux';

import { dropdownActions } from '../_actions';

class DropdownApp extends React.Component {

constructor(props) {
        super(props);

this.state = {
            us: 0

        };

    }

    componentDidMount() {
this.props.dispatch(userActions.DropdownRecords());
    }

    handleDeleteUser(id) {
        return (e) => this.props.dispatch(userActions.delete(id));
    }

    render() {
        const { user, users } = this.props;
        return (

   {users.items &&

                        {users.items.map((user, index) =>

 /*

         <select name="form-field-name" value={user.firstName} onChange={this.handleChange}/>
<option value="{user.id}">  {user.firstName + ' ' + user.lastName}  </option></select>

*/

                                {user.firstName + ' ' + user.lastName}

                        )}

                }

hello

        );
    }
}

Answer: This is how I was able to resolve it
                    <select>
<option   value='' >--select--</option>
                        {users.items.map((user, index) =>

         <option  key={user.id}  value='{ user.id }' >{ user.lastName}</option>

                        )}

</select>


Logical Indexing of 3D matrix on basis of a 1D matrix

Question: I have a 450-by-1000-by-3 double in Matlab, which consists of 19 unique values that are obviously repeated a lot of times. Let's call this A.
Let's pretend that some of these numbers are 10, 20 and 30. I store those numbers in B, such that B is 3-by-1.
Now, I really, really would like to spit out a new matrix with the same dimensions as A (450-by-1000-by-3) but with 1 where I find 10, 20 and 30, and 0 where it differs from these 3 numbers.
I've looked into both logical indexing and find, but I keep banging my head against the wall. Doing this with one number is easy, but doing it with an array somehow does not seem to work. Even with a loop.
Comment: use the [`ismember`](http://www.mathworks.com/help/matlab/ref/ismember.html) function
Answer: Approach 1: use ismember,  as suggested by Dan:
result = ismember(A, B);

Approach 2: use bsxfun:
result = any(bsxfun(@eq, A, reshape(B,1,1,1,[])), 4);

Comment: With `reshape` in 4th dimensions, `bsxfun` approach is very nice :)
Comment: Gah. That was glaringly simple. Thanks a lot.


What does $() in jquery mean

Question: I know $() is a selector , but I can't figure out what it selects, since there's nothing inside parenthesis. Is this a good practice or bad?
Example where I see it used...making a call to a data service.
<code>$().dataService({
  url: getURL('application', data),
  params: params,
  success: getResponse,
  error: errorResponse
})
</code>
Comment: `dataService` is a function set in the prototype object of jQuery. from what it look like, it doesn't need a reference to a jQuery object, so `$().dataService` works. It a kinda bad programming IMO. Instead of declaring `dataService` like that : `$.fn.dataService`, i would do it like that : `$.dataService` **then** use it that way : `$.dataService()`.
Comment: Do you have an example of where this was used? I can't come up with a reason why you would use an empty jQuery selector.
Comment: @KJPrice Well, there is some reasons... I often use it.
Comment: please see my edit in my post. i included example
Comment: `$()` is not a selector. It's a function call. The string typically passed to `$` represents a selector.
Answer: From the JQuery 1.4 Release Notes:

In jQuery 1.3, jQuery() returned a jQuery set containing just the document. in jQuery 1.4, it returns an empty jQuery set. This can be useful for creating an empty set and adding elements to it dynamically.

So to answer your question, it selects nothing, returning an empty set. This is perfectly acceptable to use, and not considered bad practice.

What does $() in jquery mean


C# multi casting example

Question: Could someone write this literally for me so I can understand how the casting is being carried out? The amount of brackets confuses me.
(Dictionary<String, String>)((Object[])e.Result)[1];
Was only able to find simple cast examples searching (possibly means I'm searching for wrong thing) which weren't very helpful.
Answer: Firstly, e.Result is casted to an array of type Object
(Object[])e.Result

Then, the item at index 1 in that array, [1], is casted to a Dictionary of type <string, string>
(Dictionary<String, String>)((Object[])e.Result)[1];

Hope that helped.
Answer: In order to understand the order of operations you need to remember that the cast will be applied to the object to the right but the rules that affect WHEN it is applied depends on MSDN's Operator precedence and associativity
(Dictionary<String, String>)((Object[])e.Result)[1];

Becomes
Object[] cast1 = (Object[]) e.Result;

The cast operation is grouped into the "Unary Operators" category which is a lower priority than the indexer - [] which is in the "Primary expressions" category.
In the original line - The ()'s are necessary around the cast:  ((Object[])e.Result) because the indexer - [] is applied immediately to the object on the left as the first priority.  Without the surrounding ()'s the cast would be applied AFTER the indexer and since e.Result is (likely?) of type object this will fail at compile time.  Without the ()'s the line would look like:
(Object[])e.Result[1]

Which would not be valid.
((Object[])e.Result)[1]

ensures that e.Result is cast to type Object[] first, and then the indexer is used to access the first element.
The second cast turns the first element of the casted object[] (in my example cast 1) into a Dictionary
Dictionary<String, String> cast2 = (Dictionary<String, String>) cast1[1];

Answer: Object[] cast1 = (Object[])e.Result;
Object secondElement = cast1 [1];
Dictionary<String, String> cast2 = (Dictionary<String, String>)secondElement;

Answer: object[] cast1result = (object[]) e.Result;
object dictionaryElement = cast1result[1];
Dictionary<string, string> cast2result = (Dictionary<string, string>) dictionaryElement;

C# multi casting example


how to save webpages to files with their addresses that has .aspx in it

Question: I would like to save a web page to a file. The addresses are like
http://propaccess.traviscad.org/clientdb/Property.aspx?prop_id=487319
I tried wget and curl, and they say 'no matches found'.
What I am going with this is that I would like to write a python script like the following to save many similar pages.
foreach prop_id in range(400000, 410000):
    cmd = 'wget http://propaccess.traviscad.org/clientdb/Property.aspx?prop_id={} > {}.txt'.format(prop_id, prop_id)
    os.system(cmd)

Background:
 I need to parse the appraisals values to build a case for my property tax protest. Manually clicking things through to collect samples is just too time consuming!
Comment: Looks like the link doesn't work outside the browser I got it.
Answer: The easiest way to do this is to use the requests library. First we should get session ID (it will be in a cookies after we visit the home page). Then we can download pages using these cookies (session id).
import requests

session = requests.Session()

#Get session cookies (session ID)
index_url = 'http://propaccess.traviscad.org/clientdb/?cid=1'
index_request = session.get(index_url)
session_cookies = index_request.cookies

#Download pages
for prop_id in range(400000, 410001):
    url = 'http://propaccess.traviscad.org/clientdb/Property.aspx?prop_id=%s' % prop_id
    r = session.get(url,cookies = session_cookies)
    print r.text #r.text contains page content

Page content will be in r.text.
Comment: Thanks! It seems I can do a lot with requests library.