Interview Question at Gaming Company

Question: I came across the following interview question :

In an online gaming company, customer churn is defined in terms of the
  number of days of continuous inactivity of the player. So how will you
  find the optimum number of days for which if the player is inactive,
  then he can be considered as churned?

I was thinking something along the lines of a Bayesian approach but I am not sure how to go ahead.
Any help in the right direction would be much appreciated.
Answer: I'd first take a look at the available data, in particular at the distribution of inactivity days before activity is resumed. Some players pause for a day or two and then become active again, some pause for a week etc. For active users, I'd expect a Poisson or an exponential distribution. Whatever the distribution, I'd try to find its parameters.
The next question would be to quantify profits and losses from correct and false classification. This is something the company should be able to tell you. I.e. each churned user in the database costs x\$, deleting a still active user would cost us y\$ etc.
With that information and the above probability distribution you can calculate the expected profits/losses and draw the boundary where expected profits and expected losses are equal.
Comment: That is a good approach. At one of my previous works we did effectively did something very similar. You can even discuss the point that certain categories of players "churn" differently that others (so for example high volume players might be inactive for 14 days and still not being churned while a person who played just two low-action consecutive days becomes churned in a week's time).\
Answer: The question is very vague, so I expect they want to see your view on it, how you would solve it. Without more information there are many ways in which you could do this.
One example would be using a logistic regression model, which would not only "classify" the players into churned or not churned, but would also give you the odds of a player doing so, given the time passed.
Another example would be to fit a distribution to the data - time passed, say Weibull distribution, finding the parameters which best fit the data, and then selecting a quantile as your threshold of churned / not churned.
Comment: yes, along those lines.
Comment: Not sure if I get your approach. For logistic regression, how do you get labelled data? Assuming you take a threshold of days to label the users, how do you decide the optimal threshold? And again for fitting distribution, how do you decide the optimal quantile threshold. That's what the initial problem is in the first place.
Comment: @AdnanTamimi Yes, the assumption is that you have some labeled data or some sort of information. Otherwise I don't see a way to solve this. How could you determine whether someone is "churned" without any information about what churn is. It could happen that there are no churned players, that they just take really long pauses. Or it could be that they all churn immediately. So you either need some data to determine this, or you need some assumptions.
Comment: @AdnanTamimi Reading through your question again, I think I see where you were going with the Bayesian approach. Did you perhaps want to assign some sort of prior to each individual player, and then check how the posterior changes as his inactivity grows larger?
Answer: There are many ways to do it.
The simple way would be the following:
You need to identify a cut-off point for which, when surpassed at least $\alpha$% of people
 never come back to play. Never can be defined as a) a big time-frame e.g:3 years or b) Uninstall of the game. You fix the $\alpha$ (for this example I'll go for $\alpha=95$) and you then try to find the minimum cut-off point. For instance, For all cases of gamers in the dataset that have surpassed the cutoff point of 6-months without playing, 90% never come back. Thus the 6 month is too low. You continue until you identify a cut-off point e.g: 7 months for which $\alpha$% so 95% of gamers who have surpassed it never came back and that would be the simplified answer. You can basically define you own parameters and do an ROC analysis or something similar to identify the optimal cut-off point.
The complicated way would be to do it a bit more "personalised". In that case you would need to cluster people based on their "natural return rates" (every time they come back to play is a time difference). There are many ways to cluster them but the idea here is the you create groups of people that have "as similar return rates as possible". Afterwards you identify cut-off points for each group based on the analysis above.
These are just some examples but it's a really open question in general.

Interview Question at Gaming Company


MySQL Error on Startup: ambiguous option '--log=/var/log/mysqld.log'

Question: I would like to try MySQL 5.6 on my machine, but I cannot start it. I always get an error :

[ERROR] /usr/local/mysql-5.6.5-m8-osx10.6-x86/bin/mysqld: ambiguous option '--log=/var/log/mysqld.log' (log-bin, log_slave_updates)

my.cnf
[mysqld]
pid-file=/usr/local/mysql-5.6.5-m8-osx10.6-x86/mysql.pid
log-error=/usr/local/mysql-5.6.5-m8-osx10.6-x86/data/mysql-error.log
log-slow-queries=/usr/local/mysql-5.6.5-m8-osx10.6-x86/data/mysql-slowquery.log
log-bin=/usr/local/mysql-5.6.5-m8-osx10.6-x86/data/mysql-bin.log
general_log_file=/usr/local/mysql-5.6.5-m8-osx10.6-x86/data/mysql-general_log_file.log
log=/usr/local/mysql-5.6.5-m8-osx10.6-x86/data/mysql.log

I tried to set the log and log-bin parameters in my.cnf and also as start parameters for mysqld, but with no luck. Any idea what I can do?
My environment
OS X 10.6.8
mysql-5.6.5-m8-osx10.6-x86 (not _x64 version)

Note: I'm also running MySQL 5.5 on this machine (different port and socket). I also try to stop this instance but I get the some error.
Update:
Thank you for help but I'm still gettings the some error. I have now changed my.cnf to:
[mysqld]
user        = myusername
port        = 3307
socket      = /tmp/mysql_56.sock
skip-external-locking
key_buffer_size = 256M
group_concat_max_len = 50240
max_allowed_packet = 16777216
table_open_cache = 256
sort_buffer_size = 1M
read_buffer_size = 1M
read_rnd_buffer_size = 4M
myisam_sort_buffer_size = 64M
thread_cache_size = 8
query_cache_size= 16M
thread_concurrency = 8
datadir=/usr/local/mysql-5.6.5-m8-osx10.6-x86/data
pid-file=/usr/local/mysql-5.6.5-m8-osx10.6-x86/mysql.pid
log-error=/usr/local/mysql-5.6.5-m8-osx10.6-x86/data/mysql-error.log
log-slow-queries=/usr/local/mysql-5.6.5-m8-osx10.6-x86/data/mysql-slowquery.log
log-bin=/usr/local/mysql-5.6.5-m8-osx10.6-x86/data/mysql-bin.log
general-log=1
general_log_file=/usr/local/mysql-5.6.5-m8-osx10.6-x86/data/mysql-general_log_file.log

And I start MySQL with a script:
cd /usr/local/mysql-5.6.5-m8-osx10.6-x86
./bin/mysqld_safe --basedir=/usr/local/mysql-5.6.5-m8-osx10.6-x86
cd $HOME

But I'm still getting the same error:

120611 16:02:02 mysqld_safe Starting mysqld daemon with databases from
  /usr/local/mysql-5.6.5-m8-osx10.6-x86/data
120611 16:02:02 [ERROR] /usr/local/mysql-5.6.5-m8-osx10.6-x86/bin/mysqld: ambiguous option '--log=/var/log/mysqld.log' (log-bin, log_slave_updates)
120611 16:02:02 [ERROR] Aborting
120611 16:02:02 [Note] Binlog end
120611 16:02:02 mysqld_safe mysqld from pid file /usr/local/mysql-5.6.5-m8-osx10.6-x86/mysql.pid ended

This is very strange because I did not set --log=/var/log/mysqld.log anywhere.
Answer: The "ambiguous option" error message should have pointed you in the right direction...
The --log option has been long deprecated, use the --general-log option instead
Please post your other errors messages so that we can help you with them.
Answer: Make sure your start.sh is using the correct my.cnf with --defaults-file=/path/to/my.cnf
You may also have another my.cnf automatically being included (usually /etc/mysql/my.cnf) that could be adding/overriding options in your base config file.
Comment: Hi! Yes, this was my problem - another my.cnf in /etc/my.cnf. I remove this file and now it starts. Thank you.


Acessar imagem do resources spring

Question: tenho o seguinte cenário:

Tenho o arquivo srping-servlet.xml com a seguinte configuração:

<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:mvc="http://www.springframework.org/schema/mvc"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
  http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
  http://www.springframework.org/schema/mvc
  http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
  http://www.springframework.org/schema/context
  http://www.springframework.org/schema/context/spring-context-4.0.xsd">

 <context:component-scan base-package="com.websystique.springmvc.controller" />

 <mvc:annotation-driven />
 <mvc:resources mapping="/resources/**" location="/resources/" />

 <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="prefix">
   <value>/WEB-INF/views/</value>
  </property>
  <property name="suffix">
   <value>.jsp</value>
  </property>
 </bean>

</beans>

Tenho o metodo Hello World que quero mostrar a imagem por exemplo logo_vallon.jpg e estou usando o seguinte codigo na classe HelloWorldController.java:

@RequestMapping(method = RequestMethod.GET)
 public String sayHello(ModelMap model) {
  model.addAttribute("greeting", "Hello World from Spring 4 MVC");
  return "welcome";
 }

porem quando mando rodar o codigo fica assim:

quando mando mostrar as informações da pagina fica assim:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>HelloWorld page</title>

 Greeting : Hello World from Spring 4 MVC

e o arquivo jsp está sendo criado dessa forma:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>HelloWorld page</title>

 Greeting : ${greeting}

Já estou a mais de 3 dias tentando fazer a imagem aparecer sem sucesso, alguem pode me dar uma luz para isso por favor? pode me dizer onde está o erro?
Answer: Depois de muitas horas, segue a resposta:

<mvc:annotation-driven />
<mvc:resources mapping="/images/**" location="/WEB-INF/images/" />

Acessar imagem do resources spring


How to display results of FormAPI form submitted in same block, minus the button(s) used to submit

Question: I have a custom module that I have created to display 3 different images with a 'vote' beneath each image. The idea is to have the viewer vote on the one they like and it gets ranked against the other 2 images using votingAPI. What I am trying to do on callback is do the voting calculations (which I have), then replace the buttons with the voting percentage for each of the images. Wait 3 seconds and refresh the form with 3 more images.
What I am having difficulty with right now is just redrawing the form after submit, with the same 3 images and the percentage displaying instead of the button.
Here is the code I am using to define the block, block_view, and form. Any suggestions or help would be greatly appreciated.
function steal_or_burn_block_info() {
  $blocks = array();
  $blocks['steal_or_burn'] = array(
    'info' => t('Steal or Burn Homepage Block'),
    'cache' => DRUPAL_NO_CACHE,
  );
return $blocks;
}

function steal_or_burn_block_view($delta = '') {
  $block = array();
  switch($delta) {
    case 'steal_or_burn':
      $block['subject'] = ("Favorite Image");
      $block['content'] = drupal_get_form('steal_or_burn_form');
    }

  return $block;
}

function steal_or_burn_form($form, &$form_state) {

  $has_cookie = get_cookie('stealorburn');

  // Get the previous Steal or Burn NodeId's as an array
  $prev_sob_nids = get_sob_cookie_nids(COOKIE_NAME);

  // Load the NodeId's of the remaining Steal or Burn images in the database
  $unviewed_nids = load_sob_node_ids('stealorburn');

  // Find the difference between the previously viewed NodeId's against the full database
  // return an array of only those that have not yet been viewed
  if($prev_sob_nids) {
    $stealorburn_raw = array_diff($unviewed_nids, $prev_sob_nids);
  } else {
    $stealorburn_raw = $unviewed_nids;
  }
  // Randomize the array of not-yet-viewed Product images
  shuffle($stealorburn_raw);
  // Select the next 3 images to display
  $stealorburn = array_slice($stealorburn_raw, 0,3, TRUE);

  $i = 1;
  foreach($stealorburn as $value) {

  $node = node_load($value);
  $image = field_get_items('node', $node, 'field_brand_image');
  $image_rendered = field_view_value('node', $node, 'field_brand_image', $image[0], array(
    'type' => 'image',
    'settings' => array(
      'image_style' => 'thumbnail',
      ),
  ));
  $brand = $node->title;
  $item_name = field_get_items('node', $node, 'field_item_name');
  $item_id = $node->nid;
  $image_uri      = $image_rendered['#item']['uri'];
  $style          = 'steal_burn_home_image';
  $derivative_uri = image_style_path($style, $image_uri);
  $new_image_url  = file_create_url($derivative_uri);

  switch ($i) {
    case 1:
      $submit_button = 'steal_burn_first';
      break;
    case 2:
      $submit_button = 'steal_burn_second';
      break;
    case 3:
      $submit_button = 'steal_burn_third';
      break;
  }

  // Block output in HTML with div wrapper
  $form['steal_or_burn_form'][]['image'] = array(
      '#prefix' => "
",
      '#type' => 'markup',
      '#markup' => "",
    );
  $form['steal_or_burn_form'][]['brand'] = array(
      '#prefix' => '
',
      '#type' => 'markup',
      '#markup' => $brand,
      '#suffix' => '
',
    );
  $form['steal_or_burn_form'][]['item_name'] = array(
      '#prefix' => '
',
      '#type' => 'markup',
      '#markup' => $item_name[0]['value'],
      '#suffix' => '
',
    );
  $form['steal_or_burn_form'][]['product_id'] = array(
      '#type' => 'hidden',
      '#value' => $item_id,
    );
  $form['steal_or_burn_form'][]['submit'] = array(
      '#type' => 'submit',
      '#id' => $submit_button,
      '#name' => $node->nid,
      '#value' => t('Vote'),
      /*'#submit' => array('steal_or_burn_submission_callback'),*/
  );

  $i++;
} // end block image loop

return $form['steal_or_burn_form'];

}

Answer: You would need to have an AJAX callback.
You would need to wrap your submit buttons --- (or your whole form, doesn't matter).
Set the 'wrapper' with the ID of that HTML element ; and then set the name of your ajax callback function in 'callback'. Your ajax callback returns the form element (in case you're just wrapping the submit buttons) or the whole form. You shouldn't do any change in the form or its state as mentioned in the documentation. You do the changes in your form builder function. In this case, that will be steal_or_burn_form. But, you can change a form element and then return that.
Read the documentation for more info.
Also, this one's a good example of a submit-driven ajax:
Form Builder
Ajax Callback of the form above
Comment: Thank you for your suggestions. I took a queue from the links you provided, re-created my form a little and now have it working. I think parts of it are still a square peg being forced through a round hole, but I'm still tweaking it.
Answer: After a few more days work tweaking the form, I was able to get it to work by modifying this form and adding a js file for some of the jQuery functionality I just couldn't figure out how to accomplish directly in the form or through helper functions. Here is my updated version of the form:
function steal_or_burn_form($form, &$form_state) {

  get_cookie('stealorburn');

  // Get the previous Steal or Burn NodeId as an offset
  $prev_sob_offset = get_sob_cookie_offset(COOKIE_NAME);

  // Load the NodeId's of the remaining Steal or Burn images in the database
  $unviewed_nids = load_sob_node_ids('stealorburn');

  // Find the index of the last viewed NodeId against the full database
  // return an array of the next 3
  if($prev_sob_offset) {
    // There was an offset saved in the cookie
    if($prev_sob_offset <= (count($unviewed_nids) - 3)) {
      $stealorburn = array_slice($unviewed_nids, ($prev_sob_offset), 3);
      $sob_offset = $prev_sob_offset + 3;
    } else {
      $stealorburn = array_slice($unviewed_nids, 0, 3);
      $sob_offset = 3;
    }
  } else {
      $stealorburn = array_slice($unviewed_nids, 0, 3);
      $sob_offset = 3;
  }

  //set hidden field for the sob_offset so it may be saved during form-submit
  $form['cookie_offset'] = array(
    '#type' => 'hidden',
    '#default_value' => $sob_offset,
  );

  $i = 1;
  foreach($stealorburn as $value) {

    $node = node_load($value, NULL, TRUE);

    $image = field_get_items('node', $node, 'field_brand_image');
    $image_rendered = field_view_value('node', $node, 'field_brand_image', $image[0], array(
      'type' => 'image',
      'settings' => array(
        'image_style' => 'thumbnail',
        ),
    ));
    $brand = $node->title;
    $item_name = field_get_items('node', $node, 'field_item_name');
    $item_id = $node->nid;

    $image_uri      = $image_rendered['#item']['uri'];
    $style          = 'steal_burn_home_image';
    $derivative_uri = image_style_path($style, $image_uri);
    $success        = file_exists($derivative_uri) || image_style_create_derivative($style, $image_uri, $derivative_uri);
    $new_image_url  = file_create_url($derivative_uri);

    switch ($i) {
      case 1:
        $submit_button = 'steal_burn_first';
        break;
      case 2:
        $submit_button = 'steal_burn_second';
        break;
      case 3:
        $submit_button = 'steal_burn_third';
        break;
    }

    // Block output in HTML with div wrapper
    $form['image'.$item_id] = array(
      '#prefix' => "
",
      '#type' => 'markup',
      '#markup' => "",
    );
    $form['brand'.$item_id] = array(
      '#prefix' => '
',
      '#type' => 'markup',
      '#markup' => $brand,
      '#suffix' => '
',
    );
    $form['item_name'.$item_id] = array(
      '#prefix' => '
',
      '#type' => 'markup',
      '#markup' => $item_name[0]['value'],
      '#suffix' => '
',
    );
    $form['product_id' . $item_id] = array(
      '#type' => 'hidden',
      '#default_value' => $item_id,
      '#value' => $item_id,
    );

    $form['submit_'.$item_id] = array(
      '#type' => 'submit',
      '#id' => $submit_button,
      '#name' => $item_id,
      '#value' => t('Vote'),
      '#prefix' => '
',
      '#suffix' => '

',
      '#ajax' => array(
        'callback' => 'steal_or_burn_ajax_callback',
        'event' => 'click',
        'progress' => array('type' => 'none'),
      ),
    );

    $i++;
  } // end block image loop

  $form['#attached']['js'] = array
  (
    array
    (
      'type'  => 'file',
      'data' => drupal_get_path('module', 'steal_or_burn') . '/steal_or_burn.js',
    ),
  );

  return $form;
}

function steal_or_burn_ajax_callback($form, &$form_state) {
  //function steal_or_burn_submit($form, &$form_state) {

  while (list($key, $value) = each($form_state['values'])) {
    if(substr_count($key, 'product_id') == 1) {
      if(!is_null($value) ) {
        $raw_values[] = $value;
      }
    }
    if($value == 'Vote') {
      $voted = $key;
    }
  }

  for($i = 0, $size = count($raw_values); $i < $size; ++$i) {
    if($raw_values[$i] != $voted) {
      $not_voted[] = $raw_values[$i];
      $votes[$raw_values[$i]]['entity_type'] = 'stealorburn';
      $votes[$raw_values[$i]]['entity_id'] = $raw_values[$i];
      $votes[$raw_values[$i]]['value_type'] = 'points';
      $votes[$raw_values[$i]]['value'] = 0;
    } else {
      $votes[$voted]['entity_type'] = 'stealorburn';
      $votes[$voted]['entity_id'] = $voted;
      $votes[$voted]['value_type'] = 'points';
      $votes[$voted]['value'] = 100;
    }
  }

  // Need to set criteria to be an empty array, otherwise it would reset votes.
  $criteria = array();
  // Add vote data to the database for these 3 images
  $current_vote = votingapi_set_votes($votes, $criteria);

  $submitted_image_nids = array_values($raw_values);

  for($i = 0, $size = count($submitted_image_nids); $i < $size; ++$i) {
    $image_nid = $submitted_image_nids[$i];
    $votes_this_round[] = $current_vote['stealorburn'][$image_nid][2]['value'];
  }

  $total_votes = array_sum($votes_this_round);

  for($i = 0, $size = count($votes_this_round); $i < $size; ++$i) {
    $points[$i] = intval(($votes_this_round[$i] / $total_votes) * 100);
  }
    //Using the $plug variable to make sure the sum of results = 100%
    $plug = 100 - array_sum($points);
    if($plug > 0) {
      $lowest_value = min($points);
    }

    foreach($points as $key => $value)
    {
      if($value == $lowest_value) {
        $points[$key] = $value + $plug;
      }
    }

  $tracking_votes = array_combine($submitted_image_nids, $points);

    $commands = array();
    foreach($tracking_votes as $key => $value) {
      $replace_id = "#vote_btn_$key";
      $commands[] = ajax_command_replace($replace_id, drupal_render($form[$replace_id]));
      $vote_percentages[] = $value . "%";
    }

  // Include a custom function that will be called in the JavaScript file:
  $commands[] = array
  (
    // The command will be used in the JavaScript file
    'command' => 'stealorburnCallback',
    // Pass the form values of each element to the JS function:
    'votePercentages' => $vote_percentages,
  );

  //delete the cookie before writing the new one
  steal_or_burn_cookie_delete('stealorburn');

  $new_sob_offset = $form_state['values']['cookie_offset'];

  //write the cookie with updated index
  $steal_or_burn_to_cookie = $new_sob_offset;
  steal_or_burn_cookie_save('stealorburn', $steal_or_burn_to_cookie);

  // And finally, we will return all of our commands to the system to be executed:
  return array('#type' => 'ajax', '#commands' => $commands);
  }

The contents of the JS file are primitive. Right now the page is getting reloaded after 2 seconds of displaying the results. My next challenge is to make a function or alter the form in a way that I can reload it after the 2-second delay without having to reload the whole page.
**myjsfile.js
(function($, Drupal)
{
    // Our function name is prototyped as part of the Drupal.ajax namespace, adding to the commands:
    Drupal.ajax.prototype.commands.stealorburnCallback = function(ajax, response, status)
    {
        $('.steal-or-burn-field-title').each(function(index, obj){
            if(index == 0) {
                $("
"+response.votePercentages[0]+"
").insertBefore(this);
            } else if (index == 1) {
                $("
"+response.votePercentages[1]+"
").insertBefore(this);
            } else if (index == 2) {
                $("
"+response.votePercentages[2]+"
").insertBefore(this);
            }
        });

        setTimeout(function() {
            location.reload(true);
        }, 2000);

        return false;

    };
}(jQuery, Drupal));


iptables udp port forwarded but ICMP UDP Port unreachable

Question: I wish to host a game server (Zandronum Doom) on port 10666 UDP, but no one can connect to it. I have troubleshot the problem and I think it's a problem with my routing. My physical network architecture is like this:
[WAN] - [Router] - [Switch] - [Pi]
                            - [Desktop]
                            - [Other]

My routing is as follows
[WAN] - [(pub. ip) Router (192.168.1.1)] - [Pi (192.168.1.5)] - [Desktop (192.168.1.11)]
                                                    - [Other (tv, printer, laptop, phone, etc)]

My router is set up to forward anything I want to the raspberry pi and only there. The raspberry pi is set up as an IDS/IPS and also acts as DNS server and DHCP server for my whole network. I want all my traffic to go through there. The rasperry pi is set as the default gateway via dhcp, the rasperry pi itself has the router as default gateway.
The router is set to port forward tcp and udp traffic on port 10666 to the pi. This is the traffic that gives me trouble. The rasperry pi has the following relevant rules in the iptable:
$> sudo iptables --list -t nat
Chain PREROUTING (policy ACCEPT)
target     prot opt source               destination
DNAT       tcp  --  fritz.box            pi.lan               tcp dpt:10666 to:192.168.1.11
DNAT       udp  --  fritz.box            pi.lan               udp dpt:10666 to:192.168.1.11

Chain INPUT (policy ACCEPT)
target     prot opt source               destination

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination

Chain POSTROUTING (policy ACCEPT)
target     prot opt source               destination
MASQUERADE  all  --  anywhere             anywhere

$> sudo iptables --list
Chain INPUT (policy ACCEPT)
target     prot opt source               destination

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination
QUEUE      all  --  anywhere             anywhere

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination

I'm not sure why some of those names are resolved while others are not.
I can not connect to the server via public ip. TCP Dump reveals the following:
$> sudo tcpdump -i eth0 | grep 10666
[...]
21:34:57.456103 IP paul-pc.lan.10667 > <pub-ip>.10666: UDP, length 50
21:34:57.457635 IP pi.lan.10667 > <pub-ip>.10666: UDP, length 50
21:34:57.458130 IP <pub-ip>.10667 > pi.lan.10666: UDP, length 50
21:34:57.458279 IP pi.lan > <pub-ip>: ICMP pi.lan udp port 10666 unreachable, length 86
21:34:57.458451 IP <pub-ip> > pi.lan: ICMP <pub-ip> udp port 10666 unreachable, length 86
21:34:57.458711 IP <pub-ip> > paul-pc.lan: ICMP <pub-ip> udp port 10666 unreachable, length 86
[repeating]
[...]

To test things I changed the network settings for the server to bypass the pi and the router to port forward directly to the desktop. Then it worked perfectly.
Comment: "_iptables udp port forwarded but ICMP UDP Port unreachable_" ICMP and UDP are two completely separate protocols. There is no such thing as an "_ICMP UDP Port_." ICMP does not use port numbers, it has request IDs. ICMP does not use UDP, and UDP does not use ICMP.
Comment: @RonMaupin the ICMP message is sent that the UDP port is not reachable. ICMP isn't sent over UDP, of course.
Comment: What it is telling you is the ICMP Request ID, not a port number, even if the programmers are lazy and not changing the description.
Answer: The option -s 192.168.1.1 is wrong. The source is passed through from the router, not repackaged (the router is not the source). Use a destination filter instead with -d 192.168.1.5


Nested and crossed effects in 3-way interaction in lmer

Question: I am running a mixed model in lmer, testing the effects of Covid restrictions on sleep, comparing 2 cohorts of individuals- one from 2019 and one from 2020, coded 0/1 (between subjects). Each individual was measured repeatedly for ~130 consecutive nights, and each row in the dataset represents a single night. I also have a binary Lockdown IV, where each night is coded 0/1 to indicate if it was before/after restrictions were imposed in 2020 (and the equivalent dates for 2019). Finally, I have a DayOfWeek IV, where each night is coded 0/1 to indicate if it represents a weekday/weekend night. The simplified dataset looks something like:

My hypotheses are: (1) there will be a Cohort by Lockdown interaction effect on sleep; and (2) there will be a Cohort by Lockdown by DayOfWeek interaction effect on sleep.
For hypothesis 1, I ran:
mod1 <- lmer(sleep ~ Cohort*Lockdown + (1|Subject) + (1|Date), data = COVID, REML=FALSE)

Results seem reasonable, but I think I am not accounting for random slopes. I have tried to model the slopes as follows, but the model failed to converge.
mod2 <- lmer(sleep ~ Cohort*Lockdown + (Lockdown|Subject), data = COVID, REML=FALSE)

As for the 2nd hypothesis, if I understand correctly, nights are nested within DayOfWeek, which are crossed with Lockdown (since each level of Lockdown includes both weekdays and weekends). I tried the following code, but am getting a singular fit warning (boundary (singular) fit: see ?isSingular)
mod3 <- lmer(sleep ~ Cohort * Lockdown * DayOfWeek + (1|DayOfWeek/date), data = COVID, REML=FALSE)

Could anyone direct me as to what should be changed in these models?
Many thanks in advance for your help!
Answer: In your second model :
mod2 <- lmer(sleep ~ Cohort*Lockdown + (Lockdown|Subject), data = COVID, REML=FALSE)

you are not accounting for repeated measures within Date. Perhaps you found from the first model that this was not needed, which seems reasonable if that is the case. You would need to include it sleep is more similar to sleep on the same date than different dates. This could be plausible, perhaps due to weather or other factors which might cause different subjects to have more or less sleep on the same nights.

nights are nested within DayOfWeek

I don't see why nights are nested within DayOfWeek. This would mean that each DayOfWeek had it's own night.
It very rarely, if ever, makes sense to fit fixed effects for a factor, so DayOfWeek should not be in the grouping part of the random effects. So the model:
mod3 <- lmer(sleep ~ Cohort * Lockdown * DayOfWeek + (1|DayOfWeek/date), data = COVID, REML=FALSE)

does not make sense. Moreove it does not account for repeated measures within subjects. It is also not clear that you need date as a grouping variable (see above)
From your description, the 2nd question could be answered with:
lmer(sleep ~ Cohort * Lockdown * DayOfWeek + (1|Subject)

Comment: Thank you very much for your help!
Comment: In my second model, if I want to account for repeated measures within date, so that different subjects can have different slopes (across dates), should I define (Date|Subject) + (Lockdown|Subject)? Also, model 1 runs fine, but when I run emmeans(mod1) to see pairwise comparisons, I get the following error: "Error in asMethod(object) : Cholmod error 'problem too large' at file ../Core/cholmod_dense.c, line 105". I have ~75,000 rows of data. Is there any other way to obtain Cohort*Lockdown pairwise comparisons? Many thanks again! Mika


EditText Android Studio

Question: Tenho Seguinte EditText:
<EditText
    android:layout_width = "match_parent"
    android:layout_height = "wrap_content"
    android:id = "@+id/textSenha"
    android:layout_marginTop="40dp"
    android:hint = "@string/senha"
    android:textCursorDrawable = "@drawable/cursor"
    android:backgroundTint = "@color/black"
    android:inputType = "textCapWords"/>

minha pergunta seguinte, como faço para ficar dessa forma? Usuário selecionar campo senha hint ele sofre elevation
Comment: https://github.com/rengwuxian/MaterialEditText
Answer: Você precisa fazer um wrap do seu EditText com um TextInputLayout ( documentação ).
 <android.support.design.widget.TextInputLayout
   android:layout_width="match_parent"
   android:layout_height="wrap_content">

   <EditText
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:hint="hint"
      android:id="@+id/editText1" />
  </android.support.design.widget.TextInputLayout>

Para manter compatibilidade seria bom utilizar a design support library.
 Adicione no graddle
 compile 'com.android.support:design:23.0.0'

EditText Android Studio


lvmcache/dm-cache writeback cache full performance

Question: I have a SSD writeback cache in front of a HDD, set up through lvmcache (so a dm-cache). When the cache LV is not full (Data% column in lvs < 100.00%), writes go to the cache device (monitored via dstat). However, when the cache LV is full (Data% = 100.00%), writes go directly to the HDD, essentially becoming a writethrough cache. Blocks do not get evicted from the SSD cache, even after some time, and performance drops. When I try reading recently read data from the cached LV, reads are from the SSD, so I assume the entire SSD has now become a read cache. Is this expected behavior for dm-cache's write cache, even in writeback mode? Is there no reserved space for writes? This seems like quite a poor design as essentially users can only write one cache LV's worth of data before the cache becomes a writethrough cache.
My understanding is that dm-cache uses the mq eviction algorithm, but that only applies to read caching and thus is irrelevant to the write caching issue I am observing.
Is there a way to reserve space for a write cache, or use both a dm-writecache (which I understand will not do any read caching) and a dm-cache at the same time?
Answer: dm-cache is a "slow moving" cache: many read/write misses are required to promote a block, especially when promoting a new block means to demote an already-cached one.
The fixed block-based nature of dm-cache, coupled with no reserved write-only area, means that many writes to the same non-cached blocks are required to trigger a block promotion/replacement. However, this also implies that the kernel pagecache is not "absorbing" these multiple missing writes, merging them in a single write to the underlying block devices.
In other words, you are probably seeing the combined effect of the kernel pagecache (which absorbs and merges writes) and the reluctance of dm-cache to promote first-missed blocks.
If you want to reserve some device/space to write cache only, you can tap into dm-writecache (and the usual lvmcache)
Additional information:
dm-cache does block promotion/demotion tracking access hits/misses. At first, you have an empty cache with all I/O directed to the origin (slow) device. So when you issue a, say, 4K read it will access the underlying slow device, with dm-cache tracking the miss. After some other misses to the same cache block (default 32K), then entire cache block is copied to the fast device. If you now writes to the cached blocks, your write will be cached. If, however, your write is for an uncached block, it goes straight to the origin (slow) device. After some other uncached writes, dm-cache will finally allocate the entire cache block (remember, 32K by default) copying the original data to the cache device. At this point, new reads/writes can be served from the cache. Demotion is simple: when a new block must be promoted, the oldest block is discarded/flushed.
In other words, for write to be cached, the corresponding cache segment must be allocated and the backing data must be copied on the cache device (allocate-on-write). To limit bandwidth usage between origin and cache device, this copy is only done after many misses (ie: a single miss will not promote a block). Note that reading many times the same uncached block will not work, as the kernel pagecache will simply provide the cached block by itself.
dm-writecache works differently, being more similar to a traditional RAID controller writeback cache. It caches all writes, ignoring reads. It can almost be considered a "write-only L2 pagecache", where dirty pages are "swapped" waiting for the slow device to catch up. To use it, you need to partition your fast devices between dm-cache (which, at this point, must be run as writethrough cache) and dm-writecache, or to dedicate different devices to them. I never tried doing that via LVM, and I suspect that the tooling will prevent you to nest/stack two different cache modules. However, you can try it via direct dmsetup commands.
Comment: "means that many writes to the same non-cached blocks are required to trigger a block promotion/replacement."

I do not understand the concept of caching a write block and promoting/demoting it. Writes are essentially buffered in write caches (such as dm-writecache) and demote other blocks in aggressive read caches if the write is counted as an access. Could you elaborate on this more?

"If you want to reserve some device/space to write cache only, you can tap into dm-writecache (and the usual lvmcache)"

How would I do this? This would entail having two caches on one LV right?
Comment: @AlbertT I've edited my answer with the required info


let pos = (document.documentElement.scrollTop || document.body.scrollTop) + document.documentElement.offsetHeight;

Question: this line doesn't show me the exact position of the scroller in the first time it shows 687 as the position in the second click it shows the same location as 617 it doesn't change after the second click.
Comment: can you share the complete code which you have written so far on stackblitz.com It will help future readers to get more context and help you solve the problem
Answer: onScroll(event: any)
    {
        //visible height + pixel scrolled = total height
        if (event.target.offsetHeight + event.target.scrollTop == event.target.scrollHeight)
        {
                 this.buttonDisabled=false;
<code>    }
    else
    {
             this.buttonDisabled=true;

    }
}
</code>


Numeros vizinhos em um Lista

Question: Olá alguém pode me ajudar com um exercício? Tenho uma Lista, Não Ordenada, e preciso percorrer uma lista, e retornar apenas os números vizinhos que são maiores que os elementos a direita e esquerda. O primeiro é último elemento da lista não serão considerados por não terem um dos números vizinhos. O resultado final deve ser os números: 916, 638 e 894.
Lista 705,693,593,646,916,637,638,176,894,370
Comment: https://pt.meta.stackoverflow.com/questions/8388/que-erro-cometi-ao-formular-minha-pergunta?cb=1
Answer: Ola, Alexandre! Boa tarde.
Consegui realizar da seguinte forma:
<code>lista = [705, 693, 593, 646, 916, 637, 638, 176, 894, 370]

for i, numero in enumerate(lista):
    if i == 0 or i == len(lista)-1:
        pass
    else:
        if numero > lista[i+1] and numero > lista[i-1]:
            print(numero)
</code>
Deve haver formas mais simples, mas essa funcionou.
Comment: Arthur obrigado pela ajuda, confesso que não conhecia a função enumerate. Agora é estudar mais, pois fiquei quase dois dias quebrando a cabeça e só consegui chegar em valores booleanos

Numeros vizinhos em um Lista


Don't understand proof of why $\cos x$ is a contraction mapping on $[0, 1]$

Question: I've read a couple proofs of why $\cos x$ is a contraction mapping on $[0,1]$ but none of them are clear enough for me to understand. What if we have something like $\lvert \cos x - \cos y \rvert = w > \lvert x - y \rvert = w - \epsilon$? Then we can not multiply the right side of the inequality by a real number that is $< 1$ to get $k \cdot (w - \epsilon) \geq w$.
I am also having trouble getting an intuitive feel of the behavior of $\lvert \cos x - \cos y \rvert$ as $\lvert x - y \rvert$ increases or decreases in value. I cannot make a direct relationship to whether the value of $\lvert \cos x - \cos y \rvert$ will increase or decrease as $\lvert x - y \rvert$ increases or decreases.
Comment: You can use MVT, noting that $\sin(x) < 1$ for all $x \in [0,1]$.
Comment: Which proofs have you read that aren't clear enough?  Sharing more context may prevent people from repeating the stuff that isn't clear to you, and allow them to help clarify.
Comment: "What if"...but does this happen?
Answer: Recall that $f: A \mapsto B$ is a contraction mapping if for all $x,y \in A$, there exists $k \in [0,1)$ independent of $x$ and $y$ such that
$$d_B(f(x),f(y)) \leq k d_A(x,y)$$
In your case, I assume $d_B(\cdot,\cdot) = d_A(\cdot,\cdot) = \vert \cdot - \cdot \vert$. The set $A = [0,1]$ and $B = [\cos(1),1]$. We have
$$\cos(x)-\cos(y) = -2\sin((x-y)/2)\sin((x+y)/2)$$
Hence, we obtain
\begin{align}
\vert \cos(x)-\cos(y) \vert & = \vert -2\sin((x-y)/2)\sin((x+y)/2) \vert = \vert -2 \vert \cdot \vert \sin((x-y)/2) \vert \cdot \vert \sin((x+y)/2)\vert\\
& \leq 2 \cdot \vert (x-y)/2 \vert \cdot \sin(1) = \sin(1) \vert x-y \vert \,\,\,\,\,\, (\spadesuit)
\end{align}
where we made use of the fact that $\sin(u)$ is increasing on $[0,1]$ and $\vert \sin(v) \vert \leq v$. Hence, from $(\spadesuit)$, we obtain
$$\vert \cos(x)-\cos(y) \vert \leq \sin(1) \vert x- y \vert$$
Hence, this is a contraction mapping with $k= \sin(1) < 1$.
Comment: To fix it, note $(x+y)/2 \in [0,1]$, so the sine of that is in $[0,\sin(1)]$ and $\sin(1)<1$.
Comment: @Ian Thanks. Fixed.


Luabind inheritance: self not defined

Question: I just got myself into weird problem with Luabind. I want to inherit C++ classes from Lua, but the way described in Luabind documentation just doesn't work.
function MyGame.__init()
    Game.__init(self)
end

This piece of code just crashes the application, because self seems undefined (returns nil if printed out).
I'm using wrapper struct as described in documentation.
struct GameWrapper: Game, luabind::wrap_base{
GameWrapper()
    : Game()
        {}

virtual int Loop(void){
     call<int>("Loop");
}

static int default_Loop(Game* ptr){
    return ptr->Game::Loop();
}

static void Lua(lua_State *lua){
    luabind::module(lua)
    [
    luabind::class_<Game, GameWrapper>("Game")
        .def(luabind::constructor<>())
        .def("Loop", &Game::Loop, &GameWrapper::default_Loop)
    ];
}
};

Any ideas what I might be doing wrong?
Answer:
but way described in Luabind doc just doesn't work.

Yes it does. You just didn't do it right. Specifically, you didn't notice the use of the : instead of the .. Which has a well-defined meaning in Lua when declaring a function:
function MyGame:__init()
    Game.__init(self)
end

Luabind inheritance: self not defined


Semi Eulerian graphs

Question: I do not understand how it is possible to for a graph to be semi-Eulerian.
For a graph G to be Eulerian, it must be connected and every vertex must have even degree.
If something is semi-Eulerian then 2 vertices have odd degrees. But then G wont be connected.
Answer: Why wouldn't $G$ be connected? Look at the path graph:
$$ - - - - - -$$
Comment: The definition of a connected graph I have is "there is a path between every pair of distinct vertices". In your diagram there is no path between for example the 2nd and 5th "dash"
Comment: @user204450 There is no EDGE, but there is a path: 2nd to 3rd to 4th to 5th.
Comment: oh ok, I think I understand fully the definition of connected graph now. There does not have to be an edge, there can be paths.

Semi Eulerian graphs


in hql scripts we use "!sh echo ---new line---" for the same . Want to know the alternative for this in impala to print any line in impala scripts?

Question: in hql scripts we use "!sh echo ---new line---" for the same .
Want to know the alternative for this in impala to print any line in impala scripts?
Comment: I added some changes to my answer. All about how to print the output to a file. Hope it helps and if it was useful, please feel free to accept my answer and upvote, I really would appreciate that.
Answer: You can invoke the shell command line from impala scripts.
As an example of how it works.
script_impala.sql
-- set a variable containing the of the game
SET hivevar:game=Monopoly;
-- return the list of the game
SELECT list_price FROM fun.games WHERE name = '${hivevar:game}';
-- return the prices of the game ate game shops
SELECT shop, price FROM fun.inventory WHERE game = '${hivevar:game}';

shell hdfs dfs -ls /user;
shell ls -ltr;
shell echo I can echo from impala scripts;
shell cat hex_color.sql

$ impala-shell -f script_impala.sql

output
Starting Impala Shell without Kerberos authentication
Connected to localhost.localdomain:21000
Server version: impalad version 2.10.0-cdh5.13.3 RELEASE (build 15a453e15865344e75ce0fc6c4c760696d50f626)
Variable GAME set to Monopoly
Query: -- return the list of the game
SELECT list_price FROM fun.games WHERE name = 'Monopoly'
Query submitted at: 2020-06-04 23:29:19 (Coordinator: http://localhost.localdomain:25000)
Query progress can be monitored at: http://localhost.localdomain:25000/query_plan?query_id=a94afc7556843cf7:8b19809d00000000
+------------+
| list_price |
+------------+
| 19.99      |
+------------+
Fetched 1 row(s) in 0.15s
Query: -- return the prices of the game ate game shops
SELECT shop, price FROM fun.inventory WHERE game = 'Monopoly'
Query submitted at: 2020-06-04 23:29:19 (Coordinator: http://localhost.localdomain:25000)
Query progress can be monitored at: http://localhost.localdomain:25000/query_plan?query_id=c64d1c8950e5e1f8:15d410cb00000000
+-----------+-------+
| shop      | price |
+-----------+-------+
| Dicey     | 17.99 |
| Board 'Em | 25.00 |
+-----------+-------+
Fetched 2 row(s) in 0.14s
Found 5 items
drwxrwxrwt   - mapred   hadoop              0 2019-04-29 18:19 /user/history
drwxrwxrwx   - hive     hive                0 2019-04-29 18:19 /user/hive
drwxr-xr-x   - hue      hue                 0 2019-11-25 10:19 /user/hue
drwxr-xr-x   - spark    spark               0 2019-04-29 18:19 /user/spark
drwxrwxrwx   - training supergroup          0 2020-05-28 11:33 /user/training
--------
Executed in 2.10s
total 56
-rw-rw-r-- 1 training training   61 Sep 25  2019 hex_color.sql
-rw-rw-r-- 1 training training  115 Sep 25  2019 color_from_rgb.sql~
-rw-rw-r-- 1 training training   58 Sep 25  2019 hex_color_impala.sql
-rwxr-xr-x 1 training training  449 Sep 25  2019 email_results.sh
-rw-rw-r-- 1 training training 1166 Sep 25  2019 zero_air_time.csv
-rw-r--r-- 1 training training  261 Sep 26  2019 change_background.sh~
-rwxr-xr-x 1 training training  262 Sep 26  2019 change_background.sh
-rw------- 1 training training 2966 Sep 26  2019 ChangeVMDesktopColor.txt
-rw------- 1 training training 3279 Sep 26  2019 Hive&ImpalaInScripts&Applications.txt~
-rw------- 1 training training 3278 Sep 26  2019 Hive&ImpalaInScripts&Applications.txt
-rw-rw-r-- 1 training training  449 Sep 26  2019 email_resuts.sh
-rw-rw-r-- 1 training training  120 Apr 27 11:38 color_from_rgb.sql
-rw-rw-r-- 1 training training  397 Jun  4 23:24 game_prices.sql~
-rw-rw-r-- 1 training training  395 Jun  4 23:29 game_prices.sql
--------
Executed in 0.00s
I can echo from impala scripts
--------
Executed in 0.00s
SELECT hex FROM wax.crayons WHERE color = '${hivevar:color}'
--------
Executed in 0.01s

As you can see, you only have to write in your script
shell <command>;

You can even invoke hdfs dfs commands
shell hdfs dfs -<command>;

The above example prints the output to the console, if you want to print the output to a file you have to do as following to redirect all the output to a file:
$ impala-shell -f script_impala.sql >> /home/..../my_file.csv

Other option would be to redirect only the echo commands from inside the script. This would be as following:
script_impala.sql
-- set a variable containing the of the game
SET hivevar:game=Monopoly;
-- return the list of the game
SELECT list_price FROM fun.games WHERE name = '${hivevar:game}';
-- return the prices of the game ate game shops
SELECT shop, price FROM fun.inventory WHERE game = '${hivevar:game}';

shell hdfs dfs -ls /user;
shell ls -ltr;
shell echo I can echo from impala scripts >> /home/..../my_file.csv;
shell echo How are you? >> /home/..../my_file.csv;
shell echo I am feeling very good, how about you? >> /home/..../my_file.csv;
shell cat hex_color.sql

and don't forget the semicolon at the end of the line ";".
I hope it helps.


Dividir layout em 2 colunas

Question: Eu tenho meu codigo de tela inicial que precisa ser dividida em duas partes iguais.
Como eu divido um linear layout em duas colunas com tamanho iguais?
Answer: Você pode usar peso:
layout_weight= "1"

Se os elementos possuir o mesmo peso, terão o mesmo tamanho.
Exemplo:
<LinearLayout
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_centerHorizontal="true">

    <EditText
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1" />

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1" />
</LinearLayout>

Segue a documentação.
Saudações

Dividir layout em 2 colunas


critical point for the curvature does not correspond to a local maximum/minimum.

Question: Draw an example where a critical point for the curvature does not correspond to a local
maximum/minimum
Does the curve for infinity sign satisfy this? I am having trouble seeing why it's true, if of course it's true! I know that at the intersection point the curvature is not defined. I am not sure about the derivative of the curvature at that point
Thanks
Comment: May be I haven't understood, but why can't you use graph of the function $y=x^3$ at the point $x=0$?
Comment: Yes, but doesn't it have a critical point of curvature in $x=0$?
Comment: $x=0$ is a critical point of the curve $y=x^3$, but the question asks about the critical point of curvature of some curve
Answer: If I read you right, you're looking to sketch a plane curve $C$ for which the curvature has a critical point at some point $p$, but $p$ is not an extremum for the $y$ coordinate along $C$. Not sure what you have in mind for "the curve for infinity" (a specific figure eight on its side?)....
If you take the parabola $y = x^{2}$ with $-1 \leq x \leq 1$ (which has maximum curvature at the origin) and rotate it slightly about the origin, you'll get a curve having a curvature maximum at the origin, but for which the tangent line at the origin is not horizontal. Particularly, the origin is not a local minimum or maximum of height. (If necessary, interpolate at the ends to get a graph defined "everywhere".)


Generate string subject to first two bytes of SHA256 of this string equal 0

Question: I have a string s like:
username-password-{random}

I would like to generate the hash SHA256 of the string s, such that first 2 bytes of the hash equal to 0, like:
0000afcbd546843....

So, username-password- is fixed and we can random the {random} part, is there any way to control the random part to get the SHA256 satisfy that condition.
I have the code bash script below, but I have run many time, it does not meet the condition.
pt="0000"
counter=10000000
while [ $counter -le 20000000 ]
do
        echo $counter
        fibyte=$(echo -n ""username-password-"$counter" | sha256sum | cut -c1-4)
        if [ "$fibyte" == "$pt" ]
        then
                echo ""username-password-"$counter"
                echo =======================================================
                break
        fi
        ((counter++))

done
echo DONE

Comment: Could you explain what you are trying to achieve with this? Your requirement makes very little sense.
Comment: In principle you should not control it. But you can do the sha and the prepend your wanted string ?
Comment: I'm sorry, I'm did not get your comment! Can you make it clear!
Comment: Generate the hash, throw away the first four digits and prepend four zeros in their place.
Comment: When saving a password verifier just using a hash function is not sufficient and just adding a salt does little to improve the security. Instead iterate over an HMAC with a random salt for about a 100ms duration and save the salt with the hash. Better yet use a function such as `PBKDF2`, `Rfc2898DeriveBytes`, `Argon2`, `password_hash`, `Bcrypt` or similar functions. The point is to make the attacker spend substantial of time finding passwords by brute force.
Answer: An important and highly crucial property of a cryptographical hash is that the result of the hashing operation cannot be predicted from the input.  So no, unless somebody breaks SHA256, there is no way to control the output.
Trying different inputs until you get an output which meets your constraints isn't really feasible.  If your current code can generate 10,000 attempts per second (in reality it's certainly a lot less, but humor me), you would need to run it for 1.767e68 seconds which is (Wolfram Alpha to the rescue 4.1e50 times the estimated age of the universe to get the result you want, give or take a few universes.
Comment: There are probably no good reasons to do what you seem to be trying to do, anyway.  This is most likely an [XY Problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem).  What are you *actually* hoping to accomplish with this?


pointer-to-pointer of derived class in multiple inheritance

Question: i have 3 classes A,B and C. C is derived from A and B. i get pointer to pointer of class C and cast to A** , and B ** , the variable that hold the the B** has the address of A** in my example B ** BdoublePtr hold the address of A** .i am using the following code
#include "conio.h"
#include "stdio.h"
#include "string.h"

class A
{
public:
    A()
    {
        strA=new char[30];
        strcpy(strA,"class A");
    }
    char *strA;
};

class B
{
public:
    B()
    {
        strB=new char[30];
        strcpy(strB,"class B");
    }
    char *strB;
};

class C : public A, public B
{
public:
    C()
    {
        strC=new char[30];
        strcpy(strC,"class C");
    }
    char *strC;
};

int main(void)
{
    C* ptrC=new C();
    A * Aptr=(A*)ptrC;
    printf("\n class A value : %s",Aptr->strA);

    B * Bptr=(B*)ptrC;
    printf("\n class B value :%s",Bptr->strB);

    printf("\n\nnow with double pointer ");
    A ** AdoublePtr=(A **)&ptrC;
    Aptr=*AdoublePtr;
    printf("\n class A value : %s",Aptr->strA);

    B * * BdoublePtr=(B ** )&ptrC;
    Bptr=* BdoublePtr;
    printf("\n class B value : %s",Bptr->strB);

    getch();
    return 0;
}

Comment: Could you post your code without the extra html markup, and either indent it all by four spaces or press the code button so it appears formatted?
Comment: Ask a question in your question.
Comment: I don't see a question here, but using C-style casts in conjunction with multiple inheritance is almost certainly going to go wrong. Use `static_cast` or `dynamic_cast` instead.
Comment: i have checked casting with static_cast and dynaic_cast and get the same result as above
Answer: The problem is that what you are trying to do is impossible; there is no valid conversion from C** to B**. The pointer at *BdoublePtr contains the address of a C, not a B, and nothing you do to BdoublePtr can change that.
The C-style cast in your code is equivalent to a reinterpret_cast; it takes the value of the C* and pretends it's a B*. This gives undefined behaviour. In your case, Bptr->strB happens to find the string in the A object in the C object that the pointer points to, but in principle absolutely anything could happen.
By the way, if you're writing C++, then you really should use C++ headers and strings. That would fix some of the memory leaks in your code for a start.


Proving that a set is infinite

Question: Consider $G\subset M_2(\mathbb{C})$ where $G =\begin{Bmatrix}
\begin{pmatrix}
a & 10b\\
b & a
\end{pmatrix}
& | a,b \in \mathbb{Q},a^2-10b^2=1&
\end{Bmatrix}
$ . Prove that G is infite.
I was thinking of searching for two numbers $a$ and $b$ from $\mathbb{Q}$ who don't satisfy the equation $a^2-10b^2=1$ , but how?
Answer: You need to prove that there are infinitely many $a,b$ such that
$$a^2-10b^2=1$$
It is easy to find one, and then if you look for Pell-Fermat equation( aka Pell equation) you will see how to construct infinitely many solutions.
Answer: Note that if $A,B\in G$ then $AB\in G$ hence if :
$$ A=\begin{pmatrix}19 &60 \\ 6 &19\end{pmatrix}\in G$$
Now prove that $A^n\in G$ for every positive integer $n$

Given two elements of $G$ :
$$A=\begin{pmatrix}a &10b \\ b&a\end{pmatrix} \,\, B=\begin{pmatrix}a&10b' \\ b' &a' \end{pmatrix} \implies AB=\begin{pmatrix}aa'+10bb' &10(ab'+ba')\\ ab'+ba'&aa'+10bb'\end{pmatrix}\in G$$
hence $G$ is closed by multiplication and for every $A,B\in G$ we have $AB\in G$ and in particular $tr(AB)\geq 2aa'=\frac{tr(A)tr(B)}{2}$
Now it's easy to observe that:
$$ M=\begin{pmatrix}19 &60 \\ 6 &19\end{pmatrix}\in G$$
and as a consequence $M^n\in G$ for evry positive integer $n$, and we know that $$tr(M^{n+1})\geq \frac{tr(M^n)tr(M)}{2}=19tr(M^n)>tr(M^n)$$
so the sequence $M^n$ is an infinte sequence of elements of $G$
Comment: Nice one.But how did you find the A?
Comment: From the pell equation , i understand now
Comment: But what if A is periodic?
Comment: it's not periodic because $tr(A)$ is always incresing
Comment: Can you prove this , please?
Comment: I updated my answer as you requeusted

Proving that a set is infinite


How to list the uploaded files (image file) of unsaved nodes?

Question: From the question What happens if a user uploads an image but doesn't save the node? and its answer, there is a table called file_managed and for any uploaded file (an image in my case), it sets 0 in status column, and if the image node is saved, it is set to 1. During each cron run, all files with 0 status will be removed.
I am using bulk_file_nodes module to upload the images. Unfortunately, this module sets the status 1 for uploaded files and no matter if their node is saved or not.
I need to accomplish what Drupal core does for unsaved nodes of uploaded files. To do so I have to list those files. There are about 30000 images and about 2500 nodes in my website that are uploaded by people and it is growing very fast every day.
The brute force method is to check the entire fid column of field_data_field_image table of the database for every file (in fact for every fid of file_managed) to see if that file is attached to a node or not, I think it is not a good solution at all.
Is there any way else to handle this?
thanks
Answer: The short answer is that there isn't really a way to do this.
The longer version is that you could make some SQL to find all candidates. The issue is that you can see if a file is used somewhere (on entites) on the file_usage table, but some files wont be "used in that manor. This means that finding a file "not being used" is not the same as it's safe to delete it.
A solution could be to make a cron job, that only checks images that has just been uploaded, but you still have the issue that you might end up deleting files that shouldn't have been deleted.
Comment: Thank you for your reply. The destination folder of that node content type is unique, other content types use their own destination. Despite of this fact, there is still no way to do that? What if I search for file name in the folder and see if there is a match in database?
Comment: I posted an answer, I guess it solves the problem
Answer: If the image field which contains image of the node type is field_data_field_image, the following query returns unassigned uploaded files to nodes:
<?php
    $result = db_select("file_managed","fmanage")
        ->fields("fmanage",array('filename'))
        ->fields("fmanage",array('uid'))
            ->fields("fmanage",array('fid'))->execute();
    foreach ($result as $row){
        $fid = $row->fid;
        $result1 = db_select("field_data_field_image","imagefid")
            ->condition("imagefid.field_image_fid",$fid,"=")
        ->fields("imagefid",array('field_image_fid'))->execute();
        if($result1->rowCount() == 0){
            print $row->filename."
";
            print $row->uid."
";
            print "
";
        }
    }
?>

Just notice that, the field_data_field_image must be the only image field in the website. If there is other image field with another name, the query should search for them too. Because I use the field_data_field_image for every image field in my website, I only need to search this table.
I executed the above code and returned the correct result.


Can I create an openssl key for a server from a different host?

Question: I have two EC2 instances with an ALB and I need an SSL certificate for Tomcat.  I don't have shell access to the EC2 instances, I can only work them via Ansible.  I have to generate a cert request but I need a key to do that.
Can I generate a key on my own machine and use that to request the cert?
Comment: It doesn't matter where you generate the key at all, as longs as you can securely transfer and install your key on the target server  together with the certificate once the CSR has been processed. -
Answer: Yes, technically the CSR request can be signed with any key anywhere, but once the signed certificate is generated you will need to use the same key you have used for the CSR request.
So in other words, you will need to transfer the key somehow to the servers so Tomcat can use the certificate along with the key.
Answer: When dealing with SSL/TLS you have to take in consideration the security aspect of your actions.
Yes technically it is possible to generate the key and copy it to another machine. But my advice is to generate and keep the key only on the destination server, and never copy the key somewhere else.
It is also possible to have 2 different certificate-and-key pairs at the same time. this has the advantage that if one site is compromised, you can still use the other machine and certificate+key that is not yet compromised.


Menu dropdown - transformar  em

Question: Gostaria de colocar o menu dropdown no meu site na hora de escolher as variações. Tanto no mobile quanto no computador.
Eu achei esse artigo ensinando a fazer, mas no script eu não consegui substituir corretamente os termos de CSS e HTML.
O script que eu usei:
https://css-tricks.com/convert-menu-to-dropdown/
Site com dropdown modelo:
https://www.madrugaosuplementos.com.br/100-whey-protein-2270g-optimum-nutrition-multishaker-gratis/
Meu site:
https://www.imperiodosuplemento.com/molho-de-tomate-grape-organico-todos-os-sabores-lergurme
O script que estou adaptando para meu site:
<code><script type="text/javascript">
// Create the dropdown base
$("<ul />").appendTo("atributo-comum");

// Create default option "Go to..."
$("<option />", {
   "selected": "selected",
   "value"   : "",
   "text"    : "SELECIONE..."
}).appendTo("atributo-comum ul");

// Populate dropdown with menu items
$("nav a").each(function() {
 var el = $(this);
 $("<option />", {
     "value"   : el.attr("href"),
     "text"    : el.text()
 }).appendTo("nav select");
});

$("nav select").change(function() {
  window.location = $(this).find("option:selected").val();
});
</script>
</code>
Alguém pode me ajudar a fazer funcionar?
Comment: Cara pq vc simplesmente não da um display none no menu e um display block no select quando a tela for menor?
Answer: Mas precisas de jquery para obter o efeito dropdown?
Apenas media query (css) resolve teu problema;
Teu layout quebra em 768px, precisa trocar a disposição dos elementos neste ponto:
@media screen and (min-width: 768px)
.menu.superior {
 /.../
}

Menu dropdown - transformar  em


JMX Monitoring on a Weblogic Cluster, how to monitor java.lang space

Question: On a remote Weblogic Cluster, I would access to each size of the Non Heap memory of each instance of my cluster.
I'm connected to my admin server with a url such as this one:
service:jmx:t3://acetp-env-admin:9091/jndi/weblogic.management.mbeanservers.runtime
How could I access to java.lang jmx package of each instance?
Thanks
Answer: The service url you have will let you connect to the MBean server that Weblogic is exposing. This is for control over services weblogic provides but not core JVM mbeans. You need to connect to the Platform MBean server - directly to the JVM. That's why you're not seeing java.lang.
Check out http://download.oracle.com/javase/1.5.0/docs/guide/management/mxbeans.html
Comment: ok, that's what I supposed! No miracle method to register the java.lang.* in mean


Density in negative Sobolev spaces

Question: Consider $\Omega = (0,2 \pi)^d$ and the negative Sobolev space $H^{-s}(\Omega)$, defined as the dual of $H^s_0(\Omega)$ for the $L^2$ inner product. Due to the simple shape of $\Omega$, we can see $H^{-s}(\Omega)$ as a Banach/Hilbert space with the inner product:
$$
\langle f, g \rangle_{H^{-s}} := \sum_{n \in \mathbb{Z}^d}  f_n g_n (1 + | n |^2)^{-s},
$$
where $(f_n)$ and $(g_n)$ are the Fourier coefficients of $f$ and $g$.
Question: Is $C^\infty_0(\Omega)$ dense in $H^{-s}(\Omega)$?
Comment: Partial answer: By truncating the Fourier series you can show that trigonometric polynomials and hence $C^{\infty}(\overline\Omega)$ is dense in $H^{-s}(\Omega)$ for all $s.$ I think you can also use $C^{\infty}_c$ functions, but I can't think of an easy argument at the moment.
Answer: The answer is affirmative. In a previous version of this post I claimed the opposite, but I was wrong. (The previous version is below. Following my usual policy, I am NOT deleting it).
Claim. The space $C^\infty(\mathbb T)$ of smooth and $2\pi$ periodic functions is dense in $H^{-s}(\mathbb T)$ for all $s\in \mathbb R$.
Proof. We will prove that $C^\infty(\mathbb T)^\bot$ is reduced to $\{0\}$. So, let $g\in H^{-s}(\mathbb T)$ be such that
$$
\sum_{-\infty}^\infty \frac{\hat{g}(n)\overline{\hat\phi(n)}}{(1+|n|^2)^s}=0, \qquad \forall \phi \in C^\infty(\mathbb T).$$
In particular, letting $\phi(x)=e^{imx}$, so that $\hat\phi(n)=0$ for $n\ne m$ and $\hat\phi(m)=1$, we see that
$$\frac{\hat{g}(m)}{(1+|m|^2)^s}=0, $$
which implies $\hat{g}(m)=0$. Since $m$ is arbitrary, we conclude that $g=0$, as claimed. $\Box$
Remark. This is exactly the proof suggested by the OP dgontier in comments below, and also by ktoi in comments to the main question.
Remark. I find this result a bit surprising. If $f\in H^{-s}(\mathbb T)$, its Fourier coefficients $\hat{f}(n)$ are allowed to grow as $n\to \infty$. If $s>1/2$, the space $H^{-s}(\mathbb T)$ contains singular distributions such as the Dirac comb $\delta$. On the other hand, if $\phi\in C^\infty(\mathbb T)$, then its Fourier coefficients decay faster than any polynomial. So, I find it  surprising that $C^\infty$ functions suffice to approximate arbitrary $H^{-s}$ elements.

PREVIOUS VERSION OF THIS ANSWER.
WARNING. There is a mistake, marked below. Now I have to go, but I am not deleting this answer, maybe someone will point out a solution, or it will be useful in some other way.

The answer is negative. To ease typing, let me assume $d=1$. Let $f_n\in C^\infty_0(0, 2\pi)$ and suppose that there is a $f\in H^{-s}$ such that $\lVert f_n-f\rVert_{H^{-s}}\to 0$. This means that
$$
\sum_{k=-\infty}^\infty \frac{\lvert \hat{f}_n(k)-\hat{f}(k)\rvert^2}{1+k^{2s}}\to 0, \qquad n\to \infty.$$
In particular, for each $k_0\in\mathbb Z$,
$$\tag{*}
\lim_{n\to \infty} \frac{\lvert \hat{f}_n(k_0)-\hat{f}(k_0)\rvert^2}{1+k_0^{2s}} =0.$$
Now, integration by parts shows that, since $f_n$ is smooth, $\hat{f}_n(k)$ decays as $\lvert k \rvert\to 0$ (faster than any power of $k$, but we won't need this quantification). For sufficiently big $n$, we have from (*) that
$$
\frac{\lvert \hat{f}_n(k_0)-\hat{f}(k_0)\rvert^2}{1+k_0^{2s}} \le 1.$$

(WARNING: this seems to be wrong). So, taking the limit as $k_0\to \infty$ shows that  $$ \lim_{k\to
 \infty} \hat{f}(k)=0.$$

However, not all $f\in H^{-s}$ satisfy this. For example, if $s>1/2$ then the Dirac comb is in $H^{-s}$, and $\hat{\delta}(k)=1$ for all $k$.
Comment: Thanks for the comment. I think I now have a proof that it is correct: I think it is enough to say that $C^\infty_0$ is dense in $L^2$ (for the $L^2$ inner product, hence also for the $H^{-s}$ one), and that $L^2$ is dense in $H^{-s}$.
Comment: @dgontier: So you say it is true? I have a concern, which I tried to express in this answer, but rather perfunctorily I am afraid. In negative order Sobolev spaces, the Fourier coefficients are not required to decay at infinity, and they can even grow, if $s$ is big enough. For example, the distribution $\delta$, which is such that $\hat{\delta}(n)=1$ for all $n$, belongs to $H^{-s}(\mathbb R^d)$ for all $s<d/2$. On the other hand, smooth functions have very fast decaying Fourier coefficients. I am not sure you can approximate distributions such as $\delta$ with such smooth functions.
Comment: @dgontier: However, your reasoning seems correct to me. To reinforce it, I checked the book of Bahouri, Chemin and Danchin "Fourier analyisis and nonlinear PDEs", and Theorem 1.61 states that $C^\infty_0(\mathbb R^d)$ is dense in $H^s(\mathbb R^d)$ for all $s\in\mathbb R$ (this is NOT the space you want, but it is very similar). The proof seems to be the exact transposition of the argument you suggest. I am thus inclined to think that my intuition was wrong.
Comment: Thx for the reference. Indeed, I know the result to be correct in the whole space $\mathbb{R}^d$. I was concerned about bounded sets $\Omega$. I now believe the answer to be positive.
Indeed, the coefficients of $H^{-s}$ functions can grow, but this is taken into account in the $H^{-s}$ norm.
Comment: @dgontier: Yes, I agree, the answer is affirmative in every case. The proof I wrote above is for $\Omega=\mathbb T$, that is $(0, 2\pi)$, but the exact same proof works for $\Omega=(0, 2\pi)^d$ for any $d\in\mathbb N$, and actually for any bounded open set, but in that case you have to change the definition of the Fourier series; instead of complex exponentials $e^{ix\cdot n}$ you will need a complete system of eigenfunctions of the Laplacian.
Comment: I think the point is that $\mathcal{C}^\infty_0$ is dense in $H^{-s}$ _for the $H^{-s}-norm$_. If you simply truncate your Fourier serie, the coefficients in the remaining part might indeed diverge, but they do tend to zero when you multiply them by $k^{-2s}$.
Comment: @Isao: right, that's a good way of seeing this question.
Comment: I think it also gives you a proof: for $f\in H^{-s}$, let $g\in L^2$ be the serie with Fourier coefficients $ (1+|k|^{2s})^{-1} \hat{f}_k$. Let then $g_n$ be a sequence in $\mathcal{C}^\infty$ approximating $g$ (in the $L^2$-sense), and $f_n$ the serie with Fourier coefficient $\hat{f}_{n,k}=(1+|k|^{2s})\hat{g}_{n,k}$. Then the $f_n$ are smooth and approximate $f$ in the $H^{-s}$ sense. I didn't check the details.
Comment: Probably that it works because of the commutative diagram $\Delta\circ \iota=\iota' \circ \Delta$, where $\Delta$ is a fractional laplacian and $\iota,\iota'$ are two Sobolev embeddings (or someting like that...).

Density in negative Sobolev spaces


Process to move SSH server keys to new server

Question: Going to be moving a server to new hardware in a new datacenter soon, and of course this means a new IP.
What is the correct process (if at all) to move the SSH keys from the original server to the new one so that connecting clients don't get any warnings or have to accept anything again?
Is it even possible, considering the IP is changing?
What files do I have to move? I'm assuming all of the ssh_host_* files.
Moving from RHEL 5 to Ubuntu 10.04.
Answer: You can move the keys from your current serer to the new server without much hassle. You just need to make sure they go into the same location and have the same permission.
Ideally though, you should take the opportunity to create new keys and update the client keys in the interest of security.
Comment: I forgot to add that your users may get a warning when they connect to the new host that they already have a host in their knownhosts file which matches the key they are authenticating against. This means they will have to remove the entry in their known hosts file. You can't get around this.
Comment: So if users might get a warning anyway, is there much of a point in moving the keys?
Comment: users will get a waring. It will be a man in the middle attack message. It looks scary but if you delete know_hosts from the client they will get a less scary message. I don't know away around a prompt of some sort.
Answer: 1) If your sshd config files are stored under /etc/ssh/, you'll need to copy all of those. You'll find the sshd config there, as well as the host-keypair.
Make sure you correctly copy the permissions too! The sshd will simply ignore keys that are not properly protected. (Good as well, as an unprotected private key is a very bad idea.)
2) If you have already added public keys of remote hosts that are trusted and don't require a password to log in anymore, you'll also have to copy that info in order for the auto-login to work again now. This info is stored normally in /home/-account-/.ssh/ (under authorized_keys). Again, don't forget the permissions here.

Regarding the IP address change, assuming the remote clients actually see a change in IP (you're not behind some reverse proxy or anything), then no, they will require the user the accept the certificate again. (since in the known_hosts file of the remote client, the server's IP & server's certificate were stored together) Worse, if you assign that IP address to another ssh server, they might even be warned of a man-in-the-middle attack.
So just using the same (external) IP address on the new server makes sense.
Answer: You didn't mention your OS.  I can tell you for certain that a RHEL host has the server keys stored in /etc/ssh.  Just copy that directory over in its entirety.  You'll then need to bounce sshd/restart the box.
I believe that as long as you are connecting via the same DNS name, you shouldn't get warnings.  Even with the new IP.

--Christopher Karel
Comment: Then yeah, /etc/ssh is the directory you want. I'd recommend just the ssh_host* keys. Don't move the config files.  And you'll want to back up the destination side of things, just to be safe.
Comment: Added note about what the OS's are


Delphi : Sorted List

Question: I need to sort close to a 1,00,000 floating point entries in Delphi. I am new to Delphi and would like to know if there are any ready made solutions available. I tried a few language provided constructs and they take an inordinate amount of time to run to completion.(a 5-10 sec execution time is fine for the application)
Comment: I suspect it is using the Indian style of digit grouping `http://en.wikipedia.org/wiki/Indian_numbering_system`
Comment: What language-provided constructs did you use, and how long did they take?
Comment: Is this '1,00,000' a typo or a weird formatting of 100,000?
Answer: why not  just implement a quick Sort algorithm?
see this simple code
program ProjectSortFoat;

{$APPTYPE CONSOLE}

uses
  SysUtils;

procedure QuickSort(var List: array of Double; iLo, iHi: Integer) ;
var
  Lo       : integer;
  Hi       : integer;
  T        : Double;
  Mid      : Double;
begin
  Lo := iLo;
  Hi := iHi;
  Mid:= List[(Lo + Hi) div 2];
  repeat

    while List[Lo] < Mid do Inc(Lo) ;
    while List[Hi] > Mid do Dec(Hi) ;

    if Lo <= Hi then
    begin
      T := List[Lo];
      List[Lo] := List[Hi];
      List[Hi] := T;
      Inc(Lo);
      Dec(Hi);
    end;

  until Lo > Hi;

  if Hi > iLo then QuickSort(List, iLo, Hi);
  if Lo < iHi then QuickSort(List, Lo, iHi);

end;

const
Elements = 1000000;
var
  doubleArray : array of Double;
  i           : integer;
  t           : TDateTime;
begin
  SetLength(doubleArray,Elements);
  try
    t:=Now;
    Writeln('Init Generating '+FormatFloat('#,',Elements)+' random numbers ');
    for i:=low(doubleArray) to high(doubleArray) do
    doubleArray[i]:=Random(10000000)+Random; //can be improved
    Writeln('Elapsed '+FormatDateTime('HH:NN:SS.ZZZ',Now-t));

    t:=Now;
    Writeln('Sorting '+FormatFloat('#,',Elements)+' random numbers ');
    QuickSort(doubleArray, Low(doubleArray), High(doubleArray)) ;
    Writeln('Elapsed '+FormatDateTime('HH:NN:SS.ZZZ',Now-t));

  finally
  Finalize(doubleArray);
  end;
  Readln;
end.

in my machine, the execution time for sorting 1.000.000 float numbers is 0.167 seconds.
if you have delphi 7 or another older version  (i don't know if exist in the new versions) you can check the

C:\Program
  Files\Borland\Delphi7\Demos\Threads

path, for a cool demo app using differents sorting algorithms an threads.
Comment: The Threads demo is still in Delphi 2010.  There is a link to the Demos directory in the Start menu.
Comment: @Bruce you are right, in Delphi 2010 the path is `C:\Users\Public\Documents\RAD Studio\7.0\Demos\DelphiWin32\VCLWin32\Threads`
Comment: The path depends on your OS, so it might be easier for people to use the Rad Studio link.
Comment: @PRUZ : Thank you. I used it in my application and it was quick :-). I am using Delphi 7 and i searched for a SortedList implementation, and instead found a SortArrayAscending procedure with array of extended, which took a long time. I assumed since the language provided sorting takes so much time, my own sorting implementation might take a longer time. My bad.
Answer: What version are you using?  If you're in Delphi 2009 or 2010, you can use generics to make a TList<real> and call its Sort method.
If you're in an earlier version, the non-generic TList has a Sort method too, but it's a bit trickier to set up since it uses pointers, and Real (or Double), which is what you probably want to use as a floating point number, is too large to cast to a pointer.

Delphi : Sorted List


Removing a stale CoreOS node from discovery.etcd.io

Question: I removed a node from a CoreOS cluster and brought up a fresh one in its place. Unfortunately, it picked up the same IP as the old machine.
This stopped etcd from discovering the rest of the cluster, with messages like this in the journal: "failed: fail on join request: Peer address has existed"
How can I remove the old node from discovery.etcd.io?
Answer: Short answer if you know the machine id
Send an HTTP DELETE request to https://discovery.etcd.io/<cluster-id>/<machine-id>
e.g.
curl https://discovery.etcd.io/abcdef0123456789abcdef0123456789/7cf9a5cf5e3b4baea82e28618bffeaf5 -XDELETE

Longer answer - how to find the machine id to delete
First, fetch the JSON object from your discovery URL, e.g.
https://discovery.etcd.io/abcdef0123456789abcdef0123456789

It will look a bit like this:
{
  "action": "get",
  "node": {
    "key": "\/_etcd\/registry\/abcdef0123456789abcdef0123456789",
    "dir": true,
    "nodes": [
      {
        "key": "\/_etcd\/registry\/abcdef0123456789abcdef0123456789\/6148dbb812a44dbe8773bebf329634e7",
        "value": "http:\/\/10.132.47.218:7001",
        "expiration": "2015-04-15T17:58:12.753046544Z",
        "ttl": 598570,
        "modifiedIndex": 453369429,
        "createdIndex": 453369429
      },
      {
        "key": "\/_etcd\/registry\/abcdef0123456789abcdef0123456789\/646fbdaee73544e6ac289894e935f0c7",
        "value": "http:\/\/10.132.47.218:7001",
        "expiration": "2015-04-15T18:30:03.08506867Z",
        "ttl": 600480,
        "modifiedIndex": 453418705,
        "createdIndex": 453418705
      },
      {
        "key": "\/_etcd\/registry\/abcdef0123456789abcdef0123456789\/05e0decf1d9240819382db7a7f8ff2e7",
        "value": "http:\/\/10.132.58.166:7001",
        "expiration": "2015-04-14T23:47:31.402148037Z",
        "ttl": 533129,
        "modifiedIndex": 451690943,
        "createdIndex": 451690943
      },
      {
        "key": "\/_etcd\/registry\/abcdef0123456789abcdef0123456789\/af2783b2327e4f3a9b6e7ea169814a06",
        "value": "http:\/\/10.132.58.167:7001",
        "expiration": "2015-04-14T23:47:38.676204353Z",
        "ttl": 533136,
        "modifiedIndex": 451691169,
        "createdIndex": 451691169
      }
    ],
    "modifiedIndex": 426955695,
    "createdIndex": 426955695
  }
}

Let's say our reused IP is 10.132.47.218 - we want to identify the machine id which corresponds to that. We can see from the key this is 6148dbb812a44dbe8773bebf329634e7
Now we can delete this simply using a DELETE verb
curl https://discovery.etcd.io/abcdef0123456789abcdef0123456789/7cf9a5cf5e3b4baea82e28618bffeaf5 -XDELETE


How to delete a cck field base in Drupal 6

Question: I have programatically created some cck fields with this function:
content_field_instance_create($field)

and I tried to delete them with this:
content_field_instance_delete($field_name, 'product', FALSE)

However, this didn't actually delete the cck field from the Product types database table. The fields didn't show up on the UI edit page but they still exist in the database, which is causing me some issues.
How can I systematically make sure the database entry is wipes as well?
Answer: I believe deleting the fields programmatically like this flags the fields as deleted by CCK or the Field API in Drupal 6/7. You must then run Cron to have the system fully purge the database tables from the system.
Comment: I just ran cron manually and inspected the table, and there was no change. Not sure if this makes a difference, but as these fields are not reused, instead of new tables in the database, they are extra columns in the content_type_product table.


Apache Flink; Determine Window Boundary Timestamps

Question: In Apache Flink, when processing the result of an aggregation, I need to know the timestamp (process time) of the start of a tumbling window.  Is there a way to get this timestamp?  Are window boundaries or is the watermark exposed tot he AggregationFunction?
Answer: Along with your AggregateFunction, you have the option to specify a WindowFunction.
According to the documentation you can do the following:

stream.
.keyBy()
.window()
.aggregate(new AverageAggregate(), new WindowFunctionTest());

public static class WindowFunctionTest implements WindowFunction<..., ...,
    Tuple, TimeWindow> {
    public void apply(Tuple key, TimeWindow window, Iterable<...> input,
    Collector<...> out) {
        long windowStartTime = window.getStart();
    }

Comment: Pleasure. Also, I have to mention that window start and end are related to the time notion that you're working with.
Comment: Thank you, this answers the question as I asked.  Though, I should have clarified that I'm looking for the timestamp as I write to the sink.

Also, FYI:  I looks like `ProcessWindowFunction` is the new preferred way and WindowFunction will be deprecated:
https://nightlies.apache.org/flink/flink-docs-release-1.16/docs/dev/datastream/operators/windows/
Comment: Turns out that the timestamps in the SinkWriter.Context are not related to the window time stamps (I'm not sure what the timestamps are for).  I ended up having to use a ProcessWindowFunction.  Thanks!
Answer: I found that the SinkWriter.Context in the ElementConverter has the window and watermark timestamp.  I only need the timestamps when writing to the sink, so this is sufficient for me.


Remover data e link da impressão

Question: Estou fazendo uma tela com diversas informações e imagens, ate ai tudo bem. Meu problema é que ao tentar imprimir essa tela, aparece data no cabeçalho e o link no rodapé. Existe algum jeito de remover isso sem ser pela configuração do browser?
Answer: Não, não existe.
Essa "feature" é totalmente independente do seu código fonte. Não existe markup que os faça desaparecer, já que isso não vem de nenhuma especificação do HTML, e não há código Javascript para controlar isso pois os desenvolvedores dos navegadores em geral não publicam API's para isso. Ainda que existisse uma API única e cross-browser para controlar a impressão dessa forma, remover essas informações da impressão seria interferir com algo que é escolha do usuário, e portanto poderia ser visto como uma falha de segurança.
Aqui e ali você pode ver alguém sugerir uma forma de contornar isso, ao tentar controlar as margens de impressão. Isso é uma gambiarra e não é garantido que funcionará em todos os navegadores - e mesmo que funcione, não se sabe por quanto tempo continuará a funcionar. Eu pessoalmente acredito que existe um lugar especial no inferno para todos aqueles que tentam burlar o comportamento padrão dos navegadores.
Comment: Ok, obrigado pela ajuda.

Remover data e link da impressão


What's the difference between distributed computing and cloud computing?

Question: What is the difference between distributed computing and cloud computing?
Answer: Distributed computing is when multiple autonomous machines communicate through a central network to perform a common goal.
Cloud Computing is more about computing as a service, that is given to a computer over a network.
For example, a distributed computing network might be 10,000 people processing SETI data on their computers through a screen saver.  And cloud computing might be when a million Apple users save all their MP3s to iCloud, rather than on their laptops.
I think the two sound more related than they are.
Answer:
The main difference between cloud computing and distributed computing is that the cloud computing provides hardware, software and other infrastructure resources over the internet while the distributed computing divides a single task among multiple computers that are connected via a network to achieve the task faster than using an individual computer.
Cloud computing helps to access hardware and software resources remotely via the network. It provides advantages such as easy resource sharing, cost reduction, scalability, and platform independence. A distributed computing, on the other hand, is a network with multiple computers to achieve a goal. Each computer in the network performs a section of the overall tasks. This method helps to obtain results faster than using a single computer. It provides advantages such as scalability, redundancy and resource sharing.

Source: Difference Between Cloud Computing and Distributed Computing
Comment: This is word by word copied from https://pediaa.com/difference-between-cloud-computing-and-distributed-computing/ . You should at least include reference to original source in the answer.
Answer: Distributed Computing:
Is a system/solution that is able to borrow resources for processing from other systems/solutions. Usually by delegation and using communication distribution systems or networks.
Cloud Computing:
Are the product/services and resources provided from such a system.
More
Distributed computing can be as complex and robust as an operating system which basically could allow you to combine several computers to act as one. Or, as simple as an application which borrows free resources from other systems it can communicate with and has a "contract" with. Contract is not a technical term for it, I just find it fitting. The distributed computing doesn't necessarily depend on all its parts and may operate independently, but is able to delegate tasks to other parts of its system.
Cloud Computing is built from/with distributed computing. Technically, if you have an application which syncs up information across several of your devices you are doing cloud computing and since it is using distributed computing.
Now to tighten up that head vice. You can build a distributed system using cloud computing. Infinite loop! It's not that crazy since you could basically build a distributed system out of other distributed systems. It's a system of systems.
Note:
I felt compelled to answer this since I felt like every other answer was missing one thing or another. I hope, I didn't do the same.
Answer: Let's start with defining what these two terms mean exactly. The difference will start becoming apparent from the definitions itself.
Cloud computing is a system where different things like software applications, infrastructure resources, or development tools are provided to the user via the Internet. Traditionally, if a user wanted to run a software application, it was mandatory for them to make sure that they fulfill all the extensive software and hardware requirements that are necessary for running that single application.
But, with cloud, that's not the case anymore since the application can be accessed simply through an Internet connection. The user no longer has to worry about any software or hardware installation on their personal system to avail the application.
It's not only software applications that can be accessed over the Internet, but many other things too like databases, servers, software development resources, data centers, etc. In fact, cloud offerings are of three types, software as a service (SaaS), infrastructure as a service (IaaS), and platform as a service (PaaS).
Next, let's define distributed computing. This is a kind of system where a single software system has components distributed across a number of computers, but they all execute as a consolidated system. These distributed components of the software are connected with each other through a network. Therefore, the computers over which the software components are spread across will have a way for communicating with each other and ensuring that there is synchronization between the software components. Depending on whether the computers are located nearby in same location or away from each other in different locations, the network connecting the computers could be a local area network or a wide area network. Distributed computing systems can be of three kinds: distributed computing systems, distributed pervasive systems, and distributed information systems.
Now, that we understand the definitions of distributed computing and cloud computing, hopefully the distinction between these two computing models has become clearer already. While cloud computing refers to the delivery of necessary resources via the Internet, distributed computing refers to sharing of resources between the systems via a connecting network. Each of these computing models has unique set of benefits to offer.
Scalability is one of the most prominent advantages of cloud computing solutions. Depending upon increasing or decreasing resource demands, it is possible to get access to more or less software, storage, network, and other computing resources over the Internet.
Cost-efficiency and simplicity are some other advantages of this model.
Distributed computing too offers scalability, in the sense that you can add or remove computer systems in the network depending on the current requirements. Distributed software applications also ensure better performance and resilience.


Calling functions on socket message (socket.io/node.js)

Question: When I start a new instance of GameServer, it sets up the socket and listeners as follows.
var GameServer = function() {
    this.player = new Player();
    var that = this;

    // Setup sockets and listeners
    var socket = io.listen(8000);
    socket.sockets.on('connection', function(client) {
        client.on('message', that.onSocketMessage);
        client.on('disconnect', that.onSocketDisconnect);
    });
}

I then have two prototypes GameServer.prototype.onSocketMessage & onSocketDisconnect.
I have two problems with the current code:

Using that = this and the closure? function. Looks ugly.
When onSocketMessage is called, the idea is it works out what the message is then calls another function within GameServer. Only this isn't possible as now this belongs to the socket.io system. See below:

...
function onSocketMessage() {
    this.player.move();
}

this.player is no longer available as this. is no longer part of GameServer.
Should my socket setup and message passing be handled outside of GameServer function and prototypes?
Or how else could I resolve this?
Cheers
EDIT
Ok so I have tried this and it works but looks pretty ugly I think:
var socket = io.listen(8000);
socket.sockets.on('connection', function(client) {
    client.on('message', function (data) {
        that.onSocketMessage(this, that, data);
    });
    client.on('disconnect', function() {
        that.onSocketDisconnect(this, that);
    });
});

Can it be improved upon?
Answer: Two things that may help. Thing the first:
You can modify a function's vision of this using the bind method.
socket.sockets.on('connection', function(client) {
    client.on('message', this.onSocketMessage);
    client.on('disconnect', this.onSocketDisconnect);
}.bind(this));

Notice the call to bind(this) at the end of the function; this instructs JavaScript to create a closure for you, making whatever this is outside the function, this inside the function. (If you wanted to make this inside the function, say, MySomething, you could just as easily call bind(MySomething), though bind(this) is the most common use).
Thing the second:
You can store data in a Socket.IO socket. So, for example, if one socket is always associated with a player, you can do
socket.set('player', player, function() {
  // callback is called when variable is successfully stored
  console.log('player has been stored');
});

// and later

socket.get('player', function(err, player) {
  // callback is called either with an error set or the value you requested
  player.move();
});

The get and set methods take callbacks because the Socket.IO data store can be set to something other than an in-memory store; for example, Redis.
Comment: The bind option works perfectly. Funnily enough I had already tried bind but I had implemented it incorrectly and it didn't work. Now I can see why! Question though: 'client.on('message', this.onSocketMessage.bind(this));' When that message is received, normally within onSocketMessage, you would have this.id available (which would be the client/sockets id) and (data) passed into your function. Data is still passed, but I no longer have any access to this.id. How would I get that passed in as well?
Comment: You cannot; that's why `bind` is really only useful for your first issue. For your second issue, I would work on getting the `player` into the method some other way.


Formatação/Quebra de linha de código no Android Studio

Question: Quando faço a reformatação automática Ctrl+L o código fica identado, porém as linhas não quebram, como acontece no Eclipse e no Netbeans, de modo que eu tenho ficar arrastando a janela constantemente para ver o final de uma linha maior, como no exemplo:
<code>NtpTimeProvider ntpTimeProvider = new NtpTimeProvider(InetAddressFactory.newFromHostString("192.168.0.1"), nodeMainExecutor.getScheduledExecutorService());
</code>
Alguém saberia onde eu posso configurar isso para que as linhas quebrem e o código fique do tamanho da janela?
Answer: Você precisa ir em Files > Settings > Editor > Code Style > Java > wrapping and Braces > Marcar a opção: Ensure right margins is not exceeded


search in strings to find word with preg match all and regex

Question: i am trying to code a search function to search in strings and find the word
like the php + mysql for example
Select * From Column Where ID Like %Word%

i tried to code the same idea with Preg match all and regex
Here is my code
$strings = '
( monstername 205 "Devil Troop of Desire")
( monstername 206 "  Devil Troop of Pain     "  )
( monstername 207       "Devil Troop of Greed")
( monstername 208   "       Devil Troop of Jealousy  ")
( monstername 207 "Mask Troop of Greed"  )';

preg_match_all('/monstername\s*(.*?)\s*\"\s*\\b(Jealousy)\b\s*\"\s*\)/i', $strings, $matches, PREG_SET_ORDER);
foreach ($matches as $match){list (, $MonsterNumber) = $match;
echo "$MonsterNumber";
}

the output should be
208

but it dont display the output correct
it display it when i replace Jealousy With Devil Troop of Jealousy
i just want to do the same idea of php + mysql
Where ID Like %Word%
without give the full string to find the number of monster
Comment: My regex skills aren't too bad right now as i was using regex yesterday in PHP. However, my problem is trying to understand what you're trying to do, why would the output be 208? If it was like mysql you would have the number of rows that match but getting 208 is like returning ONE result using MAX() :/
Answer: The part "\s*\\b(Jea does not allow for other characters than whitespace between the quote and the start of the word. You probably wanted any char (or even none?) between them, like ".*\\b(Jea and the same problem after the word.
Comment: well, it worked fine but it that possible to write only Jea  Like ".*\\b(Jea)\b.*\"  and get output, because i tried but it didnt work, and this is a search script
Answer: You have to better define what you are searching for: before and after Jealousy you may have space/non-space, non-quote characters.
preg_match_all('/\( monstername\s*(\d+)\s*"\s*([^"]*\bJealousy\b[^"]*)\s*"\s*\)/i',
$strings, $matches, PREG_SET_ORDER);

Or to use in a search script,
preg_match_all('/\( monstername\s*(\d+)\s*"\s*([^"]*(Jealousy)[^"]*)\s*"\s*\)/i',
$strings, $matches, PREG_SET_ORDER);

For each matching monster it will return matching row, monster number, monster name and matched pattern:
Array
(
    [0] => Array
        (
            [0] => ( monstername 208   "       Devil Troop of Jealousy  ")
            [1] => 208
            [2] => Devil Troop of Jealousy
            [3] => Jealousy
        )
)

Answer: Well if you only want the monster number as output, this regex matches only the number and nothing around it because of the lookahead and lookbehind:
/(?<=monstername\s)\d+(?=.*Jealousy.*)/i

But with this you can only have one whitespace character betwenn "monstername" and the number.


is it possible to load data of one block in the tpl of another

Question: I'm a novice drupal coder and trying to accomplish the following
My scenario is such that i have the template files
block-mymod-1.tpl and block-mymod-2.tpl
respectively.
What i'm intending to do is get the data of block 2 to be displayed in that of 1.
currently $block->subject and $block->content in block-mymod-1.tpl give the subject and content of block1.
Is there a drupal way of overload the $block so that it could hold the subject and content of second block also?
Apparently my google skills were not good enough or i couldn't find a direct answer.
Any positive response would be greatly appreciated..
Thanks n Cheers!!!
Comment: Is the second block a literal carbon copy of the first block?  Or is the content in the first block just a portion of what will be in the second block?
Comment: @Chapabu no they are not copies of each other.. let's say they are similar but certainly not identical..
Answer: I'm not 100% sure if this will work, but it's worth a try!
You may be able to use module_invoke to place block 2's content into the template of block one using the following code in your block-mymod-1.tpl:
$block = module_invoke('block', 'block', 'view', '2');
print $block['content']

This post might help to explain more, but for your needs you are only interested in the first and last arguments.  The first tells Drupal which module you're invoking, and the last is the block ID of the node you're looking to load the data for.
Comment: thanks for the link will try it out and let you know in a while...
Comment: worked like a charm.... you sir are an artist.... simple and elegant solution ...drupal is the best...